From 352d6bdfef536456281c04b088f170663b163918 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Thu, 19 Nov 2026 01:45:08 +0900 Subject: [PATCH 01/14] fix(panel): harden cross-environment 2.33.0+ launcher coverage with zero-subprocess fast path and on-demand UAC - Add pure Node.js [MS-SHLLINK] raw-byte fast probe (`probeWindowsShortcutsFast`) so steady-state startups and 15-minute background rechecks run in <20ms with zero subprocesses, zero COM calls, and zero recursive folder traversal into Desktop subdirectories or unrelated Start Menu vendor folders - Restrict Windows shortcut scanning to top-level Desktop / OneDrive Desktop / Taskbar / Startup `.lnk` files and `Programs\Antigravity*`, pre-filtering raw bytes before lazily instantiating `WScript.Shell` COM - Patch exact O(1) user-space `HKCU\Software\Classes` launch keys (`antigravity` protocol, `Applications\Antigravity.exe`, `AntigravitySourceFile`) via `.NET` `Registry.CurrentUser` with `--remote-debugging-port=0` placed before `-- "%1"`, resolve `%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe` explicitly, and tolerate inaccessible folders without aborting - Support All-Users read-only public shortcuts (`readOnlyPaths`) and elevated old host processes via user-consented `-Verb RunAs` on 1-click relaunch while preserving WMI `Win32_Process.Create` when already elevated and de-elevating via `Shell.Application` when the original host ran unelevated (preserving Explorer drag-and-drop) - Generalize Linux `.desktop` `Exec=` patching for `env` prefixes and `Antigravity-*.AppImage`, add pure `node:fs` `/proc` executable discovery, gate launcher checks behind leader lease acquisition, and differentiate macOS / read-only shortcut notices honestly in `BridgeStatusNotice` --- sidecars/panel/app.js | 71 +- sidecars/panel/backend/api-actions.mjs | 5 +- .../panel/backend/desktop-launcher-config.mjs | 872 ++++++++++++++++-- sidecars/panel/backend/window-bridge.mjs | 60 +- sidecars/panel/index.html | 4 +- .../components/settings/BridgeStatusNotice.js | 51 +- sidecars/panel/src/i18n/en-US.js | 10 +- sidecars/panel/src/i18n/zh-CN.js | 10 +- sidecars/panel/test/window-bridge.test.mjs | 238 ++++- 9 files changed, 1140 insertions(+), 181 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 4d62a6d..1d94acd 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1463,14 +1463,20 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.str.mountSidebar': '仅侧边栏', 'settings.bridge.restartTitle': '已自动补齐启动参数,重启一次即可启用悬浮胶囊', 'settings.bridge.ctxRestartTitle': '已自动补齐启动参数,重启一次即可激活上下文覆写', - 'settings.bridge.restartBody': '已自动为桌面 / 开始菜单 / 任务栏快捷方式及自启项写入 --remote-debugging-port=0(后续每次正常打开均 100% 全自动挂载)。点击下方按钮即可退出托盘后台并立即生效。', + 'settings.bridge.restartBody': '已自动为快捷方式、自启项及协议关联写入 --remote-debugging-port=0(后续通过常规快捷方式打开均自动生效)。点击下方按钮即可退出后台进程并立即生效。', + 'settings.bridge.readOnlyTitle': '公共桌面快捷方式受权限保护,授权重启即可生效', + 'settings.bridge.ctxReadOnlyTitle': '公共桌面快捷方式受权限保护,授权重启即可激活上下文覆写', + 'settings.bridge.readOnlyBody': '个人启动项已配好,但公共桌面或开始菜单快捷方式需管理员权限修改。点击下方按钮并在系统弹窗中确认授权,即可一次性修补公共图标并带参重开(后续日常打开均自动生效)。', + 'settings.bridge.macTitle': '当前会话未开启调试端口,一键重开即可启用挂载', + 'settings.bridge.ctxMacTitle': '当前会话未开启调试端口,一键重开即可激活上下文覆写', 'settings.bridge.noPortTitle': '未检测到本地调试端口,主窗口挂载暂未生效', 'settings.bridge.unreachableTitle': '本地调试端口未就绪,主窗口挂载暂未生效', 'settings.bridge.ctxTitle': '未连通本地调试通道,上下文窗口覆写暂未注入', 'settings.bridge.guideWin': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可自动补齐快捷方式参数、退出托盘后台并带参重启生效。', - 'settings.bridge.guideMac': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可一键带参重开客户端生效,也可复制参数通过 open -a "Antigravity" --args --remote-debugging-port=0 启动。', + 'settings.bridge.guideMac': '受 macOS 应用签名限制,从 Dock 直接冷启动默认不带调试端口参数。点击下方按钮即可一键带参重开恢复(日常仅关窗不完全退出 Cmd+Q 则持续有效)。', 'settings.bridge.guideLinux': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可自动写入 .desktop 启动器并重启生效。', 'settings.bridge.relaunchBtn': '立即重启并启用挂载', + 'settings.bridge.relaunchAuthBtn': '授权修补并立即重启', 'settings.bridge.relaunchingBtn': '正在重启客户端...', 'settings.bridge.relaunchFailed': '自动重启失败,请从托盘退出后重试', 'settings.bridge.dismissAria': '暂时关闭提示', @@ -2093,14 +2099,20 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.str.mountSidebar': 'Sidebar Only', 'settings.bridge.restartTitle': 'Launch Flag Auto-Configured — Restart Once to Activate', 'settings.bridge.ctxRestartTitle': 'Launch Flag Auto-Configured — Restart Once for Context Override', - 'settings.bridge.restartBody': 'Automatically added --remote-debugging-port=0 to your shortcuts and startup entries (future launches mount 100% automatically). Click below to close tray processes and relaunch now.', + 'settings.bridge.restartBody': 'Automatically added --remote-debugging-port=0 to your shortcuts, startup entries, and protocol handlers (subsequent shortcut launches mount automatically). Click below to close background processes and relaunch now.', + 'settings.bridge.readOnlyTitle': 'Public Shortcut Protected — Authorize & Relaunch to Activate', + 'settings.bridge.ctxReadOnlyTitle': 'Public Shortcut Protected — Authorize & Relaunch for Context Override', + 'settings.bridge.readOnlyBody': 'Personal launch entries are configured, but public shortcuts require administrator permission. Click below and approve the system prompt to patch public shortcuts once and relaunch.', + 'settings.bridge.macTitle': 'Debug Port Inactive — One-Click Relaunch to Enable Mount', + 'settings.bridge.ctxMacTitle': 'Debug Port Inactive — One-Click Relaunch for Context Override', 'settings.bridge.noPortTitle': 'Local Debug Port Missing — Window Mount Inactive', 'settings.bridge.unreachableTitle': 'Local Debug Port Not Ready — Window Mount Inactive', 'settings.bridge.ctxTitle': 'Local Debug Port Inactive — Context Override Pending', 'settings.bridge.guideWin': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to auto-configure shortcuts, close tray background processes, and relaunch.', - 'settings.bridge.guideMac': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to relaunch with the flag in one click, or run open -a "Antigravity" --args --remote-debugging-port=0.', + 'settings.bridge.guideMac': 'Due to macOS app code signing, cold launches from Dock omit the debug port flag. Click below to relaunch with the flag in one click (stays active until you fully Quit via Cmd+Q).', 'settings.bridge.guideLinux': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to update your .desktop launcher and relaunch.', 'settings.bridge.relaunchBtn': 'Relaunch & Enable Mount', + 'settings.bridge.relaunchAuthBtn': 'Authorize & Relaunch', 'settings.bridge.relaunchingBtn': 'Relaunching Host...', 'settings.bridge.relaunchFailed': 'Auto-relaunch failed — quit from tray and retry', 'settings.bridge.dismissAria': 'Dismiss notice for now', @@ -14257,6 +14269,7 @@ const BridgeStatusNotice = defineComponent({ function syncActionButtons() { const canRelaunch = lastPayload.windowBridge?.canRelaunch !== false; + const needsAuth = Boolean(lastPayload.windowBridge?.hasReadOnlyShortcuts); patchAttr(relaunchBtnEl, 'hidden', !canRelaunch); patchAttr(relaunchBtnEl, 'disabled', relaunchState === 'relaunching'); patchText( @@ -14265,7 +14278,9 @@ const BridgeStatusNotice = defineComponent({ ? t('settings.bridge.relaunchingBtn') : relaunchState === 'failed' ? t('settings.bridge.relaunchFailed') - : t('settings.bridge.relaunchBtn') + : needsAuth + ? t('settings.bridge.relaunchAuthBtn') + : t('settings.bridge.relaunchBtn') ); patchSvgIcon(copyBtnIconEl, copied ? 'check' : 'copy'); @@ -14298,38 +14313,44 @@ const BridgeStatusNotice = defineComponent({ patchAttr(rootEl, 'hidden', !shouldShow); if (!shouldShow) return; + const plat = String(lastPayload.hostPlatform || '').trim().toLowerCase(); + const hasReadOnlyShortcuts = Boolean(wb?.hasReadOnlyShortcuts); + const isMacDesktop = plat === 'darwin' && !wb?.argvConfigured; const isAutoConfigured = Boolean( wb?.launcherConfigured || wb?.argvUpdatedThisBoot || wb?.argvConfigured ); + const useRestartTheme = !hasReadOnlyShortcuts && (isAutoConfigured || isMacDesktop); + patchClasses(rootEl, { - 'is-restart': isAutoConfigured, - 'is-warn': !isAutoConfigured, + 'is-restart': useRestartTheme, + 'is-warn': !useRestartTheme, }); - patchSvgIcon(headIconEl, isAutoConfigured ? 'refresh' : 'warning'); + patchSvgIcon(headIconEl, useRestartTheme ? 'refresh' : 'warning'); let titleText = ''; - if (isAutoConfigured) { + let bodyText = ''; + if (hasReadOnlyShortcuts) { + titleText = contextMode + ? t('settings.bridge.ctxReadOnlyTitle') + : t('settings.bridge.readOnlyTitle'); + bodyText = t('settings.bridge.readOnlyBody'); + } else if (isMacDesktop) { + titleText = contextMode + ? t('settings.bridge.ctxMacTitle') + : t('settings.bridge.macTitle'); + bodyText = t('settings.bridge.guideMac'); + } else if (isAutoConfigured) { titleText = contextMode ? t('settings.bridge.ctxRestartTitle') : t('settings.bridge.restartTitle'); - } else if (contextMode) { - titleText = t('settings.bridge.ctxTitle'); - } else if (state === 'cdp_unreachable') { - titleText = t('settings.bridge.unreachableTitle'); - } else { - titleText = t('settings.bridge.noPortTitle'); - } - - const plat = String(lastPayload.hostPlatform || '').trim().toLowerCase(); - let bodyText = ''; - if (isAutoConfigured) { bodyText = t('settings.bridge.restartBody'); - } else if (plat === 'darwin') { - bodyText = t('settings.bridge.guideMac'); - } else if (plat === 'linux') { - bodyText = t('settings.bridge.guideLinux'); } else { - bodyText = t('settings.bridge.guideWin'); + titleText = contextMode + ? t('settings.bridge.ctxTitle') + : state === 'cdp_unreachable' + ? t('settings.bridge.unreachableTitle') + : t('settings.bridge.noPortTitle'); + bodyText = plat === 'linux' ? t('settings.bridge.guideLinux') : t('settings.bridge.guideWin'); } patchText(titleEl, titleText); diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index 21150e6..5c40820 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -460,9 +460,12 @@ export async function executeAccountCredentialAction(data) { export async function executeBridgeRelaunchAction() { ensureIdeRemoteDebuggingArgv({ enabled: true }); - await ensureDesktopLaunchEntriesConfigured({ enabled: true }).catch(() => {}); + const launchConfig = await ensureDesktopLaunchEntriesConfigured({ enabled: true }).catch( + () => null + ); const result = await triggerDesktopHostRelaunch({ stalePortFiles: resolveDevToolsPortCandidates(), + readOnlyShortcutPaths: launchConfig?.readOnlyPaths || [], }); return { status: result.ok ? 200 : Number(result.status || 500), diff --git a/sidecars/panel/backend/desktop-launcher-config.mjs b/sidecars/panel/backend/desktop-launcher-config.mjs index 57b10a1..9041b10 100644 --- a/sidecars/panel/backend/desktop-launcher-config.mjs +++ b/sidecars/panel/backend/desktop-launcher-config.mjs @@ -5,22 +5,35 @@ * Antigravity Desktop (`Antigravity.exe` / `Antigravity.app` / `antigravity`) 自 `2.33.0` 起 * 默认不再于启动时开启 `--remote-debugging-port=0`,且独立 Electron 桌面端不读取 VS Code 系的 `argv.json`。 * - * 本模块在不触碰任何宿主二进制与 `app.asar` 的前提下,提供两层无感恢复能力: - * 1. 日常全自动层 (`ensureDesktopLaunchEntriesConfigured`): - * - Windows:自动为当前用户的桌面(含 OneDrive 重定向桌面)、开始菜单、任务栏固定图标、启动文件夹中的 - * `Antigravity.lnk` 快捷方式及已存在的 `HKCU\...\Run` 自启项补齐 `--remote-debugging-port=0`; - * - Linux:自动在 `~/.local/share/applications/antigravity.desktop`(必要时自系统目录复制)与 - * `~/.config/autostart/antigravity.desktop` 的 `Exec=` 中补齐 `--remote-debugging-port=0`; - * - 当用户切回「仅侧边栏」且无上下文窗口覆写时,可干净移除本插件托管的 `--remote-debugging-port=0`,绝不触碰用户自定义端口; + * 本模块在不触碰任何宿主二进制与 `app.asar` 的前提下,提供两层恢复闭环: + * 1. 日常全自动层 (`ensureDesktopLaunchEntriesConfigured`,后台零弹窗): + * - Windows:自动为个人桌面(含子文件夹及并存的 OneDrive 桌面)、开始菜单、任务栏固定图标、启动文件夹中的 + * `Antigravity.lnk`、`HKCU\...\Run` 自启项以及 `HKCU\Software\Classes` 下的 `antigravity://` 协议与文件关联 + * 补齐 `--remote-debugging-port=0`;若检测到 All-Users 公共桌面/开始菜单存在只读未修补快捷方式,如实上报 + * `readOnlyPaths` 供用户点击重启按钮时按需触发 UAC 一次性修补(不在桌面制造双份重影图标); + * - Linux:自动在 `~/.local/share/applications/antigravity.desktop` 与 `~/.config/autostart/antigravity.desktop` + * 的 `Exec=`(兼容 `env` 前缀与 `.AppImage`)中补齐 `--remote-debugging-port=0`; + * - 当用户切回「仅侧边栏」且无上下文窗口覆写时,干净剥离本插件托管的 `--remote-debugging-port=0`,保留用户自定义端口; * 2. 当下裸启动会话一键重拉层 (`triggerDesktopHostRelaunch`): - * - Windows 通过 `Shell.Application` (`explorer.exe` 进程外 COM) 脱离宿主 Job Object 托管生命周期, - * macOS / Linux 通过独立会话 `nohup` 脱离进程组,自动退出系统托盘常驻实例、清理陈旧 `DevToolsActivePort` - * 并以纯净桌面环境变量追加 `--remote-debugging-port=0` 重新拉起宿主客户端。 + * - Windows 自适应当前权限层级(已提权走 WMI `Win32_Process.Create` 保权脱离 Job Object;普通权限走 `Shell.Application` + * 并回退 WMI;若存在公共只读快捷方式或已提权的旧宿主进程驻留,则在用户点击重启后请求一次 `-Verb RunAs` UAC 授权完成修补与关闭, + * 随后按宿主原有权限层级重拉以避免破坏资源管理器文件拖拽); + * - macOS / Linux 通过独立后台会话关闭旧实例、清理陈旧 `DevToolsActivePort` 并追加 `--remote-debugging-port=0` 重开。 */ -import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'; +import { + existsSync, + mkdirSync, + readdirSync, + readFileSync, + renameSync, + readlinkSync, + statSync, + unlinkSync, + writeFileSync, +} from 'node:fs'; import { homedir } from 'node:os'; -import { basename, dirname, join } from 'node:path'; +import { basename, dirname, join, win32 as pathWin32 } from 'node:path'; import { DATA_DIR, lsRuntimeEndpoint } from './config.mjs'; export const REMOTE_DEBUG_LAUNCH_FLAG = '--remote-debugging-port=0'; @@ -28,6 +41,32 @@ export const REMOTE_DEBUG_LAUNCH_FLAG = '--remote-debugging-port=0'; const REMOTE_DEBUG_ANY_RE = /(?:^|\s)--remote-debugging-port(?:=|\s|$)/i; const REMOTE_DEBUG_MANAGED_ZERO_RE = /(?:^|\s+)--remote-debugging-port=(?:"0"|'0'|0)(?=\s|$)/gi; +/** + * 解析 Windows PowerShell 5.1 可执行文件绝对路径(防止用户精简系统或异常 `PATH` 丢失裸 `powershell.exe`)。 + * + * @param {Record} [env=process.env] + * @param {(p: string) => boolean} [existsFn=existsSync] + * @returns {string} + */ +export function resolveWindowsPowerShellExecutable(env = process.env, existsFn = existsSync) { + const sysRoot = String(env?.SystemRoot || env?.WINDIR || 'C:\\Windows').trim(); + if (sysRoot) { + const candidate = pathWin32.join( + sysRoot, + 'System32', + 'WindowsPowerShell', + 'v1.0', + 'powershell.exe' + ); + try { + if (existsFn(candidate)) return candidate; + } catch { + // 忽略文件系统探测异常,回退命令名 + } + } + return 'powershell.exe'; +} + /** * 在命令行参数字符串中幂等补齐或移除托管的 `--remote-debugging-port=0`,保留用户自定义的其它参数或自定义端口。 * @@ -108,7 +147,84 @@ export function patchWindowsRunRegistryCommand(rawValue, { enabled = true } = {} } /** - * 修补 Linux XDG `.desktop` 文件文本中的 `Exec=` 启动行(仅作用于 `antigravity` 桌面端,不修改 `antigravity-ide`)。 + * 解析并无损修补 Windows `HKCU\Software\Classes\...\shell\open\command` 协议与文件关联命令行。 + * 将 `--remote-debugging-port=0` 置于主程序路径之后、原有 `--` 或 `"%1"` 占位符之前,确保 Chromium 将其识别为开关而非文件路径。 + * + * @param {unknown} rawValue + * @param {{ enabled?: boolean }} [options] + * @returns {{ matched: boolean, changed: boolean, configured: boolean, value: string }} + */ +export function patchWindowsShellOpenCommand(rawValue, { enabled = true } = {}) { + const raw = String(rawValue ?? '').trim(); + if (!raw) { + return { matched: false, changed: false, configured: false, value: raw }; + } + const m = raw.match(/^\s*(?:"([^"]+)"|([^\s"]+))([\s\S]*)$/); + if (!m) { + return { matched: false, changed: false, configured: false, value: raw }; + } + const exePath = String(m[1] || m[2] || '').trim(); + const exeLeaf = exePath.split(/[\\/]/).pop() || ''; + if (exeLeaf.toLowerCase() !== 'antigravity.exe') { + return { matched: false, changed: false, configured: false, value: raw }; + } + const quotedExe = m[1] ? `"${exePath}"` : /\s/.test(exePath) ? `"${exePath}"` : exePath; + const rest = String(m[3] || '').trim(); + + if (enabled) { + if (REMOTE_DEBUG_ANY_RE.test(rest)) { + return { matched: true, changed: false, configured: true, value: raw }; + } + const nextValue = rest + ? `${quotedExe} ${REMOTE_DEBUG_LAUNCH_FLAG} ${rest}` + : `${quotedExe} ${REMOTE_DEBUG_LAUNCH_FLAG}`; + return { + matched: true, + changed: nextValue !== raw, + configured: true, + value: nextValue, + }; + } + + const stripped = ensureRemoteDebugFlagInArgs(rest, { enabled: false }); + const nextValue = stripped.args ? `${quotedExe} ${stripped.args}` : quotedExe; + return { + matched: true, + changed: nextValue !== raw, + configured: stripped.configured, + value: nextValue, + }; +} + +function isLinuxAntigravityDesktopLeaf(leaf) { + const lower = String(leaf || '').trim().toLowerCase(); + if (!lower || lower.includes('ide')) return false; + return /^antigravity(?:$|[-_.\d]|(?:\.appimage$))/i.test(lower); +} + +function splitLinuxExecTokens(cmdBody) { + const tokens = []; + const re = /(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s"']+)+/g; + let m; + while ((m = re.exec(cmdBody)) !== null) { + tokens.push({ raw: m[0], start: m.index, end: m.index + m[0].length }); + } + return tokens; +} + +function stripOuterQuotes(tok) { + if ( + (tok.startsWith('"') && tok.endsWith('"')) || + (tok.startsWith("'") && tok.endsWith("'")) + ) { + return tok.slice(1, -1); + } + return tok; +} + +/** + * 修补 Linux XDG `.desktop` 文件文本中的 `Exec=` 启动行。 + * 兼容 `Exec=env VAR=1 ...` 前缀与 `Antigravity-*.AppImage` 可执行文件,严格排除 `antigravity-ide`。 * * @param {string} rawText * @param {{ enabled?: boolean }} [options] @@ -129,20 +245,33 @@ export function patchLinuxDesktopEntryText(rawText, { enabled = true } = {}) { if (!execMatch) return line; const prefix = execMatch[1]; const cmdBody = execMatch[2].trim(); - const binMatch = cmdBody.match(/^(?:"([^"]+)"|'([^']+)'|([^\s"']+))([\s\S]*)$/); - if (!binMatch) return line; - const rawBin = String(binMatch[1] || binMatch[2] || binMatch[3] || ''); - const leaf = (rawBin.split('/').pop() || '').toLowerCase(); - if (leaf !== 'antigravity') { + const tokens = splitLinuxExecTokens(cmdBody); + if (!tokens.length) return line; + + let binIdx = 0; + const firstLeaf = (stripOuterQuotes(tokens[0].raw).split('/').pop() || '').toLowerCase(); + if (firstLeaf === 'env') { + binIdx = 1; + while (binIdx < tokens.length) { + const unquoted = stripOuterQuotes(tokens[binIdx].raw); + if (unquoted === '-S' || /^[A-Za-z_][A-Za-z0-9_]*=/.test(unquoted)) { + binIdx += 1; + continue; + } + break; + } + } + if (binIdx >= tokens.length) return line; + + const exeTok = tokens[binIdx]; + const exeLeaf = stripOuterQuotes(exeTok.raw).split('/').pop() || ''; + if (!isLinuxAntigravityDesktopLeaf(exeLeaf)) { return line; } + matched = true; - const binToken = binMatch[1] - ? `"${binMatch[1]}"` - : binMatch[2] - ? `'${binMatch[2]}'` - : binMatch[3]; - const rest = String(binMatch[4] || '').trim(); + const headThroughExe = cmdBody.slice(0, exeTok.end).trim(); + const rest = cmdBody.slice(exeTok.end).trim(); if (enabled) { if (REMOTE_DEBUG_ANY_RE.test(rest)) { @@ -158,18 +287,18 @@ export function patchLinuxDesktopEntryText(rawText, { enabled = true } = {}) { const mid = beforeCodes ? `${beforeCodes} ${REMOTE_DEBUG_LAUNCH_FLAG}` : REMOTE_DEBUG_LAUNCH_FLAG; - return `${prefix}${binToken} ${mid} ${codes}`; + return `${prefix}${headThroughExe} ${mid} ${codes}`; } return rest - ? `${prefix}${binToken} ${rest} ${REMOTE_DEBUG_LAUNCH_FLAG}` - : `${prefix}${binToken} ${REMOTE_DEBUG_LAUNCH_FLAG}`; + ? `${prefix}${headThroughExe} ${rest} ${REMOTE_DEBUG_LAUNCH_FLAG}` + : `${prefix}${headThroughExe} ${REMOTE_DEBUG_LAUNCH_FLAG}`; } const stripped = ensureRemoteDebugFlagInArgs(rest, { enabled: false }); configured = configured || stripped.configured; if (!stripped.changed) return line; changed = true; - return stripped.args ? `${prefix}${binToken} ${stripped.args}` : `${prefix}${binToken}`; + return stripped.args ? `${prefix}${headThroughExe} ${stripped.args}` : `${prefix}${headThroughExe}`; }); return { @@ -203,7 +332,7 @@ export function buildSanitizedDesktopRelaunchEnv(baseEnv = process.env) { } /** - * 自动定位本机 Antigravity Desktop(或 IDE)主程序路径(优先从 `ANTIGRAVITY_AGENTAPI_EXE` 向上反推,回退标准安装目录)。 + * 自动定位本机 Antigravity Desktop(或 IDE)主程序路径(优先从 `USAGE_MONITOR_HOST_EXE` / `APPIMAGE` / `ANTIGRAVITY_AGENTAPI_EXE` 反推,回退标准安装目录)。 * * @param {{ * env?: Record, @@ -227,6 +356,16 @@ export function resolveDesktopHostExecutable({ } }; + if (platform === 'linux') { + const appImagePath = String(env?.APPIMAGE || '').trim(); + if (appImagePath && safeExists(appImagePath)) { + const leaf = basename(appImagePath); + if (isLinuxAntigravityDesktopLeaf(leaf)) { + return { found: true, kind: 'desktop', executablePath: appImagePath, appBundlePath: '' }; + } + } + } + const hintPaths = [ String(env?.USAGE_MONITOR_HOST_EXE || '').trim(), String(env?.ANTIGRAVITY_AGENTAPI_EXE || '').trim(), @@ -288,7 +427,7 @@ export function resolveDesktopHostExecutable({ } else if (platform === 'linux') { for (const binName of ['antigravity', 'Antigravity']) { const linuxExe = join(installRoot, binName); - if (safeExists(linuxExe)) { + if (safeExists(linuxExe) && !installRoot.startsWith('/tmp/.mount_')) { return { found: true, kind: 'desktop', executablePath: linuxExe, appBundlePath: '' }; } } @@ -357,7 +496,7 @@ async function runLauncherExecFile(file, args, options = {}) { args, { windowsHide: true, - timeout: options.timeoutMs || 8000, + timeout: options.timeoutMs || 9000, maxBuffer: 1024 * 1024, env: options.env || process.env, }, @@ -406,41 +545,237 @@ function writeTextFileAtomically(filePath, content, fsOps) { } } +/** + * 检查单个 Windows `.lnk` 二进制 Buffer 是否指向 `Antigravity.exe`(排除 `Antigravity IDE.exe`)及是否已包含调试端口参数。 + * 基于 `[MS-SHLLINK]` 原始字节扫描,纯内存耗时 `< 0.1ms`,无需拉起任何外部子进程或 COM 组件。 + * + * @param {Buffer} buf + * @returns {{ matched: boolean, hasDebugPort: boolean }} + */ +export function inspectWindowsLnkBuffer(buf) { + if (!Buffer.isBuffer(buf) || buf.length < 32 || buf.length > 65536) { + return { matched: false, hasDebugPort: false }; + } + const ascii = buf.toString('latin1').toLowerCase(); + const utf16 = buf.toString('utf16le').toLowerCase(); + const hasIde = ascii.includes('antigravity ide.exe') || utf16.includes('antigravity ide.exe'); + if (hasIde) { + return { matched: false, hasDebugPort: false }; + } + const hasDesktopExe = + ascii.includes('\\antigravity.exe') || + utf16.includes('\\antigravity.exe') || + ascii.includes('/antigravity.exe') || + utf16.includes('/antigravity.exe'); + if (!hasDesktopExe) { + return { matched: false, hasDebugPort: false }; + } + const hasDebugPort = + ascii.includes('--remote-debugging-port') || utf16.includes('--remote-debugging-port'); + return { matched: true, hasDebugPort }; +} + +/** + * 纯 Node.js 零子进程快速扫描当前机器上的 `Antigravity.exe` 快捷方式配置状态(耗时通常 `< 2ms`)。 + * 桌面与任务栏严格仅扫描顶层 `.lnk`(绝不进入用户项目文件夹或 `node_modules`),开始菜单仅检查顶层及 `Antigravity*` 一级子目录。 + * + * @param {{ + * env?: Record, + * homeDir?: string, + * fsOps?: { + * readdirFn?: typeof readdirSync, + * statFn?: typeof statSync, + * readFn?: typeof readFileSync, + * }|null, + * }} [options] + */ +export function probeWindowsShortcutsFast({ + env = process.env, + homeDir = homedir(), + fsOps = null, +} = {}) { + const readdirFn = fsOps?.readdirFn || readdirSync; + const statFn = fsOps?.statFn || statSync; + const readFn = fsOps?.readFn || readFileSync; + + const zhDesktop = '\u684C\u9762'; + const userProfile = String(env?.USERPROFILE || homeDir || '').trim(); + const appData = String(env?.APPDATA || (homeDir ? pathWin32.join(homeDir, 'AppData', 'Roaming') : '')).trim(); + const publicRoot = String(env?.PUBLIC || 'C:\\Users\\Public').trim(); + const programData = String(env?.ProgramData || 'C:\\ProgramData').trim(); + + const flatDirs = []; + if (userProfile) { + flatDirs.push(pathWin32.join(userProfile, 'Desktop'), pathWin32.join(userProfile, zhDesktop)); + } + for (const od of [env?.OneDrive, env?.OneDriveConsumer, env?.OneDriveCommercial]) { + const cleanOd = String(od || '').trim(); + if (cleanOd) { + flatDirs.push(pathWin32.join(cleanOd, 'Desktop'), pathWin32.join(cleanOd, zhDesktop)); + } + } + if (appData) { + flatDirs.push( + pathWin32.join(appData, 'Microsoft', 'Windows', 'Start Menu'), + pathWin32.join(appData, 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup'), + pathWin32.join(appData, 'Microsoft', 'Internet Explorer', 'Quick Launch', 'User Pinned', 'TaskBar') + ); + } + if (publicRoot) { + flatDirs.push(pathWin32.join(publicRoot, 'Desktop'), pathWin32.join(publicRoot, zhDesktop)); + } + + const programRoots = []; + if (appData) { + programRoots.push(pathWin32.join(appData, 'Microsoft', 'Windows', 'Start Menu', 'Programs')); + } + if (programData) { + programRoots.push(pathWin32.join(programData, 'Microsoft', 'Windows', 'Start Menu', 'Programs')); + } + + const seenDirs = new Set(); + const candidateLnks = []; + const seenLnks = new Set(); + + const collectTopLevelLnks = (dirPath, expandAntigravitySubdirs = false) => { + if (!dirPath) return; + const normDir = dirPath.toLowerCase(); + if (seenDirs.has(normDir)) return; + seenDirs.add(normDir); + let entries = []; + try { + entries = readdirFn(dirPath, { withFileTypes: true }); + } catch { + return; + } + for (const ent of entries) { + const name = String(ent?.name || ''); + if (!name) continue; + if (ent.isFile?.() && name.toLowerCase().endsWith('.lnk')) { + const full = pathWin32.join(dirPath, name); + const key = full.toLowerCase(); + if (!seenLnks.has(key)) { + seenLnks.add(key); + candidateLnks.push(full); + } + } else if ( + expandAntigravitySubdirs && + ent.isDirectory?.() && + name.toLowerCase().startsWith('antigravity') + ) { + collectTopLevelLnks(pathWin32.join(dirPath, name), false); + } + } + }; + + for (const d of flatDirs) collectTopLevelLnks(d, false); + for (const p of programRoots) collectTopLevelLnks(p, true); + + const matchedPaths = []; + const configuredPaths = []; + const unconfiguredPaths = []; + + for (const lnkPath of candidateLnks) { + try { + const st = statFn(lnkPath); + if (!st || st.size < 32 || st.size > 65536) continue; + const buf = readFn(lnkPath); + const res = inspectWindowsLnkBuffer(buf); + if (!res.matched) continue; + matchedPaths.push(lnkPath); + if (res.hasDebugPort) { + configuredPaths.push(lnkPath); + } else { + unconfiguredPaths.push(lnkPath); + } + } catch { + // 忽略单个无权限或损坏的快捷方式文件 + } + } + + return { + matchedPaths, + configuredPaths, + unconfiguredPaths, + allConfigured: matchedPaths.length > 0 && unconfiguredPaths.length === 0, + }; +} + const WIN_SHORTCUT_PROVISION_PS = ` -$ErrorActionPreference = 'Stop' +[Console]::OutputEncoding = [System.Text.Encoding]::UTF8 +$ErrorActionPreference = 'SilentlyContinue' $enableFlag = $env:AGY_LAUNCH_ENABLED -eq '1' $updated = New-Object System.Collections.Generic.List[string] $configured = New-Object System.Collections.Generic.List[string] -$ws = New-Object -ComObject WScript.Shell +$readOnly = New-Object System.Collections.Generic.List[string] +$ws = $null $userProgramsDir = [Environment]::GetFolderPath('Programs') +$zhDesktop = ([string][char]0x684C + [string][char]0x9762) -$scanSpecs = @( - @{ Dir = [Environment]::GetFolderPath('Desktop'); Recurse = $false; IsCommon = $false }, - @{ Dir = $userProgramsDir; Recurse = $true; IsCommon = $false }, - @{ Dir = [Environment]::GetFolderPath('StartMenu'); Recurse = $false; IsCommon = $false }, - @{ Dir = [Environment]::GetFolderPath('Startup'); Recurse = $false; IsCommon = $false }, - @{ Dir = (Join-Path $env:APPDATA 'Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar'); Recurse = $false; IsCommon = $false }, - @{ Dir = [Environment]::GetFolderPath('CommonDesktopDirectory'); Recurse = $false; IsCommon = $true }, - @{ Dir = [Environment]::GetFolderPath('CommonPrograms'); Recurse = $true; IsCommon = $true } -) +$flatSpecs = New-Object System.Collections.Generic.List[object] +$seenScanDir = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase) + +function Add-ScanDir([string]$dirPath, [bool]$isCommon, [string]$kind, [bool]$expandVendorSubdir) { + if (-not $dirPath) { return } + if (-not $seenScanDir.Add($dirPath)) { return } + $exists = $false + try { $exists = [bool](Test-Path -LiteralPath $dirPath -ErrorAction SilentlyContinue) } catch { $exists = $false } + if (-not $exists) { return } + $flatSpecs.Add(@{ Dir = $dirPath; IsCommon = $isCommon; Kind = $kind }) + if ($expandVendorSubdir) { + try { + foreach ($sub in @(Get-ChildItem -LiteralPath $dirPath -Directory -Filter 'Antigravity*' -ErrorAction SilentlyContinue)) { + if ($sub -and $sub.FullName -and $seenScanDir.Add([string]$sub.FullName)) { + $flatSpecs.Add(@{ Dir = [string]$sub.FullName; IsCommon = $isCommon; Kind = $kind }) + } + } + } catch {} + } +} + +foreach ($d in @( + [Environment]::GetFolderPath('Desktop'), + $(if ($env:USERPROFILE) { Join-Path $env:USERPROFILE 'Desktop' } else { '' }), + $(if ($env:USERPROFILE) { Join-Path $env:USERPROFILE $zhDesktop } else { '' }) +)) { + Add-ScanDir $d $false 'desktop' $false +} +foreach ($od in @($env:OneDrive, $env:OneDriveConsumer, $env:OneDriveCommercial)) { + if ($od) { + Add-ScanDir (Join-Path $od 'Desktop') $false 'desktop' $false + Add-ScanDir (Join-Path $od $zhDesktop) $false 'desktop' $false + } +} +Add-ScanDir $userProgramsDir $false 'programs' $true +Add-ScanDir ([Environment]::GetFolderPath('StartMenu')) $false 'startmenu' $false +Add-ScanDir ([Environment]::GetFolderPath('Startup')) $false 'startup' $false +if ($env:APPDATA) { + Add-ScanDir (Join-Path $env:APPDATA 'Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar') $false 'taskbar' $false +} +Add-ScanDir ([Environment]::GetFolderPath('CommonDesktopDirectory')) $true 'desktop' $false +Add-ScanDir ([Environment]::GetFolderPath('CommonPrograms')) $true 'programs' $true $seen = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase) -foreach ($spec in $scanSpecs) { +foreach ($spec in $flatSpecs) { $dir = [string]$spec.Dir - if (-not $dir -or -not (Test-Path -LiteralPath $dir)) { continue } $items = @() try { - if ($spec.Recurse) { - $items = @(Get-ChildItem -LiteralPath $dir -Filter '*.lnk' -File -Recurse -Depth 2 -ErrorAction SilentlyContinue) - } else { - $items = @(Get-ChildItem -LiteralPath $dir -Filter '*.lnk' -File -ErrorAction SilentlyContinue) - } + $items = @(Get-ChildItem -LiteralPath $dir -Filter '*.lnk' -File -ErrorAction SilentlyContinue) } catch { continue } foreach ($item in $items) { + if ($item.Length -lt 32 -or $item.Length -gt 65536) { continue } $lnkPath = [string]$item.FullName if (-not $seen.Add($lnkPath)) { continue } try { + $rawBytes = [System.IO.File]::ReadAllBytes($lnkPath) + $u16 = [System.Text.Encoding]::Unicode.GetString($rawBytes) + $lat = [System.Text.Encoding]::GetEncoding(28591).GetString($rawBytes) + if ($u16.IndexOf('antigravity.exe', [System.StringComparison]::OrdinalIgnoreCase) -lt 0 -and + $lat.IndexOf('antigravity.exe', [System.StringComparison]::OrdinalIgnoreCase) -lt 0) { + continue + } + if (-not $ws) { $ws = New-Object -ComObject WScript.Shell } $sc = $ws.CreateShortcut($lnkPath) $target = [string]$sc.TargetPath if ([System.IO.Path]::GetFileName($target) -ine 'Antigravity.exe') { continue } @@ -457,9 +792,10 @@ foreach ($spec in $scanSpecs) { $updated.Add($lnkPath) $configured.Add($lnkPath) } catch { - if ($spec.IsCommon -and $userProgramsDir -and (Test-Path -LiteralPath $userProgramsDir)) { + $readOnly.Add($lnkPath) + if ($spec.IsCommon -and $spec.Kind -eq 'programs' -and $userProgramsDir -and (Test-Path -LiteralPath $userProgramsDir -ErrorAction SilentlyContinue)) { $fallbackLnk = Join-Path $userProgramsDir ([System.IO.Path]::GetFileName($lnkPath)) - if (-not (Test-Path -LiteralPath $fallbackLnk)) { + if (-not (Test-Path -LiteralPath $fallbackLnk -ErrorAction SilentlyContinue)) { try { $uSc = $ws.CreateShortcut($fallbackLnk) $uSc.TargetPath = $target @@ -481,7 +817,9 @@ foreach ($spec in $scanSpecs) { $sc.Arguments = $stripped $sc.Save() $updated.Add($lnkPath) - } catch {} + } catch { + $readOnly.Add($lnkPath) + } } if ($stripped -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { $configured.Add($lnkPath) @@ -491,40 +829,108 @@ foreach ($spec in $scanSpecs) { } } -$runKey = 'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Run' -if (Test-Path -LiteralPath $runKey) { - try { - $regItem = Get-Item -LiteralPath $runKey -ErrorAction SilentlyContinue - if ($regItem) { - foreach ($valName in $regItem.GetValueNames()) { - $rawCmd = [string]$regItem.GetValue($valName, '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) - if (-not $rawCmd) { continue } - if ($rawCmd -notmatch '^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$') { continue } - $exeCandidate = if ($Matches[1]) { $Matches[1] } else { $Matches[2] } - $restPart = [string]$Matches[3] - if ([System.IO.Path]::GetFileName($exeCandidate) -ine 'Antigravity.exe') { continue } - $quotedExe = if ($Matches[1] -or $exeCandidate -match '\\s') { '"' + $exeCandidate + '"' } else { $exeCandidate } - if ($enableFlag) { - if ($restPart -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { - $configured.Add("HKCU:Run:$valName") - continue - } - $nextRest = ($restPart.Trim() + ' --remote-debugging-port=0').Trim() - $nextVal = "$quotedExe $nextRest" - Set-ItemProperty -LiteralPath $runKey -Name $valName -Value $nextVal -ErrorAction SilentlyContinue - $updated.Add("HKCU:Run:$valName") +$runSubPath = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run' +try { + $runReadKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($runSubPath, $false) + if ($runReadKey) { + $runNames = @($runReadKey.GetValueNames()) + $runReadKey.Close() + foreach ($valName in $runNames) { + $rk = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($runSubPath, $false) + if (-not $rk) { continue } + $rawCmd = [string]$rk.GetValue($valName, '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) + $rk.Close() + if (-not $rawCmd) { continue } + if ($rawCmd -notmatch '^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$') { continue } + $exeCandidate = if ($Matches[1]) { $Matches[1] } else { $Matches[2] } + $restPart = [string]$Matches[3] + if ([System.IO.Path]::GetFileName($exeCandidate) -ine 'Antigravity.exe') { continue } + $quotedExe = if ($Matches[1] -or $exeCandidate -match '\\s') { '"' + $exeCandidate + '"' } else { $exeCandidate } + if ($enableFlag) { + if ($restPart -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { $configured.Add("HKCU:Run:$valName") - } else { - $strippedRest = ([regex]::Replace($restPart, '(?:^|\\s+)--remote-debugging-port=(?:"0"|''0''|0)(?=\\s|$)', ' ')).Trim() - $nextVal = if ($strippedRest) { "$quotedExe $strippedRest" } else { $quotedExe } - if ($nextVal -ne $rawCmd.Trim()) { - Set-ItemProperty -LiteralPath $runKey -Name $valName -Value $nextVal -ErrorAction SilentlyContinue + continue + } + $nextRest = ($restPart.Trim() + ' --remote-debugging-port=0').Trim() + $nextVal = "$quotedExe $nextRest" + try { + $wk = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($runSubPath, $true) + if ($wk) { + $wk.SetValue($valName, $nextVal, [Microsoft.Win32.RegistryValueKind]::String) + $wk.Close() $updated.Add("HKCU:Run:$valName") - } - if ($strippedRest -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { $configured.Add("HKCU:Run:$valName") } + } catch {} + } else { + $strippedRest = ([regex]::Replace($restPart, '(?:^|\\s+)--remote-debugging-port=(?:"0"|''0''|0)(?=\\s|$)', ' ')).Trim() + $nextVal = if ($strippedRest) { "$quotedExe $strippedRest" } else { $quotedExe } + if ($nextVal -ne $rawCmd.Trim()) { + try { + $wk = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($runSubPath, $true) + if ($wk) { + $wk.SetValue($valName, $nextVal, [Microsoft.Win32.RegistryValueKind]::String) + $wk.Close() + $updated.Add("HKCU:Run:$valName") + } + } catch {} } + if ($strippedRest -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { + $configured.Add("HKCU:Run:$valName") + } + } + } + } +} catch {} + +$exactClassSubKeys = @( + 'Software\\Classes\\antigravity\\shell\\open\\command', + 'Software\\Classes\\Applications\\Antigravity.exe\\shell\\open\\command', + 'Software\\Classes\\AntigravitySourceFile\\shell\\open\\command' +) +foreach ($relSubKey in $exactClassSubKeys) { + try { + $rOpen = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($relSubKey, $false) + if (-not $rOpen) { continue } + $rawOpen = [string]$rOpen.GetValue('', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) + $rOpen.Close() + if (-not $rawOpen) { continue } + if ($rawOpen -notmatch '^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$') { continue } + $exeCand = if ($Matches[1]) { $Matches[1] } else { $Matches[2] } + $restOpen = ([string]$Matches[3]).Trim() + if ([System.IO.Path]::GetFileName($exeCand) -ine 'Antigravity.exe') { continue } + $quotedOpenExe = if ($Matches[1] -or $exeCand -match '\\s') { '"' + $exeCand + '"' } else { $exeCand } + $fullKeyName = "HKEY_CURRENT_USER\\$relSubKey" + if ($enableFlag) { + if ($restOpen -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { + $configured.Add($fullKeyName) + continue + } + $nextOpen = if ($restOpen) { "$quotedOpenExe --remote-debugging-port=0 $restOpen" } else { "$quotedOpenExe --remote-debugging-port=0" } + try { + $wOpen = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($relSubKey, $true) + if ($wOpen) { + $wOpen.SetValue('', $nextOpen, [Microsoft.Win32.RegistryValueKind]::String) + $wOpen.Close() + $updated.Add($fullKeyName) + $configured.Add($fullKeyName) + } + } catch {} + } else { + $strippedOpen = ([regex]::Replace($restOpen, '(?:^|\\s+)--remote-debugging-port=(?:"0"|''0''|0)(?=\\s|$)', ' ')).Trim() + $nextOpen = if ($strippedOpen) { "$quotedOpenExe $strippedOpen" } else { $quotedOpenExe } + if ($nextOpen -ne $rawOpen.Trim()) { + try { + $wOpen = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($relSubKey, $true) + if ($wOpen) { + $wOpen.SetValue('', $nextOpen, [Microsoft.Win32.RegistryValueKind]::String) + $wOpen.Close() + $updated.Add($fullKeyName) + } + } catch {} + } + if ($strippedOpen -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { + $configured.Add($fullKeyName) } } } catch {} @@ -534,14 +940,16 @@ if (Test-Path -LiteralPath $runKey) { ok = $true updatedPaths = @($updated) configuredPaths = @($configured) + readOnlyPaths = @($readOnly) } | ConvertTo-Json -Compress `.trim(); /** - * 自动同步当前系统下用户空间启动入口(Windows `.lnk` / `HKCU:Run`、Linux `.desktop`)中的 `--remote-debugging-port=0`。 + * 自动同步当前系统下用户空间启动入口(Windows `.lnk` / `HKCU:Run` / `HKCU:Classes`、Linux `.desktop`)中的 `--remote-debugging-port=0`。 * * @param {{ * enabled?: boolean, + * fastCheckIfActive?: boolean, * env?: Record, * platform?: string, * homeDir?: string, @@ -553,12 +961,15 @@ if (Test-Path -LiteralPath $runKey) { * mkdirFn?: typeof mkdirSync, * renameFn?: typeof renameSync, * unlinkFn?: typeof unlinkSync, + * readdirFn?: typeof readdirSync, + * statFn?: typeof statSync, * }|null, * allowInTest?: boolean, * }} [options] */ export async function ensureDesktopLaunchEntriesConfigured({ enabled = true, + fastCheckIfActive = false, env = process.env, platform = process.platform, homeDir = homedir(), @@ -571,8 +982,11 @@ export async function ensureDesktopLaunchEntriesConfigured({ checked: false, updated: false, alreadyConfigured: false, + configured: false, + hasReadOnlyShortcuts: false, updatedPaths: [], configuredPaths: [], + readOnlyPaths: [], reason: 'test_sandbox_skipped', }; } @@ -584,16 +998,50 @@ export async function ensureDesktopLaunchEntriesConfigured({ mkdirFn: fsOps?.mkdirFn || mkdirSync, renameFn: fsOps?.renameFn || renameSync, unlinkFn: fsOps?.unlinkFn || unlinkSync, + readdirFn: fsOps?.readdirFn || readdirSync, + statFn: fsOps?.statFn || statSync, }; if (platform === 'win32') { + // 稳态零子进程快检:当调试端口已活跃或处于周期复检且所有 `.lnk` 字节内均已含参数时,直接返回(<2ms,不拉起 PowerShell) + if (!execFileFn && fastCheckIfActive) { + const fast = probeWindowsShortcutsFast({ env, homeDir, fsOps: ops }); + if (enabled && fast.allConfigured) { + return { + checked: true, + fastPath: true, + updated: false, + alreadyConfigured: true, + configured: true, + hasReadOnlyShortcuts: false, + updatedPaths: [], + configuredPaths: fast.configuredPaths, + readOnlyPaths: [], + }; + } + if (!enabled && fast.configuredPaths.length === 0) { + return { + checked: true, + fastPath: true, + updated: false, + alreadyConfigured: false, + configured: false, + hasReadOnlyShortcuts: false, + updatedPaths: [], + configuredPaths: [], + readOnlyPaths: [], + }; + } + } + try { const runner = execFileFn || runLauncherExecFile; + const psExe = execFileFn ? 'powershell.exe' : resolveWindowsPowerShellExecutable(env, ops.existsFn); const out = await runner( - 'powershell.exe', + psExe, ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', WIN_SHORTCUT_PROVISION_PS], { - timeoutMs: 9000, + timeoutMs: 10000, env: { ...env, AGY_LAUNCH_ENABLED: enabled ? '1' : '0', @@ -609,13 +1057,19 @@ export async function ensureDesktopLaunchEntriesConfigured({ const configuredPaths = Array.isArray(parsed?.configuredPaths) ? parsed.configuredPaths.map(String).filter(Boolean) : []; + const readOnlyPaths = Array.isArray(parsed?.readOnlyPaths) + ? parsed.readOnlyPaths.map(String).filter(Boolean) + : []; + const hasReadOnlyShortcuts = enabled && readOnlyPaths.length > 0; return { checked: true, updated: updatedPaths.length > 0, alreadyConfigured: updatedPaths.length === 0 && configuredPaths.length > 0, configured: configuredPaths.length > 0, + hasReadOnlyShortcuts, updatedPaths, configuredPaths, + readOnlyPaths, }; } catch (err) { return { @@ -623,8 +1077,10 @@ export async function ensureDesktopLaunchEntriesConfigured({ updated: false, alreadyConfigured: false, configured: false, + hasReadOnlyShortcuts: false, updatedPaths: [], configuredPaths: [], + readOnlyPaths: [], reason: 'win_shortcut_error', error: err?.message || String(err), }; @@ -682,8 +1138,10 @@ export async function ensureDesktopLaunchEntriesConfigured({ updated: updatedPaths.length > 0, alreadyConfigured: updatedPaths.length === 0 && configuredPaths.length > 0, configured: configuredPaths.length > 0, + hasReadOnlyShortcuts: false, updatedPaths, configuredPaths, + readOnlyPaths: [], }; } catch (err) { return { @@ -691,8 +1149,10 @@ export async function ensureDesktopLaunchEntriesConfigured({ updated: false, alreadyConfigured: false, configured: false, + hasReadOnlyShortcuts: false, updatedPaths, configuredPaths, + readOnlyPaths: [], reason: 'linux_desktop_error', error: err?.message || String(err), }; @@ -705,24 +1165,31 @@ export async function ensureDesktopLaunchEntriesConfigured({ updated: false, alreadyConfigured: false, configured: false, + hasReadOnlyShortcuts: false, updatedPaths: [], configuredPaths: [], + readOnlyPaths: [], reason: 'macos_app_bundle_signed', }; } /** - * 当静态环境变量与默认安装目录均未命中(如用户自定义安装至 D:/E: 盘且 Sidecar 未继承 `ANTIGRAVITY_AGENTAPI_EXE`)时, + * 当静态环境变量与默认安装目录均未命中(如用户自定义安装至 D:/E: 盘、Linux 自定义目录或 AppImage)时, * 直接从当前正在运行的宿主进程动态反查主程序绝对路径。 */ -async function discoverRunningHostExecutable({ platform = process.platform, execFileFn = null } = {}) { +async function discoverRunningHostExecutable({ + platform = process.platform, + env = process.env, + execFileFn = null, +} = {}) { const runner = execFileFn || runLauncherExecFile; if (platform === 'win32') { try { + const psExe = execFileFn ? 'powershell.exe' : resolveWindowsPowerShellExecutable(env); const ps = - "@(Get-Process -Name 'Antigravity','Antigravity IDE' -ErrorAction SilentlyContinue | Where-Object { $_.Path } | Select-Object -First 1) | ForEach-Object { [pscustomobject]@{ path = [string]$_.Path; name = [string]$_.ProcessName } } | ConvertTo-Json -Compress"; + "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; @(Get-Process -Name 'Antigravity','Antigravity IDE' -ErrorAction SilentlyContinue | Where-Object { $_.Path } | Select-Object -First 1) | ForEach-Object { [pscustomobject]@{ path = [string]$_.Path; name = [string]$_.ProcessName } } | ConvertTo-Json -Compress"; const out = await runner( - 'powershell.exe', + psExe, ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', ps], { timeoutMs: 4000 } ); @@ -762,6 +1229,59 @@ async function discoverRunningHostExecutable({ platform = process.platform, exec } catch { // 忽略 AppleScript 探测异常 } + } else if (platform === 'linux') { + if (!execFileFn && typeof process.getuid === 'function') { + try { + const myUid = process.getuid(); + for (const name of readdirSync('/proc')) { + if (!/^\d+$/.test(name)) continue; + const procDir = `/proc/${name}`; + try { + const st = statSync(procDir); + if (st.uid !== myUid) continue; + const exeTarget = String(readlinkSync(`${procDir}/exe`) || '').trim(); + if (!exeTarget) continue; + const leaf = basename(exeTarget); + if (!isLinuxAntigravityDesktopLeaf(leaf)) continue; + try { + const envRaw = readFileSync(`${procDir}/environ`, 'utf8'); + for (const entry of envRaw.split('\0')) { + if (entry.startsWith('APPIMAGE=')) { + const appImg = entry.slice('APPIMAGE='.length).trim(); + if (appImg && existsSync(appImg)) { + return { found: true, kind: 'desktop', executablePath: appImg, appBundlePath: '' }; + } + } + } + } catch { + // 忽略 environ 读取异常 + } + if (exeTarget.startsWith('/tmp/.mount_')) continue; + return { found: true, kind: 'desktop', executablePath: exeTarget, appBundlePath: '' }; + } catch { + // 忽略单个瞬态退出的进程目录 + } + } + } catch { + // 忽略 /proc 原生扫描异常,回退外部命令探测 + } + } + if (execFileFn) { + try { + const out = await runner('/bin/sh', ['-c', 'true'], { timeoutMs: 2000 }); + const foundLinuxExe = String(out || '').trim().split(/\r?\n/)[0]?.trim() || ''; + if (foundLinuxExe) { + return { + found: true, + kind: 'desktop', + executablePath: foundLinuxExe, + appBundlePath: '', + }; + } + } catch { + // 忽略模拟探测异常 + } + } } return { found: false, kind: '', executablePath: '', appBundlePath: '' }; } @@ -771,26 +1291,51 @@ function psSingleQuote(val) { } /** - * 构建 Windows 脱离宿主 Job Object 的隐藏重拉内层脚本(写入临时 UTF-8 BOM `.ps1` 文件后交由 `explorer.exe` 拉起,规避 `ShellExecute` 参数长度上限)。 + * 构建 Windows 脱离宿主 Job Object 的隐藏重拉内层脚本(写入临时 UTF-8 BOM `.ps1` 文件后拉起)。 + * + * 权限自适应策略: + * 1. 若存在 All-Users 只读公共快捷方式(`$readOnlyShortcuts.Count -gt 0`)且当前未提权,先通过 `-Verb RunAs` + * 请求用户 UAC 授权一次性修补公共 `.lnk`(用户若点取消仍继续执行当次重拉,不阻塞会话恢复); + * 2. 先尝试常规温和关闭(`CloseMainWindow` + `Stop-Process`); + * 3. 若等待后仍有旧宿主进程存活(例如旧宿主是以管理员身份运行的,普通权限无法关闭),再请求一次 `-Verb RunAs` + * 关闭旧管理员宿主并以管理员身份带参重开; + * 4. 若当前脚本自身因提权运行但原宿主并非管理员(`$wasHostElevated -eq $false`),通过 `Shell.Application` + * 委托桌面 `explorer.exe` 以普通权限启动新客户端,确保资源管理器文件拖拽进窗口不被 UIPI 阻断。 * * @param {string} executablePath * @param {string[]} stalePortFiles * @param {'desktop'|'ide'|''} kind + * @param {{ readOnlyShortcutPaths?: string[], psExePath?: string }} [extra] * @returns {string} */ -export function buildWindowsRelaunchInnerScript(executablePath, stalePortFiles = [], kind = 'desktop') { +export function buildWindowsRelaunchInnerScript( + executablePath, + stalePortFiles = [], + kind = 'desktop', + extra = {} +) { const procName = kind === 'ide' ? 'Antigravity IDE' : 'Antigravity'; + const psExe = String(extra?.psExePath || 'powershell.exe').trim() || 'powershell.exe'; const portLiterals = (Array.isArray(stalePortFiles) ? stalePortFiles : []) .map((p) => String(p || '').trim()) .filter(Boolean) .map(psSingleQuote) .join(', '); + const roLiterals = (Array.isArray(extra?.readOnlyShortcutPaths) ? extra.readOnlyShortcutPaths : []) + .map((p) => String(p || '').trim()) + .filter(Boolean) + .map(psSingleQuote) + .join(', '); return ` Start-Sleep -Milliseconds 480 $exe = ${psSingleQuote(executablePath)} $procName = ${psSingleQuote(procName)} +$psExe = ${psSingleQuote(psExe)} $staleList = @(${portLiterals}) +$readOnlyShortcuts = @(${roLiterals}) +$wasHostElevated = $env:AGY_HOST_WAS_ELEVATED -eq '1' +$isSelfElevated = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) $mySid = (Get-Process -Id $PID).SessionId if (-not $exe -or -not (Test-Path -LiteralPath $exe)) { @@ -798,6 +1343,55 @@ if (-not $exe -or -not (Test-Path -LiteralPath $exe)) { if ($livePath) { $exe = [string]$livePath } } +function Patch-ShortcutList($paths) { + if (-not $paths -or $paths.Count -eq 0) { return } + try { + $ws = New-Object -ComObject WScript.Shell + foreach ($lnk in $paths) { + if (-not $lnk -or -not (Test-Path -LiteralPath $lnk)) { continue } + try { + $sc = $ws.CreateShortcut($lnk) + $cur = [string]$sc.Arguments + if ($cur -notmatch '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { + $sc.Arguments = ($cur.Trim() + ' --remote-debugging-port=0').Trim() + $sc.Save() + } + } catch {} + } + } catch {} +} + +if ($readOnlyShortcuts.Count -gt 0) { + if ($isSelfElevated) { + Patch-ShortcutList $readOnlyShortcuts + } else { + $elevPatchPs1 = Join-Path ([System.IO.Path]::GetTempPath()) ("agy-monitor-uac-lnk-" + $PID + ".ps1") + $roJoined = ($readOnlyShortcuts | ForEach-Object { "'" + ($_.Replace("'", "''")) + "'" }) -join ', ' + $elevBody = @( + "\$ws = New-Object -ComObject WScript.Shell", + "foreach (\$lnk in @($roJoined)) {", + " if (\$lnk -and (Test-Path -LiteralPath \$lnk)) {", + " try {", + " \$sc = \$ws.CreateShortcut(\$lnk)", + " \$cur = [string]\$sc.Arguments", + " if (\$cur -notmatch '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {", + " \$sc.Arguments = (\$cur.Trim() + ' --remote-debugging-port=0').Trim()", + " \$sc.Save()", + " }", + " } catch {}", + " }", + "}", + "Remove-Item -LiteralPath \$PSCommandPath -Force -ErrorAction SilentlyContinue" + ) -join "\`r\`n" + try { + [System.IO.File]::WriteAllText($elevPatchPs1, $elevBody, (New-Object System.Text.UTF8Encoding($true))) + Start-Process -FilePath $psExe -Verb RunAs -WindowStyle Hidden -Wait -ArgumentList @('-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', $elevPatchPs1) -ErrorAction Stop + } catch { + if (Test-Path -LiteralPath $elevPatchPs1) { Remove-Item -LiteralPath $elevPatchPs1 -Force -ErrorAction SilentlyContinue } + } + } +} + $findTargets = { @(Get-Process -Name $procName -ErrorAction SilentlyContinue | Where-Object { $_.SessionId -eq $mySid -and (-not $_.Path -or -not $exe -or [string]::Equals($_.Path, $exe, [System.StringComparison]::OrdinalIgnoreCase)) @@ -817,11 +1411,37 @@ foreach ($p in $remaining) { try { Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue } catch {} } -for ($i = 0; $i -lt 30; $i++) { +for ($i = 0; $i -lt 25; $i++) { if ((& $findTargets).Count -eq 0) { break } Start-Sleep -Milliseconds 200 } +if ((& $findTargets).Count -gt 0 -and -not $isSelfElevated -and $exe -and (Test-Path -LiteralPath $exe)) { + $elevRelaunchPs1 = Join-Path ([System.IO.Path]::GetTempPath()) ("agy-monitor-uac-relaunch-" + $PID + ".ps1") + $staleJoined = ($staleList | ForEach-Object { "'" + ($_.Replace("'", "''")) + "'" }) -join ', ' + $exeLit = "'" + $exe.Replace("'", "''") + "'" + $procLit = "'" + $procName.Replace("'", "''") + "'" + $elevKillBody = @( + "\$mySid = (Get-Process -Id \$PID).SessionId", + "Get-Process -Name $procLit -ErrorAction SilentlyContinue | Where-Object { \$_.SessionId -eq \$mySid } | Stop-Process -Force -ErrorAction SilentlyContinue", + "Start-Sleep -Milliseconds 600", + "foreach (\$fp in @($staleJoined)) { if (\$fp -and (Test-Path -LiteralPath \$fp)) { Remove-Item -LiteralPath \$fp -Force -ErrorAction SilentlyContinue } }", + "\$wd = Split-Path -Parent $exeLit", + "Start-Process -FilePath $exeLit -ArgumentList '--remote-debugging-port=0' -WorkingDirectory \$wd", + "Remove-Item -LiteralPath \$PSCommandPath -Force -ErrorAction SilentlyContinue" + ) -join "\`r\`n" + try { + [System.IO.File]::WriteAllText($elevRelaunchPs1, $elevKillBody, (New-Object System.Text.UTF8Encoding($true))) + Start-Process -FilePath $psExe -Verb RunAs -WindowStyle Hidden -ArgumentList @('-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', $elevRelaunchPs1) -ErrorAction Stop + if ($PSCommandPath -and (Test-Path -LiteralPath $PSCommandPath)) { + Remove-Item -LiteralPath $PSCommandPath -Force -ErrorAction SilentlyContinue + } + exit 0 + } catch { + if (Test-Path -LiteralPath $elevRelaunchPs1) { Remove-Item -LiteralPath $elevRelaunchPs1 -Force -ErrorAction SilentlyContinue } + } +} + foreach ($fp in $staleList) { if ($fp -and (Test-Path -LiteralPath $fp)) { try { Remove-Item -LiteralPath $fp -Force -ErrorAction SilentlyContinue } catch {} @@ -830,7 +1450,16 @@ foreach ($fp in $staleList) { if ($exe -and (Test-Path -LiteralPath $exe)) { $workDir = Split-Path -Parent $exe - Start-Process -FilePath $exe -ArgumentList '--remote-debugging-port=0' -WorkingDirectory $workDir + if ($isSelfElevated -and -not $wasHostElevated) { + try { + $shellApp = New-Object -ComObject Shell.Application + $shellApp.ShellExecute($exe, '--remote-debugging-port=0', $workDir, 'open', 1) + } catch { + Start-Process -FilePath $exe -ArgumentList '--remote-debugging-port=0' -WorkingDirectory $workDir + } + } else { + Start-Process -FilePath $exe -ArgumentList '--remote-debugging-port=0' -WorkingDirectory $workDir + } } if ($PSCommandPath -and (Test-Path -LiteralPath $PSCommandPath)) { @@ -840,16 +1469,44 @@ if ($PSCommandPath -and (Test-Path -LiteralPath $PSCommandPath)) { } const WIN_OUT_OF_JOB_DISPATCH_PS = ` +[Console]::OutputEncoding = [System.Text.Encoding]::UTF8 $ErrorActionPreference = 'Stop' +$psBin = if ($env:AGY_PS_EXE) { $env:AGY_PS_EXE } else { 'powershell.exe' } +$isElev = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) +$env:AGY_HOST_WAS_ELEVATED = if ($isElev) { '1' } else { '0' } $innerArgs = '-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File "' + $env:AGY_RELAUNCH_PS1 + '"' +$fullCmd = '"' + $psBin + '" ' + $innerArgs + +if ($isElev) { + try { + $wmiRes = ([wmiclass]'Win32_Process').Create($fullCmd) + if ($wmiRes -and $wmiRes.ReturnValue -eq 0) { + Write-Output '{"ok":true,"method":"wmi_elevated"}' + exit 0 + } + } catch {} + Start-Process -FilePath $psBin -ArgumentList $innerArgs -WindowStyle Hidden + Write-Output '{"ok":true,"method":"start_process_elevated"}' + exit 0 +} + try { $shellApp = New-Object -ComObject Shell.Application - $shellApp.ShellExecute('powershell.exe', $innerArgs, '', 'open', 0) + $shellApp.ShellExecute($psBin, $innerArgs, '', 'open', 0) Write-Output '{"ok":true,"method":"shell_application"}' -} catch { - Start-Process -FilePath 'powershell.exe' -ArgumentList $innerArgs -WindowStyle Hidden - Write-Output '{"ok":true,"method":"start_process"}' -} + exit 0 +} catch {} + +try { + $wmiRes = ([wmiclass]'Win32_Process').Create($fullCmd) + if ($wmiRes -and $wmiRes.ReturnValue -eq 0) { + Write-Output '{"ok":true,"method":"wmi_fallback"}' + exit 0 + } +} catch {} + +Start-Process -FilePath $psBin -ArgumentList $innerArgs -WindowStyle Hidden +Write-Output '{"ok":true,"method":"start_process"}' `.trim(); /** @@ -860,6 +1517,7 @@ try { * platform?: string, * homeDir?: string, * stalePortFiles?: string[], + * readOnlyShortcutPaths?: string[], * execFileFn?: ((file: string, args: string[], opts?: object) => Promise)|null, * spawnFn?: ((file: string, args: string[], opts?: object) => Promise<{ pid: number }>)|null, * existsFn?: typeof existsSync, @@ -873,6 +1531,7 @@ export async function triggerDesktopHostRelaunch({ platform = process.platform, homeDir = homedir(), stalePortFiles = [], + readOnlyShortcutPaths = [], execFileFn = null, spawnFn = null, existsFn = existsSync, @@ -886,7 +1545,7 @@ export async function triggerDesktopHostRelaunch({ let hostInfo = resolveDesktopHostExecutable({ env, platform, homeDir, existsFn }); if (!hostInfo.found) { - hostInfo = await discoverRunningHostExecutable({ platform, execFileFn }); + hostInfo = await discoverRunningHostExecutable({ platform, env, execFileFn }); } if (!hostInfo.found) { return { @@ -900,12 +1559,20 @@ export async function triggerDesktopHostRelaunch({ const cleanStaleFiles = (Array.isArray(stalePortFiles) ? stalePortFiles : []) .map((p) => String(p || '').trim()) .filter(Boolean); + const cleanReadOnlyPaths = (Array.isArray(readOnlyShortcutPaths) ? readOnlyShortcutPaths : []) + .map((p) => String(p || '').trim()) + .filter(Boolean); if (platform === 'win32') { + const psExe = execFileFn ? 'powershell.exe' : resolveWindowsPowerShellExecutable(env, existsFn); const innerScript = buildWindowsRelaunchInnerScript( hostInfo.executablePath, cleanStaleFiles, - hostInfo.kind + hostInfo.kind, + { + readOnlyShortcutPaths: cleanReadOnlyPaths, + psExePath: psExe, + } ); const tempDir = String(env?.TEMP || env?.TMP || DATA_DIR || homeDir).trim(); mkdirFn(tempDir, { recursive: true }); @@ -915,7 +1582,7 @@ export async function triggerDesktopHostRelaunch({ const runner = execFileFn || runLauncherExecFile; await runner( - 'powershell.exe', + psExe, [ '-Sta', '-NoProfile', @@ -929,6 +1596,7 @@ export async function triggerDesktopHostRelaunch({ timeoutMs: 6000, env: { ...cleanEnv, + AGY_PS_EXE: psExe, AGY_RELAUNCH_PS1: relaunchPs1Path, }, } @@ -973,8 +1641,8 @@ export async function triggerDesktopHostRelaunch({ const linuxScript = [ 'sleep 0.45', 'uid="$(id -u)"', - 'pkill -u "$uid" -x "$AGY_PROC_NAME" >/dev/null 2>&1 || true', - 'i=0; while [ $i -lt 25 ] && pgrep -u "$uid" -x "$AGY_PROC_NAME" >/dev/null 2>&1; do sleep 0.2; i=$((i+1)); done', + 'for pn in "$AGY_PROC_NAME" antigravity Antigravity; do [ -n "$pn" ] && pkill -u "$uid" -x "$pn" >/dev/null 2>&1 || true; done', + 'i=0; while [ $i -lt 25 ] && (pgrep -u "$uid" -x "$AGY_PROC_NAME" >/dev/null 2>&1 || pgrep -u "$uid" -x antigravity >/dev/null 2>&1 || pgrep -u "$uid" -x Antigravity >/dev/null 2>&1); do sleep 0.2; i=$((i+1)); done', 'IFS=":"; for f in $AGY_STALE_PORT_FILES; do [ -n "$f" ] && rm -f "$f"; done', 'nohup "$AGY_RELAUNCH_EXE" --remote-debugging-port=0 >/dev/null 2>&1 &', ].join('; '); diff --git a/sidecars/panel/backend/window-bridge.mjs b/sidecars/panel/backend/window-bridge.mjs index 098141a..ae53f5f 100644 --- a/sidecars/panel/backend/window-bridge.mjs +++ b/sidecars/panel/backend/window-bridge.mjs @@ -714,6 +714,7 @@ export function createWindowBridgeController(options) { onVersionDrift = null, leaseFilePath = '', autoConfigureIdeArgv = options?.env === undefined && options?.homeDir === undefined, + launcherRecheckIntervalMs = 15 * 60 * 1000, launcherExecFileFn = null, launcherFsOps = null, allowDesktopLauncherInTest = false, @@ -743,21 +744,23 @@ export function createWindowBridgeController(options) { let hadInjectedTargets = false; let hadInjectedChatFrames = false; let cdpFallbackActive = false; - let ideArgvProvisioned = false; + let lastLauncherProvisionAtMs = 0; let hostLauncherPromise = null; let argvUpdatedThisBoot = false; let argvConfigured = false; let launcherConfigured = false; + let hasReadOnlyShortcuts = false; const hostExecInfo = resolveDesktopHostExecutable({ env, platform, homeDir, existsFn: existsHostFn, }); - // Windows / macOS 支持从运行中宿主进程动态反查任意盘符路径,因此桌面端环境下即使自定义安装路径不在默认盘符也可一键重拉 + // Windows / macOS / Linux 均支持从运行中宿主进程动态反查路径(含自定义盘符与 AppImage),自定义安装路径亦可一键重拉 const canRelaunch = Boolean( hostExecInfo.found || - ((platform === 'win32' || platform === 'darwin') && options?.existsHostFn === undefined) + ((platform === 'win32' || platform === 'darwin' || platform === 'linux') && + options?.existsHostFn === undefined) ); let lastPersistedLeaseSig = ''; let lastBridgeStatus = { @@ -768,6 +771,7 @@ export function createWindowBridgeController(options) { argvUpdatedThisBoot: false, argvConfigured: false, launcherConfigured: false, + hasReadOnlyShortcuts: false, canRelaunch, updatedAtMs: 0, }; @@ -1209,11 +1213,12 @@ export function createWindowBridgeController(options) { argvUpdatedThisBoot: Boolean(argvUpdatedThisBoot), argvConfigured: Boolean(argvConfigured || launcherConfigured), launcherConfigured: Boolean(launcherConfigured || argvConfigured), + hasReadOnlyShortcuts: Boolean(hasReadOnlyShortcuts), canRelaunch: Boolean(canRelaunch), updatedAtMs: Date.now(), }; if (leasedBySelf && leaseFilePath) { - const sig = `${nextState}:${lastBridgeStatus.aliveCount}:${lastBridgeStatus.targets}:${lastBridgeStatus.argvUpdatedThisBoot ? 1 : 0}:${lastBridgeStatus.launcherConfigured ? 1 : 0}:${lastBridgeStatus.canRelaunch ? 1 : 0}`; + const sig = `${nextState}:${lastBridgeStatus.aliveCount}:${lastBridgeStatus.targets}:${lastBridgeStatus.argvUpdatedThisBoot ? 1 : 0}:${lastBridgeStatus.launcherConfigured ? 1 : 0}:${lastBridgeStatus.hasReadOnlyShortcuts ? 1 : 0}:${lastBridgeStatus.canRelaunch ? 1 : 0}`; if (sig !== lastPersistedLeaseSig) { lastPersistedLeaseSig = sig; saveJson(leaseFilePath, { @@ -1227,6 +1232,7 @@ export function createWindowBridgeController(options) { argvUpdatedThisBoot: lastBridgeStatus.argvUpdatedThisBoot, argvConfigured: lastBridgeStatus.argvConfigured, launcherConfigured: lastBridgeStatus.launcherConfigured, + hasReadOnlyShortcuts: lastBridgeStatus.hasReadOnlyShortcuts, canRelaunch: lastBridgeStatus.canRelaunch, updatedAtMs: Date.now(), }); @@ -1234,13 +1240,13 @@ export function createWindowBridgeController(options) { } } - function provisionHostLaunchersOnce() { - if (ideArgvProvisioned) return Promise.resolve(); + function provisionHostLaunchersOnce({ fastCheckIfActive = false } = {}) { if (hostLauncherPromise) return hostLauncherPromise; hostLauncherPromise = (async () => { const ideRes = ensureIdeRemoteDebuggingArgv({ env, homeDir, enabled: true }); const desktopRes = await ensureDesktopLaunchEntriesConfigured({ enabled: true, + fastCheckIfActive, env, platform, homeDir, @@ -1254,10 +1260,13 @@ export function createWindowBridgeController(options) { if (ideRes.updated || ideRes.alreadyConfigured) { argvConfigured = true; } - if (desktopRes.updated || desktopRes.alreadyConfigured || desktopRes.configured) { - launcherConfigured = true; + launcherConfigured = Boolean( + desktopRes.updated || desktopRes.alreadyConfigured || desktopRes.configured + ); + if (!desktopRes.fastPath) { + hasReadOnlyShortcuts = Boolean(desktopRes.hasReadOnlyShortcuts); } - ideArgvProvisioned = true; + lastLauncherProvisionAtMs = Date.now(); })().finally(() => { hostLauncherPromise = null; }); @@ -1280,10 +1289,6 @@ export function createWindowBridgeController(options) { const enabled = Boolean(curSettings.enableWindowOverlay !== false && mountMode !== 'sidebar'); const contextWindows = curSettings.modelContextWindows || {}; const hasContextWindows = Object.keys(contextWindows).length > 0; - const provPending = - (enabled || hasContextWindows) && autoConfigureIdeArgv && !ideArgvProvisioned - ? provisionHostLaunchersOnce() - : hostLauncherPromise; let leasedBySelf = false; let currentLease = null; @@ -1311,6 +1316,7 @@ export function createWindowBridgeController(options) { argvUpdatedThisBoot: Boolean(lease?.argvUpdatedThisBoot || argvUpdatedThisBoot), argvConfigured: mergedConfigured, launcherConfigured: mergedConfigured, + hasReadOnlyShortcuts: Boolean(lease?.hasReadOnlyShortcuts || hasReadOnlyShortcuts), canRelaunch: Boolean(lease?.canRelaunch ?? canRelaunch), updatedAtMs: Date.now(), }; @@ -1330,13 +1336,24 @@ export function createWindowBridgeController(options) { argvUpdatedThisBoot: Boolean(argvUpdatedThisBoot), argvConfigured: Boolean(argvConfigured || launcherConfigured), launcherConfigured: Boolean(launcherConfigured || argvConfigured), + hasReadOnlyShortcuts: Boolean(hasReadOnlyShortcuts), canRelaunch: Boolean(canRelaunch), updatedAtMs: Date.now(), }); } + const shouldCheckLaunchers = + (enabled || hasContextWindows) && + autoConfigureIdeArgv && + (lastLauncherProvisionAtMs === 0 || + Date.now() - lastLauncherProvisionAtMs >= launcherRecheckIntervalMs); + const isInitialLauncherPass = lastLauncherProvisionAtMs === 0; + const cdpPorts = findActiveDevToolsPorts(); if (!cdpPorts.length) { + const provPending = shouldCheckLaunchers + ? provisionHostLaunchersOnce({ fastCheckIfActive: !isInitialLauncherPass }) + : hostLauncherPromise; if (provPending) { await provPending.catch(() => {}); } @@ -1351,6 +1368,9 @@ export function createWindowBridgeController(options) { const { reachableCount, targets } = await collectAllMainWindowTargets(cdpPorts); if (reachableCount === 0) { + const provPending = shouldCheckLaunchers + ? provisionHostLaunchersOnce({ fastCheckIfActive: !isInitialLauncherPass }) + : hostLauncherPromise; if (provPending) { await provPending.catch(() => {}); } @@ -1362,6 +1382,11 @@ export function createWindowBridgeController(options) { }); return { ok: false, enabled, reason: 'cdp_unreachable', injected: 0 }; } + + if (shouldCheckLaunchers) { + // 调试端口已正常连通时走纯 Node.js 零子进程快检(<2ms),仅在发现未配参快捷方式时才拉起 PowerShell + void provisionHostLaunchersOnce({ fastCheckIfActive: true }).catch(() => {}); + } if (!targets.length) { updateBridgeStatus(enabled ? 'no_targets' : 'disabled', { enabled, @@ -1842,6 +1867,8 @@ export function createWindowBridgeController(options) { const hasCtx = Object.keys(cur.modelContextWindows || {}).length > 0; if (!hasCtx && autoConfigureIdeArgv) { launcherConfigured = false; + hasReadOnlyShortcuts = false; + lastLauncherProvisionAtMs = 0; void ensureDesktopLaunchEntriesConfigured({ enabled: false, env, @@ -1853,7 +1880,7 @@ export function createWindowBridgeController(options) { }).catch(() => {}); } } else { - ideArgvProvisioned = false; + lastLauncherProvisionAtMs = 0; hadInjectedChatFrames = true; } return syncAllWindows({ forceReinject: false }).catch(() => ({ ok: false })); @@ -1865,9 +1892,11 @@ export function createWindowBridgeController(options) { const overlayOn = Boolean(cur.enableWindowOverlay !== false && mountMode !== 'sidebar'); const hasCtx = Object.keys(cur.modelContextWindows || {}).length > 0; if (hasCtx) { - ideArgvProvisioned = false; + lastLauncherProvisionAtMs = 0; } else if (!overlayOn && autoConfigureIdeArgv) { launcherConfigured = false; + hasReadOnlyShortcuts = false; + lastLauncherProvisionAtMs = 0; void ensureDesktopLaunchEntriesConfigured({ enabled: false, env, @@ -1908,6 +1937,7 @@ export function getDefaultWindowBridgeStatus() { argvUpdatedThisBoot: false, argvConfigured: false, launcherConfigured: false, + hasReadOnlyShortcuts: false, canRelaunch: false, updatedAtMs: 0, }; diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 71755bf..5b8a8bc 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/settings/BridgeStatusNotice.js b/sidecars/panel/src/components/settings/BridgeStatusNotice.js index ee3e47b..9b760df 100644 --- a/sidecars/panel/src/components/settings/BridgeStatusNotice.js +++ b/sidecars/panel/src/components/settings/BridgeStatusNotice.js @@ -186,6 +186,7 @@ export const BridgeStatusNotice = defineComponent({ function syncActionButtons() { const canRelaunch = lastPayload.windowBridge?.canRelaunch !== false; + const needsAuth = Boolean(lastPayload.windowBridge?.hasReadOnlyShortcuts); patchAttr(relaunchBtnEl, 'hidden', !canRelaunch); patchAttr(relaunchBtnEl, 'disabled', relaunchState === 'relaunching'); patchText( @@ -194,7 +195,9 @@ export const BridgeStatusNotice = defineComponent({ ? t('settings.bridge.relaunchingBtn') : relaunchState === 'failed' ? t('settings.bridge.relaunchFailed') - : t('settings.bridge.relaunchBtn') + : needsAuth + ? t('settings.bridge.relaunchAuthBtn') + : t('settings.bridge.relaunchBtn') ); patchSvgIcon(copyBtnIconEl, copied ? 'check' : 'copy'); @@ -227,38 +230,44 @@ export const BridgeStatusNotice = defineComponent({ patchAttr(rootEl, 'hidden', !shouldShow); if (!shouldShow) return; + const plat = String(lastPayload.hostPlatform || '').trim().toLowerCase(); + const hasReadOnlyShortcuts = Boolean(wb?.hasReadOnlyShortcuts); + const isMacDesktop = plat === 'darwin' && !wb?.argvConfigured; const isAutoConfigured = Boolean( wb?.launcherConfigured || wb?.argvUpdatedThisBoot || wb?.argvConfigured ); + const useRestartTheme = !hasReadOnlyShortcuts && (isAutoConfigured || isMacDesktop); + patchClasses(rootEl, { - 'is-restart': isAutoConfigured, - 'is-warn': !isAutoConfigured, + 'is-restart': useRestartTheme, + 'is-warn': !useRestartTheme, }); - patchSvgIcon(headIconEl, isAutoConfigured ? 'refresh' : 'warning'); + patchSvgIcon(headIconEl, useRestartTheme ? 'refresh' : 'warning'); let titleText = ''; - if (isAutoConfigured) { + let bodyText = ''; + if (hasReadOnlyShortcuts) { + titleText = contextMode + ? t('settings.bridge.ctxReadOnlyTitle') + : t('settings.bridge.readOnlyTitle'); + bodyText = t('settings.bridge.readOnlyBody'); + } else if (isMacDesktop) { + titleText = contextMode + ? t('settings.bridge.ctxMacTitle') + : t('settings.bridge.macTitle'); + bodyText = t('settings.bridge.guideMac'); + } else if (isAutoConfigured) { titleText = contextMode ? t('settings.bridge.ctxRestartTitle') : t('settings.bridge.restartTitle'); - } else if (contextMode) { - titleText = t('settings.bridge.ctxTitle'); - } else if (state === 'cdp_unreachable') { - titleText = t('settings.bridge.unreachableTitle'); - } else { - titleText = t('settings.bridge.noPortTitle'); - } - - const plat = String(lastPayload.hostPlatform || '').trim().toLowerCase(); - let bodyText = ''; - if (isAutoConfigured) { bodyText = t('settings.bridge.restartBody'); - } else if (plat === 'darwin') { - bodyText = t('settings.bridge.guideMac'); - } else if (plat === 'linux') { - bodyText = t('settings.bridge.guideLinux'); } else { - bodyText = t('settings.bridge.guideWin'); + titleText = contextMode + ? t('settings.bridge.ctxTitle') + : state === 'cdp_unreachable' + ? t('settings.bridge.unreachableTitle') + : t('settings.bridge.noPortTitle'); + bodyText = plat === 'linux' ? t('settings.bridge.guideLinux') : t('settings.bridge.guideWin'); } patchText(titleEl, titleText); diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index f712f8b..7982e29 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -437,14 +437,20 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.str.mountSidebar': 'Sidebar Only', 'settings.bridge.restartTitle': 'Launch Flag Auto-Configured — Restart Once to Activate', 'settings.bridge.ctxRestartTitle': 'Launch Flag Auto-Configured — Restart Once for Context Override', - 'settings.bridge.restartBody': 'Automatically added --remote-debugging-port=0 to your shortcuts and startup entries (future launches mount 100% automatically). Click below to close tray processes and relaunch now.', + 'settings.bridge.restartBody': 'Automatically added --remote-debugging-port=0 to your shortcuts, startup entries, and protocol handlers (subsequent shortcut launches mount automatically). Click below to close background processes and relaunch now.', + 'settings.bridge.readOnlyTitle': 'Public Shortcut Protected — Authorize & Relaunch to Activate', + 'settings.bridge.ctxReadOnlyTitle': 'Public Shortcut Protected — Authorize & Relaunch for Context Override', + 'settings.bridge.readOnlyBody': 'Personal launch entries are configured, but public shortcuts require administrator permission. Click below and approve the system prompt to patch public shortcuts once and relaunch.', + 'settings.bridge.macTitle': 'Debug Port Inactive — One-Click Relaunch to Enable Mount', + 'settings.bridge.ctxMacTitle': 'Debug Port Inactive — One-Click Relaunch for Context Override', 'settings.bridge.noPortTitle': 'Local Debug Port Missing — Window Mount Inactive', 'settings.bridge.unreachableTitle': 'Local Debug Port Not Ready — Window Mount Inactive', 'settings.bridge.ctxTitle': 'Local Debug Port Inactive — Context Override Pending', 'settings.bridge.guideWin': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to auto-configure shortcuts, close tray background processes, and relaunch.', - 'settings.bridge.guideMac': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to relaunch with the flag in one click, or run open -a "Antigravity" --args --remote-debugging-port=0.', + 'settings.bridge.guideMac': 'Due to macOS app code signing, cold launches from Dock omit the debug port flag. Click below to relaunch with the flag in one click (stays active until you fully Quit via Cmd+Q).', 'settings.bridge.guideLinux': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to update your .desktop launcher and relaunch.', 'settings.bridge.relaunchBtn': 'Relaunch & Enable Mount', + 'settings.bridge.relaunchAuthBtn': 'Authorize & Relaunch', 'settings.bridge.relaunchingBtn': 'Relaunching Host...', 'settings.bridge.relaunchFailed': 'Auto-relaunch failed — quit from tray and retry', 'settings.bridge.dismissAria': 'Dismiss notice for now', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 206be74..d30607e 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -437,14 +437,20 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.str.mountSidebar': '仅侧边栏', 'settings.bridge.restartTitle': '已自动补齐启动参数,重启一次即可启用悬浮胶囊', 'settings.bridge.ctxRestartTitle': '已自动补齐启动参数,重启一次即可激活上下文覆写', - 'settings.bridge.restartBody': '已自动为桌面 / 开始菜单 / 任务栏快捷方式及自启项写入 --remote-debugging-port=0(后续每次正常打开均 100% 全自动挂载)。点击下方按钮即可退出托盘后台并立即生效。', + 'settings.bridge.restartBody': '已自动为快捷方式、自启项及协议关联写入 --remote-debugging-port=0(后续通过常规快捷方式打开均自动生效)。点击下方按钮即可退出后台进程并立即生效。', + 'settings.bridge.readOnlyTitle': '公共桌面快捷方式受权限保护,授权重启即可生效', + 'settings.bridge.ctxReadOnlyTitle': '公共桌面快捷方式受权限保护,授权重启即可激活上下文覆写', + 'settings.bridge.readOnlyBody': '个人启动项已配好,但公共桌面或开始菜单快捷方式需管理员权限修改。点击下方按钮并在系统弹窗中确认授权,即可一次性修补公共图标并带参重开(后续日常打开均自动生效)。', + 'settings.bridge.macTitle': '当前会话未开启调试端口,一键重开即可启用挂载', + 'settings.bridge.ctxMacTitle': '当前会话未开启调试端口,一键重开即可激活上下文覆写', 'settings.bridge.noPortTitle': '未检测到本地调试端口,主窗口挂载暂未生效', 'settings.bridge.unreachableTitle': '本地调试端口未就绪,主窗口挂载暂未生效', 'settings.bridge.ctxTitle': '未连通本地调试通道,上下文窗口覆写暂未注入', 'settings.bridge.guideWin': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可自动补齐快捷方式参数、退出托盘后台并带参重启生效。', - 'settings.bridge.guideMac': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可一键带参重开客户端生效,也可复制参数通过 open -a "Antigravity" --args --remote-debugging-port=0 启动。', + 'settings.bridge.guideMac': '受 macOS 应用签名限制,从 Dock 直接冷启动默认不带调试端口参数。点击下方按钮即可一键带参重开恢复(日常仅关窗不完全退出 Cmd+Q 则持续有效)。', 'settings.bridge.guideLinux': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可自动写入 .desktop 启动器并重启生效。', 'settings.bridge.relaunchBtn': '立即重启并启用挂载', + 'settings.bridge.relaunchAuthBtn': '授权修补并立即重启', 'settings.bridge.relaunchingBtn': '正在重启客户端...', 'settings.bridge.relaunchFailed': '自动重启失败,请从托盘退出后重试', 'settings.bridge.dismissAria': '暂时关闭提示', diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index a479c1f..45af999 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -25,9 +25,13 @@ import { buildWindowsRelaunchInnerScript, ensureDesktopLaunchEntriesConfigured, ensureRemoteDebugFlagInArgs, + inspectWindowsLnkBuffer, patchLinuxDesktopEntryText, patchWindowsRunRegistryCommand, + patchWindowsShellOpenCommand, + probeWindowsShortcutsFast, resolveDesktopHostExecutable, + resolveWindowsPowerShellExecutable, triggerDesktopHostRelaunch, } from '../backend/desktop-launcher-config.mjs'; import { @@ -4909,6 +4913,107 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi ); assert.equal(winRunIdeIgnored.matched, false); + // System32 PowerShell resolution & HKCU\Software\Classes shell\open\command patching + assert.equal( + resolveWindowsPowerShellExecutable( + { SystemRoot: 'D:\\WinSys' }, + (p) => p === 'D:\\WinSys\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' + ), + 'D:\\WinSys\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' + ); + assert.equal( + resolveWindowsPowerShellExecutable({ SystemRoot: 'D:\\Missing' }, () => false), + 'powershell.exe' + ); + + const shellOpenPatched = patchWindowsShellOpenCommand( + '"C:\\Users\\Dev\\AppData\\Local\\Programs\\Antigravity\\Antigravity.exe" -- "%1"', + { enabled: true } + ); + assert.equal(shellOpenPatched.matched, true); + assert.equal(shellOpenPatched.changed, true); + assert.equal( + shellOpenPatched.value, + '"C:\\Users\\Dev\\AppData\\Local\\Programs\\Antigravity\\Antigravity.exe" --remote-debugging-port=0 -- "%1"', + 'Inserts flag before -- "%1" so Chromium parses it as a switch' + ); + const shellOpenRollback = patchWindowsShellOpenCommand(shellOpenPatched.value, { enabled: false }); + assert.equal(shellOpenRollback.changed, true); + assert.equal( + shellOpenRollback.value, + '"C:\\Users\\Dev\\AppData\\Local\\Programs\\Antigravity\\Antigravity.exe" -- "%1"' + ); + assert.equal( + patchWindowsShellOpenCommand( + '"C:\\Users\\Dev\\AppData\\Local\\Programs\\Antigravity IDE\\Antigravity IDE.exe" "--open-url" "--" "%1"', + { enabled: true } + ).matched, + false + ); + + // Zero-subprocess binary .lnk inspection & non-recursive folder boundary verification + const makeFakeLnkBuf = (targetPath, argsStr = '') => + Buffer.concat([ + Buffer.alloc(76, 0x4c), + Buffer.from(`${targetPath}\0${argsStr}\0`, 'utf16le'), + ]); + assert.deepEqual( + inspectWindowsLnkBuffer( + makeFakeLnkBuf('C:\\App\\Antigravity.exe', '--remote-debugging-port=0') + ), + { matched: true, hasDebugPort: true } + ); + assert.deepEqual( + inspectWindowsLnkBuffer(makeFakeLnkBuf('C:\\App\\Antigravity IDE.exe', '')), + { matched: false, hasDebugPort: false } + ); + + const visitedDirs = []; + const fakeDesktopDir = 'C:\\Users\\Dev\\Desktop'; + const fakeProgramsDir = 'C:\\Users\\Dev\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs'; + const fakeAgySubDir = `${fakeProgramsDir}\\Antigravity`; + const fastProbeRes = probeWindowsShortcutsFast({ + env: { + USERPROFILE: 'C:\\Users\\Dev', + APPDATA: 'C:\\Users\\Dev\\AppData\\Roaming', + PUBLIC: 'C:\\Users\\Public', + ProgramData: 'C:\\ProgramData', + }, + homeDir: 'C:\\Users\\Dev', + fsOps: { + readdirFn: (dir) => { + visitedDirs.push(dir); + if (dir === fakeDesktopDir) { + return [ + { name: 'Antigravity.lnk', isFile: () => true, isDirectory: () => false }, + { name: 'huge-repo-with-node_modules', isFile: () => false, isDirectory: () => true }, + ]; + } + if (dir === fakeProgramsDir) { + return [ + { name: 'Visual Studio 2022', isFile: () => false, isDirectory: () => true }, + { name: 'Antigravity', isFile: () => false, isDirectory: () => true }, + ]; + } + if (dir === fakeAgySubDir) { + return [{ name: 'Antigravity IDE.lnk', isFile: () => true, isDirectory: () => false }]; + } + return []; + }, + statFn: () => ({ size: 512 }), + readFn: (p) => + p.endsWith('Antigravity IDE.lnk') + ? makeFakeLnkBuf('C:\\App\\Antigravity IDE.exe', '') + : makeFakeLnkBuf('C:\\App\\Antigravity.exe', '--remote-debugging-port=0'), + }, + }); + assert.equal(fastProbeRes.allConfigured, true); + assert.equal( + visitedDirs.some((d) => d.includes('huge-repo') || d.includes('Visual Studio')), + false, + 'Never recurses into Desktop subfolders or unrelated Start Menu vendor folders' + ); + const linuxDesktopRaw = [ '[Desktop Entry]', 'Name=Antigravity', @@ -4924,6 +5029,43 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi assert.equal(linuxReverted.changed, true); assert.equal(linuxReverted.text, linuxDesktopRaw); + const linuxAppImageRaw = [ + '[Desktop Entry]', + 'Name=Antigravity', + 'Exec=env DESKTOPINTEGRATION=false "/home/alice/Apps/Antigravity-2.33.0-x86_64.AppImage" %U', + 'Type=Application', + '', + ].join('\n'); + const linuxAppImagePatched = patchLinuxDesktopEntryText(linuxAppImageRaw, { enabled: true }); + assert.equal(linuxAppImagePatched.matched, true); + assert.equal(linuxAppImagePatched.changed, true); + assert.match( + linuxAppImagePatched.text, + /Exec=env DESKTOPINTEGRATION=false "\/home\/alice\/Apps\/Antigravity-2\.33\.0-x86_64\.AppImage" --remote-debugging-port=0 %U/ + ); + assert.equal( + patchLinuxDesktopEntryText(linuxAppImagePatched.text, { enabled: false }).text, + linuxAppImageRaw + ); + assert.equal( + patchLinuxDesktopEntryText('Exec=env FOO=1 /opt/antigravity-ide/antigravity-ide %F', { + enabled: true, + }).matched, + false + ); + + const resolvedLinuxAppImage = resolveDesktopHostExecutable({ + env: { + APPIMAGE: '/home/alice/Apps/Antigravity-2.33.0.AppImage', + ANTIGRAVITY_AGENTAPI_EXE: '/tmp/.mount_Antigr123/resources/bin/language_server_linux_x64', + }, + platform: 'linux', + homeDir: '/home/alice', + existsFn: (p) => p === '/home/alice/Apps/Antigravity-2.33.0.AppImage', + }); + assert.equal(resolvedLinuxAppImage.found, true); + assert.equal(resolvedLinuxAppImage.executablePath, '/home/alice/Apps/Antigravity-2.33.0.AppImage'); + // 3. Host executable resolution from ANTIGRAVITY_AGENTAPI_EXE & clean relaunch env sanitization const resolvedWinHost = resolveDesktopHostExecutable({ env: { @@ -5038,8 +5180,9 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi /--remote-debugging-port=0 %U/ ); - // Verify Windows shortcut auto-provisioning + stale port (`cdp_unreachable`) status reporting + clean rollback on disable + // Verify Windows shortcut auto-provisioning + read-only public shortcut tracking + periodic recheck + clean rollback const winPsCalls = []; + let simulateReadOnlyPublicDesktop = false; const mockWinExec = async (file, args, opts) => { winPsCalls.push({ file, args, env: opts?.env }); const enabledFlag = opts?.env?.AGY_LAUNCH_ENABLED === '1'; @@ -5051,6 +5194,10 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi configuredPaths: enabledFlag ? ['C:\\Users\\Admin\\Desktop\\Antigravity.lnk', 'C:\\TaskBar\\Antigravity.lnk'] : [], + readOnlyPaths: + enabledFlag && simulateReadOnlyPublicDesktop + ? ['C:\\Users\\Public\\Desktop\\Antigravity.lnk'] + : [], }); }; @@ -5069,6 +5216,7 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi homeDir, leaseFilePath: leaseFile, autoConfigureIdeArgv: true, + launcherRecheckIntervalMs: 25, launcherExecFileFn: mockWinExec, allowDesktopLauncherInTest: true, }); @@ -5079,10 +5227,18 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi assert.equal(stWin.state, 'cdp_unreachable'); assert.equal(stWin.argvUpdatedThisBoot, true); assert.equal(stWin.launcherConfigured, true); + assert.equal(stWin.hasReadOnlyShortcuts, false); assert.equal(stWin.canRelaunch, true); assert.equal(winPsCalls.length, 1); assert.equal(winPsCalls[0].env.AGY_LAUNCH_ENABLED, '1'); + // Periodic re-check after cooldown detects NSIS installer-wiped or read-only public shortcuts + simulateReadOnlyPublicDesktop = true; + await new Promise((r) => setTimeout(r, 35)); + await ctrlWin.syncAllWindows(); + assert.equal(winPsCalls.length, 2, 'Re-provisions automatically once cooldown interval elapses'); + assert.equal(ctrlWin.getBridgeStatus().hasReadOnlyShortcuts, true); + // Disabling overlay (Sidebar Only) cleanly triggers shortcut flag rollback currentMountSettings = { windowMountMode: 'sidebar', @@ -5091,8 +5247,9 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi }; await ctrlWin.notifySettingChanged(false); await new Promise((r) => setTimeout(r, 10)); - assert.equal(winPsCalls.length, 2); - assert.equal(winPsCalls[1].env.AGY_LAUNCH_ENABLED, '0'); + assert.equal(winPsCalls.length, 3); + assert.equal(winPsCalls[2].env.AGY_LAUNCH_ENABLED, '0'); + assert.equal(ctrlWin.getBridgeStatus().hasReadOnlyShortcuts, false); await ctrlWin.stop(); // Verify Windows out-of-job Shell.Application relaunch payload (.ps1 file with UTF-8 BOM) & macOS open -a relaunch @@ -5159,10 +5316,35 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi assert.equal(macSpawnArgs.env.AGY_RELAUNCH_APP, '/Applications/Antigravity.app'); assert.match(macSpawnArgs.args[1], /open -a "\$AGY_RELAUNCH_APP" --args --remote-debugging-port=0/); - // Explicit ANTIGRAVITY_DEVTOOLS_PORT fallback still works seamlessly - const innerScriptCheck = buildWindowsRelaunchInnerScript(fakeExe, [stalePortFile], 'desktop'); + // Verify Linux /proc dynamic AppImage discovery & multi-comm pkill handling + let linuxSpawnArgs = null; + const relaunchLinuxRes = await triggerDesktopHostRelaunch({ + env: { PATH: '/usr/bin:/bin' }, + platform: 'linux', + homeDir: '/home/alice', + stalePortFiles: ['/home/alice/.config/Antigravity/DevToolsActivePort'], + allowInTest: true, + existsFn: () => false, + execFileFn: async () => '/home/alice/Apps/Antigravity-2.33.0.AppImage\n', + spawnFn: async (file, args, opts) => { + linuxSpawnArgs = { file, args, env: opts?.env }; + return { pid: 5678 }; + }, + }); + assert.equal(relaunchLinuxRes.ok, true); + assert.equal(linuxSpawnArgs.env.AGY_RELAUNCH_EXE, '/home/alice/Apps/Antigravity-2.33.0.AppImage'); + assert.match(linuxSpawnArgs.args[1], /for pn in "\$AGY_PROC_NAME" antigravity Antigravity/); + + // Explicit ANTIGRAVITY_DEVTOOLS_PORT fallback & UAC read-only shortcut + de-elevation script generation + const innerScriptCheck = buildWindowsRelaunchInnerScript(fakeExe, [stalePortFile], 'desktop', { + readOnlyShortcutPaths: ['C:\\Users\\Public\\Desktop\\Antigravity.lnk'], + psExePath: 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', + }); assert.match(innerScriptCheck, /CloseMainWindow/); assert.match(innerScriptCheck, /Stop-Process/); + assert.match(innerScriptCheck, /-Verb RunAs/); + assert.match(innerScriptCheck, /C:\\Users\\Public\\Desktop\\Antigravity\.lnk/); + assert.match(innerScriptCheck, /\$isSelfElevated -and -not \$wasHostElevated/); } finally { fs.rmSync(simTmp, { recursive: true, force: true }); } @@ -5251,7 +5433,23 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi ); assert.match(strTab.refs.mountBridgeNotice.refs.relaunchBtnEl.textContent, /正在重启客户端/); - // macOS unconfigured state -> `.is-warn` with 1-click relaunch + copy button + // All-Users read-only Public Desktop shortcut -> `.is-warn` + UAC authorization button copy + strTab.refs.renderSettings( + { windowMountMode: 'dual', enableWindowOverlay: true }, + { + state: 'no_devtools_port', + argvUpdatedThisBoot: true, + argvConfigured: true, + launcherConfigured: true, + hasReadOnlyShortcuts: true, + canRelaunch: true, + }, + 'win32' + ); + assert.equal(noticeEl.classList.contains('is-warn'), true); + assert.match(noticeEl.textContent, /公共桌面快捷方式受权限保护/); + + // macOS Desktop -> honest code-signing notice with `.is-restart` + 1-click relaunch + copy button strTab.refs.renderSettings( { windowMountMode: 'dual', enableWindowOverlay: true }, { @@ -5259,12 +5457,13 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi argvUpdatedThisBoot: false, argvConfigured: false, launcherConfigured: false, + hasReadOnlyShortcuts: false, canRelaunch: true, }, 'darwin' ); - assert.equal(noticeEl.classList.contains('is-warn'), true); - assert.match(noticeEl.textContent, /open -a "Antigravity" --args --remote-debugging-port=0/); + assert.equal(noticeEl.classList.contains('is-restart'), true); + assert.match(noticeEl.textContent, /macOS 应用签名限制/); strTab.refs.mountBridgeNotice.refs.copyBtnEl.dispatchEvent({ type: 'click' }); await new Promise((r) => setTimeout(r, 0)); @@ -5275,10 +5474,16 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi const globalBanner = BridgeStatusNotice({ dismissible: true }); globalBanner.refs.update({ visible: true, - windowBridge: { state: 'no_devtools_port', launcherConfigured: true, canRelaunch: true }, + windowBridge: { + state: 'no_devtools_port', + launcherConfigured: true, + hasReadOnlyShortcuts: true, + canRelaunch: true, + }, hostPlatform: 'win32', }); assert.equal(globalBanner.el.hasAttribute('hidden'), false); + assert.match(globalBanner.refs.relaunchBtnEl.textContent, /授权修补并立即重启/); globalBanner.refs.dismissBtnEl.dispatchEvent({ type: 'click' }); assert.equal(globalBanner.el.hasAttribute('hidden'), true); globalBanner.refs.update({ @@ -5293,10 +5498,21 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi }); assert.equal(globalBanner.el.hasAttribute('hidden'), false, 'Re-armed after active cycle'); - // English localization check + // English localization check across macOS & read-only shortcut states setI18nLanguage('en-US'); strTab.refs.refreshLabels(); - assert.match(noticeEl.textContent, /Local Debug Port Missing/); + assert.match(noticeEl.textContent, /Due to macOS app code signing/); + globalBanner.refs.update({ + visible: true, + windowBridge: { + state: 'no_devtools_port', + launcherConfigured: true, + hasReadOnlyShortcuts: true, + canRelaunch: true, + }, + hostPlatform: 'win32', + }); + assert.match(globalBanner.refs.relaunchBtnEl.textContent, /Authorize & Relaunch/); // Switching to Sidebar Only hides notice immediately strTab.refs.renderSettings( From 2c211f67cc1be68ab0f6499435fe105078bc36ff Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Thu, 19 Nov 2026 09:34:20 +0900 Subject: [PATCH 02/14] feat(panel): add Native Swarm mode compatibility and distinct worker telemetry MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Guard conversation_parents against forked Swarm Workers (subagentSpec or trajectoryType != 22) and selectively decode CORTEX_STEP_TYPE_SYSTEM_MESSAGE (step_type = 101) for child trajectories only - Parse swarm, post_message, read_board, and swarm_wait tool calls, split zero-human-turn worker trajectories on initial brief / @mention / cron wakeup boundaries, and downgrade swarm_wait parked workers from RUNNING to IDLE ('waiting') while surfacing killed workers ('killed') - Scan brain//.system_generated/swarm/members.json with mtime+size memoization, sort workers chronologically, assign independent swarm_worker ordinals (蜂k / Wk) separate from standard subagents (子k / Sk) and side questions (问k / Qk), and preserve 100% of worker token/USD billing - Render Swarm counts, titles, scrollable sorted live worker lists, and one-shot auto-focus when navigating host routes to /c/, backed by E2E and binary SQLite tests --- sidecars/panel/app.js | 498 +++++-- sidecars/panel/backend/api-actions.mjs | 18 +- sidecars/panel/backend/cli-sqlite-reader.mjs | 51 +- sidecars/panel/backend/local-scanner.mjs | 293 +++- sidecars/panel/backend/telemetry-builder.mjs | 247 +++- sidecars/panel/index.html | 4 +- .../src/components/layout/TopSessionHeader.js | 96 +- .../components/layout/WindowOverlayShell.js | 37 +- .../components/widgets/CapsuleBarWidget.js | 19 +- .../components/widgets/LiveActivityWidget.js | 131 +- sidecars/panel/src/core/formatters.js | 96 +- sidecars/panel/src/i18n/en-US.js | 27 + sidecars/panel/src/i18n/zh-CN.js | 27 + sidecars/panel/src/store/telemetryStore.js | 61 + sidecars/panel/src/styles/views-overview.css | 27 + sidecars/panel/styles.css | 27 + sidecars/panel/test/backend-harness.mjs | 20 +- sidecars/panel/test/swarm-mode.test.mjs | 1275 +++++++++++++++++ sidecars/panel/trajectory-metrics.mjs | 369 ++++- 19 files changed, 3077 insertions(+), 246 deletions(-) create mode 100644 sidecars/panel/test/swarm-mode.test.mjs diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 1d94acd..5de2411 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1043,6 +1043,8 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'header.lockedSession': '已锁定会话 ({id})', 'header.lockedMeta': '已锁定', 'header.convMetaWithSubs': '主{main} · {subs}子 (共{total}步)', + 'header.convMetaWithSwarm': '主{main} · {swarm}蜂 (共{total}步)', + 'header.convMetaWithSwarmAndSubs': '主{main} · {swarm}蜂 · {subs}子 (共{total}步)', 'header.convMetaSteps': '{count}步', 'header.hasUpdate': '有新版本', 'header.upgradeToVer': '升级 v{ver}', @@ -1081,6 +1083,11 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'fmt.subAgent': '子代理', 'fmt.subBadge': '子{index}', 'fmt.subBadgeShort': '子', + 'fmt.swarmAgent': '蜂群', + 'fmt.swarmBadge': '蜂{index}', + 'fmt.swarmBadgeShort': '蜂', + 'fmt.swarmMonitorHint': '巡检', + 'fmt.swarmNarratorHint': '旁白', 'fmt.sideQuestion': '旁路提问', 'fmt.sideBadge': '旁{index}', 'fmt.sideBadgeShort': '旁', @@ -1094,6 +1101,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'capsule.multiZero': '0 运行中', 'capsule.multiRunning': '{count} 运行中', 'capsule.multiRunningWithSubs': '{count} 运行 · {subs} 子', + 'capsule.multiRunningWithSwarm': '{count} 运行 · {subs} 蜂', 'capsule.tpsRunning': '生成中', 'capsule.tpsIdle': '待命', 'capsule.quotaLeft': '余 {pct}%', @@ -1114,6 +1122,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'multi.empty': '当前暂无在线运行的会话', 'multi.allIdle': '全部待命', 'multi.metaWithSubs': '{main} 主会话 · {subs} 子代理运行中', + 'multi.metaWithSwarm': '{main} 主会话 · {subs} 蜂群运行中', 'multi.metaMainOnly': '{main} 个会话运行中', 'multi.hereTag': '本窗', 'multi.inspectSessionTitle': '点击在监控面板中检视会话:{title}', @@ -1210,10 +1219,16 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'live.thinking': '推理中', 'live.generating': '生成中', 'live.running': '运行中', + 'live.waiting': '待命中', + 'live.killed': '已终止', 'live.done': '已完成', 'live.doneWithSteps': '已完成 ({steps} 步)', + 'live.waitingWithSteps': '待命中 ({steps} 步)', + 'live.killedWithSteps': '已终止 ({steps} 步)', 'live.subToggleRunning': '子代理 {run}/{total} {arrow}', 'live.subToggleIdle': '子代理 ({total}) {arrow}', + 'live.swarmToggleRunning': '蜂群 {run}/{total} {arrow}', + 'live.swarmToggleIdle': '蜂群 ({total}) {arrow}', 'live.subCollapseTitle': '点击收起子代理列表', 'live.subExpandTitle': '点击展开查看子代理缩略状态', @@ -1584,6 +1599,15 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'live.act.invoke_subagent': '调用子代理', 'live.act.send_message': '通信子代理', 'live.act.manage_subagents': '管理子代理', + 'live.act.swarm_add': '派生工蜂', + 'live.act.swarm_title': '命名蜂群', + 'live.act.swarm_kill': '终止工蜂', + 'live.act.swarm_model': '切换工蜂模型', + 'live.act.swarm_channel': '蜂群频道', + 'live.act.swarm_status': '巡检蜂群', + 'live.act.post_message': '发布看板', + 'live.act.read_board': '读取看板', + 'live.act.swarm_wait': '看板待命', 'live.act.manage_task': '后台任务', 'live.act.schedule': '定时任务', 'live.act.ask_question': '等待用户选择', @@ -1594,6 +1618,9 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'live.act.compacting': '上下文压缩', 'live.act.responding': '正在输出回复', 'live.act.waiting_subagent': '等待子代理', + 'live.act.waiting_swarm': '等待工蜂', + 'live.act.swarm_waiting': '待命中', + 'live.act.swarm_killed': '已终止', 'live.act.starting': '启动中', 'live.act.done': '已完成', 'live.act.awaitingApproval': '等待确认 · {label}', @@ -1679,6 +1706,8 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'header.lockedSession': 'Pinned Session ({id})', 'header.lockedMeta': 'Pinned', 'header.convMetaWithSubs': 'Main {main} · {subs} sub ({total} steps)', + 'header.convMetaWithSwarm': 'Main {main} · {swarm} swarm ({total} steps)', + 'header.convMetaWithSwarmAndSubs': 'Main {main} · {swarm} swarm · {subs} sub ({total} steps)', 'header.convMetaSteps': '{count} steps', 'header.hasUpdate': 'Update', 'header.upgradeToVer': 'Update v{ver}', @@ -1717,6 +1746,11 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'fmt.subAgent': 'Subagent', 'fmt.subBadge': 'S{index}', 'fmt.subBadgeShort': 'Sub', + 'fmt.swarmAgent': 'Swarm', + 'fmt.swarmBadge': 'W{index}', + 'fmt.swarmBadgeShort': 'Swarm', + 'fmt.swarmMonitorHint': 'Monitor', + 'fmt.swarmNarratorHint': 'Narrator', 'fmt.sideQuestion': 'Side Question', 'fmt.sideBadge': 'Q{index}', 'fmt.sideBadgeShort': 'Q', @@ -1730,6 +1764,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'capsule.multiZero': '0 active', 'capsule.multiRunning': '{count} active', 'capsule.multiRunningWithSubs': '{count} active · {subs} sub', + 'capsule.multiRunningWithSwarm': '{count} active · {subs} swarm', 'capsule.tpsRunning': 'Running', 'capsule.tpsIdle': 'Idle', 'capsule.quotaLeft': '{pct}% left', @@ -1750,6 +1785,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'multi.empty': 'No active running sessions', 'multi.allIdle': 'All idle', 'multi.metaWithSubs': '{main} main · {subs} subagents active', + 'multi.metaWithSwarm': '{main} main · {subs} swarm active', 'multi.metaMainOnly': '{main} sessions active', 'multi.hereTag': 'Here', 'multi.inspectSessionTitle': 'Inspect session in monitor: {title}', @@ -1846,10 +1882,16 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'live.thinking': 'Thinking', 'live.generating': 'Generating', 'live.running': 'Running', + 'live.waiting': 'Waiting', + 'live.killed': 'Killed', 'live.done': 'Done', 'live.doneWithSteps': 'Done ({steps} steps)', + 'live.waitingWithSteps': 'Waiting ({steps} steps)', + 'live.killedWithSteps': 'Killed ({steps} steps)', 'live.subToggleRunning': 'Subagents {run}/{total} {arrow}', 'live.subToggleIdle': 'Subagents ({total}) {arrow}', + 'live.swarmToggleRunning': 'Swarm {run}/{total} {arrow}', + 'live.swarmToggleIdle': 'Swarm ({total}) {arrow}', 'live.subCollapseTitle': 'Collapse subagent list', 'live.subExpandTitle': 'Expand subagent activity list', @@ -2220,6 +2262,15 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'live.act.invoke_subagent': 'Invoke Subagent', 'live.act.send_message': 'Message Subagent', 'live.act.manage_subagents': 'Manage Subagents', + 'live.act.swarm_add': 'Spawn Worker', + 'live.act.swarm_title': 'Name Swarm', + 'live.act.swarm_kill': 'Kill Worker', + 'live.act.swarm_model': 'Switch Worker Model', + 'live.act.swarm_channel': 'Swarm Channel', + 'live.act.swarm_status': 'Check Swarm', + 'live.act.post_message': 'Post to Board', + 'live.act.read_board': 'Read Board', + 'live.act.swarm_wait': 'Parked on Board', 'live.act.manage_task': 'Manage Task', 'live.act.schedule': 'Schedule Task', 'live.act.ask_question': 'Waiting for User Choice', @@ -2230,6 +2281,9 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'live.act.compacting': 'Compacting Context', 'live.act.responding': 'Responding', 'live.act.waiting_subagent': 'Waiting for Subagent', + 'live.act.waiting_swarm': 'Waiting for Swarm', + 'live.act.swarm_waiting': 'Waiting', + 'live.act.swarm_killed': 'Killed', 'live.act.starting': 'Starting', 'live.act.done': 'Completed', 'live.act.awaitingApproval': 'Awaiting Approval · {label}', @@ -2744,7 +2798,7 @@ return { defineComponent }; })(); // --- src/core/formatters.js --- -const { formatMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatLiveActivityLabel, formatLiveActivityDetail } = (() => { +const { formatMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail } = (() => { /** * @fileoverview Pure formatting utilities for speed metrics, token counts, * USD estimates, countdown timers, and custom datetime displays. @@ -3230,21 +3284,48 @@ function getAgentBadgeClass(index = 0, isMain = false) { return `badge-sub-${slot}`; } +function resolveStructuredAgentKind(agent) { + if (!agent) return 'main'; + if (agent.agentKind) return agent.agentKind; + if (agent.isMain) return 'main'; + if (agent.isSideQuestion || agent.typeName === 'side_question') return 'side_question'; + if ( + agent.typeName === 'worker' || + agent.typeName === 'swarm_worker' || + /^Swarm\s+Worker\s*\(/i.test(String(agent.role || '')) + ) { + return 'swarm_worker'; + } + return 'subagent'; +} + +function normalizeSwarmMemberHandle(rawText) { + const trimmed = String(rawText || '').trim(); + if (!trimmed) return ''; + const wrapper = trimmed.match(/^Swarm\s+Worker\s*\(([^)]+)\)\s*$/i); + const inner = (wrapper ? wrapper[1] : trimmed).replace(/^@+/, '').trim(); + if ( + !inner || + inner === '蜂群' || + inner === '工蜂' || + inner.toLowerCase() === 'swarm' || + inner.toLowerCase() === 'worker' || + inner.toLowerCase() === 'swarm worker' + ) { + return ''; + } + return `@${inner}`; +} + /** - * 基于结构化 `agentKind` / `agentOrdinal` 格式化主/子代理或旁路提问的紧凑徽章文本(零正则反拆中文)。 + * 基于结构化 `agentKind` / `agentOrdinal` 格式化主/子代理、蜂群节点或旁路提问的紧凑徽章文本(零正则反拆中文)。 * * @param {object|null|undefined} agent * @returns {string} */ function formatAgentBadgeText(agent) { if (!agent) return t('fmt.mainBadge'); - const kind = - agent.agentKind || - (agent.isMain - ? 'main' - : agent.isSideQuestion || agent.typeName === 'side_question' - ? 'side_question' - : 'subagent'); + const kind = resolveStructuredAgentKind(agent); if (kind === 'all') return t('header.scopeAllShort'); if (kind === 'main') return t('fmt.mainBadge'); if (kind === 'side_question') { @@ -3253,6 +3334,12 @@ function formatAgentBadgeText(agent) { if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText); return t('fmt.sideBadgeShort'); } + if (kind === 'swarm_worker') { + const ord = Number(agent.agentOrdinal || agent.index || 0); + if (ord > 0) return t('fmt.swarmBadge', { index: ord }); + if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText); + return t('fmt.swarmBadgeShort'); + } const ord = Number(agent.agentOrdinal || agent.index || 0); if (ord > 0) return t('fmt.subBadge', { index: ord }); if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText); @@ -3267,13 +3354,7 @@ function formatAgentBadgeText(agent) { */ function formatAgentLabel(agent) { if (!agent) return t('fmt.mainAgent'); - const kind = - agent.agentKind || - (agent.isMain - ? 'main' - : agent.isSideQuestion || agent.typeName === 'side_question' - ? 'side_question' - : 'subagent'); + const kind = resolveStructuredAgentKind(agent); if (kind === 'all') return t('header.scopeAll'); if (kind === 'main') return t('fmt.mainAgent'); @@ -3294,6 +3375,20 @@ function formatAgentLabel(agent) { return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`; } + if (kind === 'swarm_worker') { + const ord = Number(agent.agentOrdinal || agent.index || 0); + const baseLabel = ord > 0 ? `${t('fmt.swarmAgent')} #${ord}` : t('fmt.swarmAgent'); + const handle = normalizeSwarmMemberHandle(rawCustom || agent.role || ''); + if (!handle) return baseLabel; + let auxSuffix = ''; + if (/^@monitor(?:-\d+)?$/i.test(handle)) { + auxSuffix = ` (${t('fmt.swarmMonitorHint')})`; + } else if (/^@narrator(?:-\d+)?$/i.test(handle)) { + auxSuffix = ` (${t('fmt.swarmNarratorHint')})`; + } + return `${baseLabel} · ${handle}${auxSuffix}`; + } + const ord = Number(agent.agentOrdinal || agent.index || 0); const baseLabel = ord > 0 ? `${t('fmt.subAgent')} #${ord}` : t('fmt.subAgent'); const isGeneric = @@ -3305,6 +3400,31 @@ function formatAgentLabel(agent) { return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`; } +/** + * 格式化会话选项右侧元信息(自适应区分纯蜂群、蜂群+子代理混合、常规子代理与单会话步数)。 + * + * @param {object|null|undefined} conv + * @returns {string} + */ +function formatConversationMeta(conv) { + if (!conv) return ''; + const main = Number(conv.stepCount || 0); + const totalSubs = Number(conv.subagentCount || 0); + const swarm = Number(conv.swarmCount || 0); + const otherSubs = Math.max(0, totalSubs - swarm); + const total = Number(conv.totalStepCount ?? conv.totalStepsAllAgents ?? main); + if (swarm > 0 && otherSubs > 0) { + return t('header.convMetaWithSwarmAndSubs', { main, swarm, subs: otherSubs, total }); + } + if (swarm > 0) { + return t('header.convMetaWithSwarm', { main, swarm, total }); + } + if (totalSubs > 0) { + return t('header.convMetaWithSubs', { main, subs: totalSubs, total }); + } + return t('header.convMetaSteps', { count: main }); +} + /** * 基于后端结构化 `actionKey` + `waitingApproval` 渲染实时动作短标题(兼容自定义 `label` 回退)。 * @@ -3344,7 +3464,7 @@ function formatLiveActivityDetail(act) { } return String(act.detail || ''); } -return { formatMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatLiveActivityLabel, formatLiveActivityDetail }; +return { formatMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail }; })(); // --- src/core/httpClient.js --- @@ -3628,7 +3748,7 @@ return { getViewTabs, uiStore, getVisibleMonitorView }; })(); // --- src/store/telemetryStore.js --- -const { extractHostRouteCascadeId, telemetryStore, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, fetchTelemetry, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveScopedConversation, isMacHostPlatform } = (() => { +const { extractHostRouteCascadeId, telemetryStore, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, fetchTelemetry, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform } = (() => { /** * @fileoverview Reactive telemetry store with async non-overlapping poll scheduler * and granular slice updates. @@ -3889,6 +4009,8 @@ function isEquivalentTelemetry(prev, next) { if (pAct?.cascadeId !== nAct?.cascadeId) return false; if (pAct?.stepCount !== nAct?.stepCount) return false; if (pAct?.subagentCount !== nAct?.subagentCount) return false; + if ((pAct?.swarmCount || 0) !== (nAct?.swarmCount || 0)) return false; + if ((pAct?.swarmTitle || '') !== (nAct?.swarmTitle || '')) return false; if (pAct?.totalStepsAllAgents !== nAct?.totalStepsAllAgents) return false; if (pAct?.isRunning !== nAct?.isRunning) return false; if ( @@ -3965,6 +4087,9 @@ function isEquivalentTelemetry(prev, next) { const na = nAgents[i]; if ( pa?.agentId !== na?.agentId || + pa?.agentKind !== na?.agentKind || + pa?.agentOrdinal !== na?.agentOrdinal || + (pa?.swarmState || '') !== (na?.swarmState || '') || pa?.role !== na?.role || pa?.stepCount !== na?.stepCount || pa?.isRunning !== na?.isRunning || @@ -4250,6 +4375,8 @@ function isEquivalentTelemetry(prev, next) { pConvs[i]?.status !== nConvs[i]?.status || pConvs[i]?.stepCount !== nConvs[i]?.stepCount || pConvs[i]?.subagentCount !== nConvs[i]?.subagentCount || + (pConvs[i]?.swarmCount || 0) !== (nConvs[i]?.swarmCount || 0) || + (pConvs[i]?.swarmTitle || '') !== (nConvs[i]?.swarmTitle || '') || pConvs[i]?.totalStepCount !== nConvs[i]?.totalStepCount ) { return false; @@ -4268,7 +4395,9 @@ function isEquivalentTelemetry(prev, next) { pr?.isCurrentSelected !== nr?.isCurrentSelected || pr?.isMainRunning !== nr?.isMainRunning || pr?.subagentCount !== nr?.subagentCount || + (pr?.swarmCount || 0) !== (nr?.swarmCount || 0) || pr?.runningSubagentCount !== nr?.runningSubagentCount || + (pr?.runningSwarmCount || 0) !== (nr?.runningSwarmCount || 0) || pr?.mainActivity?.signature !== nr?.mainActivity?.signature || pr?.mainActivity?.startedAtMs !== nr?.mainActivity?.startedAtMs ) { @@ -4280,6 +4409,8 @@ function isEquivalentTelemetry(prev, next) { for (let j = 0; j < pSubs.length; j++) { if ( pSubs[j]?.cascadeId !== nSubs[j]?.cascadeId || + pSubs[j]?.agentKind !== nSubs[j]?.agentKind || + (pSubs[j]?.swarmState || '') !== (nSubs[j]?.swarmState || '') || pSubs[j]?.role !== nSubs[j]?.role || pSubs[j]?.isRunning !== nSubs[j]?.isRunning || pSubs[j]?.stepCount !== nSubs[j]?.stepCount || @@ -4675,6 +4806,54 @@ function stopAsyncTelemetryLoop() { } +/** + * 在遥测快照中解析宿主当前路由会话 ID(兼容顶层主会话 ID 与子代理/蜂群工蜂 ID)。 + * + * @param {object|null|undefined} telemetry + * @param {string} rawRouteId + * @returns {{ rootConv: object|null, childAgent: object|null, isChildRoute: boolean } | null} + */ +function resolveHostRouteMatch(telemetry, rawRouteId) { + const routeLower = String(rawRouteId || '').trim().toLowerCase(); + if (!routeLower || !telemetry) return null; + const convs = Array.isArray(telemetry.conversations) ? telemetry.conversations : []; + const actConv = telemetry.activeConversation || null; + + const directRoot = + convs.find((c) => String(c?.cascadeId || '').toLowerCase() === routeLower) || + (String(actConv?.cascadeId || '').toLowerCase() === routeLower ? actConv : null); + if (directRoot) { + return { rootConv: directRoot, childAgent: null, isChildRoute: false }; + } + + const activeChild = (actConv?.agents || []).find( + (a) => + !a?.isMain && + (String(a?.cascadeId || '').toLowerCase() === routeLower || + String(a?.agentId || '').toLowerCase() === routeLower) + ); + if (activeChild) { + const parentInList = convs.find( + (c) => String(c?.cascadeId || '').toLowerCase() === String(actConv?.cascadeId || '').toLowerCase() + ); + return { + rootConv: parentInList || actConv, + childAgent: activeChild, + isChildRoute: true, + }; + } + + const memberParent = convs.find( + (c) => + Array.isArray(c?.memberCascadeIds) && + c.memberCascadeIds.some((id) => String(id || '').toLowerCase() === routeLower) + ); + if (memberParent) { + return { rootConv: memberParent, childAgent: null, isChildRoute: true }; + } + return null; +} + /** * 解析当前选中的主/子代理作用域视图数据与独立上下文窗口检视目标。 * 同时在客户端按需组装主代理与全部汇总的 `recentSteps`,避免后端 JSON 载荷重复序列化 2-3 倍步骤列表。 @@ -4820,7 +4999,7 @@ function isMacHostPlatform(telemetry) { } return false; } -return { extractHostRouteCascadeId, telemetryStore, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, fetchTelemetry, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveScopedConversation, isMacHostPlatform }; +return { extractHostRouteCascadeId, telemetryStore, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, fetchTelemetry, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform }; })(); // --- src/components/ui/TopLongPillNav.js --- @@ -10868,43 +11047,68 @@ function buildFallbackRunningConversations( } const activeConv = data.activeConversation || {}; if (!activeConv.isRunning && !aggregated?.isRunning) return []; + const childAgents = (agents || []).filter((a) => !a.isMain); + const swarmChildren = childAgents.filter((a) => a.agentKind === 'swarm_worker'); return [ { cascadeId: activeConv.cascadeId || 'current', title: activeConv.title || t('live.currentSession'), + ...(activeConv.swarmTitle ? { swarmTitle: activeConv.swarmTitle } : {}), isCurrentSelected: true, isMainRunning: Boolean(activeConv.isRunning), isRunning: true, mainActivity: activeConv.liveActivity || aggregated?.liveActivity || null, - subagentCount: Math.max(0, (agents?.length || 1) - 1), - runningSubagentCount: (agents || []).filter((a) => !a.isMain && a.isRunning).length, + subagentCount: childAgents.length, + swarmCount: swarmChildren.length, + runningSubagentCount: childAgents.filter((a) => a.isRunning).length, + runningSwarmCount: swarmChildren.filter((a) => a.isRunning).length, ...(latestTokPerSec !== undefined ? { latestTokPerSec } : {}), ...(contextUsedPct !== undefined ? { contextUsedPct } : {}), - subagents: (agents || []) - .filter((a) => !a.isMain) - .map((s, idx) => ({ + subagents: childAgents.map((s, idx) => { + const isSwarmW = s.agentKind === 'swarm_worker'; + const isKilled = Boolean(s.swarmState === 'killed'); + return { cascadeId: s.cascadeId || s.agentId, index: s.index || idx + 1, agentKind: s.agentKind || (s.isSideQuestion ? 'side_question' : 'subagent'), - agentOrdinal: s.agentOrdinal || (s.isSideQuestion ? s.sideIndex || 0 : s.index || idx + 1), + agentOrdinal: + s.agentOrdinal || (s.isSideQuestion ? s.sideIndex || 0 : s.index || idx + 1), customRole: s.customRole, + ...(s.swarmState ? { swarmState: s.swarmState } : {}), ...(s.isSideQuestion ? { isSideQuestion: true, sideIndex: s.sideIndex || 0 } : {}), badgeText: formatAgentBadgeText({ ...s, index: s.index || idx + 1 }), - shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`, - role: s.role || `${t('fmt.subAgent')} #${idx + 1}`, + shortLabel: + s.shortLabel || + `${isSwarmW ? t('fmt.swarmAgent') : t('fmt.subAgent')} #${s.agentOrdinal || idx + 1}`, + role: + s.role || + `${isSwarmW ? t('fmt.swarmAgent') : t('fmt.subAgent')} #${s.agentOrdinal || idx + 1}`, isRunning: Boolean(s.isRunning), stepCount: Number(s.stepCount || 0), lastModifiedMs: s.lastModifiedMs || 0, liveActivity: s.liveActivity || { - phase: s.isRunning ? 'thinking' : 'done', - actionKey: s.isRunning ? 'thinking' : 'done', - label: s.isRunning ? t('live.thinking') : t('live.done'), + phase: s.isRunning ? 'thinking' : isSwarmW && !isKilled ? 'waiting' : 'done', + actionKey: s.isRunning + ? 'thinking' + : isSwarmW + ? isKilled + ? 'swarm_killed' + : 'swarm_waiting' + : 'done', + label: s.isRunning + ? t('live.thinking') + : isSwarmW + ? isKilled + ? t('live.killed') + : t('live.waiting') + : t('live.done'), detail: '', stepProgress: '', startedAtMs: s.lastModifiedMs || 0, - signature: `${s.agentId}:${s.stepCount || 0}`, + signature: `${s.agentId}:${s.swarmState || ''}:${s.stepCount || 0}`, }, - })), + }; + }), }, ]; } @@ -11190,14 +11394,17 @@ const LiveActivityWidget = defineComponent({ const isHere = showSessionExtras && Boolean(hostRouteLower) && - String(item.cascadeId || '').toLowerCase() === hostRouteLower; + (String(item.cascadeId || '').toLowerCase() === hostRouteLower || + (item.subagents || []).some( + (s) => String(s?.cascadeId || '').toLowerCase() === hostRouteLower + )); const subSig = (item.subagents || []) .map( (s) => - `${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}` + `${s.cascadeId}:${s.isRunning}:${s.swarmState || ''}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}` ) .join('|'); - return `${locale}:${item.cascadeId}:${item.title}:${isHere}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.latestTokPerSec ?? ''}:${item.contextUsedPct ?? ''}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`; + return `${locale}:${item.cascadeId}:${item.title}:${isHere}:${item.isMainRunning}:${item.subagentCount}:${item.swarmCount || 0}:${item.runningSubagentCount}:${isExp}:${item.latestTokPerSec ?? ''}:${item.contextUsedPct ?? ''}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`; }, createRow: createLiveTaskCard, updateRow: (refs, item) => { @@ -11244,7 +11451,10 @@ const LiveActivityWidget = defineComponent({ if (showSessionExtras && refs.hereTagEl && refs.metricsEl) { const isHere = Boolean(hostRouteLower) && - String(item.cascadeId || '').toLowerCase() === hostRouteLower; + (String(item.cascadeId || '').toLowerCase() === hostRouteLower || + (item.subagents || []).some( + (s) => String(s?.cascadeId || '').toLowerCase() === hostRouteLower + )); patchText(refs.hereTagEl, t('multi.hereTag')); patchAttr(refs.hereTagEl, 'hidden', !isHere); @@ -11265,6 +11475,11 @@ const LiveActivityWidget = defineComponent({ } const subCount = Number(item.subagentCount || item.subagents?.length || 0); + const swarmCount = Number( + item.swarmCount ?? + (item.subagents || []).filter((s) => s?.agentKind === 'swarm_worker').length + ); + const isPureSwarm = subCount > 0 && swarmCount === subCount; const runSubCount = Number(item.runningSubagentCount || 0); const isExpanded = resolveIsExpanded(item); patchText(refs.mainBadge, t('fmt.mainBadge')); @@ -11274,8 +11489,15 @@ const LiveActivityWidget = defineComponent({ const arrow = isExpanded ? '▾' : '▸'; const toggleText = runSubCount > 0 - ? t('live.subToggleRunning', { run: runSubCount, total: subCount, arrow }) - : t('live.subToggleIdle', { total: subCount, arrow }); + ? t(isPureSwarm ? 'live.swarmToggleRunning' : 'live.subToggleRunning', { + run: runSubCount, + total: subCount, + arrow, + }) + : t(isPureSwarm ? 'live.swarmToggleIdle' : 'live.subToggleIdle', { + total: subCount, + arrow, + }); patchText(refs.subToggleBtn, toggleText); patchClasses(refs.subToggleBtn, { 'is-expanded': isExpanded }); if (interactive) { @@ -11323,11 +11545,28 @@ const LiveActivityWidget = defineComponent({ const showSubs = subCount > 0 && isExpanded; patchAttr(refs.subListEl, 'hidden', !showSubs); if (showSubs) { - const subItems = item.subagents || []; + const rawSubItems = item.subagents || []; + const getSubSortRank = (s) => { + if (s?.isRunning) return 0; + if (s?.swarmState === 'waiting' || s?.liveActivity?.actionKey === 'swarm_waiting') { + return 1; + } + return 2; + }; + const subItems = + rawSubItems.length > 1 + ? rawSubItems + .slice() + .sort( + (a, b) => + getSubSortRank(a) - getSubSortRank(b) || + Number(a?.index || 0) - Number(b?.index || 0) + ) + : rawSubItems; patchKeyedList(refs.subListEl, subItems, { keyFn: (sub) => sub.cascadeId, sigFn: (sub) => - `${locale}:${sub.cascadeId}:${sub.role}:${sub.isRunning}:${sub.stepCount}:${sub.liveActivity?.signature || ''}:${sub.isRunning ? activityTimersMap.has(`sub:${sub.cascadeId}`) : true}`, + `${locale}:${sub.cascadeId}:${sub.agentKind || ''}:${sub.swarmState || ''}:${sub.role}:${sub.isRunning}:${sub.stepCount}:${sub.liveActivity?.signature || ''}:${sub.isRunning ? activityTimersMap.has(`sub:${sub.cascadeId}`) : true}`, createRow: createLiveSubRow, updateRow: (subRefs, sub) => { const subAct = sub.liveActivity || { @@ -11338,7 +11577,17 @@ const LiveActivityWidget = defineComponent({ stepProgress: '', startedAtMs: sub.lastModifiedMs || 0, }; - patchClasses(subRefs.rowEl, { 'is-done': !sub.isRunning }); + const isWaitingSub = + !sub.isRunning && + (sub.swarmState === 'waiting' || subAct.actionKey === 'swarm_waiting'); + const isKilledSub = + !sub.isRunning && + (sub.swarmState === 'killed' || subAct.actionKey === 'swarm_killed'); + patchClasses(subRefs.rowEl, { + 'is-done': !sub.isRunning && !isWaitingSub, + 'is-waiting-sub': isWaitingSub, + 'is-killed-sub': isKilledSub, + }); const badgeCls = getAgentBadgeClass(sub.index || 1, false); const subBadgeText = formatAgentBadgeText({ @@ -11352,22 +11601,33 @@ const LiveActivityWidget = defineComponent({ const fallbackRole = sub.agentKind === 'side_question' || sub.isSideQuestion ? `${t('fmt.sideQuestion')}${sub.agentOrdinal || sub.sideIndex ? ` #${sub.agentOrdinal || sub.sideIndex}` : ''}` - : `${t('fmt.subAgent')}${sub.agentOrdinal || sub.index ? ` #${sub.agentOrdinal || sub.index}` : ''}`; + : sub.agentKind === 'swarm_worker' + ? `${t('fmt.swarmAgent')}${sub.agentOrdinal || sub.index ? ` #${sub.agentOrdinal || sub.index}` : ''}` + : `${t('fmt.subAgent')}${sub.agentOrdinal || sub.index ? ` #${sub.agentOrdinal || sub.index}` : ''}`; const roleText = sub.customRole !== undefined ? sub.customRole || fallbackRole : sub.role || sub.shortLabel || fallbackRole; patchText(subRefs.subRole, roleText); + const idleFallbackKey = isKilledSub + ? 'live.killed' + : isWaitingSub + ? 'live.waiting' + : 'live.done'; const subLabel = sub.isRunning ? formatLiveActivityLabel(subAct, 'live.running') - : formatLiveActivityLabel(subAct, 'live.done'); + : formatLiveActivityLabel(subAct, idleFallbackKey); const subDetail = formatLiveActivityDetail(subAct); const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : ''; const summaryStr = showSessionExtras ? sub.isRunning ? `${subLabel}${subProg}${subDetail ? ` · ${subDetail}` : ''}` - : t('live.doneWithSteps', { steps: sub.stepCount || 0 }) + : isKilledSub + ? t('live.killedWithSteps', { steps: sub.stepCount || 0 }) + : isWaitingSub + ? t('live.waitingWithSteps', { steps: sub.stepCount || 0 }) + : t('live.doneWithSteps', { steps: sub.stepCount || 0 }) : [`${subLabel}${subProg}`.trim(), subDetail].filter(Boolean).join(' '); patchAttr(subRefs.subSummary, 'hidden', !summaryStr); patchText(subRefs.subSummary, summaryStr); @@ -12146,14 +12406,29 @@ function resolveMultiSessionCapsuleState( (acc, item) => acc + Number(item.runningSubagentCount || 0), 0 ); + const runningSwarmCount = rawRunningList.reduce( + (acc, item) => acc + Number(item.runningSwarmCount || 0), + 0 + ); + const isPureSwarmSubs = runningSubCount > 0 && runningSwarmCount === runningSubCount; const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting'); const multiBtnText = runningCount > 0 ? runningSubCount > 0 - ? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount }) + ? t(isPureSwarmSubs ? 'capsule.multiRunningWithSwarm' : 'capsule.multiRunningWithSubs', { + count: runningCount, + subs: runningSubCount, + }) : t('capsule.multiRunning', { count: runningCount }) : t('capsule.multiZero'); - return { rawRunningList, runningCount, runningSubCount, hasWaiting, multiBtnText }; + return { + rawRunningList, + runningCount, + runningSubCount, + runningSwarmCount, + hasWaiting, + multiBtnText, + }; } /** @@ -16572,16 +16847,7 @@ const { TopSessionHeader } = (() => { function formatConvOptionMeta(c) { - if (!c) return ''; - const subs = Number(c.subagentCount || 0); - if (subs > 0) { - return t('header.convMetaWithSubs', { - main: c.stepCount || 0, - subs, - total: c.totalStepCount || c.stepCount || 0, - }); - } - return t('header.convMetaSteps', { count: c.stepCount || 0 }); + return formatConversationMeta(c); } const TopSessionHeader = defineComponent({ @@ -16659,10 +16925,49 @@ const TopSessionHeader = defineComponent({ const headerEl = h('header', { className: 'top-session-stack' }, [headerRowEl]); let lastActiveCascadeId = ''; + let lastAppliedHostChildRouteId = ''; - function syncSessionScopeOnCascadeChange(telemetry) { + function syncSessionScopeOnCascadeChange(telemetry, telSlice = telemetryStore.getState()) { const currentCascadeId = telemetry?.activeConversation?.cascadeId || ''; if (!currentCascadeId) return; + + const selectedId = String(telSlice?.selectedConversationId || '').trim(); + const hostRouteId = String(telSlice?.hostRouteConversationId || '').trim(); + const hostRouteLower = hostRouteId.toLowerCase(); + + if (!selectedId && hostRouteLower) { + const routeMatch = resolveHostRouteMatch(telemetry, hostRouteId); + if (routeMatch?.isChildRoute && routeMatch.childAgent?.agentId) { + lastActiveCascadeId = currentCascadeId; + if (lastAppliedHostChildRouteId !== hostRouteLower) { + lastAppliedHostChildRouteId = hostRouteLower; + const targetAgentId = routeMatch.childAgent.agentId; + const uiSt = uiStore.getState(); + if ( + uiSt.selectedAgentScope !== targetAgentId || + uiSt.ctxInspectorAgentId !== targetAgentId + ) { + uiStore.setState({ + selectedAgentScope: targetAgentId, + ctxInspectorAgentId: targetAgentId, + }); + } + } + return; + } + if (lastAppliedHostChildRouteId && !routeMatch?.isChildRoute) { + lastAppliedHostChildRouteId = ''; + const uiSt = uiStore.getState(); + if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== 'auto') { + uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); + } + lastActiveCascadeId = currentCascadeId; + return; + } + } else if (lastAppliedHostChildRouteId) { + lastAppliedHostChildRouteId = ''; + } + if (lastActiveCascadeId && currentCascadeId !== lastActiveCascadeId) { lastActiveCascadeId = currentCascadeId; const uiSt = uiStore.getState(); @@ -16686,34 +16991,44 @@ const TopSessionHeader = defineComponent({ const actConv = telemetry?.activeConversation; const convs = telemetry?.conversations || []; const hostRouteId = telSt.hostRouteConversationId || ''; - const hostMatchedConv = hostRouteId - ? convs.find((c) => c.cascadeId === hostRouteId) || - (actConv?.cascadeId === hostRouteId ? actConv : null) - : null; + const routeMatch = hostRouteId ? resolveHostRouteMatch(telemetry, hostRouteId) : null; + const hostMatchedConv = routeMatch?.rootConv || null; + const childRouteBadge = + routeMatch?.isChildRoute && routeMatch.childAgent + ? formatAgentBadgeText(routeMatch.childAgent) + : ''; + const hostBaseTitle = hostMatchedConv?.title || hostRouteId.slice(0, 8); + const hostDisplayTitle = childRouteBadge + ? `${hostBaseTitle} · ${childRouteBadge}` + : hostBaseTitle; const defaultOptLabel = hostRouteId ? t('header.currentWindowNamed', { - title: hostMatchedConv?.title || hostRouteId.slice(0, 8), + title: hostDisplayTitle, }) : convs[0]?.title ? t('header.latestNamed', { title: convs[0].title }) : t('header.followLatest'); const defaultOptMeta = hostRouteId ? hostMatchedConv - ? formatConvOptionMeta({ - stepCount: hostMatchedConv.stepCount, - subagentCount: hostMatchedConv.subagentCount, - totalStepCount: hostMatchedConv.totalStepCount ?? hostMatchedConv.totalStepsAllAgents, - }) + ? formatConvOptionMeta(hostMatchedConv) : '' : convs[0] ? formatConvOptionMeta(convs[0]) : ''; const options = [ - { value: '', label: defaultOptLabel, meta: defaultOptMeta }, + { + value: '', + label: defaultOptLabel, + meta: defaultOptMeta, + ...(hostMatchedConv?.swarmTitle ? { title: hostMatchedConv.swarmTitle } : {}), + }, ...convs.map((c) => ({ value: c.cascadeId, label: c.title || c.cascadeId.slice(0, 8), meta: formatConvOptionMeta(c), + ...(c.swarmTitle && c.swarmTitle !== c.title + ? { title: `${c.title || c.cascadeId.slice(0, 8)} · ${c.swarmTitle}` } + : {}), })), ]; const lockedId = telSt.selectedConversationId; @@ -16723,13 +17038,7 @@ const TopSessionHeader = defineComponent({ isLoadedLocked && actConv?.title ? actConv.title : t('header.lockedSession', { id: String(lockedId).slice(0, 8) }); - const lockedMeta = isLoadedLocked - ? formatConvOptionMeta({ - stepCount: actConv.stepCount, - subagentCount: actConv.subagentCount, - totalStepCount: actConv.totalStepsAllAgents, - }) - : t('header.lockedMeta'); + const lockedMeta = isLoadedLocked ? formatConvOptionMeta(actConv) : t('header.lockedMeta'); options.splice(1, 0, { value: lockedId, label: lockedTitle, @@ -16836,7 +17145,7 @@ const TopSessionHeader = defineComponent({ telemetry: st.telemetry, }), (slice) => { - syncSessionScopeOnCascadeChange(slice.telemetry); + syncSessionScopeOnCascadeChange(slice.telemetry, slice); renderHeaderState(); } ); @@ -21583,16 +21892,26 @@ function mountWindowOverlay() { syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx); } - function renderMultiRunningPanel(rawRunningList, runningCount, runningSubCount, hostRouteConversationId) { + function renderMultiRunningPanel( + rawRunningList, + runningCount, + runningSubCount, + hostRouteConversationId, + runningSwarmCount = 0 + ) { if (!multiOpen || document.hidden) { multiRunningWidget.refs.pauseTicker(); return; } + const isPureSwarm = runningSubCount > 0 && runningSwarmCount === runningSubCount; patchText( multiRunningMetaEl, runningCount > 0 ? runningSubCount > 0 - ? t('multi.metaWithSubs', { main: runningCount, subs: runningSubCount }) + ? t(isPureSwarm ? 'multi.metaWithSwarm' : 'multi.metaWithSubs', { + main: runningCount, + subs: runningSubCount, + }) : t('multi.metaMainOnly', { main: runningCount }) : t('multi.allIdle') ); @@ -21663,13 +21982,19 @@ function mountWindowOverlay() { ctxAgent, aggregated, }); - const { rawRunningList, runningCount, runningSubCount, hasWaiting, multiBtnText } = - resolveMultiSessionCapsuleState(telemetry, { - agents, - aggregated, - latestTokPerSec: overviewActive.latestTokPerSec ?? null, - contextUsedPct: slotCtx.usedPct, - }); + const { + rawRunningList, + runningCount, + runningSubCount, + runningSwarmCount, + hasWaiting, + multiBtnText, + } = resolveMultiSessionCapsuleState(telemetry, { + agents, + aggregated, + latestTokPerSec: overviewActive.latestTokPerSec ?? null, + contextUsedPct: slotCtx.usedPct, + }); patchClasses(multiBtn, { 'is-running': runningCount > 0 && !hasWaiting, @@ -21681,7 +22006,8 @@ function mountWindowOverlay() { rawRunningList, runningCount, runningSubCount, - telSt.hostRouteConversationId + telSt.hostRouteConversationId, + runningSwarmCount ); patchClasses(capsuleBtn, { 'is-running': slotCtx.isRunning }); diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index 5c40820..84131d9 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -80,18 +80,24 @@ function projectDisplayStep(st) { modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec, streamDurationSec, selectedSpeedReason, contextTokens, inputTokens, cacheReadTokens, outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, inCostUsd, - cacheCostUsd, outCostUsd, agentId, agentCascadeId, agentLabel, agentBadge, - agentRole, agentIndex, isSubagent, turnIndex, isTurnStart, isLatestTurn, - turnPrompt, rootTurnIndex, isRootTurnStart, isRootLatestTurn, rootTurnPrompt, + cacheCostUsd, outCostUsd, agentId, agentCascadeId, agentKind, agentOrdinal, + agentCustomRole, agentLabel, agentBadge, agentRole, agentIndex, isSubagent, + isSideQuestion, sideIndex, turnIndex, isTurnStart, isLatestTurn, turnPrompt, + turnPromptClean, turnHasMedia, turnMediaOnly, rootTurnIndex, isRootTurnStart, + isRootLatestTurn, rootTurnPrompt, rootTurnPromptClean, rootTurnHasMedia, + rootTurnMediaOnly, } = st; return { stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel, modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec, streamDurationSec, selectedSpeedReason, contextTokens, inputTokens, cacheReadTokens, outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, inCostUsd, - cacheCostUsd, outCostUsd, agentId, agentCascadeId, agentLabel, agentBadge, - agentRole, agentIndex, isSubagent, turnIndex, isTurnStart, isLatestTurn, - turnPrompt, rootTurnIndex, isRootTurnStart, isRootLatestTurn, rootTurnPrompt, + cacheCostUsd, outCostUsd, agentId, agentCascadeId, agentKind, agentOrdinal, + agentCustomRole, agentLabel, agentBadge, agentRole, agentIndex, isSubagent, + isSideQuestion, sideIndex, turnIndex, isTurnStart, isLatestTurn, turnPrompt, + turnPromptClean, turnHasMedia, turnMediaOnly, rootTurnIndex, isRootTurnStart, + isRootLatestTurn, rootTurnPrompt, rootTurnPromptClean, rootTurnHasMedia, + rootTurnMediaOnly, }; } diff --git a/sidecars/panel/backend/cli-sqlite-reader.mjs b/sidecars/panel/backend/cli-sqlite-reader.mjs index 4fe2a74..8118492 100644 --- a/sidecars/panel/backend/cli-sqlite-reader.mjs +++ b/sidecars/panel/backend/cli-sqlite-reader.mjs @@ -678,6 +678,16 @@ export function readLocalSummarySnapshot(productRoots = PRODUCT_DATA_ROOTS, { fo const sqLower = String(pRow?.conversation_id || '').trim().toLowerCase(); const parentLower = String(pRow?.parent_id || '').trim().toLowerCase(); if (!sqLower || !parentLower) continue; + const childSummary = nextSummariesObj[sqLower]; + if ( + childSummary && + !childSummary.isSideQuestion && + (childSummary.trajectoryMetadata?.subagentSpec || + (Number(childSummary.trajectoryType) > 0 && Number(childSummary.trajectoryType) !== 22)) + ) { + // 排除通过 fork 创建的蜂群工蜂或常规子代理,避免误归入旁路提问 + continue; + } const parentSummary = nextSummariesObj[parentLower]; const titleFromParent = String( parentSummary?.annotations?.sideQuestionTitles?.[sqLower] || @@ -1451,7 +1461,26 @@ function decodeProtoGenericStepInvokeSubagentSlice(buf, state, end) { return invokeSubagent; } -function decodeProtoSelectiveStepPayload(rawBlob, { stepTypeNum, isInvokeSubagent, keepFullText }) { +function decodeProtoSystemMessageSlice(buf, state, end) { + let message = ''; + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 2) { + message = readProtoString(buf, state, end); + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + return message; +} + +function decodeProtoSelectiveStepPayload( + rawBlob, + { stepTypeNum, isInvokeSubagent, includeSystemMessage = false, keepFullText } +) { const buf = toUint8Array(rawBlob); if (!buf || buf.length === 0) return {}; const state = { off: 0 }; @@ -1472,6 +1501,9 @@ function decodeProtoSelectiveStepPayload(rawBlob, { stepTypeNum, isInvokeSubagen readSubEnd(buf, state, end), keepFullText ); + } else if (fn === 114 && wt === 2 && stepTypeNum === 101 && includeSystemMessage) { + const sysMsg = decodeProtoSystemMessageSlice(buf, state, readSubEnd(buf, state, end)); + if (sysMsg) out.systemMessage = { message: sysMsg }; } else if (fn === 140 && wt === 2 && isInvokeSubagent) { const inv = decodeProtoGenericStepInvokeSubagentSlice(buf, state, readSubEnd(buf, state, end)); if (inv) out.invokeSubagent = inv; @@ -1728,6 +1760,17 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) { ownStepRecords.push({ idx, stepTypeNum, statusNum, metadata }); } + const isChildTrajectory = + !isSideQuestion && + Boolean( + trajectoryMetadata.parentConversationId || + parentConversationId || + (trajectoryMetadata.rootConversationId && + trajectoryMetadata.rootConversationId !== normCid) || + (rootConversationId && rootConversationId !== normCid) || + trajectoryMetadata.subagentSpec + ); + const runningTailStart = isRunning ? Math.max(0, ownStepRecords.length - 16) : ownStepRecords.length; @@ -1743,6 +1786,7 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) { if ( rec.stepTypeNum === 14 || rec.stepTypeNum === 15 || + (isChildTrajectory && rec.stepTypeNum === 101) || isInvSub || (inRunningTail && (rec.stepTypeNum !== 132 || !rec.metadata?.toolCall?.argumentsJson)) ) { @@ -1805,6 +1849,7 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) { const decodedPayload = decodeProtoSelectiveStepPayload(rawPayload, { stepTypeNum: rec.stepTypeNum, isInvokeSubagent: isInvSub, + includeSystemMessage: isChildTrajectory && rec.stepTypeNum === 101, keepFullText: inRunningTail, }); if (decodedPayload.userInput) { @@ -1816,6 +1861,10 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) { ); } } + if (decodedPayload.systemMessage) { + stepObj.systemMessage = decodedPayload.systemMessage; + stepObj.content = decodedPayload.systemMessage.message; + } if (decodedPayload.plannerResponse) { stepObj.plannerResponse = decodedPayload.plannerResponse; } diff --git a/sidecars/panel/backend/local-scanner.mjs b/sidecars/panel/backend/local-scanner.mjs index 77dab0e..1ea7fcf 100644 --- a/sidecars/panel/backend/local-scanner.mjs +++ b/sidecars/panel/backend/local-scanner.mjs @@ -15,7 +15,9 @@ import { extractLiveActivity, extractModelSteps, getMaxMeaningfulStepIndex, + isParkedOnSwarmWait, parseIsoMs, + parseSwarmWorkerRole, } from '../trajectory-metrics.mjs'; import { ANNOTATION_DIRS, @@ -353,11 +355,133 @@ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/ const failedFetchCooldownMap = new Map(); const liveActivityMemo = new Map(); const transcriptTailMemo = new Map(); +const swarmManifestMemo = new Map(); export function clearScannerRuntimeMemos() { failedFetchCooldownMap.clear(); liveActivityMemo.clear(); transcriptTailMemo.clear(); + swarmManifestMemo.clear(); +} + +function findSwarmMembersPath(cascadeId) { + if (!cascadeId) return ''; + const normId = String(cascadeId).trim().toLowerCase(); + if (!UUID_RE.test(normId)) return ''; + const dirs = Array.isArray(BRAIN_DIRS) && BRAIN_DIRS.length > 0 ? BRAIN_DIRS : [BRAIN_DIR]; + let bestPath = ''; + let bestMtime = -1; + for (const dir of dirs) { + if (!dir) continue; + const candidate = join(dir, normId, '.system_generated', 'swarm', 'members.json'); + if (!existsSync(candidate)) continue; + if (dirs.length === 1) return candidate; + try { + const mtime = Number(statSync(candidate)?.mtimeMs || 0); + if (mtime > bestMtime) { + bestMtime = mtime; + bestPath = candidate; + } + } catch { + if (!bestPath) bestPath = candidate; + } + } + return bestPath; +} + +/** + * 按会话 ID 精确读取本地 `brain//.system_generated/swarm/members.json` 蜂群花名册(O(1) 定点读取 + `mtimeMs + size` 缓存)。 + * + * @param {string} cascadeId + * @returns {{ + * title: string, + * coordinator: object|null, + * membersByCid: Map, + * membersByName: Map, + * workerRefs: Array + * } | null} + */ +export function readSwarmManifestForCascade(cascadeId) { + if (!cascadeId) return null; + const normId = String(cascadeId).trim().toLowerCase(); + if (!UUID_RE.test(normId)) return null; + const membersPath = findSwarmMembersPath(normId); + if (!membersPath) { + swarmManifestMemo.delete(normId); + return null; + } + try { + const st = statSync(membersPath); + const mtimeMs = Number(st?.mtimeMs || 0); + const size = Number(st?.size || 0); + const cached = swarmManifestMemo.get(normId); + if ( + cached && + cached.path === membersPath && + cached.mtimeMs === mtimeMs && + cached.size === size && + size > 0 + ) { + return cached.manifest; + } + const raw = readFileSync(membersPath, 'utf8'); + const parsed = raw ? JSON.parse(raw) : null; + if (!parsed || typeof parsed !== 'object') return null; + + const title = String(parsed.title || '').trim(); + const rawMembers = parsed.members && typeof parsed.members === 'object' ? parsed.members : {}; + const membersByCid = new Map(); + const membersByName = new Map(); + const workerRefs = []; + let coordinator = null; + + for (const [rawKey, m] of Object.entries(rawMembers)) { + if (!m || typeof m !== 'object') continue; + const memberName = String(m.name || rawKey || '').replace(/^@+/, '').trim(); + const cid = String(m.conversation_id || m.conversationId || '').trim().toLowerCase(); + if (!cid || !UUID_RE.test(cid)) continue; + const role = String(m.role || '').trim().toLowerCase(); + const wakeMode = String(m.wake_mode || m.wakeMode || '').trim().toLowerCase(); + const killed = Boolean(m.killed); + const workspaceMode = String(m.workspace_mode || m.workspaceMode || 'inherit').trim(); + const model = String(m.applied_model || m.model || m.desired_model || '').trim(); + const entry = { + memberName, + conversationId: cid, + role, + wakeMode, + killed, + workspaceMode, + model, + }; + membersByCid.set(cid, entry); + if (memberName) { + membersByName.set(memberName.toLowerCase(), entry); + } + if (role === 'coordinator' || cid === normId) { + coordinator = entry; + } else { + workerRefs.push({ + cascadeId: cid, + role: memberName ? `Swarm Worker (${memberName})` : 'Swarm Worker', + typeName: 'worker', + memberName, + createdTimeMs: 0, + spawnOrder: null, + }); + } + } + + const manifest = { title, coordinator, membersByCid, membersByName, workerRefs }; + if (swarmManifestMemo.size >= MAX_TRANSCRIPT_MEMO_ENTRIES && !swarmManifestMemo.has(normId)) { + const oldestKey = swarmManifestMemo.keys().next().value; + if (oldestKey !== undefined) swarmManifestMemo.delete(oldestKey); + } + swarmManifestMemo.set(normId, { path: membersPath, mtimeMs, size, manifest }); + return manifest; + } catch { + return null; + } } function findTranscriptPath(cascadeId) { @@ -461,6 +585,7 @@ function enrichSqliteStepsFromTranscriptIfNeeded(cidLower, sqliteSteps) { const needsTranscriptBackfill = sqliteSteps.some( (s) => (s?.type === 'CORTEX_STEP_TYPE_USER_INPUT' && !s.userInput) || + (s?.type === 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE' && !s.content && !s.systemMessage) || (s?.metadata?.modelUsage && !s.metadata.modelUsage.model) ); if (!needsTranscriptBackfill) { @@ -522,6 +647,12 @@ function enrichSqliteStepsFromTranscriptIfNeeded(cidLower, sqliteSteps) { if (typeof tLine.content === 'string') sq.content = tLine.content; if (tLine.userInput) sq.userInput = tLine.userInput; if (Array.isArray(tLine.media)) sq.media = tLine.media; + } else if ( + sq.type === 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE' && + !sq.content && + typeof tLine.content === 'string' + ) { + sq.content = tLine.content; } else if (sq.metadata?.modelUsage && !sq.metadata.modelUsage.model) { const fallbackModel = String(tLine.model || tLine.generator_model || '').trim(); if (fallbackModel) sq.metadata.modelUsage.model = fallbackModel; @@ -635,6 +766,23 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc }); continue; } + if (sq.type === 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE') { + const sysText = + typeof sq.content === 'string' && sq.content + ? sq.content + : typeof tLine?.content === 'string' + ? tLine.content + : ''; + if (sysText) { + sqliteRawSteps.push({ + type: sq.type, + status: sq.status, + content: sysText, + metadata: sq.metadata, + }); + } + continue; + } if (sq.metadata?.modelUsage) { const deepStep = extMatch?.steps?.[modelOrdinal] || null; @@ -672,7 +820,9 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc if ( upperType === 'USER_INPUT' || upperType === 'CORTEX_STEP_TYPE_USER_INPUT' || - (line.userInput && typeof line.userInput === 'object') + (line.userInput && typeof line.userInput === 'object') || + upperType === 'SYSTEM_MESSAGE' || + upperType === 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE' ) { sqliteRawSteps.push(line); } else if ( @@ -721,7 +871,9 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc if ( upperType === 'USER_INPUT' || upperType === 'CORTEX_STEP_TYPE_USER_INPUT' || - (line.userInput && typeof line.userInput === 'object') + (line.userInput && typeof line.userInput === 'object') || + upperType === 'SYSTEM_MESSAGE' || + upperType === 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE' ) { syntheticSteps.push(line); continue; @@ -1390,8 +1542,10 @@ export async function enumerateAndSyncConversations({ Boolean(cached?.isSubagent) || Boolean(parentConversationId) || Boolean(rootConversationId && rootConversationId !== cidLower); + const isKilled = Boolean(item?.killed || localSum?.killed); const latestLocalTouchMs = Math.max(diskMtimeMs || 0, localSum?.lastModifiedMs || 0); const localStatus = + !isKilled && localSum?.status === 'CASCADE_RUN_STATUS_RUNNING' && latestLocalTouchMs > 0 && nowSweepMs - latestLocalTouchMs <= STALE_LOCAL_RUNNING_MAX_AGE_MS @@ -1417,7 +1571,8 @@ export async function enumerateAndSyncConversations({ (isSideQuestion ? '旁路提问' : cascadeId.slice(0, 8)), stepCount: modelStepCount, rawStepCount: rawSummaryStepCount, - status: item?.status || '', + status: isKilled ? 'IDLE' : item?.status || '', + killed: isKilled, lastModifiedTime, lastModifiedMs, diskMtimeMs, @@ -1448,6 +1603,7 @@ export async function enumerateAndSyncConversations({ stepCount: cachedStepCount, rawStepCount: localSum?.stepCount || cached.rawStepCount || cachedStepCount, status: localStatus, + killed: isKilled, lastModifiedTime: localSum?.lastModifiedTime || '', lastModifiedMs: Math.max( cached.lastModifiedMs || 0, @@ -1480,6 +1636,7 @@ export async function enumerateAndSyncConversations({ stepCount: 0, rawStepCount: localSum?.stepCount || 0, status: localStatus, + killed: isKilled, lastModifiedTime: localSum?.lastModifiedTime || '', lastModifiedMs: Math.max(diskMtimeMs || 0, localSum?.lastModifiedMs || 0), diskMtimeMs, @@ -1710,6 +1867,19 @@ export async function enumerateAndSyncConversations({ } const subagentRefs = extractSubagentRefsFromSteps(rawSteps); + const ownSwarmManifest = !conv.isSubagent ? readSwarmManifestForCascade(cidLower) : null; + if (ownSwarmManifest?.workerRefs?.length) { + const seenRefCids = new Set(subagentRefs.map((r) => r.cascadeId)); + for (const wRef of ownSwarmManifest.workerRefs) { + if (!seenRefCids.has(wRef.cascadeId)) { + seenRefCids.add(wRef.cascadeId); + subagentRefs.push(wRef); + } + } + if (!nonShortTitle(conv.title) && ownSwarmManifest.title) { + conv.title = ownSwarmManifest.title; + } + } conv.subagentRefs = subagentRefs; const lastStepMs = nextLast?.createdAtMs || 0; @@ -1718,16 +1888,24 @@ export async function enumerateAndSyncConversations({ conv.stepCount = steps.length; const finalSig = buildConvSig(conv); + const effectiveIsRunning = isRunning && !isParkedOnSwarmWait(rawSteps); + if (!effectiveIsRunning && conv.status === 'CASCADE_RUN_STATUS_RUNNING') { + conv.status = 'IDLE'; + } + const liveAct = resolveBestLiveActivity( conv.cascadeId, rawSteps, - isRunning, + effectiveIsRunning, resolvedLastModMs || conv.createdTimeMs || 0 ); - if (liveAct) { + if (liveAct && liveAct.actionKey !== 'swarm_wait') { conv.liveActivity = liveAct; liveActivityMemo.set(cidLower, liveAct); } else { + if (liveAct?.actionKey === 'swarm_wait') { + conv.status = 'IDLE'; + } conv.liveActivity = null; liveActivityMemo.delete(cidLower); } @@ -1747,10 +1925,11 @@ export async function enumerateAndSyncConversations({ diskMtimeMs: conv.diskMtimeMs ?? readConversationMtime(diskConvMap.get(cidLower)), rawStepCount: conv.rawStepCount ?? stepsWithOwners.length, - wasRunning: isRunning, + wasRunning: conv.status === 'CASCADE_RUN_STATUS_RUNNING', contextLimitTelemetry: true, speedClearedTelemetry: true, turnRailTelemetry: true, + wakeupTurnTelemetry: true, contextGroupsTelemetry: 2, steps: stepsWithOwners, subagentRefs, @@ -1963,6 +2142,12 @@ export async function enumerateAndSyncConversations({ return false; } + function needsWakeupTurnRefresh(conv, cached) { + if (!conv?.isSubagent || conv.isSideQuestion || cached?.wakeupTurnTelemetry) return false; + const steps = cached?.steps || []; + return steps.length > 0 && steps.every((s) => !s?.turnIndex); + } + let remainingTimingRefreshes = LEGACY_MIGRATION_BATCH_SIZE; const toFetch = rawConversations.filter((conv) => { const sig = buildConvSig(conv); @@ -1979,6 +2164,7 @@ export async function enumerateAndSyncConversations({ if ( (!cached.turnRailTelemetry || hasMissingTurnRailFields(cached) || + needsWakeupTurnRefresh(conv, cached) || hasDroppedContextGroups(cached)) && isSelectedFamily ) { @@ -2056,7 +2242,22 @@ export async function enumerateAndSyncConversations({ for (const parentConv of [...rawConversations]) { const parentCached = getCachedTrajectory(parentConv.cascadeId); - const refs = parentConv.subagentRefs || parentCached?.subagentRefs || []; + const baseRefs = parentConv.subagentRefs || parentCached?.subagentRefs || []; + const swarmManifest = !parentConv.isSubagent + ? readSwarmManifestForCascade(parentConv.cascadeId) + : null; + let refs = baseRefs; + if (swarmManifest?.workerRefs?.length) { + const merged = Array.isArray(baseRefs) ? baseRefs.slice() : []; + const seenRefCids = new Set(merged.map((r) => String(r?.cascadeId || '').toLowerCase())); + for (const wRef of swarmManifest.workerRefs) { + if (!seenRefCids.has(wRef.cascadeId)) { + seenRefCids.add(wRef.cascadeId); + merged.push(wRef); + } + } + refs = merged; + } if (!Array.isArray(refs) || refs.length === 0) continue; const parentId = parentConv.cascadeId.toLowerCase(); @@ -2145,6 +2346,7 @@ export async function enumerateAndSyncConversations({ (!isSelectedSubFamily || (Boolean(existingSubCache.turnRailTelemetry) && !hasMissingTurnRailFields(existingSubCache) && + !needsWakeupTurnRefresh(subConv, existingSubCache) && !hasDroppedContextGroups(existingSubCache))); if (hasValidSubCache) { @@ -2253,16 +2455,33 @@ export async function enumerateAndSyncConversations({ persistTrajectoryCacheIfNeeded({ hasRunningSessions }); } - // 确保所有处于 RUNNING 状态的会话(含本轮未触发 RPC 拉取的会话)都同步了最新的实时动作摘要 + // 确保所有处于 RUNNING 状态的会话(含本轮未触发 RPC 拉取的会话)都同步了最新的实时动作摘要,并剔除已进入 swarm_wait 待命的假运行态 for (const conv of rawConversations) { if (conv.status === 'CASCADE_RUN_STATUS_RUNNING') { if (!conv.liveActivity) { + const tailSteps = readTranscriptTailSteps(conv.cascadeId); + if (isParkedOnSwarmWait(tailSteps)) { + conv.status = 'IDLE'; + conv.liveActivity = null; + liveActivityMemo.delete(conv.cascadeId.toLowerCase()); + continue; + } const fallbackMs = conv.lastModifiedMs || conv.createdTimeMs || 0; const resolved = resolveBestLiveActivity(conv.cascadeId, [], true, fallbackMs); + if (resolved?.actionKey === 'swarm_wait') { + conv.status = 'IDLE'; + conv.liveActivity = null; + liveActivityMemo.delete(conv.cascadeId.toLowerCase()); + continue; + } conv.liveActivity = resolved; if (resolved) { liveActivityMemo.set(conv.cascadeId.toLowerCase(), resolved); } + } else if (conv.liveActivity.actionKey === 'swarm_wait') { + conv.status = 'IDLE'; + conv.liveActivity = null; + liveActivityMemo.delete(conv.cascadeId.toLowerCase()); } } else { conv.liveActivity = null; @@ -2308,7 +2527,64 @@ export async function enumerateAndSyncConversations({ for (const rootConv of conversations) { const cid = rootConv.cascadeId.toLowerCase(); + const swarmManifest = readSwarmManifestForCascade(cid); + const swarmTitle = String(swarmManifest?.title || '').trim(); + if (swarmTitle) { + rootConv.swarmTitle = swarmTitle; + const curTitle = String(rootConv.title || '').trim(); + if (!curTitle || curTitle.toLowerCase() === cid.slice(0, 8)) { + rootConv.title = swarmTitle; + } + } + if (swarmManifest?.coordinator?.killed || rootConv.killed) { + rootConv.status = 'IDLE'; + rootConv.liveActivity = null; + } + const subs = subagentsByRoot.get(cid) || []; + let swarmCount = 0; + for (const s of subs) { + const subLower = s.cascadeId.toLowerCase(); + const mEntry = swarmManifest?.membersByCid.get(subLower) || null; + const subCached = getCachedTrajectory(s.cascadeId); + const parsedSwarm = !s.isSideQuestion + ? parseSwarmWorkerRole({ + role: s.subagentSpec?.role || subCached?.subagentSpec?.role || '', + typeName: s.subagentSpec?.typeName || subCached?.subagentSpec?.typeName || '', + agentScriptName: s.agentScriptName || subCached?.agentScriptName || '', + memberName: mEntry?.memberName || '', + }) + : { isSwarmWorker: false }; + if (parsedSwarm.isSwarmWorker) { + swarmCount += 1; + s.isSwarmWorker = true; + s.swarmMemberName = parsedSwarm.memberName; + s.isSwarmAuxiliary = Boolean(parsedSwarm.isAuxiliary); + s.killed = Boolean(s.killed || mEntry?.killed); + if (s.killed) { + s.status = 'IDLE'; + s.liveActivity = null; + liveActivityMemo.delete(subLower); + s.swarmState = 'killed'; + } else if (s.status === 'CASCADE_RUN_STATUS_RUNNING') { + const parkedInManifest = + Boolean(mEntry) && + (mEntry.wakeMode === 'mentions' || mEntry.wakeMode === 'anything') && + (!s.liveActivity || s.liveActivity.signature === 'init:0'); + if (s.liveActivity?.actionKey === 'swarm_wait' || parkedInManifest) { + s.status = 'IDLE'; + s.liveActivity = null; + liveActivityMemo.delete(subLower); + s.swarmState = 'waiting'; + } else { + s.swarmState = 'working'; + } + } else { + s.swarmState = 'waiting'; + } + } + } + subs.sort((a, b) => { const aSide = Boolean(a.isSideQuestion); const bSide = Boolean(b.isSideQuestion); @@ -2338,6 +2614,7 @@ export async function enumerateAndSyncConversations({ }); rootConv.subagents = subs; rootConv.subagentCount = subs.length; + rootConv.swarmCount = swarmCount; rootConv.totalStepCount = Number(rootConv.stepCount || 0) + subs.reduce((sum, s) => sum + Number(s.stepCount || 0), 0); diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index 0f0716a..4f948ae 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -14,6 +14,7 @@ import { scaleBucketsExact } from '../shared/telemetry-display-rules.mjs'; import { extractLiveActivity, parseIsoMs, + parseSwarmWorkerRole, speedMetric, summarizeSpeed, summarizeTtft, @@ -573,6 +574,8 @@ export function buildAgentUnitTelemetry({ agentKind = isMain ? 'main' : isSideQuestion ? 'side_question' : 'subagent', agentOrdinal = isMain ? 0 : isSideQuestion ? sideIndex : 0, customRole = '', + swarmState = '', + isSwarmAuxiliary = false, index, shortLabel, badgeText, @@ -628,6 +631,8 @@ export function buildAgentUnitTelemetry({ agentKind, agentOrdinal, customRole, + ...(swarmState ? { swarmState } : {}), + ...(isSwarmAuxiliary ? { isSwarmAuxiliary: true } : {}), ...(isSideQuestion ? { isSideQuestion: true, sideIndex } : {}), index, shortLabel, @@ -829,6 +834,7 @@ export async function buildTelemetryPayloadInternal( let totalFamilyOutputTokens = sessionOutputTokens; let normalSubCount = 0; + let swarmWorkerCount = 0; let sideQuestionCount = 0; for (let idx = 0; idx < subagentSummaries.length; idx++) { const subSum = subagentSummaries[idx]; @@ -844,11 +850,22 @@ export async function buildTelemetryPayloadInternal( ); const rawRole = subSpec?.role || subSum.agentScriptName || subEntry?.agentScriptName || subSpec?.typeName || ''; + const parsedSwarm = !isSideQ + ? parseSwarmWorkerRole({ + role: subSpec?.role || '', + typeName: subSpec?.typeName || '', + agentScriptName: subSum.agentScriptName || subEntry?.agentScriptName || '', + memberName: subSum.swarmMemberName || '', + }) + : { isSwarmWorker: false }; + const isSwarmW = Boolean(!isSideQ && (subSum.isSwarmWorker || parsedSwarm.isSwarmWorker)); const subIndex = idx + 1; let sideIndex = 0; let agentKind = 'subagent'; let agentOrdinal = 0; let customRole = ''; + let swarmState = ''; + let isSwarmAuxiliary = false; let shortLabel = ''; let badgeText = ''; let roleLabel = ''; @@ -871,6 +888,23 @@ export async function buildTelemetryPayloadInternal( roleLabel = cleanSideRole || '旁路提问'; typeName = 'side_question'; agentLabel = cleanSideRole ? `${shortLabel} · ${cleanSideRole}` : shortLabel; + } else if (isSwarmW) { + const swOrd = ++swarmWorkerCount; + agentKind = 'swarm_worker'; + agentOrdinal = swOrd; + const memberTag = parsedSwarm.memberName ? `@${parsedSwarm.memberName}` : ''; + customRole = memberTag; + shortLabel = `蜂群 #${swOrd}`; + badgeText = `蜂${swOrd}`; + roleLabel = memberTag || '蜂群'; + typeName = 'worker'; + agentLabel = memberTag ? `${shortLabel} · ${memberTag}` : shortLabel; + swarmState = subSum.killed + ? 'killed' + : subSum.status === 'CASCADE_RUN_STATUS_RUNNING' + ? 'working' + : subSum.swarmState || 'waiting'; + isSwarmAuxiliary = Boolean(subSum.isSwarmAuxiliary || parsedSwarm.isAuxiliary); } else { const subOrd = ++normalSubCount; agentKind = 'subagent'; @@ -892,6 +926,8 @@ export async function buildTelemetryPayloadInternal( agentKind, agentOrdinal, customRole, + swarmState, + isSwarmAuxiliary, index: subIndex, shortLabel, badgeText, @@ -1026,12 +1062,18 @@ export async function buildTelemetryPayloadInternal( .sort((a, b) => (b.lastModifiedMs || 0) - (a.lastModifiedMs || 0))[0] || mainAgentTelemetry; + const roleSummaryParts = []; + if (swarmWorkerCount > 0) roleSummaryParts.push(`${swarmWorkerCount} 蜂群`); + if (normalSubCount > 0) roleSummaryParts.push(`${normalSubCount} 子代理`); + if (sideQuestionCount > 0) { + roleSummaryParts.push( + roleSummaryParts.length > 0 ? `${sideQuestionCount} 旁问` : `${sideQuestionCount} 旁路提问` + ); + } const aggregatedRoleLabel = - normalSubCount > 0 && sideQuestionCount > 0 - ? `主代理 + ${normalSubCount} 子代理 + ${sideQuestionCount} 旁问` - : sideQuestionCount > 0 - ? `主代理 + ${sideQuestionCount} 旁路提问` - : `主代理 + ${subAgentTelemetries.length} 子代理`; + roleSummaryParts.length > 0 + ? `主代理 + ${roleSummaryParts.join(' + ')}` + : `主代理 + ${subAgentTelemetries.length} 子代理`; const totalCostUsd = roundSessionCost(totalRawSessionCostUsd); const totalUnpricedCalls = allAgents.reduce( @@ -1412,6 +1454,7 @@ export async function buildTelemetryPayloadInternal( rootConv.lastModifiedMs || rootEntry?.lastModifiedMs || rootConv.createdTimeMs || 0; let runNormalSubIdx = 0; + let runSwarmIdx = 0; let runSideIdx = 0; const subItems = rawSubs.map((subSum, idx) => { const subCid = subSum.cascadeId; @@ -1426,11 +1469,22 @@ export async function buildTelemetryPayloadInternal( subEntry?.agentScriptName || subSpec?.typeName || ''; + const parsedSwarm = !isSideQ + ? parseSwarmWorkerRole({ + role: subSpec?.role || '', + typeName: subSpec?.typeName || '', + agentScriptName: subSum.agentScriptName || subEntry?.agentScriptName || '', + memberName: subSum.swarmMemberName || '', + }) + : { isSwarmWorker: false }; + const isSwarmW = Boolean(!isSideQ && (subSum.isSwarmWorker || parsedSwarm.isSwarmWorker)); const subIndex = idx + 1; let sideIndex = 0; let agentKind = 'subagent'; let agentOrdinal = 0; let customRole = ''; + let swarmState = ''; + let isSwarmAuxiliary = false; let badgeText = ''; let shortLabel = ''; let role = ''; @@ -1449,6 +1503,16 @@ export async function buildTelemetryPayloadInternal( : ''; customRole = cleanSide; role = cleanSide || shortLabel; + } else if (isSwarmW) { + const swOrd = ++runSwarmIdx; + agentKind = 'swarm_worker'; + agentOrdinal = swOrd; + const memberTag = parsedSwarm.memberName ? `@${parsedSwarm.memberName}` : ''; + customRole = memberTag; + badgeText = `蜂${swOrd}`; + shortLabel = `蜂群 #${swOrd}`; + role = memberTag || shortLabel; + isSwarmAuxiliary = Boolean(subSum.isSwarmAuxiliary || parsedSwarm.isAuxiliary); } else { const nOrd = ++runNormalSubIdx; agentKind = 'subagent'; @@ -1459,32 +1523,62 @@ export async function buildTelemetryPayloadInternal( role = rawRole || shortLabel; } const isSubRunning = subSum.status === 'CASCADE_RUN_STATUS_RUNNING'; + const isKilled = Boolean(subSum.killed || subSum.swarmState === 'killed'); + if (isSwarmW) { + swarmState = isKilled ? 'killed' : isSubRunning ? 'working' : subSum.swarmState || 'waiting'; + } const stepCount = Number(subSum.stepCount ?? subEntry?.steps?.length ?? 0); const subModMs = subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0; const liveActivity = isSubRunning ? subSum.liveActivity || extractLiveActivity([], true, subModMs) - : { - phase: 'done', - actionKey: 'done', - waitingApproval: false, - detailKey: '', - label: '已完成', - detail: '', - stepProgress: '', - startedAtMs: subModMs, - signature: `done:${stepCount}`, - }; + : isSwarmW + ? isKilled + ? { + phase: 'done', + actionKey: 'swarm_killed', + waitingApproval: false, + detailKey: '', + label: '已终止', + detail: '', + stepProgress: '', + startedAtMs: subModMs, + signature: `killed:${stepCount}`, + } + : { + phase: 'waiting', + actionKey: 'swarm_waiting', + waitingApproval: false, + detailKey: '', + label: '待命中', + detail: '', + stepProgress: '', + startedAtMs: subModMs, + signature: `waiting:${stepCount}`, + } + : { + phase: 'done', + actionKey: 'done', + waitingApproval: false, + detailKey: '', + label: '已完成', + detail: '', + stepProgress: '', + startedAtMs: subModMs, + signature: `done:${stepCount}`, + }; return { cascadeId: subCid, index: subIndex, agentKind, agentOrdinal, customRole, + ...(swarmState ? { swarmState } : {}), + ...(isSwarmAuxiliary ? { isSwarmAuxiliary: true } : {}), ...(isSideQ ? { isSideQuestion: true, sideIndex } : {}), badgeText, shortLabel, role, - typeName: isSideQ ? 'side_question' : subSpec?.typeName || '', + typeName: isSideQ ? 'side_question' : isSwarmW ? 'worker' : subSpec?.typeName || '', isRunning: isSubRunning, status: subSum.status || 'IDLE', stepCount, @@ -1498,52 +1592,86 @@ export async function buildTelemetryPayloadInternal( : null; const runningSubCount = subItems.filter((s) => s.isRunning).length; - if ( - isMainRunning && - (mainLiveAct?.toolName === 'invoke_subagent' || mainLiveAct?.actionKey === 'invoke_subagent') && - runningSubCount === 0 - ) { + const isPendingSubSpawn = + mainLiveAct?.toolName === 'invoke_subagent' || mainLiveAct?.actionKey === 'invoke_subagent'; + const isPendingSwarmSpawn = mainLiveAct?.actionKey === 'swarm_add'; + if (isMainRunning && (isPendingSubSpawn || isPendingSwarmSpawn) && runningSubCount === 0) { const pendingIndex = subItems.length + 1; const pendingCustomRole = mainLiveAct.detail || ''; - const pendingRole = pendingCustomRole || '子代理'; - subItems.push({ - cascadeId: `${rootConv.cascadeId}:pending-sub-${pendingIndex}`, - index: pendingIndex, - agentKind: 'subagent', - agentOrdinal: pendingIndex, - customRole: pendingCustomRole, - badgeText: `子${pendingIndex}`, - shortLabel: `子代理 #${pendingIndex}`, - role: pendingRole, - typeName: '', - isRunning: true, - status: 'CASCADE_RUN_STATUS_RUNNING', - stepCount: 0, - lastModifiedMs: rootFallbackMs, - liveActivity: { - phase: 'thinking', - actionKey: 'starting', - waitingApproval: false, - detailKey: '', - label: '启动中', - detail: '', - stepProgress: '', - startedAtMs: mainLiveAct.startedAtMs || 0, - signature: `spawning-sub:${pendingIndex}:${pendingRole}`, - }, - }); + if (isPendingSwarmSpawn) { + const pendingSwarmOrd = ++runSwarmIdx; + const pendingRole = pendingCustomRole || `蜂群 #${pendingSwarmOrd}`; + subItems.push({ + cascadeId: `${rootConv.cascadeId}:pending-swarm-${pendingIndex}`, + index: pendingIndex, + agentKind: 'swarm_worker', + agentOrdinal: pendingSwarmOrd, + customRole: pendingCustomRole, + swarmState: 'working', + badgeText: `蜂${pendingSwarmOrd}`, + shortLabel: `蜂群 #${pendingSwarmOrd}`, + role: pendingRole, + typeName: 'worker', + isRunning: true, + status: 'CASCADE_RUN_STATUS_RUNNING', + stepCount: 0, + lastModifiedMs: rootFallbackMs, + liveActivity: { + phase: 'thinking', + actionKey: 'starting', + waitingApproval: false, + detailKey: '', + label: '启动中', + detail: '', + stepProgress: '', + startedAtMs: mainLiveAct.startedAtMs || 0, + signature: `spawning-swarm:${pendingSwarmOrd}:${pendingRole}`, + }, + }); + } else { + const pendingNormOrd = ++runNormalSubIdx; + const pendingRole = pendingCustomRole || '子代理'; + subItems.push({ + cascadeId: `${rootConv.cascadeId}:pending-sub-${pendingIndex}`, + index: pendingIndex, + agentKind: 'subagent', + agentOrdinal: pendingNormOrd, + customRole: pendingCustomRole, + badgeText: `子${pendingNormOrd}`, + shortLabel: `子代理 #${pendingNormOrd}`, + role: pendingRole, + typeName: '', + isRunning: true, + status: 'CASCADE_RUN_STATUS_RUNNING', + stepCount: 0, + lastModifiedMs: rootFallbackMs, + liveActivity: { + phase: 'thinking', + actionKey: 'starting', + waitingApproval: false, + detailKey: '', + label: '启动中', + detail: '', + stepProgress: '', + startedAtMs: mainLiveAct.startedAtMs || 0, + signature: `spawning-sub:${pendingIndex}:${pendingRole}`, + }, + }); + } } const runningSubList = subItems.filter((s) => s.isRunning); + const allRunningAreSwarm = + runningSubList.length > 0 && runningSubList.every((s) => s.agentKind === 'swarm_worker'); const resolvedMainActivity = mainLiveAct || (runningSubList.length > 0 ? { phase: 'waiting', - actionKey: 'waiting_subagent', + actionKey: allRunningAreSwarm ? 'waiting_swarm' : 'waiting_subagent', waitingApproval: false, detailKey: '', - label: '等待子代理', + label: allRunningAreSwarm ? '等待工蜂' : '等待子代理', detail: runningSubList.map((s) => s.customRole || s.role).join(', '), stepProgress: '', startedAtMs: runningSubList[0]?.liveActivity?.startedAtMs || rootFallbackMs, @@ -1555,6 +1683,7 @@ export async function buildTelemetryPayloadInternal( runningConversations.push({ cascadeId: rootConv.cascadeId, title: rootConv.title || rootConv.cascadeId.slice(0, 8), + ...(rootConv.swarmTitle ? { swarmTitle: rootConv.swarmTitle } : {}), isCurrentSelected: Boolean(activeCascadeId) && rootConv.cascadeId.toLowerCase() === String(activeCascadeId).toLowerCase(), @@ -1566,7 +1695,11 @@ export async function buildTelemetryPayloadInternal( lastModifiedMs: rootConv.groupLastModifiedMs || rootConv.lastModifiedMs || 0, mainActivity: resolvedMainActivity, subagentCount: subItems.length, + swarmCount: runSwarmIdx, + normalSubagentCount: runNormalSubIdx, + sideQuestionCount: runSideIdx, runningSubagentCount: runningSubList.length, + runningSwarmCount: runningSubList.filter((s) => s.agentKind === 'swarm_worker').length, subagents: subItems, modelShort: qStats.modelShort, modelUpstream: qStats.modelUpstream, @@ -1606,13 +1739,21 @@ export async function buildTelemetryPayloadInternal( const qStats = getConversationQuickStats(c); const rawSubs = Array.isArray(c.subagents) ? c.subagents : []; const runningSubCount = rawSubs.filter((s) => s.status === 'CASCADE_RUN_STATUS_RUNNING').length; + const cSwarmCount = Number(c.swarmCount ?? rawSubs.filter((s) => s.isSwarmWorker).length); + const cSideCount = rawSubs.filter((s) => s.isSideQuestion).length; + const cNormalSubCount = Math.max(0, rawSubs.length - cSwarmCount - cSideCount); return { cascadeId: c.cascadeId, title: c.title, + ...(c.swarmTitle ? { swarmTitle: c.swarmTitle } : {}), stepCount: c.stepCount, subagentCount: c.subagentCount || 0, + swarmCount: cSwarmCount, + normalSubagentCount: cNormalSubCount, + sideQuestionCount: cSideCount, runningSubagentCount: runningSubCount, totalStepCount: c.totalStepCount || c.stepCount || 0, + ...(rawSubs.length > 0 ? { memberCascadeIds: rawSubs.map((s) => s.cascadeId) } : {}), isRunning: c.status === 'CASCADE_RUN_STATUS_RUNNING' || runningSubCount > 0, status: c.status, lastModifiedTime: c.lastModifiedTime, @@ -1628,12 +1769,16 @@ export async function buildTelemetryPayloadInternal( activeConversation: { cascadeId: activeCascadeId, title: activeConvSummary?.title || '当前会话', + ...(activeConvSummary?.swarmTitle ? { swarmTitle: activeConvSummary.swarmTitle } : {}), isRunning: activeConvSummary?.status === 'CASCADE_RUN_STATUS_RUNNING', status: activeConvSummary?.status || 'IDLE', liveActivity: mainAgentTelemetry.liveActivity || null, stepCount: enrichedActiveSteps.length, hasSubagents: subAgentTelemetries.length > 0, subagentCount: subAgentTelemetries.length, + swarmCount: swarmWorkerCount, + normalSubagentCount: normalSubCount, + sideQuestionCount, totalStepsAllAgents: subAgentTelemetries.length ? allCombinedEnrichedSteps.length : enrichedActiveSteps.length, diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 5b8a8bc..57694c1 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/layout/TopSessionHeader.js b/sidecars/panel/src/components/layout/TopSessionHeader.js index 0de020b..bfb75df 100644 --- a/sidecars/panel/src/components/layout/TopSessionHeader.js +++ b/sidecars/panel/src/components/layout/TopSessionHeader.js @@ -11,7 +11,9 @@ import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js'; import { fetchTelemetry, formatAgentBadgeText, + formatConversationMeta, normalizeClientUpdateMode, + resolveHostRouteMatch, telemetryStore, triggerPluginUpdate, } from '../../store/telemetryStore.js'; @@ -19,16 +21,7 @@ import { uiStore } from '../../store/uiStore.js'; import { CustomSelect } from '../ui/CustomSelect.js'; function formatConvOptionMeta(c) { - if (!c) return ''; - const subs = Number(c.subagentCount || 0); - if (subs > 0) { - return t('header.convMetaWithSubs', { - main: c.stepCount || 0, - subs, - total: c.totalStepCount || c.stepCount || 0, - }); - } - return t('header.convMetaSteps', { count: c.stepCount || 0 }); + return formatConversationMeta(c); } export const TopSessionHeader = defineComponent({ @@ -106,10 +99,49 @@ export const TopSessionHeader = defineComponent({ const headerEl = h('header', { className: 'top-session-stack' }, [headerRowEl]); let lastActiveCascadeId = ''; + let lastAppliedHostChildRouteId = ''; - function syncSessionScopeOnCascadeChange(telemetry) { + function syncSessionScopeOnCascadeChange(telemetry, telSlice = telemetryStore.getState()) { const currentCascadeId = telemetry?.activeConversation?.cascadeId || ''; if (!currentCascadeId) return; + + const selectedId = String(telSlice?.selectedConversationId || '').trim(); + const hostRouteId = String(telSlice?.hostRouteConversationId || '').trim(); + const hostRouteLower = hostRouteId.toLowerCase(); + + if (!selectedId && hostRouteLower) { + const routeMatch = resolveHostRouteMatch(telemetry, hostRouteId); + if (routeMatch?.isChildRoute && routeMatch.childAgent?.agentId) { + lastActiveCascadeId = currentCascadeId; + if (lastAppliedHostChildRouteId !== hostRouteLower) { + lastAppliedHostChildRouteId = hostRouteLower; + const targetAgentId = routeMatch.childAgent.agentId; + const uiSt = uiStore.getState(); + if ( + uiSt.selectedAgentScope !== targetAgentId || + uiSt.ctxInspectorAgentId !== targetAgentId + ) { + uiStore.setState({ + selectedAgentScope: targetAgentId, + ctxInspectorAgentId: targetAgentId, + }); + } + } + return; + } + if (lastAppliedHostChildRouteId && !routeMatch?.isChildRoute) { + lastAppliedHostChildRouteId = ''; + const uiSt = uiStore.getState(); + if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== 'auto') { + uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); + } + lastActiveCascadeId = currentCascadeId; + return; + } + } else if (lastAppliedHostChildRouteId) { + lastAppliedHostChildRouteId = ''; + } + if (lastActiveCascadeId && currentCascadeId !== lastActiveCascadeId) { lastActiveCascadeId = currentCascadeId; const uiSt = uiStore.getState(); @@ -133,34 +165,44 @@ export const TopSessionHeader = defineComponent({ const actConv = telemetry?.activeConversation; const convs = telemetry?.conversations || []; const hostRouteId = telSt.hostRouteConversationId || ''; - const hostMatchedConv = hostRouteId - ? convs.find((c) => c.cascadeId === hostRouteId) || - (actConv?.cascadeId === hostRouteId ? actConv : null) - : null; + const routeMatch = hostRouteId ? resolveHostRouteMatch(telemetry, hostRouteId) : null; + const hostMatchedConv = routeMatch?.rootConv || null; + const childRouteBadge = + routeMatch?.isChildRoute && routeMatch.childAgent + ? formatAgentBadgeText(routeMatch.childAgent) + : ''; + const hostBaseTitle = hostMatchedConv?.title || hostRouteId.slice(0, 8); + const hostDisplayTitle = childRouteBadge + ? `${hostBaseTitle} · ${childRouteBadge}` + : hostBaseTitle; const defaultOptLabel = hostRouteId ? t('header.currentWindowNamed', { - title: hostMatchedConv?.title || hostRouteId.slice(0, 8), + title: hostDisplayTitle, }) : convs[0]?.title ? t('header.latestNamed', { title: convs[0].title }) : t('header.followLatest'); const defaultOptMeta = hostRouteId ? hostMatchedConv - ? formatConvOptionMeta({ - stepCount: hostMatchedConv.stepCount, - subagentCount: hostMatchedConv.subagentCount, - totalStepCount: hostMatchedConv.totalStepCount ?? hostMatchedConv.totalStepsAllAgents, - }) + ? formatConvOptionMeta(hostMatchedConv) : '' : convs[0] ? formatConvOptionMeta(convs[0]) : ''; const options = [ - { value: '', label: defaultOptLabel, meta: defaultOptMeta }, + { + value: '', + label: defaultOptLabel, + meta: defaultOptMeta, + ...(hostMatchedConv?.swarmTitle ? { title: hostMatchedConv.swarmTitle } : {}), + }, ...convs.map((c) => ({ value: c.cascadeId, label: c.title || c.cascadeId.slice(0, 8), meta: formatConvOptionMeta(c), + ...(c.swarmTitle && c.swarmTitle !== c.title + ? { title: `${c.title || c.cascadeId.slice(0, 8)} · ${c.swarmTitle}` } + : {}), })), ]; const lockedId = telSt.selectedConversationId; @@ -170,13 +212,7 @@ export const TopSessionHeader = defineComponent({ isLoadedLocked && actConv?.title ? actConv.title : t('header.lockedSession', { id: String(lockedId).slice(0, 8) }); - const lockedMeta = isLoadedLocked - ? formatConvOptionMeta({ - stepCount: actConv.stepCount, - subagentCount: actConv.subagentCount, - totalStepCount: actConv.totalStepsAllAgents, - }) - : t('header.lockedMeta'); + const lockedMeta = isLoadedLocked ? formatConvOptionMeta(actConv) : t('header.lockedMeta'); options.splice(1, 0, { value: lockedId, label: lockedTitle, @@ -283,7 +319,7 @@ export const TopSessionHeader = defineComponent({ telemetry: st.telemetry, }), (slice) => { - syncSessionScopeOnCascadeChange(slice.telemetry); + syncSessionScopeOnCascadeChange(slice.telemetry, slice); renderHeaderState(); } ); diff --git a/sidecars/panel/src/components/layout/WindowOverlayShell.js b/sidecars/panel/src/components/layout/WindowOverlayShell.js index 08a460a..a5ac57f 100644 --- a/sidecars/panel/src/components/layout/WindowOverlayShell.js +++ b/sidecars/panel/src/components/layout/WindowOverlayShell.js @@ -2297,16 +2297,26 @@ export function mountWindowOverlay() { syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx); } - function renderMultiRunningPanel(rawRunningList, runningCount, runningSubCount, hostRouteConversationId) { + function renderMultiRunningPanel( + rawRunningList, + runningCount, + runningSubCount, + hostRouteConversationId, + runningSwarmCount = 0 + ) { if (!multiOpen || document.hidden) { multiRunningWidget.refs.pauseTicker(); return; } + const isPureSwarm = runningSubCount > 0 && runningSwarmCount === runningSubCount; patchText( multiRunningMetaEl, runningCount > 0 ? runningSubCount > 0 - ? t('multi.metaWithSubs', { main: runningCount, subs: runningSubCount }) + ? t(isPureSwarm ? 'multi.metaWithSwarm' : 'multi.metaWithSubs', { + main: runningCount, + subs: runningSubCount, + }) : t('multi.metaMainOnly', { main: runningCount }) : t('multi.allIdle') ); @@ -2377,13 +2387,19 @@ export function mountWindowOverlay() { ctxAgent, aggregated, }); - const { rawRunningList, runningCount, runningSubCount, hasWaiting, multiBtnText } = - resolveMultiSessionCapsuleState(telemetry, { - agents, - aggregated, - latestTokPerSec: overviewActive.latestTokPerSec ?? null, - contextUsedPct: slotCtx.usedPct, - }); + const { + rawRunningList, + runningCount, + runningSubCount, + runningSwarmCount, + hasWaiting, + multiBtnText, + } = resolveMultiSessionCapsuleState(telemetry, { + agents, + aggregated, + latestTokPerSec: overviewActive.latestTokPerSec ?? null, + contextUsedPct: slotCtx.usedPct, + }); patchClasses(multiBtn, { 'is-running': runningCount > 0 && !hasWaiting, @@ -2395,7 +2411,8 @@ export function mountWindowOverlay() { rawRunningList, runningCount, runningSubCount, - telSt.hostRouteConversationId + telSt.hostRouteConversationId, + runningSwarmCount ); patchClasses(capsuleBtn, { 'is-running': slotCtx.isRunning }); diff --git a/sidecars/panel/src/components/widgets/CapsuleBarWidget.js b/sidecars/panel/src/components/widgets/CapsuleBarWidget.js index e74c8c6..0c60054 100644 --- a/sidecars/panel/src/components/widgets/CapsuleBarWidget.js +++ b/sidecars/panel/src/components/widgets/CapsuleBarWidget.js @@ -94,14 +94,29 @@ export function resolveMultiSessionCapsuleState( (acc, item) => acc + Number(item.runningSubagentCount || 0), 0 ); + const runningSwarmCount = rawRunningList.reduce( + (acc, item) => acc + Number(item.runningSwarmCount || 0), + 0 + ); + const isPureSwarmSubs = runningSubCount > 0 && runningSwarmCount === runningSubCount; const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting'); const multiBtnText = runningCount > 0 ? runningSubCount > 0 - ? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount }) + ? t(isPureSwarmSubs ? 'capsule.multiRunningWithSwarm' : 'capsule.multiRunningWithSubs', { + count: runningCount, + subs: runningSubCount, + }) : t('capsule.multiRunning', { count: runningCount }) : t('capsule.multiZero'); - return { rawRunningList, runningCount, runningSubCount, hasWaiting, multiBtnText }; + return { + rawRunningList, + runningCount, + runningSubCount, + runningSwarmCount, + hasWaiting, + multiBtnText, + }; } /** diff --git a/sidecars/panel/src/components/widgets/LiveActivityWidget.js b/sidecars/panel/src/components/widgets/LiveActivityWidget.js index 23f4b2a..c65f761 100644 --- a/sidecars/panel/src/components/widgets/LiveActivityWidget.js +++ b/sidecars/panel/src/components/widgets/LiveActivityWidget.js @@ -40,43 +40,68 @@ export function buildFallbackRunningConversations( } const activeConv = data.activeConversation || {}; if (!activeConv.isRunning && !aggregated?.isRunning) return []; + const childAgents = (agents || []).filter((a) => !a.isMain); + const swarmChildren = childAgents.filter((a) => a.agentKind === 'swarm_worker'); return [ { cascadeId: activeConv.cascadeId || 'current', title: activeConv.title || t('live.currentSession'), + ...(activeConv.swarmTitle ? { swarmTitle: activeConv.swarmTitle } : {}), isCurrentSelected: true, isMainRunning: Boolean(activeConv.isRunning), isRunning: true, mainActivity: activeConv.liveActivity || aggregated?.liveActivity || null, - subagentCount: Math.max(0, (agents?.length || 1) - 1), - runningSubagentCount: (agents || []).filter((a) => !a.isMain && a.isRunning).length, + subagentCount: childAgents.length, + swarmCount: swarmChildren.length, + runningSubagentCount: childAgents.filter((a) => a.isRunning).length, + runningSwarmCount: swarmChildren.filter((a) => a.isRunning).length, ...(latestTokPerSec !== undefined ? { latestTokPerSec } : {}), ...(contextUsedPct !== undefined ? { contextUsedPct } : {}), - subagents: (agents || []) - .filter((a) => !a.isMain) - .map((s, idx) => ({ + subagents: childAgents.map((s, idx) => { + const isSwarmW = s.agentKind === 'swarm_worker'; + const isKilled = Boolean(s.swarmState === 'killed'); + return { cascadeId: s.cascadeId || s.agentId, index: s.index || idx + 1, agentKind: s.agentKind || (s.isSideQuestion ? 'side_question' : 'subagent'), - agentOrdinal: s.agentOrdinal || (s.isSideQuestion ? s.sideIndex || 0 : s.index || idx + 1), + agentOrdinal: + s.agentOrdinal || (s.isSideQuestion ? s.sideIndex || 0 : s.index || idx + 1), customRole: s.customRole, + ...(s.swarmState ? { swarmState: s.swarmState } : {}), ...(s.isSideQuestion ? { isSideQuestion: true, sideIndex: s.sideIndex || 0 } : {}), badgeText: formatAgentBadgeText({ ...s, index: s.index || idx + 1 }), - shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`, - role: s.role || `${t('fmt.subAgent')} #${idx + 1}`, + shortLabel: + s.shortLabel || + `${isSwarmW ? t('fmt.swarmAgent') : t('fmt.subAgent')} #${s.agentOrdinal || idx + 1}`, + role: + s.role || + `${isSwarmW ? t('fmt.swarmAgent') : t('fmt.subAgent')} #${s.agentOrdinal || idx + 1}`, isRunning: Boolean(s.isRunning), stepCount: Number(s.stepCount || 0), lastModifiedMs: s.lastModifiedMs || 0, liveActivity: s.liveActivity || { - phase: s.isRunning ? 'thinking' : 'done', - actionKey: s.isRunning ? 'thinking' : 'done', - label: s.isRunning ? t('live.thinking') : t('live.done'), + phase: s.isRunning ? 'thinking' : isSwarmW && !isKilled ? 'waiting' : 'done', + actionKey: s.isRunning + ? 'thinking' + : isSwarmW + ? isKilled + ? 'swarm_killed' + : 'swarm_waiting' + : 'done', + label: s.isRunning + ? t('live.thinking') + : isSwarmW + ? isKilled + ? t('live.killed') + : t('live.waiting') + : t('live.done'), detail: '', stepProgress: '', startedAtMs: s.lastModifiedMs || 0, - signature: `${s.agentId}:${s.stepCount || 0}`, + signature: `${s.agentId}:${s.swarmState || ''}:${s.stepCount || 0}`, }, - })), + }; + }), }, ]; } @@ -362,14 +387,17 @@ export const LiveActivityWidget = defineComponent({ const isHere = showSessionExtras && Boolean(hostRouteLower) && - String(item.cascadeId || '').toLowerCase() === hostRouteLower; + (String(item.cascadeId || '').toLowerCase() === hostRouteLower || + (item.subagents || []).some( + (s) => String(s?.cascadeId || '').toLowerCase() === hostRouteLower + )); const subSig = (item.subagents || []) .map( (s) => - `${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}` + `${s.cascadeId}:${s.isRunning}:${s.swarmState || ''}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}` ) .join('|'); - return `${locale}:${item.cascadeId}:${item.title}:${isHere}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.latestTokPerSec ?? ''}:${item.contextUsedPct ?? ''}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`; + return `${locale}:${item.cascadeId}:${item.title}:${isHere}:${item.isMainRunning}:${item.subagentCount}:${item.swarmCount || 0}:${item.runningSubagentCount}:${isExp}:${item.latestTokPerSec ?? ''}:${item.contextUsedPct ?? ''}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`; }, createRow: createLiveTaskCard, updateRow: (refs, item) => { @@ -416,7 +444,10 @@ export const LiveActivityWidget = defineComponent({ if (showSessionExtras && refs.hereTagEl && refs.metricsEl) { const isHere = Boolean(hostRouteLower) && - String(item.cascadeId || '').toLowerCase() === hostRouteLower; + (String(item.cascadeId || '').toLowerCase() === hostRouteLower || + (item.subagents || []).some( + (s) => String(s?.cascadeId || '').toLowerCase() === hostRouteLower + )); patchText(refs.hereTagEl, t('multi.hereTag')); patchAttr(refs.hereTagEl, 'hidden', !isHere); @@ -437,6 +468,11 @@ export const LiveActivityWidget = defineComponent({ } const subCount = Number(item.subagentCount || item.subagents?.length || 0); + const swarmCount = Number( + item.swarmCount ?? + (item.subagents || []).filter((s) => s?.agentKind === 'swarm_worker').length + ); + const isPureSwarm = subCount > 0 && swarmCount === subCount; const runSubCount = Number(item.runningSubagentCount || 0); const isExpanded = resolveIsExpanded(item); patchText(refs.mainBadge, t('fmt.mainBadge')); @@ -446,8 +482,15 @@ export const LiveActivityWidget = defineComponent({ const arrow = isExpanded ? '▾' : '▸'; const toggleText = runSubCount > 0 - ? t('live.subToggleRunning', { run: runSubCount, total: subCount, arrow }) - : t('live.subToggleIdle', { total: subCount, arrow }); + ? t(isPureSwarm ? 'live.swarmToggleRunning' : 'live.subToggleRunning', { + run: runSubCount, + total: subCount, + arrow, + }) + : t(isPureSwarm ? 'live.swarmToggleIdle' : 'live.subToggleIdle', { + total: subCount, + arrow, + }); patchText(refs.subToggleBtn, toggleText); patchClasses(refs.subToggleBtn, { 'is-expanded': isExpanded }); if (interactive) { @@ -495,11 +538,28 @@ export const LiveActivityWidget = defineComponent({ const showSubs = subCount > 0 && isExpanded; patchAttr(refs.subListEl, 'hidden', !showSubs); if (showSubs) { - const subItems = item.subagents || []; + const rawSubItems = item.subagents || []; + const getSubSortRank = (s) => { + if (s?.isRunning) return 0; + if (s?.swarmState === 'waiting' || s?.liveActivity?.actionKey === 'swarm_waiting') { + return 1; + } + return 2; + }; + const subItems = + rawSubItems.length > 1 + ? rawSubItems + .slice() + .sort( + (a, b) => + getSubSortRank(a) - getSubSortRank(b) || + Number(a?.index || 0) - Number(b?.index || 0) + ) + : rawSubItems; patchKeyedList(refs.subListEl, subItems, { keyFn: (sub) => sub.cascadeId, sigFn: (sub) => - `${locale}:${sub.cascadeId}:${sub.role}:${sub.isRunning}:${sub.stepCount}:${sub.liveActivity?.signature || ''}:${sub.isRunning ? activityTimersMap.has(`sub:${sub.cascadeId}`) : true}`, + `${locale}:${sub.cascadeId}:${sub.agentKind || ''}:${sub.swarmState || ''}:${sub.role}:${sub.isRunning}:${sub.stepCount}:${sub.liveActivity?.signature || ''}:${sub.isRunning ? activityTimersMap.has(`sub:${sub.cascadeId}`) : true}`, createRow: createLiveSubRow, updateRow: (subRefs, sub) => { const subAct = sub.liveActivity || { @@ -510,7 +570,17 @@ export const LiveActivityWidget = defineComponent({ stepProgress: '', startedAtMs: sub.lastModifiedMs || 0, }; - patchClasses(subRefs.rowEl, { 'is-done': !sub.isRunning }); + const isWaitingSub = + !sub.isRunning && + (sub.swarmState === 'waiting' || subAct.actionKey === 'swarm_waiting'); + const isKilledSub = + !sub.isRunning && + (sub.swarmState === 'killed' || subAct.actionKey === 'swarm_killed'); + patchClasses(subRefs.rowEl, { + 'is-done': !sub.isRunning && !isWaitingSub, + 'is-waiting-sub': isWaitingSub, + 'is-killed-sub': isKilledSub, + }); const badgeCls = getAgentBadgeClass(sub.index || 1, false); const subBadgeText = formatAgentBadgeText({ @@ -524,22 +594,33 @@ export const LiveActivityWidget = defineComponent({ const fallbackRole = sub.agentKind === 'side_question' || sub.isSideQuestion ? `${t('fmt.sideQuestion')}${sub.agentOrdinal || sub.sideIndex ? ` #${sub.agentOrdinal || sub.sideIndex}` : ''}` - : `${t('fmt.subAgent')}${sub.agentOrdinal || sub.index ? ` #${sub.agentOrdinal || sub.index}` : ''}`; + : sub.agentKind === 'swarm_worker' + ? `${t('fmt.swarmAgent')}${sub.agentOrdinal || sub.index ? ` #${sub.agentOrdinal || sub.index}` : ''}` + : `${t('fmt.subAgent')}${sub.agentOrdinal || sub.index ? ` #${sub.agentOrdinal || sub.index}` : ''}`; const roleText = sub.customRole !== undefined ? sub.customRole || fallbackRole : sub.role || sub.shortLabel || fallbackRole; patchText(subRefs.subRole, roleText); + const idleFallbackKey = isKilledSub + ? 'live.killed' + : isWaitingSub + ? 'live.waiting' + : 'live.done'; const subLabel = sub.isRunning ? formatLiveActivityLabel(subAct, 'live.running') - : formatLiveActivityLabel(subAct, 'live.done'); + : formatLiveActivityLabel(subAct, idleFallbackKey); const subDetail = formatLiveActivityDetail(subAct); const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : ''; const summaryStr = showSessionExtras ? sub.isRunning ? `${subLabel}${subProg}${subDetail ? ` · ${subDetail}` : ''}` - : t('live.doneWithSteps', { steps: sub.stepCount || 0 }) + : isKilledSub + ? t('live.killedWithSteps', { steps: sub.stepCount || 0 }) + : isWaitingSub + ? t('live.waitingWithSteps', { steps: sub.stepCount || 0 }) + : t('live.doneWithSteps', { steps: sub.stepCount || 0 }) : [`${subLabel}${subProg}`.trim(), subDetail].filter(Boolean).join(' '); patchAttr(subRefs.subSummary, 'hidden', !summaryStr); patchText(subRefs.subSummary, summaryStr); diff --git a/sidecars/panel/src/core/formatters.js b/sidecars/panel/src/core/formatters.js index 5eac14e..32c1faa 100644 --- a/sidecars/panel/src/core/formatters.js +++ b/sidecars/panel/src/core/formatters.js @@ -496,21 +496,48 @@ export function getAgentBadgeClass(index = 0, isMain = false) { return `badge-sub-${slot}`; } +function resolveStructuredAgentKind(agent) { + if (!agent) return 'main'; + if (agent.agentKind) return agent.agentKind; + if (agent.isMain) return 'main'; + if (agent.isSideQuestion || agent.typeName === 'side_question') return 'side_question'; + if ( + agent.typeName === 'worker' || + agent.typeName === 'swarm_worker' || + /^Swarm\s+Worker\s*\(/i.test(String(agent.role || '')) + ) { + return 'swarm_worker'; + } + return 'subagent'; +} + +function normalizeSwarmMemberHandle(rawText) { + const trimmed = String(rawText || '').trim(); + if (!trimmed) return ''; + const wrapper = trimmed.match(/^Swarm\s+Worker\s*\(([^)]+)\)\s*$/i); + const inner = (wrapper ? wrapper[1] : trimmed).replace(/^@+/, '').trim(); + if ( + !inner || + inner === '蜂群' || + inner === '工蜂' || + inner.toLowerCase() === 'swarm' || + inner.toLowerCase() === 'worker' || + inner.toLowerCase() === 'swarm worker' + ) { + return ''; + } + return `@${inner}`; +} + /** - * 基于结构化 `agentKind` / `agentOrdinal` 格式化主/子代理或旁路提问的紧凑徽章文本(零正则反拆中文)。 + * 基于结构化 `agentKind` / `agentOrdinal` 格式化主/子代理、蜂群节点或旁路提问的紧凑徽章文本(零正则反拆中文)。 * * @param {object|null|undefined} agent * @returns {string} */ export function formatAgentBadgeText(agent) { if (!agent) return t('fmt.mainBadge'); - const kind = - agent.agentKind || - (agent.isMain - ? 'main' - : agent.isSideQuestion || agent.typeName === 'side_question' - ? 'side_question' - : 'subagent'); + const kind = resolveStructuredAgentKind(agent); if (kind === 'all') return t('header.scopeAllShort'); if (kind === 'main') return t('fmt.mainBadge'); if (kind === 'side_question') { @@ -519,6 +546,12 @@ export function formatAgentBadgeText(agent) { if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText); return t('fmt.sideBadgeShort'); } + if (kind === 'swarm_worker') { + const ord = Number(agent.agentOrdinal || agent.index || 0); + if (ord > 0) return t('fmt.swarmBadge', { index: ord }); + if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText); + return t('fmt.swarmBadgeShort'); + } const ord = Number(agent.agentOrdinal || agent.index || 0); if (ord > 0) return t('fmt.subBadge', { index: ord }); if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText); @@ -533,13 +566,7 @@ export function formatAgentBadgeText(agent) { */ export function formatAgentLabel(agent) { if (!agent) return t('fmt.mainAgent'); - const kind = - agent.agentKind || - (agent.isMain - ? 'main' - : agent.isSideQuestion || agent.typeName === 'side_question' - ? 'side_question' - : 'subagent'); + const kind = resolveStructuredAgentKind(agent); if (kind === 'all') return t('header.scopeAll'); if (kind === 'main') return t('fmt.mainAgent'); @@ -560,6 +587,20 @@ export function formatAgentLabel(agent) { return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`; } + if (kind === 'swarm_worker') { + const ord = Number(agent.agentOrdinal || agent.index || 0); + const baseLabel = ord > 0 ? `${t('fmt.swarmAgent')} #${ord}` : t('fmt.swarmAgent'); + const handle = normalizeSwarmMemberHandle(rawCustom || agent.role || ''); + if (!handle) return baseLabel; + let auxSuffix = ''; + if (/^@monitor(?:-\d+)?$/i.test(handle)) { + auxSuffix = ` (${t('fmt.swarmMonitorHint')})`; + } else if (/^@narrator(?:-\d+)?$/i.test(handle)) { + auxSuffix = ` (${t('fmt.swarmNarratorHint')})`; + } + return `${baseLabel} · ${handle}${auxSuffix}`; + } + const ord = Number(agent.agentOrdinal || agent.index || 0); const baseLabel = ord > 0 ? `${t('fmt.subAgent')} #${ord}` : t('fmt.subAgent'); const isGeneric = @@ -571,6 +612,31 @@ export function formatAgentLabel(agent) { return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`; } +/** + * 格式化会话选项右侧元信息(自适应区分纯蜂群、蜂群+子代理混合、常规子代理与单会话步数)。 + * + * @param {object|null|undefined} conv + * @returns {string} + */ +export function formatConversationMeta(conv) { + if (!conv) return ''; + const main = Number(conv.stepCount || 0); + const totalSubs = Number(conv.subagentCount || 0); + const swarm = Number(conv.swarmCount || 0); + const otherSubs = Math.max(0, totalSubs - swarm); + const total = Number(conv.totalStepCount ?? conv.totalStepsAllAgents ?? main); + if (swarm > 0 && otherSubs > 0) { + return t('header.convMetaWithSwarmAndSubs', { main, swarm, subs: otherSubs, total }); + } + if (swarm > 0) { + return t('header.convMetaWithSwarm', { main, swarm, total }); + } + if (totalSubs > 0) { + return t('header.convMetaWithSubs', { main, subs: totalSubs, total }); + } + return t('header.convMetaSteps', { count: main }); +} + /** * 基于后端结构化 `actionKey` + `waitingApproval` 渲染实时动作短标题(兼容自定义 `label` 回退)。 * diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 7982e29..e037e47 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -17,6 +17,8 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'header.lockedSession': 'Pinned Session ({id})', 'header.lockedMeta': 'Pinned', 'header.convMetaWithSubs': 'Main {main} · {subs} sub ({total} steps)', + 'header.convMetaWithSwarm': 'Main {main} · {swarm} swarm ({total} steps)', + 'header.convMetaWithSwarmAndSubs': 'Main {main} · {swarm} swarm · {subs} sub ({total} steps)', 'header.convMetaSteps': '{count} steps', 'header.hasUpdate': 'Update', 'header.upgradeToVer': 'Update v{ver}', @@ -55,6 +57,11 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'fmt.subAgent': 'Subagent', 'fmt.subBadge': 'S{index}', 'fmt.subBadgeShort': 'Sub', + 'fmt.swarmAgent': 'Swarm', + 'fmt.swarmBadge': 'W{index}', + 'fmt.swarmBadgeShort': 'Swarm', + 'fmt.swarmMonitorHint': 'Monitor', + 'fmt.swarmNarratorHint': 'Narrator', 'fmt.sideQuestion': 'Side Question', 'fmt.sideBadge': 'Q{index}', 'fmt.sideBadgeShort': 'Q', @@ -68,6 +75,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'capsule.multiZero': '0 active', 'capsule.multiRunning': '{count} active', 'capsule.multiRunningWithSubs': '{count} active · {subs} sub', + 'capsule.multiRunningWithSwarm': '{count} active · {subs} swarm', 'capsule.tpsRunning': 'Running', 'capsule.tpsIdle': 'Idle', 'capsule.quotaLeft': '{pct}% left', @@ -88,6 +96,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'multi.empty': 'No active running sessions', 'multi.allIdle': 'All idle', 'multi.metaWithSubs': '{main} main · {subs} subagents active', + 'multi.metaWithSwarm': '{main} main · {subs} swarm active', 'multi.metaMainOnly': '{main} sessions active', 'multi.hereTag': 'Here', 'multi.inspectSessionTitle': 'Inspect session in monitor: {title}', @@ -184,10 +193,16 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'live.thinking': 'Thinking', 'live.generating': 'Generating', 'live.running': 'Running', + 'live.waiting': 'Waiting', + 'live.killed': 'Killed', 'live.done': 'Done', 'live.doneWithSteps': 'Done ({steps} steps)', + 'live.waitingWithSteps': 'Waiting ({steps} steps)', + 'live.killedWithSteps': 'Killed ({steps} steps)', 'live.subToggleRunning': 'Subagents {run}/{total} {arrow}', 'live.subToggleIdle': 'Subagents ({total}) {arrow}', + 'live.swarmToggleRunning': 'Swarm {run}/{total} {arrow}', + 'live.swarmToggleIdle': 'Swarm ({total}) {arrow}', 'live.subCollapseTitle': 'Collapse subagent list', 'live.subExpandTitle': 'Expand subagent activity list', @@ -558,6 +573,15 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'live.act.invoke_subagent': 'Invoke Subagent', 'live.act.send_message': 'Message Subagent', 'live.act.manage_subagents': 'Manage Subagents', + 'live.act.swarm_add': 'Spawn Worker', + 'live.act.swarm_title': 'Name Swarm', + 'live.act.swarm_kill': 'Kill Worker', + 'live.act.swarm_model': 'Switch Worker Model', + 'live.act.swarm_channel': 'Swarm Channel', + 'live.act.swarm_status': 'Check Swarm', + 'live.act.post_message': 'Post to Board', + 'live.act.read_board': 'Read Board', + 'live.act.swarm_wait': 'Parked on Board', 'live.act.manage_task': 'Manage Task', 'live.act.schedule': 'Schedule Task', 'live.act.ask_question': 'Waiting for User Choice', @@ -568,6 +592,9 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'live.act.compacting': 'Compacting Context', 'live.act.responding': 'Responding', 'live.act.waiting_subagent': 'Waiting for Subagent', + 'live.act.waiting_swarm': 'Waiting for Swarm', + 'live.act.swarm_waiting': 'Waiting', + 'live.act.swarm_killed': 'Killed', 'live.act.starting': 'Starting', 'live.act.done': 'Completed', 'live.act.awaitingApproval': 'Awaiting Approval · {label}', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index d30607e..08a9299 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -17,6 +17,8 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'header.lockedSession': '已锁定会话 ({id})', 'header.lockedMeta': '已锁定', 'header.convMetaWithSubs': '主{main} · {subs}子 (共{total}步)', + 'header.convMetaWithSwarm': '主{main} · {swarm}蜂 (共{total}步)', + 'header.convMetaWithSwarmAndSubs': '主{main} · {swarm}蜂 · {subs}子 (共{total}步)', 'header.convMetaSteps': '{count}步', 'header.hasUpdate': '有新版本', 'header.upgradeToVer': '升级 v{ver}', @@ -55,6 +57,11 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'fmt.subAgent': '子代理', 'fmt.subBadge': '子{index}', 'fmt.subBadgeShort': '子', + 'fmt.swarmAgent': '蜂群', + 'fmt.swarmBadge': '蜂{index}', + 'fmt.swarmBadgeShort': '蜂', + 'fmt.swarmMonitorHint': '巡检', + 'fmt.swarmNarratorHint': '旁白', 'fmt.sideQuestion': '旁路提问', 'fmt.sideBadge': '旁{index}', 'fmt.sideBadgeShort': '旁', @@ -68,6 +75,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'capsule.multiZero': '0 运行中', 'capsule.multiRunning': '{count} 运行中', 'capsule.multiRunningWithSubs': '{count} 运行 · {subs} 子', + 'capsule.multiRunningWithSwarm': '{count} 运行 · {subs} 蜂', 'capsule.tpsRunning': '生成中', 'capsule.tpsIdle': '待命', 'capsule.quotaLeft': '余 {pct}%', @@ -88,6 +96,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'multi.empty': '当前暂无在线运行的会话', 'multi.allIdle': '全部待命', 'multi.metaWithSubs': '{main} 主会话 · {subs} 子代理运行中', + 'multi.metaWithSwarm': '{main} 主会话 · {subs} 蜂群运行中', 'multi.metaMainOnly': '{main} 个会话运行中', 'multi.hereTag': '本窗', 'multi.inspectSessionTitle': '点击在监控面板中检视会话:{title}', @@ -184,10 +193,16 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'live.thinking': '推理中', 'live.generating': '生成中', 'live.running': '运行中', + 'live.waiting': '待命中', + 'live.killed': '已终止', 'live.done': '已完成', 'live.doneWithSteps': '已完成 ({steps} 步)', + 'live.waitingWithSteps': '待命中 ({steps} 步)', + 'live.killedWithSteps': '已终止 ({steps} 步)', 'live.subToggleRunning': '子代理 {run}/{total} {arrow}', 'live.subToggleIdle': '子代理 ({total}) {arrow}', + 'live.swarmToggleRunning': '蜂群 {run}/{total} {arrow}', + 'live.swarmToggleIdle': '蜂群 ({total}) {arrow}', 'live.subCollapseTitle': '点击收起子代理列表', 'live.subExpandTitle': '点击展开查看子代理缩略状态', @@ -558,6 +573,15 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'live.act.invoke_subagent': '调用子代理', 'live.act.send_message': '通信子代理', 'live.act.manage_subagents': '管理子代理', + 'live.act.swarm_add': '派生工蜂', + 'live.act.swarm_title': '命名蜂群', + 'live.act.swarm_kill': '终止工蜂', + 'live.act.swarm_model': '切换工蜂模型', + 'live.act.swarm_channel': '蜂群频道', + 'live.act.swarm_status': '巡检蜂群', + 'live.act.post_message': '发布看板', + 'live.act.read_board': '读取看板', + 'live.act.swarm_wait': '看板待命', 'live.act.manage_task': '后台任务', 'live.act.schedule': '定时任务', 'live.act.ask_question': '等待用户选择', @@ -568,6 +592,9 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'live.act.compacting': '上下文压缩', 'live.act.responding': '正在输出回复', 'live.act.waiting_subagent': '等待子代理', + 'live.act.waiting_swarm': '等待工蜂', + 'live.act.swarm_waiting': '待命中', + 'live.act.swarm_killed': '已终止', 'live.act.starting': '启动中', 'live.act.done': '已完成', 'live.act.awaitingApproval': '等待确认 · {label}', diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index c0dafbd..9d647b1 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -8,6 +8,7 @@ import { callSidecarApi, getWindowBridgeConfig, isWindowOverlayMode } from '../c import { formatAgentBadgeText, formatAgentLabel, + formatConversationMeta, formatLiveActivityDetail, formatLiveActivityLabel, getAgentBadgeClass, @@ -299,6 +300,8 @@ export function isEquivalentTelemetry(prev, next) { if (pAct?.cascadeId !== nAct?.cascadeId) return false; if (pAct?.stepCount !== nAct?.stepCount) return false; if (pAct?.subagentCount !== nAct?.subagentCount) return false; + if ((pAct?.swarmCount || 0) !== (nAct?.swarmCount || 0)) return false; + if ((pAct?.swarmTitle || '') !== (nAct?.swarmTitle || '')) return false; if (pAct?.totalStepsAllAgents !== nAct?.totalStepsAllAgents) return false; if (pAct?.isRunning !== nAct?.isRunning) return false; if ( @@ -375,6 +378,9 @@ export function isEquivalentTelemetry(prev, next) { const na = nAgents[i]; if ( pa?.agentId !== na?.agentId || + pa?.agentKind !== na?.agentKind || + pa?.agentOrdinal !== na?.agentOrdinal || + (pa?.swarmState || '') !== (na?.swarmState || '') || pa?.role !== na?.role || pa?.stepCount !== na?.stepCount || pa?.isRunning !== na?.isRunning || @@ -660,6 +666,8 @@ export function isEquivalentTelemetry(prev, next) { pConvs[i]?.status !== nConvs[i]?.status || pConvs[i]?.stepCount !== nConvs[i]?.stepCount || pConvs[i]?.subagentCount !== nConvs[i]?.subagentCount || + (pConvs[i]?.swarmCount || 0) !== (nConvs[i]?.swarmCount || 0) || + (pConvs[i]?.swarmTitle || '') !== (nConvs[i]?.swarmTitle || '') || pConvs[i]?.totalStepCount !== nConvs[i]?.totalStepCount ) { return false; @@ -678,7 +686,9 @@ export function isEquivalentTelemetry(prev, next) { pr?.isCurrentSelected !== nr?.isCurrentSelected || pr?.isMainRunning !== nr?.isMainRunning || pr?.subagentCount !== nr?.subagentCount || + (pr?.swarmCount || 0) !== (nr?.swarmCount || 0) || pr?.runningSubagentCount !== nr?.runningSubagentCount || + (pr?.runningSwarmCount || 0) !== (nr?.runningSwarmCount || 0) || pr?.mainActivity?.signature !== nr?.mainActivity?.signature || pr?.mainActivity?.startedAtMs !== nr?.mainActivity?.startedAtMs ) { @@ -690,6 +700,8 @@ export function isEquivalentTelemetry(prev, next) { for (let j = 0; j < pSubs.length; j++) { if ( pSubs[j]?.cascadeId !== nSubs[j]?.cascadeId || + pSubs[j]?.agentKind !== nSubs[j]?.agentKind || + (pSubs[j]?.swarmState || '') !== (nSubs[j]?.swarmState || '') || pSubs[j]?.role !== nSubs[j]?.role || pSubs[j]?.isRunning !== nSubs[j]?.isRunning || pSubs[j]?.stepCount !== nSubs[j]?.stepCount || @@ -1087,11 +1099,60 @@ export function stopAsyncTelemetryLoop() { export { formatAgentBadgeText, formatAgentLabel, + formatConversationMeta, formatLiveActivityDetail, formatLiveActivityLabel, getAgentBadgeClass, }; +/** + * 在遥测快照中解析宿主当前路由会话 ID(兼容顶层主会话 ID 与子代理/蜂群工蜂 ID)。 + * + * @param {object|null|undefined} telemetry + * @param {string} rawRouteId + * @returns {{ rootConv: object|null, childAgent: object|null, isChildRoute: boolean } | null} + */ +export function resolveHostRouteMatch(telemetry, rawRouteId) { + const routeLower = String(rawRouteId || '').trim().toLowerCase(); + if (!routeLower || !telemetry) return null; + const convs = Array.isArray(telemetry.conversations) ? telemetry.conversations : []; + const actConv = telemetry.activeConversation || null; + + const directRoot = + convs.find((c) => String(c?.cascadeId || '').toLowerCase() === routeLower) || + (String(actConv?.cascadeId || '').toLowerCase() === routeLower ? actConv : null); + if (directRoot) { + return { rootConv: directRoot, childAgent: null, isChildRoute: false }; + } + + const activeChild = (actConv?.agents || []).find( + (a) => + !a?.isMain && + (String(a?.cascadeId || '').toLowerCase() === routeLower || + String(a?.agentId || '').toLowerCase() === routeLower) + ); + if (activeChild) { + const parentInList = convs.find( + (c) => String(c?.cascadeId || '').toLowerCase() === String(actConv?.cascadeId || '').toLowerCase() + ); + return { + rootConv: parentInList || actConv, + childAgent: activeChild, + isChildRoute: true, + }; + } + + const memberParent = convs.find( + (c) => + Array.isArray(c?.memberCascadeIds) && + c.memberCascadeIds.some((id) => String(id || '').toLowerCase() === routeLower) + ); + if (memberParent) { + return { rootConv: memberParent, childAgent: null, isChildRoute: true }; + } + return null; +} + /** * 解析当前选中的主/子代理作用域视图数据与独立上下文窗口检视目标。 * 同时在客户端按需组装主代理与全部汇总的 `recentSteps`,避免后端 JSON 载荷重复序列化 2-3 倍步骤列表。 diff --git a/sidecars/panel/src/styles/views-overview.css b/sidecars/panel/src/styles/views-overview.css index eb40399..623d1e1 100644 --- a/sidecars/panel/src/styles/views-overview.css +++ b/sidecars/panel/src/styles/views-overview.css @@ -265,10 +265,29 @@ flex-direction: column; gap: 8px; padding-top: 9px; + padding-right: 4px; margin-top: 3px; margin-left: 18px; border-top: 1px dashed var(--border-hairline); min-width: 0; + max-height: 196px; + overflow-y: auto; + overscroll-behavior: contain; + scrollbar-width: thin; + scrollbar-color: var(--border-subtle) transparent; +} + +.live-sub-list::-webkit-scrollbar { + width: 4px; +} + +.live-sub-list::-webkit-scrollbar-track { + background: transparent; +} + +.live-sub-list::-webkit-scrollbar-thumb { + background: var(--border-subtle); + border-radius: 999px; } .live-sub-row { @@ -286,6 +305,14 @@ opacity: 0.72; } +.live-sub-row.is-waiting-sub { + opacity: 0.86; +} + +.live-sub-row.is-killed-sub { + opacity: 0.56; +} + .live-sub-left { display: flex; align-items: center; diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index 3658b78..df9971c 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -1512,10 +1512,29 @@ html[data-standalone="true"] .app-shell { flex-direction: column; gap: 8px; padding-top: 9px; + padding-right: 4px; margin-top: 3px; margin-left: 18px; border-top: 1px dashed var(--border-hairline); min-width: 0; + max-height: 196px; + overflow-y: auto; + overscroll-behavior: contain; + scrollbar-width: thin; + scrollbar-color: var(--border-subtle) transparent; +} + +.live-sub-list::-webkit-scrollbar { + width: 4px; +} + +.live-sub-list::-webkit-scrollbar-track { + background: transparent; +} + +.live-sub-list::-webkit-scrollbar-thumb { + background: var(--border-subtle); + border-radius: 999px; } .live-sub-row { @@ -1533,6 +1552,14 @@ html[data-standalone="true"] .app-shell { opacity: 0.72; } +.live-sub-row.is-waiting-sub { + opacity: 0.86; +} + +.live-sub-row.is-killed-sub { + opacity: 0.56; +} + .live-sub-left { display: flex; align-items: center; diff --git a/sidecars/panel/test/backend-harness.mjs b/sidecars/panel/test/backend-harness.mjs index de33c29..57334b1 100644 --- a/sidecars/panel/test/backend-harness.mjs +++ b/sidecars/panel/test/backend-harness.mjs @@ -59,6 +59,7 @@ export function backendHarness({ cache={}, deepStats=null, transcripts={}, + swarmMembers={}, diskDirs={}, settings={}, trajectories={}, @@ -82,7 +83,7 @@ export function backendHarness({ const mainUrl = pluginRootPath ? `file://${pluginRootPath}/sidecars/panel/main.mjs` : 'file:///test/sidecars/panel/main.mjs'; const mainPath = pluginRootPath ? `${pluginRootPath}/sidecars/panel/main.mjs` : '/test/sidecars/panel/main.mjs'; const source = stripEsmSyntax(sourceText ?? loadCombinedBackendSource(), mainUrl); - const state={calls:[],errors:[],saves:[],settings,trajectories,summaries,transcripts,transcriptMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,gitConfigText,deepStats,deepStatsMtimeMs:1}; + const state={calls:[],errors:[],saves:[],settings,trajectories,summaries,transcripts,transcriptMtimeMs:1,swarmMembers,swarmMembersMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,gitConfigText,deepStats,deepStatsMtimeMs:1}; const ctx={ ...metricsImplementation, URL, AbortSignal, Buffer, TextDecoder, ...timerApi, isDeepStrictEqual, randomUUID, ...(clock ? { Date: class extends Date { @@ -110,6 +111,10 @@ export function backendHarness({ const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/logs\/transcript\.jsonl$/i); return Boolean(m && state.transcripts?.[m[1]]); } + if (norm.endsWith('/.system_generated/swarm/members.json')) { + const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/swarm\/members\.json$/i); + return Boolean(m && state.swarmMembers?.[m[1]]); + } if (norm.endsWith('/.git')) return Boolean(state.hasGitDir || state.gitConfigText); if (norm.endsWith('/.git/config')) return Boolean(state.gitConfigText); if (diskDirs && Object.prototype.hasOwnProperty.call(diskDirs, norm)) return true; @@ -131,6 +136,14 @@ export function backendHarness({ return {mtimeMs:state.transcriptMtimeMs,size:Buffer.byteLength(text,'utf8')}; } } + if (norm.endsWith('/.system_generated/swarm/members.json')) { + const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/swarm\/members\.json$/i); + const obj = m && state.swarmMembers?.[m[1]]; + if (obj) { + const text = typeof obj === 'string' ? obj : JSON.stringify(obj); + return {mtimeMs:state.swarmMembersMtimeMs,size:Buffer.byteLength(text,'utf8')}; + } + } if (norm.endsWith('/antigravity/brain/.deep_stats_cache.json') && state.deepStats) { return {mtimeMs:state.deepStatsMtimeMs,size:JSON.stringify(state.deepStats).length}; } @@ -143,6 +156,11 @@ export function backendHarness({ const lines = m && state.transcripts?.[m[1]]; return Array.isArray(lines) ? lines.map(x => JSON.stringify(x)).join('\n') : String(lines || ''); } + if (norm.endsWith('/.system_generated/swarm/members.json')) { + const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/swarm\/members\.json$/i); + const obj = m && state.swarmMembers?.[m[1]]; + return typeof obj === 'string' ? obj : JSON.stringify(obj || {}); + } if (norm.endsWith('settings.json')) return JSON.stringify(state.settings); if (norm.endsWith('/antigravity/brain/.deep_stats_cache.json')) return JSON.stringify(state.deepStats); if (norm.endsWith('pricing-catalog.json')) return JSON.stringify(state.localCatalog); diff --git a/sidecars/panel/test/swarm-mode.test.mjs b/sidecars/panel/test/swarm-mode.test.mjs new file mode 100644 index 0000000..85c519e --- /dev/null +++ b/sidecars/panel/test/swarm-mode.test.mjs @@ -0,0 +1,1275 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import { mkdtempSync, mkdirSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { + extractLiveActivity, + extractModelSteps, + isParkedOnSwarmWait, + parseSwarmWorkerRole, + summarizeToolCall, +} from '../trajectory-metrics.mjs'; +import { + readLocalSqliteTrajectory, + readLocalSummarySnapshot, +} from '../backend/cli-sqlite-reader.mjs'; +import { backendHarness } from './backend-harness.mjs'; +import { createMockDom } from './mock-dom.mjs'; +import { i18nStore, setI18nLanguage } from '../src/i18n/index.js'; +import { + formatAgentBadgeText, + formatAgentLabel, + formatConversationMeta, + formatLiveActivityLabel, + isEquivalentTelemetry, + resolveHostRouteMatch, + telemetryStore, +} from '../src/store/telemetryStore.js'; +import { uiStore } from '../src/store/uiStore.js'; +import { LiveActivityWidget } from '../src/components/widgets/LiveActivityWidget.js'; +import { TopSessionHeader } from '../src/components/layout/TopSessionHeader.js'; + +function encodeVarint(val) { + let v = BigInt(val); + if (v < 0n) v = BigInt.asUintN(64, v); + const out = []; + while (v >= 0x80n) { + out.push(Number((v & 0x7fn) | 0x80n)); + v >>= 7n; + } + out.push(Number(v)); + return Buffer.from(out); +} + +function encodeFieldVarint(fieldNo, val) { + return Buffer.concat([encodeVarint((fieldNo << 3) | 0), encodeVarint(val)]); +} + +function encodeFieldBytes(fieldNo, bufOrStr) { + const b = Buffer.isBuffer(bufOrStr) ? bufOrStr : Buffer.from(String(bufOrStr), 'utf8'); + return Buffer.concat([encodeVarint((fieldNo << 3) | 2), encodeVarint(b.length), b]); +} + +function encodeTimestamp(sec, nanos = 0) { + return Buffer.concat([encodeFieldVarint(1, sec), ...(nanos ? [encodeFieldVarint(2, nanos)] : [])]); +} + +function encodeStepMeta({ + createdSec, + finishedSec, + stepIndex, + originCascadeId = '', + modelEnumInt = 0, + inputTokens = 0, + cacheReadTokens = 0, + outputTokens = 0, + toolCallName = '', + toolCallArgsJson = '', +}) { + const parts = [encodeFieldBytes(1, encodeTimestamp(createdSec))]; + if (finishedSec) { + parts.push(encodeFieldBytes(7, encodeTimestamp(finishedSec))); + } + if (modelEnumInt || inputTokens || cacheReadTokens || outputTokens) { + const muParts = []; + if (modelEnumInt) muParts.push(encodeFieldVarint(1, modelEnumInt)); + if (inputTokens) muParts.push(encodeFieldVarint(2, inputTokens)); + if (outputTokens) muParts.push(encodeFieldVarint(3, outputTokens)); + if (cacheReadTokens) muParts.push(encodeFieldVarint(5, cacheReadTokens)); + muParts.push(encodeFieldVarint(6, 24)); + parts.push(encodeFieldBytes(9, Buffer.concat(muParts))); + } + const siParts = [encodeFieldVarint(2, stepIndex)]; + if (originCascadeId) { + siParts.push(encodeFieldBytes(4, originCascadeId)); + } + parts.push(encodeFieldBytes(20, Buffer.concat(siParts))); + if (toolCallName) { + const tcParts = [encodeFieldBytes(1, 'call-1'), encodeFieldBytes(2, toolCallName)]; + if (toolCallArgsJson) tcParts.push(encodeFieldBytes(3, toolCallArgsJson)); + parts.push(encodeFieldBytes(4, Buffer.concat(tcParts))); + } + return Buffer.concat(parts); +} + +function encodeSystemMessagePayload(text) { + return encodeFieldBytes(114, encodeFieldBytes(1, text)); +} + +function encodeSummaryBlob({ + title = '', + stepCount = 0, + lastModSec = 0, + statusInt = 1, + trajectoryType = 0, + killed = false, + forkParentId = '', + parentConversationId = '', + subagentSpec = null, + agentName = '', +}) { + const parts = []; + if (stepCount > 0) parts.push(encodeFieldVarint(2, stepCount)); + if (lastModSec > 0) parts.push(encodeFieldBytes(3, encodeTimestamp(lastModSec))); + if (statusInt > 0) parts.push(encodeFieldVarint(5, statusInt)); + if (title) { + parts.push(encodeFieldBytes(15, encodeFieldBytes(1, title))); + } + if (parentConversationId || subagentSpec || agentName) { + const tmParts = []; + if (agentName) tmParts.push(encodeFieldBytes(4, encodeFieldBytes(1, agentName))); + if (parentConversationId) tmParts.push(encodeFieldBytes(5, parentConversationId)); + if (subagentSpec) { + const specParts = []; + if (subagentSpec.typeName) specParts.push(encodeFieldBytes(1, subagentSpec.typeName)); + if (subagentSpec.role) specParts.push(encodeFieldBytes(2, subagentSpec.role)); + tmParts.push(encodeFieldBytes(8, Buffer.concat(specParts))); + } + parts.push(encodeFieldBytes(17, Buffer.concat(tmParts))); + } + if (trajectoryType > 0) parts.push(encodeFieldVarint(22, trajectoryType)); + if (killed) parts.push(encodeFieldVarint(23, 1)); + if (forkParentId) parts.push(encodeFieldBytes(24, forkParentId)); + return Buffer.concat(parts); +} + +test('Swarm tool call summaries, parked swarm_wait detection, and worker SYSTEM_MESSAGE wakeup Turn Rail', () => { + assert.deepEqual(parseSwarmWorkerRole({ role: 'Swarm Worker (bridge-actions)' }), { + isSwarmWorker: true, + memberName: 'bridge-actions', + isMonitor: false, + isNarrator: false, + isAuxiliary: false, + }); + assert.deepEqual( + parseSwarmWorkerRole({ role: 'Swarm Worker (@monitor)', agentScriptName: 'fallback' }), + { + isSwarmWorker: true, + memberName: 'monitor', + isMonitor: true, + isNarrator: false, + isAuxiliary: true, + } + ); + assert.deepEqual( + parseSwarmWorkerRole({ typeName: 'worker', agentScriptName: 'entry-runtime' }), + { + isSwarmWorker: true, + memberName: 'entry-runtime', + isMonitor: false, + isNarrator: false, + isAuxiliary: false, + } + ); + assert.equal(parseSwarmWorkerRole({ role: 'Codebase Researcher' }).isSwarmWorker, false); + + const addSingle = summarizeToolCall({ + name: 'swarm', + argumentsJson: JSON.stringify({ + action: 'add', + name: 'bridge-actions', + brief: 'Audit api-actions.mjs and window-bridge.mjs thoroughly.', + }), + }); + assert.equal(addSingle.actionKey, 'swarm_add'); + assert.equal(addSingle.detail, '@bridge-actions'); + + const addTasks = summarizeToolCall({ + name: 'swarm', + argumentsJson: JSON.stringify({ + action: 'add', + name: 'auditor', + tasks: ['m1', 'm2', 'm3', 'm4'], + brief: 'Audit assigned module.', + }), + }); + assert.equal(addTasks.actionKey, 'swarm_add'); + assert.equal(addTasks.detail, '@auditor-1..4'); + + const addCopies = summarizeToolCall({ + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'add', name: 'reviewer', n: 3 }), + }); + assert.equal(addCopies.actionKey, 'swarm_add'); + assert.equal(addCopies.detail, '@reviewer-1..3'); + + assert.equal( + summarizeToolCall({ + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'title', title: '20x Full Repo Audit' }), + }).actionKey, + 'swarm_title' + ); + assert.equal( + summarizeToolCall({ + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: 'verifier-fe' }), + }).detail, + '@verifier-fe' + ); + assert.equal( + summarizeToolCall({ + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'model', name: 'monitor', model: 'gemini-3.5-flash' }), + }).detail, + '@monitor -> gemini-3.5-flash' + ); + assert.equal( + summarizeToolCall({ name: 'swarm', argumentsJson: JSON.stringify({ action: 'status' }) }) + .actionKey, + 'swarm_status' + ); + + const postInfo = summarizeToolCall({ + name: 'post_message', + argumentsJson: JSON.stringify({ text: '@coordinator Completed audit with 3 findings.' }), + }); + assert.equal(postInfo.actionKey, 'post_message'); + assert.match(postInfo.detail, /@coordinator Completed audit/); + + const readSeqs = summarizeToolCall({ + name: 'read_board', + argumentsJson: JSON.stringify({ seqs: [9, 14] }), + }); + assert.equal(readSeqs.actionKey, 'read_board'); + assert.equal(readSeqs.detail, '#9, #14'); + + const waitInfo = summarizeToolCall({ + name: 'swarm_wait', + argumentsJson: JSON.stringify({ since: 42 }), + }); + assert.equal(waitInfo.actionKey, 'swarm_wait'); + assert.equal(waitInfo.isSwarmWait, true); + assert.equal(waitInfo.detail, '#42+'); + + const parkedTrajectorySteps = [ + { + type: 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE', + status: 'CORTEX_STEP_STATUS_DONE', + systemMessage: { message: '[swarm] new board message #9' }, + metadata: { createdAt: '2026-11-18T10:00:00Z' }, + }, + { + type: 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE', + status: 'CORTEX_STEP_STATUS_DONE', + systemMessage: { + message: + 'You have just started. Your assignment (recorded on the board as #9 for @bridge-actions):\n【只读代码审计任务】请检查 api-actions.mjs 与桥接协议的耦合度。', + }, + metadata: { createdAt: '2026-11-18T10:00:00Z' }, + }, + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + plannerResponse: { + response: 'Posted findings and sleeping.', + toolCalls: [{ name: 'swarm_wait', argumentsJson: '{"since":25}' }], + }, + metadata: { + createdAt: '2026-11-18T10:00:05Z', + completedAt: '2026-11-18T10:00:08Z', + sourceTrajectoryStepInfo: { stepIndex: 2 }, + modelUsage: { + model: 'MODEL_PLACEHOLDER_M429', + inputTokens: '12000', + cacheReadTokens: '0', + outputTokens: '600', + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: '2026-11-18T10:00:08Z', + toolCall: { name: 'swarm_wait', argumentsJson: '{"since":25}' }, + }, + }, + ]; + assert.equal(isParkedOnSwarmWait(parkedTrajectorySteps), true); + const liveParked = extractLiveActivity( + parkedTrajectorySteps, + true, + Date.parse('2026-11-18T10:00:08Z') + ); + assert.equal(liveParked?.phase, 'waiting'); + assert.equal(liveParked?.actionKey, 'swarm_wait'); + + // Once woken up with a new SYSTEM_MESSAGE + active step, worker is no longer parked + const resumedSteps = [ + ...parkedTrajectorySteps, + { + type: 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE', + status: 'CORTEX_STEP_STATUS_DONE', + systemMessage: { + message: '[board] the latest message is #30 (you have read up to #25).', + }, + metadata: { createdAt: '2026-11-18T10:02:00Z' }, + }, + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + plannerResponse: { response: 'Re-checked line 88.' }, + metadata: { + createdAt: '2026-11-18T10:02:01Z', + completedAt: '2026-11-18T10:02:04Z', + sourceTrajectoryStepInfo: { stepIndex: 5 }, + modelUsage: { + model: 'MODEL_PLACEHOLDER_M429', + inputTokens: '2000', + cacheReadTokens: '12000', + outputTokens: '400', + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE', + status: 'CORTEX_STEP_STATUS_DONE', + systemMessage: { message: 'Compacted context' }, + metadata: { createdAt: '2026-11-18T10:02:10Z' }, + }, + { + type: 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE', + status: 'CORTEX_STEP_STATUS_DONE', + systemMessage: { + message: '[monitor] tick: check swarm board (iteration 1)', + }, + metadata: { createdAt: '2026-11-18T10:05:00Z' }, + }, + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_RUNNING', + metadata: { + createdAt: '2026-11-18T10:05:01Z', + sourceTrajectoryStepInfo: { stepIndex: 8 }, + modelUsage: { + model: 'MODEL_PLACEHOLDER_M429', + inputTokens: '1500', + cacheReadTokens: '13000', + outputTokens: '200', + }, + }, + }, + ]; + assert.equal(isParkedOnSwarmWait(resumedSteps), false); + + const workerModelSteps = extractModelSteps(resumedSteps, []); + assert.equal(workerModelSteps.length, 3); + assert.equal(workerModelSteps[0].turnIndex, 1); + assert.match(workerModelSteps[0].turnPromptClean, /^#9 @bridge-actions · 【只读代码审计任务】/); + assert.equal(workerModelSteps[1].turnIndex, 2); + assert.equal(workerModelSteps[1].turnPromptClean, '[board] #25 -> #30'); + assert.equal(workerModelSteps[2].turnIndex, 3); + assert.equal(workerModelSteps[2].turnPromptClean, '[monitor] tick #1'); + + // Coordinator trajectory with human USER_INPUT must NOT split turns on SYSTEM_MESSAGE + const coordinatorSteps = [ + { + type: 'CORTEX_STEP_TYPE_USER_INPUT', + status: 'CORTEX_STEP_STATUS_DONE', + userInput: { userResponse: 'Run a 20-agent swarm audit' }, + metadata: { createdAt: '2026-11-18T09:59:00Z' }, + }, + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: '2026-11-18T09:59:05Z', + completedAt: '2026-11-18T09:59:10Z', + sourceTrajectoryStepInfo: { stepIndex: 1 }, + modelUsage: { model: 'MODEL_PLACEHOLDER_M429', inputTokens: '5000', outputTokens: '300' }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE', + status: 'CORTEX_STEP_STATUS_DONE', + systemMessage: { message: '[42] verifier-fe: @coordinator All checks passed!' }, + metadata: { createdAt: '2026-11-18T10:10:00Z' }, + }, + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: '2026-11-18T10:10:02Z', + completedAt: '2026-11-18T10:10:08Z', + sourceTrajectoryStepInfo: { stepIndex: 3 }, + modelUsage: { model: 'MODEL_PLACEHOLDER_M429', inputTokens: '6000', outputTokens: '500' }, + }, + }, + ]; + const coordModelSteps = extractModelSteps(coordinatorSteps, []); + assert.equal(coordModelSteps.length, 2); + assert.equal(coordModelSteps[0].turnIndex, 1); + assert.equal(coordModelSteps[0].isTurnStart, true); + assert.equal(coordModelSteps[0].turnPromptClean, 'Run a 20-agent swarm audit'); + assert.equal(coordModelSteps[1].turnIndex, 1); + assert.equal(coordModelSteps[1].isTurnStart, false); +}); + +test('Backend Swarm integration: members.json discovery, chronological worker ordering, swarm_wait downgrade, killed state, swarmTitle fallback, and hostRoute projection', async () => { + const promoMs = Date.parse('2026-11-18T12:00:00Z'); + const rootCid = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'; + const untitledRootCid = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'; + const wEntryCid = '11111111-1111-4111-8111-111111111111'; + const wKilledCid = '22222222-2222-4222-8222-222222222222'; + const wMonitorCid = '33333333-3333-4333-8333-333333333333'; + + const makeModelStep = (idx, secOffset, inputTokens, outputTokens) => ({ + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: new Date(promoMs - 60_000 + secOffset * 1000).toISOString(), + completedAt: new Date(promoMs - 60_000 + (secOffset + 2) * 1000).toISOString(), + sourceTrajectoryStepInfo: { stepIndex: idx }, + modelUsage: { + model: 'MODEL_PLACEHOLDER_M429', + apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + inputTokens: String(inputTokens), + cacheReadTokens: '0', + outputTokens: String(outputTokens), + }, + }, + }); + + const swarmWaitStep = (secOffset) => ({ + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: new Date(promoMs - 60_000 + secOffset * 1000).toISOString(), + toolCall: { name: 'swarm_wait', argumentsJson: '{"since":10}' }, + }, + }); + + const trajectories = { + [rootCid]: { + trajectory: { + steps: [ + { + type: 'CORTEX_STEP_TYPE_USER_INPUT', + status: 'CORTEX_STEP_STATUS_DONE', + userInput: { userResponse: 'Audit repository coupling with a swarm' }, + metadata: { createdAt: new Date(promoMs - 60_000).toISOString() }, + }, + makeModelStep(1, 2, 10_000, 1_000), + swarmWaitStep(5), + ], + }, + }, + [wEntryCid]: { + trajectory: { + steps: [ + { + type: 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE', + status: 'CORTEX_STEP_STATUS_DONE', + systemMessage: { + message: + 'You have just started. Your assignment (recorded on the board as #1 for @entry-runtime):\nAudit main.mjs entrypoints', + }, + metadata: { createdAt: new Date(promoMs - 50_000).toISOString() }, + }, + makeModelStep(1, 12, 20_000, 2_000), + swarmWaitStep(15), + ], + }, + }, + [wKilledCid]: { + trajectory: { + steps: [ + { + type: 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE', + status: 'CORTEX_STEP_STATUS_DONE', + systemMessage: { message: '[2] coordinator: @dead-worker Quick check' }, + metadata: { createdAt: new Date(promoMs - 40_000).toISOString() }, + }, + makeModelStep(1, 22, 5_000, 500), + ], + }, + }, + [wMonitorCid]: { + trajectory: { + steps: [ + { + type: 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE', + status: 'CORTEX_STEP_STATUS_DONE', + systemMessage: { + message: 'Scheduled notification (s1): [monitor] tick #1: Check board progress.', + }, + metadata: { createdAt: new Date(promoMs - 30_000).toISOString() }, + }, + makeModelStep(1, 32, 8_000, 400), + swarmWaitStep(35), + ], + }, + }, + [untitledRootCid]: { + trajectory: { + steps: [makeModelStep(0, 1, 2_000, 200)], + }, + }, + }; + + // Deliberately serialize members in alphabetical Go-map order AND mark parked workers as RUNNING in summaries + const swarmMembers = { + [rootCid]: { + title: '20x Carbon Architecture Audit', + members: { + 'dead-worker': { + conversation_id: wKilledCid, + role: 'Swarm Worker (dead-worker)', + killed: true, + }, + 'entry-runtime': { + conversation_id: wEntryCid, + role: 'Swarm Worker (entry-runtime)', + killed: false, + }, + monitor: { + conversation_id: wMonitorCid, + role: 'Swarm Worker (monitor)', + killed: false, + }, + }, + }, + [untitledRootCid]: { + title: 'Fallback Swarm Title Only', + members: {}, + }, + }; + + const summaries = { + [rootCid]: { + annotations: { title: 'Greeting and Hello' }, + stepCount: 3, + createdTime: new Date(promoMs - 60_000).toISOString(), + lastModifiedTime: new Date(promoMs - 20_000).toISOString(), + status: 'CASCADE_RUN_STATUS_IDLE', + }, + [wEntryCid]: { + stepCount: 3, + createdTime: new Date(promoMs - 50_000).toISOString(), + lastModifiedTime: new Date(promoMs - 45_000).toISOString(), + status: 'CASCADE_RUN_STATUS_RUNNING', // Parked on swarm_wait -> must downgrade! + trajectoryMetadata: { + parentConversationId: rootCid, + subagentSpec: { typeName: 'worker', role: 'Swarm Worker (entry-runtime)' }, + agentScript: { name: 'entry-runtime' }, + }, + }, + [wKilledCid]: { + stepCount: 2, + createdTime: new Date(promoMs - 40_000).toISOString(), + lastModifiedTime: new Date(promoMs - 38_000).toISOString(), + status: 'CASCADE_RUN_STATUS_IDLE', + killed: true, + trajectoryMetadata: { + parentConversationId: rootCid, + subagentSpec: { typeName: 'worker', role: 'Swarm Worker (dead-worker)' }, + }, + }, + [wMonitorCid]: { + stepCount: 3, + createdTime: new Date(promoMs - 30_000).toISOString(), + lastModifiedTime: new Date(promoMs - 25_000).toISOString(), + status: 'CASCADE_RUN_STATUS_RUNNING', // Daemon monitor parked on swarm_wait -> must downgrade! + trajectoryMetadata: { + parentConversationId: rootCid, + subagentSpec: { typeName: 'worker', role: 'Swarm Worker (monitor)' }, + }, + }, + [untitledRootCid]: { + annotations: { title: '' }, + stepCount: 1, + createdTime: new Date(promoMs - 120_000).toISOString(), + lastModifiedTime: new Date(promoMs - 110_000).toISOString(), + status: 'CASCADE_RUN_STATUS_IDLE', + }, + }; + + const h = backendHarness({ + clock: () => promoMs, + userStatus: { email: 'swarm@example.com' }, + trajectories, + summaries, + swarmMembers, + }); + + // 1. All workers parked or killed -> zero running sessions, full token & cost preservation + const idlePayload = await h.buildTelemetryPayloadInternal({ + selectedConversationId: rootCid, + stepDetails: 'display', + }); + const actIdle = idlePayload.activeConversation; + assert.equal(actIdle.cascadeId, rootCid); + assert.equal(actIdle.title, 'Greeting and Hello', 'Existing root title must never be overwritten'); + assert.equal(actIdle.swarmTitle, '20x Carbon Architecture Audit'); + assert.equal(actIdle.subagentCount, 3); + assert.equal(actIdle.swarmCount, 3); + assert.equal(actIdle.isRunning, false); + assert.equal(actIdle.aggregated.isRunning, false, 'Parked swarm_wait workers must not keep session running'); + assert.equal(idlePayload.runningConversations.length, 0); + + // Total tokens across root (11k) + entry (22k) + killed (5.5k) + monitor (8.4k) = 46,900 + assert.equal(actIdle.aggregated.totalTokens, 46_900); + assert.ok(actIdle.aggregated.sessionCostUsd > 0); + + // Chronological order by createdTimeMs: entry-runtime (#1), dead-worker (#2), monitor (#3) + const childAgents = [...actIdle.agents].filter((a) => !a.isMain); + assert.deepEqual( + childAgents.map((a) => ({ + id: a.agentId, + kind: a.agentKind, + ord: a.agentOrdinal, + badge: a.badgeText, + role: a.customRole, + state: a.swarmState, + aux: Boolean(a.isSwarmAuxiliary), + running: a.isRunning, + })), + [ + { + id: wEntryCid, + kind: 'swarm_worker', + ord: 1, + badge: '蜂1', + role: '@entry-runtime', + state: 'waiting', + aux: false, + running: false, + }, + { + id: wKilledCid, + kind: 'swarm_worker', + ord: 2, + badge: '蜂2', + role: '@dead-worker', + state: 'killed', + aux: false, + running: false, + }, + { + id: wMonitorCid, + kind: 'swarm_worker', + ord: 3, + badge: '蜂3', + role: '@monitor', + state: 'waiting', + aux: true, + running: false, + }, + ] + ); + + // Untitled root falls back to swarm.title + const untitledEntry = idlePayload.conversations.find((c) => c.cascadeId === untitledRootCid); + assert.equal(untitledEntry?.title, 'Fallback Swarm Title Only'); + + // 2. Host route pointing to a child worker (`/c/`) resolves rootCid and projects wakeup Turn Rail fields + const actionHttp = await h.executeTelemetryAction({ + conversationId: wEntryCid, + stepDetails: 'display', + }); + assert.equal(actionHttp.status, 200); + const actionRes = JSON.parse(actionHttp.body); + const routedAct = actionRes.activeConversation; + assert.equal(routedAct.cascadeId, rootCid); + const entryAgentProj = routedAct.agents.find((a) => a.agentId === wEntryCid); + const projectedEntryStep = entryAgentProj?.recentSteps?.[0]; + assert.ok(projectedEntryStep); + assert.equal(projectedEntryStep.agentKind, 'swarm_worker'); + assert.equal(projectedEntryStep.agentOrdinal, 1); + assert.equal(projectedEntryStep.agentCustomRole, '@entry-runtime'); + assert.equal(projectedEntryStep.turnIndex, 1); + assert.match(projectedEntryStep.turnPromptClean, /^#1 @entry-runtime · Audit main\.mjs entrypoints/); + assert.equal(projectedEntryStep.rootTurnPromptClean, 'Audit repository coupling with a swarm'); + + // 3. When one worker actively executes a tool (not swarm_wait), session enters waiting_swarm with runningSwarmCount=1 + trajectories[wEntryCid] = { + trajectory: { + steps: [ + ...trajectories[wEntryCid].trajectory.steps, + { + type: 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE', + status: 'CORTEX_STEP_STATUS_DONE', + systemMessage: { message: '[12] coordinator: @entry-runtime Inspect bridge-daemon.mjs' }, + metadata: { createdAt: new Date(promoMs - 5_000).toISOString() }, + }, + { + type: 'CORTEX_STEP_TYPE_VIEW_FILE', + status: 'CORTEX_STEP_STATUS_RUNNING', + viewFile: { absolutePathUri: 'file:///repo/sidecars/panel/bridge-daemon.mjs' }, + metadata: { createdAt: new Date(promoMs - 2_000).toISOString() }, + }, + ], + }, + }; + summaries[wEntryCid] = { + ...summaries[wEntryCid], + stepCount: 5, + lastModifiedTime: new Date(promoMs - 2_000).toISOString(), + status: 'CASCADE_RUN_STATUS_RUNNING', + }; + + const activePayload = await h.buildTelemetryPayloadInternal({ + selectedConversationId: rootCid, + forceRefresh: true, + stepDetails: 'summary', + }); + assert.equal(activePayload.activeConversation.aggregated.isRunning, true); + assert.equal(activePayload.runningConversations.length, 1); + const runCard = activePayload.runningConversations[0]; + assert.equal(runCard.swarmCount, 3); + assert.equal(runCard.runningSubagentCount, 1); + assert.equal(runCard.runningSwarmCount, 1); + assert.equal(runCard.mainActivity?.actionKey, 'waiting_swarm'); + const subEntry = runCard.subagents.find((s) => s.cascadeId === wEntryCid); + const subKilled = runCard.subagents.find((s) => s.cascadeId === wKilledCid); + const subMonitor = runCard.subagents.find((s) => s.cascadeId === wMonitorCid); + assert.equal(subEntry?.isRunning, true); + assert.equal(subEntry?.swarmState, 'working'); + assert.equal(subKilled?.swarmState, 'killed'); + assert.equal(subKilled?.liveActivity?.actionKey, 'swarm_killed'); + assert.equal(subMonitor?.isRunning, false); + assert.equal(subMonitor?.swarmState, 'waiting'); + assert.equal(subMonitor?.liveActivity?.actionKey, 'swarm_waiting'); +}); + +test('SQLite wire reader: forked Swarm Worker excluded from sideQuestionParents and step_type=101 SYSTEM_MESSAGE decoded selectively on child DBs', (t) => { + const sqliteMod = + typeof process.getBuiltinModule === 'function' ? process.getBuiltinModule('node:sqlite') : null; + if (!sqliteMod?.DatabaseSync) { + t.skip('node:sqlite DatabaseSync unavailable'); + return; + } + const { DatabaseSync } = sqliteMod; + const tempRoot = mkdtempSync(join(tmpdir(), 'agy-swarm-sqlite-')); + t.after(() => { + try { + rmSync(tempRoot, { recursive: true, force: true }); + } catch { + // ignore temp cleanup failure on Windows file lock + } + }); + + const convDir = join(tempRoot, 'conversations'); + mkdirSync(convDir, { recursive: true }); + + const rootCid = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc'; + const forkedWorkerCid = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd'; + const realSideCid = 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee'; + const baseSec = Math.floor(Date.parse('2026-11-18T08:00:00Z') / 1000); + + const sumDb = new DatabaseSync(join(tempRoot, 'conversation_summaries.db')); + sumDb.exec(` + CREATE TABLE conversation_summaries ( + conversation_id TEXT PRIMARY KEY, + title TEXT, + preview TEXT, + status TEXT, + source TEXT, + parent_conversation_id TEXT, + nesting_depth INTEGER, + agent_name TEXT, + not_fully_idle INTEGER, + killed INTEGER, + step_count INTEGER, + last_modified_time TEXT, + app_data_dir TEXT, + raw_summary BLOB + ); + CREATE TABLE conversation_parents ( + conversation_id TEXT, + parent_id TEXT + ); + `); + + const insSum = sumDb.prepare(` + INSERT INTO conversation_summaries ( + conversation_id, title, status, parent_conversation_id, agent_name, + not_fully_idle, killed, step_count, last_modified_time, app_data_dir, raw_summary + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `); + insSum.run( + rootCid, + 'Root Swarm Session', + 'CASCADE_RUN_STATUS_IDLE', + '', + '', + 0, + 0, + 4, + new Date(baseSec * 1000).toISOString(), + 'antigravity', + encodeSummaryBlob({ title: 'Root Swarm Session', stepCount: 4, lastModSec: baseSec, statusInt: 1 }) + ); + insSum.run( + forkedWorkerCid, + '', + 'CASCADE_RUN_STATUS_IDLE', + rootCid, + 'forked-auditor', + 0, + 0, + 3, + new Date((baseSec + 10) * 1000).toISOString(), + 'antigravity', + encodeSummaryBlob({ + stepCount: 3, + lastModSec: baseSec + 10, + statusInt: 1, + trajectoryType: 4, // Forked worker trajectory type != 22 + forkParentId: rootCid, + parentConversationId: rootCid, + agentName: 'forked-auditor', + subagentSpec: { typeName: 'worker', role: 'Swarm Worker (forked-auditor)' }, + }) + ); + insSum.run( + realSideCid, + 'Side Question About Coupling', + 'CASCADE_RUN_STATUS_IDLE', + rootCid, + '', + 0, + 0, + 2, + new Date((baseSec + 20) * 1000).toISOString(), + 'antigravity', + encodeSummaryBlob({ + title: 'Side Question About Coupling', + stepCount: 2, + lastModSec: baseSec + 20, + statusInt: 1, + trajectoryType: 22, // Real Side Question + forkParentId: rootCid, + }) + ); + + const insParent = sumDb.prepare( + 'INSERT INTO conversation_parents (conversation_id, parent_id) VALUES (?, ?)' + ); + insParent.run(forkedWorkerCid, rootCid); + insParent.run(realSideCid, rootCid); + sumDb.close(); + + const snap = readLocalSummarySnapshot([tempRoot], { forceRefresh: true }); + assert.equal(snap.available, true); + assert.ok(snap.sideQuestionParents[realSideCid], 'Real trajectoryType=22 side question must be retained'); + assert.equal( + snap.sideQuestionParents[forkedWorkerCid], + undefined, + 'Forked Swarm Worker in conversation_parents must NOT be misclassified into sideQuestionParents' + ); + + // Build child worker DB vs root DB with identical step_type=101 SYSTEM_MESSAGE payload + function createTrajectoryDb(filePath, { cascadeId, parentConversationId = '', subagentRole = '' }) { + const db = new DatabaseSync(filePath); + db.exec(` + CREATE TABLE trajectory_meta (trajectory_id TEXT, cascade_id TEXT, trajectory_type INTEGER, source INTEGER); + CREATE TABLE trajectory_metadata_blob (id TEXT PRIMARY KEY, data BLOB); + CREATE TABLE gen_metadata (idx INTEGER PRIMARY KEY, data BLOB); + CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, metadata BLOB, step_payload BLOB); + `); + db.prepare('INSERT INTO trajectory_meta VALUES (?, ?, ?, ?)').run(cascadeId, cascadeId, 0, 1); + if (parentConversationId || subagentRole) { + const tmParts = []; + if (parentConversationId) tmParts.push(encodeFieldBytes(5, parentConversationId)); + if (subagentRole) { + tmParts.push( + encodeFieldBytes( + 8, + Buffer.concat([encodeFieldBytes(1, 'worker'), encodeFieldBytes(2, subagentRole)]) + ) + ); + } + db.prepare('INSERT INTO trajectory_metadata_blob VALUES (?, ?)').run( + 'main', + Buffer.concat(tmParts) + ); + } + const insStep = db.prepare('INSERT INTO steps VALUES (?, ?, ?, ?, ?)'); + insStep.run( + 0, + 101, // CORTEX_STEP_TYPE_SYSTEM_MESSAGE + 2, // DONE + encodeStepMeta({ createdSec: baseSec + 1, stepIndex: 0, originCascadeId: cascadeId }), + encodeSystemMessagePayload('[9] coordinator: @forked-auditor Inspect sqlite-client.mjs') + ); + insStep.run( + 1, + 15, // CORTEX_STEP_TYPE_PLANNER_RESPONSE + 2, + encodeStepMeta({ + createdSec: baseSec + 3, + finishedSec: baseSec + 5, + stepIndex: 1, + originCascadeId: cascadeId, + modelEnumInt: 429, + inputTokens: 4000, + outputTokens: 200, + }), + Buffer.alloc(0) + ); + insStep.run( + 2, + 132, // CORTEX_STEP_TYPE_GENERIC (swarm_wait) + 2, + encodeStepMeta({ + createdSec: baseSec + 5, + stepIndex: 2, + originCascadeId: cascadeId, + toolCallName: 'swarm_wait', + toolCallArgsJson: '{"since":9}', + }), + Buffer.alloc(0) + ); + db.close(); + } + + const workerDbPath = join(convDir, `${forkedWorkerCid}.db`); + const rootDbPath = join(convDir, `${rootCid}.db`); + createTrajectoryDb(workerDbPath, { + cascadeId: forkedWorkerCid, + parentConversationId: rootCid, + subagentRole: 'Swarm Worker (forked-auditor)', + }); + createTrajectoryDb(rootDbPath, { cascadeId: rootCid }); + + const workerRead = readLocalSqliteTrajectory(workerDbPath, { + cascadeId: forkedWorkerCid, + isRunning: false, + }); + assert.ok(workerRead); + assert.equal(workerRead.steps[0].type, 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE'); + assert.equal( + workerRead.steps[0].systemMessage?.message, + '[9] coordinator: @forked-auditor Inspect sqlite-client.mjs' + ); + assert.equal(isParkedOnSwarmWait(workerRead.steps), true); + + const rootRead = readLocalSqliteTrajectory(rootDbPath, { + cascadeId: rootCid, + isRunning: false, + }); + assert.ok(rootRead); + assert.equal(rootRead.steps[0].type, 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE'); + assert.equal( + rootRead.steps[0].systemMessage, + undefined, + 'Main root conversations must skip decoding step_type=101 payloads for zero extra I/O' + ); +}); + +test('Frontend Swarm formatters, bilingual i18n, LiveActivityWidget priority sorting + scroll cap, and TopSessionHeader child-route auto-focus', async (t) => { + const prevLocale = i18nStore.getState().locale; + const prevDoc = globalThis.document; + const prevWin = globalThis.window; + const prevTelState = { ...telemetryStore.getState() }; + const prevUiState = { ...uiStore.getState() }; + + const { document } = createMockDom(); + globalThis.document = document; + globalThis.window = { + location: { pathname: '/' }, + addEventListener() {}, + removeEventListener() {}, + }; + + const cleanupFns = []; + t.after(() => { + for (const fn of cleanupFns.reverse()) { + try { + fn(); + } catch { + // ignore widget teardown errors + } + } + setI18nLanguage(prevLocale); + telemetryStore.setState(prevTelState); + uiStore.setState(prevUiState); + globalThis.document = prevDoc; + globalThis.window = prevWin; + }); + + // 1. Bilingual badges, labels, auxiliary role hints, and conversation meta + setI18nLanguage('zh-CN'); + assert.equal( + formatAgentBadgeText({ agentKind: 'swarm_worker', agentOrdinal: 9 }), + '蜂9' + ); + assert.equal( + formatAgentLabel({ + agentKind: 'swarm_worker', + agentOrdinal: 9, + customRole: 'Swarm Worker (bridge-actions)', + }), + '蜂群 #9 · @bridge-actions' + ); + assert.equal( + formatAgentLabel({ agentKind: 'swarm_worker', agentOrdinal: 20, customRole: '@monitor' }), + '蜂群 #20 · @monitor (巡检)' + ); + assert.equal( + formatAgentLabel({ agentKind: 'swarm_worker', agentOrdinal: 21, customRole: '@narrator' }), + '蜂群 #21 · @narrator (旁白)' + ); + assert.equal( + formatConversationMeta({ stepCount: 10, subagentCount: 20, swarmCount: 20, totalStepCount: 250 }), + '主10 · 20蜂 (共250步)' + ); + assert.equal( + formatConversationMeta({ stepCount: 10, subagentCount: 7, swarmCount: 5, totalStepCount: 80 }), + '主10 · 5蜂 · 2子 (共80步)' + ); + assert.equal(formatLiveActivityLabel({ actionKey: 'waiting_swarm' }), '等待工蜂'); + assert.equal(formatLiveActivityLabel({ actionKey: 'swarm_waiting' }), '待命中'); + assert.equal(formatLiveActivityLabel({ actionKey: 'swarm_killed' }), '已终止'); + + setI18nLanguage('en-US'); + assert.equal( + formatAgentBadgeText({ agentKind: 'swarm_worker', agentOrdinal: 9 }), + 'W9' + ); + assert.equal( + formatAgentLabel({ + agentKind: 'swarm_worker', + agentOrdinal: 9, + customRole: 'Swarm Worker (bridge-actions)', + }), + 'Swarm #9 · @bridge-actions' + ); + assert.equal( + formatAgentLabel({ agentKind: 'swarm_worker', agentOrdinal: 20, customRole: '@monitor' }), + 'Swarm #20 · @monitor (Monitor)' + ); + assert.equal( + formatConversationMeta({ stepCount: 10, subagentCount: 20, swarmCount: 20, totalStepCount: 250 }), + 'Main 10 · 20 swarm (250 steps)' + ); + assert.equal( + formatConversationMeta({ stepCount: 10, subagentCount: 7, swarmCount: 5, totalStepCount: 80 }), + 'Main 10 · 5 swarm · 2 sub (80 steps)' + ); + + setI18nLanguage('zh-CN'); + + // 2. Verify CSS bounded scroll rule on `.live-sub-list` + const builtStyles = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8'); + assert.match(builtStyles, /\.live-sub-list\s*\{[^}]*max-height:\s*196px/); + assert.match(builtStyles, /\.live-sub-list\s*\{[^}]*overflow-y:\s*auto/); + + // 3. LiveActivityWidget: running -> waiting -> killed priority sorting & child route isHere badge + const rootId = 'root-swarm-1111'; + const w1 = 'worker-killed-1'; + const w2 = 'worker-waiting-2'; + const w3 = 'worker-running-3'; + const w4 = 'worker-waiting-4'; + + const liveWidget = LiveActivityWidget({ + interactive: true, + defaultExpandRunningSubs: true, + showSessionExtras: true, + }); + cleanupFns.push(() => liveWidget.destroy()); + document.body.appendChild(liveWidget.el); + + liveWidget.refs.update({ + hostRouteConversationId: w2, + items: [ + { + cascadeId: rootId, + title: 'Greeting and Hello', + swarmTitle: '20x Carbon Audit', + isMainRunning: false, + isRunning: true, + subagentCount: 4, + swarmCount: 4, + runningSubagentCount: 1, + runningSwarmCount: 1, + mainActivity: { + phase: 'waiting', + actionKey: 'waiting_swarm', + detail: '蜂3 (@verifier-be)', + startedAtMs: Date.now() - 3_000, + signature: 'wait:swarm:1', + }, + subagents: [ + { + cascadeId: w1, + index: 1, + agentKind: 'swarm_worker', + agentOrdinal: 1, + customRole: '@dead-node', + swarmState: 'killed', + isRunning: false, + stepCount: 2, + liveActivity: { phase: 'done', actionKey: 'swarm_killed', signature: 'k1' }, + }, + { + cascadeId: w2, + index: 2, + agentKind: 'swarm_worker', + agentOrdinal: 2, + customRole: '@bridge-actions', + swarmState: 'waiting', + isRunning: false, + stepCount: 6, + liveActivity: { phase: 'waiting', actionKey: 'swarm_waiting', signature: 'w2' }, + }, + { + cascadeId: w3, + index: 3, + agentKind: 'swarm_worker', + agentOrdinal: 3, + customRole: '@verifier-be', + swarmState: 'working', + isRunning: true, + stepCount: 9, + liveActivity: { + phase: 'tool', + actionKey: 'read_file', + detail: 'api-actions.mjs', + startedAtMs: Date.now() - 2_000, + signature: 'r3', + }, + }, + { + cascadeId: w4, + index: 4, + agentKind: 'swarm_worker', + agentOrdinal: 4, + customRole: '@monitor', + swarmState: 'waiting', + isRunning: false, + stepCount: 8, + liveActivity: { phase: 'waiting', actionKey: 'swarm_waiting', signature: 'w4' }, + }, + ], + }, + ], + }); + liveWidget.refs.pauseTicker(); + + const toggleBtn = liveWidget.el.querySelector('.live-sub-toggle'); + assert.equal(toggleBtn?.textContent, '蜂群 1/4 ▾'); + const hereTag = liveWidget.el.querySelector('.wm-session-tag.is-here'); + assert.ok(hereTag && !hereTag.hasAttribute('hidden'), 'Child worker host route must light up is-here tag'); + + const renderedRows = liveWidget.el.querySelectorAll('.live-sub-row'); + assert.equal(renderedRows.length, 4); + assert.deepEqual( + renderedRows.map((r) => r.querySelector('.agent-badge')?.textContent), + ['蜂3', '蜂2', '蜂4', '蜂1'], + 'Rows must sort as running -> waiting -> killed while keeping original ordinals' + ); + assert.equal(renderedRows[1].querySelector('.live-sub-summary')?.textContent, '待命中 (6 步)'); + assert.equal(renderedRows[3].querySelector('.live-sub-summary')?.textContent, '已终止 (2 步)'); + + // 4. TopSessionHeader: child route resolution, header title, and one-shot auto-focus + const mockTelemetry = { + settings: { language: 'zh-CN' }, + activeConversation: { + cascadeId: rootId, + title: 'Greeting and Hello', + swarmTitle: '20x Carbon Audit', + stepCount: 10, + subagentCount: 4, + swarmCount: 4, + totalStepsAllAgents: 32, + hasSubagents: true, + isRunning: false, + aggregated: { isRunning: false }, + agents: [ + { agentId: rootId, isMain: true, agentKind: 'main', stepCount: 10 }, + { + agentId: w2, + cascadeId: w2, + isMain: false, + index: 2, + agentKind: 'swarm_worker', + agentOrdinal: 2, + customRole: '@bridge-actions', + swarmState: 'waiting', + stepCount: 6, + }, + ], + }, + conversations: [ + { + cascadeId: rootId, + title: 'Greeting and Hello', + swarmTitle: '20x Carbon Audit', + stepCount: 10, + subagentCount: 4, + swarmCount: 4, + totalStepCount: 32, + memberCascadeIds: [w1, w2, w3, w4], + }, + ], + }; + + assert.equal( + isEquivalentTelemetry(mockTelemetry, { + ...mockTelemetry, + activeConversation: { + ...mockTelemetry.activeConversation, + agents: [ + mockTelemetry.activeConversation.agents[0], + { ...mockTelemetry.activeConversation.agents[1], swarmState: 'killed' }, + ], + }, + }), + false, + 'isEquivalentTelemetry must detect swarmState transitions' + ); + + const routeInfo = resolveHostRouteMatch(mockTelemetry, w2); + assert.equal(routeInfo?.isChildRoute, true); + assert.equal(routeInfo?.rootConv?.cascadeId, rootId); + assert.equal(routeInfo?.childAgent?.agentId, w2); + + uiStore.setState( + { monitorVisible: true, selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }, + { sync: true } + ); + telemetryStore.setState( + { + selectedConversationId: '', + hostRouteConversationId: w2, + syncState: 'idle', + telemetry: mockTelemetry, + }, + { sync: true } + ); + + const topHeader = TopSessionHeader({}); + cleanupFns.push(() => topHeader.destroy()); + document.body.appendChild(topHeader.el); + + // Initial mount on `/c/` auto-focuses scope & inspector to `w2` and labels header option cleanly + await Promise.resolve(); + assert.equal(uiStore.getState().selectedAgentScope, w2); + assert.equal(uiStore.getState().ctxInspectorAgentId, w2); + const triggerText = topHeader.el.querySelector('.select-trigger')?.textContent || ''; + assert.match(triggerText, /当前窗口 \(Greeting and Hello · 蜂2\)/); + + // User manually switches scope back to `all` while still on `/c/` -> next poll must NOT override! + uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }, { sync: true }); + telemetryStore.setState({ + telemetry: { + ...mockTelemetry, + activeConversation: { ...mockTelemetry.activeConversation, totalStepsAllAgents: 33 }, + }, + }); + await Promise.resolve(); + assert.equal(uiStore.getState().selectedAgentScope, 'all'); + assert.equal(uiStore.getState().ctxInspectorAgentId, 'auto'); + + // Navigating host window back to root `/c/` resets auto-focus state cleanly + uiStore.setState({ selectedAgentScope: w2, ctxInspectorAgentId: w2 }, { sync: true }); + telemetryStore.setState({ hostRouteConversationId: rootId }); + await Promise.resolve(); + assert.equal(uiStore.getState().selectedAgentScope, 'all'); + assert.equal(uiStore.getState().ctxInspectorAgentId, 'auto'); +}); diff --git a/sidecars/panel/trajectory-metrics.mjs b/sidecars/panel/trajectory-metrics.mjs index 58f9c73..cfa0cdf 100644 --- a/sidecars/panel/trajectory-metrics.mjs +++ b/sidecars/panel/trajectory-metrics.mjs @@ -679,6 +679,78 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { return Boolean(step.userInput && typeof step.userInput === 'object'); }; + const hasHumanUserTurn = rawSteps.some(isUserTurnBoundary); + + const isSystemWakeupBoundary = (step) => { + if (hasHumanUserTurn || !step || typeof step !== 'object') return false; + if (isCheckpointStep(step)) return false; + const t = String(step.type || '').trim().toUpperCase(); + if (t !== 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE' && t !== 'SYSTEM_MESSAGE') { + return false; + } + const rawMsg = String(step?.systemMessage?.message || step?.content || '').trim(); + const withoutSummary = rawMsg + .replace(/[\s\S]*?<\/CONTEXT_SUMMARY>/gi, '') + .trim(); + if (!withoutSummary || /BROWSER_HOST_FACTS/i.test(withoutSummary)) return false; + return true; + }; + + const extractSystemWakeupInfo = (step) => { + let raw = String(step?.systemMessage?.message || step?.content || '').trim(); + const sysMatches = [...raw.matchAll(/([\s\S]*?)<\/SYSTEM_MESSAGE>/gi)]; + if (sysMatches.length > 0) { + raw = sysMatches[sysMatches.length - 1][1].trim(); + } else { + raw = raw.replace(/^The following is a [\s\S]*?/i, '').replace(/<\/SYSTEM_MESSAGE>\s*$/i, '').trim(); + } + raw = raw.replace(/^\[Message\]\s+timestamp=\S+\s+sender=\S+\s+priority=\S+\s+content=/i, '').trim(); + + const doorbellMatch = raw.match(/^\[swarm\]\s+new board message\s+#(\d+)\s*$/i); + if (doorbellMatch) { + const tag = `[swarm] #${doorbellMatch[1]}`; + return { cleanText: tag, legacyPrompt: tag, hasMedia: false, isDoorbellOnly: true }; + } + + const assignMatch = raw.match( + /^You have just started\.\s*Your assignment\s*\(recorded on the board as #(\d+)\s+for\s+@?([^\s):]+)\)\s*:\s*([\s\S]*)$/i + ); + if (assignMatch) { + const seq = assignMatch[1]; + const member = assignMatch[2]; + const bodyLines = String(assignMatch[3] || '') + .split(/\r?\n/) + .map((l) => l.replace(/\s+/g, ' ').trim()) + .filter(Boolean); + const bodyPreview = bodyLines.join(' '); + const full = bodyPreview ? `#${seq} @${member} · ${bodyPreview}` : `#${seq} @${member}`; + const cleanText = full.length > 180 ? `${full.slice(0, 179)}…` : full; + return { cleanText, legacyPrompt: cleanText, hasMedia: false, isDoorbellOnly: false }; + } + + const boardDeltaMatch = raw.match( + /^\[board\]\s+the latest message is #(\d+)\s*\(you have read up to #(\d+)\)/i + ); + if (boardDeltaMatch) { + const tag = `[board] #${boardDeltaMatch[2]} -> #${boardDeltaMatch[1]}`; + return { cleanText: tag, legacyPrompt: tag, hasMedia: false, isDoorbellOnly: true }; + } + + const monitorTickMatch = raw.match(/^\[monitor\]\s+tick:[^(]*\(iteration\s+(\d+)\)\s*$/i); + if (monitorTickMatch) { + const tag = `[monitor] tick #${monitorTickMatch[1]}`; + return { cleanText: tag, legacyPrompt: tag, hasMedia: false, isDoorbellOnly: false }; + } + + const cleaned = raw + .split(/\r?\n/) + .map((l) => l.replace(/\s+/g, ' ').trim()) + .filter(Boolean) + .join('\n'); + const cleanText = cleaned.length > 180 ? `${cleaned.slice(0, 179)}…` : cleaned; + return { cleanText, legacyPrompt: cleanText, hasMedia: false, isDoorbellOnly: false }; + }; + const extractUserTurnInfo = (step) => { const ui = step?.userInput; let raw = ''; @@ -717,15 +789,26 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { }; let pendingTurnCleanPrompts = []; + let pendingTurnDoorbellOnly = false; rawSteps.forEach((s, index) => { - if (isUserTurnBoundary(s)) { - const { cleanText, legacyPrompt, hasMedia } = extractUserTurnInfo(s); + const isHumanBoundary = isUserTurnBoundary(s); + const isWakeupBoundary = !isHumanBoundary && isSystemWakeupBoundary(s); + if (isHumanBoundary || isWakeupBoundary) { + const { cleanText, legacyPrompt, hasMedia, isDoorbellOnly = false } = isHumanBoundary + ? extractUserTurnInfo(s) + : extractSystemWakeupInfo(s); if (!hasUnconsumedTurn) { hasUnconsumedTurn = true; pendingTurnPrompts = legacyPrompt ? [legacyPrompt] : []; pendingTurnCleanPrompts = cleanText ? [cleanText] : []; pendingTurnHasMedia = hasMedia; - } else { + pendingTurnDoorbellOnly = Boolean(isWakeupBoundary && isDoorbellOnly); + } else if (isWakeupBoundary && pendingTurnDoorbellOnly && !isDoorbellOnly && cleanText) { + // 合并连续唤醒步时,用紧随其后的真实简报/任务正文覆盖前置的纯 #seq 门铃提示 + pendingTurnPrompts = legacyPrompt ? [legacyPrompt] : []; + pendingTurnCleanPrompts = [cleanText]; + pendingTurnDoorbellOnly = false; + } else if (!(isWakeupBoundary && isDoorbellOnly && !pendingTurnDoorbellOnly)) { if ( legacyPrompt && pendingTurnPrompts[pendingTurnPrompts.length - 1] !== legacyPrompt @@ -769,6 +852,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { pendingTurnPrompts = []; pendingTurnCleanPrompts = []; pendingTurnHasMedia = false; + pendingTurnDoorbellOnly = false; } const stepIndex = m.sourceTrajectoryStepInfo?.stepIndex ?? index; @@ -1845,6 +1929,144 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { }; } + if (nameLower === 'swarm') { + const action = pickField(['action', 'Action']).toLowerCase(); + const memberName = pickField(['name', 'Name']).replace(/^@+/, '').trim(); + if (action === 'add') { + const rawTasks = unwrapArgValue(args?.tasks); + const rawCount = Number(unwrapArgValue(args?.n) || 0); + const shardCount = Array.isArray(rawTasks) && rawTasks.length > 1 + ? rawTasks.length + : rawCount > 1 + ? Math.floor(rawCount) + : 0; + const detail = memberName + ? shardCount > 1 + ? `@${memberName}-1..${shardCount}` + : `@${memberName}` + : ''; + return { + toolName: nameLower, + actionKey: 'swarm_add', + isAskUser: false, + label: '派生工蜂', + detail, + }; + } + if (action === 'title') { + return { + toolName: nameLower, + actionKey: 'swarm_title', + isAskUser: false, + label: '命名蜂群', + detail: cleanSingleLineSnippet(pickField(['title', 'Title']), 44) || '', + }; + } + if (action === 'kill') { + return { + toolName: nameLower, + actionKey: 'swarm_kill', + isAskUser: false, + label: '终止工蜂', + detail: memberName ? `@${memberName}` : '', + }; + } + if (action === 'model') { + const target = memberName ? `@${memberName}` : '@coordinator'; + const nextModel = pickField(['model', 'Model']); + return { + toolName: nameLower, + actionKey: 'swarm_model', + isAskUser: false, + label: '切换工蜂模型', + detail: nextModel ? `${target} -> ${nextModel}` : target, + }; + } + if (action === 'channel') { + const op = pickField(['op', 'Op']); + const ch = pickField(['channel', 'Channel']).replace(/^#+/, '').trim(); + return { + toolName: nameLower, + actionKey: 'swarm_channel', + isAskUser: false, + label: '蜂群频道', + detail: ch ? `${op ? `${op} ` : ''}#${ch}` : op || '', + }; + } + return { + toolName: nameLower, + actionKey: 'swarm_status', + isAskUser: false, + label: '巡检蜂群', + detail: action || 'status', + }; + } + + if (nameLower === 'post_message') { + const channel = pickField(['channel', 'Channel']).replace(/^#+/, '').trim(); + const textSnippet = cleanSingleLineSnippet(pickField(['text', 'Text']), 48); + const detail = + channel && channel !== 'main' + ? `[#${channel}]${textSnippet ? ` ${textSnippet}` : ''}` + : textSnippet || ''; + return { + toolName: nameLower, + actionKey: 'post_message', + isAskUser: false, + label: '发布看板', + detail, + }; + } + + if (nameLower === 'read_board') { + const rawStatus = unwrapArgValue(args?.status) ?? pickField(['status']); + const isStatus = String(rawStatus).trim().toLowerCase() === 'true'; + const rawSeqs = unwrapArgValue(args?.seqs); + const seqsLabel = + Array.isArray(rawSeqs) && rawSeqs.length > 0 + ? `${rawSeqs + .slice(0, 4) + .map((n) => `#${String(unwrapArgValue(n) ?? n).trim()}`) + .join(', ')}${rawSeqs.length > 4 ? '…' : ''}` + : ''; + const sinceVal = unwrapArgValue(args?.since) ?? pickField(['since']); + const channel = pickField(['channel', 'Channel']).replace(/^#+/, '').trim(); + const detail = isStatus + ? 'status' + : [ + channel && channel !== 'main' ? `#${channel}` : '', + seqsLabel || + (sinceVal !== undefined && sinceVal !== null && String(sinceVal).trim() !== '' + ? `#${String(sinceVal).trim()}+` + : ''), + ] + .filter(Boolean) + .join(' '); + return { + toolName: nameLower, + actionKey: 'read_board', + isAskUser: false, + label: '读取看板', + detail, + }; + } + + if (nameLower === 'swarm_wait') { + const sinceVal = unwrapArgValue(args?.since) ?? pickField(['since']); + const detail = + sinceVal !== undefined && sinceVal !== null && String(sinceVal).trim() !== '' + ? `#${String(sinceVal).trim()}+` + : ''; + return { + toolName: nameLower, + actionKey: 'swarm_wait', + isAskUser: false, + isSwarmWait: true, + label: '看板待命', + detail, + }; + } + if (nameLower === 'manage_task') { const action = pickField(['Action', 'action']); const taskId = pickField(['TaskId', 'taskId']); @@ -2032,7 +2254,7 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt const info = summarizeToolCall(activeTool, lastStep); const stepProgress = tools.length > 1 && !hasBracketPrefix(info.detail) ? `${tools.length}/${tools.length}` : ''; - const phase = info.isAskUser ? 'waiting' : 'tool'; + const phase = info.isAskUser || info.isSwarmWait ? 'waiting' : 'tool'; return { phase, toolName: info.toolName, @@ -2115,8 +2337,8 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt if (hasBracketPrefix(info.detail)) { stepProgress = ''; } - const waiting = isWaitingStepStatus(lastStep?.status) || info.isAskUser; - const waitingApproval = Boolean(waiting && !info.isAskUser); + const waiting = isWaitingStepStatus(lastStep?.status) || info.isAskUser || Boolean(info.isSwarmWait); + const waitingApproval = Boolean(waiting && !info.isAskUser && !info.isSwarmWait); const resolvedStartMs = startMs || prevStepEndMs || 0; const label = waitingApproval ? `等待确认 · ${info.label}` : info.label; @@ -2207,7 +2429,7 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt getRawStepEndMs(lastStep) || getRawStepEndMs(plannerStep) || 0; - const phase = info.isAskUser ? 'waiting' : 'tool'; + const phase = info.isAskUser || info.isSwarmWait ? 'waiting' : 'tool'; return { phase, @@ -2228,6 +2450,22 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt const infos = pTools.map((t, idx) => summarizeToolCall(t, toolStepsAfterPlanner[idx] || lastStep) ); + const swarmWaitInfo = infos.find((x) => x.isSwarmWait); + if (swarmWaitInfo) { + const startMs = getRawStepFinishMs(lastStep) || getRawStepEndMs(lastStep) || 0; + return { + phase: 'waiting', + toolName: swarmWaitInfo.toolName, + actionKey: swarmWaitInfo.actionKey, + waitingApproval: false, + detailKey: '', + label: swarmWaitInfo.label, + detail: swarmWaitInfo.detail, + stepProgress: '', + startedAtMs: startMs, + signature: `swarm-wait:${lastStepId}:${swarmWaitInfo.detail}`, + }; + } const lastToolInfo = infos[infos.length - 1]; const allSameLabel = infos.every((x) => x.actionKey === lastToolInfo.actionKey); const detailsList = infos.map((x) => x.detail).filter(Boolean); @@ -2254,13 +2492,28 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt }; } - // B2.5:Connect RPC 轨迹中工具作为独立步骤存在(plannerResponse.toolCalls 为空)时,直接提取最后一个工具步骤的目标文件/命令 + // B2.5:Connect RPC / SQLite 轨迹中工具作为独立步骤存在(plannerResponse.toolCalls 为空)时,直接提取最后一个工具步骤的目标文件/命令 if (lastIdx > lastPlannerIdx) { const stepTypeUpper = String(lastStep?.type || '').toUpperCase(); - if (!stepTypeUpper.includes('USER_INPUT') && !stepTypeUpper.includes('GENERIC')) { + const hasStepToolMeta = Boolean(lastStep?.metadata?.toolCall?.name); + if (!stepTypeUpper.includes('USER_INPUT') && (!stepTypeUpper.includes('GENERIC') || hasStepToolMeta)) { const lastInfo = summarizeToolCall(null, lastStep); if (lastInfo.toolName !== 'tool' || lastInfo.detail) { const startMs = getRawStepFinishMs(lastStep) || getRawStepEndMs(lastStep) || 0; + if (lastInfo.isSwarmWait) { + return { + phase: 'waiting', + toolName: lastInfo.toolName, + actionKey: lastInfo.actionKey, + waitingApproval: false, + detailKey: '', + label: lastInfo.label, + detail: lastInfo.detail, + stepProgress: '', + startedAtMs: startMs, + signature: `swarm-wait:${lastStepId}:${lastInfo.detail}`, + }; + } return { phase: 'thinking', toolName: lastInfo.toolName, @@ -2332,3 +2585,101 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt }; } +/** + * 识别并规范化蜂群(Native Swarm)工蜂节点的身份信息,剥离冗余的 `Swarm Worker ()` 包裹。 + * + * @param {{ role?: string, typeName?: string, agentScriptName?: string, memberName?: string }} [input={}] + * @returns {{ isSwarmWorker: boolean, memberName: string, isMonitor: boolean, isNarrator: boolean, isAuxiliary: boolean }} + */ +export function parseSwarmWorkerRole(input = {}) { + const rawRole = String(input?.role || '').trim(); + const rawType = String(input?.typeName || '').trim().toLowerCase(); + const rawScript = String(input?.agentScriptName || '').trim(); + const explicitMember = String(input?.memberName || '').trim(); + + const wrapperMatch = rawRole.match(/^Swarm\s+Worker\s*\(([^)]+)\)\s*$/i); + const isSwarmWorker = Boolean( + explicitMember || wrapperMatch || rawType === 'worker' || rawType === 'swarm_worker' + ); + if (!isSwarmWorker) { + return { + isSwarmWorker: false, + memberName: '', + isMonitor: false, + isNarrator: false, + isAuxiliary: false, + }; + } + + const candidate = + explicitMember || + (wrapperMatch ? wrapperMatch[1] : '') || + rawScript || + (rawRole.toLowerCase() !== 'worker' && rawRole.toLowerCase() !== 'swarm worker' ? rawRole : ''); + const memberName = String(candidate || '').replace(/^@+/, '').trim(); + const isMonitor = /^monitor(?:-\d+)?$/i.test(memberName); + const isNarrator = /^narrator(?:-\d+)?$/i.test(memberName); + return { + isSwarmWorker: true, + memberName, + isMonitor, + isNarrator, + isAuxiliary: isMonitor || isNarrator, + }; +} + +/** + * 判断原始轨迹步骤是否已调用 `swarm_wait` 进入留言板待命状态(且后续尚未收到新的用户提问或系统唤醒消息)。 + * + * @param {Array} [rawSteps=[]] + * @returns {boolean} + */ +export function isParkedOnSwarmWait(rawSteps = []) { + if (!Array.isArray(rawSteps) || rawSteps.length === 0) return false; + let lastIdx = rawSteps.length - 1; + while (lastIdx > 0 && isAuxiliaryMetaStep(rawSteps[lastIdx]) && isRawStepComplete(rawSteps[lastIdx])) { + lastIdx--; + } + let lastPlannerIdx = -1; + for (let i = lastIdx; i >= 0; i--) { + const st = rawSteps[i]; + const t = String(st?.type || '').trim().toUpperCase(); + if (t.includes('USER_INPUT') || t.includes('SYSTEM_MESSAGE') || isCheckpointStep(st)) { + return false; + } + if (isPlannerStep(st)) { + lastPlannerIdx = i; + break; + } + } + if (lastPlannerIdx < 0) return false; + + const pTools = getStepPlannerToolCalls(rawSteps[lastPlannerIdx]); + if ( + pTools.some((tc) => { + const n = String(tc?.name || tc?.toolName || tc?.function?.name || '') + .trim() + .toLowerCase() + .replace(/^default_api:/, ''); + return n === 'swarm_wait'; + }) + ) { + return true; + } + + for (let k = lastPlannerIdx + 1; k <= lastIdx; k++) { + const st = rawSteps[k]; + const toolName = String(st?.metadata?.toolCall?.name || '') + .trim() + .toLowerCase() + .replace(/^default_api:/, ''); + if (toolName === 'swarm_wait') return true; + const rawContent = String(st?.content || '').trim(); + if (/Waiting for a message that calls on you|Waiting for any message posted after/i.test(rawContent)) { + return true; + } + } + return false; +} + + From 88b71829068bb88dfe7814e7c7b9e55d70b6466d Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Thu, 19 Nov 2026 09:37:42 +0900 Subject: [PATCH 03/14] chore(release): bump version to v1.5.2 --- plugin.json | 2 +- pricing-catalog.json | 6 +++--- sidecars/panel/index.html | 4 ++-- sidecars/panel/package.json | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/plugin.json b/plugin.json index 1342256..ca8c3bd 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "name": "usage-monitor", "displayName": "Usage & Speed Monitor", - "version": "1.5.1", + "version": "1.5.2", "description": "实时查看生成速度、首字延迟、上下文占用、可用额度及历史用量。", "logo": "assets/logo.svg", "suggestedPrompts": [ diff --git a/pricing-catalog.json b/pricing-catalog.json index 8df9fe4..d2d403a 100644 --- a/pricing-catalog.json +++ b/pricing-catalog.json @@ -1,8 +1,8 @@ { "schemaVersion": 1, - "catalogVersion": "2026.11.19.1", - "updatedAt": "2026-11-19T09:20:00+09:00", - "latestPluginVersion": "1.5.1", + "catalogVersion": "2026.11.19.2", + "updatedAt": "2026-11-19T09:35:00+09:00", + "latestPluginVersion": "1.5.2", "releaseUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest", "downloadUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip", "archiveFallbackUrl": "https://codeload.github.com/yuhuan-dev/antigravity-usage-monitor/zip/refs/heads/main", diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 57694c1..733e696 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/package.json b/sidecars/panel/package.json index d4c248a..6fdf3ce 100644 --- a/sidecars/panel/package.json +++ b/sidecars/panel/package.json @@ -1,6 +1,6 @@ { "name": "usage-monitor-panel", - "version": "1.5.1", + "version": "1.5.2", "private": true, "type": "module", "description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor.", From 70629dcd74d7cbb830e45a40b3e517de48b77114 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Thu, 19 Nov 2026 10:43:31 +0900 Subject: [PATCH 04/14] feat(panel): scale consumption bars by share percentage and unify 20-color deterministic model palette - Scale Top Models and Client Sources horizontal bars by actual share percentage instead of always filling 100%, keeping Overview at 100% - Add zero-hardcode deterministic 20-stop perceptual color ring (FNV-1a + Murmur3 with natural-slot reservation) so identical models receive consistent distinct colors across machines and sections - Aggregate per-model breakdowns across Client Sources, Monthly Breakdown, and active Usage Trend buckets, folding <1.5% long-tail models into neutral 'Others (N)' - Add per-model color dots after Top Models names, expand Usage Trend SVG height to 184px (and heatmap cell floor to 11px), and render unified model breakdown hover popovers across Usage Trend, Client Sources, and Monthly Breakdown --- sidecars/panel/app.js | 986 +++++++++++++++--- sidecars/panel/backend/usage-aggregator.mjs | 75 +- sidecars/panel/index.html | 4 +- .../src/components/charts/TrendAreaChart.js | 81 +- .../panel/src/components/ui/FourSegmentBar.js | 30 +- sidecars/panel/src/core/formatters.js | 159 +++ sidecars/panel/src/i18n/en-US.js | 3 + sidecars/panel/src/i18n/zh-CN.js | 3 + sidecars/panel/src/store/telemetryStore.js | 47 +- .../panel/src/styles/views-consumption.css | 179 +++- sidecars/panel/src/views/ConsumptionView.js | 671 ++++++++++-- sidecars/panel/styles.css | 179 +++- sidecars/panel/test/consumption-bars.test.mjs | 474 +++++++++ sidecars/panel/test/window-bridge.test.mjs | 2 +- 14 files changed, 2564 insertions(+), 329 deletions(-) create mode 100644 sidecars/panel/test/consumption-bars.test.mjs diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 5de2411..7102bb2 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1264,6 +1264,9 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'cons.clientSources': '客户端来源', 'cons.monthlyTitle': '月度统计', 'cons.monthLabel': '{m}月', + 'cons.monthFullLabel': '{year}年 {m}月', + 'cons.hoverModelsHint': '悬停查看模型', + 'cons.otherModelsCount': '其他 ({count})', 'cons.legInput': '输入', 'cons.legCache': '缓存', 'cons.legOutput': '输出', @@ -1927,6 +1930,9 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'cons.clientSources': 'Client Sources', 'cons.monthlyTitle': 'Monthly Breakdown', 'cons.monthLabel': 'M{m}', + 'cons.monthFullLabel': 'M{m}, {year}', + 'cons.hoverModelsHint': 'Hover for models', + 'cons.otherModelsCount': 'Others ({count})', 'cons.legInput': 'Input', 'cons.legCache': 'Cache', 'cons.legOutput': 'Output', @@ -2798,7 +2804,7 @@ return { defineComponent }; })(); // --- src/core/formatters.js --- -const { formatMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail } = (() => { +const { formatMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap } = (() => { /** * @fileoverview Pure formatting utilities for speed metrics, token counts, * USD estimates, countdown timers, and custom datetime displays. @@ -3464,7 +3470,166 @@ function formatLiveActivityDetail(act) { } return String(act.detail || ''); } -return { formatMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail }; + +/** + * 20 色感知均匀色环(无特定模型绑定,兼顾亮/暗背景可读性,彻底消除标准 HSL 绿色/暗红区过度聚集撞色)。 + * 每项为 `[hue, saturationPct, lightnessPct]`。 + */ +const PERCEPTUAL_MODEL_COLOR_RING = [ + [217, 82, 53], // Royal Blue + [14, 80, 52], // Coral / Vermilion + [162, 74, 41], // Teal / Jade + [272, 74, 58], // Vivid Violet + [36, 88, 47], // Rich Amber + [336, 78, 53], // Rose / Raspberry + [193, 84, 43], // Cerulean / Cyan + [138, 66, 41], // Emerald Green + [246, 74, 60], // Indigo + [25, 86, 50], // Tangerine Orange + [306, 70, 52], // Magenta / Orchid + [177, 76, 39], // Deep Seafoam + [355, 76, 54], // Crimson Red + [205, 80, 48], // Ocean Blue + [45, 88, 44], // Warm Gold + [288, 68, 55], // Amethyst Purple + [102, 60, 42], // Leaf Green + [230, 76, 57], // Cobalt Blue + [322, 74, 51], // Berry Pink + [185, 72, 46], // Turquoise +]; + +/** + * 提取跨平台、跨语言、同屏三栏(模型排行 / 客户端来源 / 月度统计)严格一致的模型颜色种子字符串。 + * + * 优先取单模型稳定 `sourceLabels[0]`;若多个外层槽位已在当前显示策略下合并(如 `4-argon`), + * 则以规范化 `displayText` 为种子,确保跨客户端与跨月份聚合子集不同时依然映射至完全相同的颜色。 + * + * @param {object|string|null|undefined} model + * @returns {string} + */ +function getCanonicalModelColorSeed(model) { + if (typeof model === 'string') { + return model.trim().toLowerCase().replace(/\s+/g, ' '); + } + if (!model || typeof model !== 'object') return ''; + if ( + Number(model.mergedCount || 0) <= 1 && + Array.isArray(model.sourceLabels) && + model.sourceLabels.length === 1 && + model.sourceLabels[0] + ) { + return String(model.sourceLabels[0]).trim().toLowerCase().replace(/\s+/g, ' '); + } + const raw = + model.displayText || + model.label || + model.modelId || + model.baseItem?.modelId || + model.shortName || + model.name || + ''; + return String(raw).trim().toLowerCase().replace(/\s+/g, ' '); +} + +function hashModelSeed32(str) { + let h = 0x811c9dc5; + for (let i = 0; i < str.length; i++) { + h ^= str.charCodeAt(i); + h = Math.imul(h, 0x01000193); + } + h ^= h >>> 16; + h = Math.imul(h, 0x85ebca6b); + h ^= h >>> 13; + h = Math.imul(h, 0xc2b2ae35); + h ^= h >>> 16; + return h >>> 0; +} + +function formatRingSlotHsl(slotIdx, shiftLight = 0) { + const [hue, sat, light] = PERCEPTUAL_MODEL_COLOR_RING[slotIdx % PERCEPTUAL_MODEL_COLOR_RING.length]; + const clampedLight = Math.min(66, Math.max(34, light + shiftLight)); + return `hsl(${hue} ${sat}% ${clampedLight}%)`; +} + +/** + * 基于模型标识通过 32 位雪崩哈希映射至 20 色感知均匀色环,确保跨电脑同模型同色且无需硬编码颜色表。 + * + * @param {object|string|null|undefined} seedOrModel + * @returns {string} + */ +function resolveDeterministicModelColor(seedOrModel) { + const seed = getCanonicalModelColorSeed(seedOrModel); + if (!seed) return 'var(--accent-primary)'; + const h = hashModelSeed32(seed); + return formatRingSlotHsl(h % PERCEPTUAL_MODEL_COLOR_RING.length); +} + +/** + * 为一组模型构建确定性颜色映射表(双遍固有槽位保护): + * 1. 所有无槽位冲突的模型 100% 保持其纯哈希固有色,不受长尾模型增减影响; + * 2. 仅当同屏两个模型恰好落入同一色环槽位时,按严格字典序以互质步长 `+7` 优先探查未被任何模型占用的空闲槽位。 + * + * @param {Array} [models=[]] + * @returns {Map} `canonicalSeed -> hsl(...)` + */ +function buildDeterministicModelColorMap(models = []) { + const ringLen = PERCEPTUAL_MODEL_COLOR_RING.length; + const uniqueSeeds = Array.from( + new Set( + (Array.isArray(models) ? models : []) + .map((m) => getCanonicalModelColorSeed(m)) + .filter(Boolean) + ) + ).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); + + const naturalSlotCounts = new Map(); + for (const seed of uniqueSeeds) { + const nat = hashModelSeed32(seed) % ringLen; + naturalSlotCounts.set(nat, (naturalSlotCounts.get(nat) || 0) + 1); + } + + const usedSlots = new Set(); + const colorMap = new Map(); + + for (const seed of uniqueSeeds) { + const h = hashModelSeed32(seed); + const nat = h % ringLen; + if (!usedSlots.has(nat)) { + usedSlots.add(nat); + colorMap.set(seed, formatRingSlotHsl(nat)); + continue; + } + + let picked = -1; + for (let k = 1; k < ringLen; k++) { + const cand = (nat + k * 7) % ringLen; + if (!usedSlots.has(cand) && !naturalSlotCounts.has(cand)) { + picked = cand; + break; + } + } + if (picked < 0) { + for (let k = 1; k < ringLen; k++) { + const cand = (nat + k * 7) % ringLen; + if (!usedSlots.has(cand)) { + picked = cand; + break; + } + } + } + + if (picked >= 0) { + usedSlots.add(picked); + colorMap.set(seed, formatRingSlotHsl(picked)); + } else { + const shift = (h >>> 8) & 1 ? 9 : -8; + colorMap.set(seed, formatRingSlotHsl(nat, shift)); + } + } + + return colorMap; +} +return { formatMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap }; })(); // --- src/core/httpClient.js --- @@ -4247,6 +4412,26 @@ function isEquivalentTelemetry(prev, next) { if (pAcct?.unpricedCalls !== nAcct?.unpricedCalls) return false; // 6. 比对历史趋势时间分桶序列与年度分月序列 + const areModelSlicesEqual = (pList, nList) => { + const a = pList || []; + const b = nList || []; + if (a.length !== b.length) return false; + for (let k = 0; k < a.length; k++) { + if ( + a[k]?.label !== b[k]?.label || + a[k]?.shortName !== b[k]?.shortName || + a[k]?.upstreamName !== b[k]?.upstreamName || + a[k]?.costUsd !== b[k]?.costUsd || + a[k]?.unpricedCalls !== b[k]?.unpricedCalls || + a[k]?.totalTokens !== b[k]?.totalTokens || + a[k]?.calls !== b[k]?.calls + ) { + return false; + } + } + return true; + }; + const pTrend = prev.consumption?.trendSeries || []; const nTrend = next.consumption?.trendSeries || []; if (pTrend.length !== nTrend.length) return false; @@ -4255,12 +4440,14 @@ function isEquivalentTelemetry(prev, next) { pTrend[i]?.tokens !== nTrend[i]?.tokens || pTrend[i]?.calls !== nTrend[i]?.calls || pTrend[i]?.label !== nTrend[i]?.label || - pTrend[i]?.fullLabel !== nTrend[i]?.fullLabel + pTrend[i]?.fullLabel !== nTrend[i]?.fullLabel || + !areModelSlicesEqual(pTrend[i]?.models, nTrend[i]?.models) ) { return false; } } if (prev.consumption?.monthlyYear !== next.consumption?.monthlyYear) return false; + const pMonthly = prev.consumption?.monthlySeries || []; const nMonthly = next.consumption?.monthlySeries || []; if (pMonthly.length !== nMonthly.length) return false; @@ -4268,28 +4455,16 @@ function isEquivalentTelemetry(prev, next) { if ( pMonthly[i]?.totalTokens !== nMonthly[i]?.totalTokens || pMonthly[i]?.costUsd !== nMonthly[i]?.costUsd || - pMonthly[i]?.calls !== nMonthly[i]?.calls + pMonthly[i]?.calls !== nMonthly[i]?.calls || + !areModelSlicesEqual(pMonthly[i]?.models, nMonthly[i]?.models) ) { return false; } } // 7. 比对按模型汇总明细与数据来源汇总明细 - const pModels = prev.modelBreakdown || []; - const nModels = next.modelBreakdown || []; - if (pModels.length !== nModels.length) return false; - for (let i = 0; i < pModels.length; i++) { - if ( - pModels[i]?.label !== nModels[i]?.label || - pModels[i]?.shortName !== nModels[i]?.shortName || - pModels[i]?.upstreamName !== nModels[i]?.upstreamName || - pModels[i]?.costUsd !== nModels[i]?.costUsd || - pModels[i]?.unpricedCalls !== nModels[i]?.unpricedCalls || - pModels[i]?.totalTokens !== nModels[i]?.totalTokens || - pModels[i]?.calls !== nModels[i]?.calls - ) { - return false; - } + if (!areModelSlicesEqual(prev.modelBreakdown, next.modelBreakdown)) { + return false; } const pSources = prev.consumption?.sourcesBreakdown || []; @@ -4301,7 +4476,8 @@ function isEquivalentTelemetry(prev, next) { pSources[i]?.costUsd !== nSources[i]?.costUsd || pSources[i]?.unpricedCalls !== nSources[i]?.unpricedCalls || pSources[i]?.totalTokens !== nSources[i]?.totalTokens || - pSources[i]?.calls !== nSources[i]?.calls + pSources[i]?.calls !== nSources[i]?.calls || + !areModelSlicesEqual(pSources[i]?.models, nSources[i]?.models) ) { return false; } @@ -6210,14 +6386,30 @@ function createFourSegmentBar() { ]); /** - * 根据四类 Token 数量重新计算并写入各分段百分比宽度。 + * 根据四类 Token 数量与整体行宽占比系数 (`scaleRatio`,默认 `1` 占满 100%) 重新计算并写入各分段百分比宽度。 */ - function update({ inputTokens = 0, cacheReadTokens = 0, responseTokens = 0, thinkingTokens = 0 }) { - const total = Math.max(1, inputTokens + cacheReadTokens + responseTokens + thinkingTokens); - patchStyleVar(segInput, '--seg-w', `${((inputTokens / total) * 100).toFixed(2)}%`); - patchStyleVar(segCached, '--seg-w', `${((cacheReadTokens / total) * 100).toFixed(2)}%`); - patchStyleVar(segOutput, '--seg-w', `${((responseTokens / total) * 100).toFixed(2)}%`); - patchStyleVar(segThinking, '--seg-w', `${((thinkingTokens / total) * 100).toFixed(2)}%`); + function update({ + inputTokens = 0, + cacheReadTokens = 0, + responseTokens = 0, + thinkingTokens = 0, + scaleRatio = 1, + }) { + const sum = inputTokens + cacheReadTokens + responseTokens + thinkingTokens; + const clampedRatio = Number.isFinite(Number(scaleRatio)) + ? Math.min(1, Math.max(0, Number(scaleRatio))) + : 1; + if (sum <= 0 || clampedRatio <= 0) { + patchStyleVar(segInput, '--seg-w', '0%'); + patchStyleVar(segCached, '--seg-w', '0%'); + patchStyleVar(segOutput, '--seg-w', '0%'); + patchStyleVar(segThinking, '--seg-w', '0%'); + return; + } + patchStyleVar(segInput, '--seg-w', `${((inputTokens / sum) * 100 * clampedRatio).toFixed(2)}%`); + patchStyleVar(segCached, '--seg-w', `${((cacheReadTokens / sum) * 100 * clampedRatio).toFixed(2)}%`); + patchStyleVar(segOutput, '--seg-w', `${((responseTokens / sum) * 100 * clampedRatio).toFixed(2)}%`); + patchStyleVar(segThinking, '--seg-w', `${((thinkingTokens / sum) * 100 * clampedRatio).toFixed(2)}%`); } return { el, update }; @@ -6421,9 +6613,9 @@ function buildHeatmapMonthTicks(slots, firstDow, totalWeeks) { */ function createTrendAreaChart() { const DEFAULT_VIEW_W = 460; - const VIEW_H = 120; - const TOP_Y = 24; - const BOTTOM_Y = 102; + const VIEW_H = 184; + const TOP_Y = 26; + const BOTTOM_Y = 164; const SPAN_Y = BOTTOM_Y - TOP_Y; let viewW = DEFAULT_VIEW_W; @@ -6468,7 +6660,12 @@ function createTrendAreaChart() { const hGridGroup = document.createElementNS(SVG_NS, 'g'); hGridGroup.setAttribute('class', 'trend-grid'); const hGridLines = []; - for (const y of [TOP_Y, Math.round((TOP_Y + BOTTOM_Y) / 2), BOTTOM_Y]) { + for (const y of [ + TOP_Y, + Math.round(TOP_Y + SPAN_Y / 3), + Math.round(TOP_Y + (SPAN_Y * 2) / 3), + BOTTOM_Y, + ]) { const line = document.createElementNS(SVG_NS, 'line'); line.setAttribute('x1', '0'); line.setAttribute('y1', String(y)); @@ -6517,12 +6714,28 @@ function createTrendAreaChart() { const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0' }); - // 共享悬停详情浮层卡片(曲线图与热力格子图共用) + function createTooltipModelRow() { + const dotEl = h('span', { className: 'dot-swatch cons-model-dot' }); + const nameEl = h('span', { className: 'cons-pop-model-name' }); + const tokEl = h('span', { className: 'cons-pop-model-tok' }); + const pctEl = h('strong', { className: 'cons-pop-model-pct' }); + const rowEl = h('div', { className: 'cons-pop-model-row' }, [ + h('span', { className: 'cons-pop-model-left' }, [dotEl, nameEl]), + h('span', { className: 'cons-pop-model-right text-mono' }, [tokEl, pctEl]), + ]); + return { + el: rowEl, + refs: { rowEl, dotEl, nameEl, tokEl, pctEl }, + }; + } + + // 共享悬停详情浮层卡片(曲线图与热力格子图共用,含该时段分模型占比明细) const tipTimeEl = h('span', { className: 'trend-tip-time text-mono' }); const tipCallsEl = h('span', { className: 'trend-tip-calls text-mono' }); const tipTokensEl = h('strong', { className: 'trend-tip-tokens text-mono' }); const tipCostEl = h('span', { className: 'trend-tip-cost text-mono' }); const tipSubEl = h('div', { className: 'trend-tip-sub text-mono', hidden: true }); + const tipModelsEl = h('div', { className: 'cons-pop-models', hidden: true }); const tooltipEl = h( 'div', @@ -6531,6 +6744,7 @@ function createTrendAreaChart() { h('div', { className: 'trend-tip-head' }, [tipTimeEl, tipCallsEl]), h('div', { className: 'trend-tip-main' }, [tipTokensEl, tipCostEl]), tipSubEl, + tipModelsEl, ] ); @@ -6632,6 +6846,21 @@ function createTrendAreaChart() { }) ); } + + const modelSegs = Array.isArray(slot.modelSegments) ? slot.modelSegments : []; + patchAttr(tipModelsEl, 'hidden', modelSegs.length === 0); + patchKeyedList(tipModelsEl, modelSegs, { + keyFn: (r) => r.key, + sigFn: (r) => `${r.key}:${r.label}:${r.color}:${r.tokText}:${r.pctText}:${r.isOther}`, + createRow: createTooltipModelRow, + updateRow: (rRefs, r) => { + patchClasses(rRefs.rowEl, { 'is-other': Boolean(r.isOther) }); + patchStyleVar(rRefs.dotEl, '--dot-color', r.color); + patchText(rRefs.nameEl, r.label); + patchText(rRefs.tokEl, r.tokText); + patchText(rRefs.pctEl, r.pctText); + }, + }); } function showLineHoverAtIndex(idx) { @@ -6652,7 +6881,11 @@ function createTrendAreaChart() { patchAttr(hoverDot, 'cy', pt.y.toFixed(1)); patchAttr(peakPill, 'hidden', true); - patchClasses(tooltipEl, { 'is-hm-bottom': false, 'is-hm-top': false }); + patchClasses(tooltipEl, { + 'is-hm-bottom': false, + 'is-hm-top': false, + 'is-line-low': pt.y < Math.round((TOP_Y + BOTTOM_Y) / 2), + }); patchAttr(tooltipEl, 'hidden', false); populateTooltipContent(slot); @@ -6687,10 +6920,11 @@ function createTrendAreaChart() { const row = Number(targetCell.getAttribute('data-hm-row') || 0); const col = Number(targetCell.getAttribute('data-hm-col') || 0); - // 上半区(周一~周四)浮层停靠底部,下半区(周五~周日)停靠顶部,互不遮挡被悬停格子且永不越界裁剪 + // 上半区(周一~周四)浮层停靠热力图下方,下半区(周五~周日)停靠热力图上方,互不遮挡被悬停格子且永不越界裁剪 patchClasses(tooltipEl, { 'is-hm-bottom': row <= 3, 'is-hm-top': row > 3, + 'is-line-low': false, }); patchAttr(tooltipEl, 'hidden', false); populateTooltipContent(slot); @@ -6719,7 +6953,7 @@ function createTrendAreaChart() { patchAttr(hoverLine, 'hidden', true); patchAttr(hoverDot, 'hidden', true); patchAttr(tooltipEl, 'hidden', true); - patchClasses(tooltipEl, { 'is-hm-bottom': false, 'is-hm-top': false }); + patchClasses(tooltipEl, { 'is-hm-bottom': false, 'is-hm-top': false, 'is-line-low': false }); if (!currentIsHeatmap) { patchAttr(peakPill, 'hidden', false); } @@ -7001,12 +7235,18 @@ function createTrendAreaChart() { const sig = `${locale}|${useHeatmap ? 'hm' : `line:${viewW}`}|` + slots - .map( - (s) => - `${s?.startMs || ''}:${s?.label || ''}:${s?.fullLabel || ''}:${safeSlotTokens(s?.tokens)}:${Number(s?.costUsd || 0)}:${Number(s?.calls || 0)}` - ) + .map((s) => { + const mSig = Array.isArray(s?.modelSegments) + ? s.modelSegments.map((m) => `${m.key}:${m.color}:${m.pctText}`).join(',') + : ''; + return `${s?.startMs || ''}:${s?.label || ''}:${s?.fullLabel || ''}:${safeSlotTokens(s?.tokens)}:${Number(s?.costUsd || 0)}:${Number(s?.calls || 0)}:${mSig}`; + }) .join('|'); + if (hoveredIdx >= 0 && hoveredIdx < slots.length && !tooltipEl.hasAttribute('hidden')) { + populateTooltipContent(slots[hoveredIdx]); + } + if (useHeatmap) { currentPts = []; if (sig !== lastRenderSig) { @@ -17585,86 +17825,205 @@ const ConsumptionView = defineComponent({ // --- Section 4: 客户端来源列表 --- const sourcesTitleSpan = h('span', { className: 'panel-title', text: t('cons.clientSources') }); + const sourcesHoverHint = h('span', { + className: 'text-muted text-mono', + style: 'font-size: var(--fs-sm);', + text: t('cons.hoverModelsHint'), + }); const sourcesListEl = h('div', { className: 'cons-item-list' }); const sourcesPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ sourcesTitleSpan, + sourcesHoverHint, ]), sourcesListEl, ]); - // --- Section 5: 按月细分 (12 个月垂直 4 段堆叠柱状图) --- - const monthlyTitleSpan = h('span', { className: 'panel-title', text: t('cons.monthlyTitle') }); + // --- Section 5: 按月细分 (12 个月垂直按模型配色堆叠柱状图 + 悬停明细浮层) --- + const monthlyTitleSpan = h('span', { text: t('cons.monthlyTitle') }); const monthlyYearBadge = h('span', { className: 'cons-badge text-mono', text: '2026' }); + const monthlyHoverHint = h('span', { + className: 'text-muted text-mono', + style: 'font-size: var(--fs-sm);', + text: t('cons.hoverModelsHint'), + }); + + let activeHoverTargetEl = null; + + function createPopoverModelRow() { + const dotEl = h('span', { className: 'dot-swatch cons-model-dot' }); + const nameEl = h('span', { className: 'cons-pop-model-name' }); + const tokEl = h('span', { className: 'cons-pop-model-tok' }); + const pctEl = h('strong', { className: 'cons-pop-model-pct' }); + const rowEl = h('div', { className: 'cons-pop-model-row' }, [ + h('span', { className: 'cons-pop-model-left' }, [dotEl, nameEl]), + h('span', { className: 'cons-pop-model-right text-mono' }, [tokEl, pctEl]), + ]); + return { + el: rowEl, + refs: { rowEl, dotEl, nameEl, tokEl, pctEl }, + }; + } + + const popTitleEl = h('span', { className: 'trend-tip-time' }); + const popCallsEl = h('span', { className: 'trend-tip-calls text-mono' }); + const popTokensEl = h('strong', { className: 'trend-tip-tokens text-mono' }); + const popCostEl = h('span', { className: 'trend-tip-cost text-mono' }); + const popListEl = h('div', { className: 'cons-pop-models' }); + const breakdownPopoverEl = h( + 'div', + { className: 'cons-breakdown-popover', hidden: true }, + [ + h('div', { className: 'trend-tip-head' }, [popTitleEl, popCallsEl]), + h('div', { className: 'trend-tip-main' }, [popTokensEl, popCostEl]), + popListEl, + ] + ); + + function hideBreakdownPopover() { + if (activeHoverTargetEl) { + patchClasses(activeHoverTargetEl, { 'is-hovered': false }); + activeHoverTargetEl = null; + } + patchAttr(breakdownPopoverEl, 'hidden', true); + } + + function positionBreakdownPopover(anchorEl, pointerClientX = null) { + const rootRect = rootEl.getBoundingClientRect?.() || { + left: 0, + top: 0, + width: 360, + height: 600, + }; + const anchorRect = anchorEl?.getBoundingClientRect?.() || { + left: 0, + top: 0, + bottom: 0, + width: 0, + height: 0, + }; + const tipRect = breakdownPopoverEl.getBoundingClientRect?.() || { + width: 220, + height: 120, + }; + const rootW = rootRect.width > 0 ? rootRect.width : 360; + const rootH = rootRect.height > 0 ? rootRect.height : 600; + const tipW = tipRect.width > 0 ? tipRect.width : 220; + const tipH = tipRect.height > 0 ? tipRect.height : 120; + + const centerX = + Number.isFinite(pointerClientX) && pointerClientX > 0 && rootRect.width > 0 + ? pointerClientX - rootRect.left + : anchorRect.left - rootRect.left + anchorRect.width / 2; + + const maxLeft = Math.max(8, rootW - tipW - 8); + const leftPx = Math.max(8, Math.min(maxLeft, centerX - tipW / 2)); + + const aboveTop = anchorRect.top - rootRect.top - tipH - 8; + const belowTop = anchorRect.bottom - rootRect.top + 8; + const topPx = + aboveTop >= 6 + ? aboveTop + : Math.min(Math.max(6, rootH - tipH - 6), Math.max(6, belowTop)); + + patchStyleVar(breakdownPopoverEl, '--pop-x', `${Math.round(leftPx)}px`); + patchStyleVar(breakdownPopoverEl, '--pop-y', `${Math.round(topPx)}px`); + } + + function showBreakdownPopover(anchorEl, payload, pointerClientX = null) { + if (!payload || !(payload.totalTokens > 0 || payload.calls > 0)) { + hideBreakdownPopover(); + return; + } + if (activeHoverTargetEl && activeHoverTargetEl !== anchorEl) { + patchClasses(activeHoverTargetEl, { 'is-hovered': false }); + } + activeHoverTargetEl = anchorEl; + patchClasses(anchorEl, { 'is-hovered': true }); + + patchText(popTitleEl, payload.title || '—'); + patchText(popCallsEl, t('cons.callsCount', { calls: payload.calls || 0 })); + patchText(popTokensEl, `${formatTokensPrecise(payload.totalTokens || 0)} tok`); + patchText(popCostEl, payload.costText || '$0.00'); + + const rows = Array.isArray(payload.segments) ? payload.segments : []; + patchAttr(popListEl, 'hidden', rows.length === 0); + patchKeyedList(popListEl, rows, { + keyFn: (r) => r.key, + sigFn: (r) => `${r.key}:${r.label}:${r.color}:${r.tokText}:${r.pctText}:${r.isOther}`, + createRow: createPopoverModelRow, + updateRow: (rRefs, r) => { + patchClasses(rRefs.rowEl, { 'is-other': Boolean(r.isOther) }); + patchStyleVar(rRefs.dotEl, '--dot-color', r.color); + patchText(rRefs.nameEl, r.label); + patchText(rRefs.tokEl, r.tokText); + patchText(rRefs.pctEl, r.pctText); + }, + }); + + patchAttr(breakdownPopoverEl, 'hidden', false); + positionBreakdownPopover(anchorEl, pointerClientX); + } + + function createMonthModelSegment() { + const segEl = h('div', { className: 'month-seg cons-model-seg' }); + return { el: segEl, refs: { segEl } }; + } + const monthlyCols = Array.from({ length: 12 }, (_, idx) => { const costText = h('span', { className: 'month-cost text-mono', text: '' }); - const barThink = h('div', { className: 'month-seg seg-thinking' }); - const barOut = h('div', { className: 'month-seg seg-output' }); - const barCache = h('div', { className: 'month-seg seg-cached' }); - const barIn = h('div', { className: 'month-seg seg-input' }); - const stackWrap = h('div', { className: 'month-stack' }, [ - barThink, - barOut, - barCache, - barIn, - ]); + const stackWrap = h('div', { className: 'month-stack' }); const zeroDot = h('span', { className: 'month-zero-dot' }); const monthLabel = h('span', { className: 'month-label', text: t('cons.monthLabel', { m: idx + 1 }) }); const tokText = h('span', { className: 'month-tok text-mono', text: '' }); - const colEl = h('div', { className: 'month-col' }, [ - costText, - h('div', { className: 'month-bar-well' }, [stackWrap, zeroDot]), - monthLabel, - tokText, - ]); + const colState = { hoverPayload: null }; + const colEl = h( + 'div', + { + className: 'month-col', + onMouseEnter: (e) => { + if (colState.hoverPayload) { + showBreakdownPopover(colEl, colState.hoverPayload, null); + } else { + e?.stopPropagation?.(); + } + }, + onMouseLeave: () => { + if (activeHoverTargetEl === colEl) hideBreakdownPopover(); + }, + }, + [ + costText, + h('div', { className: 'month-bar-well' }, [stackWrap, zeroDot]), + monthLabel, + tokText, + ] + ); return { el: colEl, costText, stackWrap, zeroDot, - barThink, - barOut, - barCache, - barIn, monthLabel, tokText, + colState, }; }); - const legInputSpan = h('span', { text: t('cons.legInput') }); - const legCacheSpan = h('span', { text: t('cons.legCache') }); - const legOutputSpan = h('span', { text: t('cons.legOutput') }); - const legThinkingSpan = h('span', { text: t('cons.legThinking') }); - const monthlyPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ - monthlyTitleSpan, - monthlyYearBadge, + h('span', { className: 'panel-title' }, [ + monthlyTitleSpan, + monthlyYearBadge, + ]), + monthlyHoverHint, ]), h( 'div', { className: 'monthly-grid' }, monthlyCols.map((c) => c.el) ), - h('div', { className: 'monthly-legend' }, [ - h('span', { className: 'legend-left' }, [ - h('span', { className: 'dot-swatch seg-input' }), - legInputSpan, - ]), - h('span', { className: 'legend-left' }, [ - h('span', { className: 'dot-swatch seg-cached' }), - legCacheSpan, - ]), - h('span', { className: 'legend-left' }, [ - h('span', { className: 'dot-swatch seg-output' }), - legOutputSpan, - ]), - h('span', { className: 'legend-left' }, [ - h('span', { className: 'dot-swatch seg-thinking' }), - legThinkingSpan, - ]), - ]), ]); const scrollInner = h( @@ -17685,12 +18044,86 @@ const ConsumptionView = defineComponent({ contentEl: scrollInner, className: 'view-pane', }); + viewScrollbar.el.addEventListener?.('scroll', hideBreakdownPopover, { passive: true }); + + const rootEl = h('div', { className: 'cons-view-stage' }, [ + viewScrollbar.el, + breakdownPopoverEl, + ]); /** - * 创建热门模型或数据来源的通用单行 DOM 结构(含标题、占比胶囊、总量、费用、4 段条与底部分项脚标)。 + * 将分模型列表收敛为主力模型 + 长尾「其他 (N)」,避免进度条尾部与浮层出现 0.0% 碎屑噪音。 + */ + function partitionModelSegments( + mergedModels, + modelColorMap, + { maxMain = 5, minSharePct = 1.5 } = {} + ) { + if (!Array.isArray(mergedModels) || mergedModels.length === 0) return []; + const sumTok = mergedModels.reduce((sum, m) => sum + Number(m.totalTokens || 0), 0); + const mainModels = []; + const tailModels = []; + + for (let i = 0; i < mergedModels.length; i++) { + const m = mergedModels[i]; + const mTok = Number(m.totalTokens || 0); + const sharePct = sumTok > 0 ? (mTok / sumTok) * 100 : 0; + if (i === 0 || (mainModels.length < maxMain && sharePct >= minSharePct)) { + mainModels.push(m); + } else { + tailModels.push(m); + } + } + + if (tailModels.length === 1) { + mainModels.push(tailModels.pop()); + } + + const out = mainModels.map((m) => { + const seed = getCanonicalModelColorSeed(m); + const color = + modelColorMap?.get(seed) || resolveDeterministicModelColor(seed || m.displayText); + const tok = Number(m.totalTokens || 0); + const pct = sumTok > 0 ? (tok / sumTok) * 100 : 0; + const label = m.displayText || m.label || m.shortName || '—'; + return { + key: label, + label, + tok, + pct, + tokText: formatTokensPrecise(tok), + pctText: `${pct.toFixed(1)}%`, + color, + isOther: false, + }; + }); + + if (tailModels.length >= 2) { + const otherTok = tailModels.reduce((sum, m) => sum + Number(m.totalTokens || 0), 0); + const otherPct = sumTok > 0 ? (otherTok / sumTok) * 100 : 0; + const otherLabel = t('cons.otherModelsCount', { count: tailModels.length }); + out.push({ + key: '__other__', + label: otherLabel, + tok: otherTok, + pct: otherPct, + tokText: formatTokensPrecise(otherTok), + pctText: `${otherPct.toFixed(1)}%`, + color: 'var(--cons-other-seg)', + isOther: true, + }); + } + + return out; + } + + /** + * 创建热门模型单行 DOM 结构(模型名称后附专属颜色圆点 + 按总占比缩放的 4 段比例条 + 底部分项脚标)。 */ function createBreakdownItemRow() { - const nameEl = h('strong', { className: 'cons-row-title' }); + const nameTextEl = h('span', { className: 'cons-row-title-text' }); + const modelDotEl = h('span', { className: 'dot-swatch cons-model-dot cons-title-model-dot' }); + const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl, modelDotEl]); const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); const costEl = h('strong', { className: 'cons-row-cost text-mono' }); @@ -17750,6 +18183,8 @@ const ConsumptionView = defineComponent({ el: rowEl, refs: { nameEl, + nameTextEl, + modelDotEl, pctBadge, totalTokEl, costEl, @@ -17769,22 +18204,27 @@ const ConsumptionView = defineComponent({ } /** - * 增量更新热门模型或数据来源单行的指标文本与 4 段比例条宽度。 + * 增量更新热门模型单行的指标文本、名称后的专属颜色圆点与按总占比缩放的 4 段比例条宽度。 */ - function updateBreakdownItemRow(refs, item, grandTotalTokens, showTokensInHeader = true) { + function updateBreakdownItemRow(refs, item, grandTotalTokens, modelColor = '') { patchText(refs.inLbl, t('cons.footInput')); patchText(refs.cacheLbl, t('cons.footCache')); patchText(refs.outLbl, t('cons.footOutput')); patchText(refs.thinkLbl, t('cons.footThinking')); patchText(refs.callsLbl, t('cons.footCalls')); const displayLabel = item.label || item.name || item.shortName || '—'; - patchText(refs.nameEl, displayLabel); + patchText(refs.nameTextEl, displayLabel); patchAttr(refs.nameEl, 'title', item.title || displayLabel); + patchAttr(refs.modelDotEl, 'hidden', !modelColor); + if (modelColor) { + patchStyleVar(refs.modelDotEl, '--dot-color', modelColor); + } const total = Number(item.totalTokens || 0); const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0; + const scaleRatio = + grandTotalTokens > 0 && total > 0 ? Math.min(1, Math.max(0.008, total / grandTotalTokens)) : 0; patchText(refs.pctBadge, `${share.toFixed(1)}%`); - patchText(refs.totalTokEl, showTokensInHeader ? formatTokensPrecise(total) : ''); - patchAttr(refs.totalTokEl, 'hidden', !showTokensInHeader); + patchText(refs.totalTokEl, formatTokensPrecise(total)); const costVal = Number(item.costUsd || 0); const callsCount = Number(item.calls || 0); const isAllUnpriced = @@ -17807,6 +18247,7 @@ const ConsumptionView = defineComponent({ cacheReadTokens: Number(item.cacheReadTokens || 0), responseTokens: responseTok, thinkingTokens: thinkingTok, + scaleRatio, }); patchText(refs.inVal, formatTokensPrecise(item.inputTokens || 0)); @@ -17816,6 +18257,148 @@ const ConsumptionView = defineComponent({ patchText(refs.callsVal, String(Number(item.calls || 0))); } + function createSourceModelSegment() { + const segEl = h('div', { className: 'progress-seg cons-model-seg' }); + return { el: segEl, refs: { segEl } }; + } + + /** + * 创建客户端来源单行 DOM 结构(保留长尾合并分段配色进度条与右侧总调用数,悬停进度条弹出各模型明细浮层)。 + */ + function createSourceBreakdownRow() { + const nameTextEl = h('span', { className: 'cons-row-title-text' }); + const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl]); + const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); + const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); + const costEl = h('strong', { className: 'cons-row-cost text-mono' }); + const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' }); + const rowState = { hoverPayload: null }; + const barHitEl = h( + 'div', + { + className: 'cons-source-bar-hit', + onMouseEnter: (e) => { + if (rowState.hoverPayload) { + showBreakdownPopover(barHitEl, rowState.hoverPayload, e?.clientX ?? null); + } + }, + onMouseMove: (e) => { + if (rowState.hoverPayload && activeHoverTargetEl === barHitEl) { + positionBreakdownPopover(barHitEl, e?.clientX ?? null); + } + }, + onMouseLeave: () => { + if (activeHoverTargetEl === barHitEl) hideBreakdownPopover(); + }, + }, + [trackEl] + ); + const callsLbl = h('span', { text: t('cons.footCalls') }); + const callsVal = h('strong', { className: 'text-mono' }); + + const rowEl = h('div', { className: 'cons-item-row cons-source-row' }, [ + h('div', { className: 'panel-header' }, [ + nameEl, + h('span', { className: 'cons-row-metrics' }, [ + pctBadge, + totalTokEl, + costEl, + ]), + ]), + barHitEl, + h('div', { className: 'cons-item-foot cons-source-foot' }, [ + h('span', { className: 'legend-left cons-calls-stat' }, [ + callsLbl, + callsVal, + ]), + ]), + ]); + + return { + el: rowEl, + refs: { + nameEl, + nameTextEl, + pctBadge, + totalTokEl, + costEl, + barHitEl, + trackEl, + callsLbl, + callsVal, + rowState, + }, + }; + } + + function updateSourceBreakdownRow(refs, item, grandTotalTokens, modelColorMap) { + patchText(refs.callsLbl, t('cons.footCalls')); + const displayLabel = item.label || item.name || '—'; + patchText(refs.nameTextEl, displayLabel); + patchAttr(refs.nameEl, 'title', item.title || displayLabel); + + const total = Number(item.totalTokens || 0); + const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0; + const scaleRatio = + grandTotalTokens > 0 && total > 0 ? Math.min(1, Math.max(0.01, total / grandTotalTokens)) : 0; + patchText(refs.pctBadge, `${share.toFixed(1)}%`); + patchText(refs.totalTokEl, formatTokensPrecise(total)); + + const costVal = Number(item.costUsd || 0); + const callsCount = Number(item.calls || 0); + const isAllUnpriced = + callsCount > 0 && Number(item.unpricedCalls || 0) >= callsCount && !(costVal > 0); + const costText = formatUsd(isAllUnpriced ? null : costVal, { + precise: costVal > 0 && costVal < 0.1, + }); + patchText(refs.costEl, costText); + patchText(refs.callsVal, String(callsCount)); + + const sourceModels = Array.isArray(item.mergedModels) ? item.mergedModels : []; + const partitioned = partitionModelSegments(sourceModels, modelColorMap, { + maxMain: 5, + minSharePct: 1.5, + }); + + const barItems = + partitioned.length > 0 + ? partitioned.map((seg) => ({ + key: seg.key, + segPct: scaleRatio > 0 ? seg.pct * scaleRatio : 0, + color: seg.color, + })) + : total > 0 + ? [ + { + key: '__source_fallback__', + segPct: scaleRatio * 100, + color: 'var(--accent-primary)', + }, + ] + : []; + + patchKeyedList(refs.trackEl, barItems, { + keyFn: (seg) => seg.key, + sigFn: (seg) => `${seg.key}:${seg.segPct.toFixed(2)}:${seg.color}`, + createRow: createSourceModelSegment, + updateRow: (segRefs, seg) => { + patchStyleVar(segRefs.segEl, '--seg-w', `${seg.segPct.toFixed(2)}%`); + patchStyleVar(segRefs.segEl, '--seg-color', seg.color); + }, + }); + + refs.rowState.hoverPayload = + total > 0 || callsCount > 0 + ? { + title: displayLabel, + calls: callsCount, + totalTokens: total, + costText, + segments: partitioned, + } + : null; + } + let latestSlice = null; let isDirty = false; @@ -17924,28 +18507,7 @@ const ConsumptionView = defineComponent({ thinkingTokens, }); - // 2. 同步历史趋势交互式 SVG 面积图 / 类 GitHub 每日热力图(>90天)与粒度提示 - const rangeBadgeText = isEnglishLocale() - ? getConsumptionTimeRangeOptions().find((o) => o.value === slice.range)?.label || - t('cons.allTime') - : preset?.label || rangeInfo.label || t('cons.allTime'); - patchText(trendRangeBadge, rangeBadgeText); - const trendSeries = cons.trendSeries || []; - const isHourlyTrend = - trendSeries[0]?.granularity === 'hour' || - (trendSeries[0]?.label || '').includes(':'); - const isHeatmapTrend = !isHourlyTrend && trendSeries.length > HEATMAP_DAYS_THRESHOLD; - patchText( - trendGranularityHint, - isHeatmapTrend - ? t('cons.trendHeatmapHint', { days: trendSeries.length }) - : isHourlyTrend - ? t('cons.trendPointsHintHourly', { points: trendSeries.length || 0 }) - : t('cons.trendPointsHintDaily', { points: trendSeries.length || 0 }) - ); - trendChart.update(trendSeries); - - // 3. 同步热门模型列表(按最终展示名称去重归并后按总 Token 数降序排列并执行键值增量对账) + // 2-5. 统一解析展示模式与全局确定性模型配色映射(确保趋势浮层、模型排行圆点、客户端来源条、月度堆叠柱四处完全同色) const localeSig = i18nStore.getState().locale; const displaySettings = { modelDisplayMode: normalizeModelDisplayMode( @@ -17955,38 +18517,130 @@ const ConsumptionView = defineComponent({ showUpstreamModel: Boolean(slice.showUpstreamModel), orchestratorIdMode: slice.orchestratorIdMode, }; + const mergeAndSortBucketModels = (rawList) => + mergeModelsByDisplayName(rawList || [], displaySettings, { + preferLabelInShort: true, + }) + .filter((m) => Number(m.totalTokens || 0) > 0 || Number(m.calls || 0) > 0) + .sort( + (a, b) => + (b.totalTokens || 0) - (a.totalTokens || 0) || (b.calls || 0) - (a.calls || 0) + ); + const models = mergeModelsByDisplayName(slice.modelBreakdown || [], displaySettings, { preferLabelInShort: true, }).sort((a, b) => (b.totalTokens || 0) - (a.totalTokens || 0)); const modelsTotalTok = models.reduce((s, m) => s + Number(m.totalTokens || 0), 0); + const rawSources = cons.sourcesBreakdown || []; + const sourcesTotalTok = rawSources.reduce((s, x) => s + Number(x.totalTokens || 0), 0); + const allSourceMergedModels = []; + const sourcesWithModels = rawSources.map((s) => { + const mergedModels = mergeAndSortBucketModels(s.models); + for (const m of mergedModels) { + allSourceMergedModels.push(m); + } + return { ...s, mergedModels }; + }); + + const monthlySeries = cons.monthlySeries || []; + const allMonthMergedModels = []; + const monthsMergedModels = Array.from({ length: 12 }, (_, idx) => { + const merged = mergeAndSortBucketModels(monthlySeries[idx]?.models); + for (const m of merged) { + allMonthMergedModels.push(m); + } + return merged; + }); + + const rawTrendSeries = cons.trendSeries || []; + const allTrendMergedModels = []; + const trendMergedByIdx = rawTrendSeries.map((slot) => { + if (!Array.isArray(slot?.models) || slot.models.length === 0) return null; + const merged = mergeAndSortBucketModels(slot.models); + for (const m of merged) { + allTrendMergedModels.push(m); + } + return merged; + }); + + const modelColorMap = buildDeterministicModelColorMap([ + ...models, + ...allSourceMergedModels, + ...allMonthMergedModels, + ...allTrendMergedModels, + ]); + + // 2. 同步历史趋势交互式 SVG 面积图 / 类 GitHub 每日热力图(>90天)与悬停分模型浮层 + const rangeBadgeText = isEnglishLocale() + ? getConsumptionTimeRangeOptions().find((o) => o.value === slice.range)?.label || + t('cons.allTime') + : preset?.label || rangeInfo.label || t('cons.allTime'); + patchText(trendRangeBadge, rangeBadgeText); + const isHourlyTrend = + rawTrendSeries[0]?.granularity === 'hour' || + (rawTrendSeries[0]?.label || '').includes(':'); + const isHeatmapTrend = !isHourlyTrend && rawTrendSeries.length > HEATMAP_DAYS_THRESHOLD; + patchText( + trendGranularityHint, + isHeatmapTrend + ? t('cons.trendHeatmapHint', { days: rawTrendSeries.length }) + : isHourlyTrend + ? t('cons.trendPointsHintHourly', { points: rawTrendSeries.length || 0 }) + : t('cons.trendPointsHintDaily', { points: rawTrendSeries.length || 0 }) + ); + const enrichedTrendSeries = rawTrendSeries.map((slot, idx) => { + const mergedSlotModels = trendMergedByIdx[idx]; + if (!mergedSlotModels || mergedSlotModels.length === 0) return slot; + return { + ...slot, + modelSegments: partitionModelSegments(mergedSlotModels, modelColorMap, { + maxMain: 5, + minSharePct: 1.5, + }), + }; + }); + trendChart.update(enrichedTrendSeries); + + // 3. 同步热门模型列表(名称后带专属颜色圆点 + 4 段条按总占比缩放长度) patchKeyedList(modelsListEl, models, { keyFn: (m) => m.displayText || m.label || m.shortName, - sigFn: (m) => - `${localeSig}:${m.displayText}:${m.displayTitle}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`, + sigFn: (m) => { + const seed = getCanonicalModelColorSeed(m); + const color = modelColorMap.get(seed) || resolveDeterministicModelColor(seed); + return `${localeSig}:${m.displayText}:${m.displayTitle}:${color}:${m.totalTokens}:${m.inputTokens}:${m.cacheReadTokens}:${m.responseTokens}:${m.thinkingTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`; + }, createRow: createBreakdownItemRow, - updateRow: (refs, m) => + updateRow: (refs, m) => { + const seed = getCanonicalModelColorSeed(m); + const color = modelColorMap.get(seed) || resolveDeterministicModelColor(seed); updateBreakdownItemRow( refs, { ...m, label: m.displayText, title: m.displayTitle }, modelsTotalTok, - true - ), + color + ); + }, }); - // 4. 同步数据来源列表 - const sources = cons.sourcesBreakdown || []; - const sourcesTotalTok = sources.reduce((s, x) => s + Number(x.totalTokens || 0), 0); - patchKeyedList(sourcesListEl, sources, { + // 4. 同步客户端来源列表(长尾合并分段配色 + 右侧总调用数 + 悬停进度条弹出明细浮层) + patchKeyedList(sourcesListEl, sourcesWithModels, { keyFn: (s) => s.name, - sigFn: (s) => `${localeSig}:${s.name}:${s.totalTokens}:${s.costUsd}:${s.unpricedCalls}:${s.calls}:${sourcesTotalTok}`, - createRow: createBreakdownItemRow, - updateRow: (refs, s) => updateBreakdownItemRow(refs, s, sourcesTotalTok, true), + sigFn: (s) => { + const modelsSig = s.mergedModels + .map((m) => { + const seed = getCanonicalModelColorSeed(m); + return `${m.displayText}:${m.totalTokens}:${m.calls}:${modelColorMap.get(seed) || ''}`; + }) + .join('|'); + return `${localeSig}:${s.name}:${s.totalTokens}:${s.costUsd}:${s.unpricedCalls}:${s.calls}:${sourcesTotalTok}:${modelsSig}`; + }, + createRow: createSourceBreakdownRow, + updateRow: (refs, s) => updateSourceBreakdownRow(refs, s, sourcesTotalTok, modelColorMap), }); - // 5. 同步 12 个月垂直堆叠柱状图(相对于年度峰值月缩放柱高,最低保留 8% 可视高度) + // 5. 同步 12 个月垂直堆叠柱状图(按模型配色堆叠 + 长尾合并 + 悬停弹出明细浮层) patchText(monthlyYearBadge, String(monthlyYear)); - const monthlySeries = cons.monthlySeries || []; const maxMonthTokens = Math.max( 1, ...monthlySeries.map((m) => Number(m.totalTokens || 0)) @@ -17994,10 +18648,12 @@ const ConsumptionView = defineComponent({ for (let i = 0; i < 12; i++) { const col = monthlyCols[i]; - const m = monthlySeries[i] || { totalTokens: 0, costUsd: 0 }; + const m = monthlySeries[i] || { totalTokens: 0, costUsd: 0, calls: 0 }; const mTot = Number(m.totalTokens || 0); + const mCalls = Number(m.calls || 0); const hasData = mTot > 0; + patchClasses(col.el, { 'is-interactive': hasData || mCalls > 0 }); patchClasses(col.monthLabel, { 'is-current': i === currentMonthIdx }); patchAttr(col.stackWrap, 'hidden', !hasData); patchAttr(col.zeroDot, 'hidden', hasData); @@ -18005,29 +18661,63 @@ const ConsumptionView = defineComponent({ if (!hasData) { patchText(col.costText, ''); patchText(col.tokText, ''); + col.colState.hoverPayload = null; + patchKeyedList(col.stackWrap, [], { + keyFn: (x) => x.key, + sigFn: (x) => x.key, + createRow: createMonthModelSegment, + updateRow: () => {}, + }); } else { const cVal = Number(m.costUsd || 0); + const isMonthUnpriced = + mCalls > 0 && Number(m.unpricedCalls || 0) >= mCalls && !(cVal > 0); patchText( col.costText, - cVal >= 10 ? `$${Math.round(cVal)}` : `$${cVal.toFixed(2)}` + isMonthUnpriced ? '—' : cVal >= 10 ? `$${Math.round(cVal)}` : `$${cVal.toFixed(2)}` ); patchText(col.tokText, formatTokensPrecise(mTot)); const totalHeightPct = Math.max(8, Math.min(100, (mTot / maxMonthTokens) * 100)); patchStyleVar(col.stackWrap, '--bar-h', `${totalHeightPct.toFixed(1)}%`); - const inPctM = (Number(m.inputTokens || 0) / mTot) * 100; - const cachePctM = (Number(m.cacheReadTokens || 0) / mTot) * 100; - const outPctM = (Number(m.responseTokens || 0) / mTot) * 100; - const thinkPctM = (Number(m.thinkingTokens || 0) / mTot) * 100; + const monthModels = monthsMergedModels[i] || []; + const barPartitioned = partitionModelSegments(monthModels, modelColorMap, { + maxMain: 5, + minSharePct: 1.5, + }); + // 垂直柱状图底端放主力模型、顶端叠放小占比及「其他」,视觉重心稳定 + const verticalSegments = + barPartitioned.length > 0 + ? [...barPartitioned].reverse() + : [{ key: '__month_fallback__', pct: 100, color: 'var(--accent-primary)' }]; - patchStyleVar(col.barIn, '--seg-h', `${inPctM.toFixed(1)}%`); - patchStyleVar(col.barCache, '--seg-h', `${cachePctM.toFixed(1)}%`); - patchStyleVar(col.barOut, '--seg-h', `${outPctM.toFixed(1)}%`); - patchStyleVar(col.barThink, '--seg-h', `${thinkPctM.toFixed(1)}%`); + patchKeyedList(col.stackWrap, verticalSegments, { + keyFn: (seg) => seg.key, + sigFn: (seg) => `${seg.key}:${seg.pct.toFixed(2)}:${seg.color}`, + createRow: createMonthModelSegment, + updateRow: (segRefs, seg) => { + patchStyleVar(segRefs.segEl, '--seg-h', `${seg.pct.toFixed(2)}%`); + patchStyleVar(segRefs.segEl, '--seg-color', seg.color); + }, + }); + + col.colState.hoverPayload = { + title: t('cons.monthFullLabel', { year: monthlyYear, m: i + 1 }), + calls: mCalls, + totalTokens: mTot, + costText: formatUsd(isMonthUnpriced ? null : cVal, { + precise: cVal > 0 && cVal < 0.1, + }), + segments: barPartitioned, + }; } } + if (activeHoverTargetEl && activeHoverTargetEl.isConnected === false) { + hideBreakdownPopover(); + } + viewScrollbar.refresh(); } @@ -18050,6 +18740,7 @@ const ConsumptionView = defineComponent({ (slice) => { latestSlice = slice; if (getVisibleMonitorView() !== 'consumption') { + hideBreakdownPopover(); isDirty = true; return; } @@ -18061,7 +18752,11 @@ const ConsumptionView = defineComponent({ const unsubView = uiStore.subscribe( getVisibleMonitorView, (activeView) => { - if (activeView === 'consumption' && isDirty) { + if (activeView !== 'consumption') { + hideBreakdownPopover(); + return; + } + if (isDirty) { isDirty = false; if (latestSlice) { renderConsumptionData(latestSlice); @@ -18087,14 +18782,12 @@ const ConsumptionView = defineComponent({ patchText(trendTitleSpan, t('cons.trendTitle')); patchText(modelsTitleSpan, t('cons.topModels')); patchText(sourcesTitleSpan, t('cons.clientSources')); + patchText(sourcesHoverHint, t('cons.hoverModelsHint')); patchText(monthlyTitleSpan, t('cons.monthlyTitle')); + patchText(monthlyHoverHint, t('cons.hoverModelsHint')); for (let i = 0; i < 12; i++) { patchText(monthlyCols[i].monthLabel, t('cons.monthLabel', { m: i + 1 })); } - patchText(legInputSpan, t('cons.legInput')); - patchText(legCacheSpan, t('cons.legCache')); - patchText(legOutputSpan, t('cons.legOutput')); - patchText(legThinkingSpan, t('cons.legThinking')); } const unsubI18n = i18nStore.subscribe( @@ -18111,6 +18804,7 @@ const ConsumptionView = defineComponent({ ); onCleanup(() => { + hideBreakdownPopover(); unsub(); unsubView(); unsubI18n(); @@ -18122,8 +18816,8 @@ const ConsumptionView = defineComponent({ }); return { - el: viewScrollbar.el, - refs: { timeFilterSwitch, startPicker, endPicker, viewScrollbar }, + el: rootEl, + refs: { timeFilterSwitch, startPicker, endPicker, viewScrollbar, breakdownPopoverEl }, }; }, }); diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs index 2cf9c5b..308dd3f 100644 --- a/sidecars/panel/backend/usage-aggregator.mjs +++ b/sidecars/panel/backend/usage-aggregator.mjs @@ -546,6 +546,8 @@ export function aggregateMultiWindowUsage({ thinkingTokens: 0, totalTokens: 0, costUsd: 0, + unpricedCalls: 0, + perModelStats: new Map(), })); const SOURCE_LABELS = { @@ -692,6 +694,7 @@ export function aggregateMultiWindowUsage({ mBucket.totalTokens += stepTotalTokens; mBucket.costUsd += resolvedCost; mBucket.unpricedCalls = (mBucket.unpricedCalls || 0) + unpriced; + accumulateStepIntoModelMap(mBucket.perModelStats, st, mInfo, stepCost); } } @@ -757,6 +760,8 @@ export function aggregateMultiWindowUsage({ outputTokens: outTok, costUsd: resolvedCost, unpricedCalls: unpriced, + mInfo, + responseModel: st.responseModel || '', }); } @@ -770,6 +775,7 @@ export function aggregateMultiWindowUsage({ thinkingTokens: 0, totalTokens: 0, costUsd: 0, + perModelStats: new Map(), }); } const sAgg = perSourceStats.get(srcKey); @@ -781,15 +787,20 @@ export function aggregateMultiWindowUsage({ sAgg.totalTokens += stepTotalTokens; sAgg.costUsd += resolvedCost; sAgg.unpricedCalls = (sAgg.unpricedCalls || 0) + unpriced; + accumulateStepIntoModelMap(sAgg.perModelStats, st, mInfo, stepCost); accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost); } } } - for (const mBucket of monthlySeries) { - mBucket.costUsd = +mBucket.costUsd.toFixed(4); - } + const finalizedMonthlySeries = monthlySeries.map( + ({ perModelStats: monthModelMap, ...mBucket }) => ({ + ...mBucket, + costUsd: +mBucket.costUsd.toFixed(4), + models: finalizeModelBreakdownMap(monthModelMap), + }) + ); // 构建当前选定时间窗口的自适应自然整点/整日趋势序列 (trendSeries) const trend = planUsageTrend(selectedWindow, nowMs, earliestSelectedStepMs, latestSelectedStepMs); @@ -940,9 +951,62 @@ export function aggregateMultiWindowUsage({ bucket.costUsd += item.costUsd; bucket.unpricedCalls = (bucket.unpricedCalls || 0) + item.unpricedCalls; bucket.calls += 1; + + if (item.mInfo && item.tokens > 0) { + bucket.perModelStats ??= new Map(); + const mInfo = item.mInfo; + const modelGroupKey = mInfo.baseLabel || mInfo.label; + let bModel = bucket.perModelStats.get(modelGroupKey); + if (!bModel) { + bModel = { + label: modelGroupKey, + shortName: mInfo.shortName, + fallbackModelId: + mInfo.modelId && mInfo.modelId !== 'unknown' + ? formatUpstreamModelId(mInfo.modelId, mInfo) + : '', + upstreamModelCounts: new Map(), + family: mInfo.family, + calls: 0, + totalTokens: 0, + costUsd: 0, + unpricedCalls: 0, + }; + bucket.perModelStats.set(modelGroupKey, bModel); + } + if (item.responseModel) { + const formattedResp = formatUpstreamModelId(item.responseModel, mInfo); + bModel.upstreamModelCounts.set( + formattedResp, + (bModel.upstreamModelCounts.get(formattedResp) || 0) + 1 + ); + } + bModel.calls += 1; + bModel.totalTokens += item.tokens; + bModel.costUsd += item.costUsd; + bModel.unpricedCalls += item.unpricedCalls || 0; + } } for (const b of trendSeries) { b.costUsd = +b.costUsd.toFixed(4); + if (b.perModelStats) { + b.models = Array.from(b.perModelStats.values()) + .sort((a, c) => c.totalTokens - a.totalTokens || c.calls - a.calls) + .map(({ upstreamModelCounts, fallbackModelId, ...m }) => { + const sortedUpstream = Array.from(upstreamModelCounts.entries()) + .sort((a, c) => c[1] - a[1]) + .map(([name]) => name); + const primaryUpstream = + sortedUpstream.length > 0 ? sortedUpstream[0] : fallbackModelId || m.shortName || m.label; + return { + ...m, + upstreamName: primaryUpstream, + upstreamModels: sortedUpstream, + costUsd: +m.costUsd.toFixed(6), + }; + }); + delete b.perModelStats; + } } } @@ -960,9 +1024,10 @@ export function aggregateMultiWindowUsage({ const sourcesBreakdown = Array.from(perSourceStats.values()) .filter((s) => s.totalTokens > 0 || s.calls > 0) - .map((s) => ({ + .map(({ perModelStats: sourceModelMap, ...s }) => ({ ...s, costUsd: +s.costUsd.toFixed(2), + models: finalizeModelBreakdownMap(sourceModelMap), })) .sort((a, b) => b.totalTokens - a.totalTokens || b.calls - a.calls); @@ -1019,7 +1084,7 @@ export function aggregateMultiWindowUsage({ trendSeries, sourcesBreakdown, currentYear, - monthlySeries, + monthlySeries: finalizedMonthlySeries, todayBucket, weekBucket, quotaWeekBucket: finalizedQuotaWeekBucket, diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 733e696..0dffd36 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/charts/TrendAreaChart.js b/sidecars/panel/src/components/charts/TrendAreaChart.js index 0acbfa2..6c46644 100644 --- a/sidecars/panel/src/components/charts/TrendAreaChart.js +++ b/sidecars/panel/src/components/charts/TrendAreaChart.js @@ -6,7 +6,14 @@ * 3. 两种模式共享自适应防溢出的悬浮详情卡片(精确日期/小时区间、Token 拆分、费用与调用次数)。 */ -import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js'; +import { + h, + patchAttr, + patchClasses, + patchKeyedList, + patchStyleVar, + patchText, +} from '../../core/domPatch.js'; import { formatTokensPrecise, formatUsd } from '../../core/formatters.js'; import { SVG_NS } from '../../icons/SvgIcon.js'; import { getEffectiveLocale, t } from '../../i18n/index.js'; @@ -196,9 +203,9 @@ function buildHeatmapMonthTicks(slots, firstDow, totalWeeks) { */ export function createTrendAreaChart() { const DEFAULT_VIEW_W = 460; - const VIEW_H = 120; - const TOP_Y = 24; - const BOTTOM_Y = 102; + const VIEW_H = 184; + const TOP_Y = 26; + const BOTTOM_Y = 164; const SPAN_Y = BOTTOM_Y - TOP_Y; let viewW = DEFAULT_VIEW_W; @@ -243,7 +250,12 @@ export function createTrendAreaChart() { const hGridGroup = document.createElementNS(SVG_NS, 'g'); hGridGroup.setAttribute('class', 'trend-grid'); const hGridLines = []; - for (const y of [TOP_Y, Math.round((TOP_Y + BOTTOM_Y) / 2), BOTTOM_Y]) { + for (const y of [ + TOP_Y, + Math.round(TOP_Y + SPAN_Y / 3), + Math.round(TOP_Y + (SPAN_Y * 2) / 3), + BOTTOM_Y, + ]) { const line = document.createElementNS(SVG_NS, 'line'); line.setAttribute('x1', '0'); line.setAttribute('y1', String(y)); @@ -292,12 +304,28 @@ export function createTrendAreaChart() { const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0' }); - // 共享悬停详情浮层卡片(曲线图与热力格子图共用) + function createTooltipModelRow() { + const dotEl = h('span', { className: 'dot-swatch cons-model-dot' }); + const nameEl = h('span', { className: 'cons-pop-model-name' }); + const tokEl = h('span', { className: 'cons-pop-model-tok' }); + const pctEl = h('strong', { className: 'cons-pop-model-pct' }); + const rowEl = h('div', { className: 'cons-pop-model-row' }, [ + h('span', { className: 'cons-pop-model-left' }, [dotEl, nameEl]), + h('span', { className: 'cons-pop-model-right text-mono' }, [tokEl, pctEl]), + ]); + return { + el: rowEl, + refs: { rowEl, dotEl, nameEl, tokEl, pctEl }, + }; + } + + // 共享悬停详情浮层卡片(曲线图与热力格子图共用,含该时段分模型占比明细) const tipTimeEl = h('span', { className: 'trend-tip-time text-mono' }); const tipCallsEl = h('span', { className: 'trend-tip-calls text-mono' }); const tipTokensEl = h('strong', { className: 'trend-tip-tokens text-mono' }); const tipCostEl = h('span', { className: 'trend-tip-cost text-mono' }); const tipSubEl = h('div', { className: 'trend-tip-sub text-mono', hidden: true }); + const tipModelsEl = h('div', { className: 'cons-pop-models', hidden: true }); const tooltipEl = h( 'div', @@ -306,6 +334,7 @@ export function createTrendAreaChart() { h('div', { className: 'trend-tip-head' }, [tipTimeEl, tipCallsEl]), h('div', { className: 'trend-tip-main' }, [tipTokensEl, tipCostEl]), tipSubEl, + tipModelsEl, ] ); @@ -407,6 +436,21 @@ export function createTrendAreaChart() { }) ); } + + const modelSegs = Array.isArray(slot.modelSegments) ? slot.modelSegments : []; + patchAttr(tipModelsEl, 'hidden', modelSegs.length === 0); + patchKeyedList(tipModelsEl, modelSegs, { + keyFn: (r) => r.key, + sigFn: (r) => `${r.key}:${r.label}:${r.color}:${r.tokText}:${r.pctText}:${r.isOther}`, + createRow: createTooltipModelRow, + updateRow: (rRefs, r) => { + patchClasses(rRefs.rowEl, { 'is-other': Boolean(r.isOther) }); + patchStyleVar(rRefs.dotEl, '--dot-color', r.color); + patchText(rRefs.nameEl, r.label); + patchText(rRefs.tokEl, r.tokText); + patchText(rRefs.pctEl, r.pctText); + }, + }); } function showLineHoverAtIndex(idx) { @@ -427,7 +471,11 @@ export function createTrendAreaChart() { patchAttr(hoverDot, 'cy', pt.y.toFixed(1)); patchAttr(peakPill, 'hidden', true); - patchClasses(tooltipEl, { 'is-hm-bottom': false, 'is-hm-top': false }); + patchClasses(tooltipEl, { + 'is-hm-bottom': false, + 'is-hm-top': false, + 'is-line-low': pt.y < Math.round((TOP_Y + BOTTOM_Y) / 2), + }); patchAttr(tooltipEl, 'hidden', false); populateTooltipContent(slot); @@ -462,10 +510,11 @@ export function createTrendAreaChart() { const row = Number(targetCell.getAttribute('data-hm-row') || 0); const col = Number(targetCell.getAttribute('data-hm-col') || 0); - // 上半区(周一~周四)浮层停靠底部,下半区(周五~周日)停靠顶部,互不遮挡被悬停格子且永不越界裁剪 + // 上半区(周一~周四)浮层停靠热力图下方,下半区(周五~周日)停靠热力图上方,互不遮挡被悬停格子且永不越界裁剪 patchClasses(tooltipEl, { 'is-hm-bottom': row <= 3, 'is-hm-top': row > 3, + 'is-line-low': false, }); patchAttr(tooltipEl, 'hidden', false); populateTooltipContent(slot); @@ -494,7 +543,7 @@ export function createTrendAreaChart() { patchAttr(hoverLine, 'hidden', true); patchAttr(hoverDot, 'hidden', true); patchAttr(tooltipEl, 'hidden', true); - patchClasses(tooltipEl, { 'is-hm-bottom': false, 'is-hm-top': false }); + patchClasses(tooltipEl, { 'is-hm-bottom': false, 'is-hm-top': false, 'is-line-low': false }); if (!currentIsHeatmap) { patchAttr(peakPill, 'hidden', false); } @@ -776,12 +825,18 @@ export function createTrendAreaChart() { const sig = `${locale}|${useHeatmap ? 'hm' : `line:${viewW}`}|` + slots - .map( - (s) => - `${s?.startMs || ''}:${s?.label || ''}:${s?.fullLabel || ''}:${safeSlotTokens(s?.tokens)}:${Number(s?.costUsd || 0)}:${Number(s?.calls || 0)}` - ) + .map((s) => { + const mSig = Array.isArray(s?.modelSegments) + ? s.modelSegments.map((m) => `${m.key}:${m.color}:${m.pctText}`).join(',') + : ''; + return `${s?.startMs || ''}:${s?.label || ''}:${s?.fullLabel || ''}:${safeSlotTokens(s?.tokens)}:${Number(s?.costUsd || 0)}:${Number(s?.calls || 0)}:${mSig}`; + }) .join('|'); + if (hoveredIdx >= 0 && hoveredIdx < slots.length && !tooltipEl.hasAttribute('hidden')) { + populateTooltipContent(slots[hoveredIdx]); + } + if (useHeatmap) { currentPts = []; if (sig !== lastRenderSig) { diff --git a/sidecars/panel/src/components/ui/FourSegmentBar.js b/sidecars/panel/src/components/ui/FourSegmentBar.js index fb23aa1..31f7566 100644 --- a/sidecars/panel/src/components/ui/FourSegmentBar.js +++ b/sidecars/panel/src/components/ui/FourSegmentBar.js @@ -33,14 +33,30 @@ export function createFourSegmentBar() { ]); /** - * 根据四类 Token 数量重新计算并写入各分段百分比宽度。 + * 根据四类 Token 数量与整体行宽占比系数 (`scaleRatio`,默认 `1` 占满 100%) 重新计算并写入各分段百分比宽度。 */ - function update({ inputTokens = 0, cacheReadTokens = 0, responseTokens = 0, thinkingTokens = 0 }) { - const total = Math.max(1, inputTokens + cacheReadTokens + responseTokens + thinkingTokens); - patchStyleVar(segInput, '--seg-w', `${((inputTokens / total) * 100).toFixed(2)}%`); - patchStyleVar(segCached, '--seg-w', `${((cacheReadTokens / total) * 100).toFixed(2)}%`); - patchStyleVar(segOutput, '--seg-w', `${((responseTokens / total) * 100).toFixed(2)}%`); - patchStyleVar(segThinking, '--seg-w', `${((thinkingTokens / total) * 100).toFixed(2)}%`); + function update({ + inputTokens = 0, + cacheReadTokens = 0, + responseTokens = 0, + thinkingTokens = 0, + scaleRatio = 1, + }) { + const sum = inputTokens + cacheReadTokens + responseTokens + thinkingTokens; + const clampedRatio = Number.isFinite(Number(scaleRatio)) + ? Math.min(1, Math.max(0, Number(scaleRatio))) + : 1; + if (sum <= 0 || clampedRatio <= 0) { + patchStyleVar(segInput, '--seg-w', '0%'); + patchStyleVar(segCached, '--seg-w', '0%'); + patchStyleVar(segOutput, '--seg-w', '0%'); + patchStyleVar(segThinking, '--seg-w', '0%'); + return; + } + patchStyleVar(segInput, '--seg-w', `${((inputTokens / sum) * 100 * clampedRatio).toFixed(2)}%`); + patchStyleVar(segCached, '--seg-w', `${((cacheReadTokens / sum) * 100 * clampedRatio).toFixed(2)}%`); + patchStyleVar(segOutput, '--seg-w', `${((responseTokens / sum) * 100 * clampedRatio).toFixed(2)}%`); + patchStyleVar(segThinking, '--seg-w', `${((thinkingTokens / sum) * 100 * clampedRatio).toFixed(2)}%`); } return { el, update }; diff --git a/sidecars/panel/src/core/formatters.js b/sidecars/panel/src/core/formatters.js index 32c1faa..f0287ae 100644 --- a/sidecars/panel/src/core/formatters.js +++ b/sidecars/panel/src/core/formatters.js @@ -676,3 +676,162 @@ export function formatLiveActivityDetail(act) { } return String(act.detail || ''); } + +/** + * 20 色感知均匀色环(无特定模型绑定,兼顾亮/暗背景可读性,彻底消除标准 HSL 绿色/暗红区过度聚集撞色)。 + * 每项为 `[hue, saturationPct, lightnessPct]`。 + */ +const PERCEPTUAL_MODEL_COLOR_RING = [ + [217, 82, 53], // Royal Blue + [14, 80, 52], // Coral / Vermilion + [162, 74, 41], // Teal / Jade + [272, 74, 58], // Vivid Violet + [36, 88, 47], // Rich Amber + [336, 78, 53], // Rose / Raspberry + [193, 84, 43], // Cerulean / Cyan + [138, 66, 41], // Emerald Green + [246, 74, 60], // Indigo + [25, 86, 50], // Tangerine Orange + [306, 70, 52], // Magenta / Orchid + [177, 76, 39], // Deep Seafoam + [355, 76, 54], // Crimson Red + [205, 80, 48], // Ocean Blue + [45, 88, 44], // Warm Gold + [288, 68, 55], // Amethyst Purple + [102, 60, 42], // Leaf Green + [230, 76, 57], // Cobalt Blue + [322, 74, 51], // Berry Pink + [185, 72, 46], // Turquoise +]; + +/** + * 提取跨平台、跨语言、同屏三栏(模型排行 / 客户端来源 / 月度统计)严格一致的模型颜色种子字符串。 + * + * 优先取单模型稳定 `sourceLabels[0]`;若多个外层槽位已在当前显示策略下合并(如 `4-argon`), + * 则以规范化 `displayText` 为种子,确保跨客户端与跨月份聚合子集不同时依然映射至完全相同的颜色。 + * + * @param {object|string|null|undefined} model + * @returns {string} + */ +export function getCanonicalModelColorSeed(model) { + if (typeof model === 'string') { + return model.trim().toLowerCase().replace(/\s+/g, ' '); + } + if (!model || typeof model !== 'object') return ''; + if ( + Number(model.mergedCount || 0) <= 1 && + Array.isArray(model.sourceLabels) && + model.sourceLabels.length === 1 && + model.sourceLabels[0] + ) { + return String(model.sourceLabels[0]).trim().toLowerCase().replace(/\s+/g, ' '); + } + const raw = + model.displayText || + model.label || + model.modelId || + model.baseItem?.modelId || + model.shortName || + model.name || + ''; + return String(raw).trim().toLowerCase().replace(/\s+/g, ' '); +} + +function hashModelSeed32(str) { + let h = 0x811c9dc5; + for (let i = 0; i < str.length; i++) { + h ^= str.charCodeAt(i); + h = Math.imul(h, 0x01000193); + } + h ^= h >>> 16; + h = Math.imul(h, 0x85ebca6b); + h ^= h >>> 13; + h = Math.imul(h, 0xc2b2ae35); + h ^= h >>> 16; + return h >>> 0; +} + +function formatRingSlotHsl(slotIdx, shiftLight = 0) { + const [hue, sat, light] = PERCEPTUAL_MODEL_COLOR_RING[slotIdx % PERCEPTUAL_MODEL_COLOR_RING.length]; + const clampedLight = Math.min(66, Math.max(34, light + shiftLight)); + return `hsl(${hue} ${sat}% ${clampedLight}%)`; +} + +/** + * 基于模型标识通过 32 位雪崩哈希映射至 20 色感知均匀色环,确保跨电脑同模型同色且无需硬编码颜色表。 + * + * @param {object|string|null|undefined} seedOrModel + * @returns {string} + */ +export function resolveDeterministicModelColor(seedOrModel) { + const seed = getCanonicalModelColorSeed(seedOrModel); + if (!seed) return 'var(--accent-primary)'; + const h = hashModelSeed32(seed); + return formatRingSlotHsl(h % PERCEPTUAL_MODEL_COLOR_RING.length); +} + +/** + * 为一组模型构建确定性颜色映射表(双遍固有槽位保护): + * 1. 所有无槽位冲突的模型 100% 保持其纯哈希固有色,不受长尾模型增减影响; + * 2. 仅当同屏两个模型恰好落入同一色环槽位时,按严格字典序以互质步长 `+7` 优先探查未被任何模型占用的空闲槽位。 + * + * @param {Array} [models=[]] + * @returns {Map} `canonicalSeed -> hsl(...)` + */ +export function buildDeterministicModelColorMap(models = []) { + const ringLen = PERCEPTUAL_MODEL_COLOR_RING.length; + const uniqueSeeds = Array.from( + new Set( + (Array.isArray(models) ? models : []) + .map((m) => getCanonicalModelColorSeed(m)) + .filter(Boolean) + ) + ).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); + + const naturalSlotCounts = new Map(); + for (const seed of uniqueSeeds) { + const nat = hashModelSeed32(seed) % ringLen; + naturalSlotCounts.set(nat, (naturalSlotCounts.get(nat) || 0) + 1); + } + + const usedSlots = new Set(); + const colorMap = new Map(); + + for (const seed of uniqueSeeds) { + const h = hashModelSeed32(seed); + const nat = h % ringLen; + if (!usedSlots.has(nat)) { + usedSlots.add(nat); + colorMap.set(seed, formatRingSlotHsl(nat)); + continue; + } + + let picked = -1; + for (let k = 1; k < ringLen; k++) { + const cand = (nat + k * 7) % ringLen; + if (!usedSlots.has(cand) && !naturalSlotCounts.has(cand)) { + picked = cand; + break; + } + } + if (picked < 0) { + for (let k = 1; k < ringLen; k++) { + const cand = (nat + k * 7) % ringLen; + if (!usedSlots.has(cand)) { + picked = cand; + break; + } + } + } + + if (picked >= 0) { + usedSlots.add(picked); + colorMap.set(seed, formatRingSlotHsl(picked)); + } else { + const shift = (h >>> 8) & 1 ? 9 : -8; + colorMap.set(seed, formatRingSlotHsl(nat, shift)); + } + } + + return colorMap; +} diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index e037e47..9045460 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -238,6 +238,9 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'cons.clientSources': 'Client Sources', 'cons.monthlyTitle': 'Monthly Breakdown', 'cons.monthLabel': 'M{m}', + 'cons.monthFullLabel': 'M{m}, {year}', + 'cons.hoverModelsHint': 'Hover for models', + 'cons.otherModelsCount': 'Others ({count})', 'cons.legInput': 'Input', 'cons.legCache': 'Cache', 'cons.legOutput': 'Output', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 08a9299..74346e1 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -238,6 +238,9 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'cons.clientSources': '客户端来源', 'cons.monthlyTitle': '月度统计', 'cons.monthLabel': '{m}月', + 'cons.monthFullLabel': '{year}年 {m}月', + 'cons.hoverModelsHint': '悬停查看模型', + 'cons.otherModelsCount': '其他 ({count})', 'cons.legInput': '输入', 'cons.legCache': '缓存', 'cons.legOutput': '输出', diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index 9d647b1..df5612c 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -538,6 +538,26 @@ export function isEquivalentTelemetry(prev, next) { if (pAcct?.unpricedCalls !== nAcct?.unpricedCalls) return false; // 6. 比对历史趋势时间分桶序列与年度分月序列 + const areModelSlicesEqual = (pList, nList) => { + const a = pList || []; + const b = nList || []; + if (a.length !== b.length) return false; + for (let k = 0; k < a.length; k++) { + if ( + a[k]?.label !== b[k]?.label || + a[k]?.shortName !== b[k]?.shortName || + a[k]?.upstreamName !== b[k]?.upstreamName || + a[k]?.costUsd !== b[k]?.costUsd || + a[k]?.unpricedCalls !== b[k]?.unpricedCalls || + a[k]?.totalTokens !== b[k]?.totalTokens || + a[k]?.calls !== b[k]?.calls + ) { + return false; + } + } + return true; + }; + const pTrend = prev.consumption?.trendSeries || []; const nTrend = next.consumption?.trendSeries || []; if (pTrend.length !== nTrend.length) return false; @@ -546,12 +566,14 @@ export function isEquivalentTelemetry(prev, next) { pTrend[i]?.tokens !== nTrend[i]?.tokens || pTrend[i]?.calls !== nTrend[i]?.calls || pTrend[i]?.label !== nTrend[i]?.label || - pTrend[i]?.fullLabel !== nTrend[i]?.fullLabel + pTrend[i]?.fullLabel !== nTrend[i]?.fullLabel || + !areModelSlicesEqual(pTrend[i]?.models, nTrend[i]?.models) ) { return false; } } if (prev.consumption?.monthlyYear !== next.consumption?.monthlyYear) return false; + const pMonthly = prev.consumption?.monthlySeries || []; const nMonthly = next.consumption?.monthlySeries || []; if (pMonthly.length !== nMonthly.length) return false; @@ -559,28 +581,16 @@ export function isEquivalentTelemetry(prev, next) { if ( pMonthly[i]?.totalTokens !== nMonthly[i]?.totalTokens || pMonthly[i]?.costUsd !== nMonthly[i]?.costUsd || - pMonthly[i]?.calls !== nMonthly[i]?.calls + pMonthly[i]?.calls !== nMonthly[i]?.calls || + !areModelSlicesEqual(pMonthly[i]?.models, nMonthly[i]?.models) ) { return false; } } // 7. 比对按模型汇总明细与数据来源汇总明细 - const pModels = prev.modelBreakdown || []; - const nModels = next.modelBreakdown || []; - if (pModels.length !== nModels.length) return false; - for (let i = 0; i < pModels.length; i++) { - if ( - pModels[i]?.label !== nModels[i]?.label || - pModels[i]?.shortName !== nModels[i]?.shortName || - pModels[i]?.upstreamName !== nModels[i]?.upstreamName || - pModels[i]?.costUsd !== nModels[i]?.costUsd || - pModels[i]?.unpricedCalls !== nModels[i]?.unpricedCalls || - pModels[i]?.totalTokens !== nModels[i]?.totalTokens || - pModels[i]?.calls !== nModels[i]?.calls - ) { - return false; - } + if (!areModelSlicesEqual(prev.modelBreakdown, next.modelBreakdown)) { + return false; } const pSources = prev.consumption?.sourcesBreakdown || []; @@ -592,7 +602,8 @@ export function isEquivalentTelemetry(prev, next) { pSources[i]?.costUsd !== nSources[i]?.costUsd || pSources[i]?.unpricedCalls !== nSources[i]?.unpricedCalls || pSources[i]?.totalTokens !== nSources[i]?.totalTokens || - pSources[i]?.calls !== nSources[i]?.calls + pSources[i]?.calls !== nSources[i]?.calls || + !areModelSlicesEqual(pSources[i]?.models, nSources[i]?.models) ) { return false; } diff --git a/sidecars/panel/src/styles/views-consumption.css b/sidecars/panel/src/styles/views-consumption.css index cb49807..beef0b5 100644 --- a/sidecars/panel/src/styles/views-consumption.css +++ b/sidecars/panel/src/styles/views-consumption.css @@ -157,15 +157,28 @@ flex-shrink: 0; } +:root, +:host { + --cons-other-seg: color-mix(in srgb, var(--text-secondary) 46%, var(--surface-panel)); +} + .dot-swatch.seg-input { background: var(--ctx-input); } .dot-swatch.seg-cached { background: var(--ctx-cached); } .dot-swatch.seg-output { background: var(--ctx-output); } .dot-swatch.seg-thinking { background: var(--ctx-thinking); } +.dot-swatch.cons-model-dot { background: var(--dot-color, var(--accent-primary)); } + +.progress-seg.cons-model-seg, +.month-seg.cons-model-seg { + background-color: var(--seg-color, var(--accent-primary)); +} /* --- 3. 热门模型与数据来源行头部对齐 (Popular Models & Sources Row Header) --- */ .cons-row-title { display: inline-flex; align-items: center; + gap: 6px; + min-width: 0; min-height: calc(20px * var(--ui-font-scale, 1)); line-height: 1.3; font-size: var(--fs-base); @@ -173,6 +186,18 @@ color: var(--text-primary); } +.cons-row-title-text { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.cons-title-model-dot { + width: 7px; + height: 7px; + flex-shrink: 0; +} + .cons-row-metrics { display: inline-flex; align-items: center; @@ -238,7 +263,7 @@ .trend-svg { width: 100%; - height: 120px; + height: 184px; display: block; overflow: visible; } @@ -301,19 +326,19 @@ .trend-tooltip { position: absolute; - top: 0; + top: 2px; left: var(--tip-x, 50%); transform: translateX(var(--tip-shift, -50%)); width: max-content; - min-width: 152px; + min-width: 196px; max-width: min(320px, calc(100% - 8px)); - padding: 5px 9px; + padding: 6px 10px; background: var(--surface-panel); border: 1px solid var(--border-strong); border-radius: var(--radius-sm); - box-shadow: none; + box-shadow: var(--shadow-popover); pointer-events: none; - z-index: 15; + z-index: 25; display: flex; flex-direction: column; gap: 2px; @@ -378,14 +403,19 @@ margin-top: 1px; } +.trend-tooltip.is-line-low { + top: auto; + bottom: 20px; +} + .trend-tooltip.is-hm-top { - top: 0; - bottom: auto; + top: auto; + bottom: calc(100% + 6px); } .trend-tooltip.is-hm-bottom { - top: auto; - bottom: 0; + top: calc(100% + 6px); + bottom: auto; } .trend-x-axis { @@ -426,8 +456,8 @@ .trend-heatmap-stage { display: flex; flex-direction: column; - gap: 6px; - padding-top: 2px; + gap: 8px; + padding-top: 4px; width: 100%; user-select: none; } @@ -435,7 +465,7 @@ .trend-heatmap-body { --hm-weeks: 26; --hm-gap: 2px; - --hm-cell: 9px; + --hm-cell: 12px; display: flex; align-items: flex-start; gap: 4px; @@ -446,9 +476,9 @@ @supports (width: 1cqi) { .trend-heatmap-body { --hm-cell: clamp( - 6.5px, + 11px, calc((100cqi - 18px - (var(--hm-weeks) - 1) * var(--hm-gap)) / var(--hm-weeks)), - 18px + 20px ); } } @@ -620,11 +650,130 @@ margin-left: auto; } +.cons-view-stage { + flex: 1; + min-height: 0; + display: flex; + flex-direction: column; + position: relative; +} + .cons-item-foot strong { color: var(--text-primary); font-weight: 600; } +.cons-source-row { + gap: 5px; +} + +.cons-source-bar-hit { + padding: 5px 0; + margin: -5px 0; + cursor: pointer; +} + +.cons-source-bar-hit:hover .cons-source-model-bar, +.cons-source-bar-hit.is-hovered .cons-source-model-bar { + box-shadow: 0 0 0 1px var(--border-strong); +} + +.cons-source-foot { + justify-content: flex-end; + min-height: 16px; +} + +.month-col.is-interactive { + cursor: pointer; +} + +.month-col.is-interactive:hover .month-stack, +.month-col.is-hovered .month-stack { + box-shadow: 0 0 0 1px var(--text-primary); +} + +.month-col.is-interactive:hover .month-label, +.month-col.is-hovered .month-label { + color: var(--text-primary); + font-weight: 600; +} + +/* --- 共享模型构成悬浮详情卡 (Client Sources & Monthly Breakdown Popover) --- */ +.cons-breakdown-popover { + position: absolute; + left: var(--pop-x, 8px); + top: var(--pop-y, 8px); + width: max-content; + min-width: 196px; + max-width: min(310px, calc(100% - 16px)); + padding: 6px 10px; + background: var(--surface-panel); + border: 1px solid var(--border-strong); + border-radius: var(--radius-sm); + box-shadow: var(--shadow-popover); + pointer-events: none; + z-index: 30; + display: flex; + flex-direction: column; + gap: 3px; +} + +.cons-pop-models { + display: flex; + flex-direction: column; + gap: 3px; + border-top: 1px solid var(--border-hairline); + padding-top: 4px; + margin-top: 2px; +} + +.cons-pop-model-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + font-size: var(--fs-sm); + line-height: 1.3; +} + +.cons-pop-model-left { + display: inline-flex; + align-items: center; + gap: 6px; + min-width: 0; + color: var(--text-primary); +} + +.cons-pop-model-name { + max-width: 156px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.cons-pop-model-row.is-other .cons-pop-model-name { + color: var(--text-secondary); +} + +.cons-pop-model-right { + display: inline-flex; + align-items: baseline; + gap: 8px; + flex-shrink: 0; +} + +.cons-pop-model-tok { + font-size: var(--fs-xs); + color: var(--text-muted); +} + +.cons-pop-model-pct { + min-width: 40px; + text-align: right; + font-weight: 600; + color: var(--text-primary); +} + /* --- 6. 12 个月垂直堆叠柱状图 (12-Month Stacked Bar Chart) --- */ .monthly-grid { display: grid; diff --git a/sidecars/panel/src/views/ConsumptionView.js b/sidecars/panel/src/views/ConsumptionView.js index 759b19a..0ab0618 100644 --- a/sidecars/panel/src/views/ConsumptionView.js +++ b/sidecars/panel/src/views/ConsumptionView.js @@ -19,13 +19,16 @@ import { patchText, } from '../core/domPatch.js'; import { + buildDeterministicModelColorMap, formatCnyApprox, formatDateSpanBadge, formatTokensPrecise, formatUsd, + getCanonicalModelColorSeed, mergeModelsByDisplayName, normalizeModelDisplayMode, normalizeOrchestratorIdDisplayMode, + resolveDeterministicModelColor, } from '../core/formatters.js'; import { scaleBucketsExact } from '../../shared/telemetry-display-rules.mjs'; import { i18nStore, isEnglishLocale, t } from '../i18n/index.js'; @@ -274,86 +277,205 @@ export const ConsumptionView = defineComponent({ // --- Section 4: 客户端来源列表 --- const sourcesTitleSpan = h('span', { className: 'panel-title', text: t('cons.clientSources') }); + const sourcesHoverHint = h('span', { + className: 'text-muted text-mono', + style: 'font-size: var(--fs-sm);', + text: t('cons.hoverModelsHint'), + }); const sourcesListEl = h('div', { className: 'cons-item-list' }); const sourcesPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ sourcesTitleSpan, + sourcesHoverHint, ]), sourcesListEl, ]); - // --- Section 5: 按月细分 (12 个月垂直 4 段堆叠柱状图) --- - const monthlyTitleSpan = h('span', { className: 'panel-title', text: t('cons.monthlyTitle') }); + // --- Section 5: 按月细分 (12 个月垂直按模型配色堆叠柱状图 + 悬停明细浮层) --- + const monthlyTitleSpan = h('span', { text: t('cons.monthlyTitle') }); const monthlyYearBadge = h('span', { className: 'cons-badge text-mono', text: '2026' }); + const monthlyHoverHint = h('span', { + className: 'text-muted text-mono', + style: 'font-size: var(--fs-sm);', + text: t('cons.hoverModelsHint'), + }); + + let activeHoverTargetEl = null; + + function createPopoverModelRow() { + const dotEl = h('span', { className: 'dot-swatch cons-model-dot' }); + const nameEl = h('span', { className: 'cons-pop-model-name' }); + const tokEl = h('span', { className: 'cons-pop-model-tok' }); + const pctEl = h('strong', { className: 'cons-pop-model-pct' }); + const rowEl = h('div', { className: 'cons-pop-model-row' }, [ + h('span', { className: 'cons-pop-model-left' }, [dotEl, nameEl]), + h('span', { className: 'cons-pop-model-right text-mono' }, [tokEl, pctEl]), + ]); + return { + el: rowEl, + refs: { rowEl, dotEl, nameEl, tokEl, pctEl }, + }; + } + + const popTitleEl = h('span', { className: 'trend-tip-time' }); + const popCallsEl = h('span', { className: 'trend-tip-calls text-mono' }); + const popTokensEl = h('strong', { className: 'trend-tip-tokens text-mono' }); + const popCostEl = h('span', { className: 'trend-tip-cost text-mono' }); + const popListEl = h('div', { className: 'cons-pop-models' }); + const breakdownPopoverEl = h( + 'div', + { className: 'cons-breakdown-popover', hidden: true }, + [ + h('div', { className: 'trend-tip-head' }, [popTitleEl, popCallsEl]), + h('div', { className: 'trend-tip-main' }, [popTokensEl, popCostEl]), + popListEl, + ] + ); + + function hideBreakdownPopover() { + if (activeHoverTargetEl) { + patchClasses(activeHoverTargetEl, { 'is-hovered': false }); + activeHoverTargetEl = null; + } + patchAttr(breakdownPopoverEl, 'hidden', true); + } + + function positionBreakdownPopover(anchorEl, pointerClientX = null) { + const rootRect = rootEl.getBoundingClientRect?.() || { + left: 0, + top: 0, + width: 360, + height: 600, + }; + const anchorRect = anchorEl?.getBoundingClientRect?.() || { + left: 0, + top: 0, + bottom: 0, + width: 0, + height: 0, + }; + const tipRect = breakdownPopoverEl.getBoundingClientRect?.() || { + width: 220, + height: 120, + }; + const rootW = rootRect.width > 0 ? rootRect.width : 360; + const rootH = rootRect.height > 0 ? rootRect.height : 600; + const tipW = tipRect.width > 0 ? tipRect.width : 220; + const tipH = tipRect.height > 0 ? tipRect.height : 120; + + const centerX = + Number.isFinite(pointerClientX) && pointerClientX > 0 && rootRect.width > 0 + ? pointerClientX - rootRect.left + : anchorRect.left - rootRect.left + anchorRect.width / 2; + + const maxLeft = Math.max(8, rootW - tipW - 8); + const leftPx = Math.max(8, Math.min(maxLeft, centerX - tipW / 2)); + + const aboveTop = anchorRect.top - rootRect.top - tipH - 8; + const belowTop = anchorRect.bottom - rootRect.top + 8; + const topPx = + aboveTop >= 6 + ? aboveTop + : Math.min(Math.max(6, rootH - tipH - 6), Math.max(6, belowTop)); + + patchStyleVar(breakdownPopoverEl, '--pop-x', `${Math.round(leftPx)}px`); + patchStyleVar(breakdownPopoverEl, '--pop-y', `${Math.round(topPx)}px`); + } + + function showBreakdownPopover(anchorEl, payload, pointerClientX = null) { + if (!payload || !(payload.totalTokens > 0 || payload.calls > 0)) { + hideBreakdownPopover(); + return; + } + if (activeHoverTargetEl && activeHoverTargetEl !== anchorEl) { + patchClasses(activeHoverTargetEl, { 'is-hovered': false }); + } + activeHoverTargetEl = anchorEl; + patchClasses(anchorEl, { 'is-hovered': true }); + + patchText(popTitleEl, payload.title || '—'); + patchText(popCallsEl, t('cons.callsCount', { calls: payload.calls || 0 })); + patchText(popTokensEl, `${formatTokensPrecise(payload.totalTokens || 0)} tok`); + patchText(popCostEl, payload.costText || '$0.00'); + + const rows = Array.isArray(payload.segments) ? payload.segments : []; + patchAttr(popListEl, 'hidden', rows.length === 0); + patchKeyedList(popListEl, rows, { + keyFn: (r) => r.key, + sigFn: (r) => `${r.key}:${r.label}:${r.color}:${r.tokText}:${r.pctText}:${r.isOther}`, + createRow: createPopoverModelRow, + updateRow: (rRefs, r) => { + patchClasses(rRefs.rowEl, { 'is-other': Boolean(r.isOther) }); + patchStyleVar(rRefs.dotEl, '--dot-color', r.color); + patchText(rRefs.nameEl, r.label); + patchText(rRefs.tokEl, r.tokText); + patchText(rRefs.pctEl, r.pctText); + }, + }); + + patchAttr(breakdownPopoverEl, 'hidden', false); + positionBreakdownPopover(anchorEl, pointerClientX); + } + + function createMonthModelSegment() { + const segEl = h('div', { className: 'month-seg cons-model-seg' }); + return { el: segEl, refs: { segEl } }; + } + const monthlyCols = Array.from({ length: 12 }, (_, idx) => { const costText = h('span', { className: 'month-cost text-mono', text: '' }); - const barThink = h('div', { className: 'month-seg seg-thinking' }); - const barOut = h('div', { className: 'month-seg seg-output' }); - const barCache = h('div', { className: 'month-seg seg-cached' }); - const barIn = h('div', { className: 'month-seg seg-input' }); - const stackWrap = h('div', { className: 'month-stack' }, [ - barThink, - barOut, - barCache, - barIn, - ]); + const stackWrap = h('div', { className: 'month-stack' }); const zeroDot = h('span', { className: 'month-zero-dot' }); const monthLabel = h('span', { className: 'month-label', text: t('cons.monthLabel', { m: idx + 1 }) }); const tokText = h('span', { className: 'month-tok text-mono', text: '' }); - const colEl = h('div', { className: 'month-col' }, [ - costText, - h('div', { className: 'month-bar-well' }, [stackWrap, zeroDot]), - monthLabel, - tokText, - ]); + const colState = { hoverPayload: null }; + const colEl = h( + 'div', + { + className: 'month-col', + onMouseEnter: (e) => { + if (colState.hoverPayload) { + showBreakdownPopover(colEl, colState.hoverPayload, null); + } else { + e?.stopPropagation?.(); + } + }, + onMouseLeave: () => { + if (activeHoverTargetEl === colEl) hideBreakdownPopover(); + }, + }, + [ + costText, + h('div', { className: 'month-bar-well' }, [stackWrap, zeroDot]), + monthLabel, + tokText, + ] + ); return { el: colEl, costText, stackWrap, zeroDot, - barThink, - barOut, - barCache, - barIn, monthLabel, tokText, + colState, }; }); - const legInputSpan = h('span', { text: t('cons.legInput') }); - const legCacheSpan = h('span', { text: t('cons.legCache') }); - const legOutputSpan = h('span', { text: t('cons.legOutput') }); - const legThinkingSpan = h('span', { text: t('cons.legThinking') }); - const monthlyPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ - monthlyTitleSpan, - monthlyYearBadge, + h('span', { className: 'panel-title' }, [ + monthlyTitleSpan, + monthlyYearBadge, + ]), + monthlyHoverHint, ]), h( 'div', { className: 'monthly-grid' }, monthlyCols.map((c) => c.el) ), - h('div', { className: 'monthly-legend' }, [ - h('span', { className: 'legend-left' }, [ - h('span', { className: 'dot-swatch seg-input' }), - legInputSpan, - ]), - h('span', { className: 'legend-left' }, [ - h('span', { className: 'dot-swatch seg-cached' }), - legCacheSpan, - ]), - h('span', { className: 'legend-left' }, [ - h('span', { className: 'dot-swatch seg-output' }), - legOutputSpan, - ]), - h('span', { className: 'legend-left' }, [ - h('span', { className: 'dot-swatch seg-thinking' }), - legThinkingSpan, - ]), - ]), ]); const scrollInner = h( @@ -374,12 +496,86 @@ export const ConsumptionView = defineComponent({ contentEl: scrollInner, className: 'view-pane', }); + viewScrollbar.el.addEventListener?.('scroll', hideBreakdownPopover, { passive: true }); + + const rootEl = h('div', { className: 'cons-view-stage' }, [ + viewScrollbar.el, + breakdownPopoverEl, + ]); /** - * 创建热门模型或数据来源的通用单行 DOM 结构(含标题、占比胶囊、总量、费用、4 段条与底部分项脚标)。 + * 将分模型列表收敛为主力模型 + 长尾「其他 (N)」,避免进度条尾部与浮层出现 0.0% 碎屑噪音。 + */ + function partitionModelSegments( + mergedModels, + modelColorMap, + { maxMain = 5, minSharePct = 1.5 } = {} + ) { + if (!Array.isArray(mergedModels) || mergedModels.length === 0) return []; + const sumTok = mergedModels.reduce((sum, m) => sum + Number(m.totalTokens || 0), 0); + const mainModels = []; + const tailModels = []; + + for (let i = 0; i < mergedModels.length; i++) { + const m = mergedModels[i]; + const mTok = Number(m.totalTokens || 0); + const sharePct = sumTok > 0 ? (mTok / sumTok) * 100 : 0; + if (i === 0 || (mainModels.length < maxMain && sharePct >= minSharePct)) { + mainModels.push(m); + } else { + tailModels.push(m); + } + } + + if (tailModels.length === 1) { + mainModels.push(tailModels.pop()); + } + + const out = mainModels.map((m) => { + const seed = getCanonicalModelColorSeed(m); + const color = + modelColorMap?.get(seed) || resolveDeterministicModelColor(seed || m.displayText); + const tok = Number(m.totalTokens || 0); + const pct = sumTok > 0 ? (tok / sumTok) * 100 : 0; + const label = m.displayText || m.label || m.shortName || '—'; + return { + key: label, + label, + tok, + pct, + tokText: formatTokensPrecise(tok), + pctText: `${pct.toFixed(1)}%`, + color, + isOther: false, + }; + }); + + if (tailModels.length >= 2) { + const otherTok = tailModels.reduce((sum, m) => sum + Number(m.totalTokens || 0), 0); + const otherPct = sumTok > 0 ? (otherTok / sumTok) * 100 : 0; + const otherLabel = t('cons.otherModelsCount', { count: tailModels.length }); + out.push({ + key: '__other__', + label: otherLabel, + tok: otherTok, + pct: otherPct, + tokText: formatTokensPrecise(otherTok), + pctText: `${otherPct.toFixed(1)}%`, + color: 'var(--cons-other-seg)', + isOther: true, + }); + } + + return out; + } + + /** + * 创建热门模型单行 DOM 结构(模型名称后附专属颜色圆点 + 按总占比缩放的 4 段比例条 + 底部分项脚标)。 */ function createBreakdownItemRow() { - const nameEl = h('strong', { className: 'cons-row-title' }); + const nameTextEl = h('span', { className: 'cons-row-title-text' }); + const modelDotEl = h('span', { className: 'dot-swatch cons-model-dot cons-title-model-dot' }); + const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl, modelDotEl]); const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); const costEl = h('strong', { className: 'cons-row-cost text-mono' }); @@ -439,6 +635,8 @@ export const ConsumptionView = defineComponent({ el: rowEl, refs: { nameEl, + nameTextEl, + modelDotEl, pctBadge, totalTokEl, costEl, @@ -458,22 +656,27 @@ export const ConsumptionView = defineComponent({ } /** - * 增量更新热门模型或数据来源单行的指标文本与 4 段比例条宽度。 + * 增量更新热门模型单行的指标文本、名称后的专属颜色圆点与按总占比缩放的 4 段比例条宽度。 */ - function updateBreakdownItemRow(refs, item, grandTotalTokens, showTokensInHeader = true) { + function updateBreakdownItemRow(refs, item, grandTotalTokens, modelColor = '') { patchText(refs.inLbl, t('cons.footInput')); patchText(refs.cacheLbl, t('cons.footCache')); patchText(refs.outLbl, t('cons.footOutput')); patchText(refs.thinkLbl, t('cons.footThinking')); patchText(refs.callsLbl, t('cons.footCalls')); const displayLabel = item.label || item.name || item.shortName || '—'; - patchText(refs.nameEl, displayLabel); + patchText(refs.nameTextEl, displayLabel); patchAttr(refs.nameEl, 'title', item.title || displayLabel); + patchAttr(refs.modelDotEl, 'hidden', !modelColor); + if (modelColor) { + patchStyleVar(refs.modelDotEl, '--dot-color', modelColor); + } const total = Number(item.totalTokens || 0); const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0; + const scaleRatio = + grandTotalTokens > 0 && total > 0 ? Math.min(1, Math.max(0.008, total / grandTotalTokens)) : 0; patchText(refs.pctBadge, `${share.toFixed(1)}%`); - patchText(refs.totalTokEl, showTokensInHeader ? formatTokensPrecise(total) : ''); - patchAttr(refs.totalTokEl, 'hidden', !showTokensInHeader); + patchText(refs.totalTokEl, formatTokensPrecise(total)); const costVal = Number(item.costUsd || 0); const callsCount = Number(item.calls || 0); const isAllUnpriced = @@ -496,6 +699,7 @@ export const ConsumptionView = defineComponent({ cacheReadTokens: Number(item.cacheReadTokens || 0), responseTokens: responseTok, thinkingTokens: thinkingTok, + scaleRatio, }); patchText(refs.inVal, formatTokensPrecise(item.inputTokens || 0)); @@ -505,6 +709,148 @@ export const ConsumptionView = defineComponent({ patchText(refs.callsVal, String(Number(item.calls || 0))); } + function createSourceModelSegment() { + const segEl = h('div', { className: 'progress-seg cons-model-seg' }); + return { el: segEl, refs: { segEl } }; + } + + /** + * 创建客户端来源单行 DOM 结构(保留长尾合并分段配色进度条与右侧总调用数,悬停进度条弹出各模型明细浮层)。 + */ + function createSourceBreakdownRow() { + const nameTextEl = h('span', { className: 'cons-row-title-text' }); + const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl]); + const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); + const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); + const costEl = h('strong', { className: 'cons-row-cost text-mono' }); + const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' }); + const rowState = { hoverPayload: null }; + const barHitEl = h( + 'div', + { + className: 'cons-source-bar-hit', + onMouseEnter: (e) => { + if (rowState.hoverPayload) { + showBreakdownPopover(barHitEl, rowState.hoverPayload, e?.clientX ?? null); + } + }, + onMouseMove: (e) => { + if (rowState.hoverPayload && activeHoverTargetEl === barHitEl) { + positionBreakdownPopover(barHitEl, e?.clientX ?? null); + } + }, + onMouseLeave: () => { + if (activeHoverTargetEl === barHitEl) hideBreakdownPopover(); + }, + }, + [trackEl] + ); + const callsLbl = h('span', { text: t('cons.footCalls') }); + const callsVal = h('strong', { className: 'text-mono' }); + + const rowEl = h('div', { className: 'cons-item-row cons-source-row' }, [ + h('div', { className: 'panel-header' }, [ + nameEl, + h('span', { className: 'cons-row-metrics' }, [ + pctBadge, + totalTokEl, + costEl, + ]), + ]), + barHitEl, + h('div', { className: 'cons-item-foot cons-source-foot' }, [ + h('span', { className: 'legend-left cons-calls-stat' }, [ + callsLbl, + callsVal, + ]), + ]), + ]); + + return { + el: rowEl, + refs: { + nameEl, + nameTextEl, + pctBadge, + totalTokEl, + costEl, + barHitEl, + trackEl, + callsLbl, + callsVal, + rowState, + }, + }; + } + + function updateSourceBreakdownRow(refs, item, grandTotalTokens, modelColorMap) { + patchText(refs.callsLbl, t('cons.footCalls')); + const displayLabel = item.label || item.name || '—'; + patchText(refs.nameTextEl, displayLabel); + patchAttr(refs.nameEl, 'title', item.title || displayLabel); + + const total = Number(item.totalTokens || 0); + const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0; + const scaleRatio = + grandTotalTokens > 0 && total > 0 ? Math.min(1, Math.max(0.01, total / grandTotalTokens)) : 0; + patchText(refs.pctBadge, `${share.toFixed(1)}%`); + patchText(refs.totalTokEl, formatTokensPrecise(total)); + + const costVal = Number(item.costUsd || 0); + const callsCount = Number(item.calls || 0); + const isAllUnpriced = + callsCount > 0 && Number(item.unpricedCalls || 0) >= callsCount && !(costVal > 0); + const costText = formatUsd(isAllUnpriced ? null : costVal, { + precise: costVal > 0 && costVal < 0.1, + }); + patchText(refs.costEl, costText); + patchText(refs.callsVal, String(callsCount)); + + const sourceModels = Array.isArray(item.mergedModels) ? item.mergedModels : []; + const partitioned = partitionModelSegments(sourceModels, modelColorMap, { + maxMain: 5, + minSharePct: 1.5, + }); + + const barItems = + partitioned.length > 0 + ? partitioned.map((seg) => ({ + key: seg.key, + segPct: scaleRatio > 0 ? seg.pct * scaleRatio : 0, + color: seg.color, + })) + : total > 0 + ? [ + { + key: '__source_fallback__', + segPct: scaleRatio * 100, + color: 'var(--accent-primary)', + }, + ] + : []; + + patchKeyedList(refs.trackEl, barItems, { + keyFn: (seg) => seg.key, + sigFn: (seg) => `${seg.key}:${seg.segPct.toFixed(2)}:${seg.color}`, + createRow: createSourceModelSegment, + updateRow: (segRefs, seg) => { + patchStyleVar(segRefs.segEl, '--seg-w', `${seg.segPct.toFixed(2)}%`); + patchStyleVar(segRefs.segEl, '--seg-color', seg.color); + }, + }); + + refs.rowState.hoverPayload = + total > 0 || callsCount > 0 + ? { + title: displayLabel, + calls: callsCount, + totalTokens: total, + costText, + segments: partitioned, + } + : null; + } + let latestSlice = null; let isDirty = false; @@ -613,28 +959,7 @@ export const ConsumptionView = defineComponent({ thinkingTokens, }); - // 2. 同步历史趋势交互式 SVG 面积图 / 类 GitHub 每日热力图(>90天)与粒度提示 - const rangeBadgeText = isEnglishLocale() - ? getConsumptionTimeRangeOptions().find((o) => o.value === slice.range)?.label || - t('cons.allTime') - : preset?.label || rangeInfo.label || t('cons.allTime'); - patchText(trendRangeBadge, rangeBadgeText); - const trendSeries = cons.trendSeries || []; - const isHourlyTrend = - trendSeries[0]?.granularity === 'hour' || - (trendSeries[0]?.label || '').includes(':'); - const isHeatmapTrend = !isHourlyTrend && trendSeries.length > HEATMAP_DAYS_THRESHOLD; - patchText( - trendGranularityHint, - isHeatmapTrend - ? t('cons.trendHeatmapHint', { days: trendSeries.length }) - : isHourlyTrend - ? t('cons.trendPointsHintHourly', { points: trendSeries.length || 0 }) - : t('cons.trendPointsHintDaily', { points: trendSeries.length || 0 }) - ); - trendChart.update(trendSeries); - - // 3. 同步热门模型列表(按最终展示名称去重归并后按总 Token 数降序排列并执行键值增量对账) + // 2-5. 统一解析展示模式与全局确定性模型配色映射(确保趋势浮层、模型排行圆点、客户端来源条、月度堆叠柱四处完全同色) const localeSig = i18nStore.getState().locale; const displaySettings = { modelDisplayMode: normalizeModelDisplayMode( @@ -644,38 +969,130 @@ export const ConsumptionView = defineComponent({ showUpstreamModel: Boolean(slice.showUpstreamModel), orchestratorIdMode: slice.orchestratorIdMode, }; + const mergeAndSortBucketModels = (rawList) => + mergeModelsByDisplayName(rawList || [], displaySettings, { + preferLabelInShort: true, + }) + .filter((m) => Number(m.totalTokens || 0) > 0 || Number(m.calls || 0) > 0) + .sort( + (a, b) => + (b.totalTokens || 0) - (a.totalTokens || 0) || (b.calls || 0) - (a.calls || 0) + ); + const models = mergeModelsByDisplayName(slice.modelBreakdown || [], displaySettings, { preferLabelInShort: true, }).sort((a, b) => (b.totalTokens || 0) - (a.totalTokens || 0)); const modelsTotalTok = models.reduce((s, m) => s + Number(m.totalTokens || 0), 0); + const rawSources = cons.sourcesBreakdown || []; + const sourcesTotalTok = rawSources.reduce((s, x) => s + Number(x.totalTokens || 0), 0); + const allSourceMergedModels = []; + const sourcesWithModels = rawSources.map((s) => { + const mergedModels = mergeAndSortBucketModels(s.models); + for (const m of mergedModels) { + allSourceMergedModels.push(m); + } + return { ...s, mergedModels }; + }); + + const monthlySeries = cons.monthlySeries || []; + const allMonthMergedModels = []; + const monthsMergedModels = Array.from({ length: 12 }, (_, idx) => { + const merged = mergeAndSortBucketModels(monthlySeries[idx]?.models); + for (const m of merged) { + allMonthMergedModels.push(m); + } + return merged; + }); + + const rawTrendSeries = cons.trendSeries || []; + const allTrendMergedModels = []; + const trendMergedByIdx = rawTrendSeries.map((slot) => { + if (!Array.isArray(slot?.models) || slot.models.length === 0) return null; + const merged = mergeAndSortBucketModels(slot.models); + for (const m of merged) { + allTrendMergedModels.push(m); + } + return merged; + }); + + const modelColorMap = buildDeterministicModelColorMap([ + ...models, + ...allSourceMergedModels, + ...allMonthMergedModels, + ...allTrendMergedModels, + ]); + + // 2. 同步历史趋势交互式 SVG 面积图 / 类 GitHub 每日热力图(>90天)与悬停分模型浮层 + const rangeBadgeText = isEnglishLocale() + ? getConsumptionTimeRangeOptions().find((o) => o.value === slice.range)?.label || + t('cons.allTime') + : preset?.label || rangeInfo.label || t('cons.allTime'); + patchText(trendRangeBadge, rangeBadgeText); + const isHourlyTrend = + rawTrendSeries[0]?.granularity === 'hour' || + (rawTrendSeries[0]?.label || '').includes(':'); + const isHeatmapTrend = !isHourlyTrend && rawTrendSeries.length > HEATMAP_DAYS_THRESHOLD; + patchText( + trendGranularityHint, + isHeatmapTrend + ? t('cons.trendHeatmapHint', { days: rawTrendSeries.length }) + : isHourlyTrend + ? t('cons.trendPointsHintHourly', { points: rawTrendSeries.length || 0 }) + : t('cons.trendPointsHintDaily', { points: rawTrendSeries.length || 0 }) + ); + const enrichedTrendSeries = rawTrendSeries.map((slot, idx) => { + const mergedSlotModels = trendMergedByIdx[idx]; + if (!mergedSlotModels || mergedSlotModels.length === 0) return slot; + return { + ...slot, + modelSegments: partitionModelSegments(mergedSlotModels, modelColorMap, { + maxMain: 5, + minSharePct: 1.5, + }), + }; + }); + trendChart.update(enrichedTrendSeries); + + // 3. 同步热门模型列表(名称后带专属颜色圆点 + 4 段条按总占比缩放长度) patchKeyedList(modelsListEl, models, { keyFn: (m) => m.displayText || m.label || m.shortName, - sigFn: (m) => - `${localeSig}:${m.displayText}:${m.displayTitle}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`, + sigFn: (m) => { + const seed = getCanonicalModelColorSeed(m); + const color = modelColorMap.get(seed) || resolveDeterministicModelColor(seed); + return `${localeSig}:${m.displayText}:${m.displayTitle}:${color}:${m.totalTokens}:${m.inputTokens}:${m.cacheReadTokens}:${m.responseTokens}:${m.thinkingTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`; + }, createRow: createBreakdownItemRow, - updateRow: (refs, m) => + updateRow: (refs, m) => { + const seed = getCanonicalModelColorSeed(m); + const color = modelColorMap.get(seed) || resolveDeterministicModelColor(seed); updateBreakdownItemRow( refs, { ...m, label: m.displayText, title: m.displayTitle }, modelsTotalTok, - true - ), + color + ); + }, }); - // 4. 同步数据来源列表 - const sources = cons.sourcesBreakdown || []; - const sourcesTotalTok = sources.reduce((s, x) => s + Number(x.totalTokens || 0), 0); - patchKeyedList(sourcesListEl, sources, { + // 4. 同步客户端来源列表(长尾合并分段配色 + 右侧总调用数 + 悬停进度条弹出明细浮层) + patchKeyedList(sourcesListEl, sourcesWithModels, { keyFn: (s) => s.name, - sigFn: (s) => `${localeSig}:${s.name}:${s.totalTokens}:${s.costUsd}:${s.unpricedCalls}:${s.calls}:${sourcesTotalTok}`, - createRow: createBreakdownItemRow, - updateRow: (refs, s) => updateBreakdownItemRow(refs, s, sourcesTotalTok, true), + sigFn: (s) => { + const modelsSig = s.mergedModels + .map((m) => { + const seed = getCanonicalModelColorSeed(m); + return `${m.displayText}:${m.totalTokens}:${m.calls}:${modelColorMap.get(seed) || ''}`; + }) + .join('|'); + return `${localeSig}:${s.name}:${s.totalTokens}:${s.costUsd}:${s.unpricedCalls}:${s.calls}:${sourcesTotalTok}:${modelsSig}`; + }, + createRow: createSourceBreakdownRow, + updateRow: (refs, s) => updateSourceBreakdownRow(refs, s, sourcesTotalTok, modelColorMap), }); - // 5. 同步 12 个月垂直堆叠柱状图(相对于年度峰值月缩放柱高,最低保留 8% 可视高度) + // 5. 同步 12 个月垂直堆叠柱状图(按模型配色堆叠 + 长尾合并 + 悬停弹出明细浮层) patchText(monthlyYearBadge, String(monthlyYear)); - const monthlySeries = cons.monthlySeries || []; const maxMonthTokens = Math.max( 1, ...monthlySeries.map((m) => Number(m.totalTokens || 0)) @@ -683,10 +1100,12 @@ export const ConsumptionView = defineComponent({ for (let i = 0; i < 12; i++) { const col = monthlyCols[i]; - const m = monthlySeries[i] || { totalTokens: 0, costUsd: 0 }; + const m = monthlySeries[i] || { totalTokens: 0, costUsd: 0, calls: 0 }; const mTot = Number(m.totalTokens || 0); + const mCalls = Number(m.calls || 0); const hasData = mTot > 0; + patchClasses(col.el, { 'is-interactive': hasData || mCalls > 0 }); patchClasses(col.monthLabel, { 'is-current': i === currentMonthIdx }); patchAttr(col.stackWrap, 'hidden', !hasData); patchAttr(col.zeroDot, 'hidden', hasData); @@ -694,29 +1113,63 @@ export const ConsumptionView = defineComponent({ if (!hasData) { patchText(col.costText, ''); patchText(col.tokText, ''); + col.colState.hoverPayload = null; + patchKeyedList(col.stackWrap, [], { + keyFn: (x) => x.key, + sigFn: (x) => x.key, + createRow: createMonthModelSegment, + updateRow: () => {}, + }); } else { const cVal = Number(m.costUsd || 0); + const isMonthUnpriced = + mCalls > 0 && Number(m.unpricedCalls || 0) >= mCalls && !(cVal > 0); patchText( col.costText, - cVal >= 10 ? `$${Math.round(cVal)}` : `$${cVal.toFixed(2)}` + isMonthUnpriced ? '—' : cVal >= 10 ? `$${Math.round(cVal)}` : `$${cVal.toFixed(2)}` ); patchText(col.tokText, formatTokensPrecise(mTot)); const totalHeightPct = Math.max(8, Math.min(100, (mTot / maxMonthTokens) * 100)); patchStyleVar(col.stackWrap, '--bar-h', `${totalHeightPct.toFixed(1)}%`); - const inPctM = (Number(m.inputTokens || 0) / mTot) * 100; - const cachePctM = (Number(m.cacheReadTokens || 0) / mTot) * 100; - const outPctM = (Number(m.responseTokens || 0) / mTot) * 100; - const thinkPctM = (Number(m.thinkingTokens || 0) / mTot) * 100; + const monthModels = monthsMergedModels[i] || []; + const barPartitioned = partitionModelSegments(monthModels, modelColorMap, { + maxMain: 5, + minSharePct: 1.5, + }); + // 垂直柱状图底端放主力模型、顶端叠放小占比及「其他」,视觉重心稳定 + const verticalSegments = + barPartitioned.length > 0 + ? [...barPartitioned].reverse() + : [{ key: '__month_fallback__', pct: 100, color: 'var(--accent-primary)' }]; - patchStyleVar(col.barIn, '--seg-h', `${inPctM.toFixed(1)}%`); - patchStyleVar(col.barCache, '--seg-h', `${cachePctM.toFixed(1)}%`); - patchStyleVar(col.barOut, '--seg-h', `${outPctM.toFixed(1)}%`); - patchStyleVar(col.barThink, '--seg-h', `${thinkPctM.toFixed(1)}%`); + patchKeyedList(col.stackWrap, verticalSegments, { + keyFn: (seg) => seg.key, + sigFn: (seg) => `${seg.key}:${seg.pct.toFixed(2)}:${seg.color}`, + createRow: createMonthModelSegment, + updateRow: (segRefs, seg) => { + patchStyleVar(segRefs.segEl, '--seg-h', `${seg.pct.toFixed(2)}%`); + patchStyleVar(segRefs.segEl, '--seg-color', seg.color); + }, + }); + + col.colState.hoverPayload = { + title: t('cons.monthFullLabel', { year: monthlyYear, m: i + 1 }), + calls: mCalls, + totalTokens: mTot, + costText: formatUsd(isMonthUnpriced ? null : cVal, { + precise: cVal > 0 && cVal < 0.1, + }), + segments: barPartitioned, + }; } } + if (activeHoverTargetEl && activeHoverTargetEl.isConnected === false) { + hideBreakdownPopover(); + } + viewScrollbar.refresh(); } @@ -739,6 +1192,7 @@ export const ConsumptionView = defineComponent({ (slice) => { latestSlice = slice; if (getVisibleMonitorView() !== 'consumption') { + hideBreakdownPopover(); isDirty = true; return; } @@ -750,7 +1204,11 @@ export const ConsumptionView = defineComponent({ const unsubView = uiStore.subscribe( getVisibleMonitorView, (activeView) => { - if (activeView === 'consumption' && isDirty) { + if (activeView !== 'consumption') { + hideBreakdownPopover(); + return; + } + if (isDirty) { isDirty = false; if (latestSlice) { renderConsumptionData(latestSlice); @@ -776,14 +1234,12 @@ export const ConsumptionView = defineComponent({ patchText(trendTitleSpan, t('cons.trendTitle')); patchText(modelsTitleSpan, t('cons.topModels')); patchText(sourcesTitleSpan, t('cons.clientSources')); + patchText(sourcesHoverHint, t('cons.hoverModelsHint')); patchText(monthlyTitleSpan, t('cons.monthlyTitle')); + patchText(monthlyHoverHint, t('cons.hoverModelsHint')); for (let i = 0; i < 12; i++) { patchText(monthlyCols[i].monthLabel, t('cons.monthLabel', { m: i + 1 })); } - patchText(legInputSpan, t('cons.legInput')); - patchText(legCacheSpan, t('cons.legCache')); - patchText(legOutputSpan, t('cons.legOutput')); - patchText(legThinkingSpan, t('cons.legThinking')); } const unsubI18n = i18nStore.subscribe( @@ -800,6 +1256,7 @@ export const ConsumptionView = defineComponent({ ); onCleanup(() => { + hideBreakdownPopover(); unsub(); unsubView(); unsubI18n(); @@ -811,8 +1268,8 @@ export const ConsumptionView = defineComponent({ }); return { - el: viewScrollbar.el, - refs: { timeFilterSwitch, startPicker, endPicker, viewScrollbar }, + el: rootEl, + refs: { timeFilterSwitch, startPicker, endPicker, viewScrollbar, breakdownPopoverEl }, }; }, }); diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index df9971c..a215260 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -2092,15 +2092,28 @@ html[data-standalone="true"] .app-shell { flex-shrink: 0; } +:root, +:host { + --cons-other-seg: color-mix(in srgb, var(--text-secondary) 46%, var(--surface-panel)); +} + .dot-swatch.seg-input { background: var(--ctx-input); } .dot-swatch.seg-cached { background: var(--ctx-cached); } .dot-swatch.seg-output { background: var(--ctx-output); } .dot-swatch.seg-thinking { background: var(--ctx-thinking); } +.dot-swatch.cons-model-dot { background: var(--dot-color, var(--accent-primary)); } + +.progress-seg.cons-model-seg, +.month-seg.cons-model-seg { + background-color: var(--seg-color, var(--accent-primary)); +} /* --- 3. 热门模型与数据来源行头部对齐 (Popular Models & Sources Row Header) --- */ .cons-row-title { display: inline-flex; align-items: center; + gap: 6px; + min-width: 0; min-height: calc(20px * var(--ui-font-scale, 1)); line-height: 1.3; font-size: var(--fs-base); @@ -2108,6 +2121,18 @@ html[data-standalone="true"] .app-shell { color: var(--text-primary); } +.cons-row-title-text { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.cons-title-model-dot { + width: 7px; + height: 7px; + flex-shrink: 0; +} + .cons-row-metrics { display: inline-flex; align-items: center; @@ -2173,7 +2198,7 @@ html[data-standalone="true"] .app-shell { .trend-svg { width: 100%; - height: 120px; + height: 184px; display: block; overflow: visible; } @@ -2236,19 +2261,19 @@ html[data-standalone="true"] .app-shell { .trend-tooltip { position: absolute; - top: 0; + top: 2px; left: var(--tip-x, 50%); transform: translateX(var(--tip-shift, -50%)); width: max-content; - min-width: 152px; + min-width: 196px; max-width: min(320px, calc(100% - 8px)); - padding: 5px 9px; + padding: 6px 10px; background: var(--surface-panel); border: 1px solid var(--border-strong); border-radius: var(--radius-sm); - box-shadow: none; + box-shadow: var(--shadow-popover); pointer-events: none; - z-index: 15; + z-index: 25; display: flex; flex-direction: column; gap: 2px; @@ -2313,14 +2338,19 @@ html[data-standalone="true"] .app-shell { margin-top: 1px; } +.trend-tooltip.is-line-low { + top: auto; + bottom: 20px; +} + .trend-tooltip.is-hm-top { - top: 0; - bottom: auto; + top: auto; + bottom: calc(100% + 6px); } .trend-tooltip.is-hm-bottom { - top: auto; - bottom: 0; + top: calc(100% + 6px); + bottom: auto; } .trend-x-axis { @@ -2361,8 +2391,8 @@ html[data-standalone="true"] .app-shell { .trend-heatmap-stage { display: flex; flex-direction: column; - gap: 6px; - padding-top: 2px; + gap: 8px; + padding-top: 4px; width: 100%; user-select: none; } @@ -2370,7 +2400,7 @@ html[data-standalone="true"] .app-shell { .trend-heatmap-body { --hm-weeks: 26; --hm-gap: 2px; - --hm-cell: 9px; + --hm-cell: 12px; display: flex; align-items: flex-start; gap: 4px; @@ -2381,9 +2411,9 @@ html[data-standalone="true"] .app-shell { @supports (width: 1cqi) { .trend-heatmap-body { --hm-cell: clamp( - 6.5px, + 11px, calc((100cqi - 18px - (var(--hm-weeks) - 1) * var(--hm-gap)) / var(--hm-weeks)), - 18px + 20px ); } } @@ -2555,11 +2585,130 @@ html[data-standalone="true"] .app-shell { margin-left: auto; } +.cons-view-stage { + flex: 1; + min-height: 0; + display: flex; + flex-direction: column; + position: relative; +} + .cons-item-foot strong { color: var(--text-primary); font-weight: 600; } +.cons-source-row { + gap: 5px; +} + +.cons-source-bar-hit { + padding: 5px 0; + margin: -5px 0; + cursor: pointer; +} + +.cons-source-bar-hit:hover .cons-source-model-bar, +.cons-source-bar-hit.is-hovered .cons-source-model-bar { + box-shadow: 0 0 0 1px var(--border-strong); +} + +.cons-source-foot { + justify-content: flex-end; + min-height: 16px; +} + +.month-col.is-interactive { + cursor: pointer; +} + +.month-col.is-interactive:hover .month-stack, +.month-col.is-hovered .month-stack { + box-shadow: 0 0 0 1px var(--text-primary); +} + +.month-col.is-interactive:hover .month-label, +.month-col.is-hovered .month-label { + color: var(--text-primary); + font-weight: 600; +} + +/* --- 共享模型构成悬浮详情卡 (Client Sources & Monthly Breakdown Popover) --- */ +.cons-breakdown-popover { + position: absolute; + left: var(--pop-x, 8px); + top: var(--pop-y, 8px); + width: max-content; + min-width: 196px; + max-width: min(310px, calc(100% - 16px)); + padding: 6px 10px; + background: var(--surface-panel); + border: 1px solid var(--border-strong); + border-radius: var(--radius-sm); + box-shadow: var(--shadow-popover); + pointer-events: none; + z-index: 30; + display: flex; + flex-direction: column; + gap: 3px; +} + +.cons-pop-models { + display: flex; + flex-direction: column; + gap: 3px; + border-top: 1px solid var(--border-hairline); + padding-top: 4px; + margin-top: 2px; +} + +.cons-pop-model-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + font-size: var(--fs-sm); + line-height: 1.3; +} + +.cons-pop-model-left { + display: inline-flex; + align-items: center; + gap: 6px; + min-width: 0; + color: var(--text-primary); +} + +.cons-pop-model-name { + max-width: 156px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.cons-pop-model-row.is-other .cons-pop-model-name { + color: var(--text-secondary); +} + +.cons-pop-model-right { + display: inline-flex; + align-items: baseline; + gap: 8px; + flex-shrink: 0; +} + +.cons-pop-model-tok { + font-size: var(--fs-xs); + color: var(--text-muted); +} + +.cons-pop-model-pct { + min-width: 40px; + text-align: right; + font-weight: 600; + color: var(--text-primary); +} + /* --- 6. 12 个月垂直堆叠柱状图 (12-Month Stacked Bar Chart) --- */ .monthly-grid { display: grid; diff --git a/sidecars/panel/test/consumption-bars.test.mjs b/sidecars/panel/test/consumption-bars.test.mjs new file mode 100644 index 0000000..5dcac7f --- /dev/null +++ b/sidecars/panel/test/consumption-bars.test.mjs @@ -0,0 +1,474 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createMockDom } from './mock-dom.mjs'; +import { backendHarness } from './backend-harness.mjs'; +import { + buildDeterministicModelColorMap, + getCanonicalModelColorSeed, + mergeModelsByDisplayName, + resolveDeterministicModelColor, +} from '../src/core/formatters.js'; +import { isEquivalentTelemetry, telemetryStore } from '../src/store/telemetryStore.js'; +import { uiStore } from '../src/store/uiStore.js'; +import { i18nStore, setI18nLanguage } from '../src/i18n/index.js'; +import { createFourSegmentBar } from '../src/components/ui/FourSegmentBar.js'; +import { ConsumptionView } from '../src/views/ConsumptionView.js'; + +function parsePctVar(el, prop = '--seg-w') { + const raw = el?.style?.getPropertyValue?.(prop) || ''; + return Number.parseFloat(raw.replace('%', '')) || 0; +} + +test('Perceptual 20-color ring: deterministic cross-machine assignment without green pileups or hardcoded tables', () => { + const realUserModels = [ + '3.7-flash', + '3-flash-b', + '3.8-flash', + 'pro-default', + '3-flash-c', + '3.6-flash', + 'opus-4-6-thinking', + '3.1-flash-lite', + 'sonnet-4-6', + '2.5-flash-lite', + '4-argon', + '4-carbon', + '3.8-flash-n', + '4-hydrogen', + 'orchestrator-carbon', + 'worker-agy-hydrogen', + ]; + + const mapForward = buildDeterministicModelColorMap(realUserModels); + const mapReversed = buildDeterministicModelColorMap([...realUserModels].reverse()); + assert.deepEqual([...mapForward.entries()], [...mapReversed.entries()]); + + // All 16 models receive 16 completely distinct perceptual HSL colors + const uniqueColors = new Set(mapForward.values()); + assert.equal(uniqueColors.size, realUserModels.length); + + // Merged upstream buckets ('4-carbon' across App vs CLI with different sourceLabels subsets) share identical seed + const appMergedCarbon = { + displayText: '4-carbon', + mergedCount: 2, + sourceLabels: ['Gemini 4 Carbon (High)', 'Gemini 4 Carbon (Medium)'], + }; + const cliMergedCarbon = { + displayText: '4-carbon', + mergedCount: 1, + sourceLabels: ['Gemini 4 Carbon (Low)'], + label: 'Gemini 4 Carbon (Low)', + }; + assert.equal(getCanonicalModelColorSeed(appMergedCarbon), '4-carbon'); + const singleModeModels = mergeModelsByDisplayName( + [ + { + label: 'Gemini 4 Carbon (Low)', + shortName: '4-carbon', + upstreamName: '4-carbon', + calls: 2, + totalTokens: 1000, + }, + ], + { modelDisplayMode: 'upstream', showUpstreamModel: true } + ); + assert.equal(singleModeModels[0].displayText, '4-carbon'); + + // Arbitrary future models work without hardcoding + const future = resolveDeterministicModelColor('Gemini 9 Krypton (Ultra)'); + assert.match(future, /^hsl\(\d+\s+\d+%\s+\d+%\)$/); + assert.equal(future, resolveDeterministicModelColor(' gemini 9 krypton (ultra) ')); + assert.ok(cliMergedCarbon); +}); + +test('FourSegmentBar supports percentage scaling while keeping 100% default for Overview', () => { + const prevDoc = globalThis.document; + const { document } = createMockDom(); + globalThis.document = document; + try { + const barFull = createFourSegmentBar(); + barFull.update({ + inputTokens: 200, + cacheReadTokens: 500, + responseTokens: 200, + thinkingTokens: 100, + }); + const segsFull = barFull.el.querySelectorAll('.progress-seg'); + const sumFull = segsFull.reduce((acc, el) => acc + parsePctVar(el), 0); + assert.ok(Math.abs(sumFull - 100) < 0.05); + + const barScaled = createFourSegmentBar(); + barScaled.update({ + inputTokens: 200, + cacheReadTokens: 500, + responseTokens: 200, + thinkingTokens: 100, + scaleRatio: 0.4, + }); + const segsScaled = barScaled.el.querySelectorAll('.progress-seg'); + const sumScaled = segsScaled.reduce((acc, el) => acc + parsePctVar(el), 0); + assert.ok(Math.abs(sumScaled - 40) < 0.05); + } finally { + globalThis.document = prevDoc; + } +}); + +test('Backend aggregates per-model breakdown on both sourcesBreakdown and monthlySeries', async () => { + const nowMs = Date.parse('2026-11-18T12:00:00Z'); + const nowIso = '2026-11-18T12:00:00Z'; + const appCid = 'aaaaaaaa-1111-4111-8111-111111111111'; + const cliCid = 'cccccccc-2222-4222-8222-222222222222'; + + const harness = backendHarness({ + clock: () => nowMs, + trajectories: { + [appCid]: { + trajectory: { + steps: [ + { + type: 'CORTEX_STEP_TYPE_USER_INPUT', + status: 'CORTEX_STEP_STATUS_DONE', + userInput: { userResponse: 'Hello App' }, + metadata: { createdAt: nowIso }, + }, + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: nowIso, + completedAt: '2026-11-18T12:00:03Z', + sourceTrajectoryStepInfo: { stepIndex: 1 }, + modelUsage: { + model: 'MODEL_PLACEHOLDER_M429', + apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + inputTokens: '6000', + cacheReadTokens: '2000', + outputTokens: '2000', + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: '2026-11-18T12:00:05Z', + completedAt: '2026-11-18T12:00:08Z', + sourceTrajectoryStepInfo: { stepIndex: 2 }, + modelUsage: { + model: 'MODEL_PLACEHOLDER_M405', + apiProvider: 'API_PROVIDER_ANTHROPIC', + inputTokens: '4000', + cacheReadTokens: '0', + outputTokens: '1000', + }, + }, + }, + ], + }, + }, + }, + summaries: { + [appCid]: { + summary: 'App Session', + status: 'CASCADE_RUN_STATUS_IDLE', + stepCount: 3, + createdTime: nowIso, + lastModifiedTime: '2026-11-18T12:00:08Z', + }, + }, + deepStats: { + perConvo: { + [`cli:${cliCid}`]: { + appSource: 'cli', + entries: [ + { + ts: '2026-11-18T12:01:00Z', + modelRuntimeId: 'MODEL_PLACEHOLDER_M429', + inp: 3000, + cache: 1000, + out: 800, + reasoning: 200, + }, + ], + }, + }, + }, + }); + + const payload = await harness.buildTelemetryPayloadInternal({ range: 'all' }); + const sources = payload.consumption?.sourcesBreakdown || []; + assert.equal(sources.length, 2); + assert.equal(sources[0].name, 'Antigravity App'); + assert.equal(sources[0].totalTokens, 15_000); + assert.equal(sources[0].models.length, 2); + assert.equal(sources[1].name, 'Antigravity CLI'); + assert.equal(sources[1].totalTokens, 5_000); + assert.equal(sources[1].models.length, 1); + + // November (index 10) in monthlySeries also carries aggregated per-model breakdown + const novBucket = payload.consumption?.monthlySeries?.[10]; + assert.ok(novBucket); + assert.equal(novBucket.totalTokens, 20_000); + assert.equal(novBucket.models.length, 2); + + // Active trendSeries bucket carries per-model breakdown while zero-token buckets omit models + const trendSlots = payload.consumption?.trendSeries || []; + const activeTrendSlot = trendSlots.find((s) => s.tokens > 0); + const zeroTrendSlot = trendSlots.find((s) => s.tokens === 0); + assert.ok(activeTrendSlot); + assert.equal(activeTrendSlot.tokens, 20_000); + assert.equal(activeTrendSlot.models.length, 2); + if (zeroTrendSlot) { + assert.equal(zeroTrendSlot.models, undefined); + } +}); + +test('ConsumptionView: Top Models color dot + % bar, clutter-free Client Sources + Monthly model bars with long-tail folding & hover popover', async (t) => { + const prevLocale = i18nStore.getState().locale; + const prevDoc = globalThis.document; + const prevWin = globalThis.window; + const prevTelState = { ...telemetryStore.getState() }; + const prevUiState = { ...uiStore.getState() }; + + const { document } = createMockDom(); + globalThis.document = document; + globalThis.window = { + location: { pathname: '/' }, + addEventListener() {}, + removeEventListener() {}, + requestAnimationFrame: (cb) => setTimeout(cb, 0), + cancelAnimationFrame: (id) => clearTimeout(id), + }; + + let view = null; + t.after(() => { + if (view) view.destroy(); + setI18nLanguage(prevLocale); + telemetryStore.setState(prevTelState, { sync: true }); + uiStore.setState(prevUiState, { sync: true }); + globalThis.document = prevDoc; + globalThis.window = prevWin; + }); + + setI18nLanguage('zh-CN'); + uiStore.setState( + { monitorVisible: true, activeView: 'consumption', settingsOpen: false }, + { sync: true } + ); + + const mkModel = (name, tok, calls = 2, costUsd = 0.1) => ({ + label: name, + shortName: name, + upstreamName: name, + calls, + inputTokens: Math.floor(tok * 0.2), + cacheReadTokens: Math.floor(tok * 0.6), + outputTokens: Math.floor(tok * 0.2), + responseTokens: Math.floor(tok * 0.15), + thinkingTokens: tok - Math.floor(tok * 0.2) - Math.floor(tok * 0.6) - Math.floor(tok * 0.15), + totalTokens: tok, + costUsd, + unpricedCalls: 0, + }); + + const mArgon = mkModel('4-argon', 50_000, 10, 0.5); + const mCarbon = mkModel('4-carbon', 30_000, 6, 0.3); + const mFlash = mkModel('3.8-flash-n', 18_000, 4, 0.12); + const mTail1 = mkModel('opus-4-6-thinking', 800, 1, 0.02); + const mTail2 = mkModel('3.1-flash-lite', 700, 1, 0.01); + const mTail3 = mkModel('2.5-flash-lite', 500, 1, 0.01); + + const emptyMonths = Array.from({ length: 12 }, (_, idx) => ({ + month: idx + 1, + label: `${idx + 1}月`, + calls: 0, + totalTokens: 0, + costUsd: 0, + models: [], + })); + emptyMonths[10] = { + month: 11, + label: '11月', + calls: 23, + totalTokens: 100_000, + costUsd: 0.96, + models: [mArgon, mCarbon, mFlash, mTail1, mTail2, mTail3], + }; + + const baseTelemetry = { + settings: { + language: 'zh-CN', + modelDisplayMode: 'upstream', + showUpstreamModel: true, + }, + modelBreakdown: [mArgon, mCarbon, mFlash, mTail1, mTail2, mTail3], + consumption: { + selectedRange: { key: 'all', label: '全部', startMs: 1_700_000_000_000, endMs: 1_700_086_400_000 }, + account: { + totalTokens: 100_000, + inputTokens: 20_000, + cacheReadTokens: 60_000, + outputTokens: 20_000, + responseTokens: 15_000, + thinkingTokens: 5_000, + calls: 23, + costUsd: 0.96, + savedCostUsd: 0.25, + cacheHitPct: 75.0, + }, + trendSeries: [ + { + index: 0, + granularity: 'day', + label: '11/17', + fullLabel: '11月17日 (周二)', + tokens: 0, + calls: 0, + costUsd: 0, + }, + { + index: 1, + granularity: 'day', + label: '11/18', + fullLabel: '11月18日 (周三)', + tokens: 100_000, + inputTokens: 20_000, + cacheReadTokens: 60_000, + outputTokens: 20_000, + calls: 23, + costUsd: 0.96, + models: [mArgon, mCarbon, mFlash, mTail1, mTail2, mTail3], + }, + ], + monthlyYear: 2026, + monthlySeries: emptyMonths, + sourcesBreakdown: [ + { + name: 'Antigravity App', + calls: 20, + totalTokens: 80_000, + costUsd: 0.8, + unpricedCalls: 0, + models: [ + mkModel('4-argon', 40_000, 8, 0.4), + mkModel('4-carbon', 25_000, 5, 0.25), + mkModel('3.8-flash-n', 13_000, 4, 0.1), + mTail1, + mTail2, + mTail3, + ], + }, + { + name: 'Antigravity CLI', + calls: 3, + totalTokens: 20_000, + costUsd: 0.16, + unpricedCalls: 0, + models: [ + mkModel('4-argon', 10_000, 2, 0.1), + mkModel('4-carbon', 5_000, 1, 0.05), + mkModel('3.8-flash-n', 5_000, 0, 0.01), + ], + }, + ], + }, + }; + + assert.equal( + isEquivalentTelemetry(baseTelemetry, { + ...baseTelemetry, + consumption: { + ...baseTelemetry.consumption, + monthlySeries: emptyMonths.map((m, idx) => + idx === 10 ? { ...m, models: [mArgon] } : m + ), + }, + }), + false, + 'isEquivalentTelemetry must detect model breakdown changes inside monthlySeries' + ); + + telemetryStore.setState( + { selectedTimeRange: 'all', telemetry: baseTelemetry }, + { sync: true } + ); + + view = ConsumptionView({}); + document.body.appendChild(view.el); + await Promise.resolve(); + + const allRows = view.el.querySelectorAll('.cons-item-row'); + const modelRows = allRows.filter((r) => !r.classList.contains('cons-source-row')); + const sourceRows = view.el.querySelectorAll('.cons-source-row'); + assert.equal(modelRows.length, 6); + assert.equal(sourceRows.length, 2); + + // 1. Top Models: colored dot appears right after model name & 4-segment bar scales to 50% (not 100%) + const argonTitleDot = modelRows[0].querySelector('.cons-title-model-dot'); + assert.ok(argonTitleDot && !argonTitleDot.hasAttribute('hidden')); + const argonDotColor = argonTitleDot.style.getPropertyValue('--dot-color'); + assert.match(argonDotColor, /^hsl\(/); + + const argonSegSum = modelRows[0] + .querySelectorAll('.progress-seg') + .reduce((s, el) => s + parsePctVar(el, '--seg-w'), 0); + assert.ok(Math.abs(argonSegSum - 50) < 0.1, `Expected 50% width for 4-argon row, got ${argonSegSum}`); + + // 2. Client Sources: NO bottom model list text dump; 3 tail models (<1.5%) fold into 1 neutral '__other__' segment! + assert.equal(sourceRows[0].querySelectorAll('.cons-source-model-chip').length, 0); + const appSegs = sourceRows[0].querySelectorAll('.cons-model-seg'); + assert.equal(appSegs.length, 4, '3 main models + 1 merged other segment'); + assert.equal(appSegs[0].style.getPropertyValue('--seg-color'), argonDotColor); + assert.equal(appSegs[3].style.getPropertyValue('--seg-color'), 'var(--cons-other-seg)'); + const appBarSum = appSegs.reduce((s, el) => s + parsePctVar(el, '--seg-w'), 0); + assert.ok(Math.abs(appBarSum - 80) < 0.1); + + // Hovering Client Source bar hit area opens shared popover with model details + '其他 (3)' + const popover = view.refs.breakdownPopoverEl; + assert.equal(popover.hasAttribute('hidden'), true); + const appBarHit = sourceRows[0].querySelector('.cons-source-bar-hit'); + appBarHit.dispatchEvent({ type: 'mouseenter', clientX: 120 }); + assert.equal(popover.hasAttribute('hidden'), false); + assert.equal(popover.querySelector('.trend-tip-time')?.textContent, 'Antigravity App'); + const popRows = popover.querySelectorAll('.cons-pop-model-row'); + assert.equal(popRows.length, 4); + assert.equal(popRows[0].querySelector('.cons-pop-model-name')?.textContent, '4-argon'); + assert.equal(popRows[0].querySelector('.cons-pop-model-pct')?.textContent, '50.0%'); + assert.equal(popRows[3].querySelector('.cons-pop-model-name')?.textContent, '其他 (3)'); + + appBarHit.dispatchEvent({ type: 'mouseleave' }); + assert.equal(popover.hasAttribute('hidden'), true); + + // 3. Monthly Breakdown: old 4-channel legend removed; Nov column renders model-colored vertical segments & hover popover + assert.equal(view.el.querySelectorAll('.monthly-legend').length, 0); + const monthCols = view.el.querySelectorAll('.month-col'); + const novCol = monthCols[10]; + const novSegs = novCol.querySelectorAll('.month-seg.cons-model-seg'); + assert.equal(novSegs.length, 4, '3 main models + 1 merged other segment stacked vertically'); + // Bottom segment of vertical stack is the #1 model (4-argon) with exact matching color + assert.equal(novSegs[novSegs.length - 1].style.getPropertyValue('--seg-color'), argonDotColor); + const novSegHeightSum = novSegs.reduce((s, el) => s + parsePctVar(el, '--seg-h'), 0); + assert.ok(Math.abs(novSegHeightSum - 100) < 0.1); + + novCol.dispatchEvent({ type: 'mouseenter' }); + assert.equal(popover.hasAttribute('hidden'), false); + assert.equal(popover.querySelector('.trend-tip-time')?.textContent, '2026年 11月'); + assert.equal(popover.querySelectorAll('.cons-pop-model-row').length, 4); + + // 4. Usage Trend: taller 184px viewBox & hovering x-axis tick opens trend tooltip with identical model colors + long-tail '其他 (3)' + const trendSvg = view.el.querySelector('.trend-svg'); + assert.match(trendSvg?.getAttribute('viewBox') || '', /\s184$/); + const trendTicks = view.el.querySelectorAll('.trend-x-tick'); + assert.equal(trendTicks.length, 2); + trendTicks[1].onclick(); + const trendTip = view.el.querySelector('.trend-tooltip'); + assert.equal(trendTip?.hasAttribute('hidden'), false); + const trendTipModelRows = trendTip.querySelectorAll('.cons-pop-model-row'); + assert.equal(trendTipModelRows.length, 4); + assert.equal(trendTipModelRows[0].querySelector('.cons-pop-model-name')?.textContent, '4-argon'); + assert.equal( + trendTipModelRows[0].querySelector('.cons-model-dot')?.style.getPropertyValue('--dot-color'), + argonDotColor + ); + assert.equal(trendTipModelRows[3].querySelector('.cons-pop-model-name')?.textContent, '其他 (3)'); +}); diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index 45af999..1ee6537 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -2033,7 +2033,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro ); assert.equal( plotStageEl.querySelector('.trend-svg').getAttribute('viewBox'), - '0 0 180 120', + '0 0 180 184', 'TrendAreaChart dynamically adapts viewBox width to measured container width (180px in MockNode)' ); assert.match( From 367ca0cd6dc835c6d4e6f05c11838d14b60d6c8b Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Thu, 19 Nov 2026 15:05:27 +0900 Subject: [PATCH 05/14] feat(panel): add experimental modern UI, sliding switchers, cycle range, and fluid animations --- sidecars/panel/app.js | 1356 +++++++++++++++-- sidecars/panel/backend/settings-schema.mjs | 4 + sidecars/panel/backend/telemetry-builder.mjs | 6 +- sidecars/panel/backend/usage-aggregator.mjs | 172 ++- sidecars/panel/index.html | 4 +- sidecars/panel/scripts/build-bundle.mjs | 1 + .../panel/shared/settings-normalization.mjs | 14 + .../components/charts/SessionStepCharts.js | 32 + .../src/components/charts/TrendAreaChart.js | 56 +- .../components/layout/WindowOverlayShell.js | 36 +- .../src/components/ui/SegmentedControl.js | 219 ++- .../components/widgets/ContextWindowWidget.js | 144 +- .../components/widgets/LiveActivityWidget.js | 202 ++- .../src/components/widgets/StepTableWidget.js | 84 + sidecars/panel/src/core/appearance.js | 347 ++++- sidecars/panel/src/core/domPatch.js | 7 +- sidecars/panel/src/i18n/en-US.js | 17 +- sidecars/panel/src/i18n/zh-CN.js | 17 +- sidecars/panel/src/main.js | 38 + sidecars/panel/src/store/telemetryStore.js | 10 +- sidecars/panel/src/styles/base.css | 4 + sidecars/panel/src/styles/controls.css | 61 +- sidecars/panel/src/styles/modern-ui.css | 706 +++++++++ .../panel/src/styles/views-consumption.css | 19 + sidecars/panel/src/styles/views-overview.css | 52 +- sidecars/panel/src/styles/views-settings.css | 46 +- sidecars/panel/src/views/ConsumptionView.js | 19 +- sidecars/panel/src/views/StepsDetailView.js | 16 +- .../src/views/settings/SettingsGeneralTab.js | 65 + .../views/settings/SettingsStructureTab.js | 41 +- sidecars/panel/styles.css | 890 ++++++++++- sidecars/panel/test/modern-ui.test.mjs | 627 ++++++++ sidecars/panel/test/quota-pools.test.mjs | 13 + sidecars/panel/test/swarm-mode.test.mjs | 6 +- sidecars/panel/test/window-bridge.test.mjs | 29 +- 35 files changed, 5066 insertions(+), 294 deletions(-) create mode 100644 sidecars/panel/src/styles/modern-ui.css create mode 100644 sidecars/panel/test/modern-ui.test.mjs diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 7102bb2..583283a 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -2,7 +2,7 @@ 'use strict'; // --- shared/settings-normalization.mjs --- -const { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort } = (() => { +const { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort, normalizeExperimentalModernUi } = (() => { /** * @fileoverview 前后端与 CLI 共用的偏好设置枚举常量、默认值与无状态纯函数归一化规则。 */ @@ -451,7 +451,21 @@ function normalizeStandalonePort(port) { if (num >= 1024 && num <= 65535) return num; return 0; } -return { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort }; + +/** + * 归一化实验性现代化新 UI 开关(默认 `false`)。 + * + * @param {unknown} val + * @returns {boolean} + */ +function normalizeExperimentalModernUi(val) { + if (typeof val === 'string') { + const lower = val.trim().toLowerCase(); + return lower === 'true' || lower === '1' || lower === 'on'; + } + return Boolean(val); +} +return { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort, normalizeExperimentalModernUi }; })(); // --- shared/telemetry-display-rules.mjs --- @@ -1171,9 +1185,9 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ // Context Window Widget 'ctx.followActive': '跟随活跃 ({badge})', 'ctx.followActiveTitle': '自动展示当前正在运行或最新活跃的代理上下文窗口', - 'ctx.expandMore': '+{count} 展开 ▾', + 'ctx.expandMore': '+{count} 展开', 'ctx.expandMoreTitle': '展开全部 {count} 个子代理的上下文窗口胶囊', - 'ctx.collapse': '收起 ▴', + 'ctx.collapse': '收起', 'ctx.collapseTitle': '折叠多余子代理胶囊', 'ctx.ch.assistant': '模型回复', 'ctx.ch.assistantTitle': '模型推理思考、回复正文与工具调用入参', @@ -1225,14 +1239,15 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'live.doneWithSteps': '已完成 ({steps} 步)', 'live.waitingWithSteps': '待命中 ({steps} 步)', 'live.killedWithSteps': '已终止 ({steps} 步)', - 'live.subToggleRunning': '子代理 {run}/{total} {arrow}', - 'live.subToggleIdle': '子代理 ({total}) {arrow}', - 'live.swarmToggleRunning': '蜂群 {run}/{total} {arrow}', - 'live.swarmToggleIdle': '蜂群 ({total}) {arrow}', + 'live.subToggleRunning': '子代理 {run}/{total}', + 'live.subToggleIdle': '子代理 ({total})', + 'live.swarmToggleRunning': '蜂群 {run}/{total}', + 'live.swarmToggleIdle': '蜂群 ({total})', 'live.subCollapseTitle': '点击收起子代理列表', 'live.subExpandTitle': '点击展开查看子代理缩略状态', // Consumption View + 'cons.rangeCycle': '周期', 'cons.rangeToday': '今天', 'cons.range24h': '1天', 'cons.range7d': '7天', @@ -1432,6 +1447,10 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.gen.fontLg': '大', 'settings.gen.fontXl': '特大', 'settings.gen.fontHint': '等比缩放侧边栏与展开面板字号,顶栏及输入框内嵌胶囊保持紧凑定高', + 'settings.gen.modernUi': '新 UI(实验性)', + 'settings.gen.modernUiOff': '关闭', + 'settings.gen.modernUiOn': '开启', + 'settings.gen.modernUiHint': '去除大部分线框,采用柔和分层底色与更流畅的现代过渡动画', 'settings.gen.updateTitle': '版本更新', 'settings.gen.updateMode': '更新方式', 'settings.gen.updateManual': '仅提示新版本,手动更新', @@ -1837,9 +1856,9 @@ const I18N_MESSAGES_EN_US = Object.freeze({ // Context Window Widget 'ctx.followActive': 'Follow Active ({badge})', 'ctx.followActiveTitle': 'Automatically inspect the active or running agent context window', - 'ctx.expandMore': '+{count} More ▾', + 'ctx.expandMore': '+{count} More', 'ctx.expandMoreTitle': 'Expand all {count} subagent context pills', - 'ctx.collapse': 'Less ▴', + 'ctx.collapse': 'Less', 'ctx.collapseTitle': 'Collapse extra subagent pills', 'ctx.ch.assistant': 'Assistant', 'ctx.ch.assistantTitle': 'Model reasoning, responses, and tool call arguments', @@ -1891,14 +1910,15 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'live.doneWithSteps': 'Done ({steps} steps)', 'live.waitingWithSteps': 'Waiting ({steps} steps)', 'live.killedWithSteps': 'Killed ({steps} steps)', - 'live.subToggleRunning': 'Subagents {run}/{total} {arrow}', - 'live.subToggleIdle': 'Subagents ({total}) {arrow}', - 'live.swarmToggleRunning': 'Swarm {run}/{total} {arrow}', - 'live.swarmToggleIdle': 'Swarm ({total}) {arrow}', + 'live.subToggleRunning': 'Subagents {run}/{total}', + 'live.subToggleIdle': 'Subagents ({total})', + 'live.swarmToggleRunning': 'Swarm {run}/{total}', + 'live.swarmToggleIdle': 'Swarm ({total})', 'live.subCollapseTitle': 'Collapse subagent list', 'live.subExpandTitle': 'Expand subagent activity list', // Consumption View + 'cons.rangeCycle': 'Cycle', 'cons.rangeToday': 'Today', 'cons.range24h': '24h', 'cons.range7d': '7d', @@ -2098,6 +2118,10 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.gen.fontLg': 'Large', 'settings.gen.fontXl': 'XL', 'settings.gen.fontHint': 'Scales sidebar and popover typography while keeping the inline capsule compact', + 'settings.gen.modernUi': 'Modern UI (Experimental)', + 'settings.gen.modernUiOff': 'Off', + 'settings.gen.modernUiOn': 'On', + 'settings.gen.modernUiHint': 'Removes most borders in favor of soft tonal surfaces and smoother animations', 'settings.gen.updateTitle': 'Updates & Pricing', 'settings.gen.updateMode': 'Update Policy', 'settings.gen.updateManual': 'Notify only, update manually', @@ -2425,7 +2449,7 @@ return { I18N_DICTIONARIES, normalizeI18nLanguage, detectHostSystemLocale, i18nS })(); // --- src/core/appearance.js --- -const { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normalizeClientThemeAccent, normalizeClientFontScale, applyAppearanceToRoot } = (() => { +const { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normalizeClientThemeAccent, normalizeClientFontScale, normalizeClientModernUi, isModernUiActiveForElement, parseCssColorLuminance, detectHostColorScheme, applyAppearanceToRoot } = (() => { /** * @fileoverview Theme accent palette & panel font-scale appearance engine. * Applies CSS custom properties cleanly to Sidebar `:root` and Shadow DOM hosts, @@ -2466,23 +2490,342 @@ function normalizeClientFontScale(raw) { return Object.prototype.hasOwnProperty.call(FONT_SCALE_FACTORS, val) ? val : 'md'; } +function normalizeClientModernUi(raw) { + if (typeof raw === 'string') { + const lower = raw.trim().toLowerCase(); + return lower === 'true' || lower === '1' || lower === 'on'; + } + return Boolean(raw); +} + +/** + * Check whether `el` (or its Shadow DOM host / document root) is currently under `[data-modern-ui="true"]`. + * + * @param {Node | null | undefined} el + * @returns {boolean} + */ +function isModernUiActiveForElement(el) { + let cur = el || null; + while (cur) { + if (typeof cur.getAttribute === 'function' && cur.getAttribute('data-modern-ui') === 'true') { + return true; + } + if (cur.parentNode) { + cur = cur.parentNode; + } else if (cur.host) { + cur = cur.host; + } else { + break; + } + } + if (typeof document !== 'undefined' && document.documentElement) { + return document.documentElement.getAttribute?.('data-modern-ui') === 'true'; + } + return false; +} + +const LIGHT_THEME_CLASSES = new Set([ + 'light', + 'vs-light', + 'vscode-light', + 'hc-light', + 'vscode-high-contrast-light', +]); + +const DARK_THEME_CLASSES = new Set([ + 'dark', + 'vs-dark', + 'vscode-dark', + 'hc-black', + 'vscode-high-contrast', +]); + +function hslToRgb(hDeg, sPct, lPct) { + const h = (((hDeg % 360) + 360) % 360) / 360; + const s = Math.max(0, Math.min(1, sPct / 100)); + const l = Math.max(0, Math.min(1, lPct / 100)); + if (s === 0) { + const v = l * 255; + return [v, v, v]; + } + const hue2rgb = (p, q, t) => { + let tt = t; + if (tt < 0) tt += 1; + if (tt > 1) tt -= 1; + if (tt < 1 / 6) return p + (q - p) * 6 * tt; + if (tt < 1 / 2) return q; + if (tt < 2 / 3) return p + (q - p) * (2 / 3 - tt) * 6; + return p; + }; + const q = l < 0.5 ? l * (1 + s) : l + s - l * s; + const p = 2 * l - q; + return [ + hue2rgb(p, q, h + 1 / 3) * 255, + hue2rgb(p, q, h) * 255, + hue2rgb(p, q, h - 1 / 3) * 255, + ]; +} + +function parseAlphaToken(rawAlpha) { + if (rawAlpha == null || rawAlpha === '') return 1; + const str = String(rawAlpha).trim(); + if (!str) return 1; + if (str.endsWith('%')) { + const pct = parseFloat(str); + return Number.isFinite(pct) ? pct / 100 : 1; + } + const num = parseFloat(str); + return Number.isFinite(num) ? num : 1; +} + +/** + * Parse `#hex`, `rgb()/rgba()`, or `hsl()/hsla()` into perceptual luminance `[0, 1]`. + * Returns `null` when transparent (`alpha <= 0.15`) or unparseable. + * + * @param {string | null | undefined} rawColor + * @returns {number | null} + */ +function parseCssColorLuminance(rawColor) { + const str = String(rawColor ?? '').trim().toLowerCase(); + if (!str || str === 'transparent' || str === 'none' || str === 'inherit' || str === 'initial') { + return null; + } + + if (str.startsWith('#')) { + const hex = str.slice(1); + let r = 0; + let g = 0; + let b = 0; + let a = 1; + if (hex.length === 3 || hex.length === 4) { + r = parseInt(hex[0] + hex[0], 16); + g = parseInt(hex[1] + hex[1], 16); + b = parseInt(hex[2] + hex[2], 16); + if (hex.length === 4) a = parseInt(hex[3] + hex[3], 16) / 255; + } else if (hex.length === 6 || hex.length === 8) { + r = parseInt(hex.slice(0, 2), 16); + g = parseInt(hex.slice(2, 4), 16); + b = parseInt(hex.slice(4, 6), 16); + if (hex.length === 8) a = parseInt(hex.slice(6, 8), 16) / 255; + } else { + return null; + } + if (!Number.isFinite(r) || !Number.isFinite(g) || !Number.isFinite(b) || a <= 0.15) { + return null; + } + return (0.299 * r + 0.587 * g + 0.114 * b) / 255; + } + + const rgbMatch = str.match(/^rgba?\(([^)]+)\)$/); + if (rgbMatch) { + const body = rgbMatch[1].trim(); + const [channelsPart, slashAlpha] = body.split('/'); + const parts = channelsPart + .trim() + .split(/[\s,]+/) + .filter(Boolean); + if (parts.length < 3) return null; + const parseChan = (tok) => + tok.endsWith('%') ? (parseFloat(tok) / 100) * 255 : parseFloat(tok); + const r = parseChan(parts[0]); + const g = parseChan(parts[1]); + const b = parseChan(parts[2]); + const a = slashAlpha !== undefined ? parseAlphaToken(slashAlpha) : parseAlphaToken(parts[3]); + if (!Number.isFinite(r) || !Number.isFinite(g) || !Number.isFinite(b) || a <= 0.15) { + return null; + } + return (0.299 * r + 0.587 * g + 0.114 * b) / 255; + } + + const hslMatch = str.match(/^hsla?\(([^)]+)\)$/); + if (hslMatch) { + const body = hslMatch[1].trim(); + const [channelsPart, slashAlpha] = body.split('/'); + const parts = channelsPart + .trim() + .split(/[\s,]+/) + .filter(Boolean); + if (parts.length < 3) return null; + const h = parseFloat(parts[0]); + const s = parseFloat(parts[1]); + const l = parseFloat(parts[2]); + const a = slashAlpha !== undefined ? parseAlphaToken(slashAlpha) : parseAlphaToken(parts[3]); + if (!Number.isFinite(h) || !Number.isFinite(s) || !Number.isFinite(l) || a <= 0.15) { + return null; + } + const [r, g, b] = hslToRgb(h, s, l); + return (0.299 * r + 0.587 * g + 0.114 * b) / 255; + } + + return null; +} + +function readStyleProp(el, cs, prop) { + if (prop.startsWith('--')) { + const inlineVal = + typeof el?.style?.getPropertyValue === 'function' + ? el.style.getPropertyValue(prop) + : el?.style?.[prop]; + if (inlineVal && String(inlineVal).trim()) return String(inlineVal).trim(); + const compVal = cs?.getPropertyValue?.(prop); + return compVal ? String(compVal).trim() : ''; + } + const inlineVal = el?.style?.[prop]; + if (inlineVal && String(inlineVal).trim()) return String(inlineVal).trim(); + const compVal = cs?.[prop]; + return compVal ? String(compVal).trim() : ''; +} + +/** + * Detect whether the active host surface is `'light'` or `'dark'`. + * Inspects explicit Antigravity / VS Code theme classes & attributes first, + * then actual computed surface/text luminance, then `prefers-color-scheme`. + * + * @param {HTMLElement | null | undefined} [targetEl] + * @returns {'light' | 'dark'} + */ +function detectHostColorScheme(targetEl = null) { + const doc = typeof document !== 'undefined' ? document : null; + const win = typeof window !== 'undefined' ? window : null; + let workbenchEl = null; + try { + workbenchEl = + typeof doc?.querySelector === 'function' ? doc.querySelector('.monaco-workbench') : null; + } catch { + workbenchEl = null; + } + + const candidates = []; + for (const el of [doc?.body, doc?.documentElement, workbenchEl, targetEl]) { + if (el && !candidates.includes(el)) { + candidates.push(el); + } + } + + // 1. Explicit host theme attributes & class tokens (never read our own data-color-scheme) + for (const el of candidates) { + const vscodeKind = String(el.getAttribute?.('data-vscode-theme-kind') || '') + .trim() + .toLowerCase(); + if (vscodeKind) { + if (vscodeKind.includes('light')) return 'light'; + if (vscodeKind.includes('dark') || vscodeKind.includes('high-contrast')) return 'dark'; + } + const dataTheme = String( + el.getAttribute?.('data-theme') || el.getAttribute?.('data-color-mode') || '' + ) + .trim() + .toLowerCase(); + if (dataTheme === 'light' || dataTheme.endsWith('-light')) return 'light'; + if (dataTheme === 'dark' || dataTheme.endsWith('-dark')) return 'dark'; + + const rawCls = typeof el.className === 'string' ? el.className : ''; + if (rawCls) { + const tokens = rawCls.trim().toLowerCase().split(/\s+/); + for (const tok of tokens) { + if (LIGHT_THEME_CLASSES.has(tok)) return 'light'; + if (DARK_THEME_CLASSES.has(tok)) return 'dark'; + } + } + } + + // 2. Computed / inline surface background luminance + const bgTargets = []; + for (const el of [targetEl, doc?.body, doc?.documentElement, workbenchEl]) { + if (el && !bgTargets.includes(el)) { + bgTargets.push(el); + } + } + const bgProps = [ + '--background', + '--card', + '--vscode-sideBar-background', + '--vscode-editor-background', + 'backgroundColor', + ]; + for (const el of bgTargets) { + let cs = null; + try { + cs = typeof win?.getComputedStyle === 'function' ? win.getComputedStyle(el) : null; + } catch { + cs = null; + } + for (const prop of bgProps) { + const lum = parseCssColorLuminance(readStyleProp(el, cs, prop)); + if (lum !== null) { + return lum > 0.52 ? 'light' : 'dark'; + } + } + } + + // 3. Computed / inline foreground text luminance + const fgProps = ['--foreground', '--vscode-foreground', '--vscode-editor-foreground', 'color']; + for (const el of bgTargets) { + let cs = null; + try { + cs = typeof win?.getComputedStyle === 'function' ? win.getComputedStyle(el) : null; + } catch { + cs = null; + } + for (const prop of fgProps) { + const lum = parseCssColorLuminance(readStyleProp(el, cs, prop)); + if (lum !== null) { + return lum < 0.48 ? 'light' : 'dark'; + } + } + } + + // 4. OS media query fallback + try { + if (win?.matchMedia?.('(prefers-color-scheme: dark)')?.matches) { + return 'dark'; + } + } catch { + // ignore matchMedia errors + } + + return 'light'; +} + +function setAttrIfChanged(el, name, value) { + if (!el || typeof el.setAttribute !== 'function') return; + if (typeof el.getAttribute === 'function' && el.getAttribute(name) === value) return; + el.setAttribute(name, value); +} + +function removeAttrIfPresent(el, name) { + if (!el || typeof el.removeAttribute !== 'function') return; + if (typeof el.hasAttribute === 'function' && !el.hasAttribute(name)) return; + el.removeAttribute(name); +} + function setOrClearStyleVar(el, propName, value) { if (!el || !el.style) return; + const cur = + typeof el.style.getPropertyValue === 'function' + ? el.style.getPropertyValue(propName) + : el.style[propName] || ''; if (value) { + if (cur === value) return; if (typeof el.style.setProperty === 'function') { el.style.setProperty(propName, value); } else { el.style[propName] = value; } - } else if (typeof el.style.removeProperty === 'function') { - el.style.removeProperty(propName); - } else if (typeof el.style.setProperty === 'function') { - el.style.setProperty(propName, ''); + } else if (cur) { + if (typeof el.style.removeProperty === 'function') { + el.style.removeProperty(propName); + } else if (typeof el.style.setProperty === 'function') { + el.style.setProperty(propName, ''); + } else { + el.style[propName] = ''; + } } } /** - * Synchronize theme accent and (optionally) font scale tokens onto a root/host element. + * Synchronize theme accent, host color scheme polarity, and (optionally) font scale tokens + * onto a root/host element. * * @param {HTMLElement | null | undefined} targetEl * @param {object | null | undefined} settings @@ -2500,7 +2843,17 @@ function applyAppearanceToRoot(targetEl, settings, { includeFontScale = true } = setOrClearStyleVar(targetEl, '--user-accent-primary', ''); setOrClearStyleVar(targetEl, '--user-accent-contrast', ''); } - targetEl.setAttribute?.('data-accent', preset.key); + setAttrIfChanged(targetEl, 'data-accent', preset.key); + + const colorScheme = detectHostColorScheme(targetEl); + setAttrIfChanged(targetEl, 'data-color-scheme', colorScheme); + + const isModernUi = normalizeClientModernUi(settings?.experimentalModernUi); + if (isModernUi) { + setAttrIfChanged(targetEl, 'data-modern-ui', 'true'); + } else { + removeAttrIfPresent(targetEl, 'data-modern-ui'); + } if (includeFontScale) { const scaleKey = normalizeClientFontScale(settings?.fontScale); @@ -2508,16 +2861,14 @@ function applyAppearanceToRoot(targetEl, settings, { includeFontScale = true } = const panelFactor = PANEL_SCALE_FACTORS[scaleKey] ?? 1; setOrClearStyleVar(targetEl, '--ui-font-scale', factor === 1 ? '' : String(factor)); setOrClearStyleVar(targetEl, '--ui-panel-scale', panelFactor === 1 ? '' : String(panelFactor)); - targetEl.setAttribute?.('data-font-scale', scaleKey); + setAttrIfChanged(targetEl, 'data-font-scale', scaleKey); } else { setOrClearStyleVar(targetEl, '--ui-font-scale', ''); setOrClearStyleVar(targetEl, '--ui-panel-scale', ''); - if (typeof targetEl.removeAttribute === 'function') { - targetEl.removeAttribute('data-font-scale'); - } + removeAttrIfPresent(targetEl, 'data-font-scale'); } } -return { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normalizeClientThemeAccent, normalizeClientFontScale, applyAppearanceToRoot }; +return { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normalizeClientThemeAccent, normalizeClientFontScale, normalizeClientModernUi, isModernUiActiveForElement, parseCssColorLuminance, detectHostColorScheme, applyAppearanceToRoot }; })(); // --- src/core/domPatch.js --- @@ -2655,7 +3006,11 @@ const keyedListState = new WeakMap(); * Keyed incremental list reconciler. * Reuses existing DOM nodes by key and patches only changed items in-place. */ -function patchKeyedList(container, items, { keyFn, sigFn, createRow, updateRow }) { +function patchKeyedList( + container, + items, + { keyFn = (_, i) => i, sigFn, createRow, updateRow, destroyRow } = {} +) { if (!container) return; let map = keyedListState.get(container); if (!map) { @@ -2699,6 +3054,7 @@ function patchKeyedList(container, items, { keyFn, sigFn, createRow, updateRow } if (record.el.parentNode === container) { container.removeChild(record.el); } + destroyRow?.(record.refs, record.el); map.delete(oldKey); } } @@ -4069,6 +4425,7 @@ function isEquivalentTelemetry(prev, next) { if ((pSet?.language ?? 'zh-CN') !== (nSet?.language ?? 'zh-CN')) return false; if ((pSet?.themeAccent ?? 'host') !== (nSet?.themeAccent ?? 'host')) return false; if ((pSet?.fontScale ?? 'md') !== (nSet?.fontScale ?? 'md')) return false; + if (Boolean(pSet?.experimentalModernUi) !== Boolean(nSet?.experimentalModernUi)) return false; if ((prev.hostPlatform || '') !== (next.hostPlatform || '')) return false; if (Boolean(pSet?.contextWindowRiskAccepted) !== Boolean(nSet?.contextWindowRiskAccepted)) { return false; @@ -4769,6 +5126,9 @@ async function saveSettingsPatch(patch) { if (Object.prototype.hasOwnProperty.call(safePatch, 'fontScale')) { safePatch.fontScale = normalizeClientFontScale(safePatch.fontScale); } + if (Object.prototype.hasOwnProperty.call(safePatch, 'experimentalModernUi')) { + safePatch.experimentalModernUi = normalizeClientModernUi(safePatch.experimentalModernUi); + } if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) { safePatch.weeklyLimitMode = normalizeWeeklyLimitMode(safePatch.weeklyLimitMode); } @@ -6203,54 +6563,215 @@ return { CustomScrollbar }; // --- src/components/ui/SegmentedControl.js --- const { SegmentedControl } = (() => { /** - * @fileoverview Micro-bezel (2px radius) SegmentedControl switcher - * for time-range filtering, context limit selection, and sub-table switching. + * @fileoverview Sliding SegmentedControl switcher with variable-width GPU glider. + * Measures active button geometry via ResizeObserver so both inline variable-width + * segments (e.g. "今天 / 1天 / ... / 自定义", "按步查看 (1520) / 总汇总") and equal-width + * grid bars ("常规 / 结构 / 其他") glide smoothly without stretching from 0px on tab reveal. */ const SegmentedControl = defineComponent({ name: 'SegmentedControl', - setup({ getProps, setProps, emit }) { - const rootEl = h('div', { - className: 'segmented', - role: 'group', - 'aria-label': getProps().ariaLabel || '分段切换器', - }); + setup({ getProps, setProps, emit, onCleanup }) { + const gliderEl = h('div', { className: 'seg-glider', 'aria-hidden': 'true' }); + const rootEl = h( + 'div', + { + className: 'segmented', + role: 'group', + 'aria-label': getProps().ariaLabel || '分段切换器', + }, + [gliderEl] + ); + + const btnMap = new Map(); + let orderedBtns = []; + let activeBtnEl = null; + let observedBtnEl = null; + let hasMeasuredVisible = false; + let readyRafId = 0; + + function cancelReadyRaf() { + if (readyRafId && typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function') { + window.cancelAnimationFrame(readyRafId); + } + readyRafId = 0; + } + + function syncGliderGeometry() { + if (!activeBtnEl) { + cancelReadyRaf(); + hasMeasuredVisible = false; + patchClasses(rootEl, { 'has-glider': false }); + patchClasses(gliderEl, { 'is-ready': false }); + return; + } + + const w = Number(activeBtnEl.offsetWidth || 0); + const h = Number(activeBtnEl.offsetHeight || 0); + if (!(w > 0 && h > 0)) { + // Hidden parent tab or headless Mock DOM: keep .seg-btn.is-active fallback background + // and snap cleanly on first real paint when tab becomes visible. + cancelReadyRaf(); + hasMeasuredVisible = false; + patchClasses(rootEl, { 'has-glider': false }); + patchClasses(gliderEl, { 'is-ready': false }); + return; + } + + const x = Number(activeBtnEl.offsetLeft || 0); + const y = Number(activeBtnEl.offsetTop || 0); + patchStyleVar(gliderEl, '--glider-x', `${x}px`); + patchStyleVar(gliderEl, '--glider-y', `${y}px`); + patchStyleVar(gliderEl, '--glider-w', `${w}px`); + patchStyleVar(gliderEl, '--glider-h', `${h}px`); + patchClasses(rootEl, { 'has-glider': true }); + + if (!hasMeasuredVisible) { + hasMeasuredVisible = true; + patchClasses(gliderEl, { 'is-ready': false }); + void gliderEl.offsetWidth; + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + cancelReadyRaf(); + readyRafId = window.requestAnimationFrame(() => { + readyRafId = 0; + if (hasMeasuredVisible) { + patchClasses(gliderEl, { 'is-ready': true }); + } + }); + } else { + patchClasses(gliderEl, { 'is-ready': true }); + } + } + } + + let resizeObs = null; + if (typeof ResizeObserver === 'function') { + resizeObs = new ResizeObserver(() => { + syncGliderGeometry(); + }); + resizeObs.observe(rootEl); + } + + function updateObservedActiveButton(nextActiveBtn) { + if (!resizeObs || observedBtnEl === nextActiveBtn) return; + if (observedBtnEl) { + try { + resizeObs.unobserve(observedBtnEl); + } catch { + // ignore + } + } + observedBtnEl = nextActiveBtn || null; + if (observedBtnEl) { + try { + resizeObs.observe(observedBtnEl); + } catch { + // ignore + } + } + } + + function selectValue(nextVal) { + if (getProps().modelValue !== nextVal) { + setProps({ modelValue: nextVal }); + emit('update:modelValue', nextVal); + } + } function syncSegments() { - const { options = [], modelValue } = getProps(); - patchKeyedList(rootEl, options, { - keyFn: (opt) => opt.value, - sigFn: (opt) => `${opt.value}::${opt.label}::${opt.value === modelValue}`, - createRow: (opt) => { - const btn = h('button', { + const { options = [], modelValue, ariaLabel } = getProps(); + if (ariaLabel) { + patchAttr(rootEl, 'aria-label', ariaLabel); + } + + const validKeys = new Set(options.map((opt) => String(opt.value))); + for (const [key, btn] of btnMap.entries()) { + if (!validKeys.has(key)) { + if (btn.parentNode === rootEl) { + rootEl.removeChild(btn); + } + btnMap.delete(key); + } + } + + orderedBtns = []; + let nextActiveBtn = null; + + for (let i = 0; i < options.length; i++) { + const opt = options[i]; + const key = String(opt.value); + let btn = btnMap.get(key); + if (!btn) { + btn = h('button', { type: 'button', className: 'seg-btn', onClick: (e) => { e.stopPropagation(); - if (getProps().modelValue !== opt.value) { - setProps({ modelValue: opt.value }); - emit('update:modelValue', opt.value); + selectValue(opt.value); + }, + onKeydown: (e) => { + if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') { + e.preventDefault(); + const curOpts = getProps().options || []; + if (!curOpts.length) return; + const curIdx = Math.max( + 0, + curOpts.findIndex((o) => String(o.value) === key) + ); + const delta = e.key === 'ArrowRight' ? 1 : -1; + const nextIdx = (curIdx + delta + curOpts.length) % curOpts.length; + const targetOpt = curOpts[nextIdx]; + if (targetOpt) { + selectValue(targetOpt.value); + btnMap.get(String(targetOpt.value))?.focus?.(); + } } }, }); - return { el: btn, refs: {} }; - }, - updateRow: (_refs, opt, _idx, el) => { - const active = opt.value === modelValue; - patchText(el, opt.label); - patchClasses(el, { 'is-active': active }); - patchAttr(el, 'aria-pressed', active ? 'true' : 'false'); - patchAttr(el, 'data-seg-value', opt.value); - }, - }); + btnMap.set(key, btn); + } + + const active = opt.value === modelValue; + patchText(btn, opt.label); + patchClasses(btn, { 'is-active': active }); + patchAttr(btn, 'aria-pressed', active ? 'true' : 'false'); + patchAttr(btn, 'data-seg-value', opt.value); + orderedBtns.push(btn); + if (active) { + nextActiveBtn = btn; + } + } + + // Ensure gliderEl remains index 0 and buttons follow in exact option order + if (rootEl.firstChild !== gliderEl) { + rootEl.insertBefore(gliderEl, rootEl.firstChild); + } + for (let i = 0; i < orderedBtns.length; i++) { + const targetNode = orderedBtns[i]; + const currentAtSlot = rootEl.children[i + 1] || null; + if (currentAtSlot !== targetNode) { + rootEl.insertBefore(targetNode, currentAtSlot); + } + } + + activeBtnEl = nextActiveBtn || orderedBtns[0] || null; + updateObservedActiveButton(activeBtnEl); + syncGliderGeometry(); } syncSegments(); + onCleanup(() => { + cancelReadyRaf(); + resizeObs?.disconnect?.(); + resizeObs = null; + observedBtnEl = null; + }); + return { el: rootEl, - refs: {}, + refs: { gliderEl, refreshGlider: syncGliderGeometry }, onPropsChange: syncSegments, getValue: () => getProps().modelValue, }; @@ -6813,6 +7334,34 @@ function createTrendAreaChart() { let hoveredIdx = -1; let hoveredCellEl = null; let lastRenderSig = ''; + let tipTrackRaf = 0; + + function cancelTipTrackRaf() { + if (tipTrackRaf && typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function') { + window.cancelAnimationFrame(tipTrackRaf); + } + tipTrackRaf = 0; + } + + function armTooltipTracking(wasHidden) { + if (!wasHidden) return; + patchClasses(tooltipEl, { 'is-tracking': false }); + patchClasses(hoverDot, { 'is-tracking': false }); + void tooltipEl.offsetWidth; + cancelTipTrackRaf(); + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + tipTrackRaf = window.requestAnimationFrame(() => { + tipTrackRaf = 0; + if (!tooltipEl.hasAttribute('hidden')) { + patchClasses(tooltipEl, { 'is-tracking': true }); + patchClasses(hoverDot, { 'is-tracking': true }); + } + }); + } else { + patchClasses(tooltipEl, { 'is-tracking': true }); + patchClasses(hoverDot, { 'is-tracking': true }); + } + } function populateTooltipContent(slot) { patchText(tipTimeEl, slot.fullLabel || slot.label || '--'); @@ -6868,6 +7417,7 @@ function createTrendAreaChart() { clearHover(); return; } + const wasHidden = tooltipEl.hasAttribute('hidden'); hoveredIdx = idx; const slot = currentSlots[idx]; const pt = currentPts[idx]; @@ -6880,19 +7430,31 @@ function createTrendAreaChart() { patchAttr(hoverDot, 'cx', pt.x.toFixed(1)); patchAttr(hoverDot, 'cy', pt.y.toFixed(1)); + const isLineLow = pt.y < Math.round((TOP_Y + BOTTOM_Y) / 2); patchAttr(peakPill, 'hidden', true); patchClasses(tooltipEl, { 'is-hm-bottom': false, 'is-hm-top': false, - 'is-line-low': pt.y < Math.round((TOP_Y + BOTTOM_Y) / 2), + 'is-line-low': isLineLow, }); patchAttr(tooltipEl, 'hidden', false); populateTooltipContent(slot); + let tipY = 0; + if (isLineLow) { + const wrapH = Number(chartWrap.offsetHeight || 0); + const tipH = Number(tooltipEl.offsetHeight || 0); + if (wrapH > 0 && tipH > 0) { + tipY = Math.max(0, wrapH - tipH - 22); + } + } + const rawPct = (pt.x / viewW) * 100; const clampedPct = Math.max(1, Math.min(99, rawPct)); patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`); patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`); + patchStyleVar(tooltipEl, '--tip-y', `${Math.round(tipY)}px`); + armTooltipTracking(wasHidden); for (const [tIdx, el] of tickElsByIdx.entries()) { patchClasses(el, { 'is-hovered': tIdx === idx }); @@ -6920,6 +7482,7 @@ function createTrendAreaChart() { const row = Number(targetCell.getAttribute('data-hm-row') || 0); const col = Number(targetCell.getAttribute('data-hm-col') || 0); + const wasHidden = tooltipEl.hasAttribute('hidden'); // 上半区(周一~周四)浮层停靠热力图下方,下半区(周五~周日)停靠热力图上方,互不遮挡被悬停格子且永不越界裁剪 patchClasses(tooltipEl, { 'is-hm-bottom': row <= 3, @@ -6946,14 +7509,23 @@ function createTrendAreaChart() { const clampedPct = Math.max(1, Math.min(99, rawPct)); patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`); patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`); + patchStyleVar(tooltipEl, '--tip-y', '0px'); + armTooltipTracking(wasHidden); } function clearHover() { + cancelTipTrackRaf(); hoveredIdx = -1; patchAttr(hoverLine, 'hidden', true); patchAttr(hoverDot, 'hidden', true); patchAttr(tooltipEl, 'hidden', true); - patchClasses(tooltipEl, { 'is-hm-bottom': false, 'is-hm-top': false, 'is-line-low': false }); + patchClasses(tooltipEl, { + 'is-hm-bottom': false, + 'is-hm-top': false, + 'is-line-low': false, + 'is-tracking': false, + }); + patchClasses(hoverDot, { 'is-tracking': false }); if (!currentIsHeatmap) { patchAttr(peakPill, 'hidden', false); } @@ -7165,6 +7737,7 @@ function createTrendAreaChart() { } function destroy() { + cancelTipTrackRaf(); resizeObs?.disconnect(); resizeObs = null; if (onWinResize && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') { @@ -8221,6 +8794,7 @@ function createSessionLineChart() { clearHover(); return; } + const wasHidden = tooltipEl.hasAttribute('hidden'); hoveredIdx = idx; const pt = currentPoints[idx]; patchAttr(hoverLine, 'hidden', false); @@ -8251,6 +8825,20 @@ function createSessionLineChart() { const clampedPct = Math.max(1, Math.min(99, rawPct)); patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`); patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`); + patchStyleVar(tooltipEl, '--tip-y', '0px'); + if (wasHidden) { + patchClasses(tooltipEl, { 'is-tracking': false }); + void tooltipEl.offsetWidth; + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + window.requestAnimationFrame(() => { + if (!tooltipEl.hasAttribute('hidden')) { + patchClasses(tooltipEl, { 'is-tracking': true }); + } + }); + } else { + patchClasses(tooltipEl, { 'is-tracking': true }); + } + } for (const [tIdx, el] of tickElsByIdx.entries()) { patchClasses(el, { 'is-hovered': tIdx === idx }); @@ -8262,6 +8850,7 @@ function createSessionLineChart() { patchAttr(hoverLine, 'hidden', true); patchAttr(hoverDot, 'hidden', true); patchAttr(tooltipEl, 'hidden', true); + patchClasses(tooltipEl, { 'is-tracking': false }); if (currentPoints.some((p) => p.valid)) { patchAttr(peakPill, 'hidden', false); } @@ -9015,6 +9604,7 @@ function createModelFitChart() { patchAttr(hoverRawDot, 'cx', sp.x.toFixed(1)); patchAttr(hoverRawDot, 'cy', sp.rawY.toFixed(1)); + const wasHidden = tooltipEl.hasAttribute('hidden'); patchAttr(tooltipEl, 'hidden', false); patchText(tipHeadLeft, sp.stepTag); patchText(tipHeadRight, sp.modelText); @@ -9050,6 +9640,20 @@ function createModelFitChart() { const clampedPct = Math.max(1, Math.min(99, rawPct)); patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`); patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`); + patchStyleVar(tooltipEl, '--tip-y', '0px'); + if (wasHidden) { + patchClasses(tooltipEl, { 'is-tracking': false }); + void tooltipEl.offsetWidth; + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + window.requestAnimationFrame(() => { + if (!tooltipEl.hasAttribute('hidden')) { + patchClasses(tooltipEl, { 'is-tracking': true }); + } + }); + } else { + patchClasses(tooltipEl, { 'is-tracking': true }); + } + } } function clearHover() { @@ -9058,6 +9662,7 @@ function createModelFitChart() { patchAttr(hoverFitDot, 'hidden', true); patchAttr(hoverRawDot, 'hidden', true); patchAttr(tooltipEl, 'hidden', true); + patchClasses(tooltipEl, { 'is-tracking': false }); } plotStage.addEventListener('mousemove', (e) => { @@ -10433,8 +11038,8 @@ const CTX_ASCII_CHAR_PX = 6.1; const CTX_PILL_GAP_PX = 4; const CTX_DEFAULT_BAR_WIDTH_PX = 310; -function estimateCtxPillWidth(text) { - let w = CTX_PILL_BASE_PAD_PX; +function estimateCtxPillWidth(text, withChevron = false) { + let w = CTX_PILL_BASE_PAD_PX + (withChevron ? 14 : 0); for (const ch of String(text || '')) { w += ch.charCodeAt(0) > 255 ? CTX_CJK_CHAR_PX : CTX_ASCII_CHAR_PX; } @@ -10647,9 +11252,30 @@ const ContextWindowWidget = defineComponent({ let latestData = null; let ctxPillsExpanded = false; + let isCollapsingCtxPills = false; + let ctxCollapseTimer = null; let lastCascadeId = ''; let cachedBarWidth = 0; + function clearCtxExpandAnim() { + if (ctxCollapseTimer) { + clearTimeout(ctxCollapseTimer); + ctxCollapseTimer = null; + } + isCollapsingCtxPills = false; + ctxInspectorBar.ontransitionend = null; + ctxInspectorBar.style.height = ''; + ctxInspectorBar.style.overflow = ''; + ctxInspectorBar.style.transition = ''; + for (const child of ctxPillGroup.children) { + child.onanimationend = null; + patchClasses(child, { + 'is-pill-entering': false, + 'is-pill-collapsing': false, + }); + } + } + function update({ data } = {}) { latestData = data || null; const curLocale = getEffectiveLocale(); @@ -10680,6 +11306,7 @@ const ContextWindowWidget = defineComponent({ const currentCascadeId = data.activeConversation?.cascadeId || ''; if (currentCascadeId && currentCascadeId !== lastCascadeId) { if (lastCascadeId) { + clearCtxExpandAnim(); ctxPillsExpanded = false; } lastCascadeId = currentCascadeId; @@ -10711,7 +11338,10 @@ const ContextWindowWidget = defineComponent({ if (interactiveInspector) { patchAttr(ctxInspectorBar, 'hidden', !hasSubagents); - if (hasSubagents && ctxAgent) { + if (!hasSubagents && isCollapsingCtxPills) { + clearCtxExpandAnim(); + } + if (hasSubagents && ctxAgent && !isCollapsingCtxPills) { const activeBadgeText = formatAgentBadgeText({ agentKind: aggregated?.activeAgentKind || @@ -10758,7 +11388,7 @@ const ContextWindowWidget = defineComponent({ if (needsCollapse && !ctxPillsExpanded) { const toggleSample = t('ctx.expandMore', { count: allAgentPills.length }); - const toggleReservePx = CTX_PILL_GAP_PX + estimateCtxPillWidth(toggleSample); + const toggleReservePx = CTX_PILL_GAP_PX + estimateCtxPillWidth(toggleSample, true); let usedW = firstPillWidth; let fitCount = 0; for (let i = 0; i < allAgentPills.length; i += 1) { @@ -10789,6 +11419,7 @@ const ContextWindowWidget = defineComponent({ title: t('ctx.expandMoreTitle', { count: allAgentPills.length - 1 }), isActive: false, isMoreToggle: true, + isExpanded: false, mode: 'toggle-expand', }); } else { @@ -10800,6 +11431,7 @@ const ContextWindowWidget = defineComponent({ title: t('ctx.collapseTitle'), isActive: false, isMoreToggle: true, + isExpanded: true, mode: 'toggle-expand', }); } @@ -10808,22 +11440,117 @@ const ContextWindowWidget = defineComponent({ patchKeyedList(ctxPillGroup, pillItems, { keyFn: (item) => item.key, sigFn: (item) => - `${item.key}:${item.label}:${item.isActive}:${item.isMoreToggle}:${item.mode}:${item.title}`, + `${item.key}:${item.label}:${item.isActive}:${item.isMoreToggle}:${Boolean(item.isExpanded)}:${item.mode}:${item.title}`, createRow: () => { - const btn = h('button', { type: 'button', className: 'ctx-agent-pill' }); - return { el: btn, refs: { btn } }; + const labelSpan = h('span', { className: 'ctx-pill-label' }); + const chevronEl = createSvgIcon('chevron-down', { + size: 11, + className: 'ctx-toggle-chevron', + }); + patchAttr(chevronEl, 'hidden', true); + const btn = h('button', { type: 'button', className: 'ctx-agent-pill' }, [ + labelSpan, + chevronEl, + ]); + return { el: btn, refs: { btn, labelSpan, chevronEl } }; }, updateRow: (refs, item) => { - patchText(refs.btn, item.label); + patchText(refs.labelSpan, item.label); + patchAttr(refs.chevronEl, 'hidden', !item.isMoreToggle); patchAttr(refs.btn, 'title', item.title); + patchAttr(refs.btn, 'data-pill-key', item.key); patchClasses(refs.btn, { 'is-active': item.isActive, 'is-more-toggle': Boolean(item.isMoreToggle), + 'is-expanded': Boolean(item.isExpanded), + 'is-pill-collapsing': false, }); refs.btn.onclick = () => { if (item.mode === 'toggle-expand') { - ctxPillsExpanded = !ctxPillsExpanded; - if (latestData) update({ data: latestData }); + const modern = isModernUiActiveForElement(ctxPanel); + const startH = Number(ctxInspectorBar.offsetHeight || 0); + clearCtxExpandAnim(); + if (!modern || !(startH > 0)) { + ctxPillsExpanded = !ctxPillsExpanded; + if (latestData) update({ data: latestData }); + return; + } + + if (!ctxPillsExpanded) { + const prevKeys = new Set( + Array.from(ctxPillGroup.children, (el) => el.getAttribute?.('data-pill-key') || '') + ); + ctxPillsExpanded = true; + if (latestData) update({ data: latestData }); + const endH = Number(ctxPillGroup.offsetHeight || 0); + for (const child of ctxPillGroup.children) { + const k = child.getAttribute?.('data-pill-key') || ''; + if (k && k !== '__toggle_more__' && !prevKeys.has(k)) { + patchClasses(child, { 'is-pill-entering': true }); + child.onanimationend = () => { + child.onanimationend = null; + patchClasses(child, { 'is-pill-entering': false }); + }; + } + } + if (endH > startH + 1) { + ctxInspectorBar.style.height = `${startH}px`; + ctxInspectorBar.style.overflow = 'hidden'; + void ctxInspectorBar.offsetHeight; + ctxInspectorBar.style.transition = + 'height 220ms cubic-bezier(0.16, 1, 0.3, 1)'; + ctxInspectorBar.style.height = `${endH}px`; + const finishExpand = () => clearCtxExpandAnim(); + ctxInspectorBar.ontransitionend = (ev) => { + if ( + ev?.target === ctxInspectorBar && + (!ev.propertyName || ev.propertyName === 'height') + ) { + finishExpand(); + } + }; + ctxCollapseTimer = setTimeout(finishExpand, 260); + } + } else { + const firstPill = ctxPillGroup.children[0] || null; + const firstTop = Number(firstPill?.offsetTop || 0); + let firstRowH = Number(firstPill?.offsetHeight || 20); + for (const child of ctxPillGroup.children) { + const top = Number(child.offsetTop || 0); + if (top <= firstTop + 4) { + const bottom = top - firstTop + Number(child.offsetHeight || 0); + if (bottom > firstRowH) firstRowH = bottom; + } + } + const targetH = Math.max(18, firstRowH); + ctxPillsExpanded = false; + isCollapsingCtxPills = true; + patchClasses(refs.btn, { 'is-expanded': false }); + for (const child of ctxPillGroup.children) { + if (Number(child.offsetTop || 0) > firstTop + 4) { + patchClasses(child, { 'is-pill-collapsing': true }); + } + } + ctxInspectorBar.style.height = `${startH}px`; + ctxInspectorBar.style.overflow = 'hidden'; + void ctxInspectorBar.offsetHeight; + ctxInspectorBar.style.transition = + 'height 200ms cubic-bezier(0.16, 1, 0.3, 1)'; + ctxInspectorBar.style.height = `${targetH}px`; + const finishCollapse = () => { + clearCtxExpandAnim(); + if (latestData) update({ data: latestData }); + }; + ctxInspectorBar.ontransitionend = (ev) => { + if ( + ev?.target === ctxInspectorBar && + (!ev.propertyName || ev.propertyName === 'height') + ) { + finishCollapse(); + } + }; + ctxCollapseTimer = setTimeout(finishCollapse, 240); + } } else { setCtxAgentId(item.key); } @@ -10902,6 +11629,7 @@ const ContextWindowWidget = defineComponent({ } onCleanup(() => { + clearCtxExpandAnim(); if (ro) ro.disconnect(); ctxSegmentBar.destroy(); }); @@ -11444,6 +12172,38 @@ const LiveActivityWidget = defineComponent({ } } + function readComputedPx(el, prop, fallback) { + if (!el || typeof window === 'undefined' || typeof window.getComputedStyle !== 'function') { + return fallback; + } + try { + const val = parseFloat(window.getComputedStyle(el)?.[prop]); + return Number.isFinite(val) ? val : fallback; + } catch { + return fallback; + } + } + + function clearSubExpandAnim(refs) { + if (!refs) return; + if (refs.subAnimTimer) { + clearTimeout(refs.subAnimTimer); + refs.subAnimTimer = null; + } + refs.isCollapsingSubs = false; + const host = refs.subScroll?.el; + if (host) { + host.ontransitionend = null; + patchClasses(host, { 'is-sub-animating': false }); + host.style.height = ''; + host.style.paddingTop = ''; + host.style.marginTop = ''; + host.style.opacity = ''; + host.style.overflow = ''; + host.style.transition = ''; + } + } + function createLiveTaskCard() { const dotIcon = createSvgIcon('dot', { size: 11 }); patchClasses(dotIcon, { 'is-pulsing': true }); @@ -11466,12 +12226,23 @@ const LiveActivityWidget = defineComponent({ text: '', }) : null; - const subToggleBtn = h('button', { - type: 'button', - className: 'live-sub-toggle', - hidden: true, - text: t('live.subToggleIdle', { total: 0, arrow: '▸' }), + const subToggleLabel = h('span', { + className: 'live-sub-toggle-label', + text: t('live.subToggleIdle', { total: 0 }), }); + const subToggleChevron = createSvgIcon('chevron-down', { + size: 11, + className: 'live-sub-toggle-chevron', + }); + const subToggleBtn = h( + 'button', + { + type: 'button', + className: 'live-sub-toggle', + hidden: true, + }, + [subToggleLabel, subToggleChevron] + ); const elapsedEl = h('span', { className: 'live-activity-elapsed text-mono', text: '0s', @@ -11520,7 +12291,16 @@ const LiveActivityWidget = defineComponent({ ]); const subListEl = h('div', { className: 'live-sub-list', hidden: true }); - const cardEl = h('div', { className: 'live-task-card' }, [headerEl, mainRowEl, subListEl]); + const subScroll = CustomScrollbar({ + contentEl: subListEl, + className: 'live-sub-scroll-host', + }); + patchAttr(subScroll.el, 'hidden', true); + const cardEl = h('div', { className: 'live-task-card' }, [ + headerEl, + mainRowEl, + subScroll.el, + ]); return { el: cardEl, @@ -11531,6 +12311,8 @@ const LiveActivityWidget = defineComponent({ hereTagEl, metricsEl, subToggleBtn, + subToggleLabel, + subToggleChevron, elapsedEl, mainBadge, mainPhase, @@ -11538,6 +12320,9 @@ const LiveActivityWidget = defineComponent({ mainSep, mainDetail, subListEl, + subScroll, + subAnimTimer: null, + isCollapsingSubs: false, }, }; } @@ -11599,7 +12384,12 @@ const LiveActivityWidget = defineComponent({ patchAttr(liveActivityBar, 'hidden', !hasRunningTasks); if (!hasRunningTasks) { stopLiveTicker(); - patchKeyedList(liveActivityBar, [], {}); + patchKeyedList(liveActivityBar, [], { + destroyRow: (refs) => { + clearSubExpandAnim(refs); + refs?.subScroll?.destroy?.(); + }, + }); return; } @@ -11726,19 +12516,16 @@ const LiveActivityWidget = defineComponent({ patchAttr(refs.mainBadge, 'hidden', subCount === 0); patchAttr(refs.subToggleBtn, 'hidden', subCount === 0); if (subCount > 0) { - const arrow = isExpanded ? '▾' : '▸'; const toggleText = runSubCount > 0 ? t(isPureSwarm ? 'live.swarmToggleRunning' : 'live.subToggleRunning', { run: runSubCount, total: subCount, - arrow, }) : t(isPureSwarm ? 'live.swarmToggleIdle' : 'live.subToggleIdle', { total: subCount, - arrow, }); - patchText(refs.subToggleBtn, toggleText); + patchText(refs.subToggleLabel, toggleText); patchClasses(refs.subToggleBtn, { 'is-expanded': isExpanded }); if (interactive) { patchAttr( @@ -11748,11 +12535,108 @@ const LiveActivityWidget = defineComponent({ ); refs.subToggleBtn.onclick = (e) => { e.stopPropagation(); - manualSubExpandMap.set(item.cascadeId, !isExpanded); - if (latestUpdateArgs) update(latestUpdateArgs); - onLayoutChange?.(); + const nextExpanded = !resolveIsExpanded(item); + const host = refs.subScroll.el; + const curH = Number(host.offsetHeight || 0); + const curPadTop = readComputedPx(host, 'paddingTop', 6); + const curMarginTop = readComputedPx(host, 'marginTop', 3); + const curOpacity = readComputedPx(host, 'opacity', 1); + const parentGap = readComputedPx(refs.cardEl, 'rowGap', 7); + const collapsedMarginTop = -Math.max(0, Math.round(parentGap)); + const wasMidAnim = Boolean(refs.subAnimTimer); + clearSubExpandAnim(refs); + manualSubExpandMap.set(item.cascadeId, nextExpanded); + + const modern = isModernUiActiveForElement(refs.cardEl); + if (!modern) { + if (latestUpdateArgs) update(latestUpdateArgs); + onLayoutChange?.(); + return; + } + + if (nextExpanded) { + if (latestUpdateArgs) update(latestUpdateArgs); + const endH = Number(host.offsetHeight || host.scrollHeight || 0); + const endPadTop = readComputedPx(host, 'paddingTop', 6); + const endMarginTop = readComputedPx(host, 'marginTop', 3); + const fromH = wasMidAnim && curH > 0 ? curH : 0; + const fromPadTop = wasMidAnim && curH > 0 ? curPadTop : 0; + const fromMarginTop = wasMidAnim && curH > 0 ? curMarginTop : collapsedMarginTop; + const fromOpacity = wasMidAnim && curH > 0 ? curOpacity : 0; + if (endH > 0) { + patchClasses(host, { 'is-sub-animating': true }); + host.style.height = `${fromH}px`; + host.style.paddingTop = `${fromPadTop}px`; + host.style.marginTop = `${fromMarginTop}px`; + host.style.opacity = `${fromOpacity}`; + host.style.overflow = 'hidden'; + void host.offsetHeight; + host.style.transition = + 'height 220ms cubic-bezier(0.16, 1, 0.3, 1), padding-top 220ms cubic-bezier(0.16, 1, 0.3, 1), margin-top 220ms cubic-bezier(0.16, 1, 0.3, 1), opacity 180ms ease-out'; + host.style.height = `${endH}px`; + host.style.paddingTop = `${endPadTop}px`; + host.style.marginTop = `${endMarginTop}px`; + host.style.opacity = '1'; + const finishExpand = () => { + clearSubExpandAnim(refs); + refs.subScroll.refresh(); + onLayoutChange?.(); + }; + host.ontransitionend = (ev) => { + if ( + ev?.target === host && + (!ev.propertyName || ev.propertyName === 'height') + ) { + finishExpand(); + } + }; + refs.subAnimTimer = setTimeout(finishExpand, 260); + } else { + onLayoutChange?.(); + } + } else { + patchClasses(refs.subToggleBtn, { 'is-expanded': false }); + patchAttr(refs.subToggleBtn, 'title', t('live.subExpandTitle')); + if (curH > 0) { + refs.isCollapsingSubs = true; + patchClasses(host, { 'is-sub-animating': true }); + host.style.height = `${curH}px`; + host.style.paddingTop = `${curPadTop}px`; + host.style.marginTop = `${curMarginTop}px`; + host.style.opacity = `${curOpacity}`; + host.style.overflow = 'hidden'; + void host.offsetHeight; + host.style.transition = + 'height 200ms cubic-bezier(0.16, 1, 0.3, 1), padding-top 200ms cubic-bezier(0.16, 1, 0.3, 1), margin-top 200ms cubic-bezier(0.16, 1, 0.3, 1), opacity 150ms ease-out'; + host.style.height = '0px'; + host.style.paddingTop = '0px'; + host.style.marginTop = `${collapsedMarginTop}px`; + host.style.opacity = '0'; + const finishCollapse = () => { + clearSubExpandAnim(refs); + patchAttr(host, 'hidden', true); + patchAttr(refs.subListEl, 'hidden', true); + if (latestUpdateArgs) update(latestUpdateArgs); + onLayoutChange?.(); + }; + host.ontransitionend = (ev) => { + if ( + ev?.target === host && + (!ev.propertyName || ev.propertyName === 'height') + ) { + finishCollapse(); + } + }; + refs.subAnimTimer = setTimeout(finishCollapse, 240); + } else { + if (latestUpdateArgs) update(latestUpdateArgs); + onLayoutChange?.(); + } + } }; } + } else if (refs.isCollapsingSubs) { + clearSubExpandAnim(refs); } const mainLabel = formatLiveActivityLabel(act, 'live.thinking'); @@ -11783,7 +12667,10 @@ const LiveActivityWidget = defineComponent({ } const showSubs = subCount > 0 && isExpanded; - patchAttr(refs.subListEl, 'hidden', !showSubs); + if (!refs.isCollapsingSubs) { + patchAttr(refs.subScroll.el, 'hidden', !showSubs); + patchAttr(refs.subListEl, 'hidden', !showSubs); + } if (showSubs) { const rawSubItems = item.subagents || []; const getSubSortRank = (s) => { @@ -11898,8 +12785,13 @@ const LiveActivityWidget = defineComponent({ } }, }); + refs.subScroll.refresh(); } }, + destroyRow: (refs) => { + clearSubExpandAnim(refs); + refs?.subScroll?.destroy?.(); + }, }); for (const key of [...activityTimersMap.keys()]) { @@ -11913,6 +12805,12 @@ const LiveActivityWidget = defineComponent({ onCleanup(() => { stopLiveTicker(); + patchKeyedList(liveActivityBar, [], { + destroyRow: (refs) => { + clearSubExpandAnim(refs); + refs?.subScroll?.destroy?.(); + }, + }); }); return { @@ -13081,6 +13979,43 @@ const StepTableWidget = defineComponent({ const hoverRows = new WeakMap(); let lastRenderedRows = null; let lastRenderOptions = ''; + let trackedCascadeId = null; + const seenStepKeys = new Set(); + const maxSeenStepByAgent = new Map(); + const activeEnterTimers = new Map(); + + function getStepRowIdentity(st, fallbackCascadeId) { + const agentKey = String(st?.agentCascadeId || fallbackCascadeId || 'conv'); + const stepNum = Number(st?.stepIndex); + const rowKey = `${agentKey}-${st?.stepIndex}`; + return { agentKey, stepNum, rowKey }; + } + + function absorbStepsIntoBaseline(stepList, fallbackCascadeId) { + if (!Array.isArray(stepList)) return; + for (const st of stepList) { + if (!st || typeof st !== 'object') continue; + const { agentKey, stepNum, rowKey } = getStepRowIdentity(st, fallbackCascadeId); + seenStepKeys.add(rowKey); + if (Number.isFinite(stepNum)) { + const prevMax = maxSeenStepByAgent.get(agentKey); + if (prevMax === undefined || stepNum > prevMax) { + maxSeenStepByAgent.set(agentKey, stepNum); + } + } + } + } + + function clearRowEnterState(tr) { + if (!tr) return; + const timer = activeEnterTimers.get(tr); + if (timer) { + clearTimeout(timer); + activeEnterTimers.delete(tr); + } + tr.onanimationend = null; + patchClasses(tr, { 'is-step-entering': false }); + } function enterStepCell(event) { const { badge, prompt } = hoverRows.get(this); @@ -13121,8 +14056,37 @@ const StepTableWidget = defineComponent({ showStepSpeedColor = false, stepTokenComboFormat = undefined, displaySettings = {}, + allConversationSteps = null, + allowNewRowFade = false, } = {} ) { + const normCascadeId = String(cascadeId || ''); + let enteringRowKeys = null; + if (!normCascadeId || trackedCascadeId === null || normCascadeId !== trackedCascadeId) { + trackedCascadeId = normCascadeId || null; + seenStepKeys.clear(); + maxSeenStepByAgent.clear(); + absorbStepsIntoBaseline(allConversationSteps, normCascadeId); + absorbStepsIntoBaseline(tableSteps, normCascadeId); + } else if (!allowNewRowFade || standalone) { + absorbStepsIntoBaseline(allConversationSteps, normCascadeId); + absorbStepsIntoBaseline(tableSteps, normCascadeId); + } else { + for (const st of tableSteps) { + if (!st || typeof st !== 'object') continue; + const { agentKey, stepNum, rowKey } = getStepRowIdentity(st, normCascadeId); + if (!seenStepKeys.has(rowKey)) { + const prevMax = maxSeenStepByAgent.get(agentKey); + if (prevMax === undefined || !Number.isFinite(stepNum) || stepNum > prevMax) { + enteringRowKeys ??= new Set(); + enteringRowKeys.add(rowKey); + } + } + } + absorbStepsIntoBaseline(allConversationSteps, normCascadeId); + absorbStepsIntoBaseline(tableSteps, normCascadeId); + } + const colOrderSig = colKeys.join(','); const normTokenFmt = normalizeClientStepTokenComboFormat(stepTokenComboFormat); const renderOptions = JSON.stringify([ @@ -13374,6 +14338,21 @@ const StepTableWidget = defineComponent({ hoverTd.onmousemove = firstColKey === 'step' ? moveInStepCell : moveAlongTurnRail; hoverTd.onmouseleave = hideTurnTip; } + + if (enteringRowKeys?.has(item.rowKey)) { + clearRowEnterState(tr); + patchClasses(tr, { 'is-step-entering': true }); + tr.onanimationend = (ev) => { + if (!ev || !ev.target || ev.target === tr) { + clearRowEnterState(tr); + } + }; + const timer = setTimeout(() => clearRowEnterState(tr), 960); + activeEnterTimers.set(tr, timer); + } + }, + destroyRow: (_refs, tr) => { + clearRowEnterState(tr); }, }); lastRenderOptions = renderOptions; @@ -13383,6 +14362,9 @@ const StepTableWidget = defineComponent({ onCleanup(() => { stepsTablePane.removeEventListener('scroll', hideTurnTip); stepsTbody.removeEventListener('mouseleave', hideTurnTip); + for (const tr of [...activeEnterTimers.keys()]) { + clearRowEnterState(tr); + } }); return { @@ -14937,6 +15919,13 @@ function getFontScaleOptions() { ]; } +function getModernUiOptions() { + return [ + { value: 'off', label: t('settings.gen.modernUiOff') }, + { value: 'on', label: t('settings.gen.modernUiOn') }, + ]; +} + function getUpdateModeOptions() { return [ { value: 'manual', label: t('settings.gen.updateManual') }, @@ -14964,6 +15953,7 @@ const SettingsGeneralTab = defineComponent({ let draftLanguage = 'zh-CN'; let draftThemeAccent = 'host'; let draftFontScale = 'md'; + let draftModernUi = false; let draftPluginUpdateMode = 'manual'; let latestSettings = null; let latestCloudStatus = null; @@ -15021,6 +16011,14 @@ const SettingsGeneralTab = defineComponent({ className: 'settings-hint-text', text: t('settings.gen.fontHint'), }); + const modernUiLabelEl = h('span', { + className: 'form-label', + text: t('settings.gen.modernUi'), + }); + const modernUiHintEl = h('span', { + className: 'settings-hint-text', + text: t('settings.gen.modernUiHint'), + }); const languageSwitch = SegmentedControl({ ariaLabel: t('settings.gen.language'), @@ -15079,6 +16077,38 @@ const SettingsGeneralTab = defineComponent({ }, }); + const modernUiSwitch = SegmentedControl({ + ariaLabel: t('settings.gen.modernUi'), + modelValue: 'off', + options: getModernUiOptions(), + onUpdateModelValue: async (val) => { + const nextModernUi = val === 'on'; + draftModernUi = nextModernUi; + modernUiSwitch.setValue(nextModernUi ? 'on' : 'off'); + if (typeof document !== 'undefined' && document.documentElement) { + applyAppearanceToRoot( + document.documentElement, + { + ...(latestSettings || {}), + themeAccent: draftThemeAccent, + fontScale: draftFontScale, + experimentalModernUi: nextModernUi, + }, + { includeFontScale: true } + ); + } + showAppearanceFeedback(t('settings.saving'), 0); + try { + await saveSettingsPatch({ experimentalModernUi: nextModernUi }); + showAppearanceFeedback(t('settings.saved'), 1500); + props.onLayoutChange?.(); + } catch { + if (latestSettings) renderSettings(latestSettings); + showAppearanceFeedback(t('settings.saveFailed'), 2500); + } + }, + }); + const appearancePanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title' }, [ @@ -15090,6 +16120,7 @@ const SettingsGeneralTab = defineComponent({ h('div', { className: 'form-row' }, [langLabelEl, languageSwitch.el]), h('div', { className: 'form-row' }, [accentLabelEl, themeColorPicker.el]), h('div', { className: 'form-row' }, [fontLabelEl, fontScaleSwitch.el, fontHintEl]), + h('div', { className: 'form-row' }, [modernUiLabelEl, modernUiSwitch.el, modernUiHintEl]), ]); // --- Card 2: 版本更新 --- @@ -15248,6 +16279,7 @@ const SettingsGeneralTab = defineComponent({ draftLanguage = normalizeI18nLanguage(settings.language); draftThemeAccent = normalizeClientThemeAccent(settings.themeAccent); draftFontScale = normalizeClientFontScale(settings.fontScale); + draftModernUi = normalizeClientModernUi(settings.experimentalModernUi); draftPluginUpdateMode = normalizeClientUpdateMode( settings.pluginUpdateMode, settings.autoUpdatePlugin @@ -15262,6 +16294,10 @@ const SettingsGeneralTab = defineComponent({ modelValue: draftFontScale, options: getFontScaleOptions(), }); + modernUiSwitch.setProps({ + modelValue: draftModernUi ? 'on' : 'off', + options: getModernUiOptions(), + }); autoUpdateSelect.setProps({ modelValue: draftPluginUpdateMode, options: getUpdateModeOptions(), @@ -15323,6 +16359,8 @@ const SettingsGeneralTab = defineComponent({ patchText(accentLabelEl, t('settings.gen.themeAccent')); patchText(fontLabelEl, t('settings.gen.fontScale')); patchText(fontHintEl, t('settings.gen.fontHint')); + patchText(modernUiLabelEl, t('settings.gen.modernUi')); + patchText(modernUiHintEl, t('settings.gen.modernUiHint')); patchText(updateTitleEl, t('settings.gen.updateTitle')); patchText(updateModeLabelEl, t('settings.gen.updateMode')); patchText(pricingCellLabelEl, t('settings.gen.pricingLabel')); @@ -15339,6 +16377,11 @@ const SettingsGeneralTab = defineComponent({ modelValue: draftFontScale, options: getFontScaleOptions(), }); + modernUiSwitch.setProps({ + ariaLabel: t('settings.gen.modernUi'), + modelValue: draftModernUi ? 'on' : 'off', + options: getModernUiOptions(), + }); autoUpdateSelect.setProps({ modelValue: draftPluginUpdateMode, options: getUpdateModeOptions(), @@ -15356,6 +16399,7 @@ const SettingsGeneralTab = defineComponent({ languageSwitch.destroy(); themeColorPicker.destroy(); fontScaleSwitch.destroy(); + modernUiSwitch.destroy(); autoUpdateSelect.destroy(); }); @@ -15365,6 +16409,7 @@ const SettingsGeneralTab = defineComponent({ languageSwitch, themeColorPicker, fontScaleSwitch, + modernUiSwitch, autoUpdateSelect, syncPricingBtn, updatePluginBtn, @@ -15515,10 +16560,29 @@ const SettingsStructureTab = defineComponent({ 'aria-selected': item.key === activeThirdTab ? 'true' : 'false', 'data-structure-tab': item.key, onClick: () => { + applyActiveThirdTab(item.key); if (uiStore.getState().settingsStructureTab !== item.key) { uiStore.setState({ settingsStructureTab: item.key }); - } else { - applyActiveThirdTab(item.key); + } + }, + onKeydown: (e) => { + if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') { + e.preventDefault(); + const curIdx = Math.max( + 0, + STRUCTURE_THIRD_TABS.findIndex((it) => it.key === item.key) + ); + const delta = e.key === 'ArrowRight' ? 1 : -1; + const nextIdx = + (curIdx + delta + STRUCTURE_THIRD_TABS.length) % STRUCTURE_THIRD_TABS.length; + const nextItem = STRUCTURE_THIRD_TABS[nextIdx]; + if (nextItem) { + applyActiveThirdTab(nextItem.key); + if (uiStore.getState().settingsStructureTab !== nextItem.key) { + uiStore.setState({ settingsStructureTab: nextItem.key }); + } + thirdNavBtnMap.get(nextItem.key)?.btn?.focus?.(); + } } }, }, @@ -15528,6 +16592,7 @@ const SettingsStructureTab = defineComponent({ return btn; }); + const thirdNavGlider = h('div', { className: 'thirdnav-glider', 'aria-hidden': 'true' }); const thirdNavBar = h( 'div', { @@ -15535,7 +16600,15 @@ const SettingsStructureTab = defineComponent({ role: 'tablist', 'aria-label': t('settings.str.thirdTabAria'), }, - thirdNavBtns + [thirdNavGlider, ...thirdNavBtns] + ); + patchStyleVar( + thirdNavBar, + '--active-third-index', + Math.max( + 0, + STRUCTURE_THIRD_TABS.findIndex((it) => it.key === activeThirdTab) + ) ); // --- Pane 1: 挂载与胶囊栏 (`mount`) --- @@ -16311,6 +17384,11 @@ const SettingsStructureTab = defineComponent({ function applyActiveThirdTab(nextRawTab) { const nextTab = normalizeStructureTabKey(nextRawTab); activeThirdTab = nextTab; + const activeIdx = Math.max( + 0, + STRUCTURE_THIRD_TABS.findIndex((it) => it.key === nextTab) + ); + patchStyleVar(thirdNavBar, '--active-third-index', activeIdx); for (const [key, entry] of thirdNavBtnMap.entries()) { const isActive = key === nextTab; patchClasses(entry.btn, { 'is-active': isActive }); @@ -17595,6 +18673,7 @@ const { ConsumptionView } = (() => { /** 消耗统计顶栏支持的时间范围预设项 */ function getConsumptionTimeRangeOptions() { return [ + { value: 'cycle', label: t('cons.rangeCycle') }, { value: 'today', label: t('cons.rangeToday') }, { value: '24h', label: t('cons.range24h') }, { value: '7d', label: t('cons.range7d') }, @@ -17683,8 +18762,7 @@ const ConsumptionView = defineComponent({ const customRangeBar = h( 'div', { - style: - 'display: flex; align-items: center; flex-wrap: wrap; gap: 6px; padding: 6px 8px; background: var(--surface-subtle); border: 1px solid var(--border-hairline); border-radius: var(--radius-xs);', + className: 'cons-custom-range-bar', hidden: true, }, [ @@ -17886,6 +18964,7 @@ const ConsumptionView = defineComponent({ activeHoverTargetEl = null; } patchAttr(breakdownPopoverEl, 'hidden', true); + patchClasses(breakdownPopoverEl, { 'is-tracking': false }); } function positionBreakdownPopover(anchorEl, pointerClientX = null) { @@ -17961,8 +19040,22 @@ const ConsumptionView = defineComponent({ }, }); + const wasHidden = breakdownPopoverEl.hasAttribute('hidden'); patchAttr(breakdownPopoverEl, 'hidden', false); positionBreakdownPopover(anchorEl, pointerClientX); + if (wasHidden) { + patchClasses(breakdownPopoverEl, { 'is-tracking': false }); + void breakdownPopoverEl.offsetWidth; + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + window.requestAnimationFrame(() => { + if (!breakdownPopoverEl.hasAttribute('hidden')) { + patchClasses(breakdownPopoverEl, { 'is-tracking': true }); + } + }); + } else { + patchClasses(breakdownPopoverEl, { 'is-tracking': true }); + } + } } function createMonthModelSegment() { @@ -19009,7 +20102,6 @@ const StepsDetailView = defineComponent({ collapseAll: true, multiUnit: t('steps.unitAgent'), modelValue: selectedAgentScopes, - icon: 'layers', placeholder: t('steps.allAgents'), className: 'steps-inline-scope-select', options: [{ value: 'all', label: t('steps.allAgents') }], @@ -19292,7 +20384,7 @@ const StepsDetailView = defineComponent({ } } - function renderStepsData(slice) { + function renderStepsData(slice, { allowNewRowFade = false } = {}) { if (!slice) return; const uiSt = uiStore.getState(); const locale = getEffectiveLocale(); @@ -19518,6 +20610,12 @@ const StepsDetailView = defineComponent({ ], }); + const allConversationSteps = hasSubagents + ? aggregated?.recentSteps || [] + : slice.recentSteps || []; + const shouldAnimateNewRows = Boolean( + allowNewRowFade && slice.experimentalModernUi && !showModels + ); if (!showModels) { const colKeys = normalizeClientStepColumns(slice.stepTableColumns); renderStepTable(tableSteps, slice.cascadeId, colKeys, locale, { @@ -19529,6 +20627,8 @@ const StepsDetailView = defineComponent({ showStepSpeedColor: slice.showStepSpeedColor === true, stepTokenComboFormat: slice.stepTokenComboFormat, displaySettings, + allConversationSteps, + allowNewRowFade: shouldAnimateNewRows, }); stepsScroll.refresh(); } @@ -19859,6 +20959,7 @@ const StepsDetailView = defineComponent({ st.telemetry?.settings?.stepTokenComboFormat ), stepTableColumns: st.telemetry?.settings?.stepTableColumns, + experimentalModernUi: Boolean(st.telemetry?.settings?.experimentalModernUi), }), (slice) => { latestSlice = slice; @@ -19870,7 +20971,9 @@ const StepsDetailView = defineComponent({ return; } isDirty = false; - renderStepsData(slice); + renderStepsData(slice, { + allowNewRowFade: uiStore.getState().stepsSubTab === 'steps', + }); } ); @@ -21686,6 +22789,7 @@ function mountWindowOverlay() { onSelectSession: inspectSessionInMonitor, onLayoutChange: () => { if (multiOpen) { + patchClasses(multiPanelEl, { 'is-instant': true }); positionFloatingElements(); } }, @@ -21743,9 +22847,23 @@ function mountWindowOverlay() { applyAppearanceToRoot(capsuleHost, settings, { includeFontScale: false }); applyAppearanceToRoot(portalHost, settings, { includeFontScale: true }); const scaleKey = normalizeClientFontScale(settings?.fontScale); - popoverEl.setAttribute?.('data-font-scale', scaleKey); - hoverTipEl.setAttribute?.('data-font-scale', scaleKey); - multiPanelEl.setAttribute?.('data-font-scale', scaleKey); + const isModernUi = normalizeClientModernUi(settings?.experimentalModernUi); + const colorScheme = portalHost.getAttribute?.('data-color-scheme') || 'light'; + for (const el of [popoverEl, hoverTipEl, multiPanelEl]) { + if (el.getAttribute?.('data-font-scale') !== scaleKey) { + el.setAttribute?.('data-font-scale', scaleKey); + } + if (el.getAttribute?.('data-color-scheme') !== colorScheme) { + el.setAttribute?.('data-color-scheme', colorScheme); + } + if (isModernUi) { + if (el.getAttribute?.('data-modern-ui') !== 'true') { + el.setAttribute?.('data-modern-ui', 'true'); + } + } else if (el.hasAttribute?.('data-modern-ui')) { + el.removeAttribute?.('data-modern-ui'); + } + } } portalShadow.appendChild(multiPanelEl); @@ -21880,6 +22998,7 @@ function mountWindowOverlay() { function ensureWorkbenchThemeObserved() { const wb = syncWorkbenchThemeVars(); + syncPortalAppearance(telemetryStore.getState().telemetry?.settings); if (wb && wb !== observedWorkbench && themeObserver) { observedWorkbench = wb; try { @@ -22909,6 +24028,7 @@ function mountWindowOverlay() { if (typeof MutationObserver !== 'undefined') { themeObserver = new MutationObserver(() => { syncWorkbenchThemeVars(); + syncPortalAppearance(telemetryStore.getState().telemetry?.settings); }); if (document.head) { themeObserver.observe(document.head, { @@ -22917,6 +24037,18 @@ function mountWindowOverlay() { subtree: true, }); } + if (document.documentElement) { + themeObserver.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'style', 'data-theme', 'data-vscode-theme-kind'], + }); + } + if (document.body) { + themeObserver.observe(document.body, { + attributes: true, + attributeFilter: ['class', 'style', 'data-theme', 'data-vscode-theme-kind'], + }); + } if (document.body) { hostDomObserver = new MutationObserver((records) => { if ( @@ -23155,10 +24287,48 @@ async function bootstrapApp(mountTarget = document.getElementById('app-root')) { syncDocAppearance ); + let hostThemeObserver = null; + let colorSchemeMql = null; + const onHostThemeChange = () => { + syncDocAppearance(telemetryStore.getState().telemetry?.settings); + }; + try { + if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') { + hostThemeObserver = new MutationObserver(onHostThemeChange); + if (document.documentElement) { + hostThemeObserver.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'style', 'data-theme', 'data-vscode-theme-kind'], + }); + } + if (document.body) { + hostThemeObserver.observe(document.body, { + attributes: true, + attributeFilter: ['class', 'style', 'data-theme', 'data-vscode-theme-kind'], + }); + } + if (document.head) { + hostThemeObserver.observe(document.head, { + childList: true, + characterData: true, + subtree: true, + }); + } + } + if (typeof window !== 'undefined' && typeof window.matchMedia === 'function') { + colorSchemeMql = window.matchMedia('(prefers-color-scheme: dark)'); + colorSchemeMql?.addEventListener?.('change', onHostThemeChange); + } + } catch { + // ignore observer setup errors in constrained environments + } + const stopPolling = startAsyncTelemetryLoop(2000); return { appInstance, stopPolling: () => { + hostThemeObserver?.disconnect?.(); + colorSchemeMql?.removeEventListener?.('change', onHostThemeChange); unsubAppearance(); stopPolling(); }, diff --git a/sidecars/panel/backend/settings-schema.mjs b/sidecars/panel/backend/settings-schema.mjs index 3c6fa79..6500ce5 100644 --- a/sidecars/panel/backend/settings-schema.mjs +++ b/sidecars/panel/backend/settings-schema.mjs @@ -26,6 +26,7 @@ import { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, TOPBAR_SLOT_KEYS, + normalizeExperimentalModernUi, normalizeFontScale, normalizeHoverModules, normalizeLanguageSetting, @@ -67,6 +68,7 @@ export { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, TOPBAR_SLOT_KEYS, + normalizeExperimentalModernUi, normalizeFontScale, normalizeHoverModules, normalizeLanguageSetting, @@ -108,6 +110,7 @@ export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({ language: 'zh-CN', themeAccent: 'host', fontScale: 'md', + experimentalModernUi: false, weeklyTokenBudget: 150000000, weeklyCostBudget: 100, weeklyLimitMode: 'official', @@ -174,6 +177,7 @@ export function normalizeFullSettings(rawInput) { language: normalizeLanguageSetting(safeRaw.language), themeAccent: normalizeThemeAccent(safeRaw.themeAccent), fontScale: normalizeFontScale(safeRaw.fontScale), + experimentalModernUi: normalizeExperimentalModernUi(safeRaw.experimentalModernUi), weeklyTokenBudget: schemaSanitizePositiveNum( safeRaw.weeklyTokenBudget ?? safeRaw.weeklyTokenLimit, DEFAULT_SETTINGS_SCHEMA.weeklyTokenBudget diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index 4f948ae..0d6c5b3 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -1232,6 +1232,9 @@ export async function buildTelemetryPayloadInternal( weeklyResetMs: accountWeeklyResetMs || parseIsoMs(activeLiveWeekly?.resetTime), }; + const isCustomWeeklyMode = + settings.weeklyLimitMode === 'custom_tokens' || settings.weeklyLimitMode === 'custom_cost'; + // 5. 多时间窗口聚合(预设窗口 + 当前选定窗口 + 趋势 + 月序列 + 来源与模型拆解 + 各配额池独立周期统计) const { selectedWindow, @@ -1252,6 +1255,7 @@ export async function buildTelemetryPayloadInternal( } = aggregateMultiWindowUsage({ filterOpts, cycleAnchors, + isCustomWeeklyMode, currentAccountName: accountScope, activeCascadeId, activeFamilyCascadeIds, @@ -1321,8 +1325,6 @@ export async function buildTelemetryPayloadInternal( +((weekBucket.totalTokens / Math.max(1000, settings.weeklyTokenBudget)) * 100).toFixed(1) ); - const isCustomWeeklyMode = - settings.weeklyLimitMode === 'custom_tokens' || settings.weeklyLimitMode === 'custom_cost'; const useOfficialWeekly = Boolean(activeLiveWeekly) && !isCustomWeeklyMode; const weeklyUsedPct = useOfficialWeekly diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs index 308dd3f..d92bb8d 100644 --- a/sidecars/panel/backend/usage-aggregator.mjs +++ b/sidecars/panel/backend/usage-aggregator.mjs @@ -2,7 +2,7 @@ * @fileoverview 多时间窗口解析、用量桶累加、趋势序列、月度序列与分模型/分来源聚合引擎。 * * 负责将内存缓存 (`trajectoryCache`) 与外部深层统计缓存 (`loadExternalDeepStatsCache`) - * 中的所有步骤按预设窗口(`all`, `5h`, `today`, `24h`, `week`, `7d`, `14d`, `30d`)与当前选定窗口 + * 中的所有步骤按预设窗口(`all`, `cycle`, `5h`, `today`, `24h`, `week`, `7d`, `14d`, `30d`)与当前选定窗口 * 进行去重遍历聚合,输出前端消费分析与模型明细所需的完整统计结构。 */ @@ -98,10 +98,24 @@ function resolveTimeWindow( customStartMs = 0, customEndMs = 0, nowMs = Date.now(), - cycleAnchors = {} + cycleAnchors = {}, + isCustomWeeklyMode = false ) { const now = new Date(nowMs); switch (rangeKey) { + case 'cycle': { + const resetWkMs = !isCustomWeeklyMode ? cycleAnchors.weeklyResetMs || 0 : 0; + const startCycleMs = + resetWkMs > nowMs + ? Math.min(nowMs, resetWkMs - 7 * 24 * 3600 * 1000) + : getStartOfCurrentWeekMs(now); + return { + key: 'cycle', + label: isCustomWeeklyMode ? '本周' : '当前周期', + startMs: startCycleMs, + endMs: nowMs, + }; + } case '5h': { const reset5hMs = cycleAnchors.fiveHourResetMs || 0; const start5hMs = @@ -460,6 +474,7 @@ function sameUsageWindows(previous, current, dates) { export function aggregateMultiWindowUsage({ filterOpts = {}, cycleAnchors = {}, + isCustomWeeklyMode = false, currentAccountName = '', activeCascadeId = null, activeFamilyCascadeIds = null, @@ -480,16 +495,17 @@ export function aggregateMultiWindowUsage({ filterOpts.startMs, filterOpts.endMs, nowMs, - cycleAnchors + cycleAnchors, + isCustomWeeklyMode ); - const presetKeys = ['all', '5h', 'today', '24h', 'week', '7d', '14d', '30d']; + const presetKeys = ['all', 'cycle', '5h', 'today', '24h', 'week', '7d', '14d', '30d']; const presetWindows = {}; const accountBuckets = {}; const sessionBuckets = {}; for (const k of presetKeys) { - presetWindows[k] = resolveTimeWindow(k, 0, 0, nowMs, cycleAnchors); + presetWindows[k] = resolveTimeWindow(k, 0, 0, nowMs, cycleAnchors, isCustomWeeklyMode); accountBuckets[k] = createUsageBucket(); sessionBuckets[k] = createUsageBucket(); } @@ -529,6 +545,7 @@ export function aggregateMultiWindowUsage({ const selectedWindowSteps = []; let earliestSelectedStepMs = Infinity; let latestSelectedStepMs = 0; + let earliestActiveCyclePoolStartMs = Infinity; const currentYear = new Date(nowMs).getFullYear(); const monthBoundsMs = Array.from({ length: 13 }, (_, idx) => @@ -621,6 +638,7 @@ export function aggregateMultiWindowUsage({ const snapshot = lastUsageSnapshot; const sameSnapshot = modelInputs && snapshot && timeZone === snapshot.timeZone && currentYear === snapshot.currentYear && + Boolean(isCustomWeeklyMode) === Boolean(snapshot.isCustomWeeklyMode) && normalizedQuotaAccount === snapshot.normalizedQuotaAccount && modelInputs.catalogRevision === snapshot.modelInputs.catalogRevision && isDeepStrictEqual(modelInputs.dynamicModelMap, snapshot.modelInputs.dynamicModelMap) && @@ -628,7 +646,11 @@ export function aggregateMultiWindowUsage({ const previous = sameSnapshot ? snapshot.ranges.get(selectedWindow.key) : null; if (previous) { // 时钟继续前进,只有实际有步骤跨过窗口边界时才重新聚合。 - const trend = planUsageTrend(selectedWindow, nowMs, previous.earliest, previous.latest); + const effectivePrevWin = + selectedWindow.key === 'cycle' && previous.effectiveSelectedWindow + ? { ...previous.effectiveSelectedWindow, endMs: nowMs } + : selectedWindow; + const trend = planUsageTrend(effectivePrevWin, nowMs, previous.earliest, previous.latest); if ( trend.hourly === previous.trend.hourly && trend.first === previous.trend.first && trend.last === previous.trend.last && @@ -637,7 +659,12 @@ export function aggregateMultiWindowUsage({ ) { snapshot.ranges.delete(selectedWindow.key); snapshot.ranges.set(selectedWindow.key, previous); - return { ...previous.result, selectedWindow, trendStartMs: trend.start, trendEndMs: trend.end }; + return { + ...previous.result, + selectedWindow: effectivePrevWin, + trendStartMs: trend.start, + trendEndMs: trend.end, + }; } } @@ -698,9 +725,70 @@ export function aggregateMultiWindowUsage({ } } + let poolBucketEntry = null; + if (poolCycleBuckets.size > 0) { + let cachedPool = poolByModel.get(mInfo); + if ( + !cachedPool || + cachedPool.key !== st.modelKey || + cachedPool.response !== st.responseModel || + cachedPool.displayName !== st.modelDisplayName + ) { + const ids = [ + st.modelKey, + st.responseModel, + mInfo.modelId, + mInfo.label, + st.modelDisplayName, + ]; + let poolKey = null; + if (hasDedicatedCarbonPool && isCarbonModelIdentifier(...ids)) poolKey = 'Carbon'; + else if (hasDedicatedArgonPool && isArgonModelIdentifier(...ids)) poolKey = 'Argon'; + else if (mInfo.family === 'Gemini') poolKey = 'Gemini'; + else if (['Claude', 'GPT', 'Other'].includes(mInfo.family)) poolKey = 'Claude & GPT'; + cachedPool = { + key: st.modelKey, + response: st.responseModel, + displayName: st.modelDisplayName, + bucket: poolCycleBuckets.get(poolKey) || null, + }; + poolByModel.set(mInfo, cachedPool); + } + poolBucketEntry = cachedPool.bucket; + } + + if (includeInQuotaPools && poolBucketEntry && tMs > 0 && tMs <= nowMs) { + if (tMs >= poolBucketEntry.start5hMs) { + accumulateStepIntoBucket(poolBucketEntry.b5h, stepUsage, cascadeId); + } + if (tMs >= poolBucketEntry.startWkMs) { + accumulateStepIntoBucket(poolBucketEntry.bWk, stepUsage, cascadeId); + } + } + + let inCurrentCycle = false; + if (tMs > 0 && tMs <= nowMs) { + if (isCustomWeeklyMode) { + inCurrentCycle = tMs >= presetWindows.week.startMs; + } else if (poolCycleBuckets.size > 0) { + const effCycleStartMs = poolBucketEntry + ? poolBucketEntry.startWkMs + : presetWindows.cycle.startMs; + inCurrentCycle = includeInQuotaPools && tMs >= effCycleStartMs; + } else { + inCurrentCycle = includeInQuotaPools && tMs >= presetWindows.cycle.startMs; + } + } + for (const k of presetKeys) { const w = presetWindows[k]; - if (k === 'all' || (tMs > 0 && tMs >= w.startMs && tMs <= w.endMs)) { + const matchesPreset = + k === 'all' + ? true + : k === 'cycle' + ? inCurrentCycle + : tMs > 0 && tMs >= w.startMs && tMs <= w.endMs; + if (matchesPreset) { accumulateStepIntoBucket(accountBuckets[k], stepUsage, cascadeId); if (isCurrentConv) { accumulateStepIntoBucket(sessionBuckets[k], stepUsage, cascadeId); @@ -711,38 +799,22 @@ export function aggregateMultiWindowUsage({ } } - if (includeInQuotaPools && poolCycleBuckets.size > 0 && tMs > 0 && tMs <= nowMs) { - let cachedPool = poolByModel.get(mInfo); - if (!cachedPool || cachedPool.key !== st.modelKey || - cachedPool.response !== st.responseModel || cachedPool.displayName !== st.modelDisplayName) { - const ids = [st.modelKey, st.responseModel, mInfo.modelId, mInfo.label, st.modelDisplayName]; - let poolKey = null; - if (hasDedicatedCarbonPool && isCarbonModelIdentifier(...ids)) poolKey = 'Carbon'; - else if (hasDedicatedArgonPool && isArgonModelIdentifier(...ids)) poolKey = 'Argon'; - else if (mInfo.family === 'Gemini') poolKey = 'Gemini'; - else if (['Claude', 'GPT', 'Other'].includes(mInfo.family)) poolKey = 'Claude & GPT'; - cachedPool = { - key: st.modelKey, response: st.responseModel, displayName: st.modelDisplayName, - bucket: poolCycleBuckets.get(poolKey), - }; - poolByModel.set(mInfo, cachedPool); - } - const poolBucketEntry = cachedPool.bucket; - if (poolBucketEntry) { - if (tMs >= poolBucketEntry.start5hMs) { - accumulateStepIntoBucket(poolBucketEntry.b5h, stepUsage, cascadeId); - } - if (tMs >= poolBucketEntry.startWkMs) { - accumulateStepIntoBucket(poolBucketEntry.bWk, stepUsage, cascadeId); - } - } - } - const inSelectedWindow = - selectedWindow.key === 'all' || - (tMs > 0 && tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs); + selectedWindow.key === 'all' + ? true + : selectedWindow.key === 'cycle' + ? inCurrentCycle + : tMs > 0 && tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs; if (inSelectedWindow) { + if ( + selectedWindow.key === 'cycle' && + !isCustomWeeklyMode && + poolBucketEntry && + poolBucketEntry.startWkMs < earliestActiveCyclePoolStartMs + ) { + earliestActiveCyclePoolStartMs = poolBucketEntry.startWkMs; + } if (selectedWindow.key === 'custom') { accumulateStepIntoBucket(selectedAccountBucket, stepUsage, cascadeId); if (isCurrentConv) { @@ -803,7 +875,21 @@ export function aggregateMultiWindowUsage({ ); // 构建当前选定时间窗口的自适应自然整点/整日趋势序列 (trendSeries) - const trend = planUsageTrend(selectedWindow, nowMs, earliestSelectedStepMs, latestSelectedStepMs); + const effectiveSelectedWindow = + selectedWindow.key === 'cycle' && + Number.isFinite(earliestActiveCyclePoolStartMs) && + earliestActiveCyclePoolStartMs < Infinity + ? { + ...selectedWindow, + startMs: Math.min(earliestActiveCyclePoolStartMs, earliestSelectedStepMs), + } + : selectedWindow; + const trend = planUsageTrend( + effectiveSelectedWindow, + nowMs, + earliestSelectedStepMs, + latestSelectedStepMs + ); const { start: trendStartMs, end: trendEndMs, hourly: useHourly } = trend; const pad2 = (n) => String(n).padStart(2, '0'); const WEEKDAY_NAMES = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']; @@ -1075,7 +1161,7 @@ export function aggregateMultiWindowUsage({ : null; const result = { - selectedWindow, + selectedWindow: effectiveSelectedWindow, trendStartMs, trendEndMs, finalizedSelectedSession, @@ -1098,6 +1184,7 @@ export function aggregateMultiWindowUsage({ timeZone, modelInputs, currentYear, + isCustomWeeklyMode: Boolean(isCustomWeeklyMode), normalizedQuotaAccount, entries: allEntriesToAggregate, dates: null, @@ -1107,7 +1194,12 @@ export function aggregateMultiWindowUsage({ const { ranges } = lastUsageSnapshot; ranges.delete(selectedWindow.key); ranges.set(selectedWindow.key, { - windows, trend, result, earliest: earliestSelectedStepMs, latest: latestSelectedStepMs, + windows, + effectiveSelectedWindow, + trend, + result, + earliest: earliestSelectedStepMs, + latest: latestSelectedStepMs, }); // 侧栏和悬浮窗可同时查看不同范围,共用时间索引并最多保留两份聚合结果。 if (ranges.size > 2) ranges.delete(ranges.keys().next().value); diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 0dffd36..0366f87 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/scripts/build-bundle.mjs b/sidecars/panel/scripts/build-bundle.mjs index 09347dd..6c7ccef 100644 --- a/sidecars/panel/scripts/build-bundle.mjs +++ b/sidecars/panel/scripts/build-bundle.mjs @@ -504,6 +504,7 @@ export function buildBundle(panelDir = PANEL_DIR) { 'src/styles/views-tables.css', 'src/styles/views-settings.css', 'src/styles/overlay.css', + 'src/styles/modern-ui.css', ]; const cssBundle = diff --git a/sidecars/panel/shared/settings-normalization.mjs b/sidecars/panel/shared/settings-normalization.mjs index f991242..07fdfde 100644 --- a/sidecars/panel/shared/settings-normalization.mjs +++ b/sidecars/panel/shared/settings-normalization.mjs @@ -446,3 +446,17 @@ export function normalizeStandalonePort(port) { if (num >= 1024 && num <= 65535) return num; return 0; } + +/** + * 归一化实验性现代化新 UI 开关(默认 `false`)。 + * + * @param {unknown} val + * @returns {boolean} + */ +export function normalizeExperimentalModernUi(val) { + if (typeof val === 'string') { + const lower = val.trim().toLowerCase(); + return lower === 'true' || lower === '1' || lower === 'on'; + } + return Boolean(val); +} diff --git a/sidecars/panel/src/components/charts/SessionStepCharts.js b/sidecars/panel/src/components/charts/SessionStepCharts.js index 359a92e..5739b74 100644 --- a/sidecars/panel/src/components/charts/SessionStepCharts.js +++ b/sidecars/panel/src/components/charts/SessionStepCharts.js @@ -783,6 +783,7 @@ export function createSessionLineChart() { clearHover(); return; } + const wasHidden = tooltipEl.hasAttribute('hidden'); hoveredIdx = idx; const pt = currentPoints[idx]; patchAttr(hoverLine, 'hidden', false); @@ -813,6 +814,20 @@ export function createSessionLineChart() { const clampedPct = Math.max(1, Math.min(99, rawPct)); patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`); patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`); + patchStyleVar(tooltipEl, '--tip-y', '0px'); + if (wasHidden) { + patchClasses(tooltipEl, { 'is-tracking': false }); + void tooltipEl.offsetWidth; + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + window.requestAnimationFrame(() => { + if (!tooltipEl.hasAttribute('hidden')) { + patchClasses(tooltipEl, { 'is-tracking': true }); + } + }); + } else { + patchClasses(tooltipEl, { 'is-tracking': true }); + } + } for (const [tIdx, el] of tickElsByIdx.entries()) { patchClasses(el, { 'is-hovered': tIdx === idx }); @@ -824,6 +839,7 @@ export function createSessionLineChart() { patchAttr(hoverLine, 'hidden', true); patchAttr(hoverDot, 'hidden', true); patchAttr(tooltipEl, 'hidden', true); + patchClasses(tooltipEl, { 'is-tracking': false }); if (currentPoints.some((p) => p.valid)) { patchAttr(peakPill, 'hidden', false); } @@ -1577,6 +1593,7 @@ export function createModelFitChart() { patchAttr(hoverRawDot, 'cx', sp.x.toFixed(1)); patchAttr(hoverRawDot, 'cy', sp.rawY.toFixed(1)); + const wasHidden = tooltipEl.hasAttribute('hidden'); patchAttr(tooltipEl, 'hidden', false); patchText(tipHeadLeft, sp.stepTag); patchText(tipHeadRight, sp.modelText); @@ -1612,6 +1629,20 @@ export function createModelFitChart() { const clampedPct = Math.max(1, Math.min(99, rawPct)); patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`); patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`); + patchStyleVar(tooltipEl, '--tip-y', '0px'); + if (wasHidden) { + patchClasses(tooltipEl, { 'is-tracking': false }); + void tooltipEl.offsetWidth; + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + window.requestAnimationFrame(() => { + if (!tooltipEl.hasAttribute('hidden')) { + patchClasses(tooltipEl, { 'is-tracking': true }); + } + }); + } else { + patchClasses(tooltipEl, { 'is-tracking': true }); + } + } } function clearHover() { @@ -1620,6 +1651,7 @@ export function createModelFitChart() { patchAttr(hoverFitDot, 'hidden', true); patchAttr(hoverRawDot, 'hidden', true); patchAttr(tooltipEl, 'hidden', true); + patchClasses(tooltipEl, { 'is-tracking': false }); } plotStage.addEventListener('mousemove', (e) => { diff --git a/sidecars/panel/src/components/charts/TrendAreaChart.js b/sidecars/panel/src/components/charts/TrendAreaChart.js index 6c46644..08f6191 100644 --- a/sidecars/panel/src/components/charts/TrendAreaChart.js +++ b/sidecars/panel/src/components/charts/TrendAreaChart.js @@ -403,6 +403,34 @@ export function createTrendAreaChart() { let hoveredIdx = -1; let hoveredCellEl = null; let lastRenderSig = ''; + let tipTrackRaf = 0; + + function cancelTipTrackRaf() { + if (tipTrackRaf && typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function') { + window.cancelAnimationFrame(tipTrackRaf); + } + tipTrackRaf = 0; + } + + function armTooltipTracking(wasHidden) { + if (!wasHidden) return; + patchClasses(tooltipEl, { 'is-tracking': false }); + patchClasses(hoverDot, { 'is-tracking': false }); + void tooltipEl.offsetWidth; + cancelTipTrackRaf(); + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + tipTrackRaf = window.requestAnimationFrame(() => { + tipTrackRaf = 0; + if (!tooltipEl.hasAttribute('hidden')) { + patchClasses(tooltipEl, { 'is-tracking': true }); + patchClasses(hoverDot, { 'is-tracking': true }); + } + }); + } else { + patchClasses(tooltipEl, { 'is-tracking': true }); + patchClasses(hoverDot, { 'is-tracking': true }); + } + } function populateTooltipContent(slot) { patchText(tipTimeEl, slot.fullLabel || slot.label || '--'); @@ -458,6 +486,7 @@ export function createTrendAreaChart() { clearHover(); return; } + const wasHidden = tooltipEl.hasAttribute('hidden'); hoveredIdx = idx; const slot = currentSlots[idx]; const pt = currentPts[idx]; @@ -470,19 +499,31 @@ export function createTrendAreaChart() { patchAttr(hoverDot, 'cx', pt.x.toFixed(1)); patchAttr(hoverDot, 'cy', pt.y.toFixed(1)); + const isLineLow = pt.y < Math.round((TOP_Y + BOTTOM_Y) / 2); patchAttr(peakPill, 'hidden', true); patchClasses(tooltipEl, { 'is-hm-bottom': false, 'is-hm-top': false, - 'is-line-low': pt.y < Math.round((TOP_Y + BOTTOM_Y) / 2), + 'is-line-low': isLineLow, }); patchAttr(tooltipEl, 'hidden', false); populateTooltipContent(slot); + let tipY = 0; + if (isLineLow) { + const wrapH = Number(chartWrap.offsetHeight || 0); + const tipH = Number(tooltipEl.offsetHeight || 0); + if (wrapH > 0 && tipH > 0) { + tipY = Math.max(0, wrapH - tipH - 22); + } + } + const rawPct = (pt.x / viewW) * 100; const clampedPct = Math.max(1, Math.min(99, rawPct)); patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`); patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`); + patchStyleVar(tooltipEl, '--tip-y', `${Math.round(tipY)}px`); + armTooltipTracking(wasHidden); for (const [tIdx, el] of tickElsByIdx.entries()) { patchClasses(el, { 'is-hovered': tIdx === idx }); @@ -510,6 +551,7 @@ export function createTrendAreaChart() { const row = Number(targetCell.getAttribute('data-hm-row') || 0); const col = Number(targetCell.getAttribute('data-hm-col') || 0); + const wasHidden = tooltipEl.hasAttribute('hidden'); // 上半区(周一~周四)浮层停靠热力图下方,下半区(周五~周日)停靠热力图上方,互不遮挡被悬停格子且永不越界裁剪 patchClasses(tooltipEl, { 'is-hm-bottom': row <= 3, @@ -536,14 +578,23 @@ export function createTrendAreaChart() { const clampedPct = Math.max(1, Math.min(99, rawPct)); patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`); patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`); + patchStyleVar(tooltipEl, '--tip-y', '0px'); + armTooltipTracking(wasHidden); } function clearHover() { + cancelTipTrackRaf(); hoveredIdx = -1; patchAttr(hoverLine, 'hidden', true); patchAttr(hoverDot, 'hidden', true); patchAttr(tooltipEl, 'hidden', true); - patchClasses(tooltipEl, { 'is-hm-bottom': false, 'is-hm-top': false, 'is-line-low': false }); + patchClasses(tooltipEl, { + 'is-hm-bottom': false, + 'is-hm-top': false, + 'is-line-low': false, + 'is-tracking': false, + }); + patchClasses(hoverDot, { 'is-tracking': false }); if (!currentIsHeatmap) { patchAttr(peakPill, 'hidden', false); } @@ -755,6 +806,7 @@ export function createTrendAreaChart() { } function destroy() { + cancelTipTrackRaf(); resizeObs?.disconnect(); resizeObs = null; if (onWinResize && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') { diff --git a/sidecars/panel/src/components/layout/WindowOverlayShell.js b/sidecars/panel/src/components/layout/WindowOverlayShell.js index a5ac57f..f187404 100644 --- a/sidecars/panel/src/components/layout/WindowOverlayShell.js +++ b/sidecars/panel/src/components/layout/WindowOverlayShell.js @@ -19,6 +19,7 @@ import { PANEL_SCALE_FACTORS, applyAppearanceToRoot, normalizeClientFontScale, + normalizeClientModernUi, } from '../../core/appearance.js'; import { h, @@ -1397,6 +1398,7 @@ export function mountWindowOverlay() { onSelectSession: inspectSessionInMonitor, onLayoutChange: () => { if (multiOpen) { + patchClasses(multiPanelEl, { 'is-instant': true }); positionFloatingElements(); } }, @@ -1454,9 +1456,23 @@ export function mountWindowOverlay() { applyAppearanceToRoot(capsuleHost, settings, { includeFontScale: false }); applyAppearanceToRoot(portalHost, settings, { includeFontScale: true }); const scaleKey = normalizeClientFontScale(settings?.fontScale); - popoverEl.setAttribute?.('data-font-scale', scaleKey); - hoverTipEl.setAttribute?.('data-font-scale', scaleKey); - multiPanelEl.setAttribute?.('data-font-scale', scaleKey); + const isModernUi = normalizeClientModernUi(settings?.experimentalModernUi); + const colorScheme = portalHost.getAttribute?.('data-color-scheme') || 'light'; + for (const el of [popoverEl, hoverTipEl, multiPanelEl]) { + if (el.getAttribute?.('data-font-scale') !== scaleKey) { + el.setAttribute?.('data-font-scale', scaleKey); + } + if (el.getAttribute?.('data-color-scheme') !== colorScheme) { + el.setAttribute?.('data-color-scheme', colorScheme); + } + if (isModernUi) { + if (el.getAttribute?.('data-modern-ui') !== 'true') { + el.setAttribute?.('data-modern-ui', 'true'); + } + } else if (el.hasAttribute?.('data-modern-ui')) { + el.removeAttribute?.('data-modern-ui'); + } + } } portalShadow.appendChild(multiPanelEl); @@ -1591,6 +1607,7 @@ export function mountWindowOverlay() { function ensureWorkbenchThemeObserved() { const wb = syncWorkbenchThemeVars(); + syncPortalAppearance(telemetryStore.getState().telemetry?.settings); if (wb && wb !== observedWorkbench && themeObserver) { observedWorkbench = wb; try { @@ -2620,6 +2637,7 @@ export function mountWindowOverlay() { if (typeof MutationObserver !== 'undefined') { themeObserver = new MutationObserver(() => { syncWorkbenchThemeVars(); + syncPortalAppearance(telemetryStore.getState().telemetry?.settings); }); if (document.head) { themeObserver.observe(document.head, { @@ -2628,6 +2646,18 @@ export function mountWindowOverlay() { subtree: true, }); } + if (document.documentElement) { + themeObserver.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'style', 'data-theme', 'data-vscode-theme-kind'], + }); + } + if (document.body) { + themeObserver.observe(document.body, { + attributes: true, + attributeFilter: ['class', 'style', 'data-theme', 'data-vscode-theme-kind'], + }); + } if (document.body) { hostDomObserver = new MutationObserver((records) => { if ( diff --git a/sidecars/panel/src/components/ui/SegmentedControl.js b/sidecars/panel/src/components/ui/SegmentedControl.js index 4c5670d..834c53f 100644 --- a/sidecars/panel/src/components/ui/SegmentedControl.js +++ b/sidecars/panel/src/components/ui/SegmentedControl.js @@ -1,54 +1,215 @@ /** - * @fileoverview Micro-bezel (2px radius) SegmentedControl switcher - * for time-range filtering, context limit selection, and sub-table switching. + * @fileoverview Sliding SegmentedControl switcher with variable-width GPU glider. + * Measures active button geometry via ResizeObserver so both inline variable-width + * segments (e.g. "今天 / 1天 / ... / 自定义", "按步查看 (1520) / 总汇总") and equal-width + * grid bars ("常规 / 结构 / 其他") glide smoothly without stretching from 0px on tab reveal. */ import { defineComponent } from '../../core/component.js'; -import { h, patchAttr, patchClasses, patchKeyedList, patchText } from '../../core/domPatch.js'; +import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js'; export const SegmentedControl = defineComponent({ name: 'SegmentedControl', - setup({ getProps, setProps, emit }) { - const rootEl = h('div', { - className: 'segmented', - role: 'group', - 'aria-label': getProps().ariaLabel || '分段切换器', - }); + setup({ getProps, setProps, emit, onCleanup }) { + const gliderEl = h('div', { className: 'seg-glider', 'aria-hidden': 'true' }); + const rootEl = h( + 'div', + { + className: 'segmented', + role: 'group', + 'aria-label': getProps().ariaLabel || '分段切换器', + }, + [gliderEl] + ); + + const btnMap = new Map(); + let orderedBtns = []; + let activeBtnEl = null; + let observedBtnEl = null; + let hasMeasuredVisible = false; + let readyRafId = 0; + + function cancelReadyRaf() { + if (readyRafId && typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function') { + window.cancelAnimationFrame(readyRafId); + } + readyRafId = 0; + } + + function syncGliderGeometry() { + if (!activeBtnEl) { + cancelReadyRaf(); + hasMeasuredVisible = false; + patchClasses(rootEl, { 'has-glider': false }); + patchClasses(gliderEl, { 'is-ready': false }); + return; + } + + const w = Number(activeBtnEl.offsetWidth || 0); + const h = Number(activeBtnEl.offsetHeight || 0); + if (!(w > 0 && h > 0)) { + // Hidden parent tab or headless Mock DOM: keep .seg-btn.is-active fallback background + // and snap cleanly on first real paint when tab becomes visible. + cancelReadyRaf(); + hasMeasuredVisible = false; + patchClasses(rootEl, { 'has-glider': false }); + patchClasses(gliderEl, { 'is-ready': false }); + return; + } + + const x = Number(activeBtnEl.offsetLeft || 0); + const y = Number(activeBtnEl.offsetTop || 0); + patchStyleVar(gliderEl, '--glider-x', `${x}px`); + patchStyleVar(gliderEl, '--glider-y', `${y}px`); + patchStyleVar(gliderEl, '--glider-w', `${w}px`); + patchStyleVar(gliderEl, '--glider-h', `${h}px`); + patchClasses(rootEl, { 'has-glider': true }); + + if (!hasMeasuredVisible) { + hasMeasuredVisible = true; + patchClasses(gliderEl, { 'is-ready': false }); + void gliderEl.offsetWidth; + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + cancelReadyRaf(); + readyRafId = window.requestAnimationFrame(() => { + readyRafId = 0; + if (hasMeasuredVisible) { + patchClasses(gliderEl, { 'is-ready': true }); + } + }); + } else { + patchClasses(gliderEl, { 'is-ready': true }); + } + } + } + + let resizeObs = null; + if (typeof ResizeObserver === 'function') { + resizeObs = new ResizeObserver(() => { + syncGliderGeometry(); + }); + resizeObs.observe(rootEl); + } + + function updateObservedActiveButton(nextActiveBtn) { + if (!resizeObs || observedBtnEl === nextActiveBtn) return; + if (observedBtnEl) { + try { + resizeObs.unobserve(observedBtnEl); + } catch { + // ignore + } + } + observedBtnEl = nextActiveBtn || null; + if (observedBtnEl) { + try { + resizeObs.observe(observedBtnEl); + } catch { + // ignore + } + } + } + + function selectValue(nextVal) { + if (getProps().modelValue !== nextVal) { + setProps({ modelValue: nextVal }); + emit('update:modelValue', nextVal); + } + } function syncSegments() { - const { options = [], modelValue } = getProps(); - patchKeyedList(rootEl, options, { - keyFn: (opt) => opt.value, - sigFn: (opt) => `${opt.value}::${opt.label}::${opt.value === modelValue}`, - createRow: (opt) => { - const btn = h('button', { + const { options = [], modelValue, ariaLabel } = getProps(); + if (ariaLabel) { + patchAttr(rootEl, 'aria-label', ariaLabel); + } + + const validKeys = new Set(options.map((opt) => String(opt.value))); + for (const [key, btn] of btnMap.entries()) { + if (!validKeys.has(key)) { + if (btn.parentNode === rootEl) { + rootEl.removeChild(btn); + } + btnMap.delete(key); + } + } + + orderedBtns = []; + let nextActiveBtn = null; + + for (let i = 0; i < options.length; i++) { + const opt = options[i]; + const key = String(opt.value); + let btn = btnMap.get(key); + if (!btn) { + btn = h('button', { type: 'button', className: 'seg-btn', onClick: (e) => { e.stopPropagation(); - if (getProps().modelValue !== opt.value) { - setProps({ modelValue: opt.value }); - emit('update:modelValue', opt.value); + selectValue(opt.value); + }, + onKeydown: (e) => { + if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') { + e.preventDefault(); + const curOpts = getProps().options || []; + if (!curOpts.length) return; + const curIdx = Math.max( + 0, + curOpts.findIndex((o) => String(o.value) === key) + ); + const delta = e.key === 'ArrowRight' ? 1 : -1; + const nextIdx = (curIdx + delta + curOpts.length) % curOpts.length; + const targetOpt = curOpts[nextIdx]; + if (targetOpt) { + selectValue(targetOpt.value); + btnMap.get(String(targetOpt.value))?.focus?.(); + } } }, }); - return { el: btn, refs: {} }; - }, - updateRow: (_refs, opt, _idx, el) => { - const active = opt.value === modelValue; - patchText(el, opt.label); - patchClasses(el, { 'is-active': active }); - patchAttr(el, 'aria-pressed', active ? 'true' : 'false'); - patchAttr(el, 'data-seg-value', opt.value); - }, - }); + btnMap.set(key, btn); + } + + const active = opt.value === modelValue; + patchText(btn, opt.label); + patchClasses(btn, { 'is-active': active }); + patchAttr(btn, 'aria-pressed', active ? 'true' : 'false'); + patchAttr(btn, 'data-seg-value', opt.value); + orderedBtns.push(btn); + if (active) { + nextActiveBtn = btn; + } + } + + // Ensure gliderEl remains index 0 and buttons follow in exact option order + if (rootEl.firstChild !== gliderEl) { + rootEl.insertBefore(gliderEl, rootEl.firstChild); + } + for (let i = 0; i < orderedBtns.length; i++) { + const targetNode = orderedBtns[i]; + const currentAtSlot = rootEl.children[i + 1] || null; + if (currentAtSlot !== targetNode) { + rootEl.insertBefore(targetNode, currentAtSlot); + } + } + + activeBtnEl = nextActiveBtn || orderedBtns[0] || null; + updateObservedActiveButton(activeBtnEl); + syncGliderGeometry(); } syncSegments(); + onCleanup(() => { + cancelReadyRaf(); + resizeObs?.disconnect?.(); + resizeObs = null; + observedBtnEl = null; + }); + return { el: rootEl, - refs: {}, + refs: { gliderEl, refreshGlider: syncGliderGeometry }, onPropsChange: syncSegments, getValue: () => getProps().modelValue, }; diff --git a/sidecars/panel/src/components/widgets/ContextWindowWidget.js b/sidecars/panel/src/components/widgets/ContextWindowWidget.js index 8540c5c..75d2426 100644 --- a/sidecars/panel/src/components/widgets/ContextWindowWidget.js +++ b/sidecars/panel/src/components/widgets/ContextWindowWidget.js @@ -5,6 +5,7 @@ */ import { defineComponent } from '../../core/component.js'; +import { isModernUiActiveForElement } from '../../core/appearance.js'; import { h, patchAttr, @@ -30,8 +31,8 @@ const CTX_ASCII_CHAR_PX = 6.1; const CTX_PILL_GAP_PX = 4; const CTX_DEFAULT_BAR_WIDTH_PX = 310; -function estimateCtxPillWidth(text) { - let w = CTX_PILL_BASE_PAD_PX; +function estimateCtxPillWidth(text, withChevron = false) { + let w = CTX_PILL_BASE_PAD_PX + (withChevron ? 14 : 0); for (const ch of String(text || '')) { w += ch.charCodeAt(0) > 255 ? CTX_CJK_CHAR_PX : CTX_ASCII_CHAR_PX; } @@ -244,9 +245,30 @@ export const ContextWindowWidget = defineComponent({ let latestData = null; let ctxPillsExpanded = false; + let isCollapsingCtxPills = false; + let ctxCollapseTimer = null; let lastCascadeId = ''; let cachedBarWidth = 0; + function clearCtxExpandAnim() { + if (ctxCollapseTimer) { + clearTimeout(ctxCollapseTimer); + ctxCollapseTimer = null; + } + isCollapsingCtxPills = false; + ctxInspectorBar.ontransitionend = null; + ctxInspectorBar.style.height = ''; + ctxInspectorBar.style.overflow = ''; + ctxInspectorBar.style.transition = ''; + for (const child of ctxPillGroup.children) { + child.onanimationend = null; + patchClasses(child, { + 'is-pill-entering': false, + 'is-pill-collapsing': false, + }); + } + } + function update({ data } = {}) { latestData = data || null; const curLocale = getEffectiveLocale(); @@ -277,6 +299,7 @@ export const ContextWindowWidget = defineComponent({ const currentCascadeId = data.activeConversation?.cascadeId || ''; if (currentCascadeId && currentCascadeId !== lastCascadeId) { if (lastCascadeId) { + clearCtxExpandAnim(); ctxPillsExpanded = false; } lastCascadeId = currentCascadeId; @@ -308,7 +331,10 @@ export const ContextWindowWidget = defineComponent({ if (interactiveInspector) { patchAttr(ctxInspectorBar, 'hidden', !hasSubagents); - if (hasSubagents && ctxAgent) { + if (!hasSubagents && isCollapsingCtxPills) { + clearCtxExpandAnim(); + } + if (hasSubagents && ctxAgent && !isCollapsingCtxPills) { const activeBadgeText = formatAgentBadgeText({ agentKind: aggregated?.activeAgentKind || @@ -355,7 +381,7 @@ export const ContextWindowWidget = defineComponent({ if (needsCollapse && !ctxPillsExpanded) { const toggleSample = t('ctx.expandMore', { count: allAgentPills.length }); - const toggleReservePx = CTX_PILL_GAP_PX + estimateCtxPillWidth(toggleSample); + const toggleReservePx = CTX_PILL_GAP_PX + estimateCtxPillWidth(toggleSample, true); let usedW = firstPillWidth; let fitCount = 0; for (let i = 0; i < allAgentPills.length; i += 1) { @@ -386,6 +412,7 @@ export const ContextWindowWidget = defineComponent({ title: t('ctx.expandMoreTitle', { count: allAgentPills.length - 1 }), isActive: false, isMoreToggle: true, + isExpanded: false, mode: 'toggle-expand', }); } else { @@ -397,6 +424,7 @@ export const ContextWindowWidget = defineComponent({ title: t('ctx.collapseTitle'), isActive: false, isMoreToggle: true, + isExpanded: true, mode: 'toggle-expand', }); } @@ -405,22 +433,117 @@ export const ContextWindowWidget = defineComponent({ patchKeyedList(ctxPillGroup, pillItems, { keyFn: (item) => item.key, sigFn: (item) => - `${item.key}:${item.label}:${item.isActive}:${item.isMoreToggle}:${item.mode}:${item.title}`, + `${item.key}:${item.label}:${item.isActive}:${item.isMoreToggle}:${Boolean(item.isExpanded)}:${item.mode}:${item.title}`, createRow: () => { - const btn = h('button', { type: 'button', className: 'ctx-agent-pill' }); - return { el: btn, refs: { btn } }; + const labelSpan = h('span', { className: 'ctx-pill-label' }); + const chevronEl = createSvgIcon('chevron-down', { + size: 11, + className: 'ctx-toggle-chevron', + }); + patchAttr(chevronEl, 'hidden', true); + const btn = h('button', { type: 'button', className: 'ctx-agent-pill' }, [ + labelSpan, + chevronEl, + ]); + return { el: btn, refs: { btn, labelSpan, chevronEl } }; }, updateRow: (refs, item) => { - patchText(refs.btn, item.label); + patchText(refs.labelSpan, item.label); + patchAttr(refs.chevronEl, 'hidden', !item.isMoreToggle); patchAttr(refs.btn, 'title', item.title); + patchAttr(refs.btn, 'data-pill-key', item.key); patchClasses(refs.btn, { 'is-active': item.isActive, 'is-more-toggle': Boolean(item.isMoreToggle), + 'is-expanded': Boolean(item.isExpanded), + 'is-pill-collapsing': false, }); refs.btn.onclick = () => { if (item.mode === 'toggle-expand') { - ctxPillsExpanded = !ctxPillsExpanded; - if (latestData) update({ data: latestData }); + const modern = isModernUiActiveForElement(ctxPanel); + const startH = Number(ctxInspectorBar.offsetHeight || 0); + clearCtxExpandAnim(); + if (!modern || !(startH > 0)) { + ctxPillsExpanded = !ctxPillsExpanded; + if (latestData) update({ data: latestData }); + return; + } + + if (!ctxPillsExpanded) { + const prevKeys = new Set( + Array.from(ctxPillGroup.children, (el) => el.getAttribute?.('data-pill-key') || '') + ); + ctxPillsExpanded = true; + if (latestData) update({ data: latestData }); + const endH = Number(ctxPillGroup.offsetHeight || 0); + for (const child of ctxPillGroup.children) { + const k = child.getAttribute?.('data-pill-key') || ''; + if (k && k !== '__toggle_more__' && !prevKeys.has(k)) { + patchClasses(child, { 'is-pill-entering': true }); + child.onanimationend = () => { + child.onanimationend = null; + patchClasses(child, { 'is-pill-entering': false }); + }; + } + } + if (endH > startH + 1) { + ctxInspectorBar.style.height = `${startH}px`; + ctxInspectorBar.style.overflow = 'hidden'; + void ctxInspectorBar.offsetHeight; + ctxInspectorBar.style.transition = + 'height 220ms cubic-bezier(0.16, 1, 0.3, 1)'; + ctxInspectorBar.style.height = `${endH}px`; + const finishExpand = () => clearCtxExpandAnim(); + ctxInspectorBar.ontransitionend = (ev) => { + if ( + ev?.target === ctxInspectorBar && + (!ev.propertyName || ev.propertyName === 'height') + ) { + finishExpand(); + } + }; + ctxCollapseTimer = setTimeout(finishExpand, 260); + } + } else { + const firstPill = ctxPillGroup.children[0] || null; + const firstTop = Number(firstPill?.offsetTop || 0); + let firstRowH = Number(firstPill?.offsetHeight || 20); + for (const child of ctxPillGroup.children) { + const top = Number(child.offsetTop || 0); + if (top <= firstTop + 4) { + const bottom = top - firstTop + Number(child.offsetHeight || 0); + if (bottom > firstRowH) firstRowH = bottom; + } + } + const targetH = Math.max(18, firstRowH); + ctxPillsExpanded = false; + isCollapsingCtxPills = true; + patchClasses(refs.btn, { 'is-expanded': false }); + for (const child of ctxPillGroup.children) { + if (Number(child.offsetTop || 0) > firstTop + 4) { + patchClasses(child, { 'is-pill-collapsing': true }); + } + } + ctxInspectorBar.style.height = `${startH}px`; + ctxInspectorBar.style.overflow = 'hidden'; + void ctxInspectorBar.offsetHeight; + ctxInspectorBar.style.transition = + 'height 200ms cubic-bezier(0.16, 1, 0.3, 1)'; + ctxInspectorBar.style.height = `${targetH}px`; + const finishCollapse = () => { + clearCtxExpandAnim(); + if (latestData) update({ data: latestData }); + }; + ctxInspectorBar.ontransitionend = (ev) => { + if ( + ev?.target === ctxInspectorBar && + (!ev.propertyName || ev.propertyName === 'height') + ) { + finishCollapse(); + } + }; + ctxCollapseTimer = setTimeout(finishCollapse, 240); + } } else { setCtxAgentId(item.key); } @@ -499,6 +622,7 @@ export const ContextWindowWidget = defineComponent({ } onCleanup(() => { + clearCtxExpandAnim(); if (ro) ro.disconnect(); ctxSegmentBar.destroy(); }); diff --git a/sidecars/panel/src/components/widgets/LiveActivityWidget.js b/sidecars/panel/src/components/widgets/LiveActivityWidget.js index c65f761..6472bd9 100644 --- a/sidecars/panel/src/components/widgets/LiveActivityWidget.js +++ b/sidecars/panel/src/components/widgets/LiveActivityWidget.js @@ -6,6 +6,7 @@ */ import { defineComponent } from '../../core/component.js'; +import { isModernUiActiveForElement } from '../../core/appearance.js'; import { h, patchAttr, @@ -29,6 +30,7 @@ import { telemetryStore, } from '../../store/telemetryStore.js'; import { uiStore } from '../../store/uiStore.js'; +import { CustomScrollbar } from '../ui/CustomScrollbar.js'; export function buildFallbackRunningConversations( data, @@ -197,6 +199,38 @@ export const LiveActivityWidget = defineComponent({ } } + function readComputedPx(el, prop, fallback) { + if (!el || typeof window === 'undefined' || typeof window.getComputedStyle !== 'function') { + return fallback; + } + try { + const val = parseFloat(window.getComputedStyle(el)?.[prop]); + return Number.isFinite(val) ? val : fallback; + } catch { + return fallback; + } + } + + function clearSubExpandAnim(refs) { + if (!refs) return; + if (refs.subAnimTimer) { + clearTimeout(refs.subAnimTimer); + refs.subAnimTimer = null; + } + refs.isCollapsingSubs = false; + const host = refs.subScroll?.el; + if (host) { + host.ontransitionend = null; + patchClasses(host, { 'is-sub-animating': false }); + host.style.height = ''; + host.style.paddingTop = ''; + host.style.marginTop = ''; + host.style.opacity = ''; + host.style.overflow = ''; + host.style.transition = ''; + } + } + function createLiveTaskCard() { const dotIcon = createSvgIcon('dot', { size: 11 }); patchClasses(dotIcon, { 'is-pulsing': true }); @@ -219,12 +253,23 @@ export const LiveActivityWidget = defineComponent({ text: '', }) : null; - const subToggleBtn = h('button', { - type: 'button', - className: 'live-sub-toggle', - hidden: true, - text: t('live.subToggleIdle', { total: 0, arrow: '▸' }), + const subToggleLabel = h('span', { + className: 'live-sub-toggle-label', + text: t('live.subToggleIdle', { total: 0 }), }); + const subToggleChevron = createSvgIcon('chevron-down', { + size: 11, + className: 'live-sub-toggle-chevron', + }); + const subToggleBtn = h( + 'button', + { + type: 'button', + className: 'live-sub-toggle', + hidden: true, + }, + [subToggleLabel, subToggleChevron] + ); const elapsedEl = h('span', { className: 'live-activity-elapsed text-mono', text: '0s', @@ -273,7 +318,16 @@ export const LiveActivityWidget = defineComponent({ ]); const subListEl = h('div', { className: 'live-sub-list', hidden: true }); - const cardEl = h('div', { className: 'live-task-card' }, [headerEl, mainRowEl, subListEl]); + const subScroll = CustomScrollbar({ + contentEl: subListEl, + className: 'live-sub-scroll-host', + }); + patchAttr(subScroll.el, 'hidden', true); + const cardEl = h('div', { className: 'live-task-card' }, [ + headerEl, + mainRowEl, + subScroll.el, + ]); return { el: cardEl, @@ -284,6 +338,8 @@ export const LiveActivityWidget = defineComponent({ hereTagEl, metricsEl, subToggleBtn, + subToggleLabel, + subToggleChevron, elapsedEl, mainBadge, mainPhase, @@ -291,6 +347,9 @@ export const LiveActivityWidget = defineComponent({ mainSep, mainDetail, subListEl, + subScroll, + subAnimTimer: null, + isCollapsingSubs: false, }, }; } @@ -352,7 +411,12 @@ export const LiveActivityWidget = defineComponent({ patchAttr(liveActivityBar, 'hidden', !hasRunningTasks); if (!hasRunningTasks) { stopLiveTicker(); - patchKeyedList(liveActivityBar, [], {}); + patchKeyedList(liveActivityBar, [], { + destroyRow: (refs) => { + clearSubExpandAnim(refs); + refs?.subScroll?.destroy?.(); + }, + }); return; } @@ -479,19 +543,16 @@ export const LiveActivityWidget = defineComponent({ patchAttr(refs.mainBadge, 'hidden', subCount === 0); patchAttr(refs.subToggleBtn, 'hidden', subCount === 0); if (subCount > 0) { - const arrow = isExpanded ? '▾' : '▸'; const toggleText = runSubCount > 0 ? t(isPureSwarm ? 'live.swarmToggleRunning' : 'live.subToggleRunning', { run: runSubCount, total: subCount, - arrow, }) : t(isPureSwarm ? 'live.swarmToggleIdle' : 'live.subToggleIdle', { total: subCount, - arrow, }); - patchText(refs.subToggleBtn, toggleText); + patchText(refs.subToggleLabel, toggleText); patchClasses(refs.subToggleBtn, { 'is-expanded': isExpanded }); if (interactive) { patchAttr( @@ -501,11 +562,108 @@ export const LiveActivityWidget = defineComponent({ ); refs.subToggleBtn.onclick = (e) => { e.stopPropagation(); - manualSubExpandMap.set(item.cascadeId, !isExpanded); - if (latestUpdateArgs) update(latestUpdateArgs); - onLayoutChange?.(); + const nextExpanded = !resolveIsExpanded(item); + const host = refs.subScroll.el; + const curH = Number(host.offsetHeight || 0); + const curPadTop = readComputedPx(host, 'paddingTop', 6); + const curMarginTop = readComputedPx(host, 'marginTop', 3); + const curOpacity = readComputedPx(host, 'opacity', 1); + const parentGap = readComputedPx(refs.cardEl, 'rowGap', 7); + const collapsedMarginTop = -Math.max(0, Math.round(parentGap)); + const wasMidAnim = Boolean(refs.subAnimTimer); + clearSubExpandAnim(refs); + manualSubExpandMap.set(item.cascadeId, nextExpanded); + + const modern = isModernUiActiveForElement(refs.cardEl); + if (!modern) { + if (latestUpdateArgs) update(latestUpdateArgs); + onLayoutChange?.(); + return; + } + + if (nextExpanded) { + if (latestUpdateArgs) update(latestUpdateArgs); + const endH = Number(host.offsetHeight || host.scrollHeight || 0); + const endPadTop = readComputedPx(host, 'paddingTop', 6); + const endMarginTop = readComputedPx(host, 'marginTop', 3); + const fromH = wasMidAnim && curH > 0 ? curH : 0; + const fromPadTop = wasMidAnim && curH > 0 ? curPadTop : 0; + const fromMarginTop = wasMidAnim && curH > 0 ? curMarginTop : collapsedMarginTop; + const fromOpacity = wasMidAnim && curH > 0 ? curOpacity : 0; + if (endH > 0) { + patchClasses(host, { 'is-sub-animating': true }); + host.style.height = `${fromH}px`; + host.style.paddingTop = `${fromPadTop}px`; + host.style.marginTop = `${fromMarginTop}px`; + host.style.opacity = `${fromOpacity}`; + host.style.overflow = 'hidden'; + void host.offsetHeight; + host.style.transition = + 'height 220ms cubic-bezier(0.16, 1, 0.3, 1), padding-top 220ms cubic-bezier(0.16, 1, 0.3, 1), margin-top 220ms cubic-bezier(0.16, 1, 0.3, 1), opacity 180ms ease-out'; + host.style.height = `${endH}px`; + host.style.paddingTop = `${endPadTop}px`; + host.style.marginTop = `${endMarginTop}px`; + host.style.opacity = '1'; + const finishExpand = () => { + clearSubExpandAnim(refs); + refs.subScroll.refresh(); + onLayoutChange?.(); + }; + host.ontransitionend = (ev) => { + if ( + ev?.target === host && + (!ev.propertyName || ev.propertyName === 'height') + ) { + finishExpand(); + } + }; + refs.subAnimTimer = setTimeout(finishExpand, 260); + } else { + onLayoutChange?.(); + } + } else { + patchClasses(refs.subToggleBtn, { 'is-expanded': false }); + patchAttr(refs.subToggleBtn, 'title', t('live.subExpandTitle')); + if (curH > 0) { + refs.isCollapsingSubs = true; + patchClasses(host, { 'is-sub-animating': true }); + host.style.height = `${curH}px`; + host.style.paddingTop = `${curPadTop}px`; + host.style.marginTop = `${curMarginTop}px`; + host.style.opacity = `${curOpacity}`; + host.style.overflow = 'hidden'; + void host.offsetHeight; + host.style.transition = + 'height 200ms cubic-bezier(0.16, 1, 0.3, 1), padding-top 200ms cubic-bezier(0.16, 1, 0.3, 1), margin-top 200ms cubic-bezier(0.16, 1, 0.3, 1), opacity 150ms ease-out'; + host.style.height = '0px'; + host.style.paddingTop = '0px'; + host.style.marginTop = `${collapsedMarginTop}px`; + host.style.opacity = '0'; + const finishCollapse = () => { + clearSubExpandAnim(refs); + patchAttr(host, 'hidden', true); + patchAttr(refs.subListEl, 'hidden', true); + if (latestUpdateArgs) update(latestUpdateArgs); + onLayoutChange?.(); + }; + host.ontransitionend = (ev) => { + if ( + ev?.target === host && + (!ev.propertyName || ev.propertyName === 'height') + ) { + finishCollapse(); + } + }; + refs.subAnimTimer = setTimeout(finishCollapse, 240); + } else { + if (latestUpdateArgs) update(latestUpdateArgs); + onLayoutChange?.(); + } + } }; } + } else if (refs.isCollapsingSubs) { + clearSubExpandAnim(refs); } const mainLabel = formatLiveActivityLabel(act, 'live.thinking'); @@ -536,7 +694,10 @@ export const LiveActivityWidget = defineComponent({ } const showSubs = subCount > 0 && isExpanded; - patchAttr(refs.subListEl, 'hidden', !showSubs); + if (!refs.isCollapsingSubs) { + patchAttr(refs.subScroll.el, 'hidden', !showSubs); + patchAttr(refs.subListEl, 'hidden', !showSubs); + } if (showSubs) { const rawSubItems = item.subagents || []; const getSubSortRank = (s) => { @@ -651,8 +812,13 @@ export const LiveActivityWidget = defineComponent({ } }, }); + refs.subScroll.refresh(); } }, + destroyRow: (refs) => { + clearSubExpandAnim(refs); + refs?.subScroll?.destroy?.(); + }, }); for (const key of [...activityTimersMap.keys()]) { @@ -666,6 +832,12 @@ export const LiveActivityWidget = defineComponent({ onCleanup(() => { stopLiveTicker(); + patchKeyedList(liveActivityBar, [], { + destroyRow: (refs) => { + clearSubExpandAnim(refs); + refs?.subScroll?.destroy?.(); + }, + }); }); return { diff --git a/sidecars/panel/src/components/widgets/StepTableWidget.js b/sidecars/panel/src/components/widgets/StepTableWidget.js index c38ce47..e114a2b 100644 --- a/sidecars/panel/src/components/widgets/StepTableWidget.js +++ b/sidecars/panel/src/components/widgets/StepTableWidget.js @@ -131,6 +131,43 @@ export const StepTableWidget = defineComponent({ const hoverRows = new WeakMap(); let lastRenderedRows = null; let lastRenderOptions = ''; + let trackedCascadeId = null; + const seenStepKeys = new Set(); + const maxSeenStepByAgent = new Map(); + const activeEnterTimers = new Map(); + + function getStepRowIdentity(st, fallbackCascadeId) { + const agentKey = String(st?.agentCascadeId || fallbackCascadeId || 'conv'); + const stepNum = Number(st?.stepIndex); + const rowKey = `${agentKey}-${st?.stepIndex}`; + return { agentKey, stepNum, rowKey }; + } + + function absorbStepsIntoBaseline(stepList, fallbackCascadeId) { + if (!Array.isArray(stepList)) return; + for (const st of stepList) { + if (!st || typeof st !== 'object') continue; + const { agentKey, stepNum, rowKey } = getStepRowIdentity(st, fallbackCascadeId); + seenStepKeys.add(rowKey); + if (Number.isFinite(stepNum)) { + const prevMax = maxSeenStepByAgent.get(agentKey); + if (prevMax === undefined || stepNum > prevMax) { + maxSeenStepByAgent.set(agentKey, stepNum); + } + } + } + } + + function clearRowEnterState(tr) { + if (!tr) return; + const timer = activeEnterTimers.get(tr); + if (timer) { + clearTimeout(timer); + activeEnterTimers.delete(tr); + } + tr.onanimationend = null; + patchClasses(tr, { 'is-step-entering': false }); + } function enterStepCell(event) { const { badge, prompt } = hoverRows.get(this); @@ -171,8 +208,37 @@ export const StepTableWidget = defineComponent({ showStepSpeedColor = false, stepTokenComboFormat = undefined, displaySettings = {}, + allConversationSteps = null, + allowNewRowFade = false, } = {} ) { + const normCascadeId = String(cascadeId || ''); + let enteringRowKeys = null; + if (!normCascadeId || trackedCascadeId === null || normCascadeId !== trackedCascadeId) { + trackedCascadeId = normCascadeId || null; + seenStepKeys.clear(); + maxSeenStepByAgent.clear(); + absorbStepsIntoBaseline(allConversationSteps, normCascadeId); + absorbStepsIntoBaseline(tableSteps, normCascadeId); + } else if (!allowNewRowFade || standalone) { + absorbStepsIntoBaseline(allConversationSteps, normCascadeId); + absorbStepsIntoBaseline(tableSteps, normCascadeId); + } else { + for (const st of tableSteps) { + if (!st || typeof st !== 'object') continue; + const { agentKey, stepNum, rowKey } = getStepRowIdentity(st, normCascadeId); + if (!seenStepKeys.has(rowKey)) { + const prevMax = maxSeenStepByAgent.get(agentKey); + if (prevMax === undefined || !Number.isFinite(stepNum) || stepNum > prevMax) { + enteringRowKeys ??= new Set(); + enteringRowKeys.add(rowKey); + } + } + } + absorbStepsIntoBaseline(allConversationSteps, normCascadeId); + absorbStepsIntoBaseline(tableSteps, normCascadeId); + } + const colOrderSig = colKeys.join(','); const normTokenFmt = normalizeClientStepTokenComboFormat(stepTokenComboFormat); const renderOptions = JSON.stringify([ @@ -424,6 +490,21 @@ export const StepTableWidget = defineComponent({ hoverTd.onmousemove = firstColKey === 'step' ? moveInStepCell : moveAlongTurnRail; hoverTd.onmouseleave = hideTurnTip; } + + if (enteringRowKeys?.has(item.rowKey)) { + clearRowEnterState(tr); + patchClasses(tr, { 'is-step-entering': true }); + tr.onanimationend = (ev) => { + if (!ev || !ev.target || ev.target === tr) { + clearRowEnterState(tr); + } + }; + const timer = setTimeout(() => clearRowEnterState(tr), 960); + activeEnterTimers.set(tr, timer); + } + }, + destroyRow: (_refs, tr) => { + clearRowEnterState(tr); }, }); lastRenderOptions = renderOptions; @@ -433,6 +514,9 @@ export const StepTableWidget = defineComponent({ onCleanup(() => { stepsTablePane.removeEventListener('scroll', hideTurnTip); stepsTbody.removeEventListener('mouseleave', hideTurnTip); + for (const tr of [...activeEnterTimers.keys()]) { + clearRowEnterState(tr); + } }); return { diff --git a/sidecars/panel/src/core/appearance.js b/sidecars/panel/src/core/appearance.js index 2ff0a5e..4957014 100644 --- a/sidecars/panel/src/core/appearance.js +++ b/sidecars/panel/src/core/appearance.js @@ -38,23 +38,342 @@ export function normalizeClientFontScale(raw) { return Object.prototype.hasOwnProperty.call(FONT_SCALE_FACTORS, val) ? val : 'md'; } +export function normalizeClientModernUi(raw) { + if (typeof raw === 'string') { + const lower = raw.trim().toLowerCase(); + return lower === 'true' || lower === '1' || lower === 'on'; + } + return Boolean(raw); +} + +/** + * Check whether `el` (or its Shadow DOM host / document root) is currently under `[data-modern-ui="true"]`. + * + * @param {Node | null | undefined} el + * @returns {boolean} + */ +export function isModernUiActiveForElement(el) { + let cur = el || null; + while (cur) { + if (typeof cur.getAttribute === 'function' && cur.getAttribute('data-modern-ui') === 'true') { + return true; + } + if (cur.parentNode) { + cur = cur.parentNode; + } else if (cur.host) { + cur = cur.host; + } else { + break; + } + } + if (typeof document !== 'undefined' && document.documentElement) { + return document.documentElement.getAttribute?.('data-modern-ui') === 'true'; + } + return false; +} + +const LIGHT_THEME_CLASSES = new Set([ + 'light', + 'vs-light', + 'vscode-light', + 'hc-light', + 'vscode-high-contrast-light', +]); + +const DARK_THEME_CLASSES = new Set([ + 'dark', + 'vs-dark', + 'vscode-dark', + 'hc-black', + 'vscode-high-contrast', +]); + +function hslToRgb(hDeg, sPct, lPct) { + const h = (((hDeg % 360) + 360) % 360) / 360; + const s = Math.max(0, Math.min(1, sPct / 100)); + const l = Math.max(0, Math.min(1, lPct / 100)); + if (s === 0) { + const v = l * 255; + return [v, v, v]; + } + const hue2rgb = (p, q, t) => { + let tt = t; + if (tt < 0) tt += 1; + if (tt > 1) tt -= 1; + if (tt < 1 / 6) return p + (q - p) * 6 * tt; + if (tt < 1 / 2) return q; + if (tt < 2 / 3) return p + (q - p) * (2 / 3 - tt) * 6; + return p; + }; + const q = l < 0.5 ? l * (1 + s) : l + s - l * s; + const p = 2 * l - q; + return [ + hue2rgb(p, q, h + 1 / 3) * 255, + hue2rgb(p, q, h) * 255, + hue2rgb(p, q, h - 1 / 3) * 255, + ]; +} + +function parseAlphaToken(rawAlpha) { + if (rawAlpha == null || rawAlpha === '') return 1; + const str = String(rawAlpha).trim(); + if (!str) return 1; + if (str.endsWith('%')) { + const pct = parseFloat(str); + return Number.isFinite(pct) ? pct / 100 : 1; + } + const num = parseFloat(str); + return Number.isFinite(num) ? num : 1; +} + +/** + * Parse `#hex`, `rgb()/rgba()`, or `hsl()/hsla()` into perceptual luminance `[0, 1]`. + * Returns `null` when transparent (`alpha <= 0.15`) or unparseable. + * + * @param {string | null | undefined} rawColor + * @returns {number | null} + */ +export function parseCssColorLuminance(rawColor) { + const str = String(rawColor ?? '').trim().toLowerCase(); + if (!str || str === 'transparent' || str === 'none' || str === 'inherit' || str === 'initial') { + return null; + } + + if (str.startsWith('#')) { + const hex = str.slice(1); + let r = 0; + let g = 0; + let b = 0; + let a = 1; + if (hex.length === 3 || hex.length === 4) { + r = parseInt(hex[0] + hex[0], 16); + g = parseInt(hex[1] + hex[1], 16); + b = parseInt(hex[2] + hex[2], 16); + if (hex.length === 4) a = parseInt(hex[3] + hex[3], 16) / 255; + } else if (hex.length === 6 || hex.length === 8) { + r = parseInt(hex.slice(0, 2), 16); + g = parseInt(hex.slice(2, 4), 16); + b = parseInt(hex.slice(4, 6), 16); + if (hex.length === 8) a = parseInt(hex.slice(6, 8), 16) / 255; + } else { + return null; + } + if (!Number.isFinite(r) || !Number.isFinite(g) || !Number.isFinite(b) || a <= 0.15) { + return null; + } + return (0.299 * r + 0.587 * g + 0.114 * b) / 255; + } + + const rgbMatch = str.match(/^rgba?\(([^)]+)\)$/); + if (rgbMatch) { + const body = rgbMatch[1].trim(); + const [channelsPart, slashAlpha] = body.split('/'); + const parts = channelsPart + .trim() + .split(/[\s,]+/) + .filter(Boolean); + if (parts.length < 3) return null; + const parseChan = (tok) => + tok.endsWith('%') ? (parseFloat(tok) / 100) * 255 : parseFloat(tok); + const r = parseChan(parts[0]); + const g = parseChan(parts[1]); + const b = parseChan(parts[2]); + const a = slashAlpha !== undefined ? parseAlphaToken(slashAlpha) : parseAlphaToken(parts[3]); + if (!Number.isFinite(r) || !Number.isFinite(g) || !Number.isFinite(b) || a <= 0.15) { + return null; + } + return (0.299 * r + 0.587 * g + 0.114 * b) / 255; + } + + const hslMatch = str.match(/^hsla?\(([^)]+)\)$/); + if (hslMatch) { + const body = hslMatch[1].trim(); + const [channelsPart, slashAlpha] = body.split('/'); + const parts = channelsPart + .trim() + .split(/[\s,]+/) + .filter(Boolean); + if (parts.length < 3) return null; + const h = parseFloat(parts[0]); + const s = parseFloat(parts[1]); + const l = parseFloat(parts[2]); + const a = slashAlpha !== undefined ? parseAlphaToken(slashAlpha) : parseAlphaToken(parts[3]); + if (!Number.isFinite(h) || !Number.isFinite(s) || !Number.isFinite(l) || a <= 0.15) { + return null; + } + const [r, g, b] = hslToRgb(h, s, l); + return (0.299 * r + 0.587 * g + 0.114 * b) / 255; + } + + return null; +} + +function readStyleProp(el, cs, prop) { + if (prop.startsWith('--')) { + const inlineVal = + typeof el?.style?.getPropertyValue === 'function' + ? el.style.getPropertyValue(prop) + : el?.style?.[prop]; + if (inlineVal && String(inlineVal).trim()) return String(inlineVal).trim(); + const compVal = cs?.getPropertyValue?.(prop); + return compVal ? String(compVal).trim() : ''; + } + const inlineVal = el?.style?.[prop]; + if (inlineVal && String(inlineVal).trim()) return String(inlineVal).trim(); + const compVal = cs?.[prop]; + return compVal ? String(compVal).trim() : ''; +} + +/** + * Detect whether the active host surface is `'light'` or `'dark'`. + * Inspects explicit Antigravity / VS Code theme classes & attributes first, + * then actual computed surface/text luminance, then `prefers-color-scheme`. + * + * @param {HTMLElement | null | undefined} [targetEl] + * @returns {'light' | 'dark'} + */ +export function detectHostColorScheme(targetEl = null) { + const doc = typeof document !== 'undefined' ? document : null; + const win = typeof window !== 'undefined' ? window : null; + let workbenchEl = null; + try { + workbenchEl = + typeof doc?.querySelector === 'function' ? doc.querySelector('.monaco-workbench') : null; + } catch { + workbenchEl = null; + } + + const candidates = []; + for (const el of [doc?.body, doc?.documentElement, workbenchEl, targetEl]) { + if (el && !candidates.includes(el)) { + candidates.push(el); + } + } + + // 1. Explicit host theme attributes & class tokens (never read our own data-color-scheme) + for (const el of candidates) { + const vscodeKind = String(el.getAttribute?.('data-vscode-theme-kind') || '') + .trim() + .toLowerCase(); + if (vscodeKind) { + if (vscodeKind.includes('light')) return 'light'; + if (vscodeKind.includes('dark') || vscodeKind.includes('high-contrast')) return 'dark'; + } + const dataTheme = String( + el.getAttribute?.('data-theme') || el.getAttribute?.('data-color-mode') || '' + ) + .trim() + .toLowerCase(); + if (dataTheme === 'light' || dataTheme.endsWith('-light')) return 'light'; + if (dataTheme === 'dark' || dataTheme.endsWith('-dark')) return 'dark'; + + const rawCls = typeof el.className === 'string' ? el.className : ''; + if (rawCls) { + const tokens = rawCls.trim().toLowerCase().split(/\s+/); + for (const tok of tokens) { + if (LIGHT_THEME_CLASSES.has(tok)) return 'light'; + if (DARK_THEME_CLASSES.has(tok)) return 'dark'; + } + } + } + + // 2. Computed / inline surface background luminance + const bgTargets = []; + for (const el of [targetEl, doc?.body, doc?.documentElement, workbenchEl]) { + if (el && !bgTargets.includes(el)) { + bgTargets.push(el); + } + } + const bgProps = [ + '--background', + '--card', + '--vscode-sideBar-background', + '--vscode-editor-background', + 'backgroundColor', + ]; + for (const el of bgTargets) { + let cs = null; + try { + cs = typeof win?.getComputedStyle === 'function' ? win.getComputedStyle(el) : null; + } catch { + cs = null; + } + for (const prop of bgProps) { + const lum = parseCssColorLuminance(readStyleProp(el, cs, prop)); + if (lum !== null) { + return lum > 0.52 ? 'light' : 'dark'; + } + } + } + + // 3. Computed / inline foreground text luminance + const fgProps = ['--foreground', '--vscode-foreground', '--vscode-editor-foreground', 'color']; + for (const el of bgTargets) { + let cs = null; + try { + cs = typeof win?.getComputedStyle === 'function' ? win.getComputedStyle(el) : null; + } catch { + cs = null; + } + for (const prop of fgProps) { + const lum = parseCssColorLuminance(readStyleProp(el, cs, prop)); + if (lum !== null) { + return lum < 0.48 ? 'light' : 'dark'; + } + } + } + + // 4. OS media query fallback + try { + if (win?.matchMedia?.('(prefers-color-scheme: dark)')?.matches) { + return 'dark'; + } + } catch { + // ignore matchMedia errors + } + + return 'light'; +} + +function setAttrIfChanged(el, name, value) { + if (!el || typeof el.setAttribute !== 'function') return; + if (typeof el.getAttribute === 'function' && el.getAttribute(name) === value) return; + el.setAttribute(name, value); +} + +function removeAttrIfPresent(el, name) { + if (!el || typeof el.removeAttribute !== 'function') return; + if (typeof el.hasAttribute === 'function' && !el.hasAttribute(name)) return; + el.removeAttribute(name); +} + function setOrClearStyleVar(el, propName, value) { if (!el || !el.style) return; + const cur = + typeof el.style.getPropertyValue === 'function' + ? el.style.getPropertyValue(propName) + : el.style[propName] || ''; if (value) { + if (cur === value) return; if (typeof el.style.setProperty === 'function') { el.style.setProperty(propName, value); } else { el.style[propName] = value; } - } else if (typeof el.style.removeProperty === 'function') { - el.style.removeProperty(propName); - } else if (typeof el.style.setProperty === 'function') { - el.style.setProperty(propName, ''); + } else if (cur) { + if (typeof el.style.removeProperty === 'function') { + el.style.removeProperty(propName); + } else if (typeof el.style.setProperty === 'function') { + el.style.setProperty(propName, ''); + } else { + el.style[propName] = ''; + } } } /** - * Synchronize theme accent and (optionally) font scale tokens onto a root/host element. + * Synchronize theme accent, host color scheme polarity, and (optionally) font scale tokens + * onto a root/host element. * * @param {HTMLElement | null | undefined} targetEl * @param {object | null | undefined} settings @@ -72,7 +391,17 @@ export function applyAppearanceToRoot(targetEl, settings, { includeFontScale = t setOrClearStyleVar(targetEl, '--user-accent-primary', ''); setOrClearStyleVar(targetEl, '--user-accent-contrast', ''); } - targetEl.setAttribute?.('data-accent', preset.key); + setAttrIfChanged(targetEl, 'data-accent', preset.key); + + const colorScheme = detectHostColorScheme(targetEl); + setAttrIfChanged(targetEl, 'data-color-scheme', colorScheme); + + const isModernUi = normalizeClientModernUi(settings?.experimentalModernUi); + if (isModernUi) { + setAttrIfChanged(targetEl, 'data-modern-ui', 'true'); + } else { + removeAttrIfPresent(targetEl, 'data-modern-ui'); + } if (includeFontScale) { const scaleKey = normalizeClientFontScale(settings?.fontScale); @@ -80,12 +409,10 @@ export function applyAppearanceToRoot(targetEl, settings, { includeFontScale = t const panelFactor = PANEL_SCALE_FACTORS[scaleKey] ?? 1; setOrClearStyleVar(targetEl, '--ui-font-scale', factor === 1 ? '' : String(factor)); setOrClearStyleVar(targetEl, '--ui-panel-scale', panelFactor === 1 ? '' : String(panelFactor)); - targetEl.setAttribute?.('data-font-scale', scaleKey); + setAttrIfChanged(targetEl, 'data-font-scale', scaleKey); } else { setOrClearStyleVar(targetEl, '--ui-font-scale', ''); setOrClearStyleVar(targetEl, '--ui-panel-scale', ''); - if (typeof targetEl.removeAttribute === 'function') { - targetEl.removeAttribute('data-font-scale'); - } + removeAttrIfPresent(targetEl, 'data-font-scale'); } } diff --git a/sidecars/panel/src/core/domPatch.js b/sidecars/panel/src/core/domPatch.js index 1e40e46..d39900e 100644 --- a/sidecars/panel/src/core/domPatch.js +++ b/sidecars/panel/src/core/domPatch.js @@ -131,7 +131,11 @@ const keyedListState = new WeakMap(); * Keyed incremental list reconciler. * Reuses existing DOM nodes by key and patches only changed items in-place. */ -export function patchKeyedList(container, items, { keyFn, sigFn, createRow, updateRow }) { +export function patchKeyedList( + container, + items, + { keyFn = (_, i) => i, sigFn, createRow, updateRow, destroyRow } = {} +) { if (!container) return; let map = keyedListState.get(container); if (!map) { @@ -175,6 +179,7 @@ export function patchKeyedList(container, items, { keyFn, sigFn, createRow, upda if (record.el.parentNode === container) { container.removeChild(record.el); } + destroyRow?.(record.refs, record.el); map.delete(oldKey); } } diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 9045460..2a61196 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -145,9 +145,9 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ // Context Window Widget 'ctx.followActive': 'Follow Active ({badge})', 'ctx.followActiveTitle': 'Automatically inspect the active or running agent context window', - 'ctx.expandMore': '+{count} More ▾', + 'ctx.expandMore': '+{count} More', 'ctx.expandMoreTitle': 'Expand all {count} subagent context pills', - 'ctx.collapse': 'Less ▴', + 'ctx.collapse': 'Less', 'ctx.collapseTitle': 'Collapse extra subagent pills', 'ctx.ch.assistant': 'Assistant', 'ctx.ch.assistantTitle': 'Model reasoning, responses, and tool call arguments', @@ -199,14 +199,15 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'live.doneWithSteps': 'Done ({steps} steps)', 'live.waitingWithSteps': 'Waiting ({steps} steps)', 'live.killedWithSteps': 'Killed ({steps} steps)', - 'live.subToggleRunning': 'Subagents {run}/{total} {arrow}', - 'live.subToggleIdle': 'Subagents ({total}) {arrow}', - 'live.swarmToggleRunning': 'Swarm {run}/{total} {arrow}', - 'live.swarmToggleIdle': 'Swarm ({total}) {arrow}', + 'live.subToggleRunning': 'Subagents {run}/{total}', + 'live.subToggleIdle': 'Subagents ({total})', + 'live.swarmToggleRunning': 'Swarm {run}/{total}', + 'live.swarmToggleIdle': 'Swarm ({total})', 'live.subCollapseTitle': 'Collapse subagent list', 'live.subExpandTitle': 'Expand subagent activity list', // Consumption View + 'cons.rangeCycle': 'Cycle', 'cons.rangeToday': 'Today', 'cons.range24h': '24h', 'cons.range7d': '7d', @@ -406,6 +407,10 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.gen.fontLg': 'Large', 'settings.gen.fontXl': 'XL', 'settings.gen.fontHint': 'Scales sidebar and popover typography while keeping the inline capsule compact', + 'settings.gen.modernUi': 'Modern UI (Experimental)', + 'settings.gen.modernUiOff': 'Off', + 'settings.gen.modernUiOn': 'On', + 'settings.gen.modernUiHint': 'Removes most borders in favor of soft tonal surfaces and smoother animations', 'settings.gen.updateTitle': 'Updates & Pricing', 'settings.gen.updateMode': 'Update Policy', 'settings.gen.updateManual': 'Notify only, update manually', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 74346e1..38c3086 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -145,9 +145,9 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ // Context Window Widget 'ctx.followActive': '跟随活跃 ({badge})', 'ctx.followActiveTitle': '自动展示当前正在运行或最新活跃的代理上下文窗口', - 'ctx.expandMore': '+{count} 展开 ▾', + 'ctx.expandMore': '+{count} 展开', 'ctx.expandMoreTitle': '展开全部 {count} 个子代理的上下文窗口胶囊', - 'ctx.collapse': '收起 ▴', + 'ctx.collapse': '收起', 'ctx.collapseTitle': '折叠多余子代理胶囊', 'ctx.ch.assistant': '模型回复', 'ctx.ch.assistantTitle': '模型推理思考、回复正文与工具调用入参', @@ -199,14 +199,15 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'live.doneWithSteps': '已完成 ({steps} 步)', 'live.waitingWithSteps': '待命中 ({steps} 步)', 'live.killedWithSteps': '已终止 ({steps} 步)', - 'live.subToggleRunning': '子代理 {run}/{total} {arrow}', - 'live.subToggleIdle': '子代理 ({total}) {arrow}', - 'live.swarmToggleRunning': '蜂群 {run}/{total} {arrow}', - 'live.swarmToggleIdle': '蜂群 ({total}) {arrow}', + 'live.subToggleRunning': '子代理 {run}/{total}', + 'live.subToggleIdle': '子代理 ({total})', + 'live.swarmToggleRunning': '蜂群 {run}/{total}', + 'live.swarmToggleIdle': '蜂群 ({total})', 'live.subCollapseTitle': '点击收起子代理列表', 'live.subExpandTitle': '点击展开查看子代理缩略状态', // Consumption View + 'cons.rangeCycle': '周期', 'cons.rangeToday': '今天', 'cons.range24h': '1天', 'cons.range7d': '7天', @@ -406,6 +407,10 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.gen.fontLg': '大', 'settings.gen.fontXl': '特大', 'settings.gen.fontHint': '等比缩放侧边栏与展开面板字号,顶栏及输入框内嵌胶囊保持紧凑定高', + 'settings.gen.modernUi': '新 UI(实验性)', + 'settings.gen.modernUiOff': '关闭', + 'settings.gen.modernUiOn': '开启', + 'settings.gen.modernUiHint': '去除大部分线框,采用柔和分层底色与更流畅的现代过渡动画', 'settings.gen.updateTitle': '版本更新', 'settings.gen.updateMode': '更新方式', 'settings.gen.updateManual': '仅提示新版本,手动更新', diff --git a/sidecars/panel/src/main.js b/sidecars/panel/src/main.js index a4dede6..90a7887 100644 --- a/sidecars/panel/src/main.js +++ b/sidecars/panel/src/main.js @@ -29,10 +29,48 @@ async function bootstrapApp(mountTarget = document.getElementById('app-root')) { syncDocAppearance ); + let hostThemeObserver = null; + let colorSchemeMql = null; + const onHostThemeChange = () => { + syncDocAppearance(telemetryStore.getState().telemetry?.settings); + }; + try { + if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') { + hostThemeObserver = new MutationObserver(onHostThemeChange); + if (document.documentElement) { + hostThemeObserver.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'style', 'data-theme', 'data-vscode-theme-kind'], + }); + } + if (document.body) { + hostThemeObserver.observe(document.body, { + attributes: true, + attributeFilter: ['class', 'style', 'data-theme', 'data-vscode-theme-kind'], + }); + } + if (document.head) { + hostThemeObserver.observe(document.head, { + childList: true, + characterData: true, + subtree: true, + }); + } + } + if (typeof window !== 'undefined' && typeof window.matchMedia === 'function') { + colorSchemeMql = window.matchMedia('(prefers-color-scheme: dark)'); + colorSchemeMql?.addEventListener?.('change', onHostThemeChange); + } + } catch { + // ignore observer setup errors in constrained environments + } + const stopPolling = startAsyncTelemetryLoop(2000); return { appInstance, stopPolling: () => { + hostThemeObserver?.disconnect?.(); + colorSchemeMql?.removeEventListener?.('change', onHostThemeChange); unsubAppearance(); stopPolling(); }, diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index df5612c..e984548 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -14,7 +14,11 @@ import { getAgentBadgeClass, } from '../core/formatters.js'; import { normalizeI18nLanguage, t } from '../i18n/index.js'; -import { normalizeClientFontScale, normalizeClientThemeAccent } from '../core/appearance.js'; +import { + normalizeClientFontScale, + normalizeClientModernUi, + normalizeClientThemeAccent, +} from '../core/appearance.js'; import { DEFAULT_HOVER_MODULES, DEFAULT_OVERVIEW_METRICS, @@ -195,6 +199,7 @@ export function isEquivalentTelemetry(prev, next) { if ((pSet?.language ?? 'zh-CN') !== (nSet?.language ?? 'zh-CN')) return false; if ((pSet?.themeAccent ?? 'host') !== (nSet?.themeAccent ?? 'host')) return false; if ((pSet?.fontScale ?? 'md') !== (nSet?.fontScale ?? 'md')) return false; + if (Boolean(pSet?.experimentalModernUi) !== Boolean(nSet?.experimentalModernUi)) return false; if ((prev.hostPlatform || '') !== (next.hostPlatform || '')) return false; if (Boolean(pSet?.contextWindowRiskAccepted) !== Boolean(nSet?.contextWindowRiskAccepted)) { return false; @@ -895,6 +900,9 @@ export async function saveSettingsPatch(patch) { if (Object.prototype.hasOwnProperty.call(safePatch, 'fontScale')) { safePatch.fontScale = normalizeClientFontScale(safePatch.fontScale); } + if (Object.prototype.hasOwnProperty.call(safePatch, 'experimentalModernUi')) { + safePatch.experimentalModernUi = normalizeClientModernUi(safePatch.experimentalModernUi); + } if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) { safePatch.weeklyLimitMode = normalizeWeeklyLimitMode(safePatch.weeklyLimitMode); } diff --git a/sidecars/panel/src/styles/base.css b/sidecars/panel/src/styles/base.css index 8d4c8e7..7f487d2 100644 --- a/sidecars/panel/src/styles/base.css +++ b/sidecars/panel/src/styles/base.css @@ -54,6 +54,10 @@ td { color: inherit; } +button:focus:not(:focus-visible) { + outline: none; +} + input[type="number"] { appearance: textfield; -moz-appearance: textfield; diff --git a/sidecars/panel/src/styles/controls.css b/sidecars/panel/src/styles/controls.css index 96c2b09..c690472 100644 --- a/sidecars/panel/src/styles/controls.css +++ b/sidecars/panel/src/styles/controls.css @@ -95,6 +95,7 @@ color: var(--text-secondary); border: 1px solid var(--border-hairline); border-radius: var(--radius-xs); + outline: none; cursor: pointer; user-select: none; transition: @@ -104,6 +105,17 @@ transform var(--dur-instant) var(--ease-fast); } +.icon-btn:focus-visible, +.pill-tab:focus-visible, +.select-trigger:focus-visible, +.seg-btn:focus-visible, +.btn-primary:focus-visible, +.btn-secondary:focus-visible, +.btn-ghost-sm:focus-visible { + outline: none; + box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--accent-primary) 55%, transparent); +} + .icon-btn:hover { background: var(--surface-hover); color: var(--text-primary); @@ -155,6 +167,7 @@ min-height: calc(26px * var(--ui-font-scale, 1)); padding: 2px var(--space-2); border: none; + outline: none; background: transparent; color: var(--text-secondary); font-size: var(--fs-base); @@ -569,17 +582,51 @@ color: var(--text-primary); } -/* --- 6. 微边框分段控制器 (Micro-Bezel Segmented Control) --- */ +/* --- 6. 微边框分段控制器 (Micro-Bezel Sliding Segmented Control) --- */ .segmented { + position: relative; display: inline-flex; + flex-wrap: wrap; align-items: center; + align-self: flex-start; + width: fit-content; gap: 2px; + max-width: 100%; padding: 0; background: transparent; border: none; + user-select: none; +} + +.seg-glider { + position: absolute; + top: 0; + left: 0; + width: var(--glider-w, 0px); + height: var(--glider-h, 0px); + border-radius: var(--radius-xs); + background: var(--accent-primary-soft); + transform: translate3d(var(--glider-x, 0px), var(--glider-y, 0px), 0); + opacity: 0; + pointer-events: none; + z-index: 0; + will-change: transform, width; +} + +.segmented.has-glider .seg-glider { + opacity: 1; +} + +.seg-glider.is-ready { + transition: + transform var(--dur-fast) var(--ease-fast), + width var(--dur-fast) var(--ease-fast), + height var(--dur-fast) var(--ease-fast); } .seg-btn { + position: relative; + z-index: 1; display: inline-flex; align-items: center; justify-content: center; @@ -587,6 +634,7 @@ min-height: calc(22px * var(--ui-font-scale, 1)); padding: 2px 7px; border: none; + outline: none; background: transparent; color: var(--text-secondary); font-size: var(--fs-md); @@ -608,6 +656,17 @@ font-weight: 600; } +.segmented.has-glider .seg-btn:hover { + background: transparent; + color: var(--text-primary); +} + +.segmented.has-glider .seg-btn.is-active { + background: transparent; + color: var(--accent-primary); + font-weight: 600; +} + /* --- 7. 独立槽位自定义滚动条 (Bespoke Custom Scrollbar) --- */ .custom-scroll-host { position: relative; diff --git a/sidecars/panel/src/styles/modern-ui.css b/sidecars/panel/src/styles/modern-ui.css new file mode 100644 index 0000000..20acd1f --- /dev/null +++ b/sidecars/panel/src/styles/modern-ui.css @@ -0,0 +1,706 @@ +/* + * 实验性现代化无边框主题与流畅动画样式层 (modern-ui.css). + * 仅在根容器或 Shadow Host 携带 [data-modern-ui="true"] 时激活: + * 1. 移除绝大部分面板、矩阵、表格、徽章、按钮、输入框与悬浮窗的 1px 线框及分隔线; + * 2. 面板内部子数据块(如版本更新价格表/当前版本、消费矩阵指标格、汇总折线区)保持透明扁平,绝不套叠二层背景卡片; + * 3. 区分深色与浅色极性 ([data-color-scheme="light" | "dark"]): + * - 深色模式采用柔和提亮顶层卡片与轻薄半透雾面滑槽(绝不混入重黑色块); + * - 浅色模式采用微凉白瓷画布 (#f7f9fb) + 纯白悬浮顶层卡片 (#ffffff) + 纯白立体滑块; + * 4. 全局分段切换器 (.segmented / .long-pill-nav / .settings-thirdnav-bar) 按内容宽度贴合滑动。 + */ + +:root[data-modern-ui="true"], +:host([data-modern-ui="true"]), +[data-modern-ui="true"] { + --radius-sm: 10px; + --radius-xs: 7px; + --ease-modern: cubic-bezier(0.16, 1, 0.3, 1); + --dur-fast: 180ms; + --dur-normal: 240ms; + --modern-canvas-bg: var(--surface-bg); + --modern-surface-card: color-mix(in srgb, var(--surface-panel) 95.2%, #ffffff 4.8%); + --modern-surface-subtle: color-mix(in srgb, var(--text-primary) 5.2%, transparent); + --modern-surface-hover: color-mix(in srgb, var(--accent-primary) 11%, color-mix(in srgb, var(--text-primary) 4%, transparent)); + --modern-card-shadow: none; + --modern-nav-track-bg: var(--modern-surface-card); + --modern-inline-track-bg: color-mix(in srgb, var(--text-primary) 4.2%, transparent); + --modern-glider-bg: color-mix(in srgb, var(--accent-primary) 17%, color-mix(in srgb, var(--text-primary) 4%, transparent)); + --modern-glider-shadow: none; + --modern-progress-track: color-mix(in srgb, var(--text-primary) 8%, transparent); + --modern-stripe-bg: rgb(255 255 255 / 0.022); + --text-secondary: color-mix(in srgb, var(--text-primary) 80%, transparent); + --text-muted: color-mix(in srgb, var(--text-primary) 62%, transparent); + --modern-active-accent: color-mix(in srgb, var(--accent-primary) 86%, var(--text-primary) 14%); + --shadow-popover: 0 10px 28px rgb(0 0 0 / 0.28), 0 2px 8px rgb(0 0 0 / 0.14); + --shadow-overlay: 0 22px 52px rgb(0 0 0 / 0.42), 0 4px 16px rgb(0 0 0 / 0.20); +} + +:root[data-modern-ui="true"][data-color-scheme="light"], +:host([data-modern-ui="true"][data-color-scheme="light"]), +[data-modern-ui="true"][data-color-scheme="light"] { + --modern-canvas-bg: color-mix(in srgb, var(--surface-bg) 95.5%, hsl(216 34% 48%) 4.5%); + --modern-surface-card: #ffffff; + --modern-surface-subtle: hsl(216 42% 97.2%); + --modern-surface-hover: hsl(216 56% 94.4%); + --modern-card-shadow: 0 1px 3px rgb(15 23 42 / 0.045), 0 4px 14px rgb(15 23 42 / 0.028); + --modern-nav-track-bg: hsl(216 28% 94.2%); + --modern-inline-track-bg: hsl(216 32% 96.2%); + --modern-glider-bg: #ffffff; + --modern-glider-shadow: 0 1px 2px rgb(15 23 42 / 0.08), 0 1px 1px rgb(15 23 42 / 0.04); + --modern-progress-track: hsl(216 28% 93.4%); + --modern-stripe-bg: hsl(216 40% 97.8%); + --text-secondary: color-mix(in srgb, var(--text-primary) 72%, transparent); + --text-muted: color-mix(in srgb, var(--text-primary) 58%, transparent); + --modern-active-accent: var(--accent-primary); + --shadow-popover: 0 10px 28px rgb(15 23 42 / 0.10), 0 2px 8px rgb(15 23 42 / 0.05); + --shadow-overlay: 0 20px 48px rgb(15 23 42 / 0.14), 0 4px 14px rgb(15 23 42 / 0.06); +} + +@keyframes anim-modern-view-in { + from { + opacity: 0; + transform: translate3d(0, 5px, 0); + } + to { + opacity: 1; + transform: translate3d(0, 0, 0); + } +} + +@keyframes anim-modern-pop-in { + from { + opacity: 0; + transform: translateY(-4px) scale(0.975); + } + to { + opacity: 1; + transform: translateY(0) scale(1); + } +} + +@keyframes anim-modern-pop-in-up { + from { + opacity: 0; + transform: translateY(4px) scale(0.975); + } + to { + opacity: 1; + transform: translateY(0) scale(1); + } +} + +@keyframes anim-modern-tip-fade { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +@keyframes anim-modern-step-row-in { + 0% { + opacity: 0; + background-color: transparent; + animation-timing-function: cubic-bezier(0.22, 1, 0.36, 1); + } + 20% { + opacity: 0.84; + background-color: color-mix(in srgb, var(--accent-primary) 7.5%, transparent); + animation-timing-function: ease-out; + } + 36% { + opacity: 1; + background-color: color-mix(in srgb, var(--accent-primary) 6%, transparent); + animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + } + 70% { + opacity: 1; + background-color: color-mix(in srgb, var(--accent-primary) 2%, transparent); + animation-timing-function: ease-out; + } + 100% { + opacity: 1; + background-color: transparent; + } +} + +@keyframes anim-modern-step-cell-in { + from { + transform: translate3d(0, -3px, 0); + } + to { + transform: translate3d(0, 0, 0); + } +} + +@keyframes anim-modern-pill-in { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +/* --- 1. 外壳画布、顶层卡片与按量贴合滑动轨道 (Canvas, Top-Level Cards & Fit-Content Sliding Tracks) --- */ +html[data-standalone="true"][data-modern-ui="true"] #app-root { + min-height: 100dvh; + background: var(--modern-canvas-bg); +} + +html[data-standalone="true"][data-modern-ui="true"] .app-shell { + border-left: none; + border-right: none; +} + +[data-modern-ui="true"] .app-shell { + background: var(--modern-canvas-bg); +} + +[data-modern-ui="true"] .view-pane { + animation: anim-modern-view-in 220ms var(--ease-modern); +} + +[data-modern-ui="true"] .panel, +[data-modern-ui="true"] .session-header { + border: none; + background: var(--modern-surface-card); + box-shadow: var(--modern-card-shadow); +} + +[data-modern-ui="true"] .panel .panel { + background: var(--modern-surface-subtle); + box-shadow: none; +} + +[data-modern-ui="true"] .long-pill-nav, +[data-modern-ui="true"] .settings-thirdnav-bar { + border: none; + background: var(--modern-nav-track-bg); +} + +[data-modern-ui="true"] .settings-subnav-bar { + padding: 0; + border: none; + background: transparent; +} + +[data-modern-ui="true"] .segmented { + padding: 2px; + border-radius: var(--radius-xs); + background: var(--modern-inline-track-bg); +} + +[data-modern-ui="true"] .settings-subnav-bar .segmented { + padding: 3px; + border-radius: var(--radius-sm); + background: var(--modern-nav-track-bg); +} + +[data-modern-ui="true"] .pill-glider { + border: none; + background: var(--modern-glider-bg); + box-shadow: var(--modern-glider-shadow); + transition: transform 230ms var(--ease-modern); +} + +[data-modern-ui="true"] .seg-glider { + border: none; + background: var(--modern-glider-bg); + box-shadow: var(--modern-glider-shadow); +} + +[data-modern-ui="true"] .seg-glider.is-ready { + transition: + transform 220ms var(--ease-modern), + width 220ms var(--ease-modern), + height 180ms var(--ease-modern); +} + +[data-modern-ui="true"] .segmented:not(.has-glider) .seg-btn.is-active { + background: var(--modern-glider-bg); + box-shadow: var(--modern-glider-shadow); +} + +[data-modern-ui="true"] .thirdnav-glider { + border: none; + background: var(--modern-glider-bg); + box-shadow: var(--modern-glider-shadow); + transition: transform 220ms var(--ease-modern); +} + +[data-modern-ui="true"] .pill-tab, +[data-modern-ui="true"] .seg-btn, +[data-modern-ui="true"] .structure-thirdnav-btn { + transition: + color 160ms var(--ease-modern), + transform 140ms var(--ease-modern); +} + +[data-modern-ui="true"] .pill-tab:active, +[data-modern-ui="true"] .seg-btn:active, +[data-modern-ui="true"] .structure-thirdnav-btn:active { + transform: scale(0.97); +} + +/* --- 2. 按钮、状态标签、代理徽章与胶囊全面去边框 --- */ +[data-modern-ui="true"] .status-tag, +[data-modern-ui="true"] .status-tag.state-running, +[data-modern-ui="true"] .status-tag.state-synced, +[data-modern-ui="true"] .status-tag.state-warn, +[data-modern-ui="true"] .update-badge-btn, +[data-modern-ui="true"] .wm-update-btn, +[data-modern-ui="true"] .wm-hover-update-bar, +:host([data-modern-ui="true"]) .wm-update-btn { + border: none; +} + +[data-modern-ui="true"] .icon-btn, +[data-modern-ui="true"] .btn-secondary, +[data-modern-ui="true"] .btn-ghost-sm, +[data-modern-ui="true"] .live-sub-toggle, +[data-modern-ui="true"] .ctx-agent-pill, +[data-modern-ui="true"] .theme-host-chip, +[data-modern-ui="true"] .collapsible-badge { + border: none; + background: var(--modern-surface-subtle); + transition: + background-color 160ms var(--ease-modern), + color 160ms var(--ease-modern), + transform 140ms var(--ease-modern); +} + +[data-modern-ui="true"] .session-header .icon-btn { + background: var(--modern-surface-subtle); +} + +[data-modern-ui="true"] .icon-btn:hover, +[data-modern-ui="true"] .btn-secondary:hover:not(:disabled), +[data-modern-ui="true"] .btn-ghost-sm:hover:not(:disabled), +[data-modern-ui="true"] .live-sub-toggle:hover, +[data-modern-ui="true"] .ctx-agent-pill:hover, +[data-modern-ui="true"] .theme-host-chip:hover { + border: none; + background: var(--modern-surface-hover); +} + +[data-modern-ui="true"] .pill-tab.is-active, +[data-modern-ui="true"] .pill-tab.is-active .svg-icon, +[data-modern-ui="true"] .pill-tab.is-active .pill-tab-badge, +[data-modern-ui="true"] .seg-btn.is-active, +[data-modern-ui="true"] .structure-thirdnav-btn.is-active { + color: var(--modern-active-accent); +} + +[data-modern-ui="true"] .live-sub-toggle.is-expanded, +[data-modern-ui="true"] .ctx-agent-pill.is-active, +[data-modern-ui="true"] .theme-host-chip.is-active { + border: none; + color: var(--modern-active-accent); + background: var(--accent-primary-soft); +} + +[data-modern-ui="true"] .ctx-agent-pill.is-more-toggle { + color: var(--text-secondary); +} + +[data-modern-ui="true"] .btn-ghost-sm:disabled { + opacity: 0.54; +} + +[data-modern-ui="true"] .live-sub-row.is-done { + opacity: 0.82; +} + +[data-modern-ui="true"] .live-sub-row.is-waiting-sub { + opacity: 0.92; +} + +[data-modern-ui="true"] .live-sub-row.is-killed-sub { + opacity: 0.68; +} + +[data-modern-ui="true"] .live-sub-toggle-chevron, +[data-modern-ui="true"] .ctx-toggle-chevron { + transition: transform 200ms var(--ease-modern); +} + +[data-modern-ui="true"] .ctx-agent-pill.is-pill-entering { + animation: anim-modern-pill-in 180ms ease-out both; +} + +[data-modern-ui="true"] .ctx-agent-pill.is-pill-collapsing { + opacity: 0; + transition: opacity 150ms ease-out; +} + +[data-modern-ui="true"] .btn-primary { + border: none; + transition: + opacity 160ms var(--ease-modern), + transform 140ms var(--ease-modern); +} + +[data-modern-ui="true"] .agent-badge, +[data-modern-ui="true"] .agent-badge.is-clickable:hover { + border: none; +} + +[data-modern-ui="true"] .agent-badge:not(.badge-main):not([class*="badge-sub-"]) { + background: var(--modern-surface-subtle); +} + +/* --- 3. 实时概览矩阵与任务卡片:顶层独立卡片,面板内子块绝不叠套背景 --- */ +[data-modern-ui="true"] .telemetry-matrix { + border: none; + background: transparent; + gap: 6px; + overflow: visible; +} + +[data-modern-ui="true"] .matrix-cell { + background: var(--modern-surface-card); + box-shadow: var(--modern-card-shadow); + border-radius: var(--radius-sm); + padding: 8px 10px; + transition: background-color 160ms var(--ease-modern); +} + +/* 面板内的双栏信息项(如版本更新中的「价格表 / 当前版本」)不套二层背景 */ +[data-modern-ui="true"] .dual-grid > .matrix-cell { + background: transparent; + box-shadow: none; + border-radius: 0; + padding: 2px 0; +} + +/* 结构页预览画布内的测速卡与任务卡保持轻微层次以呈现真实预览布局 */ +[data-modern-ui="true"] .structure-preview-canvas .matrix-cell { + background: var(--modern-surface-subtle); + box-shadow: none; + border-radius: var(--radius-xs); +} + +[data-modern-ui="true"] .live-task-card { + border: none; + background: var(--modern-surface-card); + box-shadow: var(--modern-card-shadow); + border-radius: var(--radius-sm); +} + +[data-modern-ui="true"] .structure-preview-canvas .live-task-card { + background: var(--modern-surface-subtle); + box-shadow: none; + border-radius: var(--radius-xs); +} + +[data-modern-ui="true"] .live-sub-scroll-host { + border-top: none; + padding-top: 6px; +} + +[data-modern-ui="true"] .live-sub-scroll-host.is-sub-animating > .scrollbar-rail { + opacity: 0 !important; + pointer-events: none; +} + +[data-modern-ui="true"] .progress-track { + border-radius: var(--radius-pill); + background: var(--modern-progress-track); +} + +/* --- 4. 用量统计矩阵、热力格与详情卡去边框且不叠内层背景 --- */ +[data-modern-ui="true"] .cons-box, +[data-modern-ui="true"] .cons-custom-range-bar { + border: none; + background: transparent; +} + +[data-modern-ui="true"] .dt-popover .icon-btn { + background: transparent; +} + +[data-modern-ui="true"] .dt-popover .icon-btn:hover { + background: var(--modern-surface-hover); +} + +[data-modern-ui="true"] .cons-unified-matrix { + border: none; + background: transparent; + gap: 10px 12px; + padding: 2px 0; + overflow: visible; +} + +[data-modern-ui="true"] .cons-split-3 { + gap: 12px; +} + +[data-modern-ui="true"] .cons-matrix-bottom { + border-top: none; +} + +[data-modern-ui="true"] .cons-col, +[data-modern-ui="true"] .cons-col.is-bordered-col { + border: none; + background: transparent; + border-radius: 0; + padding: 2px 0; +} + +[data-modern-ui="true"] .trend-peak-pill, +[data-modern-ui="true"] .trend-hm-cell.lv-0, +[data-modern-ui="true"] .trend-hm-swatch.lv-0 { + border: none; +} + +[data-modern-ui="true"] .trend-tip-sub, +[data-modern-ui="true"] .cons-pop-models { + border-top: none; + padding-top: 3px; +} + +[data-modern-ui="true"] .cons-source-bar-hit:hover .cons-source-model-bar, +[data-modern-ui="true"] .cons-source-bar-hit.is-hovered .cons-source-model-bar, +[data-modern-ui="true"] .month-col.is-interactive:hover .month-stack, +[data-modern-ui="true"] .month-col.is-hovered .month-stack { + box-shadow: none; + filter: brightness(1.06); + transform: scaleY(1.06); +} + +[data-modern-ui="true"] .cons-source-model-bar, +[data-modern-ui="true"] .month-stack { + transition: + height var(--dur-normal) var(--ease-modern), + transform 150ms var(--ease-modern), + filter 150ms var(--ease-modern); +} + +/* --- 5. 调用记录表格与模型分析区去横线边框且不套内层背景 --- */ +[data-modern-ui="true"] .table-scroll-host { + border-top: none; + background: transparent; +} + +[data-modern-ui="true"] .table-viewport, +[data-modern-ui="true"] .data-table th { + background: var(--modern-surface-card); +} + +[data-modern-ui="true"] .data-table th, +[data-modern-ui="true"] .data-table td { + border-bottom: none; +} + +[data-modern-ui="true"] .data-table tbody tr { + transition: background-color 130ms var(--ease-modern); +} + +[data-modern-ui="true"] .steps-data-table tbody tr.is-step-entering { + animation: anim-modern-step-row-in 850ms cubic-bezier(0.22, 1, 0.36, 1) both; +} + +[data-modern-ui="true"] .steps-data-table tbody tr.is-step-entering > td { + animation: anim-modern-step-cell-in 300ms cubic-bezier(0.22, 1, 0.36, 1) both; +} + +[data-modern-ui="true"] .data-table tbody tr:nth-child(even) { + background: var(--modern-stripe-bg); +} + +[data-modern-ui="true"] .data-table tbody tr:hover { + background: var(--modern-surface-hover); +} + +[data-modern-ui="true"] .steps-inline-scope-select .select-trigger, +[data-modern-ui="true"] .steps-inline-model-select .select-trigger, +[data-modern-ui="true"] .sstep-fit-model-select .select-trigger { + border: none; + background: var(--modern-surface-subtle); +} + +[data-modern-ui="true"] .sstep-card, +[data-modern-ui="true"] .smodel-empty { + border: none; + background: transparent; + padding-left: 2px; + padding-right: 2px; +} + +[data-modern-ui="true"] .smodel-card { + border: none; + background: transparent; +} + +[data-modern-ui="true"] .step-table-preview-host { + border: none; + background: var(--modern-surface-subtle); +} + +[data-modern-ui="true"] .smodel-card:hover { + background: var(--modern-surface-hover); +} + +[data-modern-ui="true"] .smodel-card.is-fit-active { + border: none; + background: var(--accent-primary-soft); +} + +/* --- 6. 设置表单、折叠面板、槽位排序与输入控件去边框 --- */ +[data-modern-ui="true"] .collapsible-body, +[data-modern-ui="true"] .settings-action-block + .settings-action-block, +[data-modern-ui="true"] .settings-account-entry, +[data-modern-ui="true"] .dt-time-row { + border-top: none; +} + +[data-modern-ui="true"] .settings-divider { + display: none; +} + +[data-modern-ui="true"] .editable-slot-row, +[data-modern-ui="true"] .editable-slot-empty, +[data-modern-ui="true"] .structure-preview-empty, +[data-modern-ui="true"] .preview-sidebar-note, +[data-modern-ui="true"] .preview-capsule-bar, +[data-modern-ui="true"] .preview-capsule-bar.is-composer .wm-multi-btn, +[data-modern-ui="true"] .preview-capsule-bar.is-composer .wm-capsule-btn, +[data-modern-ui="true"] .preview-composer-chip { + border: none; + background: var(--modern-surface-subtle); +} + +[data-modern-ui="true"] .slot-add-btn, +[data-modern-ui="true"] .settings-bridge-relaunch-btn { + border: none; +} + +[data-modern-ui="true"] .ctx-risk-mask, +[data-modern-ui="true"] .settings-bridge-notice, +[data-modern-ui="true"] .settings-bridge-notice.is-restart { + border: none; +} + +[data-modern-ui="true"] .number-input, +[data-modern-ui="true"] .dt-trigger, +[data-modern-ui="true"] .dt-mini-step, +[data-modern-ui="true"] .settings-text-input, +[data-modern-ui="true"] .settings-account-form input { + border: none; + background: var(--modern-surface-subtle); + transition: + background-color 150ms var(--ease-modern), + box-shadow 150ms var(--ease-modern); +} + +[data-modern-ui="true"] .num-step-btn { + background: transparent; +} + +[data-modern-ui="true"] .num-field { + border-left: none; + border-right: none; +} + +[data-modern-ui="true"] .number-input:focus-within, +[data-modern-ui="true"] .settings-text-input:focus, +[data-modern-ui="true"] .settings-account-form input:focus { + border: none; + box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--accent-primary) 55%, transparent); +} + +/* --- 7. 全景悬浮窗与工具提示浮层:零边框 + 空气阴影 + 0.15s 平滑跟随过渡 --- */ +[data-modern-ui="true"] .select-menu, +[data-modern-ui="true"] .dt-popover, +[data-modern-ui="true"] .sstep-tooltip { + border: none; + background: var(--modern-surface-card); + box-shadow: var(--shadow-popover); + animation: anim-modern-pop-in 150ms var(--ease-modern); +} + +[data-modern-ui="true"] .trend-tooltip, +[data-modern-ui="true"] .cons-breakdown-popover, +[data-modern-ui="true"] .turn-prompt-tip { + border: none; + background: var(--modern-surface-card); + box-shadow: var(--shadow-popover); + animation: anim-modern-tip-fade 150ms var(--ease-modern); +} + +[data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom) { + top: 2px; + bottom: auto; + transform: translate3d(var(--tip-shift, -50%), var(--tip-y, 0px), 0); +} + +[data-modern-ui="true"] .trend-tooltip.is-tracking { + transition: + left 150ms var(--ease-modern), + top 150ms var(--ease-modern), + bottom 150ms var(--ease-modern), + transform 150ms var(--ease-modern); +} + +[data-modern-ui="true"] .trend-hover-dot.is-tracking { + transition: + cx 150ms var(--ease-modern), + cy 150ms var(--ease-modern); +} + +[data-modern-ui="true"] .cons-breakdown-popover.is-tracking, +[data-modern-ui="true"] .turn-prompt-tip.is-tracking { + transition: + left 150ms var(--ease-modern), + top 150ms var(--ease-modern), + transform 150ms var(--ease-modern); +} + +[data-modern-ui="true"].wm-popover-panel, +[data-modern-ui="true"].wm-hover-tip, +[data-modern-ui="true"].wm-multi-panel, +:host([data-modern-ui="true"]) .wm-popover-panel, +:host([data-modern-ui="true"]) .wm-hover-tip, +:host([data-modern-ui="true"]) .wm-multi-panel { + border: none; + border-radius: 12px; + background: var(--modern-canvas-bg); + box-shadow: var(--shadow-overlay); + animation: anim-modern-pop-in 200ms var(--ease-modern); +} + +[data-modern-ui="true"].wm-popover-panel.is-above, +[data-modern-ui="true"].wm-hover-tip.is-above, +[data-modern-ui="true"].wm-multi-panel.is-above, +:host([data-modern-ui="true"]) .wm-popover-panel.is-above, +:host([data-modern-ui="true"]) .wm-hover-tip.is-above, +:host([data-modern-ui="true"]) .wm-multi-panel.is-above { + animation-name: anim-modern-pop-in-up; +} + +[data-modern-ui="true"] .wm-multi-header, +:host([data-modern-ui="true"]) .wm-multi-header, +[data-modern-ui="true"].wm-multi-panel .live-task-card + .live-task-card, +:host([data-modern-ui="true"]) .wm-multi-panel .live-task-card + .live-task-card { + border: none; +} + +[data-modern-ui="true"].wm-multi-panel, +:host([data-modern-ui="true"]) .wm-multi-panel { + background: var(--modern-surface-card); +} + +[data-modern-ui="true"].wm-multi-panel .live-activity-list, +:host([data-modern-ui="true"]) .wm-multi-panel .live-activity-list { + gap: 2px; +} + +[data-modern-ui="true"].wm-multi-panel .live-task-card, +:host([data-modern-ui="true"]) .wm-multi-panel .live-task-card { + padding: 10px 2px; + border-radius: 0; + background: transparent; + box-shadow: none; +} diff --git a/sidecars/panel/src/styles/views-consumption.css b/sidecars/panel/src/styles/views-consumption.css index beef0b5..1da21cf 100644 --- a/sidecars/panel/src/styles/views-consumption.css +++ b/sidecars/panel/src/styles/views-consumption.css @@ -14,6 +14,25 @@ gap: 6px; } +.cons-overview-head .segmented { + gap: 1px; +} + +.cons-overview-head .seg-btn { + padding: 2px 6px; +} + +.cons-custom-range-bar { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 6px; + padding: 2px 0 0; + background: transparent; + border: none; + border-radius: 0; +} + .cons-badge { font-size: var(--fs-md); font-weight: 500; diff --git a/sidecars/panel/src/styles/views-overview.css b/sidecars/panel/src/styles/views-overview.css index 623d1e1..c81be2a 100644 --- a/sidecars/panel/src/styles/views-overview.css +++ b/sidecars/panel/src/styles/views-overview.css @@ -172,6 +172,7 @@ background: var(--surface-panel); border: 1px solid var(--border-hairline); border-radius: var(--radius-xs); + outline: none; cursor: pointer; white-space: nowrap; transition: @@ -180,6 +181,15 @@ background-color var(--dur-instant) var(--ease-fast); } +.live-sub-toggle-chevron { + flex-shrink: 0; + transform: rotate(-90deg); +} + +.live-sub-toggle.is-expanded .live-sub-toggle-chevron { + transform: rotate(0deg); +} + .live-sub-toggle:hover { border-color: var(--border-strong); color: var(--text-primary); @@ -260,34 +270,31 @@ flex-shrink: 0; } -.live-sub-list { - display: flex; - flex-direction: column; - gap: 8px; +.live-sub-scroll-host { padding-top: 9px; - padding-right: 4px; margin-top: 3px; margin-left: 18px; border-top: 1px dashed var(--border-hairline); min-width: 0; +} + +.live-sub-list { + display: flex; + flex-direction: column; + gap: 8px; + padding-right: 8px; + min-width: 0; max-height: 196px; overflow-y: auto; overscroll-behavior: contain; - scrollbar-width: thin; - scrollbar-color: var(--border-subtle) transparent; + scrollbar-width: none; + -ms-overflow-style: none; } .live-sub-list::-webkit-scrollbar { - width: 4px; -} - -.live-sub-list::-webkit-scrollbar-track { - background: transparent; -} - -.live-sub-list::-webkit-scrollbar-thumb { - background: var(--border-subtle); - border-radius: 999px; + width: 0 !important; + height: 0 !important; + display: none !important; } .live-sub-row { @@ -564,7 +571,7 @@ /* --- 6. 上下文窗口内联代理切换器与代理徽章 (Scheme B Context Inspector & Agent Badges) --- */ .ctx-inspector-bar { display: flex; - align-items: center; + align-items: flex-start; width: 100%; padding: 0; background: transparent; @@ -586,6 +593,7 @@ min-height: calc(20px * var(--ui-font-scale, 1)); padding: 1px 6px; border: 1px solid var(--border-hairline); + outline: none; background: var(--surface-panel); color: var(--text-secondary); font-size: var(--fs-md); @@ -620,6 +628,14 @@ color: var(--text-primary); } +.ctx-toggle-chevron { + flex-shrink: 0; +} + +.ctx-agent-pill.is-more-toggle.is-expanded .ctx-toggle-chevron { + transform: rotate(180deg); +} + .panel-title .agent-badge { flex: 0 1 auto; min-width: 0; diff --git a/sidecars/panel/src/styles/views-settings.css b/sidecars/panel/src/styles/views-settings.css index 1c3d50a..171a05a 100644 --- a/sidecars/panel/src/styles/views-settings.css +++ b/sidecars/panel/src/styles/views-settings.css @@ -33,6 +33,7 @@ display: grid; grid-auto-flow: column; grid-auto-columns: minmax(0, 1fr); + align-self: stretch; gap: 3px; } @@ -44,13 +45,37 @@ /* --- 结构页三级子导航菜单 (.settings-thirdnav-bar) --- */ .settings-thirdnav-bar { + position: relative; display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); - gap: 4px; + align-items: center; + padding: 3px; + gap: 0; + background: var(--surface-panel); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-sm); flex-shrink: 0; + user-select: none; +} + +.thirdnav-glider { + position: absolute; + top: 3px; + bottom: 3px; + left: 3px; + width: calc((100% - 6px) / 4); + background: var(--accent-primary-soft); + border: 1px solid var(--accent-primary-border); + border-radius: var(--radius-xs); + transform: translate3d(calc(var(--active-third-index, 0) * 100%), 0, 0); + transition: transform var(--dur-fast) var(--ease-fast); + pointer-events: none; + z-index: 0; } .structure-thirdnav-btn { + position: relative; + z-index: 1; display: inline-flex; align-items: center; justify-content: center; @@ -58,29 +83,28 @@ min-height: calc(25px * var(--ui-font-scale, 1)); min-width: 0; padding: 2px 6px; - border: 1px solid var(--border-hairline); + border: none; + outline: none; border-radius: var(--radius-xs); - background: var(--surface-subtle); + background: transparent; color: var(--text-secondary); font-size: var(--fs-md); font-weight: 500; cursor: pointer; - transition: - background-color var(--dur-instant) var(--ease-fast), - color var(--dur-instant) var(--ease-fast), - border-color var(--dur-instant) var(--ease-fast); + transition: color var(--dur-instant) var(--ease-fast); +} + +.structure-thirdnav-btn:focus-visible { + outline: none; + box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--accent-primary) 55%, transparent); } .structure-thirdnav-btn:hover { color: var(--text-primary); - border-color: var(--border-strong); - background: var(--surface-hover); } .structure-thirdnav-btn.is-active { color: var(--accent-primary); - background: var(--accent-primary-soft); - border-color: var(--accent-primary-border); font-weight: 600; } diff --git a/sidecars/panel/src/views/ConsumptionView.js b/sidecars/panel/src/views/ConsumptionView.js index 0ab0618..11e6a6e 100644 --- a/sidecars/panel/src/views/ConsumptionView.js +++ b/sidecars/panel/src/views/ConsumptionView.js @@ -47,6 +47,7 @@ import { SegmentedControl } from '../components/ui/SegmentedControl.js'; /** 消耗统计顶栏支持的时间范围预设项 */ function getConsumptionTimeRangeOptions() { return [ + { value: 'cycle', label: t('cons.rangeCycle') }, { value: 'today', label: t('cons.rangeToday') }, { value: '24h', label: t('cons.range24h') }, { value: '7d', label: t('cons.range7d') }, @@ -135,8 +136,7 @@ export const ConsumptionView = defineComponent({ const customRangeBar = h( 'div', { - style: - 'display: flex; align-items: center; flex-wrap: wrap; gap: 6px; padding: 6px 8px; background: var(--surface-subtle); border: 1px solid var(--border-hairline); border-radius: var(--radius-xs);', + className: 'cons-custom-range-bar', hidden: true, }, [ @@ -338,6 +338,7 @@ export const ConsumptionView = defineComponent({ activeHoverTargetEl = null; } patchAttr(breakdownPopoverEl, 'hidden', true); + patchClasses(breakdownPopoverEl, { 'is-tracking': false }); } function positionBreakdownPopover(anchorEl, pointerClientX = null) { @@ -413,8 +414,22 @@ export const ConsumptionView = defineComponent({ }, }); + const wasHidden = breakdownPopoverEl.hasAttribute('hidden'); patchAttr(breakdownPopoverEl, 'hidden', false); positionBreakdownPopover(anchorEl, pointerClientX); + if (wasHidden) { + patchClasses(breakdownPopoverEl, { 'is-tracking': false }); + void breakdownPopoverEl.offsetWidth; + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + window.requestAnimationFrame(() => { + if (!breakdownPopoverEl.hasAttribute('hidden')) { + patchClasses(breakdownPopoverEl, { 'is-tracking': true }); + } + }); + } else { + patchClasses(breakdownPopoverEl, { 'is-tracking': true }); + } + } } function createMonthModelSegment() { diff --git a/sidecars/panel/src/views/StepsDetailView.js b/sidecars/panel/src/views/StepsDetailView.js index a3479fe..fe063ac 100644 --- a/sidecars/panel/src/views/StepsDetailView.js +++ b/sidecars/panel/src/views/StepsDetailView.js @@ -220,7 +220,6 @@ export const StepsDetailView = defineComponent({ collapseAll: true, multiUnit: t('steps.unitAgent'), modelValue: selectedAgentScopes, - icon: 'layers', placeholder: t('steps.allAgents'), className: 'steps-inline-scope-select', options: [{ value: 'all', label: t('steps.allAgents') }], @@ -503,7 +502,7 @@ export const StepsDetailView = defineComponent({ } } - function renderStepsData(slice) { + function renderStepsData(slice, { allowNewRowFade = false } = {}) { if (!slice) return; const uiSt = uiStore.getState(); const locale = getEffectiveLocale(); @@ -729,6 +728,12 @@ export const StepsDetailView = defineComponent({ ], }); + const allConversationSteps = hasSubagents + ? aggregated?.recentSteps || [] + : slice.recentSteps || []; + const shouldAnimateNewRows = Boolean( + allowNewRowFade && slice.experimentalModernUi && !showModels + ); if (!showModels) { const colKeys = normalizeClientStepColumns(slice.stepTableColumns); renderStepTable(tableSteps, slice.cascadeId, colKeys, locale, { @@ -740,6 +745,8 @@ export const StepsDetailView = defineComponent({ showStepSpeedColor: slice.showStepSpeedColor === true, stepTokenComboFormat: slice.stepTokenComboFormat, displaySettings, + allConversationSteps, + allowNewRowFade: shouldAnimateNewRows, }); stepsScroll.refresh(); } @@ -1070,6 +1077,7 @@ export const StepsDetailView = defineComponent({ st.telemetry?.settings?.stepTokenComboFormat ), stepTableColumns: st.telemetry?.settings?.stepTableColumns, + experimentalModernUi: Boolean(st.telemetry?.settings?.experimentalModernUi), }), (slice) => { latestSlice = slice; @@ -1081,7 +1089,9 @@ export const StepsDetailView = defineComponent({ return; } isDirty = false; - renderStepsData(slice); + renderStepsData(slice, { + allowNewRowFade: uiStore.getState().stepsSubTab === 'steps', + }); } ); diff --git a/sidecars/panel/src/views/settings/SettingsGeneralTab.js b/sidecars/panel/src/views/settings/SettingsGeneralTab.js index 138ade1..817bcb9 100644 --- a/sidecars/panel/src/views/settings/SettingsGeneralTab.js +++ b/sidecars/panel/src/views/settings/SettingsGeneralTab.js @@ -6,7 +6,9 @@ import { defineComponent } from '../../core/component.js'; import { + applyAppearanceToRoot, normalizeClientFontScale, + normalizeClientModernUi, normalizeClientThemeAccent, } from '../../core/appearance.js'; import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js'; @@ -39,6 +41,13 @@ function getFontScaleOptions() { ]; } +function getModernUiOptions() { + return [ + { value: 'off', label: t('settings.gen.modernUiOff') }, + { value: 'on', label: t('settings.gen.modernUiOn') }, + ]; +} + function getUpdateModeOptions() { return [ { value: 'manual', label: t('settings.gen.updateManual') }, @@ -66,6 +75,7 @@ export const SettingsGeneralTab = defineComponent({ let draftLanguage = 'zh-CN'; let draftThemeAccent = 'host'; let draftFontScale = 'md'; + let draftModernUi = false; let draftPluginUpdateMode = 'manual'; let latestSettings = null; let latestCloudStatus = null; @@ -123,6 +133,14 @@ export const SettingsGeneralTab = defineComponent({ className: 'settings-hint-text', text: t('settings.gen.fontHint'), }); + const modernUiLabelEl = h('span', { + className: 'form-label', + text: t('settings.gen.modernUi'), + }); + const modernUiHintEl = h('span', { + className: 'settings-hint-text', + text: t('settings.gen.modernUiHint'), + }); const languageSwitch = SegmentedControl({ ariaLabel: t('settings.gen.language'), @@ -181,6 +199,38 @@ export const SettingsGeneralTab = defineComponent({ }, }); + const modernUiSwitch = SegmentedControl({ + ariaLabel: t('settings.gen.modernUi'), + modelValue: 'off', + options: getModernUiOptions(), + onUpdateModelValue: async (val) => { + const nextModernUi = val === 'on'; + draftModernUi = nextModernUi; + modernUiSwitch.setValue(nextModernUi ? 'on' : 'off'); + if (typeof document !== 'undefined' && document.documentElement) { + applyAppearanceToRoot( + document.documentElement, + { + ...(latestSettings || {}), + themeAccent: draftThemeAccent, + fontScale: draftFontScale, + experimentalModernUi: nextModernUi, + }, + { includeFontScale: true } + ); + } + showAppearanceFeedback(t('settings.saving'), 0); + try { + await saveSettingsPatch({ experimentalModernUi: nextModernUi }); + showAppearanceFeedback(t('settings.saved'), 1500); + props.onLayoutChange?.(); + } catch { + if (latestSettings) renderSettings(latestSettings); + showAppearanceFeedback(t('settings.saveFailed'), 2500); + } + }, + }); + const appearancePanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title' }, [ @@ -192,6 +242,7 @@ export const SettingsGeneralTab = defineComponent({ h('div', { className: 'form-row' }, [langLabelEl, languageSwitch.el]), h('div', { className: 'form-row' }, [accentLabelEl, themeColorPicker.el]), h('div', { className: 'form-row' }, [fontLabelEl, fontScaleSwitch.el, fontHintEl]), + h('div', { className: 'form-row' }, [modernUiLabelEl, modernUiSwitch.el, modernUiHintEl]), ]); // --- Card 2: 版本更新 --- @@ -350,6 +401,7 @@ export const SettingsGeneralTab = defineComponent({ draftLanguage = normalizeI18nLanguage(settings.language); draftThemeAccent = normalizeClientThemeAccent(settings.themeAccent); draftFontScale = normalizeClientFontScale(settings.fontScale); + draftModernUi = normalizeClientModernUi(settings.experimentalModernUi); draftPluginUpdateMode = normalizeClientUpdateMode( settings.pluginUpdateMode, settings.autoUpdatePlugin @@ -364,6 +416,10 @@ export const SettingsGeneralTab = defineComponent({ modelValue: draftFontScale, options: getFontScaleOptions(), }); + modernUiSwitch.setProps({ + modelValue: draftModernUi ? 'on' : 'off', + options: getModernUiOptions(), + }); autoUpdateSelect.setProps({ modelValue: draftPluginUpdateMode, options: getUpdateModeOptions(), @@ -425,6 +481,8 @@ export const SettingsGeneralTab = defineComponent({ patchText(accentLabelEl, t('settings.gen.themeAccent')); patchText(fontLabelEl, t('settings.gen.fontScale')); patchText(fontHintEl, t('settings.gen.fontHint')); + patchText(modernUiLabelEl, t('settings.gen.modernUi')); + patchText(modernUiHintEl, t('settings.gen.modernUiHint')); patchText(updateTitleEl, t('settings.gen.updateTitle')); patchText(updateModeLabelEl, t('settings.gen.updateMode')); patchText(pricingCellLabelEl, t('settings.gen.pricingLabel')); @@ -441,6 +499,11 @@ export const SettingsGeneralTab = defineComponent({ modelValue: draftFontScale, options: getFontScaleOptions(), }); + modernUiSwitch.setProps({ + ariaLabel: t('settings.gen.modernUi'), + modelValue: draftModernUi ? 'on' : 'off', + options: getModernUiOptions(), + }); autoUpdateSelect.setProps({ modelValue: draftPluginUpdateMode, options: getUpdateModeOptions(), @@ -458,6 +521,7 @@ export const SettingsGeneralTab = defineComponent({ languageSwitch.destroy(); themeColorPicker.destroy(); fontScaleSwitch.destroy(); + modernUiSwitch.destroy(); autoUpdateSelect.destroy(); }); @@ -467,6 +531,7 @@ export const SettingsGeneralTab = defineComponent({ languageSwitch, themeColorPicker, fontScaleSwitch, + modernUiSwitch, autoUpdateSelect, syncPricingBtn, updatePluginBtn, diff --git a/sidecars/panel/src/views/settings/SettingsStructureTab.js b/sidecars/panel/src/views/settings/SettingsStructureTab.js index 2674351..4aaa801 100644 --- a/sidecars/panel/src/views/settings/SettingsStructureTab.js +++ b/sidecars/panel/src/views/settings/SettingsStructureTab.js @@ -7,7 +7,7 @@ */ import { defineComponent } from '../../core/component.js'; -import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js'; +import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js'; import { getEffectiveLocale, t } from '../../i18n/index.js'; import { createSvgIcon } from '../../icons/SvgIcon.js'; import { @@ -177,10 +177,29 @@ export const SettingsStructureTab = defineComponent({ 'aria-selected': item.key === activeThirdTab ? 'true' : 'false', 'data-structure-tab': item.key, onClick: () => { + applyActiveThirdTab(item.key); if (uiStore.getState().settingsStructureTab !== item.key) { uiStore.setState({ settingsStructureTab: item.key }); - } else { - applyActiveThirdTab(item.key); + } + }, + onKeydown: (e) => { + if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') { + e.preventDefault(); + const curIdx = Math.max( + 0, + STRUCTURE_THIRD_TABS.findIndex((it) => it.key === item.key) + ); + const delta = e.key === 'ArrowRight' ? 1 : -1; + const nextIdx = + (curIdx + delta + STRUCTURE_THIRD_TABS.length) % STRUCTURE_THIRD_TABS.length; + const nextItem = STRUCTURE_THIRD_TABS[nextIdx]; + if (nextItem) { + applyActiveThirdTab(nextItem.key); + if (uiStore.getState().settingsStructureTab !== nextItem.key) { + uiStore.setState({ settingsStructureTab: nextItem.key }); + } + thirdNavBtnMap.get(nextItem.key)?.btn?.focus?.(); + } } }, }, @@ -190,6 +209,7 @@ export const SettingsStructureTab = defineComponent({ return btn; }); + const thirdNavGlider = h('div', { className: 'thirdnav-glider', 'aria-hidden': 'true' }); const thirdNavBar = h( 'div', { @@ -197,7 +217,15 @@ export const SettingsStructureTab = defineComponent({ role: 'tablist', 'aria-label': t('settings.str.thirdTabAria'), }, - thirdNavBtns + [thirdNavGlider, ...thirdNavBtns] + ); + patchStyleVar( + thirdNavBar, + '--active-third-index', + Math.max( + 0, + STRUCTURE_THIRD_TABS.findIndex((it) => it.key === activeThirdTab) + ) ); // --- Pane 1: 挂载与胶囊栏 (`mount`) --- @@ -973,6 +1001,11 @@ export const SettingsStructureTab = defineComponent({ function applyActiveThirdTab(nextRawTab) { const nextTab = normalizeStructureTabKey(nextRawTab); activeThirdTab = nextTab; + const activeIdx = Math.max( + 0, + STRUCTURE_THIRD_TABS.findIndex((it) => it.key === nextTab) + ); + patchStyleVar(thirdNavBar, '--active-third-index', activeIdx); for (const [key, entry] of thirdNavBtnMap.entries()) { const isActive = key === nextTab; patchClasses(entry.btn, { 'is-active': isActive }); diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index a215260..94699bb 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -233,6 +233,10 @@ td { color: inherit; } +button:focus:not(:focus-visible) { + outline: none; +} + input[type="number"] { appearance: textfield; -moz-appearance: textfield; @@ -466,6 +470,7 @@ html[data-standalone="true"] .app-shell { color: var(--text-secondary); border: 1px solid var(--border-hairline); border-radius: var(--radius-xs); + outline: none; cursor: pointer; user-select: none; transition: @@ -475,6 +480,17 @@ html[data-standalone="true"] .app-shell { transform var(--dur-instant) var(--ease-fast); } +.icon-btn:focus-visible, +.pill-tab:focus-visible, +.select-trigger:focus-visible, +.seg-btn:focus-visible, +.btn-primary:focus-visible, +.btn-secondary:focus-visible, +.btn-ghost-sm:focus-visible { + outline: none; + box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--accent-primary) 55%, transparent); +} + .icon-btn:hover { background: var(--surface-hover); color: var(--text-primary); @@ -526,6 +542,7 @@ html[data-standalone="true"] .app-shell { min-height: calc(26px * var(--ui-font-scale, 1)); padding: 2px var(--space-2); border: none; + outline: none; background: transparent; color: var(--text-secondary); font-size: var(--fs-base); @@ -940,17 +957,51 @@ html[data-standalone="true"] .app-shell { color: var(--text-primary); } -/* --- 6. 微边框分段控制器 (Micro-Bezel Segmented Control) --- */ +/* --- 6. 微边框分段控制器 (Micro-Bezel Sliding Segmented Control) --- */ .segmented { + position: relative; display: inline-flex; + flex-wrap: wrap; align-items: center; + align-self: flex-start; + width: fit-content; gap: 2px; + max-width: 100%; padding: 0; background: transparent; border: none; + user-select: none; +} + +.seg-glider { + position: absolute; + top: 0; + left: 0; + width: var(--glider-w, 0px); + height: var(--glider-h, 0px); + border-radius: var(--radius-xs); + background: var(--accent-primary-soft); + transform: translate3d(var(--glider-x, 0px), var(--glider-y, 0px), 0); + opacity: 0; + pointer-events: none; + z-index: 0; + will-change: transform, width; +} + +.segmented.has-glider .seg-glider { + opacity: 1; +} + +.seg-glider.is-ready { + transition: + transform var(--dur-fast) var(--ease-fast), + width var(--dur-fast) var(--ease-fast), + height var(--dur-fast) var(--ease-fast); } .seg-btn { + position: relative; + z-index: 1; display: inline-flex; align-items: center; justify-content: center; @@ -958,6 +1009,7 @@ html[data-standalone="true"] .app-shell { min-height: calc(22px * var(--ui-font-scale, 1)); padding: 2px 7px; border: none; + outline: none; background: transparent; color: var(--text-secondary); font-size: var(--fs-md); @@ -979,6 +1031,17 @@ html[data-standalone="true"] .app-shell { font-weight: 600; } +.segmented.has-glider .seg-btn:hover { + background: transparent; + color: var(--text-primary); +} + +.segmented.has-glider .seg-btn.is-active { + background: transparent; + color: var(--accent-primary); + font-weight: 600; +} + /* --- 7. 独立槽位自定义滚动条 (Bespoke Custom Scrollbar) --- */ .custom-scroll-host { position: relative; @@ -1419,6 +1482,7 @@ html[data-standalone="true"] .app-shell { background: var(--surface-panel); border: 1px solid var(--border-hairline); border-radius: var(--radius-xs); + outline: none; cursor: pointer; white-space: nowrap; transition: @@ -1427,6 +1491,15 @@ html[data-standalone="true"] .app-shell { background-color var(--dur-instant) var(--ease-fast); } +.live-sub-toggle-chevron { + flex-shrink: 0; + transform: rotate(-90deg); +} + +.live-sub-toggle.is-expanded .live-sub-toggle-chevron { + transform: rotate(0deg); +} + .live-sub-toggle:hover { border-color: var(--border-strong); color: var(--text-primary); @@ -1507,34 +1580,31 @@ html[data-standalone="true"] .app-shell { flex-shrink: 0; } -.live-sub-list { - display: flex; - flex-direction: column; - gap: 8px; +.live-sub-scroll-host { padding-top: 9px; - padding-right: 4px; margin-top: 3px; margin-left: 18px; border-top: 1px dashed var(--border-hairline); min-width: 0; +} + +.live-sub-list { + display: flex; + flex-direction: column; + gap: 8px; + padding-right: 8px; + min-width: 0; max-height: 196px; overflow-y: auto; overscroll-behavior: contain; - scrollbar-width: thin; - scrollbar-color: var(--border-subtle) transparent; + scrollbar-width: none; + -ms-overflow-style: none; } .live-sub-list::-webkit-scrollbar { - width: 4px; -} - -.live-sub-list::-webkit-scrollbar-track { - background: transparent; -} - -.live-sub-list::-webkit-scrollbar-thumb { - background: var(--border-subtle); - border-radius: 999px; + width: 0 !important; + height: 0 !important; + display: none !important; } .live-sub-row { @@ -1811,7 +1881,7 @@ html[data-standalone="true"] .app-shell { /* --- 6. 上下文窗口内联代理切换器与代理徽章 (Scheme B Context Inspector & Agent Badges) --- */ .ctx-inspector-bar { display: flex; - align-items: center; + align-items: flex-start; width: 100%; padding: 0; background: transparent; @@ -1833,6 +1903,7 @@ html[data-standalone="true"] .app-shell { min-height: calc(20px * var(--ui-font-scale, 1)); padding: 1px 6px; border: 1px solid var(--border-hairline); + outline: none; background: var(--surface-panel); color: var(--text-secondary); font-size: var(--fs-md); @@ -1867,6 +1938,14 @@ html[data-standalone="true"] .app-shell { color: var(--text-primary); } +.ctx-toggle-chevron { + flex-shrink: 0; +} + +.ctx-agent-pill.is-more-toggle.is-expanded .ctx-toggle-chevron { + transform: rotate(180deg); +} + .panel-title .agent-badge { flex: 0 1 auto; min-width: 0; @@ -1949,6 +2028,25 @@ html[data-standalone="true"] .app-shell { gap: 6px; } +.cons-overview-head .segmented { + gap: 1px; +} + +.cons-overview-head .seg-btn { + padding: 2px 6px; +} + +.cons-custom-range-bar { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 6px; + padding: 2px 0 0; + background: transparent; + border: none; + border-radius: 0; +} + .cons-badge { font-size: var(--fs-md); font-weight: 500; @@ -3571,6 +3669,7 @@ html[data-standalone="true"] .app-shell { display: grid; grid-auto-flow: column; grid-auto-columns: minmax(0, 1fr); + align-self: stretch; gap: 3px; } @@ -3582,13 +3681,37 @@ html[data-standalone="true"] .app-shell { /* --- 结构页三级子导航菜单 (.settings-thirdnav-bar) --- */ .settings-thirdnav-bar { + position: relative; display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); - gap: 4px; + align-items: center; + padding: 3px; + gap: 0; + background: var(--surface-panel); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-sm); flex-shrink: 0; + user-select: none; +} + +.thirdnav-glider { + position: absolute; + top: 3px; + bottom: 3px; + left: 3px; + width: calc((100% - 6px) / 4); + background: var(--accent-primary-soft); + border: 1px solid var(--accent-primary-border); + border-radius: var(--radius-xs); + transform: translate3d(calc(var(--active-third-index, 0) * 100%), 0, 0); + transition: transform var(--dur-fast) var(--ease-fast); + pointer-events: none; + z-index: 0; } .structure-thirdnav-btn { + position: relative; + z-index: 1; display: inline-flex; align-items: center; justify-content: center; @@ -3596,29 +3719,28 @@ html[data-standalone="true"] .app-shell { min-height: calc(25px * var(--ui-font-scale, 1)); min-width: 0; padding: 2px 6px; - border: 1px solid var(--border-hairline); + border: none; + outline: none; border-radius: var(--radius-xs); - background: var(--surface-subtle); + background: transparent; color: var(--text-secondary); font-size: var(--fs-md); font-weight: 500; cursor: pointer; - transition: - background-color var(--dur-instant) var(--ease-fast), - color var(--dur-instant) var(--ease-fast), - border-color var(--dur-instant) var(--ease-fast); + transition: color var(--dur-instant) var(--ease-fast); +} + +.structure-thirdnav-btn:focus-visible { + outline: none; + box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--accent-primary) 55%, transparent); } .structure-thirdnav-btn:hover { color: var(--text-primary); - border-color: var(--border-strong); - background: var(--surface-hover); } .structure-thirdnav-btn.is-active { color: var(--accent-primary); - background: var(--accent-primary-soft); - border-color: var(--accent-primary-border); font-weight: 600; } @@ -5315,3 +5437,711 @@ html[data-standalone="true"] .app-shell { background: color-mix(in srgb, var(--text-secondary) 38%, transparent); flex-shrink: 0; } + +/* --- src/styles/modern-ui.css --- */ +/* + * 实验性现代化无边框主题与流畅动画样式层 (modern-ui.css). + * 仅在根容器或 Shadow Host 携带 [data-modern-ui="true"] 时激活: + * 1. 移除绝大部分面板、矩阵、表格、徽章、按钮、输入框与悬浮窗的 1px 线框及分隔线; + * 2. 面板内部子数据块(如版本更新价格表/当前版本、消费矩阵指标格、汇总折线区)保持透明扁平,绝不套叠二层背景卡片; + * 3. 区分深色与浅色极性 ([data-color-scheme="light" | "dark"]): + * - 深色模式采用柔和提亮顶层卡片与轻薄半透雾面滑槽(绝不混入重黑色块); + * - 浅色模式采用微凉白瓷画布 (#f7f9fb) + 纯白悬浮顶层卡片 (#ffffff) + 纯白立体滑块; + * 4. 全局分段切换器 (.segmented / .long-pill-nav / .settings-thirdnav-bar) 按内容宽度贴合滑动。 + */ + +:root[data-modern-ui="true"], +:host([data-modern-ui="true"]), +[data-modern-ui="true"] { + --radius-sm: 10px; + --radius-xs: 7px; + --ease-modern: cubic-bezier(0.16, 1, 0.3, 1); + --dur-fast: 180ms; + --dur-normal: 240ms; + --modern-canvas-bg: var(--surface-bg); + --modern-surface-card: color-mix(in srgb, var(--surface-panel) 95.2%, #ffffff 4.8%); + --modern-surface-subtle: color-mix(in srgb, var(--text-primary) 5.2%, transparent); + --modern-surface-hover: color-mix(in srgb, var(--accent-primary) 11%, color-mix(in srgb, var(--text-primary) 4%, transparent)); + --modern-card-shadow: none; + --modern-nav-track-bg: var(--modern-surface-card); + --modern-inline-track-bg: color-mix(in srgb, var(--text-primary) 4.2%, transparent); + --modern-glider-bg: color-mix(in srgb, var(--accent-primary) 17%, color-mix(in srgb, var(--text-primary) 4%, transparent)); + --modern-glider-shadow: none; + --modern-progress-track: color-mix(in srgb, var(--text-primary) 8%, transparent); + --modern-stripe-bg: rgb(255 255 255 / 0.022); + --text-secondary: color-mix(in srgb, var(--text-primary) 80%, transparent); + --text-muted: color-mix(in srgb, var(--text-primary) 62%, transparent); + --modern-active-accent: color-mix(in srgb, var(--accent-primary) 86%, var(--text-primary) 14%); + --shadow-popover: 0 10px 28px rgb(0 0 0 / 0.28), 0 2px 8px rgb(0 0 0 / 0.14); + --shadow-overlay: 0 22px 52px rgb(0 0 0 / 0.42), 0 4px 16px rgb(0 0 0 / 0.20); +} + +:root[data-modern-ui="true"][data-color-scheme="light"], +:host([data-modern-ui="true"][data-color-scheme="light"]), +[data-modern-ui="true"][data-color-scheme="light"] { + --modern-canvas-bg: color-mix(in srgb, var(--surface-bg) 95.5%, hsl(216 34% 48%) 4.5%); + --modern-surface-card: #ffffff; + --modern-surface-subtle: hsl(216 42% 97.2%); + --modern-surface-hover: hsl(216 56% 94.4%); + --modern-card-shadow: 0 1px 3px rgb(15 23 42 / 0.045), 0 4px 14px rgb(15 23 42 / 0.028); + --modern-nav-track-bg: hsl(216 28% 94.2%); + --modern-inline-track-bg: hsl(216 32% 96.2%); + --modern-glider-bg: #ffffff; + --modern-glider-shadow: 0 1px 2px rgb(15 23 42 / 0.08), 0 1px 1px rgb(15 23 42 / 0.04); + --modern-progress-track: hsl(216 28% 93.4%); + --modern-stripe-bg: hsl(216 40% 97.8%); + --text-secondary: color-mix(in srgb, var(--text-primary) 72%, transparent); + --text-muted: color-mix(in srgb, var(--text-primary) 58%, transparent); + --modern-active-accent: var(--accent-primary); + --shadow-popover: 0 10px 28px rgb(15 23 42 / 0.10), 0 2px 8px rgb(15 23 42 / 0.05); + --shadow-overlay: 0 20px 48px rgb(15 23 42 / 0.14), 0 4px 14px rgb(15 23 42 / 0.06); +} + +@keyframes anim-modern-view-in { + from { + opacity: 0; + transform: translate3d(0, 5px, 0); + } + to { + opacity: 1; + transform: translate3d(0, 0, 0); + } +} + +@keyframes anim-modern-pop-in { + from { + opacity: 0; + transform: translateY(-4px) scale(0.975); + } + to { + opacity: 1; + transform: translateY(0) scale(1); + } +} + +@keyframes anim-modern-pop-in-up { + from { + opacity: 0; + transform: translateY(4px) scale(0.975); + } + to { + opacity: 1; + transform: translateY(0) scale(1); + } +} + +@keyframes anim-modern-tip-fade { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +@keyframes anim-modern-step-row-in { + 0% { + opacity: 0; + background-color: transparent; + animation-timing-function: cubic-bezier(0.22, 1, 0.36, 1); + } + 20% { + opacity: 0.84; + background-color: color-mix(in srgb, var(--accent-primary) 7.5%, transparent); + animation-timing-function: ease-out; + } + 36% { + opacity: 1; + background-color: color-mix(in srgb, var(--accent-primary) 6%, transparent); + animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + } + 70% { + opacity: 1; + background-color: color-mix(in srgb, var(--accent-primary) 2%, transparent); + animation-timing-function: ease-out; + } + 100% { + opacity: 1; + background-color: transparent; + } +} + +@keyframes anim-modern-step-cell-in { + from { + transform: translate3d(0, -3px, 0); + } + to { + transform: translate3d(0, 0, 0); + } +} + +@keyframes anim-modern-pill-in { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +/* --- 1. 外壳画布、顶层卡片与按量贴合滑动轨道 (Canvas, Top-Level Cards & Fit-Content Sliding Tracks) --- */ +html[data-standalone="true"][data-modern-ui="true"] #app-root { + min-height: 100dvh; + background: var(--modern-canvas-bg); +} + +html[data-standalone="true"][data-modern-ui="true"] .app-shell { + border-left: none; + border-right: none; +} + +[data-modern-ui="true"] .app-shell { + background: var(--modern-canvas-bg); +} + +[data-modern-ui="true"] .view-pane { + animation: anim-modern-view-in 220ms var(--ease-modern); +} + +[data-modern-ui="true"] .panel, +[data-modern-ui="true"] .session-header { + border: none; + background: var(--modern-surface-card); + box-shadow: var(--modern-card-shadow); +} + +[data-modern-ui="true"] .panel .panel { + background: var(--modern-surface-subtle); + box-shadow: none; +} + +[data-modern-ui="true"] .long-pill-nav, +[data-modern-ui="true"] .settings-thirdnav-bar { + border: none; + background: var(--modern-nav-track-bg); +} + +[data-modern-ui="true"] .settings-subnav-bar { + padding: 0; + border: none; + background: transparent; +} + +[data-modern-ui="true"] .segmented { + padding: 2px; + border-radius: var(--radius-xs); + background: var(--modern-inline-track-bg); +} + +[data-modern-ui="true"] .settings-subnav-bar .segmented { + padding: 3px; + border-radius: var(--radius-sm); + background: var(--modern-nav-track-bg); +} + +[data-modern-ui="true"] .pill-glider { + border: none; + background: var(--modern-glider-bg); + box-shadow: var(--modern-glider-shadow); + transition: transform 230ms var(--ease-modern); +} + +[data-modern-ui="true"] .seg-glider { + border: none; + background: var(--modern-glider-bg); + box-shadow: var(--modern-glider-shadow); +} + +[data-modern-ui="true"] .seg-glider.is-ready { + transition: + transform 220ms var(--ease-modern), + width 220ms var(--ease-modern), + height 180ms var(--ease-modern); +} + +[data-modern-ui="true"] .segmented:not(.has-glider) .seg-btn.is-active { + background: var(--modern-glider-bg); + box-shadow: var(--modern-glider-shadow); +} + +[data-modern-ui="true"] .thirdnav-glider { + border: none; + background: var(--modern-glider-bg); + box-shadow: var(--modern-glider-shadow); + transition: transform 220ms var(--ease-modern); +} + +[data-modern-ui="true"] .pill-tab, +[data-modern-ui="true"] .seg-btn, +[data-modern-ui="true"] .structure-thirdnav-btn { + transition: + color 160ms var(--ease-modern), + transform 140ms var(--ease-modern); +} + +[data-modern-ui="true"] .pill-tab:active, +[data-modern-ui="true"] .seg-btn:active, +[data-modern-ui="true"] .structure-thirdnav-btn:active { + transform: scale(0.97); +} + +/* --- 2. 按钮、状态标签、代理徽章与胶囊全面去边框 --- */ +[data-modern-ui="true"] .status-tag, +[data-modern-ui="true"] .status-tag.state-running, +[data-modern-ui="true"] .status-tag.state-synced, +[data-modern-ui="true"] .status-tag.state-warn, +[data-modern-ui="true"] .update-badge-btn, +[data-modern-ui="true"] .wm-update-btn, +[data-modern-ui="true"] .wm-hover-update-bar, +:host([data-modern-ui="true"]) .wm-update-btn { + border: none; +} + +[data-modern-ui="true"] .icon-btn, +[data-modern-ui="true"] .btn-secondary, +[data-modern-ui="true"] .btn-ghost-sm, +[data-modern-ui="true"] .live-sub-toggle, +[data-modern-ui="true"] .ctx-agent-pill, +[data-modern-ui="true"] .theme-host-chip, +[data-modern-ui="true"] .collapsible-badge { + border: none; + background: var(--modern-surface-subtle); + transition: + background-color 160ms var(--ease-modern), + color 160ms var(--ease-modern), + transform 140ms var(--ease-modern); +} + +[data-modern-ui="true"] .session-header .icon-btn { + background: var(--modern-surface-subtle); +} + +[data-modern-ui="true"] .icon-btn:hover, +[data-modern-ui="true"] .btn-secondary:hover:not(:disabled), +[data-modern-ui="true"] .btn-ghost-sm:hover:not(:disabled), +[data-modern-ui="true"] .live-sub-toggle:hover, +[data-modern-ui="true"] .ctx-agent-pill:hover, +[data-modern-ui="true"] .theme-host-chip:hover { + border: none; + background: var(--modern-surface-hover); +} + +[data-modern-ui="true"] .pill-tab.is-active, +[data-modern-ui="true"] .pill-tab.is-active .svg-icon, +[data-modern-ui="true"] .pill-tab.is-active .pill-tab-badge, +[data-modern-ui="true"] .seg-btn.is-active, +[data-modern-ui="true"] .structure-thirdnav-btn.is-active { + color: var(--modern-active-accent); +} + +[data-modern-ui="true"] .live-sub-toggle.is-expanded, +[data-modern-ui="true"] .ctx-agent-pill.is-active, +[data-modern-ui="true"] .theme-host-chip.is-active { + border: none; + color: var(--modern-active-accent); + background: var(--accent-primary-soft); +} + +[data-modern-ui="true"] .ctx-agent-pill.is-more-toggle { + color: var(--text-secondary); +} + +[data-modern-ui="true"] .btn-ghost-sm:disabled { + opacity: 0.54; +} + +[data-modern-ui="true"] .live-sub-row.is-done { + opacity: 0.82; +} + +[data-modern-ui="true"] .live-sub-row.is-waiting-sub { + opacity: 0.92; +} + +[data-modern-ui="true"] .live-sub-row.is-killed-sub { + opacity: 0.68; +} + +[data-modern-ui="true"] .live-sub-toggle-chevron, +[data-modern-ui="true"] .ctx-toggle-chevron { + transition: transform 200ms var(--ease-modern); +} + +[data-modern-ui="true"] .ctx-agent-pill.is-pill-entering { + animation: anim-modern-pill-in 180ms ease-out both; +} + +[data-modern-ui="true"] .ctx-agent-pill.is-pill-collapsing { + opacity: 0; + transition: opacity 150ms ease-out; +} + +[data-modern-ui="true"] .btn-primary { + border: none; + transition: + opacity 160ms var(--ease-modern), + transform 140ms var(--ease-modern); +} + +[data-modern-ui="true"] .agent-badge, +[data-modern-ui="true"] .agent-badge.is-clickable:hover { + border: none; +} + +[data-modern-ui="true"] .agent-badge:not(.badge-main):not([class*="badge-sub-"]) { + background: var(--modern-surface-subtle); +} + +/* --- 3. 实时概览矩阵与任务卡片:顶层独立卡片,面板内子块绝不叠套背景 --- */ +[data-modern-ui="true"] .telemetry-matrix { + border: none; + background: transparent; + gap: 6px; + overflow: visible; +} + +[data-modern-ui="true"] .matrix-cell { + background: var(--modern-surface-card); + box-shadow: var(--modern-card-shadow); + border-radius: var(--radius-sm); + padding: 8px 10px; + transition: background-color 160ms var(--ease-modern); +} + +/* 面板内的双栏信息项(如版本更新中的「价格表 / 当前版本」)不套二层背景 */ +[data-modern-ui="true"] .dual-grid > .matrix-cell { + background: transparent; + box-shadow: none; + border-radius: 0; + padding: 2px 0; +} + +/* 结构页预览画布内的测速卡与任务卡保持轻微层次以呈现真实预览布局 */ +[data-modern-ui="true"] .structure-preview-canvas .matrix-cell { + background: var(--modern-surface-subtle); + box-shadow: none; + border-radius: var(--radius-xs); +} + +[data-modern-ui="true"] .live-task-card { + border: none; + background: var(--modern-surface-card); + box-shadow: var(--modern-card-shadow); + border-radius: var(--radius-sm); +} + +[data-modern-ui="true"] .structure-preview-canvas .live-task-card { + background: var(--modern-surface-subtle); + box-shadow: none; + border-radius: var(--radius-xs); +} + +[data-modern-ui="true"] .live-sub-scroll-host { + border-top: none; + padding-top: 6px; +} + +[data-modern-ui="true"] .live-sub-scroll-host.is-sub-animating > .scrollbar-rail { + opacity: 0 !important; + pointer-events: none; +} + +[data-modern-ui="true"] .progress-track { + border-radius: var(--radius-pill); + background: var(--modern-progress-track); +} + +/* --- 4. 用量统计矩阵、热力格与详情卡去边框且不叠内层背景 --- */ +[data-modern-ui="true"] .cons-box, +[data-modern-ui="true"] .cons-custom-range-bar { + border: none; + background: transparent; +} + +[data-modern-ui="true"] .dt-popover .icon-btn { + background: transparent; +} + +[data-modern-ui="true"] .dt-popover .icon-btn:hover { + background: var(--modern-surface-hover); +} + +[data-modern-ui="true"] .cons-unified-matrix { + border: none; + background: transparent; + gap: 10px 12px; + padding: 2px 0; + overflow: visible; +} + +[data-modern-ui="true"] .cons-split-3 { + gap: 12px; +} + +[data-modern-ui="true"] .cons-matrix-bottom { + border-top: none; +} + +[data-modern-ui="true"] .cons-col, +[data-modern-ui="true"] .cons-col.is-bordered-col { + border: none; + background: transparent; + border-radius: 0; + padding: 2px 0; +} + +[data-modern-ui="true"] .trend-peak-pill, +[data-modern-ui="true"] .trend-hm-cell.lv-0, +[data-modern-ui="true"] .trend-hm-swatch.lv-0 { + border: none; +} + +[data-modern-ui="true"] .trend-tip-sub, +[data-modern-ui="true"] .cons-pop-models { + border-top: none; + padding-top: 3px; +} + +[data-modern-ui="true"] .cons-source-bar-hit:hover .cons-source-model-bar, +[data-modern-ui="true"] .cons-source-bar-hit.is-hovered .cons-source-model-bar, +[data-modern-ui="true"] .month-col.is-interactive:hover .month-stack, +[data-modern-ui="true"] .month-col.is-hovered .month-stack { + box-shadow: none; + filter: brightness(1.06); + transform: scaleY(1.06); +} + +[data-modern-ui="true"] .cons-source-model-bar, +[data-modern-ui="true"] .month-stack { + transition: + height var(--dur-normal) var(--ease-modern), + transform 150ms var(--ease-modern), + filter 150ms var(--ease-modern); +} + +/* --- 5. 调用记录表格与模型分析区去横线边框且不套内层背景 --- */ +[data-modern-ui="true"] .table-scroll-host { + border-top: none; + background: transparent; +} + +[data-modern-ui="true"] .table-viewport, +[data-modern-ui="true"] .data-table th { + background: var(--modern-surface-card); +} + +[data-modern-ui="true"] .data-table th, +[data-modern-ui="true"] .data-table td { + border-bottom: none; +} + +[data-modern-ui="true"] .data-table tbody tr { + transition: background-color 130ms var(--ease-modern); +} + +[data-modern-ui="true"] .steps-data-table tbody tr.is-step-entering { + animation: anim-modern-step-row-in 850ms cubic-bezier(0.22, 1, 0.36, 1) both; +} + +[data-modern-ui="true"] .steps-data-table tbody tr.is-step-entering > td { + animation: anim-modern-step-cell-in 300ms cubic-bezier(0.22, 1, 0.36, 1) both; +} + +[data-modern-ui="true"] .data-table tbody tr:nth-child(even) { + background: var(--modern-stripe-bg); +} + +[data-modern-ui="true"] .data-table tbody tr:hover { + background: var(--modern-surface-hover); +} + +[data-modern-ui="true"] .steps-inline-scope-select .select-trigger, +[data-modern-ui="true"] .steps-inline-model-select .select-trigger, +[data-modern-ui="true"] .sstep-fit-model-select .select-trigger { + border: none; + background: var(--modern-surface-subtle); +} + +[data-modern-ui="true"] .sstep-card, +[data-modern-ui="true"] .smodel-empty { + border: none; + background: transparent; + padding-left: 2px; + padding-right: 2px; +} + +[data-modern-ui="true"] .smodel-card { + border: none; + background: transparent; +} + +[data-modern-ui="true"] .step-table-preview-host { + border: none; + background: var(--modern-surface-subtle); +} + +[data-modern-ui="true"] .smodel-card:hover { + background: var(--modern-surface-hover); +} + +[data-modern-ui="true"] .smodel-card.is-fit-active { + border: none; + background: var(--accent-primary-soft); +} + +/* --- 6. 设置表单、折叠面板、槽位排序与输入控件去边框 --- */ +[data-modern-ui="true"] .collapsible-body, +[data-modern-ui="true"] .settings-action-block + .settings-action-block, +[data-modern-ui="true"] .settings-account-entry, +[data-modern-ui="true"] .dt-time-row { + border-top: none; +} + +[data-modern-ui="true"] .settings-divider { + display: none; +} + +[data-modern-ui="true"] .editable-slot-row, +[data-modern-ui="true"] .editable-slot-empty, +[data-modern-ui="true"] .structure-preview-empty, +[data-modern-ui="true"] .preview-sidebar-note, +[data-modern-ui="true"] .preview-capsule-bar, +[data-modern-ui="true"] .preview-capsule-bar.is-composer .wm-multi-btn, +[data-modern-ui="true"] .preview-capsule-bar.is-composer .wm-capsule-btn, +[data-modern-ui="true"] .preview-composer-chip { + border: none; + background: var(--modern-surface-subtle); +} + +[data-modern-ui="true"] .slot-add-btn, +[data-modern-ui="true"] .settings-bridge-relaunch-btn { + border: none; +} + +[data-modern-ui="true"] .ctx-risk-mask, +[data-modern-ui="true"] .settings-bridge-notice, +[data-modern-ui="true"] .settings-bridge-notice.is-restart { + border: none; +} + +[data-modern-ui="true"] .number-input, +[data-modern-ui="true"] .dt-trigger, +[data-modern-ui="true"] .dt-mini-step, +[data-modern-ui="true"] .settings-text-input, +[data-modern-ui="true"] .settings-account-form input { + border: none; + background: var(--modern-surface-subtle); + transition: + background-color 150ms var(--ease-modern), + box-shadow 150ms var(--ease-modern); +} + +[data-modern-ui="true"] .num-step-btn { + background: transparent; +} + +[data-modern-ui="true"] .num-field { + border-left: none; + border-right: none; +} + +[data-modern-ui="true"] .number-input:focus-within, +[data-modern-ui="true"] .settings-text-input:focus, +[data-modern-ui="true"] .settings-account-form input:focus { + border: none; + box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--accent-primary) 55%, transparent); +} + +/* --- 7. 全景悬浮窗与工具提示浮层:零边框 + 空气阴影 + 0.15s 平滑跟随过渡 --- */ +[data-modern-ui="true"] .select-menu, +[data-modern-ui="true"] .dt-popover, +[data-modern-ui="true"] .sstep-tooltip { + border: none; + background: var(--modern-surface-card); + box-shadow: var(--shadow-popover); + animation: anim-modern-pop-in 150ms var(--ease-modern); +} + +[data-modern-ui="true"] .trend-tooltip, +[data-modern-ui="true"] .cons-breakdown-popover, +[data-modern-ui="true"] .turn-prompt-tip { + border: none; + background: var(--modern-surface-card); + box-shadow: var(--shadow-popover); + animation: anim-modern-tip-fade 150ms var(--ease-modern); +} + +[data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom) { + top: 2px; + bottom: auto; + transform: translate3d(var(--tip-shift, -50%), var(--tip-y, 0px), 0); +} + +[data-modern-ui="true"] .trend-tooltip.is-tracking { + transition: + left 150ms var(--ease-modern), + top 150ms var(--ease-modern), + bottom 150ms var(--ease-modern), + transform 150ms var(--ease-modern); +} + +[data-modern-ui="true"] .trend-hover-dot.is-tracking { + transition: + cx 150ms var(--ease-modern), + cy 150ms var(--ease-modern); +} + +[data-modern-ui="true"] .cons-breakdown-popover.is-tracking, +[data-modern-ui="true"] .turn-prompt-tip.is-tracking { + transition: + left 150ms var(--ease-modern), + top 150ms var(--ease-modern), + transform 150ms var(--ease-modern); +} + +[data-modern-ui="true"].wm-popover-panel, +[data-modern-ui="true"].wm-hover-tip, +[data-modern-ui="true"].wm-multi-panel, +:host([data-modern-ui="true"]) .wm-popover-panel, +:host([data-modern-ui="true"]) .wm-hover-tip, +:host([data-modern-ui="true"]) .wm-multi-panel { + border: none; + border-radius: 12px; + background: var(--modern-canvas-bg); + box-shadow: var(--shadow-overlay); + animation: anim-modern-pop-in 200ms var(--ease-modern); +} + +[data-modern-ui="true"].wm-popover-panel.is-above, +[data-modern-ui="true"].wm-hover-tip.is-above, +[data-modern-ui="true"].wm-multi-panel.is-above, +:host([data-modern-ui="true"]) .wm-popover-panel.is-above, +:host([data-modern-ui="true"]) .wm-hover-tip.is-above, +:host([data-modern-ui="true"]) .wm-multi-panel.is-above { + animation-name: anim-modern-pop-in-up; +} + +[data-modern-ui="true"] .wm-multi-header, +:host([data-modern-ui="true"]) .wm-multi-header, +[data-modern-ui="true"].wm-multi-panel .live-task-card + .live-task-card, +:host([data-modern-ui="true"]) .wm-multi-panel .live-task-card + .live-task-card { + border: none; +} + +[data-modern-ui="true"].wm-multi-panel, +:host([data-modern-ui="true"]) .wm-multi-panel { + background: var(--modern-surface-card); +} + +[data-modern-ui="true"].wm-multi-panel .live-activity-list, +:host([data-modern-ui="true"]) .wm-multi-panel .live-activity-list { + gap: 2px; +} + +[data-modern-ui="true"].wm-multi-panel .live-task-card, +:host([data-modern-ui="true"]) .wm-multi-panel .live-task-card { + padding: 10px 2px; + border-radius: 0; + background: transparent; + box-shadow: none; +} diff --git a/sidecars/panel/test/modern-ui.test.mjs b/sidecars/panel/test/modern-ui.test.mjs new file mode 100644 index 0000000..8e0357f --- /dev/null +++ b/sidecars/panel/test/modern-ui.test.mjs @@ -0,0 +1,627 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import { createMockDom } from './mock-dom.mjs'; +import { + DEFAULT_SETTINGS_SCHEMA, + normalizeExperimentalModernUi, + normalizeFullSettings, +} from '../backend/settings-schema.mjs'; +import { + applyAppearanceToRoot, + detectHostColorScheme, + normalizeClientModernUi, + parseCssColorLuminance, +} from '../src/core/appearance.js'; +import { createTrendAreaChart } from '../src/components/charts/TrendAreaChart.js'; +import { SegmentedControl } from '../src/components/ui/SegmentedControl.js'; +import { ContextWindowWidget } from '../src/components/widgets/ContextWindowWidget.js'; +import { LiveActivityWidget } from '../src/components/widgets/LiveActivityWidget.js'; +import { StepTableWidget } from '../src/components/widgets/StepTableWidget.js'; +import { isEquivalentTelemetry, telemetryStore } from '../src/store/telemetryStore.js'; +import { uiStore } from '../src/store/uiStore.js'; +import { i18nStore, setI18nLanguage } from '../src/i18n/index.js'; +import { ConsumptionView } from '../src/views/ConsumptionView.js'; +import { StepsDetailView } from '../src/views/StepsDetailView.js'; +import { SettingsGeneralTab } from '../src/views/settings/SettingsGeneralTab.js'; +import { SettingsStructureTab } from '../src/views/settings/SettingsStructureTab.js'; + +test('experimentalModernUi schema normalization defaults to false and coerces boolean/string values cleanly', () => { + assert.equal(DEFAULT_SETTINGS_SCHEMA.experimentalModernUi, false); + assert.equal(normalizeExperimentalModernUi(undefined), false); + assert.equal(normalizeExperimentalModernUi(false), false); + assert.equal(normalizeExperimentalModernUi('off'), false); + assert.equal(normalizeExperimentalModernUi(true), true); + assert.equal(normalizeExperimentalModernUi('true'), true); + assert.equal(normalizeExperimentalModernUi('on'), true); + assert.equal(normalizeClientModernUi('on'), true); + assert.equal(normalizeClientModernUi(false), false); + + assert.equal(normalizeFullSettings({}).experimentalModernUi, false); + assert.equal(normalizeFullSettings({ experimentalModernUi: true }).experimentalModernUi, true); + + assert.equal( + isEquivalentTelemetry( + { settings: { experimentalModernUi: false } }, + { settings: { experimentalModernUi: true } } + ), + false, + 'isEquivalentTelemetry must detect experimentalModernUi changes' + ); +}); + +test('detectHostColorScheme accurately distinguishes light vs dark host polarity across classes, CSS colors, and media queries', (t) => { + const prevDoc = globalThis.document; + const prevWin = globalThis.window; + + const { document } = createMockDom(); + globalThis.document = document; + globalThis.window = { + getComputedStyle: () => null, + matchMedia: () => ({ matches: false }), + }; + + t.after(() => { + globalThis.document = prevDoc; + globalThis.window = prevWin; + }); + + assert.ok(parseCssColorLuminance('#ffffff') > 0.99); + assert.ok(parseCssColorLuminance('#18181b') < 0.15); + assert.ok(parseCssColorLuminance('rgb(255, 255, 255)') > 0.99); + assert.ok(parseCssColorLuminance('rgb(21, 24, 30)') < 0.15); + assert.equal(parseCssColorLuminance('rgba(0, 0, 0, 0)'), null); + + // 1. Light webview on a Dark OS: explicit vscode-light class wins over prefers-color-scheme: dark + globalThis.window.matchMedia = () => ({ matches: true }); + document.body.className = 'vscode-light'; + assert.equal(detectHostColorScheme(document.documentElement), 'light'); + + // 2. Dark class wins cleanly + document.body.className = 'vscode-dark'; + assert.equal(detectHostColorScheme(document.documentElement), 'dark'); + + // 3. Computed surface luminance when no explicit theme class is present + document.body.className = ''; + globalThis.window.getComputedStyle = (el) => { + if (el === document.body) { + return { + backgroundColor: 'rgb(255, 255, 255)', + color: 'rgb(24, 24, 27)', + getPropertyValue: () => '', + }; + } + return null; + }; + assert.equal(detectHostColorScheme(document.documentElement), 'light'); + + globalThis.window.getComputedStyle = (el) => { + if (el === document.body) { + return { + backgroundColor: 'rgb(24, 24, 27)', + color: 'rgb(244, 244, 245)', + getPropertyValue: () => '', + }; + } + return null; + }; + assert.equal(detectHostColorScheme(document.documentElement), 'dark'); +}); + +test('applyAppearanceToRoot and SettingsGeneralTab toggle data-modern-ui + data-color-scheme and bundle includes crisp light-mode rules', async (t) => { + const prevLocale = i18nStore.getState().locale; + const prevDoc = globalThis.document; + const prevWin = globalThis.window; + const prevTelState = { ...telemetryStore.getState() }; + + const { document } = createMockDom(); + globalThis.document = document; + document.body.className = 'vscode-light'; + const savedPatches = []; + globalThis.window = { + location: { pathname: '/' }, + sidecar: { + fetch: async (_url, opts) => { + if (opts?.method === 'POST' && opts?.body) { + const parsed = JSON.parse(opts.body); + savedPatches.push(parsed); + return { + ok: true, + status: 200, + json: async () => ({ + ok: true, + settings: { language: 'zh-CN', themeAccent: 'host', fontScale: 'md', ...parsed }, + }), + }; + } + return { ok: true, status: 200, json: async () => ({ ok: true }) }; + }, + }, + addEventListener() {}, + removeEventListener() {}, + }; + + let tab = null; + t.after(() => { + if (tab) tab.destroy(); + setI18nLanguage(prevLocale); + telemetryStore.setState(prevTelState, { sync: true }); + globalThis.document = prevDoc; + globalThis.window = prevWin; + }); + + setI18nLanguage('zh-CN'); + + // 1. Default off -> no data-modern-ui attribute, stamps data-color-scheme="light" + applyAppearanceToRoot(document.documentElement, { experimentalModernUi: false }); + assert.equal(document.documentElement.hasAttribute('data-modern-ui'), false); + assert.equal(document.documentElement.getAttribute('data-color-scheme'), 'light'); + + applyAppearanceToRoot(document.documentElement, { experimentalModernUi: true }); + assert.equal(document.documentElement.getAttribute('data-modern-ui'), 'true'); + assert.equal(document.documentElement.getAttribute('data-color-scheme'), 'light'); + + document.body.className = 'vscode-dark'; + applyAppearanceToRoot(document.documentElement, { experimentalModernUi: true }); + assert.equal(document.documentElement.getAttribute('data-color-scheme'), 'dark'); + + document.body.className = 'vscode-light'; + applyAppearanceToRoot(document.documentElement, { experimentalModernUi: false }); + assert.equal(document.documentElement.hasAttribute('data-modern-ui'), false); + assert.equal(document.documentElement.getAttribute('data-color-scheme'), 'light'); + + // 2. SettingsGeneralTab renders '新 UI(实验性)' switch and toggles data-modern-ui immediately + tab = SettingsGeneralTab({}); + document.body.appendChild(tab.el); + tab.refs.renderSettings({ + language: 'zh-CN', + themeAccent: 'host', + fontScale: 'md', + experimentalModernUi: false, + pluginUpdateMode: 'manual', + }); + + assert.match(tab.el.textContent, /新 UI(实验性)/); + const modernBtns = tab.refs.modernUiSwitch.el.querySelectorAll('.seg-btn'); + assert.equal(modernBtns.length, 2); + assert.equal(modernBtns[0].classList.contains('is-active'), true); + + // Click '开启' (index 1) + modernBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 15)); + + assert.equal(document.documentElement.getAttribute('data-modern-ui'), 'true'); + assert.equal(savedPatches.length, 1); + assert.equal(savedPatches[0].experimentalModernUi, true); + + // 3. Built styles.css contains modern-ui borderless, sliding glider, and crisp pure-white light-mode rules + const builtStyles = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8'); + assert.match(builtStyles, /\[data-modern-ui="true"\]\s+\.panel/); + assert.match(builtStyles, /\[data-modern-ui="true"\]\[data-color-scheme="light"\]/); + assert.match(builtStyles, /--modern-surface-card:\s*#ffffff;/); + assert.match(builtStyles, /--modern-glider-bg:\s*#ffffff;/); + assert.match( + builtStyles, + /--text-secondary:\s*color-mix\(in srgb,\s*var\(--text-primary\)\s*80%,\s*transparent\);/ + ); + assert.match( + builtStyles, + /--text-muted:\s*color-mix\(in srgb,\s*var\(--text-primary\)\s*62%,\s*transparent\);/ + ); + assert.match( + builtStyles, + /\[data-modern-ui="true"\]\s+\.ctx-agent-pill\.is-more-toggle\s*\{[^}]*color:\s*var\(--text-secondary\);/ + ); + assert.match(builtStyles, /\.seg-glider\.is-ready/); + assert.match(builtStyles, /\.thirdnav-glider/); + assert.match(builtStyles, /\.segmented\s*\{[^}]*width:\s*fit-content;[^}]*\}/); + assert.doesNotMatch(builtStyles, /#000000/); + assert.match( + builtStyles, + /\[data-modern-ui="true"\]\s+\.dual-grid\s*>\s*\.matrix-cell\s*\{[^}]*background:\s*transparent;/ + ); + assert.match( + builtStyles, + /\.cons-custom-range-bar\s*\{[^}]*background:\s*transparent;/ + ); + assert.match( + builtStyles, + /\[data-modern-ui="true"\]\s+\.steps-data-table\s+tbody\s+tr\.is-step-entering/ + ); + assert.doesNotMatch( + builtStyles, + /(?:^|\n)\.steps-data-table\s+tbody\s+tr\.is-step-entering/, + 'Step row enter animation must ONLY exist under [data-modern-ui="true"]' + ); + assert.match( + builtStyles, + /\[data-modern-ui="true"\]\s+\.trend-tooltip\.is-tracking\s*\{[^}]*150ms/ + ); + assert.match( + builtStyles, + /\[data-modern-ui="true"\]\.wm-multi-panel\s+\.live-task-card[\s\S]*?background:\s*transparent;/ + ); + assert.match( + builtStyles, + /\.ctx-inspector-bar\s*\{[^}]*align-items:\s*flex-start;/, + 'ctx-inspector-bar must top-align pills so height clip never hides row 1 during expand/collapse' + ); + assert.match( + builtStyles, + /@keyframes\s+anim-modern-step-row-in\s*\{\s*0%\s*\{[^}]*opacity:\s*0;[^}]*background-color:\s*transparent;[\s\S]*?100%\s*\{[^}]*opacity:\s*1;[^}]*background-color:\s*transparent;/, + 'Step row fade-in must start and end with transparent background to avoid abrupt flashes' + ); + assert.doesNotMatch( + builtStyles, + /scrollbar-width:\s*thin/, + 'No element may opt into Chromium native scrollbar-width: thin' + ); +}); + +test('SegmentedControl variable-width glider snaps cleanly on reveal and glides across variable-width buttons, plus SettingsStructureTab thirdnav glider slides', (t) => { + const prevDoc = globalThis.document; + const prevWin = globalThis.window; + const prevUiState = { ...uiStore.getState() }; + + const { document } = createMockDom(); + globalThis.document = document; + let queuedRaf = null; + globalThis.window = { + requestAnimationFrame: (cb) => { + queuedRaf = cb; + return 1; + }, + cancelAnimationFrame: () => { + queuedRaf = null; + }, + addEventListener() {}, + removeEventListener() {}, + }; + + let seg = null; + let structureTab = null; + t.after(() => { + seg?.destroy(); + structureTab?.destroy(); + uiStore.setState(prevUiState, { sync: true }); + globalThis.document = prevDoc; + globalThis.window = prevWin; + }); + + // 1. Hidden / 0x0 fallback -> no .has-glider, button fallback active + const picked = []; + seg = SegmentedControl({ + ariaLabel: '视图切换', + modelValue: 'steps', + options: [ + { value: 'steps', label: '按步查看 (1520)' }, + { value: 'models', label: '总汇总' }, + ], + onUpdateModelValue: (v) => picked.push(v), + }); + + const glider = seg.refs.gliderEl; + const btns = seg.el.querySelectorAll('.seg-btn'); + assert.equal(seg.el.children[0], glider, '.seg-glider stays at child index 0'); + assert.equal(seg.el.classList.contains('has-glider'), false); + assert.equal(glider.classList.contains('is-ready'), false); + + // 2. Simulate layout reveal with variable widths: btn0 = 114px @ x=3, btn1 = 56px @ x=119 + Object.assign(btns[0], { offsetLeft: 3, offsetTop: 3, offsetWidth: 114, offsetHeight: 22 }); + Object.assign(btns[1], { offsetLeft: 119, offsetTop: 3, offsetWidth: 56, offsetHeight: 22 }); + + seg.refs.refreshGlider(); + assert.equal(seg.el.classList.contains('has-glider'), true); + assert.equal(glider.style.getPropertyValue('--glider-x'), '3px'); + assert.equal(glider.style.getPropertyValue('--glider-w'), '114px'); + assert.equal( + glider.classList.contains('is-ready'), + false, + 'Initial visible snap must not animate from 0px' + ); + + assert.equal(typeof queuedRaf, 'function'); + queuedRaf(); + assert.equal(glider.classList.contains('is-ready'), true, 'Transition armed on next frame'); + + // 3. Click second segment ('总汇总') -> glider slides to x=119px, w=56px with .is-ready intact + btns[1].dispatchEvent({ type: 'click', stopPropagation() {} }); + assert.deepEqual(picked, ['models']); + assert.equal(glider.style.getPropertyValue('--glider-x'), '119px'); + assert.equal(glider.style.getPropertyValue('--glider-w'), '56px'); + assert.equal(glider.classList.contains('is-ready'), true); + + // 4. ArrowLeft cycles back to 'steps' + btns[1].dispatchEvent({ type: 'keydown', key: 'ArrowLeft', preventDefault() {} }); + assert.deepEqual(picked, ['models', 'steps']); + assert.equal(glider.style.getPropertyValue('--glider-x'), '3px'); + assert.equal(glider.style.getPropertyValue('--glider-w'), '114px'); + + // 5. SettingsStructureTab 4-tab .settings-thirdnav-bar slides .thirdnav-glider via --active-third-index + uiStore.setState({ settingsStructureTab: 'mount' }, { sync: true }); + structureTab = SettingsStructureTab({}); + const thirdNavBar = structureTab.refs.thirdNavBar; + const thirdGlider = thirdNavBar.querySelector('.thirdnav-glider'); + const thirdBtns = thirdNavBar.querySelectorAll('.structure-thirdnav-btn'); + assert.ok(thirdGlider, 'thirdNavBar contains .thirdnav-glider'); + assert.equal(thirdNavBar.style.getPropertyValue('--active-third-index'), '0'); + + thirdBtns[2].dispatchEvent({ type: 'click' }); + uiStore.flushSync?.(); + assert.equal(thirdNavBar.style.getPropertyValue('--active-third-index'), '2'); + + thirdBtns[3].dispatchEvent({ type: 'click' }); + uiStore.flushSync?.(); + assert.equal(thirdNavBar.style.getPropertyValue('--active-third-index'), '3'); + + // 6. LiveActivityWidget wraps .live-sub-list inside CustomScrollbar (.live-sub-scroll-host) with zero native scrollbars + const liveWidget = LiveActivityWidget({ defaultExpandRunningSubs: true }); + liveWidget.refs.update({ + items: [ + { + cascadeId: 'conv-swarm-1', + title: 'Swarm Run', + isMainRunning: true, + subagentCount: 2, + runningSubagentCount: 1, + subagents: [ + { cascadeId: 'sub-1', index: 1, role: '@entry-runtime', isRunning: true, stepCount: 17 }, + { cascadeId: 'sub-2', index: 2, role: '@config-state', isRunning: false, stepCount: 7 }, + ], + }, + ], + }); + const scrollHost = liveWidget.el.querySelector('.live-sub-scroll-host'); + assert.ok(scrollHost, 'Subagent list is wrapped in CustomScrollbar .live-sub-scroll-host'); + assert.equal(scrollHost.hasAttribute('hidden'), false); + assert.ok(scrollHost.querySelector('.scrollbar-rail'), 'CustomScrollbar rail is mounted'); + assert.equal(liveWidget.el.querySelector('.live-sub-list').hasAttribute('hidden'), false); + liveWidget.destroy(); + + // 7. ConsumptionView places '周期' ('cycle') before '今天' ('today'), while defaulting active selection to 'today' + assert.equal(telemetryStore.getState().selectedTimeRange, 'today'); + setI18nLanguage('zh-CN'); + const consView = ConsumptionView({}); + const rangeBtns = consView.el.querySelector('.cons-overview-head').querySelectorAll('.seg-btn'); + assert.equal(rangeBtns[0].getAttribute('data-seg-value'), 'cycle'); + assert.equal(rangeBtns[0].textContent, '周期'); + assert.equal(rangeBtns[1].getAttribute('data-seg-value'), 'today'); + assert.equal(rangeBtns[1].textContent, '今天'); + assert.equal(rangeBtns[0].classList.contains('is-active'), false); + assert.equal(rangeBtns[1].classList.contains('is-active'), true, 'Default active range remains today'); + consView.destroy(); + + // 8. StepsDetailView inlineScopeSelect ('全部汇总') omits unnecessary leading SVG icon + const stepsView = StepsDetailView({}); + const scopeTriggerChildren = stepsView.refs.inlineScopeSelect.refs.triggerBtn.children; + assert.equal( + scopeTriggerChildren[0].hasAttribute('hidden'), + true, + 'inlineScopeSelect leading SVG icon is hidden' + ); + stepsView.destroy(); + + // 9. StepTableWidget animates ONLY genuinely newly added steps in Modern UI, never on initial load, filter change, classic UI, or conversation switch + const stepTable = StepTableWidget({}); + const cols = ['step', 'model', 'tokens_combo']; + const s1 = { stepIndex: 1, agentCascadeId: 'conv-a', modelShort: '4-carbon', inputTokens: 100 }; + const s2Sub = { + stepIndex: 1, + agentCascadeId: 'sub-1', + isSubagent: true, + agentId: 'sub-1', + modelShort: '4-carbon', + inputTokens: 80, + }; + const s2Main = { stepIndex: 2, agentCascadeId: 'conv-a', modelShort: '4-carbon', inputTokens: 200 }; + + // Initial load (conv-a, filtered to main only, while allConversationSteps has s2Sub too) -> 0 entering rows + stepTable.refs.renderStepTable([s2Main, s1], 'conv-a', cols, 'zh-CN', { + allConversationSteps: [s2Main, s2Sub, s1], + allowNewRowFade: true, + }); + assert.equal( + stepTable.refs.stepsTbody.children.some((tr) => tr.classList.contains('is-step-entering')), + false, + 'Initial render must never animate existing rows' + ); + + // Filter change reveals existing s2Sub -> 0 entering rows ("而且不是查看其他记录") + stepTable.refs.renderStepTable([s2Main, s2Sub, s1], 'conv-a', cols, 'zh-CN', { + allConversationSteps: [s2Main, s2Sub, s1], + allowNewRowFade: false, + }); + assert.equal( + stepTable.refs.stepsTbody.children.some((tr) => tr.classList.contains('is-step-entering')), + false, + 'Revealing existing subagent steps via filter must not animate' + ); + + // Classic UI (allowNewRowFade: false) when step #3 arrives -> 0 entering rows ("只有新ui才有这个动画") + const s3Classic = { stepIndex: 3, agentCascadeId: 'conv-a', modelShort: '4-carbon', inputTokens: 300 }; + stepTable.refs.renderStepTable([s3Classic, s2Main, s2Sub, s1], 'conv-a', cols, 'zh-CN', { + allConversationSteps: [s3Classic, s2Main, s2Sub, s1], + allowNewRowFade: false, + }); + assert.equal( + stepTable.refs.stepsTbody.children.some((tr) => tr.classList.contains('is-step-entering')), + false, + 'Classic UI must not animate newly added step rows' + ); + + // Modern UI live update (allowNewRowFade: true) when step #4 arrives -> ONLY row 0 (#4) gets is-step-entering + const s4New = { stepIndex: 4, agentCascadeId: 'conv-a', modelShort: '4-carbon', inputTokens: 400 }; + stepTable.refs.renderStepTable([s4New, s3Classic, s2Main, s2Sub, s1], 'conv-a', cols, 'zh-CN', { + allConversationSteps: [s4New, s3Classic, s2Main, s2Sub, s1], + allowNewRowFade: true, + }); + assert.equal(stepTable.refs.stepsTbody.children[0].classList.contains('is-step-entering'), true); + assert.equal(stepTable.refs.stepsTbody.children[1].classList.contains('is-step-entering'), false); + + // Bubbled animationend from a child must NOT cut off the highlight fade prematurely + const enteringRow = stepTable.refs.stepsTbody.children[0]; + enteringRow.onanimationend?.({ target: enteringRow.children[0] }); + assert.equal( + enteringRow.classList.contains('is-step-entering'), + true, + 'Child td animationend must not prematurely strip is-step-entering from tr' + ); + + // Clear animationend on row 0 itself, then streaming update to step #4 arrives -> must NOT re-trigger fade-in + enteringRow.onanimationend?.({ target: enteringRow }); + assert.equal(enteringRow.classList.contains('is-step-entering'), false); + const s4Updated = { ...s4New, outputTokens: 520 }; + stepTable.refs.renderStepTable([s4Updated, s3Classic, s2Main, s2Sub, s1], 'conv-a', cols, 'zh-CN', { + allConversationSteps: [s4Updated, s3Classic, s2Main, s2Sub, s1], + allowNewRowFade: true, + }); + assert.equal( + stepTable.refs.stepsTbody.children[0].classList.contains('is-step-entering'), + false, + 'In-place streaming update of an already seen step must not re-animate' + ); + + // Switching to another conversation ('conv-b') -> 0 entering rows + const otherConvStep = { stepIndex: 99, agentCascadeId: 'conv-b', modelShort: '4-carbon', inputTokens: 50 }; + stepTable.refs.renderStepTable([otherConvStep], 'conv-b', cols, 'zh-CN', { + allConversationSteps: [otherConvStep], + allowNewRowFade: true, + }); + assert.equal( + stepTable.refs.stepsTbody.children.some((tr) => tr.classList.contains('is-step-entering')), + false, + 'Switching conversation must not trigger row fade-in' + ); + stepTable.destroy(); + + // 10. TrendAreaChart tooltip arms 0.15s .is-tracking transition after initial snap and translates --tip-y smoothly + const trendChart = createTrendAreaChart(); + Object.assign(trendChart.el, { offsetHeight: 210 }); + const tipEl = trendChart.el.querySelector('.trend-tooltip'); + Object.assign(tipEl, { offsetHeight: 82 }); + trendChart.update([ + { index: 0, label: '00:00', fullLabel: '11月19日 00:00 - 01:00', tokens: 1000, calls: 2, costUsd: 0.1 }, + { index: 1, label: '10:00', fullLabel: '11月19日 10:00 - 11:00', tokens: 25_000_000, calls: 80, costUsd: 6.37 }, + ]); + const ticks = trendChart.el.querySelectorAll('.trend-x-tick'); + queuedRaf = null; + ticks[0].onclick(); // low valley -> --tip-y = 0px, initial snap has is-tracking = false + assert.equal(tipEl.style.getPropertyValue('--tip-y'), '0px'); + assert.equal(tipEl.classList.contains('is-tracking'), false); + queuedRaf?.(); + assert.equal(tipEl.classList.contains('is-tracking'), true); + + ticks[1].onclick(); // high peak -> --tip-y = 210 - 82 - 22 = 106px while is-tracking remains true + assert.equal(tipEl.style.getPropertyValue('--tip-y'), '106px'); + assert.equal(tipEl.classList.contains('is-tracking'), true); + trendChart.destroy(); + + // 11. ContextWindowWidget + LiveActivityWidget use pure SVG chevrons and animate expand/collapse under [data-modern-ui="true"] + document.documentElement.setAttribute('data-modern-ui', 'true'); + const ctxWidget = ContextWindowWidget({}); + document.body.appendChild(ctxWidget.el); + const subAgents = Array.from({ length: 8 }, (_, idx) => ({ + agentId: `sub-${idx + 1}`, + cascadeId: `sub-${idx + 1}`, + index: idx + 1, + agentKind: 'swarm_worker', + agentOrdinal: idx + 1, + isMain: false, + stepCount: 5, + context: { usedPct: 15 + idx }, + })); + ctxWidget.refs.update({ + data: { + settings: { language: 'zh-CN' }, + activeConversation: { + cascadeId: 'conv-ctx-anim', + hasSubagents: true, + agents: [ + { agentId: 'main', cascadeId: 'conv-ctx-anim', isMain: true, stepCount: 10, context: { usedPct: 40 } }, + ...subAgents, + ], + aggregated: { activeAgentId: 'main', activeAgentKind: 'main' }, + }, + }, + }); + + const moreBtn = ctxWidget.el.querySelector('.ctx-agent-pill.is-more-toggle'); + assert.ok(moreBtn, 'Overflowing agent pills render .is-more-toggle pill'); + assert.doesNotMatch(moreBtn.textContent, /[▾▴▸]/, 'Zero Unicode arrow characters in toggle text'); + assert.equal(moreBtn.querySelector('.ctx-toggle-chevron')?.hasAttribute('hidden'), false); + assert.equal(moreBtn.classList.contains('is-expanded'), false); + + const inspectorBar = ctxWidget.el.querySelector('.ctx-inspector-bar'); + const pillGroup = ctxWidget.el.querySelector('.ctx-pill-group'); + Object.assign(inspectorBar, { offsetHeight: 22 }); + Object.assign(pillGroup, { offsetHeight: 74 }); + + moreBtn.onclick(); // Expand + assert.equal(inspectorBar.style.height, '74px'); + const collapseBtn = ctxWidget.el.querySelector('.ctx-agent-pill.is-more-toggle'); + assert.equal(collapseBtn.textContent, '收起'); + assert.equal(collapseBtn.classList.contains('is-expanded'), true); + inspectorBar.ontransitionend?.({ target: inspectorBar }); + assert.equal(inspectorBar.style.height, ''); + + // Collapse back smoothly + Object.assign(inspectorBar, { offsetHeight: 74 }); + Object.assign(pillGroup.children[0], { offsetHeight: 22, offsetTop: 0 }); + collapseBtn.onclick(); + assert.equal(collapseBtn.classList.contains('is-expanded'), false); + assert.equal(inspectorBar.style.height, '22px'); + inspectorBar.ontransitionend?.({ target: inspectorBar }); + assert.equal(inspectorBar.style.height, ''); + ctxWidget.destroy(); + + // LiveActivityWidget SVG chevron + smooth collapse/expand under [data-modern-ui="true"] + const animLive = LiveActivityWidget({ defaultExpandRunningSubs: true }); + document.body.appendChild(animLive.el); + animLive.refs.update({ + items: [ + { + cascadeId: 'conv-live-anim', + title: 'Swarm Session', + isMainRunning: true, + subagentCount: 2, + swarmCount: 2, + runningSubagentCount: 0, + subagents: [ + { cascadeId: 'sw-1', index: 1, agentKind: 'swarm_worker', role: '@w1', isRunning: false, stepCount: 4 }, + { cascadeId: 'sw-2', index: 2, agentKind: 'swarm_worker', role: '@w2', isRunning: false, stepCount: 6 }, + ], + }, + ], + }); + const liveToggleBtn = animLive.el.querySelector('.live-sub-toggle'); + const liveScrollHost = animLive.el.querySelector('.live-sub-scroll-host'); + assert.equal(liveToggleBtn.textContent, '蜂群 (2)'); + assert.ok(liveToggleBtn.querySelector('.live-sub-toggle-chevron')); + assert.equal(liveToggleBtn.classList.contains('is-expanded'), false); + + Object.assign(liveScrollHost, { offsetHeight: 64, scrollHeight: 64 }); + liveToggleBtn.onclick({ stopPropagation() {} }); // Expand + assert.equal(liveToggleBtn.classList.contains('is-expanded'), true); + assert.equal(liveScrollHost.hasAttribute('hidden'), false); + assert.equal(liveScrollHost.classList.contains('is-sub-animating'), true); + assert.equal(liveScrollHost.style.height, '64px'); + // Opacity finishes earlier than height -> must NOT cut off height transition early + liveScrollHost.ontransitionend?.({ target: liveScrollHost, propertyName: 'opacity' }); + assert.equal(liveScrollHost.style.height, '64px'); + assert.equal(liveScrollHost.classList.contains('is-sub-animating'), true); + liveScrollHost.ontransitionend?.({ target: liveScrollHost, propertyName: 'height' }); + assert.equal(liveScrollHost.style.height, ''); + assert.equal(liveScrollHost.classList.contains('is-sub-animating'), false); + + liveToggleBtn.onclick({ stopPropagation() {} }); // Collapse + assert.equal(liveToggleBtn.classList.contains('is-expanded'), false); + assert.equal(liveScrollHost.style.height, '0px'); + assert.equal(liveScrollHost.classList.contains('is-sub-animating'), true); + liveScrollHost.ontransitionend?.({ target: liveScrollHost, propertyName: 'opacity' }); + assert.equal(liveScrollHost.hasAttribute('hidden'), false); + liveScrollHost.ontransitionend?.({ target: liveScrollHost, propertyName: 'height' }); + assert.equal(liveScrollHost.hasAttribute('hidden'), true); + assert.equal(liveScrollHost.classList.contains('is-sub-animating'), false); + animLive.destroy(); + document.documentElement.removeAttribute('data-modern-ui'); +}); diff --git a/sidecars/panel/test/quota-pools.test.mjs b/sidecars/panel/test/quota-pools.test.mjs index 397536c..ea372dc 100644 --- a/sidecars/panel/test/quota-pools.test.mjs +++ b/sidecars/panel/test/quota-pools.test.mjs @@ -649,4 +649,17 @@ test('per-pool cycle5h and cycleWeekly isolate each pool by its own reset window p.quotas.weekly.costUsd, +(geminiPool.cycleWeekly.costUsd + argonPool.cycleWeekly.costUsd + claudePool.cycleWeekly.costUsd).toFixed(2) ); + + // Consumption preset 'cycle' and selected range 'cycle' match quotas.weekly across heterogeneous pool reset windows + assert.equal(p.consumption.presets.cycle.account.calls, 5); + assert.equal(p.consumption.presets.cycle.account.totalTokens, 155_000); + + const pCycle = await h.buildTelemetryPayloadInternal('multiCycleConv', false, { range: 'cycle' }); + assert.equal(pCycle.consumption.selectedRange.key, 'cycle'); + assert.equal(pCycle.consumption.account.calls, 5); + assert.equal(pCycle.consumption.account.totalTokens, 155_000); + const cycleModelsTok = pCycle.modelBreakdown.reduce((sum, m) => sum + m.totalTokens, 0); + assert.equal(cycleModelsTok, 155_000); + const cycleSourcesTok = pCycle.consumption.sourcesBreakdown.reduce((sum, s) => sum + s.totalTokens, 0); + assert.equal(cycleSourcesTok, 155_000); }); diff --git a/sidecars/panel/test/swarm-mode.test.mjs b/sidecars/panel/test/swarm-mode.test.mjs index 85c519e..9620ae1 100644 --- a/sidecars/panel/test/swarm-mode.test.mjs +++ b/sidecars/panel/test/swarm-mode.test.mjs @@ -1152,7 +1152,11 @@ test('Frontend Swarm formatters, bilingual i18n, LiveActivityWidget priority sor liveWidget.refs.pauseTicker(); const toggleBtn = liveWidget.el.querySelector('.live-sub-toggle'); - assert.equal(toggleBtn?.textContent, '蜂群 1/4 ▾'); + assert.equal(toggleBtn?.textContent, '蜂群 1/4'); + assert.ok( + toggleBtn?.querySelector('.live-sub-toggle-chevron'), + 'Swarm toggle button renders pure vector SVG chevron icon' + ); const hereTag = liveWidget.el.querySelector('.wm-session-tag.is-here'); assert.ok(hereTag && !hereTag.hasAttribute('hidden'), 'Child worker host route must light up is-here tag'); diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index 1ee6537..b4fe942 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -1370,11 +1370,29 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.equal(structurePane.hasAttribute('hidden'), true); assert.equal(otherPane.hasAttribute('hidden'), true); - // --- Tab 0: 常规 (languageSwitch, themeAccent, fontScaleSwitch, pluginUpdateMode) --- + // --- Tab 0: 常规 (languageSwitch, themeAccent, fontScaleSwitch, modernUiSwitch, pluginUpdateMode) --- const generalSegControls = generalPane.querySelectorAll('.segmented'); - assert.equal(generalSegControls.length, 2, 'General tab has Language and FontScale segmented controls'); + assert.equal( + generalSegControls.length, + 3, + 'General tab has Language, FontScale, and Experimental Modern UI segmented controls' + ); const langBtns = generalSegControls[0].querySelectorAll('.seg-btn'); const fontScaleBtns = generalSegControls[1].querySelectorAll('.seg-btn'); + const modernUiBtns = generalSegControls[2].querySelectorAll('.seg-btn'); + assert.equal(modernUiBtns.length, 2, 'Experimental Modern UI switch has 关闭 / 开启'); + + modernUiBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 30)); + assert.equal(mockSettings.experimentalModernUi, true); + assert.equal(portalHost.getAttribute('data-modern-ui'), 'true'); + assert.equal(capsuleHost.getAttribute('data-modern-ui'), 'true'); + assert.equal(popoverEl.getAttribute('data-modern-ui'), 'true'); + modernUiBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 30)); + assert.equal(mockSettings.experimentalModernUi, false); + assert.equal(portalHost.hasAttribute('data-modern-ui'), false); + assert.equal(popoverEl.hasAttribute('data-modern-ui'), false); assert.equal(langBtns.length, 3, 'Language switch has 简体中文 / English / 跟随宿主'); assert.equal(langBtns[0].textContent, '简体中文'); assert.equal(langBtns[0].classList.contains('is-active'), true, 'Default language is zh-CN'); @@ -2053,10 +2071,13 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro 'Heatmap palette uses unified project blue tokens instead of hardcoded green' ); - // Click '全部' (option index 5 in ConsumptionView timeFilterSwitch) to load 120-day series + // Click '全部' ('all' in ConsumptionView timeFilterSwitch) to load 120-day series const consPane = allPanes[1]; const consTimeSegBtns = consPane.querySelectorAll('.seg-btn'); - consTimeSegBtns[5].dispatchEvent({ type: 'click', stopPropagation() {} }); + const allRangeBtn = + consTimeSegBtns.find((btn) => btn.getAttribute('data-seg-value') === 'all') || + consTimeSegBtns[6]; + allRangeBtn.dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 35)); assert.equal(plotStageEl.hasAttribute('hidden'), true, 'Line chart hidden when trend exceeds 90 days'); From 809bf0413b9a1ef8a5936f1b6e57696229e3b282 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Thu, 19 Nov 2026 15:18:42 +0900 Subject: [PATCH 06/14] fix(panel): prevent stale telemetry polls from reverting saved settings and avoid blocking forced reload --- sidecars/panel/app.js | 249 +++++++++++++++--- sidecars/panel/backend/api-actions.mjs | 4 + sidecars/panel/backend/telemetry-builder.mjs | 2 +- sidecars/panel/index.html | 4 +- sidecars/panel/src/store/telemetryStore.js | 210 +++++++++++++-- .../src/views/settings/SettingsGeneralTab.js | 40 ++- sidecars/panel/test/modern-ui.test.mjs | 138 +++++++++- 7 files changed, 577 insertions(+), 70 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 583283a..a19ad1f 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -4374,6 +4374,65 @@ let lastReceivedSteps = null; let loopActive = false; let loopIntervalMs = 2000; let loopTickFn = null; +let settingsRevision = 0; +let settingsWriteChain = Promise.resolve(); +const pendingSettingsMutations = new Map(); +const recentCommittedSettings = new Map(); + +const TELEMETRY_RECOMPUTE_SETTING_KEYS = new Set([ + 'weeklyLimitMode', + 'weeklyTokenBudget', + 'weeklyCostBudget', + 'windowMountMode', + 'enableWindowOverlay', +]); + +function enqueueSettingsWrite(task) { + const run = settingsWriteChain.then(task, task); + settingsWriteChain = run.catch(() => {}); + return run; +} + +function extractReturnedSettings(res) { + if (!res || typeof res !== 'object') return null; + if (res.settings && typeof res.settings === 'object' && !Array.isArray(res.settings)) { + return res.settings; + } + if ( + typeof res.language === 'string' || + typeof res.themeAccent === 'string' || + typeof res.windowMountMode === 'string' + ) { + return res; + } + return null; +} + +function reconcileIncomingTelemetrySettings(payload, reqSettingsRev) { + if (!payload?.settings || typeof payload.settings !== 'object') { + return payload; + } + for (const [k, entry] of [...recentCommittedSettings.entries()]) { + if (reqSettingsRev >= entry.rev) { + recentCommittedSettings.delete(k); + } + } + if (pendingSettingsMutations.size === 0 && recentCommittedSettings.size === 0) { + return payload; + } + let merged = null; + for (const [k, entry] of recentCommittedSettings.entries()) { + if (reqSettingsRev < entry.rev) { + merged ??= { ...payload.settings }; + merged[k] = entry.value; + } + } + for (const [k, entry] of pendingSettingsMutations.entries()) { + merged ??= { ...payload.settings }; + merged[k] = entry.value; + } + return merged ? { ...payload, settings: merged } : payload; +} const CLIENT_TOPBAR_SLOT_KEYS = TOPBAR_SLOT_KEYS; const DEFAULT_CLIENT_TOPBAR_SLOTS = DEFAULT_TOPBAR_SLOTS; @@ -5019,6 +5078,7 @@ function readDisplaySteps(payload) { async function requestTelemetry(params, force) { const reqSeq = ++latestRequestSeq; + const reqSettingsRev = settingsRevision; const startMs = Date.now(); if (force) { @@ -5069,6 +5129,7 @@ async function requestTelemetry(params, force) { } consecutivePollFailures = 0; + const resolvedPayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev); const latestSt = telemetryStore.getState(); if (force) { const elapsed = Date.now() - startMs; @@ -5076,11 +5137,12 @@ async function requestTelemetry(params, force) { await new Promise((r) => setTimeout(r, 220 - elapsed)); } if (reqSeq !== latestRequestSeq) { - return payload; + return resolvedPayload; } + const finalForcePayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev); if (feedbackTimer) clearTimeout(feedbackTimer); telemetryStore.setState({ - telemetry: payload, + telemetry: finalForcePayload, minuteTick: Math.floor(Date.now() / 30000), syncState: 'synced', }); @@ -5088,16 +5150,17 @@ async function requestTelemetry(params, force) { feedbackTimer = null; telemetryStore.setState({ syncState: 'idle' }); }, 1100); + return finalForcePayload; } else { - const isSame = isEquivalentTelemetry(latestSt.telemetry, payload); - const nextTelemetry = isSame ? latestSt.telemetry : payload; + const isSame = isEquivalentTelemetry(latestSt.telemetry, resolvedPayload); + const nextTelemetry = isSame ? latestSt.telemetry : resolvedPayload; telemetryStore.setState({ telemetry: nextTelemetry, minuteTick: Math.floor(Date.now() / 30000), syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle', }); + return resolvedPayload; } - return payload; } catch (err) { if (err?.name === 'AbortError' || reqSeq !== latestRequestSeq) return null; consecutivePollFailures += 1; @@ -5206,31 +5269,111 @@ async function saveSettingsPatch(patch) { safePatch.enableWindowOverlay = Boolean(safePatch.enableWindowOverlay); safePatch.windowMountMode = safePatch.enableWindowOverlay ? 'dual' : 'sidebar'; } + const myRev = ++settingsRevision; const prevTelemetry = telemetryStore.getState().telemetry; - if (prevTelemetry?.settings) { - telemetryStore.setState({ - telemetry: { - ...prevTelemetry, - settings: { ...prevTelemetry.settings, ...safePatch }, - }, - }); + const patchKeys = Object.keys(safePatch); + const prevKeyValues = new Map(); + for (const key of patchKeys) { + prevKeyValues.set(key, prevTelemetry?.settings?.[key]); + pendingSettingsMutations.set(key, { rev: myRev, value: safePatch[key] }); } + let optimisticTelemetry = null; + if (prevTelemetry?.settings) { + optimisticTelemetry = { + ...prevTelemetry, + settings: { ...prevTelemetry.settings, ...safePatch }, + }; + telemetryStore.setState({ telemetry: optimisticTelemetry }); + } + let res = null; try { - await callSidecarApi('/api/settings', { method: 'POST', body: safePatch }); + res = await enqueueSettingsWrite(() => + callSidecarApi('/api/settings', { method: 'POST', body: safePatch }) + ); } catch (err) { - if (prevTelemetry) { - telemetryStore.setState({ telemetry: prevTelemetry }); + const rollbackKeys = []; + for (const key of patchKeys) { + const activeEntry = pendingSettingsMutations.get(key); + if (activeEntry?.rev === myRev) { + pendingSettingsMutations.delete(key); + rollbackKeys.push(key); + } + } + if (rollbackKeys.length > 0) { + const curTelemetry = telemetryStore.getState().telemetry; + if (prevTelemetry && optimisticTelemetry && curTelemetry === optimisticTelemetry) { + telemetryStore.setState({ telemetry: prevTelemetry }); + } else if (curTelemetry?.settings) { + const rolledBackSettings = { ...curTelemetry.settings }; + for (const key of rollbackKeys) { + if (recentCommittedSettings.has(key)) { + rolledBackSettings[key] = recentCommittedSettings.get(key).value; + } else { + rolledBackSettings[key] = prevKeyValues.get(key); + } + } + telemetryStore.setState({ + telemetry: { ...curTelemetry, settings: rolledBackSettings }, + }); + } } throw err; } - await fetchTelemetry({ force: true }); + + const serverSettings = extractReturnedSettings(res); + const committedRev = ++settingsRevision; + for (const key of patchKeys) { + const activeEntry = pendingSettingsMutations.get(key); + const committedVal = + serverSettings && Object.prototype.hasOwnProperty.call(serverSettings, key) + ? serverSettings[key] + : safePatch[key]; + if (activeEntry?.rev === myRev) { + pendingSettingsMutations.delete(key); + recentCommittedSettings.set(key, { rev: committedRev, value: committedVal }); + } + } + + const curTelemetry = telemetryStore.getState().telemetry; + if (curTelemetry?.settings) { + const nextSettings = serverSettings + ? { ...curTelemetry.settings, ...serverSettings } + : { ...curTelemetry.settings }; + for (const [k, entry] of recentCommittedSettings.entries()) { + if (entry.rev > committedRev) { + nextSettings[k] = entry.value; + } + } + for (const [k, entry] of pendingSettingsMutations.entries()) { + nextSettings[k] = entry.value; + } + telemetryStore.setState({ + telemetry: { ...curTelemetry, settings: nextSettings }, + }); + } + + const needsTelemetryRecompute = patchKeys.some((k) => TELEMETRY_RECOMPUTE_SETTING_KEYS.has(k)); + if (needsTelemetryRecompute) { + inFlightTelemetryPoll = null; + void fetchTelemetry({ force: false }); + } } async function saveModelContextWindow(modelId, option) { - const result = await callSidecarApi('/api/context-window', { - method: 'POST', - body: { modelId, option }, - }); + const myRev = ++settingsRevision; + const result = await enqueueSettingsWrite(() => + callSidecarApi('/api/context-window', { + method: 'POST', + body: { modelId, option }, + }) + ); + const committedRev = ++settingsRevision; + if (result?.modelContextWindows) { + recentCommittedSettings.set('modelContextWindows', { + rev: Math.max(myRev, committedRev), + value: result.modelContextWindows, + }); + } const telemetry = telemetryStore.getState().telemetry; if (telemetry?.settings) { telemetryStore.setState({ @@ -5244,17 +5387,36 @@ async function saveModelContextWindow(modelId, option) { } async function resetAllSettings() { - const res = await callSidecarApi('/api/settings/reset', { method: 'POST', body: {} }); + const myRev = ++settingsRevision; + const res = await enqueueSettingsWrite(() => + callSidecarApi('/api/settings/reset', { method: 'POST', body: {} }) + ); + const committedRev = ++settingsRevision; + const serverSettings = extractReturnedSettings(res); + if (serverSettings) { + for (const [key, val] of Object.entries(serverSettings)) { + const pending = pendingSettingsMutations.get(key); + if (!pending || pending.rev <= myRev) { + pendingSettingsMutations.delete(key); + recentCommittedSettings.set(key, { rev: committedRev, value: val }); + } + } + } const prevTelemetry = telemetryStore.getState().telemetry; - if (res?.settings && prevTelemetry) { + if (serverSettings && prevTelemetry) { + const mergedSettings = { ...serverSettings }; + for (const [k, entry] of pendingSettingsMutations.entries()) { + mergedSettings[k] = entry.value; + } telemetryStore.setState({ telemetry: { ...prevTelemetry, - settings: { ...res.settings }, + settings: mergedSettings, }, }); } - await fetchTelemetry({ force: true }); + inFlightTelemetryPoll = null; + void fetchTelemetry({ force: false }); return res; } @@ -15958,6 +16120,7 @@ const SettingsGeneralTab = defineComponent({ let latestSettings = null; let latestCloudStatus = null; let appearanceTimer = null; + let appearanceSaveSeq = 0; let cloudTimer = null; const appearanceStatusText = h('span', { @@ -16029,13 +16192,18 @@ const SettingsGeneralTab = defineComponent({ draftLanguage = nextLang; setI18nLanguage(nextLang); languageSwitch.setValue(nextLang); + const saveToken = ++appearanceSaveSeq; showAppearanceFeedback(t('settings.saving'), 0); try { await saveSettingsPatch({ language: nextLang }); - showAppearanceFeedback(t('settings.saved'), 1500); + if (saveToken === appearanceSaveSeq) { + showAppearanceFeedback(t('settings.saved'), 1500); + } } catch { if (latestSettings) renderSettings(latestSettings); - showAppearanceFeedback(t('settings.saveFailed'), 2500); + if (saveToken === appearanceSaveSeq) { + showAppearanceFeedback(t('settings.saveFailed'), 2500); + } } }, }); @@ -16046,13 +16214,18 @@ const SettingsGeneralTab = defineComponent({ const nextAccent = normalizeClientThemeAccent(val); draftThemeAccent = nextAccent; themeColorPicker.refs.setValue(nextAccent); + const saveToken = ++appearanceSaveSeq; showAppearanceFeedback(t('settings.saving'), 0); try { await saveSettingsPatch({ themeAccent: nextAccent }); - showAppearanceFeedback(t('settings.saved'), 1500); + if (saveToken === appearanceSaveSeq) { + showAppearanceFeedback(t('settings.saved'), 1500); + } } catch { if (latestSettings) renderSettings(latestSettings); - showAppearanceFeedback(t('settings.saveFailed'), 2500); + if (saveToken === appearanceSaveSeq) { + showAppearanceFeedback(t('settings.saveFailed'), 2500); + } } }, }); @@ -16065,14 +16238,19 @@ const SettingsGeneralTab = defineComponent({ const nextScale = normalizeClientFontScale(val); draftFontScale = nextScale; fontScaleSwitch.setValue(nextScale); + const saveToken = ++appearanceSaveSeq; showAppearanceFeedback(t('settings.saving'), 0); try { await saveSettingsPatch({ fontScale: nextScale }); - showAppearanceFeedback(t('settings.saved'), 1500); + if (saveToken === appearanceSaveSeq) { + showAppearanceFeedback(t('settings.saved'), 1500); + } props.onLayoutChange?.(); } catch { if (latestSettings) renderSettings(latestSettings); - showAppearanceFeedback(t('settings.saveFailed'), 2500); + if (saveToken === appearanceSaveSeq) { + showAppearanceFeedback(t('settings.saveFailed'), 2500); + } } }, }); @@ -16085,7 +16263,7 @@ const SettingsGeneralTab = defineComponent({ const nextModernUi = val === 'on'; draftModernUi = nextModernUi; modernUiSwitch.setValue(nextModernUi ? 'on' : 'off'); - if (typeof document !== 'undefined' && document.documentElement) { + if (!isWindowOverlayMode() && typeof document !== 'undefined' && document.documentElement) { applyAppearanceToRoot( document.documentElement, { @@ -16097,14 +16275,19 @@ const SettingsGeneralTab = defineComponent({ { includeFontScale: true } ); } + const saveToken = ++appearanceSaveSeq; showAppearanceFeedback(t('settings.saving'), 0); try { await saveSettingsPatch({ experimentalModernUi: nextModernUi }); - showAppearanceFeedback(t('settings.saved'), 1500); + if (saveToken === appearanceSaveSeq) { + showAppearanceFeedback(t('settings.saved'), 1500); + } props.onLayoutChange?.(); } catch { if (latestSettings) renderSettings(latestSettings); - showAppearanceFeedback(t('settings.saveFailed'), 2500); + if (saveToken === appearanceSaveSeq) { + showAppearanceFeedback(t('settings.saveFailed'), 2500); + } } }, }); diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index 84131d9..d958c3e 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -18,6 +18,7 @@ import { cloudSyncState, computeRuntimeCodeVersion, createDefaultSettingsObject, + inFlightRequests, isPlainObject, loadSettings, lsRuntimeEndpoint, @@ -294,6 +295,7 @@ export function executeSettingsAction(data) { body: JSON.stringify({ ok: false, error: 'Failed to persist settings' }), }; } + inFlightRequests.clear(); const prevMountMode = normalizeWindowMountMode( current.windowMountMode, current.enableWindowOverlay @@ -361,6 +363,7 @@ export async function executeModelContextWindowAction(data) { if (!saveJson(SETTINGS_FILE, current)) { return respond(500, { error: 'Failed to persist model context window' }); } + inFlightRequests.clear(); void notifyModelContextWindowsChanged(); return respond(200, { modelContextWindows: current.modelContextWindows }); } @@ -377,6 +380,7 @@ export function executeResetSettingsAction() { body: JSON.stringify({ ok: false, error: 'Failed to reset settings' }), }; } + inFlightRequests.clear(); const prevMountMode = normalizeWindowMountMode( current.windowMountMode, current.enableWindowOverlay diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index 0d6c5b3..296e4a0 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -1718,7 +1718,7 @@ export async function buildTelemetryPayloadInternal( hostPlatform: process.platform || 'unknown', uiBundleVersion, windowBridge: getDefaultWindowBridgeStatus(), - settings, + settings: loadSettings(), contextWindowModels: getContextWindowGroups(getContextWindowModels(clientConfigs, contextModelCatalog)).map((group) => { const latest = group.members.reduce((previous, id) => { const reported = reportedContextLimits.get(id); diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 0366f87..af4f3ae 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index e984548..c7a95da 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -148,6 +148,65 @@ let lastReceivedSteps = null; let loopActive = false; let loopIntervalMs = 2000; let loopTickFn = null; +let settingsRevision = 0; +let settingsWriteChain = Promise.resolve(); +const pendingSettingsMutations = new Map(); +const recentCommittedSettings = new Map(); + +const TELEMETRY_RECOMPUTE_SETTING_KEYS = new Set([ + 'weeklyLimitMode', + 'weeklyTokenBudget', + 'weeklyCostBudget', + 'windowMountMode', + 'enableWindowOverlay', +]); + +function enqueueSettingsWrite(task) { + const run = settingsWriteChain.then(task, task); + settingsWriteChain = run.catch(() => {}); + return run; +} + +function extractReturnedSettings(res) { + if (!res || typeof res !== 'object') return null; + if (res.settings && typeof res.settings === 'object' && !Array.isArray(res.settings)) { + return res.settings; + } + if ( + typeof res.language === 'string' || + typeof res.themeAccent === 'string' || + typeof res.windowMountMode === 'string' + ) { + return res; + } + return null; +} + +function reconcileIncomingTelemetrySettings(payload, reqSettingsRev) { + if (!payload?.settings || typeof payload.settings !== 'object') { + return payload; + } + for (const [k, entry] of [...recentCommittedSettings.entries()]) { + if (reqSettingsRev >= entry.rev) { + recentCommittedSettings.delete(k); + } + } + if (pendingSettingsMutations.size === 0 && recentCommittedSettings.size === 0) { + return payload; + } + let merged = null; + for (const [k, entry] of recentCommittedSettings.entries()) { + if (reqSettingsRev < entry.rev) { + merged ??= { ...payload.settings }; + merged[k] = entry.value; + } + } + for (const [k, entry] of pendingSettingsMutations.entries()) { + merged ??= { ...payload.settings }; + merged[k] = entry.value; + } + return merged ? { ...payload, settings: merged } : payload; +} export const CLIENT_TOPBAR_SLOT_KEYS = TOPBAR_SLOT_KEYS; export const DEFAULT_CLIENT_TOPBAR_SLOTS = DEFAULT_TOPBAR_SLOTS; @@ -793,6 +852,7 @@ function readDisplaySteps(payload) { async function requestTelemetry(params, force) { const reqSeq = ++latestRequestSeq; + const reqSettingsRev = settingsRevision; const startMs = Date.now(); if (force) { @@ -843,6 +903,7 @@ async function requestTelemetry(params, force) { } consecutivePollFailures = 0; + const resolvedPayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev); const latestSt = telemetryStore.getState(); if (force) { const elapsed = Date.now() - startMs; @@ -850,11 +911,12 @@ async function requestTelemetry(params, force) { await new Promise((r) => setTimeout(r, 220 - elapsed)); } if (reqSeq !== latestRequestSeq) { - return payload; + return resolvedPayload; } + const finalForcePayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev); if (feedbackTimer) clearTimeout(feedbackTimer); telemetryStore.setState({ - telemetry: payload, + telemetry: finalForcePayload, minuteTick: Math.floor(Date.now() / 30000), syncState: 'synced', }); @@ -862,16 +924,17 @@ async function requestTelemetry(params, force) { feedbackTimer = null; telemetryStore.setState({ syncState: 'idle' }); }, 1100); + return finalForcePayload; } else { - const isSame = isEquivalentTelemetry(latestSt.telemetry, payload); - const nextTelemetry = isSame ? latestSt.telemetry : payload; + const isSame = isEquivalentTelemetry(latestSt.telemetry, resolvedPayload); + const nextTelemetry = isSame ? latestSt.telemetry : resolvedPayload; telemetryStore.setState({ telemetry: nextTelemetry, minuteTick: Math.floor(Date.now() / 30000), syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle', }); + return resolvedPayload; } - return payload; } catch (err) { if (err?.name === 'AbortError' || reqSeq !== latestRequestSeq) return null; consecutivePollFailures += 1; @@ -980,31 +1043,111 @@ export async function saveSettingsPatch(patch) { safePatch.enableWindowOverlay = Boolean(safePatch.enableWindowOverlay); safePatch.windowMountMode = safePatch.enableWindowOverlay ? 'dual' : 'sidebar'; } + const myRev = ++settingsRevision; const prevTelemetry = telemetryStore.getState().telemetry; - if (prevTelemetry?.settings) { - telemetryStore.setState({ - telemetry: { - ...prevTelemetry, - settings: { ...prevTelemetry.settings, ...safePatch }, - }, - }); + const patchKeys = Object.keys(safePatch); + const prevKeyValues = new Map(); + for (const key of patchKeys) { + prevKeyValues.set(key, prevTelemetry?.settings?.[key]); + pendingSettingsMutations.set(key, { rev: myRev, value: safePatch[key] }); } + let optimisticTelemetry = null; + if (prevTelemetry?.settings) { + optimisticTelemetry = { + ...prevTelemetry, + settings: { ...prevTelemetry.settings, ...safePatch }, + }; + telemetryStore.setState({ telemetry: optimisticTelemetry }); + } + let res = null; try { - await callSidecarApi('/api/settings', { method: 'POST', body: safePatch }); + res = await enqueueSettingsWrite(() => + callSidecarApi('/api/settings', { method: 'POST', body: safePatch }) + ); } catch (err) { - if (prevTelemetry) { - telemetryStore.setState({ telemetry: prevTelemetry }); + const rollbackKeys = []; + for (const key of patchKeys) { + const activeEntry = pendingSettingsMutations.get(key); + if (activeEntry?.rev === myRev) { + pendingSettingsMutations.delete(key); + rollbackKeys.push(key); + } + } + if (rollbackKeys.length > 0) { + const curTelemetry = telemetryStore.getState().telemetry; + if (prevTelemetry && optimisticTelemetry && curTelemetry === optimisticTelemetry) { + telemetryStore.setState({ telemetry: prevTelemetry }); + } else if (curTelemetry?.settings) { + const rolledBackSettings = { ...curTelemetry.settings }; + for (const key of rollbackKeys) { + if (recentCommittedSettings.has(key)) { + rolledBackSettings[key] = recentCommittedSettings.get(key).value; + } else { + rolledBackSettings[key] = prevKeyValues.get(key); + } + } + telemetryStore.setState({ + telemetry: { ...curTelemetry, settings: rolledBackSettings }, + }); + } } throw err; } - await fetchTelemetry({ force: true }); + + const serverSettings = extractReturnedSettings(res); + const committedRev = ++settingsRevision; + for (const key of patchKeys) { + const activeEntry = pendingSettingsMutations.get(key); + const committedVal = + serverSettings && Object.prototype.hasOwnProperty.call(serverSettings, key) + ? serverSettings[key] + : safePatch[key]; + if (activeEntry?.rev === myRev) { + pendingSettingsMutations.delete(key); + recentCommittedSettings.set(key, { rev: committedRev, value: committedVal }); + } + } + + const curTelemetry = telemetryStore.getState().telemetry; + if (curTelemetry?.settings) { + const nextSettings = serverSettings + ? { ...curTelemetry.settings, ...serverSettings } + : { ...curTelemetry.settings }; + for (const [k, entry] of recentCommittedSettings.entries()) { + if (entry.rev > committedRev) { + nextSettings[k] = entry.value; + } + } + for (const [k, entry] of pendingSettingsMutations.entries()) { + nextSettings[k] = entry.value; + } + telemetryStore.setState({ + telemetry: { ...curTelemetry, settings: nextSettings }, + }); + } + + const needsTelemetryRecompute = patchKeys.some((k) => TELEMETRY_RECOMPUTE_SETTING_KEYS.has(k)); + if (needsTelemetryRecompute) { + inFlightTelemetryPoll = null; + void fetchTelemetry({ force: false }); + } } export async function saveModelContextWindow(modelId, option) { - const result = await callSidecarApi('/api/context-window', { - method: 'POST', - body: { modelId, option }, - }); + const myRev = ++settingsRevision; + const result = await enqueueSettingsWrite(() => + callSidecarApi('/api/context-window', { + method: 'POST', + body: { modelId, option }, + }) + ); + const committedRev = ++settingsRevision; + if (result?.modelContextWindows) { + recentCommittedSettings.set('modelContextWindows', { + rev: Math.max(myRev, committedRev), + value: result.modelContextWindows, + }); + } const telemetry = telemetryStore.getState().telemetry; if (telemetry?.settings) { telemetryStore.setState({ @@ -1018,17 +1161,36 @@ export async function saveModelContextWindow(modelId, option) { } export async function resetAllSettings() { - const res = await callSidecarApi('/api/settings/reset', { method: 'POST', body: {} }); + const myRev = ++settingsRevision; + const res = await enqueueSettingsWrite(() => + callSidecarApi('/api/settings/reset', { method: 'POST', body: {} }) + ); + const committedRev = ++settingsRevision; + const serverSettings = extractReturnedSettings(res); + if (serverSettings) { + for (const [key, val] of Object.entries(serverSettings)) { + const pending = pendingSettingsMutations.get(key); + if (!pending || pending.rev <= myRev) { + pendingSettingsMutations.delete(key); + recentCommittedSettings.set(key, { rev: committedRev, value: val }); + } + } + } const prevTelemetry = telemetryStore.getState().telemetry; - if (res?.settings && prevTelemetry) { + if (serverSettings && prevTelemetry) { + const mergedSettings = { ...serverSettings }; + for (const [k, entry] of pendingSettingsMutations.entries()) { + mergedSettings[k] = entry.value; + } telemetryStore.setState({ telemetry: { ...prevTelemetry, - settings: { ...res.settings }, + settings: mergedSettings, }, }); } - await fetchTelemetry({ force: true }); + inFlightTelemetryPoll = null; + void fetchTelemetry({ force: false }); return res; } diff --git a/sidecars/panel/src/views/settings/SettingsGeneralTab.js b/sidecars/panel/src/views/settings/SettingsGeneralTab.js index 817bcb9..2983f8c 100644 --- a/sidecars/panel/src/views/settings/SettingsGeneralTab.js +++ b/sidecars/panel/src/views/settings/SettingsGeneralTab.js @@ -12,6 +12,7 @@ import { normalizeClientThemeAccent, } from '../../core/appearance.js'; import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js'; +import { isWindowOverlayMode } from '../../core/httpClient.js'; import { createSvgIcon } from '../../icons/SvgIcon.js'; import { normalizeI18nLanguage, setI18nLanguage, t } from '../../i18n/index.js'; import { @@ -80,6 +81,7 @@ export const SettingsGeneralTab = defineComponent({ let latestSettings = null; let latestCloudStatus = null; let appearanceTimer = null; + let appearanceSaveSeq = 0; let cloudTimer = null; const appearanceStatusText = h('span', { @@ -151,13 +153,18 @@ export const SettingsGeneralTab = defineComponent({ draftLanguage = nextLang; setI18nLanguage(nextLang); languageSwitch.setValue(nextLang); + const saveToken = ++appearanceSaveSeq; showAppearanceFeedback(t('settings.saving'), 0); try { await saveSettingsPatch({ language: nextLang }); - showAppearanceFeedback(t('settings.saved'), 1500); + if (saveToken === appearanceSaveSeq) { + showAppearanceFeedback(t('settings.saved'), 1500); + } } catch { if (latestSettings) renderSettings(latestSettings); - showAppearanceFeedback(t('settings.saveFailed'), 2500); + if (saveToken === appearanceSaveSeq) { + showAppearanceFeedback(t('settings.saveFailed'), 2500); + } } }, }); @@ -168,13 +175,18 @@ export const SettingsGeneralTab = defineComponent({ const nextAccent = normalizeClientThemeAccent(val); draftThemeAccent = nextAccent; themeColorPicker.refs.setValue(nextAccent); + const saveToken = ++appearanceSaveSeq; showAppearanceFeedback(t('settings.saving'), 0); try { await saveSettingsPatch({ themeAccent: nextAccent }); - showAppearanceFeedback(t('settings.saved'), 1500); + if (saveToken === appearanceSaveSeq) { + showAppearanceFeedback(t('settings.saved'), 1500); + } } catch { if (latestSettings) renderSettings(latestSettings); - showAppearanceFeedback(t('settings.saveFailed'), 2500); + if (saveToken === appearanceSaveSeq) { + showAppearanceFeedback(t('settings.saveFailed'), 2500); + } } }, }); @@ -187,14 +199,19 @@ export const SettingsGeneralTab = defineComponent({ const nextScale = normalizeClientFontScale(val); draftFontScale = nextScale; fontScaleSwitch.setValue(nextScale); + const saveToken = ++appearanceSaveSeq; showAppearanceFeedback(t('settings.saving'), 0); try { await saveSettingsPatch({ fontScale: nextScale }); - showAppearanceFeedback(t('settings.saved'), 1500); + if (saveToken === appearanceSaveSeq) { + showAppearanceFeedback(t('settings.saved'), 1500); + } props.onLayoutChange?.(); } catch { if (latestSettings) renderSettings(latestSettings); - showAppearanceFeedback(t('settings.saveFailed'), 2500); + if (saveToken === appearanceSaveSeq) { + showAppearanceFeedback(t('settings.saveFailed'), 2500); + } } }, }); @@ -207,7 +224,7 @@ export const SettingsGeneralTab = defineComponent({ const nextModernUi = val === 'on'; draftModernUi = nextModernUi; modernUiSwitch.setValue(nextModernUi ? 'on' : 'off'); - if (typeof document !== 'undefined' && document.documentElement) { + if (!isWindowOverlayMode() && typeof document !== 'undefined' && document.documentElement) { applyAppearanceToRoot( document.documentElement, { @@ -219,14 +236,19 @@ export const SettingsGeneralTab = defineComponent({ { includeFontScale: true } ); } + const saveToken = ++appearanceSaveSeq; showAppearanceFeedback(t('settings.saving'), 0); try { await saveSettingsPatch({ experimentalModernUi: nextModernUi }); - showAppearanceFeedback(t('settings.saved'), 1500); + if (saveToken === appearanceSaveSeq) { + showAppearanceFeedback(t('settings.saved'), 1500); + } props.onLayoutChange?.(); } catch { if (latestSettings) renderSettings(latestSettings); - showAppearanceFeedback(t('settings.saveFailed'), 2500); + if (saveToken === appearanceSaveSeq) { + showAppearanceFeedback(t('settings.saveFailed'), 2500); + } } }, }); diff --git a/sidecars/panel/test/modern-ui.test.mjs b/sidecars/panel/test/modern-ui.test.mjs index 8e0357f..c517716 100644 --- a/sidecars/panel/test/modern-ui.test.mjs +++ b/sidecars/panel/test/modern-ui.test.mjs @@ -18,7 +18,13 @@ import { SegmentedControl } from '../src/components/ui/SegmentedControl.js'; import { ContextWindowWidget } from '../src/components/widgets/ContextWindowWidget.js'; import { LiveActivityWidget } from '../src/components/widgets/LiveActivityWidget.js'; import { StepTableWidget } from '../src/components/widgets/StepTableWidget.js'; -import { isEquivalentTelemetry, telemetryStore } from '../src/store/telemetryStore.js'; +import { + fetchTelemetry, + isEquivalentTelemetry, + saveSettingsPatch, + stopAsyncTelemetryLoop, + telemetryStore, +} from '../src/store/telemetryStore.js'; import { uiStore } from '../src/store/uiStore.js'; import { i18nStore, setI18nLanguage } from '../src/i18n/index.js'; import { ConsumptionView } from '../src/views/ConsumptionView.js'; @@ -625,3 +631,133 @@ test('SegmentedControl variable-width glider snaps cleanly on reveal and glides animLive.destroy(); document.documentElement.removeAttribute('data-modern-ui'); }); + +test('saveSettingsPatch prevents stale in-flight telemetry polls from snapping settings back and commits UI preferences without blocking on forced telemetry', async (t) => { + const prevDoc = globalThis.document; + const prevWin = globalThis.window; + const prevTelState = { ...telemetryStore.getState() }; + + const { document } = createMockDom(); + globalThis.document = document; + + const baseSettings = { + language: 'zh-CN', + themeAccent: 'host', + fontScale: 'md', + experimentalModernUi: false, + windowMountMode: 'dual', + enableWindowOverlay: true, + }; + const diskSettings = { ...baseSettings }; + telemetryStore.setState( + { telemetry: { settings: { ...baseSettings }, activeConversation: { stepCount: 1 } } }, + { sync: true } + ); + + let resolveStalePoll = null; + let resolveSlowPost = null; + let telemetryGetCalls = 0; + const postOrder = []; + + globalThis.window = { + location: { pathname: '/' }, + sidecar: { + fetch: async (url, opts = {}) => { + const method = String(opts.method || 'GET').toUpperCase(); + if (method === 'GET' && String(url).startsWith('/api/telemetry')) { + telemetryGetCalls += 1; + if (telemetryGetCalls === 1) { + // Simulate a slow poll that started BEFORE the user changed any setting + return new Promise((resolve) => { + resolveStalePoll = () => + resolve({ + ok: true, + status: 200, + json: async () => ({ + settings: { ...baseSettings }, + activeConversation: { stepCount: 2 }, + }), + }); + }); + } + return { + ok: true, + status: 200, + json: async () => ({ + settings: { ...diskSettings }, + activeConversation: { stepCount: 3 }, + }), + }; + } + if (method === 'POST' && url === '/api/settings') { + const body = JSON.parse(opts.body); + postOrder.push(body); + if (postOrder.length === 1) { + return new Promise((resolve) => { + resolveSlowPost = () => { + Object.assign(diskSettings, body); + resolve({ ok: true, status: 200, json: async () => ({ ...diskSettings }) }); + }; + }); + } + Object.assign(diskSettings, body); + return { ok: true, status: 200, json: async () => ({ ...diskSettings }) }; + } + return { ok: true, status: 200, json: async () => ({}) }; + }, + }, + addEventListener() {}, + removeEventListener() {}, + }; + + t.after(() => { + stopAsyncTelemetryLoop(); + telemetryStore.setState(prevTelState, { sync: true }); + globalThis.document = prevDoc; + globalThis.window = prevWin; + }); + + // 1. Start background telemetry poll (capturing stale settings: experimentalModernUi=false, fontScale='md') + const stalePollPromise = fetchTelemetry({ force: false }); + assert.equal(telemetryGetCalls, 1); + + // 2. While poll is in flight, user toggles experimentalModernUi -> true AND rapidly switches fontScale -> 'lg' + const save1 = saveSettingsPatch({ experimentalModernUi: true }); + const save2 = saveSettingsPatch({ fontScale: 'lg' }); + assert.equal(telemetryStore.getState().telemetry.settings.experimentalModernUi, true); + assert.equal(telemetryStore.getState().telemetry.settings.fontScale, 'lg'); + + // 3. Stale poll returns BEFORE POST finishes -> live stepCount updates to 2, yet settings NEVER snap back! + resolveStalePoll(); + await stalePollPromise; + assert.equal(telemetryStore.getState().telemetry.activeConversation.stepCount, 2); + assert.equal( + telemetryStore.getState().telemetry.settings.experimentalModernUi, + true, + 'Stale in-flight poll must not revert pending experimentalModernUi' + ); + assert.equal( + telemetryStore.getState().telemetry.settings.fontScale, + 'lg', + 'Stale in-flight poll must not revert pending fontScale' + ); + + // 4. First POST completes; second serialized POST executes right after -> both settle WITHOUT forcing extra telemetry GET + resolveSlowPost(); + await Promise.all([save1, save2]); + assert.deepEqual(postOrder, [{ experimentalModernUi: true }, { fontScale: 'lg' }]); + assert.equal( + telemetryGetCalls, + 1, + 'Pure UI setting patches must not block on an unnecessary forced /api/telemetry reload' + ); + assert.equal(telemetryStore.getState().telemetry.settings.experimentalModernUi, true); + assert.equal(telemetryStore.getState().telemetry.settings.fontScale, 'lg'); + + // 5. Subsequent fresh poll started after commit observes authoritative diskSettings and retires local overlay cleanly + await fetchTelemetry({ force: false }); + assert.equal(telemetryGetCalls, 2); + assert.equal(telemetryStore.getState().telemetry.activeConversation.stepCount, 3); + assert.equal(telemetryStore.getState().telemetry.settings.experimentalModernUi, true); + assert.equal(telemetryStore.getState().telemetry.settings.fontScale, 'lg'); +}); From 56844550f01070d22eda54536c8e0a2074605a32 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Thu, 19 Nov 2026 16:40:04 +0900 Subject: [PATCH 07/14] perf(panel): virtualize large step tables and optimize steps view switching and LOESS fit --- sidecars/panel/app.js | 1363 +++++++++++++++-- sidecars/panel/index.html | 4 +- sidecars/panel/src/App.js | 1 + .../components/charts/SessionStepCharts.js | 136 +- .../components/layout/WindowOverlayShell.js | 1 + .../src/components/ui/CustomScrollbar.js | 17 +- .../src/components/widgets/StepTableWidget.js | 1103 +++++++++++-- sidecars/panel/src/styles/modern-ui.css | 8 +- sidecars/panel/src/styles/views-tables.css | 37 +- sidecars/panel/src/views/StepsDetailView.js | 107 +- sidecars/panel/styles.css | 45 +- sidecars/panel/test/modern-ui.test.mjs | 227 +++ 12 files changed, 2719 insertions(+), 330 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index a19ad1f..c111c3e 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -6591,6 +6591,7 @@ const CustomScrollbar = defineComponent({ let isDragging = false; let dragStartY = 0; let dragStartScrollTop = 0; + let scrollRafId = 0; function syncThumb() { const scrollHeight = Number(contentEl.scrollHeight || 0); @@ -6617,7 +6618,15 @@ const CustomScrollbar = defineComponent({ } function onContentScroll() { - syncThumb(); + if (isDragging || typeof requestAnimationFrame !== 'function') { + syncThumb(); + return; + } + if (scrollRafId) return; + scrollRafId = requestAnimationFrame(() => { + scrollRafId = 0; + syncThumb(); + }); } function onDocMouseMove(e) { @@ -6672,7 +6681,7 @@ const CustomScrollbar = defineComponent({ syncThumb(); }); - contentEl.addEventListener('scroll', onContentScroll); + contentEl.addEventListener('scroll', onContentScroll, { passive: true }); hostEl.addEventListener('mouseenter', syncThumb); let resizeObserver = null; @@ -6686,6 +6695,10 @@ const CustomScrollbar = defineComponent({ onCleanup(() => { onDocMouseUp(); + if (scrollRafId && typeof cancelAnimationFrame === 'function') { + cancelAnimationFrame(scrollRafId); + scrollRafId = 0; + } contentEl.removeEventListener('scroll', onContentScroll); hostEl.removeEventListener('mouseenter', syncThumb); if (resizeObserver) { @@ -8500,7 +8513,7 @@ function computePublicationFit( if (sw <= 1e-12) { const fallbackVal = ols.intercept + ols.slope * x0; - return { rawFit: fallbackVal, leverageNormSq: 1 / n, diagHat: 1 / n }; + return { rawFit: fallbackVal, leverageNormSq: 1 / n, diagHat: 1 / n, localHatDiag: 1 / n }; } const mx = swx / sw; @@ -8516,6 +8529,7 @@ function computePublicationFit( const useSlope = sxxW > 1e-12; const inverseWeightSum = 1 / sw; const slopeScale = useSlope ? dx0 / sxxW : 0; + const localHatDiag = inverseWeightSum + (useSlope ? (dx0 * dx0) / sxxW : 0); let rawFit = 0; let leverageNormSq = 0; let diagHat = 0; @@ -8529,21 +8543,53 @@ function computePublicationFit( if (j === diagIdx) diagHat = lj; } - return { rawFit, leverageNormSq, diagHat }; + return { rawFit, leverageNormSq, diagHat, localHatDiag }; } const rawSampleFits = new Float64Array(n); const sampleLevSq = new Float64Array(n); let sse = 0; let traceL = 0; + let precomputedGridEval = null; - for (let i = 0; i < n; i++) { - const res = evalLoessPoint(xs[i], i); - rawSampleFits[i] = res.rawFit; - sampleLevSq[i] = res.leverageNormSq; - traceL += res.diagHat; - const diff = ys[i] - res.rawFit; - sse += diff * diff; + // 大样本(n > 200 且 x 单调有序)采用与 R `stats::loess(surface = "interpolate")` 一致的网格插值加速: + // 仅在 M 个均匀网格顶点做精确 LOESS(O(M·N)),再线性插值样本拟合值与杠杆度,避免 O(N²) 阻塞主线程。 + if (n > 200 && sortedXs && M >= 2) { + const gridRawFit = new Float64Array(M); + const gridLevSq = new Float64Array(M); + const gridHatDiag = new Float64Array(M); + for (let k = 0; k < M; k++) { + const res = evalLoessPoint(gridXs[k], -1); + gridRawFit[k] = res.rawFit; + gridLevSq[k] = res.leverageNormSq; + gridHatDiag[k] = res.localHatDiag; + } + precomputedGridEval = { gridRawFit, gridLevSq }; + + const invSpan = (M - 1) / xSpan; + const maxK0 = M - 2; + for (let i = 0; i < n; i++) { + const u = (xs[i] - xMin) * invSpan; + const k0 = u <= 0 ? 0 : u >= maxK0 ? maxK0 : Math.floor(u); + const frac = Math.max(0, Math.min(1, u - k0)); + const rf = gridRawFit[k0] + frac * (gridRawFit[k0 + 1] - gridRawFit[k0]); + const ls = Math.max(0, gridLevSq[k0] + frac * (gridLevSq[k0 + 1] - gridLevSq[k0])); + const hd = gridHatDiag[k0] + frac * (gridHatDiag[k0 + 1] - gridHatDiag[k0]); + rawSampleFits[i] = rf; + sampleLevSq[i] = ls; + traceL += hd; + const diff = ys[i] - rf; + sse += diff * diff; + } + } else { + for (let i = 0; i < n; i++) { + const res = evalLoessPoint(xs[i], i); + rawSampleFits[i] = res.rawFit; + sampleLevSq[i] = res.leverageNormSq; + traceL += res.diagHat; + const diff = ys[i] - res.rawFit; + sse += diff * diff; + } } const dfRes = Math.max(1, n - traceL); @@ -8567,16 +8613,27 @@ function computePublicationFit( clampedSse += d * d; } - const grid = gridXs.map((gx) => { - const res = evalLoessPoint(gx, -1); - const half = tCrit * sigmaHat * Math.sqrt(res.leverageNormSq); - return { - x: gx, - fit: clampValue(res.rawFit, minVal, maxVal), - ciLow: clampValue(res.rawFit - half, minVal, maxVal), - ciHigh: clampValue(res.rawFit + half, minVal, maxVal), - }; - }); + const grid = precomputedGridEval + ? gridXs.map((gx, k) => { + const rf = precomputedGridEval.gridRawFit[k]; + const half = tCrit * sigmaHat * Math.sqrt(Math.max(0, precomputedGridEval.gridLevSq[k])); + return { + x: gx, + fit: clampValue(rf, minVal, maxVal), + ciLow: clampValue(rf - half, minVal, maxVal), + ciHigh: clampValue(rf + half, minVal, maxVal), + }; + }) + : gridXs.map((gx) => { + const res = evalLoessPoint(gx, -1); + const half = tCrit * sigmaHat * Math.sqrt(res.leverageNormSq); + return { + x: gx, + fit: clampValue(res.rawFit, minVal, maxVal), + ciLow: clampValue(res.rawFit - half, minVal, maxVal), + ciHigh: clampValue(res.rawFit + half, minVal, maxVal), + }; + }); const r2Loess = syy > 1e-12 ? clampValue(1 - clampedSse / syy, 0, 1) : 1; @@ -9832,14 +9889,19 @@ function createModelFitChart() { const rect = svg.getBoundingClientRect(); if (!rect || rect.width <= 0) return; const relX = ((e.clientX - rect.left) / rect.width) * viewW; - let bestIdx = 0; - let bestDist = Math.abs(currentSamples[0].x - relX); - for (let i = 1; i < currentSamples.length; i++) { - const d = Math.abs(currentSamples[i].x - relX); - if (d < bestDist) { - bestDist = d; - bestIdx = i; - } + let lo = 0; + let hi = currentSamples.length - 1; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + if (currentSamples[mid].x < relX) lo = mid + 1; + else hi = mid; + } + let bestIdx = lo; + if ( + lo > 0 && + Math.abs(currentSamples[lo - 1].x - relX) <= Math.abs(currentSamples[lo].x - relX) + ) { + bestIdx = lo - 1; } showHoverAt(bestIdx); }); @@ -10253,16 +10315,28 @@ function createModelFitChart() { const dotRadius = combinedSamples.length > 80 ? '1.8' : combinedSamples.length > 36 ? '2.1' : '2.4'; + const dedupOverdraw = combinedSamples.length > 200; + const scatterTarget = + typeof document.createDocumentFragment === 'function' + ? document.createDocumentFragment() + : scatterGroup; for (const s of seriesList) { + const binCounts = dedupOverdraw ? new Map() : null; for (const sp of s.samples) { + if (binCounts) { + const binKey = (Math.round(sp.x * 2) << 11) ^ Math.round(sp.rawY * 2); + const prevCnt = binCounts.get(binKey) || 0; + if (prevCnt >= 6) continue; + binCounts.set(binKey, prevCnt + 1); + } const dot = document.createElementNS(SVG_NS, 'circle'); dot.setAttribute('cx', sp.x.toFixed(1)); dot.setAttribute('cy', sp.rawY.toFixed(1)); dot.setAttribute('r', dotRadius); dot.setAttribute('class', 'sstep-scatter-dot is-multi'); patchStyleVar(dot, '--sstep-fit-accent', s.colorVar); - scatterGroup.appendChild(dot); + scatterTarget.appendChild(dot); } if (s.samples.length === 1) { @@ -10312,6 +10386,9 @@ function createModelFitChart() { multiCurveGroup.appendChild(curveEl); } } + if (scatterTarget !== scatterGroup) { + scatterGroup.appendChild(scatterTarget); + } while (multiLegendEl.firstChild) multiLegendEl.removeChild(multiLegendEl.firstChild); for (const s of seriesList) { @@ -10444,13 +10521,27 @@ function createModelFitChart() { // 2. 绘制半透明冷蓝灰实心观测散点(自然呈现局部密度,不抢夺拟合曲线焦点) while (scatterGroup.firstChild) scatterGroup.removeChild(scatterGroup.firstChild); const dotRadius = samples.length > 80 ? '1.8' : samples.length > 36 ? '2.1' : '2.4'; + const binCounts = samples.length > 200 ? new Map() : null; + const scatterTarget = + typeof document.createDocumentFragment === 'function' + ? document.createDocumentFragment() + : scatterGroup; for (const s of samples) { + if (binCounts) { + const binKey = (Math.round(s.x * 2) << 11) ^ Math.round(s.rawY * 2); + const prevCnt = binCounts.get(binKey) || 0; + if (prevCnt >= 6) continue; + binCounts.set(binKey, prevCnt + 1); + } const dot = document.createElementNS(SVG_NS, 'circle'); dot.setAttribute('cx', s.x.toFixed(1)); dot.setAttribute('cy', s.rawY.toFixed(1)); dot.setAttribute('r', dotRadius); dot.setAttribute('class', 'sstep-scatter-dot'); - scatterGroup.appendChild(dot); + scatterTarget.appendChild(dot); + } + if (scatterTarget !== scatterGroup) { + scatterGroup.appendChild(scatterTarget); } // 3. 绘制 95% CI 置信带闭合多边形与回归拟合曲线(绝不向底部 X 轴填充面积!) @@ -14042,6 +14133,341 @@ function formatTurnPromptText(rawPrompt, { hasMedia = false, mediaOnly = false } return hasMedia ? `${text} ${t('steps.turnMediaSuffix')}` : text; } +const VIRTUAL_ROW_THRESHOLD = 80; +const VIRTUAL_OVERSCAN_ROWS = 16; +const VIRTUAL_REFILL_MARGIN = 6; +const MAX_ROW_POOL_SIZE = 96; +const FALLBACK_VIEWPORT_H = 560; +const BASE_SINGLE_ROW_H = 28; +const BASE_REASON_ROW_H = 42; +const SIZER_ROW_KEY = '__vsizer__'; +const SPACER_TOP_KEY = '__vspacer_top__'; +const SPACER_BOTTOM_KEY = '__vspacer_bottom__'; + +function estTokenChars(val) { + const n = Math.max(0, Number(val || 0)); + if (n >= 1_000_000) return n >= 10_000_000 ? 6 : 5; + if (n >= 100_000) return 6; + if (n >= 10_000) return 5; + if (n >= 1_000) return 4; + if (n >= 100) return 3; + if (n >= 10) return 2; + return 1; +} + +function estCostChars(val) { + const n = Number(val); + if (!Number.isFinite(n) || n <= 0) return 1; + if (n >= 100) return 7; + if (n >= 10) return 6; + if (n >= 0.01) return 5; + return 7; +} + +function estSegmentChars(seg, st) { + const inTok = Math.max(0, Number(st?.inputTokens || 0)); + const cacheTok = Math.max(0, Number(st?.cacheReadTokens || 0)); + const outTok = Math.max(0, Number(st?.outputTokens || 0)); + const thinkTok = Math.max(0, Number(st?.thinkingTokens || 0)); + const respTok = + st?.responseTokens != null + ? Math.max(0, Number(st.responseTokens)) + : Math.max(0, outTok - thinkTok); + switch (seg) { + case 'context': + return estTokenChars(st?.contextTokens ?? inTok + cacheTok + outTok); + case 'in': + return estTokenChars(inTok); + case 'out': + return estTokenChars(outTok); + case 'cache': + return estTokenChars(cacheTok); + case 'think': + return estTokenChars(thinkTok); + case 'reply': + return estTokenChars(respTok); + case 'total': + default: + return estTokenChars(inTok + cacheTok + outTok); + } +} + +function resolveBadgeTextForStep(st) { + return formatAgentBadgeText({ + agentKind: + st?.agentKind || + (!st?.isSubagent ? 'main' : st?.isSideQuestion ? 'side_question' : 'subagent'), + agentOrdinal: + st?.agentOrdinal || (st?.isSideQuestion ? st?.sideIndex || 0 : st?.agentIndex || 0), + isMain: !st?.isSubagent, + isSideQuestion: Boolean(st?.isSideQuestion), + sideIndex: st?.sideIndex || 0, + index: st?.agentIndex || 0, + badgeText: st?.agentBadge, + }); +} + +function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) { + const firstStep = tableSteps[0] || {}; + const colSteps = {}; + const needStep = wantedSet.has('step'); + const needTime = wantedSet.has('time'); + const needModel = wantedSet.has('model'); + const needTps = wantedSet.has('tps'); + const needTtft = wantedSet.has('ttft'); + const needDuration = wantedSet.has('duration'); + const needTokensCombo = wantedSet.has('tokens_combo'); + const needTokensIoCache = wantedSet.has('tokens_io_cache'); + const needTokensCustom = wantedSet.has('tokens_custom'); + const needInput = wantedSet.has('input_tokens'); + const needCacheTok = wantedSet.has('cache_tokens'); + const needOutput = wantedSet.has('output_tokens'); + const needCachePct = wantedSet.has('cache'); + const needCost = wantedSet.has('cost'); + const customSegs = needTokensCustom + ? parseStepTokenComboSegments(cellCtx?.stepTokenComboFormat) + : null; + + let bestStepNum = -1; + let bestStepObj = firstStep; + let bestTimeObj = null; + const modelCandidates = needModel ? new Map() : null; + let maxTpsVal = -1; + let maxTpsObj = null; + const reasonCandidates = needTps ? new Set() : null; + let maxTtftVal = -1; + let bestTtftObj = firstStep; + let maxDurVal = -1; + let bestDurObj = firstStep; + let bestComboScore = -1; + let bestComboObj = firstStep; + let bestIoCacheScore = -1; + let bestIoCacheObj = firstStep; + let bestCustomScore = -1; + let bestCustomObj = firstStep; + let maxInputVal = -1; + let bestInputObj = firstStep; + let maxCacheTokVal = -1; + let bestCacheTokObj = firstStep; + let maxOutputVal = -1; + let bestOutputObj = firstStep; + let bestCachePctScore = -1; + let bestCachePctObj = firstStep; + let bestCostScore = -1; + let bestCostObj = firstStep; + + let bestBadgeText = ''; + let bestBadgeClass = ''; + const badgeCandidates = cellCtx?.showAgentBadge ? new Set() : null; + + for (let i = 0; i < tableSteps.length; i++) { + const st = tableSteps[i]; + if (!st || typeof st !== 'object') continue; + + if (badgeCandidates) { + const bKey = `${st.agentKind || ''}|${st.isSubagent ? 1 : 0}|${st.isSideQuestion ? 1 : 0}|${st.agentOrdinal || 0}|${st.sideIndex || 0}|${st.agentIndex || 0}|${st.agentBadge || ''}`; + if (!badgeCandidates.has(bKey)) { + badgeCandidates.add(bKey); + const text = resolveBadgeTextForStep(st); + if (text.length > bestBadgeText.length) { + bestBadgeText = text; + bestBadgeClass = getAgentBadgeClass(st.agentIndex || 0, !st.isSubagent); + } + } + } + + if (needStep) { + const idxNum = Number(st.stepIndex) || 0; + if (idxNum > bestStepNum) { + bestStepNum = idxNum; + bestStepObj = st; + } + } + + if (needTime && !bestTimeObj && Number(st.createdAtMs || 0) > 0) { + bestTimeObj = st; + } + + if (modelCandidates) { + const mKey = `${st.baseModelShort || st.modelShort || ''}|${st.baseModelLabel || st.modelLabel || ''}|${st.rawModel || ''}|${st.isCompactionStep ? 1 : 0}`; + if (!modelCandidates.has(mKey)) { + modelCandidates.set(mKey, st); + } + } + + if (needTps) { + const tpsVal = Number(st.tokPerSec); + if (Number.isFinite(tpsVal) && tpsVal > maxTpsVal) { + maxTpsVal = tpsVal; + maxTpsObj = st; + } + if (st.selectedSpeedReason) { + reasonCandidates.add(st.selectedSpeedReason); + } + } + + if (needTtft) { + const v = Number(st.ttftSec); + if (Number.isFinite(v) && v > maxTtftVal) { + maxTtftVal = v; + bestTtftObj = st; + } + } + + if (needDuration) { + const v = Number(st.totalDurationSec ?? st.streamDurationSec); + if (Number.isFinite(v) && v > maxDurVal) { + maxDurVal = v; + bestDurObj = st; + } + } + + if (needTokensCombo) { + const inTok = Math.max(0, Number(st.inputTokens || 0)); + const cacheTok = Math.max(0, Number(st.cacheReadTokens || 0)); + const outTok = Math.max(0, Number(st.outputTokens || 0)); + const thinkTok = Math.max(0, Number(st.thinkingTokens || 0)); + const respTok = + st.responseTokens != null + ? Math.max(0, Number(st.responseTokens)) + : Math.max(0, outTok - thinkTok); + const ctxTok = Math.max(0, Number(st.contextTokens ?? inTok + cacheTok + outTok)); + const score = + (estTokenChars(ctxTok) + estTokenChars(thinkTok) + estTokenChars(respTok)) * 1e9 + + ctxTok; + if (score > bestComboScore) { + bestComboScore = score; + bestComboObj = st; + } + } + + if (needTokensIoCache) { + const inTok = Math.max(0, Number(st.inputTokens || 0)); + const outTok = Math.max(0, Number(st.outputTokens || 0)); + const cacheTok = Math.max(0, Number(st.cacheReadTokens || 0)); + const score = + (estTokenChars(inTok) + estTokenChars(outTok) + estTokenChars(cacheTok)) * 1e9 + + cacheTok; + if (score > bestIoCacheScore) { + bestIoCacheScore = score; + bestIoCacheObj = st; + } + } + + if (needTokensCustom && customSegs) { + let chars = 0; + for (let s = 0; s < customSegs.length; s++) { + chars += estSegmentChars(customSegs[s], st); + } + if (chars > bestCustomScore) { + bestCustomScore = chars; + bestCustomObj = st; + } + } + + if (needInput) { + const v = Math.max(0, Number(st.inputTokens || 0)); + const score = estTokenChars(v) * 1e9 + v; + if (score > maxInputVal) { + maxInputVal = score; + bestInputObj = st; + } + } + + if (needCacheTok) { + const v = Math.max(0, Number(st.cacheReadTokens || 0)); + const score = estTokenChars(v) * 1e9 + v; + if (score > maxCacheTokVal) { + maxCacheTokVal = score; + bestCacheTokObj = st; + } + } + + if (needOutput) { + const v = Math.max(0, Number(st.outputTokens || 0)); + const score = estTokenChars(v) * 1e9 + v; + if (score > maxOutputVal) { + maxOutputVal = score; + bestOutputObj = st; + } + } + + if (needCachePct) { + const pct = Number(st.cacheHitPct ?? 0); + const hasDec = pct > 0 && pct < 100 && Math.abs(pct - Math.round(pct)) > 1e-6; + const score = pct >= 100 ? 4 : hasDec ? (pct >= 10 ? 5 : 4) : pct >= 10 ? 3 : 2; + if (score > bestCachePctScore) { + bestCachePctScore = score; + bestCachePctObj = st; + } + } + + if (needCost) { + const c = Number(st.costUsd); + const score = estCostChars(c) * 1e6 + (Number.isFinite(c) && c > 0 ? c : 0); + if (score > bestCostScore) { + bestCostScore = score; + bestCostObj = st; + } + } + } + + if (needStep) colSteps.step = bestStepObj; + if (needTime) colSteps.time = bestTimeObj || firstStep; + if (needModel && modelCandidates) { + let bestModelLen = -1; + let bestModelObj = firstStep; + for (const cand of modelCandidates.values()) { + const disp = resolveModelDisplayInfo(cand, cellCtx?.displaySettings, { fallback: '—' }); + const len = (disp.baseText?.length || 0) + (disp.compactionSuffix?.length || 0); + if (len > bestModelLen) { + bestModelLen = len; + bestModelObj = cand; + } + } + colSteps.model = bestModelObj; + } + if (needTps) { + let longestReasonKey = null; + let longestReasonLen = 0; + if (reasonCandidates) { + for (const rk of reasonCandidates) { + const txt = speedReasonText(rk); + if (txt && txt.length > longestReasonLen) { + longestReasonLen = txt.length; + longestReasonKey = rk; + } + } + } + colSteps.tps = { + ...(maxTpsObj || firstStep), + tokPerSec: maxTpsVal > 0 ? maxTpsVal : firstStep.tokPerSec, + selectedSpeedReason: longestReasonKey, + }; + } + if (needTtft) colSteps.ttft = bestTtftObj; + if (needDuration) colSteps.duration = bestDurObj; + if (needTokensCombo) colSteps.tokens_combo = bestComboObj; + if (needTokensIoCache) colSteps.tokens_io_cache = bestIoCacheObj; + if (needTokensCustom) colSteps.tokens_custom = bestCustomObj; + if (needInput) colSteps.input_tokens = bestInputObj; + if (needCacheTok) colSteps.cache_tokens = bestCacheTokObj; + if (needOutput) colSteps.output_tokens = bestOutputObj; + if (needCachePct) colSteps.cache = bestCachePctObj; + if (needCost) colSteps.cost = bestCostObj; + + const sigParts = colKeys.map((colKey) => { + const st = colSteps[colKey] || firstStep; + return `${colKey}=${STEP_COLUMN_REGISTRY[colKey].sigPart(st, cellCtx)}`; + }); + return { + colSteps, + badgeText: bestBadgeText, + badgeClass: bestBadgeClass, + sig: `sizer:${bestBadgeText}:${sigParts.join('|')}`, + }; +} + const StepTableWidget = defineComponent({ name: 'StepTableWidget', setup({ props, onCleanup }) { @@ -14049,8 +14475,11 @@ const StepTableWidget = defineComponent({ const interactiveBadges = props.interactiveBadges !== false; const onSelectAgentScopes = typeof props.onSelectAgentScopes === 'function' ? props.onSelectAgentScopes : null; + const onVirtualHeightChange = + typeof props.onVirtualHeightChange === 'function' ? props.onVirtualHeightChange : null; const stepsTheadRow = h('tr'); + const stepsThead = h('thead', {}, [stepsTheadRow]); const stepsTbody = h('tbody'); function syncTableHeaderColumns(colKeys, headerCtx = {}) { @@ -14073,7 +14502,7 @@ const StepTableWidget = defineComponent({ syncTableHeaderColumns(DEFAULT_STEP_COLUMN_KEYS); const stepsTableEl = h('table', { className: 'data-table steps-data-table' }, [ - h('thead', {}, [stepsTheadRow]), + stepsThead, stepsTbody, ]); const stepsTablePane = h('div', { className: 'table-viewport is-step-table' }, [stepsTableEl]); @@ -14136,16 +14565,98 @@ const StepTableWidget = defineComponent({ } } - stepsTablePane.addEventListener('scroll', hideTurnTip); - stepsTbody.addEventListener('mouseleave', hideTurnTip); const hoverRows = new WeakMap(); let lastRenderedRows = null; let lastRenderOptions = ''; let trackedCascadeId = null; + let lastAbsorbedAllSteps = null; const seenStepKeys = new Set(); const maxSeenStepByAgent = new Map(); const activeEnterTimers = new Map(); + // Virtualization state (activates transparently only when !standalone && rowCount > 80) + let activeDataset = null; + let renderedSliceStart = -1; + let renderedSliceEnd = -1; + let renderedTopSpacerH = -1; + let renderedBottomSpacerH = -1; + let scrollRafId = 0; + let calibrateRafId = 0; + let lastFontScale = 1; + let calibratedSingleRowH = 0; + let calibratedReasonRowH = 0; + const rowPool = []; + + function readUiFontScale() { + try { + if (typeof getComputedStyle === 'function') { + const target = + stepsTableEl || (typeof document !== 'undefined' ? document.documentElement : null); + if (target) { + const raw = getComputedStyle(target)?.getPropertyValue?.('--ui-font-scale'); + const parsed = Number.parseFloat(raw); + if (Number.isFinite(parsed) && parsed >= 0.5 && parsed <= 2.5) { + return parsed; + } + } + } + } catch { + // Fallback to default scale in headless/mock environments. + } + return 1; + } + + function getEstRowHeights() { + const single = + calibratedSingleRowH > 0 + ? calibratedSingleRowH + : Math.round(BASE_SINGLE_ROW_H * lastFontScale); + const reason = + calibratedReasonRowH > 0 + ? calibratedReasonRowH + : Math.round(BASE_REASON_ROW_H * lastFontScale); + return { single, reason }; + } + + function buildRowTops(n, hasReasonFlags) { + const { single, reason } = getEstRowHeights(); + const tops = new Float64Array(n + 1); + let acc = 0; + for (let i = 0; i < n; i++) { + tops[i] = acc; + acc += hasReasonFlags && hasReasonFlags[i] ? reason : single; + } + tops[n] = acc; + return { rowTops: tops, totalBodyH: acc }; + } + + function findRowIndexAtOffset(rowTops, n, offset) { + if (n <= 0 || offset <= 0) return 0; + if (offset >= rowTops[n - 1]) return n - 1; + let lo = 0; + let hi = n - 1; + while (lo < hi) { + const mid = (lo + hi + 1) >>> 1; + if (rowTops[mid] <= offset) lo = mid; + else hi = mid - 1; + } + return lo; + } + + function syncFontScaleIfChanged() { + const nextScale = readUiFontScale(); + if (Math.abs(nextScale - lastFontScale) < 0.005) return false; + lastFontScale = nextScale; + calibratedSingleRowH = 0; + calibratedReasonRowH = 0; + if (activeDataset?.isVirtualized) { + const rebuilt = buildRowTops(activeDataset.tableSteps.length, activeDataset.hasReasonFlags); + activeDataset.rowTops = rebuilt.rowTops; + activeDataset.totalBodyH = rebuilt.totalBodyH; + } + return true; + } + function getStepRowIdentity(st, fallbackCascadeId) { const agentKey = String(st?.agentCascadeId || fallbackCascadeId || 'conv'); const stepNum = Number(st?.stepIndex); @@ -14204,80 +14715,185 @@ const StepTableWidget = defineComponent({ cell.onmouseleave = null; } - function renderStepTable( - tableSteps, - cascadeId, - colKeys, - locale, - { - effectiveScopes = ['all'], - hasSubagents = false, - isMergedMultiAgents = false, - showStepTurnRail = false, - showStepAgentBadge = true, - showStepSpeedColor = false, - stepTokenComboFormat = undefined, - displaySettings = {}, - allConversationSteps = null, - allowNewRowFade = false, - } = {} - ) { - const normCascadeId = String(cascadeId || ''); - let enteringRowKeys = null; - if (!normCascadeId || trackedCascadeId === null || normCascadeId !== trackedCascadeId) { - trackedCascadeId = normCascadeId || null; - seenStepKeys.clear(); - maxSeenStepByAgent.clear(); - absorbStepsIntoBaseline(allConversationSteps, normCascadeId); - absorbStepsIntoBaseline(tableSteps, normCascadeId); - } else if (!allowNewRowFade || standalone) { - absorbStepsIntoBaseline(allConversationSteps, normCascadeId); - absorbStepsIntoBaseline(tableSteps, normCascadeId); - } else { - for (const st of tableSteps) { - if (!st || typeof st !== 'object') continue; - const { agentKey, stepNum, rowKey } = getStepRowIdentity(st, normCascadeId); - if (!seenStepKeys.has(rowKey)) { - const prevMax = maxSeenStepByAgent.get(agentKey); - if (prevMax === undefined || !Number.isFinite(stepNum) || stepNum > prevMax) { - enteringRowKeys ??= new Set(); - enteringRowKeys.add(rowKey); + function calibrateRowHeights() { + calibrateRafId = 0; + if (!activeDataset?.isVirtualized) return; + if (Number(stepsTablePane.clientHeight || 0) <= 0) return; + const needSingle = calibratedSingleRowH <= 0; + const needReason = calibratedReasonRowH <= 0 && activeDataset.hasAnyReason; + if (!needSingle && !needReason) return; + + let measuredSingle = 0; + let measuredReason = 0; + // Measure contiguous run of normal rows to eliminate single-row subpixel/border-collapse drift. + let runStartTop = 0; + let runEndBottom = 0; + let runCount = 0; + let bestRunStride = 0; + let bestRunCount = 0; + + const children = stepsTbody.children || []; + for (let i = 0; i < children.length; i++) { + const tr = children[i]; + if (!tr || tr.classList?.contains('step-vspacer') || tr.classList?.contains('step-vsizer')) { + runCount = 0; + continue; + } + const isReason = tr.dataset?.hasReason === '1'; + if (!isReason && needSingle) { + const rect = tr.getBoundingClientRect?.(); + const hVal = Number(rect?.height || tr.offsetHeight || 0); + if (hVal >= 14 && hVal <= 120) { + if (!measuredSingle) measuredSingle = hVal; + if (rect && Number.isFinite(rect.top) && Number.isFinite(rect.bottom) && rect.bottom > rect.top) { + if (runCount === 0) { + runStartTop = rect.top; + } + runEndBottom = rect.bottom; + runCount += 1; + if (runCount > bestRunCount && runCount >= 2) { + const stride = (runEndBottom - runStartTop) / runCount; + if (stride >= 14 && stride <= 120) { + bestRunCount = runCount; + bestRunStride = stride; + } + } } } + } else { + runCount = 0; + if (isReason && needReason && !measuredReason) { + const hVal = Number(tr.getBoundingClientRect?.()?.height || tr.offsetHeight || 0); + if (hVal >= 18 && hVal <= 160) measuredReason = hVal; + } + } + if ((!needSingle || bestRunCount >= 12) && (!needReason || measuredReason > 0)) { + break; } - absorbStepsIntoBaseline(allConversationSteps, normCascadeId); - absorbStepsIntoBaseline(tableSteps, normCascadeId); } - const colOrderSig = colKeys.join(','); - const normTokenFmt = normalizeClientStepTokenComboFormat(stepTokenComboFormat); - const renderOptions = JSON.stringify([ - cascadeId, locale, colOrderSig, effectiveScopes, hasSubagents, isMergedMultiAgents, - showStepTurnRail, showStepAgentBadge, showStepSpeedColor, normTokenFmt, - displaySettings.modelDisplayMode, displaySettings.showUpstreamModel, - displaySettings.orchestratorIdMode, - ]); - if (lastRenderOptions === renderOptions && lastRenderedRows && - (lastRenderedRows === tableSteps || (lastRenderedRows.length === tableSteps.length && - tableSteps.every((step, i) => step === lastRenderedRows[i])))) { - return; + if (bestRunStride > 0) { + measuredSingle = bestRunStride; } - const wantedSet = new Set(colKeys); - syncTableHeaderColumns(colKeys, { stepTokenComboFormat: normTokenFmt }); - const showAgentBadge = Boolean(hasSubagents && showStepAgentBadge); - const cellCtx = { - hasSubagents, + let changed = false; + if (measuredSingle > 0) { + const prev = getEstRowHeights().single; + calibratedSingleRowH = measuredSingle; + if (Math.abs(measuredSingle - prev) >= 0.25) changed = true; + } + if (measuredReason > 0) { + const prev = getEstRowHeights().reason; + calibratedReasonRowH = measuredReason; + if (Math.abs(measuredReason - prev) >= 0.25) changed = true; + } + + if (changed && activeDataset) { + const prevTops = activeDataset.rowTops; + const anchorIdx = renderedSliceStart > 0 ? renderedSliceStart : 0; + const prevAnchorTop = prevTops ? prevTops[anchorIdx] : 0; + const rebuilt = buildRowTops(activeDataset.tableSteps.length, activeDataset.hasReasonFlags); + activeDataset.rowTops = rebuilt.rowTops; + activeDataset.totalBodyH = rebuilt.totalBodyH; + const curScrollTop = Number(stepsTablePane.scrollTop || 0); + if (anchorIdx > 0 && curScrollTop > 0) { + const delta = rebuilt.rowTops[anchorIdx] - prevAnchorTop; + if (Math.abs(delta) >= 0.5) { + stepsTablePane.scrollTop = Math.max(0, curScrollTop + delta); + } + } + renderCurrentWindow({ force: true, enteringRowKeys: null }); + onVirtualHeightChange?.(); + } + } + + function scheduleCalibrateRowHeights() { + if (!activeDataset?.isVirtualized) return; + const needSingle = calibratedSingleRowH <= 0; + const needReason = calibratedReasonRowH <= 0 && activeDataset.hasAnyReason; + if (!needSingle && !needReason) return; + if (calibrateRafId) return; + if (typeof requestAnimationFrame === 'function') { + calibrateRafId = requestAnimationFrame(calibrateRowHeights); + } else { + calibrateRowHeights(); + } + } + + function renderCurrentWindow({ force = false, enteringRowKeys = null } = {}) { + const ds = activeDataset; + if (!ds) return; + const { + tableSteps, + cascadeId, + colKeys, + wantedSet, + colOrderSig, + locale, + cellCtx, + railActive, showAgentBadge, - showStepSpeedColor, - stepTokenComboFormat: normTokenFmt, + showStepTurnRail, + useRootTurn, + isVirtualized, + hasReasonFlags, + rowTops, + totalBodyH, + sizerSpec, effectiveScopes, - scopeSigKey: effectiveScopes.join(','), - displaySettings, - onSelectAgentScopes, - }; + formattedPrompts, + } = ds; + + const n = tableSteps.length; + let startIdx = 0; + let endIdx = n; + let topSpacerH = 0; + let bottomSpacerH = 0; + + if (isVirtualized) { + const scrollTop = Math.max(0, Number(stepsTablePane.scrollTop || 0)); + const rawClientH = Number(stepsTablePane.clientHeight || 0); + const viewportH = rawClientH > 0 ? rawClientH : FALLBACK_VIEWPORT_H; + const rawTheadH = Number( + stepsThead.offsetHeight || stepsThead.getBoundingClientRect?.()?.height || 0 + ); + const theadH = rawTheadH > 0 ? rawTheadH : getEstRowHeights().single; + const viewTop = Math.max(0, scrollTop - theadH); + const viewBottom = viewTop + viewportH; + const firstVis = findRowIndexAtOffset(rowTops, n, viewTop); + const lastVis = findRowIndexAtOffset(rowTops, n, viewBottom); + + if ( + !force && + renderedSliceStart >= 0 && + renderedSliceEnd > renderedSliceStart && + renderedSliceEnd <= n + ) { + const topSafe = + renderedSliceStart === 0 || firstVis - renderedSliceStart >= VIRTUAL_REFILL_MARGIN; + const bottomSafe = + renderedSliceEnd === n || renderedSliceEnd - 1 - lastVis >= VIRTUAL_REFILL_MARGIN; + if (topSafe && bottomSafe) { + return; + } + } + + startIdx = Math.max(0, firstVis - VIRTUAL_OVERSCAN_ROWS); + endIdx = Math.min(n, lastVis + 1 + VIRTUAL_OVERSCAN_ROWS); + topSpacerH = +rowTops[startIdx].toFixed(2); + bottomSpacerH = +Math.max(0, totalBodyH - rowTops[endIdx]).toFixed(2); + + if ( + !force && + startIdx === renderedSliceStart && + endIdx === renderedSliceEnd && + topSpacerH === renderedTopSpacerH && + bottomSpacerH === renderedBottomSpacerH + ) { + return; + } + } - const useRootTurn = Boolean(hasSubagents && isMergedMultiAgents); const getStepTurnIdx = (st) => useRootTurn ? (st?.rootTurnIndex ?? st?.turnIndex) : st?.turnIndex; const getStepIsStart = (st) => @@ -14292,12 +14908,15 @@ const StepTableWidget = defineComponent({ Boolean(useRootTurn ? (st?.rootTurnHasMedia ?? st?.turnHasMedia) : st?.turnHasMedia); const getStepMediaOnly = (st) => Boolean(useRootTurn ? (st?.rootTurnMediaOnly ?? st?.turnMediaOnly) : st?.turnMediaOnly); - const turnKeys = showStepTurnRail ? tableSteps.map((st) => { + + function getTurnKeyAt(idx) { + if (!showStepTurnRail || idx < 0 || idx >= n) return ''; + const st = tableSteps[idx]; const tIdx = getStepTurnIdx(st); if (!Number.isInteger(tIdx) || tIdx <= 0) return ''; return useRootTurn ? `root:${tIdx}` : `${st?.agentId || 'main'}:${tIdx}`; - }) : []; - const formattedPrompts = new Map(); + } + function formattedTurnPrompt(st) { const raw = getStepPrompt(st); const hasMedia = getStepHasMedia(st); @@ -14309,13 +14928,38 @@ const StepTableWidget = defineComponent({ return formattedPrompts.get(cacheKey); } - const decoratedSteps = tableSteps.map((st, idx) => { - const tKey = turnKeys[idx]; + const windowItems = []; + if (isVirtualized && sizerSpec) { + windowItems.push({ + isSizer: true, + isSpacer: false, + rowKey: SIZER_ROW_KEY, + sizerSpec, + }); + } + if (isVirtualized && topSpacerH > 0) { + windowItems.push({ + isSizer: false, + isSpacer: true, + rowKey: SPACER_TOP_KEY, + height: topSpacerH, + colSpan: colKeys.length, + }); + } + + for (let idx = startIdx; idx < endIdx; idx++) { + const st = tableSteps[idx]; + const tKey = getTurnKeyAt(idx); const hasTurn = Boolean(tKey); - const hasUp = hasTurn && turnKeys[idx - 1] === tKey; - const hasDown = hasTurn && turnKeys[idx + 1] === tKey; - return { + const hasUp = hasTurn && getTurnKeyAt(idx - 1) === tKey; + const hasDown = hasTurn && getTurnKeyAt(idx + 1) === tKey; + windowItems.push({ + isSizer: false, + isSpacer: false, st, + logicalIdx: idx, + isStripeEven: (idx & 1) === 1, + hasReason: Boolean(hasReasonFlags && hasReasonFlags[idx]), rowKey: `${st.agentCascadeId || cascadeId || 'conv'}-${st.stepIndex}`, hasTurn, hasUp, @@ -14323,18 +14967,28 @@ const StepTableWidget = defineComponent({ isStart: Boolean(hasTurn && (getStepIsStart(st) || !hasDown)), isLatest: hasTurn && getStepIsLatest(st), prompt: hasTurn ? formattedTurnPrompt(st) : '', - }; - }); - - const railActive = Boolean(showStepTurnRail && decoratedSteps.some((d) => d.hasTurn)); - if (!railActive) { - hideTurnTip(); + }); } - patchClasses(stepsTableEl, { 'has-turn-rail': railActive }); - patchKeyedList(stepsTbody, decoratedSteps, { + if (isVirtualized && bottomSpacerH > 0) { + windowItems.push({ + isSizer: false, + isSpacer: true, + rowKey: SPACER_BOTTOM_KEY, + height: bottomSpacerH, + colSpan: colKeys.length, + }); + } + + patchKeyedList(stepsTbody, windowItems, { keyFn: (item) => item.rowKey, sigFn: (item) => { + if (item.isSizer) { + return `${locale}:${colOrderSig}:${showAgentBadge ? 1 : 0}:${railActive ? 1 : 0}:${item.sizerSpec.sig}`; + } + if (item.isSpacer) { + return `spacer:${item.colSpan}:${item.height}`; + } const { st } = item; const parts = colKeys .map((colKey) => STEP_COLUMN_REGISTRY[colKey].sigPart(st, cellCtx)) @@ -14342,13 +14996,40 @@ const StepTableWidget = defineComponent({ const badgeSig = showAgentBadge ? `${cellCtx.scopeSigKey}:${st.agentId || 'main'}:${st.agentBadge || ''}:${st.agentLabel || ''}` : ''; - return `${locale}:${colOrderSig}:${badgeSig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`; + const stripeSig = isVirtualized ? (item.isStripeEven ? 'E' : 'O') : 'N'; + return `${locale}:${colOrderSig}:${stripeSig}:${badgeSig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`; }, - createRow: () => { + createRow: (item) => { + if (item.isSizer) { + const tr = h('tr', { className: 'step-vsizer', 'aria-hidden': 'true' }); + return { + el: tr, + refs: { + isSizer: true, + isSpacer: false, + cellMap: new Map(), + colOrderSig: '', + agentBadgeEl: null, + }, + }; + } + if (item.isSpacer) { + const td = h('td', { + className: 'step-vspacer-cell', + colspan: String(item.colSpan), + }); + const tr = h('tr', { className: 'step-vspacer', 'aria-hidden': 'true' }, [td]); + return { el: tr, refs: { isSizer: false, isSpacer: true, td } }; + } + if (rowPool.length > 0) { + return rowPool.pop(); + } const tr = h('tr'); return { el: tr, refs: { + isSizer: false, + isSpacer: false, cellMap: new Map(), colOrderSig: '', railEl: null, @@ -14358,7 +15039,78 @@ const StepTableWidget = defineComponent({ }; }, updateRow: (refs, item, _idx, tr) => { + if (item.isSizer) { + const spec = item.sizerSpec; + if (refs.colOrderSig !== colOrderSig) { + for (const [oldColKey, entry] of refs.cellMap) { + if (!wantedSet.has(oldColKey)) { + if (refs.agentBadgeEl?.parentNode === entry.innerEl) { + entry.innerEl.removeChild(refs.agentBadgeEl); + } + tr.removeChild(entry.td); + refs.cellMap.delete(oldColKey); + } + } + const isNewSizer = refs.colOrderSig === ''; + for (let i = 0; i < colKeys.length; i++) { + const colKey = colKeys[i]; + let entry = refs.cellMap.get(colKey); + if (!entry) { + const created = STEP_COLUMN_REGISTRY[colKey].createCell(); + const innerEl = h('div', { className: 'step-vsizer-inner' }); + while (created.td.firstChild) { + innerEl.appendChild(created.td.firstChild); + } + created.td.appendChild(innerEl); + entry = { td: created.td, refs: created.refs, innerEl }; + refs.cellMap.set(colKey, entry); + } + if (isNewSizer) { + tr.appendChild(entry.td); + } else { + const currentTd = tr.children[i] || null; + if (currentTd !== entry.td) tr.insertBefore(entry.td, currentTd); + } + } + refs.colOrderSig = colOrderSig; + } + for (const colKey of colKeys) { + const entry = refs.cellMap.get(colKey); + const probeStep = spec.colSteps[colKey] || tableSteps[0]; + if (entry && probeStep) { + STEP_COLUMN_REGISTRY[colKey].updateCell(entry.refs, probeStep, cellCtx); + } + } + const firstColKey = colKeys[0]; + const firstInner = firstColKey ? refs.cellMap.get(firstColKey)?.innerEl || null : null; + const showSizerBadge = Boolean(showAgentBadge && firstInner && spec.badgeText); + if (showSizerBadge && !refs.agentBadgeEl) { + refs.agentBadgeEl = h('span', { className: 'agent-badge', style: 'margin-right: 4px;' }); + } + if (firstInner && refs.agentBadgeEl) { + if (refs.agentBadgeEl.parentNode !== firstInner || firstInner.firstChild !== refs.agentBadgeEl) { + firstInner.insertBefore(refs.agentBadgeEl, firstInner.firstChild); + } + patchAttr(refs.agentBadgeEl, 'hidden', !showSizerBadge); + if (showSizerBadge) { + patchAttr(refs.agentBadgeEl, 'class', `agent-badge ${spec.badgeClass || ''}`.trim()); + patchText(refs.agentBadgeEl, spec.badgeText); + } + } + return; + } + if (item.isSpacer) { + patchAttr(refs.td, 'colspan', String(item.colSpan)); + if (refs.td?.style) { + refs.td.style.height = `${item.height}px`; + } + return; + } const { st, hasTurn, hasUp, hasDown, isStart, isLatest, prompt } = item; + patchClasses(tr, { 'is-stripe-even': Boolean(isVirtualized && item.isStripeEven) }); + if (tr.dataset) { + tr.dataset.hasReason = item.hasReason ? '1' : '0'; + } if (refs.colOrderSig !== colOrderSig) { if (refs.hoverTd) { @@ -14417,8 +15169,10 @@ const StepTableWidget = defineComponent({ const afterRail = refs.railEl ? refs.railEl.nextSibling ?? firstTd.children[1] ?? null : firstTd.firstChild; - if (refs.agentBadgeEl && - (refs.agentBadgeEl.parentNode !== firstTd || afterRail !== refs.agentBadgeEl)) { + if ( + refs.agentBadgeEl && + (refs.agentBadgeEl.parentNode !== firstTd || afterRail !== refs.agentBadgeEl) + ) { firstTd.insertBefore(refs.agentBadgeEl, afterRail); } } @@ -14488,7 +15242,11 @@ const StepTableWidget = defineComponent({ patchAttr(refs.railEl, 'hidden', !showRowRail); if (showRowRail) { const marker = isStart ? ' is-origin' : !hasUp && hasDown ? ' is-cap' : ''; - patchAttr(refs.railEl, 'class', `turn-rail${isLatest ? ' is-latest' : ''}${hasUp ? ' has-up' : ''}${hasDown ? ' has-down' : ''}${marker}`); + patchAttr( + refs.railEl, + 'class', + `turn-rail${isLatest ? ' is-latest' : ''}${hasUp ? ' has-up' : ''}${hasDown ? ' has-down' : ''}${marker}` + ); } const hoverTd = showRowRail && prompt ? firstTd : null; @@ -14513,17 +15271,270 @@ const StepTableWidget = defineComponent({ activeEnterTimers.set(tr, timer); } }, - destroyRow: (_refs, tr) => { + destroyRow: (refs, tr) => { + if (refs?.hoverTd) { + clearCellHover(refs.hoverTd); + refs.hoverTd = null; + } clearRowEnterState(tr); + if (!refs?.isSpacer && !refs?.isSizer && tr) { + patchClasses(tr, { 'is-stripe-even': false, 'is-step-entering': false }); + if (refs.agentBadgeEl) { + refs.agentBadgeEl.onclick = null; + } + if (rowPool.length < MAX_ROW_POOL_SIZE) { + rowPool.push({ el: tr, refs }); + } + } }, }); + + renderedSliceStart = startIdx; + renderedSliceEnd = endIdx; + renderedTopSpacerH = topSpacerH; + renderedBottomSpacerH = bottomSpacerH; + + if (isVirtualized) { + scheduleCalibrateRowHeights(); + } + } + + function refreshViewport() { + if (!activeDataset?.isVirtualized) return; + const scaleChanged = syncFontScaleIfChanged(); + renderCurrentWindow({ force: scaleChanged, enteringRowKeys: null }); + scheduleCalibrateRowHeights(); + } + + function onPaneScroll() { + hideTurnTip(); + if (!activeDataset?.isVirtualized) return; + if (typeof requestAnimationFrame === 'function') { + if (scrollRafId) return; + scrollRafId = requestAnimationFrame(() => { + scrollRafId = 0; + renderCurrentWindow({ force: false, enteringRowKeys: null }); + }); + } else { + renderCurrentWindow({ force: false, enteringRowKeys: null }); + } + } + + stepsTablePane.addEventListener('scroll', onPaneScroll, { passive: true }); + stepsTbody.addEventListener('mouseleave', hideTurnTip); + + let paneResizeObs = null; + if (typeof ResizeObserver === 'function') { + paneResizeObs = new ResizeObserver(() => { + if (!activeDataset?.isVirtualized) return; + refreshViewport(); + }); + paneResizeObs.observe(stepsTablePane); + } + + function renderStepTable( + tableSteps, + cascadeId, + colKeys, + locale, + { + effectiveScopes = ['all'], + hasSubagents = false, + isMergedMultiAgents = false, + showStepTurnRail = false, + showStepAgentBadge = true, + showStepSpeedColor = false, + stepTokenComboFormat = undefined, + displaySettings = {}, + allConversationSteps = null, + allowNewRowFade = false, + } = {} + ) { + const normCascadeId = String(cascadeId || ''); + let enteringRowKeys = null; + if (!normCascadeId || trackedCascadeId === null || normCascadeId !== trackedCascadeId) { + trackedCascadeId = normCascadeId || null; + lastAbsorbedAllSteps = null; + seenStepKeys.clear(); + maxSeenStepByAgent.clear(); + if (allConversationSteps && allConversationSteps !== tableSteps) { + absorbStepsIntoBaseline(allConversationSteps, normCascadeId); + lastAbsorbedAllSteps = allConversationSteps; + } + absorbStepsIntoBaseline(tableSteps, normCascadeId); + } else if (!allowNewRowFade || standalone) { + if (allConversationSteps && allConversationSteps !== lastAbsorbedAllSteps && allConversationSteps !== tableSteps) { + absorbStepsIntoBaseline(allConversationSteps, normCascadeId); + lastAbsorbedAllSteps = allConversationSteps; + } + if (tableSteps !== lastRenderedRows) { + absorbStepsIntoBaseline(tableSteps, normCascadeId); + } + } else if (tableSteps !== lastRenderedRows) { + let pendingMaxByAgent = null; + for (const st of tableSteps) { + if (!st || typeof st !== 'object') continue; + const { agentKey, stepNum, rowKey } = getStepRowIdentity(st, normCascadeId); + if (!seenStepKeys.has(rowKey)) { + seenStepKeys.add(rowKey); + const prevMax = maxSeenStepByAgent.get(agentKey); + if (prevMax === undefined || !Number.isFinite(stepNum) || stepNum > prevMax) { + enteringRowKeys ??= new Set(); + enteringRowKeys.add(rowKey); + } + if (Number.isFinite(stepNum)) { + const curPending = pendingMaxByAgent?.get(agentKey); + if (curPending === undefined || stepNum > curPending) { + pendingMaxByAgent ??= new Map(); + pendingMaxByAgent.set(agentKey, stepNum); + } + } + } + } + if (pendingMaxByAgent) { + for (const [agentKey, maxStep] of pendingMaxByAgent) { + const prevMax = maxSeenStepByAgent.get(agentKey); + if (prevMax === undefined || maxStep > prevMax) { + maxSeenStepByAgent.set(agentKey, maxStep); + } + } + } + if (allConversationSteps && allConversationSteps !== lastAbsorbedAllSteps && allConversationSteps !== tableSteps) { + absorbStepsIntoBaseline(allConversationSteps, normCascadeId); + lastAbsorbedAllSteps = allConversationSteps; + } + } else if (allConversationSteps && allConversationSteps !== lastAbsorbedAllSteps && allConversationSteps !== tableSteps) { + absorbStepsIntoBaseline(allConversationSteps, normCascadeId); + lastAbsorbedAllSteps = allConversationSteps; + } + + const colOrderSig = colKeys.join(','); + const normTokenFmt = normalizeClientStepTokenComboFormat(stepTokenComboFormat); + const renderOptions = JSON.stringify([ + cascadeId, locale, colOrderSig, effectiveScopes, hasSubagents, isMergedMultiAgents, + showStepTurnRail, showStepAgentBadge, showStepSpeedColor, normTokenFmt, + displaySettings.modelDisplayMode, displaySettings.showUpstreamModel, + displaySettings.orchestratorIdMode, + ]); + if ( + lastRenderOptions === renderOptions && + lastRenderedRows && + (lastRenderedRows === tableSteps || + (lastRenderedRows.length === tableSteps.length && + tableSteps.every((step, i) => step === lastRenderedRows[i]))) + ) { + if (activeDataset?.isVirtualized) { + refreshViewport(); + } + return; + } + + syncFontScaleIfChanged(); + const wantedSet = new Set(colKeys); + syncTableHeaderColumns(colKeys, { stepTokenComboFormat: normTokenFmt }); + + const showAgentBadge = Boolean(hasSubagents && showStepAgentBadge); + const cellCtx = { + hasSubagents, + showAgentBadge, + showStepSpeedColor, + stepTokenComboFormat: normTokenFmt, + effectiveScopes, + scopeSigKey: effectiveScopes.join(','), + displaySettings, + onSelectAgentScopes, + }; + + const useRootTurn = Boolean(hasSubagents && isMergedMultiAgents); + let railActive = false; + if (showStepTurnRail) { + for (let i = 0; i < tableSteps.length; i++) { + const st = tableSteps[i]; + const tIdx = useRootTurn ? (st?.rootTurnIndex ?? st?.turnIndex) : st?.turnIndex; + if (Number.isInteger(tIdx) && tIdx > 0) { + railActive = true; + break; + } + } + } + if (!railActive) { + hideTurnTip(); + } + + const isVirtualized = !standalone && tableSteps.length > VIRTUAL_ROW_THRESHOLD; + patchClasses(stepsTableEl, { + 'has-turn-rail': railActive, + 'is-virtualized': isVirtualized, + }); + + let hasReasonFlags = null; + let hasAnyReason = false; + let rowTops = null; + let totalBodyH = 0; + let sizerSpec = null; + if (isVirtualized) { + const hasTpsCol = wantedSet.has('tps'); + if (hasTpsCol) { + hasReasonFlags = new Uint8Array(tableSteps.length); + for (let i = 0; i < tableSteps.length; i++) { + const rawReason = tableSteps[i]?.selectedSpeedReason; + if (rawReason && speedReasonText(rawReason)) { + hasReasonFlags[i] = 1; + hasAnyReason = true; + } + } + } + const built = buildRowTops(tableSteps.length, hasReasonFlags); + rowTops = built.rowTops; + totalBodyH = built.totalBodyH; + sizerSpec = buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx); + } + + activeDataset = { + tableSteps, + cascadeId, + colKeys, + wantedSet, + colOrderSig, + locale, + cellCtx, + railActive, + showAgentBadge, + showStepTurnRail, + useRootTurn, + isVirtualized, + hasReasonFlags, + hasAnyReason, + rowTops, + totalBodyH, + sizerSpec, + effectiveScopes, + formattedPrompts: new Map(), + }; + renderedSliceStart = -1; + renderedSliceEnd = -1; + renderedTopSpacerH = -1; + renderedBottomSpacerH = -1; + + renderCurrentWindow({ force: true, enteringRowKeys }); lastRenderOptions = renderOptions; lastRenderedRows = tableSteps; } onCleanup(() => { - stepsTablePane.removeEventListener('scroll', hideTurnTip); + stepsTablePane.removeEventListener('scroll', onPaneScroll); stepsTbody.removeEventListener('mouseleave', hideTurnTip); + if (scrollRafId && typeof cancelAnimationFrame === 'function') { + cancelAnimationFrame(scrollRafId); + scrollRafId = 0; + } + if (calibrateRafId && typeof cancelAnimationFrame === 'function') { + cancelAnimationFrame(calibrateRafId); + calibrateRafId = 0; + } + paneResizeObs?.disconnect(); + paneResizeObs = null; + rowPool.length = 0; for (const tr of [...activeEnterTimers.keys()]) { clearRowEnterState(tr); } @@ -14539,6 +15550,7 @@ const StepTableWidget = defineComponent({ turnTipEl, syncTableHeaderColumns, renderStepTable, + refreshViewport, hideTurnTip, setBoundsElGetter, }, @@ -20325,8 +21337,10 @@ const StepsDetailView = defineComponent({ }); // --- 子视图 1:单步明细表(委托给可复用的 `StepTableWidget` 解耦组件) --- + let stepsScroll = null; const stepTableWidget = StepTableWidget({ onSelectAgentScopes: applyAgentScopesSelection, + onVirtualHeightChange: () => stepsScroll?.refresh(), }); const { stepsTablePane, @@ -20337,8 +21351,9 @@ const StepsDetailView = defineComponent({ hideTurnTip, syncTableHeaderColumns, renderStepTable, + refreshViewport: refreshStepTableViewport, } = stepTableWidget.refs; - const stepsScroll = CustomScrollbar({ + stepsScroll = CustomScrollbar({ contentEl: stepsTablePane, className: 'table-scroll-host', }); @@ -20497,6 +21512,19 @@ const StepsDetailView = defineComponent({ let latestSlice = null; let isDirty = false; + let cachedChronoSrc = null; + let cachedChronoMerged = false; + let cachedChronoOut = []; + + function getMemoizedChronoSteps(steps, isMergedMultiAgents) { + if (cachedChronoSrc === steps && cachedChronoMerged === isMergedMultiAgents) { + return cachedChronoOut; + } + cachedChronoSrc = steps; + cachedChronoMerged = isMergedMultiAgents; + cachedChronoOut = toChronologicalSteps(steps, isMergedMultiAgents); + return cachedChronoOut; + } function resolveDefaultActiveModelKey(scopedConv, chronoSteps, models, availableModelKeys) { if (scopedConv?.hasKnownModel !== false) { @@ -20683,33 +21711,14 @@ const StepsDetailView = defineComponent({ const showAgentPrefix = isMergedMultiAgents; const showModels = uiSt.stepsSubTab === 'models'; - const chronoSteps = toChronologicalSteps(steps, isMergedMultiAgents); - - const stepTtftFallbackMap = new Map(); - const stepModelOptionMap = new Map(); - for (const st of chronoSteps) { - const gk = getStepModelGroupKey(st); - if (!stepModelOptionMap.has(gk)) { - const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk }); - stepModelOptionMap.set(gk, { - label: disp.baseText || disp.text || gk, - calls: 0, - }); - } - stepModelOptionMap.get(gk).calls += 1; - - if (showModels && !st.isCompactionStep && Number.isFinite(st.ttftSec) && st.ttftSec >= 0) { - const prev = stepTtftFallbackMap.get(gk) || { sum: 0, count: 0 }; - prev.sum += Number(st.ttftSec); - prev.count += 1; - stepTtftFallbackMap.set(gk, prev); - } - } const availableModelKeys = new Set(); const modelColorByGroup = new Map(); const perModelOptions = []; + let breakdownCalls = 0; for (const m of models) { + if (!m || typeof m !== 'object') continue; + breakdownCalls += Math.max(0, Number(m.calls || 0)); const gk = getStepModelGroupKey(m); if (availableModelKeys.has(gk)) continue; availableModelKeys.add(gk); @@ -20727,18 +21736,35 @@ const StepsDetailView = defineComponent({ meta: t('header.convMetaSteps', { count: Number(m.calls || 0) }), }); } - for (const [gk, info] of stepModelOptionMap.entries()) { - if (!availableModelKeys.has(gk)) { - availableModelKeys.add(gk); - modelColorByGroup.set( - gk, - MODEL_COLOR_VARS[(availableModelKeys.size - 1) % MODEL_COLOR_VARS.length] - ); - perModelOptions.push({ - value: gk, - label: info.label, - meta: t('header.convMetaSteps', { count: info.calls }), - }); + + const needStepModelFallback = + steps.length > 0 && (models.length === 0 || breakdownCalls < steps.length); + if (needStepModelFallback) { + const stepModelOptionMap = new Map(); + for (const st of steps) { + const gk = getStepModelGroupKey(st); + if (!stepModelOptionMap.has(gk)) { + const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk }); + stepModelOptionMap.set(gk, { + label: disp.baseText || disp.text || gk, + calls: 0, + }); + } + stepModelOptionMap.get(gk).calls += 1; + } + for (const [gk, info] of stepModelOptionMap.entries()) { + if (!availableModelKeys.has(gk)) { + availableModelKeys.add(gk); + modelColorByGroup.set( + gk, + MODEL_COLOR_VARS[(availableModelKeys.size - 1) % MODEL_COLOR_VARS.length] + ); + perModelOptions.push({ + value: gk, + label: info.label, + meta: t('header.convMetaSteps', { count: info.calls }), + }); + } } } @@ -20814,6 +21840,23 @@ const StepsDetailView = defineComponent({ allowNewRowFade: shouldAnimateNewRows, }); stepsScroll.refresh(); + fitPinnedWhileVisible = false; + return; + } + + const chronoSteps = getMemoizedChronoSteps(steps, isMergedMultiAgents); + const stepTtftFallbackMap = new Map(); + const needTtftFallback = models.some((m) => m && m.avgTtftSec == null); + if (needTtftFallback) { + for (const st of chronoSteps) { + if (!st.isCompactionStep && Number.isFinite(st.ttftSec) && st.ttftSec >= 0) { + const gk = getStepModelGroupKey(st); + const prev = stepTtftFallbackMap.get(gk) || { sum: 0, count: 0 }; + prev.sum += Number(st.ttftSec); + prev.count += 1; + stepTtftFallbackMap.set(gk, prev); + } + } } // 2. 顶部“会话走势”更新 @@ -20833,15 +21876,11 @@ const StepsDetailView = defineComponent({ ? ['__all__'] : Array.from(new Set(fitLockedModelKeys.filter((k) => availableModelKeys.has(k)))); - if (!showModels) { - fitPinnedWhileVisible = false; - } if ((!fitPinnedWhileVisible && !fitUserPicked) || sanitizedLocked.length === 0) { fitLockedModelKeys = [defaultActiveModelKey]; } else { fitLockedModelKeys = sanitizedLocked; } - if (!showModels) return; if (availableModelKeys.size > 0) fitPinnedWhileVisible = true; patchAttr(lineModelSelect.el, 'hidden', !hasMultipleModels); @@ -21114,6 +22153,7 @@ const StepsDetailView = defineComponent({ if (getVisibleMonitorView() === 'steps' && latestSlice) { renderStepsData(latestSlice); } else if (tab === 'steps') { + refreshStepTableViewport(); stepsScroll.refresh(); } else { modelsScroll.refresh(); @@ -21238,6 +22278,7 @@ const StepsDetailView = defineComponent({ fitMetricSwitch, stepsScroll, modelsScroll, + refreshStepTableViewport, }, }; }, @@ -21547,6 +22588,7 @@ const App = defineComponent({ } else if (activeView === 'consumption') { consumptionView.refs?.viewScrollbar?.refresh(); } else if (activeView === 'steps') { + stepsView.refs?.refreshStepTableViewport?.(); stepsView.refs?.stepsScroll?.refresh(); stepsView.refs?.modelsScroll?.refresh(); } else if (activeView === 'settings') { @@ -23777,6 +24819,7 @@ function mountWindowOverlay() { } else if (activeView === 'consumption') { refs?.consumptionView?.refs?.viewScrollbar?.refresh(); } else if (activeView === 'steps') { + refs?.stepsView?.refs?.refreshStepTableViewport?.(); refs?.stepsView?.refs?.stepsScroll?.refresh(); refs?.stepsView?.refs?.modelsScroll?.refresh(); } else if (activeView === 'settings') { diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index af4f3ae..e9c6d9f 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/App.js b/sidecars/panel/src/App.js index 1aaddef..0fc4844 100644 --- a/sidecars/panel/src/App.js +++ b/sidecars/panel/src/App.js @@ -119,6 +119,7 @@ export const App = defineComponent({ } else if (activeView === 'consumption') { consumptionView.refs?.viewScrollbar?.refresh(); } else if (activeView === 'steps') { + stepsView.refs?.refreshStepTableViewport?.(); stepsView.refs?.stepsScroll?.refresh(); stepsView.refs?.modelsScroll?.refresh(); } else if (activeView === 'settings') { diff --git a/sidecars/panel/src/components/charts/SessionStepCharts.js b/sidecars/panel/src/components/charts/SessionStepCharts.js index 5739b74..e9bf1ca 100644 --- a/sidecars/panel/src/components/charts/SessionStepCharts.js +++ b/sidecars/panel/src/components/charts/SessionStepCharts.js @@ -327,7 +327,7 @@ export function computePublicationFit( if (sw <= 1e-12) { const fallbackVal = ols.intercept + ols.slope * x0; - return { rawFit: fallbackVal, leverageNormSq: 1 / n, diagHat: 1 / n }; + return { rawFit: fallbackVal, leverageNormSq: 1 / n, diagHat: 1 / n, localHatDiag: 1 / n }; } const mx = swx / sw; @@ -343,6 +343,7 @@ export function computePublicationFit( const useSlope = sxxW > 1e-12; const inverseWeightSum = 1 / sw; const slopeScale = useSlope ? dx0 / sxxW : 0; + const localHatDiag = inverseWeightSum + (useSlope ? (dx0 * dx0) / sxxW : 0); let rawFit = 0; let leverageNormSq = 0; let diagHat = 0; @@ -356,21 +357,53 @@ export function computePublicationFit( if (j === diagIdx) diagHat = lj; } - return { rawFit, leverageNormSq, diagHat }; + return { rawFit, leverageNormSq, diagHat, localHatDiag }; } const rawSampleFits = new Float64Array(n); const sampleLevSq = new Float64Array(n); let sse = 0; let traceL = 0; + let precomputedGridEval = null; - for (let i = 0; i < n; i++) { - const res = evalLoessPoint(xs[i], i); - rawSampleFits[i] = res.rawFit; - sampleLevSq[i] = res.leverageNormSq; - traceL += res.diagHat; - const diff = ys[i] - res.rawFit; - sse += diff * diff; + // 大样本(n > 200 且 x 单调有序)采用与 R `stats::loess(surface = "interpolate")` 一致的网格插值加速: + // 仅在 M 个均匀网格顶点做精确 LOESS(O(M·N)),再线性插值样本拟合值与杠杆度,避免 O(N²) 阻塞主线程。 + if (n > 200 && sortedXs && M >= 2) { + const gridRawFit = new Float64Array(M); + const gridLevSq = new Float64Array(M); + const gridHatDiag = new Float64Array(M); + for (let k = 0; k < M; k++) { + const res = evalLoessPoint(gridXs[k], -1); + gridRawFit[k] = res.rawFit; + gridLevSq[k] = res.leverageNormSq; + gridHatDiag[k] = res.localHatDiag; + } + precomputedGridEval = { gridRawFit, gridLevSq }; + + const invSpan = (M - 1) / xSpan; + const maxK0 = M - 2; + for (let i = 0; i < n; i++) { + const u = (xs[i] - xMin) * invSpan; + const k0 = u <= 0 ? 0 : u >= maxK0 ? maxK0 : Math.floor(u); + const frac = Math.max(0, Math.min(1, u - k0)); + const rf = gridRawFit[k0] + frac * (gridRawFit[k0 + 1] - gridRawFit[k0]); + const ls = Math.max(0, gridLevSq[k0] + frac * (gridLevSq[k0 + 1] - gridLevSq[k0])); + const hd = gridHatDiag[k0] + frac * (gridHatDiag[k0 + 1] - gridHatDiag[k0]); + rawSampleFits[i] = rf; + sampleLevSq[i] = ls; + traceL += hd; + const diff = ys[i] - rf; + sse += diff * diff; + } + } else { + for (let i = 0; i < n; i++) { + const res = evalLoessPoint(xs[i], i); + rawSampleFits[i] = res.rawFit; + sampleLevSq[i] = res.leverageNormSq; + traceL += res.diagHat; + const diff = ys[i] - res.rawFit; + sse += diff * diff; + } } const dfRes = Math.max(1, n - traceL); @@ -394,16 +427,27 @@ export function computePublicationFit( clampedSse += d * d; } - const grid = gridXs.map((gx) => { - const res = evalLoessPoint(gx, -1); - const half = tCrit * sigmaHat * Math.sqrt(res.leverageNormSq); - return { - x: gx, - fit: clampValue(res.rawFit, minVal, maxVal), - ciLow: clampValue(res.rawFit - half, minVal, maxVal), - ciHigh: clampValue(res.rawFit + half, minVal, maxVal), - }; - }); + const grid = precomputedGridEval + ? gridXs.map((gx, k) => { + const rf = precomputedGridEval.gridRawFit[k]; + const half = tCrit * sigmaHat * Math.sqrt(Math.max(0, precomputedGridEval.gridLevSq[k])); + return { + x: gx, + fit: clampValue(rf, minVal, maxVal), + ciLow: clampValue(rf - half, minVal, maxVal), + ciHigh: clampValue(rf + half, minVal, maxVal), + }; + }) + : gridXs.map((gx) => { + const res = evalLoessPoint(gx, -1); + const half = tCrit * sigmaHat * Math.sqrt(res.leverageNormSq); + return { + x: gx, + fit: clampValue(res.rawFit, minVal, maxVal), + ciLow: clampValue(res.rawFit - half, minVal, maxVal), + ciHigh: clampValue(res.rawFit + half, minVal, maxVal), + }; + }); const r2Loess = syy > 1e-12 ? clampValue(1 - clampedSse / syy, 0, 1) : 1; @@ -1659,14 +1703,19 @@ export function createModelFitChart() { const rect = svg.getBoundingClientRect(); if (!rect || rect.width <= 0) return; const relX = ((e.clientX - rect.left) / rect.width) * viewW; - let bestIdx = 0; - let bestDist = Math.abs(currentSamples[0].x - relX); - for (let i = 1; i < currentSamples.length; i++) { - const d = Math.abs(currentSamples[i].x - relX); - if (d < bestDist) { - bestDist = d; - bestIdx = i; - } + let lo = 0; + let hi = currentSamples.length - 1; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + if (currentSamples[mid].x < relX) lo = mid + 1; + else hi = mid; + } + let bestIdx = lo; + if ( + lo > 0 && + Math.abs(currentSamples[lo - 1].x - relX) <= Math.abs(currentSamples[lo].x - relX) + ) { + bestIdx = lo - 1; } showHoverAt(bestIdx); }); @@ -2080,16 +2129,28 @@ export function createModelFitChart() { const dotRadius = combinedSamples.length > 80 ? '1.8' : combinedSamples.length > 36 ? '2.1' : '2.4'; + const dedupOverdraw = combinedSamples.length > 200; + const scatterTarget = + typeof document.createDocumentFragment === 'function' + ? document.createDocumentFragment() + : scatterGroup; for (const s of seriesList) { + const binCounts = dedupOverdraw ? new Map() : null; for (const sp of s.samples) { + if (binCounts) { + const binKey = (Math.round(sp.x * 2) << 11) ^ Math.round(sp.rawY * 2); + const prevCnt = binCounts.get(binKey) || 0; + if (prevCnt >= 6) continue; + binCounts.set(binKey, prevCnt + 1); + } const dot = document.createElementNS(SVG_NS, 'circle'); dot.setAttribute('cx', sp.x.toFixed(1)); dot.setAttribute('cy', sp.rawY.toFixed(1)); dot.setAttribute('r', dotRadius); dot.setAttribute('class', 'sstep-scatter-dot is-multi'); patchStyleVar(dot, '--sstep-fit-accent', s.colorVar); - scatterGroup.appendChild(dot); + scatterTarget.appendChild(dot); } if (s.samples.length === 1) { @@ -2139,6 +2200,9 @@ export function createModelFitChart() { multiCurveGroup.appendChild(curveEl); } } + if (scatterTarget !== scatterGroup) { + scatterGroup.appendChild(scatterTarget); + } while (multiLegendEl.firstChild) multiLegendEl.removeChild(multiLegendEl.firstChild); for (const s of seriesList) { @@ -2271,13 +2335,27 @@ export function createModelFitChart() { // 2. 绘制半透明冷蓝灰实心观测散点(自然呈现局部密度,不抢夺拟合曲线焦点) while (scatterGroup.firstChild) scatterGroup.removeChild(scatterGroup.firstChild); const dotRadius = samples.length > 80 ? '1.8' : samples.length > 36 ? '2.1' : '2.4'; + const binCounts = samples.length > 200 ? new Map() : null; + const scatterTarget = + typeof document.createDocumentFragment === 'function' + ? document.createDocumentFragment() + : scatterGroup; for (const s of samples) { + if (binCounts) { + const binKey = (Math.round(s.x * 2) << 11) ^ Math.round(s.rawY * 2); + const prevCnt = binCounts.get(binKey) || 0; + if (prevCnt >= 6) continue; + binCounts.set(binKey, prevCnt + 1); + } const dot = document.createElementNS(SVG_NS, 'circle'); dot.setAttribute('cx', s.x.toFixed(1)); dot.setAttribute('cy', s.rawY.toFixed(1)); dot.setAttribute('r', dotRadius); dot.setAttribute('class', 'sstep-scatter-dot'); - scatterGroup.appendChild(dot); + scatterTarget.appendChild(dot); + } + if (scatterTarget !== scatterGroup) { + scatterGroup.appendChild(scatterTarget); } // 3. 绘制 95% CI 置信带闭合多边形与回归拟合曲线(绝不向底部 X 轴填充面积!) diff --git a/sidecars/panel/src/components/layout/WindowOverlayShell.js b/sidecars/panel/src/components/layout/WindowOverlayShell.js index f187404..2bcdc64 100644 --- a/sidecars/panel/src/components/layout/WindowOverlayShell.js +++ b/sidecars/panel/src/components/layout/WindowOverlayShell.js @@ -2203,6 +2203,7 @@ export function mountWindowOverlay() { } else if (activeView === 'consumption') { refs?.consumptionView?.refs?.viewScrollbar?.refresh(); } else if (activeView === 'steps') { + refs?.stepsView?.refs?.refreshStepTableViewport?.(); refs?.stepsView?.refs?.stepsScroll?.refresh(); refs?.stepsView?.refs?.modelsScroll?.refresh(); } else if (activeView === 'settings') { diff --git a/sidecars/panel/src/components/ui/CustomScrollbar.js b/sidecars/panel/src/components/ui/CustomScrollbar.js index 435ddfe..b1c80fd 100644 --- a/sidecars/panel/src/components/ui/CustomScrollbar.js +++ b/sidecars/panel/src/components/ui/CustomScrollbar.js @@ -34,6 +34,7 @@ export const CustomScrollbar = defineComponent({ let isDragging = false; let dragStartY = 0; let dragStartScrollTop = 0; + let scrollRafId = 0; function syncThumb() { const scrollHeight = Number(contentEl.scrollHeight || 0); @@ -60,7 +61,15 @@ export const CustomScrollbar = defineComponent({ } function onContentScroll() { - syncThumb(); + if (isDragging || typeof requestAnimationFrame !== 'function') { + syncThumb(); + return; + } + if (scrollRafId) return; + scrollRafId = requestAnimationFrame(() => { + scrollRafId = 0; + syncThumb(); + }); } function onDocMouseMove(e) { @@ -115,7 +124,7 @@ export const CustomScrollbar = defineComponent({ syncThumb(); }); - contentEl.addEventListener('scroll', onContentScroll); + contentEl.addEventListener('scroll', onContentScroll, { passive: true }); hostEl.addEventListener('mouseenter', syncThumb); let resizeObserver = null; @@ -129,6 +138,10 @@ export const CustomScrollbar = defineComponent({ onCleanup(() => { onDocMouseUp(); + if (scrollRafId && typeof cancelAnimationFrame === 'function') { + cancelAnimationFrame(scrollRafId); + scrollRafId = 0; + } contentEl.removeEventListener('scroll', onContentScroll); hostEl.removeEventListener('mouseenter', syncThumb); if (resizeObserver) { diff --git a/sidecars/panel/src/components/widgets/StepTableWidget.js b/sidecars/panel/src/components/widgets/StepTableWidget.js index e114a2b..c68d727 100644 --- a/sidecars/panel/src/components/widgets/StepTableWidget.js +++ b/sidecars/panel/src/components/widgets/StepTableWidget.js @@ -13,6 +13,7 @@ import { patchKeyedList, patchText, } from '../../core/domPatch.js'; +import { resolveModelDisplayInfo, speedReasonText } from '../../core/formatters.js'; import { getEffectiveLocale, t } from '../../i18n/index.js'; import { DEFAULT_STEP_COLUMN_KEYS, @@ -24,6 +25,7 @@ import { getAgentBadgeClass, normalizeClientStepTokenComboFormat, } from '../../store/telemetryStore.js'; +import { parseStepTokenComboSegments } from '../../../shared/settings-normalization.mjs'; export function formatTurnPromptText(rawPrompt, { hasMedia = false, mediaOnly = false } = {}) { const text = String(rawPrompt || '').trim(); @@ -32,6 +34,341 @@ export function formatTurnPromptText(rawPrompt, { hasMedia = false, mediaOnly = return hasMedia ? `${text} ${t('steps.turnMediaSuffix')}` : text; } +const VIRTUAL_ROW_THRESHOLD = 80; +const VIRTUAL_OVERSCAN_ROWS = 16; +const VIRTUAL_REFILL_MARGIN = 6; +const MAX_ROW_POOL_SIZE = 96; +const FALLBACK_VIEWPORT_H = 560; +const BASE_SINGLE_ROW_H = 28; +const BASE_REASON_ROW_H = 42; +const SIZER_ROW_KEY = '__vsizer__'; +const SPACER_TOP_KEY = '__vspacer_top__'; +const SPACER_BOTTOM_KEY = '__vspacer_bottom__'; + +function estTokenChars(val) { + const n = Math.max(0, Number(val || 0)); + if (n >= 1_000_000) return n >= 10_000_000 ? 6 : 5; + if (n >= 100_000) return 6; + if (n >= 10_000) return 5; + if (n >= 1_000) return 4; + if (n >= 100) return 3; + if (n >= 10) return 2; + return 1; +} + +function estCostChars(val) { + const n = Number(val); + if (!Number.isFinite(n) || n <= 0) return 1; + if (n >= 100) return 7; + if (n >= 10) return 6; + if (n >= 0.01) return 5; + return 7; +} + +function estSegmentChars(seg, st) { + const inTok = Math.max(0, Number(st?.inputTokens || 0)); + const cacheTok = Math.max(0, Number(st?.cacheReadTokens || 0)); + const outTok = Math.max(0, Number(st?.outputTokens || 0)); + const thinkTok = Math.max(0, Number(st?.thinkingTokens || 0)); + const respTok = + st?.responseTokens != null + ? Math.max(0, Number(st.responseTokens)) + : Math.max(0, outTok - thinkTok); + switch (seg) { + case 'context': + return estTokenChars(st?.contextTokens ?? inTok + cacheTok + outTok); + case 'in': + return estTokenChars(inTok); + case 'out': + return estTokenChars(outTok); + case 'cache': + return estTokenChars(cacheTok); + case 'think': + return estTokenChars(thinkTok); + case 'reply': + return estTokenChars(respTok); + case 'total': + default: + return estTokenChars(inTok + cacheTok + outTok); + } +} + +function resolveBadgeTextForStep(st) { + return formatAgentBadgeText({ + agentKind: + st?.agentKind || + (!st?.isSubagent ? 'main' : st?.isSideQuestion ? 'side_question' : 'subagent'), + agentOrdinal: + st?.agentOrdinal || (st?.isSideQuestion ? st?.sideIndex || 0 : st?.agentIndex || 0), + isMain: !st?.isSubagent, + isSideQuestion: Boolean(st?.isSideQuestion), + sideIndex: st?.sideIndex || 0, + index: st?.agentIndex || 0, + badgeText: st?.agentBadge, + }); +} + +function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) { + const firstStep = tableSteps[0] || {}; + const colSteps = {}; + const needStep = wantedSet.has('step'); + const needTime = wantedSet.has('time'); + const needModel = wantedSet.has('model'); + const needTps = wantedSet.has('tps'); + const needTtft = wantedSet.has('ttft'); + const needDuration = wantedSet.has('duration'); + const needTokensCombo = wantedSet.has('tokens_combo'); + const needTokensIoCache = wantedSet.has('tokens_io_cache'); + const needTokensCustom = wantedSet.has('tokens_custom'); + const needInput = wantedSet.has('input_tokens'); + const needCacheTok = wantedSet.has('cache_tokens'); + const needOutput = wantedSet.has('output_tokens'); + const needCachePct = wantedSet.has('cache'); + const needCost = wantedSet.has('cost'); + const customSegs = needTokensCustom + ? parseStepTokenComboSegments(cellCtx?.stepTokenComboFormat) + : null; + + let bestStepNum = -1; + let bestStepObj = firstStep; + let bestTimeObj = null; + const modelCandidates = needModel ? new Map() : null; + let maxTpsVal = -1; + let maxTpsObj = null; + const reasonCandidates = needTps ? new Set() : null; + let maxTtftVal = -1; + let bestTtftObj = firstStep; + let maxDurVal = -1; + let bestDurObj = firstStep; + let bestComboScore = -1; + let bestComboObj = firstStep; + let bestIoCacheScore = -1; + let bestIoCacheObj = firstStep; + let bestCustomScore = -1; + let bestCustomObj = firstStep; + let maxInputVal = -1; + let bestInputObj = firstStep; + let maxCacheTokVal = -1; + let bestCacheTokObj = firstStep; + let maxOutputVal = -1; + let bestOutputObj = firstStep; + let bestCachePctScore = -1; + let bestCachePctObj = firstStep; + let bestCostScore = -1; + let bestCostObj = firstStep; + + let bestBadgeText = ''; + let bestBadgeClass = ''; + const badgeCandidates = cellCtx?.showAgentBadge ? new Set() : null; + + for (let i = 0; i < tableSteps.length; i++) { + const st = tableSteps[i]; + if (!st || typeof st !== 'object') continue; + + if (badgeCandidates) { + const bKey = `${st.agentKind || ''}|${st.isSubagent ? 1 : 0}|${st.isSideQuestion ? 1 : 0}|${st.agentOrdinal || 0}|${st.sideIndex || 0}|${st.agentIndex || 0}|${st.agentBadge || ''}`; + if (!badgeCandidates.has(bKey)) { + badgeCandidates.add(bKey); + const text = resolveBadgeTextForStep(st); + if (text.length > bestBadgeText.length) { + bestBadgeText = text; + bestBadgeClass = getAgentBadgeClass(st.agentIndex || 0, !st.isSubagent); + } + } + } + + if (needStep) { + const idxNum = Number(st.stepIndex) || 0; + if (idxNum > bestStepNum) { + bestStepNum = idxNum; + bestStepObj = st; + } + } + + if (needTime && !bestTimeObj && Number(st.createdAtMs || 0) > 0) { + bestTimeObj = st; + } + + if (modelCandidates) { + const mKey = `${st.baseModelShort || st.modelShort || ''}|${st.baseModelLabel || st.modelLabel || ''}|${st.rawModel || ''}|${st.isCompactionStep ? 1 : 0}`; + if (!modelCandidates.has(mKey)) { + modelCandidates.set(mKey, st); + } + } + + if (needTps) { + const tpsVal = Number(st.tokPerSec); + if (Number.isFinite(tpsVal) && tpsVal > maxTpsVal) { + maxTpsVal = tpsVal; + maxTpsObj = st; + } + if (st.selectedSpeedReason) { + reasonCandidates.add(st.selectedSpeedReason); + } + } + + if (needTtft) { + const v = Number(st.ttftSec); + if (Number.isFinite(v) && v > maxTtftVal) { + maxTtftVal = v; + bestTtftObj = st; + } + } + + if (needDuration) { + const v = Number(st.totalDurationSec ?? st.streamDurationSec); + if (Number.isFinite(v) && v > maxDurVal) { + maxDurVal = v; + bestDurObj = st; + } + } + + if (needTokensCombo) { + const inTok = Math.max(0, Number(st.inputTokens || 0)); + const cacheTok = Math.max(0, Number(st.cacheReadTokens || 0)); + const outTok = Math.max(0, Number(st.outputTokens || 0)); + const thinkTok = Math.max(0, Number(st.thinkingTokens || 0)); + const respTok = + st.responseTokens != null + ? Math.max(0, Number(st.responseTokens)) + : Math.max(0, outTok - thinkTok); + const ctxTok = Math.max(0, Number(st.contextTokens ?? inTok + cacheTok + outTok)); + const score = + (estTokenChars(ctxTok) + estTokenChars(thinkTok) + estTokenChars(respTok)) * 1e9 + + ctxTok; + if (score > bestComboScore) { + bestComboScore = score; + bestComboObj = st; + } + } + + if (needTokensIoCache) { + const inTok = Math.max(0, Number(st.inputTokens || 0)); + const outTok = Math.max(0, Number(st.outputTokens || 0)); + const cacheTok = Math.max(0, Number(st.cacheReadTokens || 0)); + const score = + (estTokenChars(inTok) + estTokenChars(outTok) + estTokenChars(cacheTok)) * 1e9 + + cacheTok; + if (score > bestIoCacheScore) { + bestIoCacheScore = score; + bestIoCacheObj = st; + } + } + + if (needTokensCustom && customSegs) { + let chars = 0; + for (let s = 0; s < customSegs.length; s++) { + chars += estSegmentChars(customSegs[s], st); + } + if (chars > bestCustomScore) { + bestCustomScore = chars; + bestCustomObj = st; + } + } + + if (needInput) { + const v = Math.max(0, Number(st.inputTokens || 0)); + const score = estTokenChars(v) * 1e9 + v; + if (score > maxInputVal) { + maxInputVal = score; + bestInputObj = st; + } + } + + if (needCacheTok) { + const v = Math.max(0, Number(st.cacheReadTokens || 0)); + const score = estTokenChars(v) * 1e9 + v; + if (score > maxCacheTokVal) { + maxCacheTokVal = score; + bestCacheTokObj = st; + } + } + + if (needOutput) { + const v = Math.max(0, Number(st.outputTokens || 0)); + const score = estTokenChars(v) * 1e9 + v; + if (score > maxOutputVal) { + maxOutputVal = score; + bestOutputObj = st; + } + } + + if (needCachePct) { + const pct = Number(st.cacheHitPct ?? 0); + const hasDec = pct > 0 && pct < 100 && Math.abs(pct - Math.round(pct)) > 1e-6; + const score = pct >= 100 ? 4 : hasDec ? (pct >= 10 ? 5 : 4) : pct >= 10 ? 3 : 2; + if (score > bestCachePctScore) { + bestCachePctScore = score; + bestCachePctObj = st; + } + } + + if (needCost) { + const c = Number(st.costUsd); + const score = estCostChars(c) * 1e6 + (Number.isFinite(c) && c > 0 ? c : 0); + if (score > bestCostScore) { + bestCostScore = score; + bestCostObj = st; + } + } + } + + if (needStep) colSteps.step = bestStepObj; + if (needTime) colSteps.time = bestTimeObj || firstStep; + if (needModel && modelCandidates) { + let bestModelLen = -1; + let bestModelObj = firstStep; + for (const cand of modelCandidates.values()) { + const disp = resolveModelDisplayInfo(cand, cellCtx?.displaySettings, { fallback: '—' }); + const len = (disp.baseText?.length || 0) + (disp.compactionSuffix?.length || 0); + if (len > bestModelLen) { + bestModelLen = len; + bestModelObj = cand; + } + } + colSteps.model = bestModelObj; + } + if (needTps) { + let longestReasonKey = null; + let longestReasonLen = 0; + if (reasonCandidates) { + for (const rk of reasonCandidates) { + const txt = speedReasonText(rk); + if (txt && txt.length > longestReasonLen) { + longestReasonLen = txt.length; + longestReasonKey = rk; + } + } + } + colSteps.tps = { + ...(maxTpsObj || firstStep), + tokPerSec: maxTpsVal > 0 ? maxTpsVal : firstStep.tokPerSec, + selectedSpeedReason: longestReasonKey, + }; + } + if (needTtft) colSteps.ttft = bestTtftObj; + if (needDuration) colSteps.duration = bestDurObj; + if (needTokensCombo) colSteps.tokens_combo = bestComboObj; + if (needTokensIoCache) colSteps.tokens_io_cache = bestIoCacheObj; + if (needTokensCustom) colSteps.tokens_custom = bestCustomObj; + if (needInput) colSteps.input_tokens = bestInputObj; + if (needCacheTok) colSteps.cache_tokens = bestCacheTokObj; + if (needOutput) colSteps.output_tokens = bestOutputObj; + if (needCachePct) colSteps.cache = bestCachePctObj; + if (needCost) colSteps.cost = bestCostObj; + + const sigParts = colKeys.map((colKey) => { + const st = colSteps[colKey] || firstStep; + return `${colKey}=${STEP_COLUMN_REGISTRY[colKey].sigPart(st, cellCtx)}`; + }); + return { + colSteps, + badgeText: bestBadgeText, + badgeClass: bestBadgeClass, + sig: `sizer:${bestBadgeText}:${sigParts.join('|')}`, + }; +} + export const StepTableWidget = defineComponent({ name: 'StepTableWidget', setup({ props, onCleanup }) { @@ -39,8 +376,11 @@ export const StepTableWidget = defineComponent({ const interactiveBadges = props.interactiveBadges !== false; const onSelectAgentScopes = typeof props.onSelectAgentScopes === 'function' ? props.onSelectAgentScopes : null; + const onVirtualHeightChange = + typeof props.onVirtualHeightChange === 'function' ? props.onVirtualHeightChange : null; const stepsTheadRow = h('tr'); + const stepsThead = h('thead', {}, [stepsTheadRow]); const stepsTbody = h('tbody'); function syncTableHeaderColumns(colKeys, headerCtx = {}) { @@ -63,7 +403,7 @@ export const StepTableWidget = defineComponent({ syncTableHeaderColumns(DEFAULT_STEP_COLUMN_KEYS); const stepsTableEl = h('table', { className: 'data-table steps-data-table' }, [ - h('thead', {}, [stepsTheadRow]), + stepsThead, stepsTbody, ]); const stepsTablePane = h('div', { className: 'table-viewport is-step-table' }, [stepsTableEl]); @@ -126,16 +466,98 @@ export const StepTableWidget = defineComponent({ } } - stepsTablePane.addEventListener('scroll', hideTurnTip); - stepsTbody.addEventListener('mouseleave', hideTurnTip); const hoverRows = new WeakMap(); let lastRenderedRows = null; let lastRenderOptions = ''; let trackedCascadeId = null; + let lastAbsorbedAllSteps = null; const seenStepKeys = new Set(); const maxSeenStepByAgent = new Map(); const activeEnterTimers = new Map(); + // Virtualization state (activates transparently only when !standalone && rowCount > 80) + let activeDataset = null; + let renderedSliceStart = -1; + let renderedSliceEnd = -1; + let renderedTopSpacerH = -1; + let renderedBottomSpacerH = -1; + let scrollRafId = 0; + let calibrateRafId = 0; + let lastFontScale = 1; + let calibratedSingleRowH = 0; + let calibratedReasonRowH = 0; + const rowPool = []; + + function readUiFontScale() { + try { + if (typeof getComputedStyle === 'function') { + const target = + stepsTableEl || (typeof document !== 'undefined' ? document.documentElement : null); + if (target) { + const raw = getComputedStyle(target)?.getPropertyValue?.('--ui-font-scale'); + const parsed = Number.parseFloat(raw); + if (Number.isFinite(parsed) && parsed >= 0.5 && parsed <= 2.5) { + return parsed; + } + } + } + } catch { + // Fallback to default scale in headless/mock environments. + } + return 1; + } + + function getEstRowHeights() { + const single = + calibratedSingleRowH > 0 + ? calibratedSingleRowH + : Math.round(BASE_SINGLE_ROW_H * lastFontScale); + const reason = + calibratedReasonRowH > 0 + ? calibratedReasonRowH + : Math.round(BASE_REASON_ROW_H * lastFontScale); + return { single, reason }; + } + + function buildRowTops(n, hasReasonFlags) { + const { single, reason } = getEstRowHeights(); + const tops = new Float64Array(n + 1); + let acc = 0; + for (let i = 0; i < n; i++) { + tops[i] = acc; + acc += hasReasonFlags && hasReasonFlags[i] ? reason : single; + } + tops[n] = acc; + return { rowTops: tops, totalBodyH: acc }; + } + + function findRowIndexAtOffset(rowTops, n, offset) { + if (n <= 0 || offset <= 0) return 0; + if (offset >= rowTops[n - 1]) return n - 1; + let lo = 0; + let hi = n - 1; + while (lo < hi) { + const mid = (lo + hi + 1) >>> 1; + if (rowTops[mid] <= offset) lo = mid; + else hi = mid - 1; + } + return lo; + } + + function syncFontScaleIfChanged() { + const nextScale = readUiFontScale(); + if (Math.abs(nextScale - lastFontScale) < 0.005) return false; + lastFontScale = nextScale; + calibratedSingleRowH = 0; + calibratedReasonRowH = 0; + if (activeDataset?.isVirtualized) { + const rebuilt = buildRowTops(activeDataset.tableSteps.length, activeDataset.hasReasonFlags); + activeDataset.rowTops = rebuilt.rowTops; + activeDataset.totalBodyH = rebuilt.totalBodyH; + } + return true; + } + function getStepRowIdentity(st, fallbackCascadeId) { const agentKey = String(st?.agentCascadeId || fallbackCascadeId || 'conv'); const stepNum = Number(st?.stepIndex); @@ -194,80 +616,185 @@ export const StepTableWidget = defineComponent({ cell.onmouseleave = null; } - function renderStepTable( - tableSteps, - cascadeId, - colKeys, - locale, - { - effectiveScopes = ['all'], - hasSubagents = false, - isMergedMultiAgents = false, - showStepTurnRail = false, - showStepAgentBadge = true, - showStepSpeedColor = false, - stepTokenComboFormat = undefined, - displaySettings = {}, - allConversationSteps = null, - allowNewRowFade = false, - } = {} - ) { - const normCascadeId = String(cascadeId || ''); - let enteringRowKeys = null; - if (!normCascadeId || trackedCascadeId === null || normCascadeId !== trackedCascadeId) { - trackedCascadeId = normCascadeId || null; - seenStepKeys.clear(); - maxSeenStepByAgent.clear(); - absorbStepsIntoBaseline(allConversationSteps, normCascadeId); - absorbStepsIntoBaseline(tableSteps, normCascadeId); - } else if (!allowNewRowFade || standalone) { - absorbStepsIntoBaseline(allConversationSteps, normCascadeId); - absorbStepsIntoBaseline(tableSteps, normCascadeId); - } else { - for (const st of tableSteps) { - if (!st || typeof st !== 'object') continue; - const { agentKey, stepNum, rowKey } = getStepRowIdentity(st, normCascadeId); - if (!seenStepKeys.has(rowKey)) { - const prevMax = maxSeenStepByAgent.get(agentKey); - if (prevMax === undefined || !Number.isFinite(stepNum) || stepNum > prevMax) { - enteringRowKeys ??= new Set(); - enteringRowKeys.add(rowKey); + function calibrateRowHeights() { + calibrateRafId = 0; + if (!activeDataset?.isVirtualized) return; + if (Number(stepsTablePane.clientHeight || 0) <= 0) return; + const needSingle = calibratedSingleRowH <= 0; + const needReason = calibratedReasonRowH <= 0 && activeDataset.hasAnyReason; + if (!needSingle && !needReason) return; + + let measuredSingle = 0; + let measuredReason = 0; + // Measure contiguous run of normal rows to eliminate single-row subpixel/border-collapse drift. + let runStartTop = 0; + let runEndBottom = 0; + let runCount = 0; + let bestRunStride = 0; + let bestRunCount = 0; + + const children = stepsTbody.children || []; + for (let i = 0; i < children.length; i++) { + const tr = children[i]; + if (!tr || tr.classList?.contains('step-vspacer') || tr.classList?.contains('step-vsizer')) { + runCount = 0; + continue; + } + const isReason = tr.dataset?.hasReason === '1'; + if (!isReason && needSingle) { + const rect = tr.getBoundingClientRect?.(); + const hVal = Number(rect?.height || tr.offsetHeight || 0); + if (hVal >= 14 && hVal <= 120) { + if (!measuredSingle) measuredSingle = hVal; + if (rect && Number.isFinite(rect.top) && Number.isFinite(rect.bottom) && rect.bottom > rect.top) { + if (runCount === 0) { + runStartTop = rect.top; + } + runEndBottom = rect.bottom; + runCount += 1; + if (runCount > bestRunCount && runCount >= 2) { + const stride = (runEndBottom - runStartTop) / runCount; + if (stride >= 14 && stride <= 120) { + bestRunCount = runCount; + bestRunStride = stride; + } + } } } + } else { + runCount = 0; + if (isReason && needReason && !measuredReason) { + const hVal = Number(tr.getBoundingClientRect?.()?.height || tr.offsetHeight || 0); + if (hVal >= 18 && hVal <= 160) measuredReason = hVal; + } + } + if ((!needSingle || bestRunCount >= 12) && (!needReason || measuredReason > 0)) { + break; } - absorbStepsIntoBaseline(allConversationSteps, normCascadeId); - absorbStepsIntoBaseline(tableSteps, normCascadeId); } - const colOrderSig = colKeys.join(','); - const normTokenFmt = normalizeClientStepTokenComboFormat(stepTokenComboFormat); - const renderOptions = JSON.stringify([ - cascadeId, locale, colOrderSig, effectiveScopes, hasSubagents, isMergedMultiAgents, - showStepTurnRail, showStepAgentBadge, showStepSpeedColor, normTokenFmt, - displaySettings.modelDisplayMode, displaySettings.showUpstreamModel, - displaySettings.orchestratorIdMode, - ]); - if (lastRenderOptions === renderOptions && lastRenderedRows && - (lastRenderedRows === tableSteps || (lastRenderedRows.length === tableSteps.length && - tableSteps.every((step, i) => step === lastRenderedRows[i])))) { - return; + if (bestRunStride > 0) { + measuredSingle = bestRunStride; } - const wantedSet = new Set(colKeys); - syncTableHeaderColumns(colKeys, { stepTokenComboFormat: normTokenFmt }); - const showAgentBadge = Boolean(hasSubagents && showStepAgentBadge); - const cellCtx = { - hasSubagents, + let changed = false; + if (measuredSingle > 0) { + const prev = getEstRowHeights().single; + calibratedSingleRowH = measuredSingle; + if (Math.abs(measuredSingle - prev) >= 0.25) changed = true; + } + if (measuredReason > 0) { + const prev = getEstRowHeights().reason; + calibratedReasonRowH = measuredReason; + if (Math.abs(measuredReason - prev) >= 0.25) changed = true; + } + + if (changed && activeDataset) { + const prevTops = activeDataset.rowTops; + const anchorIdx = renderedSliceStart > 0 ? renderedSliceStart : 0; + const prevAnchorTop = prevTops ? prevTops[anchorIdx] : 0; + const rebuilt = buildRowTops(activeDataset.tableSteps.length, activeDataset.hasReasonFlags); + activeDataset.rowTops = rebuilt.rowTops; + activeDataset.totalBodyH = rebuilt.totalBodyH; + const curScrollTop = Number(stepsTablePane.scrollTop || 0); + if (anchorIdx > 0 && curScrollTop > 0) { + const delta = rebuilt.rowTops[anchorIdx] - prevAnchorTop; + if (Math.abs(delta) >= 0.5) { + stepsTablePane.scrollTop = Math.max(0, curScrollTop + delta); + } + } + renderCurrentWindow({ force: true, enteringRowKeys: null }); + onVirtualHeightChange?.(); + } + } + + function scheduleCalibrateRowHeights() { + if (!activeDataset?.isVirtualized) return; + const needSingle = calibratedSingleRowH <= 0; + const needReason = calibratedReasonRowH <= 0 && activeDataset.hasAnyReason; + if (!needSingle && !needReason) return; + if (calibrateRafId) return; + if (typeof requestAnimationFrame === 'function') { + calibrateRafId = requestAnimationFrame(calibrateRowHeights); + } else { + calibrateRowHeights(); + } + } + + function renderCurrentWindow({ force = false, enteringRowKeys = null } = {}) { + const ds = activeDataset; + if (!ds) return; + const { + tableSteps, + cascadeId, + colKeys, + wantedSet, + colOrderSig, + locale, + cellCtx, + railActive, showAgentBadge, - showStepSpeedColor, - stepTokenComboFormat: normTokenFmt, + showStepTurnRail, + useRootTurn, + isVirtualized, + hasReasonFlags, + rowTops, + totalBodyH, + sizerSpec, effectiveScopes, - scopeSigKey: effectiveScopes.join(','), - displaySettings, - onSelectAgentScopes, - }; + formattedPrompts, + } = ds; + + const n = tableSteps.length; + let startIdx = 0; + let endIdx = n; + let topSpacerH = 0; + let bottomSpacerH = 0; + + if (isVirtualized) { + const scrollTop = Math.max(0, Number(stepsTablePane.scrollTop || 0)); + const rawClientH = Number(stepsTablePane.clientHeight || 0); + const viewportH = rawClientH > 0 ? rawClientH : FALLBACK_VIEWPORT_H; + const rawTheadH = Number( + stepsThead.offsetHeight || stepsThead.getBoundingClientRect?.()?.height || 0 + ); + const theadH = rawTheadH > 0 ? rawTheadH : getEstRowHeights().single; + const viewTop = Math.max(0, scrollTop - theadH); + const viewBottom = viewTop + viewportH; + const firstVis = findRowIndexAtOffset(rowTops, n, viewTop); + const lastVis = findRowIndexAtOffset(rowTops, n, viewBottom); + + if ( + !force && + renderedSliceStart >= 0 && + renderedSliceEnd > renderedSliceStart && + renderedSliceEnd <= n + ) { + const topSafe = + renderedSliceStart === 0 || firstVis - renderedSliceStart >= VIRTUAL_REFILL_MARGIN; + const bottomSafe = + renderedSliceEnd === n || renderedSliceEnd - 1 - lastVis >= VIRTUAL_REFILL_MARGIN; + if (topSafe && bottomSafe) { + return; + } + } + + startIdx = Math.max(0, firstVis - VIRTUAL_OVERSCAN_ROWS); + endIdx = Math.min(n, lastVis + 1 + VIRTUAL_OVERSCAN_ROWS); + topSpacerH = +rowTops[startIdx].toFixed(2); + bottomSpacerH = +Math.max(0, totalBodyH - rowTops[endIdx]).toFixed(2); + + if ( + !force && + startIdx === renderedSliceStart && + endIdx === renderedSliceEnd && + topSpacerH === renderedTopSpacerH && + bottomSpacerH === renderedBottomSpacerH + ) { + return; + } + } - const useRootTurn = Boolean(hasSubagents && isMergedMultiAgents); const getStepTurnIdx = (st) => useRootTurn ? (st?.rootTurnIndex ?? st?.turnIndex) : st?.turnIndex; const getStepIsStart = (st) => @@ -282,12 +809,15 @@ export const StepTableWidget = defineComponent({ Boolean(useRootTurn ? (st?.rootTurnHasMedia ?? st?.turnHasMedia) : st?.turnHasMedia); const getStepMediaOnly = (st) => Boolean(useRootTurn ? (st?.rootTurnMediaOnly ?? st?.turnMediaOnly) : st?.turnMediaOnly); - const turnKeys = showStepTurnRail ? tableSteps.map((st) => { + + function getTurnKeyAt(idx) { + if (!showStepTurnRail || idx < 0 || idx >= n) return ''; + const st = tableSteps[idx]; const tIdx = getStepTurnIdx(st); if (!Number.isInteger(tIdx) || tIdx <= 0) return ''; return useRootTurn ? `root:${tIdx}` : `${st?.agentId || 'main'}:${tIdx}`; - }) : []; - const formattedPrompts = new Map(); + } + function formattedTurnPrompt(st) { const raw = getStepPrompt(st); const hasMedia = getStepHasMedia(st); @@ -299,13 +829,38 @@ export const StepTableWidget = defineComponent({ return formattedPrompts.get(cacheKey); } - const decoratedSteps = tableSteps.map((st, idx) => { - const tKey = turnKeys[idx]; + const windowItems = []; + if (isVirtualized && sizerSpec) { + windowItems.push({ + isSizer: true, + isSpacer: false, + rowKey: SIZER_ROW_KEY, + sizerSpec, + }); + } + if (isVirtualized && topSpacerH > 0) { + windowItems.push({ + isSizer: false, + isSpacer: true, + rowKey: SPACER_TOP_KEY, + height: topSpacerH, + colSpan: colKeys.length, + }); + } + + for (let idx = startIdx; idx < endIdx; idx++) { + const st = tableSteps[idx]; + const tKey = getTurnKeyAt(idx); const hasTurn = Boolean(tKey); - const hasUp = hasTurn && turnKeys[idx - 1] === tKey; - const hasDown = hasTurn && turnKeys[idx + 1] === tKey; - return { + const hasUp = hasTurn && getTurnKeyAt(idx - 1) === tKey; + const hasDown = hasTurn && getTurnKeyAt(idx + 1) === tKey; + windowItems.push({ + isSizer: false, + isSpacer: false, st, + logicalIdx: idx, + isStripeEven: (idx & 1) === 1, + hasReason: Boolean(hasReasonFlags && hasReasonFlags[idx]), rowKey: `${st.agentCascadeId || cascadeId || 'conv'}-${st.stepIndex}`, hasTurn, hasUp, @@ -313,18 +868,28 @@ export const StepTableWidget = defineComponent({ isStart: Boolean(hasTurn && (getStepIsStart(st) || !hasDown)), isLatest: hasTurn && getStepIsLatest(st), prompt: hasTurn ? formattedTurnPrompt(st) : '', - }; - }); - - const railActive = Boolean(showStepTurnRail && decoratedSteps.some((d) => d.hasTurn)); - if (!railActive) { - hideTurnTip(); + }); } - patchClasses(stepsTableEl, { 'has-turn-rail': railActive }); - patchKeyedList(stepsTbody, decoratedSteps, { + if (isVirtualized && bottomSpacerH > 0) { + windowItems.push({ + isSizer: false, + isSpacer: true, + rowKey: SPACER_BOTTOM_KEY, + height: bottomSpacerH, + colSpan: colKeys.length, + }); + } + + patchKeyedList(stepsTbody, windowItems, { keyFn: (item) => item.rowKey, sigFn: (item) => { + if (item.isSizer) { + return `${locale}:${colOrderSig}:${showAgentBadge ? 1 : 0}:${railActive ? 1 : 0}:${item.sizerSpec.sig}`; + } + if (item.isSpacer) { + return `spacer:${item.colSpan}:${item.height}`; + } const { st } = item; const parts = colKeys .map((colKey) => STEP_COLUMN_REGISTRY[colKey].sigPart(st, cellCtx)) @@ -332,13 +897,40 @@ export const StepTableWidget = defineComponent({ const badgeSig = showAgentBadge ? `${cellCtx.scopeSigKey}:${st.agentId || 'main'}:${st.agentBadge || ''}:${st.agentLabel || ''}` : ''; - return `${locale}:${colOrderSig}:${badgeSig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`; + const stripeSig = isVirtualized ? (item.isStripeEven ? 'E' : 'O') : 'N'; + return `${locale}:${colOrderSig}:${stripeSig}:${badgeSig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`; }, - createRow: () => { + createRow: (item) => { + if (item.isSizer) { + const tr = h('tr', { className: 'step-vsizer', 'aria-hidden': 'true' }); + return { + el: tr, + refs: { + isSizer: true, + isSpacer: false, + cellMap: new Map(), + colOrderSig: '', + agentBadgeEl: null, + }, + }; + } + if (item.isSpacer) { + const td = h('td', { + className: 'step-vspacer-cell', + colspan: String(item.colSpan), + }); + const tr = h('tr', { className: 'step-vspacer', 'aria-hidden': 'true' }, [td]); + return { el: tr, refs: { isSizer: false, isSpacer: true, td } }; + } + if (rowPool.length > 0) { + return rowPool.pop(); + } const tr = h('tr'); return { el: tr, refs: { + isSizer: false, + isSpacer: false, cellMap: new Map(), colOrderSig: '', railEl: null, @@ -348,7 +940,78 @@ export const StepTableWidget = defineComponent({ }; }, updateRow: (refs, item, _idx, tr) => { + if (item.isSizer) { + const spec = item.sizerSpec; + if (refs.colOrderSig !== colOrderSig) { + for (const [oldColKey, entry] of refs.cellMap) { + if (!wantedSet.has(oldColKey)) { + if (refs.agentBadgeEl?.parentNode === entry.innerEl) { + entry.innerEl.removeChild(refs.agentBadgeEl); + } + tr.removeChild(entry.td); + refs.cellMap.delete(oldColKey); + } + } + const isNewSizer = refs.colOrderSig === ''; + for (let i = 0; i < colKeys.length; i++) { + const colKey = colKeys[i]; + let entry = refs.cellMap.get(colKey); + if (!entry) { + const created = STEP_COLUMN_REGISTRY[colKey].createCell(); + const innerEl = h('div', { className: 'step-vsizer-inner' }); + while (created.td.firstChild) { + innerEl.appendChild(created.td.firstChild); + } + created.td.appendChild(innerEl); + entry = { td: created.td, refs: created.refs, innerEl }; + refs.cellMap.set(colKey, entry); + } + if (isNewSizer) { + tr.appendChild(entry.td); + } else { + const currentTd = tr.children[i] || null; + if (currentTd !== entry.td) tr.insertBefore(entry.td, currentTd); + } + } + refs.colOrderSig = colOrderSig; + } + for (const colKey of colKeys) { + const entry = refs.cellMap.get(colKey); + const probeStep = spec.colSteps[colKey] || tableSteps[0]; + if (entry && probeStep) { + STEP_COLUMN_REGISTRY[colKey].updateCell(entry.refs, probeStep, cellCtx); + } + } + const firstColKey = colKeys[0]; + const firstInner = firstColKey ? refs.cellMap.get(firstColKey)?.innerEl || null : null; + const showSizerBadge = Boolean(showAgentBadge && firstInner && spec.badgeText); + if (showSizerBadge && !refs.agentBadgeEl) { + refs.agentBadgeEl = h('span', { className: 'agent-badge', style: 'margin-right: 4px;' }); + } + if (firstInner && refs.agentBadgeEl) { + if (refs.agentBadgeEl.parentNode !== firstInner || firstInner.firstChild !== refs.agentBadgeEl) { + firstInner.insertBefore(refs.agentBadgeEl, firstInner.firstChild); + } + patchAttr(refs.agentBadgeEl, 'hidden', !showSizerBadge); + if (showSizerBadge) { + patchAttr(refs.agentBadgeEl, 'class', `agent-badge ${spec.badgeClass || ''}`.trim()); + patchText(refs.agentBadgeEl, spec.badgeText); + } + } + return; + } + if (item.isSpacer) { + patchAttr(refs.td, 'colspan', String(item.colSpan)); + if (refs.td?.style) { + refs.td.style.height = `${item.height}px`; + } + return; + } const { st, hasTurn, hasUp, hasDown, isStart, isLatest, prompt } = item; + patchClasses(tr, { 'is-stripe-even': Boolean(isVirtualized && item.isStripeEven) }); + if (tr.dataset) { + tr.dataset.hasReason = item.hasReason ? '1' : '0'; + } if (refs.colOrderSig !== colOrderSig) { if (refs.hoverTd) { @@ -407,8 +1070,10 @@ export const StepTableWidget = defineComponent({ const afterRail = refs.railEl ? refs.railEl.nextSibling ?? firstTd.children[1] ?? null : firstTd.firstChild; - if (refs.agentBadgeEl && - (refs.agentBadgeEl.parentNode !== firstTd || afterRail !== refs.agentBadgeEl)) { + if ( + refs.agentBadgeEl && + (refs.agentBadgeEl.parentNode !== firstTd || afterRail !== refs.agentBadgeEl) + ) { firstTd.insertBefore(refs.agentBadgeEl, afterRail); } } @@ -478,7 +1143,11 @@ export const StepTableWidget = defineComponent({ patchAttr(refs.railEl, 'hidden', !showRowRail); if (showRowRail) { const marker = isStart ? ' is-origin' : !hasUp && hasDown ? ' is-cap' : ''; - patchAttr(refs.railEl, 'class', `turn-rail${isLatest ? ' is-latest' : ''}${hasUp ? ' has-up' : ''}${hasDown ? ' has-down' : ''}${marker}`); + patchAttr( + refs.railEl, + 'class', + `turn-rail${isLatest ? ' is-latest' : ''}${hasUp ? ' has-up' : ''}${hasDown ? ' has-down' : ''}${marker}` + ); } const hoverTd = showRowRail && prompt ? firstTd : null; @@ -503,17 +1172,270 @@ export const StepTableWidget = defineComponent({ activeEnterTimers.set(tr, timer); } }, - destroyRow: (_refs, tr) => { + destroyRow: (refs, tr) => { + if (refs?.hoverTd) { + clearCellHover(refs.hoverTd); + refs.hoverTd = null; + } clearRowEnterState(tr); + if (!refs?.isSpacer && !refs?.isSizer && tr) { + patchClasses(tr, { 'is-stripe-even': false, 'is-step-entering': false }); + if (refs.agentBadgeEl) { + refs.agentBadgeEl.onclick = null; + } + if (rowPool.length < MAX_ROW_POOL_SIZE) { + rowPool.push({ el: tr, refs }); + } + } }, }); + + renderedSliceStart = startIdx; + renderedSliceEnd = endIdx; + renderedTopSpacerH = topSpacerH; + renderedBottomSpacerH = bottomSpacerH; + + if (isVirtualized) { + scheduleCalibrateRowHeights(); + } + } + + function refreshViewport() { + if (!activeDataset?.isVirtualized) return; + const scaleChanged = syncFontScaleIfChanged(); + renderCurrentWindow({ force: scaleChanged, enteringRowKeys: null }); + scheduleCalibrateRowHeights(); + } + + function onPaneScroll() { + hideTurnTip(); + if (!activeDataset?.isVirtualized) return; + if (typeof requestAnimationFrame === 'function') { + if (scrollRafId) return; + scrollRafId = requestAnimationFrame(() => { + scrollRafId = 0; + renderCurrentWindow({ force: false, enteringRowKeys: null }); + }); + } else { + renderCurrentWindow({ force: false, enteringRowKeys: null }); + } + } + + stepsTablePane.addEventListener('scroll', onPaneScroll, { passive: true }); + stepsTbody.addEventListener('mouseleave', hideTurnTip); + + let paneResizeObs = null; + if (typeof ResizeObserver === 'function') { + paneResizeObs = new ResizeObserver(() => { + if (!activeDataset?.isVirtualized) return; + refreshViewport(); + }); + paneResizeObs.observe(stepsTablePane); + } + + function renderStepTable( + tableSteps, + cascadeId, + colKeys, + locale, + { + effectiveScopes = ['all'], + hasSubagents = false, + isMergedMultiAgents = false, + showStepTurnRail = false, + showStepAgentBadge = true, + showStepSpeedColor = false, + stepTokenComboFormat = undefined, + displaySettings = {}, + allConversationSteps = null, + allowNewRowFade = false, + } = {} + ) { + const normCascadeId = String(cascadeId || ''); + let enteringRowKeys = null; + if (!normCascadeId || trackedCascadeId === null || normCascadeId !== trackedCascadeId) { + trackedCascadeId = normCascadeId || null; + lastAbsorbedAllSteps = null; + seenStepKeys.clear(); + maxSeenStepByAgent.clear(); + if (allConversationSteps && allConversationSteps !== tableSteps) { + absorbStepsIntoBaseline(allConversationSteps, normCascadeId); + lastAbsorbedAllSteps = allConversationSteps; + } + absorbStepsIntoBaseline(tableSteps, normCascadeId); + } else if (!allowNewRowFade || standalone) { + if (allConversationSteps && allConversationSteps !== lastAbsorbedAllSteps && allConversationSteps !== tableSteps) { + absorbStepsIntoBaseline(allConversationSteps, normCascadeId); + lastAbsorbedAllSteps = allConversationSteps; + } + if (tableSteps !== lastRenderedRows) { + absorbStepsIntoBaseline(tableSteps, normCascadeId); + } + } else if (tableSteps !== lastRenderedRows) { + let pendingMaxByAgent = null; + for (const st of tableSteps) { + if (!st || typeof st !== 'object') continue; + const { agentKey, stepNum, rowKey } = getStepRowIdentity(st, normCascadeId); + if (!seenStepKeys.has(rowKey)) { + seenStepKeys.add(rowKey); + const prevMax = maxSeenStepByAgent.get(agentKey); + if (prevMax === undefined || !Number.isFinite(stepNum) || stepNum > prevMax) { + enteringRowKeys ??= new Set(); + enteringRowKeys.add(rowKey); + } + if (Number.isFinite(stepNum)) { + const curPending = pendingMaxByAgent?.get(agentKey); + if (curPending === undefined || stepNum > curPending) { + pendingMaxByAgent ??= new Map(); + pendingMaxByAgent.set(agentKey, stepNum); + } + } + } + } + if (pendingMaxByAgent) { + for (const [agentKey, maxStep] of pendingMaxByAgent) { + const prevMax = maxSeenStepByAgent.get(agentKey); + if (prevMax === undefined || maxStep > prevMax) { + maxSeenStepByAgent.set(agentKey, maxStep); + } + } + } + if (allConversationSteps && allConversationSteps !== lastAbsorbedAllSteps && allConversationSteps !== tableSteps) { + absorbStepsIntoBaseline(allConversationSteps, normCascadeId); + lastAbsorbedAllSteps = allConversationSteps; + } + } else if (allConversationSteps && allConversationSteps !== lastAbsorbedAllSteps && allConversationSteps !== tableSteps) { + absorbStepsIntoBaseline(allConversationSteps, normCascadeId); + lastAbsorbedAllSteps = allConversationSteps; + } + + const colOrderSig = colKeys.join(','); + const normTokenFmt = normalizeClientStepTokenComboFormat(stepTokenComboFormat); + const renderOptions = JSON.stringify([ + cascadeId, locale, colOrderSig, effectiveScopes, hasSubagents, isMergedMultiAgents, + showStepTurnRail, showStepAgentBadge, showStepSpeedColor, normTokenFmt, + displaySettings.modelDisplayMode, displaySettings.showUpstreamModel, + displaySettings.orchestratorIdMode, + ]); + if ( + lastRenderOptions === renderOptions && + lastRenderedRows && + (lastRenderedRows === tableSteps || + (lastRenderedRows.length === tableSteps.length && + tableSteps.every((step, i) => step === lastRenderedRows[i]))) + ) { + if (activeDataset?.isVirtualized) { + refreshViewport(); + } + return; + } + + syncFontScaleIfChanged(); + const wantedSet = new Set(colKeys); + syncTableHeaderColumns(colKeys, { stepTokenComboFormat: normTokenFmt }); + + const showAgentBadge = Boolean(hasSubagents && showStepAgentBadge); + const cellCtx = { + hasSubagents, + showAgentBadge, + showStepSpeedColor, + stepTokenComboFormat: normTokenFmt, + effectiveScopes, + scopeSigKey: effectiveScopes.join(','), + displaySettings, + onSelectAgentScopes, + }; + + const useRootTurn = Boolean(hasSubagents && isMergedMultiAgents); + let railActive = false; + if (showStepTurnRail) { + for (let i = 0; i < tableSteps.length; i++) { + const st = tableSteps[i]; + const tIdx = useRootTurn ? (st?.rootTurnIndex ?? st?.turnIndex) : st?.turnIndex; + if (Number.isInteger(tIdx) && tIdx > 0) { + railActive = true; + break; + } + } + } + if (!railActive) { + hideTurnTip(); + } + + const isVirtualized = !standalone && tableSteps.length > VIRTUAL_ROW_THRESHOLD; + patchClasses(stepsTableEl, { + 'has-turn-rail': railActive, + 'is-virtualized': isVirtualized, + }); + + let hasReasonFlags = null; + let hasAnyReason = false; + let rowTops = null; + let totalBodyH = 0; + let sizerSpec = null; + if (isVirtualized) { + const hasTpsCol = wantedSet.has('tps'); + if (hasTpsCol) { + hasReasonFlags = new Uint8Array(tableSteps.length); + for (let i = 0; i < tableSteps.length; i++) { + const rawReason = tableSteps[i]?.selectedSpeedReason; + if (rawReason && speedReasonText(rawReason)) { + hasReasonFlags[i] = 1; + hasAnyReason = true; + } + } + } + const built = buildRowTops(tableSteps.length, hasReasonFlags); + rowTops = built.rowTops; + totalBodyH = built.totalBodyH; + sizerSpec = buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx); + } + + activeDataset = { + tableSteps, + cascadeId, + colKeys, + wantedSet, + colOrderSig, + locale, + cellCtx, + railActive, + showAgentBadge, + showStepTurnRail, + useRootTurn, + isVirtualized, + hasReasonFlags, + hasAnyReason, + rowTops, + totalBodyH, + sizerSpec, + effectiveScopes, + formattedPrompts: new Map(), + }; + renderedSliceStart = -1; + renderedSliceEnd = -1; + renderedTopSpacerH = -1; + renderedBottomSpacerH = -1; + + renderCurrentWindow({ force: true, enteringRowKeys }); lastRenderOptions = renderOptions; lastRenderedRows = tableSteps; } onCleanup(() => { - stepsTablePane.removeEventListener('scroll', hideTurnTip); + stepsTablePane.removeEventListener('scroll', onPaneScroll); stepsTbody.removeEventListener('mouseleave', hideTurnTip); + if (scrollRafId && typeof cancelAnimationFrame === 'function') { + cancelAnimationFrame(scrollRafId); + scrollRafId = 0; + } + if (calibrateRafId && typeof cancelAnimationFrame === 'function') { + cancelAnimationFrame(calibrateRafId); + calibrateRafId = 0; + } + paneResizeObs?.disconnect(); + paneResizeObs = null; + rowPool.length = 0; for (const tr of [...activeEnterTimers.keys()]) { clearRowEnterState(tr); } @@ -529,6 +1451,7 @@ export const StepTableWidget = defineComponent({ turnTipEl, syncTableHeaderColumns, renderStepTable, + refreshViewport, hideTurnTip, setBoundsElGetter, }, diff --git a/sidecars/panel/src/styles/modern-ui.css b/sidecars/panel/src/styles/modern-ui.css index 20acd1f..37f173a 100644 --- a/sidecars/panel/src/styles/modern-ui.css +++ b/sidecars/panel/src/styles/modern-ui.css @@ -494,7 +494,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { border-bottom: none; } -[data-modern-ui="true"] .data-table tbody tr { +[data-modern-ui="true"] .data-table tbody tr:not(.step-vspacer):not(.step-vsizer) { transition: background-color 130ms var(--ease-modern); } @@ -506,11 +506,13 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { animation: anim-modern-step-cell-in 300ms cubic-bezier(0.22, 1, 0.36, 1) both; } -[data-modern-ui="true"] .data-table tbody tr:nth-child(even) { +[data-modern-ui="true"] .data-table:not(.is-virtualized) tbody tr:nth-child(even), +[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even { background: var(--modern-stripe-bg); } -[data-modern-ui="true"] .data-table tbody tr:hover { +[data-modern-ui="true"] .data-table tbody tr:not(.step-vspacer):not(.step-vsizer):hover, +[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even:hover { background: var(--modern-surface-hover); } diff --git a/sidecars/panel/src/styles/views-tables.css b/sidecars/panel/src/styles/views-tables.css index f1c9336..8cb810f 100644 --- a/sidecars/panel/src/styles/views-tables.css +++ b/sidecars/panel/src/styles/views-tables.css @@ -29,6 +29,7 @@ .table-viewport.is-step-table { overflow-x: auto; + overflow-anchor: none; } /* --- 2. 粘性表头数据表 (Sticky-Header Data Table) --- */ @@ -72,10 +73,44 @@ font-weight: 600; } -.data-table tbody tr:hover { +.data-table tbody tr:not(.step-vspacer):not(.step-vsizer):hover { background: var(--surface-hover); } +.data-table tbody tr.step-vspacer, +.data-table tbody tr.step-vspacer:hover, +.data-table tbody tr.step-vsizer, +.data-table tbody tr.step-vsizer:hover { + background: transparent !important; + pointer-events: none; +} + +.data-table tbody tr.step-vsizer { + visibility: hidden; + height: 0; +} + +.data-table tbody tr.step-vsizer td { + padding-top: 0 !important; + padding-bottom: 0 !important; + border: none !important; + line-height: 0; + height: 0; +} + +.step-vsizer-inner { + display: block; + height: 0; + overflow: hidden; + white-space: nowrap; +} + +.data-table tbody tr.step-vspacer td.step-vspacer-cell { + padding: 0 !important; + border: none !important; + line-height: 0; +} + .step-model-cell { display: inline-flex; align-items: baseline; diff --git a/sidecars/panel/src/views/StepsDetailView.js b/sidecars/panel/src/views/StepsDetailView.js index fe063ac..eac8a0d 100644 --- a/sidecars/panel/src/views/StepsDetailView.js +++ b/sidecars/panel/src/views/StepsDetailView.js @@ -260,8 +260,10 @@ export const StepsDetailView = defineComponent({ }); // --- 子视图 1:单步明细表(委托给可复用的 `StepTableWidget` 解耦组件) --- + let stepsScroll = null; const stepTableWidget = StepTableWidget({ onSelectAgentScopes: applyAgentScopesSelection, + onVirtualHeightChange: () => stepsScroll?.refresh(), }); const { stepsTablePane, @@ -272,8 +274,9 @@ export const StepsDetailView = defineComponent({ hideTurnTip, syncTableHeaderColumns, renderStepTable, + refreshViewport: refreshStepTableViewport, } = stepTableWidget.refs; - const stepsScroll = CustomScrollbar({ + stepsScroll = CustomScrollbar({ contentEl: stepsTablePane, className: 'table-scroll-host', }); @@ -432,6 +435,19 @@ export const StepsDetailView = defineComponent({ let latestSlice = null; let isDirty = false; + let cachedChronoSrc = null; + let cachedChronoMerged = false; + let cachedChronoOut = []; + + function getMemoizedChronoSteps(steps, isMergedMultiAgents) { + if (cachedChronoSrc === steps && cachedChronoMerged === isMergedMultiAgents) { + return cachedChronoOut; + } + cachedChronoSrc = steps; + cachedChronoMerged = isMergedMultiAgents; + cachedChronoOut = toChronologicalSteps(steps, isMergedMultiAgents); + return cachedChronoOut; + } function resolveDefaultActiveModelKey(scopedConv, chronoSteps, models, availableModelKeys) { if (scopedConv?.hasKnownModel !== false) { @@ -618,33 +634,14 @@ export const StepsDetailView = defineComponent({ const showAgentPrefix = isMergedMultiAgents; const showModels = uiSt.stepsSubTab === 'models'; - const chronoSteps = toChronologicalSteps(steps, isMergedMultiAgents); - - const stepTtftFallbackMap = new Map(); - const stepModelOptionMap = new Map(); - for (const st of chronoSteps) { - const gk = getStepModelGroupKey(st); - if (!stepModelOptionMap.has(gk)) { - const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk }); - stepModelOptionMap.set(gk, { - label: disp.baseText || disp.text || gk, - calls: 0, - }); - } - stepModelOptionMap.get(gk).calls += 1; - - if (showModels && !st.isCompactionStep && Number.isFinite(st.ttftSec) && st.ttftSec >= 0) { - const prev = stepTtftFallbackMap.get(gk) || { sum: 0, count: 0 }; - prev.sum += Number(st.ttftSec); - prev.count += 1; - stepTtftFallbackMap.set(gk, prev); - } - } const availableModelKeys = new Set(); const modelColorByGroup = new Map(); const perModelOptions = []; + let breakdownCalls = 0; for (const m of models) { + if (!m || typeof m !== 'object') continue; + breakdownCalls += Math.max(0, Number(m.calls || 0)); const gk = getStepModelGroupKey(m); if (availableModelKeys.has(gk)) continue; availableModelKeys.add(gk); @@ -662,18 +659,35 @@ export const StepsDetailView = defineComponent({ meta: t('header.convMetaSteps', { count: Number(m.calls || 0) }), }); } - for (const [gk, info] of stepModelOptionMap.entries()) { - if (!availableModelKeys.has(gk)) { - availableModelKeys.add(gk); - modelColorByGroup.set( - gk, - MODEL_COLOR_VARS[(availableModelKeys.size - 1) % MODEL_COLOR_VARS.length] - ); - perModelOptions.push({ - value: gk, - label: info.label, - meta: t('header.convMetaSteps', { count: info.calls }), - }); + + const needStepModelFallback = + steps.length > 0 && (models.length === 0 || breakdownCalls < steps.length); + if (needStepModelFallback) { + const stepModelOptionMap = new Map(); + for (const st of steps) { + const gk = getStepModelGroupKey(st); + if (!stepModelOptionMap.has(gk)) { + const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk }); + stepModelOptionMap.set(gk, { + label: disp.baseText || disp.text || gk, + calls: 0, + }); + } + stepModelOptionMap.get(gk).calls += 1; + } + for (const [gk, info] of stepModelOptionMap.entries()) { + if (!availableModelKeys.has(gk)) { + availableModelKeys.add(gk); + modelColorByGroup.set( + gk, + MODEL_COLOR_VARS[(availableModelKeys.size - 1) % MODEL_COLOR_VARS.length] + ); + perModelOptions.push({ + value: gk, + label: info.label, + meta: t('header.convMetaSteps', { count: info.calls }), + }); + } } } @@ -749,6 +763,23 @@ export const StepsDetailView = defineComponent({ allowNewRowFade: shouldAnimateNewRows, }); stepsScroll.refresh(); + fitPinnedWhileVisible = false; + return; + } + + const chronoSteps = getMemoizedChronoSteps(steps, isMergedMultiAgents); + const stepTtftFallbackMap = new Map(); + const needTtftFallback = models.some((m) => m && m.avgTtftSec == null); + if (needTtftFallback) { + for (const st of chronoSteps) { + if (!st.isCompactionStep && Number.isFinite(st.ttftSec) && st.ttftSec >= 0) { + const gk = getStepModelGroupKey(st); + const prev = stepTtftFallbackMap.get(gk) || { sum: 0, count: 0 }; + prev.sum += Number(st.ttftSec); + prev.count += 1; + stepTtftFallbackMap.set(gk, prev); + } + } } // 2. 顶部“会话走势”更新 @@ -768,15 +799,11 @@ export const StepsDetailView = defineComponent({ ? ['__all__'] : Array.from(new Set(fitLockedModelKeys.filter((k) => availableModelKeys.has(k)))); - if (!showModels) { - fitPinnedWhileVisible = false; - } if ((!fitPinnedWhileVisible && !fitUserPicked) || sanitizedLocked.length === 0) { fitLockedModelKeys = [defaultActiveModelKey]; } else { fitLockedModelKeys = sanitizedLocked; } - if (!showModels) return; if (availableModelKeys.size > 0) fitPinnedWhileVisible = true; patchAttr(lineModelSelect.el, 'hidden', !hasMultipleModels); @@ -1049,6 +1076,7 @@ export const StepsDetailView = defineComponent({ if (getVisibleMonitorView() === 'steps' && latestSlice) { renderStepsData(latestSlice); } else if (tab === 'steps') { + refreshStepTableViewport(); stepsScroll.refresh(); } else { modelsScroll.refresh(); @@ -1173,6 +1201,7 @@ export const StepsDetailView = defineComponent({ fitMetricSwitch, stepsScroll, modelsScroll, + refreshStepTableViewport, }, }; }, diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index 94699bb..6b75a83 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -2931,6 +2931,7 @@ html[data-standalone="true"] .app-shell { .table-viewport.is-step-table { overflow-x: auto; + overflow-anchor: none; } /* --- 2. 粘性表头数据表 (Sticky-Header Data Table) --- */ @@ -2974,10 +2975,44 @@ html[data-standalone="true"] .app-shell { font-weight: 600; } -.data-table tbody tr:hover { +.data-table tbody tr:not(.step-vspacer):not(.step-vsizer):hover { background: var(--surface-hover); } +.data-table tbody tr.step-vspacer, +.data-table tbody tr.step-vspacer:hover, +.data-table tbody tr.step-vsizer, +.data-table tbody tr.step-vsizer:hover { + background: transparent !important; + pointer-events: none; +} + +.data-table tbody tr.step-vsizer { + visibility: hidden; + height: 0; +} + +.data-table tbody tr.step-vsizer td { + padding-top: 0 !important; + padding-bottom: 0 !important; + border: none !important; + line-height: 0; + height: 0; +} + +.step-vsizer-inner { + display: block; + height: 0; + overflow: hidden; + white-space: nowrap; +} + +.data-table tbody tr.step-vspacer td.step-vspacer-cell { + padding: 0 !important; + border: none !important; + line-height: 0; +} + .step-model-cell { display: inline-flex; align-items: baseline; @@ -5935,7 +5970,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { border-bottom: none; } -[data-modern-ui="true"] .data-table tbody tr { +[data-modern-ui="true"] .data-table tbody tr:not(.step-vspacer):not(.step-vsizer) { transition: background-color 130ms var(--ease-modern); } @@ -5947,11 +5982,13 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { animation: anim-modern-step-cell-in 300ms cubic-bezier(0.22, 1, 0.36, 1) both; } -[data-modern-ui="true"] .data-table tbody tr:nth-child(even) { +[data-modern-ui="true"] .data-table:not(.is-virtualized) tbody tr:nth-child(even), +[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even { background: var(--modern-stripe-bg); } -[data-modern-ui="true"] .data-table tbody tr:hover { +[data-modern-ui="true"] .data-table tbody tr:not(.step-vspacer):not(.step-vsizer):hover, +[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even:hover { background: var(--modern-surface-hover); } diff --git a/sidecars/panel/test/modern-ui.test.mjs b/sidecars/panel/test/modern-ui.test.mjs index c517716..392760b 100644 --- a/sidecars/panel/test/modern-ui.test.mjs +++ b/sidecars/panel/test/modern-ui.test.mjs @@ -14,6 +14,7 @@ import { parseCssColorLuminance, } from '../src/core/appearance.js'; import { createTrendAreaChart } from '../src/components/charts/TrendAreaChart.js'; +import { computePublicationFit } from '../src/components/charts/SessionStepCharts.js'; import { SegmentedControl } from '../src/components/ui/SegmentedControl.js'; import { ContextWindowWidget } from '../src/components/widgets/ContextWindowWidget.js'; import { LiveActivityWidget } from '../src/components/widgets/LiveActivityWidget.js'; @@ -761,3 +762,229 @@ test('saveSettingsPatch prevents stale in-flight telemetry polls from snapping s assert.equal(telemetryStore.getState().telemetry.settings.experimentalModernUi, true); assert.equal(telemetryStore.getState().telemetry.settings.fontScale, 'lg'); }); + +test('StepTableWidget virtualizes large sessions (>80 rows) with exact turn-rail boundaries, stable zebra parity, live fade-in, and zero blank top gap on tab return', (t) => { + const prevDoc = globalThis.document; + const prevWin = globalThis.window; + const { document: mockDoc } = createMockDom(); + globalThis.document = mockDoc; + globalThis.window = { + addEventListener() {}, + removeEventListener() {}, + }; + + t.after(() => { + globalThis.document = prevDoc; + globalThis.window = prevWin; + }); + + const stepTable = StepTableWidget({}); + const { stepsTablePane, stepsTableEl, stepsTbody, renderStepTable } = stepTable.refs; + stepsTablePane.clientHeight = 500; + stepsTablePane.clientWidth = 520; + stepsTablePane.scrollTop = 0; + + const cols = ['step', 'model', 'tps', 'ttft', 'tokens_combo', 'cache', 'cost']; + const makeStep = (idx, extra = {}) => ({ + stepIndex: idx, + modelShort: idx % 5 === 0 ? '4-neon' : '4-carbon', + tokPerSec: idx % 17 === 0 ? null : 62.5, + selectedSpeedReason: idx % 17 === 0 ? 'below_min_output' : null, + ttftSec: 1.2, + inputTokens: 1200, + cacheReadTokens: 80000, + outputTokens: 600, + thinkingTokens: 200, + responseTokens: 400, + contextTokens: 81800, + cacheHitPct: 98.5, + costUsd: 0.021, + turnIndex: Math.floor((idx - 1) / 4) + 1, + isTurnStart: (idx - 1) % 4 === 0, + isLatestTurn: idx > 1718, + turnPromptClean: `Turn ${Math.floor((idx - 1) / 4) + 1}`, + ...extra, + }); + + // 1. Small dataset (<=80 rows) stays direct without virtualization or spacers + const smallSteps = Array.from({ length: 12 }, (_, i) => makeStep(12 - i)); + renderStepTable(smallSteps, 'conv-small', cols, 'zh-CN', { + showStepTurnRail: true, + allConversationSteps: smallSteps, + allowNewRowFade: false, + }); + assert.equal(stepsTableEl.classList.contains('is-virtualized'), false); + assert.equal(stepsTbody.children.length, 12); + assert.equal( + stepsTbody.children.some((tr) => tr.classList.contains('step-vspacer')), + false + ); + + // 2. Large 1,722-step session activates transparent virtual windowing + const isRealRow = (tr) => + !tr.classList.contains('step-vspacer') && !tr.classList.contains('step-vsizer'); + const totalSteps = 1722; + const bigSteps = Array.from({ length: totalSteps }, (_, i) => + makeStep( + totalSteps - i, + i === 900 + ? { modelShort: '4-hydrogen', modelLabel: 'Gemini 4 Hydrogen', isCompactionStep: true } + : {} + ) + ); + const t0 = performance.now(); + renderStepTable(bigSteps, 'conv-big', cols, 'zh-CN', { + showStepTurnRail: true, + allConversationSteps: bigSteps, + allowNewRowFade: false, + }); + const initialRenderMs = performance.now() - t0; + assert.equal(stepsTableEl.classList.contains('is-virtualized'), true); + assert.equal(stepsTableEl.classList.contains('has-turn-rail'), true); + + const initialRealRows = stepsTbody.children.filter(isRealRow); + const initialSpacers = stepsTbody.children.filter((tr) => tr.classList.contains('step-vspacer')); + const initialSizers = stepsTbody.children.filter((tr) => tr.classList.contains('step-vsizer')); + assert.equal(initialSizers.length, 1, 'Virtualized table mounts one zero-height global width sizer row'); + assert.match( + initialSizers[0].children[1].textContent, + /4-hydrogen/, + 'Sizer row pre-measures global widest model from off-screen row #900 on frame 1' + ); + assert.ok( + initialRealRows.length >= 25 && initialRealRows.length < 75, + `Expected bounded mounted row window, got ${initialRealRows.length}` + ); + assert.equal(initialSpacers.length, 1, 'At scrollTop=0 only bottom spacer should be mounted'); + assert.equal(initialRealRows[0].children[0].textContent, '#1722'); + assert.equal(initialRealRows[0].classList.contains('is-stripe-even'), false, 'Logical row 0 is odd'); + assert.equal(initialRealRows[1].classList.contains('is-stripe-even'), true, 'Logical row 1 is even'); + + // 2.5 Hysteresis: small wheel scroll inside overscan margin skips DOM updates completely + const initialSnapshot = [...initialRealRows]; + stepsTablePane.scrollTop = 56; + stepsTablePane.dispatchEvent({ type: 'scroll' }); + const afterSmallScroll = stepsTbody.children.filter(isRealRow); + assert.equal(afterSmallScroll.length, initialSnapshot.length); + assert.equal( + afterSmallScroll[0], + initialSnapshot[0], + 'Small scroll within hysteresis margin must keep mounted rows untouched' + ); + + // 3. Scrolling mid-table shifts window, mounts both spacers, keeps logical parity & seamless turn-rail boundary + const initialRowSet = new Set(initialSnapshot); + stepsTablePane.scrollTop = 24000; + stepsTablePane.dispatchEvent({ type: 'scroll' }); + const midRealRows = stepsTbody.children.filter(isRealRow); + const midSpacers = stepsTbody.children.filter((tr) => tr.classList.contains('step-vspacer')); + assert.equal(midSpacers.length, 2, 'Mid-scroll must mount both top and bottom spacers'); + assert.ok(midRealRows.length >= 25 && midRealRows.length < 75); + assert.equal( + midRealRows.some((tr) => tr.classList.contains('is-step-entering')), + false, + 'Scrolling into historical rows must never trigger new-row fade-in animation' + ); + + // 3.5 Second distant jump recycles pooled nodes from the first jump (zero fresh allocations) + stepsTablePane.scrollTop = 36000; + stepsTablePane.dispatchEvent({ type: 'scroll' }); + const farRealRows = stepsTbody.children.filter(isRealRow); + assert.ok( + farRealRows.some((tr) => initialRowSet.has(tr)), + 'Distant jump must recycle previously unmounted nodes from rowPool' + ); + assert.equal( + stepTable.refs.stepsTheadRow.children.every((th) => !th.style.minWidth), + true, + 'Scrolling must never ratchet th.style.minWidth and clip trailing columns' + ); + // Return to mid-table to continue boundary checks + stepsTablePane.scrollTop = 24000; + stepsTablePane.dispatchEvent({ type: 'scroll' }); + const midCheckRows = stepsTbody.children.filter(isRealRow); + + // Verify logical zebra parity & turn-rail boundary continuity on first & last mounted mid rows + for (const tr of midCheckRows) { + const stepNum = Number(tr.children[0].textContent.replace(/^#/, '')); + const logicalIdx = totalSteps - stepNum; + assert.equal( + tr.classList.contains('is-stripe-even'), + logicalIdx % 2 === 1, + `Row #${stepNum} (logicalIdx=${logicalIdx}) must preserve exact logical zebra parity` + ); + } + const firstMidRow = midCheckRows[0]; + const firstMidStepNum = Number(firstMidRow.children[0].textContent.replace(/^#/, '')); + const firstMidIdx = totalSteps - firstMidStepNum; + const expectedHasUp = bigSteps[firstMidIdx - 1]?.turnIndex === bigSteps[firstMidIdx]?.turnIndex; + const firstMidRail = firstMidRow.querySelector('.turn-rail'); + assert.ok(firstMidRail, 'Mid-table virtualized row must preserve turn-rail element'); + assert.equal( + firstMidRail.classList.contains('has-up'), + expectedHasUp, + 'First mounted row in virtual window must compute has-up from real adjacent step outside window' + ); + + // 4. Simulating tab switch away & back (display:none resets scrollTop to 0 with unchanged bigSteps reference) + stepsTablePane.scrollTop = 0; + renderStepTable(bigSteps, 'conv-big', cols, 'zh-CN', { + showStepTurnRail: true, + allConversationSteps: bigSteps, + allowNewRowFade: false, + }); + const returnedRealRows = stepsTbody.children.filter(isRealRow); + const returnedSpacers = stepsTbody.children.filter((tr) => tr.classList.contains('step-vspacer')); + assert.equal(returnedSpacers.length, 1, 'Returning to scrollTop=0 must drop top spacer immediately'); + assert.equal(returnedRealRows[0].children[0].textContent, '#1722'); + + // 5. Live new step prepended at top animates ONLY the new row even when virtualized + const nextBigSteps = [makeStep(1723, { isLatestTurn: true }), ...bigSteps]; + renderStepTable(nextBigSteps, 'conv-big', cols, 'zh-CN', { + showStepTurnRail: true, + allConversationSteps: nextBigSteps, + allowNewRowFade: true, + }); + const liveRealRows = stepsTbody.children.filter(isRealRow); + assert.equal(liveRealRows[0].children[0].textContent, '#1723'); + assert.equal(liveRealRows[0].classList.contains('is-step-entering'), true); + assert.equal(liveRealRows[1].classList.contains('is-step-entering'), false); + + // 6. Narrowing filter below threshold cleanly exits virtualization + const filteredSteps = nextBigSteps.slice(0, 20); + renderStepTable(filteredSteps, 'conv-big', cols, 'zh-CN', { + showStepTurnRail: true, + allConversationSteps: nextBigSteps, + allowNewRowFade: false, + }); + assert.equal(stepsTableEl.classList.contains('is-virtualized'), false); + assert.equal(stepsTbody.children.length, 20); + assert.equal( + stepsTbody.children.some((tr) => !isRealRow(tr)), + false + ); + + // Verify compiled CSS ships virtualized zebra striping, sizer, spacer, and overflow-anchor rules + const builtStyles = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8'); + assert.match(builtStyles, /\.data-table\.is-virtualized\s+tbody\s+tr\.is-stripe-even/); + assert.match(builtStyles, /\.step-vspacer-cell/); + assert.match(builtStyles, /\.step-vsizer-inner/); + assert.match(builtStyles, /overflow-anchor:\s*none;/); + assert.ok(initialRenderMs < 150, `Virtualized 1722-row initial render should stay fast (was ${initialRenderMs.toFixed(1)}ms)`); + + // 7. Large-N LOESS grid interpolation tracks trends accurately without O(N^2) stalls + const loessXs = Array.from({ length: totalSteps }, (_, i) => i + 1); + const loessYs = loessXs.map((x) => 80 - 30 * (x / totalSteps) + ((x * 17) % 9) - 4); + const lt0 = performance.now(); + const bigFit = computePublicationFit(loessXs, loessYs, { minVal: 0 }); + const loessMs = performance.now() - lt0; + assert.equal(bigFit.method, 'LOESS'); + assert.equal(bigFit.grid.length, 64); + assert.equal(bigFit.sampleFits.length, totalSteps); + assert.ok(bigFit.sampleFits[0] > 76 && bigFit.sampleFits[totalSteps - 1] < 54); + assert.ok(bigFit.r2 > 0.85, `Expected high R² on smooth downward trend, got ${bigFit.r2}`); + assert.ok(bigFit.grid.every((g) => g.ciLow <= g.fit + 1e-9 && g.fit <= g.ciHigh + 1e-9)); + assert.ok(loessMs < 80, `Interpolated 1722-sample LOESS should stay fast (was ${loessMs.toFixed(1)}ms)`); + + stepTable.destroy(); +}); From 5c37e40822d6d04cef22d61b1853f51f894c4c39 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Thu, 19 Nov 2026 18:43:33 +0900 Subject: [PATCH 08/14] fix(bridge): harden Windows UAC/HKLM, Linux desktop/AppImage, and macOS relaunch for 2.33.0+ --- .../panel/backend/desktop-launcher-config.mjs | 678 ++++++++++++++---- sidecars/panel/backend/window-bridge.mjs | 114 ++- sidecars/panel/test/window-bridge.test.mjs | 229 +++++- 3 files changed, 850 insertions(+), 171 deletions(-) diff --git a/sidecars/panel/backend/desktop-launcher-config.mjs b/sidecars/panel/backend/desktop-launcher-config.mjs index 9041b10..8ad0004 100644 --- a/sidecars/panel/backend/desktop-launcher-config.mjs +++ b/sidecars/panel/backend/desktop-launcher-config.mjs @@ -199,7 +199,13 @@ export function patchWindowsShellOpenCommand(rawValue, { enabled = true } = {}) function isLinuxAntigravityDesktopLeaf(leaf) { const lower = String(leaf || '').trim().toLowerCase(); if (!lower || lower.includes('ide')) return false; - return /^antigravity(?:$|[-_.\d]|(?:\.appimage$))/i.test(lower); + return /^(?:google[-_])?antigravity(?:$|[-_.\d]|(?:\.appimage$))/i.test(lower); +} + +function isWindowsVendorSubdirName(dirName) { + const lower = String(dirName || '').trim().toLowerCase(); + if (!lower) return false; + return lower.includes('antigravity') || /^google(?:\b|[\s_-]|$)/i.test(lower); } function splitLinuxExecTokens(cmdBody) { @@ -254,7 +260,17 @@ export function patchLinuxDesktopEntryText(rawText, { enabled = true } = {}) { binIdx = 1; while (binIdx < tokens.length) { const unquoted = stripOuterQuotes(tokens[binIdx].raw); - if (unquoted === '-S' || /^[A-Za-z_][A-Za-z0-9_]*=/.test(unquoted)) { + if (unquoted === '-u' || unquoted === '--unset') { + binIdx += 2; + continue; + } + if ( + unquoted === '-S' || + unquoted === '-i' || + unquoted === '--ignore-environment' || + unquoted.startsWith('--unset=') || + /^[A-Za-z_][A-Za-z0-9_]*=/.test(unquoted) + ) { binIdx += 1; continue; } @@ -280,6 +296,15 @@ export function patchLinuxDesktopEntryText(rawText, { enabled = true } = {}) { } configured = true; changed = true; + const doubleDashMatch = rest.match(/^(.*?)(?:^|\s)(--(?:\s+.*)?)$/); + if (doubleDashMatch) { + const beforeDash = doubleDashMatch[1].trim(); + const fromDash = doubleDashMatch[2].trim(); + const mid = beforeDash + ? `${beforeDash} ${REMOTE_DEBUG_LAUNCH_FLAG}` + : REMOTE_DEBUG_LAUNCH_FLAG; + return `${prefix}${headThroughExe} ${mid} ${fromDash}`; + } const fieldCodeMatch = rest.match(/^(.*?)\s*(%[fFuUdDnNickvm](?:\s+%[fFuUdDnNickvm])*)\s*$/); if (fieldCodeMatch) { const beforeCodes = fieldCodeMatch[1].trim(); @@ -309,8 +334,24 @@ export function patchLinuxDesktopEntryText(rawText, { enabled = true } = {}) { }; } +function stripAppImageMountPathEntries(rawVal, { omitIfEmpty = false } = {}) { + const str = String(rawVal ?? ''); + if (!str || !str.includes('/.mount_')) { + return str; + } + const parts = str.split(':').filter((entry) => { + const trimmed = entry.trim(); + return trimmed && !trimmed.startsWith('/tmp/.mount_') && !trimmed.includes('/.mount_'); + }); + if (parts.length === 0 && omitIfEmpty) { + return null; + } + return parts.join(':'); +} + /** * 清理 Sidecar / MCP 子进程继承的宿主会话私有环境变量,确保重拉后的客户端运行于纯净桌面上下文。 + * 同时剔除 Linux AppImage 挂载期注入的临时变量与 `/tmp/.mount_*` 路径,防止旧挂载卸载后新进程加载失败。 * * @param {Record} [baseEnv=process.env] * @returns {Record} @@ -320,12 +361,26 @@ export function buildSanitizedDesktopRelaunchEnv(baseEnv = process.env) { for (const [key, val] of Object.entries(baseEnv || {})) { if (val === undefined || val === null) continue; if ( - /^(?:ANTIGRAVITY_|CHROME_DEVTOOLS_MCP_|USAGE_MONITOR_|ELECTRON_RUN_AS_NODE$|NODE_OPTIONS$)/i.test( + /^(?:ANTIGRAVITY_|CHROME_DEVTOOLS_MCP_|USAGE_MONITOR_|ELECTRON_RUN_AS_NODE$|NODE_OPTIONS$|APPIMAGE$|APPDIR$|OWD$|ARGV0$|APPIMAGE_EXTRACT_AND_RUN$)/i.test( key ) ) { continue; } + if (key === 'LD_LIBRARY_PATH') { + const cleanedLib = stripAppImageMountPathEntries(val, { omitIfEmpty: true }); + if (cleanedLib !== null) { + clean[key] = cleanedLib; + } + continue; + } + if (key === 'PATH' && String(val).includes('/.mount_')) { + const cleanedPath = stripAppImageMountPathEntries(val, { omitIfEmpty: false }); + if (cleanedPath) { + clean[key] = cleanedPath; + } + continue; + } clean[key] = String(val); } return clean; @@ -440,9 +495,11 @@ export function resolveDesktopHostExecutable({ if (platform === 'win32') { const localAppData = env?.LOCALAPPDATA || join(homeDir, 'AppData', 'Local'); const programFiles = env?.ProgramFiles || 'C:\\Program Files'; + const programFilesX86 = String(env?.['ProgramFiles(x86)'] || '').trim(); const winCandidates = [ join(localAppData, 'Programs', 'Antigravity', 'Antigravity.exe'), join(programFiles, 'Antigravity', 'Antigravity.exe'), + ...(programFilesX86 ? [join(programFilesX86, 'Antigravity', 'Antigravity.exe')] : []), join(localAppData, 'Antigravity', 'Antigravity.exe'), ]; for (const cand of winCandidates) { @@ -469,9 +526,12 @@ export function resolveDesktopHostExecutable({ } else { const linuxCandidates = [ '/opt/Antigravity/antigravity', + '/opt/Antigravity/Antigravity', '/opt/antigravity/antigravity', '/usr/share/antigravity/antigravity', '/usr/bin/antigravity', + '/usr/bin/google-antigravity', + '/usr/local/bin/antigravity', join(homeDir, '.local', 'bin', 'antigravity'), ]; for (const cand of linuxCandidates) { @@ -577,11 +637,12 @@ export function inspectWindowsLnkBuffer(buf) { /** * 纯 Node.js 零子进程快速扫描当前机器上的 `Antigravity.exe` 快捷方式配置状态(耗时通常 `< 2ms`)。 - * 桌面与任务栏严格仅扫描顶层 `.lnk`(绝不进入用户项目文件夹或 `node_modules`),开始菜单仅检查顶层及 `Antigravity*` 一级子目录。 + * 桌面与任务栏严格仅扫描顶层 `.lnk`(绝不进入用户项目文件夹或 `node_modules`),开始菜单仅检查顶层及 Antigravity/Google 一级厂商子目录。 * * @param {{ * env?: Record, * homeDir?: string, + * extraDirs?: string[], * fsOps?: { * readdirFn?: typeof readdirSync, * statFn?: typeof statSync, @@ -592,6 +653,7 @@ export function inspectWindowsLnkBuffer(buf) { export function probeWindowsShortcutsFast({ env = process.env, homeDir = homedir(), + extraDirs = [], fsOps = null, } = {}) { const readdirFn = fsOps?.readdirFn || readdirSync; @@ -605,6 +667,12 @@ export function probeWindowsShortcutsFast({ const programData = String(env?.ProgramData || 'C:\\ProgramData').trim(); const flatDirs = []; + if (Array.isArray(extraDirs)) { + for (const d of extraDirs) { + const clean = String(d || '').trim(); + if (clean) flatDirs.push(clean); + } + } if (userProfile) { flatDirs.push(pathWin32.join(userProfile, 'Desktop'), pathWin32.join(userProfile, zhDesktop)); } @@ -637,7 +705,7 @@ export function probeWindowsShortcutsFast({ const candidateLnks = []; const seenLnks = new Set(); - const collectTopLevelLnks = (dirPath, expandAntigravitySubdirs = false) => { + const collectTopLevelLnks = (dirPath, expandVendorSubdirs = false) => { if (!dirPath) return; const normDir = dirPath.toLowerCase(); if (seenDirs.has(normDir)) return; @@ -659,9 +727,9 @@ export function probeWindowsShortcutsFast({ candidateLnks.push(full); } } else if ( - expandAntigravitySubdirs && + expandVendorSubdirs && ent.isDirectory?.() && - name.toLowerCase().startsWith('antigravity') + isWindowsVendorSubdirName(name) ) { collectTopLevelLnks(pathWin32.join(dirPath, name), false); } @@ -708,52 +776,59 @@ $enableFlag = $env:AGY_LAUNCH_ENABLED -eq '1' $updated = New-Object System.Collections.Generic.List[string] $configured = New-Object System.Collections.Generic.List[string] $readOnly = New-Object System.Collections.Generic.List[string] +$discoveredDirs = New-Object System.Collections.Generic.List[string] $ws = $null +$userDesktopDir = [Environment]::GetFolderPath('Desktop') +$commonDesktopDir = [Environment]::GetFolderPath('CommonDesktopDirectory') $userProgramsDir = [Environment]::GetFolderPath('Programs') +$commonProgramsDir = [Environment]::GetFolderPath('CommonPrograms') +$userStartupDir = [Environment]::GetFolderPath('Startup') $zhDesktop = ([string][char]0x684C + [string][char]0x9762) $flatSpecs = New-Object System.Collections.Generic.List[object] $seenScanDir = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase) -function Add-ScanDir([string]$dirPath, [bool]$isCommon, [string]$kind, [bool]$expandVendorSubdir) { +function Add-ScanDir([string]$dirPath, [bool]$isCommon, [string]$kind, [bool]$expandVendorSubdir, [bool]$recordDiscovered) { if (-not $dirPath) { return } if (-not $seenScanDir.Add($dirPath)) { return } $exists = $false try { $exists = [bool](Test-Path -LiteralPath $dirPath -ErrorAction SilentlyContinue) } catch { $exists = $false } if (-not $exists) { return } $flatSpecs.Add(@{ Dir = $dirPath; IsCommon = $isCommon; Kind = $kind }) + if ($recordDiscovered) { $discoveredDirs.Add($dirPath) } if ($expandVendorSubdir) { try { - foreach ($sub in @(Get-ChildItem -LiteralPath $dirPath -Directory -Filter 'Antigravity*' -ErrorAction SilentlyContinue)) { - if ($sub -and $sub.FullName -and $seenScanDir.Add([string]$sub.FullName)) { + foreach ($sub in @(Get-ChildItem -LiteralPath $dirPath -Directory -ErrorAction SilentlyContinue)) { + if ($sub -and $sub.Name -and ($sub.Name -match '(?i)antigravity|^google(?:\\b|[\\s_-]|$)') -and $sub.FullName -and $seenScanDir.Add([string]$sub.FullName)) { $flatSpecs.Add(@{ Dir = [string]$sub.FullName; IsCommon = $isCommon; Kind = $kind }) + if ($recordDiscovered) { $discoveredDirs.Add([string]$sub.FullName) } } } } catch {} } } +Add-ScanDir $userDesktopDir $false 'desktop' $false $true foreach ($d in @( - [Environment]::GetFolderPath('Desktop'), $(if ($env:USERPROFILE) { Join-Path $env:USERPROFILE 'Desktop' } else { '' }), $(if ($env:USERPROFILE) { Join-Path $env:USERPROFILE $zhDesktop } else { '' }) )) { - Add-ScanDir $d $false 'desktop' $false + Add-ScanDir $d $false 'desktop' $false $false } foreach ($od in @($env:OneDrive, $env:OneDriveConsumer, $env:OneDriveCommercial)) { if ($od) { - Add-ScanDir (Join-Path $od 'Desktop') $false 'desktop' $false - Add-ScanDir (Join-Path $od $zhDesktop) $false 'desktop' $false + Add-ScanDir (Join-Path $od 'Desktop') $false 'desktop' $false $false + Add-ScanDir (Join-Path $od $zhDesktop) $false 'desktop' $false $false } } -Add-ScanDir $userProgramsDir $false 'programs' $true -Add-ScanDir ([Environment]::GetFolderPath('StartMenu')) $false 'startmenu' $false -Add-ScanDir ([Environment]::GetFolderPath('Startup')) $false 'startup' $false +Add-ScanDir $userProgramsDir $false 'programs' $true $true +Add-ScanDir ([Environment]::GetFolderPath('StartMenu')) $false 'startmenu' $false $false +Add-ScanDir $userStartupDir $false 'startup' $false $true if ($env:APPDATA) { - Add-ScanDir (Join-Path $env:APPDATA 'Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar') $false 'taskbar' $false + Add-ScanDir (Join-Path $env:APPDATA 'Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar') $false 'taskbar' $false $false } -Add-ScanDir ([Environment]::GetFolderPath('CommonDesktopDirectory')) $true 'desktop' $false -Add-ScanDir ([Environment]::GetFolderPath('CommonPrograms')) $true 'programs' $true +Add-ScanDir $commonDesktopDir $true 'desktop' $false $true +Add-ScanDir $commonProgramsDir $true 'programs' $true $true $seen = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase) foreach ($spec in $flatSpecs) { @@ -829,14 +904,19 @@ foreach ($spec in $flatSpecs) { } } -$runSubPath = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run' -try { - $runReadKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($runSubPath, $false) - if ($runReadKey) { +$runTargets = @( + @{ Root = [Microsoft.Win32.Registry]::CurrentUser; Label = 'HKCU'; SubPath = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run' }, + @{ Root = [Microsoft.Win32.Registry]::LocalMachine; Label = 'HKLM'; SubPath = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run' }, + @{ Root = [Microsoft.Win32.Registry]::LocalMachine; Label = 'HKLM'; SubPath = 'Software\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Run' } +) +foreach ($rt in $runTargets) { + try { + $runReadKey = $rt.Root.OpenSubKey($rt.SubPath, $false) + if (-not $runReadKey) { continue } $runNames = @($runReadKey.GetValueNames()) $runReadKey.Close() foreach ($valName in $runNames) { - $rk = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($runSubPath, $false) + $rk = $rt.Root.OpenSubKey($rt.SubPath, $false) if (-not $rk) { continue } $rawCmd = [string]$rk.GetValue($valName, '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) $rk.Close() @@ -846,94 +926,125 @@ try { $restPart = [string]$Matches[3] if ([System.IO.Path]::GetFileName($exeCandidate) -ine 'Antigravity.exe') { continue } $quotedExe = if ($Matches[1] -or $exeCandidate -match '\\s') { '"' + $exeCandidate + '"' } else { $exeCandidate } + $entryId = if ($rt.Label -eq 'HKLM') { "HKLM:Run:$($rt.SubPath)|$valName" } else { "HKCU:Run:$valName" } if ($enableFlag) { if ($restPart -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { - $configured.Add("HKCU:Run:$valName") + $configured.Add($entryId) continue } $nextRest = ($restPart.Trim() + ' --remote-debugging-port=0').Trim() $nextVal = "$quotedExe $nextRest" + $saved = $false try { - $wk = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($runSubPath, $true) + $wk = $rt.Root.OpenSubKey($rt.SubPath, $true) if ($wk) { $wk.SetValue($valName, $nextVal, [Microsoft.Win32.RegistryValueKind]::String) $wk.Close() - $updated.Add("HKCU:Run:$valName") - $configured.Add("HKCU:Run:$valName") + $saved = $true } } catch {} + if ($saved) { + $updated.Add($entryId) + $configured.Add($entryId) + } elseif ($rt.Label -eq 'HKLM') { + $readOnly.Add($entryId) + } } else { $strippedRest = ([regex]::Replace($restPart, '(?:^|\\s+)--remote-debugging-port=(?:"0"|''0''|0)(?=\\s|$)', ' ')).Trim() $nextVal = if ($strippedRest) { "$quotedExe $strippedRest" } else { $quotedExe } if ($nextVal -ne $rawCmd.Trim()) { + $saved = $false try { - $wk = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($runSubPath, $true) + $wk = $rt.Root.OpenSubKey($rt.SubPath, $true) if ($wk) { $wk.SetValue($valName, $nextVal, [Microsoft.Win32.RegistryValueKind]::String) $wk.Close() - $updated.Add("HKCU:Run:$valName") + $saved = $true } } catch {} + if ($saved) { + $updated.Add($entryId) + } elseif ($rt.Label -eq 'HKLM') { + $readOnly.Add($entryId) + } } if ($strippedRest -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { - $configured.Add("HKCU:Run:$valName") + $configured.Add($entryId) } } } - } -} catch {} + } catch {} +} $exactClassSubKeys = @( 'Software\\Classes\\antigravity\\shell\\open\\command', 'Software\\Classes\\Applications\\Antigravity.exe\\shell\\open\\command', 'Software\\Classes\\AntigravitySourceFile\\shell\\open\\command' ) -foreach ($relSubKey in $exactClassSubKeys) { - try { - $rOpen = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($relSubKey, $false) - if (-not $rOpen) { continue } - $rawOpen = [string]$rOpen.GetValue('', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) - $rOpen.Close() - if (-not $rawOpen) { continue } - if ($rawOpen -notmatch '^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$') { continue } - $exeCand = if ($Matches[1]) { $Matches[1] } else { $Matches[2] } - $restOpen = ([string]$Matches[3]).Trim() - if ([System.IO.Path]::GetFileName($exeCand) -ine 'Antigravity.exe') { continue } - $quotedOpenExe = if ($Matches[1] -or $exeCand -match '\\s') { '"' + $exeCand + '"' } else { $exeCand } - $fullKeyName = "HKEY_CURRENT_USER\\$relSubKey" - if ($enableFlag) { - if ($restOpen -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { - $configured.Add($fullKeyName) - continue - } - $nextOpen = if ($restOpen) { "$quotedOpenExe --remote-debugging-port=0 $restOpen" } else { "$quotedOpenExe --remote-debugging-port=0" } - try { - $wOpen = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($relSubKey, $true) - if ($wOpen) { - $wOpen.SetValue('', $nextOpen, [Microsoft.Win32.RegistryValueKind]::String) - $wOpen.Close() - $updated.Add($fullKeyName) +$classRoots = @( + @{ Root = [Microsoft.Win32.Registry]::CurrentUser; Label = 'HKCU'; FullPrefix = 'HKEY_CURRENT_USER' }, + @{ Root = [Microsoft.Win32.Registry]::LocalMachine; Label = 'HKLM'; FullPrefix = 'HKEY_LOCAL_MACHINE' } +) +foreach ($cr in $classRoots) { + foreach ($relSubKey in $exactClassSubKeys) { + try { + $rOpen = $cr.Root.OpenSubKey($relSubKey, $false) + if (-not $rOpen) { continue } + $rawOpen = [string]$rOpen.GetValue('', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) + $rOpen.Close() + if (-not $rawOpen) { continue } + if ($rawOpen -notmatch '^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$') { continue } + $exeCand = if ($Matches[1]) { $Matches[1] } else { $Matches[2] } + $restOpen = ([string]$Matches[3]).Trim() + if ([System.IO.Path]::GetFileName($exeCand) -ine 'Antigravity.exe') { continue } + $quotedOpenExe = if ($Matches[1] -or $exeCand -match '\\s') { '"' + $exeCand + '"' } else { $exeCand } + $fullKeyName = if ($cr.Label -eq 'HKLM') { "HKLM:Class:$relSubKey" } else { "$($cr.FullPrefix)\\$relSubKey" } + if ($enableFlag) { + if ($restOpen -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { $configured.Add($fullKeyName) + continue } - } catch {} - } else { - $strippedOpen = ([regex]::Replace($restOpen, '(?:^|\\s+)--remote-debugging-port=(?:"0"|''0''|0)(?=\\s|$)', ' ')).Trim() - $nextOpen = if ($strippedOpen) { "$quotedOpenExe $strippedOpen" } else { $quotedOpenExe } - if ($nextOpen -ne $rawOpen.Trim()) { + $nextOpen = if ($restOpen) { "$quotedOpenExe --remote-debugging-port=0 $restOpen" } else { "$quotedOpenExe --remote-debugging-port=0" } + $saved = $false try { - $wOpen = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($relSubKey, $true) + $wOpen = $cr.Root.OpenSubKey($relSubKey, $true) if ($wOpen) { $wOpen.SetValue('', $nextOpen, [Microsoft.Win32.RegistryValueKind]::String) $wOpen.Close() - $updated.Add($fullKeyName) + $saved = $true } } catch {} + if ($saved) { + $updated.Add($fullKeyName) + $configured.Add($fullKeyName) + } elseif ($cr.Label -eq 'HKLM') { + $readOnly.Add($fullKeyName) + } + } else { + $strippedOpen = ([regex]::Replace($restOpen, '(?:^|\\s+)--remote-debugging-port=(?:"0"|''0''|0)(?=\\s|$)', ' ')).Trim() + $nextOpen = if ($strippedOpen) { "$quotedOpenExe $strippedOpen" } else { $quotedOpenExe } + if ($nextOpen -ne $rawOpen.Trim()) { + $saved = $false + try { + $wOpen = $cr.Root.OpenSubKey($relSubKey, $true) + if ($wOpen) { + $wOpen.SetValue('', $nextOpen, [Microsoft.Win32.RegistryValueKind]::String) + $wOpen.Close() + $saved = $true + } + } catch {} + if ($saved) { + $updated.Add($fullKeyName) + } elseif ($cr.Label -eq 'HKLM') { + $readOnly.Add($fullKeyName) + } + } + if ($strippedOpen -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { + $configured.Add($fullKeyName) + } } - if ($strippedOpen -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { - $configured.Add($fullKeyName) - } - } - } catch {} + } catch {} + } } [pscustomobject]@{ @@ -941,9 +1052,80 @@ foreach ($relSubKey in $exactClassSubKeys) { updatedPaths = @($updated) configuredPaths = @($configured) readOnlyPaths = @($readOnly) + discoveredDirs = @($discoveredDirs) } | ConvertTo-Json -Compress `.trim(); +const cachedDiscoveredWinDirsByHome = new Map(); + +function getCachedWinDiscoveredDirs(homeDir) { + const key = String(homeDir || '').trim().toLowerCase(); + return cachedDiscoveredWinDirsByHome.get(key) || []; +} + +function rememberWinDiscoveredDirs(homeDir, dirs) { + if (!Array.isArray(dirs) || dirs.length === 0) return; + const key = String(homeDir || '').trim().toLowerCase(); + const seen = new Set(); + const list = []; + for (const d of dirs) { + const clean = String(d || '').trim(); + if (!clean) continue; + const norm = clean.toLowerCase(); + if (!seen.has(norm)) { + seen.add(norm); + list.push(clean); + } + } + if (list.length > 0) { + cachedDiscoveredWinDirsByHome.set(key, list); + } +} + +function collectLinuxDesktopCandidates(dirPath, ops, { filterByName = false, fallbackNames = [] } = {}) { + const files = []; + const seen = new Set(); + const joinDir = (name) => + dirPath.startsWith('/') + ? `${dirPath.replace(/\/+$/, '')}/${name}` + : join(dirPath, name); + const addName = (name) => { + const clean = String(name || '').trim(); + if (!clean || !clean.toLowerCase().endsWith('.desktop')) return; + if (filterByName && !clean.toLowerCase().includes('antigravity')) return; + const full = joinDir(clean); + if (!seen.has(full)) { + seen.add(full); + files.push({ name: clean, full }); + } + }; + + try { + const rawEntries = ops.readdirFn(dirPath); + if (Array.isArray(rawEntries)) { + let count = 0; + for (const entry of rawEntries) { + const name = typeof entry === 'string' ? entry : String(entry?.name || ''); + if (!name || !name.toLowerCase().endsWith('.desktop')) continue; + count += 1; + if (count > 256) break; + addName(name); + } + } + } catch { + // 目录不存在或无读取权限时退回显式候选探测 + } + + for (const fallback of fallbackNames) { + const full = joinDir(fallback); + if (!seen.has(full) && ops.existsFn(full)) { + seen.add(full); + files.push({ name: fallback, full }); + } + } + return files; +} + /** * 自动同步当前系统下用户空间启动入口(Windows `.lnk` / `HKCU:Run` / `HKCU:Classes`、Linux `.desktop`)中的 `--remote-debugging-port=0`。 * @@ -1005,7 +1187,12 @@ export async function ensureDesktopLaunchEntriesConfigured({ if (platform === 'win32') { // 稳态零子进程快检:当调试端口已活跃或处于周期复检且所有 `.lnk` 字节内均已含参数时,直接返回(<2ms,不拉起 PowerShell) if (!execFileFn && fastCheckIfActive) { - const fast = probeWindowsShortcutsFast({ env, homeDir, fsOps: ops }); + const fast = probeWindowsShortcutsFast({ + env, + homeDir, + extraDirs: getCachedWinDiscoveredDirs(homeDir), + fsOps: ops, + }); if (enabled && fast.allConfigured) { return { checked: true, @@ -1060,6 +1247,9 @@ export async function ensureDesktopLaunchEntriesConfigured({ const readOnlyPaths = Array.isArray(parsed?.readOnlyPaths) ? parsed.readOnlyPaths.map(String).filter(Boolean) : []; + if (Array.isArray(parsed?.discoveredDirs) && parsed.discoveredDirs.length > 0) { + rememberWinDiscoveredDirs(homeDir, parsed.discoveredDirs); + } const hasReadOnlyShortcuts = enabled && readOnlyPaths.length > 0; return { checked: true, @@ -1090,46 +1280,116 @@ export async function ensureDesktopLaunchEntriesConfigured({ if (platform === 'linux') { const dataHome = env?.XDG_DATA_HOME || join(homeDir, '.local', 'share'); const configHome = env?.XDG_CONFIG_HOME || join(homeDir, '.config'); - const userDesktopFile = join(dataHome, 'applications', 'antigravity.desktop'); - const systemDesktopFiles = [ - '/usr/share/applications/antigravity.desktop', - '/usr/local/share/applications/antigravity.desktop', - ]; - const autostartDesktopFile = join(configHome, 'autostart', 'antigravity.desktop'); + const userAppsDir = join(dataHome, 'applications'); + const userAutostartDir = join(configHome, 'autostart'); + const systemAppsDirs = []; + const seenSysDirs = new Set([userAppsDir]); + const addSysAppsDir = (d) => { + const clean = String(d || '').trim(); + if (!clean || seenSysDirs.has(clean)) return; + seenSysDirs.add(clean); + systemAppsDirs.push(clean); + }; + addSysAppsDir('/usr/share/applications'); + addSysAppsDir('/usr/local/share/applications'); + const rawDataDirs = String(env?.XDG_DATA_DIRS || '').trim(); + if (rawDataDirs) { + const dataDirParts = /^[A-Za-z]:[\\/]/.test(rawDataDirs) + ? rawDataDirs.split(';') + : rawDataDirs.split(':'); + for (const base of dataDirParts) { + const cleanBase = base.trim(); + if (cleanBase) { + addSysAppsDir( + cleanBase.startsWith('/') + ? `${cleanBase.replace(/\/+$/, '')}/applications` + : join(cleanBase, 'applications') + ); + } + } + } const updatedPaths = []; const configuredPaths = []; + const handledUserFileNames = new Set(); + + const readDesktopTextSafe = (filePath) => { + try { + const st = ops.statFn(filePath); + if (st && Number(st.size) > 65536) return ''; + } catch { + // 允许单测 mock 仅实现 existsFn/readFn 而不提供 statFn + } + try { + return String(ops.readFn(filePath, 'utf8') || ''); + } catch { + return ''; + } + }; try { - let baseUserText = ''; - if (ops.existsFn(userDesktopFile)) { - baseUserText = String(ops.readFn(userDesktopFile, 'utf8') || ''); - } else if (enabled) { - const sysSource = systemDesktopFiles.find((p) => ops.existsFn(p)); - if (sysSource) { - baseUserText = String(ops.readFn(sysSource, 'utf8') || ''); - } - } - if (baseUserText) { - const patched = patchLinuxDesktopEntryText(baseUserText, { enabled }); + const userCandidates = collectLinuxDesktopCandidates(userAppsDir, ops, { + filterByName: false, + fallbackNames: ['antigravity.desktop'], + }); + for (const cand of userCandidates) { + const rawText = readDesktopTextSafe(cand.full); + if (!rawText) continue; + const patched = patchLinuxDesktopEntryText(rawText, { enabled }); + if (!patched.matched) continue; + handledUserFileNames.add(cand.name.toLowerCase()); if (patched.changed) { - writeTextFileAtomically(userDesktopFile, patched.text, ops); - updatedPaths.push(userDesktopFile); + writeTextFileAtomically(cand.full, patched.text, ops); + updatedPaths.push(cand.full); } if (patched.configured) { - configuredPaths.push(userDesktopFile); + configuredPaths.push(cand.full); } } - if (ops.existsFn(autostartDesktopFile)) { - const autoRaw = String(ops.readFn(autostartDesktopFile, 'utf8') || ''); + if (enabled) { + for (const sysDir of systemAppsDirs) { + const sysCandidates = collectLinuxDesktopCandidates(sysDir, ops, { + filterByName: true, + fallbackNames: ['antigravity.desktop'], + }); + for (const cand of sysCandidates) { + const nameKey = cand.name.toLowerCase(); + if (handledUserFileNames.has(nameKey)) continue; + const rawText = readDesktopTextSafe(cand.full); + if (!rawText) continue; + const patched = patchLinuxDesktopEntryText(rawText, { enabled: true }); + if (!patched.matched) continue; + handledUserFileNames.add(nameKey); + if (patched.changed) { + const targetUserFile = join(userAppsDir, cand.name); + writeTextFileAtomically(targetUserFile, patched.text, ops); + updatedPaths.push(targetUserFile); + if (patched.configured) { + configuredPaths.push(targetUserFile); + } + } else if (patched.configured) { + configuredPaths.push(cand.full); + } + } + } + } + + const autostartCandidates = collectLinuxDesktopCandidates(userAutostartDir, ops, { + filterByName: false, + fallbackNames: ['antigravity.desktop'], + }); + for (const cand of autostartCandidates) { + const autoRaw = readDesktopTextSafe(cand.full); + if (!autoRaw) continue; const patchedAuto = patchLinuxDesktopEntryText(autoRaw, { enabled }); + if (!patchedAuto.matched) continue; if (patchedAuto.changed) { - writeTextFileAtomically(autostartDesktopFile, patchedAuto.text, ops); - updatedPaths.push(autostartDesktopFile); + writeTextFileAtomically(cand.full, patchedAuto.text, ops); + updatedPaths.push(cand.full); } if (patchedAuto.configured) { - configuredPaths.push(autostartDesktopFile); + configuredPaths.push(cand.full); } } @@ -1221,13 +1481,33 @@ async function discoverRunningHostExecutable({ if (bundlePath && /\.app$/i.test(bundlePath)) { return { found: true, - kind: 'desktop', + kind: /antigravity\s*ide\.app$/i.test(bundlePath) ? 'ide' : 'desktop', executablePath: bundlePath, appBundlePath: bundlePath, }; } } catch { - // 忽略 AppleScript 探测异常 + // 忽略 AppleScript 探测异常(例如 TCC 限制),回退无权限依赖的 ps 扫描 + } + try { + const psOut = await runner('ps', ['-axo', 'comm='], { timeoutMs: 3000 }); + for (const rawLine of String(psOut || '').split(/\r?\n/)) { + const line = rawLine.trim(); + const m = line.match(/^(\/.+?\.app)\/Contents\/MacOS\/([^/]+)$/i); + if (!m) continue; + const bundlePath = m[1]; + const binLeaf = m[2]; + if (!/antigravity/i.test(bundlePath) && !/antigravity/i.test(binLeaf)) continue; + if (/helper/i.test(binLeaf)) continue; + return { + found: true, + kind: /antigravity\s*ide\.app$/i.test(bundlePath) ? 'ide' : 'desktop', + executablePath: line, + appBundlePath: bundlePath, + }; + } + } catch { + // 忽略 ps 探测异常 } } else if (platform === 'linux') { if (!execFileFn && typeof process.getuid === 'function') { @@ -1239,7 +1519,9 @@ async function discoverRunningHostExecutable({ try { const st = statSync(procDir); if (st.uid !== myUid) continue; - const exeTarget = String(readlinkSync(`${procDir}/exe`) || '').trim(); + const exeTarget = String(readlinkSync(`${procDir}/exe`) || '') + .trim() + .replace(/\s+\(deleted\)$/, ''); if (!exeTarget) continue; const leaf = basename(exeTarget); if (!isLinuxAntigravityDesktopLeaf(leaf)) continue; @@ -1328,13 +1610,14 @@ export function buildWindowsRelaunchInnerScript( .join(', '); return ` +param([string]$HostElevated = '0') Start-Sleep -Milliseconds 480 $exe = ${psSingleQuote(executablePath)} $procName = ${psSingleQuote(procName)} $psExe = ${psSingleQuote(psExe)} $staleList = @(${portLiterals}) $readOnlyShortcuts = @(${roLiterals}) -$wasHostElevated = $env:AGY_HOST_WAS_ELEVATED -eq '1' +$wasHostElevated = ($HostElevated -eq '1') -or ($env:AGY_HOST_WAS_ELEVATED -eq '1') $isSelfElevated = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) $mySid = (Get-Process -Id $PID).SessionId @@ -1345,20 +1628,67 @@ if (-not $exe -or -not (Test-Path -LiteralPath $exe)) { function Patch-ShortcutList($paths) { if (-not $paths -or $paths.Count -eq 0) { return } - try { - $ws = New-Object -ComObject WScript.Shell - foreach ($lnk in $paths) { - if (-not $lnk -or -not (Test-Path -LiteralPath $lnk)) { continue } + $ws = $null + foreach ($item in $paths) { + if (-not $item) { continue } + if ($item.StartsWith('HKLM:Run:')) { try { - $sc = $ws.CreateShortcut($lnk) - $cur = [string]$sc.Arguments - if ($cur -notmatch '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { - $sc.Arguments = ($cur.Trim() + ' --remote-debugging-port=0').Trim() - $sc.Save() + $restKey = $item.Substring(9) + $sepIdx = $restKey.IndexOf('|') + if ($sepIdx -gt 0) { + $subPath = $restKey.Substring(0, $sepIdx) + $valName = $restKey.Substring($sepIdx + 1) + $rk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($subPath, $false) + if ($rk) { + $rawCmd = [string]$rk.GetValue($valName, '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) + $rk.Close() + if ($rawCmd -match '^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$') { + $exeCand = if ($Matches[1]) { $Matches[1] } else { $Matches[2] } + $restPart = [string]$Matches[3] + if ([System.IO.Path]::GetFileName($exeCand) -ieq 'Antigravity.exe' -and $restPart -notmatch '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { + $qExe = if ($Matches[1] -or $exeCand -match '\\s') { '"' + $exeCand + '"' } else { $exeCand } + $nextVal = ($qExe + ' ' + ($restPart.Trim() + ' --remote-debugging-port=0').Trim()).Trim() + $wk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($subPath, $true) + if ($wk) { $wk.SetValue($valName, $nextVal, [Microsoft.Win32.RegistryValueKind]::String); $wk.Close() } + } + } + } } } catch {} + continue } - } catch {} + if ($item.StartsWith('HKLM:Class:')) { + try { + $relKey = $item.Substring(11) + $rk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($relKey, $false) + if ($rk) { + $rawOpen = [string]$rk.GetValue('', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) + $rk.Close() + if ($rawOpen -match '^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$') { + $exeCand = if ($Matches[1]) { $Matches[1] } else { $Matches[2] } + $restOpen = ([string]$Matches[3]).Trim() + if ([System.IO.Path]::GetFileName($exeCand) -ieq 'Antigravity.exe' -and $restOpen -notmatch '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { + $qExe = if ($Matches[1] -or $exeCand -match '\\s') { '"' + $exeCand + '"' } else { $exeCand } + $nextOpen = if ($restOpen) { "$qExe --remote-debugging-port=0 $restOpen" } else { "$qExe --remote-debugging-port=0" } + $wk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($relKey, $true) + if ($wk) { $wk.SetValue('', $nextOpen, [Microsoft.Win32.RegistryValueKind]::String); $wk.Close() } + } + } + } + } catch {} + continue + } + if (-not (Test-Path -LiteralPath $item)) { continue } + try { + if (-not $ws) { $ws = New-Object -ComObject WScript.Shell } + $sc = $ws.CreateShortcut($item) + $cur = [string]$sc.Arguments + if ($cur -notmatch '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { + $sc.Arguments = ($cur.Trim() + ' --remote-debugging-port=0').Trim() + $sc.Save() + } + } catch {} + } } if ($readOnlyShortcuts.Count -gt 0) { @@ -1368,20 +1698,70 @@ if ($readOnlyShortcuts.Count -gt 0) { $elevPatchPs1 = Join-Path ([System.IO.Path]::GetTempPath()) ("agy-monitor-uac-lnk-" + $PID + ".ps1") $roJoined = ($readOnlyShortcuts | ForEach-Object { "'" + ($_.Replace("'", "''")) + "'" }) -join ', ' $elevBody = @( - "\$ws = New-Object -ComObject WScript.Shell", - "foreach (\$lnk in @($roJoined)) {", - " if (\$lnk -and (Test-Path -LiteralPath \$lnk)) {", - " try {", - " \$sc = \$ws.CreateShortcut(\$lnk)", - " \$cur = [string]\$sc.Arguments", - " if (\$cur -notmatch '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {", - " \$sc.Arguments = (\$cur.Trim() + ' --remote-debugging-port=0').Trim()", - " \$sc.Save()", - " }", - " } catch {}", - " }", - "}", - "Remove-Item -LiteralPath \$PSCommandPath -Force -ErrorAction SilentlyContinue" + ('$targets = @(' + $roJoined + ')'), + '$ws = $null', + 'foreach ($item in $targets) {', + ' if (-not $item) { continue }', + ' if ($item.StartsWith(''HKLM:Run:'')) {', + ' try {', + ' $restKey = $item.Substring(9)', + ' $sepIdx = $restKey.IndexOf(''|'')', + ' if ($sepIdx -gt 0) {', + ' $subPath = $restKey.Substring(0, $sepIdx)', + ' $valName = $restKey.Substring($sepIdx + 1)', + ' $rk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($subPath, $false)', + ' if ($rk) {', + ' $rawCmd = [string]$rk.GetValue($valName, '''', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)', + ' $rk.Close()', + ' if ($rawCmd -match ''^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$'') {', + ' $exeCand = if ($Matches[1]) { $Matches[1] } else { $Matches[2] }', + ' $restPart = [string]$Matches[3]', + ' if ([System.IO.Path]::GetFileName($exeCand) -ieq ''Antigravity.exe'' -and $restPart -notmatch ''(?:^|\\s)--remote-debugging-port(?:=|\\s|$)'') {', + ' $qExe = if ($Matches[1] -or $exeCand -match ''\\s'') { ''"'' + $exeCand + ''"'' } else { $exeCand }', + ' $nextVal = ($qExe + '' '' + ($restPart.Trim() + '' --remote-debugging-port=0'').Trim()).Trim()', + ' $wk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($subPath, $true)', + ' if ($wk) { $wk.SetValue($valName, $nextVal, [Microsoft.Win32.RegistryValueKind]::String); $wk.Close() }', + ' }', + ' }', + ' }', + ' }', + ' } catch {}', + ' continue', + ' }', + ' if ($item.StartsWith(''HKLM:Class:'')) {', + ' try {', + ' $relKey = $item.Substring(11)', + ' $rk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($relKey, $false)', + ' if ($rk) {', + ' $rawOpen = [string]$rk.GetValue('''', '''', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)', + ' $rk.Close()', + ' if ($rawOpen -match ''^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$'') {', + ' $exeCand = if ($Matches[1]) { $Matches[1] } else { $Matches[2] }', + ' $restOpen = ([string]$Matches[3]).Trim()', + ' if ([System.IO.Path]::GetFileName($exeCand) -ieq ''Antigravity.exe'' -and $restOpen -notmatch ''(?:^|\\s)--remote-debugging-port(?:=|\\s|$)'') {', + ' $qExe = if ($Matches[1] -or $exeCand -match ''\\s'') { ''"'' + $exeCand + ''"'' } else { $exeCand }', + ' $nextOpen = if ($restOpen) { $qExe + '' --remote-debugging-port=0 '' + $restOpen } else { $qExe + '' --remote-debugging-port=0'' }', + ' $wk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($relKey, $true)', + ' if ($wk) { $wk.SetValue('''', $nextOpen, [Microsoft.Win32.RegistryValueKind]::String); $wk.Close() }', + ' }', + ' }', + ' }', + ' } catch {}', + ' continue', + ' }', + ' if (Test-Path -LiteralPath $item) {', + ' try {', + ' if (-not $ws) { $ws = New-Object -ComObject WScript.Shell }', + ' $sc = $ws.CreateShortcut($item)', + ' $cur = [string]$sc.Arguments', + ' if ($cur -notmatch ''(?:^|\\s)--remote-debugging-port(?:=|\\s|$)'') {', + ' $sc.Arguments = ($cur.Trim() + '' --remote-debugging-port=0'').Trim()', + ' $sc.Save()', + ' }', + ' } catch {}', + ' }', + '}', + 'Remove-Item -LiteralPath $PSCommandPath -Force -ErrorAction SilentlyContinue' ) -join "\`r\`n" try { [System.IO.File]::WriteAllText($elevPatchPs1, $elevBody, (New-Object System.Text.UTF8Encoding($true))) @@ -1422,13 +1802,17 @@ if ((& $findTargets).Count -gt 0 -and -not $isSelfElevated -and $exe -and (Test- $exeLit = "'" + $exe.Replace("'", "''") + "'" $procLit = "'" + $procName.Replace("'", "''") + "'" $elevKillBody = @( - "\$mySid = (Get-Process -Id \$PID).SessionId", - "Get-Process -Name $procLit -ErrorAction SilentlyContinue | Where-Object { \$_.SessionId -eq \$mySid } | Stop-Process -Force -ErrorAction SilentlyContinue", - "Start-Sleep -Milliseconds 600", - "foreach (\$fp in @($staleJoined)) { if (\$fp -and (Test-Path -LiteralPath \$fp)) { Remove-Item -LiteralPath \$fp -Force -ErrorAction SilentlyContinue } }", - "\$wd = Split-Path -Parent $exeLit", - "Start-Process -FilePath $exeLit -ArgumentList '--remote-debugging-port=0' -WorkingDirectory \$wd", - "Remove-Item -LiteralPath \$PSCommandPath -Force -ErrorAction SilentlyContinue" + ('$exe = ' + $exeLit), + ('$procName = ' + $procLit), + ('$staleList = @(' + $staleJoined + ')'), + '$mySid = (Get-Process -Id $PID).SessionId', + '$findTargets = { @(Get-Process -Name $procName -ErrorAction SilentlyContinue | Where-Object { $_.SessionId -eq $mySid -and (-not $_.Path -or -not $exe -or [string]::Equals($_.Path, $exe, [System.StringComparison]::OrdinalIgnoreCase)) }) }', + '& $findTargets | Stop-Process -Force -ErrorAction SilentlyContinue', + 'for ($i = 0; $i -lt 25; $i++) { if ((& $findTargets).Count -eq 0) { break }; Start-Sleep -Milliseconds 200 }', + 'foreach ($fp in $staleList) { if ($fp -and (Test-Path -LiteralPath $fp)) { Remove-Item -LiteralPath $fp -Force -ErrorAction SilentlyContinue } }', + '$wd = Split-Path -Parent $exe', + 'Start-Process -FilePath $exe -ArgumentList ''--remote-debugging-port=0'' -WorkingDirectory $wd', + 'Remove-Item -LiteralPath $PSCommandPath -Force -ErrorAction SilentlyContinue' ) -join "\`r\`n" try { [System.IO.File]::WriteAllText($elevRelaunchPs1, $elevKillBody, (New-Object System.Text.UTF8Encoding($true))) @@ -1473,8 +1857,9 @@ const WIN_OUT_OF_JOB_DISPATCH_PS = ` $ErrorActionPreference = 'Stop' $psBin = if ($env:AGY_PS_EXE) { $env:AGY_PS_EXE } else { 'powershell.exe' } $isElev = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -$env:AGY_HOST_WAS_ELEVATED = if ($isElev) { '1' } else { '0' } -$innerArgs = '-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File "' + $env:AGY_RELAUNCH_PS1 + '"' +$elevFlag = if ($isElev) { '1' } else { '0' } +$env:AGY_HOST_WAS_ELEVATED = $elevFlag +$innerArgs = '-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File "' + $env:AGY_RELAUNCH_PS1 + '" -HostElevated ' + $elevFlag $fullCmd = '"' + $psBin + '" ' + $innerArgs if ($isElev) { @@ -1613,18 +1998,23 @@ export async function triggerDesktopHostRelaunch({ if (platform === 'darwin') { const appTarget = hostInfo.appBundlePath || hostInfo.executablePath; - const appName = hostInfo.kind === 'ide' ? 'Antigravity IDE' : 'Antigravity'; + const bundleDerivedName = hostInfo.appBundlePath + ? basename(hostInfo.appBundlePath).replace(/\.app$/i, '').trim() + : ''; + const appName = + bundleDerivedName || (hostInfo.kind === 'ide' ? 'Antigravity IDE' : 'Antigravity'); const shScript = [ 'sleep 0.45', - `osascript -e 'tell application "${appName}" to quit' >/dev/null 2>&1 || true`, - `i=0; while [ $i -lt 25 ] && pgrep -x "${appName}" >/dev/null 2>&1; do sleep 0.2; i=$((i+1)); done`, - `if pgrep -x "${appName}" >/dev/null 2>&1; then killall "${appName}" >/dev/null 2>&1 || true; sleep 0.4; fi`, - 'IFS=":"; for f in $AGY_STALE_PORT_FILES; do [ -n "$f" ] && rm -f "$f"; done', + 'if osascript -e \'on run argv\' -e \'tell application (item 1 of argv) to quit\' -e \'end run\' -- "$AGY_APP_NAME" >/dev/null 2>&1; then i=0; while [ $i -lt 25 ] && pgrep -x "$AGY_APP_NAME" >/dev/null 2>&1; do sleep 0.2; i=$((i+1)); done; fi', + 'if pgrep -x "$AGY_APP_NAME" >/dev/null 2>&1; then pkill -TERM -x "$AGY_APP_NAME" >/dev/null 2>&1 || killall -TERM "$AGY_APP_NAME" >/dev/null 2>&1 || true; j=0; while [ $j -lt 20 ] && pgrep -x "$AGY_APP_NAME" >/dev/null 2>&1; do sleep 0.2; j=$((j+1)); done; fi', + 'if pgrep -x "$AGY_APP_NAME" >/dev/null 2>&1; then pkill -KILL -x "$AGY_APP_NAME" >/dev/null 2>&1 || killall -KILL "$AGY_APP_NAME" >/dev/null 2>&1 || true; k=0; while [ $k -lt 15 ] && pgrep -x "$AGY_APP_NAME" >/dev/null 2>&1; do sleep 0.2; k=$((k+1)); done; fi', + 'old_ifs="$IFS"; set -f; IFS=":"; for f in $AGY_STALE_PORT_FILES; do [ -n "$f" ] && rm -f "$f"; done; set +f; IFS="$old_ifs"', 'open -a "$AGY_RELAUNCH_APP" --args --remote-debugging-port=0 >/dev/null 2>&1', ].join('; '); await spawner('/bin/sh', ['-c', shScript], { env: { ...cleanEnv, + AGY_APP_NAME: appName, AGY_RELAUNCH_APP: appTarget, AGY_STALE_PORT_FILES: cleanStaleFiles.join(':'), }, @@ -1638,12 +2028,15 @@ export async function triggerDesktopHostRelaunch({ } const procLeaf = basename(hostInfo.executablePath) || 'antigravity'; + const procComm = procLeaf.slice(0, 15); const linuxScript = [ 'sleep 0.45', 'uid="$(id -u)"', - 'for pn in "$AGY_PROC_NAME" antigravity Antigravity; do [ -n "$pn" ] && pkill -u "$uid" -x "$pn" >/dev/null 2>&1 || true; done', - 'i=0; while [ $i -lt 25 ] && (pgrep -u "$uid" -x "$AGY_PROC_NAME" >/dev/null 2>&1 || pgrep -u "$uid" -x antigravity >/dev/null 2>&1 || pgrep -u "$uid" -x Antigravity >/dev/null 2>&1); do sleep 0.2; i=$((i+1)); done', - 'IFS=":"; for f in $AGY_STALE_PORT_FILES; do [ -n "$f" ] && rm -f "$f"; done', + 'is_alive() { for pn in "$AGY_PROC_NAME" antigravity Antigravity "$AGY_PROC_COMM" google-antigravity; do [ -n "$pn" ] && pgrep -u "$uid" -x "$pn" >/dev/null 2>&1 && return 0; done; return 1; }', + 'for pn in "$AGY_PROC_NAME" antigravity Antigravity "$AGY_PROC_COMM" google-antigravity; do [ -n "$pn" ] && pkill -TERM -u "$uid" -x "$pn" >/dev/null 2>&1 || true; done', + 'i=0; while [ $i -lt 25 ] && is_alive; do sleep 0.2; i=$((i+1)); done', + 'if is_alive; then for pn in "$AGY_PROC_NAME" antigravity Antigravity "$AGY_PROC_COMM" google-antigravity; do [ -n "$pn" ] && pkill -KILL -u "$uid" -x "$pn" >/dev/null 2>&1 || true; done; j=0; while [ $j -lt 15 ] && is_alive; do sleep 0.2; j=$((j+1)); done; fi', + 'old_ifs="$IFS"; set -f; IFS=":"; for f in $AGY_STALE_PORT_FILES; do [ -n "$f" ] && rm -f "$f"; done; set +f; IFS="$old_ifs"', 'nohup "$AGY_RELAUNCH_EXE" --remote-debugging-port=0 >/dev/null 2>&1 &', ].join('; '); await spawner('/bin/sh', ['-c', linuxScript], { @@ -1651,6 +2044,7 @@ export async function triggerDesktopHostRelaunch({ ...cleanEnv, AGY_RELAUNCH_EXE: hostInfo.executablePath, AGY_PROC_NAME: procLeaf, + AGY_PROC_COMM: procComm, AGY_STALE_PORT_FILES: cleanStaleFiles.join(':'), }, }); diff --git a/sidecars/panel/backend/window-bridge.mjs b/sidecars/panel/backend/window-bridge.mjs index ae53f5f..eddc4b5 100644 --- a/sidecars/panel/backend/window-bridge.mjs +++ b/sidecars/panel/backend/window-bridge.mjs @@ -10,7 +10,15 @@ * 3. 完全不触碰宿主 `app.asar` 文件,客户端升级或无调试端口时静默回退至右侧辅助栏。 */ -import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'; +import { + existsSync, + mkdirSync, + readdirSync, + readFileSync, + renameSync, + unlinkSync, + writeFileSync, +} from 'node:fs'; import { homedir } from 'node:os'; import { dirname, join } from 'node:path'; import { @@ -54,46 +62,110 @@ const ALLOWED_BRIDGE_PATHS = new Set(BRIDGE_API_PATHS); /** * 解析各操作系统下 Antigravity 2.0 与 Antigravity IDE 写入 `DevToolsActivePort` 的候选路径列表。 + * Linux 额外兼容全小写目录名、自定义 `XDG_CONFIG_HOME` 回退以及 Flatpak / Snap 一级容器配置目录。 * * @param {Record} [env=process.env] * @param {string} [platform=process.platform] * @param {string} [homeDir=homedir()] + * @param {{ readdirFn?: typeof readdirSync }|null} [fsOps=null] * @returns {string[]} */ export function resolveDevToolsPortCandidates( env = process.env, platform = process.platform, - homeDir = homedir() + homeDir = homedir(), + fsOps = null ) { const explicitFile = String(env?.ANTIGRAVITY_DEVTOOLS_PORT_FILE || '').trim(); if (explicitFile) { return [explicitFile]; } + const out = []; + const seen = new Set(); + const pushUnique = (p) => { + const clean = String(p || '').trim(); + if (clean && !seen.has(clean)) { + seen.add(clean); + out.push(clean); + } + }; + const portableRoot = String(env?.VSCODE_PORTABLE || '').trim(); + if (platform === 'win32') { const appData = env?.APPDATA || join(homeDir, 'AppData', 'Roaming'); const localAppData = env?.LOCALAPPDATA || join(homeDir, 'AppData', 'Local'); - return [ - join(appData, 'Antigravity', 'DevToolsActivePort'), - join(localAppData, 'Antigravity', 'DevToolsActivePort'), - join(appData, 'Antigravity IDE', 'DevToolsActivePort'), - join(localAppData, 'Antigravity IDE', 'DevToolsActivePort'), - ]; + pushUnique(join(appData, 'Antigravity', 'DevToolsActivePort')); + pushUnique(join(localAppData, 'Antigravity', 'DevToolsActivePort')); + pushUnique(join(appData, 'Antigravity IDE', 'DevToolsActivePort')); + pushUnique(join(localAppData, 'Antigravity IDE', 'DevToolsActivePort')); + if (portableRoot) { + pushUnique(join(portableRoot, 'user-data', 'DevToolsActivePort')); + } + return out; } if (platform === 'darwin') { - return [ - join(homeDir, 'Library', 'Application Support', 'Antigravity', 'DevToolsActivePort'), - join(homeDir, 'Library', 'Application Support', 'Antigravity IDE', 'DevToolsActivePort'), - join(homeDir, 'Library', 'Application Support', 'antigravity', 'DevToolsActivePort'), - join(homeDir, 'Library', 'Application Support', 'antigravity-ide', 'DevToolsActivePort'), - join(homeDir, '.config', 'Antigravity', 'DevToolsActivePort'), - join(homeDir, '.config', 'Antigravity IDE', 'DevToolsActivePort'), - ]; + pushUnique(join(homeDir, 'Library', 'Application Support', 'Antigravity', 'DevToolsActivePort')); + pushUnique( + join(homeDir, 'Library', 'Application Support', 'Antigravity IDE', 'DevToolsActivePort') + ); + pushUnique(join(homeDir, 'Library', 'Application Support', 'antigravity', 'DevToolsActivePort')); + pushUnique( + join(homeDir, 'Library', 'Application Support', 'antigravity-ide', 'DevToolsActivePort') + ); + pushUnique(join(homeDir, '.config', 'Antigravity', 'DevToolsActivePort')); + pushUnique(join(homeDir, '.config', 'Antigravity IDE', 'DevToolsActivePort')); + if (portableRoot) { + pushUnique(join(portableRoot, 'user-data', 'DevToolsActivePort')); + } + return out; } - const configHome = env?.XDG_CONFIG_HOME || join(homeDir, '.config'); - return [ - join(configHome, 'Antigravity', 'DevToolsActivePort'), - join(configHome, 'Antigravity IDE', 'DevToolsActivePort'), - ]; + + const defaultConfigHome = join(homeDir, '.config'); + const configHome = env?.XDG_CONFIG_HOME || defaultConfigHome; + pushUnique(join(configHome, 'Antigravity', 'DevToolsActivePort')); + pushUnique(join(configHome, 'Antigravity IDE', 'DevToolsActivePort')); + pushUnique(join(configHome, 'antigravity', 'DevToolsActivePort')); + pushUnique(join(configHome, 'antigravity-ide', 'DevToolsActivePort')); + if (configHome !== defaultConfigHome) { + pushUnique(join(defaultConfigHome, 'Antigravity', 'DevToolsActivePort')); + pushUnique(join(defaultConfigHome, 'Antigravity IDE', 'DevToolsActivePort')); + pushUnique(join(defaultConfigHome, 'antigravity', 'DevToolsActivePort')); + pushUnique(join(defaultConfigHome, 'antigravity-ide', 'DevToolsActivePort')); + } + if (portableRoot) { + pushUnique(join(portableRoot, 'user-data', 'DevToolsActivePort')); + } + + const readdirFn = fsOps?.readdirFn || readdirSync; + const flatpakRoot = join(homeDir, '.var', 'app'); + try { + for (const rawEntry of readdirFn(flatpakRoot) || []) { + const appId = typeof rawEntry === 'string' ? rawEntry : String(rawEntry?.name || ''); + if (!appId || !/antigravity/i.test(appId)) continue; + pushUnique(join(flatpakRoot, appId, 'config', 'Antigravity', 'DevToolsActivePort')); + pushUnique(join(flatpakRoot, appId, 'config', 'antigravity', 'DevToolsActivePort')); + pushUnique(join(flatpakRoot, appId, 'config', 'Antigravity IDE', 'DevToolsActivePort')); + } + } catch { + // 宿主机未安装 Flatpak 或目录不可读时静默忽略 + } + + const snapRoot = join(homeDir, 'snap'); + try { + for (const rawEntry of readdirFn(snapRoot) || []) { + const snapName = typeof rawEntry === 'string' ? rawEntry : String(rawEntry?.name || ''); + if (!snapName || !/antigravity/i.test(snapName)) continue; + pushUnique(join(snapRoot, snapName, 'current', '.config', 'Antigravity', 'DevToolsActivePort')); + pushUnique(join(snapRoot, snapName, 'current', '.config', 'antigravity', 'DevToolsActivePort')); + pushUnique( + join(snapRoot, snapName, 'current', '.config', 'Antigravity IDE', 'DevToolsActivePort') + ); + } + } catch { + // 宿主机未安装 Snap 或目录不可读时静默忽略 + } + + return out; } /** diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index b4fe942..4dd279d 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -113,9 +113,40 @@ test('DevToolsActivePort parsing, cross-platform discovery (2.0 + IDE), and stri ); const linuxPaths = resolveDevToolsPortCandidates({ XDG_CONFIG_HOME: '/home/dev/.config' }, 'linux', '/home/dev'); - assert.equal(linuxPaths.length, 2); + assert.equal(linuxPaths.length, 4); assert.equal(linuxPaths[0], path.join('/home/dev/.config', 'Antigravity', 'DevToolsActivePort')); assert.equal(linuxPaths[1], path.join('/home/dev/.config', 'Antigravity IDE', 'DevToolsActivePort')); + assert.equal(linuxPaths[2], path.join('/home/dev/.config', 'antigravity', 'DevToolsActivePort')); + assert.equal(linuxPaths[3], path.join('/home/dev/.config', 'antigravity-ide', 'DevToolsActivePort')); + + const linuxContainerPaths = resolveDevToolsPortCandidates( + { XDG_CONFIG_HOME: '/home/dev/.custom-cfg', VSCODE_PORTABLE: '/opt/ag-portable' }, + 'linux', + '/home/dev', + { + readdirFn: (dir) => { + if (dir === path.join('/home/dev', '.var', 'app')) { + return ['org.mozilla.firefox', 'com.google.Antigravity']; + } + if (dir === path.join('/home/dev', 'snap')) { + return ['firefox', 'antigravity']; + } + return []; + }, + } + ); + assert.ok(linuxContainerPaths.includes(path.join('/home/dev/.config', 'Antigravity', 'DevToolsActivePort'))); + assert.ok(linuxContainerPaths.includes(path.join('/opt/ag-portable', 'user-data', 'DevToolsActivePort'))); + assert.ok( + linuxContainerPaths.includes( + path.join('/home/dev', '.var', 'app', 'com.google.Antigravity', 'config', 'Antigravity', 'DevToolsActivePort') + ) + ); + assert.ok( + linuxContainerPaths.includes( + path.join('/home/dev', 'snap', 'antigravity', 'current', '.config', 'antigravity', 'DevToolsActivePort') + ) + ); assert.equal( isAntigravityMainPageTarget({ @@ -4991,8 +5022,10 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi const visitedDirs = []; const fakeDesktopDir = 'C:\\Users\\Dev\\Desktop'; + const fakeRedirectedDesktopDir = 'D:\\LocalizedDesktop'; const fakeProgramsDir = 'C:\\Users\\Dev\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs'; const fakeAgySubDir = `${fakeProgramsDir}\\Antigravity`; + const fakeGoogleSubDir = `${fakeProgramsDir}\\Google`; const fastProbeRes = probeWindowsShortcutsFast({ env: { USERPROFILE: 'C:\\Users\\Dev', @@ -5001,6 +5034,7 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi ProgramData: 'C:\\ProgramData', }, homeDir: 'C:\\Users\\Dev', + extraDirs: [fakeRedirectedDesktopDir], fsOps: { readdirFn: (dir) => { visitedDirs.push(dir); @@ -5010,15 +5044,22 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi { name: 'huge-repo-with-node_modules', isFile: () => false, isDirectory: () => true }, ]; } + if (dir === fakeRedirectedDesktopDir) { + return [{ name: 'Antigravity-Redir.lnk', isFile: () => true, isDirectory: () => false }]; + } if (dir === fakeProgramsDir) { return [ { name: 'Visual Studio 2022', isFile: () => false, isDirectory: () => true }, { name: 'Antigravity', isFile: () => false, isDirectory: () => true }, + { name: 'Google', isFile: () => false, isDirectory: () => true }, ]; } if (dir === fakeAgySubDir) { return [{ name: 'Antigravity IDE.lnk', isFile: () => true, isDirectory: () => false }]; } + if (dir === fakeGoogleSubDir) { + return [{ name: 'Antigravity-Google.lnk', isFile: () => true, isDirectory: () => false }]; + } return []; }, statFn: () => ({ size: 512 }), @@ -5029,6 +5070,9 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi }, }); assert.equal(fastProbeRes.allConfigured, true); + assert.equal(fastProbeRes.configuredPaths.length, 3); + assert.ok(fastProbeRes.configuredPaths.some((p) => p.includes('Antigravity-Redir.lnk'))); + assert.ok(fastProbeRes.configuredPaths.some((p) => p.includes('Antigravity-Google.lnk'))); assert.equal( visitedDirs.some((d) => d.includes('huge-repo') || d.includes('Visual Studio')), false, @@ -5074,6 +5118,13 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi }).matched, false ); + const linuxGoogleDashRaw = 'Exec=env -u BAD_VAR /usr/bin/google-antigravity -- %U'; + const linuxGoogleDashPatched = patchLinuxDesktopEntryText(linuxGoogleDashRaw, { enabled: true }); + assert.equal(linuxGoogleDashPatched.matched, true); + assert.equal( + linuxGoogleDashPatched.text, + 'Exec=env -u BAD_VAR /usr/bin/google-antigravity --remote-debugging-port=0 -- %U' + ); const resolvedLinuxAppImage = resolveDesktopHostExecutable({ env: { @@ -5121,7 +5172,8 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi assert.equal(resolvedMacHost.appBundlePath, '/Applications/Antigravity.app'); const sanitizedEnv = buildSanitizedDesktopRelaunchEnv({ - PATH: 'C:\\Windows\\System32', + PATH: '/tmp/.mount_Antigr123/usr/bin:/usr/local/bin:/usr/bin', + LD_LIBRARY_PATH: '/tmp/.mount_Antigr123/usr/lib:/usr/lib/x86_64-linux-gnu', USERPROFILE: 'C:\\Users\\Administrator', ANTIGRAVITY_LS_ADDRESS: 'localhost:13088', ANTIGRAVITY_CSRF_TOKEN: 'secret', @@ -5129,11 +5181,22 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi USAGE_MONITOR_HOST_PPID: '123', ELECTRON_RUN_AS_NODE: '1', NODE_OPTIONS: '--inspect', + APPIMAGE: '/home/alice/Antigravity.AppImage', + APPDIR: '/tmp/.mount_Antigr123', + OWD: '/home/alice', + ARGV0: '/home/alice/Antigravity.AppImage', + APPIMAGE_EXTRACT_AND_RUN: '1', }); assert.deepEqual(sanitizedEnv, { - PATH: 'C:\\Windows\\System32', + PATH: '/usr/local/bin:/usr/bin', + LD_LIBRARY_PATH: '/usr/lib/x86_64-linux-gnu', USERPROFILE: 'C:\\Users\\Administrator', }); + assert.equal( + buildSanitizedDesktopRelaunchEnv({ LD_LIBRARY_PATH: '/tmp/.mount_Only/lib' }).LD_LIBRARY_PATH, + undefined, + 'Omits LD_LIBRARY_PATH completely when only AppImage mount entries were present' + ); // 4. Linux .desktop provisioning on real temp dir + Windows shortcut provisioning + stale DevToolsActivePort (cdp_unreachable) + relaunch dispatch const simTmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ag-233-auto-')); @@ -5201,6 +5264,105 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi /--remote-debugging-port=0 %U/ ); + // Dynamic Linux .desktop discovery: vendor/AppImageLauncher/capitalized filenames across user, system, XDG_DATA_DIRS, and autostart + const linuxDynData = path.join(simTmp, 'xdg-data-dyn'); + const linuxDynCfg = path.join(simTmp, 'xdg-cfg-dyn'); + const linuxSysVendor = path.join(simTmp, 'sys-vendor-share'); + const appImageDesktop = path.join( + linuxDynData, + 'applications', + 'appimagekit_1a2b3c-Antigravity.desktop' + ); + const vendorSysDesktop = path.join(linuxSysVendor, 'applications', 'google-antigravity.desktop'); + const unrelatedSysDesktop = path.join(linuxSysVendor, 'applications', 'firefox.desktop'); + const capAutostart = path.join(linuxDynCfg, 'autostart', 'Antigravity.desktop'); + fs.mkdirSync(path.dirname(appImageDesktop), { recursive: true }); + fs.mkdirSync(path.dirname(vendorSysDesktop), { recursive: true }); + fs.mkdirSync(path.dirname(capAutostart), { recursive: true }); + fs.writeFileSync(appImageDesktop, linuxAppImageRaw, 'utf8'); + fs.writeFileSync( + vendorSysDesktop, + '[Desktop Entry]\nName=Antigravity\nExec=/usr/bin/google-antigravity %U\nType=Application\n', + 'utf8' + ); + fs.writeFileSync(unrelatedSysDesktop, '[Desktop Entry]\nName=Firefox\nExec=firefox %u\n', 'utf8'); + fs.writeFileSync(capAutostart, linuxDesktopRaw, 'utf8'); + const linuxDynProv = await ensureDesktopLaunchEntriesConfigured({ + enabled: true, + env: { + XDG_DATA_HOME: linuxDynData, + XDG_CONFIG_HOME: linuxDynCfg, + XDG_DATA_DIRS: linuxSysVendor, + }, + platform: 'linux', + homeDir, + allowInTest: true, + fsOps: { + existsFn: fs.existsSync, + readFn: fs.readFileSync, + writeFn: fs.writeFileSync, + mkdirFn: fs.mkdirSync, + renameFn: fs.renameSync, + unlinkFn: fs.unlinkSync, + readdirFn: fs.readdirSync, + statFn: fs.statSync, + }, + }); + assert.equal(linuxDynProv.updated, true); + assert.equal(linuxDynProv.updatedPaths.length, 3); + assert.match(fs.readFileSync(appImageDesktop, 'utf8'), /--remote-debugging-port=0 %U/); + assert.match( + fs.readFileSync(path.join(linuxDynData, 'applications', 'google-antigravity.desktop'), 'utf8'), + /google-antigravity --remote-debugging-port=0 %U/ + ); + assert.match(fs.readFileSync(capAutostart, 'utf8'), /--remote-debugging-port=0 %U/); + assert.equal(fs.existsSync(path.join(linuxDynData, 'applications', 'firefox.desktop')), false); + + // Verify Windows PowerShell provisioning covers HKLM Run/WOW6432Node/Classes + caches discoveredDirs for subsequent fastCheckIfActive + let capturedWinProvPs = ''; + const redirHome = 'C:\\Users\\RedirUser'; + const redirDesktop = 'D:\\RedirectedDesktop'; + await ensureDesktopLaunchEntriesConfigured({ + enabled: true, + env: { USERPROFILE: redirHome }, + platform: 'win32', + homeDir: redirHome, + allowInTest: true, + execFileFn: async (_f, args) => { + capturedWinProvPs = args[args.length - 1]; + return JSON.stringify({ + ok: true, + updatedPaths: [`${redirDesktop}\\Antigravity.lnk`], + configuredPaths: [`${redirDesktop}\\Antigravity.lnk`], + readOnlyPaths: [], + discoveredDirs: [redirDesktop], + }); + }, + }); + assert.match(capturedWinProvPs, /LocalMachine/); + assert.match(capturedWinProvPs, /WOW6432Node/); + assert.match(capturedWinProvPs, /HKLM:Run:/); + assert.match(capturedWinProvPs, /HKLM:Class:/); + const fastCachedRes = await ensureDesktopLaunchEntriesConfigured({ + enabled: true, + fastCheckIfActive: true, + env: { USERPROFILE: redirHome, APPDATA: '', PUBLIC: '', ProgramData: '' }, + platform: 'win32', + homeDir: redirHome, + allowInTest: true, + fsOps: { + readdirFn: (dir) => + dir === redirDesktop + ? [{ name: 'Antigravity.lnk', isFile: () => true, isDirectory: () => false }] + : [], + statFn: () => ({ size: 512 }), + readFn: () => makeFakeLnkBuf('C:\\App\\Antigravity.exe', '--remote-debugging-port=0'), + }, + }); + assert.equal(fastCachedRes.fastPath, true); + assert.equal(fastCachedRes.allConfigured ?? fastCachedRes.configured, true); + assert.ok(fastCachedRes.configuredPaths.some((p) => p.includes('RedirectedDesktop'))); + // Verify Windows shortcut auto-provisioning + read-only public shortcut tracking + periodic recheck + clean rollback const winPsCalls = []; let simulateReadOnlyPublicDesktop = false; @@ -5291,10 +5453,16 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi assert.equal(relaunchWinRes.ok, true); assert.equal(relaunchWinRes.relaunching, true); assert.equal(capturedRelaunchArgs.includes('-Sta'), true, 'Forces STA for Shell.Application COM'); + assert.match( + capturedRelaunchArgs[capturedRelaunchArgs.length - 1], + /-HostElevated /, + 'Passes -HostElevated via CLI arg so WMI/Shell.Application preserve elevation state' + ); assert.equal(capturedRelaunchEnv.ANTIGRAVITY_LS_ADDRESS, undefined, 'Strips host LS env'); assert.equal(fs.existsSync(capturedRelaunchEnv.AGY_RELAUNCH_PS1), true); const writtenPs1 = fs.readFileSync(capturedRelaunchEnv.AGY_RELAUNCH_PS1, 'utf8'); assert.equal(writtenPs1.startsWith('\uFEFF'), true, 'Writes UTF-8 BOM for Windows PowerShell 5.1'); + assert.match(writtenPs1, /^[\uFEFF]?param\(\[string\]\$HostElevated = '0'\)/); assert.match(writtenPs1, /--remote-debugging-port=0/); assert.ok(writtenPs1.includes(stalePortFile)); @@ -5335,12 +5503,44 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi }); assert.equal(relaunchMacRes.ok, true); assert.equal(macSpawnArgs.env.AGY_RELAUNCH_APP, '/Applications/Antigravity.app'); + assert.equal(macSpawnArgs.env.AGY_APP_NAME, 'Antigravity'); + assert.match(macSpawnArgs.args[1], /if osascript .* then .* fi/); + assert.match(macSpawnArgs.args[1], /pkill -TERM -x "\$AGY_APP_NAME"/); + assert.match(macSpawnArgs.args[1], /pkill -KILL -x "\$AGY_APP_NAME"/); assert.match(macSpawnArgs.args[1], /open -a "\$AGY_RELAUNCH_APP" --args --remote-debugging-port=0/); - // Verify Linux /proc dynamic AppImage discovery & multi-comm pkill handling + // macOS TCC-blocked osascript falls back to ps -axo comm= and derives custom .app name + let macPsFallbackSpawn = null; + const relaunchMacPsRes = await triggerDesktopHostRelaunch({ + env: { PATH: '/usr/bin:/bin' }, + platform: 'darwin', + homeDir: '/Users/dev', + allowInTest: true, + existsFn: () => false, + execFileFn: async (file) => { + if (file === 'osascript') throw new Error('Not authorized to send Apple events (-1743)'); + if (file === 'ps') { + return '/Users/dev/Apps/Antigravity Beta.app/Contents/MacOS/Antigravity Beta\n'; + } + return ''; + }, + spawnFn: async (file, args, opts) => { + macPsFallbackSpawn = { file, args, env: opts?.env }; + return { pid: 4322 }; + }, + }); + assert.equal(relaunchMacPsRes.ok, true); + assert.equal(macPsFallbackSpawn.env.AGY_RELAUNCH_APP, '/Users/dev/Apps/Antigravity Beta.app'); + assert.equal(macPsFallbackSpawn.env.AGY_APP_NAME, 'Antigravity Beta'); + + // Verify Linux /proc dynamic AppImage discovery, 15-char comm truncation, and SIGKILL fallback let linuxSpawnArgs = null; const relaunchLinuxRes = await triggerDesktopHostRelaunch({ - env: { PATH: '/usr/bin:/bin' }, + env: { + PATH: '/tmp/.mount_Ag/bin:/usr/bin:/bin', + APPIMAGE: '/home/alice/Apps/Antigravity-2.33.0.AppImage', + LD_LIBRARY_PATH: '/tmp/.mount_Ag/lib', + }, platform: 'linux', homeDir: '/home/alice', stalePortFiles: ['/home/alice/.config/Antigravity/DevToolsActivePort'], @@ -5354,17 +5554,30 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi }); assert.equal(relaunchLinuxRes.ok, true); assert.equal(linuxSpawnArgs.env.AGY_RELAUNCH_EXE, '/home/alice/Apps/Antigravity-2.33.0.AppImage'); - assert.match(linuxSpawnArgs.args[1], /for pn in "\$AGY_PROC_NAME" antigravity Antigravity/); + assert.equal(linuxSpawnArgs.env.AGY_PROC_COMM, 'Antigravity-2.3'); + assert.equal(linuxSpawnArgs.env.APPIMAGE, undefined, 'Strips APPIMAGE from relaunch env'); + assert.equal(linuxSpawnArgs.env.LD_LIBRARY_PATH, undefined, 'Strips mount LD_LIBRARY_PATH'); + assert.match(linuxSpawnArgs.args[1], /for pn in "\$AGY_PROC_NAME" antigravity Antigravity "\$AGY_PROC_COMM"/); + assert.match(linuxSpawnArgs.args[1], /pkill -KILL -u "\$uid" -x "\$pn"/); - // Explicit ANTIGRAVITY_DEVTOOLS_PORT fallback & UAC read-only shortcut + de-elevation script generation + // Explicit ANTIGRAVITY_DEVTOOLS_PORT fallback, HKLM UAC patching, single-quoted UAC script safety & de-elevation const innerScriptCheck = buildWindowsRelaunchInnerScript(fakeExe, [stalePortFile], 'desktop', { - readOnlyShortcutPaths: ['C:\\Users\\Public\\Desktop\\Antigravity.lnk'], + readOnlyShortcutPaths: [ + 'C:\\Users\\Public\\Desktop\\Antigravity.lnk', + 'HKLM:Run:Software\\Microsoft\\Windows\\CurrentVersion\\Run|Antigravity', + 'HKLM:Class:Software\\Classes\\antigravity\\shell\\open\\command', + ], psExePath: 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', }); assert.match(innerScriptCheck, /CloseMainWindow/); assert.match(innerScriptCheck, /Stop-Process/); assert.match(innerScriptCheck, /-Verb RunAs/); assert.match(innerScriptCheck, /C:\\Users\\Public\\Desktop\\Antigravity\.lnk/); + assert.match(innerScriptCheck, /HKLM:Run:/); + assert.match(innerScriptCheck, /HKLM:Class:/); + assert.match(innerScriptCheck, /'\$ws = \$null'/); + assert.match(innerScriptCheck, /'\$mySid = \(Get-Process -Id \$PID\)\.SessionId'/); + assert.match(innerScriptCheck, /'Remove-Item -LiteralPath \$PSCommandPath -Force -ErrorAction SilentlyContinue'/); assert.match(innerScriptCheck, /\$isSelfElevated -and -not \$wasHostElevated/); } finally { fs.rmSync(simTmp, { recursive: true, force: true }); From c998a8133010b3a1983e236ca56b4a0a3844e8dc Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Thu, 19 Nov 2026 20:03:05 +0900 Subject: [PATCH 09/14] perf(panel): instant consumption time-range switching via pruned scope API and client preset cache --- sidecars/panel/app.js | 501 +++++- sidecars/panel/backend/api-actions.mjs | 35 +- sidecars/panel/backend/telemetry-builder.mjs | 116 +- sidecars/panel/backend/usage-aggregator.mjs | 1349 +++++++++++------ sidecars/panel/index.html | 4 +- .../src/components/charts/TrendAreaChart.js | 14 +- sidecars/panel/src/store/telemetryStore.js | 356 ++++- sidecars/panel/src/views/ConsumptionView.js | 133 +- sidecars/panel/test/backend.test.mjs | 163 ++ sidecars/panel/test/consumption-bars.test.mjs | 173 ++- 10 files changed, 2307 insertions(+), 537 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index c111c3e..f8c636c 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -4269,7 +4269,7 @@ return { getViewTabs, uiStore, getVisibleMonitorView }; })(); // --- src/store/telemetryStore.js --- -const { extractHostRouteCascadeId, telemetryStore, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, fetchTelemetry, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform } = (() => { +const { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, fetchTelemetry, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform } = (() => { /** * @fileoverview Reactive telemetry store with async non-overlapping poll scheduler * and granular slice updates. @@ -4367,9 +4367,16 @@ let pollTimer = null; let feedbackTimer = null; let activeBundleVersion = 0; let latestRequestSeq = 0; +let latestConsumptionReqSeq = 0; let activeForceCount = 0; let consecutivePollFailures = 0; let inFlightTelemetryPoll = null; +let inFlightPresetsPrefetch = null; +let lastPrefetchedUsageRevision = 0; +let consumptionCacheScopeSig = ''; +const MAX_CONSUMPTION_RANGE_CACHE = 12; +const CONSUMPTION_PRESET_KEYS = ['cycle', 'today', '24h', '7d', '14d', '30d', 'all']; +const consumptionRangeCache = new Map(); let lastReceivedSteps = null; let loopActive = false; let loopIntervalMs = 2000; @@ -4387,6 +4394,96 @@ const TELEMETRY_RECOMPUTE_SETTING_KEYS = new Set([ 'enableWindowOverlay', ]); +function makeConsumptionRangeCacheKey(range, customStartMs = 0, customEndMs = 0) { + const key = String(range || 'all'); + if (key === 'custom') { + return `custom:${Number(customStartMs || 0)}:${Number(customEndMs || 0)}`; + } + return key; +} + +function clearConsumptionRangeCache() { + consumptionRangeCache.clear(); + lastPrefetchedUsageRevision = 0; + inFlightPresetsPrefetch = null; +} + +function buildConsumptionScopeSig(payload) { + if (!payload || typeof payload !== 'object') return ''; + const acct = payload.account || {}; + const set = payload.settings || {}; + const cloud = payload.cloudStatus || {}; + return `${String(acct.status || '')}|${String(acct.email || acct.name || '').toLowerCase()}|${String(set.weeklyLimitMode || '')}|${String(cloud.catalogVersion || '')}`; +} + +function syncConsumptionCacheScope(payload) { + const nextSig = buildConsumptionScopeSig(payload); + if (!nextSig) return; + if (consumptionCacheScopeSig && consumptionCacheScopeSig !== nextSig) { + clearConsumptionRangeCache(); + } + consumptionCacheScopeSig = nextSig; +} + +function putConsumptionRangeCacheEntry(cacheKey, entry) { + if (!cacheKey || !entry) return; + consumptionRangeCache.delete(cacheKey); + consumptionRangeCache.set(cacheKey, entry); + while (consumptionRangeCache.size > MAX_CONSUMPTION_RANGE_CACHE) { + consumptionRangeCache.delete(consumptionRangeCache.keys().next().value); + } +} + +function recordConsumptionSliceToCache( + cons, + modelBreakdown, + { customStartMs = 0, customEndMs = 0, usageRevision = 0 } = {} +) { + const rangeKey = String(cons?.selectedRange?.key || ''); + if (!rangeKey) return; + const cacheKey = makeConsumptionRangeCacheKey( + rangeKey, + rangeKey === 'custom' ? customStartMs || cons.selectedRange?.startMs || 0 : 0, + rangeKey === 'custom' ? customEndMs || cons.selectedRange?.endMs || 0 : 0 + ); + putConsumptionRangeCacheEntry(cacheKey, { + revision: Number(cons.revision ?? usageRevision ?? 0), + selectedRange: cons.selectedRange, + session: cons.session, + account: cons.account, + trendSeries: Array.isArray(cons.trendSeries) ? cons.trendSeries : [], + sourcesBreakdown: Array.isArray(cons.sourcesBreakdown) ? cons.sourcesBreakdown : [], + modelBreakdown: Array.isArray(modelBreakdown) ? modelBreakdown : [], + }); +} + +function applyCachedConsumptionSlice(baseTelemetry, cachedEntry, targetRevision = 0) { + if (!baseTelemetry || !cachedEntry) return baseTelemetry; + const prevCons = baseTelemetry.consumption || {}; + return { + ...baseTelemetry, + consumption: { + ...prevCons, + ...(targetRevision > 0 ? { revision: targetRevision } : {}), + selectedRange: cachedEntry.selectedRange, + session: cachedEntry.session ?? prevCons.session, + account: cachedEntry.account ?? prevCons.account, + trendSeries: cachedEntry.trendSeries, + sourcesBreakdown: cachedEntry.sourcesBreakdown, + }, + modelBreakdown: cachedEntry.modelBreakdown, + }; +} + +function hasAllPresetRangesCached(expectedRevision) { + for (const key of CONSUMPTION_PRESET_KEYS) { + const entry = consumptionRangeCache.get(key); + if (!entry) return false; + if (expectedRevision > 0 && entry.revision !== expectedRevision) return false; + } + return true; +} + function enqueueSettingsWrite(task) { const run = settingsWriteChain.then(task, task); settingsWriteChain = run.catch(() => {}); @@ -5079,6 +5176,9 @@ function readDisplaySteps(payload) { async function requestTelemetry(params, force) { const reqSeq = ++latestRequestSeq; const reqSettingsRev = settingsRevision; + const reqRange = String(params.get('range') || ''); + const reqStartMs = Number(params.get('startMs') || 0); + const reqEndMs = Number(params.get('endMs') || 0); const startMs = Date.now(); if (force) { @@ -5129,8 +5229,57 @@ async function requestTelemetry(params, force) { } consecutivePollFailures = 0; - const resolvedPayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev); + let resolvedPayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev); + syncConsumptionCacheScope(resolvedPayload); + if (resolvedPayload?.consumption) { + recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, { + customStartMs: reqStartMs, + customEndMs: reqEndMs, + }); + } + const latestSt = telemetryStore.getState(); + const incomingRev = Number(resolvedPayload?.consumption?.revision || 0); + const matchesCurrentRange = + !reqRange || + (reqRange === latestSt.selectedTimeRange && + (reqRange !== 'custom' || + (reqStartMs === Number(latestSt.customStartMs || 0) && + reqEndMs === Number(latestSt.customEndMs || 0)))); + + // 常规 2 秒轮询在途期间若用户已通过前端缓存瞬切到其他时间段,保留用户当前选中的范围不回跳, + // 若后端 usageRevision 已推进则静默补发一次轻量范围校准。 + let needsSilentRangeRevalidate = false; + if (!force && !matchesCurrentRange && resolvedPayload?.consumption) { + const activeKey = makeConsumptionRangeCacheKey( + latestSt.selectedTimeRange, + latestSt.customStartMs, + latestSt.customEndMs + ); + const cachedActive = consumptionRangeCache.get(activeKey); + if (cachedActive) { + resolvedPayload = applyCachedConsumptionSlice(resolvedPayload, cachedActive, incomingRev); + if (incomingRev > 0 && cachedActive.revision !== incomingRev) { + needsSilentRangeRevalidate = true; + } + } else if ( + latestSt.telemetry?.consumption?.selectedRange?.key === latestSt.selectedTimeRange + ) { + resolvedPayload = { + ...resolvedPayload, + consumption: { + ...resolvedPayload.consumption, + selectedRange: latestSt.telemetry.consumption.selectedRange, + session: latestSt.telemetry.consumption.session, + account: latestSt.telemetry.consumption.account, + trendSeries: latestSt.telemetry.consumption.trendSeries, + sourcesBreakdown: latestSt.telemetry.consumption.sourcesBreakdown, + }, + modelBreakdown: latestSt.telemetry.modelBreakdown, + }; + } + } + if (force) { const elapsed = Date.now() - startMs; if (elapsed < 220) { @@ -5159,6 +5308,13 @@ async function requestTelemetry(params, force) { minuteTick: Math.floor(Date.now() / 30000), syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle', }); + if (needsSilentRangeRevalidate) { + void fetchConsumptionRangeSlice({ + range: latestSt.selectedTimeRange, + customStartMs: latestSt.customStartMs, + customEndMs: latestSt.customEndMs, + }); + } return resolvedPayload; } } catch (err) { @@ -5178,6 +5334,198 @@ async function requestTelemetry(params, force) { } } +async function fetchConsumptionRangeSlice({ + range, + customStartMs = 0, + customEndMs = 0, +} = {}) { + const reqSeq = ++latestConsumptionReqSeq; + const targetRange = String(range || 'today'); + const current = telemetryStore.getState(); + const effectiveConvId = current.selectedConversationId || current.hostRouteConversationId || ''; + const params = new URLSearchParams(); + if (effectiveConvId) params.set('conversationId', effectiveConvId); + params.set('range', targetRange); + if (targetRange === 'custom') { + if (customStartMs > 0) params.set('startMs', String(customStartMs)); + if (customEndMs > 0) params.set('endMs', String(customEndMs)); + } + params.set('scope', 'consumption'); + + try { + const payload = await callSidecarApi(`/api/telemetry?${params}`, { + method: 'GET', + abortKey: 'consumption-range', + }); + if (!payload || typeof payload !== 'object') return null; + + if (payload.scope === 'consumption' && payload.consumption) { + const usageRev = Number(payload.usageRevision ?? payload.consumption.revision ?? 0); + recordConsumptionSliceToCache(payload.consumption, payload.modelBreakdown, { + customStartMs, + customEndMs, + usageRevision: usageRev, + }); + if (reqSeq !== latestConsumptionReqSeq) return payload; + + const latestSt = telemetryStore.getState(); + const stillMatches = + latestSt.selectedTimeRange === targetRange && + (targetRange !== 'custom' || + (Number(latestSt.customStartMs || 0) === Number(customStartMs || 0) && + Number(latestSt.customEndMs || 0) === Number(customEndMs || 0))); + if (!stillMatches) return payload; + + const prevTelemetry = latestSt.telemetry; + if (prevTelemetry) { + const nextTelemetry = { + ...prevTelemetry, + consumption: { + ...(prevTelemetry.consumption || {}), + ...payload.consumption, + ...(usageRev > 0 ? { revision: usageRev } : {}), + }, + modelBreakdown: Array.isArray(payload.modelBreakdown) + ? payload.modelBreakdown + : prevTelemetry.modelBreakdown, + }; + if (!isEquivalentTelemetry(prevTelemetry, nextTelemetry)) { + telemetryStore.setState({ telemetry: nextTelemetry }); + } + } + return payload; + } + + // 冷启动阶段后端尚无基础快照时会回退返回完整 telemetry,直接平滑复用现有状态合并 + if (payload.consumption) { + syncConsumptionCacheScope(payload); + recordConsumptionSliceToCache(payload.consumption, payload.modelBreakdown, { + customStartMs, + customEndMs, + }); + if (reqSeq === latestConsumptionReqSeq) { + const latestSt = telemetryStore.getState(); + if (!isEquivalentTelemetry(latestSt.telemetry, payload)) { + telemetryStore.setState({ telemetry: payload }); + } + } + } + return payload; + } catch (err) { + if (err?.name === 'AbortError') return null; + return null; + } +} + +/** + * 切换「用量统计」时间范围: + * - 命中前端 rangeCache 时,在单次 setState 内 0ms 原子更新概览/趋势/模型/来源(若 usageRevision 一致则 0 次 HTTP 请求); + * - 若后台数据已更新则先 0ms 展示缓存,再静默发起轻量 `scope=consumption` 校准; + * - 未命中缓存(如自定义时段或进页首 20ms 抢点)则直接走 `<5ms` 的 `scope=consumption` 通道。 + */ +function selectConsumptionTimeRange( + nextRange, + { customStartMs = undefined, customEndMs = undefined } = {} +) { + const targetRange = String(nextRange || 'today'); + const prevSt = telemetryStore.getState(); + const nextStartMs = + targetRange === 'custom' + ? Number(customStartMs !== undefined ? customStartMs : prevSt.customStartMs || 0) + : prevSt.customStartMs; + const nextEndMs = + targetRange === 'custom' + ? Number(customEndMs !== undefined ? customEndMs : prevSt.customEndMs || 0) + : prevSt.customEndMs; + + const statePatch = { selectedTimeRange: targetRange }; + if (targetRange === 'custom') { + statePatch.customStartMs = nextStartMs; + statePatch.customEndMs = nextEndMs; + } + + const cacheKey = makeConsumptionRangeCacheKey(targetRange, nextStartMs, nextEndMs); + const cached = consumptionRangeCache.get(cacheKey); + const prevTelemetry = prevSt.telemetry; + + if (cached && prevTelemetry) { + const currentRev = Number(prevTelemetry.consumption?.revision || 0); + const nextTelemetry = applyCachedConsumptionSlice( + prevTelemetry, + cached, + currentRev > 0 ? currentRev : cached.revision + ); + telemetryStore.setState({ ...statePatch, telemetry: nextTelemetry }); + if (currentRev > 0 && cached.revision === currentRev) { + return Promise.resolve(nextTelemetry); + } + return fetchConsumptionRangeSlice({ + range: targetRange, + customStartMs: nextStartMs, + customEndMs: nextEndMs, + }); + } + + telemetryStore.setState(statePatch); + return fetchConsumptionRangeSlice({ + range: targetRange, + customStartMs: nextStartMs, + customEndMs: nextEndMs, + }); +} + +/** + * 仅在进入「用量统计」视图时触发一次静默后台预取,拉齐全部 7 个预设区间到前端缓存以实现 0ms 瞬切。 + */ +function prefetchConsumptionPresets() { + const prevTelemetry = telemetryStore.getState().telemetry; + const currentRev = Number(prevTelemetry?.consumption?.revision || 0); + if (currentRev > 0 && lastPrefetchedUsageRevision === currentRev && hasAllPresetRangesCached(currentRev)) { + return Promise.resolve(true); + } + if (inFlightPresetsPrefetch) { + return inFlightPresetsPrefetch; + } + + const current = telemetryStore.getState(); + const effectiveConvId = current.selectedConversationId || current.hostRouteConversationId || ''; + const params = new URLSearchParams(); + if (effectiveConvId) params.set('conversationId', effectiveConvId); + params.set('scope', 'consumption-presets'); + + const task = callSidecarApi(`/api/telemetry?${params}`, { + method: 'GET', + abortKey: 'consumption-presets', + }) + .then((payload) => { + if (payload?.scope === 'consumption-presets' && payload.ranges && typeof payload.ranges === 'object') { + const rev = Number(payload.usageRevision || currentRev || 0); + for (const [rangeKey, entry] of Object.entries(payload.ranges)) { + if (!entry || typeof entry !== 'object') continue; + recordConsumptionSliceToCache( + { ...entry, revision: rev }, + entry.modelBreakdown, + { usageRevision: rev } + ); + } + if (rev > 0) { + lastPrefetchedUsageRevision = rev; + } + return true; + } + return false; + }) + .catch(() => false) + .finally(() => { + if (inFlightPresetsPrefetch === task) { + inFlightPresetsPrefetch = null; + } + }); + + inFlightPresetsPrefetch = task; + return task; +} + async function saveSettingsPatch(patch) { const safePatch = patch && typeof patch === 'object' ? { ...patch } : {}; if (Object.prototype.hasOwnProperty.call(safePatch, 'language')) { @@ -5353,6 +5701,9 @@ async function saveSettingsPatch(patch) { } const needsTelemetryRecompute = patchKeys.some((k) => TELEMETRY_RECOMPUTE_SETTING_KEYS.has(k)); + if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) { + clearConsumptionRangeCache(); + } if (needsTelemetryRecompute) { inFlightTelemetryPoll = null; void fetchTelemetry({ force: false }); @@ -5416,18 +5767,21 @@ async function resetAllSettings() { }); } inFlightTelemetryPoll = null; + clearConsumptionRangeCache(); void fetchTelemetry({ force: false }); return res; } async function rebuildTrajectoryCache() { const res = await callSidecarApi('/api/cache/rebuild', { method: 'POST', body: {} }); + clearConsumptionRangeCache(); await fetchTelemetry({ force: true }); return res; } async function triggerCloudSync() { const res = await callSidecarApi('/api/cloud-sync', { method: 'POST', body: {} }); + clearConsumptionRangeCache(); await fetchTelemetry({ force: true }); return res; } @@ -5697,7 +6051,7 @@ function isMacHostPlatform(telemetry) { } return false; } -return { extractHostRouteCascadeId, telemetryStore, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, fetchTelemetry, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform }; +return { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, fetchTelemetry, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform }; })(); // --- src/components/ui/TopLongPillNav.js --- @@ -8026,13 +8380,18 @@ function createTrendAreaChart() { hmMonthsEl.appendChild(mEl); } - // 重建 7 行 × N 周列的每日小格子(一格一天) + // 重建 7 行 × N 周列的每日小格子(一格一天),使用 DocumentFragment 一次性批量挂载减少重排 while (hmGridEl.firstChild) hmGridEl.removeChild(hmGridEl.firstChild); hoveredCellEl = null; currentCellEls = new Array(slots.length); + const gridFrag = + typeof document !== 'undefined' && typeof document.createDocumentFragment === 'function' + ? document.createDocumentFragment() + : null; + const gridTarget = gridFrag || hmGridEl; for (let pad = 0; pad < firstDow; pad++) { - hmGridEl.appendChild( + gridTarget.appendChild( h('span', { className: 'trend-hm-cell is-pad', 'aria-hidden': 'true' }) ); } @@ -8051,9 +8410,12 @@ function createTrendAreaChart() { 'data-hm-row': String(row), role: 'gridcell', }); - hmGridEl.appendChild(cellEl); + gridTarget.appendChild(cellEl); currentCellEls[i] = cellEl; } + if (gridFrag) { + hmGridEl.appendChild(gridFrag); + } if (typeof requestAnimationFrame === 'function') { requestAnimationFrame(() => { @@ -19902,8 +20264,7 @@ const ConsumptionView = defineComponent({ } else { hasUncommittedCustomDraft = false; } - telemetryStore.setState({ selectedTimeRange: nextRange }); - fetchTelemetry({ force: false }); + selectConsumptionTimeRange(nextRange); }, }); @@ -19942,12 +20303,10 @@ const ConsumptionView = defineComponent({ hasUncommittedCustomDraft = false; startPicker.setValue(minMs); endPicker.setValue(maxMs); - telemetryStore.setState({ - selectedTimeRange: 'custom', + selectConsumptionTimeRange('custom', { customStartMs: minMs, customEndMs: maxMs, }); - fetchTelemetry({ force: true }); }, }, [createSvgIcon('check', { size: 12 }), applyCustomBtnLabel] @@ -20689,8 +21048,21 @@ const ConsumptionView = defineComponent({ let latestSlice = null; let isDirty = false; + let prefetchedOnCurrentVisit = false; - let lastRenderedUsage = ''; + let lastRenderedTuple = null; + let cachedMonthlySeriesRef = null; + let cachedMonthlyDisplayKey = ''; + let cachedMonthsMergedModels = null; + let cachedAllMonthMergedModels = null; + + function isSameRenderTuple(prev, next) { + if (!prev || prev.length !== next.length) return false; + for (let i = 0; i < prev.length; i++) { + if (!Object.is(prev[i], next[i])) return false; + } + return true; + } /** * 将遥测状态切片同步渲染至消费统计视图的 5 个子面板。 @@ -20698,31 +21070,9 @@ const ConsumptionView = defineComponent({ function renderConsumptionData(slice) { if (!slice) return; const cons = slice.consumption || {}; - const preset = - slice.range !== 'custom' && cons.presets?.[slice.range] - ? cons.presets[slice.range] - : null; - const acct = preset?.account || cons.account || {}; const rangeInfo = cons.selectedRange || {}; - const dateSpan = formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs); - const now = new Date(); - const currentMonthIdx = now.getMonth(); - const monthlyYear = cons.monthlyYear || now.getFullYear(); - const locale = i18nStore.getState().locale; - // 额度与会话状态也会发布遥测更新,只对用量页实际展示的数据重绘。 - const signature = JSON.stringify([ - locale, slice.range, slice.customStartMs, slice.customEndMs, slice.modelDisplayMode, - slice.showUpstreamModel, slice.orchestratorIdMode, dateSpan, - preset?.label || rangeInfo.label, acct, - cons.trendSeries, slice.modelBreakdown, cons.sourcesBreakdown, - monthlyYear, currentMonthIdx, cons.monthlySeries, - ]); - if (signature === lastRenderedUsage) return; - drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear }); - lastRenderedUsage = signature; - } - function drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear }) { + // 始终在 0ms 同步顶部时间段滑块与自定义日期条显隐,给予即刻交互反馈 timeFilterSwitch.setValue(slice.range); patchAttr(customRangeBar, 'hidden', slice.range !== 'custom'); if (!hasUncommittedCustomDraft) { @@ -20732,6 +21082,45 @@ const ConsumptionView = defineComponent({ endPicker.setValue(draftEndMs); } + // 极少数缓存未命中时(如自定义新区间或进页瞬间抢点),跳过用旧趋势/模型跑无效半更新重绘,待几毫秒后单帧原子绘制 + if (rangeInfo.key && slice.range && rangeInfo.key !== slice.range) { + return; + } + + const preset = + slice.range !== 'custom' && cons.presets?.[slice.range] + ? cons.presets[slice.range] + : null; + const acct = cons.account || preset?.account || {}; + const dateSpan = formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs); + const now = new Date(); + const currentMonthIdx = now.getMonth(); + const monthlyYear = cons.monthlyYear || now.getFullYear(); + const locale = i18nStore.getState().locale; + const renderTuple = [ + locale, + slice.range, + slice.customStartMs, + slice.customEndMs, + slice.modelDisplayMode, + slice.showUpstreamModel, + slice.orchestratorIdMode, + dateSpan, + preset?.label || rangeInfo.label, + acct, + cons.trendSeries, + slice.modelBreakdown, + cons.sourcesBreakdown, + monthlyYear, + currentMonthIdx, + cons.monthlySeries, + ]; + if (isSameRenderTuple(lastRenderedTuple, renderTuple)) return; + drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear }); + lastRenderedTuple = renderTuple; + } + + function drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear }) { // 1. 同步用量概览矩阵与顶部 4 段比例条 patchText(dateSpanBadge, dateSpan); const totalTokens = Number(acct.totalTokens || 0); @@ -20832,14 +21221,31 @@ const ConsumptionView = defineComponent({ }); const monthlySeries = cons.monthlySeries || []; - const allMonthMergedModels = []; - const monthsMergedModels = Array.from({ length: 12 }, (_, idx) => { - const merged = mergeAndSortBucketModels(monthlySeries[idx]?.models); - for (const m of merged) { - allMonthMergedModels.push(m); - } - return merged; - }); + const monthlyDisplayKey = `${displaySettings.modelDisplayMode}|${displaySettings.showUpstreamModel ? 1 : 0}|${displaySettings.orchestratorIdMode}`; + let monthsMergedModels; + let allMonthMergedModels; + if ( + cachedMonthlySeriesRef === monthlySeries && + cachedMonthlyDisplayKey === monthlyDisplayKey && + cachedMonthsMergedModels && + cachedAllMonthMergedModels + ) { + monthsMergedModels = cachedMonthsMergedModels; + allMonthMergedModels = cachedAllMonthMergedModels; + } else { + allMonthMergedModels = []; + monthsMergedModels = Array.from({ length: 12 }, (_, idx) => { + const merged = mergeAndSortBucketModels(monthlySeries[idx]?.models); + for (const m of merged) { + allMonthMergedModels.push(m); + } + return merged; + }); + cachedMonthlySeriesRef = monthlySeries; + cachedMonthlyDisplayKey = monthlyDisplayKey; + cachedMonthsMergedModels = monthsMergedModels; + cachedAllMonthMergedModels = allMonthMergedModels; + } const rawTrendSeries = cons.trendSeries || []; const allTrendMergedModels = []; @@ -21034,6 +21440,10 @@ const ConsumptionView = defineComponent({ } isDirty = false; renderConsumptionData(slice); + if (!prefetchedOnCurrentVisit && Number(slice?.consumption?.revision || 0) > 0) { + prefetchedOnCurrentVisit = true; + void prefetchConsumptionPresets(); + } } ); @@ -21041,6 +21451,7 @@ const ConsumptionView = defineComponent({ getVisibleMonitorView, (activeView) => { if (activeView !== 'consumption') { + prefetchedOnCurrentVisit = false; hideBreakdownPopover(); return; } @@ -21050,6 +21461,10 @@ const ConsumptionView = defineComponent({ renderConsumptionData(latestSlice); } } + if (!prefetchedOnCurrentVisit && Number(latestSlice?.consumption?.revision || 0) > 0) { + prefetchedOnCurrentVisit = true; + void prefetchConsumptionPresets(); + } } ); diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index d958c3e..aa43f49 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -44,7 +44,7 @@ import { syncCloudCatalog, } from './plugin-updater.mjs'; import { getCloudStatus } from './pricing-catalog.mjs'; -import { buildTelemetryPayload } from './telemetry-builder.mjs'; +import { buildTelemetryPayload, clearTelemetryBuilderMemo } from './telemetry-builder.mjs'; import { ensureDesktopLaunchEntriesConfigured, triggerDesktopHostRelaunch, @@ -192,10 +192,14 @@ export async function executeTelemetryAction(data, { onRestart = null } = {}) { } } } + const rawScope = String(data?.scope || '').trim(); + const scope = + rawScope === 'consumption' || rawScope === 'consumption-presets' ? rawScope : ''; const filterOpts = { range: data?.range || 'all', startMs: sanitizePositiveFiniteMs(data?.startMs), endMs: sanitizePositiveFiniteMs(data?.endMs), + ...(scope ? { scope } : {}), }; let payload; try { @@ -216,7 +220,7 @@ export async function executeTelemetryAction(data, { onRestart = null } = {}) { } if ( bootBundleVersion && - payload.uiBundleVersion && + payload?.uiBundleVersion && String(payload.uiBundleVersion) !== String(bootBundleVersion) ) { if (typeof onRestart === 'function') { @@ -225,9 +229,12 @@ export async function executeTelemetryAction(data, { onRestart = null } = {}) { scheduleSidecarRestart(150); } } - const responsePayload = data?.stepDetails === 'display' - ? projectDisplayTelemetry(payload, data.stepRevision) - : payload; + const isScopedConsumptionPayload = + payload?.scope === 'consumption' || payload?.scope === 'consumption-presets'; + const responsePayload = + !isScopedConsumptionPayload && data?.stepDetails === 'display' + ? projectDisplayTelemetry(payload, data.stepRevision) + : payload; return { status: 200, contentType: 'application/json', @@ -295,11 +302,20 @@ export function executeSettingsAction(data) { body: JSON.stringify({ ok: false, error: 'Failed to persist settings' }), }; } - inFlightRequests.clear(); const prevMountMode = normalizeWindowMountMode( current.windowMountMode, current.enableWindowOverlay ); + const affectsBackendTelemetry = + updated.weeklyLimitMode !== current.weeklyLimitMode || + updated.weeklyTokenBudget !== current.weeklyTokenBudget || + updated.weeklyCostBudget !== current.weeklyCostBudget || + updated.enableWindowOverlay !== (current.enableWindowOverlay !== false) || + updated.windowMountMode !== prevMountMode; + inFlightRequests.clear(); + if (affectsBackendTelemetry) { + clearTelemetryBuilderMemo(); + } if ( updated.enableWindowOverlay !== (current.enableWindowOverlay !== false) || updated.windowMountMode !== prevMountMode @@ -364,6 +380,7 @@ export async function executeModelContextWindowAction(data) { return respond(500, { error: 'Failed to persist model context window' }); } inFlightRequests.clear(); + clearTelemetryBuilderMemo(); void notifyModelContextWindowsChanged(); return respond(200, { modelContextWindows: current.modelContextWindows }); } @@ -381,6 +398,7 @@ export function executeResetSettingsAction() { }; } inFlightRequests.clear(); + clearTelemetryBuilderMemo(); const prevMountMode = normalizeWindowMountMode( current.windowMountMode, current.enableWindowOverlay @@ -429,6 +447,7 @@ export function executeRebuildCacheAction() { } displayStepsCache.clear(); clearScannerRuntimeMemos(); + clearTelemetryBuilderMemo(); return { ok: true, status: 200, @@ -440,6 +459,7 @@ export function executeRebuildCacheAction() { export async function executeCloudSyncAction() { const cloudStatus = await syncCloudCatalog({ force: true }); + clearTelemetryBuilderMemo(); return { status: 200, contentType: 'application/json', @@ -460,6 +480,9 @@ export async function executePluginUpdateAction() { export async function executeAccountCredentialAction(data) { const result = await handleAccountCredentialAction(data); + if (data?.action === 'switch') { + clearTelemetryBuilderMemo(); + } return { status: 200, contentType: 'application/json', diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index 296e4a0..f0c7a9a 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -46,8 +46,11 @@ import { getCloudStatus, getPricingPhaseEpoch, pricingCatalogRevision } from './ import { buildOfficialQuotaPools } from './quota-pools.mjs'; import { getDefaultWindowBridgeStatus } from './window-bridge.mjs'; import { + aggregateConsumptionPresetBundle, aggregateMultiWindowUsage, + aggregateSelectedWindowUsage, buildScopedModelBreakdown, + clearUsageAggregatorMemo, getNextMondayResetIso, } from './usage-aggregator.mjs'; @@ -56,6 +59,13 @@ const POOL_PRIORITY_ORDER = ['Gemini', 'Argon', 'Carbon', 'Claude & GPT']; const inFlightTelemetrySources = new Map(); const trajectoryModelFacts = new WeakMap(); let lastMainPreparation = null; +let lastCompletedTelemetrySnapshot = null; + +export function clearTelemetryBuilderMemo() { + lastMainPreparation = null; + lastCompletedTelemetrySnapshot = null; + clearUsageAggregatorMemo(); +} function roundSessionCost(val) { if (!Number.isFinite(val) || val <= 0) return 0; @@ -1237,6 +1247,7 @@ export async function buildTelemetryPayloadInternal( // 5. 多时间窗口聚合(预设窗口 + 当前选定窗口 + 趋势 + 月序列 + 来源与模型拆解 + 各配额池独立周期统计) const { + usageRevision, selectedWindow, trendStartMs, trendEndMs, @@ -1816,6 +1827,7 @@ export async function buildTelemetryPayloadInternal( aggregated: aggregatedTelemetry, }, consumption: { + revision: usageRevision, selectedRange: { key: selectedWindow.key, label: selectedWindow.label, @@ -1883,6 +1895,24 @@ export async function buildTelemetryPayloadInternal( modelBreakdown, }; + lastCompletedTelemetrySnapshot = { + lsAddr: String(lsRuntimeEndpoint.addr || ''), + weeklyLimitMode: settings.weeklyLimitMode, + catalogRevision: modelInputs.catalogRevision, + phaseEpoch: modelInputs.phaseEpoch, + basePayload: finalPayload, + aggContext: { + cycleAnchors, + isCustomWeeklyMode, + currentAccountName: accountScope, + activeCascadeId, + activeFamilyCascadeIds, + resolveStepModel, + quotaPoolsMap, + modelInputs, + }, + }; + if (lsRuntimeEndpoint.addr !== 'test.invalid') { try { saveJson(CLI_STATUS_SNAPSHOT_FILE, buildCliStatusSnapshot(finalPayload, Date.now())); @@ -1894,6 +1924,65 @@ export async function buildTelemetryPayloadInternal( return finalPayload; } +function resolveValidFastSnapshot() { + const snap = lastCompletedTelemetrySnapshot; + if (!snap || !snap.basePayload || !snap.aggContext) return null; + if (snap.lsAddr !== String(lsRuntimeEndpoint.addr || '')) return null; + if ( + snap.catalogRevision !== pricingCatalogRevision || + snap.phaseEpoch !== getPricingPhaseEpoch() + ) { + return null; + } + const latestSettings = loadSettings(); + if (latestSettings.weeklyLimitMode !== snap.weeklyLimitMode) { + return null; + } + return snap; +} + +function tryBuildFastConsumptionPayload(filterOpts = {}) { + const snap = resolveValidFastSnapshot(); + if (!snap) return null; + const agg = aggregateSelectedWindowUsage({ + filterOpts, + ...snap.aggContext, + }); + return { + scope: 'consumption', + timestamp: new Date().toISOString(), + uiBundleVersion: snap.basePayload.uiBundleVersion || computeRuntimeCodeVersion(), + usageRevision: agg.usageRevision, + consumption: { + revision: agg.usageRevision, + selectedRange: { + key: agg.selectedWindow.key, + label: agg.selectedWindow.label, + startMs: agg.trendStartMs, + endMs: agg.trendEndMs, + }, + session: agg.finalizedSelectedSession, + account: agg.finalizedSelectedAccount, + trendSeries: agg.trendSeries, + sourcesBreakdown: agg.sourcesBreakdown, + }, + modelBreakdown: agg.modelBreakdown, + }; +} + +function tryBuildConsumptionPresetsPayload() { + const snap = resolveValidFastSnapshot(); + if (!snap) return null; + const bundle = aggregateConsumptionPresetBundle(snap.aggContext); + return { + scope: 'consumption-presets', + timestamp: new Date().toISOString(), + uiBundleVersion: snap.basePayload.uiBundleVersion || computeRuntimeCodeVersion(), + usageRevision: bundle.usageRevision, + ranges: bundle.ranges, + }; +} + export function buildCliStatusSnapshot(finalPayload, updatedAtMs = Date.now()) { const ac = finalPayload?.activeConversation || {}; const capSource = ac.aggregated || ac; @@ -1938,7 +2027,7 @@ export function buildCliStatusSnapshot(finalPayload, updatedAtMs = Date.now()) { * * @param {string} requestedConvId * @param {boolean} [forceQuotaRefresh=false] - * @param {{ range?: string, startMs?: number, endMs?: number }} [filterOpts={}] + * @param {{ range?: string, startMs?: number, endMs?: number, scope?: string }} [filterOpts={}] * @returns {Promise} */ export function buildTelemetryPayload( @@ -1946,6 +2035,31 @@ export function buildTelemetryPayload( forceQuotaRefresh = false, filterOpts = {} ) { + if (!forceQuotaRefresh) { + if (filterOpts?.scope === 'consumption-presets') { + const presetsPayload = tryBuildConsumptionPresetsPayload(); + if (presetsPayload) { + return Promise.resolve(presetsPayload); + } + const key = `${requestedConvId || '__auto__'}::presets-cold`; + if (inFlightRequests.has(key)) { + return inFlightRequests.get(key); + } + const p = buildTelemetryPayloadInternal(requestedConvId, false, { range: 'today' }) + .then(() => tryBuildConsumptionPresetsPayload()) + .finally(() => { + inFlightRequests.delete(key); + }); + inFlightRequests.set(key, p); + return p; + } + if (filterOpts?.scope === 'consumption') { + const litePayload = tryBuildFastConsumptionPayload(filterOpts); + if (litePayload) { + return Promise.resolve(litePayload); + } + } + } const rangeSig = `${filterOpts.range || 'all'}:${filterOpts.startMs || 0}:${filterOpts.endMs || 0}`; const key = `${requestedConvId || '__auto__'}::${forceQuotaRefresh ? 'force' : 'normal'}::${rangeSig}`; if (inFlightRequests.has(key)) { diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs index d92bb8d..c3d57e3 100644 --- a/sidecars/panel/backend/usage-aggregator.mjs +++ b/sidecars/panel/backend/usage-aggregator.mjs @@ -389,190 +389,42 @@ export function buildScopedModelBreakdown(steps, resolveStepModel) { } let lastUsageSnapshot = null; +let usageSnapshotRevisionSeq = 0; +const stepsTimeBoundsCache = new WeakMap(); const MAX_TREND_TIMESTAMP_MS = 8_640_000_000_000_000; +export const CONSUMPTION_PRESET_RANGE_KEYS = ['cycle', 'today', '24h', '7d', '14d', '30d', 'all']; +const USAGE_SOURCE_LABELS = { + standalone: 'Antigravity App', + ide: 'Antigravity IDE', + cli: 'Antigravity CLI', +}; -function planUsageTrend(window, nowMs, earliest, latest) { - const safeMs = (value, fallback) => - Number.isFinite(value) && value > 0 && value <= MAX_TREND_TIMESTAMP_MS ? value : fallback; - const end = Math.max(safeMs(window.endMs, Math.max(nowMs, latest || nowMs)), latest); - const defaultStart = end - 24 * 3600 * 1000; - const start = window.key === 'all' - ? Math.min(safeMs(earliest, defaultStart), end - 3600 * 1000) - : Math.min(safeMs(window.startMs, defaultStart), end); - const hourly = window.key === 'today' || window.key === '24h' || window.key === '5h' || - end - start <= 72 * 3600 * 1000; - const first = new Date(start); - const last = new Date(end); - if (hourly) { - first.setMinutes(0, 0, 0); - last.setMinutes(0, 0, 0); - } else { - first.setHours(0, 0, 0, 0); - last.setHours(0, 0, 0, 0); +export function clearUsageAggregatorMemo() { + lastUsageSnapshot = null; + usageSnapshotRevisionSeq += 1; +} + +function getStepsTimeBounds(steps) { + if (!Array.isArray(steps) || steps.length === 0) { + return { minMs: Infinity, maxMs: 0 }; } - return { start, end, hourly, first: first.getTime(), last: last.getTime() }; -} - -function sameUsageEntries(previous, current) { - return previous.length === current.length && current.every((entry, index) => { - const before = previous[index]; - return entry.steps === before.steps && entry.cascadeId === before.cascadeId && - entry.appSource === before.appSource && entry.accountName === before.accountName && - entry.isCurrentConv === before.isCurrentConv; - }); -} - -function sortedUsageTimestamps(entries) { - const dates = new Float64Array(entries.reduce((sum, entry) => sum + entry.steps.length, 0)); - let count = 0; - for (const { steps } of entries) { - for (const step of steps) { - const date = Number(step?.createdAtMs); - if (date > 0) dates[count++] = date; + const cached = stepsTimeBoundsCache.get(steps); + if (cached) return cached; + let minMs = Infinity; + let maxMs = 0; + for (let i = 0; i < steps.length; i++) { + const tMs = Number(steps[i]?.createdAtMs); + if (tMs > 0) { + if (tMs < minMs) minMs = tMs; + if (tMs > maxMs) maxMs = tMs; } } - return dates.subarray(0, count).sort(); + const bounds = { minMs, maxMs }; + stepsTimeBoundsCache.set(steps, bounds); + return bounds; } -function usageTimestampBoundary(dates, value, inclusive) { - let start = 0; - let end = dates.length; - while (start < end) { - const i = (start + end) >>> 1; - if (dates[i] < value || (inclusive && dates[i] === value)) start = i + 1; - else end = i; - } - return start; -} - -function sameUsageWindows(previous, current, dates) { - return previous.length === current.length && current.every((window, index) => { - const before = previous[index]; - return before.key === window.key && before.label === window.label && - (before.startMs === window.startMs || - usageTimestampBoundary(dates, before.startMs, false) === - usageTimestampBoundary(dates, window.startMs, false)) && - (before.endMs === window.endMs || - usageTimestampBoundary(dates, before.endMs, true) === - usageTimestampBoundary(dates, window.endMs, true)); - }); -} - -/** - * 聚合所有预设时间窗口、当前选定窗口、趋势图、年度月序列、来源占比与分模型统计。 - * - * @param {{ - * filterOpts?: { range?: string, startMs?: number, endMs?: number }, - * cycleAnchors?: { fiveHourResetMs?: number, weeklyResetMs?: number }, - * currentAccountName?: string|null, - * activeCascadeId?: string|null, - * activeFamilyCascadeIds?: Set|null, - * resolveStepModel: StepModelResolver - * modelInputs?: { catalogRevision: number, dynamicModelMap: Map } - * }} params - */ -export function aggregateMultiWindowUsage({ - filterOpts = {}, - cycleAnchors = {}, - isCustomWeeklyMode = false, - currentAccountName = '', - activeCascadeId = null, - activeFamilyCascadeIds = null, - resolveStepModel, - quotaPoolsMap = null, - modelInputs = null, -}) { - const rawFamilyIds = - activeFamilyCascadeIds instanceof Set - ? Array.from(activeFamilyCascadeIds) - : activeCascadeId - ? [activeCascadeId] - : []; - const familySet = new Set(rawFamilyIds.map((id) => String(id || '').toLowerCase())); - const nowMs = Date.now(); - const selectedWindow = resolveTimeWindow( - filterOpts.range || 'all', - filterOpts.startMs, - filterOpts.endMs, - nowMs, - cycleAnchors, - isCustomWeeklyMode - ); - - const presetKeys = ['all', 'cycle', '5h', 'today', '24h', 'week', '7d', '14d', '30d']; - const presetWindows = {}; - const accountBuckets = {}; - const sessionBuckets = {}; - - for (const k of presetKeys) { - presetWindows[k] = resolveTimeWindow(k, 0, 0, nowMs, cycleAnchors, isCustomWeeklyMode); - accountBuckets[k] = createUsageBucket(); - sessionBuckets[k] = createUsageBucket(); - } - - // 为每个配额池建立独立的 5h 与周限周期统计桶(按各池自身的 resetTime / weeklyResetTime 截取窗口) - const poolCycleBuckets = new Map(); - if (quotaPoolsMap instanceof Map && quotaPoolsMap.size > 0) { - const weekFallbackStartMs = getStartOfCurrentWeekMs(new Date(nowMs)); - for (const [poolKey, poolObj] of quotaPoolsMap.entries()) { - const reset5hMs = parseIsoMs(poolObj?.resetTime) || 0; - const start5hMs = - reset5hMs > nowMs - ? Math.min(nowMs, reset5hMs - 5 * 3600 * 1000) - : nowMs - 5 * 3600 * 1000; - const resetWkMs = parseIsoMs(poolObj?.weeklyResetTime) || 0; - const startWkMs = - resetWkMs > nowMs - ? Math.min(nowMs, resetWkMs - 7 * 24 * 3600 * 1000) - : weekFallbackStartMs; - poolCycleBuckets.set(poolKey, { - start5hMs, - startWkMs, - b5h: createUsageBucket(), - bWk: createUsageBucket(), - }); - } - } - const hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon'); - const hasDedicatedArgonPool = poolCycleBuckets.has('Argon'); - const poolByModel = new Map(); - const quotaWeekBucket = createUsageBucket(); - const normalizedQuotaAccount = - currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName); - const selectedAccountBucket = accountBuckets[selectedWindow.key] || createUsageBucket(); - const selectedSessionBucket = sessionBuckets[selectedWindow.key] || createUsageBucket(); - const perModelStats = new Map(); - const selectedWindowSteps = []; - let earliestSelectedStepMs = Infinity; - let latestSelectedStepMs = 0; - let earliestActiveCyclePoolStartMs = Infinity; - - const currentYear = new Date(nowMs).getFullYear(); - const monthBoundsMs = Array.from({ length: 13 }, (_, idx) => - new Date(currentYear, idx, 1).getTime() - ); - const yearStartMs = monthBoundsMs[0]; - const nextYearStartMs = monthBoundsMs[12]; - const monthlySeries = Array.from({ length: 12 }, (_, idx) => ({ - month: idx + 1, - label: `${idx + 1}月`, - calls: 0, - inputTokens: 0, - cacheReadTokens: 0, - responseTokens: 0, - thinkingTokens: 0, - totalTokens: 0, - costUsd: 0, - unpricedCalls: 0, - perModelStats: new Map(), - })); - - const SOURCE_LABELS = { - standalone: 'Antigravity App', - ide: 'Antigravity IDE', - cli: 'Antigravity CLI', - }; - const perSourceStats = new Map(); +function collectUsageEntriesToAggregate(familySet) { const externalConvos = loadExternalDeepStatsCache(); // 构建大小写归一化的内存缓存与跨端深层缓存索引,彻底杜绝 `${appSource}:${cascadeId}` 键不匹配导致的双倍重复计费 @@ -629,261 +481,82 @@ export function aggregateMultiWindowUsage({ }); } - const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : ''; - const quotaWindows = Array.from(poolCycleBuckets, ([key, { start5hMs, startWkMs }]) => [ - { key: `${key}:5h`, startMs: start5hMs, endMs: nowMs }, - { key: `${key}:week`, startMs: startWkMs, endMs: nowMs }, - ]).flat(); - const windows = [selectedWindow, ...Object.values(presetWindows), ...quotaWindows]; - const snapshot = lastUsageSnapshot; - const sameSnapshot = modelInputs && snapshot && timeZone === snapshot.timeZone && - currentYear === snapshot.currentYear && - Boolean(isCustomWeeklyMode) === Boolean(snapshot.isCustomWeeklyMode) && - normalizedQuotaAccount === snapshot.normalizedQuotaAccount && - modelInputs.catalogRevision === snapshot.modelInputs.catalogRevision && - isDeepStrictEqual(modelInputs.dynamicModelMap, snapshot.modelInputs.dynamicModelMap) && - sameUsageEntries(snapshot.entries, allEntriesToAggregate); - const previous = sameSnapshot ? snapshot.ranges.get(selectedWindow.key) : null; - if (previous) { - // 时钟继续前进,只有实际有步骤跨过窗口边界时才重新聚合。 - const effectivePrevWin = - selectedWindow.key === 'cycle' && previous.effectiveSelectedWindow - ? { ...previous.effectiveSelectedWindow, endMs: nowMs } - : selectedWindow; - const trend = planUsageTrend(effectivePrevWin, nowMs, previous.earliest, previous.latest); - if ( - trend.hourly === previous.trend.hourly && trend.first === previous.trend.first && - trend.last === previous.trend.last && - sameUsageWindows(previous.windows, windows, - snapshot.dates ??= sortedUsageTimestamps(allEntriesToAggregate)) - ) { - snapshot.ranges.delete(selectedWindow.key); - snapshot.ranges.set(selectedWindow.key, previous); - return { - ...previous.result, - selectedWindow: effectivePrevWin, - trendStartMs: trend.start, - trendEndMs: trend.end, - }; + return allEntriesToAggregate; +} + +function buildQuotaPoolCycleMap(quotaPoolsMap, nowMs) { + const poolCycleBuckets = new Map(); + if (quotaPoolsMap instanceof Map && quotaPoolsMap.size > 0) { + const weekFallbackStartMs = getStartOfCurrentWeekMs(new Date(nowMs)); + for (const [poolKey, poolObj] of quotaPoolsMap.entries()) { + const reset5hMs = parseIsoMs(poolObj?.resetTime) || 0; + const start5hMs = + reset5hMs > nowMs + ? Math.min(nowMs, reset5hMs - 5 * 3600 * 1000) + : nowMs - 5 * 3600 * 1000; + const resetWkMs = parseIsoMs(poolObj?.weeklyResetTime) || 0; + const startWkMs = + resetWkMs > nowMs + ? Math.min(nowMs, resetWkMs - 7 * 24 * 3600 * 1000) + : weekFallbackStartMs; + poolCycleBuckets.set(poolKey, { + start5hMs, + startWkMs, + b5h: createUsageBucket(), + bWk: createUsageBucket(), + }); } } + return poolCycleBuckets; +} - for (const entry of allEntriesToAggregate) { - const { cascadeId, isCurrentConv } = entry; - const entryOwner = normalizeOwnerAccount(entry.accountName); - const srcKey = entry.appSource || 'standalone'; - const srcName = SOURCE_LABELS[srcKey] || `Antigravity (${srcKey})`; - - for (const st of entry.steps || []) { - if (!st || typeof st !== 'object') continue; - const stepOwner = normalizeOwnerAccount(st.accountName) || entryOwner; - const includeInQuotaPools = - normalizedQuotaAccount === null - ? false - : normalizedQuotaAccount === '' - ? true - : stepOwner === normalizedQuotaAccount; - const mInfo = resolveStepModel(st); - const inTok = safeTok(st.inputTokens); - const cacheTok = safeTok(st.cacheReadTokens); - const outTok = safeTok(st.outputTokens); - const thinkTok = safeTok(st.thinkingTokens); - const respTok = - st.responseTokens !== undefined && st.responseTokens !== null - ? safeTok(st.responseTokens) - : Math.max(0, outTok - thinkTok); - const stepTotalTokens = inTok + cacheTok + outTok; - const stepCost = computeStepCost(st, mInfo.pricing); - const resolvedCost = Number.isFinite(stepCost) ? stepCost : 0; - const unpriced = stepCost === null ? 1 : 0; - const tMs = Number(st.createdAtMs) > 0 ? Number(st.createdAtMs) : 0; - const savedCost = mInfo.pricing - ? (cacheTok / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache) - : 0; - const stepUsage = { inTok, cacheTok, outTok, thinkTok, respTok, stepTotalTokens, - resolvedCost, savedCost, unpriced }; - - if (tMs >= yearStartMs && tMs < nextYearStartMs) { - let monthIdx = 11; - for (let m = 0; m < 12; m++) { - if (tMs < monthBoundsMs[m + 1]) { - monthIdx = m; - break; - } - } - const mBucket = monthlySeries[monthIdx]; - if (mBucket) { - mBucket.calls += 1; - mBucket.inputTokens += inTok; - mBucket.cacheReadTokens += cacheTok; - mBucket.responseTokens += respTok; - mBucket.thinkingTokens += thinkTok; - mBucket.totalTokens += stepTotalTokens; - mBucket.costUsd += resolvedCost; - mBucket.unpricedCalls = (mBucket.unpricedCalls || 0) + unpriced; - accumulateStepIntoModelMap(mBucket.perModelStats, st, mInfo, stepCost); - } - } - - let poolBucketEntry = null; - if (poolCycleBuckets.size > 0) { - let cachedPool = poolByModel.get(mInfo); - if ( - !cachedPool || - cachedPool.key !== st.modelKey || - cachedPool.response !== st.responseModel || - cachedPool.displayName !== st.modelDisplayName - ) { - const ids = [ - st.modelKey, - st.responseModel, - mInfo.modelId, - mInfo.label, - st.modelDisplayName, - ]; - let poolKey = null; - if (hasDedicatedCarbonPool && isCarbonModelIdentifier(...ids)) poolKey = 'Carbon'; - else if (hasDedicatedArgonPool && isArgonModelIdentifier(...ids)) poolKey = 'Argon'; - else if (mInfo.family === 'Gemini') poolKey = 'Gemini'; - else if (['Claude', 'GPT', 'Other'].includes(mInfo.family)) poolKey = 'Claude & GPT'; - cachedPool = { - key: st.modelKey, - response: st.responseModel, - displayName: st.modelDisplayName, - bucket: poolCycleBuckets.get(poolKey) || null, - }; - poolByModel.set(mInfo, cachedPool); - } - poolBucketEntry = cachedPool.bucket; - } - - if (includeInQuotaPools && poolBucketEntry && tMs > 0 && tMs <= nowMs) { - if (tMs >= poolBucketEntry.start5hMs) { - accumulateStepIntoBucket(poolBucketEntry.b5h, stepUsage, cascadeId); - } - if (tMs >= poolBucketEntry.startWkMs) { - accumulateStepIntoBucket(poolBucketEntry.bWk, stepUsage, cascadeId); - } - } - - let inCurrentCycle = false; - if (tMs > 0 && tMs <= nowMs) { - if (isCustomWeeklyMode) { - inCurrentCycle = tMs >= presetWindows.week.startMs; - } else if (poolCycleBuckets.size > 0) { - const effCycleStartMs = poolBucketEntry - ? poolBucketEntry.startWkMs - : presetWindows.cycle.startMs; - inCurrentCycle = includeInQuotaPools && tMs >= effCycleStartMs; - } else { - inCurrentCycle = includeInQuotaPools && tMs >= presetWindows.cycle.startMs; - } - } - - for (const k of presetKeys) { - const w = presetWindows[k]; - const matchesPreset = - k === 'all' - ? true - : k === 'cycle' - ? inCurrentCycle - : tMs > 0 && tMs >= w.startMs && tMs <= w.endMs; - if (matchesPreset) { - accumulateStepIntoBucket(accountBuckets[k], stepUsage, cascadeId); - if (isCurrentConv) { - accumulateStepIntoBucket(sessionBuckets[k], stepUsage, cascadeId); - } - if (k === 'week' && includeInQuotaPools) { - accumulateStepIntoBucket(quotaWeekBucket, stepUsage, cascadeId); - } - } - } - - const inSelectedWindow = - selectedWindow.key === 'all' - ? true - : selectedWindow.key === 'cycle' - ? inCurrentCycle - : tMs > 0 && tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs; - - if (inSelectedWindow) { - if ( - selectedWindow.key === 'cycle' && - !isCustomWeeklyMode && - poolBucketEntry && - poolBucketEntry.startWkMs < earliestActiveCyclePoolStartMs - ) { - earliestActiveCyclePoolStartMs = poolBucketEntry.startWkMs; - } - if (selectedWindow.key === 'custom') { - accumulateStepIntoBucket(selectedAccountBucket, stepUsage, cascadeId); - if (isCurrentConv) { - accumulateStepIntoBucket(selectedSessionBucket, stepUsage, cascadeId); - } - } - if (tMs > 0) { - if (tMs < earliestSelectedStepMs) earliestSelectedStepMs = tMs; - if (tMs > latestSelectedStepMs && tMs <= MAX_TREND_TIMESTAMP_MS) latestSelectedStepMs = tMs; - selectedWindowSteps.push({ - tMs, - tokens: stepTotalTokens, - inputTokens: inTok, - cacheReadTokens: cacheTok, - outputTokens: outTok, - costUsd: resolvedCost, - unpricedCalls: unpriced, - mInfo, - responseModel: st.responseModel || '', - }); - } - - if (!perSourceStats.has(srcKey)) { - perSourceStats.set(srcKey, { - name: srcName, - calls: 0, - inputTokens: 0, - cacheReadTokens: 0, - responseTokens: 0, - thinkingTokens: 0, - totalTokens: 0, - costUsd: 0, - perModelStats: new Map(), - }); - } - const sAgg = perSourceStats.get(srcKey); - sAgg.calls += 1; - sAgg.inputTokens += inTok; - sAgg.cacheReadTokens += cacheTok; - sAgg.responseTokens += respTok; - sAgg.thinkingTokens += thinkTok; - sAgg.totalTokens += stepTotalTokens; - sAgg.costUsd += resolvedCost; - sAgg.unpricedCalls = (sAgg.unpricedCalls || 0) + unpriced; - accumulateStepIntoModelMap(sAgg.perModelStats, st, mInfo, stepCost); - - accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost); - } - } +function resolvePoolBucketForStep( + st, + mInfo, + poolCycleBuckets, + poolByModel, + hasDedicatedCarbonPool, + hasDedicatedArgonPool +) { + if (poolCycleBuckets.size === 0) return null; + let cachedPool = poolByModel.get(mInfo); + if ( + !cachedPool || + cachedPool.key !== st.modelKey || + cachedPool.response !== st.responseModel || + cachedPool.displayName !== st.modelDisplayName + ) { + const ids = [ + st.modelKey, + st.responseModel, + mInfo.modelId, + mInfo.label, + st.modelDisplayName, + ]; + let poolKey = null; + if (hasDedicatedCarbonPool && isCarbonModelIdentifier(...ids)) poolKey = 'Carbon'; + else if (hasDedicatedArgonPool && isArgonModelIdentifier(...ids)) poolKey = 'Argon'; + else if (mInfo.family === 'Gemini') poolKey = 'Gemini'; + else if (['Claude', 'GPT', 'Other'].includes(mInfo.family)) poolKey = 'Claude & GPT'; + cachedPool = { + key: st.modelKey, + response: st.responseModel, + displayName: st.modelDisplayName, + bucket: poolCycleBuckets.get(poolKey) || null, + }; + poolByModel.set(mInfo, cachedPool); } + return cachedPool.bucket; +} - const finalizedMonthlySeries = monthlySeries.map( - ({ perModelStats: monthModelMap, ...mBucket }) => ({ - ...mBucket, - costUsd: +mBucket.costUsd.toFixed(4), - models: finalizeModelBreakdownMap(monthModelMap), - }) - ); - - // 构建当前选定时间窗口的自适应自然整点/整日趋势序列 (trendSeries) - const effectiveSelectedWindow = - selectedWindow.key === 'cycle' && - Number.isFinite(earliestActiveCyclePoolStartMs) && - earliestActiveCyclePoolStartMs < Infinity - ? { - ...selectedWindow, - startMs: Math.min(earliestActiveCyclePoolStartMs, earliestSelectedStepMs), - } - : selectedWindow; +function buildUsageTrendSeries( + selectedWindow, + effectiveSelectedWindow, + selectedWindowSteps, + nowMs, + earliestSelectedStepMs, + latestSelectedStepMs +) { const trend = planUsageTrend( effectiveSelectedWindow, nowMs, @@ -1096,6 +769,409 @@ export function aggregateMultiWindowUsage({ } } + return { trend, trendStartMs, trendEndMs, trendSeries }; +} + +function planUsageTrend(window, nowMs, earliest, latest) { + const safeMs = (value, fallback) => + Number.isFinite(value) && value > 0 && value <= MAX_TREND_TIMESTAMP_MS ? value : fallback; + const end = Math.max(safeMs(window.endMs, Math.max(nowMs, latest || nowMs)), latest); + const defaultStart = end - 24 * 3600 * 1000; + const start = window.key === 'all' + ? Math.min(safeMs(earliest, defaultStart), end - 3600 * 1000) + : Math.min(safeMs(window.startMs, defaultStart), end); + const hourly = window.key === 'today' || window.key === '24h' || window.key === '5h' || + end - start <= 72 * 3600 * 1000; + const first = new Date(start); + const last = new Date(end); + if (hourly) { + first.setMinutes(0, 0, 0); + last.setMinutes(0, 0, 0); + } else { + first.setHours(0, 0, 0, 0); + last.setHours(0, 0, 0, 0); + } + return { start, end, hourly, first: first.getTime(), last: last.getTime() }; +} + +function sameUsageEntries(previous, current) { + return previous.length === current.length && current.every((entry, index) => { + const before = previous[index]; + return entry.steps === before.steps && entry.cascadeId === before.cascadeId && + entry.appSource === before.appSource && entry.accountName === before.accountName && + entry.isCurrentConv === before.isCurrentConv; + }); +} + +function sortedUsageTimestamps(entries) { + const dates = new Float64Array(entries.reduce((sum, entry) => sum + entry.steps.length, 0)); + let count = 0; + for (const { steps } of entries) { + for (const step of steps) { + const date = Number(step?.createdAtMs); + if (date > 0) dates[count++] = date; + } + } + return dates.subarray(0, count).sort(); +} + +function usageTimestampBoundary(dates, value, inclusive) { + let start = 0; + let end = dates.length; + while (start < end) { + const i = (start + end) >>> 1; + if (dates[i] < value || (inclusive && dates[i] === value)) start = i + 1; + else end = i; + } + return start; +} + +function sameUsageWindows(previous, current, dates) { + return previous.length === current.length && current.every((window, index) => { + const before = previous[index]; + return before.key === window.key && before.label === window.label && + (before.startMs === window.startMs || + usageTimestampBoundary(dates, before.startMs, false) === + usageTimestampBoundary(dates, window.startMs, false)) && + (before.endMs === window.endMs || + usageTimestampBoundary(dates, before.endMs, true) === + usageTimestampBoundary(dates, window.endMs, true)); + }); +} + +/** + * 聚合所有预设时间窗口、当前选定窗口、趋势图、年度月序列、来源占比与分模型统计。 + * + * @param {{ + * filterOpts?: { range?: string, startMs?: number, endMs?: number }, + * cycleAnchors?: { fiveHourResetMs?: number, weeklyResetMs?: number }, + * currentAccountName?: string|null, + * activeCascadeId?: string|null, + * activeFamilyCascadeIds?: Set|null, + * resolveStepModel: StepModelResolver + * modelInputs?: { catalogRevision: number, dynamicModelMap: Map } + * }} params + */ +export function aggregateMultiWindowUsage({ + filterOpts = {}, + cycleAnchors = {}, + isCustomWeeklyMode = false, + currentAccountName = '', + activeCascadeId = null, + activeFamilyCascadeIds = null, + resolveStepModel, + quotaPoolsMap = null, + modelInputs = null, +}) { + const rawFamilyIds = + activeFamilyCascadeIds instanceof Set + ? Array.from(activeFamilyCascadeIds) + : activeCascadeId + ? [activeCascadeId] + : []; + const familySet = new Set(rawFamilyIds.map((id) => String(id || '').toLowerCase())); + const nowMs = Date.now(); + const selectedWindow = resolveTimeWindow( + filterOpts.range || 'all', + filterOpts.startMs, + filterOpts.endMs, + nowMs, + cycleAnchors, + isCustomWeeklyMode + ); + + const presetKeys = ['all', 'cycle', '5h', 'today', '24h', 'week', '7d', '14d', '30d']; + const presetWindows = {}; + const accountBuckets = {}; + const sessionBuckets = {}; + + for (const k of presetKeys) { + presetWindows[k] = resolveTimeWindow(k, 0, 0, nowMs, cycleAnchors, isCustomWeeklyMode); + accountBuckets[k] = createUsageBucket(); + sessionBuckets[k] = createUsageBucket(); + } + + // 为每个配额池建立独立的 5h 与周限周期统计桶(按各池自身的 resetTime / weeklyResetTime 截取窗口) + const poolCycleBuckets = buildQuotaPoolCycleMap(quotaPoolsMap, nowMs); + const hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon'); + const hasDedicatedArgonPool = poolCycleBuckets.has('Argon'); + const poolByModel = new Map(); + const quotaWeekBucket = createUsageBucket(); + const normalizedQuotaAccount = + currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName); + const selectedAccountBucket = accountBuckets[selectedWindow.key] || createUsageBucket(); + const selectedSessionBucket = sessionBuckets[selectedWindow.key] || createUsageBucket(); + const perModelStats = new Map(); + const selectedWindowSteps = []; + let earliestSelectedStepMs = Infinity; + let latestSelectedStepMs = 0; + let earliestActiveCyclePoolStartMs = Infinity; + + const currentYear = new Date(nowMs).getFullYear(); + const monthBoundsMs = Array.from({ length: 13 }, (_, idx) => + new Date(currentYear, idx, 1).getTime() + ); + const yearStartMs = monthBoundsMs[0]; + const nextYearStartMs = monthBoundsMs[12]; + const monthlySeries = Array.from({ length: 12 }, (_, idx) => ({ + month: idx + 1, + label: `${idx + 1}月`, + calls: 0, + inputTokens: 0, + cacheReadTokens: 0, + responseTokens: 0, + thinkingTokens: 0, + totalTokens: 0, + costUsd: 0, + unpricedCalls: 0, + perModelStats: new Map(), + })); + + const perSourceStats = new Map(); + const allEntriesToAggregate = collectUsageEntriesToAggregate(familySet); + + const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : ''; + const quotaWindows = Array.from(poolCycleBuckets, ([key, { start5hMs, startWkMs }]) => [ + { key: `${key}:5h`, startMs: start5hMs, endMs: nowMs }, + { key: `${key}:week`, startMs: startWkMs, endMs: nowMs }, + ]).flat(); + const windows = [selectedWindow, ...Object.values(presetWindows), ...quotaWindows]; + const snapshot = lastUsageSnapshot; + const sameSnapshot = modelInputs && snapshot && timeZone === snapshot.timeZone && + currentYear === snapshot.currentYear && + Boolean(isCustomWeeklyMode) === Boolean(snapshot.isCustomWeeklyMode) && + normalizedQuotaAccount === snapshot.normalizedQuotaAccount && + modelInputs.catalogRevision === snapshot.modelInputs.catalogRevision && + isDeepStrictEqual(modelInputs.dynamicModelMap, snapshot.modelInputs.dynamicModelMap) && + sameUsageEntries(snapshot.entries, allEntriesToAggregate); + const previous = sameSnapshot ? snapshot.ranges.get(selectedWindow.key) : null; + if (previous) { + // 时钟继续前进,只有实际有步骤跨过窗口边界时才重新聚合。 + const effectivePrevWin = + selectedWindow.key === 'cycle' && previous.effectiveSelectedWindow + ? { ...previous.effectiveSelectedWindow, endMs: nowMs } + : selectedWindow; + const trend = planUsageTrend(effectivePrevWin, nowMs, previous.earliest, previous.latest); + if ( + trend.hourly === previous.trend.hourly && trend.first === previous.trend.first && + trend.last === previous.trend.last && + sameUsageWindows(previous.windows, windows, + snapshot.dates ??= sortedUsageTimestamps(allEntriesToAggregate)) + ) { + snapshot.ranges.delete(selectedWindow.key); + snapshot.ranges.set(selectedWindow.key, previous); + return { + ...previous.result, + usageRevision: snapshot.revision, + selectedWindow: effectivePrevWin, + trendStartMs: trend.start, + trendEndMs: trend.end, + }; + } + } + + for (const entry of allEntriesToAggregate) { + const { cascadeId, isCurrentConv } = entry; + const entryOwner = normalizeOwnerAccount(entry.accountName); + const srcKey = entry.appSource || 'standalone'; + const srcName = USAGE_SOURCE_LABELS[srcKey] || `Antigravity (${srcKey})`; + + for (const st of entry.steps || []) { + if (!st || typeof st !== 'object') continue; + const stepOwner = normalizeOwnerAccount(st.accountName) || entryOwner; + const includeInQuotaPools = + normalizedQuotaAccount === null + ? false + : normalizedQuotaAccount === '' + ? true + : stepOwner === normalizedQuotaAccount; + const mInfo = resolveStepModel(st); + const inTok = safeTok(st.inputTokens); + const cacheTok = safeTok(st.cacheReadTokens); + const outTok = safeTok(st.outputTokens); + const thinkTok = safeTok(st.thinkingTokens); + const respTok = + st.responseTokens !== undefined && st.responseTokens !== null + ? safeTok(st.responseTokens) + : Math.max(0, outTok - thinkTok); + const stepTotalTokens = inTok + cacheTok + outTok; + const stepCost = computeStepCost(st, mInfo.pricing); + const resolvedCost = Number.isFinite(stepCost) ? stepCost : 0; + const unpriced = stepCost === null ? 1 : 0; + const tMs = Number(st.createdAtMs) > 0 ? Number(st.createdAtMs) : 0; + const savedCost = mInfo.pricing + ? (cacheTok / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache) + : 0; + const stepUsage = { inTok, cacheTok, outTok, thinkTok, respTok, stepTotalTokens, + resolvedCost, savedCost, unpriced }; + + if (tMs >= yearStartMs && tMs < nextYearStartMs) { + let monthIdx = 11; + for (let m = 0; m < 12; m++) { + if (tMs < monthBoundsMs[m + 1]) { + monthIdx = m; + break; + } + } + const mBucket = monthlySeries[monthIdx]; + if (mBucket) { + mBucket.calls += 1; + mBucket.inputTokens += inTok; + mBucket.cacheReadTokens += cacheTok; + mBucket.responseTokens += respTok; + mBucket.thinkingTokens += thinkTok; + mBucket.totalTokens += stepTotalTokens; + mBucket.costUsd += resolvedCost; + mBucket.unpricedCalls = (mBucket.unpricedCalls || 0) + unpriced; + accumulateStepIntoModelMap(mBucket.perModelStats, st, mInfo, stepCost); + } + } + + const poolBucketEntry = resolvePoolBucketForStep( + st, + mInfo, + poolCycleBuckets, + poolByModel, + hasDedicatedCarbonPool, + hasDedicatedArgonPool + ); + + if (includeInQuotaPools && poolBucketEntry && tMs > 0 && tMs <= nowMs) { + if (tMs >= poolBucketEntry.start5hMs) { + accumulateStepIntoBucket(poolBucketEntry.b5h, stepUsage, cascadeId); + } + if (tMs >= poolBucketEntry.startWkMs) { + accumulateStepIntoBucket(poolBucketEntry.bWk, stepUsage, cascadeId); + } + } + + let inCurrentCycle = false; + if (tMs > 0 && tMs <= nowMs) { + if (isCustomWeeklyMode) { + inCurrentCycle = tMs >= presetWindows.week.startMs; + } else if (poolCycleBuckets.size > 0) { + const effCycleStartMs = poolBucketEntry + ? poolBucketEntry.startWkMs + : presetWindows.cycle.startMs; + inCurrentCycle = includeInQuotaPools && tMs >= effCycleStartMs; + } else { + inCurrentCycle = includeInQuotaPools && tMs >= presetWindows.cycle.startMs; + } + } + + for (const k of presetKeys) { + const w = presetWindows[k]; + const matchesPreset = + k === 'all' + ? true + : k === 'cycle' + ? inCurrentCycle + : tMs > 0 && tMs >= w.startMs && tMs <= w.endMs; + if (matchesPreset) { + accumulateStepIntoBucket(accountBuckets[k], stepUsage, cascadeId); + if (isCurrentConv) { + accumulateStepIntoBucket(sessionBuckets[k], stepUsage, cascadeId); + } + if (k === 'week' && includeInQuotaPools) { + accumulateStepIntoBucket(quotaWeekBucket, stepUsage, cascadeId); + } + } + } + + const inSelectedWindow = + selectedWindow.key === 'all' + ? true + : selectedWindow.key === 'cycle' + ? inCurrentCycle + : tMs > 0 && tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs; + + if (inSelectedWindow) { + if ( + selectedWindow.key === 'cycle' && + !isCustomWeeklyMode && + poolBucketEntry && + poolBucketEntry.startWkMs < earliestActiveCyclePoolStartMs + ) { + earliestActiveCyclePoolStartMs = poolBucketEntry.startWkMs; + } + if (selectedWindow.key === 'custom') { + accumulateStepIntoBucket(selectedAccountBucket, stepUsage, cascadeId); + if (isCurrentConv) { + accumulateStepIntoBucket(selectedSessionBucket, stepUsage, cascadeId); + } + } + if (tMs > 0) { + if (tMs < earliestSelectedStepMs) earliestSelectedStepMs = tMs; + if (tMs > latestSelectedStepMs && tMs <= MAX_TREND_TIMESTAMP_MS) latestSelectedStepMs = tMs; + selectedWindowSteps.push({ + tMs, + tokens: stepTotalTokens, + inputTokens: inTok, + cacheReadTokens: cacheTok, + outputTokens: outTok, + costUsd: resolvedCost, + unpricedCalls: unpriced, + mInfo, + responseModel: st.responseModel || '', + }); + } + + if (!perSourceStats.has(srcKey)) { + perSourceStats.set(srcKey, { + name: srcName, + calls: 0, + inputTokens: 0, + cacheReadTokens: 0, + responseTokens: 0, + thinkingTokens: 0, + totalTokens: 0, + costUsd: 0, + perModelStats: new Map(), + }); + } + const sAgg = perSourceStats.get(srcKey); + sAgg.calls += 1; + sAgg.inputTokens += inTok; + sAgg.cacheReadTokens += cacheTok; + sAgg.responseTokens += respTok; + sAgg.thinkingTokens += thinkTok; + sAgg.totalTokens += stepTotalTokens; + sAgg.costUsd += resolvedCost; + sAgg.unpricedCalls = (sAgg.unpricedCalls || 0) + unpriced; + accumulateStepIntoModelMap(sAgg.perModelStats, st, mInfo, stepCost); + + accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost); + } + } + } + + const finalizedMonthlySeries = monthlySeries.map( + ({ perModelStats: monthModelMap, ...mBucket }) => ({ + ...mBucket, + costUsd: +mBucket.costUsd.toFixed(4), + models: finalizeModelBreakdownMap(monthModelMap), + }) + ); + + // 构建当前选定时间窗口的自适应自然整点/整日趋势序列 (trendSeries) + const effectiveSelectedWindow = + selectedWindow.key === 'cycle' && + Number.isFinite(earliestActiveCyclePoolStartMs) && + earliestActiveCyclePoolStartMs < Infinity + ? { + ...selectedWindow, + startMs: Math.min(earliestActiveCyclePoolStartMs, earliestSelectedStepMs), + } + : selectedWindow; + const { trend, trendStartMs, trendEndMs, trendSeries } = buildUsageTrendSeries( + selectedWindow, + effectiveSelectedWindow, + selectedWindowSteps, + nowMs, + earliestSelectedStepMs, + latestSelectedStepMs + ); + const finalizedPresets = {}; for (const k of presetKeys) { finalizedPresets[k] = { @@ -1160,7 +1236,31 @@ export function aggregateMultiWindowUsage({ } : null; + let resolvedUsageRevision = usageSnapshotRevisionSeq; + if (modelInputs) { + if (!sameSnapshot) { + resolvedUsageRevision = ++usageSnapshotRevisionSeq; + lastUsageSnapshot = { + revision: resolvedUsageRevision, + timeZone, + modelInputs, + currentYear, + isCustomWeeklyMode: Boolean(isCustomWeeklyMode), + normalizedQuotaAccount, + entries: allEntriesToAggregate, + dates: null, + ranges: new Map(), + selectedRanges: new Map(), + }; + } else { + resolvedUsageRevision = lastUsageSnapshot.revision; + } + } else { + resolvedUsageRevision = ++usageSnapshotRevisionSeq; + } + const result = { + usageRevision: resolvedUsageRevision, selectedWindow: effectiveSelectedWindow, trendStartMs, trendEndMs, @@ -1178,31 +1278,396 @@ export function aggregateMultiWindowUsage({ poolCycleStats, poolsWeeklySummary, }; - if (modelInputs) { - if (!sameSnapshot) { - lastUsageSnapshot = { - timeZone, - modelInputs, - currentYear, - isCustomWeeklyMode: Boolean(isCustomWeeklyMode), - normalizedQuotaAccount, - entries: allEntriesToAggregate, - dates: null, - ranges: new Map(), - }; - } + if (modelInputs && lastUsageSnapshot) { const { ranges } = lastUsageSnapshot; ranges.delete(selectedWindow.key); ranges.set(selectedWindow.key, { windows, + selectedWindow, effectiveSelectedWindow, trend, result, earliest: earliestSelectedStepMs, latest: latestSelectedStepMs, }); - // 侧栏和悬浮窗可同时查看不同范围,共用时间索引并最多保留两份聚合结果。 - if (ranges.size > 2) ranges.delete(ranges.keys().next().value); + // 缓存各时间窗口的完整多窗口聚合结果,同快照复用时亚毫秒命中。 + if (ranges.size > 10) ranges.delete(ranges.keys().next().value); } return result; } + +/** + * 轻量级单时间窗口剪枝聚合器(专为 `scope=consumption` / `scope=consumption-presets` 瞬切服务): + * 1. 跳过 12 个月年度柱、9 预设桶与配额池 5h/周统计; + * 2. 基于会话级 `[minMs, maxMs]` 边界直接跳过时间完全不重叠的历史会话; + * 3. 与 `aggregateMultiWindowUsage` 共用完全一致的周期锚点、来源/模型归并及趋势分桶逻辑。 + */ +export function aggregateSelectedWindowUsage({ + filterOpts = {}, + cycleAnchors = {}, + isCustomWeeklyMode = false, + currentAccountName = '', + activeCascadeId = null, + activeFamilyCascadeIds = null, + resolveStepModel, + quotaPoolsMap = null, + modelInputs = null, + precollectedEntries = null, +}) { + const rawFamilyIds = + activeFamilyCascadeIds instanceof Set + ? Array.from(activeFamilyCascadeIds) + : activeCascadeId + ? [activeCascadeId] + : []; + const familySet = new Set(rawFamilyIds.map((id) => String(id || '').toLowerCase())); + const nowMs = Date.now(); + const selectedWindow = resolveTimeWindow( + filterOpts.range || 'all', + filterOpts.startMs, + filterOpts.endMs, + nowMs, + cycleAnchors, + isCustomWeeklyMode + ); + const weekStartMs = + selectedWindow.key === 'cycle' + ? resolveTimeWindow('week', 0, 0, nowMs, cycleAnchors, isCustomWeeklyMode).startMs + : 0; + const poolCycleBuckets = + selectedWindow.key === 'cycle' ? buildQuotaPoolCycleMap(quotaPoolsMap, nowMs) : new Map(); + const hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon'); + const hasDedicatedArgonPool = poolCycleBuckets.has('Argon'); + const poolByModel = new Map(); + const normalizedQuotaAccount = + currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName); + + const allEntriesToAggregate = Array.isArray(precollectedEntries) + ? precollectedEntries + : collectUsageEntriesToAggregate(familySet); + const currentYear = new Date(nowMs).getFullYear(); + const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : ''; + + const snapshot = lastUsageSnapshot; + const sameSnapshot = Boolean( + modelInputs && + snapshot && + timeZone === snapshot.timeZone && + currentYear === snapshot.currentYear && + Boolean(isCustomWeeklyMode) === Boolean(snapshot.isCustomWeeklyMode) && + normalizedQuotaAccount === snapshot.normalizedQuotaAccount && + modelInputs.catalogRevision === snapshot.modelInputs.catalogRevision && + isDeepStrictEqual(modelInputs.dynamicModelMap, snapshot.modelInputs.dynamicModelMap) && + sameUsageEntries(snapshot.entries, allEntriesToAggregate) + ); + + if (sameSnapshot) { + snapshot.selectedRanges ??= new Map(); + const cachedFull = snapshot.ranges.get(selectedWindow.key); + const cachedLite = snapshot.selectedRanges.get(selectedWindow.key); + const candidate = cachedFull || cachedLite; + if (candidate) { + const prevWin = candidate.selectedWindow || candidate.windows?.[0] || selectedWindow; + const effectivePrevWin = + selectedWindow.key === 'cycle' && candidate.effectiveSelectedWindow + ? { ...candidate.effectiveSelectedWindow, endMs: nowMs } + : selectedWindow; + const trend = planUsageTrend(effectivePrevWin, nowMs, candidate.earliest, candidate.latest); + if ( + trend.hourly === candidate.trend.hourly && + trend.first === candidate.trend.first && + trend.last === candidate.trend.last && + sameUsageWindows( + [prevWin], + [selectedWindow], + (snapshot.dates ??= sortedUsageTimestamps(allEntriesToAggregate)) + ) + ) { + const res = candidate.result; + return { + usageRevision: snapshot.revision, + selectedWindow: effectivePrevWin, + trendStartMs: trend.start, + trendEndMs: trend.end, + finalizedSelectedSession: res.finalizedSelectedSession, + finalizedSelectedAccount: res.finalizedSelectedAccount, + trendSeries: res.trendSeries, + sourcesBreakdown: res.sourcesBreakdown, + modelBreakdown: res.modelBreakdown, + }; + } + } + } + + let minCutoffMs = 0; + let maxCutoffMs = Infinity; + let canPruneByTime = false; + if (selectedWindow.key === 'cycle') { + canPruneByTime = true; + maxCutoffMs = nowMs; + if (isCustomWeeklyMode) { + minCutoffMs = weekStartMs; + } else if (poolCycleBuckets.size > 0) { + minCutoffMs = selectedWindow.startMs; + for (const entry of poolCycleBuckets.values()) { + if (entry.startWkMs < minCutoffMs) minCutoffMs = entry.startWkMs; + } + } else { + minCutoffMs = selectedWindow.startMs; + } + } else if (selectedWindow.key !== 'all') { + canPruneByTime = true; + minCutoffMs = selectedWindow.startMs; + maxCutoffMs = selectedWindow.endMs; + } + + const selectedAccountBucket = createUsageBucket(); + const selectedSessionBucket = createUsageBucket(); + const perModelStats = new Map(); + const perSourceStats = new Map(); + const selectedWindowSteps = []; + let earliestSelectedStepMs = Infinity; + let latestSelectedStepMs = 0; + let earliestActiveCyclePoolStartMs = Infinity; + + for (const entry of allEntriesToAggregate) { + const steps = entry.steps || []; + if (steps.length === 0) continue; + if (canPruneByTime) { + const bounds = getStepsTimeBounds(steps); + if (bounds.maxMs <= 0 || bounds.maxMs < minCutoffMs || bounds.minMs > maxCutoffMs) { + continue; + } + } + const { cascadeId, isCurrentConv } = entry; + const entryOwner = normalizeOwnerAccount(entry.accountName); + const srcKey = entry.appSource || 'standalone'; + const srcName = USAGE_SOURCE_LABELS[srcKey] || `Antigravity (${srcKey})`; + + for (const st of steps) { + if (!st || typeof st !== 'object') continue; + const tMs = Number(st.createdAtMs) > 0 ? Number(st.createdAtMs) : 0; + if (canPruneByTime && (tMs <= 0 || tMs < minCutoffMs || tMs > maxCutoffMs)) { + continue; + } + + let poolBucketEntry = null; + let mInfo = null; + if (selectedWindow.key === 'cycle') { + const stepOwner = normalizeOwnerAccount(st.accountName) || entryOwner; + const includeInQuotaPools = + normalizedQuotaAccount === null + ? false + : normalizedQuotaAccount === '' + ? true + : stepOwner === normalizedQuotaAccount; + let inCurrentCycle = false; + if (isCustomWeeklyMode) { + inCurrentCycle = tMs >= weekStartMs; + } else if (poolCycleBuckets.size > 0) { + if (!includeInQuotaPools) continue; + mInfo = resolveStepModel(st); + poolBucketEntry = resolvePoolBucketForStep( + st, + mInfo, + poolCycleBuckets, + poolByModel, + hasDedicatedCarbonPool, + hasDedicatedArgonPool + ); + const effCycleStartMs = poolBucketEntry + ? poolBucketEntry.startWkMs + : selectedWindow.startMs; + inCurrentCycle = tMs >= effCycleStartMs; + } else { + inCurrentCycle = includeInQuotaPools && tMs >= selectedWindow.startMs; + } + if (!inCurrentCycle) continue; + if ( + !isCustomWeeklyMode && + poolBucketEntry && + poolBucketEntry.startWkMs < earliestActiveCyclePoolStartMs + ) { + earliestActiveCyclePoolStartMs = poolBucketEntry.startWkMs; + } + } + + mInfo ??= resolveStepModel(st); + const inTok = safeTok(st.inputTokens); + const cacheTok = safeTok(st.cacheReadTokens); + const outTok = safeTok(st.outputTokens); + const thinkTok = safeTok(st.thinkingTokens); + const respTok = + st.responseTokens !== undefined && st.responseTokens !== null + ? safeTok(st.responseTokens) + : Math.max(0, outTok - thinkTok); + const stepTotalTokens = inTok + cacheTok + outTok; + const stepCost = computeStepCost(st, mInfo.pricing); + const resolvedCost = Number.isFinite(stepCost) ? stepCost : 0; + const unpriced = stepCost === null ? 1 : 0; + const savedCost = mInfo.pricing + ? (cacheTok / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache) + : 0; + const stepUsage = { + inTok, + cacheTok, + outTok, + thinkTok, + respTok, + stepTotalTokens, + resolvedCost, + savedCost, + unpriced, + }; + + accumulateStepIntoBucket(selectedAccountBucket, stepUsage, cascadeId); + if (isCurrentConv) { + accumulateStepIntoBucket(selectedSessionBucket, stepUsage, cascadeId); + } + + if (tMs > 0) { + if (tMs < earliestSelectedStepMs) earliestSelectedStepMs = tMs; + if (tMs > latestSelectedStepMs && tMs <= MAX_TREND_TIMESTAMP_MS) latestSelectedStepMs = tMs; + selectedWindowSteps.push({ + tMs, + tokens: stepTotalTokens, + inputTokens: inTok, + cacheReadTokens: cacheTok, + outputTokens: outTok, + costUsd: resolvedCost, + unpricedCalls: unpriced, + mInfo, + responseModel: st.responseModel || '', + }); + } + + if (!perSourceStats.has(srcKey)) { + perSourceStats.set(srcKey, { + name: srcName, + calls: 0, + inputTokens: 0, + cacheReadTokens: 0, + responseTokens: 0, + thinkingTokens: 0, + totalTokens: 0, + costUsd: 0, + perModelStats: new Map(), + }); + } + const sAgg = perSourceStats.get(srcKey); + sAgg.calls += 1; + sAgg.inputTokens += inTok; + sAgg.cacheReadTokens += cacheTok; + sAgg.responseTokens += respTok; + sAgg.thinkingTokens += thinkTok; + sAgg.totalTokens += stepTotalTokens; + sAgg.costUsd += resolvedCost; + sAgg.unpricedCalls = (sAgg.unpricedCalls || 0) + unpriced; + accumulateStepIntoModelMap(sAgg.perModelStats, st, mInfo, stepCost); + + accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost); + } + } + + const effectiveSelectedWindow = + selectedWindow.key === 'cycle' && + Number.isFinite(earliestActiveCyclePoolStartMs) && + earliestActiveCyclePoolStartMs < Infinity + ? { + ...selectedWindow, + startMs: Math.min(earliestActiveCyclePoolStartMs, earliestSelectedStepMs), + } + : selectedWindow; + + const { trend, trendStartMs, trendEndMs, trendSeries } = buildUsageTrendSeries( + selectedWindow, + effectiveSelectedWindow, + selectedWindowSteps, + nowMs, + earliestSelectedStepMs, + latestSelectedStepMs + ); + + const finalizedSelectedSession = finalizeUsageBucket(selectedSessionBucket); + const finalizedSelectedAccount = finalizeUsageBucket(selectedAccountBucket); + const sourcesBreakdown = Array.from(perSourceStats.values()) + .filter((s) => s.totalTokens > 0 || s.calls > 0) + .map(({ perModelStats: sourceModelMap, ...s }) => ({ + ...s, + costUsd: +s.costUsd.toFixed(2), + models: finalizeModelBreakdownMap(sourceModelMap), + })) + .sort((a, b) => b.totalTokens - a.totalTokens || b.calls - a.calls); + const modelBreakdown = finalizeModelBreakdownMap(perModelStats); + + const sliceResult = { + usageRevision: sameSnapshot ? snapshot.revision : usageSnapshotRevisionSeq, + selectedWindow: effectiveSelectedWindow, + trendStartMs, + trendEndMs, + finalizedSelectedSession, + finalizedSelectedAccount, + trendSeries, + sourcesBreakdown, + modelBreakdown, + }; + + if (sameSnapshot) { + snapshot.selectedRanges ??= new Map(); + snapshot.selectedRanges.delete(selectedWindow.key); + snapshot.selectedRanges.set(selectedWindow.key, { + selectedWindow, + effectiveSelectedWindow, + trend, + result: sliceResult, + earliest: earliestSelectedStepMs, + latest: latestSelectedStepMs, + }); + if (snapshot.selectedRanges.size > 12) { + snapshot.selectedRanges.delete(snapshot.selectedRanges.keys().next().value); + } + } + + return sliceResult; +} + +/** + * 批量预聚合全部 7 个用量页预设区间(复用同一次条目收集与时间剪枝),供前端进入「用量统计」时静默预取实现 0ms 瞬切。 + */ +export function aggregateConsumptionPresetBundle(params) { + const { activeCascadeId = null, activeFamilyCascadeIds = null } = params || {}; + const rawFamilyIds = + activeFamilyCascadeIds instanceof Set + ? Array.from(activeFamilyCascadeIds) + : activeCascadeId + ? [activeCascadeId] + : []; + const familySet = new Set(rawFamilyIds.map((id) => String(id || '').toLowerCase())); + const precollectedEntries = collectUsageEntriesToAggregate(familySet); + const ranges = {}; + let usageRevision = usageSnapshotRevisionSeq; + + for (const rangeKey of CONSUMPTION_PRESET_RANGE_KEYS) { + const agg = aggregateSelectedWindowUsage({ + ...params, + filterOpts: { range: rangeKey }, + precollectedEntries, + }); + usageRevision = agg.usageRevision; + ranges[rangeKey] = { + selectedRange: { + key: agg.selectedWindow.key, + label: agg.selectedWindow.label, + startMs: agg.trendStartMs, + endMs: agg.trendEndMs, + }, + session: agg.finalizedSelectedSession, + account: agg.finalizedSelectedAccount, + trendSeries: agg.trendSeries, + sourcesBreakdown: agg.sourcesBreakdown, + modelBreakdown: agg.modelBreakdown, + }; + } + + return { usageRevision, ranges }; +} diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index e9c6d9f..19e3f87 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/charts/TrendAreaChart.js b/sidecars/panel/src/components/charts/TrendAreaChart.js index 08f6191..aced2d2 100644 --- a/sidecars/panel/src/components/charts/TrendAreaChart.js +++ b/sidecars/panel/src/components/charts/TrendAreaChart.js @@ -920,13 +920,18 @@ export function createTrendAreaChart() { hmMonthsEl.appendChild(mEl); } - // 重建 7 行 × N 周列的每日小格子(一格一天) + // 重建 7 行 × N 周列的每日小格子(一格一天),使用 DocumentFragment 一次性批量挂载减少重排 while (hmGridEl.firstChild) hmGridEl.removeChild(hmGridEl.firstChild); hoveredCellEl = null; currentCellEls = new Array(slots.length); + const gridFrag = + typeof document !== 'undefined' && typeof document.createDocumentFragment === 'function' + ? document.createDocumentFragment() + : null; + const gridTarget = gridFrag || hmGridEl; for (let pad = 0; pad < firstDow; pad++) { - hmGridEl.appendChild( + gridTarget.appendChild( h('span', { className: 'trend-hm-cell is-pad', 'aria-hidden': 'true' }) ); } @@ -945,9 +950,12 @@ export function createTrendAreaChart() { 'data-hm-row': String(row), role: 'gridcell', }); - hmGridEl.appendChild(cellEl); + gridTarget.appendChild(cellEl); currentCellEls[i] = cellEl; } + if (gridFrag) { + hmGridEl.appendChild(gridFrag); + } if (typeof requestAnimationFrame === 'function') { requestAnimationFrame(() => { diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index c7a95da..d449691 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -141,9 +141,16 @@ let pollTimer = null; let feedbackTimer = null; let activeBundleVersion = 0; let latestRequestSeq = 0; +let latestConsumptionReqSeq = 0; let activeForceCount = 0; let consecutivePollFailures = 0; let inFlightTelemetryPoll = null; +let inFlightPresetsPrefetch = null; +let lastPrefetchedUsageRevision = 0; +let consumptionCacheScopeSig = ''; +const MAX_CONSUMPTION_RANGE_CACHE = 12; +const CONSUMPTION_PRESET_KEYS = ['cycle', 'today', '24h', '7d', '14d', '30d', 'all']; +const consumptionRangeCache = new Map(); let lastReceivedSteps = null; let loopActive = false; let loopIntervalMs = 2000; @@ -161,6 +168,96 @@ const TELEMETRY_RECOMPUTE_SETTING_KEYS = new Set([ 'enableWindowOverlay', ]); +function makeConsumptionRangeCacheKey(range, customStartMs = 0, customEndMs = 0) { + const key = String(range || 'all'); + if (key === 'custom') { + return `custom:${Number(customStartMs || 0)}:${Number(customEndMs || 0)}`; + } + return key; +} + +export function clearConsumptionRangeCache() { + consumptionRangeCache.clear(); + lastPrefetchedUsageRevision = 0; + inFlightPresetsPrefetch = null; +} + +function buildConsumptionScopeSig(payload) { + if (!payload || typeof payload !== 'object') return ''; + const acct = payload.account || {}; + const set = payload.settings || {}; + const cloud = payload.cloudStatus || {}; + return `${String(acct.status || '')}|${String(acct.email || acct.name || '').toLowerCase()}|${String(set.weeklyLimitMode || '')}|${String(cloud.catalogVersion || '')}`; +} + +function syncConsumptionCacheScope(payload) { + const nextSig = buildConsumptionScopeSig(payload); + if (!nextSig) return; + if (consumptionCacheScopeSig && consumptionCacheScopeSig !== nextSig) { + clearConsumptionRangeCache(); + } + consumptionCacheScopeSig = nextSig; +} + +function putConsumptionRangeCacheEntry(cacheKey, entry) { + if (!cacheKey || !entry) return; + consumptionRangeCache.delete(cacheKey); + consumptionRangeCache.set(cacheKey, entry); + while (consumptionRangeCache.size > MAX_CONSUMPTION_RANGE_CACHE) { + consumptionRangeCache.delete(consumptionRangeCache.keys().next().value); + } +} + +function recordConsumptionSliceToCache( + cons, + modelBreakdown, + { customStartMs = 0, customEndMs = 0, usageRevision = 0 } = {} +) { + const rangeKey = String(cons?.selectedRange?.key || ''); + if (!rangeKey) return; + const cacheKey = makeConsumptionRangeCacheKey( + rangeKey, + rangeKey === 'custom' ? customStartMs || cons.selectedRange?.startMs || 0 : 0, + rangeKey === 'custom' ? customEndMs || cons.selectedRange?.endMs || 0 : 0 + ); + putConsumptionRangeCacheEntry(cacheKey, { + revision: Number(cons.revision ?? usageRevision ?? 0), + selectedRange: cons.selectedRange, + session: cons.session, + account: cons.account, + trendSeries: Array.isArray(cons.trendSeries) ? cons.trendSeries : [], + sourcesBreakdown: Array.isArray(cons.sourcesBreakdown) ? cons.sourcesBreakdown : [], + modelBreakdown: Array.isArray(modelBreakdown) ? modelBreakdown : [], + }); +} + +function applyCachedConsumptionSlice(baseTelemetry, cachedEntry, targetRevision = 0) { + if (!baseTelemetry || !cachedEntry) return baseTelemetry; + const prevCons = baseTelemetry.consumption || {}; + return { + ...baseTelemetry, + consumption: { + ...prevCons, + ...(targetRevision > 0 ? { revision: targetRevision } : {}), + selectedRange: cachedEntry.selectedRange, + session: cachedEntry.session ?? prevCons.session, + account: cachedEntry.account ?? prevCons.account, + trendSeries: cachedEntry.trendSeries, + sourcesBreakdown: cachedEntry.sourcesBreakdown, + }, + modelBreakdown: cachedEntry.modelBreakdown, + }; +} + +function hasAllPresetRangesCached(expectedRevision) { + for (const key of CONSUMPTION_PRESET_KEYS) { + const entry = consumptionRangeCache.get(key); + if (!entry) return false; + if (expectedRevision > 0 && entry.revision !== expectedRevision) return false; + } + return true; +} + function enqueueSettingsWrite(task) { const run = settingsWriteChain.then(task, task); settingsWriteChain = run.catch(() => {}); @@ -853,6 +950,9 @@ function readDisplaySteps(payload) { async function requestTelemetry(params, force) { const reqSeq = ++latestRequestSeq; const reqSettingsRev = settingsRevision; + const reqRange = String(params.get('range') || ''); + const reqStartMs = Number(params.get('startMs') || 0); + const reqEndMs = Number(params.get('endMs') || 0); const startMs = Date.now(); if (force) { @@ -903,8 +1003,57 @@ async function requestTelemetry(params, force) { } consecutivePollFailures = 0; - const resolvedPayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev); + let resolvedPayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev); + syncConsumptionCacheScope(resolvedPayload); + if (resolvedPayload?.consumption) { + recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, { + customStartMs: reqStartMs, + customEndMs: reqEndMs, + }); + } + const latestSt = telemetryStore.getState(); + const incomingRev = Number(resolvedPayload?.consumption?.revision || 0); + const matchesCurrentRange = + !reqRange || + (reqRange === latestSt.selectedTimeRange && + (reqRange !== 'custom' || + (reqStartMs === Number(latestSt.customStartMs || 0) && + reqEndMs === Number(latestSt.customEndMs || 0)))); + + // 常规 2 秒轮询在途期间若用户已通过前端缓存瞬切到其他时间段,保留用户当前选中的范围不回跳, + // 若后端 usageRevision 已推进则静默补发一次轻量范围校准。 + let needsSilentRangeRevalidate = false; + if (!force && !matchesCurrentRange && resolvedPayload?.consumption) { + const activeKey = makeConsumptionRangeCacheKey( + latestSt.selectedTimeRange, + latestSt.customStartMs, + latestSt.customEndMs + ); + const cachedActive = consumptionRangeCache.get(activeKey); + if (cachedActive) { + resolvedPayload = applyCachedConsumptionSlice(resolvedPayload, cachedActive, incomingRev); + if (incomingRev > 0 && cachedActive.revision !== incomingRev) { + needsSilentRangeRevalidate = true; + } + } else if ( + latestSt.telemetry?.consumption?.selectedRange?.key === latestSt.selectedTimeRange + ) { + resolvedPayload = { + ...resolvedPayload, + consumption: { + ...resolvedPayload.consumption, + selectedRange: latestSt.telemetry.consumption.selectedRange, + session: latestSt.telemetry.consumption.session, + account: latestSt.telemetry.consumption.account, + trendSeries: latestSt.telemetry.consumption.trendSeries, + sourcesBreakdown: latestSt.telemetry.consumption.sourcesBreakdown, + }, + modelBreakdown: latestSt.telemetry.modelBreakdown, + }; + } + } + if (force) { const elapsed = Date.now() - startMs; if (elapsed < 220) { @@ -933,6 +1082,13 @@ async function requestTelemetry(params, force) { minuteTick: Math.floor(Date.now() / 30000), syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle', }); + if (needsSilentRangeRevalidate) { + void fetchConsumptionRangeSlice({ + range: latestSt.selectedTimeRange, + customStartMs: latestSt.customStartMs, + customEndMs: latestSt.customEndMs, + }); + } return resolvedPayload; } } catch (err) { @@ -952,6 +1108,198 @@ async function requestTelemetry(params, force) { } } +async function fetchConsumptionRangeSlice({ + range, + customStartMs = 0, + customEndMs = 0, +} = {}) { + const reqSeq = ++latestConsumptionReqSeq; + const targetRange = String(range || 'today'); + const current = telemetryStore.getState(); + const effectiveConvId = current.selectedConversationId || current.hostRouteConversationId || ''; + const params = new URLSearchParams(); + if (effectiveConvId) params.set('conversationId', effectiveConvId); + params.set('range', targetRange); + if (targetRange === 'custom') { + if (customStartMs > 0) params.set('startMs', String(customStartMs)); + if (customEndMs > 0) params.set('endMs', String(customEndMs)); + } + params.set('scope', 'consumption'); + + try { + const payload = await callSidecarApi(`/api/telemetry?${params}`, { + method: 'GET', + abortKey: 'consumption-range', + }); + if (!payload || typeof payload !== 'object') return null; + + if (payload.scope === 'consumption' && payload.consumption) { + const usageRev = Number(payload.usageRevision ?? payload.consumption.revision ?? 0); + recordConsumptionSliceToCache(payload.consumption, payload.modelBreakdown, { + customStartMs, + customEndMs, + usageRevision: usageRev, + }); + if (reqSeq !== latestConsumptionReqSeq) return payload; + + const latestSt = telemetryStore.getState(); + const stillMatches = + latestSt.selectedTimeRange === targetRange && + (targetRange !== 'custom' || + (Number(latestSt.customStartMs || 0) === Number(customStartMs || 0) && + Number(latestSt.customEndMs || 0) === Number(customEndMs || 0))); + if (!stillMatches) return payload; + + const prevTelemetry = latestSt.telemetry; + if (prevTelemetry) { + const nextTelemetry = { + ...prevTelemetry, + consumption: { + ...(prevTelemetry.consumption || {}), + ...payload.consumption, + ...(usageRev > 0 ? { revision: usageRev } : {}), + }, + modelBreakdown: Array.isArray(payload.modelBreakdown) + ? payload.modelBreakdown + : prevTelemetry.modelBreakdown, + }; + if (!isEquivalentTelemetry(prevTelemetry, nextTelemetry)) { + telemetryStore.setState({ telemetry: nextTelemetry }); + } + } + return payload; + } + + // 冷启动阶段后端尚无基础快照时会回退返回完整 telemetry,直接平滑复用现有状态合并 + if (payload.consumption) { + syncConsumptionCacheScope(payload); + recordConsumptionSliceToCache(payload.consumption, payload.modelBreakdown, { + customStartMs, + customEndMs, + }); + if (reqSeq === latestConsumptionReqSeq) { + const latestSt = telemetryStore.getState(); + if (!isEquivalentTelemetry(latestSt.telemetry, payload)) { + telemetryStore.setState({ telemetry: payload }); + } + } + } + return payload; + } catch (err) { + if (err?.name === 'AbortError') return null; + return null; + } +} + +/** + * 切换「用量统计」时间范围: + * - 命中前端 rangeCache 时,在单次 setState 内 0ms 原子更新概览/趋势/模型/来源(若 usageRevision 一致则 0 次 HTTP 请求); + * - 若后台数据已更新则先 0ms 展示缓存,再静默发起轻量 `scope=consumption` 校准; + * - 未命中缓存(如自定义时段或进页首 20ms 抢点)则直接走 `<5ms` 的 `scope=consumption` 通道。 + */ +export function selectConsumptionTimeRange( + nextRange, + { customStartMs = undefined, customEndMs = undefined } = {} +) { + const targetRange = String(nextRange || 'today'); + const prevSt = telemetryStore.getState(); + const nextStartMs = + targetRange === 'custom' + ? Number(customStartMs !== undefined ? customStartMs : prevSt.customStartMs || 0) + : prevSt.customStartMs; + const nextEndMs = + targetRange === 'custom' + ? Number(customEndMs !== undefined ? customEndMs : prevSt.customEndMs || 0) + : prevSt.customEndMs; + + const statePatch = { selectedTimeRange: targetRange }; + if (targetRange === 'custom') { + statePatch.customStartMs = nextStartMs; + statePatch.customEndMs = nextEndMs; + } + + const cacheKey = makeConsumptionRangeCacheKey(targetRange, nextStartMs, nextEndMs); + const cached = consumptionRangeCache.get(cacheKey); + const prevTelemetry = prevSt.telemetry; + + if (cached && prevTelemetry) { + const currentRev = Number(prevTelemetry.consumption?.revision || 0); + const nextTelemetry = applyCachedConsumptionSlice( + prevTelemetry, + cached, + currentRev > 0 ? currentRev : cached.revision + ); + telemetryStore.setState({ ...statePatch, telemetry: nextTelemetry }); + if (currentRev > 0 && cached.revision === currentRev) { + return Promise.resolve(nextTelemetry); + } + return fetchConsumptionRangeSlice({ + range: targetRange, + customStartMs: nextStartMs, + customEndMs: nextEndMs, + }); + } + + telemetryStore.setState(statePatch); + return fetchConsumptionRangeSlice({ + range: targetRange, + customStartMs: nextStartMs, + customEndMs: nextEndMs, + }); +} + +/** + * 仅在进入「用量统计」视图时触发一次静默后台预取,拉齐全部 7 个预设区间到前端缓存以实现 0ms 瞬切。 + */ +export function prefetchConsumptionPresets() { + const prevTelemetry = telemetryStore.getState().telemetry; + const currentRev = Number(prevTelemetry?.consumption?.revision || 0); + if (currentRev > 0 && lastPrefetchedUsageRevision === currentRev && hasAllPresetRangesCached(currentRev)) { + return Promise.resolve(true); + } + if (inFlightPresetsPrefetch) { + return inFlightPresetsPrefetch; + } + + const current = telemetryStore.getState(); + const effectiveConvId = current.selectedConversationId || current.hostRouteConversationId || ''; + const params = new URLSearchParams(); + if (effectiveConvId) params.set('conversationId', effectiveConvId); + params.set('scope', 'consumption-presets'); + + const task = callSidecarApi(`/api/telemetry?${params}`, { + method: 'GET', + abortKey: 'consumption-presets', + }) + .then((payload) => { + if (payload?.scope === 'consumption-presets' && payload.ranges && typeof payload.ranges === 'object') { + const rev = Number(payload.usageRevision || currentRev || 0); + for (const [rangeKey, entry] of Object.entries(payload.ranges)) { + if (!entry || typeof entry !== 'object') continue; + recordConsumptionSliceToCache( + { ...entry, revision: rev }, + entry.modelBreakdown, + { usageRevision: rev } + ); + } + if (rev > 0) { + lastPrefetchedUsageRevision = rev; + } + return true; + } + return false; + }) + .catch(() => false) + .finally(() => { + if (inFlightPresetsPrefetch === task) { + inFlightPresetsPrefetch = null; + } + }); + + inFlightPresetsPrefetch = task; + return task; +} + export async function saveSettingsPatch(patch) { const safePatch = patch && typeof patch === 'object' ? { ...patch } : {}; if (Object.prototype.hasOwnProperty.call(safePatch, 'language')) { @@ -1127,6 +1475,9 @@ export async function saveSettingsPatch(patch) { } const needsTelemetryRecompute = patchKeys.some((k) => TELEMETRY_RECOMPUTE_SETTING_KEYS.has(k)); + if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) { + clearConsumptionRangeCache(); + } if (needsTelemetryRecompute) { inFlightTelemetryPoll = null; void fetchTelemetry({ force: false }); @@ -1190,18 +1541,21 @@ export async function resetAllSettings() { }); } inFlightTelemetryPoll = null; + clearConsumptionRangeCache(); void fetchTelemetry({ force: false }); return res; } export async function rebuildTrajectoryCache() { const res = await callSidecarApi('/api/cache/rebuild', { method: 'POST', body: {} }); + clearConsumptionRangeCache(); await fetchTelemetry({ force: true }); return res; } export async function triggerCloudSync() { const res = await callSidecarApi('/api/cloud-sync', { method: 'POST', body: {} }); + clearConsumptionRangeCache(); await fetchTelemetry({ force: true }); return res; } diff --git a/sidecars/panel/src/views/ConsumptionView.js b/sidecars/panel/src/views/ConsumptionView.js index 11e6a6e..7c26f2c 100644 --- a/sidecars/panel/src/views/ConsumptionView.js +++ b/sidecars/panel/src/views/ConsumptionView.js @@ -33,7 +33,11 @@ import { import { scaleBucketsExact } from '../../shared/telemetry-display-rules.mjs'; import { i18nStore, isEnglishLocale, t } from '../i18n/index.js'; import { createSvgIcon } from '../icons/SvgIcon.js'; -import { fetchTelemetry, telemetryStore } from '../store/telemetryStore.js'; +import { + prefetchConsumptionPresets, + selectConsumptionTimeRange, + telemetryStore, +} from '../store/telemetryStore.js'; import { getVisibleMonitorView, uiStore } from '../store/uiStore.js'; import { createTrendAreaChart, @@ -81,8 +85,7 @@ export const ConsumptionView = defineComponent({ } else { hasUncommittedCustomDraft = false; } - telemetryStore.setState({ selectedTimeRange: nextRange }); - fetchTelemetry({ force: false }); + selectConsumptionTimeRange(nextRange); }, }); @@ -121,12 +124,10 @@ export const ConsumptionView = defineComponent({ hasUncommittedCustomDraft = false; startPicker.setValue(minMs); endPicker.setValue(maxMs); - telemetryStore.setState({ - selectedTimeRange: 'custom', + selectConsumptionTimeRange('custom', { customStartMs: minMs, customEndMs: maxMs, }); - fetchTelemetry({ force: true }); }, }, [createSvgIcon('check', { size: 12 }), applyCustomBtnLabel] @@ -868,8 +869,21 @@ export const ConsumptionView = defineComponent({ let latestSlice = null; let isDirty = false; + let prefetchedOnCurrentVisit = false; - let lastRenderedUsage = ''; + let lastRenderedTuple = null; + let cachedMonthlySeriesRef = null; + let cachedMonthlyDisplayKey = ''; + let cachedMonthsMergedModels = null; + let cachedAllMonthMergedModels = null; + + function isSameRenderTuple(prev, next) { + if (!prev || prev.length !== next.length) return false; + for (let i = 0; i < prev.length; i++) { + if (!Object.is(prev[i], next[i])) return false; + } + return true; + } /** * 将遥测状态切片同步渲染至消费统计视图的 5 个子面板。 @@ -877,31 +891,9 @@ export const ConsumptionView = defineComponent({ function renderConsumptionData(slice) { if (!slice) return; const cons = slice.consumption || {}; - const preset = - slice.range !== 'custom' && cons.presets?.[slice.range] - ? cons.presets[slice.range] - : null; - const acct = preset?.account || cons.account || {}; const rangeInfo = cons.selectedRange || {}; - const dateSpan = formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs); - const now = new Date(); - const currentMonthIdx = now.getMonth(); - const monthlyYear = cons.monthlyYear || now.getFullYear(); - const locale = i18nStore.getState().locale; - // 额度与会话状态也会发布遥测更新,只对用量页实际展示的数据重绘。 - const signature = JSON.stringify([ - locale, slice.range, slice.customStartMs, slice.customEndMs, slice.modelDisplayMode, - slice.showUpstreamModel, slice.orchestratorIdMode, dateSpan, - preset?.label || rangeInfo.label, acct, - cons.trendSeries, slice.modelBreakdown, cons.sourcesBreakdown, - monthlyYear, currentMonthIdx, cons.monthlySeries, - ]); - if (signature === lastRenderedUsage) return; - drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear }); - lastRenderedUsage = signature; - } - function drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear }) { + // 始终在 0ms 同步顶部时间段滑块与自定义日期条显隐,给予即刻交互反馈 timeFilterSwitch.setValue(slice.range); patchAttr(customRangeBar, 'hidden', slice.range !== 'custom'); if (!hasUncommittedCustomDraft) { @@ -911,6 +903,45 @@ export const ConsumptionView = defineComponent({ endPicker.setValue(draftEndMs); } + // 极少数缓存未命中时(如自定义新区间或进页瞬间抢点),跳过用旧趋势/模型跑无效半更新重绘,待几毫秒后单帧原子绘制 + if (rangeInfo.key && slice.range && rangeInfo.key !== slice.range) { + return; + } + + const preset = + slice.range !== 'custom' && cons.presets?.[slice.range] + ? cons.presets[slice.range] + : null; + const acct = cons.account || preset?.account || {}; + const dateSpan = formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs); + const now = new Date(); + const currentMonthIdx = now.getMonth(); + const monthlyYear = cons.monthlyYear || now.getFullYear(); + const locale = i18nStore.getState().locale; + const renderTuple = [ + locale, + slice.range, + slice.customStartMs, + slice.customEndMs, + slice.modelDisplayMode, + slice.showUpstreamModel, + slice.orchestratorIdMode, + dateSpan, + preset?.label || rangeInfo.label, + acct, + cons.trendSeries, + slice.modelBreakdown, + cons.sourcesBreakdown, + monthlyYear, + currentMonthIdx, + cons.monthlySeries, + ]; + if (isSameRenderTuple(lastRenderedTuple, renderTuple)) return; + drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear }); + lastRenderedTuple = renderTuple; + } + + function drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear }) { // 1. 同步用量概览矩阵与顶部 4 段比例条 patchText(dateSpanBadge, dateSpan); const totalTokens = Number(acct.totalTokens || 0); @@ -1011,14 +1042,31 @@ export const ConsumptionView = defineComponent({ }); const monthlySeries = cons.monthlySeries || []; - const allMonthMergedModels = []; - const monthsMergedModels = Array.from({ length: 12 }, (_, idx) => { - const merged = mergeAndSortBucketModels(monthlySeries[idx]?.models); - for (const m of merged) { - allMonthMergedModels.push(m); - } - return merged; - }); + const monthlyDisplayKey = `${displaySettings.modelDisplayMode}|${displaySettings.showUpstreamModel ? 1 : 0}|${displaySettings.orchestratorIdMode}`; + let monthsMergedModels; + let allMonthMergedModels; + if ( + cachedMonthlySeriesRef === monthlySeries && + cachedMonthlyDisplayKey === monthlyDisplayKey && + cachedMonthsMergedModels && + cachedAllMonthMergedModels + ) { + monthsMergedModels = cachedMonthsMergedModels; + allMonthMergedModels = cachedAllMonthMergedModels; + } else { + allMonthMergedModels = []; + monthsMergedModels = Array.from({ length: 12 }, (_, idx) => { + const merged = mergeAndSortBucketModels(monthlySeries[idx]?.models); + for (const m of merged) { + allMonthMergedModels.push(m); + } + return merged; + }); + cachedMonthlySeriesRef = monthlySeries; + cachedMonthlyDisplayKey = monthlyDisplayKey; + cachedMonthsMergedModels = monthsMergedModels; + cachedAllMonthMergedModels = allMonthMergedModels; + } const rawTrendSeries = cons.trendSeries || []; const allTrendMergedModels = []; @@ -1213,6 +1261,10 @@ export const ConsumptionView = defineComponent({ } isDirty = false; renderConsumptionData(slice); + if (!prefetchedOnCurrentVisit && Number(slice?.consumption?.revision || 0) > 0) { + prefetchedOnCurrentVisit = true; + void prefetchConsumptionPresets(); + } } ); @@ -1220,6 +1272,7 @@ export const ConsumptionView = defineComponent({ getVisibleMonitorView, (activeView) => { if (activeView !== 'consumption') { + prefetchedOnCurrentVisit = false; hideBreakdownPopover(); return; } @@ -1229,6 +1282,10 @@ export const ConsumptionView = defineComponent({ renderConsumptionData(latestSlice); } } + if (!prefetchedOnCurrentVisit && Number(latestSlice?.consumption?.revision || 0) > 0) { + prefetchedOnCurrentVisit = true; + void prefetchConsumptionPresets(); + } } ); diff --git a/sidecars/panel/test/backend.test.mjs b/sidecars/panel/test/backend.test.mjs index 150bedb..0e1ad70 100644 --- a/sidecars/panel/test/backend.test.mjs +++ b/sidecars/panel/test/backend.test.mjs @@ -2423,3 +2423,166 @@ test('v1.5 feedback settings schema: custom token combo DSL, 3-way model display rmSync(workerTemp, { recursive: true, force: true }); } }); + +test('scope=consumption and scope=consumption-presets bypass matchesConv, >30s idle, and visual settings, match full aggregation, and invalidate on weeklyLimitMode/cache rebuild', async (t) => { + let clockMs = Date.parse('2026-11-19T12:00:00.000Z'); + const mkStep = (idx, offsetMs, tok) => ({ + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + ...(offsetMs !== null + ? { + createdAt: new Date(clockMs - offsetMs).toISOString(), + completedAt: new Date(clockMs - offsetMs + 1200).toISOString(), + } + : {}), + sourceTrajectoryStepInfo: { stepIndex: idx }, + modelUsage: { + model: 'MODEL_CLAUDE_4_5_SONNET', + inputTokens: String(tok), + cacheReadTokens: '0', + outputTokens: '0', + }, + }, + plannerResponse: { response: `step-${idx}` }, + }); + + const h = backendHarness({ + clock: () => clockMs, + trajectories: { + 'conv-old': { + trajectory: { + steps: [ + mkStep(1, 20 * 86400_000, 1000), + mkStep(2, null, 250), + ], + }, + }, + 'conv-recent': { + trajectory: { + steps: [ + mkStep(1, 4 * 86400_000, 3000), + mkStep(2, 2 * 3600_000, 500), + ], + }, + }, + }, + summaries: { + 'conv-old': { + stepCount: 2, + lastModifiedTime: new Date(clockMs - 20 * 86400_000).toISOString(), + status: 'CASCADE_RUN_STATUS_IDLE', + }, + 'conv-recent': { + stepCount: 2, + lastModifiedTime: new Date(clockMs - 2 * 3600_000).toISOString(), + status: 'CASCADE_RUN_STATUS_RUNNING', + }, + }, + }); + + const initBody = JSON.parse( + ( + await h.executeTelemetryAction({ + conversationId: 'conv-recent', + range: 'today', + stepDetails: 'display', + stepRevision: '', + }) + ).body + ); + assert.ok(Number(initBody.consumption?.revision || 0) > 0); + const rpcCallsAfterInit = h.state.calls.length; + + // Advance clock by 2 minutes and toggle visual-only settings + clockMs += 120_000; + h.executeSettingsAction({ themeAccent: 'emerald', fontScale: 'lg' }); + + // Query from a DIFFERENT conversationId (simulating sidebar vs overlay mismatch) + const presetsRes = JSON.parse( + ( + await h.executeTelemetryAction({ + conversationId: 'conv-different-pane', + scope: 'consumption-presets', + }) + ).body + ); + assert.equal(presetsRes.scope, 'consumption-presets'); + assert.equal(presetsRes.activeConversation, undefined); + assert.equal(presetsRes.quotas, undefined); + assert.equal(presetsRes.ranges.today.account.totalTokens, 500); + assert.equal(presetsRes.ranges['7d'].account.totalTokens, 3500); + assert.equal(presetsRes.ranges['30d'].account.totalTokens, 4500); + assert.equal(presetsRes.ranges.all.account.totalTokens, 4750); + + const liteCustom = JSON.parse( + ( + await h.executeTelemetryAction({ + conversationId: 'conv-different-pane', + range: 'custom', + startMs: String(clockMs - 6 * 86400_000), + endMs: String(clockMs - 2 * 86400_000), + scope: 'consumption', + }) + ).body + ); + assert.equal(liteCustom.scope, 'consumption'); + assert.equal(liteCustom.activeConversation, undefined); + assert.equal(liteCustom.consumption.account.totalTokens, 3000); + assert.equal( + h.state.calls.length, + rpcCallsAfterInit, + 'scope=consumption / presets must skip LS RPCs across pane mismatch, >30s idle, and visual settings changes' + ); + + // Changing weeklyLimitMode DOES invalidate snapshot and trigger fresh full build + h.executeSettingsAction({ weeklyLimitMode: 'custom_tokens' }); + await h.executeTelemetryAction({ + conversationId: 'conv-recent', + range: '7d', + scope: 'consumption', + }); + const rpcCallsAfterWeeklyChange = h.state.calls.length; + assert.ok( + rpcCallsAfterWeeklyChange > rpcCallsAfterInit, + 'Changing weeklyLimitMode must invalidate cached fast consumption snapshot' + ); + + // Cache rebuild also invalidates snapshot and falls back to full RPC sync + h.executeRebuildCacheAction(); + await h.executeTelemetryAction({ + conversationId: 'conv-recent', + range: 'all', + scope: 'consumption', + }); + assert.ok( + h.state.calls.length > rpcCallsAfterWeeklyChange, + 'Cache rebuild must invalidate cached fast consumption snapshot' + ); + + // Verify frontend selectConsumptionTimeRange sends scope=consumption without force=1 + const { + clearConsumptionRangeCache, + selectConsumptionTimeRange, + stopAsyncTelemetryLoop, + telemetryStore, + } = await import('../src/store/telemetryStore.js'); + const prevRange = telemetryStore.getState().selectedTimeRange; + const requestedUrls = []; + t.after(() => { + stopAsyncTelemetryLoop(); + clearConsumptionRangeCache(); + telemetryStore.setState({ selectedTimeRange: prevRange }); + }); + clearConsumptionRangeCache(); + t.mock.method(globalThis, 'fetch', async (url) => { + requestedUrls.push(String(url)); + return { ok: true, json: async () => liteCustom }; + }); + await selectConsumptionTimeRange('30d'); + assert.equal(requestedUrls.length, 1); + assert.match(requestedUrls[0], /range=30d/); + assert.match(requestedUrls[0], /scope=consumption/); + assert.doesNotMatch(requestedUrls[0], /force=1/); + assert.doesNotMatch(requestedUrls[0], /fastRange=1/); +}); diff --git a/sidecars/panel/test/consumption-bars.test.mjs b/sidecars/panel/test/consumption-bars.test.mjs index 5dcac7f..4363ca2 100644 --- a/sidecars/panel/test/consumption-bars.test.mjs +++ b/sidecars/panel/test/consumption-bars.test.mjs @@ -8,7 +8,16 @@ import { mergeModelsByDisplayName, resolveDeterministicModelColor, } from '../src/core/formatters.js'; -import { isEquivalentTelemetry, telemetryStore } from '../src/store/telemetryStore.js'; +import { + clearConsumptionRangeCache, + fetchTelemetry, + isEquivalentTelemetry, + prefetchConsumptionPresets, + selectConsumptionTimeRange, + stopAsyncTelemetryLoop, + telemetryStore, +} from '../src/store/telemetryStore.js'; +import { createTrendAreaChart } from '../src/components/charts/TrendAreaChart.js'; import { uiStore } from '../src/store/uiStore.js'; import { i18nStore, setI18nLanguage } from '../src/i18n/index.js'; import { createFourSegmentBar } from '../src/components/ui/FourSegmentBar.js'; @@ -472,3 +481,165 @@ test('ConsumptionView: Top Models color dot + % bar, clutter-free Client Sources ); assert.equal(trendTipModelRows[3].querySelector('.cons-pop-model-name')?.textContent, '其他 (3)'); }); + +test('selectConsumptionTimeRange serves prefetched presets with 0 network calls, blocks stale 2s poll overwrites, and TrendAreaChart heatmap batches via DocumentFragment', async (t) => { + const prevTelState = { ...telemetryStore.getState() }; + const prevDoc = globalThis.document; + t.after(() => { + stopAsyncTelemetryLoop(); + clearConsumptionRangeCache(); + telemetryStore.setState(prevTelState, { sync: true }); + globalThis.document = prevDoc; + }); + + clearConsumptionRangeCache(); + const mkSlice = (key, label, totalTokens, rev = 7) => ({ + revision: rev, + selectedRange: { key, label, startMs: 1_700_000_000_000, endMs: 1_700_086_400_000 }, + session: { totalTokens }, + account: { totalTokens, calls: 2, inputTokens: totalTokens, cacheReadTokens: 0, outputTokens: 0, costUsd: 0.1, savedCostUsd: 0, cacheHitPct: 0 }, + trendSeries: [{ index: 0, label: '11/19', fullLabel: '11月19日', tokens: totalTokens, calls: 2, costUsd: 0.1 }], + sourcesBreakdown: [{ name: 'Antigravity App', calls: 2, totalTokens, costUsd: 0.1, models: [] }], + modelBreakdown: [{ label: 'Claude 4.5 Sonnet', shortName: 'Sonnet 4.5', calls: 2, totalTokens, costUsd: 0.1 }], + }); + + const baseTelemetry = { + account: { email: 'u@example.com', status: 'signedIn' }, + settings: { language: 'zh-CN', weeklyLimitMode: 'official' }, + cloudStatus: { catalogVersion: 'v1' }, + activeConversation: { cascadeId: 'c1', recentSteps: [], agents: [] }, + consumption: { + ...mkSlice('today', '今日', 1000, 7), + presets: { today: { label: '今日', account: { totalTokens: 1000 } } }, + monthlyYear: 2026, + monthlySeries: [], + }, + modelBreakdown: mkSlice('today', '今日', 1000, 7).modelBreakdown, + }; + telemetryStore.setState({ selectedTimeRange: 'today', telemetry: baseTelemetry }, { sync: true }); + + const requestedUrls = []; + let resolveStalePoll = null; + t.mock.method(globalThis, 'fetch', async (url) => { + const u = String(url); + requestedUrls.push(u); + if (u.includes('scope=consumption-presets')) { + return { + ok: true, + json: async () => ({ + scope: 'consumption-presets', + usageRevision: 7, + ranges: { + cycle: mkSlice('cycle', '当前周期', 4000, 7), + today: mkSlice('today', '今日', 1000, 7), + '24h': mkSlice('24h', '近 24 小时', 1500, 7), + '7d': mkSlice('7d', '近 7 天', 7000, 7), + '14d': mkSlice('14d', '近 14 天', 14000, 7), + '30d': mkSlice('30d', '近 30 天', 30000, 7), + all: mkSlice('all', '全部时间', 90000, 7), + }, + }), + }; + } + if (u.includes('scope=consumption') && u.includes('range=30d')) { + return { + ok: true, + json: async () => ({ + scope: 'consumption', + usageRevision: 8, + consumption: mkSlice('30d', '近 30 天', 31000, 8), + modelBreakdown: mkSlice('30d', '近 30 天', 31000, 8).modelBreakdown, + }), + }; + } + // Simulated slow 2s background poll started on 'today' that resolves later with rev=8 + return { + ok: true, + json: async () => + new Promise((resolve) => { + resolveStalePoll = () => + resolve({ + ...baseTelemetry, + consumption: { + ...baseTelemetry.consumption, + ...mkSlice('today', '今日', 1200, 8), + }, + modelBreakdown: mkSlice('today', '今日', 1200, 8).modelBreakdown, + }); + }), + }; + }); + + // 1. Entering ConsumptionView prefetches all 7 presets once + assert.equal(await prefetchConsumptionPresets(), true); + assert.equal(requestedUrls.length, 1); + assert.match(requestedUrls[0], /scope=consumption-presets/); + + // 2. Switching across presets hits rangeCache with ZERO network requests and atomic state swap + await selectConsumptionTimeRange('7d'); + assert.equal(requestedUrls.length, 1, 'Cached preset switch must issue 0 HTTP requests'); + assert.equal(telemetryStore.getState().selectedTimeRange, '7d'); + assert.equal(telemetryStore.getState().telemetry.consumption.selectedRange.key, '7d'); + assert.equal(telemetryStore.getState().telemetry.consumption.account.totalTokens, 7000); + + await selectConsumptionTimeRange('today'); + assert.equal(requestedUrls.length, 1); + + // 3. Stale in-flight 2s background poll ('today', rev=8) finishes AFTER user switched to '30d' locally: + // must NOT overwrite view back to 'today', and should trigger silent background revalidation for '30d' + const stalePollPromise = fetchTelemetry({ force: false }); + await Promise.resolve(); + await selectConsumptionTimeRange('30d'); + assert.equal(telemetryStore.getState().telemetry.consumption.selectedRange.key, '30d'); + assert.equal(telemetryStore.getState().telemetry.consumption.account.totalTokens, 30000); + + assert.equal(typeof resolveStalePoll, 'function'); + resolveStalePoll(); + await stalePollPromise; + // Wait microtasks for silent background scope=consumption revalidation of 30d + await new Promise((r) => setTimeout(r, 10)); + assert.equal(telemetryStore.getState().selectedTimeRange, '30d'); + assert.equal(telemetryStore.getState().telemetry.consumption.selectedRange.key, '30d'); + assert.equal(telemetryStore.getState().telemetry.consumption.account.totalTokens, 31000); + + // 4. TrendAreaChart >90d heatmap builds all cells cleanly via DocumentFragment when available + const { document } = createMockDom(); + let fragUsed = false; + document.createDocumentFragment = () => { + fragUsed = true; + const holder = document.createElement('div'); + holder.isFragment = true; + return holder; + }; + const origAppend = Object.getPrototypeOf(document.createElement('div')).appendChild; + globalThis.document = document; + const chart = createTrendAreaChart(); + const hmGrid = chart.el.querySelector('.trend-hm-grid'); + hmGrid.appendChild = function (node) { + if (node?.isFragment) { + for (const child of [...(node.children || [])]) { + origAppend.call(this, child); + } + return node; + } + return origAppend.call(this, node); + }; + const startDay = Date.parse('2026-06-01T00:00:00.000Z'); + const slots = Array.from({ length: 100 }, (_, i) => ({ + index: i, + granularity: 'day', + startMs: startDay + i * 86400_000, + label: `D${i}`, + fullLabel: `Day ${i}`, + tokens: (i % 5) * 1000, + calls: i % 5, + costUsd: 0.05, + })); + chart.update(slots); + assert.equal(fragUsed, true); + assert.equal( + chart.el.querySelectorAll('.trend-hm-cell').filter((c) => !c.classList.contains('is-pad')).length, + 100 + ); + chart.destroy(); +}); From dfba5ead7b59e8362c4e71b0e8fcd3bdaddfb12e Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Thu, 19 Nov 2026 20:37:48 +0900 Subject: [PATCH 10/14] fix(panel): add popup collision clamping and modern-ui capsule odometer --- sidecars/panel/app.js | 450 +++++++++++++++++- sidecars/panel/index.html | 4 +- .../components/layout/WindowOverlayShell.js | 5 +- .../src/components/ui/CustomDateTimePicker.js | 40 +- .../panel/src/components/ui/CustomSelect.js | 44 +- .../components/widgets/CapsuleBarWidget.js | 168 ++++++- sidecars/panel/src/core/domPatch.js | 191 ++++++++ sidecars/panel/src/styles/controls.css | 6 +- sidecars/panel/src/styles/modern-ui.css | 93 ++++ sidecars/panel/styles.css | 99 +++- sidecars/panel/test/modern-ui.test.mjs | 175 +++++++ 11 files changed, 1248 insertions(+), 27 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index f8c636c..f78d9e2 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -2872,7 +2872,7 @@ return { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normaliz })(); // --- src/core/domPatch.js --- -const { h, patchText, patchAttr, patchClasses, patchStyleVar, isEventInside, patchKeyedList } = (() => { +const { h, patchText, patchAttr, patchClasses, patchStyleVar, isEventInside, patchKeyedList, positionAnchoredPopup } = (() => { /** * @fileoverview Incremental DOM patching utilities and keyed list reconciler. * Prevents full innerHTML replacements and preserves active DOM element state. @@ -3077,7 +3077,198 @@ function patchKeyedList( } } } -return { h, patchText, patchAttr, patchClasses, patchStyleVar, isEventInside, patchKeyedList }; + +const CLIPPING_OVERFLOW_RE = /(?:hidden|clip|auto|scroll)/i; + +/** + * 解析浮层所在的可视裁剪边界(兼容 Shadow DOM 悬浮窗 `.wm-popover-panel`、 + * 侧栏 `.app-shell`、自定义滚动容器 `.custom-scroll-content` 与窗口视口)。 + * + * @param {HTMLElement} anchorRootEl + * @returns {{ left: number, top: number, right: number, bottom: number, width: number, height: number } | null} + */ +function resolvePopupBoundaryRect(anchorRootEl) { + if (!anchorRootEl) return null; + const winW = typeof window !== 'undefined' ? Number(window.innerWidth || 0) : 0; + const winH = typeof window !== 'undefined' ? Number(window.innerHeight || 0) : 0; + let boundLeft = 0; + let boundTop = 0; + let boundRight = winW > 0 ? winW : Infinity; + let boundBottom = winH > 0 ? winH : Infinity; + let hasBoundary = winW > 0 && winH > 0; + + const getStyle = + typeof window !== 'undefined' && typeof window.getComputedStyle === 'function' + ? window.getComputedStyle + : null; + + let cur = anchorRootEl.parentNode || null; + while (cur) { + if (cur.nodeType === 1 || typeof cur.getBoundingClientRect === 'function') { + const cls = cur.classList; + const isShell = Boolean( + cls?.contains?.('wm-popover-panel') || + cls?.contains?.('wm-multi-panel') || + cls?.contains?.('app-shell') || + cls?.contains?.('custom-scroll-host') || + cls?.contains?.('custom-scroll-content') + ); + let clipsX = isShell; + let clipsY = isShell; + if (!isShell && getStyle) { + try { + const cs = getStyle(cur); + if (cs) { + clipsX = CLIPPING_OVERFLOW_RE.test(cs.overflowX || cs.overflow || ''); + clipsY = CLIPPING_OVERFLOW_RE.test(cs.overflowY || cs.overflow || ''); + } + } catch { + // 忽略 Mock DOM 样式查询异常 + } + } + if (clipsX || clipsY) { + const r = cur.getBoundingClientRect?.(); + if (r && r.width > 0 && r.height > 0) { + hasBoundary = true; + if (clipsX) { + boundLeft = Math.max(boundLeft, r.left); + boundRight = Math.min(boundRight, r.right); + } + if (clipsY) { + boundTop = Math.max(boundTop, r.top); + boundBottom = Math.min(boundBottom, r.bottom); + } + } + } + } + // 到达 ShadowRoot 或文档顶层后停止,避免误受宿主页面外层容器干扰 + if (!cur.parentNode) break; + cur = cur.parentNode; + } + + if (!hasBoundary || !Number.isFinite(boundRight) || !Number.isFinite(boundBottom)) { + return null; + } + const width = Math.max(0, boundRight - boundLeft); + const height = Math.max(0, boundBottom - boundTop); + if (width <= 0 || height <= 0) return null; + return { left: boundLeft, top: boundTop, right: boundRight, bottom: boundBottom, width, height }; +} + +/** + * 为锚定在触发器上的绝对定位下拉浮层执行水平/垂直碰撞检测与边界夹紧: + * - 水平方向优先左对齐,右侧溢出时切右对齐,仍越界则直接夹紧在容器可视安全区内; + * - 垂直方向底部空间不足且上方更宽裕时自动向上翻转(追加 `.is-above`),并按可用空间收紧 `max-height`。 + * + * @param {HTMLElement} rootEl 定位基准容器 (`position: relative`) + * @param {HTMLElement} triggerEl 触发按钮 + * @param {HTMLElement} popupEl 下拉浮层 (`position: absolute`) + * @param {{ margin?: number, gap?: number, maxHeight?: number, minFlipSpace?: number }} [opts] + */ +function positionAnchoredPopup( + rootEl, + triggerEl, + popupEl, + { margin = 6, gap = 4, maxHeight = 220, minFlipSpace = 140 } = {} +) { + if (!rootEl || !triggerEl || !popupEl || !popupEl.style) return; + if (popupEl.hasAttribute?.('hidden')) return; + + const rootRect = rootEl.getBoundingClientRect?.(); + const triggerRect = triggerEl.getBoundingClientRect?.(); + if ( + !rootRect || + !triggerRect || + !(triggerRect.width > 0 && triggerRect.height > 0) + ) { + return; + } + + const bound = resolvePopupBoundaryRect(rootEl); + if (!bound) return; + + // 清除旧的动态夹紧值以便读取自然布局宽度 + popupEl.style.left = ''; + popupEl.style.right = ''; + popupEl.style.top = ''; + popupEl.style.bottom = ''; + popupEl.style.minWidth = ''; + popupEl.style.maxWidth = ''; + popupEl.style.maxHeight = ''; + + const availWidth = Math.max(120, Math.floor(bound.width - margin * 2)); + popupEl.style.maxWidth = `${availWidth}px`; + + const rawRect = popupEl.getBoundingClientRect?.(); + // 优先读取 offsetWidth,避免入场动画 scale(0.975) 导致测宽偏小 + const naturalW = Math.max( + Number(popupEl.offsetWidth || 0), + Math.ceil(Number(rawRect?.width || 0)) + ); + if (naturalW > availWidth) { + popupEl.style.minWidth = '0px'; + } + const popupW = Math.min(availWidth, naturalW > 0 ? naturalW : Math.max(triggerRect.width, 210)); + + const safeLeft = bound.left + margin; + const safeRight = bound.right - margin; + const rawLeft = Number(rawRect?.left); + const rawRight = Number(rawRect?.right); + const hasRawBox = Number.isFinite(rawLeft) && Number.isFinite(rawRight) && rawRight > rawLeft; + // 若入场缩放动画(如 scale(0.975))正在首帧生效,按对称补偿还原终态边界再判断是否越界 + const scalePadX = hasRawBox ? Math.max(0, (popupW - (rawRight - rawLeft)) / 2) : 0; + const naturalLeft = hasRawBox ? rawLeft - scalePadX : triggerRect.left; + const naturalRight = hasRawBox + ? Math.max(rawRight + scalePadX, naturalLeft + popupW) + : naturalLeft + popupW; + const fitsAsDefault = hasRawBox && naturalLeft >= safeLeft && naturalRight <= safeRight; + + if (!fitsAsDefault) { + let targetLeft = triggerRect.left; + if (targetLeft + popupW > safeRight) { + const rightAlignedLeft = triggerRect.right - popupW; + if (rightAlignedLeft >= safeLeft) { + targetLeft = rightAlignedLeft; + } else { + targetLeft = Math.max(safeLeft, safeRight - popupW); + } + } + if (targetLeft < safeLeft) { + targetLeft = safeLeft; + } + + const offsetLeft = Math.round(targetLeft - rootRect.left); + popupEl.style.left = `${offsetLeft}px`; + popupEl.style.right = 'auto'; + } + + const spaceBelow = Math.max(0, bound.bottom - triggerRect.bottom - gap - margin); + const spaceAbove = Math.max(0, triggerRect.top - bound.top - gap - margin); + const naturalH = Math.max( + Number(popupEl.scrollHeight || 0), + Number(popupEl.offsetHeight || 0), + Math.ceil(Number(rawRect?.height || 0)) + ); + const desiredH = maxHeight > 0 ? Math.min(maxHeight, naturalH || maxHeight) : naturalH || 240; + const shouldOpenAbove = + spaceBelow < Math.min(desiredH, minFlipSpace) && spaceAbove > spaceBelow; + + patchClasses(popupEl, { 'is-above': shouldOpenAbove }); + if (shouldOpenAbove) { + popupEl.style.top = 'auto'; + popupEl.style.bottom = `calc(100% + ${gap}px)`; + if (maxHeight > 0) { + popupEl.style.maxHeight = `${Math.max(88, Math.floor(Math.min(maxHeight, spaceAbove)))}px`; + } + } else { + popupEl.style.top = `calc(100% + ${gap}px)`; + popupEl.style.bottom = 'auto'; + if (maxHeight > 0) { + popupEl.style.maxHeight = `${Math.max(88, Math.floor(Math.min(maxHeight, spaceBelow)))}px`; + } + } +} +return { h, patchText, patchAttr, patchClasses, patchStyleVar, isEventInside, patchKeyedList, positionAnchoredPopup }; })(); // --- src/core/component.js --- @@ -6271,6 +6462,37 @@ const CustomSelect = defineComponent({ return new Set(normalizeMultiSelection(modelValue, options, allValue)); } + function positionMenu() { + if (!isOpen) return; + positionAnchoredPopup(rootEl, triggerBtn, menuEl, { + margin: 6, + gap: 4, + maxHeight: 220, + minFlipSpace: 140, + }); + } + + let boundReposition = false; + function handleViewportChange(e) { + if (!isOpen) return; + if (e?.type === 'scroll' && e.target === menuEl) return; + positionMenu(); + } + + function setRepositionListeners(active) { + if (active === boundReposition) return; + boundReposition = active; + if (typeof window !== 'undefined' && window.addEventListener) { + if (active) { + window.addEventListener('resize', handleViewportChange, { passive: true }); + window.addEventListener('scroll', handleViewportChange, true); + } else { + window.removeEventListener('resize', handleViewportChange); + window.removeEventListener('scroll', handleViewportChange, true); + } + } + } + function toggleOpen(nextOpen) { isOpen = Boolean(nextOpen); if (isOpen) { @@ -6286,6 +6508,10 @@ const CustomSelect = defineComponent({ patchAttr(triggerBtn, 'aria-expanded', isOpen ? 'true' : 'false'); patchAttr(menuEl, 'hidden', !isOpen); patchSvgIcon(chevronIcon, isOpen ? 'chevron-up' : 'chevron-down'); + setRepositionListeners(isOpen); + if (isOpen) { + positionMenu(); + } } function chooseOption(option) { @@ -6476,6 +6702,7 @@ const CustomSelect = defineComponent({ patchAttr(triggerBtn, 'title', titleText); if (isOpen) { renderMenuOptions(); + positionMenu(); } } @@ -6487,7 +6714,12 @@ const CustomSelect = defineComponent({ if (typeof document !== 'undefined' && document.addEventListener) { document.addEventListener('click', handleDocClick, true); - onCleanup(() => document.removeEventListener('click', handleDocClick, true)); + onCleanup(() => { + setRepositionListeners(false); + document.removeEventListener('click', handleDocClick, true); + }); + } else { + onCleanup(() => setRepositionListeners(false)); } syncTriggerAndMenu(); @@ -6824,15 +7056,47 @@ const CustomDateTimePicker = defineComponent({ const rootEl = h('div', { className: 'datetime-picker' }, [triggerBtn, popoverEl]); + function positionPopover() { + if (!isOpen) return; + positionAnchoredPopup(rootEl, triggerBtn, popoverEl, { + margin: 6, + gap: 4, + maxHeight: 0, + minFlipSpace: 260, + }); + } + + let boundReposition = false; + function handleViewportChange() { + if (!isOpen) return; + positionPopover(); + } + + function setRepositionListeners(active) { + if (active === boundReposition) return; + boundReposition = active; + if (typeof window !== 'undefined' && window.addEventListener) { + if (active) { + window.addEventListener('resize', handleViewportChange, { passive: true }); + window.addEventListener('scroll', handleViewportChange, true); + } else { + window.removeEventListener('resize', handleViewportChange); + window.removeEventListener('scroll', handleViewportChange, true); + } + } + } + function togglePopover(nextOpen) { isOpen = Boolean(nextOpen); patchAttr(popoverEl, 'hidden', !isOpen); patchAttr(triggerBtn, 'aria-expanded', isOpen ? 'true' : 'false'); + setRepositionListeners(isOpen); if (isOpen) { const cur = new Date(getProps().modelValue || Date.now()); viewYear = cur.getFullYear(); viewMonth = cur.getMonth(); renderCalendar(); + positionPopover(); } } @@ -6894,7 +7158,12 @@ const CustomDateTimePicker = defineComponent({ if (typeof document !== 'undefined' && document.addEventListener) { document.addEventListener('click', handleDocClick, true); - onCleanup(() => document.removeEventListener('click', handleDocClick, true)); + onCleanup(() => { + setRepositionListeners(false); + document.removeEventListener('click', handleDocClick, true); + }); + } else { + onCleanup(() => setRepositionListeners(false)); } syncDisplay(); @@ -14073,7 +14342,7 @@ return { STEP_COLUMN_KEYS, DEFAULT_STEP_COLUMN_KEYS, formatCustomTokenComboHeade })(); // --- src/components/widgets/CapsuleBarWidget.js --- -const { RING_RADIUS, RING_CIRCUMFERENCE, buildCapsuleSlotContext, resolveMultiSessionCapsuleState, createCapsuleSlotNode, syncCapsuleSlotNodes, CapsuleBarWidget } = (() => { +const { RING_RADIUS, RING_CIRCUMFERENCE, tokenizeCapsuleOdometerText, patchCapsuleOdometerText, buildCapsuleSlotContext, resolveMultiSessionCapsuleState, createCapsuleSlotNode, syncCapsuleSlotNodes, CapsuleBarWidget } = (() => { /** * @fileoverview Shared Decoupled Capsule Bar Primitives & Widget (`CapsuleBarWidget.js`). * Powers both the live host window capsule (`WindowOverlayShell.js`) and the @@ -14084,6 +14353,165 @@ const { RING_RADIUS, RING_CIRCUMFERENCE, buildCapsuleSlotContext, resolveMultiSe const RING_RADIUS = 5.2; const RING_CIRCUMFERENCE = +(2 * Math.PI * RING_RADIUS).toFixed(2); +const ODOMETER_DIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; +const capsuleOdometerState = new WeakMap(); + +/** + * 将胶囊指标文本拆分为「按数位对齐的数字滚轮 + 静态字符片段」: + * - 整数部分从右向左按位次键控(个位 `i:0`、十位 `i:1`...),小数部分从左向右键控(`f:0`...); + * - 位数增减时既有数位节点原地复用,仅发生变化的数字位执行 0.15s 老虎机垂直滚动,未变位与单位纹丝不动。 + * + * @param {string} rawText + * @returns {Array<{ key: string, kind: 'digit' | 'static', digit?: number, text?: string }>} + */ +function tokenizeCapsuleOdometerText(rawText) { + const str = String(rawText ?? ''); + if (!str) return []; + const parts = str.split(/(\d+(?:\.\d+)?)/g); + const tokens = []; + let numIdx = 0; + let staticIdx = 0; + + for (let p = 0; p < parts.length; p += 1) { + const seg = parts[p]; + if (!seg) continue; + if (/^\d+(?:\.\d+)?$/.test(seg)) { + const dotPos = seg.indexOf('.'); + const intPart = dotPos >= 0 ? seg.slice(0, dotPos) : seg; + const fracPart = dotPos >= 0 ? seg.slice(dotPos + 1) : ''; + const intLen = intPart.length; + for (let i = 0; i < intLen; i += 1) { + const place = intLen - 1 - i; + tokens.push({ + key: `n:${numIdx}:i:${place}`, + kind: 'digit', + digit: Number(intPart[i]), + }); + } + if (dotPos >= 0) { + tokens.push({ key: `n:${numIdx}:dot`, kind: 'static', text: '.' }); + for (let j = 0; j < fracPart.length; j += 1) { + tokens.push({ + key: `n:${numIdx}:f:${j}`, + kind: 'digit', + digit: Number(fracPart[j]), + }); + } + } + numIdx += 1; + } else { + tokens.push({ key: `s:${staticIdx}`, kind: 'static', text: seg }); + staticIdx += 1; + } + } + return tokens; +} + +function createOdometerDigitReel(initialDigit) { + const cells = ODOMETER_DIGITS.map((d) => h('span', { className: 'wm-od-cell', text: d })); + const trackEl = h('span', { className: 'wm-od-track' }, cells); + patchStyleVar(trackEl, '--od-val', String(initialDigit)); + const digitEl = h('span', { className: 'wm-od-digit', 'aria-hidden': 'true' }, [trackEl]); + return { el: digitEl, trackEl, kind: 'digit', digit: initialDigit }; +} + +/** + * 在实验性新 UI (`[data-modern-ui="true"]`) 下将胶囊数字渲染为 0.15s 老虎机垂直滚轮; + * 经典 UI 或无数字占位文本(如 `-- t/s`)严格退回原生纯文本 `patchText`,零多余 DOM 与动画。 + */ +function patchCapsuleOdometerText( + el, + nextValue, + { resetKey = '', modernUi = undefined } = {} +) { + if (!el) return false; + const nextStr = String(nextValue ?? ''); + const isModern = typeof modernUi === 'boolean' ? modernUi : isModernUiActiveForElement(el); + const prev = capsuleOdometerState.get(el); + + if (!isModern || !/\d/.test(nextStr)) { + if (prev?.active) { + while (el.firstChild) el.removeChild(el.firstChild); + patchAttr(el, 'data-od-active', null); + patchAttr(el, 'data-od-value', null); + patchAttr(el, 'aria-label', null); + } + const changed = patchText(el, nextStr); + capsuleOdometerState.set(el, { active: false, text: nextStr, resetKey, nodes: null }); + return changed; + } + + if (prev?.active && prev.text === nextStr && prev.resetKey === resetKey) { + return false; + } + + let nodes; + if (!prev?.active || prev.resetKey !== resetKey || !(prev.nodes instanceof Map)) { + while (el.firstChild) el.removeChild(el.firstChild); + nodes = new Map(); + } else { + nodes = prev.nodes; + } + + const tokens = tokenizeCapsuleOdometerText(nextStr); + const nextKeys = new Set(); + const orderedEls = []; + + for (let i = 0; i < tokens.length; i += 1) { + const tok = tokens[i]; + nextKeys.add(tok.key); + let rec = nodes.get(tok.key); + if (!rec || rec.kind !== tok.kind) { + if (rec?.el?.parentNode === el) { + el.removeChild(rec.el); + } + if (tok.kind === 'digit') { + rec = createOdometerDigitReel(tok.digit); + } else { + rec = { + el: h('span', { className: 'wm-od-static', 'aria-hidden': 'true', text: tok.text }), + trackEl: null, + kind: 'static', + text: tok.text, + }; + } + nodes.set(tok.key, rec); + } else if (tok.kind === 'digit') { + if (rec.digit !== tok.digit) { + patchStyleVar(rec.trackEl, '--od-val', String(tok.digit)); + rec.digit = tok.digit; + } + } else if (rec.text !== tok.text) { + patchText(rec.el, tok.text); + rec.text = tok.text; + } + orderedEls.push(rec.el); + } + + for (const [oldKey, rec] of nodes.entries()) { + if (!nextKeys.has(oldKey)) { + if (rec.el?.parentNode === el) { + el.removeChild(rec.el); + } + nodes.delete(oldKey); + } + } + + for (let i = 0; i < orderedEls.length; i += 1) { + const targetNode = orderedEls[i]; + const currentNode = el.children[i] || null; + if (currentNode !== targetNode) { + el.insertBefore(targetNode, currentNode); + } + } + + patchAttr(el, 'data-od-active', '1'); + patchAttr(el, 'data-od-value', nextStr); + patchAttr(el, 'aria-label', nextStr); + capsuleOdometerState.set(el, { active: true, text: nextStr, resetKey, nodes }); + return true; +} + /** * Compute shared context ring + 1..5 capsule slot metric payload from telemetry & scoped conversation. */ @@ -14289,7 +14717,7 @@ function syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx) { patchAttr(slot.el, 'class', fullSegClass); const fullTextClass = `${pres.textClass}${toneCls ? ` ${toneCls}` : ''}`; patchAttr(slot.textSpan, 'class', fullTextClass); - patchText(slot.textSpan, pres.text); + patchCapsuleOdometerText(slot.textSpan, pres.text, { resetKey: pres.metric }); if (pres.showRing) { slot.ringFill.setAttribute('stroke-dashoffset', String(pres.dashOffset)); @@ -14435,7 +14863,7 @@ const CapsuleBarWidget = defineComponent({ if (!data) { patchClasses(multiBtn, { 'is-running': false, 'is-waiting': false }); - patchText(multiLabel, t('capsule.multiZero')); + patchCapsuleOdometerText(multiLabel, t('capsule.multiZero'), { resetKey: 'multi' }); syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, { hasTelemetry: false }); return; } @@ -14456,7 +14884,7 @@ const CapsuleBarWidget = defineComponent({ 'is-running': runningCount > 0 && !hasWaiting, 'is-waiting': runningCount > 0 && hasWaiting, }); - patchText(multiLabel, multiBtnText); + patchCapsuleOdometerText(multiLabel, multiBtnText, { resetKey: 'multi' }); patchClasses(capsuleBtn, { 'is-running': slotCtx.isRunning }); syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx); @@ -14475,7 +14903,7 @@ const CapsuleBarWidget = defineComponent({ }; }, }); -return { RING_RADIUS, RING_CIRCUMFERENCE, buildCapsuleSlotContext, resolveMultiSessionCapsuleState, createCapsuleSlotNode, syncCapsuleSlotNodes, CapsuleBarWidget }; +return { RING_RADIUS, RING_CIRCUMFERENCE, tokenizeCapsuleOdometerText, patchCapsuleOdometerText, buildCapsuleSlotContext, resolveMultiSessionCapsuleState, createCapsuleSlotNode, syncCapsuleSlotNodes, CapsuleBarWidget }; })(); // --- src/components/widgets/StepTableWidget.js --- @@ -25414,7 +25842,7 @@ function mountWindowOverlay() { if (!telemetry) { patchClasses(multiBtn, { 'is-running': false, 'is-waiting': false }); - patchText(multiLabel, t('capsule.multiZero')); + patchCapsuleOdometerText(multiLabel, t('capsule.multiZero'), { resetKey: 'multi' }); patchText(multiRunningMetaEl, t('multi.loading')); multiRunningWidget.refs.stopLiveTicker(); @@ -25454,7 +25882,7 @@ function mountWindowOverlay() { 'is-running': runningCount > 0 && !hasWaiting, 'is-waiting': runningCount > 0 && hasWaiting, }); - patchText(multiLabel, multiBtnText); + patchCapsuleOdometerText(multiLabel, multiBtnText, { resetKey: 'multi' }); renderMultiRunningPanel( rawRunningList, diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 19e3f87..ff0ac01 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/layout/WindowOverlayShell.js b/sidecars/panel/src/components/layout/WindowOverlayShell.js index 2bcdc64..9758f3f 100644 --- a/sidecars/panel/src/components/layout/WindowOverlayShell.js +++ b/sidecars/panel/src/components/layout/WindowOverlayShell.js @@ -34,6 +34,7 @@ import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js'; import { buildCapsuleSlotContext, createCapsuleSlotNode, + patchCapsuleOdometerText, resolveMultiSessionCapsuleState, syncCapsuleSlotNodes, } from '../widgets/CapsuleBarWidget.js'; @@ -2383,7 +2384,7 @@ export function mountWindowOverlay() { if (!telemetry) { patchClasses(multiBtn, { 'is-running': false, 'is-waiting': false }); - patchText(multiLabel, t('capsule.multiZero')); + patchCapsuleOdometerText(multiLabel, t('capsule.multiZero'), { resetKey: 'multi' }); patchText(multiRunningMetaEl, t('multi.loading')); multiRunningWidget.refs.stopLiveTicker(); @@ -2423,7 +2424,7 @@ export function mountWindowOverlay() { 'is-running': runningCount > 0 && !hasWaiting, 'is-waiting': runningCount > 0 && hasWaiting, }); - patchText(multiLabel, multiBtnText); + patchCapsuleOdometerText(multiLabel, multiBtnText, { resetKey: 'multi' }); renderMultiRunningPanel( rawRunningList, diff --git a/sidecars/panel/src/components/ui/CustomDateTimePicker.js b/sidecars/panel/src/components/ui/CustomDateTimePicker.js index c95dfba..e0d9681 100644 --- a/sidecars/panel/src/components/ui/CustomDateTimePicker.js +++ b/sidecars/panel/src/components/ui/CustomDateTimePicker.js @@ -11,6 +11,7 @@ import { patchClasses, patchKeyedList, patchText, + positionAnchoredPopup, } from '../../core/domPatch.js'; import { formatCompactDateTime } from '../../core/formatters.js'; import { createSvgIcon } from '../../icons/SvgIcon.js'; @@ -195,15 +196,47 @@ export const CustomDateTimePicker = defineComponent({ const rootEl = h('div', { className: 'datetime-picker' }, [triggerBtn, popoverEl]); + function positionPopover() { + if (!isOpen) return; + positionAnchoredPopup(rootEl, triggerBtn, popoverEl, { + margin: 6, + gap: 4, + maxHeight: 0, + minFlipSpace: 260, + }); + } + + let boundReposition = false; + function handleViewportChange() { + if (!isOpen) return; + positionPopover(); + } + + function setRepositionListeners(active) { + if (active === boundReposition) return; + boundReposition = active; + if (typeof window !== 'undefined' && window.addEventListener) { + if (active) { + window.addEventListener('resize', handleViewportChange, { passive: true }); + window.addEventListener('scroll', handleViewportChange, true); + } else { + window.removeEventListener('resize', handleViewportChange); + window.removeEventListener('scroll', handleViewportChange, true); + } + } + } + function togglePopover(nextOpen) { isOpen = Boolean(nextOpen); patchAttr(popoverEl, 'hidden', !isOpen); patchAttr(triggerBtn, 'aria-expanded', isOpen ? 'true' : 'false'); + setRepositionListeners(isOpen); if (isOpen) { const cur = new Date(getProps().modelValue || Date.now()); viewYear = cur.getFullYear(); viewMonth = cur.getMonth(); renderCalendar(); + positionPopover(); } } @@ -265,7 +298,12 @@ export const CustomDateTimePicker = defineComponent({ if (typeof document !== 'undefined' && document.addEventListener) { document.addEventListener('click', handleDocClick, true); - onCleanup(() => document.removeEventListener('click', handleDocClick, true)); + onCleanup(() => { + setRepositionListeners(false); + document.removeEventListener('click', handleDocClick, true); + }); + } else { + onCleanup(() => setRepositionListeners(false)); } syncDisplay(); diff --git a/sidecars/panel/src/components/ui/CustomSelect.js b/sidecars/panel/src/components/ui/CustomSelect.js index 656418a..377e588 100644 --- a/sidecars/panel/src/components/ui/CustomSelect.js +++ b/sidecars/panel/src/components/ui/CustomSelect.js @@ -12,6 +12,7 @@ import { patchClasses, patchKeyedList, patchText, + positionAnchoredPopup, } from '../../core/domPatch.js'; import { isEnglishLocale, t } from '../../i18n/index.js'; import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js'; @@ -102,6 +103,37 @@ export const CustomSelect = defineComponent({ return new Set(normalizeMultiSelection(modelValue, options, allValue)); } + function positionMenu() { + if (!isOpen) return; + positionAnchoredPopup(rootEl, triggerBtn, menuEl, { + margin: 6, + gap: 4, + maxHeight: 220, + minFlipSpace: 140, + }); + } + + let boundReposition = false; + function handleViewportChange(e) { + if (!isOpen) return; + if (e?.type === 'scroll' && e.target === menuEl) return; + positionMenu(); + } + + function setRepositionListeners(active) { + if (active === boundReposition) return; + boundReposition = active; + if (typeof window !== 'undefined' && window.addEventListener) { + if (active) { + window.addEventListener('resize', handleViewportChange, { passive: true }); + window.addEventListener('scroll', handleViewportChange, true); + } else { + window.removeEventListener('resize', handleViewportChange); + window.removeEventListener('scroll', handleViewportChange, true); + } + } + } + function toggleOpen(nextOpen) { isOpen = Boolean(nextOpen); if (isOpen) { @@ -117,6 +149,10 @@ export const CustomSelect = defineComponent({ patchAttr(triggerBtn, 'aria-expanded', isOpen ? 'true' : 'false'); patchAttr(menuEl, 'hidden', !isOpen); patchSvgIcon(chevronIcon, isOpen ? 'chevron-up' : 'chevron-down'); + setRepositionListeners(isOpen); + if (isOpen) { + positionMenu(); + } } function chooseOption(option) { @@ -307,6 +343,7 @@ export const CustomSelect = defineComponent({ patchAttr(triggerBtn, 'title', titleText); if (isOpen) { renderMenuOptions(); + positionMenu(); } } @@ -318,7 +355,12 @@ export const CustomSelect = defineComponent({ if (typeof document !== 'undefined' && document.addEventListener) { document.addEventListener('click', handleDocClick, true); - onCleanup(() => document.removeEventListener('click', handleDocClick, true)); + onCleanup(() => { + setRepositionListeners(false); + document.removeEventListener('click', handleDocClick, true); + }); + } else { + onCleanup(() => setRepositionListeners(false)); } syncTriggerAndMenu(); diff --git a/sidecars/panel/src/components/widgets/CapsuleBarWidget.js b/sidecars/panel/src/components/widgets/CapsuleBarWidget.js index 0c60054..fe78488 100644 --- a/sidecars/panel/src/components/widgets/CapsuleBarWidget.js +++ b/sidecars/panel/src/components/widgets/CapsuleBarWidget.js @@ -4,8 +4,9 @@ * real-UI structure preview (`SettingsStructureTab.js`), ensuring 100% DOM/CSS parity. */ +import { isModernUiActiveForElement } from '../../core/appearance.js'; import { defineComponent } from '../../core/component.js'; -import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js'; +import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js'; import { t } from '../../i18n/index.js'; import { createSvgIcon, SVG_NS } from '../../icons/SvgIcon.js'; import { resolveCapsuleMetricPresentation } from '../../registries/metricRegistry.js'; @@ -19,6 +20,165 @@ import { buildFallbackRunningConversations } from './LiveActivityWidget.js'; export const RING_RADIUS = 5.2; export const RING_CIRCUMFERENCE = +(2 * Math.PI * RING_RADIUS).toFixed(2); +const ODOMETER_DIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; +const capsuleOdometerState = new WeakMap(); + +/** + * 将胶囊指标文本拆分为「按数位对齐的数字滚轮 + 静态字符片段」: + * - 整数部分从右向左按位次键控(个位 `i:0`、十位 `i:1`...),小数部分从左向右键控(`f:0`...); + * - 位数增减时既有数位节点原地复用,仅发生变化的数字位执行 0.15s 老虎机垂直滚动,未变位与单位纹丝不动。 + * + * @param {string} rawText + * @returns {Array<{ key: string, kind: 'digit' | 'static', digit?: number, text?: string }>} + */ +export function tokenizeCapsuleOdometerText(rawText) { + const str = String(rawText ?? ''); + if (!str) return []; + const parts = str.split(/(\d+(?:\.\d+)?)/g); + const tokens = []; + let numIdx = 0; + let staticIdx = 0; + + for (let p = 0; p < parts.length; p += 1) { + const seg = parts[p]; + if (!seg) continue; + if (/^\d+(?:\.\d+)?$/.test(seg)) { + const dotPos = seg.indexOf('.'); + const intPart = dotPos >= 0 ? seg.slice(0, dotPos) : seg; + const fracPart = dotPos >= 0 ? seg.slice(dotPos + 1) : ''; + const intLen = intPart.length; + for (let i = 0; i < intLen; i += 1) { + const place = intLen - 1 - i; + tokens.push({ + key: `n:${numIdx}:i:${place}`, + kind: 'digit', + digit: Number(intPart[i]), + }); + } + if (dotPos >= 0) { + tokens.push({ key: `n:${numIdx}:dot`, kind: 'static', text: '.' }); + for (let j = 0; j < fracPart.length; j += 1) { + tokens.push({ + key: `n:${numIdx}:f:${j}`, + kind: 'digit', + digit: Number(fracPart[j]), + }); + } + } + numIdx += 1; + } else { + tokens.push({ key: `s:${staticIdx}`, kind: 'static', text: seg }); + staticIdx += 1; + } + } + return tokens; +} + +function createOdometerDigitReel(initialDigit) { + const cells = ODOMETER_DIGITS.map((d) => h('span', { className: 'wm-od-cell', text: d })); + const trackEl = h('span', { className: 'wm-od-track' }, cells); + patchStyleVar(trackEl, '--od-val', String(initialDigit)); + const digitEl = h('span', { className: 'wm-od-digit', 'aria-hidden': 'true' }, [trackEl]); + return { el: digitEl, trackEl, kind: 'digit', digit: initialDigit }; +} + +/** + * 在实验性新 UI (`[data-modern-ui="true"]`) 下将胶囊数字渲染为 0.15s 老虎机垂直滚轮; + * 经典 UI 或无数字占位文本(如 `-- t/s`)严格退回原生纯文本 `patchText`,零多余 DOM 与动画。 + */ +export function patchCapsuleOdometerText( + el, + nextValue, + { resetKey = '', modernUi = undefined } = {} +) { + if (!el) return false; + const nextStr = String(nextValue ?? ''); + const isModern = typeof modernUi === 'boolean' ? modernUi : isModernUiActiveForElement(el); + const prev = capsuleOdometerState.get(el); + + if (!isModern || !/\d/.test(nextStr)) { + if (prev?.active) { + while (el.firstChild) el.removeChild(el.firstChild); + patchAttr(el, 'data-od-active', null); + patchAttr(el, 'data-od-value', null); + patchAttr(el, 'aria-label', null); + } + const changed = patchText(el, nextStr); + capsuleOdometerState.set(el, { active: false, text: nextStr, resetKey, nodes: null }); + return changed; + } + + if (prev?.active && prev.text === nextStr && prev.resetKey === resetKey) { + return false; + } + + let nodes; + if (!prev?.active || prev.resetKey !== resetKey || !(prev.nodes instanceof Map)) { + while (el.firstChild) el.removeChild(el.firstChild); + nodes = new Map(); + } else { + nodes = prev.nodes; + } + + const tokens = tokenizeCapsuleOdometerText(nextStr); + const nextKeys = new Set(); + const orderedEls = []; + + for (let i = 0; i < tokens.length; i += 1) { + const tok = tokens[i]; + nextKeys.add(tok.key); + let rec = nodes.get(tok.key); + if (!rec || rec.kind !== tok.kind) { + if (rec?.el?.parentNode === el) { + el.removeChild(rec.el); + } + if (tok.kind === 'digit') { + rec = createOdometerDigitReel(tok.digit); + } else { + rec = { + el: h('span', { className: 'wm-od-static', 'aria-hidden': 'true', text: tok.text }), + trackEl: null, + kind: 'static', + text: tok.text, + }; + } + nodes.set(tok.key, rec); + } else if (tok.kind === 'digit') { + if (rec.digit !== tok.digit) { + patchStyleVar(rec.trackEl, '--od-val', String(tok.digit)); + rec.digit = tok.digit; + } + } else if (rec.text !== tok.text) { + patchText(rec.el, tok.text); + rec.text = tok.text; + } + orderedEls.push(rec.el); + } + + for (const [oldKey, rec] of nodes.entries()) { + if (!nextKeys.has(oldKey)) { + if (rec.el?.parentNode === el) { + el.removeChild(rec.el); + } + nodes.delete(oldKey); + } + } + + for (let i = 0; i < orderedEls.length; i += 1) { + const targetNode = orderedEls[i]; + const currentNode = el.children[i] || null; + if (currentNode !== targetNode) { + el.insertBefore(targetNode, currentNode); + } + } + + patchAttr(el, 'data-od-active', '1'); + patchAttr(el, 'data-od-value', nextStr); + patchAttr(el, 'aria-label', nextStr); + capsuleOdometerState.set(el, { active: true, text: nextStr, resetKey, nodes }); + return true; +} + /** * Compute shared context ring + 1..5 capsule slot metric payload from telemetry & scoped conversation. */ @@ -224,7 +384,7 @@ export function syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCt patchAttr(slot.el, 'class', fullSegClass); const fullTextClass = `${pres.textClass}${toneCls ? ` ${toneCls}` : ''}`; patchAttr(slot.textSpan, 'class', fullTextClass); - patchText(slot.textSpan, pres.text); + patchCapsuleOdometerText(slot.textSpan, pres.text, { resetKey: pres.metric }); if (pres.showRing) { slot.ringFill.setAttribute('stroke-dashoffset', String(pres.dashOffset)); @@ -370,7 +530,7 @@ export const CapsuleBarWidget = defineComponent({ if (!data) { patchClasses(multiBtn, { 'is-running': false, 'is-waiting': false }); - patchText(multiLabel, t('capsule.multiZero')); + patchCapsuleOdometerText(multiLabel, t('capsule.multiZero'), { resetKey: 'multi' }); syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, { hasTelemetry: false }); return; } @@ -391,7 +551,7 @@ export const CapsuleBarWidget = defineComponent({ 'is-running': runningCount > 0 && !hasWaiting, 'is-waiting': runningCount > 0 && hasWaiting, }); - patchText(multiLabel, multiBtnText); + patchCapsuleOdometerText(multiLabel, multiBtnText, { resetKey: 'multi' }); patchClasses(capsuleBtn, { 'is-running': slotCtx.isRunning }); syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx); diff --git a/sidecars/panel/src/core/domPatch.js b/sidecars/panel/src/core/domPatch.js index d39900e..e55705d 100644 --- a/sidecars/panel/src/core/domPatch.js +++ b/sidecars/panel/src/core/domPatch.js @@ -202,3 +202,194 @@ export function patchKeyedList( } } } + +const CLIPPING_OVERFLOW_RE = /(?:hidden|clip|auto|scroll)/i; + +/** + * 解析浮层所在的可视裁剪边界(兼容 Shadow DOM 悬浮窗 `.wm-popover-panel`、 + * 侧栏 `.app-shell`、自定义滚动容器 `.custom-scroll-content` 与窗口视口)。 + * + * @param {HTMLElement} anchorRootEl + * @returns {{ left: number, top: number, right: number, bottom: number, width: number, height: number } | null} + */ +function resolvePopupBoundaryRect(anchorRootEl) { + if (!anchorRootEl) return null; + const winW = typeof window !== 'undefined' ? Number(window.innerWidth || 0) : 0; + const winH = typeof window !== 'undefined' ? Number(window.innerHeight || 0) : 0; + let boundLeft = 0; + let boundTop = 0; + let boundRight = winW > 0 ? winW : Infinity; + let boundBottom = winH > 0 ? winH : Infinity; + let hasBoundary = winW > 0 && winH > 0; + + const getStyle = + typeof window !== 'undefined' && typeof window.getComputedStyle === 'function' + ? window.getComputedStyle + : null; + + let cur = anchorRootEl.parentNode || null; + while (cur) { + if (cur.nodeType === 1 || typeof cur.getBoundingClientRect === 'function') { + const cls = cur.classList; + const isShell = Boolean( + cls?.contains?.('wm-popover-panel') || + cls?.contains?.('wm-multi-panel') || + cls?.contains?.('app-shell') || + cls?.contains?.('custom-scroll-host') || + cls?.contains?.('custom-scroll-content') + ); + let clipsX = isShell; + let clipsY = isShell; + if (!isShell && getStyle) { + try { + const cs = getStyle(cur); + if (cs) { + clipsX = CLIPPING_OVERFLOW_RE.test(cs.overflowX || cs.overflow || ''); + clipsY = CLIPPING_OVERFLOW_RE.test(cs.overflowY || cs.overflow || ''); + } + } catch { + // 忽略 Mock DOM 样式查询异常 + } + } + if (clipsX || clipsY) { + const r = cur.getBoundingClientRect?.(); + if (r && r.width > 0 && r.height > 0) { + hasBoundary = true; + if (clipsX) { + boundLeft = Math.max(boundLeft, r.left); + boundRight = Math.min(boundRight, r.right); + } + if (clipsY) { + boundTop = Math.max(boundTop, r.top); + boundBottom = Math.min(boundBottom, r.bottom); + } + } + } + } + // 到达 ShadowRoot 或文档顶层后停止,避免误受宿主页面外层容器干扰 + if (!cur.parentNode) break; + cur = cur.parentNode; + } + + if (!hasBoundary || !Number.isFinite(boundRight) || !Number.isFinite(boundBottom)) { + return null; + } + const width = Math.max(0, boundRight - boundLeft); + const height = Math.max(0, boundBottom - boundTop); + if (width <= 0 || height <= 0) return null; + return { left: boundLeft, top: boundTop, right: boundRight, bottom: boundBottom, width, height }; +} + +/** + * 为锚定在触发器上的绝对定位下拉浮层执行水平/垂直碰撞检测与边界夹紧: + * - 水平方向优先左对齐,右侧溢出时切右对齐,仍越界则直接夹紧在容器可视安全区内; + * - 垂直方向底部空间不足且上方更宽裕时自动向上翻转(追加 `.is-above`),并按可用空间收紧 `max-height`。 + * + * @param {HTMLElement} rootEl 定位基准容器 (`position: relative`) + * @param {HTMLElement} triggerEl 触发按钮 + * @param {HTMLElement} popupEl 下拉浮层 (`position: absolute`) + * @param {{ margin?: number, gap?: number, maxHeight?: number, minFlipSpace?: number }} [opts] + */ +export function positionAnchoredPopup( + rootEl, + triggerEl, + popupEl, + { margin = 6, gap = 4, maxHeight = 220, minFlipSpace = 140 } = {} +) { + if (!rootEl || !triggerEl || !popupEl || !popupEl.style) return; + if (popupEl.hasAttribute?.('hidden')) return; + + const rootRect = rootEl.getBoundingClientRect?.(); + const triggerRect = triggerEl.getBoundingClientRect?.(); + if ( + !rootRect || + !triggerRect || + !(triggerRect.width > 0 && triggerRect.height > 0) + ) { + return; + } + + const bound = resolvePopupBoundaryRect(rootEl); + if (!bound) return; + + // 清除旧的动态夹紧值以便读取自然布局宽度 + popupEl.style.left = ''; + popupEl.style.right = ''; + popupEl.style.top = ''; + popupEl.style.bottom = ''; + popupEl.style.minWidth = ''; + popupEl.style.maxWidth = ''; + popupEl.style.maxHeight = ''; + + const availWidth = Math.max(120, Math.floor(bound.width - margin * 2)); + popupEl.style.maxWidth = `${availWidth}px`; + + const rawRect = popupEl.getBoundingClientRect?.(); + // 优先读取 offsetWidth,避免入场动画 scale(0.975) 导致测宽偏小 + const naturalW = Math.max( + Number(popupEl.offsetWidth || 0), + Math.ceil(Number(rawRect?.width || 0)) + ); + if (naturalW > availWidth) { + popupEl.style.minWidth = '0px'; + } + const popupW = Math.min(availWidth, naturalW > 0 ? naturalW : Math.max(triggerRect.width, 210)); + + const safeLeft = bound.left + margin; + const safeRight = bound.right - margin; + const rawLeft = Number(rawRect?.left); + const rawRight = Number(rawRect?.right); + const hasRawBox = Number.isFinite(rawLeft) && Number.isFinite(rawRight) && rawRight > rawLeft; + // 若入场缩放动画(如 scale(0.975))正在首帧生效,按对称补偿还原终态边界再判断是否越界 + const scalePadX = hasRawBox ? Math.max(0, (popupW - (rawRight - rawLeft)) / 2) : 0; + const naturalLeft = hasRawBox ? rawLeft - scalePadX : triggerRect.left; + const naturalRight = hasRawBox + ? Math.max(rawRight + scalePadX, naturalLeft + popupW) + : naturalLeft + popupW; + const fitsAsDefault = hasRawBox && naturalLeft >= safeLeft && naturalRight <= safeRight; + + if (!fitsAsDefault) { + let targetLeft = triggerRect.left; + if (targetLeft + popupW > safeRight) { + const rightAlignedLeft = triggerRect.right - popupW; + if (rightAlignedLeft >= safeLeft) { + targetLeft = rightAlignedLeft; + } else { + targetLeft = Math.max(safeLeft, safeRight - popupW); + } + } + if (targetLeft < safeLeft) { + targetLeft = safeLeft; + } + + const offsetLeft = Math.round(targetLeft - rootRect.left); + popupEl.style.left = `${offsetLeft}px`; + popupEl.style.right = 'auto'; + } + + const spaceBelow = Math.max(0, bound.bottom - triggerRect.bottom - gap - margin); + const spaceAbove = Math.max(0, triggerRect.top - bound.top - gap - margin); + const naturalH = Math.max( + Number(popupEl.scrollHeight || 0), + Number(popupEl.offsetHeight || 0), + Math.ceil(Number(rawRect?.height || 0)) + ); + const desiredH = maxHeight > 0 ? Math.min(maxHeight, naturalH || maxHeight) : naturalH || 240; + const shouldOpenAbove = + spaceBelow < Math.min(desiredH, minFlipSpace) && spaceAbove > spaceBelow; + + patchClasses(popupEl, { 'is-above': shouldOpenAbove }); + if (shouldOpenAbove) { + popupEl.style.top = 'auto'; + popupEl.style.bottom = `calc(100% + ${gap}px)`; + if (maxHeight > 0) { + popupEl.style.maxHeight = `${Math.max(88, Math.floor(Math.min(maxHeight, spaceAbove)))}px`; + } + } else { + popupEl.style.top = `calc(100% + ${gap}px)`; + popupEl.style.bottom = 'auto'; + if (maxHeight > 0) { + popupEl.style.maxHeight = `${Math.max(88, Math.floor(Math.min(maxHeight, spaceBelow)))}px`; + } + } +} diff --git a/sidecars/panel/src/styles/controls.css b/sidecars/panel/src/styles/controls.css index c690472..4624cc7 100644 --- a/sidecars/panel/src/styles/controls.css +++ b/sidecars/panel/src/styles/controls.css @@ -31,10 +31,10 @@ .steps-inline-scope-select .select-menu, .steps-inline-model-select .select-menu { - left: auto; - right: 0; + left: 0; + right: auto; min-width: 220px; - max-width: min(320px, 82vw); + max-width: min(320px, calc(100vw - 24px)); } .session-left { diff --git a/sidecars/panel/src/styles/modern-ui.css b/sidecars/panel/src/styles/modern-ui.css index 37f173a..8bc74bb 100644 --- a/sidecars/panel/src/styles/modern-ui.css +++ b/sidecars/panel/src/styles/modern-ui.css @@ -623,6 +623,11 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { animation: anim-modern-pop-in 150ms var(--ease-modern); } +[data-modern-ui="true"] .select-menu.is-above, +[data-modern-ui="true"] .dt-popover.is-above { + animation-name: anim-modern-pop-in-up; +} + [data-modern-ui="true"] .trend-tooltip, [data-modern-ui="true"] .cons-breakdown-popover, [data-modern-ui="true"] .turn-prompt-tip { @@ -706,3 +711,91 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { background: transparent; box-shadow: none; } + +/* --- 8. 顶栏胶囊老虎机滚动数字 (0.15s) 与语义色平滑渐变 (0.1s),严格限定实验性新 UI --- */ +:host([data-modern-ui="true"]) .wm-cap-slot, +:host([data-modern-ui="true"]) .wm-cap-slot .wm-slot-text, +:host([data-modern-ui="true"]) .wm-multi-label, +[data-modern-ui="true"] .wm-cap-slot, +[data-modern-ui="true"] .wm-cap-slot .wm-slot-text, +[data-modern-ui="true"] .wm-multi-label { + transition: color 100ms ease-out; +} + +:host([data-modern-ui="true"]) .wm-ring-fill, +[data-modern-ui="true"] .wm-ring-fill { + transition: + stroke-dashoffset var(--dur-normal) var(--ease-modern), + stroke 100ms ease-out; +} + +:host([data-modern-ui="true"]) .wm-multi-dot, +[data-modern-ui="true"] .wm-multi-dot { + transition: background-color 100ms ease-out; +} + +:host([data-modern-ui="true"]) .wm-slot-text[data-od-active="1"], +:host([data-modern-ui="true"]) .wm-multi-label[data-od-active="1"], +[data-modern-ui="true"] .wm-slot-text[data-od-active="1"], +[data-modern-ui="true"] .wm-multi-label[data-od-active="1"] { + display: inline-flex; + align-items: center; + height: 18px; + line-height: 18px; +} + +:host([data-modern-ui="true"]) .wm-od-digit, +[data-modern-ui="true"] .wm-od-digit { + display: inline-block; + position: relative; + height: 18px; + line-height: 18px; + overflow: hidden; + vertical-align: top; + text-align: center; + font-variant-numeric: tabular-nums; +} + +:host([data-modern-ui="true"]) .wm-od-track, +[data-modern-ui="true"] .wm-od-track { + display: flex; + flex-direction: column; + align-items: center; + transform: translate3d(0, calc(var(--od-val, 0) * -18px), 0); + transition: transform 150ms cubic-bezier(0.22, 1, 0.36, 1); + will-change: transform; +} + +:host([data-modern-ui="true"]) .wm-od-cell, +[data-modern-ui="true"] .wm-od-cell { + display: block; + height: 18px; + line-height: 18px; + flex-shrink: 0; +} + +:host([data-modern-ui="true"]) .wm-od-static, +[data-modern-ui="true"] .wm-od-static { + display: inline-block; + height: 18px; + line-height: 18px; + vertical-align: top; + white-space: pre; +} + +@media (prefers-reduced-motion: reduce) { + :host([data-modern-ui="true"]) .wm-od-track, + [data-modern-ui="true"] .wm-od-track, + :host([data-modern-ui="true"]) .wm-cap-slot, + :host([data-modern-ui="true"]) .wm-cap-slot .wm-slot-text, + :host([data-modern-ui="true"]) .wm-multi-label, + :host([data-modern-ui="true"]) .wm-ring-fill, + :host([data-modern-ui="true"]) .wm-multi-dot, + [data-modern-ui="true"] .wm-cap-slot, + [data-modern-ui="true"] .wm-cap-slot .wm-slot-text, + [data-modern-ui="true"] .wm-multi-label, + [data-modern-ui="true"] .wm-ring-fill, + [data-modern-ui="true"] .wm-multi-dot { + transition: none !important; + } +} diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index 6b75a83..adb5780 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -406,10 +406,10 @@ html[data-standalone="true"] .app-shell { .steps-inline-scope-select .select-menu, .steps-inline-model-select .select-menu { - left: auto; - right: 0; + left: 0; + right: auto; min-width: 220px; - max-width: min(320px, 82vw); + max-width: min(320px, calc(100vw - 24px)); } .session-left { @@ -6099,6 +6099,11 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { animation: anim-modern-pop-in 150ms var(--ease-modern); } +[data-modern-ui="true"] .select-menu.is-above, +[data-modern-ui="true"] .dt-popover.is-above { + animation-name: anim-modern-pop-in-up; +} + [data-modern-ui="true"] .trend-tooltip, [data-modern-ui="true"] .cons-breakdown-popover, [data-modern-ui="true"] .turn-prompt-tip { @@ -6182,3 +6187,91 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { background: transparent; box-shadow: none; } + +/* --- 8. 顶栏胶囊老虎机滚动数字 (0.15s) 与语义色平滑渐变 (0.1s),严格限定实验性新 UI --- */ +:host([data-modern-ui="true"]) .wm-cap-slot, +:host([data-modern-ui="true"]) .wm-cap-slot .wm-slot-text, +:host([data-modern-ui="true"]) .wm-multi-label, +[data-modern-ui="true"] .wm-cap-slot, +[data-modern-ui="true"] .wm-cap-slot .wm-slot-text, +[data-modern-ui="true"] .wm-multi-label { + transition: color 100ms ease-out; +} + +:host([data-modern-ui="true"]) .wm-ring-fill, +[data-modern-ui="true"] .wm-ring-fill { + transition: + stroke-dashoffset var(--dur-normal) var(--ease-modern), + stroke 100ms ease-out; +} + +:host([data-modern-ui="true"]) .wm-multi-dot, +[data-modern-ui="true"] .wm-multi-dot { + transition: background-color 100ms ease-out; +} + +:host([data-modern-ui="true"]) .wm-slot-text[data-od-active="1"], +:host([data-modern-ui="true"]) .wm-multi-label[data-od-active="1"], +[data-modern-ui="true"] .wm-slot-text[data-od-active="1"], +[data-modern-ui="true"] .wm-multi-label[data-od-active="1"] { + display: inline-flex; + align-items: center; + height: 18px; + line-height: 18px; +} + +:host([data-modern-ui="true"]) .wm-od-digit, +[data-modern-ui="true"] .wm-od-digit { + display: inline-block; + position: relative; + height: 18px; + line-height: 18px; + overflow: hidden; + vertical-align: top; + text-align: center; + font-variant-numeric: tabular-nums; +} + +:host([data-modern-ui="true"]) .wm-od-track, +[data-modern-ui="true"] .wm-od-track { + display: flex; + flex-direction: column; + align-items: center; + transform: translate3d(0, calc(var(--od-val, 0) * -18px), 0); + transition: transform 150ms cubic-bezier(0.22, 1, 0.36, 1); + will-change: transform; +} + +:host([data-modern-ui="true"]) .wm-od-cell, +[data-modern-ui="true"] .wm-od-cell { + display: block; + height: 18px; + line-height: 18px; + flex-shrink: 0; +} + +:host([data-modern-ui="true"]) .wm-od-static, +[data-modern-ui="true"] .wm-od-static { + display: inline-block; + height: 18px; + line-height: 18px; + vertical-align: top; + white-space: pre; +} + +@media (prefers-reduced-motion: reduce) { + :host([data-modern-ui="true"]) .wm-od-track, + [data-modern-ui="true"] .wm-od-track, + :host([data-modern-ui="true"]) .wm-cap-slot, + :host([data-modern-ui="true"]) .wm-cap-slot .wm-slot-text, + :host([data-modern-ui="true"]) .wm-multi-label, + :host([data-modern-ui="true"]) .wm-ring-fill, + :host([data-modern-ui="true"]) .wm-multi-dot, + [data-modern-ui="true"] .wm-cap-slot, + [data-modern-ui="true"] .wm-cap-slot .wm-slot-text, + [data-modern-ui="true"] .wm-multi-label, + [data-modern-ui="true"] .wm-ring-fill, + [data-modern-ui="true"] .wm-multi-dot { + transition: none !important; + } +} diff --git a/sidecars/panel/test/modern-ui.test.mjs b/sidecars/panel/test/modern-ui.test.mjs index 392760b..18edb22 100644 --- a/sidecars/panel/test/modern-ui.test.mjs +++ b/sidecars/panel/test/modern-ui.test.mjs @@ -15,7 +15,12 @@ import { } from '../src/core/appearance.js'; import { createTrendAreaChart } from '../src/components/charts/TrendAreaChart.js'; import { computePublicationFit } from '../src/components/charts/SessionStepCharts.js'; +import { CustomSelect } from '../src/components/ui/CustomSelect.js'; import { SegmentedControl } from '../src/components/ui/SegmentedControl.js'; +import { + patchCapsuleOdometerText, + tokenizeCapsuleOdometerText, +} from '../src/components/widgets/CapsuleBarWidget.js'; import { ContextWindowWidget } from '../src/components/widgets/ContextWindowWidget.js'; import { LiveActivityWidget } from '../src/components/widgets/LiveActivityWidget.js'; import { StepTableWidget } from '../src/components/widgets/StepTableWidget.js'; @@ -988,3 +993,173 @@ test('StepTableWidget virtualizes large sessions (>80 rows) with exact turn-rail stepTable.destroy(); }); + +test('CustomSelect collision detection clamps left/right overflow and flips upward near bottom boundary', (t) => { + const prevDoc = globalThis.document; + const prevWin = globalThis.window; + const { document } = createMockDom(); + globalThis.document = document; + globalThis.window = { + innerWidth: 1200, + innerHeight: 800, + getComputedStyle: () => ({ overflow: 'visible', overflowX: 'visible', overflowY: 'visible' }), + addEventListener() {}, + removeEventListener() {}, + }; + + let selectComp = null; + t.after(() => { + selectComp?.destroy?.(); + globalThis.document = prevDoc; + globalThis.window = prevWin; + }); + + const shell = document.createElement('div'); + shell.className = 'wm-popover-panel'; + shell.getBoundingClientRect = () => ({ left: 20, top: 40, right: 560, bottom: 620, width: 540, height: 580 }); + document.body.appendChild(shell); + + selectComp = CustomSelect({ + className: 'steps-inline-scope-select', + modelValue: 'all', + options: [ + { value: 'all', label: '全部汇总', meta: '1994步' }, + { value: 'main', label: '主代理', meta: '1759步' }, + { value: 'w1', label: '蜂群 #1 · @entry-runtime', meta: '17步' }, + ], + }); + shell.appendChild(selectComp.el); + + const menuEl = selectComp.refs.menuEl; + const triggerBtn = selectComp.refs.triggerBtn; + + // 1. Trigger near left edge with a wide 260px menu whose raw layout overflows left (-50 < 26) + selectComp.el.getBoundingClientRect = () => ({ left: 90, top: 100, right: 190, bottom: 124, width: 100, height: 24 }); + triggerBtn.getBoundingClientRect = () => ({ left: 90, top: 100, right: 190, bottom: 124, width: 100, height: 24 }); + menuEl.offsetWidth = 260; + menuEl.offsetHeight = 180; + menuEl.scrollHeight = 180; + menuEl.getBoundingClientRect = () => ({ left: -50, top: 128, right: 210, bottom: 308, width: 260, height: 180 }); + + triggerBtn.dispatchEvent({ type: 'click', stopPropagation() {} }); + assert.equal(menuEl.style.left, '0px'); + assert.equal(menuEl.style.right, 'auto'); + assert.equal(menuEl.classList.contains('is-above'), false); + + // 2. Trigger near right edge (460..540) overflows right (460+260 > 554) -> right-aligns cleanly inside shell + triggerBtn.dispatchEvent({ type: 'click', stopPropagation() {} }); // close + selectComp.el.getBoundingClientRect = () => ({ left: 460, top: 100, right: 540, bottom: 124, width: 80, height: 24 }); + triggerBtn.getBoundingClientRect = () => ({ left: 460, top: 100, right: 540, bottom: 124, width: 80, height: 24 }); + menuEl.getBoundingClientRect = () => ({ left: 460, top: 128, right: 720, bottom: 308, width: 260, height: 180 }); + + triggerBtn.dispatchEvent({ type: 'click', stopPropagation() {} }); // reopen + assert.equal(menuEl.style.left, '-180px', 'Right-edge menu shifts left to align with trigger right edge (540-260=280, offset=-180)'); + assert.equal(menuEl.style.right, 'auto'); + + // 3. Trigger near bottom edge (580..604) flips upward (.is-above) + triggerBtn.dispatchEvent({ type: 'click', stopPropagation() {} }); // close + selectComp.el.getBoundingClientRect = () => ({ left: 90, top: 580, right: 190, bottom: 604, width: 100, height: 24 }); + triggerBtn.getBoundingClientRect = () => ({ left: 90, top: 580, right: 190, bottom: 604, width: 100, height: 24 }); + menuEl.getBoundingClientRect = () => ({ left: 90, top: 608, right: 350, bottom: 788, width: 260, height: 180 }); + + triggerBtn.dispatchEvent({ type: 'click', stopPropagation() {} }); // reopen + assert.equal(menuEl.classList.contains('is-above'), true); + assert.equal(menuEl.style.bottom, 'calc(100% + 4px)'); + assert.equal(menuEl.style.top, 'auto'); +}); + +test('Capsule odometer digit rolling (0.15s) and color transition (0.1s) stay strictly isolated to Modern UI', (t) => { + const prevDoc = globalThis.document; + const { document } = createMockDom(); + globalThis.document = document; + t.after(() => { + globalThis.document = prevDoc; + }); + + // Tokenizer keys integer digits right-to-left by place value and fraction digits left-to-right + const toks = tokenizeCapsuleOdometerText('37.2 t/s'); + assert.deepEqual( + toks.map((x) => `${x.key}=${x.kind === 'digit' ? x.digit : x.text}`), + ['n:0:i:1=3', 'n:0:i:0=7', 'n:0:dot=.', 'n:0:f:0=2', 's:0= t/s'] + ); + + const host = document.createElement('div'); + const slotText = document.createElement('span'); + slotText.className = 'wm-slot-text wm-speed-text'; + host.appendChild(slotText); + document.body.appendChild(host); + + // 1. Classic UI (no data-modern-ui): strictly plain text, zero odometer reels + patchCapsuleOdometerText(slotText, '37.2 t/s', { resetKey: 'tps' }); + assert.equal(slotText.textContent, '37.2 t/s'); + assert.equal(slotText.querySelectorAll('.wm-od-digit').length, 0); + assert.equal(slotText.hasAttribute('data-od-active'), false); + + // 2. Enable Modern UI: builds 3 digit reels in place and preserves reel identity across digit updates + host.setAttribute('data-modern-ui', 'true'); + patchCapsuleOdometerText(slotText, '37.2 t/s', { resetKey: 'tps' }); + assert.equal(slotText.getAttribute('data-od-active'), '1'); + assert.equal(slotText.getAttribute('data-od-value'), '37.2 t/s'); + assert.equal(slotText.getAttribute('aria-label'), '37.2 t/s'); + const reels1 = slotText.querySelectorAll('.wm-od-digit'); + assert.equal(reels1.length, 3); + const tensTrack = reels1[0].querySelector('.wm-od-track'); + const onesTrack = reels1[1].querySelector('.wm-od-track'); + const fracTrack = reels1[2].querySelector('.wm-od-track'); + assert.equal(tensTrack.style.getPropertyValue('--od-val'), '3'); + assert.equal(onesTrack.style.getPropertyValue('--od-val'), '7'); + assert.equal(fracTrack.style.getPropertyValue('--od-val'), '2'); + + // Update 37.2 -> 38.5: same DOM reel nodes reused, only changed digits update --od-val + patchCapsuleOdometerText(slotText, '38.5 t/s', { resetKey: 'tps' }); + const reels2 = slotText.querySelectorAll('.wm-od-digit'); + assert.equal(reels2[0], reels1[0]); + assert.equal(reels2[1], reels1[1]); + assert.equal(reels2[2], reels1[2]); + assert.equal(tensTrack.style.getPropertyValue('--od-val'), '3'); + assert.equal(onesTrack.style.getPropertyValue('--od-val'), '8'); + assert.equal(fracTrack.style.getPropertyValue('--od-val'), '5'); + + // Digit count change 38.5 -> 9.4 -> 12.6 preserves ones & tenths place reels cleanly + patchCapsuleOdometerText(slotText, '9.4 t/s', { resetKey: 'tps' }); + const reels3 = slotText.querySelectorAll('.wm-od-digit'); + assert.equal(reels3.length, 2); + assert.equal(reels3[0], reels1[1], 'Ones-place reel stays mounted across 2-digit -> 1-digit shrink'); + assert.equal(reels3[1], reels1[2], 'Tenths-place reel stays mounted'); + assert.equal(onesTrack.style.getPropertyValue('--od-val'), '9'); + assert.equal(fracTrack.style.getPropertyValue('--od-val'), '4'); + + patchCapsuleOdometerText(slotText, '12.6 t/s', { resetKey: 'tps' }); + const reels4 = slotText.querySelectorAll('.wm-od-digit'); + assert.equal(reels4.length, 3); + assert.equal(reels4[1], reels1[1], 'Ones-place reel stays mounted across 1-digit -> 2-digit grow'); + assert.equal(reels4[2], reels1[2], 'Tenths-place reel stays mounted'); + assert.equal(reels4[0].querySelector('.wm-od-track').style.getPropertyValue('--od-val'), '1'); + assert.equal(onesTrack.style.getPropertyValue('--od-val'), '2'); + assert.equal(fracTrack.style.getPropertyValue('--od-val'), '6'); + + // 3. Disable Modern UI: restores clean plain text with zero leftover odometer DOM + host.removeAttribute('data-modern-ui'); + patchCapsuleOdometerText(slotText, '12.6 t/s', { resetKey: 'tps' }); + assert.equal(slotText.textContent, '12.6 t/s'); + assert.equal(slotText.querySelectorAll('.wm-od-digit').length, 0); + assert.equal(slotText.hasAttribute('data-od-active'), false); + + // 4. Compiled CSS strictly scopes 150ms roll & 100ms color transition under [data-modern-ui="true"] + const builtStyles = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8'); + assert.match(builtStyles, /\.steps-inline-scope-select\s+\.select-menu[\s\S]*?left:\s*0;\s*right:\s*auto;/); + assert.match(builtStyles, /\[data-modern-ui="true"\]\s+\.select-menu\.is-above/); + assert.match( + builtStyles, + /\[data-modern-ui="true"\]\s+\.wm-od-track\s*\{[^}]*transition:\s*transform\s+150ms/ + ); + assert.match( + builtStyles, + /\[data-modern-ui="true"\]\s+\.wm-multi-label\s*\{[^}]*transition:\s*color\s+100ms/ + ); + assert.doesNotMatch( + builtStyles, + /(?:^|\n)\.wm-od-track\s*\{/, + 'Odometer roll CSS must ONLY exist under [data-modern-ui="true"]' + ); +}); From 4a4e4832095e6a683bfc30adc84cac5fb9607a8a Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Thu, 19 Nov 2026 22:28:39 +0900 Subject: [PATCH 11/14] feat(panel): add step anomaly diagnostics, >=100 tok/s integer speed formatting, and capsule alignment fix --- sidecars/panel/app.js | 821 ++++++++++++++++-- sidecars/panel/backend/api-actions.mjs | 10 +- sidecars/panel/backend/cli-sqlite-reader.mjs | 111 ++- sidecars/panel/backend/local-scanner.mjs | 44 +- sidecars/panel/backend/usage-aggregator.mjs | 42 + sidecars/panel/index.html | 4 +- .../components/charts/SessionStepCharts.js | 107 ++- .../src/components/widgets/StepTableWidget.js | 217 ++++- sidecars/panel/src/core/formatters.js | 163 ++++ sidecars/panel/src/i18n/en-US.js | 34 + sidecars/panel/src/i18n/zh-CN.js | 34 + .../src/registries/stepColumnRegistry.js | 3 +- sidecars/panel/src/store/telemetryStore.js | 9 +- sidecars/panel/src/styles/modern-ui.css | 58 +- sidecars/panel/src/styles/views-tables.css | 283 ++++++ sidecars/panel/src/views/StepsDetailView.js | 264 +++++- sidecars/panel/styles.css | 341 +++++++- sidecars/panel/test/step-anomalies.test.mjs | 782 +++++++++++++++++ sidecars/panel/test/window-bridge.test.mjs | 2 +- sidecars/panel/trajectory-metrics.mjs | 360 ++++++++ 20 files changed, 3546 insertions(+), 143 deletions(-) create mode 100644 sidecars/panel/test/step-anomalies.test.mjs diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index f78d9e2..271c274 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1077,6 +1077,8 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'fmt.pending': '待定', 'fmt.speedIncomplete': '计时不完整', 'fmt.speedCanceled': '已取消', + 'fmt.speedError': '调用报错', + 'fmt.speedInterrupted': '连接中断', 'fmt.speedCompactionTimingUnavailable': '压缩无计时', 'fmt.speedInvalidOutput': '无有效输出', 'fmt.speedInconsistent': '耗时数据异常', @@ -1339,6 +1341,38 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'steps.fitInactiveCardTitle': '点击在上方拟合图查看 {text}(按住 Ctrl/Shift 点击可多选同图对比)', 'steps.turnMediaOnly': '[图片/附件提问]', 'steps.turnMediaSuffix': '[附图]', + 'steps.anomalyTag.timeout': '超时{n}', + 'steps.anomalyTag.rate_limit': '限流{n}', + 'steps.anomalyTag.capacity': '503×{n}', + 'steps.anomalyTag.capacitySingle': '503', + 'steps.anomalyTag.disconnect': '断连{n}', + 'steps.anomalyTag.upstream': '500×{n}', + 'steps.anomalyTag.upstreamSingle': '500', + 'steps.anomalyTag.model_output': '纠偏{n}', + 'steps.anomalyTag.safety': '过滤{n}', + 'steps.anomalyTag.auth_or_model': '受限{n}', + 'steps.anomalyTag.error': '报错{n}', + 'steps.anomalyTag.mixed': '异常{n}', + 'steps.anomalyKind.timeout': '流空闲 / 连接超时', + 'steps.anomalyKind.rate_limit': '429 限流 / 配额耗尽', + 'steps.anomalyKind.capacity': '503 上游算力不足', + 'steps.anomalyKind.disconnect': '连接中断 / 断流', + 'steps.anomalyKind.upstream': '上游 5xx 内部错误', + 'steps.anomalyKind.model_output': '模型输出 / 工具参数无效', + 'steps.anomalyKind.safety': '内容安全过滤', + 'steps.anomalyKind.auth_or_model': '请求受限 / 模型不可用', + 'steps.anomalyKind.error': '调用异常', + 'steps.anomalyKind.canceled': '用户取消', + 'steps.anomalyStepTitle': '#{step} · 异常 {count} 次', + 'steps.anomalyDelayPart': '退避 {sec}s', + 'steps.anomalyTerminalTag': '中止', + 'steps.anomalyModelTitle': '{model} · 异常 {count} 次', + 'steps.anomalyModelSub': '涉及 {steps} 步', + 'steps.anomalyModelKindRow': '{kind}:{count} 次', + 'steps.anomalyModelClickHint': '点击前往「按步查看」筛选异常步', + 'steps.anomalySummaryMeta': '异常 {count} 次({steps} 步)', + 'steps.anomalyFilterLabel': '仅看异常 ({count})', + 'steps.anomalyFilterAll': '返回全部步骤', // Step Table Columns (Headers & Option Labels) 'stepCol.step.th': '步序', @@ -1748,6 +1782,8 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'fmt.pending': 'N/A', 'fmt.speedIncomplete': 'Incomplete timing', 'fmt.speedCanceled': 'Canceled', + 'fmt.speedError': 'Call error', + 'fmt.speedInterrupted': 'Interrupted', 'fmt.speedCompactionTimingUnavailable': 'Untimed compaction', 'fmt.speedInvalidOutput': 'No valid output', 'fmt.speedInconsistent': 'Invalid timing', @@ -2010,6 +2046,38 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'steps.fitInactiveCardTitle': 'Click to inspect {text} in Trend Fit (Ctrl/Shift-click to compare)', 'steps.turnMediaOnly': '[Media Attachment]', 'steps.turnMediaSuffix': '[Media]', + 'steps.anomalyTag.timeout': 'TO{n}', + 'steps.anomalyTag.rate_limit': '429×{n}', + 'steps.anomalyTag.capacity': '503×{n}', + 'steps.anomalyTag.capacitySingle': '503', + 'steps.anomalyTag.disconnect': 'Drop{n}', + 'steps.anomalyTag.upstream': '500×{n}', + 'steps.anomalyTag.upstreamSingle': '500', + 'steps.anomalyTag.model_output': 'Fix{n}', + 'steps.anomalyTag.safety': 'Safe{n}', + 'steps.anomalyTag.auth_or_model': 'Err{n}', + 'steps.anomalyTag.error': 'Err{n}', + 'steps.anomalyTag.mixed': 'Warn{n}', + 'steps.anomalyKind.timeout': 'Stream Idle / Connect Timeout', + 'steps.anomalyKind.rate_limit': '429 Rate Limit / Quota Reached', + 'steps.anomalyKind.capacity': '503 No Capacity Available', + 'steps.anomalyKind.disconnect': 'Connection Reset / Stream Interrupted', + 'steps.anomalyKind.upstream': 'Upstream 5xx Internal Error', + 'steps.anomalyKind.model_output': 'Invalid Model Output / Tool Call', + 'steps.anomalyKind.safety': 'Content Safety Filter', + 'steps.anomalyKind.auth_or_model': 'Request / Model Rejected', + 'steps.anomalyKind.error': 'Call Error', + 'steps.anomalyKind.canceled': 'Canceled by User', + 'steps.anomalyStepTitle': '#{step} · {count} Retries / Errors', + 'steps.anomalyDelayPart': 'Backoff {sec}s', + 'steps.anomalyTerminalTag': 'Stopped', + 'steps.anomalyModelTitle': '{model} · {count} Retries / Errors', + 'steps.anomalyModelSub': '{steps} steps affected', + 'steps.anomalyModelKindRow': '{kind}: {count}', + 'steps.anomalyModelClickHint': 'Click to filter anomalous steps', + 'steps.anomalySummaryMeta': '{count} retries/errors ({steps} steps)', + 'steps.anomalyFilterLabel': 'Anomalies Only ({count})', + 'steps.anomalyFilterAll': 'Show All Steps', // Step Table Columns (Headers & Option Labels) 'stepCol.step.th': 'Step', @@ -3351,7 +3419,7 @@ return { defineComponent }; })(); // --- src/core/formatters.js --- -const { formatMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap } = (() => { +const { formatMetric, formatSpeedMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap } = (() => { /** * @fileoverview Pure formatting utilities for speed metrics, token counts, * USD estimates, countdown timers, and custom datetime displays. @@ -3367,6 +3435,12 @@ function formatMetric(value, unit = '') { return Number.isFinite(value) ? `${value.toFixed(1)}${unit}` : '—'; } +function formatSpeedMetric(value, unit = ' tok/s') { + if (!Number.isFinite(value)) return '—'; + const numStr = value >= 100 ? String(Math.round(value)) : value.toFixed(1); + return `${numStr}${unit}`; +} + function formatCachePct(value) { if (value == null || !Number.isFinite(Number(value))) return '—'; const num = Math.max(0, Math.min(100, +Number(value).toFixed(1))); @@ -3440,6 +3514,8 @@ const SPEED_REASON_LABELS = { __proto__: null, incomplete_or_invalid_timing: 'fmt.speedIncomplete', canceled: 'fmt.speedCanceled', + error: 'fmt.speedError', + interrupted: 'fmt.speedInterrupted', compaction_timing_unavailable: 'fmt.speedCompactionTimingUnavailable', invalid_output_tokens: 'fmt.speedInvalidOutput', inconsistent_timing: 'fmt.speedInconsistent', @@ -3452,6 +3528,135 @@ function speedReasonText(reason) { return label ? t(label) : ''; } +const ANOMALY_KIND_ORDER = Object.freeze([ + 'rate_limit', + 'timeout', + 'capacity', + 'disconnect', + 'upstream', + 'model_output', + 'safety', + 'auth_or_model', + 'error', +]); + +function formatAnomalyKindLabel(kind) { + const k = String(kind || 'error'); + const key = `steps.anomalyKind.${k}`; + const text = t(key); + return text === key ? t('steps.anomalyKind.error') : text; +} + +function formatAnomalyTagText(primaryKind, count = 1) { + const n = Math.max(1, Math.floor(Number(count) || 1)); + const k = String(primaryKind || 'error'); + if (k === 'capacity' && n === 1) return t('steps.anomalyTag.capacitySingle'); + if (k === 'upstream' && n === 1) return t('steps.anomalyTag.upstreamSingle'); + const key = `steps.anomalyTag.${k}`; + const formatted = t(key, { n }); + return formatted === key ? t('steps.anomalyTag.error', { n }) : formatted; +} + +function resolveModelAnomalySummary(m) { + const count = Math.max(0, Number(m?.anomalyCount || 0)); + const steps = Math.max(0, Number(m?.anomalySteps || 0)); + if (count <= 0 && steps <= 0) return null; + const byKind = m?.anomalyByKind && typeof m.anomalyByKind === 'object' ? m.anomalyByKind : {}; + const entries = Object.entries(byKind) + .map(([k, v]) => [k, Math.max(0, Number(v || 0))]) + .filter(([, v]) => v > 0) + .sort((a, b) => { + if (b[1] !== a[1]) return b[1] - a[1]; + const pa = ANOMALY_KIND_ORDER.indexOf(a[0]); + const pb = ANOMALY_KIND_ORDER.indexOf(b[0]); + return (pa < 0 ? 99 : pa) - (pb < 0 ? 99 : pb); + }); + const totalCount = count || entries.reduce((sum, [, v]) => sum + v, 0) || steps; + const primaryKind = entries.length === 1 ? entries[0][0] : entries.length > 1 ? 'mixed' : 'error'; + const severity = + Number(m?.anomalyDangerCount || 0) > 0 || + entries.some(([k]) => k === 'rate_limit' || k === 'auth_or_model') + ? 'danger' + : 'warn'; + return { + count: totalCount, + steps: steps || totalCount, + totalDelaySec: Math.max(0, Number(m?.anomalyTotalDelaySec || 0)), + primaryKind, + severity, + entries, + tagText: formatAnomalyTagText(primaryKind, totalCount), + }; +} + +function formatStepAnomalyInlineSummary(anomaly) { + if (!anomaly || !(Number(anomaly.count) > 0)) return ''; + const tag = formatAnomalyTagText(anomaly.primaryKind, anomaly.count); + const label = formatAnomalyKindLabel(anomaly.primaryKind); + const delaySec = Number(anomaly.totalDelaySec || 0); + const delayPart = delaySec > 0 ? ` · ${t('steps.anomalyDelayPart', { sec: delaySec })}` : ''; + return `${tag} · ${label}${delayPart}`; +} + +function buildStepAnomalyDiagnostic(st) { + const a = st?.anomaly; + if (!a || !(Number(a.count) > 0)) return null; + const title = t('steps.anomalyStepTitle', { + step: Number(st.stepIndex ?? 0), + count: Number(a.count), + }); + const delaySec = Number(a.totalDelaySec || 0); + const sub = delaySec > 0 ? t('steps.anomalyDelayPart', { sec: delaySec }) : ''; + const events = Array.isArray(a.events) ? a.events : []; + const rows = events.map((ev, idx) => { + const label = formatAnomalyKindLabel(ev.kind); + const parts = [`#${ev.attempt || idx + 1} ${label}`]; + if (Number(ev.delaySec) > 0) { + parts.push(t('steps.anomalyDelayPart', { sec: ev.delaySec })); + } + if (ev.terminal) { + parts.push(t('steps.anomalyTerminalTag')); + } + return { + text: parts.join(' · '), + detail: ev.message || '', + danger: Boolean(ev.terminal || ev.kind === 'rate_limit' || ev.kind === 'auth_or_model'), + }; + }); + return { + title, + sub, + rows, + hint: '', + severity: a.severity === 'danger' ? 'danger' : 'warn', + }; +} + +function buildModelAnomalyDiagnostic(m) { + const sum = resolveModelAnomalySummary(m); + if (!sum) return null; + const title = t('steps.anomalyModelTitle', { + model: m?.displayText || m?.shortName || m?.label || '—', + count: sum.count, + }); + const subParts = [t('steps.anomalyModelSub', { steps: sum.steps })]; + if (sum.totalDelaySec > 0) { + subParts.push(t('steps.anomalyDelayPart', { sec: sum.totalDelaySec })); + } + const rows = sum.entries.map(([k, v]) => ({ + text: t('steps.anomalyModelKindRow', { kind: formatAnomalyKindLabel(k), count: v }), + detail: '', + danger: k === 'rate_limit' || k === 'auth_or_model', + })); + return { + title, + sub: subParts.join(' · '), + rows, + hint: t('steps.anomalyModelClickHint'), + severity: sum.severity, + }; +} + function sampleSummary(summary) { const valid = summary?.sampleCount || 0; const excluded = summary?.excludedCount || 0; @@ -3730,6 +3935,12 @@ function mergeModelsByDisplayName(models = [], settings = {}, options = {}) { ttftWeightedSum: hasTtft ? Number(m.avgTtftSec) * ttftWeight : 0, ttftWeight: hasTtft ? ttftWeight : 0, ttftSampleCount, + anomalySteps: Math.max(0, Number(m.anomalySteps || 0)), + anomalyCount: Math.max(0, Number(m.anomalyCount || 0)), + anomalyDangerCount: Math.max(0, Number(m.anomalyDangerCount || 0)), + anomalyTotalDelaySec: Math.max(0, Number(m.anomalyTotalDelaySec || 0)), + anomalyByKind: + m.anomalyByKind && typeof m.anomalyByKind === 'object' ? { ...m.anomalyByKind } : {}, }; if (m.upstreamName) acc.upstreamSet.add(m.upstreamName); byDisplay.set(key, acc); @@ -3758,6 +3969,17 @@ function mergeModelsByDisplayName(models = [], settings = {}, options = {}) { acc.costUsd += costUsd; acc.unpricedCalls += unpricedCalls; + acc.anomalySteps += Math.max(0, Number(m.anomalySteps || 0)); + acc.anomalyCount += Math.max(0, Number(m.anomalyCount || 0)); + acc.anomalyDangerCount += Math.max(0, Number(m.anomalyDangerCount || 0)); + acc.anomalyTotalDelaySec += Math.max(0, Number(m.anomalyTotalDelaySec || 0)); + if (m.anomalyByKind && typeof m.anomalyByKind === 'object') { + for (const [ak, av] of Object.entries(m.anomalyByKind)) { + const cnt = Math.max(0, Number(av || 0)); + if (cnt > 0) acc.anomalyByKind[ak] = (acc.anomalyByKind[ak] || 0) + cnt; + } + } + if (hasSpeed) { acc.speedWeightedSum += Number(m.avgTokPerSec) * speedWeight; acc.speedWeight += speedWeight; @@ -3808,6 +4030,15 @@ function mergeModelsByDisplayName(models = [], settings = {}, options = {}) { avgTokPerSec, avgTtftSec, ttftSampleCount: acc.ttftSampleCount, + ...(acc.anomalyCount > 0 + ? { + anomalySteps: acc.anomalySteps, + anomalyCount: acc.anomalyCount, + anomalyDangerCount: acc.anomalyDangerCount, + anomalyTotalDelaySec: +acc.anomalyTotalDelaySec.toFixed(1), + anomalyByKind: acc.anomalyByKind, + } + : {}), speedSummary: acc.baseItem.speedSummary ? { ...acc.baseItem.speedSummary, @@ -4176,7 +4407,7 @@ function buildDeterministicModelColorMap(models = []) { return colorMap; } -return { formatMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap }; +return { formatMetric, formatSpeedMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap }; })(); // --- src/core/httpClient.js --- @@ -5020,6 +5251,7 @@ function isEquivalentTelemetry(prev, next) { bs?.contextTokens !== as?.contextTokens || bs?.cacheHitPct !== as?.cacheHitPct || bs?.selectedSpeedReason !== as?.selectedSpeedReason || + bs?.anomalySig !== as?.anomalySig || bs?.turnIndex !== as?.turnIndex || bs?.rootTurnIndex !== as?.rootTurnIndex || bs?.isTurnStart !== as?.isTurnStart || @@ -5076,6 +5308,7 @@ function isEquivalentTelemetry(prev, next) { before.contextTokens !== after.contextTokens || before.cacheHitPct !== after.cacheHitPct || before.selectedSpeedReason !== after.selectedSpeedReason || + before.anomalySig !== after.anomalySig || before.turnIndex !== after.turnIndex || before.rootTurnIndex !== after.rootTurnIndex || before.isTurnStart !== after.isTurnStart || @@ -5128,7 +5361,9 @@ function isEquivalentTelemetry(prev, next) { a[k]?.costUsd !== b[k]?.costUsd || a[k]?.unpricedCalls !== b[k]?.unpricedCalls || a[k]?.totalTokens !== b[k]?.totalTokens || - a[k]?.calls !== b[k]?.calls + a[k]?.calls !== b[k]?.calls || + Number(a[k]?.anomalyCount || 0) !== Number(b[k]?.anomalyCount || 0) || + Number(a[k]?.anomalySteps || 0) !== Number(b[k]?.anomalySteps || 0) ) { return false; } @@ -5167,6 +5402,9 @@ function isEquivalentTelemetry(prev, next) { } // 7. 比对按模型汇总明细与数据来源汇总明细 + if (!areModelSlicesEqual(pAct?.modelBreakdown, nAct?.modelBreakdown)) { + return false; + } if (!areModelSlicesEqual(prev.modelBreakdown, next.modelBreakdown)) { return false; } @@ -9458,7 +9696,7 @@ function formatChartMetricValue(metric, val) { case 'context': return `${formatTokensPrecise(val)} tok`; case 'tps': - return `${val.toFixed(1)} tok/s`; + return formatSpeedMetric(val, ' tok/s'); case 'ttft': return `${val.toFixed(1)}s`; case 'cache': @@ -9477,7 +9715,7 @@ function formatChartMetricCompact(metric, val) { case 'context': return formatTokens(val); case 'tps': - return `${val.toFixed(1)} tok/s`; + return formatSpeedMetric(val, ' tok/s'); case 'ttft': return `${val.toFixed(1)}s`; case 'cache': @@ -9567,6 +9805,10 @@ function createSessionLineChart() { const dotsGroup = document.createElementNS(SVG_NS, 'g'); svg.appendChild(dotsGroup); + const anomalyDotsGroup = document.createElementNS(SVG_NS, 'g'); + anomalyDotsGroup.setAttribute('class', 'sstep-anomaly-dots'); + svg.appendChild(anomalyDotsGroup); + const hoverLine = document.createElementNS(SVG_NS, 'line'); hoverLine.setAttribute('class', 'trend-hover-line'); hoverLine.setAttribute('y1', '10'); @@ -9593,10 +9835,12 @@ function createSessionLineChart() { const tipMainLeft = h('strong', { className: 'trend-tip-tokens text-mono' }); const tipMainRight = h('span', { className: 'trend-tip-cost text-mono' }); const tipSub = h('div', { className: 'trend-tip-sub text-mono', hidden: true }); + const tipAnomaly = h('div', { className: 'trend-tip-anomaly text-mono', hidden: true }); const tooltipEl = h('div', { className: 'trend-tooltip', hidden: true }, [ h('div', { className: 'trend-tip-head' }, [tipHeadLeft, tipHeadRight]), h('div', { className: 'trend-tip-main' }, [tipMainLeft, tipMainRight]), tipSub, + tipAnomaly, ]); const xAxisEl = h('div', { className: 'trend-x-axis' }); @@ -9654,7 +9898,12 @@ function createSessionLineChart() { patchAttr(hoverDot, 'hidden', false); patchAttr(hoverDot, 'cx', pt.x.toFixed(1)); patchAttr(hoverDot, 'cy', pt.y.toFixed(1)); - patchStyleVar(hoverDot, '--hover-dot-color', pt.hoverColor || 'var(--ctx-cached)'); + const hoverAccent = pt.anomalySummary + ? pt.anomalySeverity === 'danger' + ? 'var(--metric-danger)' + : 'var(--metric-warn)' + : pt.hoverColor || 'var(--ctx-cached)'; + patchStyleVar(hoverDot, '--hover-dot-color', hoverAccent); patchAttr(peakPill, 'hidden', true); patchAttr(tooltipEl, 'hidden', false); @@ -9670,6 +9919,11 @@ function createSessionLineChart() { if (pt.subDetail) { patchText(tipSub, pt.subDetail); } + patchAttr(tipAnomaly, 'hidden', !pt.anomalySummary); + if (pt.anomalySummary) { + patchText(tipAnomaly, pt.anomalySummary); + patchClasses(tipAnomaly, { 'is-danger': pt.anomalySeverity === 'danger' }); + } const rawPct = (pt.x / viewW) * 100; const clampedPct = Math.max(1, Math.min(99, rawPct)); @@ -9815,6 +10069,7 @@ function createSessionLineChart() { while (multiAreaGroup.firstChild) multiAreaGroup.removeChild(multiAreaGroup.firstChild); while (multiLineGroup.firstChild) multiLineGroup.removeChild(multiLineGroup.firstChild); while (dotsGroup.firstChild) dotsGroup.removeChild(dotsGroup.firstChild); + while (anomalyDotsGroup.firstChild) anomalyDotsGroup.removeChild(anomalyDotsGroup.firstChild); while (xAxisEl.firstChild) xAxisEl.removeChild(xAxisEl.firstChild); patchAttr(modelLegendEl, 'hidden', true); patchAttr(peakPill, 'hidden', true); @@ -9943,7 +10198,7 @@ function createSessionLineChart() { } else if (metric === 'ttft') { valid = !st.isCompactionStep && Number.isFinite(st.ttftSec) && st.ttftSec >= 0; value = valid ? Number(st.ttftSec) : 0; - secondaryRight = Number.isFinite(st.tokPerSec) ? `${st.tokPerSec.toFixed(1)} tok/s` : ''; + secondaryRight = Number.isFinite(st.tokPerSec) ? formatSpeedMetric(st.tokPerSec, ' tok/s') : ''; subDetail = valid ? t('chart.step.ctxAndCache', { ctxTok: formatTokens(ctxTok), @@ -9982,6 +10237,7 @@ function createSessionLineChart() { } const dotColor = modelColorMap.get(gk) || accentColor; + const anomalySummary = formatStepAnomalyInlineSummary(st.anomaly); return { idx, st, @@ -9994,6 +10250,8 @@ function createSessionLineChart() { value, secondaryRight, subDetail, + anomalySummary, + anomalySeverity: st.anomaly?.severity || '', }; }); @@ -10029,7 +10287,10 @@ function createSessionLineChart() { const sig = `${locale}|${viewW}|${metric}|${showAgentPrefix}|${isMultiCompare ? 'multi' : 'single'}:${targetKeys.join(',')}|${colorSig}|` + points - .map((p) => `${p.stepTag}:${p.modelText}:${p.valid ? p.value.toFixed(4) : 'x'}`) + .map( + (p) => + `${p.stepTag}:${p.modelText}:${p.valid ? p.value.toFixed(4) : 'x'}:${p.st?.anomalySig || ''}` + ) .join('|'); if (sig !== lastSig) { @@ -10037,6 +10298,7 @@ function createSessionLineChart() { while (multiAreaGroup.firstChild) multiAreaGroup.removeChild(multiAreaGroup.firstChild); while (multiLineGroup.firstChild) multiLineGroup.removeChild(multiLineGroup.firstChild); while (dotsGroup.firstChild) dotsGroup.removeChild(dotsGroup.firstChild); + while (anomalyDotsGroup.firstChild) anomalyDotsGroup.removeChild(anomalyDotsGroup.firstChild); if (isMultiCompare) { patchAttr(linePath, 'd', ''); @@ -10132,6 +10394,19 @@ function createSessionLineChart() { } } + for (const pt of points) { + if (!pt.valid || !pt.anomalySummary) continue; + const aDot = document.createElementNS(SVG_NS, 'circle'); + aDot.setAttribute('cx', pt.x.toFixed(1)); + aDot.setAttribute('cy', pt.y.toFixed(1)); + aDot.setAttribute('r', '2.9'); + aDot.setAttribute( + 'class', + `sstep-anomaly-dot${pt.anomalySeverity === 'danger' ? ' is-danger' : ''}` + ); + anomalyDotsGroup.appendChild(aDot); + } + const tickIndices = computeStepTickIndices(points.length); while (xAxisEl.firstChild) xAxisEl.removeChild(xAxisEl.firstChild); tickElsByIdx = new Map(); @@ -10359,10 +10634,12 @@ function createModelFitChart() { const tipMainLeft = h('strong', { className: 'trend-tip-tokens text-mono' }); const tipMainRight = h('span', { className: 'trend-tip-cost text-mono' }); const tipSub = h('div', { className: 'trend-tip-sub text-mono', hidden: true }); + const tipAnomaly = h('div', { className: 'trend-tip-anomaly text-mono', hidden: true }); const tooltipEl = h('div', { className: 'trend-tooltip', hidden: true }, [ h('div', { className: 'trend-tip-head' }, [tipHeadLeft, tipHeadRight]), h('div', { className: 'trend-tip-main' }, [tipMainLeft, tipMainRight]), tipSub, + tipAnomaly, ]); const fitMethodLabelEl = h('span', { text: t('chart.fit.loess') }); @@ -10453,6 +10730,10 @@ function createModelFitChart() { patchAttr(hoverRawDot, 'hidden', false); patchAttr(hoverRawDot, 'cx', sp.x.toFixed(1)); patchAttr(hoverRawDot, 'cy', sp.rawY.toFixed(1)); + patchClasses(hoverRawDot, { + 'is-anomaly': Boolean(sp.anomalySummary), + 'is-danger': Boolean(sp.anomalySummary && sp.anomalySeverity === 'danger'), + }); const wasHidden = tooltipEl.hasAttribute('hidden'); patchAttr(tooltipEl, 'hidden', false); @@ -10485,6 +10766,11 @@ function createModelFitChart() { }) ); } + patchAttr(tipAnomaly, 'hidden', !sp.anomalySummary); + if (sp.anomalySummary) { + patchText(tipAnomaly, sp.anomalySummary); + patchClasses(tipAnomaly, { 'is-danger': sp.anomalySeverity === 'danger' }); + } const rawPct = (sp.x / viewW) * 100; const clampedPct = Math.max(1, Math.min(99, rawPct)); @@ -10769,6 +11055,8 @@ function createModelFitChart() { rawVal, stepTag: formatStepAxisTag(st, showAgentPrefix), modelText: disp.baseText || disp.text, + anomalySummary: formatStepAnomalyInlineSummary(st.anomaly), + anomalySeverity: st.anomaly?.severity || '', }); } } @@ -10922,7 +11210,12 @@ function createModelFitChart() { .map( (s) => `${s.key}:${s.colorVar}:` + - s.samples.map((p) => `${p.xVal}:${p.rawVal.toFixed(3)}:${p.fitVal.toFixed(3)}`).join(',') + s.samples + .map( + (p) => + `${p.xVal}:${p.rawVal.toFixed(3)}:${p.fitVal.toFixed(3)}:${p.st?.anomalySig || ''}` + ) + .join(',') ) .join('||'); @@ -10951,10 +11244,15 @@ function createModelFitChart() { typeof document.createDocumentFragment === 'function' ? document.createDocumentFragment() : scatterGroup; + const anomalyOverlayDots = []; for (const s of seriesList) { const binCounts = dedupOverdraw ? new Map() : null; for (const sp of s.samples) { + if (sp.anomalySummary) { + anomalyOverlayDots.push(sp); + continue; + } if (binCounts) { const binKey = (Math.round(sp.x * 2) << 11) ^ Math.round(sp.rawY * 2); const prevCnt = binCounts.get(binKey) || 0; @@ -11017,6 +11315,17 @@ function createModelFitChart() { multiCurveGroup.appendChild(curveEl); } } + for (const sp of anomalyOverlayDots) { + const aDot = document.createElementNS(SVG_NS, 'circle'); + aDot.setAttribute('cx', sp.x.toFixed(1)); + aDot.setAttribute('cy', sp.rawY.toFixed(1)); + aDot.setAttribute('r', '2.9'); + aDot.setAttribute( + 'class', + `sstep-scatter-dot is-anomaly${sp.anomalySeverity === 'danger' ? ' is-danger' : ''}` + ); + scatterTarget.appendChild(aDot); + } if (scatterTarget !== scatterGroup) { scatterGroup.appendChild(scatterTarget); } @@ -11133,7 +11442,11 @@ function createModelFitChart() { const sig = `single|${locale}|${viewW}|${targetKeys[0]}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` + - samples.map((s) => `${s.xVal}:${s.rawVal.toFixed(4)}:${s.fitVal.toFixed(4)}`).join('|'); + samples + .map( + (s) => `${s.xVal}:${s.rawVal.toFixed(4)}:${s.fitVal.toFixed(4)}:${s.st?.anomalySig || ''}` + ) + .join('|'); if (sig !== lastSig) { lastSig = sig; @@ -11157,7 +11470,12 @@ function createModelFitChart() { typeof document.createDocumentFragment === 'function' ? document.createDocumentFragment() : scatterGroup; + const singleAnomalyDots = []; for (const s of samples) { + if (s.anomalySummary) { + singleAnomalyDots.push(s); + continue; + } if (binCounts) { const binKey = (Math.round(s.x * 2) << 11) ^ Math.round(s.rawY * 2); const prevCnt = binCounts.get(binKey) || 0; @@ -11171,6 +11489,17 @@ function createModelFitChart() { dot.setAttribute('class', 'sstep-scatter-dot'); scatterTarget.appendChild(dot); } + for (const s of singleAnomalyDots) { + const aDot = document.createElementNS(SVG_NS, 'circle'); + aDot.setAttribute('cx', s.x.toFixed(1)); + aDot.setAttribute('cy', s.rawY.toFixed(1)); + aDot.setAttribute('r', '2.9'); + aDot.setAttribute( + 'class', + `sstep-scatter-dot is-anomaly${s.anomalySeverity === 'danger' ? ' is-danger' : ''}` + ); + scatterTarget.appendChild(aDot); + } if (scatterTarget !== scatterGroup) { scatterGroup.appendChild(scatterTarget); } @@ -14094,7 +14423,7 @@ const STEP_COLUMN_REGISTRY = Object.freeze({ return { td, refs: { wrapEl, speedMain, speedReason: null } }; }, updateCell: (refs, st, ctx) => { - patchText(refs.speedMain, formatMetric(st.tokPerSec, ' tok/s')); + patchText(refs.speedMain, formatSpeedMetric(st.tokPerSec, ' tok/s')); const hasValidSpeed = st.tokPerSec != null && Number.isFinite(Number(st.tokPerSec)) && Number(st.tokPerSec) > 0; const toneCls = @@ -15087,9 +15416,14 @@ function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) { if (needTps) { const tpsVal = Number(st.tokPerSec); - if (Number.isFinite(tpsVal) && tpsVal > maxTpsVal) { - maxTpsVal = tpsVal; - maxTpsObj = st; + if (Number.isFinite(tpsVal) && tpsVal >= 0) { + const tpsScore = + (tpsVal >= 100 ? String(Math.round(tpsVal)).length : tpsVal.toFixed(1).length) * 1e6 + + tpsVal; + if (tpsScore > maxTpsVal) { + maxTpsVal = tpsScore; + maxTpsObj = st; + } } if (st.selectedSpeedReason) { reasonCandidates.add(st.selectedSpeedReason); @@ -15304,8 +15638,31 @@ const StepTableWidget = defineComponent({ }); const hideTurnTip = () => patchAttr(turnTipEl, 'hidden', true); + const anomalyTipTitleEl = h('div', { className: 'step-anomaly-tip-title' }); + const anomalyTipSubEl = h('div', { className: 'step-anomaly-tip-sub text-mono', hidden: true }); + const anomalyTipHeadEl = h('div', { className: 'step-anomaly-tip-head' }, [ + anomalyTipTitleEl, + anomalyTipSubEl, + ]); + const anomalyTipListEl = h('div', { className: 'step-anomaly-tip-list' }); + const anomalyTipHintEl = h('div', { className: 'step-anomaly-tip-hint', hidden: true }); + const anomalyTipEl = h( + 'div', + { + className: 'step-anomaly-tip', + role: 'tooltip', + hidden: true, + }, + [anomalyTipHeadEl, anomalyTipListEl, anomalyTipHintEl] + ); + const hideAnomalyTip = () => patchAttr(anomalyTipEl, 'hidden', true); + const standaloneHostEl = standalone - ? h('div', { className: 'step-table-preview-host' }, [stepsTablePane, turnTipEl]) + ? h('div', { className: 'step-table-preview-host' }, [ + stepsTablePane, + turnTipEl, + anomalyTipEl, + ]) : null; let boundsContainerGetter = @@ -15319,40 +15676,85 @@ const StepTableWidget = defineComponent({ } } + function positionFloatingTip(tipEl, anchorEl) { + const boundsEl = boundsContainerGetter?.(); + if ( + !boundsEl || + typeof boundsEl.getBoundingClientRect !== 'function' || + typeof anchorEl?.getBoundingClientRect !== 'function' + ) { + return; + } + const panelRect = boundsEl.getBoundingClientRect(); + const anchorRect = anchorEl.getBoundingClientRect(); + if (!(panelRect.width > 0 && panelRect.height > 0)) return; + const tipH = tipEl.offsetHeight || 56; + const tipW = tipEl.offsetWidth || 220; + const placeAbove = + panelRect.bottom - anchorRect.bottom < tipH + 10 && + anchorRect.top - panelRect.top > tipH + 6; + const topPx = placeAbove + ? Math.max(4, Math.round(anchorRect.top - panelRect.top - tipH - 5)) + : Math.round(anchorRect.bottom - panelRect.top + 5); + const maxLeft = Math.max(6, Math.round(panelRect.width - tipW - 8)); + const leftPx = Math.min( + maxLeft, + Math.max(6, Math.round(anchorRect.left - panelRect.left)) + ); + tipEl.style.top = `${topPx}px`; + tipEl.style.left = `${leftPx}px`; + } + function showTurnTip(anchorCell, promptText) { const text = String(promptText || '').trim(); - const boundsEl = boundsContainerGetter?.(); if (!anchorCell || !text) { hideTurnTip(); return; } + hideAnomalyTip(); patchText(turnTipEl, text); patchAttr(turnTipEl, 'hidden', false); - if ( - boundsEl && - typeof boundsEl.getBoundingClientRect === 'function' && - typeof anchorCell.getBoundingClientRect === 'function' - ) { - const panelRect = boundsEl.getBoundingClientRect(); - const cellRect = anchorCell.getBoundingClientRect(); - if (panelRect.width > 0 && panelRect.height > 0) { - const tipH = turnTipEl.offsetHeight || 36; - const tipW = turnTipEl.offsetWidth || 180; - const placeAbove = - panelRect.bottom - cellRect.bottom < tipH + 10 && - cellRect.top - panelRect.top > tipH + 6; - const topPx = placeAbove - ? Math.max(4, Math.round(cellRect.top - panelRect.top - tipH - 4)) - : Math.round(cellRect.bottom - panelRect.top + 4); - const maxLeft = Math.max(6, Math.round(panelRect.width - tipW - 8)); - const leftPx = Math.min( - maxLeft, - Math.max(6, Math.round(cellRect.left - panelRect.left + 4)) - ); - turnTipEl.style.top = `${topPx}px`; - turnTipEl.style.left = `${leftPx}px`; - } + positionFloatingTip(turnTipEl, anchorCell); + } + + function showAnomalyTip(anchorEl, diag) { + if (!anchorEl || !diag || !diag.title) { + hideAnomalyTip(); + return; } + hideTurnTip(); + patchClasses(anomalyTipEl, { 'is-danger': diag.severity === 'danger' }); + patchText(anomalyTipTitleEl, diag.title); + patchAttr(anomalyTipSubEl, 'hidden', !diag.sub); + if (diag.sub) patchText(anomalyTipSubEl, diag.sub); + + while (anomalyTipListEl.firstChild) { + anomalyTipListEl.removeChild(anomalyTipListEl.firstChild); + } + const rows = Array.isArray(diag.rows) ? diag.rows : []; + for (const row of rows) { + const lineEl = h('div', { + className: `step-anomaly-tip-row${row.danger ? ' is-danger' : ''}`, + text: row.text, + }); + const itemChildren = [lineEl]; + if (row.detail) { + itemChildren.push( + h('div', { + className: 'step-anomaly-tip-detail text-mono', + text: row.detail, + }) + ); + } + anomalyTipListEl.appendChild(h('div', { className: 'step-anomaly-tip-item' }, itemChildren)); + } + patchAttr(anomalyTipListEl, 'hidden', rows.length === 0); + + patchAttr(anomalyTipHintEl, 'hidden', !diag.hint); + if (diag.hint) patchText(anomalyTipHintEl, diag.hint); + + patchAttr(anomalyTipEl, 'hidden', false); + positionFloatingTip(anomalyTipEl, anchorEl); } const hoverRows = new WeakMap(); @@ -15487,15 +15889,30 @@ const StepTableWidget = defineComponent({ } function moveInStepCell(event) { - if (event?.target === hoverRows.get(this).badge) hideTurnTip(); + const { badge } = hoverRows.get(this); + if (event?.target === badge) hideTurnTip(); } function moveAlongTurnRail(event) { - const { badge, prompt } = hoverRows.get(this); + const { badge, prompt, anomalyStep } = hoverRows.get(this); const rect = this.getBoundingClientRect?.(); const relX = rect ? (event?.clientX ?? 0) - rect.left : 0; - if (event?.target !== badge && relX <= 18) showTurnTip(this, prompt); - else hideTurnTip(); + if (event?.target !== badge && relX <= 18) { + showTurnTip(this, prompt); + } else { + hideTurnTip(); + if (anomalyStep) { + showAnomalyTip(this, buildStepAnomalyDiagnostic(anomalyStep)); + } + } + } + + function leaveStepCell(event) { + const entry = hoverRows.get(this); + hideTurnTip(); + if (entry?.anomalyStep && entry.tr && event?.relatedTarget && entry.tr.contains?.(event.relatedTarget)) { + showAnomalyTip(this, buildStepAnomalyDiagnostic(entry.anomalyStep)); + } } function clearCellHover(cell) { @@ -15787,7 +16204,8 @@ const StepTableWidget = defineComponent({ ? `${cellCtx.scopeSigKey}:${st.agentId || 'main'}:${st.agentBadge || ''}:${st.agentLabel || ''}` : ''; const stripeSig = isVirtualized ? (item.isStripeEven ? 'E' : 'O') : 'N'; - return `${locale}:${colOrderSig}:${stripeSig}:${badgeSig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`; + const anomalySig = st.anomalySig || ''; + return `${locale}:${colOrderSig}:${stripeSig}:${badgeSig}:${anomalySig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`; }, createRow: (item) => { if (item.isSizer) { @@ -16029,6 +16447,24 @@ const StepTableWidget = defineComponent({ refs.agentBadgeEl.onclick = null; } + const hasStepAnomaly = Boolean(st?.anomaly && Number(st.anomaly.count) > 0); + const isAnomalyDanger = Boolean(hasStepAnomaly && st.anomaly.severity === 'danger'); + const isAnomalyWarn = Boolean(hasStepAnomaly && !isAnomalyDanger); + patchClasses(tr, { + 'is-anomaly-warn': isAnomalyWarn, + 'is-anomaly-danger': isAnomalyDanger, + }); + if (hasStepAnomaly) { + const anchorEl = firstTd || tr; + tr.onmouseenter = () => { + showAnomalyTip(anchorEl, buildStepAnomalyDiagnostic(st)); + }; + tr.onmouseleave = hideAnomalyTip; + } else { + tr.onmouseenter = null; + tr.onmouseleave = null; + } + patchAttr(refs.railEl, 'hidden', !showRowRail); if (showRowRail) { const marker = isStart ? ' is-origin' : !hasUp && hasDown ? ' is-cap' : ''; @@ -16043,10 +16479,16 @@ const StepTableWidget = defineComponent({ if (refs.hoverTd !== hoverTd) clearCellHover(refs.hoverTd); refs.hoverTd = hoverTd; if (hoverTd) { - hoverRows.set(hoverTd, { badge: refs.agentBadgeEl, prompt }); - hoverTd.onmouseenter = firstColKey === 'step' ? enterStepCell : null; - hoverTd.onmousemove = firstColKey === 'step' ? moveInStepCell : moveAlongTurnRail; - hoverTd.onmouseleave = hideTurnTip; + hoverRows.set(hoverTd, { + badge: refs.agentBadgeEl, + prompt, + anomalyStep: hasStepAnomaly ? st : null, + tr, + }); + const useWholeCellTurnTip = firstColKey === 'step' && !hasStepAnomaly; + hoverTd.onmouseenter = useWholeCellTurnTip ? enterStepCell : null; + hoverTd.onmousemove = useWholeCellTurnTip ? moveInStepCell : moveAlongTurnRail; + hoverTd.onmouseleave = leaveStepCell; } if (enteringRowKeys?.has(item.rowKey)) { @@ -16068,7 +16510,14 @@ const StepTableWidget = defineComponent({ } clearRowEnterState(tr); if (!refs?.isSpacer && !refs?.isSizer && tr) { - patchClasses(tr, { 'is-stripe-even': false, 'is-step-entering': false }); + patchClasses(tr, { + 'is-stripe-even': false, + 'is-step-entering': false, + 'is-anomaly-warn': false, + 'is-anomaly-danger': false, + }); + tr.onmouseenter = null; + tr.onmouseleave = null; if (refs.agentBadgeEl) { refs.agentBadgeEl.onclick = null; } @@ -16098,6 +16547,7 @@ const StepTableWidget = defineComponent({ function onPaneScroll() { hideTurnTip(); + hideAnomalyTip(); if (!activeDataset?.isVirtualized) return; if (typeof requestAnimationFrame === 'function') { if (scrollRafId) return; @@ -16110,8 +16560,13 @@ const StepTableWidget = defineComponent({ } } + function onTbodyLeave() { + hideTurnTip(); + hideAnomalyTip(); + } + stepsTablePane.addEventListener('scroll', onPaneScroll, { passive: true }); - stepsTbody.addEventListener('mouseleave', hideTurnTip); + stepsTbody.addEventListener('mouseleave', onTbodyLeave); let paneResizeObs = null; if (typeof ResizeObserver === 'function') { @@ -16313,7 +16768,7 @@ const StepTableWidget = defineComponent({ onCleanup(() => { stepsTablePane.removeEventListener('scroll', onPaneScroll); - stepsTbody.removeEventListener('mouseleave', hideTurnTip); + stepsTbody.removeEventListener('mouseleave', onTbodyLeave); if (scrollRafId && typeof cancelAnimationFrame === 'function') { cancelAnimationFrame(scrollRafId); scrollRafId = 0; @@ -16338,10 +16793,13 @@ const StepTableWidget = defineComponent({ stepsTheadRow, stepsTbody, turnTipEl, + anomalyTipEl, syncTableHeaderColumns, renderStepTable, refreshViewport, hideTurnTip, + showAnomalyTip, + hideAnomalyTip, setBoundsElGetter, }, }; @@ -21997,6 +22455,11 @@ function mergeSelectedAgentUnits(units) { totalTokens: 0, costUsd: 0, unpricedCalls: 0, + anomalySteps: 0, + anomalyCount: 0, + anomalyDangerCount: 0, + anomalyTotalDelaySec: 0, + anomalyByKind: {}, _speedWeightedSum: 0, _speedWeight: 0, _ttftWeightedSum: 0, @@ -22036,6 +22499,16 @@ function mergeSelectedAgentUnits(units) { acc.totalTokens += totTok; acc.costUsd += costUsd; acc.unpricedCalls += unpricedCalls; + acc.anomalySteps += Math.max(0, Number(m.anomalySteps || 0)); + acc.anomalyCount += Math.max(0, Number(m.anomalyCount || 0)); + acc.anomalyDangerCount += Math.max(0, Number(m.anomalyDangerCount || 0)); + acc.anomalyTotalDelaySec += Math.max(0, Number(m.anomalyTotalDelaySec || 0)); + if (m.anomalyByKind && typeof m.anomalyByKind === 'object') { + for (const [kind, cnt] of Object.entries(m.anomalyByKind)) { + const n = Math.max(0, Number(cnt || 0)); + if (n > 0) acc.anomalyByKind[kind] = (acc.anomalyByKind[kind] || 0) + n; + } + } if (Number.isFinite(Number(m.avgTokPerSec)) && Number(m.avgTokPerSec) > 0) { const w = Math.max(1, outTok || calls || 1); @@ -22084,6 +22557,15 @@ function mergeSelectedAgentUnits(units) { avgTtftSec: acc._ttftWeight > 0 ? +(acc._ttftWeightedSum / acc._ttftWeight).toFixed(1) : null, cacheHitPct: promptTok > 0 ? +((acc.cacheReadTokens / promptTok) * 100).toFixed(1) : 0, + ...(acc.anomalyCount > 0 + ? { + anomalySteps: acc.anomalySteps, + anomalyCount: acc.anomalyCount, + anomalyDangerCount: acc.anomalyDangerCount, + anomalyTotalDelaySec: +acc.anomalyTotalDelaySec.toFixed(1), + anomalyByKind: acc.anomalyByKind, + } + : {}), }; }) .sort((a, b) => b.totalTokens - a.totalTokens || b.calls - a.calls); @@ -22117,6 +22599,8 @@ const StepsDetailView = defineComponent({ let lastSyncedUiScope = uiStore.getState().selectedAgentScope || 'all'; let selectedTableModels = ['__all__']; let selectedLineModels = ['__all__']; + let onlyAnomalies = false; + let anomalyKindFilter = ''; function applyAgentScopesSelection(nextScopes) { selectedAgentScopes = nextScopes; @@ -22191,7 +22675,10 @@ const StepsDetailView = defineComponent({ stepsTheadRow, stepsTbody, turnTipEl, + anomalyTipEl, hideTurnTip, + showAnomalyTip, + hideAnomalyTip, syncTableHeaderColumns, renderStepTable, refreshViewport: refreshStepTableViewport, @@ -22201,6 +22688,23 @@ const StepsDetailView = defineComponent({ className: 'table-scroll-host', }); + const anomalyFilterLabelEl = h('span', { className: 'steps-anomaly-filter-label text-mono' }); + const anomalyFilterClearBtn = h('button', { + type: 'button', + className: 'btn-ghost-sm steps-anomaly-filter-clear', + text: t('steps.anomalyFilterAll'), + onclick: () => { + onlyAnomalies = false; + anomalyKindFilter = ''; + if (latestSlice) renderStepsData(latestSlice); + }, + }); + const anomalyFilterBarEl = h( + 'div', + { className: 'steps-anomaly-filterbar', hidden: true }, + [anomalyFilterLabelEl, anomalyFilterClearBtn] + ); + // --- 子视图 2:总汇总分析面板 --- let selectedLineMetric = 'totalTokens'; let selectedFitMetric = 'tps'; @@ -22303,6 +22807,24 @@ const StepsDetailView = defineComponent({ className: 'cons-badge text-mono', text: t('cons.callsCount', { calls: 0 }), }); + const modelsAnomalyMetaEl = h('button', { + type: 'button', + className: 'steps-anomaly-strip-meta text-mono', + onclick: () => { + hideAnomalyTip(); + selectedTableModels = ['__all__']; + onlyAnomalies = true; + anomalyKindFilter = ''; + uiStore.setState({ stepsSubTab: 'steps' }); + }, + }); + const modelsAnomalyTagsEl = h('div', { className: 'steps-anomaly-strip-tags' }); + const modelsAnomalyStripEl = h( + 'div', + { className: 'steps-anomaly-strip', hidden: true }, + [modelsAnomalyMetaEl, modelsAnomalyTagsEl] + ); + let lastAnomalyStripSig = ''; const modelsEmptyEl = h('div', { className: 'smodel-empty text-muted', text: t('steps.modelsEmpty'), @@ -22310,6 +22832,7 @@ const StepsDetailView = defineComponent({ const modelsListEl = h('div', { className: 'smodel-list' }); const modelsSummarySection = h('div', { className: 'smodel-section' }, [ h('div', { className: 'smodel-section-head' }, [modelsSectionTitleEl, modelsSummaryMeta]), + modelsAnomalyStripEl, modelsEmptyEl, modelsListEl, ]); @@ -22319,6 +22842,8 @@ const StepsDetailView = defineComponent({ modelFitCard, modelsSummarySection, ]); + const onModelsPaneScroll = () => hideAnomalyTip(); + modelsAnalyticsPane.addEventListener('scroll', onModelsPaneScroll, { passive: true }); const modelsScroll = CustomScrollbar({ contentEl: modelsAnalyticsPane, className: 'table-scroll-host', @@ -22344,9 +22869,11 @@ const StepsDetailView = defineComponent({ subTabSwitch.el, ]), ]), + anomalyFilterBarEl, stepsScroll.el, modelsScroll.el, turnTipEl, + anomalyTipEl, ] ); stepTableWidget.refs.setBoundsElGetter(() => panelEl); @@ -22417,6 +22944,8 @@ const StepsDetailView = defineComponent({ patchText(fitTitleEl, t('steps.fitTitle')); patchText(modelsSectionTitleEl, t('steps.modelsTitle')); patchText(modelsEmptyEl, t('steps.modelsEmpty')); + patchText(anomalyFilterClearBtn, t('steps.anomalyFilterAll')); + lastAnomalyStripSig = ''; lineMetricSwitch.setProps({ modelValue: selectedLineMetric, options: getLineMetricSwitchOptions(), @@ -22450,6 +22979,8 @@ const StepsDetailView = defineComponent({ lastSyncedUiScope = uiSt.selectedAgentScope || 'all'; selectedTableModels = ['__all__']; selectedLineModels = ['__all__']; + onlyAnomalies = false; + anomalyKindFilter = ''; } fitLockedCascadeId = currentCid; fitUserPicked = false; @@ -22643,9 +23174,29 @@ const StepsDetailView = defineComponent({ const tableModelFilterSet = selectedTableModels.includes('__all__') ? null : new Set(selectedTableModels); - const tableSteps = tableModelFilterSet + const modelFilteredSteps = tableModelFilterSet ? steps.filter((st) => tableModelFilterSet.has(getStepModelGroupKey(st))) : steps; + const tableSteps = onlyAnomalies + ? modelFilteredSteps.filter((st) => { + const a = st?.anomaly; + if (!a || !(Number(a.count) > 0)) return false; + if (anomalyKindFilter) { + return Number(a.kinds?.[anomalyKindFilter] || 0) > 0; + } + return true; + }) + : modelFilteredSteps; + + const showAnomalyFilterBar = !showModels && onlyAnomalies; + patchAttr(anomalyFilterBarEl, 'hidden', !showAnomalyFilterBar); + if (showAnomalyFilterBar) { + const baseLabel = t('steps.anomalyFilterLabel', { count: tableSteps.length }); + const kindSuffix = anomalyKindFilter + ? ` · ${formatAnomalyKindLabel(anomalyKindFilter)}` + : ''; + patchText(anomalyFilterLabelEl, `${baseLabel}${kindSuffix}`); + } const stepsTabLabel = tableSteps.length !== steps.length @@ -22783,10 +23334,79 @@ const StepsDetailView = defineComponent({ // 4. 极简模型总览列表增量对账 const displayModels = mergeModelsByDisplayName(models, displaySettings, { fallback: '—' }); + const needStepAnomalyFallback = displayModels.every((m) => !(Number(m?.anomalyCount) > 0)); + let stepAnomalyByGroup = null; + if (needStepAnomalyFallback) { + for (const st of chronoSteps) { + const a = st?.anomaly; + if (!a || !(Number(a.count) > 0)) continue; + if (!stepAnomalyByGroup) stepAnomalyByGroup = new Map(); + const gk = getStepModelGroupKey(st); + let acc = stepAnomalyByGroup.get(gk); + if (!acc) { + acc = { + anomalySteps: 0, + anomalyCount: 0, + anomalyDangerCount: 0, + anomalyTotalDelaySec: 0, + anomalyByKind: {}, + }; + stepAnomalyByGroup.set(gk, acc); + } + acc.anomalySteps += 1; + acc.anomalyCount += Number(a.count) || 0; + if (a.severity === 'danger') acc.anomalyDangerCount += 1; + acc.anomalyTotalDelaySec += Number(a.totalDelaySec) || 0; + if (a.kinds && typeof a.kinds === 'object') { + for (const [k, cnt] of Object.entries(a.kinds)) { + const n = Math.max(0, Number(cnt || 0)); + if (n > 0) acc.anomalyByKind[k] = (acc.anomalyByKind[k] || 0) + n; + } + } + } + } + const resolveEffectiveAnomalyModel = (m) => { + if (Number(m?.anomalyCount) > 0 || !stepAnomalyByGroup) return m; + const gk = getStepModelGroupKey(m); + const groupKeys = + Array.isArray(m.sourceLabels) && m.sourceLabels.length > 0 + ? Array.from(new Set(m.sourceLabels.map((lbl) => getStepModelGroupKey({ label: lbl })))) + : [gk]; + let anomalySteps = 0; + let anomalyCount = 0; + let anomalyDangerCount = 0; + let anomalyTotalDelaySec = 0; + const anomalyByKind = {}; + for (const key of groupKeys) { + const hit = stepAnomalyByGroup.get(key); + if (!hit) continue; + anomalySteps += hit.anomalySteps; + anomalyCount += hit.anomalyCount; + anomalyDangerCount += hit.anomalyDangerCount; + anomalyTotalDelaySec += hit.anomalyTotalDelaySec; + for (const [k, cnt] of Object.entries(hit.anomalyByKind)) { + anomalyByKind[k] = (anomalyByKind[k] || 0) + cnt; + } + } + if (anomalyCount <= 0) return m; + return { + ...m, + anomalySteps, + anomalyCount, + anomalyDangerCount, + anomalyTotalDelaySec: +anomalyTotalDelaySec.toFixed(1), + anomalyByKind, + }; + }; + let sumCalls = 0; let sumTokens = 0; let sumCost = 0; let sumUnpriced = 0; + let sumAnomalyCount = 0; + let sumAnomalySteps = 0; + const sumAnomalyByKind = {}; + const effectiveAnomalyModels = new Map(); for (const m of displayModels) { sumCalls += Math.max(0, Number(m.calls || 0)); sumTokens += Math.max(0, Number(m.totalTokens || 0)); @@ -22794,6 +23414,54 @@ const StepsDetailView = defineComponent({ if (Number.isFinite(Number(m.costUsd))) { sumCost += Math.max(0, Number(m.costUsd)); } + const effM = resolveEffectiveAnomalyModel(m); + effectiveAnomalyModels.set(m, effM); + const anomSum = resolveModelAnomalySummary(effM); + if (anomSum) { + sumAnomalyCount += anomSum.count; + sumAnomalySteps += anomSum.steps; + for (const [k, v] of anomSum.entries) { + sumAnomalyByKind[k] = (sumAnomalyByKind[k] || 0) + v; + } + } + } + + if (sumAnomalyCount > 0) { + patchAttr(modelsAnomalyStripEl, 'hidden', false); + const sortedKinds = Object.entries(sumAnomalyByKind) + .filter(([, v]) => v > 0) + .sort((a, b) => b[1] - a[1]); + const stripSig = `${locale}:${sumAnomalyCount}:${sumAnomalySteps}:${sortedKinds.map(([k, v]) => `${k}=${v}`).join(',')}`; + if (stripSig !== lastAnomalyStripSig) { + lastAnomalyStripSig = stripSig; + patchText( + modelsAnomalyMetaEl, + t('steps.anomalySummaryMeta', { count: sumAnomalyCount, steps: sumAnomalySteps }) + ); + while (modelsAnomalyTagsEl.firstChild) { + modelsAnomalyTagsEl.removeChild(modelsAnomalyTagsEl.firstChild); + } + for (const [kind, cnt] of sortedKinds) { + const isDanger = kind === 'rate_limit' || kind === 'auth_or_model'; + const btn = h('button', { + type: 'button', + className: `step-anomaly-tag smodel-anomaly-tag text-mono${isDanger ? ' is-danger' : ''}`, + text: formatAnomalyTagText(kind, cnt), + title: `${formatAnomalyKindLabel(kind)} · ${t('steps.anomalyModelClickHint')}`, + onclick: () => { + hideAnomalyTip(); + selectedTableModels = ['__all__']; + onlyAnomalies = true; + anomalyKindFilter = kind; + uiStore.setState({ stepsSubTab: 'steps' }); + }, + }); + modelsAnomalyTagsEl.appendChild(btn); + } + } + } else { + lastAnomalyStripSig = ''; + patchAttr(modelsAnomalyStripEl, 'hidden', true); } if (displayModels.length === 0) { @@ -22837,11 +23505,20 @@ const StepsDetailView = defineComponent({ : [gk]; const isActiveFit = hasMultipleModels && cardGroupKeys.some((k) => fitActiveKeySet.has(k)); - return `${locale}:${m.displayText}:${m.displayTitle}:${m.calls}:${sumCalls}:${displayModels.length}:${m.avgTokPerSec}:${avgTtft}:${m.cacheHitPct}:${m.inputTokens}:${m.cacheReadTokens}:${m.thinkingTokens}:${m.responseTokens}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${isActiveFit}:${hasMultipleModels}`; + const effM = effectiveAnomalyModels.get(m) || m; + const anomSum = resolveModelAnomalySummary(effM); + const anomSig = anomSum + ? `${anomSum.count}:${anomSum.steps}:${anomSum.primaryKind}:${anomSum.severity}:${anomSum.totalDelaySec}` + : ''; + return `${locale}:${m.displayText}:${m.displayTitle}:${m.calls}:${sumCalls}:${displayModels.length}:${m.avgTokPerSec}:${avgTtft}:${m.cacheHitPct}:${m.inputTokens}:${m.cacheReadTokens}:${m.thinkingTokens}:${m.responseTokens}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${isActiveFit}:${hasMultipleModels}:${anomSig}`; }, createRow: () => { const nameEl = h('strong', { className: 'smodel-name' }); const callsPillEl = h('span', { className: 'smodel-calls-pill text-mono' }); + const anomalyTagEl = h('span', { + className: 'step-anomaly-tag smodel-anomaly-tag text-mono', + hidden: true, + }); const tokEl = h('span', { className: 'smodel-tok text-mono' }); const costEl = h('strong', { className: 'smodel-cost text-mono' }); const segBar = createFourSegmentBar(); @@ -22852,7 +23529,7 @@ const StepsDetailView = defineComponent({ const cardEl = h('div', { className: 'smodel-card' }, [ h('div', { className: 'smodel-head' }, [ - h('div', { className: 'smodel-ident' }, [nameEl, callsPillEl]), + h('div', { className: 'smodel-ident' }, [nameEl, callsPillEl, anomalyTagEl]), h('div', { className: 'smodel-totals' }, [tokEl, costEl]), ]), segBar.el, @@ -22861,7 +23538,7 @@ const StepsDetailView = defineComponent({ return { el: cardEl, - refs: { nameEl, callsPillEl, tokEl, costEl, segBar, perfEl, splitEl }, + refs: { nameEl, callsPillEl, anomalyTagEl, tokEl, costEl, segBar, perfEl, splitEl }, }; }, updateRow: (refs, m, _idx, cardEl) => { @@ -22886,6 +23563,29 @@ const StepsDetailView = defineComponent({ : t('steps.modelCallsOnly', { calls }) ); + const effM = effectiveAnomalyModels.get(m) || m; + const anomSum = resolveModelAnomalySummary(effM); + patchAttr(refs.anomalyTagEl, 'hidden', !anomSum); + if (anomSum) { + patchText(refs.anomalyTagEl, anomSum.tagText); + patchClasses(refs.anomalyTagEl, { 'is-danger': anomSum.severity === 'danger' }); + refs.anomalyTagEl.onmouseenter = () => + showAnomalyTip(refs.anomalyTagEl, buildModelAnomalyDiagnostic(effM)); + refs.anomalyTagEl.onmouseleave = hideAnomalyTip; + refs.anomalyTagEl.onclick = (e) => { + e?.stopPropagation?.(); + hideAnomalyTip(); + selectedTableModels = hasMultipleModels ? [...cardGroupKeys] : ['__all__']; + onlyAnomalies = true; + anomalyKindFilter = ''; + uiStore.setState({ stepsSubTab: 'steps' }); + }; + } else { + refs.anomalyTagEl.onmouseenter = null; + refs.anomalyTagEl.onmouseleave = null; + refs.anomalyTagEl.onclick = null; + } + const inTok = Math.max(0, Number(m.inputTokens || 0)); const cacheTok = Math.max(0, Number(m.cacheReadTokens || 0)); const outTok = Math.max(0, Number(m.outputTokens || 0)); @@ -22929,7 +23629,7 @@ const StepsDetailView = defineComponent({ patchText( refs.perfEl, t('steps.modelPerfFoot', { - tps: formatMetric(m.avgTokPerSec, ' tok/s'), + tps: formatSpeedMetric(m.avgTokPerSec, ' tok/s'), ttft: formatMetric(resolvedAvgTtft, 's'), cache: resolvedCachePct, }) @@ -22990,7 +23690,9 @@ const StepsDetailView = defineComponent({ (st) => st.stepsSubTab, (tab) => { hideTurnTip(); + hideAnomalyTip(); subTabSwitch.setValue(tab); + patchAttr(anomalyFilterBarEl, 'hidden', tab !== 'steps' || !onlyAnomalies); patchAttr(stepsScroll.el, 'hidden', tab !== 'steps'); patchAttr(modelsScroll.el, 'hidden', tab !== 'models'); if (getVisibleMonitorView() === 'steps' && latestSlice) { @@ -23062,6 +23764,7 @@ const StepsDetailView = defineComponent({ prevActiveView = uiSlice.activeView; if (uiSlice.activeView !== 'steps') { hideTurnTip(); + hideAnomalyTip(); fitPinnedWhileVisible = false; if (scopeChanged) isDirty = true; return; @@ -23086,6 +23789,7 @@ const StepsDetailView = defineComponent({ ); onCleanup(() => { + modelsAnalyticsPane.removeEventListener('scroll', onModelsPaneScroll); unsubUi(); unsubTelemetry(); unsubView(); @@ -23111,6 +23815,9 @@ const StepsDetailView = defineComponent({ stepsTheadRow, stepsTbody, turnTipEl, + anomalyTipEl, + anomalyFilterBarEl, + modelsAnomalyStripEl, modelsListEl, inlineScopeSelect, stepsModelSelect, diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index aa43f49..835636e 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -79,7 +79,7 @@ function projectDisplayStep(st) { const { stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel, modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec, - streamDurationSec, selectedSpeedReason, contextTokens, inputTokens, cacheReadTokens, + streamDurationSec, selectedSpeedReason, anomaly, anomalySig, contextTokens, inputTokens, cacheReadTokens, outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, inCostUsd, cacheCostUsd, outCostUsd, agentId, agentCascadeId, agentKind, agentOrdinal, agentCustomRole, agentLabel, agentBadge, agentRole, agentIndex, isSubagent, @@ -91,7 +91,9 @@ function projectDisplayStep(st) { return { stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel, modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec, - streamDurationSec, selectedSpeedReason, contextTokens, inputTokens, cacheReadTokens, + streamDurationSec, selectedSpeedReason, + ...(anomaly ? { anomaly, anomalySig } : {}), + contextTokens, inputTokens, cacheReadTokens, outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, inCostUsd, cacheCostUsd, outCostUsd, agentId, agentCascadeId, agentKind, agentOrdinal, agentCustomRole, agentLabel, agentBadge, agentRole, agentIndex, isSubagent, @@ -104,7 +106,9 @@ function projectDisplayStep(st) { const MAX_DISPLAY_STEP_CACHE_ENTRIES = 8; const displayStepsCache = new Map(); -const displayStepFields = Object.keys(projectDisplayStep({})); +const displayStepFields = Object.keys(projectDisplayStep({ anomaly: true, anomalySig: '' })).filter( + (k) => k !== 'anomaly' +); function haveSameDisplaySteps(previous, current) { if (!previous || !current) return previous === current; diff --git a/sidecars/panel/backend/cli-sqlite-reader.mjs b/sidecars/panel/backend/cli-sqlite-reader.mjs index 8118492..5ccb237 100644 --- a/sidecars/panel/backend/cli-sqlite-reader.mjs +++ b/sidecars/panel/backend/cli-sqlite-reader.mjs @@ -914,6 +914,84 @@ function decodeProtoContextWindowMetaSlice(buf, state, end, includeBreakdown) { }; } +function decodeProtoRetryInfoSlice(buf, state, end) { + const ri = {}; + while (state.off < end) { + const rTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const rFn = rTag >>> 3; + const rWt = rTag & 7; + if (rFn === 2 && rWt === 2) { + ri.usage = decodeProtoModelUsageSlice(buf, state, readSubEnd(buf, state, end)); + } else if (rFn === 3 && rWt === 2) { + const errStr = readProtoString(buf, state, end).trim(); + if (errStr) { + ri.error = errStr.length > 320 ? `${errStr.slice(0, 319)}…` : errStr; + } + } else if (rFn === 5 && rWt === 0) { + const code = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + if (code > 0) ri.reasonCode = code; + } else if (rFn === 7 && rWt === 2) { + const dur = decodeProtoDurationSlice(buf, state, readSubEnd(buf, state, end)); + if (dur) ri.retryDelay = dur; + } else { + skipProtoField(buf, state, rWt, end); + } + } + state.off = end; + return ri; +} + +function decodeProtoErrorMessageSlice(buf, state, end) { + let userErrorMessage = ''; + let shortError = ''; + let errorCode = 0; + let shouldShowModel = false; + let shouldShowUser = false; + + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 3 && wt === 2) { + const eEnd = readSubEnd(buf, state, end); + while (state.off < eEnd) { + const eTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, eEnd))); + const eFn = eTag >>> 3; + const eWt = eTag & 7; + if (eFn === 1 && eWt === 2) { + const s = readProtoString(buf, state, eEnd).trim(); + if (s) userErrorMessage = s.length > 240 ? `${s.slice(0, 239)}…` : s; + } else if (eFn === 2 && eWt === 2) { + const s = readProtoString(buf, state, eEnd).trim(); + if (s) shortError = s.length > 320 ? `${s.slice(0, 319)}…` : s; + } else if (eFn === 7 && eWt === 0) { + errorCode = Number(BigInt.asUintN(32, readProtoVarint(buf, state, eEnd))); + } else { + skipProtoField(buf, state, eWt, eEnd); + } + } + state.off = eEnd; + } else if (fn === 4 && wt === 0) { + shouldShowModel = readProtoVarint(buf, state, end) !== 0n; + } else if (fn === 5 && wt === 0) { + shouldShowUser = readProtoVarint(buf, state, end) !== 0n; + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + if (!userErrorMessage && !shortError && !errorCode) return null; + return { + error: { + ...(userErrorMessage ? { userErrorMessage } : {}), + ...(shortError ? { shortError } : {}), + ...(errorCode > 0 ? { errorCode } : {}), + }, + ...(shouldShowModel ? { shouldShowModel: true } : {}), + ...(shouldShowUser ? { shouldShowUser: true } : {}), + }; +} + function decodeProtoChatModelMetaSlice(buf, state, end, includeBreakdown) { let model = ''; let usage = null; @@ -922,6 +1000,8 @@ function decodeProtoChatModelMetaSlice(buf, state, end, includeBreakdown) { let streamingDuration = ''; let responseModel = ''; let modelDisplayName = ''; + let retryCount = 0; + let retryInfos = null; const extraMeta = {}; let messagePrompts = null; let tools = null; @@ -1004,6 +1084,8 @@ function decodeProtoChatModelMetaSlice(buf, state, end, includeBreakdown) { timeToFirstToken = decodeProtoDurationSlice(buf, state, readSubEnd(buf, state, end)); } else if (fn === 12 && wt === 2) { streamingDuration = decodeProtoDurationSlice(buf, state, readSubEnd(buf, state, end)); + } else if (fn === 14 && wt === 0) { + retryCount = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); } else if (fn === 16 && wt === 2) { if (includeBreakdown) { const psEnd = readSubEnd(buf, state, end); @@ -1030,6 +1112,10 @@ function decodeProtoChatModelMetaSlice(buf, state, end, includeBreakdown) { } else { skipProtoField(buf, state, wt, end); } + } else if (fn === 17 && wt === 2) { + const ri = decodeProtoRetryInfoSlice(buf, state, readSubEnd(buf, state, end)); + if (!retryInfos) retryInfos = []; + retryInfos.push(ri); } else if (fn === 19 && wt === 2) { responseModel = readProtoString(buf, state, end).trim(); } else if (fn === 20 && wt === 2) { @@ -1056,6 +1142,8 @@ function decodeProtoChatModelMetaSlice(buf, state, end, includeBreakdown) { usage.apiProvider = 'API_PROVIDER_ANTHROPIC'; } + const hasRetryEvidence = + retryCount > 0 || Boolean(retryInfos && retryInfos.some((r) => r?.error || r?.reasonCode)); return { chatModel: { ...(model ? { model } : {}), @@ -1065,6 +1153,8 @@ function decodeProtoChatModelMetaSlice(buf, state, end, includeBreakdown) { : {}), ...(timeToFirstToken ? { timeToFirstToken } : {}), ...(streamingDuration ? { streamingDuration } : {}), + ...(retryCount > 0 ? { retryCount } : {}), + ...(hasRetryEvidence && retryInfos ? { retryInfos } : {}), ...(responseModel ? { responseModel } : {}), ...(modelDisplayName ? { modelDisplayName } : {}), ...(messagePrompts ? { messagePrompts } : {}), @@ -1233,19 +1323,7 @@ function decodeProtoStepMeta(rawBlob, fallbackIdx) { } state.off = siEnd; } else if (fn === 28 && wt === 2) { - const riEnd = readSubEnd(buf, state, end); - const ri = {}; - while (state.off < riEnd) { - const rTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, riEnd))); - const rFn = rTag >>> 3; - const rWt = rTag & 7; - if (rFn === 2 && rWt === 2) { - ri.usage = decodeProtoModelUsageSlice(buf, state, readSubEnd(buf, state, riEnd)); - } else { - skipProtoField(buf, state, rWt, riEnd); - } - } - state.off = riEnd; + const ri = decodeProtoRetryInfoSlice(buf, state, readSubEnd(buf, state, end)); if (!retryInfos) retryInfos = []; retryInfos.push(ri); } else if (fn === 30 && wt === 2) { @@ -1501,6 +1579,9 @@ function decodeProtoSelectiveStepPayload( readSubEnd(buf, state, end), keepFullText ); + } else if (fn === 24 && wt === 2 && stepTypeNum === 17) { + const em = decodeProtoErrorMessageSlice(buf, state, readSubEnd(buf, state, end)); + if (em) out.errorMessage = em; } else if (fn === 114 && wt === 2 && stepTypeNum === 101 && includeSystemMessage) { const sysMsg = decodeProtoSystemMessageSlice(buf, state, readSubEnd(buf, state, end)); if (sysMsg) out.systemMessage = { message: sysMsg }; @@ -1786,6 +1867,7 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) { if ( rec.stepTypeNum === 14 || rec.stepTypeNum === 15 || + rec.stepTypeNum === 17 || (isChildTrajectory && rec.stepTypeNum === 101) || isInvSub || (inRunningTail && (rec.stepTypeNum !== 132 || !rec.metadata?.toolCall?.argumentsJson)) @@ -1868,6 +1950,9 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) { if (decodedPayload.plannerResponse) { stepObj.plannerResponse = decodedPayload.plannerResponse; } + if (decodedPayload.errorMessage) { + stepObj.errorMessage = decodedPayload.errorMessage; + } if (decodedPayload.invokeSubagent) { stepObj.invokeSubagent = decodedPayload.invokeSubagent; } diff --git a/sidecars/panel/backend/local-scanner.mjs b/sidecars/panel/backend/local-scanner.mjs index 1ea7fcf..405b6e6 100644 --- a/sidecars/panel/backend/local-scanner.mjs +++ b/sidecars/panel/backend/local-scanner.mjs @@ -783,11 +783,23 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc } continue; } + if (sq.type === 'CORTEX_STEP_TYPE_ERROR_MESSAGE') { + sqliteRawSteps.push({ + type: sq.type, + status: sq.status, + ...(sq.errorMessage ? { errorMessage: sq.errorMessage } : {}), + ...(typeof tLine?.error === 'string' && tLine.error ? { error: tLine.error } : {}), + ...(typeof tLine?.content === 'string' && tLine.content ? { content: tLine.content } : {}), + metadata: sq.metadata, + }); + continue; + } - if (sq.metadata?.modelUsage) { + const rawUsage = sq.metadata?.modelUsage || sq.metadata?.retryInfos?.[0]?.usage; + if (rawUsage) { const deepStep = extMatch?.steps?.[modelOrdinal] || null; modelOrdinal += 1; - const mu = { ...sq.metadata.modelUsage }; + const mu = { ...rawUsage }; if (!mu.model) { const fallbackModel = String( tLine?.model || tLine?.generator_model || deepStep?.modelKey || '' @@ -822,7 +834,9 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc upperType === 'CORTEX_STEP_TYPE_USER_INPUT' || (line.userInput && typeof line.userInput === 'object') || upperType === 'SYSTEM_MESSAGE' || - upperType === 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE' + upperType === 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE' || + upperType === 'ERROR_MESSAGE' || + upperType === 'CORTEX_STEP_TYPE_ERROR_MESSAGE' ) { sqliteRawSteps.push(line); } else if ( @@ -830,14 +844,19 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc line.cache_read_tokens !== undefined || line.output_tokens !== undefined ) { + const tailStatus = String(line.status || '').trim().toUpperCase(); sqliteRawSteps.push({ type: upperType === 'CHECKPOINT' || upperType === 'CORTEX_STEP_TYPE_CHECKPOINT' ? 'CORTEX_STEP_TYPE_CHECKPOINT' : String(line.type || 'PLANNER_RESPONSE'), - status: /CANCEL/i.test(String(line.status || '')) + status: /CANCEL/.test(tailStatus) ? 'CORTEX_STEP_STATUS_CANCELED' - : 'CORTEX_STEP_STATUS_DONE', + : /ERROR/.test(tailStatus) + ? 'CORTEX_STEP_STATUS_ERROR' + : /INTERRUPT/.test(tailStatus) + ? 'CORTEX_STEP_STATUS_INTERRUPTED' + : 'CORTEX_STEP_STATUS_DONE', plannerResponse: { response: typeof line.content === 'string' ? line.content : '', thinking: typeof line.thinking === 'string' ? line.thinking : '', @@ -873,7 +892,9 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc upperType === 'CORTEX_STEP_TYPE_USER_INPUT' || (line.userInput && typeof line.userInput === 'object') || upperType === 'SYSTEM_MESSAGE' || - upperType === 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE' + upperType === 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE' || + upperType === 'ERROR_MESSAGE' || + upperType === 'CORTEX_STEP_TYPE_ERROR_MESSAGE' ) { syntheticSteps.push(line); continue; @@ -898,7 +919,11 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc const rawStatus = String(line.status || '').trim().toUpperCase(); const mappedStatus = /CANCEL/.test(rawStatus) ? 'CORTEX_STEP_STATUS_CANCELED' - : 'CORTEX_STEP_STATUS_DONE'; + : /ERROR/.test(rawStatus) + ? 'CORTEX_STEP_STATUS_ERROR' + : /INTERRUPT/.test(rawStatus) + ? 'CORTEX_STEP_STATUS_INTERRUPTED' + : 'CORTEX_STEP_STATUS_DONE'; const finishedAt = String( line.finished_generating_at || line.finishedGeneratingAt || @@ -1931,6 +1956,7 @@ export async function enumerateAndSyncConversations({ turnRailTelemetry: true, wakeupTurnTelemetry: true, contextGroupsTelemetry: 2, + anomalyTelemetry: 1, steps: stepsWithOwners, subagentRefs, }; @@ -1964,6 +1990,7 @@ export async function enumerateAndSyncConversations({ !prev.speedClearedTelemetry || !prev.turnRailTelemetry || !prev.contextGroupsTelemetry || + !prev.anomalyTelemetry || metaChanged || !isDeepStrictEqual(prev.steps, stepsWithOwners); @@ -2033,6 +2060,7 @@ export async function enumerateAndSyncConversations({ speedClearedTelemetry: true, turnRailTelemetry: true, contextGroupsTelemetry: 2, + anomalyTelemetry: 1, steps: offlineStepsWithOwners, subagentRefs: offlineFallback.subagentRefs, }; @@ -2163,6 +2191,7 @@ export async function enumerateAndSyncConversations({ if (!cached.contextLimitTelemetry && lowerCid === contextTelemetryCascadeId) return true; if ( (!cached.turnRailTelemetry || + !cached.anomalyTelemetry || hasMissingTurnRailFields(cached) || needsWakeupTurnRefresh(conv, cached) || hasDroppedContextGroups(cached)) && @@ -2345,6 +2374,7 @@ export async function enumerateAndSyncConversations({ !hasMissingStepFields(existingSubCache) && (!isSelectedSubFamily || (Boolean(existingSubCache.turnRailTelemetry) && + Boolean(existingSubCache.anomalyTelemetry) && !hasMissingTurnRailFields(existingSubCache) && !needsWakeupTurnRefresh(subConv, existingSubCache) && !hasDroppedContextGroups(existingSubCache))); diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs index c3d57e3..c5b8397 100644 --- a/sidecars/panel/backend/usage-aggregator.mjs +++ b/sidecars/panel/backend/usage-aggregator.mjs @@ -291,6 +291,11 @@ function accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost) { ttftSumSec: 0, ttftSampleCount: 0, speedAccumulator: createSpeedAccumulator(), + anomalySteps: 0, + anomalyCount: 0, + anomalyDangerCount: 0, + anomalyTotalDelaySec: 0, + anomalyByKind: {}, }); } const agg = perModelStats.get(modelGroupKey); @@ -315,6 +320,28 @@ function accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost) { agg.ttftSampleCount += 1; } + if (st?.anomaly && Number(st.anomaly.count) > 0) { + agg.anomalySteps += 1; + agg.anomalyCount += Number(st.anomaly.count); + if (st.anomaly.severity === 'danger') { + agg.anomalyDangerCount += 1; + } + if (Number(st.anomaly.totalDelaySec) > 0) { + agg.anomalyTotalDelaySec += Number(st.anomaly.totalDelaySec); + } + if (st.anomaly.kinds && typeof st.anomaly.kinds === 'object') { + for (const [k, v] of Object.entries(st.anomaly.kinds)) { + const cnt = Number(v || 0); + if (cnt > 0) { + agg.anomalyByKind[k] = (agg.anomalyByKind[k] || 0) + cnt; + } + } + } else if (st.anomaly.primaryKind) { + agg.anomalyByKind[st.anomaly.primaryKind] = + (agg.anomalyByKind[st.anomaly.primaryKind] || 0) + Number(st.anomaly.count); + } + } + agg.calls += 1; agg.inputTokens += inTok; agg.cacheReadTokens += cacheTok; @@ -342,6 +369,11 @@ function finalizeModelBreakdownMap(perModelStats) { fallbackModelId, ttftSumSec, ttftSampleCount, + anomalySteps, + anomalyCount, + anomalyDangerCount, + anomalyTotalDelaySec, + anomalyByKind, ...m }) => { const sortedUpstream = Array.from((upstreamModelCounts || new Map()).entries()) @@ -355,6 +387,7 @@ function finalizeModelBreakdownMap(perModelStats) { promptTokens > 0 ? +((m.cacheReadTokens / promptTokens) * 100).toFixed(1) : 0; const avgTtftSec = ttftSampleCount > 0 ? roundMetric(ttftSumSec / ttftSampleCount) : null; + const hasAnomalies = Number(anomalyCount || 0) > 0; return { ...m, upstreamName: primaryUpstream, @@ -365,6 +398,15 @@ function finalizeModelBreakdownMap(perModelStats) { ttftSampleCount, avgTokPerSec: roundMetric(finishedSpeed.avgTokPerSec), speedSummary: finishedSpeed, + ...(hasAnomalies + ? { + anomalySteps: Number(anomalySteps || 0), + anomalyCount: Number(anomalyCount || 0), + anomalyDangerCount: Number(anomalyDangerCount || 0), + anomalyTotalDelaySec: +(Number(anomalyTotalDelaySec || 0)).toFixed(1), + anomalyByKind: anomalyByKind || {}, + } + : {}), }; } ); diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index ff0ac01..9d61edf 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/charts/SessionStepCharts.js b/sidecars/panel/src/components/charts/SessionStepCharts.js index e9bf1ca..84aa5d1 100644 --- a/sidecars/panel/src/components/charts/SessionStepCharts.js +++ b/sidecars/panel/src/components/charts/SessionStepCharts.js @@ -11,6 +11,8 @@ import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js'; import { formatAgentBadgeText, + formatSpeedMetric, + formatStepAnomalyInlineSummary, formatTokens, formatTokensPrecise, formatUsd, @@ -641,7 +643,7 @@ function formatChartMetricValue(metric, val) { case 'context': return `${formatTokensPrecise(val)} tok`; case 'tps': - return `${val.toFixed(1)} tok/s`; + return formatSpeedMetric(val, ' tok/s'); case 'ttft': return `${val.toFixed(1)}s`; case 'cache': @@ -660,7 +662,7 @@ function formatChartMetricCompact(metric, val) { case 'context': return formatTokens(val); case 'tps': - return `${val.toFixed(1)} tok/s`; + return formatSpeedMetric(val, ' tok/s'); case 'ttft': return `${val.toFixed(1)}s`; case 'cache': @@ -750,6 +752,10 @@ export function createSessionLineChart() { const dotsGroup = document.createElementNS(SVG_NS, 'g'); svg.appendChild(dotsGroup); + const anomalyDotsGroup = document.createElementNS(SVG_NS, 'g'); + anomalyDotsGroup.setAttribute('class', 'sstep-anomaly-dots'); + svg.appendChild(anomalyDotsGroup); + const hoverLine = document.createElementNS(SVG_NS, 'line'); hoverLine.setAttribute('class', 'trend-hover-line'); hoverLine.setAttribute('y1', '10'); @@ -776,10 +782,12 @@ export function createSessionLineChart() { const tipMainLeft = h('strong', { className: 'trend-tip-tokens text-mono' }); const tipMainRight = h('span', { className: 'trend-tip-cost text-mono' }); const tipSub = h('div', { className: 'trend-tip-sub text-mono', hidden: true }); + const tipAnomaly = h('div', { className: 'trend-tip-anomaly text-mono', hidden: true }); const tooltipEl = h('div', { className: 'trend-tooltip', hidden: true }, [ h('div', { className: 'trend-tip-head' }, [tipHeadLeft, tipHeadRight]), h('div', { className: 'trend-tip-main' }, [tipMainLeft, tipMainRight]), tipSub, + tipAnomaly, ]); const xAxisEl = h('div', { className: 'trend-x-axis' }); @@ -837,7 +845,12 @@ export function createSessionLineChart() { patchAttr(hoverDot, 'hidden', false); patchAttr(hoverDot, 'cx', pt.x.toFixed(1)); patchAttr(hoverDot, 'cy', pt.y.toFixed(1)); - patchStyleVar(hoverDot, '--hover-dot-color', pt.hoverColor || 'var(--ctx-cached)'); + const hoverAccent = pt.anomalySummary + ? pt.anomalySeverity === 'danger' + ? 'var(--metric-danger)' + : 'var(--metric-warn)' + : pt.hoverColor || 'var(--ctx-cached)'; + patchStyleVar(hoverDot, '--hover-dot-color', hoverAccent); patchAttr(peakPill, 'hidden', true); patchAttr(tooltipEl, 'hidden', false); @@ -853,6 +866,11 @@ export function createSessionLineChart() { if (pt.subDetail) { patchText(tipSub, pt.subDetail); } + patchAttr(tipAnomaly, 'hidden', !pt.anomalySummary); + if (pt.anomalySummary) { + patchText(tipAnomaly, pt.anomalySummary); + patchClasses(tipAnomaly, { 'is-danger': pt.anomalySeverity === 'danger' }); + } const rawPct = (pt.x / viewW) * 100; const clampedPct = Math.max(1, Math.min(99, rawPct)); @@ -998,6 +1016,7 @@ export function createSessionLineChart() { while (multiAreaGroup.firstChild) multiAreaGroup.removeChild(multiAreaGroup.firstChild); while (multiLineGroup.firstChild) multiLineGroup.removeChild(multiLineGroup.firstChild); while (dotsGroup.firstChild) dotsGroup.removeChild(dotsGroup.firstChild); + while (anomalyDotsGroup.firstChild) anomalyDotsGroup.removeChild(anomalyDotsGroup.firstChild); while (xAxisEl.firstChild) xAxisEl.removeChild(xAxisEl.firstChild); patchAttr(modelLegendEl, 'hidden', true); patchAttr(peakPill, 'hidden', true); @@ -1126,7 +1145,7 @@ export function createSessionLineChart() { } else if (metric === 'ttft') { valid = !st.isCompactionStep && Number.isFinite(st.ttftSec) && st.ttftSec >= 0; value = valid ? Number(st.ttftSec) : 0; - secondaryRight = Number.isFinite(st.tokPerSec) ? `${st.tokPerSec.toFixed(1)} tok/s` : ''; + secondaryRight = Number.isFinite(st.tokPerSec) ? formatSpeedMetric(st.tokPerSec, ' tok/s') : ''; subDetail = valid ? t('chart.step.ctxAndCache', { ctxTok: formatTokens(ctxTok), @@ -1165,6 +1184,7 @@ export function createSessionLineChart() { } const dotColor = modelColorMap.get(gk) || accentColor; + const anomalySummary = formatStepAnomalyInlineSummary(st.anomaly); return { idx, st, @@ -1177,6 +1197,8 @@ export function createSessionLineChart() { value, secondaryRight, subDetail, + anomalySummary, + anomalySeverity: st.anomaly?.severity || '', }; }); @@ -1212,7 +1234,10 @@ export function createSessionLineChart() { const sig = `${locale}|${viewW}|${metric}|${showAgentPrefix}|${isMultiCompare ? 'multi' : 'single'}:${targetKeys.join(',')}|${colorSig}|` + points - .map((p) => `${p.stepTag}:${p.modelText}:${p.valid ? p.value.toFixed(4) : 'x'}`) + .map( + (p) => + `${p.stepTag}:${p.modelText}:${p.valid ? p.value.toFixed(4) : 'x'}:${p.st?.anomalySig || ''}` + ) .join('|'); if (sig !== lastSig) { @@ -1220,6 +1245,7 @@ export function createSessionLineChart() { while (multiAreaGroup.firstChild) multiAreaGroup.removeChild(multiAreaGroup.firstChild); while (multiLineGroup.firstChild) multiLineGroup.removeChild(multiLineGroup.firstChild); while (dotsGroup.firstChild) dotsGroup.removeChild(dotsGroup.firstChild); + while (anomalyDotsGroup.firstChild) anomalyDotsGroup.removeChild(anomalyDotsGroup.firstChild); if (isMultiCompare) { patchAttr(linePath, 'd', ''); @@ -1315,6 +1341,19 @@ export function createSessionLineChart() { } } + for (const pt of points) { + if (!pt.valid || !pt.anomalySummary) continue; + const aDot = document.createElementNS(SVG_NS, 'circle'); + aDot.setAttribute('cx', pt.x.toFixed(1)); + aDot.setAttribute('cy', pt.y.toFixed(1)); + aDot.setAttribute('r', '2.9'); + aDot.setAttribute( + 'class', + `sstep-anomaly-dot${pt.anomalySeverity === 'danger' ? ' is-danger' : ''}` + ); + anomalyDotsGroup.appendChild(aDot); + } + const tickIndices = computeStepTickIndices(points.length); while (xAxisEl.firstChild) xAxisEl.removeChild(xAxisEl.firstChild); tickElsByIdx = new Map(); @@ -1542,10 +1581,12 @@ export function createModelFitChart() { const tipMainLeft = h('strong', { className: 'trend-tip-tokens text-mono' }); const tipMainRight = h('span', { className: 'trend-tip-cost text-mono' }); const tipSub = h('div', { className: 'trend-tip-sub text-mono', hidden: true }); + const tipAnomaly = h('div', { className: 'trend-tip-anomaly text-mono', hidden: true }); const tooltipEl = h('div', { className: 'trend-tooltip', hidden: true }, [ h('div', { className: 'trend-tip-head' }, [tipHeadLeft, tipHeadRight]), h('div', { className: 'trend-tip-main' }, [tipMainLeft, tipMainRight]), tipSub, + tipAnomaly, ]); const fitMethodLabelEl = h('span', { text: t('chart.fit.loess') }); @@ -1636,6 +1677,10 @@ export function createModelFitChart() { patchAttr(hoverRawDot, 'hidden', false); patchAttr(hoverRawDot, 'cx', sp.x.toFixed(1)); patchAttr(hoverRawDot, 'cy', sp.rawY.toFixed(1)); + patchClasses(hoverRawDot, { + 'is-anomaly': Boolean(sp.anomalySummary), + 'is-danger': Boolean(sp.anomalySummary && sp.anomalySeverity === 'danger'), + }); const wasHidden = tooltipEl.hasAttribute('hidden'); patchAttr(tooltipEl, 'hidden', false); @@ -1668,6 +1713,11 @@ export function createModelFitChart() { }) ); } + patchAttr(tipAnomaly, 'hidden', !sp.anomalySummary); + if (sp.anomalySummary) { + patchText(tipAnomaly, sp.anomalySummary); + patchClasses(tipAnomaly, { 'is-danger': sp.anomalySeverity === 'danger' }); + } const rawPct = (sp.x / viewW) * 100; const clampedPct = Math.max(1, Math.min(99, rawPct)); @@ -1952,6 +2002,8 @@ export function createModelFitChart() { rawVal, stepTag: formatStepAxisTag(st, showAgentPrefix), modelText: disp.baseText || disp.text, + anomalySummary: formatStepAnomalyInlineSummary(st.anomaly), + anomalySeverity: st.anomaly?.severity || '', }); } } @@ -2105,7 +2157,12 @@ export function createModelFitChart() { .map( (s) => `${s.key}:${s.colorVar}:` + - s.samples.map((p) => `${p.xVal}:${p.rawVal.toFixed(3)}:${p.fitVal.toFixed(3)}`).join(',') + s.samples + .map( + (p) => + `${p.xVal}:${p.rawVal.toFixed(3)}:${p.fitVal.toFixed(3)}:${p.st?.anomalySig || ''}` + ) + .join(',') ) .join('||'); @@ -2134,10 +2191,15 @@ export function createModelFitChart() { typeof document.createDocumentFragment === 'function' ? document.createDocumentFragment() : scatterGroup; + const anomalyOverlayDots = []; for (const s of seriesList) { const binCounts = dedupOverdraw ? new Map() : null; for (const sp of s.samples) { + if (sp.anomalySummary) { + anomalyOverlayDots.push(sp); + continue; + } if (binCounts) { const binKey = (Math.round(sp.x * 2) << 11) ^ Math.round(sp.rawY * 2); const prevCnt = binCounts.get(binKey) || 0; @@ -2200,6 +2262,17 @@ export function createModelFitChart() { multiCurveGroup.appendChild(curveEl); } } + for (const sp of anomalyOverlayDots) { + const aDot = document.createElementNS(SVG_NS, 'circle'); + aDot.setAttribute('cx', sp.x.toFixed(1)); + aDot.setAttribute('cy', sp.rawY.toFixed(1)); + aDot.setAttribute('r', '2.9'); + aDot.setAttribute( + 'class', + `sstep-scatter-dot is-anomaly${sp.anomalySeverity === 'danger' ? ' is-danger' : ''}` + ); + scatterTarget.appendChild(aDot); + } if (scatterTarget !== scatterGroup) { scatterGroup.appendChild(scatterTarget); } @@ -2316,7 +2389,11 @@ export function createModelFitChart() { const sig = `single|${locale}|${viewW}|${targetKeys[0]}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` + - samples.map((s) => `${s.xVal}:${s.rawVal.toFixed(4)}:${s.fitVal.toFixed(4)}`).join('|'); + samples + .map( + (s) => `${s.xVal}:${s.rawVal.toFixed(4)}:${s.fitVal.toFixed(4)}:${s.st?.anomalySig || ''}` + ) + .join('|'); if (sig !== lastSig) { lastSig = sig; @@ -2340,7 +2417,12 @@ export function createModelFitChart() { typeof document.createDocumentFragment === 'function' ? document.createDocumentFragment() : scatterGroup; + const singleAnomalyDots = []; for (const s of samples) { + if (s.anomalySummary) { + singleAnomalyDots.push(s); + continue; + } if (binCounts) { const binKey = (Math.round(s.x * 2) << 11) ^ Math.round(s.rawY * 2); const prevCnt = binCounts.get(binKey) || 0; @@ -2354,6 +2436,17 @@ export function createModelFitChart() { dot.setAttribute('class', 'sstep-scatter-dot'); scatterTarget.appendChild(dot); } + for (const s of singleAnomalyDots) { + const aDot = document.createElementNS(SVG_NS, 'circle'); + aDot.setAttribute('cx', s.x.toFixed(1)); + aDot.setAttribute('cy', s.rawY.toFixed(1)); + aDot.setAttribute('r', '2.9'); + aDot.setAttribute( + 'class', + `sstep-scatter-dot is-anomaly${s.anomalySeverity === 'danger' ? ' is-danger' : ''}` + ); + scatterTarget.appendChild(aDot); + } if (scatterTarget !== scatterGroup) { scatterGroup.appendChild(scatterTarget); } diff --git a/sidecars/panel/src/components/widgets/StepTableWidget.js b/sidecars/panel/src/components/widgets/StepTableWidget.js index c68d727..52e764c 100644 --- a/sidecars/panel/src/components/widgets/StepTableWidget.js +++ b/sidecars/panel/src/components/widgets/StepTableWidget.js @@ -13,7 +13,11 @@ import { patchKeyedList, patchText, } from '../../core/domPatch.js'; -import { resolveModelDisplayInfo, speedReasonText } from '../../core/formatters.js'; +import { + buildStepAnomalyDiagnostic, + resolveModelDisplayInfo, + speedReasonText, +} from '../../core/formatters.js'; import { getEffectiveLocale, t } from '../../i18n/index.js'; import { DEFAULT_STEP_COLUMN_KEYS, @@ -198,9 +202,14 @@ function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) { if (needTps) { const tpsVal = Number(st.tokPerSec); - if (Number.isFinite(tpsVal) && tpsVal > maxTpsVal) { - maxTpsVal = tpsVal; - maxTpsObj = st; + if (Number.isFinite(tpsVal) && tpsVal >= 0) { + const tpsScore = + (tpsVal >= 100 ? String(Math.round(tpsVal)).length : tpsVal.toFixed(1).length) * 1e6 + + tpsVal; + if (tpsScore > maxTpsVal) { + maxTpsVal = tpsScore; + maxTpsObj = st; + } } if (st.selectedSpeedReason) { reasonCandidates.add(st.selectedSpeedReason); @@ -415,8 +424,31 @@ export const StepTableWidget = defineComponent({ }); const hideTurnTip = () => patchAttr(turnTipEl, 'hidden', true); + const anomalyTipTitleEl = h('div', { className: 'step-anomaly-tip-title' }); + const anomalyTipSubEl = h('div', { className: 'step-anomaly-tip-sub text-mono', hidden: true }); + const anomalyTipHeadEl = h('div', { className: 'step-anomaly-tip-head' }, [ + anomalyTipTitleEl, + anomalyTipSubEl, + ]); + const anomalyTipListEl = h('div', { className: 'step-anomaly-tip-list' }); + const anomalyTipHintEl = h('div', { className: 'step-anomaly-tip-hint', hidden: true }); + const anomalyTipEl = h( + 'div', + { + className: 'step-anomaly-tip', + role: 'tooltip', + hidden: true, + }, + [anomalyTipHeadEl, anomalyTipListEl, anomalyTipHintEl] + ); + const hideAnomalyTip = () => patchAttr(anomalyTipEl, 'hidden', true); + const standaloneHostEl = standalone - ? h('div', { className: 'step-table-preview-host' }, [stepsTablePane, turnTipEl]) + ? h('div', { className: 'step-table-preview-host' }, [ + stepsTablePane, + turnTipEl, + anomalyTipEl, + ]) : null; let boundsContainerGetter = @@ -430,40 +462,85 @@ export const StepTableWidget = defineComponent({ } } + function positionFloatingTip(tipEl, anchorEl) { + const boundsEl = boundsContainerGetter?.(); + if ( + !boundsEl || + typeof boundsEl.getBoundingClientRect !== 'function' || + typeof anchorEl?.getBoundingClientRect !== 'function' + ) { + return; + } + const panelRect = boundsEl.getBoundingClientRect(); + const anchorRect = anchorEl.getBoundingClientRect(); + if (!(panelRect.width > 0 && panelRect.height > 0)) return; + const tipH = tipEl.offsetHeight || 56; + const tipW = tipEl.offsetWidth || 220; + const placeAbove = + panelRect.bottom - anchorRect.bottom < tipH + 10 && + anchorRect.top - panelRect.top > tipH + 6; + const topPx = placeAbove + ? Math.max(4, Math.round(anchorRect.top - panelRect.top - tipH - 5)) + : Math.round(anchorRect.bottom - panelRect.top + 5); + const maxLeft = Math.max(6, Math.round(panelRect.width - tipW - 8)); + const leftPx = Math.min( + maxLeft, + Math.max(6, Math.round(anchorRect.left - panelRect.left)) + ); + tipEl.style.top = `${topPx}px`; + tipEl.style.left = `${leftPx}px`; + } + function showTurnTip(anchorCell, promptText) { const text = String(promptText || '').trim(); - const boundsEl = boundsContainerGetter?.(); if (!anchorCell || !text) { hideTurnTip(); return; } + hideAnomalyTip(); patchText(turnTipEl, text); patchAttr(turnTipEl, 'hidden', false); - if ( - boundsEl && - typeof boundsEl.getBoundingClientRect === 'function' && - typeof anchorCell.getBoundingClientRect === 'function' - ) { - const panelRect = boundsEl.getBoundingClientRect(); - const cellRect = anchorCell.getBoundingClientRect(); - if (panelRect.width > 0 && panelRect.height > 0) { - const tipH = turnTipEl.offsetHeight || 36; - const tipW = turnTipEl.offsetWidth || 180; - const placeAbove = - panelRect.bottom - cellRect.bottom < tipH + 10 && - cellRect.top - panelRect.top > tipH + 6; - const topPx = placeAbove - ? Math.max(4, Math.round(cellRect.top - panelRect.top - tipH - 4)) - : Math.round(cellRect.bottom - panelRect.top + 4); - const maxLeft = Math.max(6, Math.round(panelRect.width - tipW - 8)); - const leftPx = Math.min( - maxLeft, - Math.max(6, Math.round(cellRect.left - panelRect.left + 4)) - ); - turnTipEl.style.top = `${topPx}px`; - turnTipEl.style.left = `${leftPx}px`; - } + positionFloatingTip(turnTipEl, anchorCell); + } + + function showAnomalyTip(anchorEl, diag) { + if (!anchorEl || !diag || !diag.title) { + hideAnomalyTip(); + return; } + hideTurnTip(); + patchClasses(anomalyTipEl, { 'is-danger': diag.severity === 'danger' }); + patchText(anomalyTipTitleEl, diag.title); + patchAttr(anomalyTipSubEl, 'hidden', !diag.sub); + if (diag.sub) patchText(anomalyTipSubEl, diag.sub); + + while (anomalyTipListEl.firstChild) { + anomalyTipListEl.removeChild(anomalyTipListEl.firstChild); + } + const rows = Array.isArray(diag.rows) ? diag.rows : []; + for (const row of rows) { + const lineEl = h('div', { + className: `step-anomaly-tip-row${row.danger ? ' is-danger' : ''}`, + text: row.text, + }); + const itemChildren = [lineEl]; + if (row.detail) { + itemChildren.push( + h('div', { + className: 'step-anomaly-tip-detail text-mono', + text: row.detail, + }) + ); + } + anomalyTipListEl.appendChild(h('div', { className: 'step-anomaly-tip-item' }, itemChildren)); + } + patchAttr(anomalyTipListEl, 'hidden', rows.length === 0); + + patchAttr(anomalyTipHintEl, 'hidden', !diag.hint); + if (diag.hint) patchText(anomalyTipHintEl, diag.hint); + + patchAttr(anomalyTipEl, 'hidden', false); + positionFloatingTip(anomalyTipEl, anchorEl); } const hoverRows = new WeakMap(); @@ -598,15 +675,30 @@ export const StepTableWidget = defineComponent({ } function moveInStepCell(event) { - if (event?.target === hoverRows.get(this).badge) hideTurnTip(); + const { badge } = hoverRows.get(this); + if (event?.target === badge) hideTurnTip(); } function moveAlongTurnRail(event) { - const { badge, prompt } = hoverRows.get(this); + const { badge, prompt, anomalyStep } = hoverRows.get(this); const rect = this.getBoundingClientRect?.(); const relX = rect ? (event?.clientX ?? 0) - rect.left : 0; - if (event?.target !== badge && relX <= 18) showTurnTip(this, prompt); - else hideTurnTip(); + if (event?.target !== badge && relX <= 18) { + showTurnTip(this, prompt); + } else { + hideTurnTip(); + if (anomalyStep) { + showAnomalyTip(this, buildStepAnomalyDiagnostic(anomalyStep)); + } + } + } + + function leaveStepCell(event) { + const entry = hoverRows.get(this); + hideTurnTip(); + if (entry?.anomalyStep && entry.tr && event?.relatedTarget && entry.tr.contains?.(event.relatedTarget)) { + showAnomalyTip(this, buildStepAnomalyDiagnostic(entry.anomalyStep)); + } } function clearCellHover(cell) { @@ -898,7 +990,8 @@ export const StepTableWidget = defineComponent({ ? `${cellCtx.scopeSigKey}:${st.agentId || 'main'}:${st.agentBadge || ''}:${st.agentLabel || ''}` : ''; const stripeSig = isVirtualized ? (item.isStripeEven ? 'E' : 'O') : 'N'; - return `${locale}:${colOrderSig}:${stripeSig}:${badgeSig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`; + const anomalySig = st.anomalySig || ''; + return `${locale}:${colOrderSig}:${stripeSig}:${badgeSig}:${anomalySig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`; }, createRow: (item) => { if (item.isSizer) { @@ -1140,6 +1233,24 @@ export const StepTableWidget = defineComponent({ refs.agentBadgeEl.onclick = null; } + const hasStepAnomaly = Boolean(st?.anomaly && Number(st.anomaly.count) > 0); + const isAnomalyDanger = Boolean(hasStepAnomaly && st.anomaly.severity === 'danger'); + const isAnomalyWarn = Boolean(hasStepAnomaly && !isAnomalyDanger); + patchClasses(tr, { + 'is-anomaly-warn': isAnomalyWarn, + 'is-anomaly-danger': isAnomalyDanger, + }); + if (hasStepAnomaly) { + const anchorEl = firstTd || tr; + tr.onmouseenter = () => { + showAnomalyTip(anchorEl, buildStepAnomalyDiagnostic(st)); + }; + tr.onmouseleave = hideAnomalyTip; + } else { + tr.onmouseenter = null; + tr.onmouseleave = null; + } + patchAttr(refs.railEl, 'hidden', !showRowRail); if (showRowRail) { const marker = isStart ? ' is-origin' : !hasUp && hasDown ? ' is-cap' : ''; @@ -1154,10 +1265,16 @@ export const StepTableWidget = defineComponent({ if (refs.hoverTd !== hoverTd) clearCellHover(refs.hoverTd); refs.hoverTd = hoverTd; if (hoverTd) { - hoverRows.set(hoverTd, { badge: refs.agentBadgeEl, prompt }); - hoverTd.onmouseenter = firstColKey === 'step' ? enterStepCell : null; - hoverTd.onmousemove = firstColKey === 'step' ? moveInStepCell : moveAlongTurnRail; - hoverTd.onmouseleave = hideTurnTip; + hoverRows.set(hoverTd, { + badge: refs.agentBadgeEl, + prompt, + anomalyStep: hasStepAnomaly ? st : null, + tr, + }); + const useWholeCellTurnTip = firstColKey === 'step' && !hasStepAnomaly; + hoverTd.onmouseenter = useWholeCellTurnTip ? enterStepCell : null; + hoverTd.onmousemove = useWholeCellTurnTip ? moveInStepCell : moveAlongTurnRail; + hoverTd.onmouseleave = leaveStepCell; } if (enteringRowKeys?.has(item.rowKey)) { @@ -1179,7 +1296,14 @@ export const StepTableWidget = defineComponent({ } clearRowEnterState(tr); if (!refs?.isSpacer && !refs?.isSizer && tr) { - patchClasses(tr, { 'is-stripe-even': false, 'is-step-entering': false }); + patchClasses(tr, { + 'is-stripe-even': false, + 'is-step-entering': false, + 'is-anomaly-warn': false, + 'is-anomaly-danger': false, + }); + tr.onmouseenter = null; + tr.onmouseleave = null; if (refs.agentBadgeEl) { refs.agentBadgeEl.onclick = null; } @@ -1209,6 +1333,7 @@ export const StepTableWidget = defineComponent({ function onPaneScroll() { hideTurnTip(); + hideAnomalyTip(); if (!activeDataset?.isVirtualized) return; if (typeof requestAnimationFrame === 'function') { if (scrollRafId) return; @@ -1221,8 +1346,13 @@ export const StepTableWidget = defineComponent({ } } + function onTbodyLeave() { + hideTurnTip(); + hideAnomalyTip(); + } + stepsTablePane.addEventListener('scroll', onPaneScroll, { passive: true }); - stepsTbody.addEventListener('mouseleave', hideTurnTip); + stepsTbody.addEventListener('mouseleave', onTbodyLeave); let paneResizeObs = null; if (typeof ResizeObserver === 'function') { @@ -1424,7 +1554,7 @@ export const StepTableWidget = defineComponent({ onCleanup(() => { stepsTablePane.removeEventListener('scroll', onPaneScroll); - stepsTbody.removeEventListener('mouseleave', hideTurnTip); + stepsTbody.removeEventListener('mouseleave', onTbodyLeave); if (scrollRafId && typeof cancelAnimationFrame === 'function') { cancelAnimationFrame(scrollRafId); scrollRafId = 0; @@ -1449,10 +1579,13 @@ export const StepTableWidget = defineComponent({ stepsTheadRow, stepsTbody, turnTipEl, + anomalyTipEl, syncTableHeaderColumns, renderStepTable, refreshViewport, hideTurnTip, + showAnomalyTip, + hideAnomalyTip, setBoundsElGetter, }, }; diff --git a/sidecars/panel/src/core/formatters.js b/sidecars/panel/src/core/formatters.js index f0287ae..3f6f294 100644 --- a/sidecars/panel/src/core/formatters.js +++ b/sidecars/panel/src/core/formatters.js @@ -25,6 +25,12 @@ export function formatMetric(value, unit = '') { return Number.isFinite(value) ? `${value.toFixed(1)}${unit}` : '—'; } +export function formatSpeedMetric(value, unit = ' tok/s') { + if (!Number.isFinite(value)) return '—'; + const numStr = value >= 100 ? String(Math.round(value)) : value.toFixed(1); + return `${numStr}${unit}`; +} + export function formatCachePct(value) { if (value == null || !Number.isFinite(Number(value))) return '—'; const num = Math.max(0, Math.min(100, +Number(value).toFixed(1))); @@ -98,6 +104,8 @@ const SPEED_REASON_LABELS = { __proto__: null, incomplete_or_invalid_timing: 'fmt.speedIncomplete', canceled: 'fmt.speedCanceled', + error: 'fmt.speedError', + interrupted: 'fmt.speedInterrupted', compaction_timing_unavailable: 'fmt.speedCompactionTimingUnavailable', invalid_output_tokens: 'fmt.speedInvalidOutput', inconsistent_timing: 'fmt.speedInconsistent', @@ -110,6 +118,135 @@ export function speedReasonText(reason) { return label ? t(label) : ''; } +const ANOMALY_KIND_ORDER = Object.freeze([ + 'rate_limit', + 'timeout', + 'capacity', + 'disconnect', + 'upstream', + 'model_output', + 'safety', + 'auth_or_model', + 'error', +]); + +export function formatAnomalyKindLabel(kind) { + const k = String(kind || 'error'); + const key = `steps.anomalyKind.${k}`; + const text = t(key); + return text === key ? t('steps.anomalyKind.error') : text; +} + +export function formatAnomalyTagText(primaryKind, count = 1) { + const n = Math.max(1, Math.floor(Number(count) || 1)); + const k = String(primaryKind || 'error'); + if (k === 'capacity' && n === 1) return t('steps.anomalyTag.capacitySingle'); + if (k === 'upstream' && n === 1) return t('steps.anomalyTag.upstreamSingle'); + const key = `steps.anomalyTag.${k}`; + const formatted = t(key, { n }); + return formatted === key ? t('steps.anomalyTag.error', { n }) : formatted; +} + +export function resolveModelAnomalySummary(m) { + const count = Math.max(0, Number(m?.anomalyCount || 0)); + const steps = Math.max(0, Number(m?.anomalySteps || 0)); + if (count <= 0 && steps <= 0) return null; + const byKind = m?.anomalyByKind && typeof m.anomalyByKind === 'object' ? m.anomalyByKind : {}; + const entries = Object.entries(byKind) + .map(([k, v]) => [k, Math.max(0, Number(v || 0))]) + .filter(([, v]) => v > 0) + .sort((a, b) => { + if (b[1] !== a[1]) return b[1] - a[1]; + const pa = ANOMALY_KIND_ORDER.indexOf(a[0]); + const pb = ANOMALY_KIND_ORDER.indexOf(b[0]); + return (pa < 0 ? 99 : pa) - (pb < 0 ? 99 : pb); + }); + const totalCount = count || entries.reduce((sum, [, v]) => sum + v, 0) || steps; + const primaryKind = entries.length === 1 ? entries[0][0] : entries.length > 1 ? 'mixed' : 'error'; + const severity = + Number(m?.anomalyDangerCount || 0) > 0 || + entries.some(([k]) => k === 'rate_limit' || k === 'auth_or_model') + ? 'danger' + : 'warn'; + return { + count: totalCount, + steps: steps || totalCount, + totalDelaySec: Math.max(0, Number(m?.anomalyTotalDelaySec || 0)), + primaryKind, + severity, + entries, + tagText: formatAnomalyTagText(primaryKind, totalCount), + }; +} + +export function formatStepAnomalyInlineSummary(anomaly) { + if (!anomaly || !(Number(anomaly.count) > 0)) return ''; + const tag = formatAnomalyTagText(anomaly.primaryKind, anomaly.count); + const label = formatAnomalyKindLabel(anomaly.primaryKind); + const delaySec = Number(anomaly.totalDelaySec || 0); + const delayPart = delaySec > 0 ? ` · ${t('steps.anomalyDelayPart', { sec: delaySec })}` : ''; + return `${tag} · ${label}${delayPart}`; +} + +export function buildStepAnomalyDiagnostic(st) { + const a = st?.anomaly; + if (!a || !(Number(a.count) > 0)) return null; + const title = t('steps.anomalyStepTitle', { + step: Number(st.stepIndex ?? 0), + count: Number(a.count), + }); + const delaySec = Number(a.totalDelaySec || 0); + const sub = delaySec > 0 ? t('steps.anomalyDelayPart', { sec: delaySec }) : ''; + const events = Array.isArray(a.events) ? a.events : []; + const rows = events.map((ev, idx) => { + const label = formatAnomalyKindLabel(ev.kind); + const parts = [`#${ev.attempt || idx + 1} ${label}`]; + if (Number(ev.delaySec) > 0) { + parts.push(t('steps.anomalyDelayPart', { sec: ev.delaySec })); + } + if (ev.terminal) { + parts.push(t('steps.anomalyTerminalTag')); + } + return { + text: parts.join(' · '), + detail: ev.message || '', + danger: Boolean(ev.terminal || ev.kind === 'rate_limit' || ev.kind === 'auth_or_model'), + }; + }); + return { + title, + sub, + rows, + hint: '', + severity: a.severity === 'danger' ? 'danger' : 'warn', + }; +} + +export function buildModelAnomalyDiagnostic(m) { + const sum = resolveModelAnomalySummary(m); + if (!sum) return null; + const title = t('steps.anomalyModelTitle', { + model: m?.displayText || m?.shortName || m?.label || '—', + count: sum.count, + }); + const subParts = [t('steps.anomalyModelSub', { steps: sum.steps })]; + if (sum.totalDelaySec > 0) { + subParts.push(t('steps.anomalyDelayPart', { sec: sum.totalDelaySec })); + } + const rows = sum.entries.map(([k, v]) => ({ + text: t('steps.anomalyModelKindRow', { kind: formatAnomalyKindLabel(k), count: v }), + detail: '', + danger: k === 'rate_limit' || k === 'auth_or_model', + })); + return { + title, + sub: subParts.join(' · '), + rows, + hint: t('steps.anomalyModelClickHint'), + severity: sum.severity, + }; +} + export function sampleSummary(summary) { const valid = summary?.sampleCount || 0; const excluded = summary?.excludedCount || 0; @@ -389,6 +526,12 @@ export function mergeModelsByDisplayName(models = [], settings = {}, options = { ttftWeightedSum: hasTtft ? Number(m.avgTtftSec) * ttftWeight : 0, ttftWeight: hasTtft ? ttftWeight : 0, ttftSampleCount, + anomalySteps: Math.max(0, Number(m.anomalySteps || 0)), + anomalyCount: Math.max(0, Number(m.anomalyCount || 0)), + anomalyDangerCount: Math.max(0, Number(m.anomalyDangerCount || 0)), + anomalyTotalDelaySec: Math.max(0, Number(m.anomalyTotalDelaySec || 0)), + anomalyByKind: + m.anomalyByKind && typeof m.anomalyByKind === 'object' ? { ...m.anomalyByKind } : {}, }; if (m.upstreamName) acc.upstreamSet.add(m.upstreamName); byDisplay.set(key, acc); @@ -417,6 +560,17 @@ export function mergeModelsByDisplayName(models = [], settings = {}, options = { acc.costUsd += costUsd; acc.unpricedCalls += unpricedCalls; + acc.anomalySteps += Math.max(0, Number(m.anomalySteps || 0)); + acc.anomalyCount += Math.max(0, Number(m.anomalyCount || 0)); + acc.anomalyDangerCount += Math.max(0, Number(m.anomalyDangerCount || 0)); + acc.anomalyTotalDelaySec += Math.max(0, Number(m.anomalyTotalDelaySec || 0)); + if (m.anomalyByKind && typeof m.anomalyByKind === 'object') { + for (const [ak, av] of Object.entries(m.anomalyByKind)) { + const cnt = Math.max(0, Number(av || 0)); + if (cnt > 0) acc.anomalyByKind[ak] = (acc.anomalyByKind[ak] || 0) + cnt; + } + } + if (hasSpeed) { acc.speedWeightedSum += Number(m.avgTokPerSec) * speedWeight; acc.speedWeight += speedWeight; @@ -467,6 +621,15 @@ export function mergeModelsByDisplayName(models = [], settings = {}, options = { avgTokPerSec, avgTtftSec, ttftSampleCount: acc.ttftSampleCount, + ...(acc.anomalyCount > 0 + ? { + anomalySteps: acc.anomalySteps, + anomalyCount: acc.anomalyCount, + anomalyDangerCount: acc.anomalyDangerCount, + anomalyTotalDelaySec: +acc.anomalyTotalDelaySec.toFixed(1), + anomalyByKind: acc.anomalyByKind, + } + : {}), speedSummary: acc.baseItem.speedSummary ? { ...acc.baseItem.speedSummary, diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 2a61196..039ffa0 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -37,6 +37,8 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'fmt.pending': 'N/A', 'fmt.speedIncomplete': 'Incomplete timing', 'fmt.speedCanceled': 'Canceled', + 'fmt.speedError': 'Call error', + 'fmt.speedInterrupted': 'Interrupted', 'fmt.speedCompactionTimingUnavailable': 'Untimed compaction', 'fmt.speedInvalidOutput': 'No valid output', 'fmt.speedInconsistent': 'Invalid timing', @@ -299,6 +301,38 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'steps.fitInactiveCardTitle': 'Click to inspect {text} in Trend Fit (Ctrl/Shift-click to compare)', 'steps.turnMediaOnly': '[Media Attachment]', 'steps.turnMediaSuffix': '[Media]', + 'steps.anomalyTag.timeout': 'TO{n}', + 'steps.anomalyTag.rate_limit': '429×{n}', + 'steps.anomalyTag.capacity': '503×{n}', + 'steps.anomalyTag.capacitySingle': '503', + 'steps.anomalyTag.disconnect': 'Drop{n}', + 'steps.anomalyTag.upstream': '500×{n}', + 'steps.anomalyTag.upstreamSingle': '500', + 'steps.anomalyTag.model_output': 'Fix{n}', + 'steps.anomalyTag.safety': 'Safe{n}', + 'steps.anomalyTag.auth_or_model': 'Err{n}', + 'steps.anomalyTag.error': 'Err{n}', + 'steps.anomalyTag.mixed': 'Warn{n}', + 'steps.anomalyKind.timeout': 'Stream Idle / Connect Timeout', + 'steps.anomalyKind.rate_limit': '429 Rate Limit / Quota Reached', + 'steps.anomalyKind.capacity': '503 No Capacity Available', + 'steps.anomalyKind.disconnect': 'Connection Reset / Stream Interrupted', + 'steps.anomalyKind.upstream': 'Upstream 5xx Internal Error', + 'steps.anomalyKind.model_output': 'Invalid Model Output / Tool Call', + 'steps.anomalyKind.safety': 'Content Safety Filter', + 'steps.anomalyKind.auth_or_model': 'Request / Model Rejected', + 'steps.anomalyKind.error': 'Call Error', + 'steps.anomalyKind.canceled': 'Canceled by User', + 'steps.anomalyStepTitle': '#{step} · {count} Retries / Errors', + 'steps.anomalyDelayPart': 'Backoff {sec}s', + 'steps.anomalyTerminalTag': 'Stopped', + 'steps.anomalyModelTitle': '{model} · {count} Retries / Errors', + 'steps.anomalyModelSub': '{steps} steps affected', + 'steps.anomalyModelKindRow': '{kind}: {count}', + 'steps.anomalyModelClickHint': 'Click to filter anomalous steps', + 'steps.anomalySummaryMeta': '{count} retries/errors ({steps} steps)', + 'steps.anomalyFilterLabel': 'Anomalies Only ({count})', + 'steps.anomalyFilterAll': 'Show All Steps', // Step Table Columns (Headers & Option Labels) 'stepCol.step.th': 'Step', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 38c3086..018a047 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -37,6 +37,8 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'fmt.pending': '待定', 'fmt.speedIncomplete': '计时不完整', 'fmt.speedCanceled': '已取消', + 'fmt.speedError': '调用报错', + 'fmt.speedInterrupted': '连接中断', 'fmt.speedCompactionTimingUnavailable': '压缩无计时', 'fmt.speedInvalidOutput': '无有效输出', 'fmt.speedInconsistent': '耗时数据异常', @@ -299,6 +301,38 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'steps.fitInactiveCardTitle': '点击在上方拟合图查看 {text}(按住 Ctrl/Shift 点击可多选同图对比)', 'steps.turnMediaOnly': '[图片/附件提问]', 'steps.turnMediaSuffix': '[附图]', + 'steps.anomalyTag.timeout': '超时{n}', + 'steps.anomalyTag.rate_limit': '限流{n}', + 'steps.anomalyTag.capacity': '503×{n}', + 'steps.anomalyTag.capacitySingle': '503', + 'steps.anomalyTag.disconnect': '断连{n}', + 'steps.anomalyTag.upstream': '500×{n}', + 'steps.anomalyTag.upstreamSingle': '500', + 'steps.anomalyTag.model_output': '纠偏{n}', + 'steps.anomalyTag.safety': '过滤{n}', + 'steps.anomalyTag.auth_or_model': '受限{n}', + 'steps.anomalyTag.error': '报错{n}', + 'steps.anomalyTag.mixed': '异常{n}', + 'steps.anomalyKind.timeout': '流空闲 / 连接超时', + 'steps.anomalyKind.rate_limit': '429 限流 / 配额耗尽', + 'steps.anomalyKind.capacity': '503 上游算力不足', + 'steps.anomalyKind.disconnect': '连接中断 / 断流', + 'steps.anomalyKind.upstream': '上游 5xx 内部错误', + 'steps.anomalyKind.model_output': '模型输出 / 工具参数无效', + 'steps.anomalyKind.safety': '内容安全过滤', + 'steps.anomalyKind.auth_or_model': '请求受限 / 模型不可用', + 'steps.anomalyKind.error': '调用异常', + 'steps.anomalyKind.canceled': '用户取消', + 'steps.anomalyStepTitle': '#{step} · 异常 {count} 次', + 'steps.anomalyDelayPart': '退避 {sec}s', + 'steps.anomalyTerminalTag': '中止', + 'steps.anomalyModelTitle': '{model} · 异常 {count} 次', + 'steps.anomalyModelSub': '涉及 {steps} 步', + 'steps.anomalyModelKindRow': '{kind}:{count} 次', + 'steps.anomalyModelClickHint': '点击前往「按步查看」筛选异常步', + 'steps.anomalySummaryMeta': '异常 {count} 次({steps} 步)', + 'steps.anomalyFilterLabel': '仅看异常 ({count})', + 'steps.anomalyFilterAll': '返回全部步骤', // Step Table Columns (Headers & Option Labels) 'stepCol.step.th': '步序', diff --git a/sidecars/panel/src/registries/stepColumnRegistry.js b/sidecars/panel/src/registries/stepColumnRegistry.js index ddee8f9..3ca858f 100644 --- a/sidecars/panel/src/registries/stepColumnRegistry.js +++ b/sidecars/panel/src/registries/stepColumnRegistry.js @@ -9,6 +9,7 @@ import { h, patchAttr, patchText } from '../core/domPatch.js'; import { formatCachePct, formatMetric, + formatSpeedMetric, formatTokens, formatUsd, getCacheToneClass, @@ -191,7 +192,7 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({ return { td, refs: { wrapEl, speedMain, speedReason: null } }; }, updateCell: (refs, st, ctx) => { - patchText(refs.speedMain, formatMetric(st.tokPerSec, ' tok/s')); + patchText(refs.speedMain, formatSpeedMetric(st.tokPerSec, ' tok/s')); const hasValidSpeed = st.tokPerSec != null && Number.isFinite(Number(st.tokPerSec)) && Number(st.tokPerSec) > 0; const toneCls = diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index d449691..53c531a 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -603,6 +603,7 @@ export function isEquivalentTelemetry(prev, next) { bs?.contextTokens !== as?.contextTokens || bs?.cacheHitPct !== as?.cacheHitPct || bs?.selectedSpeedReason !== as?.selectedSpeedReason || + bs?.anomalySig !== as?.anomalySig || bs?.turnIndex !== as?.turnIndex || bs?.rootTurnIndex !== as?.rootTurnIndex || bs?.isTurnStart !== as?.isTurnStart || @@ -659,6 +660,7 @@ export function isEquivalentTelemetry(prev, next) { before.contextTokens !== after.contextTokens || before.cacheHitPct !== after.cacheHitPct || before.selectedSpeedReason !== after.selectedSpeedReason || + before.anomalySig !== after.anomalySig || before.turnIndex !== after.turnIndex || before.rootTurnIndex !== after.rootTurnIndex || before.isTurnStart !== after.isTurnStart || @@ -711,7 +713,9 @@ export function isEquivalentTelemetry(prev, next) { a[k]?.costUsd !== b[k]?.costUsd || a[k]?.unpricedCalls !== b[k]?.unpricedCalls || a[k]?.totalTokens !== b[k]?.totalTokens || - a[k]?.calls !== b[k]?.calls + a[k]?.calls !== b[k]?.calls || + Number(a[k]?.anomalyCount || 0) !== Number(b[k]?.anomalyCount || 0) || + Number(a[k]?.anomalySteps || 0) !== Number(b[k]?.anomalySteps || 0) ) { return false; } @@ -750,6 +754,9 @@ export function isEquivalentTelemetry(prev, next) { } // 7. 比对按模型汇总明细与数据来源汇总明细 + if (!areModelSlicesEqual(pAct?.modelBreakdown, nAct?.modelBreakdown)) { + return false; + } if (!areModelSlicesEqual(prev.modelBreakdown, next.modelBreakdown)) { return false; } diff --git a/sidecars/panel/src/styles/modern-ui.css b/sidecars/panel/src/styles/modern-ui.css index 8bc74bb..8c22768 100644 --- a/sidecars/panel/src/styles/modern-ui.css +++ b/sidecars/panel/src/styles/modern-ui.css @@ -343,7 +343,8 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { } [data-modern-ui="true"] .agent-badge, -[data-modern-ui="true"] .agent-badge.is-clickable:hover { +[data-modern-ui="true"] .agent-badge.is-clickable:hover, +[data-modern-ui="true"] .step-anomaly-tag { border: none; } @@ -456,6 +457,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { } [data-modern-ui="true"] .trend-tip-sub, +[data-modern-ui="true"] .trend-tip-anomaly, [data-modern-ui="true"] .cons-pop-models { border-top: none; padding-top: 3px; @@ -516,6 +518,28 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { background: var(--modern-surface-hover); } +[data-modern-ui="true"] .data-table tbody tr.is-anomaly-warn, +[data-modern-ui="true"] .data-table:not(.is-virtualized) tbody tr.is-anomaly-warn:nth-child(even), +[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-warn { + background: color-mix(in srgb, var(--metric-warn) 12%, transparent); +} + +[data-modern-ui="true"] .data-table tbody tr.is-anomaly-warn:hover, +[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-warn:hover { + background: color-mix(in srgb, var(--metric-warn) 19%, transparent); +} + +[data-modern-ui="true"] .data-table tbody tr.is-anomaly-danger, +[data-modern-ui="true"] .data-table:not(.is-virtualized) tbody tr.is-anomaly-danger:nth-child(even), +[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-danger { + background: color-mix(in srgb, var(--metric-danger) 14%, transparent); +} + +[data-modern-ui="true"] .data-table tbody tr.is-anomaly-danger:hover, +[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-danger:hover { + background: color-mix(in srgb, var(--metric-danger) 21%, transparent); +} + [data-modern-ui="true"] .steps-inline-scope-select .select-trigger, [data-modern-ui="true"] .steps-inline-model-select .select-trigger, [data-modern-ui="true"] .sstep-fit-model-select .select-trigger { @@ -550,6 +574,22 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { background: var(--accent-primary-soft); } +[data-modern-ui="true"] .steps-anomaly-filterbar, +[data-modern-ui="true"] .steps-anomaly-strip { + border: none; + border-radius: var(--radius-xs); + background: var(--metric-warn-soft); +} + +[data-modern-ui="true"] .steps-anomaly-filterbar { + margin: 4px 2px 2px; +} + +[data-modern-ui="true"] .sstep-anomaly-dot, +[data-modern-ui="true"] .sstep-scatter-dot.is-anomaly { + fill: var(--modern-surface-card); +} + /* --- 6. 设置表单、折叠面板、槽位排序与输入控件去边框 --- */ [data-modern-ui="true"] .collapsible-body, [data-modern-ui="true"] .settings-action-block + .settings-action-block, @@ -630,13 +670,19 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { [data-modern-ui="true"] .trend-tooltip, [data-modern-ui="true"] .cons-breakdown-popover, -[data-modern-ui="true"] .turn-prompt-tip { +[data-modern-ui="true"] .turn-prompt-tip, +[data-modern-ui="true"] .step-anomaly-tip { border: none; background: var(--modern-surface-card); box-shadow: var(--shadow-popover); animation: anim-modern-tip-fade 150ms var(--ease-modern); } +[data-modern-ui="true"] .step-anomaly-tip-list, +[data-modern-ui="true"] .step-anomaly-tip-hint { + border-top-color: var(--modern-surface-hover); +} + [data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom) { top: 2px; bottom: auto; @@ -740,10 +786,18 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { [data-modern-ui="true"] .wm-multi-label[data-od-active="1"] { display: inline-flex; align-items: center; + justify-content: center; height: 18px; line-height: 18px; } +:host([data-modern-ui="true"]) .wm-slot-text.wm-ctx-pct[data-od-active="1"], +:host([data-modern-ui="true"]) .wm-multi-label[data-od-active="1"], +[data-modern-ui="true"] .wm-slot-text.wm-ctx-pct[data-od-active="1"], +[data-modern-ui="true"] .wm-multi-label[data-od-active="1"] { + justify-content: flex-start; +} + :host([data-modern-ui="true"]) .wm-od-digit, [data-modern-ui="true"] .wm-od-digit { display: inline-block; diff --git a/sidecars/panel/src/styles/views-tables.css b/sidecars/panel/src/styles/views-tables.css index 8cb810f..cb2f46b 100644 --- a/sidecars/panel/src/styles/views-tables.css +++ b/sidecars/panel/src/styles/views-tables.css @@ -295,6 +295,248 @@ animation: anim-popover-in var(--dur-instant) var(--ease-fast); } +/* --- 2.6 单步异常整行语义着色、模型汇总微标、筛选条与悬停诊断卡 --- */ +.data-table tbody tr.is-anomaly-warn { + background: color-mix(in srgb, var(--metric-warn) 11%, transparent); +} + +.data-table tbody tr.is-anomaly-warn:hover { + background: color-mix(in srgb, var(--metric-warn) 18%, transparent); +} + +.data-table tbody tr.is-anomaly-warn td:first-child { + box-shadow: inset 2px 0 0 var(--metric-warn); +} + +.data-table tbody tr.is-anomaly-warn td:first-child > span:not(.agent-badge):not(.turn-rail) { + color: var(--metric-warn); + font-weight: 600; +} + +.data-table tbody tr.is-anomaly-danger { + background: color-mix(in srgb, var(--metric-danger) 13%, transparent); +} + +.data-table tbody tr.is-anomaly-danger:hover { + background: color-mix(in srgb, var(--metric-danger) 20%, transparent); +} + +.data-table tbody tr.is-anomaly-danger td:first-child { + box-shadow: inset 2px 0 0 var(--metric-danger); +} + +.data-table tbody tr.is-anomaly-danger td:first-child > span:not(.agent-badge):not(.turn-rail) { + color: var(--metric-danger); + font-weight: 600; +} + +.step-anomaly-tag { + display: inline-flex; + align-items: center; + vertical-align: middle; + margin-left: 4px; + padding: 0 3.5px; + font-size: var(--fs-2xs); + font-weight: 600; + line-height: 1.35; + border-radius: 3px; + color: var(--metric-warn); + background: var(--metric-warn-soft); + border: 1px solid color-mix(in srgb, var(--metric-warn) 34%, transparent); + cursor: help; + white-space: nowrap; + flex-shrink: 0; +} + +.step-anomaly-tag.is-danger { + color: var(--metric-danger); + background: var(--metric-danger-soft); + border-color: color-mix(in srgb, var(--metric-danger) 36%, transparent); +} + +.step-anomaly-tag[hidden] { + display: none !important; +} + +.smodel-anomaly-tag { + margin-left: 0; + cursor: pointer; + font-family: inherit; + transition: + background-color var(--dur-instant) var(--ease-fast), + border-color var(--dur-instant) var(--ease-fast); +} + +.smodel-anomaly-tag:hover { + background: color-mix(in srgb, var(--metric-warn) 22%, transparent); +} + +.smodel-anomaly-tag.is-danger:hover { + background: color-mix(in srgb, var(--metric-danger) 22%, transparent); +} + +.step-anomaly-tip { + position: absolute; + z-index: 46; + max-width: min(300px, calc(100% - 16px)); + min-width: 176px; + padding: 7px 9px; + display: flex; + flex-direction: column; + gap: 5px; + font-size: var(--fs-sm); + line-height: 1.38; + color: var(--text-primary); + background: var(--surface-panel); + border: 1px solid color-mix(in srgb, var(--metric-warn) 42%, var(--border-strong)); + border-radius: var(--radius-xs); + box-shadow: var(--shadow-popover); + pointer-events: none; + animation: anim-popover-in var(--dur-instant) var(--ease-fast); +} + +.step-anomaly-tip.is-danger { + border-color: color-mix(in srgb, var(--metric-danger) 46%, var(--border-strong)); +} + +.step-anomaly-tip[hidden], +.step-anomaly-tip-sub[hidden], +.step-anomaly-tip-list[hidden], +.step-anomaly-tip-hint[hidden] { + display: none !important; +} + +.step-anomaly-tip-head { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; +} + +.step-anomaly-tip-title { + font-weight: 600; + color: var(--metric-warn); + white-space: nowrap; +} + +.step-anomaly-tip.is-danger .step-anomaly-tip-title { + color: var(--metric-danger); +} + +.step-anomaly-tip-sub { + font-size: var(--fs-xs); + color: var(--text-secondary); + white-space: nowrap; +} + +.step-anomaly-tip-list { + display: flex; + flex-direction: column; + gap: 4px; + padding-top: 4px; + border-top: 1px solid var(--border-hairline); +} + +.step-anomaly-tip-item { + display: flex; + flex-direction: column; + gap: 1px; +} + +.step-anomaly-tip-row { + font-size: var(--fs-xs); + font-weight: 500; + color: var(--text-primary); +} + +.step-anomaly-tip-row.is-danger { + color: var(--metric-danger); +} + +.step-anomaly-tip-detail { + font-size: var(--fs-2xs); + line-height: 1.35; + color: var(--text-muted); + word-break: break-word; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; + overflow: hidden; +} + +.step-anomaly-tip-hint { + font-size: var(--fs-2xs); + color: var(--text-muted); + padding-top: 3px; + border-top: 1px solid var(--border-hairline); +} + +.steps-anomaly-filterbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + padding: 4px 8px; + border-top: 1px solid var(--border-hairline); + background: color-mix(in srgb, var(--metric-warn) 8%, var(--surface-panel)); + font-size: var(--fs-xs); +} + +.steps-anomaly-filterbar[hidden] { + display: none !important; +} + +.steps-anomaly-filter-label { + font-weight: 600; + color: var(--metric-warn); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.steps-anomaly-filter-clear { + flex-shrink: 0; + padding: 1px 7px; + font-size: var(--fs-xs); +} + +.steps-anomaly-strip { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 4px 6px; + padding: 4px 8px; + border: 1px solid color-mix(in srgb, var(--metric-warn) 26%, var(--border-hairline)); + border-radius: var(--radius-xs); + background: color-mix(in srgb, var(--metric-warn) 7%, var(--surface-panel)); +} + +.steps-anomaly-strip[hidden] { + display: none !important; +} + +.steps-anomaly-strip-meta { + border: none; + background: transparent; + padding: 0; + font-size: var(--fs-xs); + font-weight: 600; + color: var(--metric-warn); + cursor: pointer; + white-space: nowrap; +} + +.steps-anomaly-strip-meta:hover { + text-decoration: underline; +} + +.steps-anomaly-strip-tags { + display: inline-flex; + align-items: center; + flex-wrap: wrap; + gap: 4px; +} + /* --- 3. 按模型汇总分析视图:双趋势图与极简模型总览 (Models Analytics Pane) --- */ .models-analytics-pane { display: flex; @@ -517,6 +759,47 @@ pointer-events: none; } +.sstep-hover-raw-dot.is-anomaly { + stroke: var(--metric-warn); + stroke-width: 1.85; +} + +.sstep-hover-raw-dot.is-danger { + stroke: var(--metric-danger); +} + +.sstep-anomaly-dot, +.sstep-scatter-dot.is-anomaly { + fill: var(--surface-panel); + fill-opacity: 1; + stroke: var(--metric-warn); + stroke-width: 1.6; + pointer-events: none; +} + +.sstep-anomaly-dot.is-danger, +.sstep-scatter-dot.is-anomaly.is-danger { + stroke: var(--metric-danger); +} + +.trend-tip-anomaly { + margin-top: 3px; + padding-top: 3px; + border-top: 1px solid var(--border-hairline); + font-size: var(--fs-xs); + font-weight: 600; + color: var(--metric-warn); + white-space: nowrap; +} + +.trend-tip-anomaly.is-danger { + color: var(--metric-danger); +} + +.trend-tip-anomaly[hidden] { + display: none !important; +} + .sstep-empty-hint { position: absolute; inset: 0; diff --git a/sidecars/panel/src/views/StepsDetailView.js b/sidecars/panel/src/views/StepsDetailView.js index eac8a0d..db0b1bb 100644 --- a/sidecars/panel/src/views/StepsDetailView.js +++ b/sidecars/panel/src/views/StepsDetailView.js @@ -14,12 +14,17 @@ import { patchText, } from '../core/domPatch.js'; import { + buildModelAnomalyDiagnostic, + formatAnomalyKindLabel, + formatAnomalyTagText, formatMetric, + formatSpeedMetric, formatTokens, formatUsd, mergeModelsByDisplayName, normalizeModelDisplayMode, normalizeOrchestratorIdDisplayMode, + resolveModelAnomalySummary, resolveModelDisplayInfo, } from '../core/formatters.js'; import { createSvgIcon } from '../icons/SvgIcon.js'; @@ -77,6 +82,11 @@ function mergeSelectedAgentUnits(units) { totalTokens: 0, costUsd: 0, unpricedCalls: 0, + anomalySteps: 0, + anomalyCount: 0, + anomalyDangerCount: 0, + anomalyTotalDelaySec: 0, + anomalyByKind: {}, _speedWeightedSum: 0, _speedWeight: 0, _ttftWeightedSum: 0, @@ -116,6 +126,16 @@ function mergeSelectedAgentUnits(units) { acc.totalTokens += totTok; acc.costUsd += costUsd; acc.unpricedCalls += unpricedCalls; + acc.anomalySteps += Math.max(0, Number(m.anomalySteps || 0)); + acc.anomalyCount += Math.max(0, Number(m.anomalyCount || 0)); + acc.anomalyDangerCount += Math.max(0, Number(m.anomalyDangerCount || 0)); + acc.anomalyTotalDelaySec += Math.max(0, Number(m.anomalyTotalDelaySec || 0)); + if (m.anomalyByKind && typeof m.anomalyByKind === 'object') { + for (const [kind, cnt] of Object.entries(m.anomalyByKind)) { + const n = Math.max(0, Number(cnt || 0)); + if (n > 0) acc.anomalyByKind[kind] = (acc.anomalyByKind[kind] || 0) + n; + } + } if (Number.isFinite(Number(m.avgTokPerSec)) && Number(m.avgTokPerSec) > 0) { const w = Math.max(1, outTok || calls || 1); @@ -164,6 +184,15 @@ function mergeSelectedAgentUnits(units) { avgTtftSec: acc._ttftWeight > 0 ? +(acc._ttftWeightedSum / acc._ttftWeight).toFixed(1) : null, cacheHitPct: promptTok > 0 ? +((acc.cacheReadTokens / promptTok) * 100).toFixed(1) : 0, + ...(acc.anomalyCount > 0 + ? { + anomalySteps: acc.anomalySteps, + anomalyCount: acc.anomalyCount, + anomalyDangerCount: acc.anomalyDangerCount, + anomalyTotalDelaySec: +acc.anomalyTotalDelaySec.toFixed(1), + anomalyByKind: acc.anomalyByKind, + } + : {}), }; }) .sort((a, b) => b.totalTokens - a.totalTokens || b.calls - a.calls); @@ -197,6 +226,8 @@ export const StepsDetailView = defineComponent({ let lastSyncedUiScope = uiStore.getState().selectedAgentScope || 'all'; let selectedTableModels = ['__all__']; let selectedLineModels = ['__all__']; + let onlyAnomalies = false; + let anomalyKindFilter = ''; function applyAgentScopesSelection(nextScopes) { selectedAgentScopes = nextScopes; @@ -271,7 +302,10 @@ export const StepsDetailView = defineComponent({ stepsTheadRow, stepsTbody, turnTipEl, + anomalyTipEl, hideTurnTip, + showAnomalyTip, + hideAnomalyTip, syncTableHeaderColumns, renderStepTable, refreshViewport: refreshStepTableViewport, @@ -281,6 +315,23 @@ export const StepsDetailView = defineComponent({ className: 'table-scroll-host', }); + const anomalyFilterLabelEl = h('span', { className: 'steps-anomaly-filter-label text-mono' }); + const anomalyFilterClearBtn = h('button', { + type: 'button', + className: 'btn-ghost-sm steps-anomaly-filter-clear', + text: t('steps.anomalyFilterAll'), + onclick: () => { + onlyAnomalies = false; + anomalyKindFilter = ''; + if (latestSlice) renderStepsData(latestSlice); + }, + }); + const anomalyFilterBarEl = h( + 'div', + { className: 'steps-anomaly-filterbar', hidden: true }, + [anomalyFilterLabelEl, anomalyFilterClearBtn] + ); + // --- 子视图 2:总汇总分析面板 --- let selectedLineMetric = 'totalTokens'; let selectedFitMetric = 'tps'; @@ -383,6 +434,24 @@ export const StepsDetailView = defineComponent({ className: 'cons-badge text-mono', text: t('cons.callsCount', { calls: 0 }), }); + const modelsAnomalyMetaEl = h('button', { + type: 'button', + className: 'steps-anomaly-strip-meta text-mono', + onclick: () => { + hideAnomalyTip(); + selectedTableModels = ['__all__']; + onlyAnomalies = true; + anomalyKindFilter = ''; + uiStore.setState({ stepsSubTab: 'steps' }); + }, + }); + const modelsAnomalyTagsEl = h('div', { className: 'steps-anomaly-strip-tags' }); + const modelsAnomalyStripEl = h( + 'div', + { className: 'steps-anomaly-strip', hidden: true }, + [modelsAnomalyMetaEl, modelsAnomalyTagsEl] + ); + let lastAnomalyStripSig = ''; const modelsEmptyEl = h('div', { className: 'smodel-empty text-muted', text: t('steps.modelsEmpty'), @@ -390,6 +459,7 @@ export const StepsDetailView = defineComponent({ const modelsListEl = h('div', { className: 'smodel-list' }); const modelsSummarySection = h('div', { className: 'smodel-section' }, [ h('div', { className: 'smodel-section-head' }, [modelsSectionTitleEl, modelsSummaryMeta]), + modelsAnomalyStripEl, modelsEmptyEl, modelsListEl, ]); @@ -399,6 +469,8 @@ export const StepsDetailView = defineComponent({ modelFitCard, modelsSummarySection, ]); + const onModelsPaneScroll = () => hideAnomalyTip(); + modelsAnalyticsPane.addEventListener('scroll', onModelsPaneScroll, { passive: true }); const modelsScroll = CustomScrollbar({ contentEl: modelsAnalyticsPane, className: 'table-scroll-host', @@ -424,9 +496,11 @@ export const StepsDetailView = defineComponent({ subTabSwitch.el, ]), ]), + anomalyFilterBarEl, stepsScroll.el, modelsScroll.el, turnTipEl, + anomalyTipEl, ] ); stepTableWidget.refs.setBoundsElGetter(() => panelEl); @@ -497,6 +571,8 @@ export const StepsDetailView = defineComponent({ patchText(fitTitleEl, t('steps.fitTitle')); patchText(modelsSectionTitleEl, t('steps.modelsTitle')); patchText(modelsEmptyEl, t('steps.modelsEmpty')); + patchText(anomalyFilterClearBtn, t('steps.anomalyFilterAll')); + lastAnomalyStripSig = ''; lineMetricSwitch.setProps({ modelValue: selectedLineMetric, options: getLineMetricSwitchOptions(), @@ -530,6 +606,8 @@ export const StepsDetailView = defineComponent({ lastSyncedUiScope = uiSt.selectedAgentScope || 'all'; selectedTableModels = ['__all__']; selectedLineModels = ['__all__']; + onlyAnomalies = false; + anomalyKindFilter = ''; } fitLockedCascadeId = currentCid; fitUserPicked = false; @@ -723,9 +801,29 @@ export const StepsDetailView = defineComponent({ const tableModelFilterSet = selectedTableModels.includes('__all__') ? null : new Set(selectedTableModels); - const tableSteps = tableModelFilterSet + const modelFilteredSteps = tableModelFilterSet ? steps.filter((st) => tableModelFilterSet.has(getStepModelGroupKey(st))) : steps; + const tableSteps = onlyAnomalies + ? modelFilteredSteps.filter((st) => { + const a = st?.anomaly; + if (!a || !(Number(a.count) > 0)) return false; + if (anomalyKindFilter) { + return Number(a.kinds?.[anomalyKindFilter] || 0) > 0; + } + return true; + }) + : modelFilteredSteps; + + const showAnomalyFilterBar = !showModels && onlyAnomalies; + patchAttr(anomalyFilterBarEl, 'hidden', !showAnomalyFilterBar); + if (showAnomalyFilterBar) { + const baseLabel = t('steps.anomalyFilterLabel', { count: tableSteps.length }); + const kindSuffix = anomalyKindFilter + ? ` · ${formatAnomalyKindLabel(anomalyKindFilter)}` + : ''; + patchText(anomalyFilterLabelEl, `${baseLabel}${kindSuffix}`); + } const stepsTabLabel = tableSteps.length !== steps.length @@ -863,10 +961,79 @@ export const StepsDetailView = defineComponent({ // 4. 极简模型总览列表增量对账 const displayModels = mergeModelsByDisplayName(models, displaySettings, { fallback: '—' }); + const needStepAnomalyFallback = displayModels.every((m) => !(Number(m?.anomalyCount) > 0)); + let stepAnomalyByGroup = null; + if (needStepAnomalyFallback) { + for (const st of chronoSteps) { + const a = st?.anomaly; + if (!a || !(Number(a.count) > 0)) continue; + if (!stepAnomalyByGroup) stepAnomalyByGroup = new Map(); + const gk = getStepModelGroupKey(st); + let acc = stepAnomalyByGroup.get(gk); + if (!acc) { + acc = { + anomalySteps: 0, + anomalyCount: 0, + anomalyDangerCount: 0, + anomalyTotalDelaySec: 0, + anomalyByKind: {}, + }; + stepAnomalyByGroup.set(gk, acc); + } + acc.anomalySteps += 1; + acc.anomalyCount += Number(a.count) || 0; + if (a.severity === 'danger') acc.anomalyDangerCount += 1; + acc.anomalyTotalDelaySec += Number(a.totalDelaySec) || 0; + if (a.kinds && typeof a.kinds === 'object') { + for (const [k, cnt] of Object.entries(a.kinds)) { + const n = Math.max(0, Number(cnt || 0)); + if (n > 0) acc.anomalyByKind[k] = (acc.anomalyByKind[k] || 0) + n; + } + } + } + } + const resolveEffectiveAnomalyModel = (m) => { + if (Number(m?.anomalyCount) > 0 || !stepAnomalyByGroup) return m; + const gk = getStepModelGroupKey(m); + const groupKeys = + Array.isArray(m.sourceLabels) && m.sourceLabels.length > 0 + ? Array.from(new Set(m.sourceLabels.map((lbl) => getStepModelGroupKey({ label: lbl })))) + : [gk]; + let anomalySteps = 0; + let anomalyCount = 0; + let anomalyDangerCount = 0; + let anomalyTotalDelaySec = 0; + const anomalyByKind = {}; + for (const key of groupKeys) { + const hit = stepAnomalyByGroup.get(key); + if (!hit) continue; + anomalySteps += hit.anomalySteps; + anomalyCount += hit.anomalyCount; + anomalyDangerCount += hit.anomalyDangerCount; + anomalyTotalDelaySec += hit.anomalyTotalDelaySec; + for (const [k, cnt] of Object.entries(hit.anomalyByKind)) { + anomalyByKind[k] = (anomalyByKind[k] || 0) + cnt; + } + } + if (anomalyCount <= 0) return m; + return { + ...m, + anomalySteps, + anomalyCount, + anomalyDangerCount, + anomalyTotalDelaySec: +anomalyTotalDelaySec.toFixed(1), + anomalyByKind, + }; + }; + let sumCalls = 0; let sumTokens = 0; let sumCost = 0; let sumUnpriced = 0; + let sumAnomalyCount = 0; + let sumAnomalySteps = 0; + const sumAnomalyByKind = {}; + const effectiveAnomalyModels = new Map(); for (const m of displayModels) { sumCalls += Math.max(0, Number(m.calls || 0)); sumTokens += Math.max(0, Number(m.totalTokens || 0)); @@ -874,6 +1041,54 @@ export const StepsDetailView = defineComponent({ if (Number.isFinite(Number(m.costUsd))) { sumCost += Math.max(0, Number(m.costUsd)); } + const effM = resolveEffectiveAnomalyModel(m); + effectiveAnomalyModels.set(m, effM); + const anomSum = resolveModelAnomalySummary(effM); + if (anomSum) { + sumAnomalyCount += anomSum.count; + sumAnomalySteps += anomSum.steps; + for (const [k, v] of anomSum.entries) { + sumAnomalyByKind[k] = (sumAnomalyByKind[k] || 0) + v; + } + } + } + + if (sumAnomalyCount > 0) { + patchAttr(modelsAnomalyStripEl, 'hidden', false); + const sortedKinds = Object.entries(sumAnomalyByKind) + .filter(([, v]) => v > 0) + .sort((a, b) => b[1] - a[1]); + const stripSig = `${locale}:${sumAnomalyCount}:${sumAnomalySteps}:${sortedKinds.map(([k, v]) => `${k}=${v}`).join(',')}`; + if (stripSig !== lastAnomalyStripSig) { + lastAnomalyStripSig = stripSig; + patchText( + modelsAnomalyMetaEl, + t('steps.anomalySummaryMeta', { count: sumAnomalyCount, steps: sumAnomalySteps }) + ); + while (modelsAnomalyTagsEl.firstChild) { + modelsAnomalyTagsEl.removeChild(modelsAnomalyTagsEl.firstChild); + } + for (const [kind, cnt] of sortedKinds) { + const isDanger = kind === 'rate_limit' || kind === 'auth_or_model'; + const btn = h('button', { + type: 'button', + className: `step-anomaly-tag smodel-anomaly-tag text-mono${isDanger ? ' is-danger' : ''}`, + text: formatAnomalyTagText(kind, cnt), + title: `${formatAnomalyKindLabel(kind)} · ${t('steps.anomalyModelClickHint')}`, + onclick: () => { + hideAnomalyTip(); + selectedTableModels = ['__all__']; + onlyAnomalies = true; + anomalyKindFilter = kind; + uiStore.setState({ stepsSubTab: 'steps' }); + }, + }); + modelsAnomalyTagsEl.appendChild(btn); + } + } + } else { + lastAnomalyStripSig = ''; + patchAttr(modelsAnomalyStripEl, 'hidden', true); } if (displayModels.length === 0) { @@ -917,11 +1132,20 @@ export const StepsDetailView = defineComponent({ : [gk]; const isActiveFit = hasMultipleModels && cardGroupKeys.some((k) => fitActiveKeySet.has(k)); - return `${locale}:${m.displayText}:${m.displayTitle}:${m.calls}:${sumCalls}:${displayModels.length}:${m.avgTokPerSec}:${avgTtft}:${m.cacheHitPct}:${m.inputTokens}:${m.cacheReadTokens}:${m.thinkingTokens}:${m.responseTokens}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${isActiveFit}:${hasMultipleModels}`; + const effM = effectiveAnomalyModels.get(m) || m; + const anomSum = resolveModelAnomalySummary(effM); + const anomSig = anomSum + ? `${anomSum.count}:${anomSum.steps}:${anomSum.primaryKind}:${anomSum.severity}:${anomSum.totalDelaySec}` + : ''; + return `${locale}:${m.displayText}:${m.displayTitle}:${m.calls}:${sumCalls}:${displayModels.length}:${m.avgTokPerSec}:${avgTtft}:${m.cacheHitPct}:${m.inputTokens}:${m.cacheReadTokens}:${m.thinkingTokens}:${m.responseTokens}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${isActiveFit}:${hasMultipleModels}:${anomSig}`; }, createRow: () => { const nameEl = h('strong', { className: 'smodel-name' }); const callsPillEl = h('span', { className: 'smodel-calls-pill text-mono' }); + const anomalyTagEl = h('span', { + className: 'step-anomaly-tag smodel-anomaly-tag text-mono', + hidden: true, + }); const tokEl = h('span', { className: 'smodel-tok text-mono' }); const costEl = h('strong', { className: 'smodel-cost text-mono' }); const segBar = createFourSegmentBar(); @@ -932,7 +1156,7 @@ export const StepsDetailView = defineComponent({ const cardEl = h('div', { className: 'smodel-card' }, [ h('div', { className: 'smodel-head' }, [ - h('div', { className: 'smodel-ident' }, [nameEl, callsPillEl]), + h('div', { className: 'smodel-ident' }, [nameEl, callsPillEl, anomalyTagEl]), h('div', { className: 'smodel-totals' }, [tokEl, costEl]), ]), segBar.el, @@ -941,7 +1165,7 @@ export const StepsDetailView = defineComponent({ return { el: cardEl, - refs: { nameEl, callsPillEl, tokEl, costEl, segBar, perfEl, splitEl }, + refs: { nameEl, callsPillEl, anomalyTagEl, tokEl, costEl, segBar, perfEl, splitEl }, }; }, updateRow: (refs, m, _idx, cardEl) => { @@ -966,6 +1190,29 @@ export const StepsDetailView = defineComponent({ : t('steps.modelCallsOnly', { calls }) ); + const effM = effectiveAnomalyModels.get(m) || m; + const anomSum = resolveModelAnomalySummary(effM); + patchAttr(refs.anomalyTagEl, 'hidden', !anomSum); + if (anomSum) { + patchText(refs.anomalyTagEl, anomSum.tagText); + patchClasses(refs.anomalyTagEl, { 'is-danger': anomSum.severity === 'danger' }); + refs.anomalyTagEl.onmouseenter = () => + showAnomalyTip(refs.anomalyTagEl, buildModelAnomalyDiagnostic(effM)); + refs.anomalyTagEl.onmouseleave = hideAnomalyTip; + refs.anomalyTagEl.onclick = (e) => { + e?.stopPropagation?.(); + hideAnomalyTip(); + selectedTableModels = hasMultipleModels ? [...cardGroupKeys] : ['__all__']; + onlyAnomalies = true; + anomalyKindFilter = ''; + uiStore.setState({ stepsSubTab: 'steps' }); + }; + } else { + refs.anomalyTagEl.onmouseenter = null; + refs.anomalyTagEl.onmouseleave = null; + refs.anomalyTagEl.onclick = null; + } + const inTok = Math.max(0, Number(m.inputTokens || 0)); const cacheTok = Math.max(0, Number(m.cacheReadTokens || 0)); const outTok = Math.max(0, Number(m.outputTokens || 0)); @@ -1009,7 +1256,7 @@ export const StepsDetailView = defineComponent({ patchText( refs.perfEl, t('steps.modelPerfFoot', { - tps: formatMetric(m.avgTokPerSec, ' tok/s'), + tps: formatSpeedMetric(m.avgTokPerSec, ' tok/s'), ttft: formatMetric(resolvedAvgTtft, 's'), cache: resolvedCachePct, }) @@ -1070,7 +1317,9 @@ export const StepsDetailView = defineComponent({ (st) => st.stepsSubTab, (tab) => { hideTurnTip(); + hideAnomalyTip(); subTabSwitch.setValue(tab); + patchAttr(anomalyFilterBarEl, 'hidden', tab !== 'steps' || !onlyAnomalies); patchAttr(stepsScroll.el, 'hidden', tab !== 'steps'); patchAttr(modelsScroll.el, 'hidden', tab !== 'models'); if (getVisibleMonitorView() === 'steps' && latestSlice) { @@ -1142,6 +1391,7 @@ export const StepsDetailView = defineComponent({ prevActiveView = uiSlice.activeView; if (uiSlice.activeView !== 'steps') { hideTurnTip(); + hideAnomalyTip(); fitPinnedWhileVisible = false; if (scopeChanged) isDirty = true; return; @@ -1166,6 +1416,7 @@ export const StepsDetailView = defineComponent({ ); onCleanup(() => { + modelsAnalyticsPane.removeEventListener('scroll', onModelsPaneScroll); unsubUi(); unsubTelemetry(); unsubView(); @@ -1191,6 +1442,9 @@ export const StepsDetailView = defineComponent({ stepsTheadRow, stepsTbody, turnTipEl, + anomalyTipEl, + anomalyFilterBarEl, + modelsAnomalyStripEl, modelsListEl, inlineScopeSelect, stepsModelSelect, diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index adb5780..7e21a11 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -3197,6 +3197,248 @@ html[data-standalone="true"] .app-shell { animation: anim-popover-in var(--dur-instant) var(--ease-fast); } +/* --- 2.6 单步异常整行语义着色、模型汇总微标、筛选条与悬停诊断卡 --- */ +.data-table tbody tr.is-anomaly-warn { + background: color-mix(in srgb, var(--metric-warn) 11%, transparent); +} + +.data-table tbody tr.is-anomaly-warn:hover { + background: color-mix(in srgb, var(--metric-warn) 18%, transparent); +} + +.data-table tbody tr.is-anomaly-warn td:first-child { + box-shadow: inset 2px 0 0 var(--metric-warn); +} + +.data-table tbody tr.is-anomaly-warn td:first-child > span:not(.agent-badge):not(.turn-rail) { + color: var(--metric-warn); + font-weight: 600; +} + +.data-table tbody tr.is-anomaly-danger { + background: color-mix(in srgb, var(--metric-danger) 13%, transparent); +} + +.data-table tbody tr.is-anomaly-danger:hover { + background: color-mix(in srgb, var(--metric-danger) 20%, transparent); +} + +.data-table tbody tr.is-anomaly-danger td:first-child { + box-shadow: inset 2px 0 0 var(--metric-danger); +} + +.data-table tbody tr.is-anomaly-danger td:first-child > span:not(.agent-badge):not(.turn-rail) { + color: var(--metric-danger); + font-weight: 600; +} + +.step-anomaly-tag { + display: inline-flex; + align-items: center; + vertical-align: middle; + margin-left: 4px; + padding: 0 3.5px; + font-size: var(--fs-2xs); + font-weight: 600; + line-height: 1.35; + border-radius: 3px; + color: var(--metric-warn); + background: var(--metric-warn-soft); + border: 1px solid color-mix(in srgb, var(--metric-warn) 34%, transparent); + cursor: help; + white-space: nowrap; + flex-shrink: 0; +} + +.step-anomaly-tag.is-danger { + color: var(--metric-danger); + background: var(--metric-danger-soft); + border-color: color-mix(in srgb, var(--metric-danger) 36%, transparent); +} + +.step-anomaly-tag[hidden] { + display: none !important; +} + +.smodel-anomaly-tag { + margin-left: 0; + cursor: pointer; + font-family: inherit; + transition: + background-color var(--dur-instant) var(--ease-fast), + border-color var(--dur-instant) var(--ease-fast); +} + +.smodel-anomaly-tag:hover { + background: color-mix(in srgb, var(--metric-warn) 22%, transparent); +} + +.smodel-anomaly-tag.is-danger:hover { + background: color-mix(in srgb, var(--metric-danger) 22%, transparent); +} + +.step-anomaly-tip { + position: absolute; + z-index: 46; + max-width: min(300px, calc(100% - 16px)); + min-width: 176px; + padding: 7px 9px; + display: flex; + flex-direction: column; + gap: 5px; + font-size: var(--fs-sm); + line-height: 1.38; + color: var(--text-primary); + background: var(--surface-panel); + border: 1px solid color-mix(in srgb, var(--metric-warn) 42%, var(--border-strong)); + border-radius: var(--radius-xs); + box-shadow: var(--shadow-popover); + pointer-events: none; + animation: anim-popover-in var(--dur-instant) var(--ease-fast); +} + +.step-anomaly-tip.is-danger { + border-color: color-mix(in srgb, var(--metric-danger) 46%, var(--border-strong)); +} + +.step-anomaly-tip[hidden], +.step-anomaly-tip-sub[hidden], +.step-anomaly-tip-list[hidden], +.step-anomaly-tip-hint[hidden] { + display: none !important; +} + +.step-anomaly-tip-head { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; +} + +.step-anomaly-tip-title { + font-weight: 600; + color: var(--metric-warn); + white-space: nowrap; +} + +.step-anomaly-tip.is-danger .step-anomaly-tip-title { + color: var(--metric-danger); +} + +.step-anomaly-tip-sub { + font-size: var(--fs-xs); + color: var(--text-secondary); + white-space: nowrap; +} + +.step-anomaly-tip-list { + display: flex; + flex-direction: column; + gap: 4px; + padding-top: 4px; + border-top: 1px solid var(--border-hairline); +} + +.step-anomaly-tip-item { + display: flex; + flex-direction: column; + gap: 1px; +} + +.step-anomaly-tip-row { + font-size: var(--fs-xs); + font-weight: 500; + color: var(--text-primary); +} + +.step-anomaly-tip-row.is-danger { + color: var(--metric-danger); +} + +.step-anomaly-tip-detail { + font-size: var(--fs-2xs); + line-height: 1.35; + color: var(--text-muted); + word-break: break-word; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; + overflow: hidden; +} + +.step-anomaly-tip-hint { + font-size: var(--fs-2xs); + color: var(--text-muted); + padding-top: 3px; + border-top: 1px solid var(--border-hairline); +} + +.steps-anomaly-filterbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + padding: 4px 8px; + border-top: 1px solid var(--border-hairline); + background: color-mix(in srgb, var(--metric-warn) 8%, var(--surface-panel)); + font-size: var(--fs-xs); +} + +.steps-anomaly-filterbar[hidden] { + display: none !important; +} + +.steps-anomaly-filter-label { + font-weight: 600; + color: var(--metric-warn); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.steps-anomaly-filter-clear { + flex-shrink: 0; + padding: 1px 7px; + font-size: var(--fs-xs); +} + +.steps-anomaly-strip { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 4px 6px; + padding: 4px 8px; + border: 1px solid color-mix(in srgb, var(--metric-warn) 26%, var(--border-hairline)); + border-radius: var(--radius-xs); + background: color-mix(in srgb, var(--metric-warn) 7%, var(--surface-panel)); +} + +.steps-anomaly-strip[hidden] { + display: none !important; +} + +.steps-anomaly-strip-meta { + border: none; + background: transparent; + padding: 0; + font-size: var(--fs-xs); + font-weight: 600; + color: var(--metric-warn); + cursor: pointer; + white-space: nowrap; +} + +.steps-anomaly-strip-meta:hover { + text-decoration: underline; +} + +.steps-anomaly-strip-tags { + display: inline-flex; + align-items: center; + flex-wrap: wrap; + gap: 4px; +} + /* --- 3. 按模型汇总分析视图:双趋势图与极简模型总览 (Models Analytics Pane) --- */ .models-analytics-pane { display: flex; @@ -3419,6 +3661,47 @@ html[data-standalone="true"] .app-shell { pointer-events: none; } +.sstep-hover-raw-dot.is-anomaly { + stroke: var(--metric-warn); + stroke-width: 1.85; +} + +.sstep-hover-raw-dot.is-danger { + stroke: var(--metric-danger); +} + +.sstep-anomaly-dot, +.sstep-scatter-dot.is-anomaly { + fill: var(--surface-panel); + fill-opacity: 1; + stroke: var(--metric-warn); + stroke-width: 1.6; + pointer-events: none; +} + +.sstep-anomaly-dot.is-danger, +.sstep-scatter-dot.is-anomaly.is-danger { + stroke: var(--metric-danger); +} + +.trend-tip-anomaly { + margin-top: 3px; + padding-top: 3px; + border-top: 1px solid var(--border-hairline); + font-size: var(--fs-xs); + font-weight: 600; + color: var(--metric-warn); + white-space: nowrap; +} + +.trend-tip-anomaly.is-danger { + color: var(--metric-danger); +} + +.trend-tip-anomaly[hidden] { + display: none !important; +} + .sstep-empty-hint { position: absolute; inset: 0; @@ -5819,7 +6102,8 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { } [data-modern-ui="true"] .agent-badge, -[data-modern-ui="true"] .agent-badge.is-clickable:hover { +[data-modern-ui="true"] .agent-badge.is-clickable:hover, +[data-modern-ui="true"] .step-anomaly-tag { border: none; } @@ -5932,6 +6216,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { } [data-modern-ui="true"] .trend-tip-sub, +[data-modern-ui="true"] .trend-tip-anomaly, [data-modern-ui="true"] .cons-pop-models { border-top: none; padding-top: 3px; @@ -5992,6 +6277,28 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { background: var(--modern-surface-hover); } +[data-modern-ui="true"] .data-table tbody tr.is-anomaly-warn, +[data-modern-ui="true"] .data-table:not(.is-virtualized) tbody tr.is-anomaly-warn:nth-child(even), +[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-warn { + background: color-mix(in srgb, var(--metric-warn) 12%, transparent); +} + +[data-modern-ui="true"] .data-table tbody tr.is-anomaly-warn:hover, +[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-warn:hover { + background: color-mix(in srgb, var(--metric-warn) 19%, transparent); +} + +[data-modern-ui="true"] .data-table tbody tr.is-anomaly-danger, +[data-modern-ui="true"] .data-table:not(.is-virtualized) tbody tr.is-anomaly-danger:nth-child(even), +[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-danger { + background: color-mix(in srgb, var(--metric-danger) 14%, transparent); +} + +[data-modern-ui="true"] .data-table tbody tr.is-anomaly-danger:hover, +[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-danger:hover { + background: color-mix(in srgb, var(--metric-danger) 21%, transparent); +} + [data-modern-ui="true"] .steps-inline-scope-select .select-trigger, [data-modern-ui="true"] .steps-inline-model-select .select-trigger, [data-modern-ui="true"] .sstep-fit-model-select .select-trigger { @@ -6026,6 +6333,22 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { background: var(--accent-primary-soft); } +[data-modern-ui="true"] .steps-anomaly-filterbar, +[data-modern-ui="true"] .steps-anomaly-strip { + border: none; + border-radius: var(--radius-xs); + background: var(--metric-warn-soft); +} + +[data-modern-ui="true"] .steps-anomaly-filterbar { + margin: 4px 2px 2px; +} + +[data-modern-ui="true"] .sstep-anomaly-dot, +[data-modern-ui="true"] .sstep-scatter-dot.is-anomaly { + fill: var(--modern-surface-card); +} + /* --- 6. 设置表单、折叠面板、槽位排序与输入控件去边框 --- */ [data-modern-ui="true"] .collapsible-body, [data-modern-ui="true"] .settings-action-block + .settings-action-block, @@ -6106,13 +6429,19 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { [data-modern-ui="true"] .trend-tooltip, [data-modern-ui="true"] .cons-breakdown-popover, -[data-modern-ui="true"] .turn-prompt-tip { +[data-modern-ui="true"] .turn-prompt-tip, +[data-modern-ui="true"] .step-anomaly-tip { border: none; background: var(--modern-surface-card); box-shadow: var(--shadow-popover); animation: anim-modern-tip-fade 150ms var(--ease-modern); } +[data-modern-ui="true"] .step-anomaly-tip-list, +[data-modern-ui="true"] .step-anomaly-tip-hint { + border-top-color: var(--modern-surface-hover); +} + [data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom) { top: 2px; bottom: auto; @@ -6216,10 +6545,18 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { [data-modern-ui="true"] .wm-multi-label[data-od-active="1"] { display: inline-flex; align-items: center; + justify-content: center; height: 18px; line-height: 18px; } +:host([data-modern-ui="true"]) .wm-slot-text.wm-ctx-pct[data-od-active="1"], +:host([data-modern-ui="true"]) .wm-multi-label[data-od-active="1"], +[data-modern-ui="true"] .wm-slot-text.wm-ctx-pct[data-od-active="1"], +[data-modern-ui="true"] .wm-multi-label[data-od-active="1"] { + justify-content: flex-start; +} + :host([data-modern-ui="true"]) .wm-od-digit, [data-modern-ui="true"] .wm-od-digit { display: inline-block; diff --git a/sidecars/panel/test/step-anomalies.test.mjs b/sidecars/panel/test/step-anomalies.test.mjs new file mode 100644 index 0000000..9a9d933 --- /dev/null +++ b/sidecars/panel/test/step-anomalies.test.mjs @@ -0,0 +1,782 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { readLocalSqliteTrajectory } from '../backend/cli-sqlite-reader.mjs'; +import { classifyStepAnomalyError, extractModelSteps } from '../trajectory-metrics.mjs'; +import { buildScopedModelBreakdown } from '../backend/usage-aggregator.mjs'; +import { createMockDom } from './mock-dom.mjs'; +import { i18nStore } from '../src/i18n/index.js'; +import { + buildModelAnomalyDiagnostic, + buildStepAnomalyDiagnostic, + formatAnomalyTagText, + formatSpeedMetric, +} from '../src/core/formatters.js'; +import { STEP_COLUMN_REGISTRY } from '../src/registries/stepColumnRegistry.js'; +import { StepTableWidget } from '../src/components/widgets/StepTableWidget.js'; +import { + createModelFitChart, + createSessionLineChart, +} from '../src/components/charts/SessionStepCharts.js'; +import { StepsDetailView } from '../src/views/StepsDetailView.js'; +import { telemetryStore } from '../src/store/telemetryStore.js'; +import { uiStore } from '../src/store/uiStore.js'; + +function encodeVarint(val) { + let v = BigInt(val); + if (v < 0n) v = BigInt.asUintN(64, v); + const out = []; + while (v >= 0x80n) { + out.push(Number((v & 0x7fn) | 0x80n)); + v >>= 7n; + } + out.push(Number(v)); + return Buffer.from(out); +} + +function encodeFieldVarint(fieldNo, val) { + return Buffer.concat([encodeVarint((fieldNo << 3) | 0), encodeVarint(val)]); +} + +function encodeFieldBytes(fieldNo, bufOrStr) { + const b = Buffer.isBuffer(bufOrStr) ? bufOrStr : Buffer.from(String(bufOrStr), 'utf8'); + return Buffer.concat([encodeVarint((fieldNo << 3) | 2), encodeVarint(b.length), b]); +} + +function encodeTimestamp(sec, nanos = 0) { + return Buffer.concat([encodeFieldVarint(1, sec), ...(nanos ? [encodeFieldVarint(2, nanos)] : [])]); +} + +function encodeRetryInfo({ error = '', reasonCode = 1, delaySec = 0, delayNanos = 0 } = {}) { + const parts = []; + if (error) parts.push(encodeFieldBytes(3, error)); + if (reasonCode) parts.push(encodeFieldVarint(5, reasonCode)); + if (delaySec || delayNanos) { + parts.push(encodeFieldBytes(7, encodeTimestamp(delaySec, delayNanos))); + } + return Buffer.concat(parts); +} + +function encodeStepMeta({ + createdSec, + finishedSec, + stepIndex, + modelEnumInt = 0, + inputTokens = 0, + cacheReadTokens = 0, + outputTokens = 0, + retryInfos = [], +}) { + const parts = [encodeFieldBytes(1, encodeTimestamp(createdSec))]; + if (finishedSec) parts.push(encodeFieldBytes(7, encodeTimestamp(finishedSec))); + if (modelEnumInt || inputTokens || cacheReadTokens || outputTokens) { + const muParts = []; + if (modelEnumInt) muParts.push(encodeFieldVarint(1, modelEnumInt)); + if (inputTokens) muParts.push(encodeFieldVarint(2, inputTokens)); + if (outputTokens) muParts.push(encodeFieldVarint(3, outputTokens)); + if (cacheReadTokens) muParts.push(encodeFieldVarint(5, cacheReadTokens)); + muParts.push(encodeFieldVarint(6, 24)); + parts.push(encodeFieldBytes(9, Buffer.concat(muParts))); + } + parts.push(encodeFieldBytes(20, encodeFieldVarint(2, stepIndex))); + for (const ri of retryInfos) { + parts.push(encodeFieldBytes(28, encodeRetryInfo(ri))); + } + return Buffer.concat(parts); +} + +function encodeErrorMessagePayload({ + userErrorMessage = '', + shortError = '', + errorCode = '', + shouldShowModel = false, + shouldShowUser = false, +}) { + const errParts = []; + if (userErrorMessage) errParts.push(encodeFieldBytes(1, userErrorMessage)); + if (shortError) errParts.push(encodeFieldBytes(2, shortError)); + if (errorCode) errParts.push(encodeFieldBytes(7, errorCode)); + const inner = [encodeFieldBytes(3, Buffer.concat(errParts))]; + if (shouldShowModel) inner.push(encodeFieldVarint(4, 1)); + if (shouldShowUser) inner.push(encodeFieldVarint(5, 1)); + return encodeFieldBytes(24, Buffer.concat(inner)); +} + +function encodeGenMeta({ + stepIndex, + cascadeId, + responseModel, + modelDisplayName, + retryCount = 0, + retryInfos = [], +}) { + const mapCascade = Buffer.concat([ + encodeFieldBytes(1, 'cascade_id'), + encodeFieldBytes(2, cascadeId), + ]); + const chatParts = [ + encodeFieldBytes(11, encodeTimestamp(1, 0)), + encodeFieldBytes(19, responseModel), + encodeFieldBytes(20, mapCascade), + encodeFieldBytes(21, modelDisplayName), + ]; + if (retryCount > 0) chatParts.push(encodeFieldVarint(14, retryCount)); + for (const ri of retryInfos) { + chatParts.push(encodeFieldBytes(17, encodeRetryInfo(ri))); + } + return Buffer.concat([ + encodeFieldVarint(2, stepIndex), + encodeFieldBytes(1, Buffer.concat(chatParts)), + ]); +} + +function installMockBrowser() { + const prevDoc = globalThis.document; + const prevWin = globalThis.window; + const prevRaf = globalThis.requestAnimationFrame; + const prevCaf = globalThis.cancelAnimationFrame; + const prevResizeObs = globalThis.ResizeObserver; + const { document } = createMockDom(); + globalThis.document = document; + globalThis.window = { + innerWidth: 960, + innerHeight: 720, + getComputedStyle: () => ({ getPropertyValue: () => '' }), + addEventListener: () => {}, + removeEventListener: () => {}, + }; + globalThis.requestAnimationFrame = (fn) => { + fn(); + return 1; + }; + globalThis.cancelAnimationFrame = () => {}; + globalThis.ResizeObserver = class { + observe() {} + disconnect() {} + }; + return { + document, + restore() { + globalThis.document = prevDoc; + globalThis.window = prevWin; + globalThis.requestAnimationFrame = prevRaf; + globalThis.cancelAnimationFrame = prevCaf; + globalThis.ResizeObserver = prevResizeObs; + }, + }; +} + +test('SQLite protobuf decoder + trajectory-metrics + usage-aggregator decode chatModel retries, checkpoint retries, deduplicated ERROR_MESSAGE, and trailing terminal errors', (t) => { + const sqliteMod = + typeof process.getBuiltinModule === 'function' ? process.getBuiltinModule('node:sqlite') : null; + if (!sqliteMod?.DatabaseSync) { + t.skip('node:sqlite DatabaseSync unavailable'); + return; + } + const { DatabaseSync } = sqliteMod; + const tempRoot = mkdtempSync(join(tmpdir(), 'agy-anomaly-sqlite-')); + t.after(() => rmSync(tempRoot, { recursive: true, force: true })); + + const cid = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'; + const dbPath = join(tempRoot, `${cid}.db`); + const db = new DatabaseSync(dbPath); + db.exec(` + CREATE TABLE trajectory_meta (trajectory_id TEXT, cascade_id TEXT, trajectory_type INTEGER, source INTEGER); + CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, metadata BLOB, step_payload BLOB); + CREATE TABLE gen_metadata (idx INTEGER PRIMARY KEY, data BLOB); + `); + db.prepare('INSERT INTO trajectory_meta VALUES (?, ?, 1, 1)').run(cid, cid); + + const baseSec = 1794960000; + // Step 0: USER_INPUT (step_type=14) + db.prepare('INSERT INTO steps VALUES (0, 14, 3, ?, ?)').run( + encodeStepMeta({ createdSec: baseSec, finishedSec: baseSec, stepIndex: 0 }), + encodeFieldBytes(19, encodeFieldBytes(2, '帮我排查超时')) + ); + // Step 1: Normal model response (zero anomalies) + db.prepare('INSERT INTO steps VALUES (1, 15, 3, ?, ?)').run( + encodeStepMeta({ + createdSec: baseSec + 1, + finishedSec: baseSec + 3, + stepIndex: 1, + modelEnumInt: 1035, + inputTokens: 500, + cacheReadTokens: 2000, + outputTokens: 260, + }), + encodeFieldBytes(20, encodeFieldBytes(1, 'ok')) + ); + db.prepare('INSERT INTO gen_metadata VALUES (0, ?)').run( + encodeGenMeta({ + stepIndex: 1, + cascadeId: cid, + responseModel: 'gemini-3-flash', + modelDisplayName: 'Gemini 3 Flash', + }) + ); + + // Step 2: Preceding ERROR_MESSAGE (duplicate of retryInfo capacity 503) — should be deduplicated against step 3 retryInfos + db.prepare('INSERT INTO steps VALUES (2, 17, 3, ?, ?)').run( + encodeStepMeta({ createdSec: baseSec + 4, finishedSec: baseSec + 4, stepIndex: 2 }), + encodeErrorMessagePayload({ + shortError: 'HTTP 503 No capacity available for model', + errorCode: 'UNAVAILABLE', + shouldShowUser: false, + }) + ); + // Step 3: Retried model response with 2 retryInfos (timeout 2.5s + capacity 5s) + db.prepare('INSERT INTO steps VALUES (3, 15, 3, ?, ?)').run( + encodeStepMeta({ + createdSec: baseSec + 5, + finishedSec: baseSec + 15, + stepIndex: 3, + modelEnumInt: 1035, + inputTokens: 600, + cacheReadTokens: 3000, + outputTokens: 300, + }), + encodeFieldBytes(20, encodeFieldBytes(1, 'retried ok')) + ); + db.prepare('INSERT INTO gen_metadata VALUES (1, ?)').run( + encodeGenMeta({ + stepIndex: 3, + cascadeId: cid, + responseModel: 'gemini-3-flash', + modelDisplayName: 'Gemini 3 Flash', + retryCount: 2, + retryInfos: [ + { + error: 'stream idle timeout: no data received for 60s', + reasonCode: 1, + delaySec: 2, + delayNanos: 500_000_000, + }, + { + error: 'HTTP 503 No capacity available for model', + reasonCode: 1, + delaySec: 5, + }, + ], + }) + ); + + // Step 4: CHECKPOINT (step_type=18) with metadata.fn=28 retryInfo (model_output) + db.prepare('INSERT INTO steps VALUES (4, 18, 3, ?, NULL)').run( + encodeStepMeta({ + createdSec: baseSec + 16, + finishedSec: baseSec + 19, + stepIndex: 4, + modelEnumInt: 1035, + inputTokens: 400, + outputTokens: 120, + retryInfos: [ + { + error: 'invalid tool call arguments JSON', + reasonCode: 2, + delaySec: 1, + }, + ], + }) + ); + + // Step 5: Model step followed by turn-ending terminal ERROR_MESSAGE (status=7 CORTEX_STEP_STATUS_ERROR) + db.prepare('INSERT INTO steps VALUES (5, 15, 7, ?, ?)').run( + encodeStepMeta({ + createdSec: baseSec + 20, + finishedSec: baseSec + 25, + stepIndex: 5, + modelEnumInt: 1035, + inputTokens: 200, + outputTokens: 0, + }), + encodeFieldBytes(20, encodeFieldBytes(1, '')) + ); + db.prepare('INSERT INTO gen_metadata VALUES (2, ?)').run( + encodeGenMeta({ + stepIndex: 5, + cascadeId: cid, + responseModel: 'gemini-3-pro', + modelDisplayName: 'Gemini 3 Pro', + }) + ); + // Step 6: Trailing terminal ERROR_MESSAGE (should attach to step 5) + db.prepare('INSERT INTO steps VALUES (6, 17, 3, ?, ?)').run( + encodeStepMeta({ createdSec: baseSec + 25, finishedSec: baseSec + 25, stepIndex: 6 }), + encodeErrorMessagePayload({ + userErrorMessage: 'TLS handshake timeout while reaching upstream', + shortError: 'dial tcp: TLS handshake timeout', + errorCode: 'DEADLINE_EXCEEDED', + shouldShowUser: true, + }) + ); + db.close(); + + const traj = readLocalSqliteTrajectory(dbPath); + assert.ok(traj, 'SQLite trajectory decoded'); + const gen1 = traj.generatorMetadata.find((g) => g.stepIndices?.includes(3)); + assert.equal(gen1?.chatModel?.retryCount, 2); + assert.equal(gen1?.chatModel?.retryInfos?.length, 2); + assert.equal(gen1?.chatModel?.retryInfos?.[0]?.retryDelay, '2.5s'); + assert.equal(traj.steps[4]?.metadata?.retryInfos?.length, 1); + assert.equal(traj.steps[6]?.errorMessage?.shouldShowUser, true); + assert.match(traj.steps[6]?.errorMessage?.error?.userErrorMessage || '', /TLS handshake timeout/); + + const extracted = extractModelSteps(traj.steps, traj.generatorMetadata); + const s1 = extracted.find((s) => s.stepIndex === 1); + const s3 = extracted.find((s) => s.stepIndex === 3); + const s4 = extracted.find((s) => s.stepIndex === 4); + const s5 = extracted.find((s) => s.stepIndex === 5); + + assert.equal(s1.anomaly, undefined, 'Normal step carries zero anomaly payload'); + assert.equal(s1.anomalySig, undefined, 'Normal step omits anomalySig'); + + assert.ok(s3.anomaly, 'Step 3 has anomaly record'); + assert.equal(s3.anomaly.count, 2, 'Duplicate preceding 503 ERROR_MESSAGE is deduplicated against retryInfos'); + assert.equal(s3.anomaly.totalDelaySec, 7.5); + assert.equal(s3.anomaly.kinds.timeout, 1); + assert.equal(s3.anomaly.kinds.capacity, 1); + assert.equal(s3.anomaly.severity, 'warn'); + + assert.ok(s4.anomaly, 'Checkpoint step 4 decodes metadata.fn=28 retryInfo'); + assert.equal(s4.anomaly.primaryKind, 'model_output'); + assert.equal(s4.anomaly.count, 1); + + assert.ok(s5.anomaly, 'Trailing turn-ending ERROR_MESSAGE attaches to step 5'); + assert.equal(s5.anomaly.primaryKind, 'timeout'); + assert.equal(s5.anomaly.severity, 'danger', 'Terminal error escalates severity to danger'); + assert.equal(s5.anomaly.events[0]?.terminal, true); + assert.equal(s5.speedReason, 'error'); + assert.equal(s5.totalTokPerSec, null); + + // Also check classifyStepAnomalyError directly for rate_limit & safety + assert.equal(classifyStepAnomalyError('HTTP 429 RESOURCE_EXHAUSTED quota exceeded'), 'rate_limit'); + assert.equal(classifyStepAnomalyError('blocked by safety filter policy'), 'safety'); + + const breakdown = buildScopedModelBreakdown(extracted, (st) => ({ + label: st.responseModel || 'Unknown', + shortName: st.responseModel || 'Unknown', + rawModel: st.model || '', + upstreamName: st.responseModel || '', + costUsd: 0.01, + })); + const flash = breakdown.find((m) => m.label === 'gemini-3-flash'); + const pro = breakdown.find((m) => m.label === 'gemini-3-pro'); + assert.ok(flash && pro); + assert.equal(flash.anomalySteps, 1); + assert.equal(flash.anomalyCount, 2); + assert.equal(flash.anomalyTotalDelaySec, 7.5); + assert.equal(pro.anomalySteps, 1); + assert.equal(pro.anomalyCount, 1); + assert.equal(pro.anomalyDangerCount, 1); + assert.equal(pro.anomalyByKind.timeout, 1); +}); + +test('formatSpeedMetric drops decimals at >= 100 tok/s and STEP_COLUMN_REGISTRY.tps renders integer speeds and error reasons', () => { + const env = installMockBrowser(); + try { + i18nStore.setState({ locale: 'zh-CN' }); + + assert.equal(formatSpeedMetric(100), '100 tok/s'); + assert.equal(formatSpeedMetric(128.4), '128 tok/s'); + assert.equal(formatSpeedMetric(145.6), '146 tok/s'); + assert.equal(formatSpeedMetric(99.9), '99.9 tok/s'); + assert.equal(formatSpeedMetric(65.7), '65.7 tok/s'); + assert.equal(formatSpeedMetric(0), '0.0 tok/s'); + assert.equal(formatSpeedMetric(null), '—'); + + const fastCell = STEP_COLUMN_REGISTRY.tps.createCell(); + STEP_COLUMN_REGISTRY.tps.updateCell(fastCell.refs, { tokPerSec: 128.4 }, { showStepSpeedColor: false }); + assert.equal(fastCell.refs.speedMain.textContent, '128 tok/s'); + + STEP_COLUMN_REGISTRY.tps.updateCell(fastCell.refs, { tokPerSec: 65.7 }, { showStepSpeedColor: false }); + assert.equal(fastCell.refs.speedMain.textContent, '65.7 tok/s'); + + STEP_COLUMN_REGISTRY.tps.updateCell( + fastCell.refs, + { tokPerSec: null, selectedSpeedReason: 'error' }, + { showStepSpeedColor: false } + ); + assert.equal(fastCell.refs.speedMain.textContent, '—'); + assert.equal(fastCell.refs.speedReason.textContent, '调用报错'); + } finally { + env.restore(); + } +}); + +test('StepTableWidget tints entire anomaly rows with zero extra column width and reveals full diagnostic popover on row hover', () => { + const env = installMockBrowser(); + const widget = StepTableWidget({ standalone: true }); + try { + i18nStore.setState({ locale: 'zh-CN' }); + + const colKeys = ['step', 'model', 'tps', 'ttft']; + const steps = [ + { + stepIndex: 4924, + modelShort: '4-neon', + modelLabel: '4-neon', + tokPerSec: 132.6, + ttftSec: 2.1, + anomalySig: 'timeout:1:w:2.5', + anomaly: { + count: 1, + primaryKind: 'timeout', + severity: 'warn', + totalDelaySec: 2.5, + kinds: { timeout: 1 }, + events: [ + { + attempt: 1, + kind: 'timeout', + delaySec: 2.5, + terminal: false, + message: 'stream idle timeout: no data received', + }, + ], + }, + }, + { + stepIndex: 4922, + modelShort: '4-neon', + modelLabel: '4-neon', + tokPerSec: null, + selectedSpeedReason: 'error', + ttftSec: null, + anomalySig: 'rate_limit:1:d:0', + anomaly: { + count: 1, + primaryKind: 'rate_limit', + severity: 'danger', + totalDelaySec: 0, + kinds: { rate_limit: 1 }, + events: [ + { + attempt: 1, + kind: 'rate_limit', + delaySec: 0, + terminal: true, + message: 'HTTP 429 RESOURCE_EXHAUSTED', + }, + ], + }, + }, + { + stepIndex: 4920, + modelShort: '4-neon', + modelLabel: '4-neon', + tokPerSec: 65.7, + ttftSec: 1.4, + anomalySig: '', + }, + ]; + + widget.refs.renderStepTable(steps, 'cid-1', colKeys, 'zh-CN', { + hasSubagents: false, + showStepAgentBadge: true, + showStepTurnRail: false, + }); + + // Zero extra columns and zero inline text badges added to table cells + assert.equal(widget.refs.stepsTheadRow.children.length, colKeys.length); + const rows = widget.refs.stepsTbody.children; + assert.equal(rows.length, 3); + assert.equal(rows[0].children.length, colKeys.length); + assert.equal(rows[0].querySelector('.step-anomaly-tag'), null, 'No inline tag widening the #step column'); + + // Row 0: warn tint (orange) + integer speed 133 tok/s + assert.equal(rows[0].classList.contains('is-anomaly-warn'), true); + assert.equal(rows[0].classList.contains('is-anomaly-danger'), false); + assert.equal(rows[0].children[2].textContent, '133 tok/s'); + + // Row 1: danger tint (red) + assert.equal(rows[1].classList.contains('is-anomaly-danger'), true); + assert.equal(rows[1].classList.contains('is-anomaly-warn'), false); + + // Row 2: normal step has NO anomaly row classes and keeps 1 decimal < 100 tok/s + assert.equal(rows[2].classList.contains('is-anomaly-warn'), false); + assert.equal(rows[2].classList.contains('is-anomaly-danger'), false); + assert.equal(rows[2].children[2].textContent, '65.7 tok/s'); + + // Hovering the tinted row expands the structured diagnostic popover + const tipEl = widget.refs.anomalyTipEl; + assert.equal(tipEl.hasAttribute('hidden'), true); + rows[0].onmouseenter(); + assert.equal(tipEl.hasAttribute('hidden'), false); + assert.match(tipEl.querySelector('.step-anomaly-tip-title').textContent, /#4924.*异常 1 次/); + assert.equal(tipEl.querySelector('.step-anomaly-tip-sub').textContent, '退避 2.5s'); + assert.match(tipEl.querySelector('.step-anomaly-tip-detail').textContent, /stream idle timeout/); + + rows[0].onmouseleave(); + assert.equal(tipEl.hasAttribute('hidden'), true); + + // Hovering danger row sets danger style on tooltip + rows[1].onmouseenter(); + assert.equal(tipEl.hasAttribute('hidden'), false); + assert.equal(tipEl.classList.contains('is-danger'), true); + assert.match(tipEl.querySelector('.step-anomaly-tip-detail').textContent, /429 RESOURCE_EXHAUSTED/); + rows[1].onmouseleave(); + assert.equal(tipEl.hasAttribute('hidden'), true); + + // Verify helper outputs cleanly + assert.equal(formatAnomalyTagText('capacity', 1), '503'); + assert.equal(formatAnomalyTagText('capacity', 3), '503×3'); + assert.ok(buildStepAnomalyDiagnostic(steps[0])); + assert.equal(buildStepAnomalyDiagnostic(steps[2]), null); + } finally { + widget.destroy(); + env.restore(); + } +}); + +test('StepsDetailView total summary cards, session anomaly strip, click-to-filter jump, and line/fit chart anomaly markers & hover tooltips work across UI modes', async () => { + const env = installMockBrowser(); + const prevUi = uiStore.getState(); + const prevTel = telemetryStore.getState(); + let view = null; + let lineChart = null; + let fitChart = null; + try { + i18nStore.setState({ locale: 'zh-CN' }); + view = StepsDetailView(); + + const anomalyObj = { + count: 2, + primaryKind: 'timeout', + severity: 'danger', + totalDelaySec: 4.5, + kinds: { timeout: 2 }, + events: [ + { attempt: 1, kind: 'timeout', delaySec: 2, terminal: false, message: 'idle timeout #1' }, + { attempt: 2, kind: 'timeout', delaySec: 2.5, terminal: true, message: 'TLS handshake timeout' }, + ], + }; + + const recentSteps = [ + { + stepIndex: 10, + createdAtMs: 1794960100000, + modelLabel: 'Gemini 3 Pro', + modelShort: '3-pro', + tokPerSec: 120.4, + ttftSec: 1.5, + inputTokens: 1000, + cacheReadTokens: 4000, + outputTokens: 300, + thinkingTokens: 100, + responseTokens: 200, + contextTokens: 5300, + cacheHitPct: 80, + costUsd: 0.02, + anomalySig: 'timeout:2:d:4.5', + anomaly: anomalyObj, + }, + { + stepIndex: 9, + createdAtMs: 1794960050000, + modelLabel: 'Gemini 3 Flash', + modelShort: '3-flash', + tokPerSec: 88.2, + ttftSec: 0.9, + inputTokens: 500, + cacheReadTokens: 2000, + outputTokens: 150, + thinkingTokens: 50, + responseTokens: 100, + contextTokens: 2650, + cacheHitPct: 80, + costUsd: 0.005, + anomalySig: '', + }, + ]; + + const modelBreakdown = [ + { + label: 'Gemini 3 Pro', + shortName: '3-pro', + calls: 1, + inputTokens: 1000, + cacheReadTokens: 4000, + outputTokens: 300, + thinkingTokens: 100, + responseTokens: 200, + totalTokens: 5300, + costUsd: 0.02, + avgTokPerSec: 120.4, + avgTtftSec: 1.5, + cacheHitPct: 80, + anomalySteps: 1, + anomalyCount: 2, + anomalyDangerCount: 1, + anomalyTotalDelaySec: 4.5, + anomalyByKind: { timeout: 2 }, + }, + { + label: 'Gemini 3 Flash', + shortName: '3-flash', + calls: 1, + inputTokens: 500, + cacheReadTokens: 2000, + outputTokens: 150, + thinkingTokens: 50, + responseTokens: 100, + totalTokens: 2650, + costUsd: 0.005, + avgTokPerSec: 88.2, + avgTtftSec: 0.9, + cacheHitPct: 80, + }, + ]; + + uiStore.setState({ + monitorVisible: true, + activeView: 'steps', + stepsSubTab: 'models', + selectedAgentScope: 'all', + }); + telemetryStore.setState({ + telemetry: { + settings: { + stepTableColumns: ['step', 'model', 'tps', 'ttft'], + experimentalModernUi: false, + }, + activeConversation: { + cascadeId: 'cid-summary-test', + recentSteps, + modelBreakdown, + }, + }, + }); + await Promise.resolve(); + + // Session-level anomaly strip is visible with timeout tag + const stripEl = view.refs.modelsAnomalyStripEl; + assert.equal(stripEl.hasAttribute('hidden'), false); + assert.match(stripEl.textContent, /异常 2 次.*1 步/); + + // Model summary cards: Pro shows danger anomaly badge + integer 120 tok/s; Flash hides badge + keeps 88.2 tok/s + const cards = view.refs.modelsListEl.querySelectorAll('.smodel-card'); + assert.equal(cards.length, 2); + const proBadge = cards[0].querySelector('.smodel-anomaly-tag'); + const flashBadge = cards[1].querySelector('.smodel-anomaly-tag'); + assert.equal(proBadge.hasAttribute('hidden'), false); + assert.equal(proBadge.textContent, '超时2'); + assert.equal(proBadge.classList.contains('is-danger'), true); + assert.match(cards[0].querySelector('.smodel-perf').textContent, /120 tok\/s/); + assert.equal(flashBadge.hasAttribute('hidden'), true); + assert.match(cards[1].querySelector('.smodel-perf').textContent, /88\.2 tok\/s/); + + // Hovering model card anomaly badge opens diagnostic popover with click hint + const modelDiag = buildModelAnomalyDiagnostic(modelBreakdown[0]); + assert.ok(modelDiag && modelDiag.hint); + proBadge.onmouseenter(); + assert.equal(view.refs.anomalyTipEl.hasAttribute('hidden'), false); + assert.match(view.refs.anomalyTipEl.querySelector('.step-anomaly-tip-hint').textContent, /按步查看/); + proBadge.onmouseleave(); + assert.equal(view.refs.anomalyTipEl.hasAttribute('hidden'), true); + + // Clicking model card anomaly badge jumps to 'steps', activates anomaly filterbar, and filters to only anomaly step #10 + proBadge.onclick({ stopPropagation() {} }); + await Promise.resolve(); + assert.equal(uiStore.getState().stepsSubTab, 'steps'); + assert.equal(view.refs.anomalyFilterBarEl.hasAttribute('hidden'), false); + assert.equal(view.refs.stepsTbody.children.length, 1); + assert.match(view.refs.stepsTbody.children[0].children[0].textContent, /#10/); + + // Clicking "返回全部步骤" restores all rows and hides the filterbar + view.refs.anomalyFilterBarEl + .querySelector('.steps-anomaly-filter-clear') + .dispatchEvent({ type: 'click', stopPropagation() {} }); + assert.equal(view.refs.anomalyFilterBarEl.hasAttribute('hidden'), true); + assert.equal(view.refs.stepsTbody.children.length, 1); + + // Switch back to 'models' and click a session-level anomaly strip category pill -> jumps to 'steps' filtered by kind + uiStore.setState({ stepsSubTab: 'models' }); + await Promise.resolve(); + const stripTagBtn = stripEl.querySelector('.smodel-anomaly-tag'); + assert.ok(stripTagBtn, 'Session anomaly strip renders clickable category micro-tag'); + assert.equal(stripTagBtn.textContent, '超时2'); + stripTagBtn.dispatchEvent({ type: 'click', stopPropagation() {} }); + await Promise.resolve(); + assert.equal(uiStore.getState().stepsSubTab, 'steps'); + assert.equal(view.refs.anomalyFilterBarEl.hasAttribute('hidden'), false); + assert.match(view.refs.anomalyFilterBarEl.textContent, /流空闲 \/ 连接超时/); + assert.equal(view.refs.stepsTbody.children.length, 1); + + // Line chart (>64 points still renders anomaly ring overlay!) and Fit chart scatter anomaly overlay + hover tooltip linkage + const manySteps = Array.from({ length: 70 }, (_, idx) => ({ + stepIndex: idx + 1, + createdAtMs: 1794960000000 + idx * 1000, + modelLabel: 'Gemini 3 Pro', + modelShort: '3-pro', + tokPerSec: 90 + (idx % 25), + ttftSec: 1.2, + inputTokens: 1000, + cacheReadTokens: 3000, + outputTokens: 200, + contextTokens: 4200, + cacheHitPct: 75, + costUsd: 0.01, + ...(idx === 35 ? { anomalySig: 'timeout:2:d:4.5', anomaly: anomalyObj } : { anomalySig: '' }), + })); + + lineChart = createSessionLineChart(); + lineChart.update({ + steps: manySteps, + modelGroupKey: '__all__', + modelGroupKeys: ['__all__'], + metric: 'tps', + }); + const lineAnomalyDots = lineChart.el.querySelectorAll('.sstep-anomaly-dot'); + assert.equal(lineAnomalyDots.length, 1, 'Line chart renders anomaly ring marker even when steps > 64'); + assert.equal(lineAnomalyDots[0].classList.contains('is-danger'), true); + + fitChart = createModelFitChart(); + fitChart.update({ + steps: manySteps, + modelGroupKey: 'Gemini 3 Pro', + modelGroupKeys: ['Gemini 3 Pro'], + metric: 'tps', + }); + const fitAnomalyDots = fitChart.el.querySelectorAll('.sstep-scatter-dot.is-anomaly'); + assert.equal(fitAnomalyDots.length, 1, 'Fit scatter chart renders anomaly ring overlay without overdraw drop'); + assert.equal(fitAnomalyDots[0].classList.contains('is-danger'), true); + assert.ok(fitChart.el.querySelector('.trend-tip-anomaly'), 'Fit chart tooltip mounts linked anomaly diagnostic row'); + } finally { + lineChart?.destroy?.(); + fitChart?.destroy?.(); + view?.destroy?.(); + uiStore.setState(prevUi); + telemetryStore.setState(prevTel); + env.restore(); + } +}); + +test('Compiled styles.css centers odometer capsule slot text and ships both classic & modern-ui anomaly styles', () => { + const builtCss = readFileSync(new URL('../styles.css', import.meta.url), 'utf8'); + + // Capsule bar alignment fix: centered by default for fixed-width slots, flex-start for ctx-pct and multi-label + assert.match( + builtCss, + /\.wm-slot-text\[data-od-active="1"\][\s\S]*?justify-content:\s*center;/, + 'Odometer active slot text centers horizontally inside fixed-width capsule slots' + ); + assert.match( + builtCss, + /\.wm-slot-text\.wm-ctx-pct\[data-od-active="1"\][\s\S]*?justify-content:\s*flex-start;/, + 'Context percentage slot stays left-aligned next to its progress ring' + ); + + // Universal Classic + Modern UI anomaly styling + assert.match(builtCss, /tr\.is-anomaly-warn\s*\{/); + assert.match(builtCss, /tr\.is-anomaly-danger\s*\{/); + assert.match(builtCss, /\[data-modern-ui="true"\][\s\S]*?tr\.is-anomaly-warn/); + assert.match(builtCss, /\.step-anomaly-tag\s*\{/); + assert.match(builtCss, /\.step-anomaly-tip\s*\{/); + assert.match(builtCss, /\.steps-anomaly-strip\s*\{/); + assert.match(builtCss, /\.steps-anomaly-filterbar\s*\{/); + assert.match(builtCss, /\.sstep-anomaly-dot/); + assert.match(builtCss, /\.trend-tip-anomaly/); + assert.match(builtCss, /\[data-modern-ui="true"\]\s*\.step-anomaly-tip/); +}); diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index 4dd279d..6b9ea45 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -2474,7 +2474,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro smodelCards = modelsAnalyticsPane.querySelectorAll('.smodel-card'); assert.equal(smodelCards.length, 1, 'Scoped to subagent #1 model only'); assert.equal(smodelCards[0].querySelector('.smodel-name').textContent, 'gemini-3-flash'); - assert.match(fitCard.querySelector('.cons-badge').textContent, /^1步 · 均 145\.0 tok\/s$/); + assert.match(fitCard.querySelector('.cons-badge').textContent, /^1步 · 均 145 tok\/s$/); assert.equal( lineModelSelectEl.hasAttribute('hidden'), true, diff --git a/sidecars/panel/trajectory-metrics.mjs b/sidecars/panel/trajectory-metrics.mjs index cfa0cdf..0f80bb5 100644 --- a/sidecars/panel/trajectory-metrics.mjs +++ b/sidecars/panel/trajectory-metrics.mjs @@ -597,6 +597,260 @@ export function extractContextBreakdown(chat) { }; } +const ANOMALY_SEVERITY_PRIORITY = Object.freeze({ + rate_limit: 9, + auth_or_model: 8, + timeout: 7, + capacity: 6, + disconnect: 5, + upstream: 4, + model_output: 3, + safety: 2, + error: 1, + canceled: 0, +}); + +/** + * 将模型调用重试、超时或错误文本归类为标准化异常类型。 + * + * @param {string} [rawError=''] + * @param {{ reasonCode?: number, errorCode?: number, isCanceled?: boolean }} [opts] + * @returns {'timeout'|'rate_limit'|'capacity'|'disconnect'|'upstream'|'model_output'|'safety'|'auth_or_model'|'canceled'|'error'} + */ +export function classifyStepAnomalyError( + rawError = '', + { reasonCode = 0, errorCode = 0, isCanceled = false } = {} +) { + const s = String(rawError || '').trim(); + if (isCanceled || /context canceled by user|stream reading error:\s*context canceled/i.test(s)) { + return 'canceled'; + } + if (reasonCode === 2 || /model output error|model produced invalid output|invalid tool call/i.test(s)) { + return 'model_output'; + } + if ( + errorCode === 429 || + /\b429\b|RESOURCE_EXHAUSTED|quota reached|rate.?limit/i.test(s) + ) { + return 'rate_limit'; + } + if ( + /stream idle timeout|TLS handshake timeout|i\/o timeout|context deadline exceeded|\btimeout\b/i.test( + s + ) + ) { + return 'timeout'; + } + if ( + errorCode === 503 || + /\b503\b|UNAVAILABLE|No capacity available|overloaded|high demand/i.test(s) + ) { + return 'capacity'; + } + if ( + /wsarecv|wsasend|forcibly closed|connection reset|broken pipe|ECONNRESET|unexpected EOF|:\s*EOF\b|The stream was interrupted|no such host|dial tcp|tls:|bad record MAC/i.test( + s + ) + ) { + return 'disconnect'; + } + if (/safety filter|content safety|sensitive words/i.test(s)) { + return 'safety'; + } + if ( + errorCode === 500 || + errorCode === 502 || + errorCode === 504 || + /\b(?:500|502|504)\b|\bINTERNAL\b|BAD_GATEWAY/i.test(s) + ) { + return 'upstream'; + } + if ( + errorCode === 400 || + errorCode === 401 || + errorCode === 403 || + errorCode === 404 || + /\b(?:400|401|403|404)\b|PERMISSION_DENIED|UNAUTHENTICATED|FAILED_PRECONDITION|NOT_FOUND|unknown model|unsupported mime/i.test( + s + ) + ) { + return 'auth_or_model'; + } + return 'error'; +} + +function cleanAnomalyErrorExcerpt(rawText) { + let s = String(rawText || '') + .replace(/\s+/g, ' ') + .trim(); + if (!s) return ''; + s = s.replace(/^API error \(attempt \d+\):\s*/i, ''); + s = s.replace(/^agent executor error:\s*generating and executing:\s*/i, ''); + s = s.replace(/^request failed:\s*/i, ''); + return s.length > 180 ? `${s.slice(0, 179)}…` : s; +} + +function extractErrorStepPayload(step) { + if (!step || typeof step !== 'object') return null; + const em = step.errorMessage; + const errObj = em?.error && typeof em.error === 'object' ? em.error : em; + const shortErr = String( + errObj?.shortError || + errObj?.message || + step.error || + '' + ).trim(); + const userMsg = String(errObj?.userErrorMessage || '').trim(); + const fallbackContent = + !shortErr && !userMsg && typeof step.content === 'string' + ? step.content.replace(/^Error:\s*/i, '').trim() + : ''; + const message = shortErr || userMsg || fallbackContent; + if (!message) return null; + const errorCode = Number(errObj?.errorCode || 0) || 0; + const terminal = Boolean(em?.shouldShowUser); + return { message, userMsg, errorCode, terminal }; +} + +function buildStepAnomalyRecord(step, meta, chat, pendingErrorSteps = []) { + const retryInfosRaw = [ + ...(Array.isArray(chat?.retryInfos) ? chat.retryInfos : []), + ...(Array.isArray(meta?.retryInfos) ? meta.retryInfos : []), + ]; + const retryErrorEntries = []; + for (let i = 0; i < retryInfosRaw.length; i += 1) { + const ri = retryInfosRaw[i]; + if (!ri || typeof ri !== 'object') continue; + const errText = String(ri.error || ri.errorMessage || '').trim(); + const reasonCode = Number(ri.reasonCode || 0) || 0; + const delaySec = duration(ri.retryDelay); + if (!errText && !(reasonCode > 0 && reasonCode !== 3)) continue; + const kind = classifyStepAnomalyError(errText, { reasonCode }); + // 纯用户取消且无其他重试时不重复打告警微标(速度列已有「已取消」) + if (kind === 'canceled') continue; + retryErrorEntries.push({ + attempt: retryErrorEntries.length + 1, + kind, + delaySec: delaySec != null && delaySec > 0 ? +delaySec.toFixed(1) : 0, + message: cleanAnomalyErrorExcerpt(errText), + terminal: reasonCode === 3, + source: 'retry', + }); + } + + const events = [...retryErrorEntries]; + const declaredRetryCount = Math.max(0, Math.floor(Number(chat?.retryCount || 0))); + + // 合并同一轮前置 ERROR_MESSAGE 步骤(对已被 retryInfos 记录的同源重试做去重,保留断流续跑/安全过滤/离线日志补充) + const usedRetryKinds = new Map(); + for (const ev of retryErrorEntries) { + usedRetryKinds.set(ev.kind, (usedRetryKinds.get(ev.kind) || 0) + 1); + } + const matchedKindBudget = new Map(usedRetryKinds); + + for (const errStep of pendingErrorSteps || []) { + const info = extractErrorStepPayload(errStep); + if (!info) continue; + const kind = classifyStepAnomalyError(info.message, { errorCode: info.errorCode }); + if (kind === 'canceled') continue; + const isInterruptOrSafety = + kind === 'safety' || + /The stream was interrupted/i.test(info.message) || + info.terminal; + if (!isInterruptOrSafety) { + const rem = matchedKindBudget.get(kind) || 0; + if (rem > 0) { + matchedKindBudget.set(kind, rem - 1); + continue; + } + } + events.push({ + attempt: events.length + 1, + kind, + delaySec: 0, + message: cleanAnomalyErrorExcerpt(info.message), + terminal: Boolean(info.terminal), + source: 'error_step', + }); + } + + const isStatusError = step?.status === 'CORTEX_STEP_STATUS_ERROR'; + const isStatusInterrupted = step?.status === 'CORTEX_STEP_STATUS_INTERRUPTED'; + if (events.length === 0 && (isStatusError || isStatusInterrupted)) { + events.push({ + attempt: 1, + kind: isStatusInterrupted ? 'disconnect' : 'error', + delaySec: 0, + message: '', + terminal: isStatusError, + source: 'status', + }); + } + + const count = Math.max(events.length, declaredRetryCount); + if (count <= 0) return null; + + if (events.length === 0 && declaredRetryCount > 0) { + events.push({ + attempt: 1, + kind: 'error', + delaySec: 0, + message: '', + terminal: false, + source: 'retry_count', + }); + } + + const kinds = {}; + let totalDelaySec = 0; + let hasDanger = isStatusError; + for (const ev of events) { + kinds[ev.kind] = (kinds[ev.kind] || 0) + 1; + if (ev.delaySec > 0) totalDelaySec += ev.delaySec; + if (ev.terminal || ev.kind === 'rate_limit' || ev.kind === 'auth_or_model') { + hasDanger = true; + } + } + // 归并主分类:按出现次数降序,同次数按严重度优先级决胜 + let primaryKind = events[0].kind; + let bestCount = -1; + let bestPrio = -1; + for (const [k, c] of Object.entries(kinds)) { + const prio = ANOMALY_SEVERITY_PRIORITY[k] ?? 1; + if (c > bestCount || (c === bestCount && prio > bestPrio)) { + primaryKind = k; + bestCount = c; + bestPrio = prio; + } + } + + const roundedDelay = totalDelaySec > 0 ? +totalDelaySec.toFixed(1) : 0; + const severity = hasDanger ? 'danger' : 'warn'; + const compactEvents = events.slice(0, 6).map((ev, idx) => ({ + attempt: idx + 1, + kind: ev.kind, + ...(ev.delaySec > 0 ? { delaySec: ev.delaySec } : {}), + ...(ev.message ? { message: ev.message } : {}), + ...(ev.terminal ? { terminal: true } : {}), + })); + const kindSig = Object.entries(kinds) + .sort((a, b) => a[0].localeCompare(b[0])) + .map(([k, v]) => `${k}=${v}`) + .join(','); + const sig = `${primaryKind}:${count}:${severity}:${roundedDelay}:${kindSig}`; + return { + anomaly: { + count, + primaryKind, + severity, + totalDelaySec: roundedDelay, + kinds, + events: compactEvents, + }, + anomalySig: sig, + }; +} + /** * 从原始轨迹步骤数组与生成器元数据中提取标准化模型步骤指标。 * @@ -790,10 +1044,95 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { let pendingTurnCleanPrompts = []; let pendingTurnDoorbellOnly = false; + let pendingErrorSteps = []; + + const isErrorMessageStep = (step) => { + if (!step || typeof step !== 'object') return false; + const t = String(step.type || '').trim().toUpperCase(); + return ( + t === 'CORTEX_STEP_TYPE_ERROR_MESSAGE' || + t === 'ERROR_MESSAGE' || + Boolean(step.errorMessage && typeof step.errorMessage === 'object') + ); + }; + + const mergeTrailingErrorsIntoStep = (targetStep, errSteps) => { + if (!targetStep || !Array.isArray(errSteps) || errSteps.length === 0) return; + const prevEvents = Array.isArray(targetStep.anomaly?.events) ? targetStep.anomaly.events : []; + const trailingRec = buildStepAnomalyRecord(null, null, null, errSteps); + if (!trailingRec) return; + const isStatusOnlyPlaceholder = + prevEvents.length === 1 && + Number(targetStep.anomaly?.count || 0) === 1 && + !prevEvents[0].message && + !(Number(prevEvents[0].delaySec) > 0) && + (prevEvents[0].kind === 'error' || prevEvents[0].kind === 'disconnect'); + if (prevEvents.length === 0 || isStatusOnlyPlaceholder) { + const nextAnomaly = + isStatusOnlyPlaceholder && + targetStep.anomaly?.severity === 'danger' && + trailingRec.anomaly.severity !== 'danger' + ? { ...trailingRec.anomaly, severity: 'danger' } + : trailingRec.anomaly; + targetStep.anomaly = nextAnomaly; + targetStep.anomalySig = + nextAnomaly === trailingRec.anomaly + ? trailingRec.anomalySig + : trailingRec.anomalySig.replace(':warn:', ':danger:'); + return; + } + const mergedKinds = { ...(targetStep.anomaly.kinds || {}) }; + for (const [k, c] of Object.entries(trailingRec.anomaly.kinds || {})) { + mergedKinds[k] = (mergedKinds[k] || 0) + c; + } + const mergedCount = Number(targetStep.anomaly.count || 0) + Number(trailingRec.anomaly.count || 0); + const mergedDelay = +( + Number(targetStep.anomaly.totalDelaySec || 0) + Number(trailingRec.anomaly.totalDelaySec || 0) + ).toFixed(1); + const mergedSeverity = + targetStep.anomaly.severity === 'danger' || trailingRec.anomaly.severity === 'danger' + ? 'danger' + : 'warn'; + let primaryKind = targetStep.anomaly.primaryKind || trailingRec.anomaly.primaryKind; + let bestCount = -1; + let bestPrio = -1; + for (const [k, c] of Object.entries(mergedKinds)) { + const prio = ANOMALY_SEVERITY_PRIORITY[k] ?? 1; + if (c > bestCount || (c === bestCount && prio > bestPrio)) { + primaryKind = k; + bestCount = c; + bestPrio = prio; + } + } + const combinedEvents = [...prevEvents, ...(trailingRec.anomaly.events || [])] + .slice(0, 6) + .map((ev, i) => ({ ...ev, attempt: i + 1 })); + const kindSig = Object.entries(mergedKinds) + .sort((a, b) => a[0].localeCompare(b[0])) + .map(([k, v]) => `${k}=${v}`) + .join(','); + targetStep.anomaly = { + count: mergedCount, + primaryKind, + severity: mergedSeverity, + totalDelaySec: mergedDelay, + kinds: mergedKinds, + events: combinedEvents, + }; + targetStep.anomalySig = `${primaryKind}:${mergedCount}:${mergedSeverity}:${mergedDelay}:${kindSig}`; + }; + rawSteps.forEach((s, index) => { const isHumanBoundary = isUserTurnBoundary(s); const isWakeupBoundary = !isHumanBoundary && isSystemWakeupBoundary(s); if (isHumanBoundary || isWakeupBoundary) { + if (pendingErrorSteps.length > 0 && result.length > 0) { + const lastPrev = result[result.length - 1]; + if (lastPrev.turnIndex === activeTurnIndex) { + mergeTrailingErrorsIntoStep(lastPrev, pendingErrorSteps); + } + } + pendingErrorSteps = []; const { cleanText, legacyPrompt, hasMedia, isDoorbellOnly = false } = isHumanBoundary ? extractUserTurnInfo(s) : extractSystemWakeupInfo(s); @@ -825,11 +1164,18 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { } } + if (isErrorMessageStep(s)) { + pendingErrorSteps.push(s); + return; + } + const m = s?.metadata; const u = m?.modelUsage || m?.retryInfos?.[0]?.usage; if (!u) { return; } + const stepPendingErrors = pendingErrorSteps; + pendingErrorSteps = []; let stepIsTurnStart = false; let stepTurnPrompt = ''; @@ -917,6 +1263,10 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { let timingReason = null; if (s.status === 'CORTEX_STEP_STATUS_CANCELED') { timingReason = 'canceled'; + } else if (s.status === 'CORTEX_STEP_STATUS_ERROR') { + timingReason = 'error'; + } else if (s.status === 'CORTEX_STEP_STATUS_INTERRUPTED') { + timingReason = 'interrupted'; } else if (!complete || !(totalDurationSec > 0)) { timingReason = 'incomplete_or_invalid_timing'; } else if (!validCount(u.outputTokens)) { @@ -981,6 +1331,8 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { ? 'Orchestrator Worker (Hydrogen)' : rawDisplayName; + const anomalyRec = buildStepAnomalyRecord(s, m, chat, stepPendingErrors); + result.push({ stepIndex, isCompactionStep, @@ -1020,6 +1372,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { speedSampleEligible: totalTokPerSec !== null && !shortOutputSample && !isCompactionStep, speedReason, + ...(anomalyRec ? { anomaly: anomalyRec.anomaly, anomalySig: anomalyRec.anomalySig } : {}), turnIndex: activeTurnIndex, isTurnStart: stepIsTurnStart, ...(stepIsTurnStart && stepTurnPrompt ? { turnPrompt: stepTurnPrompt } : {}), @@ -1028,6 +1381,13 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { }); }); + if (pendingErrorSteps.length > 0 && result.length > 0) { + const lastStep = result[result.length - 1]; + if (lastStep.turnIndex === activeTurnIndex) { + mergeTrailingErrorsIntoStep(lastStep, pendingErrorSteps); + } + } + // 末尾步骤上下文回填:若最后一个非压缩步骤缺少 contextBreakdown,且最近一次有效的 generatorMetadata 未跨过压缩边界,则补齐 if ( result.length > 0 && From e93f1bc0ad889b374119610104854de333c269b2 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Thu, 19 Nov 2026 23:16:01 +0900 Subject: [PATCH 12/14] feat(panel): add single-line top models to client sources and fast scope=conversation session switching --- sidecars/panel/app.js | 402 ++++++++- sidecars/panel/backend/api-actions.mjs | 6 +- sidecars/panel/backend/local-scanner.mjs | 19 +- sidecars/panel/backend/telemetry-builder.mjs | 837 ++++++++++++------ sidecars/panel/backend/usage-aggregator.mjs | 272 +++++- sidecars/panel/index.html | 4 +- .../src/components/layout/TopSessionHeader.js | 4 +- .../components/layout/WindowOverlayShell.js | 15 +- .../components/widgets/LiveActivityWidget.js | 5 +- sidecars/panel/src/core/httpClient.js | 9 + sidecars/panel/src/store/telemetryStore.js | 292 +++++- .../panel/src/styles/views-consumption.css | 86 +- sidecars/panel/src/views/ConsumptionView.js | 80 +- sidecars/panel/styles.css | 86 +- sidecars/panel/test/backend.test.mjs | 228 +++++ sidecars/panel/test/consumption-bars.test.mjs | 28 +- 16 files changed, 2049 insertions(+), 324 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 271c274..87c4279 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -4411,7 +4411,7 @@ return { formatMetric, formatSpeedMetric, formatCachePct, getSpeedToneClass, get })(); // --- src/core/httpClient.js --- -const { getWindowBridgeConfig, isWindowOverlayMode, deliverCdpBridgeResponses, callSidecarApi } = (() => { +const { abortSidecarApiKey, getWindowBridgeConfig, isWindowOverlayMode, deliverCdpBridgeResponses, callSidecarApi } = (() => { /** * @fileoverview Async HTTP client with AbortController cancellation for stale * polling requests, concurrent GET deduplication, and dual-mode transport @@ -4422,6 +4422,15 @@ const { getWindowBridgeConfig, isWindowOverlayMode, deliverCdpBridgeResponses, c const inFlightGets = new Map(); const activeControllers = new Map(); +function abortSidecarApiKey(abortKey) { + if (!abortKey) return; + const prev = activeControllers.get(abortKey); + if (prev) { + activeControllers.delete(abortKey); + prev.abort(); + } +} + /** * 读取主窗口双栖模式下注入的本地桥接配置(`port`、`token`、`bundleVersion`、`stylesCss`)。 * @@ -4655,7 +4664,7 @@ async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTi } return promise; } -return { getWindowBridgeConfig, isWindowOverlayMode, deliverCdpBridgeResponses, callSidecarApi }; +return { abortSidecarApiKey, getWindowBridgeConfig, isWindowOverlayMode, deliverCdpBridgeResponses, callSidecarApi }; })(); // --- src/store/uiStore.js --- @@ -4691,7 +4700,7 @@ return { getViewTabs, uiStore, getVisibleMonitorView }; })(); // --- src/store/telemetryStore.js --- -const { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, fetchTelemetry, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform } = (() => { +const { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform } = (() => { /** * @fileoverview Reactive telemetry store with async non-overlapping poll scheduler * and granular slice updates. @@ -4787,9 +4796,11 @@ const telemetryStore = createReactiveStore({ let pollTimer = null; let feedbackTimer = null; +let deferredConvSyncTimer = null; let activeBundleVersion = 0; let latestRequestSeq = 0; let latestConsumptionReqSeq = 0; +let latestConversationSwitchSeq = 0; let activeForceCount = 0; let consecutivePollFailures = 0; let inFlightTelemetryPoll = null; @@ -4797,8 +4808,10 @@ let inFlightPresetsPrefetch = null; let lastPrefetchedUsageRevision = 0; let consumptionCacheScopeSig = ''; const MAX_CONSUMPTION_RANGE_CACHE = 12; +const MAX_CONVERSATION_VIEW_CACHE = 12; const CONSUMPTION_PRESET_KEYS = ['cycle', 'today', '24h', '7d', '14d', '30d', 'all']; const consumptionRangeCache = new Map(); +const conversationViewCache = new Map(); let lastReceivedSteps = null; let loopActive = false; let loopIntervalMs = 2000; @@ -4830,6 +4843,14 @@ function clearConsumptionRangeCache() { inFlightPresetsPrefetch = null; } +function clearConversationViewCache() { + conversationViewCache.clear(); + if (deferredConvSyncTimer) { + clearTimeout(deferredConvSyncTimer); + deferredConvSyncTimer = null; + } +} + function buildConsumptionScopeSig(payload) { if (!payload || typeof payload !== 'object') return ''; const acct = payload.account || {}; @@ -4843,10 +4864,112 @@ function syncConsumptionCacheScope(payload) { if (!nextSig) return; if (consumptionCacheScopeSig && consumptionCacheScopeSig !== nextSig) { clearConsumptionRangeCache(); + clearConversationViewCache(); } consumptionCacheScopeSig = nextSig; } +function recordConversationViewToCache(payload) { + const active = payload?.activeConversation; + const cidLower = String(active?.cascadeId || '').trim().toLowerCase(); + if (!cidLower || !Array.isArray(active?.recentSteps)) return; + const entry = { + cascadeId: active.cascadeId, + activeConversation: active, + activePool: payload.quotas?.activePool || null, + weekly: payload.quotas?.weekly || null, + sessionConsumption: payload.consumption?.session || null, + sessionPresets: + payload.consumption?.sessionPresets || + (payload.consumption?.presets + ? Object.fromEntries( + Object.entries(payload.consumption.presets).map(([k, v]) => [k, v?.session || null]) + ) + : null), + stepRevision: String(payload.stepRevision || ''), + cachedAtMs: Date.now(), + }; + conversationViewCache.delete(cidLower); + conversationViewCache.set(cidLower, entry); + while (conversationViewCache.size > MAX_CONVERSATION_VIEW_CACHE) { + conversationViewCache.delete(conversationViewCache.keys().next().value); + } +} + +function resolveCachedConversationRootId(telemetry, effectiveConvId) { + const target = String(effectiveConvId || '').trim(); + const convs = Array.isArray(telemetry?.conversations) ? telemetry.conversations : []; + if (!target) { + return String(convs[0]?.cascadeId || '').trim().toLowerCase(); + } + const lower = target.toLowerCase(); + if (conversationViewCache.has(lower)) return lower; + const matchedRoot = convs.find( + (c) => + String(c?.cascadeId || '').toLowerCase() === lower || + (Array.isArray(c?.memberCascadeIds) && + c.memberCascadeIds.some((m) => String(m || '').toLowerCase() === lower)) + ); + return String(matchedRoot?.cascadeId || lower).trim().toLowerCase(); +} + +function applyConversationSliceToTelemetry(baseTelemetry, slice) { + if (!baseTelemetry || !slice?.activeConversation) return baseTelemetry; + const activeCidLower = String(slice.activeConversation.cascadeId || '').toLowerCase(); + const prevQuotas = baseTelemetry.quotas || {}; + const nextQuotas = + slice.activePool || slice.weekly + ? { + ...prevQuotas, + ...(slice.activePool ? { activePool: slice.activePool } : {}), + ...(slice.weekly ? { weekly: slice.weekly } : {}), + } + : prevQuotas; + + const prevCons = baseTelemetry.consumption || {}; + let nextPresets = prevCons.presets; + if (slice.sessionPresets && prevCons.presets && typeof prevCons.presets === 'object') { + nextPresets = { ...prevCons.presets }; + for (const [k, sBucket] of Object.entries(slice.sessionPresets)) { + if (sBucket && nextPresets[k]) { + nextPresets[k] = { ...nextPresets[k], session: sBucket }; + } + } + } + const nextCons = + slice.sessionConsumption || nextPresets !== prevCons.presets + ? { + ...prevCons, + ...(slice.sessionConsumption ? { session: slice.sessionConsumption } : {}), + ...(nextPresets !== prevCons.presets ? { presets: nextPresets } : {}), + } + : prevCons; + + const prevRunning = Array.isArray(baseTelemetry.runningConversations) + ? baseTelemetry.runningConversations + : null; + let nextRunning = prevRunning; + if (prevRunning && prevRunning.length > 0 && activeCidLower) { + let anyChanged = false; + const mapped = prevRunning.map((item) => { + const shouldSelect = String(item?.cascadeId || '').toLowerCase() === activeCidLower; + if (Boolean(item?.isCurrentSelected) === shouldSelect) return item; + anyChanged = true; + return { ...item, isCurrentSelected: shouldSelect }; + }); + if (anyChanged) nextRunning = mapped; + } + + return { + ...baseTelemetry, + ...(slice.stepRevision ? { stepRevision: slice.stepRevision } : {}), + activeConversation: slice.activeConversation, + quotas: nextQuotas, + consumption: nextCons, + ...(nextRunning ? { runningConversations: nextRunning } : {}), + }; +} + function putConsumptionRangeCacheEntry(cacheKey, entry) { if (!cacheKey || !entry) return; consumptionRangeCache.delete(cacheKey); @@ -5660,6 +5783,7 @@ async function requestTelemetry(params, force) { let resolvedPayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev); syncConsumptionCacheScope(resolvedPayload); + recordConversationViewToCache(resolvedPayload); if (resolvedPayload?.consumption) { recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, { customStartMs: reqStartMs, @@ -5846,6 +5970,162 @@ async function fetchConsumptionRangeSlice({ } } +/** + * 快速切换当前查看的会话: + * - 命中前端 `conversationViewCache` 时,0ms 原子切换当前会话快照,并静默走轻量 `scope=conversation` 校准; + * - 未命中缓存时直接走零 LS RPC、零全盘扫描的 `scope=conversation` 通道; + * - 若后端提示该会话需要补读最新运行态或懒迁移字段(`needsBackgroundSync`),展示后再在后台静默补齐。 + */ +async function selectConversation( + nextConvId, + { hostRouteConversationId = undefined } = {} +) { + const switchSeq = ++latestConversationSwitchSeq; + latestRequestSeq += 1; + inFlightTelemetryPoll = null; + abortSidecarApiKey('telemetry-poll'); + if (deferredConvSyncTimer) { + clearTimeout(deferredConvSyncTimer); + deferredConvSyncTimer = null; + } + + const targetSelectedId = String(nextConvId || '').trim(); + const prevSt = telemetryStore.getState(); + const nextHostRouteId = + hostRouteConversationId !== undefined + ? String(hostRouteConversationId || '').trim() + : prevSt.hostRouteConversationId; + const effectiveConvId = targetSelectedId || nextHostRouteId || ''; + const statePatch = { + selectedConversationId: targetSelectedId, + ...(hostRouteConversationId !== undefined ? { hostRouteConversationId: nextHostRouteId } : {}), + }; + + const prevTelemetry = prevSt.telemetry; + const lookupRootId = resolveCachedConversationRootId(prevTelemetry, effectiveConvId); + const cachedEntry = lookupRootId ? conversationViewCache.get(lookupRootId) : null; + const cachedSteps = + cachedEntry && cachedEntry.stepRevision + ? readDisplaySteps({ + stepRevision: cachedEntry.stepRevision, + activeConversation: cachedEntry.activeConversation, + }) + : null; + + if (cachedEntry && prevTelemetry) { + const optimisticTelemetry = applyConversationSliceToTelemetry(prevTelemetry, cachedEntry); + if (cachedSteps) { + lastReceivedSteps = cachedSteps; + } + telemetryStore.setState({ + ...statePatch, + telemetry: optimisticTelemetry, + }); + } else { + telemetryStore.setState(statePatch); + } + + const current = telemetryStore.getState(); + const params = new URLSearchParams(); + if (effectiveConvId) params.set('conversationId', effectiveConvId); + if (current.selectedTimeRange) params.set('range', current.selectedTimeRange); + if (current.selectedTimeRange === 'custom') { + if (current.customStartMs > 0) params.set('startMs', String(current.customStartMs)); + if (current.customEndMs > 0) params.set('endMs', String(current.customEndMs)); + } + params.set('stepDetails', 'display'); + params.set('stepRevision', cachedSteps?.revision || ''); + params.set('scope', 'conversation'); + + const reqSettingsRev = settingsRevision; + try { + const payload = await callSidecarApi(`/api/telemetry?${params}`, { + method: 'GET', + abortKey: 'conversation-switch', + }); + if (!payload || typeof payload !== 'object') return null; + if (switchSeq !== latestConversationSwitchSeq) return payload; + + const latestSt = telemetryStore.getState(); + const latestEffectiveId = + String(latestSt.selectedConversationId || latestSt.hostRouteConversationId || '').trim(); + if (latestEffectiveId !== effectiveConvId) return payload; + + const active = payload.activeConversation; + if (payload.stepsUnchanged) { + const stepsSource = + (cachedSteps && payload.stepRevision === cachedSteps.revision ? cachedSteps : null) || + (lastReceivedSteps && payload.stepRevision === lastReceivedSteps.revision + ? lastReceivedSteps + : null); + if (!active || !stepsSource) { + return fetchTelemetry({ force: false }); + } + active.recentSteps = stepsSource.recentSteps; + active.agents.forEach((agent, index) => { + const steps = stepsSource.agentSteps[index]; + if (steps) agent.recentSteps = steps; + }); + } + + if (payload.scope === 'conversation' && active) { + lastReceivedSteps = readDisplaySteps(payload) || lastReceivedSteps; + recordConversationViewToCache(payload); + const baseTelemetry = latestSt.telemetry; + if (baseTelemetry) { + const mergedTelemetry = applyConversationSliceToTelemetry(baseTelemetry, { + activeConversation: active, + activePool: payload.quotas?.activePool || null, + weekly: payload.quotas?.weekly || null, + sessionConsumption: payload.consumption?.session || null, + sessionPresets: payload.consumption?.sessionPresets || null, + stepRevision: payload.stepRevision || '', + }); + if (!isEquivalentTelemetry(baseTelemetry, mergedTelemetry)) { + telemetryStore.setState({ + telemetry: mergedTelemetry, + minuteTick: Math.floor(Date.now() / 30000), + }); + } + } else { + return fetchTelemetry({ force: false }); + } + if (payload.needsBackgroundSync && loopActive && typeof setTimeout === 'function') { + deferredConvSyncTimer = setTimeout(() => { + deferredConvSyncTimer = null; + if (switchSeq === latestConversationSwitchSeq && loopActive) { + void fetchTelemetry({ force: false }); + } + }, 35); + } + return payload; + } + + // 冷启动或全新未入缓存会话回退至完整载荷 + const resolvedPayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev); + syncConsumptionCacheScope(resolvedPayload); + lastReceivedSteps = readDisplaySteps(resolvedPayload) || lastReceivedSteps; + recordConversationViewToCache(resolvedPayload); + if (resolvedPayload?.consumption) { + recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, { + customStartMs: Number(current.customStartMs || 0), + customEndMs: Number(current.customEndMs || 0), + }); + } + if (!isEquivalentTelemetry(latestSt.telemetry, resolvedPayload)) { + telemetryStore.setState({ + telemetry: resolvedPayload, + minuteTick: Math.floor(Date.now() / 30000), + syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle', + }); + } + return resolvedPayload; + } catch (err) { + if (err?.name === 'AbortError' || switchSeq !== latestConversationSwitchSeq) return null; + return null; + } +} + /** * 切换「用量统计」时间范围: * - 命中前端 rangeCache 时,在单次 setState 内 0ms 原子更新概览/趋势/模型/来源(若 usageRevision 一致则 0 次 HTTP 请求); @@ -6130,8 +6410,13 @@ async function saveSettingsPatch(patch) { } const needsTelemetryRecompute = patchKeys.some((k) => TELEMETRY_RECOMPUTE_SETTING_KEYS.has(k)); - if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) { + if ( + Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode') || + Object.prototype.hasOwnProperty.call(safePatch, 'weeklyTokenBudget') || + Object.prototype.hasOwnProperty.call(safePatch, 'weeklyCostBudget') + ) { clearConsumptionRangeCache(); + clearConversationViewCache(); } if (needsTelemetryRecompute) { inFlightTelemetryPoll = null; @@ -6197,6 +6482,7 @@ async function resetAllSettings() { } inFlightTelemetryPoll = null; clearConsumptionRangeCache(); + clearConversationViewCache(); void fetchTelemetry({ force: false }); return res; } @@ -6204,6 +6490,7 @@ async function resetAllSettings() { async function rebuildTrajectoryCache() { const res = await callSidecarApi('/api/cache/rebuild', { method: 'POST', body: {} }); clearConsumptionRangeCache(); + clearConversationViewCache(); await fetchTelemetry({ force: true }); return res; } @@ -6211,6 +6498,7 @@ async function rebuildTrajectoryCache() { async function triggerCloudSync() { const res = await callSidecarApi('/api/cloud-sync', { method: 'POST', body: {} }); clearConsumptionRangeCache(); + clearConversationViewCache(); await fetchTelemetry({ force: true }); return res; } @@ -6284,6 +6572,10 @@ function stopAsyncTelemetryLoop() { clearTimeout(feedbackTimer); feedbackTimer = null; } + if (deferredConvSyncTimer) { + clearTimeout(deferredConvSyncTimer); + deferredConvSyncTimer = null; + } } @@ -6480,7 +6772,7 @@ function isMacHostPlatform(telemetry) { } return false; } -return { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, fetchTelemetry, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform }; +return { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform }; })(); // --- src/components/ui/TopLongPillNav.js --- @@ -13685,8 +13977,7 @@ const LiveActivityWidget = defineComponent({ onSelectSession(item.cascadeId); } else if (item.cascadeId && item.cascadeId !== 'current') { uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); - telemetryStore.setState({ selectedConversationId: item.cascadeId }); - fetchTelemetry({ force: false }); + void selectConversation(item.cascadeId); } }; } @@ -20620,8 +20911,7 @@ const TopSessionHeader = defineComponent({ options: [{ value: '', label: t('header.followLatest') }], onUpdateModelValue: (nextConvId) => { uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); - telemetryStore.setState({ selectedConversationId: nextConvId }); - fetchTelemetry({ force: false }); + void selectConversation(nextConvId); }, }); @@ -21795,8 +22085,23 @@ const ConsumptionView = defineComponent({ return { el: segEl, refs: { segEl } }; } + function createSourceTopModelItem() { + const dotEl = h('span', { className: 'dot-swatch cons-model-dot cons-source-top-dot' }); + const nameEl = h('span', { className: 'cons-source-top-name' }); + const pctEl = h('strong', { className: 'cons-source-top-pct text-mono' }); + const itemEl = h('span', { className: 'cons-source-top-item' }, [dotEl, nameEl, pctEl]); + return { el: itemEl, refs: { itemEl, dotEl, nameEl, pctEl } }; + } + + function formatCompactSourceSharePct(pct) { + const num = Number(pct || 0); + if (!Number.isFinite(num) || num <= 0) return '0%'; + if (num >= 10) return `${Math.round(num)}%`; + return `${num.toFixed(1)}%`; + } + /** - * 创建客户端来源单行 DOM 结构(保留长尾合并分段配色进度条与右侧总调用数,悬停进度条弹出各模型明细浮层)。 + * 创建客户端来源单行 DOM 结构(保留长尾合并分段配色进度条、单行不换行的 Top 2-3 模型速览和右侧总调用数,悬停进度条或速览区弹出完整明细浮层)。 */ function createSourceBreakdownRow() { const nameTextEl = h('span', { className: 'cons-row-title-text' }); @@ -21806,26 +22111,39 @@ const ConsumptionView = defineComponent({ const costEl = h('strong', { className: 'cons-row-cost text-mono' }); const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' }); const rowState = { hoverPayload: null }; + const bindPopoverHover = (targetEl) => ({ + onMouseEnter: (e) => { + if (rowState.hoverPayload) { + showBreakdownPopover(targetEl, rowState.hoverPayload, e?.clientX ?? null); + } + }, + onMouseMove: (e) => { + if (rowState.hoverPayload && activeHoverTargetEl === targetEl) { + positionBreakdownPopover(targetEl, e?.clientX ?? null); + } + }, + onMouseLeave: () => { + if (activeHoverTargetEl === targetEl) hideBreakdownPopover(); + }, + }); const barHitEl = h( 'div', { className: 'cons-source-bar-hit', - onMouseEnter: (e) => { - if (rowState.hoverPayload) { - showBreakdownPopover(barHitEl, rowState.hoverPayload, e?.clientX ?? null); - } - }, - onMouseMove: (e) => { - if (rowState.hoverPayload && activeHoverTargetEl === barHitEl) { - positionBreakdownPopover(barHitEl, e?.clientX ?? null); - } - }, - onMouseLeave: () => { - if (activeHoverTargetEl === barHitEl) hideBreakdownPopover(); - }, }, [trackEl] ); + const barHandlers = bindPopoverHover(barHitEl); + barHitEl.addEventListener('mouseenter', barHandlers.onMouseEnter); + barHitEl.addEventListener('mousemove', barHandlers.onMouseMove); + barHitEl.addEventListener('mouseleave', barHandlers.onMouseLeave); + + const topModelsEl = h('div', { className: 'cons-source-top-models', hidden: true }); + const topHandlers = bindPopoverHover(topModelsEl); + topModelsEl.addEventListener('mouseenter', topHandlers.onMouseEnter); + topModelsEl.addEventListener('mousemove', topHandlers.onMouseMove); + topModelsEl.addEventListener('mouseleave', topHandlers.onMouseLeave); + const callsLbl = h('span', { text: t('cons.footCalls') }); const callsVal = h('strong', { className: 'text-mono' }); @@ -21840,6 +22158,7 @@ const ConsumptionView = defineComponent({ ]), barHitEl, h('div', { className: 'cons-item-foot cons-source-foot' }, [ + topModelsEl, h('span', { className: 'legend-left cons-calls-stat' }, [ callsLbl, callsVal, @@ -21857,6 +22176,7 @@ const ConsumptionView = defineComponent({ costEl, barHitEl, trackEl, + topModelsEl, callsLbl, callsVal, rowState, @@ -21920,6 +22240,28 @@ const ConsumptionView = defineComponent({ }, }); + const topModels = partitioned + .filter((seg) => !seg.isOther) + .slice(0, 3) + .map((seg) => ({ + key: seg.key, + label: seg.label, + pctText: formatCompactSourceSharePct(seg.pct), + color: seg.color, + })); + patchAttr(refs.topModelsEl, 'hidden', topModels.length === 0); + patchKeyedList(refs.topModelsEl, topModels, { + keyFn: (m) => m.key, + sigFn: (m) => `${m.key}:${m.label}:${m.pctText}:${m.color}`, + createRow: createSourceTopModelItem, + updateRow: (mRefs, m) => { + patchStyleVar(mRefs.dotEl, '--dot-color', m.color); + patchText(mRefs.nameEl, m.label); + patchText(mRefs.pctEl, m.pctText); + patchAttr(mRefs.itemEl, 'title', `${m.label} (${m.pctText})`); + }, + }); + refs.rowState.hoverPayload = total > 0 || callsCount > 0 ? { @@ -25251,8 +25593,7 @@ function mountWindowOverlay() { selectedAgentScope: 'all', ctxInspectorAgentId: 'auto', }); - telemetryStore.setState({ selectedConversationId: cascadeId }); - void fetchTelemetry({ force: false }); + void selectConversation(cascadeId); setMultiOpen(false); setPopoverOpen(true); } @@ -26732,13 +27073,12 @@ function mountWindowOverlay() { if (currentRouteId === lastObservedRouteId) return; lastObservedRouteId = currentRouteId; const st = telemetryStore.getState(); - const patch = { hostRouteConversationId: currentRouteId }; - if (currentRouteId && st.selectedConversationId && st.selectedConversationId !== currentRouteId) { - patch.selectedConversationId = ''; - } + const nextSelectedId = + currentRouteId && st.selectedConversationId && st.selectedConversationId !== currentRouteId + ? '' + : st.selectedConversationId; uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); - telemetryStore.setState(patch); - void fetchTelemetry({ force: false }); + void selectConversation(nextSelectedId, { hostRouteConversationId: currentRouteId }); } const onDocMouseDown = (e) => { diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index 835636e..f409d2b 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -198,7 +198,11 @@ export async function executeTelemetryAction(data, { onRestart = null } = {}) { } const rawScope = String(data?.scope || '').trim(); const scope = - rawScope === 'consumption' || rawScope === 'consumption-presets' ? rawScope : ''; + rawScope === 'consumption' || + rawScope === 'consumption-presets' || + rawScope === 'conversation' + ? rawScope + : ''; const filterOpts = { range: data?.range || 'all', startMs: sanitizePositiveFiniteMs(data?.startMs), diff --git a/sidecars/panel/backend/local-scanner.mjs b/sidecars/panel/backend/local-scanner.mjs index 405b6e6..31d5d58 100644 --- a/sidecars/panel/backend/local-scanner.mjs +++ b/sidecars/panel/backend/local-scanner.mjs @@ -99,13 +99,20 @@ function discoverLocalConversationFiles() { const annotationDirs = Array.isArray(ANNOTATION_DIRS) ? ANNOTATION_DIRS : []; if (annotationDirs.length > 0 && map.size > 0) { - for (const [cascadeId, fileList] of map.entries()) { - for (const annDir of annotationDirs) { - if (!annDir) continue; - const pbtxtPath = join(annDir, `${cascadeId}.pbtxt`); - if (existsSync(pbtxtPath)) { - fileList.push(pbtxtPath); + for (const annDir of annotationDirs) { + if (!annDir || !existsSync(annDir)) continue; + try { + for (const rawName of readdirSync(annDir)) { + const name = String(rawName || ''); + if (!name.toLowerCase().endsWith('.pbtxt')) continue; + const cascadeId = name.slice(0, -6).toLowerCase(); + const fileList = map.get(cascadeId); + if (fileList) { + fileList.push(join(annDir, name)); + } } + } catch { + // 忽略注释目录读取异常 } } } diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index f0c7a9a..0f94893 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -49,20 +49,24 @@ import { aggregateConsumptionPresetBundle, aggregateMultiWindowUsage, aggregateSelectedWindowUsage, + aggregateSessionUsageForFamily, buildScopedModelBreakdown, clearUsageAggregatorMemo, getNextMondayResetIso, } from './usage-aggregator.mjs'; const MAX_RECENT_CONVERSATIONS = 30; +const MAX_CONVERSATION_ASSEMBLY_CACHE = 8; const POOL_PRIORITY_ORDER = ['Gemini', 'Argon', 'Carbon', 'Claude & GPT']; const inFlightTelemetrySources = new Map(); const trajectoryModelFacts = new WeakMap(); -let lastMainPreparation = null; +let agentStepPrepCache = new WeakMap(); +const conversationAssemblyCache = new Map(); let lastCompletedTelemetrySnapshot = null; export function clearTelemetryBuilderMemo() { - lastMainPreparation = null; + agentStepPrepCache = new WeakMap(); + conversationAssemblyCache.clear(); lastCompletedTelemetrySnapshot = null; clearUsageAggregatorMemo(); } @@ -95,17 +99,22 @@ function readTrajectoryModelFacts(steps) { if (cached) return cached; const upstream = new Map(); const limits = new Map(); + const fallbackModelKeys = new Set(); let sortableLimits = true; for (const step of steps) { - if (step?.modelKey && step.modelKey !== 'unknown' && step.responseModel) { - upstream.set(step.modelKey, step.responseModel); + if (step?.modelKey && step.modelKey !== 'unknown') { + if (step.responseModel) { + upstream.set(step.modelKey, step.responseModel); + } else { + fallbackModelKeys.add(step.modelKey); + } } if (!step?.isCompactionStep && step?.reportedContextLimitTokens > 0) { sortableLimits &&= Number.isFinite(step.createdAtMs); rememberModelContextLimit(limits, step); } } - const result = { upstream, limits: sortableLimits ? limits : null }; + const result = { upstream, limits: sortableLimits ? limits : null, fallbackModelKeys }; trajectoryModelFacts.set(steps, result); return result; } @@ -548,13 +557,41 @@ function extractActiveContextTelemetry( }; } +function snapshotFallbackUpstreams(fallbackModelKeys, upstream) { + const map = new Map(); + if (fallbackModelKeys && upstream) { + for (const key of fallbackModelKeys) { + map.set(key, upstream.get(key) || ''); + } + } + return map; +} + +function sameFallbackUpstreams(prevMap, fallbackModelKeys, upstream) { + if (!prevMap) return !fallbackModelKeys || fallbackModelKeys.size === 0; + if ((fallbackModelKeys?.size || 0) !== prevMap.size) return false; + for (const [key, val] of prevMap.entries()) { + if ((upstream?.get(key) || '') !== val) return false; + } + return true; +} + function prepareAgentSteps(rawSteps, resolveStepModel, upstream, agentFields, reuseInputs) { - for (const [key, model] of readTrajectoryModelFacts(rawSteps).upstream) upstream.set(key, model); - const previous = lastMainPreparation; - if (reuseInputs && previous?.rawSteps === rawSteps && - isDeepStrictEqual(previous.inputs, reuseInputs) && isDeepStrictEqual(previous.upstream, upstream)) { - const prepared = previous.prepared.deref(); - if (prepared) return prepared; + const facts = readTrajectoryModelFacts(rawSteps); + for (const [key, model] of facts.upstream) upstream.set(key, model); + const canCache = Boolean(reuseInputs && Array.isArray(rawSteps)); + if (canCache) { + const previous = agentStepPrepCache.get(rawSteps); + if ( + previous && + isDeepStrictEqual(previous.agentFields, agentFields) && + previous.catalogRevision === reuseInputs.catalogRevision && + previous.phaseEpoch === reuseInputs.phaseEpoch && + isDeepStrictEqual(previous.dynamicModelMap, reuseInputs.dynamicModelMap) && + sameFallbackUpstreams(previous.fallbackUpstreams, facts.fallbackModelKeys, upstream) + ) { + return previous.prepared; + } } const enrichedRes = enrichActiveConversationSteps(rawSteps, resolveStepModel, upstream, agentFields); const taggedSteps = enrichedRes.enrichedActiveSteps; @@ -565,9 +602,16 @@ function prepareAgentSteps(rawSteps, resolveStepModel, upstream, agentFields, re enrichedRes.sessionInputTokens, enrichedRes.sessionCacheReadTokens), modelBreakdown: buildScopedModelBreakdown(taggedSteps, resolveStepModel), }; - // 单代理行可跨轮询复用。内存紧张时允许回收,运行状态仍单独实时组装。 - if (reuseInputs) { - lastMainPreparation = { rawSteps, inputs: reuseInputs, upstream, prepared: new WeakRef(prepared) }; + // 按 rawSteps 数组引用缓存各代理(含多代理子代理)步骤富化结果,步骤变更后由 WeakMap 自动淘汰。 + if (canCache) { + agentStepPrepCache.set(rawSteps, { + agentFields, + catalogRevision: reuseInputs.catalogRevision, + phaseEpoch: reuseInputs.phaseEpoch, + dynamicModelMap: reuseInputs.dynamicModelMap, + fallbackUpstreams: snapshotFallbackUpstreams(facts.fallbackModelKeys, upstream), + prepared, + }); } return prepared; } @@ -729,75 +773,83 @@ function getTelemetrySources(requestedConvId, forceQuotaRefresh, currentAccountN return pending; } -/** - * 构建完整的前端遥测载荷(核心内部实现,直接供单元测试沙箱调用)。 - * - * @param {string} requestedConvId 请求指定的会话 ID(为空时自动选定最近活跃会话) - * @param {boolean} [forceQuotaRefresh=false] 是否强制穿透官方配额缓存与失败退避 - * @param {{ range?: string, startMs?: number, endMs?: number }} [filterOpts={}] 时间范围筛选选项 - * @returns {Promise} - */ -export async function buildTelemetryPayloadInternal( - requestedConvId, - forceQuotaRefresh = false, - filterOpts = {} -) { - const settings = loadSettings(); - let userStatus = await callLsRpc('GetUserStatus', {}) - .then((data) => data?.userStatus) - .catch(() => null); - if ( - !userStatus && - lsRuntimeEndpoint.addr !== 'test.invalid' && - (!lsRuntimeEndpoint.baseUrl || lsRuntimeEndpoint.isDynamic) - ) { - const prevBaseUrl = lsRuntimeEndpoint.baseUrl; - const prevCsrf = lsRuntimeEndpoint.csrfToken; - await ensureLsEndpointDiscovered({ - force: true, - respectCooldown: !forceQuotaRefresh, - }); - if ( - lsRuntimeEndpoint.baseUrl && - (lsRuntimeEndpoint.baseUrl !== prevBaseUrl || lsRuntimeEndpoint.csrfToken !== prevCsrf) - ) { - userStatus = await callLsRpc('GetUserStatus', {}) - .then((data) => data?.userStatus) - .catch(() => null); - } - } - const currentAccountName = userStatus?.email || userStatus?.name || ''; - const accountStatus = currentAccountName ? 'signedIn' : - userStatus && !userStatus.userTier && !userStatus.planStatus ? 'signedOut' : 'unknown'; - const accountScope = accountStatus === 'signedOut' ? null : currentAccountName; - const { officialQuotaInfo, contextModelCatalog, sessions } = await getTelemetrySources( - requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus - ); - const { conversations, activeConvSummary, activeCascadeId } = sessions; - - const officialQuota = officialQuotaInfo?.data || null; - const clientConfigs = userStatus?.cascadeModelConfigData?.clientModelConfigs || []; - - // 1. 构建官方实时配额池与动态模型目录 - const { dynamicModelMap, quotaPoolsMap } = buildOfficialQuotaPools( - officialQuota, - clientConfigs - ); - - const resolveStepModel = createStepModelResolver(dynamicModelMap); - - // 3. 计算当前活跃根会话及其子代理的步骤指标、10 通道上下文拆解与按模型汇总 - const reportedContextLimits = new Map(); - const knownUpstreamByModelKey = buildKnownUpstreamModelMap(reportedContextLimits); - const activeEntry = findTrajectoryCacheEntry(activeCascadeId); +function buildActiveConversationAssembly({ + activeCascadeId, + activeConvSummary, + activeEntry, + resolveStepModel, + knownUpstreamByModelKey, + modelInputs, + accountScope, +}) { const activeSteps = activeEntry?.steps || []; const subagentSummaries = activeConvSummary?.subagents || []; - if (subagentSummaries.length) lastMainPreparation = null; - const modelInputs = { - catalogRevision: pricingCatalogRevision, - phaseEpoch: getPricingPhaseEpoch(), - dynamicModelMap, - }; + const cacheKey = String(activeCascadeId || '__empty__').toLowerCase(); + + const subEntries = subagentSummaries.map((subSum) => findTrajectoryCacheEntry(subSum.cascadeId)); + const subRawStepsList = subEntries.map((entry) => entry?.steps || []); + const combinedFallbackKeys = new Set(); + for (const k of readTrajectoryModelFacts(activeSteps).fallbackModelKeys) { + combinedFallbackKeys.add(k); + } + for (const steps of subRawStepsList) { + for (const k of readTrajectoryModelFacts(steps).fallbackModelKeys) { + combinedFallbackKeys.add(k); + } + } + + const assemblyMetaSig = JSON.stringify([ + activeCascadeId || '', + activeConvSummary?.title || '', + activeConvSummary?.swarmTitle || '', + activeConvSummary?.status || 'IDLE', + activeConvSummary?.lastModifiedMs || activeEntry?.lastModifiedMs || 0, + activeConvSummary?.liveActivity?.signature || '', + activeConvSummary?.liveActivity?.startedAtMs || 0, + subagentSummaries.map((subSum, idx) => { + const subEntry = subEntries[idx]; + const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null; + return [ + subSum.cascadeId || '', + subSum.status || 'IDLE', + Boolean(subSum.killed), + subSum.swarmState || '', + Boolean(subSum.isSwarmWorker), + Boolean(subSum.isSwarmAuxiliary), + Boolean(subSum.isSideQuestion || subEntry?.isSideQuestion), + subSum.swarmMemberName || '', + subSum.agentScriptName || subEntry?.agentScriptName || '', + subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0, + subSum.liveActivity?.signature || '', + subSum.liveActivity?.startedAtMs || 0, + subSpec?.role || '', + subSpec?.typeName || '', + ]; + }), + ]); + + const cachedAssembly = conversationAssemblyCache.get(cacheKey); + if ( + cachedAssembly && + cachedAssembly.activeSteps === activeSteps && + cachedAssembly.assemblyMetaSig === assemblyMetaSig && + cachedAssembly.subRawStepsList.length === subRawStepsList.length && + cachedAssembly.subRawStepsList.every((s, idx) => s === subRawStepsList[idx]) && + cachedAssembly.catalogRevision === modelInputs.catalogRevision && + cachedAssembly.phaseEpoch === modelInputs.phaseEpoch && + isDeepStrictEqual(cachedAssembly.dynamicModelMap, modelInputs.dynamicModelMap) && + sameFallbackUpstreams( + cachedAssembly.fallbackUpstreams, + combinedFallbackKeys, + knownUpstreamByModelKey + ) + ) { + conversationAssemblyCache.delete(cacheKey); + conversationAssemblyCache.set(cacheKey, cachedAssembly); + return cachedAssembly.result; + } + + const agentReuseInputs = { ...modelInputs, activeCascadeId, accountScope }; const mainUnit = buildAgentUnitTelemetry({ agentId: 'main', cascadeId: activeCascadeId, @@ -815,7 +867,7 @@ export async function buildTelemetryPayloadInternal( resolveStepModel, knownUpstreamByModelKey, includeRecentSteps: false, - reuseInputs: subagentSummaries.length ? null : { ...modelInputs, activeCascadeId, accountScope }, + reuseInputs: agentReuseInputs, }); const enrichedActiveSteps = mainUnit.taggedSteps; @@ -836,8 +888,12 @@ export async function buildTelemetryPayloadInternal( const activeFamilyCascadeIds = new Set(activeCascadeId ? [activeCascadeId.toLowerCase()] : []); const subAgentTelemetries = []; - const allCombinedRawSteps = subagentSummaries.length ? activeSteps.slice() : []; - const allCombinedEnrichedSteps = subagentSummaries.length ? enrichedActiveSteps.slice() : []; + const hasSubagentSummaries = subagentSummaries.length > 0; + const mainStepsForFamily = hasSubagentSummaries + ? enrichedActiveSteps.map((st) => ({ ...st })) + : enrichedActiveSteps; + const allCombinedRawSteps = hasSubagentSummaries ? activeSteps.slice() : []; + const allCombinedEnrichedSteps = hasSubagentSummaries ? mainStepsForFamily.slice() : []; let totalRawSessionCostUsd = sessionCostUsd; let totalFamilyInputTokens = sessionInputTokens; let totalFamilyCacheReadTokens = sessionCacheReadTokens; @@ -850,8 +906,8 @@ export async function buildTelemetryPayloadInternal( const subSum = subagentSummaries[idx]; const subCid = subSum.cascadeId; activeFamilyCascadeIds.add(String(subCid || '').toLowerCase()); - const subEntry = findTrajectoryCacheEntry(subCid); - const subRawSteps = subEntry?.steps || []; + const subEntry = subEntries[idx]; + const subRawSteps = subRawStepsList[idx]; for (const step of subRawSteps) allCombinedRawSteps.push(step); const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null; @@ -950,21 +1006,28 @@ export async function buildTelemetryPayloadInternal( fallbackLastModMs: subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0, resolveStepModel, knownUpstreamByModelKey, - includeRecentSteps: true, + includeRecentSteps: false, + reuseInputs: agentReuseInputs, }); - for (const step of subUnit.taggedSteps) allCombinedEnrichedSteps.push(step); + const clonedSubSteps = subUnit.taggedSteps.map((st) => ({ ...st })); + for (const step of clonedSubSteps) allCombinedEnrichedSteps.push(step); totalRawSessionCostUsd += subUnit.enrichedRes.sessionCostUsd; totalFamilyInputTokens += subUnit.enrichedRes.sessionInputTokens; totalFamilyCacheReadTokens += subUnit.enrichedRes.sessionCacheReadTokens; totalFamilyOutputTokens += subUnit.enrichedRes.sessionOutputTokens; - subAgentTelemetries.push(subUnit.telemetryUnit); + subAgentTelemetries.push({ + ...subUnit.telemetryUnit, + recentSteps: clonedSubSteps.slice().reverse(), + }); } const allAgents = [mainAgentTelemetry, ...subAgentTelemetries]; let aggregatedTelemetry = mainAgentTelemetry; + let mainRecentSteps = mainUnit.recentSteps; if (subAgentTelemetries.length > 0) { + mainRecentSteps = mainStepsForFamily.slice().reverse(); allCombinedRawSteps.sort( (a, b) => (a.createdAtMs || 0) - (b.createdAtMs || 0) || (a.stepIndex || 0) - (b.stepIndex || 0) ); @@ -978,7 +1041,7 @@ export async function buildTelemetryPayloadInternal( // 在多代理汇总视图下,将并行交错的子代理步骤按时间归入对应的主会话用户轮次,避免导轨被交错步骤切碎 const mainTurnByIdx = new Map(); let maxRootTurn = 0; - for (const mSt of enrichedActiveSteps) { + for (const mSt of mainStepsForFamily) { const tIdx = mSt.turnIndex; if (!Number.isInteger(tIdx) || tIdx <= 0) continue; if (tIdx > maxRootTurn) maxRootTurn = tIdx; @@ -1169,11 +1232,99 @@ export async function buildTelemetryPayloadInternal( }; } - // 4. 识别当前活跃会话家族绑定的模型池(与 quota-pools.mjs 保持一致,将 Other 第三方模型归入 Claude & GPT) const latestFamilyStep = allCombinedEnrichedSteps.length > 0 ? allCombinedEnrichedSteps[allCombinedEnrichedSteps.length - 1] : latestEnriched; + + const activeConversation = { + cascadeId: activeCascadeId, + title: activeConvSummary?.title || '当前会话', + ...(activeConvSummary?.swarmTitle ? { swarmTitle: activeConvSummary.swarmTitle } : {}), + isRunning: activeConvSummary?.status === 'CASCADE_RUN_STATUS_RUNNING', + status: activeConvSummary?.status || 'IDLE', + liveActivity: mainAgentTelemetry.liveActivity || null, + stepCount: enrichedActiveSteps.length, + hasSubagents: subAgentTelemetries.length > 0, + subagentCount: subAgentTelemetries.length, + swarmCount: swarmWorkerCount, + normalSubagentCount: normalSubCount, + sideQuestionCount, + totalStepsAllAgents: subAgentTelemetries.length + ? allCombinedEnrichedSteps.length + : enrichedActiveSteps.length, + latestTokPerSec: latestEnriched?.tokPerSec ?? null, + latestTtftSec: latestEnriched?.ttftSec ?? null, + latestSpeedReason: latestEnriched?.selectedSpeedReason ?? null, + avgTokPerSec: sessionAvgTokPerSec, + speedSummary: sessionSpeed, + ttftSummary: sessionTtft, + latestStepCostUsd: latestEnriched?.costUsd ?? null, + sessionCostUsd: roundSessionCost(sessionCostUsd), + sessionUnpricedCalls, + inputTokens: sessionInputTokens, + cacheReadTokens: sessionCacheReadTokens, + outputTokens: sessionOutputTokens, + totalTokens: sessionInputTokens + sessionCacheReadTokens + sessionOutputTokens, + latestPromptTokens: latestEnriched + ? Number(latestEnriched.inputTokens || 0) + Number(latestEnriched.cacheReadTokens || 0) + : 0, + latestCacheHitPct, + sessionCacheHitPct, + hasKnownModel: Boolean(latestEnriched?.hasKnownModel), + activeBaseModelShort: latestEnriched?.baseModelShort || '', + activeBaseModelLabel: latestEnriched?.baseModelLabel || '', + activeModelShort: latestEnriched?.modelShort || '模型未知', + activeModelLabel: latestEnriched?.modelLabel || '模型未知', + activeModelUpstream: + latestEnriched?.modelUpstream || latestEnriched?.modelShort || '模型未知', + context, + recentSteps: mainRecentSteps, + modelBreakdown: mainModelBreakdown, + agents: allAgents, + aggregated: aggregatedTelemetry, + }; + + const result = { + activeConversation, + activeFamilyCascadeIds, + latestFamilyStep, + }; + + if ( + !conversationAssemblyCache.has(cacheKey) && + conversationAssemblyCache.size >= MAX_CONVERSATION_ASSEMBLY_CACHE + ) { + conversationAssemblyCache.delete(conversationAssemblyCache.keys().next().value); + } + conversationAssemblyCache.delete(cacheKey); + conversationAssemblyCache.set(cacheKey, { + activeSteps, + subRawStepsList, + assemblyMetaSig, + catalogRevision: modelInputs.catalogRevision, + phaseEpoch: modelInputs.phaseEpoch, + dynamicModelMap: modelInputs.dynamicModelMap, + fallbackUpstreams: snapshotFallbackUpstreams(combinedFallbackKeys, knownUpstreamByModelKey), + result, + }); + + return result; +} + +function createEmptyCycleSummary() { + return { + calls: 0, + tokens: 0, + inputTokens: 0, + cacheReadTokens: 0, + outputTokens: 0, + costUsd: 0, + unpricedCalls: 0, + }; +} + +function resolveActivePoolKeyFromStep(latestFamilyStep, quotaPoolsMap) { const hasResolvedStepModel = Boolean( latestFamilyStep && latestFamilyStep.modelKey && latestFamilyStep.modelKey !== 'unknown' ); @@ -1222,6 +1373,205 @@ export async function buildTelemetryPayloadInternal( resetTime: matchedActivePool.weeklyResetTime, } : null; + return { activePoolKey, matchedActivePool, activeLive5h, activeLiveWeekly }; +} + +function buildActivePoolAndWeeklyQuotas({ + activePoolKey, + activeLive5h, + activeLiveWeekly, + quotaPoolsMap, + isCustomWeeklyMode, + settings, + weekBucket, + quotaWeekBucket, + poolsWeeklySummary, +}) { + const familyPoolQuota = quotaPoolsMap.get(activePoolKey); + const activePoolLabel = familyPoolQuota?.poolLabel || activePoolKey; + const activePoolQuota = familyPoolQuota || { + poolKey: activePoolKey, + poolLabel: activePoolKey === 'Unknown' ? '未知' : activePoolKey, + poolName: + activePoolKey === 'Carbon' + ? 'Gemini 4 Carbon 模型池' + : activePoolKey === 'Argon' + ? 'Gemini 4 Argon 模型池' + : activePoolKey === 'Gemini' + ? 'Gemini 模型池' + : activePoolKey === 'Claude & GPT' + ? 'Claude & GPT 模型池' + : '模型池未知', + family: activePoolKey, + isAvailable: Boolean(activeLive5h || activeLiveWeekly), + has5h: Boolean(activeLive5h), + hasWeekly: Boolean(activeLiveWeekly), + remainingPct: activeLive5h?.remainingPct ?? null, + remainingIntPct: activeLive5h?.remainingIntPct ?? null, + usedPct: activeLive5h?.usedPct ?? null, + resetTime: activeLive5h?.resetTime || null, + weeklyRemainingPct: activeLiveWeekly?.remainingPct ?? null, + weeklyRemainingIntPct: activeLiveWeekly?.remainingIntPct ?? null, + weeklyUsedPct: activeLiveWeekly?.usedPct ?? null, + weeklyResetTime: activeLiveWeekly?.resetTime || null, + cycle5h: createEmptyCycleSummary(), + cycleWeekly: createEmptyCycleSummary(), + models: [], + }; + + const fallbackWeeklyPct = + settings.weeklyLimitMode === 'custom_cost' + ? weekBucket.unpricedCalls > 0 + ? null + : Math.min( + 100, + +((weekBucket.costUsd / Math.max(1, settings.weeklyCostBudget)) * 100).toFixed(1) + ) + : Math.min( + 100, + +((weekBucket.totalTokens / Math.max(1000, settings.weeklyTokenBudget)) * 100).toFixed(1) + ); + + const useOfficialWeekly = Boolean(activeLiveWeekly) && !isCustomWeeklyMode; + const weeklyUsedPct = useOfficialWeekly + ? activeLiveWeekly.usedPct + : isCustomWeeklyMode + ? fallbackWeeklyPct + : null; + const weeklyRemainingPct = useOfficialWeekly + ? activeLiveWeekly.remainingPct + : isCustomWeeklyMode && fallbackWeeklyPct !== null + ? +(100 - fallbackWeeklyPct).toFixed(1) + : null; + const weeklyRemainingIntPct = useOfficialWeekly + ? activeLiveWeekly.remainingIntPct + : isCustomWeeklyMode && fallbackWeeklyPct !== null + ? Math.max(0, Math.floor(100 - fallbackWeeklyPct)) + : null; + const officialFallbackWeekBucket = quotaWeekBucket || weekBucket; + const weeklyQuota = { + isOfficial: useOfficialWeekly, + poolFamily: activePoolKey, + title: isCustomWeeklyMode + ? '每周限额 (自定义本机)' + : `每周限额 (${activePoolLabel && activePoolLabel !== 'Unknown' ? activePoolLabel : '当前'})`, + calls: isCustomWeeklyMode + ? weekBucket.calls + : poolsWeeklySummary + ? poolsWeeklySummary.calls + : officialFallbackWeekBucket.calls, + tokens: isCustomWeeklyMode + ? weekBucket.totalTokens + : poolsWeeklySummary + ? poolsWeeklySummary.tokens + : officialFallbackWeekBucket.totalTokens, + costUsd: isCustomWeeklyMode + ? weekBucket.costUsd + : poolsWeeklySummary + ? poolsWeeklySummary.costUsd + : officialFallbackWeekBucket.costUsd, + unpricedCalls: isCustomWeeklyMode + ? weekBucket.unpricedCalls + : poolsWeeklySummary + ? poolsWeeklySummary.unpricedCalls + : officialFallbackWeekBucket.unpricedCalls, + usedPct: weeklyUsedPct, + remainingPct: weeklyRemainingPct, + remainingIntPct: weeklyRemainingIntPct, + resetTime: useOfficialWeekly + ? activeLiveWeekly.resetTime + : isCustomWeeklyMode + ? getNextMondayResetIso() + : null, + }; + return { activePoolQuota, weeklyQuota }; +} + +/** + * 构建完整的前端遥测载荷(核心内部实现,直接供单元测试沙箱调用)。 + * + * @param {string} requestedConvId 请求指定的会话 ID(为空时自动选定最近活跃会话) + * @param {boolean} [forceQuotaRefresh=false] 是否强制穿透官方配额缓存与失败退避 + * @param {{ range?: string, startMs?: number, endMs?: number }} [filterOpts={}] 时间范围筛选选项 + * @returns {Promise} + */ +export async function buildTelemetryPayloadInternal( + requestedConvId, + forceQuotaRefresh = false, + filterOpts = {} +) { + const settings = loadSettings(); + let userStatus = await callLsRpc('GetUserStatus', {}) + .then((data) => data?.userStatus) + .catch(() => null); + if ( + !userStatus && + lsRuntimeEndpoint.addr !== 'test.invalid' && + (!lsRuntimeEndpoint.baseUrl || lsRuntimeEndpoint.isDynamic) + ) { + const prevBaseUrl = lsRuntimeEndpoint.baseUrl; + const prevCsrf = lsRuntimeEndpoint.csrfToken; + await ensureLsEndpointDiscovered({ + force: true, + respectCooldown: !forceQuotaRefresh, + }); + if ( + lsRuntimeEndpoint.baseUrl && + (lsRuntimeEndpoint.baseUrl !== prevBaseUrl || lsRuntimeEndpoint.csrfToken !== prevCsrf) + ) { + userStatus = await callLsRpc('GetUserStatus', {}) + .then((data) => data?.userStatus) + .catch(() => null); + } + } + const currentAccountName = userStatus?.email || userStatus?.name || ''; + const accountStatus = currentAccountName ? 'signedIn' : + userStatus && !userStatus.userTier && !userStatus.planStatus ? 'signedOut' : 'unknown'; + const accountScope = accountStatus === 'signedOut' ? null : currentAccountName; + const { officialQuotaInfo, contextModelCatalog, sessions } = await getTelemetrySources( + requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus + ); + const { conversations, activeConvSummary, activeCascadeId } = sessions; + + const officialQuota = officialQuotaInfo?.data || null; + const clientConfigs = userStatus?.cascadeModelConfigData?.clientModelConfigs || []; + + // 1. 构建官方实时配额池与动态模型目录 + const { dynamicModelMap, quotaPoolsMap } = buildOfficialQuotaPools( + officialQuota, + clientConfigs + ); + + const resolveStepModel = createStepModelResolver(dynamicModelMap); + + // 3. 计算当前活跃根会话及其子代理的步骤指标、10 通道上下文拆解与按模型汇总 + const reportedContextLimits = new Map(); + const knownUpstreamByModelKey = buildKnownUpstreamModelMap(reportedContextLimits); + const activeEntry = findTrajectoryCacheEntry(activeCascadeId); + const modelInputs = { + catalogRevision: pricingCatalogRevision, + phaseEpoch: getPricingPhaseEpoch(), + dynamicModelMap, + }; + const { + activeConversation: assembledActiveConversation, + activeFamilyCascadeIds, + latestFamilyStep, + } = buildActiveConversationAssembly({ + activeCascadeId, + activeConvSummary, + activeEntry, + resolveStepModel, + knownUpstreamByModelKey, + modelInputs, + accountScope, + }); + + // 4. 识别当前活跃会话家族绑定的模型池(与 quota-pools.mjs 保持一致,将 Other 第三方模型归入 Claude & GPT) + const { activePoolKey, activeLive5h, activeLiveWeekly } = resolveActivePoolKeyFromStep( + latestFamilyStep, + quotaPoolsMap + ); // 全局账号周期锚点采用稳定的配额池优先级(Gemini -> Argon -> Carbon -> Claude & GPT), // 防止切换不同会话时全局消费统计(consumption.presets.week / 5h)因重置时间偏移而突变 @@ -1275,84 +1625,24 @@ export async function buildTelemetryPayloadInternal( modelInputs, }); - const emptyCycleSummary = () => ({ - calls: 0, - tokens: 0, - inputTokens: 0, - cacheReadTokens: 0, - outputTokens: 0, - costUsd: 0, - unpricedCalls: 0, - }); for (const [pk, poolObj] of quotaPoolsMap.entries()) { const pStats = poolCycleStats?.get(pk); - poolObj.cycle5h = pStats?.cycle5h || emptyCycleSummary(); - poolObj.cycleWeekly = pStats?.cycleWeekly || emptyCycleSummary(); + poolObj.cycle5h = pStats?.cycle5h || createEmptyCycleSummary(); + poolObj.cycleWeekly = pStats?.cycleWeekly || createEmptyCycleSummary(); } // 6. 组装当前活跃配额池与每周限额视图数据 - const familyPoolQuota = quotaPoolsMap.get(activePoolKey); - const activePoolLabel = familyPoolQuota?.poolLabel || activePoolKey; - const activePoolQuota = familyPoolQuota || { - poolKey: activePoolKey, - poolLabel: activePoolKey === 'Unknown' ? '未知' : activePoolKey, - poolName: - activePoolKey === 'Carbon' - ? 'Gemini 4 Carbon 模型池' - : activePoolKey === 'Argon' - ? 'Gemini 4 Argon 模型池' - : activePoolKey === 'Gemini' - ? 'Gemini 模型池' - : activePoolKey === 'Claude & GPT' - ? 'Claude & GPT 模型池' - : '模型池未知', - family: activePoolKey, - isAvailable: Boolean(activeLive5h || activeLiveWeekly), - has5h: Boolean(activeLive5h), - hasWeekly: Boolean(activeLiveWeekly), - remainingPct: activeLive5h?.remainingPct ?? null, - remainingIntPct: activeLive5h?.remainingIntPct ?? null, - usedPct: activeLive5h?.usedPct ?? null, - resetTime: activeLive5h?.resetTime || null, - weeklyRemainingPct: activeLiveWeekly?.remainingPct ?? null, - weeklyRemainingIntPct: activeLiveWeekly?.remainingIntPct ?? null, - weeklyUsedPct: activeLiveWeekly?.usedPct ?? null, - weeklyResetTime: activeLiveWeekly?.resetTime || null, - cycle5h: emptyCycleSummary(), - cycleWeekly: emptyCycleSummary(), - models: [], - }; - - const fallbackWeeklyPct = - settings.weeklyLimitMode === 'custom_cost' - ? weekBucket.unpricedCalls > 0 - ? null - : Math.min( - 100, - +((weekBucket.costUsd / Math.max(1, settings.weeklyCostBudget)) * 100).toFixed(1) - ) - : Math.min( - 100, - +((weekBucket.totalTokens / Math.max(1000, settings.weeklyTokenBudget)) * 100).toFixed(1) - ); - - const useOfficialWeekly = Boolean(activeLiveWeekly) && !isCustomWeeklyMode; - - const weeklyUsedPct = useOfficialWeekly - ? activeLiveWeekly.usedPct - : isCustomWeeklyMode - ? fallbackWeeklyPct - : null; - const weeklyRemainingPct = useOfficialWeekly - ? activeLiveWeekly.remainingPct - : isCustomWeeklyMode && fallbackWeeklyPct !== null - ? +(100 - fallbackWeeklyPct).toFixed(1) - : null; - const weeklyRemainingIntPct = useOfficialWeekly - ? activeLiveWeekly.remainingIntPct - : isCustomWeeklyMode && fallbackWeeklyPct !== null - ? Math.max(0, Math.floor(100 - fallbackWeeklyPct)) - : null; + const { activePoolQuota, weeklyQuota } = buildActivePoolAndWeeklyQuotas({ + activePoolKey, + activeLive5h, + activeLiveWeekly, + quotaPoolsMap, + isCustomWeeklyMode, + settings, + weekBucket, + quotaWeekBucket, + poolsWeeklySummary, + }); const g1CreditEntry = (userStatus?.userTier?.availableCredits || []).find( (c) => c?.creditType === 'GOOGLE_ONE_AI' @@ -1723,7 +2013,6 @@ export async function buildTelemetryPayloadInternal( }); } - const officialFallbackWeekBucket = quotaWeekBucket || weekBucket; const finalPayload = { timestamp: new Date().toISOString(), hostPlatform: process.platform || 'unknown', @@ -1779,53 +2068,7 @@ export async function buildTelemetryPayloadInternal( sessionUnpricedCalls: qStats.sessionUnpricedCalls, }; }), - activeConversation: { - cascadeId: activeCascadeId, - title: activeConvSummary?.title || '当前会话', - ...(activeConvSummary?.swarmTitle ? { swarmTitle: activeConvSummary.swarmTitle } : {}), - isRunning: activeConvSummary?.status === 'CASCADE_RUN_STATUS_RUNNING', - status: activeConvSummary?.status || 'IDLE', - liveActivity: mainAgentTelemetry.liveActivity || null, - stepCount: enrichedActiveSteps.length, - hasSubagents: subAgentTelemetries.length > 0, - subagentCount: subAgentTelemetries.length, - swarmCount: swarmWorkerCount, - normalSubagentCount: normalSubCount, - sideQuestionCount, - totalStepsAllAgents: subAgentTelemetries.length - ? allCombinedEnrichedSteps.length - : enrichedActiveSteps.length, - latestTokPerSec: latestEnriched?.tokPerSec ?? null, - latestTtftSec: latestEnriched?.ttftSec ?? null, - latestSpeedReason: latestEnriched?.selectedSpeedReason ?? null, - avgTokPerSec: sessionAvgTokPerSec, - speedSummary: sessionSpeed, - ttftSummary: sessionTtft, - latestStepCostUsd: latestEnriched?.costUsd ?? null, - sessionCostUsd: roundSessionCost(sessionCostUsd), - sessionUnpricedCalls, - inputTokens: sessionInputTokens, - cacheReadTokens: sessionCacheReadTokens, - outputTokens: sessionOutputTokens, - totalTokens: sessionInputTokens + sessionCacheReadTokens + sessionOutputTokens, - latestPromptTokens: latestEnriched - ? Number(latestEnriched.inputTokens || 0) + Number(latestEnriched.cacheReadTokens || 0) - : 0, - latestCacheHitPct, - sessionCacheHitPct, - hasKnownModel: Boolean(latestEnriched?.hasKnownModel), - activeBaseModelShort: latestEnriched?.baseModelShort || '', - activeBaseModelLabel: latestEnriched?.baseModelLabel || '', - activeModelShort: latestEnriched?.modelShort || '模型未知', - activeModelLabel: latestEnriched?.modelLabel || '模型未知', - activeModelUpstream: - latestEnriched?.modelUpstream || latestEnriched?.modelShort || '模型未知', - context, - recentSteps: mainUnit.recentSteps, - modelBreakdown: mainModelBreakdown, - agents: allAgents, - aggregated: aggregatedTelemetry, - }, + activeConversation: assembledActiveConversation, consumption: { revision: usageRevision, selectedRange: { @@ -1856,41 +2099,7 @@ export async function buildTelemetryPayloadInternal( const order = { Gemini: 0, Argon: 1, Carbon: 2, 'Claude & GPT': 3 }; return (order[a.family] ?? 99) - (order[b.family] ?? 99); }), - weekly: { - isOfficial: useOfficialWeekly, - poolFamily: activePoolKey, - title: isCustomWeeklyMode - ? '每周限额 (自定义本机)' - : `每周限额 (${activePoolLabel && activePoolLabel !== 'Unknown' ? activePoolLabel : '当前'})`, - calls: isCustomWeeklyMode - ? weekBucket.calls - : poolsWeeklySummary - ? poolsWeeklySummary.calls - : officialFallbackWeekBucket.calls, - tokens: isCustomWeeklyMode - ? weekBucket.totalTokens - : poolsWeeklySummary - ? poolsWeeklySummary.tokens - : officialFallbackWeekBucket.totalTokens, - costUsd: isCustomWeeklyMode - ? weekBucket.costUsd - : poolsWeeklySummary - ? poolsWeeklySummary.costUsd - : officialFallbackWeekBucket.costUsd, - unpricedCalls: isCustomWeeklyMode - ? weekBucket.unpricedCalls - : poolsWeeklySummary - ? poolsWeeklySummary.unpricedCalls - : officialFallbackWeekBucket.unpricedCalls, - usedPct: weeklyUsedPct, - remainingPct: weeklyRemainingPct, - remainingIntPct: weeklyRemainingIntPct, - resetTime: useOfficialWeekly - ? activeLiveWeekly.resetTime - : isCustomWeeklyMode - ? getNextMondayResetIso() - : null, - }, + weekly: weeklyQuota, }, modelBreakdown, }; @@ -1898,9 +2107,22 @@ export async function buildTelemetryPayloadInternal( lastCompletedTelemetrySnapshot = { lsAddr: String(lsRuntimeEndpoint.addr || ''), weeklyLimitMode: settings.weeklyLimitMode, + weeklyTokenBudget: settings.weeklyTokenBudget, + weeklyCostBudget: settings.weeklyCostBudget, catalogRevision: modelInputs.catalogRevision, phaseEpoch: modelInputs.phaseEpoch, basePayload: finalPayload, + sessions: { + conversations, + }, + knownUpstreamByModelKey, + quotaContext: { + quotaPoolsMap, + isCustomWeeklyMode, + weekBucket, + quotaWeekBucket, + poolsWeeklySummary, + }, aggContext: { cycleAnchors, isCustomWeeklyMode, @@ -1935,12 +2157,125 @@ function resolveValidFastSnapshot() { return null; } const latestSettings = loadSettings(); - if (latestSettings.weeklyLimitMode !== snap.weeklyLimitMode) { + if ( + latestSettings.weeklyLimitMode !== snap.weeklyLimitMode || + latestSettings.weeklyTokenBudget !== snap.weeklyTokenBudget || + latestSettings.weeklyCostBudget !== snap.weeklyCostBudget + ) { return null; } return snap; } +function entryNeedsLazyTelemetryUpgrade(entry) { + if (!entry || !Array.isArray(entry.steps) || entry.steps.length === 0) return false; + return ( + !entry.turnRailTelemetry || + !entry.anomalyTelemetry || + entry.contextGroupsTelemetry !== 2 + ); +} + +function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) { + const snap = resolveValidFastSnapshot(); + if (!snap || !Array.isArray(snap.sessions?.conversations)) return null; + + const convList = snap.sessions.conversations; + const reqLower = String(requestedConvId || '').trim().toLowerCase(); + const activeConvSummary = reqLower + ? convList.find((c) => String(c?.cascadeId || '').toLowerCase() === reqLower) || + convList.find((c) => + (c?.subagents || []).some((s) => String(s?.cascadeId || '').toLowerCase() === reqLower) + ) || + null + : convList[0] || null; + if (!activeConvSummary?.cascadeId) return null; + + const activeCascadeId = activeConvSummary.cascadeId; + const activeEntry = findTrajectoryCacheEntry(activeCascadeId); + if (!activeEntry) return null; + + const subagentSummaries = Array.isArray(activeConvSummary.subagents) + ? activeConvSummary.subagents + : []; + let needsBackgroundSync = + activeConvSummary.status === 'CASCADE_RUN_STATUS_RUNNING' || + entryNeedsLazyTelemetryUpgrade(activeEntry); + if (!needsBackgroundSync) { + for (const subSum of subagentSummaries) { + if (subSum?.status === 'CASCADE_RUN_STATUS_RUNNING') { + needsBackgroundSync = true; + break; + } + const subEntry = findTrajectoryCacheEntry(subSum?.cascadeId); + if (!subEntry || entryNeedsLazyTelemetryUpgrade(subEntry)) { + needsBackgroundSync = true; + break; + } + } + } + + const settings = loadSettings(); + const { + activeConversation, + activeFamilyCascadeIds, + latestFamilyStep, + } = buildActiveConversationAssembly({ + activeCascadeId, + activeConvSummary, + activeEntry, + resolveStepModel: snap.aggContext.resolveStepModel, + knownUpstreamByModelKey: snap.knownUpstreamByModelKey, + modelInputs: snap.aggContext.modelInputs, + accountScope: snap.aggContext.currentAccountName, + }); + + const { activePoolKey, activeLive5h, activeLiveWeekly } = resolveActivePoolKeyFromStep( + latestFamilyStep, + snap.quotaContext.quotaPoolsMap + ); + const { activePoolQuota, weeklyQuota } = buildActivePoolAndWeeklyQuotas({ + activePoolKey, + activeLive5h, + activeLiveWeekly, + quotaPoolsMap: snap.quotaContext.quotaPoolsMap, + isCustomWeeklyMode: snap.quotaContext.isCustomWeeklyMode, + settings, + weekBucket: snap.quotaContext.weekBucket, + quotaWeekBucket: snap.quotaContext.quotaWeekBucket, + poolsWeeklySummary: snap.quotaContext.poolsWeeklySummary, + }); + + const sessionUsage = aggregateSessionUsageForFamily({ + filterOpts, + cycleAnchors: snap.aggContext.cycleAnchors, + isCustomWeeklyMode: snap.aggContext.isCustomWeeklyMode, + currentAccountName: snap.aggContext.currentAccountName, + activeCascadeId, + activeFamilyCascadeIds, + resolveStepModel: snap.aggContext.resolveStepModel, + quotaPoolsMap: snap.quotaContext.quotaPoolsMap, + }); + + return { + scope: 'conversation', + timestamp: new Date().toISOString(), + uiBundleVersion: snap.basePayload.uiBundleVersion || computeRuntimeCodeVersion(), + account: snap.basePayload.account, + activeCascadeId, + activeConversation, + quotas: { + activePool: activePoolQuota, + weekly: weeklyQuota, + }, + consumption: { + session: sessionUsage.finalizedSelectedSession, + sessionPresets: sessionUsage.sessionPresets, + }, + needsBackgroundSync, + }; +} + function tryBuildFastConsumptionPayload(filterOpts = {}) { const snap = resolveValidFastSnapshot(); if (!snap) return null; @@ -2036,6 +2371,12 @@ export function buildTelemetryPayload( filterOpts = {} ) { if (!forceQuotaRefresh) { + if (filterOpts?.scope === 'conversation') { + const convPayload = tryBuildFastConversationPayload(requestedConvId, filterOpts); + if (convPayload) { + return Promise.resolve(convPayload); + } + } if (filterOpts?.scope === 'consumption-presets') { const presetsPayload = tryBuildConsumptionPresetsPayload(); if (presetsPayload) { diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs index c5b8397..d196032 100644 --- a/sidecars/panel/backend/usage-aggregator.mjs +++ b/sidecars/panel/backend/usage-aggregator.mjs @@ -840,11 +840,158 @@ function sameUsageEntries(previous, current) { return previous.length === current.length && current.every((entry, index) => { const before = previous[index]; return entry.steps === before.steps && entry.cascadeId === before.cascadeId && - entry.appSource === before.appSource && entry.accountName === before.accountName && - entry.isCurrentConv === before.isCurrentConv; + entry.appSource === before.appSource && entry.accountName === before.accountName; }); } +function buildFamilySig(familySet) { + if (!(familySet instanceof Set) || familySet.size === 0) return ''; + return Array.from(familySet).sort().join(','); +} + +function computeFamilySessionBuckets({ + entries, + familySet, + presetKeys = [], + presetWindows = {}, + selectedWindow, + isCustomWeeklyMode = false, + poolCycleBuckets = new Map(), + normalizedQuotaAccount = '', + nowMs = Date.now(), + resolveStepModel, + weekStartMs = 0, +}) { + const sessionBuckets = {}; + for (const k of presetKeys) { + sessionBuckets[k] = createUsageBucket(); + } + const selectedSessionBucket = + (selectedWindow?.key && sessionBuckets[selectedWindow.key]) || createUsageBucket(); + if (!(familySet instanceof Set) || familySet.size === 0) { + const sessionPresets = {}; + for (const k of presetKeys) { + sessionPresets[k] = finalizeUsageBucket(sessionBuckets[k]); + } + return { + finalizedSelectedSession: finalizeUsageBucket(selectedSessionBucket), + sessionPresets, + }; + } + + const hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon'); + const hasDedicatedArgonPool = poolCycleBuckets.has('Argon'); + const poolByModel = new Map(); + const effectiveWeekStartMs = weekStartMs || presetWindows.week?.startMs || 0; + const cycleStartFallbackMs = + presetWindows.cycle?.startMs ?? + (selectedWindow?.key === 'cycle' ? selectedWindow.startMs : 0); + + for (const entry of entries || []) { + const cidLower = String(entry?.cascadeId || '').toLowerCase(); + if (!cidLower || !familySet.has(cidLower)) continue; + const entryOwner = normalizeOwnerAccount(entry.accountName); + for (const st of entry.steps || []) { + if (!st || typeof st !== 'object') continue; + const stepOwner = normalizeOwnerAccount(st.accountName) || entryOwner; + const includeInQuotaPools = + normalizedQuotaAccount === null + ? false + : normalizedQuotaAccount === '' + ? true + : stepOwner === normalizedQuotaAccount; + const mInfo = resolveStepModel(st); + const inTok = safeTok(st.inputTokens); + const cacheTok = safeTok(st.cacheReadTokens); + const outTok = safeTok(st.outputTokens); + const thinkTok = safeTok(st.thinkingTokens); + const respTok = + st.responseTokens !== undefined && st.responseTokens !== null + ? safeTok(st.responseTokens) + : Math.max(0, outTok - thinkTok); + const stepTotalTokens = inTok + cacheTok + outTok; + const stepCost = computeStepCost(st, mInfo.pricing); + const resolvedCost = Number.isFinite(stepCost) ? stepCost : 0; + const unpriced = stepCost === null ? 1 : 0; + const tMs = Number(st.createdAtMs) > 0 ? Number(st.createdAtMs) : 0; + const savedCost = mInfo.pricing + ? (cacheTok / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache) + : 0; + const stepUsage = { + inTok, + cacheTok, + outTok, + thinkTok, + respTok, + stepTotalTokens, + resolvedCost, + savedCost, + unpriced, + }; + + const poolBucketEntry = + poolCycleBuckets.size > 0 + ? resolvePoolBucketForStep( + st, + mInfo, + poolCycleBuckets, + poolByModel, + hasDedicatedCarbonPool, + hasDedicatedArgonPool + ) + : null; + + let inCurrentCycle = false; + if (tMs > 0 && tMs <= nowMs) { + if (isCustomWeeklyMode) { + inCurrentCycle = tMs >= effectiveWeekStartMs; + } else if (poolCycleBuckets.size > 0) { + const effCycleStartMs = poolBucketEntry + ? poolBucketEntry.startWkMs + : cycleStartFallbackMs; + inCurrentCycle = includeInQuotaPools && tMs >= effCycleStartMs; + } else { + inCurrentCycle = includeInQuotaPools && tMs >= cycleStartFallbackMs; + } + } + + for (const k of presetKeys) { + const w = presetWindows[k]; + const matchesPreset = + k === 'all' + ? true + : k === 'cycle' + ? inCurrentCycle + : tMs > 0 && tMs >= w.startMs && tMs <= w.endMs; + if (matchesPreset) { + accumulateStepIntoBucket(sessionBuckets[k], stepUsage, entry.cascadeId); + } + } + + if (selectedWindow && (!sessionBuckets[selectedWindow.key] || selectedWindow.key === 'custom')) { + const inSelectedWindow = + selectedWindow.key === 'all' + ? true + : selectedWindow.key === 'cycle' + ? inCurrentCycle + : tMs > 0 && tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs; + if (inSelectedWindow) { + accumulateStepIntoBucket(selectedSessionBucket, stepUsage, entry.cascadeId); + } + } + } + } + + const sessionPresets = {}; + for (const k of presetKeys) { + sessionPresets[k] = finalizeUsageBucket(sessionBuckets[k]); + } + return { + finalizedSelectedSession: finalizeUsageBucket(selectedSessionBucket), + sessionPresets, + }; +} + function sortedUsageTimestamps(entries) { const dates = new Float64Array(entries.reduce((sum, entry) => sum + entry.steps.length, 0)); let count = 0; @@ -971,6 +1118,7 @@ export function aggregateMultiWindowUsage({ const perSourceStats = new Map(); const allEntriesToAggregate = collectUsageEntriesToAggregate(familySet); + const familySig = buildFamilySig(familySet); const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : ''; const quotaWindows = Array.from(poolCycleBuckets, ([key, { start5hMs, startWkMs }]) => [ @@ -1002,12 +1150,44 @@ export function aggregateMultiWindowUsage({ ) { snapshot.ranges.delete(selectedWindow.key); snapshot.ranges.set(selectedWindow.key, previous); + if (previous.familySig === familySig) { + return { + ...previous.result, + usageRevision: snapshot.revision, + selectedWindow: effectivePrevWin, + trendStartMs: trend.start, + trendEndMs: trend.end, + }; + } + const { finalizedSelectedSession: nextSelSession, sessionPresets } = + computeFamilySessionBuckets({ + entries: allEntriesToAggregate, + familySet, + presetKeys, + presetWindows, + selectedWindow, + isCustomWeeklyMode, + poolCycleBuckets, + normalizedQuotaAccount, + nowMs, + resolveStepModel, + }); + const prevPresets = previous.result.finalizedPresets || {}; + const nextFinalizedPresets = {}; + for (const k of presetKeys) { + nextFinalizedPresets[k] = { + ...(prevPresets[k] || { label: presetWindows[k].label }), + session: sessionPresets[k], + }; + } return { ...previous.result, usageRevision: snapshot.revision, selectedWindow: effectivePrevWin, trendStartMs: trend.start, trendEndMs: trend.end, + finalizedSelectedSession: nextSelSession, + finalizedPresets: nextFinalizedPresets, }; } } @@ -1324,6 +1504,7 @@ export function aggregateMultiWindowUsage({ const { ranges } = lastUsageSnapshot; ranges.delete(selectedWindow.key); ranges.set(selectedWindow.key, { + familySig, windows, selectedWindow, effectiveSelectedWindow, @@ -1387,6 +1568,7 @@ export function aggregateSelectedWindowUsage({ const allEntriesToAggregate = Array.isArray(precollectedEntries) ? precollectedEntries : collectUsageEntriesToAggregate(familySet); + const familySig = buildFamilySig(familySet); const currentYear = new Date(nowMs).getFullYear(); const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : ''; @@ -1426,12 +1608,28 @@ export function aggregateSelectedWindowUsage({ ) ) { const res = candidate.result; + const resolvedSelectedSession = + candidate.familySig === familySig + ? res.finalizedSelectedSession + : computeFamilySessionBuckets({ + entries: allEntriesToAggregate, + familySet, + presetKeys: [], + presetWindows: {}, + selectedWindow, + isCustomWeeklyMode, + poolCycleBuckets, + normalizedQuotaAccount, + nowMs, + resolveStepModel, + weekStartMs, + }).finalizedSelectedSession; return { usageRevision: snapshot.revision, selectedWindow: effectivePrevWin, trendStartMs: trend.start, trendEndMs: trend.end, - finalizedSelectedSession: res.finalizedSelectedSession, + finalizedSelectedSession: resolvedSelectedSession, finalizedSelectedAccount: res.finalizedSelectedAccount, trendSeries: res.trendSeries, sourcesBreakdown: res.sourcesBreakdown, @@ -1658,6 +1856,7 @@ export function aggregateSelectedWindowUsage({ snapshot.selectedRanges ??= new Map(); snapshot.selectedRanges.delete(selectedWindow.key); snapshot.selectedRanges.set(selectedWindow.key, { + familySig, selectedWindow, effectiveSelectedWindow, trend, @@ -1673,6 +1872,73 @@ export function aggregateSelectedWindowUsage({ return sliceResult; } +/** + * 轻量级单会话家族用量汇总(专为 `scope=conversation` 瞬切服务): + * 仅遍历当前选中根会话及其子代理步骤,不触碰其余历史会话与全局账户聚合缓存。 + */ +export function aggregateSessionUsageForFamily({ + filterOpts = {}, + cycleAnchors = {}, + isCustomWeeklyMode = false, + currentAccountName = '', + activeCascadeId = null, + activeFamilyCascadeIds = null, + resolveStepModel, + quotaPoolsMap = null, +}) { + const rawFamilyIds = + activeFamilyCascadeIds instanceof Set + ? Array.from(activeFamilyCascadeIds) + : activeCascadeId + ? [activeCascadeId] + : []; + const familySet = new Set(rawFamilyIds.map((id) => String(id || '').toLowerCase()).filter(Boolean)); + const nowMs = Date.now(); + const selectedWindow = resolveTimeWindow( + filterOpts.range || 'all', + filterOpts.startMs, + filterOpts.endMs, + nowMs, + cycleAnchors, + isCustomWeeklyMode + ); + const presetKeys = ['all', 'cycle', '5h', 'today', '24h', 'week', '7d', '14d', '30d']; + const presetWindows = {}; + for (const k of presetKeys) { + presetWindows[k] = resolveTimeWindow(k, 0, 0, nowMs, cycleAnchors, isCustomWeeklyMode); + } + const poolCycleBuckets = buildQuotaPoolCycleMap(quotaPoolsMap, nowMs); + const normalizedQuotaAccount = + currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName); + + const familyEntries = []; + for (const [cid, entry] of listCachedTrajectoryEntries()) { + if (!entry || !Array.isArray(entry.steps) || entry.steps.length === 0) continue; + const cidLower = String(cid || '').toLowerCase(); + if (!familySet.has(cidLower)) continue; + familyEntries.push({ + cascadeId: cid, + appSource: entry.appSource || 'standalone', + accountName: entry.accountName || '', + steps: entry.steps, + isCurrentConv: true, + }); + } + + return computeFamilySessionBuckets({ + entries: familyEntries, + familySet, + presetKeys, + presetWindows, + selectedWindow, + isCustomWeeklyMode, + poolCycleBuckets, + normalizedQuotaAccount, + nowMs, + resolveStepModel, + }); +} + /** * 批量预聚合全部 7 个用量页预设区间(复用同一次条目收集与时间剪枝),供前端进入「用量统计」时静默预取实现 0ms 瞬切。 */ diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 9d61edf..265e406 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/layout/TopSessionHeader.js b/sidecars/panel/src/components/layout/TopSessionHeader.js index bfb75df..7efcab1 100644 --- a/sidecars/panel/src/components/layout/TopSessionHeader.js +++ b/sidecars/panel/src/components/layout/TopSessionHeader.js @@ -14,6 +14,7 @@ import { formatConversationMeta, normalizeClientUpdateMode, resolveHostRouteMatch, + selectConversation, telemetryStore, triggerPluginUpdate, } from '../../store/telemetryStore.js'; @@ -33,8 +34,7 @@ export const TopSessionHeader = defineComponent({ options: [{ value: '', label: t('header.followLatest') }], onUpdateModelValue: (nextConvId) => { uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); - telemetryStore.setState({ selectedConversationId: nextConvId }); - fetchTelemetry({ force: false }); + void selectConversation(nextConvId); }, }); diff --git a/sidecars/panel/src/components/layout/WindowOverlayShell.js b/sidecars/panel/src/components/layout/WindowOverlayShell.js index 9758f3f..b608027 100644 --- a/sidecars/panel/src/components/layout/WindowOverlayShell.js +++ b/sidecars/panel/src/components/layout/WindowOverlayShell.js @@ -52,6 +52,7 @@ import { normalizeClientUpdateMode, normalizeClientWindowMountMode, resolveScopedConversation, + selectConversation, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, telemetryStore, @@ -1086,8 +1087,7 @@ export function mountWindowOverlay() { selectedAgentScope: 'all', ctxInspectorAgentId: 'auto', }); - telemetryStore.setState({ selectedConversationId: cascadeId }); - void fetchTelemetry({ force: false }); + void selectConversation(cascadeId); setMultiOpen(false); setPopoverOpen(true); } @@ -2567,13 +2567,12 @@ export function mountWindowOverlay() { if (currentRouteId === lastObservedRouteId) return; lastObservedRouteId = currentRouteId; const st = telemetryStore.getState(); - const patch = { hostRouteConversationId: currentRouteId }; - if (currentRouteId && st.selectedConversationId && st.selectedConversationId !== currentRouteId) { - patch.selectedConversationId = ''; - } + const nextSelectedId = + currentRouteId && st.selectedConversationId && st.selectedConversationId !== currentRouteId + ? '' + : st.selectedConversationId; uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); - telemetryStore.setState(patch); - void fetchTelemetry({ force: false }); + void selectConversation(nextSelectedId, { hostRouteConversationId: currentRouteId }); } const onDocMouseDown = (e) => { diff --git a/sidecars/panel/src/components/widgets/LiveActivityWidget.js b/sidecars/panel/src/components/widgets/LiveActivityWidget.js index 6472bd9..3973262 100644 --- a/sidecars/panel/src/components/widgets/LiveActivityWidget.js +++ b/sidecars/panel/src/components/widgets/LiveActivityWidget.js @@ -25,8 +25,8 @@ import { createSvgIcon } from '../../icons/SvgIcon.js'; import { getEffectiveLocale, t } from '../../i18n/index.js'; import { extractHostRouteCascadeId, - fetchTelemetry, resolveScopedConversation, + selectConversation, telemetryStore, } from '../../store/telemetryStore.js'; import { uiStore } from '../../store/uiStore.js'; @@ -499,8 +499,7 @@ export const LiveActivityWidget = defineComponent({ onSelectSession(item.cascadeId); } else if (item.cascadeId && item.cascadeId !== 'current') { uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); - telemetryStore.setState({ selectedConversationId: item.cascadeId }); - fetchTelemetry({ force: false }); + void selectConversation(item.cascadeId); } }; } diff --git a/sidecars/panel/src/core/httpClient.js b/sidecars/panel/src/core/httpClient.js index f18c9d3..653a39e 100644 --- a/sidecars/panel/src/core/httpClient.js +++ b/sidecars/panel/src/core/httpClient.js @@ -9,6 +9,15 @@ import { readInjectedWindowBridge } from '../../shared/window-bridge-protocol.mj const inFlightGets = new Map(); const activeControllers = new Map(); +export function abortSidecarApiKey(abortKey) { + if (!abortKey) return; + const prev = activeControllers.get(abortKey); + if (prev) { + activeControllers.delete(abortKey); + prev.abort(); + } +} + /** * 读取主窗口双栖模式下注入的本地桥接配置(`port`、`token`、`bundleVersion`、`stylesCss`)。 * diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index 53c531a..5ba27a6 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -4,7 +4,12 @@ */ import { createReactiveStore } from '../core/reactive.js'; -import { callSidecarApi, getWindowBridgeConfig, isWindowOverlayMode } from '../core/httpClient.js'; +import { + abortSidecarApiKey, + callSidecarApi, + getWindowBridgeConfig, + isWindowOverlayMode, +} from '../core/httpClient.js'; import { formatAgentBadgeText, formatAgentLabel, @@ -139,9 +144,11 @@ export const telemetryStore = createReactiveStore({ let pollTimer = null; let feedbackTimer = null; +let deferredConvSyncTimer = null; let activeBundleVersion = 0; let latestRequestSeq = 0; let latestConsumptionReqSeq = 0; +let latestConversationSwitchSeq = 0; let activeForceCount = 0; let consecutivePollFailures = 0; let inFlightTelemetryPoll = null; @@ -149,8 +156,10 @@ let inFlightPresetsPrefetch = null; let lastPrefetchedUsageRevision = 0; let consumptionCacheScopeSig = ''; const MAX_CONSUMPTION_RANGE_CACHE = 12; +const MAX_CONVERSATION_VIEW_CACHE = 12; const CONSUMPTION_PRESET_KEYS = ['cycle', 'today', '24h', '7d', '14d', '30d', 'all']; const consumptionRangeCache = new Map(); +const conversationViewCache = new Map(); let lastReceivedSteps = null; let loopActive = false; let loopIntervalMs = 2000; @@ -182,6 +191,14 @@ export function clearConsumptionRangeCache() { inFlightPresetsPrefetch = null; } +export function clearConversationViewCache() { + conversationViewCache.clear(); + if (deferredConvSyncTimer) { + clearTimeout(deferredConvSyncTimer); + deferredConvSyncTimer = null; + } +} + function buildConsumptionScopeSig(payload) { if (!payload || typeof payload !== 'object') return ''; const acct = payload.account || {}; @@ -195,10 +212,112 @@ function syncConsumptionCacheScope(payload) { if (!nextSig) return; if (consumptionCacheScopeSig && consumptionCacheScopeSig !== nextSig) { clearConsumptionRangeCache(); + clearConversationViewCache(); } consumptionCacheScopeSig = nextSig; } +function recordConversationViewToCache(payload) { + const active = payload?.activeConversation; + const cidLower = String(active?.cascadeId || '').trim().toLowerCase(); + if (!cidLower || !Array.isArray(active?.recentSteps)) return; + const entry = { + cascadeId: active.cascadeId, + activeConversation: active, + activePool: payload.quotas?.activePool || null, + weekly: payload.quotas?.weekly || null, + sessionConsumption: payload.consumption?.session || null, + sessionPresets: + payload.consumption?.sessionPresets || + (payload.consumption?.presets + ? Object.fromEntries( + Object.entries(payload.consumption.presets).map(([k, v]) => [k, v?.session || null]) + ) + : null), + stepRevision: String(payload.stepRevision || ''), + cachedAtMs: Date.now(), + }; + conversationViewCache.delete(cidLower); + conversationViewCache.set(cidLower, entry); + while (conversationViewCache.size > MAX_CONVERSATION_VIEW_CACHE) { + conversationViewCache.delete(conversationViewCache.keys().next().value); + } +} + +function resolveCachedConversationRootId(telemetry, effectiveConvId) { + const target = String(effectiveConvId || '').trim(); + const convs = Array.isArray(telemetry?.conversations) ? telemetry.conversations : []; + if (!target) { + return String(convs[0]?.cascadeId || '').trim().toLowerCase(); + } + const lower = target.toLowerCase(); + if (conversationViewCache.has(lower)) return lower; + const matchedRoot = convs.find( + (c) => + String(c?.cascadeId || '').toLowerCase() === lower || + (Array.isArray(c?.memberCascadeIds) && + c.memberCascadeIds.some((m) => String(m || '').toLowerCase() === lower)) + ); + return String(matchedRoot?.cascadeId || lower).trim().toLowerCase(); +} + +function applyConversationSliceToTelemetry(baseTelemetry, slice) { + if (!baseTelemetry || !slice?.activeConversation) return baseTelemetry; + const activeCidLower = String(slice.activeConversation.cascadeId || '').toLowerCase(); + const prevQuotas = baseTelemetry.quotas || {}; + const nextQuotas = + slice.activePool || slice.weekly + ? { + ...prevQuotas, + ...(slice.activePool ? { activePool: slice.activePool } : {}), + ...(slice.weekly ? { weekly: slice.weekly } : {}), + } + : prevQuotas; + + const prevCons = baseTelemetry.consumption || {}; + let nextPresets = prevCons.presets; + if (slice.sessionPresets && prevCons.presets && typeof prevCons.presets === 'object') { + nextPresets = { ...prevCons.presets }; + for (const [k, sBucket] of Object.entries(slice.sessionPresets)) { + if (sBucket && nextPresets[k]) { + nextPresets[k] = { ...nextPresets[k], session: sBucket }; + } + } + } + const nextCons = + slice.sessionConsumption || nextPresets !== prevCons.presets + ? { + ...prevCons, + ...(slice.sessionConsumption ? { session: slice.sessionConsumption } : {}), + ...(nextPresets !== prevCons.presets ? { presets: nextPresets } : {}), + } + : prevCons; + + const prevRunning = Array.isArray(baseTelemetry.runningConversations) + ? baseTelemetry.runningConversations + : null; + let nextRunning = prevRunning; + if (prevRunning && prevRunning.length > 0 && activeCidLower) { + let anyChanged = false; + const mapped = prevRunning.map((item) => { + const shouldSelect = String(item?.cascadeId || '').toLowerCase() === activeCidLower; + if (Boolean(item?.isCurrentSelected) === shouldSelect) return item; + anyChanged = true; + return { ...item, isCurrentSelected: shouldSelect }; + }); + if (anyChanged) nextRunning = mapped; + } + + return { + ...baseTelemetry, + ...(slice.stepRevision ? { stepRevision: slice.stepRevision } : {}), + activeConversation: slice.activeConversation, + quotas: nextQuotas, + consumption: nextCons, + ...(nextRunning ? { runningConversations: nextRunning } : {}), + }; +} + function putConsumptionRangeCacheEntry(cacheKey, entry) { if (!cacheKey || !entry) return; consumptionRangeCache.delete(cacheKey); @@ -1012,6 +1131,7 @@ async function requestTelemetry(params, force) { let resolvedPayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev); syncConsumptionCacheScope(resolvedPayload); + recordConversationViewToCache(resolvedPayload); if (resolvedPayload?.consumption) { recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, { customStartMs: reqStartMs, @@ -1198,6 +1318,162 @@ async function fetchConsumptionRangeSlice({ } } +/** + * 快速切换当前查看的会话: + * - 命中前端 `conversationViewCache` 时,0ms 原子切换当前会话快照,并静默走轻量 `scope=conversation` 校准; + * - 未命中缓存时直接走零 LS RPC、零全盘扫描的 `scope=conversation` 通道; + * - 若后端提示该会话需要补读最新运行态或懒迁移字段(`needsBackgroundSync`),展示后再在后台静默补齐。 + */ +export async function selectConversation( + nextConvId, + { hostRouteConversationId = undefined } = {} +) { + const switchSeq = ++latestConversationSwitchSeq; + latestRequestSeq += 1; + inFlightTelemetryPoll = null; + abortSidecarApiKey('telemetry-poll'); + if (deferredConvSyncTimer) { + clearTimeout(deferredConvSyncTimer); + deferredConvSyncTimer = null; + } + + const targetSelectedId = String(nextConvId || '').trim(); + const prevSt = telemetryStore.getState(); + const nextHostRouteId = + hostRouteConversationId !== undefined + ? String(hostRouteConversationId || '').trim() + : prevSt.hostRouteConversationId; + const effectiveConvId = targetSelectedId || nextHostRouteId || ''; + const statePatch = { + selectedConversationId: targetSelectedId, + ...(hostRouteConversationId !== undefined ? { hostRouteConversationId: nextHostRouteId } : {}), + }; + + const prevTelemetry = prevSt.telemetry; + const lookupRootId = resolveCachedConversationRootId(prevTelemetry, effectiveConvId); + const cachedEntry = lookupRootId ? conversationViewCache.get(lookupRootId) : null; + const cachedSteps = + cachedEntry && cachedEntry.stepRevision + ? readDisplaySteps({ + stepRevision: cachedEntry.stepRevision, + activeConversation: cachedEntry.activeConversation, + }) + : null; + + if (cachedEntry && prevTelemetry) { + const optimisticTelemetry = applyConversationSliceToTelemetry(prevTelemetry, cachedEntry); + if (cachedSteps) { + lastReceivedSteps = cachedSteps; + } + telemetryStore.setState({ + ...statePatch, + telemetry: optimisticTelemetry, + }); + } else { + telemetryStore.setState(statePatch); + } + + const current = telemetryStore.getState(); + const params = new URLSearchParams(); + if (effectiveConvId) params.set('conversationId', effectiveConvId); + if (current.selectedTimeRange) params.set('range', current.selectedTimeRange); + if (current.selectedTimeRange === 'custom') { + if (current.customStartMs > 0) params.set('startMs', String(current.customStartMs)); + if (current.customEndMs > 0) params.set('endMs', String(current.customEndMs)); + } + params.set('stepDetails', 'display'); + params.set('stepRevision', cachedSteps?.revision || ''); + params.set('scope', 'conversation'); + + const reqSettingsRev = settingsRevision; + try { + const payload = await callSidecarApi(`/api/telemetry?${params}`, { + method: 'GET', + abortKey: 'conversation-switch', + }); + if (!payload || typeof payload !== 'object') return null; + if (switchSeq !== latestConversationSwitchSeq) return payload; + + const latestSt = telemetryStore.getState(); + const latestEffectiveId = + String(latestSt.selectedConversationId || latestSt.hostRouteConversationId || '').trim(); + if (latestEffectiveId !== effectiveConvId) return payload; + + const active = payload.activeConversation; + if (payload.stepsUnchanged) { + const stepsSource = + (cachedSteps && payload.stepRevision === cachedSteps.revision ? cachedSteps : null) || + (lastReceivedSteps && payload.stepRevision === lastReceivedSteps.revision + ? lastReceivedSteps + : null); + if (!active || !stepsSource) { + return fetchTelemetry({ force: false }); + } + active.recentSteps = stepsSource.recentSteps; + active.agents.forEach((agent, index) => { + const steps = stepsSource.agentSteps[index]; + if (steps) agent.recentSteps = steps; + }); + } + + if (payload.scope === 'conversation' && active) { + lastReceivedSteps = readDisplaySteps(payload) || lastReceivedSteps; + recordConversationViewToCache(payload); + const baseTelemetry = latestSt.telemetry; + if (baseTelemetry) { + const mergedTelemetry = applyConversationSliceToTelemetry(baseTelemetry, { + activeConversation: active, + activePool: payload.quotas?.activePool || null, + weekly: payload.quotas?.weekly || null, + sessionConsumption: payload.consumption?.session || null, + sessionPresets: payload.consumption?.sessionPresets || null, + stepRevision: payload.stepRevision || '', + }); + if (!isEquivalentTelemetry(baseTelemetry, mergedTelemetry)) { + telemetryStore.setState({ + telemetry: mergedTelemetry, + minuteTick: Math.floor(Date.now() / 30000), + }); + } + } else { + return fetchTelemetry({ force: false }); + } + if (payload.needsBackgroundSync && loopActive && typeof setTimeout === 'function') { + deferredConvSyncTimer = setTimeout(() => { + deferredConvSyncTimer = null; + if (switchSeq === latestConversationSwitchSeq && loopActive) { + void fetchTelemetry({ force: false }); + } + }, 35); + } + return payload; + } + + // 冷启动或全新未入缓存会话回退至完整载荷 + const resolvedPayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev); + syncConsumptionCacheScope(resolvedPayload); + lastReceivedSteps = readDisplaySteps(resolvedPayload) || lastReceivedSteps; + recordConversationViewToCache(resolvedPayload); + if (resolvedPayload?.consumption) { + recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, { + customStartMs: Number(current.customStartMs || 0), + customEndMs: Number(current.customEndMs || 0), + }); + } + if (!isEquivalentTelemetry(latestSt.telemetry, resolvedPayload)) { + telemetryStore.setState({ + telemetry: resolvedPayload, + minuteTick: Math.floor(Date.now() / 30000), + syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle', + }); + } + return resolvedPayload; + } catch (err) { + if (err?.name === 'AbortError' || switchSeq !== latestConversationSwitchSeq) return null; + return null; + } +} + /** * 切换「用量统计」时间范围: * - 命中前端 rangeCache 时,在单次 setState 内 0ms 原子更新概览/趋势/模型/来源(若 usageRevision 一致则 0 次 HTTP 请求); @@ -1482,8 +1758,13 @@ export async function saveSettingsPatch(patch) { } const needsTelemetryRecompute = patchKeys.some((k) => TELEMETRY_RECOMPUTE_SETTING_KEYS.has(k)); - if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) { + if ( + Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode') || + Object.prototype.hasOwnProperty.call(safePatch, 'weeklyTokenBudget') || + Object.prototype.hasOwnProperty.call(safePatch, 'weeklyCostBudget') + ) { clearConsumptionRangeCache(); + clearConversationViewCache(); } if (needsTelemetryRecompute) { inFlightTelemetryPoll = null; @@ -1549,6 +1830,7 @@ export async function resetAllSettings() { } inFlightTelemetryPoll = null; clearConsumptionRangeCache(); + clearConversationViewCache(); void fetchTelemetry({ force: false }); return res; } @@ -1556,6 +1838,7 @@ export async function resetAllSettings() { export async function rebuildTrajectoryCache() { const res = await callSidecarApi('/api/cache/rebuild', { method: 'POST', body: {} }); clearConsumptionRangeCache(); + clearConversationViewCache(); await fetchTelemetry({ force: true }); return res; } @@ -1563,6 +1846,7 @@ export async function rebuildTrajectoryCache() { export async function triggerCloudSync() { const res = await callSidecarApi('/api/cloud-sync', { method: 'POST', body: {} }); clearConsumptionRangeCache(); + clearConversationViewCache(); await fetchTelemetry({ force: true }); return res; } @@ -1636,6 +1920,10 @@ export function stopAsyncTelemetryLoop() { clearTimeout(feedbackTimer); feedbackTimer = null; } + if (deferredConvSyncTimer) { + clearTimeout(deferredConvSyncTimer); + deferredConvSyncTimer = null; + } } export { diff --git a/sidecars/panel/src/styles/views-consumption.css b/sidecars/panel/src/styles/views-consumption.css index 1da21cf..3e99a2b 100644 --- a/sidecars/panel/src/styles/views-consumption.css +++ b/sidecars/panel/src/styles/views-consumption.css @@ -684,6 +684,8 @@ .cons-source-row { gap: 5px; + width: 100%; + container-type: inline-size; } .cons-source-bar-hit { @@ -698,8 +700,90 @@ } .cons-source-foot { - justify-content: flex-end; + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: nowrap; + gap: 8px; + min-width: 0; min-height: 16px; + overflow: hidden; +} + +.cons-source-top-models { + display: flex; + align-items: center; + flex-wrap: nowrap; + gap: 8px; + flex: 1 1 auto; + min-width: 0; + overflow: hidden; + cursor: pointer; +} + +.cons-source-top-models[hidden] { + display: none; +} + +.cons-source-top-item { + display: inline-flex; + align-items: center; + gap: 4px; + flex: 0 1 auto; + min-width: 0; + max-width: 100%; + white-space: nowrap; + overflow: hidden; + line-height: 1.25; +} + +.cons-source-top-item:first-child { + flex-shrink: 0.5; +} + +.cons-source-top-dot { + width: 6px; + height: 6px; + flex-shrink: 0; +} + +.cons-source-top-name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + min-width: 0; + color: var(--text-secondary); + transition: color 120ms ease; +} + +.cons-source-top-models:hover .cons-source-top-name, +.cons-source-top-models.is-hovered .cons-source-top-name { + color: var(--text-primary); +} + +.cons-source-top-pct { + flex-shrink: 0; + white-space: nowrap; + color: var(--text-primary); + font-weight: 600; +} + +.cons-source-foot > .cons-calls-stat { + flex: 0 0 auto; + white-space: nowrap; + margin-left: auto; +} + +@container (max-width: 340px) { + .cons-source-top-item:nth-child(n + 3) { + display: none; + } +} + +@container (max-width: 210px) { + .cons-source-top-item:nth-child(n + 2) { + display: none; + } } .month-col.is-interactive { diff --git a/sidecars/panel/src/views/ConsumptionView.js b/sidecars/panel/src/views/ConsumptionView.js index 7c26f2c..f46b6e4 100644 --- a/sidecars/panel/src/views/ConsumptionView.js +++ b/sidecars/panel/src/views/ConsumptionView.js @@ -730,8 +730,23 @@ export const ConsumptionView = defineComponent({ return { el: segEl, refs: { segEl } }; } + function createSourceTopModelItem() { + const dotEl = h('span', { className: 'dot-swatch cons-model-dot cons-source-top-dot' }); + const nameEl = h('span', { className: 'cons-source-top-name' }); + const pctEl = h('strong', { className: 'cons-source-top-pct text-mono' }); + const itemEl = h('span', { className: 'cons-source-top-item' }, [dotEl, nameEl, pctEl]); + return { el: itemEl, refs: { itemEl, dotEl, nameEl, pctEl } }; + } + + function formatCompactSourceSharePct(pct) { + const num = Number(pct || 0); + if (!Number.isFinite(num) || num <= 0) return '0%'; + if (num >= 10) return `${Math.round(num)}%`; + return `${num.toFixed(1)}%`; + } + /** - * 创建客户端来源单行 DOM 结构(保留长尾合并分段配色进度条与右侧总调用数,悬停进度条弹出各模型明细浮层)。 + * 创建客户端来源单行 DOM 结构(保留长尾合并分段配色进度条、单行不换行的 Top 2-3 模型速览和右侧总调用数,悬停进度条或速览区弹出完整明细浮层)。 */ function createSourceBreakdownRow() { const nameTextEl = h('span', { className: 'cons-row-title-text' }); @@ -741,26 +756,39 @@ export const ConsumptionView = defineComponent({ const costEl = h('strong', { className: 'cons-row-cost text-mono' }); const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' }); const rowState = { hoverPayload: null }; + const bindPopoverHover = (targetEl) => ({ + onMouseEnter: (e) => { + if (rowState.hoverPayload) { + showBreakdownPopover(targetEl, rowState.hoverPayload, e?.clientX ?? null); + } + }, + onMouseMove: (e) => { + if (rowState.hoverPayload && activeHoverTargetEl === targetEl) { + positionBreakdownPopover(targetEl, e?.clientX ?? null); + } + }, + onMouseLeave: () => { + if (activeHoverTargetEl === targetEl) hideBreakdownPopover(); + }, + }); const barHitEl = h( 'div', { className: 'cons-source-bar-hit', - onMouseEnter: (e) => { - if (rowState.hoverPayload) { - showBreakdownPopover(barHitEl, rowState.hoverPayload, e?.clientX ?? null); - } - }, - onMouseMove: (e) => { - if (rowState.hoverPayload && activeHoverTargetEl === barHitEl) { - positionBreakdownPopover(barHitEl, e?.clientX ?? null); - } - }, - onMouseLeave: () => { - if (activeHoverTargetEl === barHitEl) hideBreakdownPopover(); - }, }, [trackEl] ); + const barHandlers = bindPopoverHover(barHitEl); + barHitEl.addEventListener('mouseenter', barHandlers.onMouseEnter); + barHitEl.addEventListener('mousemove', barHandlers.onMouseMove); + barHitEl.addEventListener('mouseleave', barHandlers.onMouseLeave); + + const topModelsEl = h('div', { className: 'cons-source-top-models', hidden: true }); + const topHandlers = bindPopoverHover(topModelsEl); + topModelsEl.addEventListener('mouseenter', topHandlers.onMouseEnter); + topModelsEl.addEventListener('mousemove', topHandlers.onMouseMove); + topModelsEl.addEventListener('mouseleave', topHandlers.onMouseLeave); + const callsLbl = h('span', { text: t('cons.footCalls') }); const callsVal = h('strong', { className: 'text-mono' }); @@ -775,6 +803,7 @@ export const ConsumptionView = defineComponent({ ]), barHitEl, h('div', { className: 'cons-item-foot cons-source-foot' }, [ + topModelsEl, h('span', { className: 'legend-left cons-calls-stat' }, [ callsLbl, callsVal, @@ -792,6 +821,7 @@ export const ConsumptionView = defineComponent({ costEl, barHitEl, trackEl, + topModelsEl, callsLbl, callsVal, rowState, @@ -855,6 +885,28 @@ export const ConsumptionView = defineComponent({ }, }); + const topModels = partitioned + .filter((seg) => !seg.isOther) + .slice(0, 3) + .map((seg) => ({ + key: seg.key, + label: seg.label, + pctText: formatCompactSourceSharePct(seg.pct), + color: seg.color, + })); + patchAttr(refs.topModelsEl, 'hidden', topModels.length === 0); + patchKeyedList(refs.topModelsEl, topModels, { + keyFn: (m) => m.key, + sigFn: (m) => `${m.key}:${m.label}:${m.pctText}:${m.color}`, + createRow: createSourceTopModelItem, + updateRow: (mRefs, m) => { + patchStyleVar(mRefs.dotEl, '--dot-color', m.color); + patchText(mRefs.nameEl, m.label); + patchText(mRefs.pctEl, m.pctText); + patchAttr(mRefs.itemEl, 'title', `${m.label} (${m.pctText})`); + }, + }); + refs.rowState.hoverPayload = total > 0 || callsCount > 0 ? { diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index 7e21a11..7e0e315 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -2698,6 +2698,8 @@ html[data-standalone="true"] .app-shell { .cons-source-row { gap: 5px; + width: 100%; + container-type: inline-size; } .cons-source-bar-hit { @@ -2712,8 +2714,90 @@ html[data-standalone="true"] .app-shell { } .cons-source-foot { - justify-content: flex-end; + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: nowrap; + gap: 8px; + min-width: 0; min-height: 16px; + overflow: hidden; +} + +.cons-source-top-models { + display: flex; + align-items: center; + flex-wrap: nowrap; + gap: 8px; + flex: 1 1 auto; + min-width: 0; + overflow: hidden; + cursor: pointer; +} + +.cons-source-top-models[hidden] { + display: none; +} + +.cons-source-top-item { + display: inline-flex; + align-items: center; + gap: 4px; + flex: 0 1 auto; + min-width: 0; + max-width: 100%; + white-space: nowrap; + overflow: hidden; + line-height: 1.25; +} + +.cons-source-top-item:first-child { + flex-shrink: 0.5; +} + +.cons-source-top-dot { + width: 6px; + height: 6px; + flex-shrink: 0; +} + +.cons-source-top-name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + min-width: 0; + color: var(--text-secondary); + transition: color 120ms ease; +} + +.cons-source-top-models:hover .cons-source-top-name, +.cons-source-top-models.is-hovered .cons-source-top-name { + color: var(--text-primary); +} + +.cons-source-top-pct { + flex-shrink: 0; + white-space: nowrap; + color: var(--text-primary); + font-weight: 600; +} + +.cons-source-foot > .cons-calls-stat { + flex: 0 0 auto; + white-space: nowrap; + margin-left: auto; +} + +@container (max-width: 340px) { + .cons-source-top-item:nth-child(n + 3) { + display: none; + } +} + +@container (max-width: 210px) { + .cons-source-top-item:nth-child(n + 2) { + display: none; + } } .month-col.is-interactive { diff --git a/sidecars/panel/test/backend.test.mjs b/sidecars/panel/test/backend.test.mjs index 0e1ad70..1fde589 100644 --- a/sidecars/panel/test/backend.test.mjs +++ b/sidecars/panel/test/backend.test.mjs @@ -2586,3 +2586,231 @@ test('scope=consumption and scope=consumption-presets bypass matchesConv, >30s i assert.doesNotMatch(requestedUrls[0], /force=1/); assert.doesNotMatch(requestedUrls[0], /fastRange=1/); }); + +test('scope=conversation switches sessions with zero LS RPCs, preserves usageRevision, reuses stepRevision/multi-agent cache, and powers 0ms client cache switching', async (t) => { + const clockMs = Date.parse('2026-11-19T14:00:00.000Z'); + const mkStep = (idx, offsetMs, model, tok) => ({ + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: new Date(clockMs - offsetMs).toISOString(), + completedAt: new Date(clockMs - offsetMs + 1000).toISOString(), + sourceTrajectoryStepInfo: { stepIndex: idx }, + modelUsage: { + model, + inputTokens: String(tok), + cacheReadTokens: '0', + outputTokens: '120', + }, + }, + plannerResponse: { response: `step-${idx}` }, + }); + + const h = backendHarness({ + clock: () => clockMs, + quotaSummary: { + groups: [ + { + displayName: 'Gemini', + remainingFraction: 0.85, + resetTime: new Date(clockMs + 3 * 3600_000).toISOString(), + }, + { + displayName: 'Claude & GPT', + remainingFraction: 0.42, + resetTime: new Date(clockMs + 4 * 3600_000).toISOString(), + }, + ], + }, + trajectories: { + 'conv-claude': { + trajectory: { + steps: [ + mkStep(1, 30 * 60_000, 'MODEL_CLAUDE_4_5_SONNET', 1200), + mkStep(2, 20 * 60_000, 'MODEL_CLAUDE_4_5_SONNET', 1800), + ], + }, + }, + 'conv-gemini': { + trajectory: { + steps: [ + mkStep(1, 10 * 60_000, 'MODEL_PLACEHOLDER_M37', 4000), + ], + }, + }, + 'conv-gemini-sub': { + trajectory: { + metadata: { + parentConversationId: 'conv-gemini', + rootConversationId: 'conv-gemini', + subagentSpec: { typeName: 'research', role: 'Helper' }, + }, + steps: [ + mkStep(1, 9 * 60_000, 'MODEL_PLACEHOLDER_M37', 900), + ], + }, + }, + }, + summaries: { + 'conv-claude': { + annotations: { title: 'Claude Session' }, + stepCount: 2, + lastModifiedTime: new Date(clockMs - 20 * 60_000).toISOString(), + status: 'CASCADE_RUN_STATUS_IDLE', + }, + 'conv-gemini': { + annotations: { title: 'Gemini Swarm' }, + stepCount: 1, + lastModifiedTime: new Date(clockMs - 10 * 60_000).toISOString(), + status: 'CASCADE_RUN_STATUS_IDLE', + }, + 'conv-gemini-sub': { + stepCount: 1, + lastModifiedTime: new Date(clockMs - 9 * 60_000).toISOString(), + status: 'CASCADE_RUN_STATUS_IDLE', + trajectoryMetadata: { + parentConversationId: 'conv-gemini', + rootConversationId: 'conv-gemini', + subagentSpec: { typeName: 'research', role: 'Helper' }, + }, + }, + }, + }); + + // 1. Initial full telemetry load on conv-gemini (multi-agent root) + const initRes = JSON.parse( + ( + await h.executeTelemetryAction({ + conversationId: 'conv-gemini', + range: 'today', + stepDetails: 'display', + stepRevision: '', + }) + ).body + ); + assert.equal(initRes.activeConversation.cascadeId, 'conv-gemini'); + assert.equal(initRes.activeConversation.subagentCount, 1); + assert.equal(initRes.quotas.activePool.family, 'Gemini'); + const initialUsageRev = Number(initRes.consumption.revision); + const rpcAfterInit = h.state.calls.length; + + // 2. Fast switch to conv-claude via scope=conversation: ZERO LS RPCs! + const switchClaude = JSON.parse( + ( + await h.executeTelemetryAction({ + conversationId: 'conv-claude', + range: 'today', + stepDetails: 'display', + stepRevision: '', + scope: 'conversation', + }) + ).body + ); + assert.equal(h.state.calls.length, rpcAfterInit, 'scope=conversation must make 0 LS RPC calls'); + assert.equal(switchClaude.scope, 'conversation'); + assert.equal(switchClaude.activeConversation.cascadeId, 'conv-claude'); + assert.equal(switchClaude.activeConversation.stepCount, 2); + assert.equal(switchClaude.activeConversation.recentSteps.length, 2); + assert.equal(switchClaude.quotas.activePool.family, 'Claude & GPT'); + assert.equal(switchClaude.consumption.session.calls, 2); + assert.equal(switchClaude.needsBackgroundSync, false); + assert.ok(switchClaude.stepRevision); + + // 3. Fast switch back to conv-gemini with cached stepRevision -> stepsUnchanged=true & 0 RPCs + const switchBackGemini = JSON.parse( + ( + await h.executeTelemetryAction({ + conversationId: 'conv-gemini', + range: 'today', + stepDetails: 'display', + stepRevision: initRes.stepRevision, + scope: 'conversation', + }) + ).body + ); + assert.equal(h.state.calls.length, rpcAfterInit); + assert.equal(switchBackGemini.scope, 'conversation'); + assert.equal(switchBackGemini.stepsUnchanged, true); + assert.equal(switchBackGemini.activeConversation.recentSteps, undefined); + assert.equal(switchBackGemini.quotas.activePool.family, 'Gemini'); + + // 4. Subsequent full poll on conv-claude keeps usageRevision identical (decoupled from isCurrentConv!) + const fullClaude = JSON.parse( + ( + await h.executeTelemetryAction({ + conversationId: 'conv-claude', + range: 'today', + stepDetails: 'display', + stepRevision: switchClaude.stepRevision, + }) + ).body + ); + assert.equal(fullClaude.consumption.revision, initialUsageRev); + assert.equal(fullClaude.stepsUnchanged, true); + assert.equal(fullClaude.consumption.session.calls, 2); + + // 5. Frontend selectConversation: first switch hits scope=conversation; repeat switch hits 0ms client cache + rehydrates stepsUnchanged + const { + clearConsumptionRangeCache, + clearConversationViewCache, + selectConversation, + stopAsyncTelemetryLoop, + telemetryStore, + } = await import('../src/store/telemetryStore.js'); + const prevTel = telemetryStore.getState().telemetry; + const prevSel = telemetryStore.getState().selectedConversationId; + t.after(() => { + stopAsyncTelemetryLoop(); + clearConsumptionRangeCache(); + clearConversationViewCache(); + telemetryStore.setState({ selectedConversationId: prevSel, telemetry: prevTel }); + }); + clearConversationViewCache(); + telemetryStore.setState({ selectedConversationId: 'conv-gemini', telemetry: initRes }, { sync: true }); + + const fetchedUrls = []; + t.mock.method(globalThis, 'fetch', async (url) => { + const u = String(url); + fetchedUrls.push(u); + const parsed = new URL(u, 'http://127.0.0.1'); + const q = Object.fromEntries(parsed.searchParams.entries()); + const out = await h.executeTelemetryAction(q); + return { ok: true, json: async () => JSON.parse(out.body) }; + }); + + // Seed cache by visiting conv-claude first + await selectConversation('conv-claude'); + assert.equal(fetchedUrls.length, 1); + assert.match(fetchedUrls[0], /scope=conversation/); + assert.match(fetchedUrls[0], /conversationId=conv-claude/); + assert.equal(telemetryStore.getState().telemetry.activeConversation.cascadeId, 'conv-claude'); + assert.equal(telemetryStore.getState().telemetry.quotas.activePool.family, 'Claude & GPT'); + + // Visit conv-gemini (cached from initRes? Let's visit once to cache, then toggle back to conv-claude for 0ms hit!) + await selectConversation('conv-gemini'); + assert.equal(telemetryStore.getState().telemetry.activeConversation.cascadeId, 'conv-gemini'); + + // Toggle back to conv-claude: store MUST update synchronously BEFORE fetch resolves! + let releaseSecondFetch; + t.mock.method(globalThis, 'fetch', async (url) => { + fetchedUrls.push(String(url)); + await new Promise((resolve) => { + releaseSecondFetch = resolve; + }); + const parsed = new URL(String(url), 'http://127.0.0.1'); + const out = await h.executeTelemetryAction(Object.fromEntries(parsed.searchParams.entries())); + return { ok: true, json: async () => JSON.parse(out.body) }; + }); + + const pendingSwitch = selectConversation('conv-claude'); + assert.equal( + telemetryStore.getState().telemetry.activeConversation.cascadeId, + 'conv-claude', + 'Repeat conversation switch must update activeConversation synchronously in 0ms from client LRU cache' + ); + assert.equal(telemetryStore.getState().telemetry.activeConversation.recentSteps.length, 2); + assert.match(fetchedUrls[fetchedUrls.length - 1], new RegExp(`stepRevision=${switchClaude.stepRevision}`)); + releaseSecondFetch(); + await pendingSwitch; + assert.equal(telemetryStore.getState().telemetry.activeConversation.recentSteps.length, 2); +}); diff --git a/sidecars/panel/test/consumption-bars.test.mjs b/sidecars/panel/test/consumption-bars.test.mjs index 4363ca2..4bd7f7b 100644 --- a/sidecars/panel/test/consumption-bars.test.mjs +++ b/sidecars/panel/test/consumption-bars.test.mjs @@ -423,8 +423,18 @@ test('ConsumptionView: Top Models color dot + % bar, clutter-free Client Sources .reduce((s, el) => s + parsePctVar(el, '--seg-w'), 0); assert.ok(Math.abs(argonSegSum - 50) < 0.1, `Expected 50% width for 4-argon row, got ${argonSegSum}`); - // 2. Client Sources: NO bottom model list text dump; 3 tail models (<1.5%) fold into 1 neutral '__other__' segment! + // 2. Client Sources: NO multi-line .cons-source-model-chip dump; renders single-line Top 2-3 models + 1 merged '__other__' segment on the bar! assert.equal(sourceRows[0].querySelectorAll('.cons-source-model-chip').length, 0); + const appTopItems = sourceRows[0].querySelectorAll('.cons-source-top-item'); + assert.equal(appTopItems.length, 3, 'Should show top 3 non-other models in single-line footer'); + assert.equal(appTopItems[0].querySelector('.cons-source-top-name')?.textContent, '4-argon'); + assert.equal(appTopItems[0].querySelector('.cons-source-top-pct')?.textContent, '50%'); + assert.equal(appTopItems[0].querySelector('.cons-source-top-dot')?.style.getPropertyValue('--dot-color'), argonDotColor); + assert.equal(appTopItems[1].querySelector('.cons-source-top-name')?.textContent, '4-carbon'); + assert.equal(appTopItems[1].querySelector('.cons-source-top-pct')?.textContent, '31%'); + assert.equal(appTopItems[2].querySelector('.cons-source-top-name')?.textContent, '3.8-flash-n'); + assert.equal(appTopItems[2].querySelector('.cons-source-top-pct')?.textContent, '16%'); + const appSegs = sourceRows[0].querySelectorAll('.cons-model-seg'); assert.equal(appSegs.length, 4, '3 main models + 1 merged other segment'); assert.equal(appSegs[0].style.getPropertyValue('--seg-color'), argonDotColor); @@ -432,7 +442,7 @@ test('ConsumptionView: Top Models color dot + % bar, clutter-free Client Sources const appBarSum = appSegs.reduce((s, el) => s + parsePctVar(el, '--seg-w'), 0); assert.ok(Math.abs(appBarSum - 80) < 0.1); - // Hovering Client Source bar hit area opens shared popover with model details + '其他 (3)' + // Hovering Client Source bar hit area OR top-models summary opens shared popover with model details + '其他 (3)' const popover = view.refs.breakdownPopoverEl; assert.equal(popover.hasAttribute('hidden'), true); const appBarHit = sourceRows[0].querySelector('.cons-source-bar-hit'); @@ -448,6 +458,20 @@ test('ConsumptionView: Top Models color dot + % bar, clutter-free Client Sources appBarHit.dispatchEvent({ type: 'mouseleave' }); assert.equal(popover.hasAttribute('hidden'), true); + const appTopModelsEl = sourceRows[0].querySelector('.cons-source-top-models'); + appTopModelsEl.dispatchEvent({ type: 'mouseenter', clientX: 90 }); + assert.equal(popover.hasAttribute('hidden'), false); + assert.equal(popover.querySelector('.trend-tip-time')?.textContent, 'Antigravity App'); + appTopModelsEl.dispatchEvent({ type: 'mouseleave' }); + assert.equal(popover.hasAttribute('hidden'), true); + + // Verify single-line non-wrapping CSS rules exist for client source top models + const { readFileSync } = await import('node:fs'); + const consCss = readFileSync(new URL('../src/styles/views-consumption.css', import.meta.url), 'utf8'); + assert.match(consCss, /\.cons-source-foot\s*\{[\s\S]*flex-wrap:\s*nowrap/); + assert.match(consCss, /\.cons-source-top-models\s*\{[\s\S]*flex-wrap:\s*nowrap/); + assert.match(consCss, /@container\s*\(max-width:\s*340px\)\s*\{\s*\.cons-source-top-item:nth-child\(n\s*\+\s*3\)/); + // 3. Monthly Breakdown: old 4-channel legend removed; Nov column renders model-colored vertical segments & hover popover assert.equal(view.el.querySelectorAll('.monthly-legend').length, 0); const monthCols = view.el.querySelectorAll('.month-col'); From 88abdaf56e5c8a807d82a0f7a78545cc63286663 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Thu, 19 Nov 2026 23:29:56 +0900 Subject: [PATCH 13/14] fix(panel): drop decimals at >=100s, round segmented context bar, and suppress card title over anomaly tip --- sidecars/panel/app.js | 95 +++++++++++++------ sidecars/panel/index.html | 4 +- .../components/charts/SessionStepCharts.js | 7 +- .../src/components/ui/ContextSegmentMeter.js | 39 +++++--- sidecars/panel/src/core/formatters.js | 8 +- sidecars/panel/src/styles/modern-ui.css | 6 ++ sidecars/panel/src/styles/tokens.css | 35 +++++-- sidecars/panel/src/styles/views-overview.css | 42 ++++++++ sidecars/panel/src/views/StepsDetailView.js | 44 ++++++--- sidecars/panel/styles.css | 83 ++++++++++++++-- sidecars/panel/test/step-anomalies.test.mjs | 47 ++++++++- 11 files changed, 325 insertions(+), 85 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 87c4279..a512d4d 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -3432,13 +3432,13 @@ const EN_MONTH_SHORT = Object.freeze([ ]); function formatMetric(value, unit = '') { - return Number.isFinite(value) ? `${value.toFixed(1)}${unit}` : '—'; + if (!Number.isFinite(value)) return '—'; + const numStr = Math.abs(value) >= 100 ? String(Math.round(value)) : value.toFixed(1); + return `${numStr}${unit}`; } function formatSpeedMetric(value, unit = ' tok/s') { - if (!Number.isFinite(value)) return '—'; - const numStr = value >= 100 ? String(Math.round(value)) : value.toFixed(1); - return `${numStr}${unit}`; + return formatMetric(value, unit); } function formatCachePct(value) { @@ -8118,20 +8118,21 @@ const { ContextSegmentMeter } = (() => { const SEGMENT_DEFS = [ - { key: 'assistant', cls: 'seg-assistant', getVal: (c) => Number(c.assistantTokens || 0) }, - { key: 'toolResults', cls: 'seg-tool-results', getVal: (c) => Number(c.toolResultsTokens || 0) }, + { key: 'assistant', labelKey: 'ctx.ch.assistant', cls: 'seg-assistant', getVal: (c) => Number(c.assistantTokens || 0) }, + { key: 'toolResults', labelKey: 'ctx.ch.toolResults', cls: 'seg-tool-results', getVal: (c) => Number(c.toolResultsTokens || 0) }, { key: 'userInput', + labelKey: 'ctx.ch.userInput', cls: 'seg-user-input', getVal: (c) => Number(c.userInputTokens ?? c.messagesTokens ?? 0), }, - { key: 'subagent', cls: 'seg-subagent-msg', getVal: (c) => Number(c.subagentTokens || 0) }, - { key: 'checkpoint', cls: 'seg-checkpoint', getVal: (c) => Number(c.checkpointTokens || 0) }, - { key: 'systemPrompt', cls: 'seg-system-prompt', getVal: (c) => Number(c.systemPromptTokens || 0) }, - { key: 'systemTools', cls: 'seg-system-tools', getVal: (c) => Number(c.systemToolsTokens || 0) }, - { key: 'mcpTools', cls: 'seg-mcp-tools', getVal: (c) => Number(c.mcpToolsTokens || 0) }, - { key: 'skills', cls: 'seg-skills', getVal: (c) => Number(c.skillsTokens || 0) }, - { key: 'userRules', cls: 'seg-user-rules', getVal: (c) => Number(c.userRulesTokens || 0) }, + { key: 'subagent', labelKey: 'ctx.ch.subagent', cls: 'seg-subagent-msg', getVal: (c) => Number(c.subagentTokens || 0) }, + { key: 'checkpoint', labelKey: 'ctx.ch.checkpoint', cls: 'seg-checkpoint', getVal: (c) => Number(c.checkpointTokens || 0) }, + { key: 'systemPrompt', labelKey: 'ctx.ch.systemPrompt', cls: 'seg-system-prompt', getVal: (c) => Number(c.systemPromptTokens || 0) }, + { key: 'systemTools', labelKey: 'ctx.ch.systemTools', cls: 'seg-system-tools', getVal: (c) => Number(c.systemToolsTokens || 0) }, + { key: 'mcpTools', labelKey: 'ctx.ch.mcpTools', cls: 'seg-mcp-tools', getVal: (c) => Number(c.mcpToolsTokens || 0) }, + { key: 'skills', labelKey: 'ctx.ch.skills', cls: 'seg-skills', getVal: (c) => Number(c.skillsTokens || 0) }, + { key: 'userRules', labelKey: 'ctx.ch.userRules', cls: 'seg-user-rules', getVal: (c) => Number(c.userRulesTokens || 0) }, ]; const ContextSegmentMeter = defineComponent({ @@ -8145,7 +8146,7 @@ const ContextSegmentMeter = defineComponent({ const trackEl = h( 'div', { - className: 'progress-track', + className: 'progress-track ctx-segment-meter', role: 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': '100', @@ -8177,11 +8178,23 @@ const ContextSegmentMeter = defineComponent({ patchClasses(trackEl, { 'is-reordering': orderChanged }); + let seenActive = false; for (let i = 0; i < slotEls.length; i++) { const slotEl = slotEls[i]; const item = scored[i]; - patchAttr(slotEl, 'class', `progress-seg ${item.def.cls}`); - patchStyleVar(slotEl, '--seg-w', `${item.pct.toFixed(2)}%`); + const isActive = item.val > 0 && item.pct > 0; + const hasSep = isActive && seenActive; + if (isActive) seenActive = true; + const cls = `progress-seg ${item.def.cls}${isActive ? ' is-active' : ''}${hasSep ? ' has-sep' : ''}`; + patchAttr(slotEl, 'class', cls); + patchStyleVar(slotEl, '--seg-w', isActive ? `${item.pct.toFixed(2)}%` : '0%'); + patchAttr( + slotEl, + 'title', + isActive + ? `${t(item.def.labelKey)} · ${formatTokens(item.val)} (${item.pct.toFixed(1)}%)` + : null + ); } patchAttr(trackEl, 'aria-valuenow', Math.round(ctx.compactionUsedPct ?? ctx.usedPct ?? 0)); @@ -9990,7 +10003,7 @@ function formatChartMetricValue(metric, val) { case 'tps': return formatSpeedMetric(val, ' tok/s'); case 'ttft': - return `${val.toFixed(1)}s`; + return formatMetric(val, 's'); case 'cache': return `${val.toFixed(1)}%`; case 'cost': @@ -10009,7 +10022,7 @@ function formatChartMetricCompact(metric, val) { case 'tps': return formatSpeedMetric(val, ' tok/s'); case 'ttft': - return `${val.toFixed(1)}s`; + return formatMetric(val, 's'); case 'cache': return `${val.toFixed(1)}%`; case 'cost': @@ -10478,7 +10491,7 @@ function createSessionLineChart() { valid = !st.isCompactionStep && Number.isFinite(st.tokPerSec) && st.tokPerSec > 0; value = valid ? Number(st.tokPerSec) : 0; secondaryRight = Number.isFinite(st.ttftSec) - ? t('chart.step.ttftShort', { sec: st.ttftSec.toFixed(1) }) + ? t('chart.step.ttftShort', { sec: formatMetric(st.ttftSec, '') }) : ''; subDetail = valid ? t('chart.step.outAndCtx', { @@ -23859,6 +23872,7 @@ const StepsDetailView = defineComponent({ const callsPillEl = h('span', { className: 'smodel-calls-pill text-mono' }); const anomalyTagEl = h('span', { className: 'step-anomaly-tag smodel-anomaly-tag text-mono', + title: '', hidden: true, }); const tokEl = h('span', { className: 'smodel-tok text-mono' }); @@ -23880,7 +23894,18 @@ const StepsDetailView = defineComponent({ return { el: cardEl, - refs: { nameEl, callsPillEl, anomalyTagEl, tokEl, costEl, segBar, perfEl, splitEl }, + refs: { + nameEl, + callsPillEl, + anomalyTagEl, + tokEl, + costEl, + segBar, + perfEl, + splitEl, + cardTitle: '', + isHoveringAnomaly: false, + }, }; }, updateRow: (refs, m, _idx, cardEl) => { @@ -23911,11 +23936,21 @@ const StepsDetailView = defineComponent({ if (anomSum) { patchText(refs.anomalyTagEl, anomSum.tagText); patchClasses(refs.anomalyTagEl, { 'is-danger': anomSum.severity === 'danger' }); - refs.anomalyTagEl.onmouseenter = () => + patchAttr(refs.anomalyTagEl, 'title', ''); + refs.anomalyTagEl.onmouseenter = () => { + refs.isHoveringAnomaly = true; + patchAttr(cardEl, 'title', null); showAnomalyTip(refs.anomalyTagEl, buildModelAnomalyDiagnostic(effM)); - refs.anomalyTagEl.onmouseleave = hideAnomalyTip; + }; + refs.anomalyTagEl.onmouseleave = () => { + refs.isHoveringAnomaly = false; + patchAttr(cardEl, 'title', refs.cardTitle || null); + hideAnomalyTip(); + }; refs.anomalyTagEl.onclick = (e) => { e?.stopPropagation?.(); + refs.isHoveringAnomaly = false; + patchAttr(cardEl, 'title', refs.cardTitle || null); hideAnomalyTip(); selectedTableModels = hasMultipleModels ? [...cardGroupKeys] : ['__all__']; onlyAnomalies = true; @@ -23923,6 +23958,7 @@ const StepsDetailView = defineComponent({ uiStore.setState({ stepsSubTab: 'steps' }); }; } else { + refs.isHoveringAnomaly = false; refs.anomalyTagEl.onmouseenter = null; refs.anomalyTagEl.onmouseleave = null; refs.anomalyTagEl.onclick = null; @@ -23989,15 +24025,12 @@ const StepsDetailView = defineComponent({ const isActiveFit = hasMultipleModels && cardGroupKeys.some((k) => fitActiveKeySet.has(k)); patchClasses(cardEl, { 'is-fit-active': isActiveFit }); - patchAttr( - cardEl, - 'title', - !hasMultipleModels - ? dispTitle - : isActiveFit - ? t('steps.fitActiveCardTitle', { title: dispTitle }) - : t('steps.fitInactiveCardTitle', { text: dispText }) - ); + refs.cardTitle = !hasMultipleModels + ? dispTitle + : isActiveFit + ? t('steps.fitActiveCardTitle', { title: dispTitle }) + : t('steps.fitInactiveCardTitle', { text: dispText }); + patchAttr(cardEl, 'title', refs.isHoveringAnomaly ? null : refs.cardTitle); cardEl.onclick = (e) => { if (!hasMultipleModels) return; if (e && (e.ctrlKey || e.metaKey || e.shiftKey) && !isFitPooledAll) { diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 265e406..416579f 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/charts/SessionStepCharts.js b/sidecars/panel/src/components/charts/SessionStepCharts.js index 84aa5d1..733bad3 100644 --- a/sidecars/panel/src/components/charts/SessionStepCharts.js +++ b/sidecars/panel/src/components/charts/SessionStepCharts.js @@ -11,6 +11,7 @@ import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js'; import { formatAgentBadgeText, + formatMetric, formatSpeedMetric, formatStepAnomalyInlineSummary, formatTokens, @@ -645,7 +646,7 @@ function formatChartMetricValue(metric, val) { case 'tps': return formatSpeedMetric(val, ' tok/s'); case 'ttft': - return `${val.toFixed(1)}s`; + return formatMetric(val, 's'); case 'cache': return `${val.toFixed(1)}%`; case 'cost': @@ -664,7 +665,7 @@ function formatChartMetricCompact(metric, val) { case 'tps': return formatSpeedMetric(val, ' tok/s'); case 'ttft': - return `${val.toFixed(1)}s`; + return formatMetric(val, 's'); case 'cache': return `${val.toFixed(1)}%`; case 'cost': @@ -1133,7 +1134,7 @@ export function createSessionLineChart() { valid = !st.isCompactionStep && Number.isFinite(st.tokPerSec) && st.tokPerSec > 0; value = valid ? Number(st.tokPerSec) : 0; secondaryRight = Number.isFinite(st.ttftSec) - ? t('chart.step.ttftShort', { sec: st.ttftSec.toFixed(1) }) + ? t('chart.step.ttftShort', { sec: formatMetric(st.ttftSec, '') }) : ''; subDetail = valid ? t('chart.step.outAndCtx', { diff --git a/sidecars/panel/src/components/ui/ContextSegmentMeter.js b/sidecars/panel/src/components/ui/ContextSegmentMeter.js index 6ef3e52..b342f43 100644 --- a/sidecars/panel/src/components/ui/ContextSegmentMeter.js +++ b/sidecars/panel/src/components/ui/ContextSegmentMeter.js @@ -6,22 +6,25 @@ import { defineComponent } from '../../core/component.js'; import { h, patchAttr, patchClasses, patchStyleVar } from '../../core/domPatch.js'; +import { formatTokens } from '../../core/formatters.js'; +import { t } from '../../i18n/index.js'; const SEGMENT_DEFS = [ - { key: 'assistant', cls: 'seg-assistant', getVal: (c) => Number(c.assistantTokens || 0) }, - { key: 'toolResults', cls: 'seg-tool-results', getVal: (c) => Number(c.toolResultsTokens || 0) }, + { key: 'assistant', labelKey: 'ctx.ch.assistant', cls: 'seg-assistant', getVal: (c) => Number(c.assistantTokens || 0) }, + { key: 'toolResults', labelKey: 'ctx.ch.toolResults', cls: 'seg-tool-results', getVal: (c) => Number(c.toolResultsTokens || 0) }, { key: 'userInput', + labelKey: 'ctx.ch.userInput', cls: 'seg-user-input', getVal: (c) => Number(c.userInputTokens ?? c.messagesTokens ?? 0), }, - { key: 'subagent', cls: 'seg-subagent-msg', getVal: (c) => Number(c.subagentTokens || 0) }, - { key: 'checkpoint', cls: 'seg-checkpoint', getVal: (c) => Number(c.checkpointTokens || 0) }, - { key: 'systemPrompt', cls: 'seg-system-prompt', getVal: (c) => Number(c.systemPromptTokens || 0) }, - { key: 'systemTools', cls: 'seg-system-tools', getVal: (c) => Number(c.systemToolsTokens || 0) }, - { key: 'mcpTools', cls: 'seg-mcp-tools', getVal: (c) => Number(c.mcpToolsTokens || 0) }, - { key: 'skills', cls: 'seg-skills', getVal: (c) => Number(c.skillsTokens || 0) }, - { key: 'userRules', cls: 'seg-user-rules', getVal: (c) => Number(c.userRulesTokens || 0) }, + { key: 'subagent', labelKey: 'ctx.ch.subagent', cls: 'seg-subagent-msg', getVal: (c) => Number(c.subagentTokens || 0) }, + { key: 'checkpoint', labelKey: 'ctx.ch.checkpoint', cls: 'seg-checkpoint', getVal: (c) => Number(c.checkpointTokens || 0) }, + { key: 'systemPrompt', labelKey: 'ctx.ch.systemPrompt', cls: 'seg-system-prompt', getVal: (c) => Number(c.systemPromptTokens || 0) }, + { key: 'systemTools', labelKey: 'ctx.ch.systemTools', cls: 'seg-system-tools', getVal: (c) => Number(c.systemToolsTokens || 0) }, + { key: 'mcpTools', labelKey: 'ctx.ch.mcpTools', cls: 'seg-mcp-tools', getVal: (c) => Number(c.mcpToolsTokens || 0) }, + { key: 'skills', labelKey: 'ctx.ch.skills', cls: 'seg-skills', getVal: (c) => Number(c.skillsTokens || 0) }, + { key: 'userRules', labelKey: 'ctx.ch.userRules', cls: 'seg-user-rules', getVal: (c) => Number(c.userRulesTokens || 0) }, ]; export const ContextSegmentMeter = defineComponent({ @@ -35,7 +38,7 @@ export const ContextSegmentMeter = defineComponent({ const trackEl = h( 'div', { - className: 'progress-track', + className: 'progress-track ctx-segment-meter', role: 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': '100', @@ -67,11 +70,23 @@ export const ContextSegmentMeter = defineComponent({ patchClasses(trackEl, { 'is-reordering': orderChanged }); + let seenActive = false; for (let i = 0; i < slotEls.length; i++) { const slotEl = slotEls[i]; const item = scored[i]; - patchAttr(slotEl, 'class', `progress-seg ${item.def.cls}`); - patchStyleVar(slotEl, '--seg-w', `${item.pct.toFixed(2)}%`); + const isActive = item.val > 0 && item.pct > 0; + const hasSep = isActive && seenActive; + if (isActive) seenActive = true; + const cls = `progress-seg ${item.def.cls}${isActive ? ' is-active' : ''}${hasSep ? ' has-sep' : ''}`; + patchAttr(slotEl, 'class', cls); + patchStyleVar(slotEl, '--seg-w', isActive ? `${item.pct.toFixed(2)}%` : '0%'); + patchAttr( + slotEl, + 'title', + isActive + ? `${t(item.def.labelKey)} · ${formatTokens(item.val)} (${item.pct.toFixed(1)}%)` + : null + ); } patchAttr(trackEl, 'aria-valuenow', Math.round(ctx.compactionUsedPct ?? ctx.usedPct ?? 0)); diff --git a/sidecars/panel/src/core/formatters.js b/sidecars/panel/src/core/formatters.js index 3f6f294..8926777 100644 --- a/sidecars/panel/src/core/formatters.js +++ b/sidecars/panel/src/core/formatters.js @@ -22,13 +22,13 @@ const EN_MONTH_SHORT = Object.freeze([ ]); export function formatMetric(value, unit = '') { - return Number.isFinite(value) ? `${value.toFixed(1)}${unit}` : '—'; + if (!Number.isFinite(value)) return '—'; + const numStr = Math.abs(value) >= 100 ? String(Math.round(value)) : value.toFixed(1); + return `${numStr}${unit}`; } export function formatSpeedMetric(value, unit = ' tok/s') { - if (!Number.isFinite(value)) return '—'; - const numStr = value >= 100 ? String(Math.round(value)) : value.toFixed(1); - return `${numStr}${unit}`; + return formatMetric(value, unit); } export function formatCachePct(value) { diff --git a/sidecars/panel/src/styles/modern-ui.css b/sidecars/panel/src/styles/modern-ui.css index 8c22768..a7ef1b8 100644 --- a/sidecars/panel/src/styles/modern-ui.css +++ b/sidecars/panel/src/styles/modern-ui.css @@ -411,6 +411,12 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { background: var(--modern-progress-track); } +[data-modern-ui="true"] .progress-track.ctx-segment-meter { + height: 6px; + border-radius: 3px; + background: var(--modern-progress-track); +} + /* --- 4. 用量统计矩阵、热力格与详情卡去边框且不叠内层背景 --- */ [data-modern-ui="true"] .cons-box, [data-modern-ui="true"] .cons-custom-range-bar { diff --git a/sidecars/panel/src/styles/tokens.css b/sidecars/panel/src/styles/tokens.css index eee1401..caf9a1f 100644 --- a/sidecars/panel/src/styles/tokens.css +++ b/sidecars/panel/src/styles/tokens.css @@ -89,16 +89,16 @@ --metric-danger-soft: color-mix(in srgb, var(--metric-danger) 14%, transparent); /* Context Window 10-Channel Palette */ - --ctx-assistant: hsl(217 82% 54%); - --ctx-tool-results: hsl(192 82% 43%); - --ctx-user-input: hsl(245 72% 62%); - --ctx-subagent-msg: hsl(280 70% 58%); - --ctx-checkpoint: hsl(38 90% 50%); - --ctx-system-tools: hsl(22 86% 50%); - --ctx-mcp-tools: hsl(316 72% 54%); - --ctx-skills: hsl(145 64% 38%); - --ctx-system-prompt: hsl(168 72% 40%); - --ctx-user-rules: hsl(346 78% 54%); + --ctx-assistant: hsl(215 62% 52%); + --ctx-tool-results: hsl(172 68% 40%); + --ctx-user-input: hsl(256 76% 62%); + --ctx-subagent-msg: hsl(286 64% 58%); + --ctx-checkpoint: hsl(42 90% 49%); + --ctx-system-tools: hsl(24 86% 52%); + --ctx-mcp-tools: hsl(336 78% 58%); + --ctx-skills: hsl(150 60% 41%); + --ctx-system-prompt: hsl(214 26% 54%); + --ctx-user-rules: hsl(352 78% 56%); /* Legacy 4-Channel Palette (retained for compatibility) */ --ctx-cached: hsl(217 82% 51%); @@ -123,6 +123,21 @@ --space-5: 12px; } +:root[data-color-scheme="dark"], +:host([data-color-scheme="dark"]), +[data-color-scheme="dark"] { + --ctx-assistant: hsl(216 30% 58%); + --ctx-tool-results: hsl(168 72% 54%); + --ctx-user-input: hsl(258 86% 73%); + --ctx-subagent-msg: hsl(288 72% 70%); + --ctx-checkpoint: hsl(43 94% 58%); + --ctx-system-tools: hsl(24 90% 62%); + --ctx-mcp-tools: hsl(338 82% 69%); + --ctx-skills: hsl(150 64% 55%); + --ctx-system-prompt: hsl(214 28% 68%); + --ctx-user-rules: hsl(354 82% 66%); +} + :root[data-font-scale="sm"], :host([data-font-scale="sm"]), [data-font-scale="sm"] { diff --git a/sidecars/panel/src/styles/views-overview.css b/sidecars/panel/src/styles/views-overview.css index c81be2a..3b20082 100644 --- a/sidecars/panel/src/styles/views-overview.css +++ b/sidecars/panel/src/styles/views-overview.css @@ -458,6 +458,48 @@ width var(--dur-normal) var(--ease-fast) 0.05s; } +/* 块状微圆角风格上下文进度条(保持 6px 紧凑高度 + 色块间 2px 轻间隙 + 每段 2px 边缘圆润处理) */ +.progress-track.ctx-segment-meter { + height: 6px; + border-radius: 3px; + align-items: stretch; +} + +.progress-track.ctx-segment-meter .progress-seg { + flex: 0 1 auto; + box-sizing: border-box; + width: 0%; + min-width: 0; + margin-left: 0; + border-radius: 2px; + transition: + background-color 0.08s ease, + width var(--dur-normal) var(--ease-fast), + margin-left var(--dur-fast) var(--ease-fast), + filter 120ms ease; +} + +.progress-track.ctx-segment-meter.is-reordering .progress-seg { + transition: + background-color 0.05s ease, + width var(--dur-normal) var(--ease-fast) 0.05s, + margin-left var(--dur-fast) var(--ease-fast), + filter 120ms ease; +} + +.progress-track.ctx-segment-meter .progress-seg.is-active { + width: var(--seg-w, 0%); + min-width: 3px; +} + +.progress-track.ctx-segment-meter .progress-seg.is-active.has-sep { + margin-left: 2px; +} + +.progress-track.ctx-segment-meter .progress-seg.is-active:hover { + filter: brightness(1.12); +} + .progress-seg.seg-assistant { background-color: var(--ctx-assistant); } diff --git a/sidecars/panel/src/views/StepsDetailView.js b/sidecars/panel/src/views/StepsDetailView.js index db0b1bb..46a26b0 100644 --- a/sidecars/panel/src/views/StepsDetailView.js +++ b/sidecars/panel/src/views/StepsDetailView.js @@ -1144,6 +1144,7 @@ export const StepsDetailView = defineComponent({ const callsPillEl = h('span', { className: 'smodel-calls-pill text-mono' }); const anomalyTagEl = h('span', { className: 'step-anomaly-tag smodel-anomaly-tag text-mono', + title: '', hidden: true, }); const tokEl = h('span', { className: 'smodel-tok text-mono' }); @@ -1165,7 +1166,18 @@ export const StepsDetailView = defineComponent({ return { el: cardEl, - refs: { nameEl, callsPillEl, anomalyTagEl, tokEl, costEl, segBar, perfEl, splitEl }, + refs: { + nameEl, + callsPillEl, + anomalyTagEl, + tokEl, + costEl, + segBar, + perfEl, + splitEl, + cardTitle: '', + isHoveringAnomaly: false, + }, }; }, updateRow: (refs, m, _idx, cardEl) => { @@ -1196,11 +1208,21 @@ export const StepsDetailView = defineComponent({ if (anomSum) { patchText(refs.anomalyTagEl, anomSum.tagText); patchClasses(refs.anomalyTagEl, { 'is-danger': anomSum.severity === 'danger' }); - refs.anomalyTagEl.onmouseenter = () => + patchAttr(refs.anomalyTagEl, 'title', ''); + refs.anomalyTagEl.onmouseenter = () => { + refs.isHoveringAnomaly = true; + patchAttr(cardEl, 'title', null); showAnomalyTip(refs.anomalyTagEl, buildModelAnomalyDiagnostic(effM)); - refs.anomalyTagEl.onmouseleave = hideAnomalyTip; + }; + refs.anomalyTagEl.onmouseleave = () => { + refs.isHoveringAnomaly = false; + patchAttr(cardEl, 'title', refs.cardTitle || null); + hideAnomalyTip(); + }; refs.anomalyTagEl.onclick = (e) => { e?.stopPropagation?.(); + refs.isHoveringAnomaly = false; + patchAttr(cardEl, 'title', refs.cardTitle || null); hideAnomalyTip(); selectedTableModels = hasMultipleModels ? [...cardGroupKeys] : ['__all__']; onlyAnomalies = true; @@ -1208,6 +1230,7 @@ export const StepsDetailView = defineComponent({ uiStore.setState({ stepsSubTab: 'steps' }); }; } else { + refs.isHoveringAnomaly = false; refs.anomalyTagEl.onmouseenter = null; refs.anomalyTagEl.onmouseleave = null; refs.anomalyTagEl.onclick = null; @@ -1274,15 +1297,12 @@ export const StepsDetailView = defineComponent({ const isActiveFit = hasMultipleModels && cardGroupKeys.some((k) => fitActiveKeySet.has(k)); patchClasses(cardEl, { 'is-fit-active': isActiveFit }); - patchAttr( - cardEl, - 'title', - !hasMultipleModels - ? dispTitle - : isActiveFit - ? t('steps.fitActiveCardTitle', { title: dispTitle }) - : t('steps.fitInactiveCardTitle', { text: dispText }) - ); + refs.cardTitle = !hasMultipleModels + ? dispTitle + : isActiveFit + ? t('steps.fitActiveCardTitle', { title: dispTitle }) + : t('steps.fitInactiveCardTitle', { text: dispText }); + patchAttr(cardEl, 'title', refs.isHoveringAnomaly ? null : refs.cardTitle); cardEl.onclick = (e) => { if (!hasMultipleModels) return; if (e && (e.ctrlKey || e.metaKey || e.shiftKey) && !isFitPooledAll) { diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index 7e0e315..688a6ad 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -90,16 +90,16 @@ --metric-danger-soft: color-mix(in srgb, var(--metric-danger) 14%, transparent); /* Context Window 10-Channel Palette */ - --ctx-assistant: hsl(217 82% 54%); - --ctx-tool-results: hsl(192 82% 43%); - --ctx-user-input: hsl(245 72% 62%); - --ctx-subagent-msg: hsl(280 70% 58%); - --ctx-checkpoint: hsl(38 90% 50%); - --ctx-system-tools: hsl(22 86% 50%); - --ctx-mcp-tools: hsl(316 72% 54%); - --ctx-skills: hsl(145 64% 38%); - --ctx-system-prompt: hsl(168 72% 40%); - --ctx-user-rules: hsl(346 78% 54%); + --ctx-assistant: hsl(215 62% 52%); + --ctx-tool-results: hsl(172 68% 40%); + --ctx-user-input: hsl(256 76% 62%); + --ctx-subagent-msg: hsl(286 64% 58%); + --ctx-checkpoint: hsl(42 90% 49%); + --ctx-system-tools: hsl(24 86% 52%); + --ctx-mcp-tools: hsl(336 78% 58%); + --ctx-skills: hsl(150 60% 41%); + --ctx-system-prompt: hsl(214 26% 54%); + --ctx-user-rules: hsl(352 78% 56%); /* Legacy 4-Channel Palette (retained for compatibility) */ --ctx-cached: hsl(217 82% 51%); @@ -124,6 +124,21 @@ --space-5: 12px; } +:root[data-color-scheme="dark"], +:host([data-color-scheme="dark"]), +[data-color-scheme="dark"] { + --ctx-assistant: hsl(216 30% 58%); + --ctx-tool-results: hsl(168 72% 54%); + --ctx-user-input: hsl(258 86% 73%); + --ctx-subagent-msg: hsl(288 72% 70%); + --ctx-checkpoint: hsl(43 94% 58%); + --ctx-system-tools: hsl(24 90% 62%); + --ctx-mcp-tools: hsl(338 82% 69%); + --ctx-skills: hsl(150 64% 55%); + --ctx-system-prompt: hsl(214 28% 68%); + --ctx-user-rules: hsl(354 82% 66%); +} + :root[data-font-scale="sm"], :host([data-font-scale="sm"]), [data-font-scale="sm"] { @@ -1768,6 +1783,48 @@ html[data-standalone="true"] .app-shell { width var(--dur-normal) var(--ease-fast) 0.05s; } +/* 块状微圆角风格上下文进度条(保持 6px 紧凑高度 + 色块间 2px 轻间隙 + 每段 2px 边缘圆润处理) */ +.progress-track.ctx-segment-meter { + height: 6px; + border-radius: 3px; + align-items: stretch; +} + +.progress-track.ctx-segment-meter .progress-seg { + flex: 0 1 auto; + box-sizing: border-box; + width: 0%; + min-width: 0; + margin-left: 0; + border-radius: 2px; + transition: + background-color 0.08s ease, + width var(--dur-normal) var(--ease-fast), + margin-left var(--dur-fast) var(--ease-fast), + filter 120ms ease; +} + +.progress-track.ctx-segment-meter.is-reordering .progress-seg { + transition: + background-color 0.05s ease, + width var(--dur-normal) var(--ease-fast) 0.05s, + margin-left var(--dur-fast) var(--ease-fast), + filter 120ms ease; +} + +.progress-track.ctx-segment-meter .progress-seg.is-active { + width: var(--seg-w, 0%); + min-width: 3px; +} + +.progress-track.ctx-segment-meter .progress-seg.is-active.has-sep { + margin-left: 2px; +} + +.progress-track.ctx-segment-meter .progress-seg.is-active:hover { + filter: brightness(1.12); +} + .progress-seg.seg-assistant { background-color: var(--ctx-assistant); } @@ -6254,6 +6311,12 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { background: var(--modern-progress-track); } +[data-modern-ui="true"] .progress-track.ctx-segment-meter { + height: 6px; + border-radius: 3px; + background: var(--modern-progress-track); +} + /* --- 4. 用量统计矩阵、热力格与详情卡去边框且不叠内层背景 --- */ [data-modern-ui="true"] .cons-box, [data-modern-ui="true"] .cons-custom-range-bar { diff --git a/sidecars/panel/test/step-anomalies.test.mjs b/sidecars/panel/test/step-anomalies.test.mjs index 9a9d933..fded8b2 100644 --- a/sidecars/panel/test/step-anomalies.test.mjs +++ b/sidecars/panel/test/step-anomalies.test.mjs @@ -12,8 +12,10 @@ import { buildModelAnomalyDiagnostic, buildStepAnomalyDiagnostic, formatAnomalyTagText, + formatMetric, formatSpeedMetric, } from '../src/core/formatters.js'; +import { ContextSegmentMeter } from '../src/components/ui/ContextSegmentMeter.js'; import { STEP_COLUMN_REGISTRY } from '../src/registries/stepColumnRegistry.js'; import { StepTableWidget } from '../src/components/widgets/StepTableWidget.js'; import { @@ -400,6 +402,43 @@ test('formatSpeedMetric drops decimals at >= 100 tok/s and STEP_COLUMN_REGISTRY. ); assert.equal(fastCell.refs.speedMain.textContent, '—'); assert.equal(fastCell.refs.speedReason.textContent, '调用报错'); + + // Seconds >= 100s also drop decimals in ttft & duration columns + assert.equal(formatMetric(100, 's'), '100s'); + assert.equal(formatMetric(142.6, 's'), '143s'); + assert.equal(formatMetric(99.9, 's'), '99.9s'); + + const ttftCell = STEP_COLUMN_REGISTRY.ttft.createCell(); + STEP_COLUMN_REGISTRY.ttft.updateCell(ttftCell.refs, { ttftSec: 124.7 }); + assert.equal(ttftCell.refs.valEl.textContent, '125s'); + STEP_COLUMN_REGISTRY.ttft.updateCell(ttftCell.refs, { ttftSec: 14.2 }); + assert.equal(ttftCell.refs.valEl.textContent, '14.2s'); + + const durCell = STEP_COLUMN_REGISTRY.duration.createCell(); + STEP_COLUMN_REGISTRY.duration.updateCell(durCell.refs, { totalDurationSec: 108.4 }); + assert.equal(durCell.refs.valEl.textContent, '108s'); + STEP_COLUMN_REGISTRY.duration.updateCell(durCell.refs, { totalDurationSec: 42.3 }); + assert.equal(durCell.refs.valEl.textContent, '42.3s'); + + // ContextSegmentMeter renders crisp separated blocks (.ctx-segment-meter + .is-active + .has-sep) + const meter = ContextSegmentMeter({ + context: { + limitTokens: 200_000, + toolResultsTokens: 60_000, + assistantTokens: 20_000, + skillsTokens: 1_000, + }, + }); + assert.equal(meter.el.classList.contains('ctx-segment-meter'), true); + const activeSegs = meter.refs.segments.filter((s) => s.classList.contains('is-active')); + assert.equal(activeSegs.length, 3); + assert.equal(activeSegs[0].classList.contains('has-sep'), false, 'First active segment has no left cut gap'); + assert.equal(activeSegs[1].classList.contains('has-sep'), true, 'Second active segment has 2px cut gap'); + assert.equal(activeSegs[2].classList.contains('has-sep'), true, 'Third active segment has 2px cut gap'); + assert.match(activeSegs[0].getAttribute('title') || '', /60\.0k/); + const inactiveSegs = meter.refs.segments.filter((s) => !s.classList.contains('is-active')); + assert.equal(inactiveSegs.length, 7); + assert.equal(inactiveSegs.every((s) => !s.classList.contains('has-sep') && !s.getAttribute('title')), true); } finally { env.restore(); } @@ -667,13 +706,16 @@ test('StepsDetailView total summary cards, session anomaly strip, click-to-filte assert.equal(flashBadge.hasAttribute('hidden'), true); assert.match(cards[1].querySelector('.smodel-perf').textContent, /88\.2 tok\/s/); - // Hovering model card anomaly badge opens diagnostic popover with click hint + // Hovering model card anomaly badge opens diagnostic popover with click hint AND suppresses parent card native title tooltip const modelDiag = buildModelAnomalyDiagnostic(modelBreakdown[0]); assert.ok(modelDiag && modelDiag.hint); + assert.ok(cards[0].getAttribute('title'), 'Model card has native fit-chart title before hovering anomaly badge'); proBadge.onmouseenter(); + assert.equal(cards[0].getAttribute('title'), null, 'Parent model card native title must be suppressed while hovering anomaly badge'); assert.equal(view.refs.anomalyTipEl.hasAttribute('hidden'), false); assert.match(view.refs.anomalyTipEl.querySelector('.step-anomaly-tip-hint').textContent, /按步查看/); proBadge.onmouseleave(); + assert.ok(cards[0].getAttribute('title'), 'Parent model card native title restores after leaving anomaly badge'); assert.equal(view.refs.anomalyTipEl.hasAttribute('hidden'), true); // Clicking model card anomaly badge jumps to 'steps', activates anomaly filterbar, and filters to only anomaly step #10 @@ -779,4 +821,7 @@ test('Compiled styles.css centers odometer capsule slot text and ships both clas assert.match(builtCss, /\.sstep-anomaly-dot/); assert.match(builtCss, /\.trend-tip-anomaly/); assert.match(builtCss, /\[data-modern-ui="true"\]\s*\.step-anomaly-tip/); + assert.match(builtCss, /\.progress-track\.ctx-segment-meter\s*\{[\s\S]*?height:\s*6px;/); + assert.match(builtCss, /\.progress-track\.ctx-segment-meter\s+\.progress-seg\s*\{[\s\S]*?border-radius:\s*2px;/); + assert.match(builtCss, /\.progress-track\.ctx-segment-meter\s+\.progress-seg\.is-active\.has-sep\s*\{[\s\S]*?margin-left:\s*2px;/); }); From 4f37b6e2d076603e614bf51302343c7e66fc9de6 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Thu, 19 Nov 2026 23:54:33 +0900 Subject: [PATCH 14/14] chore(release): add runtime-only whitelist ZIP packager, harden Windows ZIP extraction, and update install docs --- .gitignore | 2 + README.md | 38 +-- README.zh-CN.md | 40 +-- sidecars/panel/backend/plugin-updater.mjs | 2 +- sidecars/panel/package.json | 1 + sidecars/panel/scripts/pack-release-zip.mjs | 264 ++++++++++++++++++++ sidecars/panel/test/release-pack.test.mjs | 105 ++++++++ 7 files changed, 412 insertions(+), 40 deletions(-) create mode 100644 sidecars/panel/scripts/pack-release-zip.mjs create mode 100644 sidecars/panel/test/release-pack.test.mjs diff --git a/.gitignore b/.gitignore index 8739bcb..524df6a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,8 @@ .data/ node_modules/ plan/ +dist/ +usage-monitor.zip *.log *.dpapi .account-test-* diff --git a/README.md b/README.md index 0fd77ff..1a3af90 100644 --- a/README.md +++ b/README.md @@ -117,25 +117,7 @@ English · [简体中文](README.zh-CN.md) Keep the folder name as `usage-monitor`. **No `npm install` is needed.** -### Option 1: Git Clone - -```powershell -# Windows (PowerShell) -git clone https://github.com/yuhuan-dev/antigravity-usage-monitor.git "$env:USERPROFILE\.gemini\config\plugins\usage-monitor" -``` - -```bash -# macOS / Linux -git clone https://github.com/yuhuan-dev/antigravity-usage-monitor.git ~/.gemini/config/plugins/usage-monitor -``` - -Or ask Antigravity directly: - -```text -Clone https://github.com/yuhuan-dev/antigravity-usage-monitor to ~/.gemini/config/plugins/usage-monitor and enable the plugin -``` - -### Option 2: Release ZIP +### Option 1: Release ZIP Download [`usage-monitor.zip`](https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip) and extract it into `~/.gemini/config/plugins/` so the directory path is `~/.gemini/config/plugins/usage-monitor`. @@ -151,6 +133,24 @@ Expand-Archive -Path "$env:TEMP\usage-monitor.zip" -DestinationPath $pluginsDir +### Option 2: Git Clone + +```powershell +# Windows (PowerShell) +git clone --filter=blob:none --single-branch https://github.com/yuhuan-dev/antigravity-usage-monitor.git "$env:USERPROFILE\.gemini\config\plugins\usage-monitor" +``` + +```bash +# macOS / Linux +git clone --filter=blob:none --single-branch https://github.com/yuhuan-dev/antigravity-usage-monitor.git ~/.gemini/config/plugins/usage-monitor +``` + +Or ask Antigravity directly: + +```text +Clone https://github.com/yuhuan-dev/antigravity-usage-monitor with --filter=blob:none --single-branch to ~/.gemini/config/plugins/usage-monitor and enable the plugin +``` + --- ## Usage diff --git a/README.zh-CN.md b/README.zh-CN.md index 0a27513..550ec68 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -117,30 +117,12 @@ Google Antigravity 2.0、Antigravity IDE 与 Antigravity CLI 的本地用量、 插件目录名需保持为 `usage-monitor`,**无需运行 `npm install`**。 -### 方式一:Git 克隆 - -```powershell -# Windows PowerShell -git clone https://github.com/yuhuan-dev/antigravity-usage-monitor.git "$env:USERPROFILE\.gemini\config\plugins\usage-monitor" -``` - -```bash -# macOS / Linux -git clone https://github.com/yuhuan-dev/antigravity-usage-monitor.git ~/.gemini/config/plugins/usage-monitor -``` - -也可以直接在 Antigravity 对话中执行: - -```text -把 https://github.com/yuhuan-dev/antigravity-usage-monitor 克隆到 ~/.gemini/config/plugins/usage-monitor 并启用插件 -``` - -### 方式二:下载 Release 压缩包 +### 方式一:下载 Release 压缩包 下载 [`usage-monitor.zip`](https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip),解压到 `~/.gemini/config/plugins/` 下并保持文件夹名为 `usage-monitor`。
-Windows PowerShell 下载与解压命令 +Windows PowerShell 下载及解压命令 ```powershell $pluginsDir = "$env:USERPROFILE\.gemini\config\plugins" @@ -151,6 +133,24 @@ Expand-Archive -Path "$env:TEMP\usage-monitor.zip" -DestinationPath $pluginsDir
+### 方式二:Git 克隆 + +```powershell +# Windows PowerShell +git clone --filter=blob:none --single-branch https://github.com/yuhuan-dev/antigravity-usage-monitor.git "$env:USERPROFILE\.gemini\config\plugins\usage-monitor" +``` + +```bash +# macOS / Linux +git clone --filter=blob:none --single-branch https://github.com/yuhuan-dev/antigravity-usage-monitor.git ~/.gemini/config/plugins/usage-monitor +``` + +也可以直接在 Antigravity 对话中执行: + +```text +把 https://github.com/yuhuan-dev/antigravity-usage-monitor 用 --filter=blob:none --single-branch 克隆到 ~/.gemini/config/plugins/usage-monitor 并启用插件 +``` + --- ## 使用方式 diff --git a/sidecars/panel/backend/plugin-updater.mjs b/sidecars/panel/backend/plugin-updater.mjs index 6b27f03..2951e98 100644 --- a/sidecars/panel/backend/plugin-updater.mjs +++ b/sidecars/panel/backend/plugin-updater.mjs @@ -494,7 +494,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) { '-NoProfile', '-NonInteractive', '-Command', - `Expand-Archive -LiteralPath '${zipFile.replace(/'/g, "''")}' -DestinationPath '${extractDir.replace(/'/g, "''")}' -Force`, + `Add-Type -AssemblyName System.IO.Compression.FileSystem; [System.IO.Compression.ZipFile]::ExtractToDirectory('${zipFile.replace(/'/g, "''")}', '${extractDir.replace(/'/g, "''")}')`, ]); } else { await runExecFile('unzip', ['-oq', zipFile, '-d', extractDir]); diff --git a/sidecars/panel/package.json b/sidecars/panel/package.json index 6fdf3ce..9339e4e 100644 --- a/sidecars/panel/package.json +++ b/sidecars/panel/package.json @@ -6,6 +6,7 @@ "description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor.", "scripts": { "build": "node scripts/build-bundle.mjs", + "pack:release": "node scripts/pack-release-zip.mjs", "standalone": "node standalone.mjs", "test": "node --test test/*.test.mjs" } diff --git a/sidecars/panel/scripts/pack-release-zip.mjs b/sidecars/panel/scripts/pack-release-zip.mjs new file mode 100644 index 0000000..b077e95 --- /dev/null +++ b/sidecars/panel/scripts/pack-release-zip.mjs @@ -0,0 +1,264 @@ +#!/usr/bin/env node +/** + * @fileoverview Pure Node.js whitelist packager for `usage-monitor.zip`. + * + * Packs ONLY the runtime-essential plugin files (~520 KB compressed) into a + * cross-platform PKZIP archive prefixed with `usage-monitor/`, excluding dev-only + * frontend sources (`src/`), unit tests (`test/`), build scripts (`scripts/`), + * README preview PNGs (`assets/*.png`), local data (`.data/`), and planning docs (`plan/`). + */ + +import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { deflateRawSync } from 'node:zlib'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +export const DEFAULT_REPO_ROOT = resolve(__dirname, '..', '..', '..'); +export const DEFAULT_ZIP_OUT = join(DEFAULT_REPO_ROOT, 'dist', 'usage-monitor.zip'); +export const RELEASE_ARCHIVE_ROOT = 'usage-monitor'; + +const ROOT_WHITELIST = Object.freeze([ + 'plugin.json', + 'mcp_config.json', + 'pricing-catalog.json', + 'LICENSE', + 'assets/logo.svg', +]); + +const PANEL_TOP_WHITELIST = Object.freeze([ + 'sidecars/panel/sidecar.json', + 'sidecars/panel/index.html', + 'sidecars/panel/app.js', + 'sidecars/panel/styles.css', + 'sidecars/panel/main.mjs', + 'sidecars/panel/mcp-entry.mjs', + 'sidecars/panel/bridge-daemon.mjs', + 'sidecars/panel/standalone.mjs', + 'sidecars/panel/cli-statusline.mjs', + 'sidecars/panel/trajectory-metrics.mjs', +]); + +const RUNTIME_SUBDIRS = Object.freeze([ + 'sidecars/panel/backend', + 'sidecars/panel/shared', +]); + +const ALLOWED_SUBDIR_EXT_RE = /\.(?:mjs|ps1|sh|json)$/i; +const FORBIDDEN_PATH_RE = + /(?:^|\/)(?:\.git|\.data|node_modules|plan|dist|src|test|scripts)(?:\/|$)|\.png$|\.jpg$|\.jpeg$|\.webp$|\.log$|\.dpapi$/i; + +const CRC32_TABLE = (() => { + const table = new Uint32Array(256); + for (let i = 0; i < 256; i += 1) { + let c = i; + for (let k = 0; k < 8; k += 1) { + c = (c & 1) !== 0 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + } + table[i] = c >>> 0; + } + return table; +})(); + +function crc32(buf) { + let crc = 0xffffffff; + for (let i = 0; i < buf.length; i += 1) { + crc = CRC32_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8); + } + return (crc ^ 0xffffffff) >>> 0; +} + +function toDosTimeDate(date) { + const d = date instanceof Date && Number.isFinite(date.getTime()) ? date : new Date(2026, 0, 1); + const year = Math.max(1980, Math.min(2107, d.getFullYear())); + const dosTime = + ((d.getHours() & 0x1f) << 11) | + ((d.getMinutes() & 0x3f) << 5) | + ((Math.floor(d.getSeconds() / 2)) & 0x1f); + const dosDate = + (((year - 1980) & 0x7f) << 9) | + (((d.getMonth() + 1) & 0x0f) << 5) | + (d.getDate() & 0x1f); + return { dosTime, dosDate }; +} + +function collectRuntimeSubdirFiles(repoRoot, relDir, out) { + const absDir = join(repoRoot, relDir); + if (!existsSync(absDir)) { + throw new Error(`Missing required runtime directory: ${relDir}`); + } + const entries = readdirSync(absDir, { withFileTypes: true }).sort((a, b) => + a.name.localeCompare(b.name) + ); + for (const entry of entries) { + if (entry.name.startsWith('.')) continue; + const childRel = `${relDir}/${entry.name}`; + if (entry.isDirectory()) { + collectRuntimeSubdirFiles(repoRoot, childRel, out); + continue; + } + if (!entry.isFile()) continue; + if (!ALLOWED_SUBDIR_EXT_RE.test(entry.name)) continue; + if (entry.name.includes('.test.')) continue; + out.push(childRel); + } +} + +/** + * Collects the deterministic whitelist of runtime-essential repository paths + * (POSIX relative paths from `repoRoot`). + * + * @param {string} [repoRoot=DEFAULT_REPO_ROOT] + * @returns {string[]} + */ +export function collectReleaseRuntimeFiles(repoRoot = DEFAULT_REPO_ROOT) { + const files = [...ROOT_WHITELIST, ...PANEL_TOP_WHITELIST]; + for (const rel of files) { + const abs = join(repoRoot, rel); + if (!existsSync(abs) || !statSync(abs).isFile()) { + throw new Error(`Missing required runtime file: ${rel}`); + } + } + for (const relDir of RUNTIME_SUBDIRS) { + collectRuntimeSubdirFiles(repoRoot, relDir, files); + } + const uniqueSorted = Array.from(new Set(files)).sort((a, b) => a.localeCompare(b)); + for (const rel of uniqueSorted) { + if (FORBIDDEN_PATH_RE.test(rel)) { + throw new Error(`Forbidden non-runtime file matched release list: ${rel}`); + } + } + return uniqueSorted; +} + +/** + * Builds a standard PKZIP (DEFLATE level 9, UTF-8 POSIX entry names) buffer in pure Node.js. + * + * @param {Array<{ name: string, data: Buffer, mtime?: Date }>} entries + * @returns {Buffer} + */ +export function buildZipBuffer(entries) { + const localParts = []; + const centralParts = []; + let offset = 0; + + for (const entry of entries) { + const nameStr = String(entry.name || '').replace(/\\/g, '/').replace(/^\/+/, ''); + const nameBuf = Buffer.from(nameStr, 'utf8'); + const rawBuf = Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(entry.data || ''); + const deflated = deflateRawSync(rawBuf, { level: 9 }); + const useDeflate = deflated.length < rawBuf.length; + const payload = useDeflate ? deflated : rawBuf; + const method = useDeflate ? 8 : 0; + const checksum = crc32(rawBuf); + const { dosTime, dosDate } = toDosTimeDate(entry.mtime); + + const localHeader = Buffer.alloc(30); + localHeader.writeUInt32LE(0x04034b50, 0); + localHeader.writeUInt16LE(20, 4); // version needed: 2.0 + localHeader.writeUInt16LE(0x0800, 6); // UTF-8 filename flag + localHeader.writeUInt16LE(method, 8); + localHeader.writeUInt16LE(dosTime, 10); + localHeader.writeUInt16LE(dosDate, 12); + localHeader.writeUInt32LE(checksum, 14); + localHeader.writeUInt32LE(payload.length, 18); + localHeader.writeUInt32LE(rawBuf.length, 22); + localHeader.writeUInt16LE(nameBuf.length, 26); + localHeader.writeUInt16LE(0, 28); + + localParts.push(localHeader, nameBuf, payload); + + const centralHeader = Buffer.alloc(46); + centralHeader.writeUInt32LE(0x02014b50, 0); + centralHeader.writeUInt16LE((3 << 8) | 20, 4); // version made by: Unix / 2.0 + centralHeader.writeUInt16LE(20, 6); // version needed: 2.0 + centralHeader.writeUInt16LE(0x0800, 8); // UTF-8 filename flag + centralHeader.writeUInt16LE(method, 10); + centralHeader.writeUInt16LE(dosTime, 12); + centralHeader.writeUInt16LE(dosDate, 14); + centralHeader.writeUInt32LE(checksum, 16); + centralHeader.writeUInt32LE(payload.length, 20); + centralHeader.writeUInt32LE(rawBuf.length, 24); + centralHeader.writeUInt16LE(nameBuf.length, 28); + centralHeader.writeUInt16LE(0, 30); + centralHeader.writeUInt16LE(0, 32); + centralHeader.writeUInt16LE(0, 34); + centralHeader.writeUInt16LE(0, 36); + centralHeader.writeUInt32LE((0o100644 << 16) >>> 0, 38); // regular file mode + centralHeader.writeUInt32LE(offset, 42); + + centralParts.push(centralHeader, nameBuf); + offset += localHeader.length + nameBuf.length + payload.length; + } + + const centralDirBuf = Buffer.concat(centralParts); + const eocd = Buffer.alloc(22); + eocd.writeUInt32LE(0x06054b50, 0); + eocd.writeUInt16LE(0, 4); + eocd.writeUInt16LE(0, 6); + eocd.writeUInt16LE(entries.length, 8); + eocd.writeUInt16LE(entries.length, 10); + eocd.writeUInt32LE(centralDirBuf.length, 12); + eocd.writeUInt32LE(offset, 16); + eocd.writeUInt16LE(0, 20); + + return Buffer.concat([...localParts, centralDirBuf, eocd]); +} + +/** + * Packs the runtime-only `usage-monitor.zip` release bundle. + * + * @param {{ repoRoot?: string, outFile?: string, rootPrefix?: string }} [options] + */ +export function packReleaseZip({ + repoRoot = DEFAULT_REPO_ROOT, + outFile = DEFAULT_ZIP_OUT, + rootPrefix = RELEASE_ARCHIVE_ROOT, +} = {}) { + const relFiles = collectReleaseRuntimeFiles(repoRoot); + let totalRawBytes = 0; + const zipEntries = relFiles.map((rel) => { + const abs = join(repoRoot, rel); + const data = readFileSync(abs); + const st = statSync(abs); + totalRawBytes += data.length; + return { + name: rootPrefix ? `${rootPrefix}/${rel}` : rel, + data, + mtime: st.mtime, + }; + }); + + const zipBuf = buildZipBuffer(zipEntries); + mkdirSync(dirname(outFile), { recursive: true }); + writeFileSync(outFile, zipBuf); + + return { + outFile, + fileCount: relFiles.length, + files: relFiles, + rawBytes: totalRawBytes, + zipBytes: zipBuf.length, + }; +} + +function parseCliOutArg(argv) { + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + if (arg === '--out' && argv[i + 1]) { + return resolve(argv[i + 1]); + } + if (arg.startsWith('--out=')) { + return resolve(arg.slice(6)); + } + } + return DEFAULT_ZIP_OUT; +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const outFile = parseCliOutArg(process.argv.slice(2)); + const summary = packReleaseZip({ repoRoot: DEFAULT_REPO_ROOT, outFile }); + console.log( + `Packed ${summary.outFile} (${summary.fileCount} runtime files, raw ${(summary.rawBytes / 1024).toFixed(1)} KB -> zip ${(summary.zipBytes / 1024).toFixed(1)} KB)` + ); +} diff --git a/sidecars/panel/test/release-pack.test.mjs b/sidecars/panel/test/release-pack.test.mjs new file mode 100644 index 0000000..0cfec53 --- /dev/null +++ b/sidecars/panel/test/release-pack.test.mjs @@ -0,0 +1,105 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { + DEFAULT_REPO_ROOT, + collectReleaseRuntimeFiles, + packReleaseZip, +} from '../scripts/pack-release-zip.mjs'; + +test('pack-release-zip ships only runtime-essential files, excludes dev bloat, and extracts a self-contained runnable plugin', async (t) => { + const relFiles = collectReleaseRuntimeFiles(DEFAULT_REPO_ROOT); + + // Required runtime files exist in whitelist + for (const mustHave of [ + 'plugin.json', + 'mcp_config.json', + 'pricing-catalog.json', + 'LICENSE', + 'assets/logo.svg', + 'sidecars/panel/sidecar.json', + 'sidecars/panel/index.html', + 'sidecars/panel/app.js', + 'sidecars/panel/styles.css', + 'sidecars/panel/main.mjs', + 'sidecars/panel/mcp-entry.mjs', + 'sidecars/panel/bridge-daemon.mjs', + 'sidecars/panel/standalone.mjs', + 'sidecars/panel/cli-statusline.mjs', + 'sidecars/panel/trajectory-metrics.mjs', + 'sidecars/panel/backend/api-actions.mjs', + 'sidecars/panel/backend/account-credentials.ps1', + 'sidecars/panel/shared/settings-normalization.mjs', + ]) { + assert.ok(relFiles.includes(mustHave), `Release whitelist must include ${mustHave}`); + } + + // Non-runtime dev/doc/test/preview files must NEVER enter the release ZIP + for (const rel of relFiles) { + assert.doesNotMatch(rel, /^sidecars\/panel\/(?:src|test|scripts)\//); + assert.doesNotMatch(rel, /\.png$/i); + assert.doesNotMatch(rel, /^README/i); + assert.doesNotMatch(rel, /^\.gitignore$/); + assert.doesNotMatch(rel, /(?:^|\/)(?:\.git|\.data|node_modules|plan|dist)(?:\/|$)/); + } + assert.equal(relFiles.includes('sidecars/panel/package.json'), false); + + const workDir = mkdtempSync(join(tmpdir(), 'ag-um-pack-test-')); + t.after(() => { + try { + rmSync(workDir, { recursive: true, force: true }); + } catch { + // ignore temp cleanup error + } + }); + + const zipPath = join(workDir, 'usage-monitor.zip'); + const extractDir = join(workDir, 'extracted'); + const summary = packReleaseZip({ repoRoot: DEFAULT_REPO_ROOT, outFile: zipPath }); + + assert.ok(existsSync(zipPath)); + assert.ok(summary.zipBytes > 100 * 1024, 'ZIP should contain compiled assets and backend'); + assert.ok( + summary.zipBytes < 750 * 1024, + `Runtime-only ZIP should stay compact (<750 KB), got ${(summary.zipBytes / 1024).toFixed(1)} KB` + ); + + // Extract via OS-native expander (same path used by plugin-updater.mjs, where extractDir already exists) + mkdirSync(extractDir, { recursive: true }); + if (process.platform === 'win32') { + execFileSync( + 'powershell.exe', + [ + '-NoProfile', + '-NonInteractive', + '-Command', + `Add-Type -AssemblyName System.IO.Compression.FileSystem; [System.IO.Compression.ZipFile]::ExtractToDirectory('${zipPath.replace(/'/g, "''")}', '${extractDir.replace(/'/g, "''")}')`, + ], + { stdio: 'pipe', windowsHide: true } + ); + } else { + execFileSync('unzip', ['-oq', zipPath, '-d', extractDir], { stdio: 'pipe' }); + } + + const pluginRoot = join(extractDir, 'usage-monitor'); + assert.ok(existsSync(join(pluginRoot, 'plugin.json'))); + const manifest = JSON.parse(readFileSync(join(pluginRoot, 'plugin.json'), 'utf8')); + assert.equal(manifest.name, 'usage-monitor'); + assert.ok(existsSync(join(pluginRoot, manifest.logo))); + + // Verify zero broken syntax and clean standalone ESM load from the extracted clean tree (no src/, test/, package.json) + for (const rel of relFiles) { + if (rel.endsWith('.mjs') || rel === 'sidecars/panel/app.js') { + execFileSync(process.execPath, ['--check', join(pluginRoot, rel)], { stdio: 'pipe' }); + } + } + + const apiMod = await import(pathToFileURL(join(pluginRoot, 'sidecars/panel/backend/api-actions.mjs')).href); + assert.equal(typeof apiMod.executeTelemetryAction, 'function'); + const cliMod = await import(pathToFileURL(join(pluginRoot, 'sidecars/panel/cli-statusline.mjs')).href); + assert.equal(typeof cliMod.runCliStatusLineMain, 'function'); +});