diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 30cec7b..d157b86 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1544,6 +1544,89 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.resetConfirmBtn': '再次点击确认重置', 'settings.oth.resettingBtn': '重置中…', 'settings.oth.resetAllDone': '已恢复全部默认设置', + + // Structured Live Activity Actions + 'live.act.run_command': '执行命令', + 'live.act.read_file': '读取文件', + 'live.act.edit_file': '修改文件', + 'live.act.write_file': '写入文件', + 'live.act.grep_search': '搜索代码', + 'live.act.find_file': '查找文件', + 'live.act.read_url': '读取网页', + 'live.act.search_web': '网页搜索', + 'live.act.invoke_subagent': '调用子代理', + 'live.act.send_message': '通信子代理', + 'live.act.manage_subagents': '管理子代理', + 'live.act.manage_task': '后台任务', + 'live.act.schedule': '定时任务', + 'live.act.ask_question': '等待用户选择', + 'live.act.search_marketplace': '查询插件', + 'live.act.mcp_tool': '调用 MCP', + 'live.act.tool_call': '调用工具', + 'live.act.thinking': '推理中', + 'live.act.compacting': '上下文压缩', + 'live.act.responding': '正在输出回复', + 'live.act.waiting_subagent': '等待子代理', + 'live.act.starting': '启动中', + 'live.act.done': '已完成', + 'live.act.awaitingApproval': '等待确认 · {label}', + 'live.act.compactionResuming': '已完成压缩,正在恢复推理', + + // SVG Charts (SessionStepCharts & TrendAreaChart) + 'chart.step.empty': '当前范围暂无可绘制的调用步骤', + 'chart.step.excluded': '未纳入', + 'chart.step.zeroSteps': '0 步', + 'chart.step.stepAdd': '本步 +{tokens}', + 'chart.step.ioSplit': '入 {inTok} · 缓 {cacheTok} · 出 {outTok}', + 'chart.step.cacheShort': '缓存 {pct}%', + 'chart.step.compactionCheckpoint': '上下文自动压缩检查点', + 'chart.step.cacheHitOut': '缓存命中 {pct}% · 输出 +{outTok}', + 'chart.step.ttftShort': '首字 {sec}s', + 'chart.step.outAndCtx': '输出 {outTok} · 上下文 {ctxTok}', + 'chart.step.compactionStep': '上下文压缩步', + 'chart.step.noSpeedSample': '无测速样本', + 'chart.step.ctxAndCache': '上下文 {ctxTok} · 缓存 {pct}%', + 'chart.step.noTtftSample': '无首字计时样本', + 'chart.step.cumCost': '累计 {cost}', + 'chart.step.cacheAndStepTok': '缓存 {pct}% · 本步 {tokens}', + 'chart.step.noSamples': '无样本', + 'chart.step.peakShort': '峰 {val}', + 'chart.step.peakPill': '峰值 {tag} · {val}', + 'chart.step.stepsCount': '{count}步', + 'chart.step.multiPrefix': '{count} 模型 · ', + 'chart.step.sumTokens': '{prefix}累计 {tokens}', + 'chart.step.peakTokens': '{prefix}峰值 {tokens}', + 'chart.step.currentCtx': '当前 {tokens}', + 'chart.step.meanTps': '{prefix}均值 {val} tok/s', + 'chart.step.meanSec': '{prefix}均值 {val}s', + 'chart.step.noValidSamples': '暂无有效样本', + 'chart.step.sumCost': '{prefix}累计 {cost}', + 'chart.fit.empty': '该模型暂无有效拟合样本', + 'chart.fit.loess': 'LOESS 拟合', + 'chart.fit.olsLinear': 'OLS 线性', + 'chart.fit.olsReg': 'OLS 回归', + 'chart.fit.observed': '观测值', + 'chart.fit.tipFit': '拟合 {val}', + 'chart.fit.tipObs': '观测 {val}', + 'chart.fit.zeroSamples': '0 样本', + 'chart.fit.peerMean': '{label} 均 {val}', + 'chart.fit.peerCompare': '同图对比:{peers}', + 'chart.fit.curvesCount': '{count} 条拟合线', + 'chart.fit.multiBadge': '{steps}步 · {models} 模型对比', + 'chart.fit.singleBadge': '{steps}步 · 均 {mean}', + 'chart.fit.olsTitle': 'OLS: y = {slope}x + {intercept} · 样本标准差 SD = ±{sd}', + 'chart.trend.hmMonthYear': '{yy}年{month}月', + 'chart.trend.hmMonthOnly': '{month}月', + 'chart.trend.wdayMon': '一', + 'chart.trend.wdayWed': '三', + 'chart.trend.wdayFri': '五', + 'chart.trend.wdaySun': '日', + 'chart.trend.hmAria': '每日用量热力格子图', + 'chart.trend.hmLess': '少', + 'chart.trend.hmMore': '多', + 'chart.trend.hmActivePeak': '活跃 {active}/{total} 天 · 峰值 {label} · {tokens}', + 'chart.trend.hmActiveZero': '活跃 0/{total} 天', + 'chart.trend.peakPill': '峰值 {label} · {tokens}', }); return { I18N_MESSAGES_ZH_CN }; })(); @@ -2075,6 +2158,89 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.resetConfirmBtn': 'Click Again to Confirm', 'settings.oth.resettingBtn': 'Resetting…', 'settings.oth.resetAllDone': 'All preferences restored to defaults', + + // Structured Live Activity Actions + 'live.act.run_command': 'Run Command', + 'live.act.read_file': 'Read File', + 'live.act.edit_file': 'Edit File', + 'live.act.write_file': 'Write File', + 'live.act.grep_search': 'Search Code', + 'live.act.find_file': 'Find Files', + 'live.act.read_url': 'Read Web Page', + 'live.act.search_web': 'Search Web', + 'live.act.invoke_subagent': 'Invoke Subagent', + 'live.act.send_message': 'Message Subagent', + 'live.act.manage_subagents': 'Manage Subagents', + 'live.act.manage_task': 'Manage Task', + 'live.act.schedule': 'Schedule Task', + 'live.act.ask_question': 'Waiting for User Choice', + 'live.act.search_marketplace': 'Search Plugins', + 'live.act.mcp_tool': 'Call MCP Tool', + 'live.act.tool_call': 'Call Tool', + 'live.act.thinking': 'Thinking', + 'live.act.compacting': 'Compacting Context', + 'live.act.responding': 'Responding', + 'live.act.waiting_subagent': 'Waiting for Subagent', + 'live.act.starting': 'Starting', + 'live.act.done': 'Completed', + 'live.act.awaitingApproval': 'Awaiting Approval · {label}', + 'live.act.compactionResuming': 'Compaction finished, resuming reasoning', + + // SVG Charts (SessionStepCharts & TrendAreaChart) + 'chart.step.empty': 'No plottable steps in current scope', + 'chart.step.excluded': 'Excluded', + 'chart.step.zeroSteps': '0 steps', + 'chart.step.stepAdd': 'Step +{tokens}', + 'chart.step.ioSplit': 'In {inTok} · Cache {cacheTok} · Out {outTok}', + 'chart.step.cacheShort': 'Cache {pct}%', + 'chart.step.compactionCheckpoint': 'Auto-compaction checkpoint', + 'chart.step.cacheHitOut': 'Cache hit {pct}% · Out +{outTok}', + 'chart.step.ttftShort': 'TTFT {sec}s', + 'chart.step.outAndCtx': 'Out {outTok} · Context {ctxTok}', + 'chart.step.compactionStep': 'Compaction step', + 'chart.step.noSpeedSample': 'No speed sample', + 'chart.step.ctxAndCache': 'Context {ctxTok} · Cache {pct}%', + 'chart.step.noTtftSample': 'No TTFT sample', + 'chart.step.cumCost': 'Total {cost}', + 'chart.step.cacheAndStepTok': 'Cache {pct}% · Step {tokens}', + 'chart.step.noSamples': 'No samples', + 'chart.step.peakShort': 'Peak {val}', + 'chart.step.peakPill': 'Peak {tag} · {val}', + 'chart.step.stepsCount': '{count} steps', + 'chart.step.multiPrefix': '{count} models · ', + 'chart.step.sumTokens': '{prefix}Total {tokens}', + 'chart.step.peakTokens': '{prefix}Peak {tokens}', + 'chart.step.currentCtx': 'Current {tokens}', + 'chart.step.meanTps': '{prefix}Avg {val} tok/s', + 'chart.step.meanSec': '{prefix}Avg {val}s', + 'chart.step.noValidSamples': 'No valid samples', + 'chart.step.sumCost': '{prefix}Total {cost}', + 'chart.fit.empty': 'No valid regression samples for this model', + 'chart.fit.loess': 'LOESS Fit', + 'chart.fit.olsLinear': 'OLS Linear', + 'chart.fit.olsReg': 'OLS Reg', + 'chart.fit.observed': 'Observed', + 'chart.fit.tipFit': 'Fit {val}', + 'chart.fit.tipObs': 'Obs {val}', + 'chart.fit.zeroSamples': '0 samples', + 'chart.fit.peerMean': '{label} Avg {val}', + 'chart.fit.peerCompare': 'Compare: {peers}', + 'chart.fit.curvesCount': '{count} fit curves', + 'chart.fit.multiBadge': '{steps} steps · {models} models', + 'chart.fit.singleBadge': '{steps} steps · Avg {mean}', + 'chart.fit.olsTitle': 'OLS: y = {slope}x + {intercept} · Sample SD = ±{sd}', + 'chart.trend.hmMonthYear': "{month}/{yy}", + 'chart.trend.hmMonthOnly': 'M{month}', + 'chart.trend.wdayMon': 'M', + 'chart.trend.wdayWed': 'W', + 'chart.trend.wdayFri': 'F', + 'chart.trend.wdaySun': 'S', + 'chart.trend.hmAria': 'Daily usage heatmap', + 'chart.trend.hmLess': 'Less', + 'chart.trend.hmMore': 'More', + 'chart.trend.hmActivePeak': 'Active {active}/{total}d · Peak {label} · {tokens}', + 'chart.trend.hmActiveZero': 'Active 0/{total}d', + 'chart.trend.peakPill': 'Peak {label} · {tokens}', }); return { I18N_MESSAGES_EN_US }; })(); @@ -2529,7 +2695,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 } = (() => { +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 } = (() => { /** * @fileoverview Pure formatting utilities for speed metrics, token counts, * USD estimates, countdown timers, and custom datetime displays. @@ -2736,23 +2902,35 @@ function resolveModelDisplayInfo(target, settings = {}, options = {}) { } const shortText = String( - target.activeModelShort ?? target.modelShort ?? target.shortName ?? '' + target.activeBaseModelShort ?? + target.baseModelShort ?? + target.activeModelShort ?? + target.modelShort ?? + target.shortName ?? + '' ).trim(); const labelText = String( - target.activeModelLabel ?? target.modelLabel ?? target.label ?? '' + target.activeBaseModelLabel ?? + target.baseModelLabel ?? + target.activeModelLabel ?? + target.modelLabel ?? + target.label ?? + '' ).trim(); const upstreamText = String( - target.activeModelUpstream ?? target.modelUpstream ?? target.upstreamName ?? '' + target.baseModelUpstream ?? + target.activeModelUpstream ?? + target.modelUpstream ?? + target.upstreamName ?? + '' ).trim(); + const rawCompactionText = `${target.activeModelShort ?? target.modelShort ?? ''} ${target.activeModelLabel ?? target.modelLabel ?? ''} ${target.activeModelUpstream ?? target.modelUpstream ?? ''}`; const responseText = String(target.responseModel ?? '').trim(); const modelKeyText = String(target.modelKey ?? '').trim(); const isCompaction = Boolean(target.isCompactionStep) || - /·(?:压缩|compact)\s*$/iu.test(shortText) || - /·(?:压缩|compact)\s*$/iu.test(upstreamText) || - /·(?:压缩|compact)\s*$/iu.test(labelText) || - /\[自动压缩\]\s*$/u.test(labelText); + /·(?:压缩|compact)(?=\s|$)|\[自动压缩\]/iu.test(rawCompactionText); const compactionSuffix = isCompaction ? t('fmt.compactionSuffix') : ''; @@ -2989,7 +3167,135 @@ function mergeModelsByDisplayName(models = [], settings = {}, options = {}) { }; }); } -return { formatMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName }; + +/** + * 根据代理索引返回对应的微边框语义徽章样式类名。 + * + * @param {number} [index=0] + * @param {boolean} [isMain=false] + * @returns {string} + */ +function getAgentBadgeClass(index = 0, isMain = false) { + if (isMain || index <= 0) return 'badge-main'; + const slot = ((index - 1) % 3) + 1; + return `badge-sub-${slot}`; +} + +/** + * 基于结构化 `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'); + if (kind === 'all') return t('header.scopeAllShort'); + if (kind === 'main') return t('fmt.mainBadge'); + if (kind === 'side_question') { + const ord = Number(agent.agentOrdinal || agent.sideIndex || 0); + if (ord > 0) return t('fmt.sideBadge', { index: ord }); + if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText); + return t('fmt.sideBadgeShort'); + } + 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); + return t('fmt.subBadgeShort'); +} + +/** + * 基于结构化 `agentKind` / `agentOrdinal` / `customRole` 格式化代理完整显示名称(零正则反拆中文)。 + * + * @param {object|null|undefined} agent + * @returns {string} + */ +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'); + if (kind === 'all') return t('header.scopeAll'); + if (kind === 'main') return t('fmt.mainAgent'); + + const rawCustom = + agent.customRole !== undefined + ? String(agent.customRole || '').trim() + : String(agent.role || '').trim(); + if (kind === 'side_question') { + const ord = Number(agent.agentOrdinal || agent.sideIndex || 0); + const baseLabel = ord > 0 ? `${t('fmt.sideQuestion')} #${ord}` : t('fmt.sideQuestion'); + const isGeneric = + !rawCustom || + rawCustom === baseLabel || + rawCustom === agent.shortLabel || + rawCustom === t('fmt.sideQuestion') || + rawCustom === 'Side Question' || + rawCustom === 'side_question'; + return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`; + } + + const ord = Number(agent.agentOrdinal || agent.index || 0); + const baseLabel = ord > 0 ? `${t('fmt.subAgent')} #${ord}` : t('fmt.subAgent'); + const isGeneric = + !rawCustom || + rawCustom === baseLabel || + rawCustom === agent.shortLabel || + rawCustom === t('fmt.subAgent') || + rawCustom === 'Subagent'; + return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`; +} + +/** + * 基于后端结构化 `actionKey` + `waitingApproval` 渲染实时动作短标题(兼容自定义 `label` 回退)。 + * + * @param {object|null|undefined} act + * @param {string} [fallbackKey='live.thinking'] + * @returns {string} + */ +function formatLiveActivityLabel(act, fallbackKey = 'live.thinking') { + if (!act || typeof act !== 'object') return t(fallbackKey); + let baseLabel = ''; + if (act.actionKey) { + const i18nKey = `live.act.${act.actionKey}`; + const translated = t(i18nKey); + if (translated && translated !== i18nKey) { + baseLabel = translated; + } + } + if (!baseLabel) { + baseLabel = String(act.label || '').trim() || t(fallbackKey); + } + if (act.waitingApproval) { + return t('live.act.awaitingApproval', { label: baseLabel }); + } + return baseLabel; +} + +/** + * 基于后端结构化 `detailKey` 渲染实时动作补充说明(兼容自由文本 `detail`)。 + * + * @param {object|null|undefined} act + * @returns {string} + */ +function formatLiveActivityDetail(act) { + if (!act || typeof act !== 'object') return ''; + if (act.detailKey === 'compaction_resuming') { + return t('live.act.compactionResuming'); + } + 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 }; })(); // --- src/core/httpClient.js --- @@ -3273,7 +3579,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, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, 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, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveScopedConversation, isMacHostPlatform } = (() => { /** * @fileoverview Reactive telemetry store with async non-overlapping poll scheduler * and granular slice updates. @@ -4295,101 +4601,6 @@ function stopAsyncTelemetryLoop() { } } -/** - * 根据代理索引返回对应的微边框语义徽章样式类名。 - * - * @param {number} [index=0] - * @param {boolean} [isMain=false] - * @returns {string} - */ -function getAgentBadgeClass(index = 0, isMain = false) { - if (isMain || index <= 0) return 'badge-main'; - const slot = ((index - 1) % 3) + 1; - return `badge-sub-${slot}`; -} - -/** - * 格式化主/子代理的紧凑短徽章文本(中文如 `主` / `子1`,英文如 `Main` / `S1`)。 - * - * @param {object|null|undefined} agent - * @returns {string} - */ -function formatAgentBadgeText(agent) { - const isSideQ = Boolean( - agent?.isSideQuestion || - agent?.typeName === 'side_question' || - /^旁\d*$/.test(String(agent?.badgeText || '')) - ); - if (!isEnglishLocale()) { - if (!agent || agent.isMain) return agent?.badgeText || '主'; - if (isSideQ) { - const sIdx = Number(agent.sideIndex || 0); - return agent.badgeText || (sIdx > 0 ? `旁${sIdx}` : '旁'); - } - return agent.badgeText || `子${agent.index || ''}`; - } - if (!agent || agent.isMain) return t('fmt.mainBadge'); - if (isSideQ) { - const m = String(agent.badgeText || '').match(/^旁(\d+)$/); - const sIdx = Number(agent.sideIndex || (m ? m[1] : 0)); - return sIdx > 0 ? t('fmt.sideBadge', { index: sIdx }) : t('fmt.sideBadgeShort'); - } - const subMatch = String(agent.badgeText || '').match(/^子(\d+)$/); - const subOrd = Number(subMatch ? subMatch[1] : agent.index || 0); - return subOrd > 0 ? t('fmt.subBadge', { index: subOrd }) : t('fmt.subBadgeShort'); -} - -/** - * 格式化主/子代理或旁路提问的完整显示名称(如 `子代理 #1 · Codebase Researcher` / `旁路提问 #1 · ...`)。 - * - * @param {object|null|undefined} agent - * @returns {string} - */ -function formatAgentLabel(agent) { - const isSideQ = Boolean( - agent?.isSideQuestion || - agent?.typeName === 'side_question' || - /^旁/.test(String(agent?.badgeText || agent?.shortLabel || '')) - ); - if (!isEnglishLocale()) { - if (!agent) return '主代理'; - if (agent.isMain) return agent.shortLabel || '主代理'; - if (isSideQ) { - const sIdx = Number(agent.sideIndex || 0); - const fallbackShort = sIdx > 0 ? `旁路提问 #${sIdx}` : '旁路提问'; - const rolePart = - agent.role && - agent.role !== '旁路提问' && - agent.role !== 'Side Question' && - agent.role !== agent.shortLabel - ? ` · ${agent.role}` - : ''; - return `${agent.shortLabel || fallbackShort}${rolePart}`; - } - const rolePart = agent.role && agent.role !== '子代理' ? ` · ${agent.role}` : ''; - return `${agent.shortLabel || '子代理'}${rolePart}`; - } - if (!agent || agent.isMain) return t('fmt.mainAgent'); - if (isSideQ) { - const m = String(agent.shortLabel || agent.badgeText || '').match(/(\d+)/); - const sIdx = Number(agent.sideIndex || (m ? m[1] : 0)); - const baseLabel = sIdx > 0 ? `${t('fmt.sideQuestion')} #${sIdx}` : t('fmt.sideQuestion'); - const rolePart = - agent.role && - agent.role !== '旁路提问' && - agent.role !== 'Side Question' && - agent.role !== agent.shortLabel - ? ` · ${agent.role}` - : ''; - return `${baseLabel}${rolePart}`; - } - const subMatch = String(agent.shortLabel || agent.badgeText || '').match(/(\d+)/); - const idx = Number(subMatch ? subMatch[1] : agent.index || 0); - const baseLabel = idx > 0 ? `${t('fmt.subAgent')} #${idx}` : t('fmt.subAgent'); - const rolePart = - agent.role && agent.role !== '子代理' && agent.role !== 'Subagent' ? ` · ${agent.role}` : ''; - return `${baseLabel}${rolePart}`; -} /** * 解析当前选中的主/子代理作用域视图数据与独立上下文窗口检视目标。 @@ -4536,7 +4747,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, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, 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, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveScopedConversation, isMacHostPlatform }; })(); // --- src/components/ui/TopLongPillNav.js --- @@ -5939,7 +6150,9 @@ function buildHeatmapMonthTicks(slots, firstDow, totalWeeks) { if (totalWeeks > 16 && c.col >= totalWeeks - 1) continue; if (ticks.length > 0 && c.col < nextAllowedCol) continue; const showYear = crossYear && (c.month === 1 || ticks.length === 0); - const text = showYear ? `${String(c.year).slice(-2)}年${c.month}月` : `${c.month}月`; + const text = showYear + ? t('chart.trend.hmMonthYear', { yy: String(c.year).slice(-2), month: c.month }) + : t('chart.trend.hmMonthOnly', { month: c.month }); ticks.push({ col: c.col, text }); nextAllowedCol = c.col + (showYear ? baseMinGap + 1 : baseMinGap); } @@ -6074,26 +6287,41 @@ function createTrendAreaChart() { const plotStage = h('div', { className: 'trend-plot-stage' }, [peakPill, svg]); // 类 GitHub 每日小格子热力图容器(> 90 天模式) - const weekdayLabels = ['一', '', '三', '', '五', '', '日']; + const wdayMonEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdayMon') }); + const wdayWedEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdayWed') }); + const wdayFriEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdayFri') }); + const wdaySunEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdaySun') }); const hmWeekdaysEl = h('div', { className: 'trend-hm-weekdays', 'aria-hidden': 'true' }, [ h('span', { className: 'trend-hm-month-spacer' }), - ...weekdayLabels.map((txt) => h('span', { className: 'trend-hm-wday', text: txt })), + wdayMonEl, + h('span', { className: 'trend-hm-wday', text: '' }), + wdayWedEl, + h('span', { className: 'trend-hm-wday', text: '' }), + wdayFriEl, + h('span', { className: 'trend-hm-wday', text: '' }), + wdaySunEl, ]); const hmMonthsEl = h('div', { className: 'trend-hm-months' }); - const hmGridEl = h('div', { className: 'trend-hm-grid', role: 'grid', 'aria-label': '每日用量热力格子图' }); + const hmGridEl = h('div', { + className: 'trend-hm-grid', + role: 'grid', + 'aria-label': t('chart.trend.hmAria'), + }); const hmTrackEl = h('div', { className: 'trend-hm-track' }, [hmMonthsEl, hmGridEl]); const hmScrollEl = h('div', { className: 'trend-hm-scroll' }, [hmTrackEl]); const hmBodyEl = h('div', { className: 'trend-heatmap-body' }, [hmWeekdaysEl, hmScrollEl]); const hmSummaryEl = h('span', { className: 'trend-hm-summary text-mono', text: '' }); + const hmLessEl = h('span', { text: t('chart.trend.hmLess') }); + const hmMoreEl = h('span', { text: t('chart.trend.hmMore') }); const hmLegendEl = h('span', { className: 'trend-hm-legend', 'aria-hidden': 'true' }, [ - h('span', { text: '少' }), + hmLessEl, h('span', { className: 'trend-hm-swatch lv-0' }), h('span', { className: 'trend-hm-swatch lv-1' }), h('span', { className: 'trend-hm-swatch lv-2' }), h('span', { className: 'trend-hm-swatch lv-3' }), h('span', { className: 'trend-hm-swatch lv-4' }), - h('span', { text: '多' }), + hmMoreEl, ]); const hmFooterEl = h('div', { className: 'trend-hm-footer' }, [hmSummaryEl, hmLegendEl]); const heatmapStage = h('div', { className: 'trend-heatmap-stage', hidden: true }, [ @@ -6122,7 +6350,10 @@ function createTrendAreaChart() { function populateTooltipContent(slot) { patchText(tipTimeEl, slot.fullLabel || slot.label || '--'); - patchText(tipCallsEl, `${Math.max(0, Math.floor(Number(slot.calls) || 0))} 次`); + patchText( + tipCallsEl, + t('cons.callsCount', { calls: Math.max(0, Math.floor(Number(slot.calls) || 0)) }) + ); const slotTok = safeSlotTokens(slot.tokens); patchText(tipTokensEl, `${formatTokensPrecise(slotTok)} tok`); const slotCost = Number.isFinite(Number(slot.costUsd)) ? Math.max(0, Number(slot.costUsd)) : 0; @@ -6142,7 +6373,11 @@ function createTrendAreaChart() { if (hasSubBreakdown) { patchText( tipSubEl, - `入 ${formatTokensPrecise(safeSlotTokens(slot.inputTokens))} · 缓 ${formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens))} · 出 ${formatTokensPrecise(safeSlotTokens(slot.outputTokens))}` + t('chart.step.ioSplit', { + inTok: formatTokensPrecise(safeSlotTokens(slot.inputTokens)), + cacheTok: formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens)), + outTok: formatTokensPrecise(safeSlotTokens(slot.outputTokens)), + }) ); } } @@ -6491,19 +6726,28 @@ function createTrendAreaChart() { const nonZeroVals = []; for (let i = 0; i < slots.length; i++) { - const t = safeSlotTokens(slots[i]?.tokens); - if (t > 0) { + const tokVal = safeSlotTokens(slots[i]?.tokens); + if (tokVal > 0) { activeDays++; - nonZeroVals.push(t); + nonZeroVals.push(tokVal); } - if (t >= maxTokens) { - maxTokens = t; + if (tokVal >= maxTokens) { + maxTokens = tokVal; peakIdx = i; } } + const locale = getEffectiveLocale(); + patchText(wdayMonEl, t('chart.trend.wdayMon')); + patchText(wdayWedEl, t('chart.trend.wdayWed')); + patchText(wdayFriEl, t('chart.trend.wdayFri')); + patchText(wdaySunEl, t('chart.trend.wdaySun')); + patchAttr(hmGridEl, 'aria-label', t('chart.trend.hmAria')); + patchText(hmLessEl, t('chart.trend.hmLess')); + patchText(hmMoreEl, t('chart.trend.hmMore')); + const sig = - `${useHeatmap ? 'hm' : `line:${viewW}`}|` + + `${locale}|${useHeatmap ? 'hm' : `line:${viewW}`}|` + slots .map( (s) => @@ -6583,8 +6827,13 @@ function createTrendAreaChart() { const peakSlot = slots[peakIdx]; const summaryText = maxTokens > 0 && peakSlot?.label - ? `活跃 ${activeDays}/${slots.length} 天 · 峰值 ${peakSlot.label} · ${formatTokensPrecise(maxTokens)}` - : `活跃 0/${slots.length} 天`; + ? t('chart.trend.hmActivePeak', { + active: activeDays, + total: slots.length, + label: peakSlot.label, + tokens: formatTokensPrecise(maxTokens), + }) + : t('chart.trend.hmActiveZero', { total: slots.length }); patchText(hmSummaryEl, summaryText); if (hoveredIdx >= slots.length) { @@ -6683,7 +6932,10 @@ function createTrendAreaChart() { const peakSlot = slots[peakIdx]; const peakText = maxTokens > 0 && peakSlot?.label - ? `峰值 ${peakSlot.label} · ${formatTokensPrecise(maxTokens)}` + ? t('chart.trend.peakPill', { + label: peakSlot.label, + tokens: formatTokensPrecise(maxTokens), + }) : formatTokensPrecise(maxTokens); patchText(peakPill, peakText); const pctLeft = Math.max(12, Math.min(88, (peakPt.x / viewW) * 100)); @@ -6734,16 +6986,16 @@ const MODEL_COLOR_VARS = Object.freeze([ * @returns {string} */ function getStepModelGroupKey(step) { - if (!step || typeof step !== 'object') return '模型未知'; - const rawLabel = String(step.modelLabel || step.label || '') + if (!step || typeof step !== 'object') return t('fmt.unknownModel'); + const rawLabel = String(step.baseModelLabel || step.modelLabel || step.label || '') .replace(/\s*\[自动压缩\]\s*$/u, '') .replace(/\s*\((?:Max|XHigh|High|Medium|Low|Thinking|Extra Low|Tiered)\)\s*$/i, '') .trim(); if (rawLabel) return rawLabel; - const rawShort = String(step.modelShort || step.shortName || '') - .replace(/·压缩\s*$/u, '') + const rawShort = String(step.baseModelShort || step.modelShort || step.shortName || '') + .replace(/·(?:压缩|Compact)\s*$/iu, '') .trim(); - return rawShort || '模型未知'; + return rawShort || t('fmt.unknownModel'); } /** @@ -7270,7 +7522,17 @@ function computeStepTickIndices(count) { function formatStepAxisTag(st, showAgentPrefix) { const num = `#${Number(st?.stepIndex ?? 0)}`; if (!showAgentPrefix) return num; - const badge = st?.agentBadge || (st?.isSubagent ? '子' : '主'); + const badge = 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, + }); return `${badge}${num}`; } @@ -7405,7 +7667,7 @@ function createSessionLineChart() { const emptyHintEl = h('div', { className: 'sstep-empty-hint text-muted', - text: '当前范围暂无可绘制的调用步骤', + text: t('chart.step.empty'), hidden: true, }); @@ -7483,7 +7745,10 @@ function createSessionLineChart() { patchText(tipHeadLeft, pt.stepTag); patchText(tipHeadRight, pt.modelText); - patchText(tipMainLeft, pt.valid ? formatChartMetricValue(currentMetric, pt.value) : '未纳入'); + patchText( + tipMainLeft, + pt.valid ? formatChartMetricValue(currentMetric, pt.value) : t('chart.step.excluded') + ); patchText(tipMainRight, pt.secondaryRight || ''); patchAttr(tipSub, 'hidden', !pt.subDetail); if (pt.subDetail) { @@ -7610,6 +7875,7 @@ function createSessionLineChart() { ? steps : steps.filter((st) => st && targetKeySet.has(getStepModelGroupKey(st))); + patchText(emptyHintEl, t('chart.step.empty')); if (!matchedSteps.length) { currentPoints = []; lastSig = 'empty'; @@ -7623,7 +7889,7 @@ function createSessionLineChart() { patchAttr(peakPill, 'hidden', true); patchAttr(emptyHintEl, 'hidden', false); clearHover(); - return { summaryBadge: '0 步' }; + return { summaryBadge: t('chart.step.zeroSteps') }; } const modelColorMap = new Map(); @@ -7637,7 +7903,7 @@ function createSessionLineChart() { const disp = resolveModelDisplayInfo({ modelLabel: gk, label: gk }, displaySettings, { fallback: gk, }); - modelLabelByGroup.set(gk, disp.text.replace(/·压缩\s*$/u, '').trim() || gk); + modelLabelByGroup.set(gk, disp.baseText || disp.text || gk); } } for (const st of matchedSteps) { @@ -7650,7 +7916,7 @@ function createSessionLineChart() { } if (!modelLabelByGroup.has(gk)) { const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk }); - modelLabelByGroup.set(gk, disp.text.replace(/·压缩\s*$/u, '').trim() || gk); + modelLabelByGroup.set(gk, disp.baseText || disp.text || gk); } } @@ -7710,41 +7976,62 @@ function createSessionLineChart() { if (metric === 'totalTokens') { value = isMultiCompare ? modelCumTok : runningTokens; - secondaryRight = `本步 +${formatTokens(stepTotalTok)}`; - subDetail = `入 ${formatTokens(inTok)} · 缓 ${formatTokens(cacheTok)} · 出 ${formatTokens(outTok)}`; + secondaryRight = t('chart.step.stepAdd', { tokens: formatTokens(stepTotalTok) }); + subDetail = t('chart.step.ioSplit', { + inTok: formatTokens(inTok), + cacheTok: formatTokens(cacheTok), + outTok: formatTokens(outTok), + }); } else if (metric === 'context') { value = ctxTok; if (hasPrevCtx) { const sign = ctxDelta >= 0 ? '+' : '-'; secondaryRight = `${sign}${formatTokens(Math.abs(ctxDelta))}`; } else { - secondaryRight = `缓存 ${Number(st.cacheHitPct ?? 0)}%`; + secondaryRight = t('chart.step.cacheShort', { pct: Number(st.cacheHitPct ?? 0) }); } subDetail = st.isCompactionStep - ? '上下文自动压缩检查点' - : `缓存命中 ${Number(st.cacheHitPct ?? 0)}% · 输出 +${formatTokens(outTok)}`; + ? t('chart.step.compactionCheckpoint') + : t('chart.step.cacheHitOut', { + pct: Number(st.cacheHitPct ?? 0), + outTok: formatTokens(outTok), + }); } else if (metric === 'tps') { valid = !st.isCompactionStep && Number.isFinite(st.tokPerSec) && st.tokPerSec > 0; value = valid ? Number(st.tokPerSec) : 0; - secondaryRight = Number.isFinite(st.ttftSec) ? `首字 ${st.ttftSec.toFixed(1)}s` : ''; + secondaryRight = Number.isFinite(st.ttftSec) + ? t('chart.step.ttftShort', { sec: st.ttftSec.toFixed(1) }) + : ''; subDetail = valid - ? `输出 ${formatTokens(outTok)} · 上下文 ${formatTokens(ctxTok)}` - : speedReasonText(st.selectedSpeedReason) || (st.isCompactionStep ? '上下文压缩步' : '无测速样本'); + ? t('chart.step.outAndCtx', { + outTok: formatTokens(outTok), + ctxTok: formatTokens(ctxTok), + }) + : speedReasonText(st.selectedSpeedReason) || + (st.isCompactionStep ? t('chart.step.compactionStep') : t('chart.step.noSpeedSample')); } 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` : ''; subDetail = valid - ? `上下文 ${formatTokens(ctxTok)} · 缓存 ${Number(st.cacheHitPct ?? 0)}%` + ? t('chart.step.ctxAndCache', { + ctxTok: formatTokens(ctxTok), + pct: Number(st.cacheHitPct ?? 0), + }) : st.isCompactionStep - ? '上下文压缩步' - : '无首字计时样本'; + ? t('chart.step.compactionStep') + : t('chart.step.noTtftSample'); } else if (metric === 'cost') { valid = stepCost !== null; value = valid ? stepCost : 0; const shownCumCost = isMultiCompare ? modelCumCost : runningCost; - secondaryRight = `累计 ${formatUsd(shownCumCost, { precise: shownCumCost > 0 && shownCumCost < 0.1 })}`; - subDetail = `缓存 ${Number(st.cacheHitPct ?? 0)}% · 本步 ${formatTokens(stepTotalTok)}`; + secondaryRight = t('chart.step.cumCost', { + cost: formatUsd(shownCumCost, { precise: shownCumCost > 0 && shownCumCost < 0.1 }), + }); + subDetail = t('chart.step.cacheAndStepTok', { + pct: Number(st.cacheHitPct ?? 0), + tokens: formatTokens(stepTotalTok), + }); } if (valid) { @@ -7804,11 +8091,12 @@ function createSessionLineChart() { const validPoints = points.filter((p) => p.valid); patchAttr(emptyHintEl, 'hidden', validPoints.length > 0); + const locale = getEffectiveLocale(); const colorSig = Array.from(modelColorMap.entries()) .map(([k, v]) => `${k}=${v}`) .join(','); const sig = - `${viewW}|${metric}|${showAgentPrefix}|${isMultiCompare ? 'multi' : 'single'}:${targetKeys.join(',')}|${colorSig}|` + + `${locale}|${viewW}|${metric}|${showAgentPrefix}|${isMultiCompare ? 'multi' : 'single'}:${targetKeys.join(',')}|${colorSig}|` + points .map((p) => `${p.stepTag}:${p.modelText}:${p.valid ? p.value.toFixed(4) : 'x'}`) .join('|'); @@ -7943,12 +8231,12 @@ function createSessionLineChart() { patchStyleVar(swatch, '--swatch-bg', colorVar); const stStat = perModelStats.get(gk); const baseLabel = modelLabelByGroup.get(gk) || gk; - let summarySuffix = '无样本'; + let summarySuffix = t('chart.step.noSamples'); if (stStat && stStat.count > 0) { if (metric === 'totalTokens') { summarySuffix = formatTokens(stStat.cumTok); } else if (metric === 'context') { - summarySuffix = `峰 ${formatTokens(stStat.max)}`; + summarySuffix = t('chart.step.peakShort', { val: formatTokens(stStat.max) }); } else if (metric === 'tps' || metric === 'ttft') { summarySuffix = formatChartMetricCompact(metric, stStat.sum / stStat.count); } else if (metric === 'cost') { @@ -7986,7 +8274,10 @@ function createSessionLineChart() { const peakPt = points[peakIdx]; patchText( peakPill, - `峰值 ${peakPt.stepTag} · ${formatChartMetricCompact(metric, peakPt.value)}` + t('chart.step.peakPill', { + tag: peakPt.stepTag, + val: formatChartMetricCompact(metric, peakPt.value), + }) ); patchStyleVar(peakPill, '--sstep-accent', isMultiCompare ? peakPt.dotColor : accentColor); const pctLeft = Math.max(14, Math.min(86, (peakPt.x / viewW) * 100)); @@ -8002,28 +8293,42 @@ function createSessionLineChart() { showHoverAt(hoveredIdx); } - let summaryBadge = `${matchedSteps.length}步`; + let summaryBadge = t('chart.step.stepsCount', { count: matchedSteps.length }); const activeCompareCount = isMultiCompare ? targetKeys.length : 1; - const multiPrefix = isMultiCompare ? `${activeCompareCount} 模型 · ` : ''; + const multiPrefix = isMultiCompare + ? t('chart.step.multiPrefix', { count: activeCompareCount }) + : ''; if (metric === 'totalTokens') { - summaryBadge = `${multiPrefix}累计 ${formatTokens(runningTokens)}`; + summaryBadge = t('chart.step.sumTokens', { + prefix: multiPrefix, + tokens: formatTokens(runningTokens), + }); } else if (metric === 'context') { const lastCtx = points[points.length - 1]?.value || 0; summaryBadge = isMultiCompare - ? `${multiPrefix}峰值 ${formatTokens(maxVal)}` - : `当前 ${formatTokens(lastCtx)}`; + ? t('chart.step.peakTokens', { prefix: multiPrefix, tokens: formatTokens(maxVal) }) + : t('chart.step.currentCtx', { tokens: formatTokens(lastCtx) }); } else if (metric === 'tps') { summaryBadge = validCount > 0 - ? `${multiPrefix}均值 ${(validSum / validCount).toFixed(1)} tok/s` - : '暂无有效样本'; + ? t('chart.step.meanTps', { + prefix: multiPrefix, + val: (validSum / validCount).toFixed(1), + }) + : t('chart.step.noValidSamples'); } else if (metric === 'ttft') { summaryBadge = validCount > 0 - ? `${multiPrefix}均值 ${(validSum / validCount).toFixed(1)}s` - : '暂无有效样本'; + ? t('chart.step.meanSec', { + prefix: multiPrefix, + val: (validSum / validCount).toFixed(1), + }) + : t('chart.step.noValidSamples'); } else if (metric === 'cost') { - summaryBadge = `${multiPrefix}累计 ${formatUsd(runningCost, { precise: runningCost > 0 && runningCost < 0.1 })}`; + summaryBadge = t('chart.step.sumCost', { + prefix: multiPrefix, + cost: formatUsd(runningCost, { precise: runningCost > 0 && runningCost < 0.1 }), + }); } return { summaryBadge }; @@ -8114,7 +8419,7 @@ function createModelFitChart() { const emptyHintEl = h('div', { className: 'sstep-empty-hint text-muted', - text: '该模型暂无有效拟合样本', + text: t('chart.fit.empty'), hidden: true, }); @@ -8129,14 +8434,16 @@ function createModelFitChart() { tipSub, ]); - const fitMethodLabelEl = h('span', { text: 'LOESS 拟合' }); + const fitMethodLabelEl = h('span', { text: t('chart.fit.loess') }); + const olsLegendTextEl = h('span', { text: t('chart.fit.olsLinear') }); const olsLegendWrapEl = h('span', { className: 'sstep-fit-legend-ols' }, [ h('span', { className: 'sstep-fit-swatch is-ols' }), - h('span', { text: 'OLS 线性' }), + olsLegendTextEl, ]); + const obsLegendTextEl = h('span', { text: t('chart.fit.observed') }); const singleLegendEl = h('span', { className: 'sstep-fit-legend' }, [ h('span', { className: 'sstep-fit-swatch is-scatter' }), - h('span', { text: '观测值' }), + obsLegendTextEl, h('span', { className: 'sstep-fit-swatch is-curve' }), fitMethodLabelEl, h('span', { className: 'sstep-fit-swatch is-ci' }), @@ -8219,8 +8526,14 @@ function createModelFitChart() { patchAttr(tooltipEl, 'hidden', false); patchText(tipHeadLeft, sp.stepTag); patchText(tipHeadRight, sp.modelText); - patchText(tipMainLeft, `拟合 ${formatChartMetricValue(currentMetric, sp.fitVal)}`); - patchText(tipMainRight, `观测 ${formatChartMetricValue(currentMetric, sp.rawVal)}`); + patchText( + tipMainLeft, + t('chart.fit.tipFit', { val: formatChartMetricValue(currentMetric, sp.fitVal) }) + ); + patchText( + tipMainRight, + t('chart.fit.tipObs', { val: formatChartMetricValue(currentMetric, sp.rawVal) }) + ); patchAttr(tipSub, 'hidden', false); if (sp.compareHint) { @@ -8234,7 +8547,10 @@ function createModelFitChart() { const ctxTok = Math.max(0, Number(sp.st?.contextTokens || 0)); patchText( tipSub, - `上下文 ${formatTokens(ctxTok)} · 缓存 ${Number(sp.st?.cacheHitPct ?? 0)}%` + t('chart.step.ctxAndCache', { + ctxTok: formatTokens(ctxTok), + pct: Number(sp.st?.cacheHitPct ?? 0), + }) ); } @@ -8500,11 +8816,16 @@ function createModelFitChart() { xVal: globalX, rawVal, stepTag: formatStepAxisTag(st, showAgentPrefix), - modelText: disp.text.replace(/·压缩\s*$/u, '').trim() || disp.text, + modelText: disp.baseText || disp.text, }); } } + const locale = getEffectiveLocale(); + patchText(emptyHintEl, t('chart.fit.empty')); + patchText(obsLegendTextEl, t('chart.fit.observed')); + patchText(olsLegendTextEl, t('chart.fit.olsLinear')); + if (fitCacheMetric !== metric) { fitCache.clear(); fitCacheMetric = metric; @@ -8528,9 +8849,10 @@ function createModelFitChart() { patchAttr(singleLegendEl, 'hidden', false); patchAttr(multiLegendEl, 'hidden', true); patchAttr(emptyHintEl, 'hidden', false); + patchText(fitMethodLabelEl, t('chart.fit.loess')); patchText(fitStatsEl, 'n = 0'); clearHover(); - return { sampleCount: 0, summaryBadge: '0 样本' }; + return { sampleCount: 0, summaryBadge: t('chart.fit.zeroSamples') }; } patchAttr(emptyHintEl, 'hidden', true); @@ -8612,7 +8934,12 @@ function createModelFitChart() { if (interp !== null) { peerParts.push(`${other.label} ${formatChartMetricCompact(metric, interp)}`); } else { - peerParts.push(`${other.label} 均 ${formatChartMetricCompact(metric, other.pubFit.mean)}`); + peerParts.push( + t('chart.fit.peerMean', { + label: other.label, + val: formatChartMetricCompact(metric, other.pubFit.mean), + }) + ); } } return { @@ -8625,7 +8952,10 @@ function createModelFitChart() { ciHigh: s.pubFit.sampleCiHigh[i], ciHalf: s.pubFit.sampleCiHalf[i], seriesColor: s.colorVar, - compareHint: peerParts.length > 0 ? `同图对比:${peerParts.join(' · ')}` : '', + compareHint: + peerParts.length > 0 + ? t('chart.fit.peerCompare', { peers: peerParts.join(' · ') }) + : '', }; }); s.samples = sSamples; @@ -8635,7 +8965,7 @@ function createModelFitChart() { currentSamples = combinedSamples; const sig = - `multi|${viewW}|${targetKeys.join(',')}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` + + `multi|${locale}|${viewW}|${targetKeys.join(',')}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` + seriesList .map( (s) => @@ -8749,7 +9079,7 @@ function createModelFitChart() { fitStatsEl, seriesList.length <= 2 ? seriesList.map((s) => `R²=${s.pubFit.r2.toFixed(2)}`).join(' · ') - : `${seriesList.length} 条拟合线` + : t('chart.fit.curvesCount', { count: seriesList.length }) ); patchAttr(fitStatsEl, 'title', r2SummaryTitle); @@ -8761,7 +9091,10 @@ function createModelFitChart() { return { sampleCount: combinedSamples.length, - summaryBadge: `${combinedSamples.length}步 · ${seriesList.length} 模型对比`, + summaryBadge: t('chart.fit.multiBadge', { + steps: combinedSamples.length, + models: seriesList.length, + }), }; } @@ -8776,7 +9109,10 @@ function createModelFitChart() { const rawYs = filtered.map((d) => d.rawVal); const pubFit = reusePublicationFit(null, xs, rawYs, maxBound, false); - patchText(fitMethodLabelEl, pubFit.method === 'LOESS' ? 'LOESS 拟合' : 'OLS 回归'); + patchText( + fitMethodLabelEl, + pubFit.method === 'LOESS' ? t('chart.fit.loess') : t('chart.fit.olsReg') + ); patchAttr(olsLegendWrapEl, 'hidden', filtered.length < 6); let dataMin = Infinity; @@ -8829,7 +9165,7 @@ function createModelFitChart() { currentSamples = samples; const sig = - `single|${viewW}|${targetKeys[0]}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` + + `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('|'); if (sig !== lastSig) { @@ -8905,7 +9241,10 @@ function createModelFitChart() { } } - const summaryBadge = `${samples.length}步 · 均 ${formatChartMetricCompact(metric, pubFit.mean)}`; + const summaryBadge = t('chart.fit.singleBadge', { + steps: samples.length, + mean: formatChartMetricCompact(metric, pubFit.mean), + }); if (samples.length >= 2) { const rSign = pubFit.r >= 0 ? '+' : ''; const slopeSign = pubFit.slope >= 0 ? '+' : ''; @@ -8913,7 +9252,11 @@ function createModelFitChart() { patchAttr( fitStatsEl, 'title', - `OLS: y = ${slopeSign}${pubFit.slope.toFixed(3)}x + ${pubFit.intercept.toFixed(2)} · 样本标准差 SD = ±${pubFit.sd.toFixed(2)}` + t('chart.fit.olsTitle', { + slope: `${slopeSign}${pubFit.slope.toFixed(3)}`, + intercept: pubFit.intercept.toFixed(2), + sd: pubFit.sd.toFixed(2), + }) ); } else { patchText(fitStatsEl, `n = ${samples.length}`); @@ -9262,15 +9605,16 @@ function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumference) }; } -function translateRawAgentBadge(rawBadge) { - if (!rawBadge) return ''; - if (!isEnglishLocale()) return String(rawBadge); - const str = String(rawBadge).trim(); - if (str === '主') return t('fmt.mainBadge'); - const m = str.match(/^子(\d+)$/); - if (m) return t('fmt.subBadge', { index: m[1] }); - if (str === '子') return t('fmt.subBadgeShort'); - return str; +function resolveActiveBadgeText(active) { + if (!active?.activeAgentBadge && !active?.activeAgentKind) return ''; + return formatAgentBadgeText({ + agentKind: + active.activeAgentKind || + (!active.activeAgentId || active.activeAgentId === 'main' ? 'main' : 'subagent'), + agentOrdinal: Number(active.activeAgentOrdinal || 0), + isMain: !active.activeAgentId || active.activeAgentId === 'main', + badgeText: active.activeAgentBadge, + }); } /** @@ -9292,7 +9636,7 @@ function resolveOverviewMetricCell(metricKey, cellCtx = {}) { fallback: t('fmt.unknownModel'), }).text; const reason = speedReasonText(active.latestSpeedReason); - const badgeStr = translateRawAgentBadge(active.activeAgentBadge); + const badgeStr = resolveActiveBadgeText(active); const modelAndAgent = hasSubagents && badgeStr ? `[${badgeStr}] ${activeModelDisplay}` : activeModelDisplay; const hasSpeed = Number.isFinite(active.latestTokPerSec) && Number(active.latestTokPerSec) > 0; @@ -9876,14 +10220,16 @@ const ContextWindowWidget = defineComponent({ if (interactiveInspector) { patchAttr(ctxInspectorBar, 'hidden', !hasSubagents); if (hasSubagents && ctxAgent) { - const rawActiveBadge = aggregated?.activeAgentBadge || '主'; - const activeBadgeText = isEnglishLocale() - ? rawActiveBadge === '主' - ? t('fmt.mainBadge') - : rawActiveBadge - .replace(/^子(\d+)$/, (_, n) => t('fmt.subBadge', { index: n })) - .replace(/^旁(\d+)$/, (_, n) => t('fmt.sideBadge', { index: n })) - : rawActiveBadge; + const activeBadgeText = formatAgentBadgeText({ + agentKind: + aggregated?.activeAgentKind || + (!aggregated?.activeAgentId || aggregated.activeAgentId === 'main' + ? 'main' + : 'subagent'), + agentOrdinal: Number(aggregated?.activeAgentOrdinal || 0), + isMain: !aggregated?.activeAgentId || aggregated.activeAgentId === 'main', + badgeText: aggregated?.activeAgentBadge, + }); const pillItems = [ { @@ -10430,19 +10776,77 @@ return { buildQuotaPoolItems, createPoolQuotaRow, formatQuotaSummaryFooter, sync })(); // --- src/components/widgets/LiveActivityWidget.js --- -const { LiveActivityWidget } = (() => { +const { buildFallbackRunningConversations, LiveActivityWidget } = (() => { /** * @fileoverview Standalone decoupled Live Running Tasks Widget (`LiveActivityWidget.js`). * Displays active multi-session running conversations & collapsible subagent activity - * with an isolated 1s elapsed timer lifecycle. + * with an isolated 1s elapsed timer lifecycle. Supports both Overview/Hover widget mode + * and controlled Multi-Session Floating Panel mode (`WindowOverlayShell.js`). */ +function buildFallbackRunningConversations( + data, + { agents = [], aggregated = null, latestTokPerSec = undefined, contextUsedPct = undefined } = {} +) { + if (!data) return []; + if (Array.isArray(data.runningConversations) && data.runningConversations.length > 0) { + return data.runningConversations; + } + const activeConv = data.activeConversation || {}; + if (!activeConv.isRunning && !aggregated?.isRunning) return []; + return [ + { + cascadeId: activeConv.cascadeId || 'current', + title: activeConv.title || t('live.currentSession'), + 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, + ...(latestTokPerSec !== undefined ? { latestTokPerSec } : {}), + ...(contextUsedPct !== undefined ? { contextUsedPct } : {}), + subagents: (agents || []) + .filter((a) => !a.isMain) + .map((s, idx) => ({ + 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), + customRole: s.customRole, + ...(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}`, + 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'), + detail: '', + stepProgress: '', + startedAtMs: s.lastModifiedMs || 0, + signature: `${s.agentId}:${s.stepCount || 0}`, + }, + })), + }, + ]; +} + const LiveActivityWidget = defineComponent({ name: 'LiveActivityWidget', setup({ props, onCleanup }) { const interactive = props.interactive !== false; const preview = Boolean(props.preview); + const defaultExpandRunningSubs = Boolean(props.defaultExpandRunningSubs); + const showSessionExtras = Boolean(props.showSessionExtras); + const onSelectSession = + typeof props.onSelectSession === 'function' ? props.onSelectSession : null; + const onLayoutChange = + typeof props.onLayoutChange === 'function' ? props.onLayoutChange : null; const getCtxAgentId = typeof props.getCtxAgentId === 'function' ? props.getCtxAgentId @@ -10456,10 +10860,19 @@ const LiveActivityWidget = defineComponent({ 'aria-live': 'polite', }); - const expandedTaskConvIds = new Set(); + const manualSubExpandMap = new Map(); const activityTimersMap = new Map(); let liveTickTimer = null; - let latestData = null; + let latestUpdateArgs = null; + + function resolveIsExpanded(item) { + const runSubCount = Number(item?.runningSubagentCount || 0); + if (!interactive) return runSubCount > 0; + if (manualSubExpandMap.has(item.cascadeId)) { + return Boolean(manualSubExpandMap.get(item.cascadeId)); + } + return defaultExpandRunningSubs ? runSubCount > 0 : false; + } function bindLiveElapsedTimer(timerKey, sig, rawStartMs, targetEl) { const now = Date.now(); @@ -10522,6 +10935,20 @@ const LiveActivityWidget = defineComponent({ className: 'live-task-title', text: t('live.currentSession'), }); + const hereTagEl = showSessionExtras + ? h('span', { + className: 'wm-session-tag is-here', + hidden: true, + text: t('multi.hereTag'), + }) + : null; + const metricsEl = showSessionExtras + ? h('span', { + className: 'wm-task-metrics text-mono', + hidden: true, + text: '', + }) + : null; const subToggleBtn = h('button', { type: 'button', className: 'live-sub-toggle', @@ -10534,8 +10961,16 @@ const LiveActivityWidget = defineComponent({ }); const headerEl = h('div', { className: 'live-task-header' }, [ - h('div', { className: 'live-task-title-wrap' }, [dotWrap, titleEl]), - h('div', { className: 'live-task-header-right' }, [subToggleBtn, elapsedEl]), + h('div', { className: 'live-task-title-wrap' }, [ + dotWrap, + titleEl, + ...(hereTagEl ? [hereTagEl] : []), + ]), + h('div', { className: 'live-task-header-right' }, [ + ...(metricsEl ? [metricsEl] : []), + subToggleBtn, + elapsedEl, + ]), ]); const mainBadge = h('span', { @@ -10576,6 +11011,8 @@ const LiveActivityWidget = defineComponent({ cardEl, dotIcon, titleEl, + hereTagEl, + metricsEl, subToggleBtn, elapsedEl, mainBadge, @@ -10614,103 +11051,86 @@ const LiveActivityWidget = defineComponent({ }; } - function update({ data } = {}) { - latestData = data || null; - if (!data) { + function update({ data = null, items = null, hostRouteConversationId = '' } = {}) { + latestUpdateArgs = { data, items, hostRouteConversationId }; + if (!data && !Array.isArray(items)) { patchAttr(liveActivityBar, 'hidden', true); stopLiveTicker(); return; } - const { agents, aggregated } = resolveScopedConversation( - data, - 'all', - getCtxAgentId() - ); + let rawRunningList = Array.isArray(items) ? items : null; + if (!rawRunningList) { + const { agents, aggregated } = resolveScopedConversation( + data, + 'all', + getCtxAgentId() + ); + rawRunningList = buildFallbackRunningConversations(data, { agents, aggregated }); + } - const rawRunningList = - Array.isArray(data.runningConversations) && data.runningConversations.length > 0 - ? data.runningConversations - : data.activeConversation?.isRunning || aggregated?.isRunning - ? [ - { - cascadeId: data.activeConversation?.cascadeId || 'current', - title: data.activeConversation?.title || t('live.currentSession'), - isCurrentSelected: true, - isMainRunning: Boolean(data.activeConversation?.isRunning), - isRunning: true, - mainActivity: - data.activeConversation?.liveActivity || aggregated?.liveActivity || null, - subagentCount: Math.max(0, agents.length - 1), - runningSubagentCount: agents.filter((a) => !a.isMain && a.isRunning).length, - subagents: agents - .filter((a) => !a.isMain) - .map((s, idx) => ({ - cascadeId: s.cascadeId || s.agentId, - index: s.index || idx + 1, - badgeText: formatAgentBadgeText({ ...s, index: s.index || idx + 1 }), - shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`, - role: s.role || `${t('fmt.subAgent')} #${idx + 1}`, - isRunning: Boolean(s.isRunning), - stepCount: Number(s.stepCount || 0), - lastModifiedMs: s.lastModifiedMs || 0, - liveActivity: s.liveActivity || { - phase: s.isRunning ? 'thinking' : 'done', - label: s.isRunning ? t('live.thinking') : t('live.done'), - detail: '', - stepProgress: '', - startedAtMs: s.lastModifiedMs || 0, - signature: `${s.agentId}:${s.stepCount || 0}`, - }, - })), - }, - ] - : []; + if (manualSubExpandMap.size > 0) { + const runningIdsSet = new Set(rawRunningList.map((item) => item.cascadeId)); + for (const id of [...manualSubExpandMap.keys()]) { + if (!runningIdsSet.has(id)) { + manualSubExpandMap.delete(id); + } + } + } const hasRunningTasks = rawRunningList.length > 0; patchAttr(liveActivityBar, 'hidden', !hasRunningTasks); if (!hasRunningTasks) { stopLiveTicker(); - expandedTaskConvIds.clear(); + patchKeyedList(liveActivityBar, [], {}); return; } + if (!isVisibleFn()) { + pauseTicker(); + return; + } + + const locale = getEffectiveLocale(); + const hostRouteLower = showSessionExtras + ? String(hostRouteConversationId || extractHostRouteCascadeId() || '').toLowerCase() + : ''; + const activeTimerKeys = new Set(); for (const item of rawRunningList) { activeTimerKeys.add(`main:${item.cascadeId}`); - for (const sub of item.subagents || []) { - if (sub?.isRunning) { - activeTimerKeys.add(`sub:${sub.cascadeId}`); + const subCount = Number(item.subagentCount || item.subagents?.length || 0); + const isExp = resolveIsExpanded(item); + if (subCount > 0 && isExp) { + for (const sub of item.subagents || []) { + if (sub?.isRunning) { + activeTimerKeys.add(`sub:${sub.cascadeId}`); + } } } } - const runningIdsSet = new Set(rawRunningList.map((item) => item.cascadeId)); - for (const id of [...expandedTaskConvIds]) { - if (!runningIdsSet.has(id)) { - expandedTaskConvIds.delete(id); - } - } - - const locale = getEffectiveLocale(); patchKeyedList(liveActivityBar, rawRunningList, { keyFn: (item) => item.cascadeId, sigFn: (item) => { - const isExp = interactive - ? expandedTaskConvIds.has(item.cascadeId) - : Number(item.runningSubagentCount || 0) > 0; + const isExp = resolveIsExpanded(item); + const isHere = + showSessionExtras && + Boolean(hostRouteLower) && + String(item.cascadeId || '').toLowerCase() === hostRouteLower; const subSig = (item.subagents || []) .map( (s) => `${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}` ) .join('|'); - return `${locale}:${item.cascadeId}:${item.title}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`; + 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}`; }, createRow: createLiveTaskCard, updateRow: (refs, item) => { const act = item.mainActivity || { phase: 'thinking', + actionKey: 'thinking', label: t('live.thinking'), detail: '', stepProgress: '', @@ -10729,9 +11149,18 @@ const LiveActivityWidget = defineComponent({ const convTitle = item.title || item.cascadeId?.slice(0, 8) || t('live.currentSession'); patchText(refs.titleEl, convTitle); if (interactive && !preview) { - patchAttr(refs.titleEl, 'title', t('live.switchSessionTitle', { title: convTitle })); - refs.titleEl.onclick = () => { - if (item.cascadeId && item.cascadeId !== 'current') { + patchAttr( + refs.titleEl, + 'title', + onSelectSession + ? t('multi.inspectSessionTitle', { title: convTitle }) + : t('live.switchSessionTitle', { title: convTitle }) + ); + refs.titleEl.onclick = (e) => { + e?.stopPropagation?.(); + if (onSelectSession) { + onSelectSession(item.cascadeId); + } else if (item.cascadeId && item.cascadeId !== 'current') { uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); telemetryStore.setState({ selectedConversationId: item.cascadeId }); fetchTelemetry({ force: false }); @@ -10739,11 +11168,32 @@ const LiveActivityWidget = defineComponent({ }; } + if (showSessionExtras && refs.hereTagEl && refs.metricsEl) { + const isHere = + Boolean(hostRouteLower) && + String(item.cascadeId || '').toLowerCase() === hostRouteLower; + patchText(refs.hereTagEl, t('multi.hereTag')); + patchAttr(refs.hereTagEl, 'hidden', !isHere); + + const metricParts = []; + if (Number.isFinite(item.latestTokPerSec) && item.latestTokPerSec > 0) { + metricParts.push( + `${item.latestTokPerSec >= 100 ? Math.round(item.latestTokPerSec) : item.latestTokPerSec.toFixed(1)} t/s` + ); + } + if (item.contextUsedPct != null && Number.isFinite(Number(item.contextUsedPct))) { + metricParts.push(`${Math.round(Number(item.contextUsedPct))}%`); + } + const metricsStr = metricParts.join(' · '); + patchAttr(refs.metricsEl, 'hidden', !metricsStr); + if (metricsStr) { + patchText(refs.metricsEl, metricsStr); + } + } + const subCount = Number(item.subagentCount || item.subagents?.length || 0); const runSubCount = Number(item.runningSubagentCount || 0); - const isExpanded = interactive - ? expandedTaskConvIds.has(item.cascadeId) - : runSubCount > 0; + const isExpanded = resolveIsExpanded(item); patchText(refs.mainBadge, t('fmt.mainBadge')); patchAttr(refs.mainBadge, 'hidden', subCount === 0); patchAttr(refs.subToggleBtn, 'hidden', subCount === 0); @@ -10763,39 +11213,37 @@ const LiveActivityWidget = defineComponent({ ); refs.subToggleBtn.onclick = (e) => { e.stopPropagation(); - if (expandedTaskConvIds.has(item.cascadeId)) { - expandedTaskConvIds.delete(item.cascadeId); - } else { - expandedTaskConvIds.add(item.cascadeId); - } - if (latestData) update({ data: latestData }); + manualSubExpandMap.set(item.cascadeId, !isExpanded); + if (latestUpdateArgs) update(latestUpdateArgs); + onLayoutChange?.(); }; } } + const mainLabel = formatLiveActivityLabel(act, 'live.thinking'); + const detailStr = formatLiveActivityDetail(act); const mainTimerKey = `main:${item.cascadeId}`; activeTimerKeys.add(mainTimerKey); bindLiveElapsedTimer( mainTimerKey, - `${item.cascadeId}:${act.signature || act.label}`, + `${item.cascadeId}:${act.signature || mainLabel}`, act.startedAtMs, refs.elapsedEl ); - patchText(refs.mainPhase, act.label || t('live.thinking')); + patchText(refs.mainPhase, mainLabel); const progText = act.stepProgress ? `[${act.stepProgress}]` : ''; patchAttr(refs.mainProgress, 'hidden', !progText); if (progText) { patchText(refs.mainProgress, progText); } - const detailStr = act.detail || ''; patchAttr(refs.mainSep, 'hidden', !detailStr); patchAttr(refs.mainDetail, 'hidden', !detailStr); patchText(refs.mainDetail, detailStr); - if (interactive) { - const fullTooltip = `[${convTitle}] ${t('fmt.mainAgent')} · ${act.label || ''}${progText ? ` ${progText}` : ''}${detailStr ? ` · ${detailStr}` : ''}`; + if (interactive && !showSessionExtras) { + const fullTooltip = `[${convTitle}] ${t('fmt.mainAgent')} · ${mainLabel}${progText ? ` ${progText}` : ''}${detailStr ? ` · ${detailStr}` : ''}`; patchAttr(refs.cardEl, 'title', fullTooltip); } @@ -10811,6 +11259,7 @@ const LiveActivityWidget = defineComponent({ updateRow: (subRefs, sub) => { const subAct = sub.liveActivity || { phase: sub.isRunning ? 'thinking' : 'done', + actionKey: sub.isRunning ? 'thinking' : 'done', label: sub.isRunning ? t('live.thinking') : t('live.done'), detail: '', stepProgress: '', @@ -10827,20 +11276,30 @@ const LiveActivityWidget = defineComponent({ patchAttr(subRefs.subBadge, 'class', `agent-badge ${badgeCls}`); patchText(subRefs.subBadge, subBadgeText); - const roleText = sub.role || sub.shortLabel || t('fmt.subAgent'); + 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}` : ''}`; + const roleText = + sub.customRole !== undefined + ? sub.customRole || fallbackRole + : sub.role || sub.shortLabel || fallbackRole; patchText(subRefs.subRole, roleText); - const rawSubLabel = sub.isRunning - ? subAct.label || '' - : subAct.label || t('live.done'); + const subLabel = sub.isRunning + ? formatLiveActivityLabel(subAct, 'live.running') + : formatLiveActivityLabel(subAct, 'live.done'); + const subDetail = formatLiveActivityDetail(subAct); const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : ''; - const summaryStr = [`${rawSubLabel}${subProg}`.trim(), subAct.detail || ''] - .filter(Boolean) - .join(' '); + const summaryStr = showSessionExtras + ? sub.isRunning + ? `${subLabel}${subProg}${subDetail ? ` · ${subDetail}` : ''}` + : t('live.doneWithSteps', { steps: sub.stepCount || 0 }) + : [`${subLabel}${subProg}`.trim(), subDetail].filter(Boolean).join(' '); patchAttr(subRefs.subSummary, 'hidden', !summaryStr); patchText(subRefs.subSummary, summaryStr); - if (interactive) { + if (interactive && !showSessionExtras) { patchAttr( subRefs.rowEl, 'title', @@ -10853,8 +11312,8 @@ const LiveActivityWidget = defineComponent({ activeTimerKeys.add(subTimerKey); bindLiveElapsedTimer( subTimerKey, - `${sub.cascadeId}:${subAct.signature || subAct.label}`, - subAct.startedAtMs, + `${sub.cascadeId}:${subAct.signature || subLabel}`, + subAct.startedAtMs || sub.lastModifiedMs, subRefs.subElapsed ); } else { @@ -10894,7 +11353,7 @@ const LiveActivityWidget = defineComponent({ }; }, }); -return { LiveActivityWidget }; +return { buildFallbackRunningConversations, LiveActivityWidget }; })(); // --- src/registries/widgetRegistry.js --- @@ -11528,7 +11987,7 @@ return { STEP_COLUMN_KEYS, DEFAULT_STEP_COLUMN_KEYS, formatCustomTokenComboHeade })(); // --- src/components/widgets/CapsuleBarWidget.js --- -const { RING_RADIUS, RING_CIRCUMFERENCE, createCapsuleSlotNode, syncCapsuleSlotNodes, CapsuleBarWidget } = (() => { +const { RING_RADIUS, RING_CIRCUMFERENCE, 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 @@ -11539,6 +11998,91 @@ const { RING_RADIUS, RING_CIRCUMFERENCE, createCapsuleSlotNode, syncCapsuleSlotN const RING_RADIUS = 5.2; const RING_CIRCUMFERENCE = +(2 * Math.PI * RING_RADIUS).toFixed(2); +/** + * Compute shared context ring + 1..5 capsule slot metric payload from telemetry & scoped conversation. + */ +function buildCapsuleSlotContext( + data, + { scopedConv = null, overviewConv = null, ctxAgent = null, aggregated = null } = {} +) { + if (!data) return { hasTelemetry: false }; + const activeConv = data.activeConversation || {}; + const overviewActive = overviewConv || scopedConv || aggregated || activeConv; + const capActive = scopedConv || aggregated || activeConv || {}; + const ctx = ctxAgent?.context || overviewActive.context || activeConv.context || {}; + const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000); + const totalTokens = Number(ctx.totalTokens || 0); + const usedPct = + limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0; + const dashOffset = +( + RING_CIRCUMFERENCE * + (1 - Math.max(0, Math.min(100, usedPct)) / 100) + ).toFixed(2); + + const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning); + const capInTok = Math.max(0, Number(capActive.inputTokens || 0)); + const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0)); + const capOutTok = Math.max(0, Number(capActive.outputTokens || 0)); + const sessionTokens = + Number(capActive.stepCount || 0) > 0 || + capActive.totalTokens != null || + capInTok + capCacheTok + capOutTok > 0 + ? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok)) + : null; + + return { + hasTelemetry: true, + usedPct, + dashOffset, + isRunning, + tps: scopedConv?.latestTokPerSec ?? aggregated?.latestTokPerSec ?? activeConv.latestTokPerSec ?? null, + avgTps: scopedConv?.avgTokPerSec ?? aggregated?.avgTokPerSec ?? activeConv.avgTokPerSec ?? null, + ttft: scopedConv?.latestTtftSec ?? aggregated?.latestTtftSec ?? activeConv.latestTtftSec ?? null, + stepCost: + scopedConv?.latestStepCostUsd ?? + aggregated?.latestStepCostUsd ?? + activeConv.latestStepCostUsd ?? + null, + sessionCost: + scopedConv?.sessionCostUsd ?? aggregated?.sessionCostUsd ?? activeConv.sessionCostUsd ?? null, + cacheHitPct: + Number(capActive.stepCount || 0) > 0 + ? capActive.latestCacheHitPct ?? capActive.sessionCacheHitPct ?? null + : null, + latestPromptTokens: capActive.latestPromptTokens ?? null, + sessionTokens, + quotas: data.quotas, + }; +} + +/** + * Compute multi-session button state & normalized running conversation list. + */ +function resolveMultiSessionCapsuleState( + data, + { agents = [], aggregated = null, latestTokPerSec = undefined, contextUsedPct = undefined } = {} +) { + const rawRunningList = buildFallbackRunningConversations(data, { + agents, + aggregated, + latestTokPerSec, + contextUsedPct, + }); + const runningCount = rawRunningList.length; + const runningSubCount = rawRunningList.reduce( + (acc, item) => acc + Number(item.runningSubagentCount || 0), + 0 + ); + const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting'); + const multiBtnText = + runningCount > 0 + ? runningSubCount > 0 + ? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount }) + : t('capsule.multiRunning', { count: runningCount }) + : t('capsule.multiZero'); + return { rawRunningList, runningCount, runningSubCount, hasWaiting, multiBtnText }; +} + /** * Create a single reusable capsule metric slot node (`0..4`) with an optional SVG context ring. */ @@ -11795,75 +12339,26 @@ const CapsuleBarWidget = defineComponent({ return; } - const { scopedConv, ctxAgent, aggregated } = resolveScopedConversation( + const { agents, scopedConv, ctxAgent, aggregated } = resolveScopedConversation( data, 'all', 'auto' ); - const activeConv = data.activeConversation || {}; - const capActive = scopedConv || aggregated || activeConv; - const ctx = ctxAgent?.context || capActive.context || activeConv.context || {}; - const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000); - const totalTokens = Number(ctx.totalTokens || 0); - const usedPct = - limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0; - const dashOffset = +( - RING_CIRCUMFERENCE * - (1 - Math.max(0, Math.min(100, usedPct)) / 100) - ).toFixed(2); - - const rawRunningList = Array.isArray(data.runningConversations) - ? data.runningConversations - : []; - const runningCount = rawRunningList.length; - const runningSubCount = rawRunningList.reduce( - (acc, item) => acc + Number(item.runningSubagentCount || 0), - 0 - ); - const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting'); + const slotCtx = buildCapsuleSlotContext(data, { scopedConv, ctxAgent, aggregated }); + const { runningCount, hasWaiting, multiBtnText } = resolveMultiSessionCapsuleState(data, { + agents, + aggregated, + contextUsedPct: slotCtx.usedPct, + }); patchClasses(multiBtn, { 'is-running': runningCount > 0 && !hasWaiting, 'is-waiting': runningCount > 0 && hasWaiting, }); - const multiBtnText = - runningCount > 0 - ? runningSubCount > 0 - ? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount }) - : t('capsule.multiRunning', { count: runningCount }) - : t('capsule.multiZero'); patchText(multiLabel, multiBtnText); - const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning); - const capInTok = Math.max(0, Number(capActive.inputTokens || 0)); - const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0)); - const capOutTok = Math.max(0, Number(capActive.outputTokens || 0)); - const sessionTokens = - Number(capActive.stepCount || 0) > 0 || - capActive.totalTokens != null || - capInTok + capCacheTok + capOutTok > 0 - ? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok)) - : null; - - patchClasses(capsuleBtn, { 'is-running': isRunning }); - syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, { - hasTelemetry: true, - usedPct, - dashOffset, - isRunning, - tps: capActive.latestTokPerSec ?? null, - avgTps: capActive.avgTokPerSec ?? null, - ttft: capActive.latestTtftSec ?? null, - stepCost: capActive.latestStepCostUsd ?? null, - sessionCost: capActive.sessionCostUsd ?? null, - cacheHitPct: - Number(capActive.stepCount || 0) > 0 - ? capActive.latestCacheHitPct ?? capActive.sessionCacheHitPct ?? null - : null, - latestPromptTokens: capActive.latestPromptTokens ?? null, - sessionTokens, - quotas: data.quotas, - }); + patchClasses(capsuleBtn, { 'is-running': slotCtx.isRunning }); + syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx); } return { @@ -11879,7 +12374,7 @@ const CapsuleBarWidget = defineComponent({ }; }, }); -return { RING_RADIUS, RING_CIRCUMFERENCE, createCapsuleSlotNode, syncCapsuleSlotNodes, CapsuleBarWidget }; +return { RING_RADIUS, RING_CIRCUMFERENCE, buildCapsuleSlotContext, resolveMultiSessionCapsuleState, createCapsuleSlotNode, syncCapsuleSlotNodes, CapsuleBarWidget }; })(); // --- src/components/widgets/StepTableWidget.js --- @@ -11892,14 +12387,11 @@ const { formatTurnPromptText, StepTableWidget } = (() => { */ -function formatTurnPromptText(rawPrompt) { +function formatTurnPromptText(rawPrompt, { hasMedia = false, mediaOnly = false } = {}) { const text = String(rawPrompt || '').trim(); - if (!text || !isEnglishLocale()) return text; - if (text === '[图片/附件提问]') return t('steps.turnMediaOnly'); - if (text.endsWith(' [附图]')) { - return `${text.slice(0, -5)} ${t('steps.turnMediaSuffix')}`; - } - return text; + if (mediaOnly || (!text && hasMedia)) return t('steps.turnMediaOnly'); + if (!text) return ''; + return hasMedia ? `${text} ${t('steps.turnMediaSuffix')}` : text; } const StepTableWidget = defineComponent({ @@ -12079,7 +12571,13 @@ const StepTableWidget = defineComponent({ const getStepIsLatest = (st) => Boolean(useRootTurn ? (st?.isRootLatestTurn ?? st?.isLatestTurn) : st?.isLatestTurn); const getStepPrompt = (st) => - (useRootTurn ? (st?.rootTurnPrompt ?? st?.turnPrompt) : st?.turnPrompt) || ''; + (useRootTurn + ? (st?.rootTurnPromptClean ?? st?.rootTurnPrompt ?? st?.turnPromptClean ?? st?.turnPrompt) + : (st?.turnPromptClean ?? st?.turnPrompt)) || ''; + const getStepHasMedia = (st) => + 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) => { const tIdx = getStepTurnIdx(st); if (!Number.isInteger(tIdx) || tIdx <= 0) return ''; @@ -12088,8 +12586,13 @@ const StepTableWidget = defineComponent({ const formattedPrompts = new Map(); function formattedTurnPrompt(st) { const raw = getStepPrompt(st); - if (!formattedPrompts.has(raw)) formattedPrompts.set(raw, formatTurnPromptText(raw)); - return formattedPrompts.get(raw); + const hasMedia = getStepHasMedia(st); + const mediaOnly = getStepMediaOnly(st); + const cacheKey = `${mediaOnly ? 2 : hasMedia ? 1 : 0}:${raw}`; + if (!formattedPrompts.has(cacheKey)) { + formattedPrompts.set(cacheKey, formatTurnPromptText(raw, { hasMedia, mediaOnly })); + } + return formattedPrompts.get(cacheKey); } const decoratedSteps = tableSteps.map((st, idx) => { @@ -12211,28 +12714,38 @@ const StepTableWidget = defineComponent({ const badgeCls = getAgentBadgeClass(st.agentIndex || 0, !st.isSubagent); const clickableCls = interactiveBadges && onSelectAgentScopes ? ' is-clickable' : ''; patchAttr(refs.agentBadgeEl, 'class', `agent-badge${clickableCls} ${badgeCls}`); - const badgeText = isEnglishLocale() - ? formatAgentBadgeText({ - isMain: !st.isSubagent, - isSideQuestion: Boolean(st.isSideQuestion), - sideIndex: st.sideIndex || 0, - index: st.agentIndex || 0, - badgeText: st.agentBadge, - }) - : st.agentBadge || (st.isSideQuestion ? '旁' : st.isSubagent ? '子' : '主'); + const badgeText = 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, + }); patchText(refs.agentBadgeEl, badgeText); if (interactiveBadges && onSelectAgentScopes) { const targetScope = st.agentId || 'main'; const isSoleTarget = effectiveScopes.length === 1 && effectiveScopes[0] === targetScope; - const agentName = isEnglishLocale() - ? formatAgentLabel({ - isMain: !st.isSubagent, - index: st.agentIndex || 0, - role: st.agentRole || '', - }) - : st.agentLabel || t('steps.unitAgent'); + const agentName = formatAgentLabel({ + agentKind: + st.agentKind || + (!st.isSubagent ? 'main' : st.isSideQuestion ? 'side_question' : 'subagent'), + agentOrdinal: + st.agentOrdinal || (st.isSideQuestion ? st.sideIndex || 0 : st.agentIndex || 0), + customRole: st.agentCustomRole, + isMain: !st.isSubagent, + isSideQuestion: Boolean(st.isSideQuestion), + sideIndex: st.sideIndex || 0, + index: st.agentIndex || 0, + role: st.agentRole || '', + shortLabel: st.agentLabel || '', + }); patchAttr( refs.agentBadgeEl, 'title', @@ -12634,8 +13147,12 @@ function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) ...mainAgent, agentId: 'all', isMain: false, - badgeText: '全部', + agentKind: 'all', + agentOrdinal: 0, + badgeText: t('header.scopeAllShort'), activeAgentId: 'main', + activeAgentKind: 'main', + activeAgentOrdinal: 0, stepCount: 24, speedSampleCount: 23, speedSummary: { sampleCount: 23, excludedCount: 1 }, @@ -12649,7 +13166,7 @@ function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) cacheReadTokens: 1540000, outputTokens: 28400, totalTokens: 1754800, - activeAgentBadge: '主', + activeAgentBadge: t('fmt.mainBadge'), modelBreakdown: [...mainAgent.modelBreakdown, ...subAgent1.modelBreakdown], recentSteps: mockSteps, }; @@ -17281,17 +17798,20 @@ const StepsDetailView = defineComponent({ let isDirty = false; function resolveDefaultActiveModelKey(scopedConv, chronoSteps, models, availableModelKeys) { - const activeCand = getStepModelGroupKey({ - modelLabel: scopedConv?.activeModelLabel, - modelShort: scopedConv?.activeModelShort, - }); - if ( - activeCand && - activeCand !== '模型未知' && - activeCand !== t('fmt.unknownModel') && - availableModelKeys.has(activeCand) - ) { - return activeCand; + if (scopedConv?.hasKnownModel !== false) { + const activeCand = getStepModelGroupKey({ + baseModelLabel: scopedConv?.activeBaseModelLabel, + baseModelShort: scopedConv?.activeBaseModelShort, + modelLabel: scopedConv?.activeModelLabel, + modelShort: scopedConv?.activeModelShort, + }); + if ( + activeCand && + activeCand !== t('fmt.unknownModel') && + availableModelKeys.has(activeCand) + ) { + return activeCand; + } } for (let i = chronoSteps.length - 1; i >= 0; i--) { const st = chronoSteps[i]; @@ -17471,7 +17991,7 @@ const StepsDetailView = defineComponent({ if (!stepModelOptionMap.has(gk)) { const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk }); stepModelOptionMap.set(gk, { - label: disp.text.replace(/·(?:压缩|Compact)\s*$/iu, '').trim() || gk, + label: disp.baseText || disp.text || gk, calls: 0, }); } @@ -17502,7 +18022,7 @@ const StepsDetailView = defineComponent({ }); perModelOptions.push({ value: gk, - label: disp.text.replace(/·(?:压缩|Compact)\s*$/iu, '').trim() || gk, + label: disp.baseText || disp.text || gk, meta: t('header.convMetaSteps', { count: Number(m.calls || 0) }), }); } @@ -19262,9 +19782,6 @@ function mountWindowOverlay() { let multiPinned = false; let hoverLeaveTimer = null; let multiLeaveTimer = null; - const manualSubExpandMap = new Map(); - const multiTimersMap = new Map(); - let multiLiveTickTimer = null; let hasPointerCoords = Boolean( carryOverPointer && Number.isFinite(carryOverPointer.x) && @@ -19362,52 +19879,6 @@ function mountWindowOverlay() { }, 90); } - function bindMultiElapsedTimer(timerKey, sig, rawStartMs, targetEl) { - const now = Date.now(); - const prev = multiTimersMap.get(timerKey); - let startMs = prev?.startMs || 0; - if (!prev || prev.sig !== sig) { - const validRaw = Number(rawStartMs || 0); - startMs = validRaw > 0 && validRaw <= now + 2000 ? validRaw : now; - } else if (startMs <= 0 && Number(rawStartMs) > 0 && Number(rawStartMs) <= now + 2000) { - startMs = Number(rawStartMs); - } - multiTimersMap.set(timerKey, { sig, startMs, el: targetEl }); - const elapsedSec = Math.max(0, (now - startMs) / 1000); - patchText(targetEl, formatElapsedSec(elapsedSec)); - } - - function tickMultiElapsedDisplay() { - const now = Date.now(); - for (const entry of multiTimersMap.values()) { - if (!entry?.el) continue; - const elapsedSec = entry.startMs > 0 ? Math.max(0, (now - entry.startMs) / 1000) : 0; - patchText(entry.el, formatElapsedSec(elapsedSec)); - } - } - - function pauseMultiLiveTicker() { - if (multiLiveTickTimer) { - clearInterval(multiLiveTickTimer); - multiLiveTickTimer = null; - } - } - - function stopMultiLiveTicker() { - pauseMultiLiveTicker(); - multiTimersMap.clear(); - } - - function ensureMultiLiveTicker() { - if (multiTimersMap.size === 0) { - stopMultiLiveTicker(); - return; - } - if (!multiLiveTickTimer) { - multiLiveTickTimer = setInterval(tickMultiElapsedDisplay, 1000); - } - } - function inspectSessionInMonitor(cascadeId) { if (!cascadeId || cascadeId === 'current') return; uiStore.setState({ @@ -19704,105 +20175,7 @@ function mountWindowOverlay() { [hoverUpdateBar, hoverWidgetsContainer] ); - // 左侧多会话实时看板浮层(活跃运行会话卡片 + 近期多窗口会话速览,全槽位预占、就地补丁更新) - function createMultiLiveSubRow() { - const subBadge = h('span', { - className: 'agent-badge badge-sub-1', - text: t('fmt.subBadge', { index: 1 }), - }); - const subRole = h('span', { className: 'live-sub-role', text: t('fmt.subAgent') }); - const subSummary = h('span', { className: 'live-sub-summary', text: '' }); - const subElapsed = h('span', { className: 'live-sub-elapsed text-mono', text: '0s' }); - const rowEl = h('div', { className: 'live-sub-row' }, [ - h('div', { className: 'live-sub-left' }, [subBadge, subRole, subSummary]), - subElapsed, - ]); - return { - el: rowEl, - refs: { rowEl, subBadge, subRole, subSummary, subElapsed }, - }; - } - - function createMultiLiveTaskCard() { - const dotIcon = createSvgIcon('dot', { size: 11 }); - patchClasses(dotIcon, { 'is-pulsing': true }); - const dotWrap = h('span', { className: 'live-activity-dot' }, [dotIcon]); - const titleEl = h('strong', { className: 'live-task-title', text: t('live.currentSession') }); - const hereTagEl = h('span', { - className: 'wm-session-tag is-here', - hidden: true, - text: t('multi.hereTag'), - }); - const metricsEl = h('span', { - className: 'wm-task-metrics text-mono', - hidden: true, - text: '', - }); - const subToggleBtn = h('button', { - type: 'button', - className: 'live-sub-toggle', - hidden: true, - text: t('live.subToggleIdle', { total: 0, arrow: '▸' }), - }); - const elapsedEl = h('span', { - className: 'live-activity-elapsed text-mono', - text: '0s', - }); - - const headerEl = h('div', { className: 'live-task-header' }, [ - h('div', { className: 'live-task-title-wrap' }, [dotWrap, titleEl, hereTagEl]), - h('div', { className: 'live-task-header-right' }, [metricsEl, subToggleBtn, elapsedEl]), - ]); - - const mainBadge = h('span', { - className: 'agent-badge badge-main', - hidden: true, - text: t('fmt.mainBadge'), - }); - const mainPhase = h('strong', { className: 'live-activity-phase', text: t('live.thinking') }); - const mainProgress = h('span', { - className: 'live-activity-progress text-mono', - hidden: true, - text: '', - }); - const mainSep = h('span', { className: 'live-activity-sep', hidden: true, text: '·' }); - const mainDetail = h('span', { - className: 'live-activity-detail', - hidden: true, - text: '', - }); - - const mainRowEl = h('div', { className: 'live-task-main-row' }, [ - mainBadge, - mainPhase, - mainProgress, - mainSep, - mainDetail, - ]); - - const subListEl = h('div', { className: 'live-sub-list', hidden: true }); - const cardEl = h('div', { className: 'live-task-card' }, [headerEl, mainRowEl, subListEl]); - - return { - el: cardEl, - refs: { - cardEl, - dotIcon, - titleEl, - hereTagEl, - metricsEl, - subToggleBtn, - elapsedEl, - mainBadge, - mainPhase, - mainProgress, - mainSep, - mainDetail, - subListEl, - }, - }; - } - + // 左侧多会话实时看板浮层(受控复用 LiveActivityWidget,保持零硬编码与同一套计时器状态机) const multiPinBadge = h('span', { className: 'wm-pin-badge', hidden: true, @@ -19819,10 +20192,16 @@ function mountWindowOverlay() { multiEmptyTextEl, ]), ]); - const multiRunningListEl = h('div', { - className: 'live-activity-list', - hidden: true, - 'aria-live': 'polite', + const multiRunningWidget = LiveActivityWidget({ + defaultExpandRunningSubs: true, + showSessionExtras: true, + isVisibleFn: () => Boolean(multiOpen && !document.hidden && !disposed), + onSelectSession: inspectSessionInMonitor, + onLayoutChange: () => { + if (multiOpen) { + positionFloatingElements(); + } + }, }); const multiTitleTextEl = h('span', { text: t('multi.title') }); @@ -19856,7 +20235,7 @@ function mountWindowOverlay() { } }, }, - [multiHeaderEl, multiEmptyEl, multiRunningListEl] + [multiHeaderEl, multiEmptyEl, multiRunningWidget.el] ); // 完整四标签悬浮容器 @@ -20640,12 +21019,13 @@ function mountWindowOverlay() { patchAttr(multiPanelEl, 'hidden', !multiOpen); if (multiOpen) { renderCapsuleTelemetry(); + multiRunningWidget.refs.resumeTicker(); positionFloatingElements(); if (typeof requestAnimationFrame === 'function') { requestAnimationFrame(() => positionFloatingElements()); } } else { - pauseMultiLiveTicker(); + multiRunningWidget.refs.pauseTicker(); } } @@ -20720,18 +21100,10 @@ function mountWindowOverlay() { } function renderMultiRunningPanel(rawRunningList, runningCount, runningSubCount, hostRouteConversationId) { - if (manualSubExpandMap.size > 0) { - const runningIds = new Set(rawRunningList.map((item) => item.cascadeId)); - for (const id of manualSubExpandMap.keys()) { - if (!runningIds.has(id)) manualSubExpandMap.delete(id); - } + if (!multiOpen || document.hidden) { + multiRunningWidget.refs.pauseTicker(); + return; } - if (!multiOpen || document.hidden) return; - const localeKey = getEffectiveLocale(); - const hostRouteLower = String( - hostRouteConversationId || extractHostRouteCascadeId() || '' - ).toLowerCase(); - patchText( multiRunningMetaEl, runningCount > 0 @@ -20741,201 +21113,10 @@ function mountWindowOverlay() { : t('multi.allIdle') ); patchAttr(multiEmptyEl, 'hidden', runningCount > 0); - patchAttr(multiRunningListEl, 'hidden', runningCount === 0); - - if (runningCount === 0) { - stopMultiLiveTicker(); - patchKeyedList(multiRunningListEl, [], {}); - } else { - const activeTimerKeys = new Set(); - for (const item of rawRunningList) { - activeTimerKeys.add(`main:${item.cascadeId}`); - const subCount = Number(item.subagentCount || item.subagents?.length || 0); - const runSubs = Number(item.runningSubagentCount || 0); - const isExp = manualSubExpandMap.has(item.cascadeId) - ? manualSubExpandMap.get(item.cascadeId) - : runSubs > 0; - if (subCount > 0 && isExp) { - for (const sub of item.subagents || []) { - if (sub?.isRunning) { - activeTimerKeys.add(`sub:${sub.cascadeId}`); - } - } - } - } - - patchKeyedList(multiRunningListEl, rawRunningList, { - keyFn: (item) => item.cascadeId, - sigFn: (item) => { - const runSubs = Number(item.runningSubagentCount || 0); - const isExp = manualSubExpandMap.has(item.cascadeId) - ? manualSubExpandMap.get(item.cascadeId) - : runSubs > 0; - const isHere = - Boolean(hostRouteLower) && - String(item.cascadeId || '').toLowerCase() === hostRouteLower; - const subSig = (item.subagents || []) - .map( - (s) => - `${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}` - ) - .join('|'); - return `${localeKey}:${item.cascadeId}:${item.title}:${isHere}:${item.isMainRunning}:${item.subagentCount}:${runSubs}:${isExp}:${item.latestTokPerSec ?? ''}:${item.contextUsedPct ?? ''}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`; - }, - createRow: createMultiLiveTaskCard, - updateRow: (refs, item) => { - const act = item.mainActivity || { - phase: 'thinking', - label: t('live.thinking'), - detail: '', - stepProgress: '', - startedAtMs: item.lastModifiedMs || 0, - signature: `fallback:${item.lastModifiedMs || 0}`, - }; - const isWaiting = act.phase === 'waiting'; - const isCompacting = act.phase === 'compacting'; - patchClasses(refs.cardEl, { - 'is-waiting': isWaiting, - 'is-compacting': isCompacting, - }); - patchClasses(refs.dotIcon, { 'is-pulsing': true }); - - const convTitle = - item.title || item.cascadeId?.slice(0, 8) || t('live.currentSession'); - patchText(refs.titleEl, convTitle); - patchAttr(refs.titleEl, 'title', t('multi.inspectSessionTitle', { title: convTitle })); - refs.titleEl.onclick = (e) => { - e.stopPropagation(); - inspectSessionInMonitor(item.cascadeId); - }; - - const isHere = - Boolean(hostRouteLower) && - String(item.cascadeId || '').toLowerCase() === hostRouteLower; - patchText(refs.hereTagEl, t('multi.hereTag')); - patchAttr(refs.hereTagEl, 'hidden', !isHere); - - const metricParts = []; - if (Number.isFinite(item.latestTokPerSec) && item.latestTokPerSec > 0) { - metricParts.push( - `${item.latestTokPerSec >= 100 ? Math.round(item.latestTokPerSec) : item.latestTokPerSec.toFixed(1)} t/s` - ); - } - if (item.contextUsedPct != null && Number.isFinite(Number(item.contextUsedPct))) { - metricParts.push(`${Math.round(Number(item.contextUsedPct))}%`); - } - const metricsStr = metricParts.join(' · '); - patchAttr(refs.metricsEl, 'hidden', !metricsStr); - if (metricsStr) { - patchText(refs.metricsEl, metricsStr); - } - - const subCount = Number(item.subagentCount || item.subagents?.length || 0); - const runSubCount = Number(item.runningSubagentCount || 0); - const isExpanded = manualSubExpandMap.has(item.cascadeId) - ? manualSubExpandMap.get(item.cascadeId) - : runSubCount > 0; - patchText(refs.mainBadge, t('fmt.mainBadge')); - patchAttr(refs.mainBadge, 'hidden', subCount === 0); - patchAttr(refs.subToggleBtn, 'hidden', subCount === 0); - if (subCount > 0) { - const arrow = isExpanded ? '▾' : '▸'; - const toggleText = - runSubCount > 0 - ? t('live.subToggleRunning', { run: runSubCount, total: subCount, arrow }) - : t('live.subToggleIdle', { total: subCount, arrow }); - patchText(refs.subToggleBtn, toggleText); - patchClasses(refs.subToggleBtn, { 'is-expanded': isExpanded }); - refs.subToggleBtn.onclick = (e) => { - e.stopPropagation(); - manualSubExpandMap.set(item.cascadeId, !isExpanded); - renderCapsuleTelemetry(); - if (multiOpen) { - positionFloatingElements(); - } - }; - } - - const mainTimerKey = `main:${item.cascadeId}`; - activeTimerKeys.add(mainTimerKey); - bindMultiElapsedTimer( - mainTimerKey, - `${item.cascadeId}:${act.signature || act.label}`, - act.startedAtMs, - refs.elapsedEl - ); - - patchText(refs.mainPhase, act.label || t('live.thinking')); - const progText = act.stepProgress ? `[${act.stepProgress}]` : ''; - patchAttr(refs.mainProgress, 'hidden', !progText); - if (progText) { - patchText(refs.mainProgress, progText); - } - - const detailStr = act.detail || ''; - patchAttr(refs.mainSep, 'hidden', !detailStr); - patchAttr(refs.mainDetail, 'hidden', !detailStr); - patchText(refs.mainDetail, detailStr); - - const showSubs = subCount > 0 && isExpanded; - patchAttr(refs.subListEl, 'hidden', !showSubs); - if (showSubs) { - const subItems = item.subagents || []; - patchKeyedList(refs.subListEl, subItems, { - keyFn: (sub) => sub.cascadeId, - sigFn: (sub) => - `${localeKey}:${sub.cascadeId}:${sub.role}:${sub.isRunning}:${sub.stepCount}:${sub.liveActivity?.signature || ''}:${sub.isRunning ? multiTimersMap.has(`sub:${sub.cascadeId}`) : true}`, - createRow: createMultiLiveSubRow, - updateRow: (subRefs, sub) => { - const subAct = sub.liveActivity || { - phase: sub.isRunning ? 'thinking' : 'done', - label: sub.isRunning ? t('live.thinking') : t('live.done'), - detail: '', - stepProgress: '', - startedAtMs: sub.lastModifiedMs || 0, - }; - patchClasses(subRefs.rowEl, { 'is-done': !sub.isRunning }); - const subBadgeCls = getAgentBadgeClass(sub.index || 1, false); - patchAttr(subRefs.subBadge, 'class', `agent-badge ${subBadgeCls}`); - patchText(subRefs.subBadge, formatAgentBadgeText(sub)); - patchText(subRefs.subRole, sub.role || sub.shortLabel || t('fmt.subAgent')); - - const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : ''; - const summaryText = sub.isRunning - ? `${subAct.label || t('live.running')}${subProg}${subAct.detail ? ` · ${subAct.detail}` : ''}` - : t('live.doneWithSteps', { steps: sub.stepCount || 0 }); - patchText(subRefs.subSummary, summaryText); - - const subTimerKey = `sub:${sub.cascadeId}`; - if (sub.isRunning) { - activeTimerKeys.add(subTimerKey); - bindMultiElapsedTimer( - subTimerKey, - `${sub.cascadeId}:${subAct.signature || subAct.label}`, - subAct.startedAtMs || sub.lastModifiedMs, - subRefs.subElapsed - ); - } else { - multiTimersMap.delete(subTimerKey); - patchText( - subRefs.subElapsed, - t('header.convMetaSteps', { count: sub.stepCount || 0 }) - ); - } - }, - }); - } - }, - }); - - for (const k of [...multiTimersMap.keys()]) { - if (!activeTimerKeys.has(k)) { - multiTimersMap.delete(k); - } - } - ensureMultiLiveTicker(); - tickMultiElapsedDisplay(); - } + multiRunningWidget.refs.update({ + items: rawRunningList, + hostRouteConversationId, + }); } function renderHoverWidgets() { @@ -20978,7 +21159,7 @@ function mountWindowOverlay() { patchClasses(multiBtn, { 'is-running': false, 'is-waiting': false }); patchText(multiLabel, t('capsule.multiZero')); patchText(multiRunningMetaEl, t('multi.loading')); - stopMultiLiveTicker(); + multiRunningWidget.refs.stopLiveTicker(); applyCapsuleSlots(slotKeys, { hasTelemetry: false }); return; @@ -20991,138 +21172,36 @@ function mountWindowOverlay() { uiSt.selectedAgentScope, uiSt.ctxInspectorAgentId ); - const activeConv = telemetry.activeConversation || {}; - const overviewActive = overviewScopedConv || activeConv; - const ctx = ctxAgent?.context || overviewActive.context || activeConv.context || {}; - const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000); - const totalTokens = Number(ctx.totalTokens || 0); - const usedPct = - limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0; - const dashOffset = +( - RING_CIRCUMFERENCE * - (1 - Math.max(0, Math.min(100, usedPct)) / 100) - ).toFixed(2); - // --- 4a. 同步左侧多会话实时状态胶囊与浮层看板 --- - const rawRunningList = - Array.isArray(telemetry.runningConversations) && telemetry.runningConversations.length > 0 - ? telemetry.runningConversations - : activeConv.isRunning || aggregated?.isRunning - ? [ - { - cascadeId: activeConv.cascadeId || 'current', - title: activeConv.title || t('live.currentSession'), - 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, - latestTokPerSec: overviewActive.latestTokPerSec ?? null, - contextUsedPct: usedPct, - subagents: (agents || []) - .filter((a) => !a.isMain) - .map((s, idx) => ({ - cascadeId: s.cascadeId || s.agentId, - index: s.index || idx + 1, - badgeText: s.badgeText || t('fmt.subBadge', { index: idx + 1 }), - shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`, - role: s.role || `${t('fmt.subAgent')} #${idx + 1}`, - isRunning: Boolean(s.isRunning), - stepCount: Number(s.stepCount || 0), - lastModifiedMs: s.lastModifiedMs || 0, - liveActivity: s.liveActivity || { - phase: s.isRunning ? 'thinking' : 'done', - label: s.isRunning ? t('live.thinking') : t('live.done'), - detail: '', - stepProgress: '', - startedAtMs: s.lastModifiedMs || 0, - signature: `${s.agentId}:${s.stepCount || 0}`, - }, - })), - }, - ] - : []; - - const runningCount = rawRunningList.length; - const runningSubCount = rawRunningList.reduce( - (acc, item) => acc + Number(item.runningSubagentCount || 0), - 0 - ); - const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting'); + const overviewActive = overviewScopedConv || telemetry.activeConversation || {}; + const slotCtx = buildCapsuleSlotContext(telemetry, { + scopedConv: capsuleScopedConv, + overviewConv: overviewActive, + ctxAgent, + aggregated, + }); + const { rawRunningList, runningCount, runningSubCount, hasWaiting, multiBtnText } = + resolveMultiSessionCapsuleState(telemetry, { + agents, + aggregated, + latestTokPerSec: overviewActive.latestTokPerSec ?? null, + contextUsedPct: slotCtx.usedPct, + }); patchClasses(multiBtn, { 'is-running': runningCount > 0 && !hasWaiting, 'is-waiting': runningCount > 0 && hasWaiting, }); - const multiBtnText = - runningCount > 0 - ? runningSubCount > 0 - ? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount }) - : t('capsule.multiRunning', { count: runningCount }) - : t('capsule.multiZero'); patchText(multiLabel, multiBtnText); - renderMultiRunningPanel(rawRunningList, runningCount, runningSubCount, telSt.hostRouteConversationId); + renderMultiRunningPanel( + rawRunningList, + runningCount, + runningSubCount, + telSt.hostRouteConversationId + ); - // --- 4b. 同步右侧 1..5 动态槽位胶囊与组件化悬停浮层 --- - const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning); - const capActive = capsuleScopedConv || aggregated || activeConv || {}; - const tps = - capsuleScopedConv?.latestTokPerSec ?? - aggregated?.latestTokPerSec ?? - activeConv.latestTokPerSec ?? - null; - const avgTps = - capsuleScopedConv?.avgTokPerSec ?? - aggregated?.avgTokPerSec ?? - activeConv.avgTokPerSec ?? - null; - const ttft = - capsuleScopedConv?.latestTtftSec ?? - aggregated?.latestTtftSec ?? - activeConv.latestTtftSec ?? - null; - const capsuleStepCost = - capsuleScopedConv?.latestStepCostUsd ?? - aggregated?.latestStepCostUsd ?? - activeConv.latestStepCostUsd ?? - null; - const sessionCost = - capsuleScopedConv?.sessionCostUsd ?? - aggregated?.sessionCostUsd ?? - activeConv.sessionCostUsd ?? - null; - const cacheHitPct = - Number(capActive.stepCount || 0) > 0 - ? capActive.latestCacheHitPct ?? capActive.sessionCacheHitPct ?? null - : null; - const latestPromptTokens = capActive.latestPromptTokens ?? null; - const capInTok = Math.max(0, Number(capActive.inputTokens || 0)); - const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0)); - const capOutTok = Math.max(0, Number(capActive.outputTokens || 0)); - const sessionTokens = - Number(capActive.stepCount || 0) > 0 || - capActive.totalTokens != null || - capInTok + capCacheTok + capOutTok > 0 - ? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok)) - : null; - - patchClasses(capsuleBtn, { 'is-running': isRunning }); - applyCapsuleSlots(slotKeys, { - hasTelemetry: true, - usedPct, - dashOffset, - isRunning, - tps, - avgTps, - ttft, - stepCost: capsuleStepCost, - sessionCost, - cacheHitPct, - latestPromptTokens, - sessionTokens, - quotas: telemetry.quotas, - }); + patchClasses(capsuleBtn, { 'is-running': slotCtx.isRunning }); + applyCapsuleSlots(slotKeys, slotCtx); const updateMode = normalizeClientUpdateMode( telemetry.settings?.pluginUpdateMode, @@ -21299,7 +21378,7 @@ function mountWindowOverlay() { const onVisibilityChange = () => { if (document.hidden) { uiStore.setState({ monitorVisible: false }); - pauseMultiLiveTicker(); + multiRunningWidget.refs.pauseTicker(); hasPointerCoords = false; if (tooltipOpen) { setTooltipOpen(false); @@ -21492,7 +21571,7 @@ function mountWindowOverlay() { clearTimeout(multiLeaveTimer); multiLeaveTimer = null; } - stopMultiLiveTicker(); + multiRunningWidget.refs.stopLiveTicker(); if (dockRafId && typeof cancelAnimationFrame === 'function') { cancelAnimationFrame(dockRafId); dockRafId = 0; diff --git a/sidecars/panel/backend/cli-sqlite-reader.mjs b/sidecars/panel/backend/cli-sqlite-reader.mjs index 67b8385..4fe2a74 100644 --- a/sidecars/panel/backend/cli-sqlite-reader.mjs +++ b/sidecars/panel/backend/cli-sqlite-reader.mjs @@ -10,194 +10,38 @@ * 及运行态末尾步骤,O(1) 跳过大体积工具输出页),完整保留耗时、TTFT、轮次导轨与 10 通道上下文构成。 */ -import { existsSync, readFileSync, statSync } from 'node:fs'; +import { existsSync, readFileSync } from 'node:fs'; import { basename, join } from 'node:path'; import { parseIsoMs } from '../trajectory-metrics.mjs'; import { ANNOTATION_DIRS, PRODUCT_DATA_ROOTS, localSummaryMemo } from './config.mjs'; +import { + SQLITE_IN_CHUNK_SIZE, + computeSqliteWalSig, + getNodeSqliteDatabaseSync, + hasBuiltinNodeSqlite, + normalizeSqliteIsoTime, + withReadOnlySqliteDb, +} from './sqlite-client.mjs'; +import { + decodeProtoDurationSlice, + decodeProtoMapStringEntry, + decodeProtoTimestampSlice, + readProtoString, + readProtoVarint, + readSubEnd, + skipProtoField, + toUint8Array, + unescapePbtxtString, +} from './proto-wire.mjs'; + +export { + computeSqliteWalSig, + getNodeSqliteDatabaseSync, + hasBuiltinNodeSqlite, + withReadOnlySqliteDb, +}; const UUID_FILE_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; -const SQLITE_IN_CHUNK_SIZE = 400; -const utf8Decoder = typeof TextDecoder === 'function' ? new TextDecoder('utf-8') : null; - -let sqliteResolved = false; -let sqliteDatabaseSyncCtor = null; - -/** - * 惰性获取 Node 内置 `node:sqlite` 的 `DatabaseSync` 构造器(兼容测试沙箱注入的 `globalThis.DatabaseSync`)。 - * 首次加载时静默过滤 Node 22 的实验特性告警;当前运行时不支持时返回 `null`。 - * - * @returns {Function | null} - */ -export function getNodeSqliteDatabaseSync() { - if (typeof globalThis.DatabaseSync === 'function') { - return globalThis.DatabaseSync; - } - if (sqliteResolved) return sqliteDatabaseSyncCtor; - sqliteResolved = true; - if (typeof process === 'undefined' || typeof process.getBuiltinModule !== 'function') { - return null; - } - const origEmitWarning = process.emitWarning; - try { - if (typeof origEmitWarning === 'function') { - process.emitWarning = function filteredSqliteWarning(warning, ...rest) { - const msg = typeof warning === 'string' ? warning : String(warning?.message || ''); - if (/SQLite is an experimental feature/i.test(msg)) return; - return origEmitWarning.call(this, warning, ...rest); - }; - } - const mod = process.getBuiltinModule('node:sqlite'); - sqliteDatabaseSyncCtor = typeof mod?.DatabaseSync === 'function' ? mod.DatabaseSync : null; - } catch { - sqliteDatabaseSyncCtor = null; - } finally { - if (typeof origEmitWarning === 'function') { - process.emitWarning = origEmitWarning; - } - } - return sqliteDatabaseSyncCtor; -} - -/** - * 当前运行时是否具备内置 `node:sqlite` 读取能力。 - * - * @returns {boolean} - */ -export function hasBuiltinNodeSqlite() { - return Boolean(getNodeSqliteDatabaseSync()); -} - -/** - * 计算 SQLite 主库与 `.db-wal` 预写日志的复合签名(忽略易抖动的 `-shm` 共享内存头),精准感知未 checkpoint 的实时写入。 - * - * @param {string} dbPath - * @returns {{ exists: boolean, mtimeMs: number, sig: string }} - */ -export function computeSqliteWalSig(dbPath) { - if (!dbPath || typeof dbPath !== 'string' || !existsSync(dbPath)) { - return { exists: false, mtimeMs: 0, sig: '' }; - } - let dbStat = null; - try { - dbStat = statSync(dbPath); - } catch { - return { exists: false, mtimeMs: 0, sig: '' }; - } - if (!dbStat) return { exists: false, mtimeMs: 0, sig: '' }; - - let walStat = null; - const walPath = `${dbPath}-wal`; - if (existsSync(walPath)) { - try { - walStat = statSync(walPath); - } catch { - walStat = null; - } - } - const dbMtimeMs = Number(dbStat.mtimeMs || 0); - const dbSize = Number(dbStat.size || 0); - const walMtimeMs = Number(walStat?.mtimeMs || 0); - const walSize = Number(walStat?.size || 0); - return { - exists: true, - mtimeMs: Math.max(dbMtimeMs, walMtimeMs), - sig: `${Math.floor(dbMtimeMs)}:${dbSize}|${Math.floor(walMtimeMs)}:${walSize}`, - }; -} - -function isSqliteBusyError(err) { - const msg = String(err?.message || err?.code || ''); - return /SQLITE_BUSY|database is locked/i.test(msg); -} - -/** - * 以只读模式打开 SQLite 数据库执行查询并在 `finally` 中立即关闭连接,避免长连接阻塞宿主 WAL checkpoint。 - * 遇到瞬时锁竞争(`SQLITE_BUSY`)时自动重试 1 次。 - */ -export function withReadOnlySqliteDb(dbPath, queryFn) { - const DatabaseSync = getNodeSqliteDatabaseSync(); - if (!DatabaseSync) return null; - for (let attempt = 0; attempt < 2; attempt++) { - let db = null; - try { - db = new DatabaseSync(dbPath, { readOnly: true }); - try { - db.exec('PRAGMA busy_timeout = 1000;'); - } catch { - // 兼容最小测试桩 - } - return queryFn(db); - } catch (err) { - if (attempt === 0 && isSqliteBusyError(err)) { - continue; - } - throw err; - } finally { - if (db) { - try { - db.close(); - } catch { - // 忽略关闭异常 - } - } - } - } - return null; -} - -/** - * 解码 Protobuf Text Format (`prototext`) 字符串字面量,兼容 UTF-8 原文与 `\ddd` / `\xHH` 字节转义。 - * - * @param {string} raw - * @returns {string} - */ -function unescapePbtxtString(raw) { - if (typeof raw !== 'string' || !raw) return ''; - if (!raw.includes('\\')) return raw; - const bytes = []; - for (let i = 0; i < raw.length; i++) { - const ch = raw[i]; - if (ch !== '\\' || i + 1 >= raw.length) { - const encoded = Buffer.from(ch, 'utf8'); - for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]); - continue; - } - const next = raw[++i]; - if (next >= '0' && next <= '7') { - let oct = next; - if (i + 1 < raw.length && raw[i + 1] >= '0' && raw[i + 1] <= '7') oct += raw[++i]; - if (i + 1 < raw.length && raw[i + 1] >= '0' && raw[i + 1] <= '7') oct += raw[++i]; - bytes.push(parseInt(oct, 8) & 0xff); - } else if ((next === 'x' || next === 'X') && i + 2 < raw.length) { - const hex = raw.slice(i + 1, i + 3); - if (/^[0-9a-fA-F]{2}$/.test(hex)) { - bytes.push(parseInt(hex, 16)); - i += 2; - } else { - bytes.push(next.charCodeAt(0)); - } - } else if (next === 'u' && i + 4 < raw.length) { - const uHex = raw.slice(i + 1, i + 5); - if (/^[0-9a-fA-F]{4}$/.test(uHex)) { - const encoded = Buffer.from(String.fromCharCode(parseInt(uHex, 16)), 'utf8'); - for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]); - i += 4; - } else { - bytes.push(next.charCodeAt(0)); - } - } else if (next === 'n') { - bytes.push(0x0a); - } else if (next === 'r') { - bytes.push(0x0d); - } else if (next === 't') { - bytes.push(0x09); - } else { - const encoded = Buffer.from(next, 'utf8'); - for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]); - } - } - return Buffer.from(bytes).toString('utf8'); -} /** * 从 `annotations/.pbtxt` 文本内容中提取顶层 `title` 字段。 @@ -243,12 +87,6 @@ export function readAnnotationTitleForCascade(cascadeId, annotationDirs = ANNOTA return ''; } -function normalizeSqliteIsoTime(value) { - const raw = String(value || '').trim(); - if (!raw || raw.startsWith('0001-01-01') || raw.startsWith('1970-01-01 00:00:00')) return ''; - return raw.replace(/^(\d{4}-\d{2}-\d{2})\s+/, '$1T').replace(/\+00:00$/, 'Z'); -} - // --------------------------------------------------------------------------- // 零依赖轻量 Protobuf Wire 解码器(按需提取指标字段,O(1) 跳过大体积载荷) // --------------------------------------------------------------------------- @@ -372,133 +210,6 @@ const PROTO_CHAT_MSG_SOURCES = Object.freeze({ 6: 'CHAT_MESSAGE_SOURCE_CONTEXT', }); -function toUint8Array(raw) { - if (!raw) return null; - if (raw instanceof Uint8Array) return raw; - if (ArrayBuffer.isView(raw)) { - return new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength); - } - if (raw instanceof ArrayBuffer) { - return new Uint8Array(raw); - } - return null; -} - -function decodeUtf8Slice(buf, start, end) { - if (start >= end) return ''; - if (utf8Decoder) { - return utf8Decoder.decode(buf.subarray(start, end)); - } - return Buffer.from(buf.buffer, buf.byteOffset + start, end - start).toString('utf8'); -} - -function readProtoVarint(buf, state, limit = buf.length) { - if (state.off >= limit) return 0n; - const b0 = buf[state.off]; - if (b0 < 0x80) { - state.off += 1; - return BigInt(b0); - } - let result = 0n; - let shift = 0n; - for (let i = 0; i < 10 && state.off < limit; i++) { - const byte = buf[state.off++]; - result |= BigInt(byte & 0x7f) << shift; - if ((byte & 0x80) === 0) { - return BigInt.asUintN(64, result); - } - shift += 7n; - } - while (state.off < limit && (buf[state.off++] & 0x80) !== 0) { - // 安全排空超长 varint 延续字节 - } - return BigInt.asUintN(64, result); -} - -function readSubEnd(buf, state, limit = buf.length) { - const len = Number(BigInt.asUintN(32, readProtoVarint(buf, state, limit))); - return Math.min(limit, state.off + len); -} - -function readProtoString(buf, state, limit = buf.length) { - const end = readSubEnd(buf, state, limit); - const str = decodeUtf8Slice(buf, state.off, end); - state.off = end; - return str; -} - -function skipProtoField(buf, state, wireType, limit = buf.length) { - if (wireType === 0) { - readProtoVarint(buf, state, limit); - } else if (wireType === 1) { - state.off = Math.min(limit, state.off + 8); - } else if (wireType === 2) { - state.off = readSubEnd(buf, state, limit); - } else if (wireType === 5) { - state.off = Math.min(limit, state.off + 4); - } else if (wireType === 3) { - while (state.off < limit) { - const innerTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, limit))); - const innerWt = innerTag & 7; - if (innerWt === 4) break; - skipProtoField(buf, state, innerWt, limit); - } - } else if (wireType !== 4) { - state.off = limit; - } -} - -function decodeProtoTimestampSlice(buf, state, end) { - let seconds = 0n; - let nanos = 0n; - 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 === 0) { - seconds = BigInt.asIntN(64, readProtoVarint(buf, state, end)); - } else if (fn === 2 && wt === 0) { - nanos = BigInt.asIntN(32, readProtoVarint(buf, state, end)); - } else { - skipProtoField(buf, state, wt, end); - } - } - state.off = end; - if (seconds <= 0n || seconds > 253402300799n) return ''; - const baseIso = new Date(Number(seconds) * 1000).toISOString().slice(0, 19); - if (nanos > 0n && nanos < 1_000_000_000n) { - const frac = String(nanos).padStart(9, '0').replace(/0+$/, ''); - return frac ? `${baseIso}.${frac}Z` : `${baseIso}Z`; - } - return `${baseIso}Z`; -} - -function decodeProtoDurationSlice(buf, state, end) { - let seconds = 0n; - let nanos = 0n; - 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 === 0) { - seconds = BigInt.asIntN(64, readProtoVarint(buf, state, end)); - } else if (fn === 2 && wt === 0) { - nanos = BigInt.asIntN(32, readProtoVarint(buf, state, end)); - } else { - skipProtoField(buf, state, wt, end); - } - } - state.off = end; - const totalNs = seconds * 1_000_000_000n + nanos; - if (totalNs < 0n) return ''; - if (totalNs === 0n) return '0s'; - const wholeSec = totalNs / 1_000_000_000n; - const remNs = Number(totalNs % 1_000_000_000n); - if (remNs === 0) return `${wholeSec}s`; - const frac = String(remNs).padStart(9, '0').replace(/0+$/, ''); - return `${wholeSec}.${frac}s`; -} - function decodeProtoModelEnumInt(val) { const n = Math.trunc(Number(val)); if (!Number.isFinite(n) || n <= 0) return ''; @@ -518,25 +229,6 @@ function decodeProtoStepStatusEnum(val) { return PROTO_STEP_STATUSES[n] || 'CORTEX_STEP_STATUS_DONE'; } -function decodeProtoMapStringEntry(buf, state, end) { - let key = ''; - let val = ''; - 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) { - key = readProtoString(buf, state, end); - } else if (fn === 2 && wt === 2) { - val = readProtoString(buf, state, end); - } else { - skipProtoField(buf, state, wt, end); - } - } - state.off = end; - return [key, val]; -} - function decodeProtoSubagentSpecSlice(buf, state, end) { let typeName = ''; let role = ''; diff --git a/sidecars/panel/backend/proto-wire.mjs b/sidecars/panel/backend/proto-wire.mjs new file mode 100644 index 0000000..ca6c225 --- /dev/null +++ b/sidecars/panel/backend/proto-wire.mjs @@ -0,0 +1,210 @@ +/** + * @fileoverview 零外部依赖的二进制 Protobuf Wire 跳读游标与 `prototext` 字符串反转义原语 (`proto-wire.mjs`)。 + * + * 核心能力: + * 1. 无需引入 `protobufjs`,以 `O(1)` 游标位移跳过大体积定长/变长/Group 载荷; + * 2. 基于 `BigInt` 无损解码 64-bit Varint、`google.protobuf.Timestamp` 纳秒级时间戳与 `Duration`; + * 3. 按原始 UTF-8 字节流无损反转义 `prototext` 的 `\ddd` 八进制、`\xHH` 十六进制与 `\uXXXX` 多字节字符。 + */ + +const protoUtf8Decoder = typeof TextDecoder === 'function' ? new TextDecoder('utf-8') : null; + +/** + * 解码 Protobuf Text Format (`prototext`) 字符串字面量,兼容 UTF-8 原文与 `\ddd` / `\xHH` 字节转义。 + * + * @param {string} raw + * @returns {string} + */ +export function unescapePbtxtString(raw) { + if (typeof raw !== 'string' || !raw) return ''; + if (!raw.includes('\\')) return raw; + const bytes = []; + for (let i = 0; i < raw.length; i++) { + const ch = raw[i]; + if (ch !== '\\' || i + 1 >= raw.length) { + const encoded = Buffer.from(ch, 'utf8'); + for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]); + continue; + } + const next = raw[++i]; + if (next >= '0' && next <= '7') { + let oct = next; + if (i + 1 < raw.length && raw[i + 1] >= '0' && raw[i + 1] <= '7') oct += raw[++i]; + if (i + 1 < raw.length && raw[i + 1] >= '0' && raw[i + 1] <= '7') oct += raw[++i]; + bytes.push(parseInt(oct, 8) & 0xff); + } else if ((next === 'x' || next === 'X') && i + 2 < raw.length) { + const hex = raw.slice(i + 1, i + 3); + if (/^[0-9a-fA-F]{2}$/.test(hex)) { + bytes.push(parseInt(hex, 16)); + i += 2; + } else { + bytes.push(next.charCodeAt(0)); + } + } else if (next === 'u' && i + 4 < raw.length) { + const uHex = raw.slice(i + 1, i + 5); + if (/^[0-9a-fA-F]{4}$/.test(uHex)) { + const encoded = Buffer.from(String.fromCharCode(parseInt(uHex, 16)), 'utf8'); + for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]); + i += 4; + } else { + bytes.push(next.charCodeAt(0)); + } + } else if (next === 'n') { + bytes.push(0x0a); + } else if (next === 'r') { + bytes.push(0x0d); + } else if (next === 't') { + bytes.push(0x09); + } else { + const encoded = Buffer.from(next, 'utf8'); + for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]); + } + } + return Buffer.from(bytes).toString('utf8'); +} + +export function toUint8Array(raw) { + if (!raw) return null; + if (raw instanceof Uint8Array) return raw; + if (ArrayBuffer.isView(raw)) { + return new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength); + } + if (raw instanceof ArrayBuffer) { + return new Uint8Array(raw); + } + return null; +} + +export function decodeUtf8Slice(buf, start, end) { + if (start >= end) return ''; + if (protoUtf8Decoder) { + return protoUtf8Decoder.decode(buf.subarray(start, end)); + } + return Buffer.from(buf.buffer, buf.byteOffset + start, end - start).toString('utf8'); +} + +export function readProtoVarint(buf, state, limit = buf.length) { + if (state.off >= limit) return 0n; + const b0 = buf[state.off]; + if (b0 < 0x80) { + state.off += 1; + return BigInt(b0); + } + let result = 0n; + let shift = 0n; + for (let i = 0; i < 10 && state.off < limit; i++) { + const byte = buf[state.off++]; + result |= BigInt(byte & 0x7f) << shift; + if ((byte & 0x80) === 0) { + return BigInt.asUintN(64, result); + } + shift += 7n; + } + while (state.off < limit && (buf[state.off++] & 0x80) !== 0) { + // 安全排空超长 varint 延续字节 + } + return BigInt.asUintN(64, result); +} + +export function readSubEnd(buf, state, limit = buf.length) { + const len = Number(BigInt.asUintN(32, readProtoVarint(buf, state, limit))); + return Math.min(limit, state.off + len); +} + +export function readProtoString(buf, state, limit = buf.length) { + const end = readSubEnd(buf, state, limit); + const str = decodeUtf8Slice(buf, state.off, end); + state.off = end; + return str; +} + +export function skipProtoField(buf, state, wireType, limit = buf.length) { + if (wireType === 0) { + readProtoVarint(buf, state, limit); + } else if (wireType === 1) { + state.off = Math.min(limit, state.off + 8); + } else if (wireType === 2) { + state.off = readSubEnd(buf, state, limit); + } else if (wireType === 5) { + state.off = Math.min(limit, state.off + 4); + } else if (wireType === 3) { + while (state.off < limit) { + const innerTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, limit))); + const innerWt = innerTag & 7; + if (innerWt === 4) break; + skipProtoField(buf, state, innerWt, limit); + } + } else if (wireType !== 4) { + state.off = limit; + } +} + +export function decodeProtoTimestampSlice(buf, state, end) { + let seconds = 0n; + let nanos = 0n; + 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 === 0) { + seconds = BigInt.asIntN(64, readProtoVarint(buf, state, end)); + } else if (fn === 2 && wt === 0) { + nanos = BigInt.asIntN(32, readProtoVarint(buf, state, end)); + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + if (seconds <= 0n || seconds > 253402300799n) return ''; + const baseIso = new Date(Number(seconds) * 1000).toISOString().slice(0, 19); + if (nanos > 0n && nanos < 1_000_000_000n) { + const frac = String(nanos).padStart(9, '0').replace(/0+$/, ''); + return frac ? `${baseIso}.${frac}Z` : `${baseIso}Z`; + } + return `${baseIso}Z`; +} + +export function decodeProtoDurationSlice(buf, state, end) { + let seconds = 0n; + let nanos = 0n; + 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 === 0) { + seconds = BigInt.asIntN(64, readProtoVarint(buf, state, end)); + } else if (fn === 2 && wt === 0) { + nanos = BigInt.asIntN(32, readProtoVarint(buf, state, end)); + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + const totalNs = seconds * 1_000_000_000n + nanos; + if (totalNs < 0n) return ''; + if (totalNs === 0n) return '0s'; + const wholeSec = totalNs / 1_000_000_000n; + const remNs = Number(totalNs % 1_000_000_000n); + if (remNs === 0) return `${wholeSec}s`; + const frac = String(remNs).padStart(9, '0').replace(/0+$/, ''); + return `${wholeSec}.${frac}s`; +} + +export function decodeProtoMapStringEntry(buf, state, end) { + let key = ''; + let val = ''; + 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) { + key = readProtoString(buf, state, end); + } else if (fn === 2 && wt === 2) { + val = readProtoString(buf, state, end); + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + return [key, val]; +} diff --git a/sidecars/panel/backend/sqlite-client.mjs b/sidecars/panel/backend/sqlite-client.mjs new file mode 100644 index 0000000..03da145 --- /dev/null +++ b/sidecars/panel/backend/sqlite-client.mjs @@ -0,0 +1,155 @@ +/** + * @fileoverview 零业务依赖的本地 SQLite + WAL 非阻塞只读短连接原语 (`sqlite-client.mjs`)。 + * + * 核心能力: + * 1. 惰性加载 Node 22.5+ 内置 `node:sqlite`,自动静默实验特性告警,避免污染 CLI / MCP `stdio`; + * 2. 组合主库 `.db` 与 `.db-wal` 的 `mtime + size` 生成复合签名(忽略易抖动的 `-shm` 共享内存头),精准感知未 checkpoint 的实时写入; + * 3. 采用短连接 + `PRAGMA busy_timeout = 1000` + `SQLITE_BUSY` 瞬时锁重试并在 `finally` 中立即释放句柄,绝不阻塞宿主 WAL checkpoint。 + */ + +import { existsSync, statSync } from 'node:fs'; + +export const SQLITE_IN_CHUNK_SIZE = 400; + +let sqliteResolved = false; +let sqliteDatabaseSyncCtor = null; + +/** + * 惰性获取 Node 内置 `node:sqlite` 的 `DatabaseSync` 构造器(兼容测试沙箱注入的 `globalThis.DatabaseSync`)。 + * 首次加载时静默过滤 Node 22 的实验特性告警;当前运行时不支持时返回 `null`。 + * + * @returns {Function | null} + */ +export function getNodeSqliteDatabaseSync() { + if (typeof globalThis.DatabaseSync === 'function') { + return globalThis.DatabaseSync; + } + if (sqliteResolved) return sqliteDatabaseSyncCtor; + sqliteResolved = true; + if (typeof process === 'undefined' || typeof process.getBuiltinModule !== 'function') { + return null; + } + const origEmitWarning = process.emitWarning; + try { + if (typeof origEmitWarning === 'function') { + process.emitWarning = function filteredSqliteWarning(warning, ...rest) { + const msg = typeof warning === 'string' ? warning : String(warning?.message || ''); + if (/SQLite is an experimental feature/i.test(msg)) return; + return origEmitWarning.call(this, warning, ...rest); + }; + } + const mod = process.getBuiltinModule('node:sqlite'); + sqliteDatabaseSyncCtor = typeof mod?.DatabaseSync === 'function' ? mod.DatabaseSync : null; + } catch { + sqliteDatabaseSyncCtor = null; + } finally { + if (typeof origEmitWarning === 'function') { + process.emitWarning = origEmitWarning; + } + } + return sqliteDatabaseSyncCtor; +} + +/** + * 当前运行时是否具备内置 `node:sqlite` 读取能力。 + * + * @returns {boolean} + */ +export function hasBuiltinNodeSqlite() { + return Boolean(getNodeSqliteDatabaseSync()); +} + +/** + * 计算 SQLite 主库与 `.db-wal` 预写日志的复合签名(忽略易抖动的 `-shm` 共享内存头),精准感知未 checkpoint 的实时写入。 + * + * @param {string} dbPath + * @returns {{ exists: boolean, mtimeMs: number, sig: string }} + */ +export function computeSqliteWalSig(dbPath) { + if (!dbPath || typeof dbPath !== 'string' || !existsSync(dbPath)) { + return { exists: false, mtimeMs: 0, sig: '' }; + } + let dbStat = null; + try { + dbStat = statSync(dbPath); + } catch { + return { exists: false, mtimeMs: 0, sig: '' }; + } + if (!dbStat) return { exists: false, mtimeMs: 0, sig: '' }; + + let walStat = null; + const walPath = `${dbPath}-wal`; + if (existsSync(walPath)) { + try { + walStat = statSync(walPath); + } catch { + walStat = null; + } + } + const dbMtimeMs = Number(dbStat.mtimeMs || 0); + const dbSize = Number(dbStat.size || 0); + const walMtimeMs = Number(walStat?.mtimeMs || 0); + const walSize = Number(walStat?.size || 0); + return { + exists: true, + mtimeMs: Math.max(dbMtimeMs, walMtimeMs), + sig: `${Math.floor(dbMtimeMs)}:${dbSize}|${Math.floor(walMtimeMs)}:${walSize}`, + }; +} + +export function isSqliteBusyError(err) { + const msg = String(err?.message || err?.code || ''); + return /SQLITE_BUSY|database is locked/i.test(msg); +} + +/** + * 以只读模式打开 SQLite 数据库执行查询并在 `finally` 中立即关闭连接,避免长连接阻塞宿主 WAL checkpoint。 + * 遇到瞬时锁竞争(`SQLITE_BUSY`)时自动重试 1 次。 + * + * @template T + * @param {string} dbPath + * @param {(db: any) => T} queryFn + * @returns {T | null} + */ +export function withReadOnlySqliteDb(dbPath, queryFn) { + const DatabaseSync = getNodeSqliteDatabaseSync(); + if (!DatabaseSync) return null; + for (let attempt = 0; attempt < 2; attempt++) { + let db = null; + try { + db = new DatabaseSync(dbPath, { readOnly: true }); + try { + db.exec('PRAGMA busy_timeout = 1000;'); + } catch { + // 兼容最小测试桩 + } + return queryFn(db); + } catch (err) { + if (attempt === 0 && isSqliteBusyError(err)) { + continue; + } + throw err; + } finally { + if (db) { + try { + db.close(); + } catch { + // 忽略关闭异常 + } + } + } + } + return null; +} + +/** + * 归一化 SQLite `TEXT` 时间列(如 `'2026-11-18 08:12:00+00:00'` -> ISO-8601),剔除零值哨兵时间。 + * + * @param {unknown} value + * @returns {string} + */ +export function normalizeSqliteIsoTime(value) { + const raw = String(value || '').trim(); + if (!raw || raw.startsWith('0001-01-01') || raw.startsWith('1970-01-01 00:00:00')) return ''; + return raw.replace(/^(\d{4}-\d{2}-\d{2})\s+/, '$1T').replace(/\+00:00$/, 'Z'); +} diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index 4af3e36..937a34e 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -190,6 +190,10 @@ function enrichActiveConversationSteps( return { ...serializedStep, responseModel: st.responseModel || '', + hasKnownModel: Boolean(mInfo.modelId && mInfo.modelId !== 'unknown'), + baseModelUpstream: annotatedUpstreamModel, + baseModelLabel: mInfo.label, + baseModelShort: mInfo.shortName, modelUpstream, modelLabel: st.isCompactionStep ? `${mInfo.label} [自动压缩]` : mInfo.label, modelShort: st.isCompactionStep ? `${mInfo.shortName}·压缩` : mInfo.shortName, @@ -210,6 +214,7 @@ function enrichActiveConversationSteps( // 关联每轮用户提问摘要与最新轮次标识,供步骤表极简导轨与气泡展示 let maxTurnIndex = 0; const promptByTurn = new Map(); + const mediaByTurn = new Map(); for (const st of enrichedActiveSteps) { const tIdx = st.turnIndex; if (!Number.isInteger(tIdx) || tIdx <= 0) continue; @@ -217,6 +222,13 @@ function enrichActiveConversationSteps( if (st.turnPrompt && (st.isTurnStart || !promptByTurn.has(tIdx))) { promptByTurn.set(tIdx, st.turnPrompt); } + if (st.isTurnStart || !mediaByTurn.has(tIdx)) { + mediaByTurn.set(tIdx, { + cleanPrompt: st.turnPromptClean ?? '', + hasMedia: Boolean(st.turnHasMedia), + mediaOnly: Boolean(st.turnMediaOnly), + }); + } } for (const st of enrichedActiveSteps) { const tIdx = st.turnIndex; @@ -225,11 +237,18 @@ function enrichActiveConversationSteps( st.isTurnStart = false; st.isLatestTurn = false; st.turnPrompt = ''; + st.turnPromptClean = ''; + st.turnHasMedia = false; + st.turnMediaOnly = false; continue; } + const turnMedia = mediaByTurn.get(tIdx); st.isTurnStart = Boolean(st.isTurnStart); st.isLatestTurn = tIdx === maxTurnIndex; st.turnPrompt = promptByTurn.get(tIdx) || ''; + st.turnPromptClean = turnMedia?.cleanPrompt || ''; + st.turnHasMedia = Boolean(turnMedia?.hasMedia); + st.turnMediaOnly = Boolean(turnMedia?.mediaOnly); } const latestEnriched = @@ -544,12 +563,15 @@ function prepareAgentSteps(rawSteps, resolveStepModel, upstream, agentFields, re /** * 构建单个代理(主代理或子代理)的标准遥测单元对象。 */ -function buildAgentUnitTelemetry({ +export function buildAgentUnitTelemetry({ agentId, cascadeId, isMain, isSideQuestion = false, sideIndex = 0, + agentKind = isMain ? 'main' : isSideQuestion ? 'side_question' : 'subagent', + agentOrdinal = isMain ? 0 : isSideQuestion ? sideIndex : 0, + customRole = '', index, shortLabel, badgeText, @@ -572,6 +594,9 @@ function buildAgentUnitTelemetry({ { agentId, agentCascadeId: cascadeId, + agentKind, + agentOrdinal, + agentCustomRole: customRole, agentLabel, agentBadge: badgeText, agentRole: role, @@ -599,6 +624,9 @@ function buildAgentUnitTelemetry({ agentId, cascadeId, isMain, + agentKind, + agentOrdinal, + customRole, ...(isSideQuestion ? { isSideQuestion: true, sideIndex } : {}), index, shortLabel, @@ -631,6 +659,9 @@ function buildAgentUnitTelemetry({ : 0, latestCacheHitPct: ctxRes.latestCacheHitPct, sessionCacheHitPct: ctxRes.sessionCacheHitPct, + hasKnownModel: Boolean(enrichedRes.latestEnriched?.hasKnownModel), + activeBaseModelShort: enrichedRes.latestEnriched?.baseModelShort || '', + activeBaseModelLabel: enrichedRes.latestEnriched?.baseModelLabel || '', activeModelShort: enrichedRes.latestEnriched?.modelShort || '模型未知', activeModelLabel: enrichedRes.latestEnriched?.modelLabel || '模型未知', activeModelUpstream: @@ -814,6 +845,9 @@ export async function buildTelemetryPayloadInternal( subSpec?.role || subSum.agentScriptName || subEntry?.agentScriptName || subSpec?.typeName || ''; const subIndex = idx + 1; let sideIndex = 0; + let agentKind = 'subagent'; + let agentOrdinal = 0; + let customRole = ''; let shortLabel = ''; let badgeText = ''; let roleLabel = ''; @@ -821,6 +855,8 @@ export async function buildTelemetryPayloadInternal( let agentLabel = ''; if (isSideQ) { sideIndex = ++sideQuestionCount; + agentKind = 'side_question'; + agentOrdinal = sideIndex; shortLabel = `旁路提问 #${sideIndex}`; badgeText = `旁${sideIndex}`; const cleanSideRole = @@ -830,11 +866,15 @@ export async function buildTelemetryPayloadInternal( rawRole !== 'side_question' ? rawRole : ''; + customRole = cleanSideRole; roleLabel = cleanSideRole || '旁路提问'; typeName = 'side_question'; agentLabel = cleanSideRole ? `${shortLabel} · ${cleanSideRole}` : shortLabel; } else { const subOrd = ++normalSubCount; + agentKind = 'subagent'; + agentOrdinal = subOrd; + customRole = rawRole && rawRole !== '子代理' && rawRole !== 'Subagent' ? rawRole : ''; shortLabel = `子代理 #${subOrd}`; badgeText = `子${subOrd}`; roleLabel = rawRole || '子代理'; @@ -848,6 +888,9 @@ export async function buildTelemetryPayloadInternal( isMain: false, isSideQuestion: isSideQ, sideIndex, + agentKind, + agentOrdinal, + customRole, index: subIndex, shortLabel, badgeText, @@ -897,6 +940,9 @@ export async function buildTelemetryPayloadInternal( turnIndex: tIdx, startMs: mSt.createdAtMs || 0, prompt: mSt.turnPrompt || '', + cleanPrompt: mSt.turnPromptClean ?? '', + hasMedia: Boolean(mSt.turnHasMedia), + mediaOnly: Boolean(mSt.turnMediaOnly), }); } } @@ -923,6 +969,9 @@ export async function buildTelemetryPayloadInternal( st.rootTurnIndex = matched.turnIndex; st.isRootLatestTurn = matched.turnIndex === maxRootTurn; st.rootTurnPrompt = matched.prompt || ''; + st.rootTurnPromptClean = matched.cleanPrompt ?? ''; + st.rootTurnHasMedia = Boolean(matched.hasMedia); + st.rootTurnMediaOnly = Boolean(matched.mediaOnly); if (!seenRootStarts.has(matched.turnIndex)) { seenRootStarts.add(matched.turnIndex); st.isRootTurnStart = true; @@ -1004,6 +1053,8 @@ export async function buildTelemetryPayloadInternal( ? { ...activeActivityAgent.liveActivity, agentId: activeActivityAgent.agentId, + agentKind: activeActivityAgent.agentKind || (activeActivityAgent.isMain ? 'main' : activeActivityAgent.isSideQuestion ? 'side_question' : 'subagent'), + agentOrdinal: activeActivityAgent.agentOrdinal || 0, agentBadge: activeActivityAgent.badgeText, agentShortLabel: activeActivityAgent.shortLabel, agentRole: activeActivityAgent.role, @@ -1020,12 +1071,16 @@ export async function buildTelemetryPayloadInternal( agentId: 'all', cascadeId: activeCascadeId, isMain: false, + agentKind: 'all', + agentOrdinal: 0, index: -1, shortLabel: '全部汇总', badgeText: '全部', role: aggregatedRoleLabel, typeName: 'all', activeAgentId: activeMainlineAgent.agentId, + activeAgentKind: activeMainlineAgent.agentKind || (activeMainlineAgent.isMain ? 'main' : activeMainlineAgent.isSideQuestion ? 'side_question' : 'subagent'), + activeAgentOrdinal: activeMainlineAgent.agentOrdinal || 0, activeAgentShortLabel: activeMainlineAgent.shortLabel, activeAgentBadge: activeMainlineAgent.badgeText, activeAgentRole: activeMainlineAgent.role, @@ -1049,6 +1104,9 @@ export async function buildTelemetryPayloadInternal( latestPromptTokens: latestMetricAgent.latestPromptTokens ?? 0, latestCacheHitPct: latestMetricAgent.latestCacheHitPct, sessionCacheHitPct: combinedSessionCacheHitPct, + hasKnownModel: Boolean(latestMetricAgent.hasKnownModel), + activeBaseModelShort: latestMetricAgent.activeBaseModelShort || '', + activeBaseModelLabel: latestMetricAgent.activeBaseModelLabel || '', activeModelShort: latestMetricAgent.activeModelShort, activeModelLabel: latestMetricAgent.activeModelLabel, activeModelUpstream: latestMetricAgent.activeModelUpstream, @@ -1369,11 +1427,16 @@ export async function buildTelemetryPayloadInternal( ''; const subIndex = idx + 1; let sideIndex = 0; + let agentKind = 'subagent'; + let agentOrdinal = 0; + let customRole = ''; let badgeText = ''; let shortLabel = ''; let role = ''; if (isSideQ) { sideIndex = ++runSideIdx; + agentKind = 'side_question'; + agentOrdinal = sideIndex; badgeText = `旁${sideIndex}`; shortLabel = `旁路提问 #${sideIndex}`; const cleanSide = @@ -1383,9 +1446,13 @@ export async function buildTelemetryPayloadInternal( rawRole !== 'side_question' ? rawRole : ''; + customRole = cleanSide; role = cleanSide || shortLabel; } else { const nOrd = ++runNormalSubIdx; + agentKind = 'subagent'; + agentOrdinal = nOrd; + customRole = rawRole && rawRole !== '子代理' && rawRole !== 'Subagent' ? rawRole : ''; badgeText = `子${nOrd}`; shortLabel = `子代理 #${nOrd}`; role = rawRole || shortLabel; @@ -1397,6 +1464,9 @@ export async function buildTelemetryPayloadInternal( ? subSum.liveActivity || extractLiveActivity([], true, subModMs) : { phase: 'done', + actionKey: 'done', + waitingApproval: false, + detailKey: '', label: '已完成', detail: '', stepProgress: '', @@ -1406,6 +1476,9 @@ export async function buildTelemetryPayloadInternal( return { cascadeId: subCid, index: subIndex, + agentKind, + agentOrdinal, + customRole, ...(isSideQ ? { isSideQuestion: true, sideIndex } : {}), badgeText, shortLabel, @@ -1426,14 +1499,18 @@ export async function buildTelemetryPayloadInternal( const runningSubCount = subItems.filter((s) => s.isRunning).length; if ( isMainRunning && - (mainLiveAct?.toolName === 'invoke_subagent' || mainLiveAct?.label === '调用子代理') && + (mainLiveAct?.toolName === 'invoke_subagent' || mainLiveAct?.actionKey === 'invoke_subagent') && runningSubCount === 0 ) { const pendingIndex = subItems.length + 1; - const pendingRole = mainLiveAct.detail || '子代理'; + 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, @@ -1444,6 +1521,9 @@ export async function buildTelemetryPayloadInternal( lastModifiedMs: rootFallbackMs, liveActivity: { phase: 'thinking', + actionKey: 'starting', + waitingApproval: false, + detailKey: '', label: '启动中', detail: '', stepProgress: '', @@ -1459,8 +1539,11 @@ export async function buildTelemetryPayloadInternal( (runningSubList.length > 0 ? { phase: 'waiting', + actionKey: 'waiting_subagent', + waitingApproval: false, + detailKey: '', label: '等待子代理', - detail: runningSubList.map((s) => s.role).join(', '), + detail: runningSubList.map((s) => s.customRole || s.role).join(', '), stepProgress: '', startedAtMs: runningSubList[0]?.liveActivity?.startedAtMs || rootFallbackMs, signature: `wait-subs:${runningSubList.length}:${runningSubList[0]?.cascadeId || ''}`, @@ -1570,6 +1653,9 @@ export async function buildTelemetryPayloadInternal( : 0, latestCacheHitPct, sessionCacheHitPct, + hasKnownModel: Boolean(latestEnriched?.hasKnownModel), + activeBaseModelShort: latestEnriched?.baseModelShort || '', + activeBaseModelLabel: latestEnriched?.baseModelLabel || '', activeModelShort: latestEnriched?.modelShort || '模型未知', activeModelLabel: latestEnriched?.modelLabel || '模型未知', activeModelUpstream: diff --git a/sidecars/panel/cli-statusline.mjs b/sidecars/panel/cli-statusline.mjs index 7f598da..d2a8908 100644 --- a/sidecars/panel/cli-statusline.mjs +++ b/sidecars/panel/cli-statusline.mjs @@ -27,8 +27,8 @@ import { import { readLocalSqliteTrajectory, readLocalSummaryIndex, - withReadOnlySqliteDb, } from './backend/cli-sqlite-reader.mjs'; +import { withReadOnlySqliteDb } from './backend/sqlite-client.mjs'; import { ensureCliStatusLineConfigured, formatCliStatusLineCapsule, diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index b62cdfc..2397aaa 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 148ee27..359a92e 100644 --- a/sidecars/panel/src/components/charts/SessionStepCharts.js +++ b/sidecars/panel/src/components/charts/SessionStepCharts.js @@ -10,6 +10,7 @@ import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js'; import { + formatAgentBadgeText, formatTokens, formatTokensPrecise, formatUsd, @@ -17,6 +18,7 @@ import { speedReasonText, } from '../../core/formatters.js'; import { SVG_NS } from '../../icons/SvgIcon.js'; +import { getEffectiveLocale, t } from '../../i18n/index.js'; let sessionChartUid = 0; @@ -38,16 +40,16 @@ export const MODEL_COLOR_VARS = Object.freeze([ * @returns {string} */ export function getStepModelGroupKey(step) { - if (!step || typeof step !== 'object') return '模型未知'; - const rawLabel = String(step.modelLabel || step.label || '') + if (!step || typeof step !== 'object') return t('fmt.unknownModel'); + const rawLabel = String(step.baseModelLabel || step.modelLabel || step.label || '') .replace(/\s*\[自动压缩\]\s*$/u, '') .replace(/\s*\((?:Max|XHigh|High|Medium|Low|Thinking|Extra Low|Tiered)\)\s*$/i, '') .trim(); if (rawLabel) return rawLabel; - const rawShort = String(step.modelShort || step.shortName || '') - .replace(/·压缩\s*$/u, '') + const rawShort = String(step.baseModelShort || step.modelShort || step.shortName || '') + .replace(/·(?:压缩|Compact)\s*$/iu, '') .trim(); - return rawShort || '模型未知'; + return rawShort || t('fmt.unknownModel'); } /** @@ -574,7 +576,17 @@ function computeStepTickIndices(count) { function formatStepAxisTag(st, showAgentPrefix) { const num = `#${Number(st?.stepIndex ?? 0)}`; if (!showAgentPrefix) return num; - const badge = st?.agentBadge || (st?.isSubagent ? '子' : '主'); + const badge = 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, + }); return `${badge}${num}`; } @@ -709,7 +721,7 @@ export function createSessionLineChart() { const emptyHintEl = h('div', { className: 'sstep-empty-hint text-muted', - text: '当前范围暂无可绘制的调用步骤', + text: t('chart.step.empty'), hidden: true, }); @@ -787,7 +799,10 @@ export function createSessionLineChart() { patchText(tipHeadLeft, pt.stepTag); patchText(tipHeadRight, pt.modelText); - patchText(tipMainLeft, pt.valid ? formatChartMetricValue(currentMetric, pt.value) : '未纳入'); + patchText( + tipMainLeft, + pt.valid ? formatChartMetricValue(currentMetric, pt.value) : t('chart.step.excluded') + ); patchText(tipMainRight, pt.secondaryRight || ''); patchAttr(tipSub, 'hidden', !pt.subDetail); if (pt.subDetail) { @@ -914,6 +929,7 @@ export function createSessionLineChart() { ? steps : steps.filter((st) => st && targetKeySet.has(getStepModelGroupKey(st))); + patchText(emptyHintEl, t('chart.step.empty')); if (!matchedSteps.length) { currentPoints = []; lastSig = 'empty'; @@ -927,7 +943,7 @@ export function createSessionLineChart() { patchAttr(peakPill, 'hidden', true); patchAttr(emptyHintEl, 'hidden', false); clearHover(); - return { summaryBadge: '0 步' }; + return { summaryBadge: t('chart.step.zeroSteps') }; } const modelColorMap = new Map(); @@ -941,7 +957,7 @@ export function createSessionLineChart() { const disp = resolveModelDisplayInfo({ modelLabel: gk, label: gk }, displaySettings, { fallback: gk, }); - modelLabelByGroup.set(gk, disp.text.replace(/·压缩\s*$/u, '').trim() || gk); + modelLabelByGroup.set(gk, disp.baseText || disp.text || gk); } } for (const st of matchedSteps) { @@ -954,7 +970,7 @@ export function createSessionLineChart() { } if (!modelLabelByGroup.has(gk)) { const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk }); - modelLabelByGroup.set(gk, disp.text.replace(/·压缩\s*$/u, '').trim() || gk); + modelLabelByGroup.set(gk, disp.baseText || disp.text || gk); } } @@ -1014,41 +1030,62 @@ export function createSessionLineChart() { if (metric === 'totalTokens') { value = isMultiCompare ? modelCumTok : runningTokens; - secondaryRight = `本步 +${formatTokens(stepTotalTok)}`; - subDetail = `入 ${formatTokens(inTok)} · 缓 ${formatTokens(cacheTok)} · 出 ${formatTokens(outTok)}`; + secondaryRight = t('chart.step.stepAdd', { tokens: formatTokens(stepTotalTok) }); + subDetail = t('chart.step.ioSplit', { + inTok: formatTokens(inTok), + cacheTok: formatTokens(cacheTok), + outTok: formatTokens(outTok), + }); } else if (metric === 'context') { value = ctxTok; if (hasPrevCtx) { const sign = ctxDelta >= 0 ? '+' : '-'; secondaryRight = `${sign}${formatTokens(Math.abs(ctxDelta))}`; } else { - secondaryRight = `缓存 ${Number(st.cacheHitPct ?? 0)}%`; + secondaryRight = t('chart.step.cacheShort', { pct: Number(st.cacheHitPct ?? 0) }); } subDetail = st.isCompactionStep - ? '上下文自动压缩检查点' - : `缓存命中 ${Number(st.cacheHitPct ?? 0)}% · 输出 +${formatTokens(outTok)}`; + ? t('chart.step.compactionCheckpoint') + : t('chart.step.cacheHitOut', { + pct: Number(st.cacheHitPct ?? 0), + outTok: formatTokens(outTok), + }); } else if (metric === 'tps') { valid = !st.isCompactionStep && Number.isFinite(st.tokPerSec) && st.tokPerSec > 0; value = valid ? Number(st.tokPerSec) : 0; - secondaryRight = Number.isFinite(st.ttftSec) ? `首字 ${st.ttftSec.toFixed(1)}s` : ''; + secondaryRight = Number.isFinite(st.ttftSec) + ? t('chart.step.ttftShort', { sec: st.ttftSec.toFixed(1) }) + : ''; subDetail = valid - ? `输出 ${formatTokens(outTok)} · 上下文 ${formatTokens(ctxTok)}` - : speedReasonText(st.selectedSpeedReason) || (st.isCompactionStep ? '上下文压缩步' : '无测速样本'); + ? t('chart.step.outAndCtx', { + outTok: formatTokens(outTok), + ctxTok: formatTokens(ctxTok), + }) + : speedReasonText(st.selectedSpeedReason) || + (st.isCompactionStep ? t('chart.step.compactionStep') : t('chart.step.noSpeedSample')); } 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` : ''; subDetail = valid - ? `上下文 ${formatTokens(ctxTok)} · 缓存 ${Number(st.cacheHitPct ?? 0)}%` + ? t('chart.step.ctxAndCache', { + ctxTok: formatTokens(ctxTok), + pct: Number(st.cacheHitPct ?? 0), + }) : st.isCompactionStep - ? '上下文压缩步' - : '无首字计时样本'; + ? t('chart.step.compactionStep') + : t('chart.step.noTtftSample'); } else if (metric === 'cost') { valid = stepCost !== null; value = valid ? stepCost : 0; const shownCumCost = isMultiCompare ? modelCumCost : runningCost; - secondaryRight = `累计 ${formatUsd(shownCumCost, { precise: shownCumCost > 0 && shownCumCost < 0.1 })}`; - subDetail = `缓存 ${Number(st.cacheHitPct ?? 0)}% · 本步 ${formatTokens(stepTotalTok)}`; + secondaryRight = t('chart.step.cumCost', { + cost: formatUsd(shownCumCost, { precise: shownCumCost > 0 && shownCumCost < 0.1 }), + }); + subDetail = t('chart.step.cacheAndStepTok', { + pct: Number(st.cacheHitPct ?? 0), + tokens: formatTokens(stepTotalTok), + }); } if (valid) { @@ -1108,11 +1145,12 @@ export function createSessionLineChart() { const validPoints = points.filter((p) => p.valid); patchAttr(emptyHintEl, 'hidden', validPoints.length > 0); + const locale = getEffectiveLocale(); const colorSig = Array.from(modelColorMap.entries()) .map(([k, v]) => `${k}=${v}`) .join(','); const sig = - `${viewW}|${metric}|${showAgentPrefix}|${isMultiCompare ? 'multi' : 'single'}:${targetKeys.join(',')}|${colorSig}|` + + `${locale}|${viewW}|${metric}|${showAgentPrefix}|${isMultiCompare ? 'multi' : 'single'}:${targetKeys.join(',')}|${colorSig}|` + points .map((p) => `${p.stepTag}:${p.modelText}:${p.valid ? p.value.toFixed(4) : 'x'}`) .join('|'); @@ -1247,12 +1285,12 @@ export function createSessionLineChart() { patchStyleVar(swatch, '--swatch-bg', colorVar); const stStat = perModelStats.get(gk); const baseLabel = modelLabelByGroup.get(gk) || gk; - let summarySuffix = '无样本'; + let summarySuffix = t('chart.step.noSamples'); if (stStat && stStat.count > 0) { if (metric === 'totalTokens') { summarySuffix = formatTokens(stStat.cumTok); } else if (metric === 'context') { - summarySuffix = `峰 ${formatTokens(stStat.max)}`; + summarySuffix = t('chart.step.peakShort', { val: formatTokens(stStat.max) }); } else if (metric === 'tps' || metric === 'ttft') { summarySuffix = formatChartMetricCompact(metric, stStat.sum / stStat.count); } else if (metric === 'cost') { @@ -1290,7 +1328,10 @@ export function createSessionLineChart() { const peakPt = points[peakIdx]; patchText( peakPill, - `峰值 ${peakPt.stepTag} · ${formatChartMetricCompact(metric, peakPt.value)}` + t('chart.step.peakPill', { + tag: peakPt.stepTag, + val: formatChartMetricCompact(metric, peakPt.value), + }) ); patchStyleVar(peakPill, '--sstep-accent', isMultiCompare ? peakPt.dotColor : accentColor); const pctLeft = Math.max(14, Math.min(86, (peakPt.x / viewW) * 100)); @@ -1306,28 +1347,42 @@ export function createSessionLineChart() { showHoverAt(hoveredIdx); } - let summaryBadge = `${matchedSteps.length}步`; + let summaryBadge = t('chart.step.stepsCount', { count: matchedSteps.length }); const activeCompareCount = isMultiCompare ? targetKeys.length : 1; - const multiPrefix = isMultiCompare ? `${activeCompareCount} 模型 · ` : ''; + const multiPrefix = isMultiCompare + ? t('chart.step.multiPrefix', { count: activeCompareCount }) + : ''; if (metric === 'totalTokens') { - summaryBadge = `${multiPrefix}累计 ${formatTokens(runningTokens)}`; + summaryBadge = t('chart.step.sumTokens', { + prefix: multiPrefix, + tokens: formatTokens(runningTokens), + }); } else if (metric === 'context') { const lastCtx = points[points.length - 1]?.value || 0; summaryBadge = isMultiCompare - ? `${multiPrefix}峰值 ${formatTokens(maxVal)}` - : `当前 ${formatTokens(lastCtx)}`; + ? t('chart.step.peakTokens', { prefix: multiPrefix, tokens: formatTokens(maxVal) }) + : t('chart.step.currentCtx', { tokens: formatTokens(lastCtx) }); } else if (metric === 'tps') { summaryBadge = validCount > 0 - ? `${multiPrefix}均值 ${(validSum / validCount).toFixed(1)} tok/s` - : '暂无有效样本'; + ? t('chart.step.meanTps', { + prefix: multiPrefix, + val: (validSum / validCount).toFixed(1), + }) + : t('chart.step.noValidSamples'); } else if (metric === 'ttft') { summaryBadge = validCount > 0 - ? `${multiPrefix}均值 ${(validSum / validCount).toFixed(1)}s` - : '暂无有效样本'; + ? t('chart.step.meanSec', { + prefix: multiPrefix, + val: (validSum / validCount).toFixed(1), + }) + : t('chart.step.noValidSamples'); } else if (metric === 'cost') { - summaryBadge = `${multiPrefix}累计 ${formatUsd(runningCost, { precise: runningCost > 0 && runningCost < 0.1 })}`; + summaryBadge = t('chart.step.sumCost', { + prefix: multiPrefix, + cost: formatUsd(runningCost, { precise: runningCost > 0 && runningCost < 0.1 }), + }); } return { summaryBadge }; @@ -1418,7 +1473,7 @@ export function createModelFitChart() { const emptyHintEl = h('div', { className: 'sstep-empty-hint text-muted', - text: '该模型暂无有效拟合样本', + text: t('chart.fit.empty'), hidden: true, }); @@ -1433,14 +1488,16 @@ export function createModelFitChart() { tipSub, ]); - const fitMethodLabelEl = h('span', { text: 'LOESS 拟合' }); + const fitMethodLabelEl = h('span', { text: t('chart.fit.loess') }); + const olsLegendTextEl = h('span', { text: t('chart.fit.olsLinear') }); const olsLegendWrapEl = h('span', { className: 'sstep-fit-legend-ols' }, [ h('span', { className: 'sstep-fit-swatch is-ols' }), - h('span', { text: 'OLS 线性' }), + olsLegendTextEl, ]); + const obsLegendTextEl = h('span', { text: t('chart.fit.observed') }); const singleLegendEl = h('span', { className: 'sstep-fit-legend' }, [ h('span', { className: 'sstep-fit-swatch is-scatter' }), - h('span', { text: '观测值' }), + obsLegendTextEl, h('span', { className: 'sstep-fit-swatch is-curve' }), fitMethodLabelEl, h('span', { className: 'sstep-fit-swatch is-ci' }), @@ -1523,8 +1580,14 @@ export function createModelFitChart() { patchAttr(tooltipEl, 'hidden', false); patchText(tipHeadLeft, sp.stepTag); patchText(tipHeadRight, sp.modelText); - patchText(tipMainLeft, `拟合 ${formatChartMetricValue(currentMetric, sp.fitVal)}`); - patchText(tipMainRight, `观测 ${formatChartMetricValue(currentMetric, sp.rawVal)}`); + patchText( + tipMainLeft, + t('chart.fit.tipFit', { val: formatChartMetricValue(currentMetric, sp.fitVal) }) + ); + patchText( + tipMainRight, + t('chart.fit.tipObs', { val: formatChartMetricValue(currentMetric, sp.rawVal) }) + ); patchAttr(tipSub, 'hidden', false); if (sp.compareHint) { @@ -1538,7 +1601,10 @@ export function createModelFitChart() { const ctxTok = Math.max(0, Number(sp.st?.contextTokens || 0)); patchText( tipSub, - `上下文 ${formatTokens(ctxTok)} · 缓存 ${Number(sp.st?.cacheHitPct ?? 0)}%` + t('chart.step.ctxAndCache', { + ctxTok: formatTokens(ctxTok), + pct: Number(sp.st?.cacheHitPct ?? 0), + }) ); } @@ -1804,11 +1870,16 @@ export function createModelFitChart() { xVal: globalX, rawVal, stepTag: formatStepAxisTag(st, showAgentPrefix), - modelText: disp.text.replace(/·压缩\s*$/u, '').trim() || disp.text, + modelText: disp.baseText || disp.text, }); } } + const locale = getEffectiveLocale(); + patchText(emptyHintEl, t('chart.fit.empty')); + patchText(obsLegendTextEl, t('chart.fit.observed')); + patchText(olsLegendTextEl, t('chart.fit.olsLinear')); + if (fitCacheMetric !== metric) { fitCache.clear(); fitCacheMetric = metric; @@ -1832,9 +1903,10 @@ export function createModelFitChart() { patchAttr(singleLegendEl, 'hidden', false); patchAttr(multiLegendEl, 'hidden', true); patchAttr(emptyHintEl, 'hidden', false); + patchText(fitMethodLabelEl, t('chart.fit.loess')); patchText(fitStatsEl, 'n = 0'); clearHover(); - return { sampleCount: 0, summaryBadge: '0 样本' }; + return { sampleCount: 0, summaryBadge: t('chart.fit.zeroSamples') }; } patchAttr(emptyHintEl, 'hidden', true); @@ -1916,7 +1988,12 @@ export function createModelFitChart() { if (interp !== null) { peerParts.push(`${other.label} ${formatChartMetricCompact(metric, interp)}`); } else { - peerParts.push(`${other.label} 均 ${formatChartMetricCompact(metric, other.pubFit.mean)}`); + peerParts.push( + t('chart.fit.peerMean', { + label: other.label, + val: formatChartMetricCompact(metric, other.pubFit.mean), + }) + ); } } return { @@ -1929,7 +2006,10 @@ export function createModelFitChart() { ciHigh: s.pubFit.sampleCiHigh[i], ciHalf: s.pubFit.sampleCiHalf[i], seriesColor: s.colorVar, - compareHint: peerParts.length > 0 ? `同图对比:${peerParts.join(' · ')}` : '', + compareHint: + peerParts.length > 0 + ? t('chart.fit.peerCompare', { peers: peerParts.join(' · ') }) + : '', }; }); s.samples = sSamples; @@ -1939,7 +2019,7 @@ export function createModelFitChart() { currentSamples = combinedSamples; const sig = - `multi|${viewW}|${targetKeys.join(',')}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` + + `multi|${locale}|${viewW}|${targetKeys.join(',')}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` + seriesList .map( (s) => @@ -2053,7 +2133,7 @@ export function createModelFitChart() { fitStatsEl, seriesList.length <= 2 ? seriesList.map((s) => `R²=${s.pubFit.r2.toFixed(2)}`).join(' · ') - : `${seriesList.length} 条拟合线` + : t('chart.fit.curvesCount', { count: seriesList.length }) ); patchAttr(fitStatsEl, 'title', r2SummaryTitle); @@ -2065,7 +2145,10 @@ export function createModelFitChart() { return { sampleCount: combinedSamples.length, - summaryBadge: `${combinedSamples.length}步 · ${seriesList.length} 模型对比`, + summaryBadge: t('chart.fit.multiBadge', { + steps: combinedSamples.length, + models: seriesList.length, + }), }; } @@ -2080,7 +2163,10 @@ export function createModelFitChart() { const rawYs = filtered.map((d) => d.rawVal); const pubFit = reusePublicationFit(null, xs, rawYs, maxBound, false); - patchText(fitMethodLabelEl, pubFit.method === 'LOESS' ? 'LOESS 拟合' : 'OLS 回归'); + patchText( + fitMethodLabelEl, + pubFit.method === 'LOESS' ? t('chart.fit.loess') : t('chart.fit.olsReg') + ); patchAttr(olsLegendWrapEl, 'hidden', filtered.length < 6); let dataMin = Infinity; @@ -2133,7 +2219,7 @@ export function createModelFitChart() { currentSamples = samples; const sig = - `single|${viewW}|${targetKeys[0]}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` + + `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('|'); if (sig !== lastSig) { @@ -2209,7 +2295,10 @@ export function createModelFitChart() { } } - const summaryBadge = `${samples.length}步 · 均 ${formatChartMetricCompact(metric, pubFit.mean)}`; + const summaryBadge = t('chart.fit.singleBadge', { + steps: samples.length, + mean: formatChartMetricCompact(metric, pubFit.mean), + }); if (samples.length >= 2) { const rSign = pubFit.r >= 0 ? '+' : ''; const slopeSign = pubFit.slope >= 0 ? '+' : ''; @@ -2217,7 +2306,11 @@ export function createModelFitChart() { patchAttr( fitStatsEl, 'title', - `OLS: y = ${slopeSign}${pubFit.slope.toFixed(3)}x + ${pubFit.intercept.toFixed(2)} · 样本标准差 SD = ±${pubFit.sd.toFixed(2)}` + t('chart.fit.olsTitle', { + slope: `${slopeSign}${pubFit.slope.toFixed(3)}`, + intercept: pubFit.intercept.toFixed(2), + sd: pubFit.sd.toFixed(2), + }) ); } else { patchText(fitStatsEl, `n = ${samples.length}`); diff --git a/sidecars/panel/src/components/charts/TrendAreaChart.js b/sidecars/panel/src/components/charts/TrendAreaChart.js index b8b9aee..0acbfa2 100644 --- a/sidecars/panel/src/components/charts/TrendAreaChart.js +++ b/sidecars/panel/src/components/charts/TrendAreaChart.js @@ -9,6 +9,7 @@ import { h, patchAttr, patchClasses, 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'; /** 超过该自然日天数(> 90 天)时,趋势图切换为类 GitHub 每日小格子热力图 */ export const HEATMAP_DAYS_THRESHOLD = 90; @@ -176,7 +177,9 @@ function buildHeatmapMonthTicks(slots, firstDow, totalWeeks) { if (totalWeeks > 16 && c.col >= totalWeeks - 1) continue; if (ticks.length > 0 && c.col < nextAllowedCol) continue; const showYear = crossYear && (c.month === 1 || ticks.length === 0); - const text = showYear ? `${String(c.year).slice(-2)}年${c.month}月` : `${c.month}月`; + const text = showYear + ? t('chart.trend.hmMonthYear', { yy: String(c.year).slice(-2), month: c.month }) + : t('chart.trend.hmMonthOnly', { month: c.month }); ticks.push({ col: c.col, text }); nextAllowedCol = c.col + (showYear ? baseMinGap + 1 : baseMinGap); } @@ -311,26 +314,41 @@ export function createTrendAreaChart() { const plotStage = h('div', { className: 'trend-plot-stage' }, [peakPill, svg]); // 类 GitHub 每日小格子热力图容器(> 90 天模式) - const weekdayLabels = ['一', '', '三', '', '五', '', '日']; + const wdayMonEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdayMon') }); + const wdayWedEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdayWed') }); + const wdayFriEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdayFri') }); + const wdaySunEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdaySun') }); const hmWeekdaysEl = h('div', { className: 'trend-hm-weekdays', 'aria-hidden': 'true' }, [ h('span', { className: 'trend-hm-month-spacer' }), - ...weekdayLabels.map((txt) => h('span', { className: 'trend-hm-wday', text: txt })), + wdayMonEl, + h('span', { className: 'trend-hm-wday', text: '' }), + wdayWedEl, + h('span', { className: 'trend-hm-wday', text: '' }), + wdayFriEl, + h('span', { className: 'trend-hm-wday', text: '' }), + wdaySunEl, ]); const hmMonthsEl = h('div', { className: 'trend-hm-months' }); - const hmGridEl = h('div', { className: 'trend-hm-grid', role: 'grid', 'aria-label': '每日用量热力格子图' }); + const hmGridEl = h('div', { + className: 'trend-hm-grid', + role: 'grid', + 'aria-label': t('chart.trend.hmAria'), + }); const hmTrackEl = h('div', { className: 'trend-hm-track' }, [hmMonthsEl, hmGridEl]); const hmScrollEl = h('div', { className: 'trend-hm-scroll' }, [hmTrackEl]); const hmBodyEl = h('div', { className: 'trend-heatmap-body' }, [hmWeekdaysEl, hmScrollEl]); const hmSummaryEl = h('span', { className: 'trend-hm-summary text-mono', text: '' }); + const hmLessEl = h('span', { text: t('chart.trend.hmLess') }); + const hmMoreEl = h('span', { text: t('chart.trend.hmMore') }); const hmLegendEl = h('span', { className: 'trend-hm-legend', 'aria-hidden': 'true' }, [ - h('span', { text: '少' }), + hmLessEl, h('span', { className: 'trend-hm-swatch lv-0' }), h('span', { className: 'trend-hm-swatch lv-1' }), h('span', { className: 'trend-hm-swatch lv-2' }), h('span', { className: 'trend-hm-swatch lv-3' }), h('span', { className: 'trend-hm-swatch lv-4' }), - h('span', { text: '多' }), + hmMoreEl, ]); const hmFooterEl = h('div', { className: 'trend-hm-footer' }, [hmSummaryEl, hmLegendEl]); const heatmapStage = h('div', { className: 'trend-heatmap-stage', hidden: true }, [ @@ -359,7 +377,10 @@ export function createTrendAreaChart() { function populateTooltipContent(slot) { patchText(tipTimeEl, slot.fullLabel || slot.label || '--'); - patchText(tipCallsEl, `${Math.max(0, Math.floor(Number(slot.calls) || 0))} 次`); + patchText( + tipCallsEl, + t('cons.callsCount', { calls: Math.max(0, Math.floor(Number(slot.calls) || 0)) }) + ); const slotTok = safeSlotTokens(slot.tokens); patchText(tipTokensEl, `${formatTokensPrecise(slotTok)} tok`); const slotCost = Number.isFinite(Number(slot.costUsd)) ? Math.max(0, Number(slot.costUsd)) : 0; @@ -379,7 +400,11 @@ export function createTrendAreaChart() { if (hasSubBreakdown) { patchText( tipSubEl, - `入 ${formatTokensPrecise(safeSlotTokens(slot.inputTokens))} · 缓 ${formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens))} · 出 ${formatTokensPrecise(safeSlotTokens(slot.outputTokens))}` + t('chart.step.ioSplit', { + inTok: formatTokensPrecise(safeSlotTokens(slot.inputTokens)), + cacheTok: formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens)), + outTok: formatTokensPrecise(safeSlotTokens(slot.outputTokens)), + }) ); } } @@ -728,19 +753,28 @@ export function createTrendAreaChart() { const nonZeroVals = []; for (let i = 0; i < slots.length; i++) { - const t = safeSlotTokens(slots[i]?.tokens); - if (t > 0) { + const tokVal = safeSlotTokens(slots[i]?.tokens); + if (tokVal > 0) { activeDays++; - nonZeroVals.push(t); + nonZeroVals.push(tokVal); } - if (t >= maxTokens) { - maxTokens = t; + if (tokVal >= maxTokens) { + maxTokens = tokVal; peakIdx = i; } } + const locale = getEffectiveLocale(); + patchText(wdayMonEl, t('chart.trend.wdayMon')); + patchText(wdayWedEl, t('chart.trend.wdayWed')); + patchText(wdayFriEl, t('chart.trend.wdayFri')); + patchText(wdaySunEl, t('chart.trend.wdaySun')); + patchAttr(hmGridEl, 'aria-label', t('chart.trend.hmAria')); + patchText(hmLessEl, t('chart.trend.hmLess')); + patchText(hmMoreEl, t('chart.trend.hmMore')); + const sig = - `${useHeatmap ? 'hm' : `line:${viewW}`}|` + + `${locale}|${useHeatmap ? 'hm' : `line:${viewW}`}|` + slots .map( (s) => @@ -820,8 +854,13 @@ export function createTrendAreaChart() { const peakSlot = slots[peakIdx]; const summaryText = maxTokens > 0 && peakSlot?.label - ? `活跃 ${activeDays}/${slots.length} 天 · 峰值 ${peakSlot.label} · ${formatTokensPrecise(maxTokens)}` - : `活跃 0/${slots.length} 天`; + ? t('chart.trend.hmActivePeak', { + active: activeDays, + total: slots.length, + label: peakSlot.label, + tokens: formatTokensPrecise(maxTokens), + }) + : t('chart.trend.hmActiveZero', { total: slots.length }); patchText(hmSummaryEl, summaryText); if (hoveredIdx >= slots.length) { @@ -920,7 +959,10 @@ export function createTrendAreaChart() { const peakSlot = slots[peakIdx]; const peakText = maxTokens > 0 && peakSlot?.label - ? `峰值 ${peakSlot.label} · ${formatTokensPrecise(maxTokens)}` + ? t('chart.trend.peakPill', { + label: peakSlot.label, + tokens: formatTokensPrecise(maxTokens), + }) : formatTokensPrecise(maxTokens); patchText(peakPill, peakText); const pctLeft = Math.max(12, Math.min(88, (peakPt.x / viewW) * 100)); diff --git a/sidecars/panel/src/components/layout/WindowOverlayShell.js b/sidecars/panel/src/components/layout/WindowOverlayShell.js index aa56831..08a460a 100644 --- a/sidecars/panel/src/components/layout/WindowOverlayShell.js +++ b/sidecars/panel/src/components/layout/WindowOverlayShell.js @@ -25,25 +25,23 @@ import { isEventInside, patchAttr, patchClasses, - patchKeyedList, patchText, } from '../../core/domPatch.js'; -import { formatElapsedSec } from '../../core/formatters.js'; import { deliverCdpBridgeResponses, getWindowBridgeConfig } from '../../core/httpClient.js'; -import { getEffectiveLocale, i18nStore, setI18nLanguage, t } from '../../i18n/index.js'; +import { i18nStore, setI18nLanguage, t } from '../../i18n/index.js'; import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js'; import { - RING_CIRCUMFERENCE, + buildCapsuleSlotContext, createCapsuleSlotNode, + resolveMultiSessionCapsuleState, syncCapsuleSlotNodes, } from '../widgets/CapsuleBarWidget.js'; +import { LiveActivityWidget } from '../widgets/LiveActivityWidget.js'; import { createDynamicWidgetHost } from '../../registries/widgetRegistry.js'; import { DEFAULT_CLIENT_HOVER_MODULES, extractHostRouteCascadeId, fetchTelemetry, - formatAgentBadgeText, - getAgentBadgeClass, isMacHostPlatform, normalizeClientHoverModules, normalizeClientPopoverWidth, @@ -982,9 +980,6 @@ export function mountWindowOverlay() { let multiPinned = false; let hoverLeaveTimer = null; let multiLeaveTimer = null; - const manualSubExpandMap = new Map(); - const multiTimersMap = new Map(); - let multiLiveTickTimer = null; let hasPointerCoords = Boolean( carryOverPointer && Number.isFinite(carryOverPointer.x) && @@ -1082,52 +1077,6 @@ export function mountWindowOverlay() { }, 90); } - function bindMultiElapsedTimer(timerKey, sig, rawStartMs, targetEl) { - const now = Date.now(); - const prev = multiTimersMap.get(timerKey); - let startMs = prev?.startMs || 0; - if (!prev || prev.sig !== sig) { - const validRaw = Number(rawStartMs || 0); - startMs = validRaw > 0 && validRaw <= now + 2000 ? validRaw : now; - } else if (startMs <= 0 && Number(rawStartMs) > 0 && Number(rawStartMs) <= now + 2000) { - startMs = Number(rawStartMs); - } - multiTimersMap.set(timerKey, { sig, startMs, el: targetEl }); - const elapsedSec = Math.max(0, (now - startMs) / 1000); - patchText(targetEl, formatElapsedSec(elapsedSec)); - } - - function tickMultiElapsedDisplay() { - const now = Date.now(); - for (const entry of multiTimersMap.values()) { - if (!entry?.el) continue; - const elapsedSec = entry.startMs > 0 ? Math.max(0, (now - entry.startMs) / 1000) : 0; - patchText(entry.el, formatElapsedSec(elapsedSec)); - } - } - - function pauseMultiLiveTicker() { - if (multiLiveTickTimer) { - clearInterval(multiLiveTickTimer); - multiLiveTickTimer = null; - } - } - - function stopMultiLiveTicker() { - pauseMultiLiveTicker(); - multiTimersMap.clear(); - } - - function ensureMultiLiveTicker() { - if (multiTimersMap.size === 0) { - stopMultiLiveTicker(); - return; - } - if (!multiLiveTickTimer) { - multiLiveTickTimer = setInterval(tickMultiElapsedDisplay, 1000); - } - } - function inspectSessionInMonitor(cascadeId) { if (!cascadeId || cascadeId === 'current') return; uiStore.setState({ @@ -1424,105 +1373,7 @@ export function mountWindowOverlay() { [hoverUpdateBar, hoverWidgetsContainer] ); - // 左侧多会话实时看板浮层(活跃运行会话卡片 + 近期多窗口会话速览,全槽位预占、就地补丁更新) - function createMultiLiveSubRow() { - const subBadge = h('span', { - className: 'agent-badge badge-sub-1', - text: t('fmt.subBadge', { index: 1 }), - }); - const subRole = h('span', { className: 'live-sub-role', text: t('fmt.subAgent') }); - const subSummary = h('span', { className: 'live-sub-summary', text: '' }); - const subElapsed = h('span', { className: 'live-sub-elapsed text-mono', text: '0s' }); - const rowEl = h('div', { className: 'live-sub-row' }, [ - h('div', { className: 'live-sub-left' }, [subBadge, subRole, subSummary]), - subElapsed, - ]); - return { - el: rowEl, - refs: { rowEl, subBadge, subRole, subSummary, subElapsed }, - }; - } - - function createMultiLiveTaskCard() { - const dotIcon = createSvgIcon('dot', { size: 11 }); - patchClasses(dotIcon, { 'is-pulsing': true }); - const dotWrap = h('span', { className: 'live-activity-dot' }, [dotIcon]); - const titleEl = h('strong', { className: 'live-task-title', text: t('live.currentSession') }); - const hereTagEl = h('span', { - className: 'wm-session-tag is-here', - hidden: true, - text: t('multi.hereTag'), - }); - const metricsEl = h('span', { - className: 'wm-task-metrics text-mono', - hidden: true, - text: '', - }); - const subToggleBtn = h('button', { - type: 'button', - className: 'live-sub-toggle', - hidden: true, - text: t('live.subToggleIdle', { total: 0, arrow: '▸' }), - }); - const elapsedEl = h('span', { - className: 'live-activity-elapsed text-mono', - text: '0s', - }); - - const headerEl = h('div', { className: 'live-task-header' }, [ - h('div', { className: 'live-task-title-wrap' }, [dotWrap, titleEl, hereTagEl]), - h('div', { className: 'live-task-header-right' }, [metricsEl, subToggleBtn, elapsedEl]), - ]); - - const mainBadge = h('span', { - className: 'agent-badge badge-main', - hidden: true, - text: t('fmt.mainBadge'), - }); - const mainPhase = h('strong', { className: 'live-activity-phase', text: t('live.thinking') }); - const mainProgress = h('span', { - className: 'live-activity-progress text-mono', - hidden: true, - text: '', - }); - const mainSep = h('span', { className: 'live-activity-sep', hidden: true, text: '·' }); - const mainDetail = h('span', { - className: 'live-activity-detail', - hidden: true, - text: '', - }); - - const mainRowEl = h('div', { className: 'live-task-main-row' }, [ - mainBadge, - mainPhase, - mainProgress, - mainSep, - mainDetail, - ]); - - const subListEl = h('div', { className: 'live-sub-list', hidden: true }); - const cardEl = h('div', { className: 'live-task-card' }, [headerEl, mainRowEl, subListEl]); - - return { - el: cardEl, - refs: { - cardEl, - dotIcon, - titleEl, - hereTagEl, - metricsEl, - subToggleBtn, - elapsedEl, - mainBadge, - mainPhase, - mainProgress, - mainSep, - mainDetail, - subListEl, - }, - }; - } - + // 左侧多会话实时看板浮层(受控复用 LiveActivityWidget,保持零硬编码与同一套计时器状态机) const multiPinBadge = h('span', { className: 'wm-pin-badge', hidden: true, @@ -1539,10 +1390,16 @@ export function mountWindowOverlay() { multiEmptyTextEl, ]), ]); - const multiRunningListEl = h('div', { - className: 'live-activity-list', - hidden: true, - 'aria-live': 'polite', + const multiRunningWidget = LiveActivityWidget({ + defaultExpandRunningSubs: true, + showSessionExtras: true, + isVisibleFn: () => Boolean(multiOpen && !document.hidden && !disposed), + onSelectSession: inspectSessionInMonitor, + onLayoutChange: () => { + if (multiOpen) { + positionFloatingElements(); + } + }, }); const multiTitleTextEl = h('span', { text: t('multi.title') }); @@ -1576,7 +1433,7 @@ export function mountWindowOverlay() { } }, }, - [multiHeaderEl, multiEmptyEl, multiRunningListEl] + [multiHeaderEl, multiEmptyEl, multiRunningWidget.el] ); // 完整四标签悬浮容器 @@ -2360,12 +2217,13 @@ export function mountWindowOverlay() { patchAttr(multiPanelEl, 'hidden', !multiOpen); if (multiOpen) { renderCapsuleTelemetry(); + multiRunningWidget.refs.resumeTicker(); positionFloatingElements(); if (typeof requestAnimationFrame === 'function') { requestAnimationFrame(() => positionFloatingElements()); } } else { - pauseMultiLiveTicker(); + multiRunningWidget.refs.pauseTicker(); } } @@ -2440,18 +2298,10 @@ export function mountWindowOverlay() { } function renderMultiRunningPanel(rawRunningList, runningCount, runningSubCount, hostRouteConversationId) { - if (manualSubExpandMap.size > 0) { - const runningIds = new Set(rawRunningList.map((item) => item.cascadeId)); - for (const id of manualSubExpandMap.keys()) { - if (!runningIds.has(id)) manualSubExpandMap.delete(id); - } + if (!multiOpen || document.hidden) { + multiRunningWidget.refs.pauseTicker(); + return; } - if (!multiOpen || document.hidden) return; - const localeKey = getEffectiveLocale(); - const hostRouteLower = String( - hostRouteConversationId || extractHostRouteCascadeId() || '' - ).toLowerCase(); - patchText( multiRunningMetaEl, runningCount > 0 @@ -2461,201 +2311,10 @@ export function mountWindowOverlay() { : t('multi.allIdle') ); patchAttr(multiEmptyEl, 'hidden', runningCount > 0); - patchAttr(multiRunningListEl, 'hidden', runningCount === 0); - - if (runningCount === 0) { - stopMultiLiveTicker(); - patchKeyedList(multiRunningListEl, [], {}); - } else { - const activeTimerKeys = new Set(); - for (const item of rawRunningList) { - activeTimerKeys.add(`main:${item.cascadeId}`); - const subCount = Number(item.subagentCount || item.subagents?.length || 0); - const runSubs = Number(item.runningSubagentCount || 0); - const isExp = manualSubExpandMap.has(item.cascadeId) - ? manualSubExpandMap.get(item.cascadeId) - : runSubs > 0; - if (subCount > 0 && isExp) { - for (const sub of item.subagents || []) { - if (sub?.isRunning) { - activeTimerKeys.add(`sub:${sub.cascadeId}`); - } - } - } - } - - patchKeyedList(multiRunningListEl, rawRunningList, { - keyFn: (item) => item.cascadeId, - sigFn: (item) => { - const runSubs = Number(item.runningSubagentCount || 0); - const isExp = manualSubExpandMap.has(item.cascadeId) - ? manualSubExpandMap.get(item.cascadeId) - : runSubs > 0; - const isHere = - Boolean(hostRouteLower) && - String(item.cascadeId || '').toLowerCase() === hostRouteLower; - const subSig = (item.subagents || []) - .map( - (s) => - `${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}` - ) - .join('|'); - return `${localeKey}:${item.cascadeId}:${item.title}:${isHere}:${item.isMainRunning}:${item.subagentCount}:${runSubs}:${isExp}:${item.latestTokPerSec ?? ''}:${item.contextUsedPct ?? ''}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`; - }, - createRow: createMultiLiveTaskCard, - updateRow: (refs, item) => { - const act = item.mainActivity || { - phase: 'thinking', - label: t('live.thinking'), - detail: '', - stepProgress: '', - startedAtMs: item.lastModifiedMs || 0, - signature: `fallback:${item.lastModifiedMs || 0}`, - }; - const isWaiting = act.phase === 'waiting'; - const isCompacting = act.phase === 'compacting'; - patchClasses(refs.cardEl, { - 'is-waiting': isWaiting, - 'is-compacting': isCompacting, - }); - patchClasses(refs.dotIcon, { 'is-pulsing': true }); - - const convTitle = - item.title || item.cascadeId?.slice(0, 8) || t('live.currentSession'); - patchText(refs.titleEl, convTitle); - patchAttr(refs.titleEl, 'title', t('multi.inspectSessionTitle', { title: convTitle })); - refs.titleEl.onclick = (e) => { - e.stopPropagation(); - inspectSessionInMonitor(item.cascadeId); - }; - - const isHere = - Boolean(hostRouteLower) && - String(item.cascadeId || '').toLowerCase() === hostRouteLower; - patchText(refs.hereTagEl, t('multi.hereTag')); - patchAttr(refs.hereTagEl, 'hidden', !isHere); - - const metricParts = []; - if (Number.isFinite(item.latestTokPerSec) && item.latestTokPerSec > 0) { - metricParts.push( - `${item.latestTokPerSec >= 100 ? Math.round(item.latestTokPerSec) : item.latestTokPerSec.toFixed(1)} t/s` - ); - } - if (item.contextUsedPct != null && Number.isFinite(Number(item.contextUsedPct))) { - metricParts.push(`${Math.round(Number(item.contextUsedPct))}%`); - } - const metricsStr = metricParts.join(' · '); - patchAttr(refs.metricsEl, 'hidden', !metricsStr); - if (metricsStr) { - patchText(refs.metricsEl, metricsStr); - } - - const subCount = Number(item.subagentCount || item.subagents?.length || 0); - const runSubCount = Number(item.runningSubagentCount || 0); - const isExpanded = manualSubExpandMap.has(item.cascadeId) - ? manualSubExpandMap.get(item.cascadeId) - : runSubCount > 0; - patchText(refs.mainBadge, t('fmt.mainBadge')); - patchAttr(refs.mainBadge, 'hidden', subCount === 0); - patchAttr(refs.subToggleBtn, 'hidden', subCount === 0); - if (subCount > 0) { - const arrow = isExpanded ? '▾' : '▸'; - const toggleText = - runSubCount > 0 - ? t('live.subToggleRunning', { run: runSubCount, total: subCount, arrow }) - : t('live.subToggleIdle', { total: subCount, arrow }); - patchText(refs.subToggleBtn, toggleText); - patchClasses(refs.subToggleBtn, { 'is-expanded': isExpanded }); - refs.subToggleBtn.onclick = (e) => { - e.stopPropagation(); - manualSubExpandMap.set(item.cascadeId, !isExpanded); - renderCapsuleTelemetry(); - if (multiOpen) { - positionFloatingElements(); - } - }; - } - - const mainTimerKey = `main:${item.cascadeId}`; - activeTimerKeys.add(mainTimerKey); - bindMultiElapsedTimer( - mainTimerKey, - `${item.cascadeId}:${act.signature || act.label}`, - act.startedAtMs, - refs.elapsedEl - ); - - patchText(refs.mainPhase, act.label || t('live.thinking')); - const progText = act.stepProgress ? `[${act.stepProgress}]` : ''; - patchAttr(refs.mainProgress, 'hidden', !progText); - if (progText) { - patchText(refs.mainProgress, progText); - } - - const detailStr = act.detail || ''; - patchAttr(refs.mainSep, 'hidden', !detailStr); - patchAttr(refs.mainDetail, 'hidden', !detailStr); - patchText(refs.mainDetail, detailStr); - - const showSubs = subCount > 0 && isExpanded; - patchAttr(refs.subListEl, 'hidden', !showSubs); - if (showSubs) { - const subItems = item.subagents || []; - patchKeyedList(refs.subListEl, subItems, { - keyFn: (sub) => sub.cascadeId, - sigFn: (sub) => - `${localeKey}:${sub.cascadeId}:${sub.role}:${sub.isRunning}:${sub.stepCount}:${sub.liveActivity?.signature || ''}:${sub.isRunning ? multiTimersMap.has(`sub:${sub.cascadeId}`) : true}`, - createRow: createMultiLiveSubRow, - updateRow: (subRefs, sub) => { - const subAct = sub.liveActivity || { - phase: sub.isRunning ? 'thinking' : 'done', - label: sub.isRunning ? t('live.thinking') : t('live.done'), - detail: '', - stepProgress: '', - startedAtMs: sub.lastModifiedMs || 0, - }; - patchClasses(subRefs.rowEl, { 'is-done': !sub.isRunning }); - const subBadgeCls = getAgentBadgeClass(sub.index || 1, false); - patchAttr(subRefs.subBadge, 'class', `agent-badge ${subBadgeCls}`); - patchText(subRefs.subBadge, formatAgentBadgeText(sub)); - patchText(subRefs.subRole, sub.role || sub.shortLabel || t('fmt.subAgent')); - - const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : ''; - const summaryText = sub.isRunning - ? `${subAct.label || t('live.running')}${subProg}${subAct.detail ? ` · ${subAct.detail}` : ''}` - : t('live.doneWithSteps', { steps: sub.stepCount || 0 }); - patchText(subRefs.subSummary, summaryText); - - const subTimerKey = `sub:${sub.cascadeId}`; - if (sub.isRunning) { - activeTimerKeys.add(subTimerKey); - bindMultiElapsedTimer( - subTimerKey, - `${sub.cascadeId}:${subAct.signature || subAct.label}`, - subAct.startedAtMs || sub.lastModifiedMs, - subRefs.subElapsed - ); - } else { - multiTimersMap.delete(subTimerKey); - patchText( - subRefs.subElapsed, - t('header.convMetaSteps', { count: sub.stepCount || 0 }) - ); - } - }, - }); - } - }, - }); - - for (const k of [...multiTimersMap.keys()]) { - if (!activeTimerKeys.has(k)) { - multiTimersMap.delete(k); - } - } - ensureMultiLiveTicker(); - tickMultiElapsedDisplay(); - } + multiRunningWidget.refs.update({ + items: rawRunningList, + hostRouteConversationId, + }); } function renderHoverWidgets() { @@ -2698,7 +2357,7 @@ export function mountWindowOverlay() { patchClasses(multiBtn, { 'is-running': false, 'is-waiting': false }); patchText(multiLabel, t('capsule.multiZero')); patchText(multiRunningMetaEl, t('multi.loading')); - stopMultiLiveTicker(); + multiRunningWidget.refs.stopLiveTicker(); applyCapsuleSlots(slotKeys, { hasTelemetry: false }); return; @@ -2711,138 +2370,36 @@ export function mountWindowOverlay() { uiSt.selectedAgentScope, uiSt.ctxInspectorAgentId ); - const activeConv = telemetry.activeConversation || {}; - const overviewActive = overviewScopedConv || activeConv; - const ctx = ctxAgent?.context || overviewActive.context || activeConv.context || {}; - const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000); - const totalTokens = Number(ctx.totalTokens || 0); - const usedPct = - limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0; - const dashOffset = +( - RING_CIRCUMFERENCE * - (1 - Math.max(0, Math.min(100, usedPct)) / 100) - ).toFixed(2); - // --- 4a. 同步左侧多会话实时状态胶囊与浮层看板 --- - const rawRunningList = - Array.isArray(telemetry.runningConversations) && telemetry.runningConversations.length > 0 - ? telemetry.runningConversations - : activeConv.isRunning || aggregated?.isRunning - ? [ - { - cascadeId: activeConv.cascadeId || 'current', - title: activeConv.title || t('live.currentSession'), - 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, - latestTokPerSec: overviewActive.latestTokPerSec ?? null, - contextUsedPct: usedPct, - subagents: (agents || []) - .filter((a) => !a.isMain) - .map((s, idx) => ({ - cascadeId: s.cascadeId || s.agentId, - index: s.index || idx + 1, - badgeText: s.badgeText || t('fmt.subBadge', { index: idx + 1 }), - shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`, - role: s.role || `${t('fmt.subAgent')} #${idx + 1}`, - isRunning: Boolean(s.isRunning), - stepCount: Number(s.stepCount || 0), - lastModifiedMs: s.lastModifiedMs || 0, - liveActivity: s.liveActivity || { - phase: s.isRunning ? 'thinking' : 'done', - label: s.isRunning ? t('live.thinking') : t('live.done'), - detail: '', - stepProgress: '', - startedAtMs: s.lastModifiedMs || 0, - signature: `${s.agentId}:${s.stepCount || 0}`, - }, - })), - }, - ] - : []; - - const runningCount = rawRunningList.length; - const runningSubCount = rawRunningList.reduce( - (acc, item) => acc + Number(item.runningSubagentCount || 0), - 0 - ); - const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting'); + const overviewActive = overviewScopedConv || telemetry.activeConversation || {}; + const slotCtx = buildCapsuleSlotContext(telemetry, { + scopedConv: capsuleScopedConv, + overviewConv: overviewActive, + ctxAgent, + aggregated, + }); + const { rawRunningList, runningCount, runningSubCount, hasWaiting, multiBtnText } = + resolveMultiSessionCapsuleState(telemetry, { + agents, + aggregated, + latestTokPerSec: overviewActive.latestTokPerSec ?? null, + contextUsedPct: slotCtx.usedPct, + }); patchClasses(multiBtn, { 'is-running': runningCount > 0 && !hasWaiting, 'is-waiting': runningCount > 0 && hasWaiting, }); - const multiBtnText = - runningCount > 0 - ? runningSubCount > 0 - ? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount }) - : t('capsule.multiRunning', { count: runningCount }) - : t('capsule.multiZero'); patchText(multiLabel, multiBtnText); - renderMultiRunningPanel(rawRunningList, runningCount, runningSubCount, telSt.hostRouteConversationId); + renderMultiRunningPanel( + rawRunningList, + runningCount, + runningSubCount, + telSt.hostRouteConversationId + ); - // --- 4b. 同步右侧 1..5 动态槽位胶囊与组件化悬停浮层 --- - const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning); - const capActive = capsuleScopedConv || aggregated || activeConv || {}; - const tps = - capsuleScopedConv?.latestTokPerSec ?? - aggregated?.latestTokPerSec ?? - activeConv.latestTokPerSec ?? - null; - const avgTps = - capsuleScopedConv?.avgTokPerSec ?? - aggregated?.avgTokPerSec ?? - activeConv.avgTokPerSec ?? - null; - const ttft = - capsuleScopedConv?.latestTtftSec ?? - aggregated?.latestTtftSec ?? - activeConv.latestTtftSec ?? - null; - const capsuleStepCost = - capsuleScopedConv?.latestStepCostUsd ?? - aggregated?.latestStepCostUsd ?? - activeConv.latestStepCostUsd ?? - null; - const sessionCost = - capsuleScopedConv?.sessionCostUsd ?? - aggregated?.sessionCostUsd ?? - activeConv.sessionCostUsd ?? - null; - const cacheHitPct = - Number(capActive.stepCount || 0) > 0 - ? capActive.latestCacheHitPct ?? capActive.sessionCacheHitPct ?? null - : null; - const latestPromptTokens = capActive.latestPromptTokens ?? null; - const capInTok = Math.max(0, Number(capActive.inputTokens || 0)); - const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0)); - const capOutTok = Math.max(0, Number(capActive.outputTokens || 0)); - const sessionTokens = - Number(capActive.stepCount || 0) > 0 || - capActive.totalTokens != null || - capInTok + capCacheTok + capOutTok > 0 - ? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok)) - : null; - - patchClasses(capsuleBtn, { 'is-running': isRunning }); - applyCapsuleSlots(slotKeys, { - hasTelemetry: true, - usedPct, - dashOffset, - isRunning, - tps, - avgTps, - ttft, - stepCost: capsuleStepCost, - sessionCost, - cacheHitPct, - latestPromptTokens, - sessionTokens, - quotas: telemetry.quotas, - }); + patchClasses(capsuleBtn, { 'is-running': slotCtx.isRunning }); + applyCapsuleSlots(slotKeys, slotCtx); const updateMode = normalizeClientUpdateMode( telemetry.settings?.pluginUpdateMode, @@ -3019,7 +2576,7 @@ export function mountWindowOverlay() { const onVisibilityChange = () => { if (document.hidden) { uiStore.setState({ monitorVisible: false }); - pauseMultiLiveTicker(); + multiRunningWidget.refs.pauseTicker(); hasPointerCoords = false; if (tooltipOpen) { setTooltipOpen(false); @@ -3212,7 +2769,7 @@ export function mountWindowOverlay() { clearTimeout(multiLeaveTimer); multiLeaveTimer = null; } - stopMultiLiveTicker(); + multiRunningWidget.refs.stopLiveTicker(); if (dockRafId && typeof cancelAnimationFrame === 'function') { cancelAnimationFrame(dockRafId); dockRafId = 0; diff --git a/sidecars/panel/src/components/settings/structurePreviewMock.js b/sidecars/panel/src/components/settings/structurePreviewMock.js index 60c3053..9cc2e4a 100644 --- a/sidecars/panel/src/components/settings/structurePreviewMock.js +++ b/sidecars/panel/src/components/settings/structurePreviewMock.js @@ -328,8 +328,12 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides ...mainAgent, agentId: 'all', isMain: false, - badgeText: '全部', + agentKind: 'all', + agentOrdinal: 0, + badgeText: t('header.scopeAllShort'), activeAgentId: 'main', + activeAgentKind: 'main', + activeAgentOrdinal: 0, stepCount: 24, speedSampleCount: 23, speedSummary: { sampleCount: 23, excludedCount: 1 }, @@ -343,7 +347,7 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides cacheReadTokens: 1540000, outputTokens: 28400, totalTokens: 1754800, - activeAgentBadge: '主', + activeAgentBadge: t('fmt.mainBadge'), modelBreakdown: [...mainAgent.modelBreakdown, ...subAgent1.modelBreakdown], recentSteps: mockSteps, }; diff --git a/sidecars/panel/src/components/widgets/CapsuleBarWidget.js b/sidecars/panel/src/components/widgets/CapsuleBarWidget.js index c8ec65b..e74c8c6 100644 --- a/sidecars/panel/src/components/widgets/CapsuleBarWidget.js +++ b/sidecars/panel/src/components/widgets/CapsuleBarWidget.js @@ -14,10 +14,96 @@ import { normalizeClientWindowMountMode, resolveScopedConversation, } from '../../store/telemetryStore.js'; +import { buildFallbackRunningConversations } from './LiveActivityWidget.js'; export const RING_RADIUS = 5.2; export const RING_CIRCUMFERENCE = +(2 * Math.PI * RING_RADIUS).toFixed(2); +/** + * Compute shared context ring + 1..5 capsule slot metric payload from telemetry & scoped conversation. + */ +export function buildCapsuleSlotContext( + data, + { scopedConv = null, overviewConv = null, ctxAgent = null, aggregated = null } = {} +) { + if (!data) return { hasTelemetry: false }; + const activeConv = data.activeConversation || {}; + const overviewActive = overviewConv || scopedConv || aggregated || activeConv; + const capActive = scopedConv || aggregated || activeConv || {}; + const ctx = ctxAgent?.context || overviewActive.context || activeConv.context || {}; + const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000); + const totalTokens = Number(ctx.totalTokens || 0); + const usedPct = + limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0; + const dashOffset = +( + RING_CIRCUMFERENCE * + (1 - Math.max(0, Math.min(100, usedPct)) / 100) + ).toFixed(2); + + const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning); + const capInTok = Math.max(0, Number(capActive.inputTokens || 0)); + const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0)); + const capOutTok = Math.max(0, Number(capActive.outputTokens || 0)); + const sessionTokens = + Number(capActive.stepCount || 0) > 0 || + capActive.totalTokens != null || + capInTok + capCacheTok + capOutTok > 0 + ? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok)) + : null; + + return { + hasTelemetry: true, + usedPct, + dashOffset, + isRunning, + tps: scopedConv?.latestTokPerSec ?? aggregated?.latestTokPerSec ?? activeConv.latestTokPerSec ?? null, + avgTps: scopedConv?.avgTokPerSec ?? aggregated?.avgTokPerSec ?? activeConv.avgTokPerSec ?? null, + ttft: scopedConv?.latestTtftSec ?? aggregated?.latestTtftSec ?? activeConv.latestTtftSec ?? null, + stepCost: + scopedConv?.latestStepCostUsd ?? + aggregated?.latestStepCostUsd ?? + activeConv.latestStepCostUsd ?? + null, + sessionCost: + scopedConv?.sessionCostUsd ?? aggregated?.sessionCostUsd ?? activeConv.sessionCostUsd ?? null, + cacheHitPct: + Number(capActive.stepCount || 0) > 0 + ? capActive.latestCacheHitPct ?? capActive.sessionCacheHitPct ?? null + : null, + latestPromptTokens: capActive.latestPromptTokens ?? null, + sessionTokens, + quotas: data.quotas, + }; +} + +/** + * Compute multi-session button state & normalized running conversation list. + */ +export function resolveMultiSessionCapsuleState( + data, + { agents = [], aggregated = null, latestTokPerSec = undefined, contextUsedPct = undefined } = {} +) { + const rawRunningList = buildFallbackRunningConversations(data, { + agents, + aggregated, + latestTokPerSec, + contextUsedPct, + }); + const runningCount = rawRunningList.length; + const runningSubCount = rawRunningList.reduce( + (acc, item) => acc + Number(item.runningSubagentCount || 0), + 0 + ); + const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting'); + const multiBtnText = + runningCount > 0 + ? runningSubCount > 0 + ? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount }) + : t('capsule.multiRunning', { count: runningCount }) + : t('capsule.multiZero'); + return { rawRunningList, runningCount, runningSubCount, hasWaiting, multiBtnText }; +} + /** * Create a single reusable capsule metric slot node (`0..4`) with an optional SVG context ring. */ @@ -274,75 +360,26 @@ export const CapsuleBarWidget = defineComponent({ return; } - const { scopedConv, ctxAgent, aggregated } = resolveScopedConversation( + const { agents, scopedConv, ctxAgent, aggregated } = resolveScopedConversation( data, 'all', 'auto' ); - const activeConv = data.activeConversation || {}; - const capActive = scopedConv || aggregated || activeConv; - const ctx = ctxAgent?.context || capActive.context || activeConv.context || {}; - const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000); - const totalTokens = Number(ctx.totalTokens || 0); - const usedPct = - limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0; - const dashOffset = +( - RING_CIRCUMFERENCE * - (1 - Math.max(0, Math.min(100, usedPct)) / 100) - ).toFixed(2); - - const rawRunningList = Array.isArray(data.runningConversations) - ? data.runningConversations - : []; - const runningCount = rawRunningList.length; - const runningSubCount = rawRunningList.reduce( - (acc, item) => acc + Number(item.runningSubagentCount || 0), - 0 - ); - const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting'); + const slotCtx = buildCapsuleSlotContext(data, { scopedConv, ctxAgent, aggregated }); + const { runningCount, hasWaiting, multiBtnText } = resolveMultiSessionCapsuleState(data, { + agents, + aggregated, + contextUsedPct: slotCtx.usedPct, + }); patchClasses(multiBtn, { 'is-running': runningCount > 0 && !hasWaiting, 'is-waiting': runningCount > 0 && hasWaiting, }); - const multiBtnText = - runningCount > 0 - ? runningSubCount > 0 - ? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount }) - : t('capsule.multiRunning', { count: runningCount }) - : t('capsule.multiZero'); patchText(multiLabel, multiBtnText); - const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning); - const capInTok = Math.max(0, Number(capActive.inputTokens || 0)); - const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0)); - const capOutTok = Math.max(0, Number(capActive.outputTokens || 0)); - const sessionTokens = - Number(capActive.stepCount || 0) > 0 || - capActive.totalTokens != null || - capInTok + capCacheTok + capOutTok > 0 - ? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok)) - : null; - - patchClasses(capsuleBtn, { 'is-running': isRunning }); - syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, { - hasTelemetry: true, - usedPct, - dashOffset, - isRunning, - tps: capActive.latestTokPerSec ?? null, - avgTps: capActive.avgTokPerSec ?? null, - ttft: capActive.latestTtftSec ?? null, - stepCost: capActive.latestStepCostUsd ?? null, - sessionCost: capActive.sessionCostUsd ?? null, - cacheHitPct: - Number(capActive.stepCount || 0) > 0 - ? capActive.latestCacheHitPct ?? capActive.sessionCacheHitPct ?? null - : null, - latestPromptTokens: capActive.latestPromptTokens ?? null, - sessionTokens, - quotas: data.quotas, - }); + patchClasses(capsuleBtn, { 'is-running': slotCtx.isRunning }); + syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx); } return { diff --git a/sidecars/panel/src/components/widgets/ContextWindowWidget.js b/sidecars/panel/src/components/widgets/ContextWindowWidget.js index 83673b5..8540c5c 100644 --- a/sidecars/panel/src/components/widgets/ContextWindowWidget.js +++ b/sidecars/panel/src/components/widgets/ContextWindowWidget.js @@ -309,14 +309,16 @@ export const ContextWindowWidget = defineComponent({ if (interactiveInspector) { patchAttr(ctxInspectorBar, 'hidden', !hasSubagents); if (hasSubagents && ctxAgent) { - const rawActiveBadge = aggregated?.activeAgentBadge || '主'; - const activeBadgeText = isEnglishLocale() - ? rawActiveBadge === '主' - ? t('fmt.mainBadge') - : rawActiveBadge - .replace(/^子(\d+)$/, (_, n) => t('fmt.subBadge', { index: n })) - .replace(/^旁(\d+)$/, (_, n) => t('fmt.sideBadge', { index: n })) - : rawActiveBadge; + const activeBadgeText = formatAgentBadgeText({ + agentKind: + aggregated?.activeAgentKind || + (!aggregated?.activeAgentId || aggregated.activeAgentId === 'main' + ? 'main' + : 'subagent'), + agentOrdinal: Number(aggregated?.activeAgentOrdinal || 0), + isMain: !aggregated?.activeAgentId || aggregated.activeAgentId === 'main', + badgeText: aggregated?.activeAgentBadge, + }); const pillItems = [ { diff --git a/sidecars/panel/src/components/widgets/LiveActivityWidget.js b/sidecars/panel/src/components/widgets/LiveActivityWidget.js index 0b42767..23f4b2a 100644 --- a/sidecars/panel/src/components/widgets/LiveActivityWidget.js +++ b/sidecars/panel/src/components/widgets/LiveActivityWidget.js @@ -1,7 +1,8 @@ /** * @fileoverview Standalone decoupled Live Running Tasks Widget (`LiveActivityWidget.js`). * Displays active multi-session running conversations & collapsible subagent activity - * with an isolated 1s elapsed timer lifecycle. + * with an isolated 1s elapsed timer lifecycle. Supports both Overview/Hover widget mode + * and controlled Multi-Session Floating Panel mode (`WindowOverlayShell.js`). */ import { defineComponent } from '../../core/component.js'; @@ -12,23 +13,85 @@ import { patchKeyedList, patchText, } from '../../core/domPatch.js'; -import { formatElapsedSec } from '../../core/formatters.js'; +import { + formatAgentBadgeText, + formatElapsedSec, + formatLiveActivityDetail, + formatLiveActivityLabel, + getAgentBadgeClass, +} from '../../core/formatters.js'; import { createSvgIcon } from '../../icons/SvgIcon.js'; import { getEffectiveLocale, t } from '../../i18n/index.js'; import { + extractHostRouteCascadeId, fetchTelemetry, - formatAgentBadgeText, - getAgentBadgeClass, resolveScopedConversation, telemetryStore, } from '../../store/telemetryStore.js'; import { uiStore } from '../../store/uiStore.js'; +export function buildFallbackRunningConversations( + data, + { agents = [], aggregated = null, latestTokPerSec = undefined, contextUsedPct = undefined } = {} +) { + if (!data) return []; + if (Array.isArray(data.runningConversations) && data.runningConversations.length > 0) { + return data.runningConversations; + } + const activeConv = data.activeConversation || {}; + if (!activeConv.isRunning && !aggregated?.isRunning) return []; + return [ + { + cascadeId: activeConv.cascadeId || 'current', + title: activeConv.title || t('live.currentSession'), + 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, + ...(latestTokPerSec !== undefined ? { latestTokPerSec } : {}), + ...(contextUsedPct !== undefined ? { contextUsedPct } : {}), + subagents: (agents || []) + .filter((a) => !a.isMain) + .map((s, idx) => ({ + 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), + customRole: s.customRole, + ...(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}`, + 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'), + detail: '', + stepProgress: '', + startedAtMs: s.lastModifiedMs || 0, + signature: `${s.agentId}:${s.stepCount || 0}`, + }, + })), + }, + ]; +} + export const LiveActivityWidget = defineComponent({ name: 'LiveActivityWidget', setup({ props, onCleanup }) { const interactive = props.interactive !== false; const preview = Boolean(props.preview); + const defaultExpandRunningSubs = Boolean(props.defaultExpandRunningSubs); + const showSessionExtras = Boolean(props.showSessionExtras); + const onSelectSession = + typeof props.onSelectSession === 'function' ? props.onSelectSession : null; + const onLayoutChange = + typeof props.onLayoutChange === 'function' ? props.onLayoutChange : null; const getCtxAgentId = typeof props.getCtxAgentId === 'function' ? props.getCtxAgentId @@ -42,10 +105,19 @@ export const LiveActivityWidget = defineComponent({ 'aria-live': 'polite', }); - const expandedTaskConvIds = new Set(); + const manualSubExpandMap = new Map(); const activityTimersMap = new Map(); let liveTickTimer = null; - let latestData = null; + let latestUpdateArgs = null; + + function resolveIsExpanded(item) { + const runSubCount = Number(item?.runningSubagentCount || 0); + if (!interactive) return runSubCount > 0; + if (manualSubExpandMap.has(item.cascadeId)) { + return Boolean(manualSubExpandMap.get(item.cascadeId)); + } + return defaultExpandRunningSubs ? runSubCount > 0 : false; + } function bindLiveElapsedTimer(timerKey, sig, rawStartMs, targetEl) { const now = Date.now(); @@ -108,6 +180,20 @@ export const LiveActivityWidget = defineComponent({ className: 'live-task-title', text: t('live.currentSession'), }); + const hereTagEl = showSessionExtras + ? h('span', { + className: 'wm-session-tag is-here', + hidden: true, + text: t('multi.hereTag'), + }) + : null; + const metricsEl = showSessionExtras + ? h('span', { + className: 'wm-task-metrics text-mono', + hidden: true, + text: '', + }) + : null; const subToggleBtn = h('button', { type: 'button', className: 'live-sub-toggle', @@ -120,8 +206,16 @@ export const LiveActivityWidget = defineComponent({ }); const headerEl = h('div', { className: 'live-task-header' }, [ - h('div', { className: 'live-task-title-wrap' }, [dotWrap, titleEl]), - h('div', { className: 'live-task-header-right' }, [subToggleBtn, elapsedEl]), + h('div', { className: 'live-task-title-wrap' }, [ + dotWrap, + titleEl, + ...(hereTagEl ? [hereTagEl] : []), + ]), + h('div', { className: 'live-task-header-right' }, [ + ...(metricsEl ? [metricsEl] : []), + subToggleBtn, + elapsedEl, + ]), ]); const mainBadge = h('span', { @@ -162,6 +256,8 @@ export const LiveActivityWidget = defineComponent({ cardEl, dotIcon, titleEl, + hereTagEl, + metricsEl, subToggleBtn, elapsedEl, mainBadge, @@ -200,103 +296,86 @@ export const LiveActivityWidget = defineComponent({ }; } - function update({ data } = {}) { - latestData = data || null; - if (!data) { + function update({ data = null, items = null, hostRouteConversationId = '' } = {}) { + latestUpdateArgs = { data, items, hostRouteConversationId }; + if (!data && !Array.isArray(items)) { patchAttr(liveActivityBar, 'hidden', true); stopLiveTicker(); return; } - const { agents, aggregated } = resolveScopedConversation( - data, - 'all', - getCtxAgentId() - ); + let rawRunningList = Array.isArray(items) ? items : null; + if (!rawRunningList) { + const { agents, aggregated } = resolveScopedConversation( + data, + 'all', + getCtxAgentId() + ); + rawRunningList = buildFallbackRunningConversations(data, { agents, aggregated }); + } - const rawRunningList = - Array.isArray(data.runningConversations) && data.runningConversations.length > 0 - ? data.runningConversations - : data.activeConversation?.isRunning || aggregated?.isRunning - ? [ - { - cascadeId: data.activeConversation?.cascadeId || 'current', - title: data.activeConversation?.title || t('live.currentSession'), - isCurrentSelected: true, - isMainRunning: Boolean(data.activeConversation?.isRunning), - isRunning: true, - mainActivity: - data.activeConversation?.liveActivity || aggregated?.liveActivity || null, - subagentCount: Math.max(0, agents.length - 1), - runningSubagentCount: agents.filter((a) => !a.isMain && a.isRunning).length, - subagents: agents - .filter((a) => !a.isMain) - .map((s, idx) => ({ - cascadeId: s.cascadeId || s.agentId, - index: s.index || idx + 1, - badgeText: formatAgentBadgeText({ ...s, index: s.index || idx + 1 }), - shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`, - role: s.role || `${t('fmt.subAgent')} #${idx + 1}`, - isRunning: Boolean(s.isRunning), - stepCount: Number(s.stepCount || 0), - lastModifiedMs: s.lastModifiedMs || 0, - liveActivity: s.liveActivity || { - phase: s.isRunning ? 'thinking' : 'done', - label: s.isRunning ? t('live.thinking') : t('live.done'), - detail: '', - stepProgress: '', - startedAtMs: s.lastModifiedMs || 0, - signature: `${s.agentId}:${s.stepCount || 0}`, - }, - })), - }, - ] - : []; + if (manualSubExpandMap.size > 0) { + const runningIdsSet = new Set(rawRunningList.map((item) => item.cascadeId)); + for (const id of [...manualSubExpandMap.keys()]) { + if (!runningIdsSet.has(id)) { + manualSubExpandMap.delete(id); + } + } + } const hasRunningTasks = rawRunningList.length > 0; patchAttr(liveActivityBar, 'hidden', !hasRunningTasks); if (!hasRunningTasks) { stopLiveTicker(); - expandedTaskConvIds.clear(); + patchKeyedList(liveActivityBar, [], {}); return; } + if (!isVisibleFn()) { + pauseTicker(); + return; + } + + const locale = getEffectiveLocale(); + const hostRouteLower = showSessionExtras + ? String(hostRouteConversationId || extractHostRouteCascadeId() || '').toLowerCase() + : ''; + const activeTimerKeys = new Set(); for (const item of rawRunningList) { activeTimerKeys.add(`main:${item.cascadeId}`); - for (const sub of item.subagents || []) { - if (sub?.isRunning) { - activeTimerKeys.add(`sub:${sub.cascadeId}`); + const subCount = Number(item.subagentCount || item.subagents?.length || 0); + const isExp = resolveIsExpanded(item); + if (subCount > 0 && isExp) { + for (const sub of item.subagents || []) { + if (sub?.isRunning) { + activeTimerKeys.add(`sub:${sub.cascadeId}`); + } } } } - const runningIdsSet = new Set(rawRunningList.map((item) => item.cascadeId)); - for (const id of [...expandedTaskConvIds]) { - if (!runningIdsSet.has(id)) { - expandedTaskConvIds.delete(id); - } - } - - const locale = getEffectiveLocale(); patchKeyedList(liveActivityBar, rawRunningList, { keyFn: (item) => item.cascadeId, sigFn: (item) => { - const isExp = interactive - ? expandedTaskConvIds.has(item.cascadeId) - : Number(item.runningSubagentCount || 0) > 0; + const isExp = resolveIsExpanded(item); + const isHere = + showSessionExtras && + Boolean(hostRouteLower) && + String(item.cascadeId || '').toLowerCase() === hostRouteLower; const subSig = (item.subagents || []) .map( (s) => `${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}` ) .join('|'); - return `${locale}:${item.cascadeId}:${item.title}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`; + 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}`; }, createRow: createLiveTaskCard, updateRow: (refs, item) => { const act = item.mainActivity || { phase: 'thinking', + actionKey: 'thinking', label: t('live.thinking'), detail: '', stepProgress: '', @@ -315,9 +394,18 @@ export const LiveActivityWidget = defineComponent({ const convTitle = item.title || item.cascadeId?.slice(0, 8) || t('live.currentSession'); patchText(refs.titleEl, convTitle); if (interactive && !preview) { - patchAttr(refs.titleEl, 'title', t('live.switchSessionTitle', { title: convTitle })); - refs.titleEl.onclick = () => { - if (item.cascadeId && item.cascadeId !== 'current') { + patchAttr( + refs.titleEl, + 'title', + onSelectSession + ? t('multi.inspectSessionTitle', { title: convTitle }) + : t('live.switchSessionTitle', { title: convTitle }) + ); + refs.titleEl.onclick = (e) => { + e?.stopPropagation?.(); + if (onSelectSession) { + onSelectSession(item.cascadeId); + } else if (item.cascadeId && item.cascadeId !== 'current') { uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); telemetryStore.setState({ selectedConversationId: item.cascadeId }); fetchTelemetry({ force: false }); @@ -325,11 +413,32 @@ export const LiveActivityWidget = defineComponent({ }; } + if (showSessionExtras && refs.hereTagEl && refs.metricsEl) { + const isHere = + Boolean(hostRouteLower) && + String(item.cascadeId || '').toLowerCase() === hostRouteLower; + patchText(refs.hereTagEl, t('multi.hereTag')); + patchAttr(refs.hereTagEl, 'hidden', !isHere); + + const metricParts = []; + if (Number.isFinite(item.latestTokPerSec) && item.latestTokPerSec > 0) { + metricParts.push( + `${item.latestTokPerSec >= 100 ? Math.round(item.latestTokPerSec) : item.latestTokPerSec.toFixed(1)} t/s` + ); + } + if (item.contextUsedPct != null && Number.isFinite(Number(item.contextUsedPct))) { + metricParts.push(`${Math.round(Number(item.contextUsedPct))}%`); + } + const metricsStr = metricParts.join(' · '); + patchAttr(refs.metricsEl, 'hidden', !metricsStr); + if (metricsStr) { + patchText(refs.metricsEl, metricsStr); + } + } + const subCount = Number(item.subagentCount || item.subagents?.length || 0); const runSubCount = Number(item.runningSubagentCount || 0); - const isExpanded = interactive - ? expandedTaskConvIds.has(item.cascadeId) - : runSubCount > 0; + const isExpanded = resolveIsExpanded(item); patchText(refs.mainBadge, t('fmt.mainBadge')); patchAttr(refs.mainBadge, 'hidden', subCount === 0); patchAttr(refs.subToggleBtn, 'hidden', subCount === 0); @@ -349,39 +458,37 @@ export const LiveActivityWidget = defineComponent({ ); refs.subToggleBtn.onclick = (e) => { e.stopPropagation(); - if (expandedTaskConvIds.has(item.cascadeId)) { - expandedTaskConvIds.delete(item.cascadeId); - } else { - expandedTaskConvIds.add(item.cascadeId); - } - if (latestData) update({ data: latestData }); + manualSubExpandMap.set(item.cascadeId, !isExpanded); + if (latestUpdateArgs) update(latestUpdateArgs); + onLayoutChange?.(); }; } } + const mainLabel = formatLiveActivityLabel(act, 'live.thinking'); + const detailStr = formatLiveActivityDetail(act); const mainTimerKey = `main:${item.cascadeId}`; activeTimerKeys.add(mainTimerKey); bindLiveElapsedTimer( mainTimerKey, - `${item.cascadeId}:${act.signature || act.label}`, + `${item.cascadeId}:${act.signature || mainLabel}`, act.startedAtMs, refs.elapsedEl ); - patchText(refs.mainPhase, act.label || t('live.thinking')); + patchText(refs.mainPhase, mainLabel); const progText = act.stepProgress ? `[${act.stepProgress}]` : ''; patchAttr(refs.mainProgress, 'hidden', !progText); if (progText) { patchText(refs.mainProgress, progText); } - const detailStr = act.detail || ''; patchAttr(refs.mainSep, 'hidden', !detailStr); patchAttr(refs.mainDetail, 'hidden', !detailStr); patchText(refs.mainDetail, detailStr); - if (interactive) { - const fullTooltip = `[${convTitle}] ${t('fmt.mainAgent')} · ${act.label || ''}${progText ? ` ${progText}` : ''}${detailStr ? ` · ${detailStr}` : ''}`; + if (interactive && !showSessionExtras) { + const fullTooltip = `[${convTitle}] ${t('fmt.mainAgent')} · ${mainLabel}${progText ? ` ${progText}` : ''}${detailStr ? ` · ${detailStr}` : ''}`; patchAttr(refs.cardEl, 'title', fullTooltip); } @@ -397,6 +504,7 @@ export const LiveActivityWidget = defineComponent({ updateRow: (subRefs, sub) => { const subAct = sub.liveActivity || { phase: sub.isRunning ? 'thinking' : 'done', + actionKey: sub.isRunning ? 'thinking' : 'done', label: sub.isRunning ? t('live.thinking') : t('live.done'), detail: '', stepProgress: '', @@ -413,20 +521,30 @@ export const LiveActivityWidget = defineComponent({ patchAttr(subRefs.subBadge, 'class', `agent-badge ${badgeCls}`); patchText(subRefs.subBadge, subBadgeText); - const roleText = sub.role || sub.shortLabel || t('fmt.subAgent'); + 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}` : ''}`; + const roleText = + sub.customRole !== undefined + ? sub.customRole || fallbackRole + : sub.role || sub.shortLabel || fallbackRole; patchText(subRefs.subRole, roleText); - const rawSubLabel = sub.isRunning - ? subAct.label || '' - : subAct.label || t('live.done'); + const subLabel = sub.isRunning + ? formatLiveActivityLabel(subAct, 'live.running') + : formatLiveActivityLabel(subAct, 'live.done'); + const subDetail = formatLiveActivityDetail(subAct); const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : ''; - const summaryStr = [`${rawSubLabel}${subProg}`.trim(), subAct.detail || ''] - .filter(Boolean) - .join(' '); + const summaryStr = showSessionExtras + ? sub.isRunning + ? `${subLabel}${subProg}${subDetail ? ` · ${subDetail}` : ''}` + : t('live.doneWithSteps', { steps: sub.stepCount || 0 }) + : [`${subLabel}${subProg}`.trim(), subDetail].filter(Boolean).join(' '); patchAttr(subRefs.subSummary, 'hidden', !summaryStr); patchText(subRefs.subSummary, summaryStr); - if (interactive) { + if (interactive && !showSessionExtras) { patchAttr( subRefs.rowEl, 'title', @@ -439,8 +557,8 @@ export const LiveActivityWidget = defineComponent({ activeTimerKeys.add(subTimerKey); bindLiveElapsedTimer( subTimerKey, - `${sub.cascadeId}:${subAct.signature || subAct.label}`, - subAct.startedAtMs, + `${sub.cascadeId}:${subAct.signature || subLabel}`, + subAct.startedAtMs || sub.lastModifiedMs, subRefs.subElapsed ); } else { diff --git a/sidecars/panel/src/components/widgets/StepTableWidget.js b/sidecars/panel/src/components/widgets/StepTableWidget.js index 7fc52e6..c38ce47 100644 --- a/sidecars/panel/src/components/widgets/StepTableWidget.js +++ b/sidecars/panel/src/components/widgets/StepTableWidget.js @@ -13,7 +13,7 @@ import { patchKeyedList, patchText, } from '../../core/domPatch.js'; -import { getEffectiveLocale, isEnglishLocale, t } from '../../i18n/index.js'; +import { getEffectiveLocale, t } from '../../i18n/index.js'; import { DEFAULT_STEP_COLUMN_KEYS, STEP_COLUMN_REGISTRY, @@ -25,14 +25,11 @@ import { normalizeClientStepTokenComboFormat, } from '../../store/telemetryStore.js'; -export function formatTurnPromptText(rawPrompt) { +export function formatTurnPromptText(rawPrompt, { hasMedia = false, mediaOnly = false } = {}) { const text = String(rawPrompt || '').trim(); - if (!text || !isEnglishLocale()) return text; - if (text === '[图片/附件提问]') return t('steps.turnMediaOnly'); - if (text.endsWith(' [附图]')) { - return `${text.slice(0, -5)} ${t('steps.turnMediaSuffix')}`; - } - return text; + if (mediaOnly || (!text && hasMedia)) return t('steps.turnMediaOnly'); + if (!text) return ''; + return hasMedia ? `${text} ${t('steps.turnMediaSuffix')}` : text; } export const StepTableWidget = defineComponent({ @@ -212,7 +209,13 @@ export const StepTableWidget = defineComponent({ const getStepIsLatest = (st) => Boolean(useRootTurn ? (st?.isRootLatestTurn ?? st?.isLatestTurn) : st?.isLatestTurn); const getStepPrompt = (st) => - (useRootTurn ? (st?.rootTurnPrompt ?? st?.turnPrompt) : st?.turnPrompt) || ''; + (useRootTurn + ? (st?.rootTurnPromptClean ?? st?.rootTurnPrompt ?? st?.turnPromptClean ?? st?.turnPrompt) + : (st?.turnPromptClean ?? st?.turnPrompt)) || ''; + const getStepHasMedia = (st) => + 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) => { const tIdx = getStepTurnIdx(st); if (!Number.isInteger(tIdx) || tIdx <= 0) return ''; @@ -221,8 +224,13 @@ export const StepTableWidget = defineComponent({ const formattedPrompts = new Map(); function formattedTurnPrompt(st) { const raw = getStepPrompt(st); - if (!formattedPrompts.has(raw)) formattedPrompts.set(raw, formatTurnPromptText(raw)); - return formattedPrompts.get(raw); + const hasMedia = getStepHasMedia(st); + const mediaOnly = getStepMediaOnly(st); + const cacheKey = `${mediaOnly ? 2 : hasMedia ? 1 : 0}:${raw}`; + if (!formattedPrompts.has(cacheKey)) { + formattedPrompts.set(cacheKey, formatTurnPromptText(raw, { hasMedia, mediaOnly })); + } + return formattedPrompts.get(cacheKey); } const decoratedSteps = tableSteps.map((st, idx) => { @@ -344,28 +352,38 @@ export const StepTableWidget = defineComponent({ const badgeCls = getAgentBadgeClass(st.agentIndex || 0, !st.isSubagent); const clickableCls = interactiveBadges && onSelectAgentScopes ? ' is-clickable' : ''; patchAttr(refs.agentBadgeEl, 'class', `agent-badge${clickableCls} ${badgeCls}`); - const badgeText = isEnglishLocale() - ? formatAgentBadgeText({ - isMain: !st.isSubagent, - isSideQuestion: Boolean(st.isSideQuestion), - sideIndex: st.sideIndex || 0, - index: st.agentIndex || 0, - badgeText: st.agentBadge, - }) - : st.agentBadge || (st.isSideQuestion ? '旁' : st.isSubagent ? '子' : '主'); + const badgeText = 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, + }); patchText(refs.agentBadgeEl, badgeText); if (interactiveBadges && onSelectAgentScopes) { const targetScope = st.agentId || 'main'; const isSoleTarget = effectiveScopes.length === 1 && effectiveScopes[0] === targetScope; - const agentName = isEnglishLocale() - ? formatAgentLabel({ - isMain: !st.isSubagent, - index: st.agentIndex || 0, - role: st.agentRole || '', - }) - : st.agentLabel || t('steps.unitAgent'); + const agentName = formatAgentLabel({ + agentKind: + st.agentKind || + (!st.isSubagent ? 'main' : st.isSideQuestion ? 'side_question' : 'subagent'), + agentOrdinal: + st.agentOrdinal || (st.isSideQuestion ? st.sideIndex || 0 : st.agentIndex || 0), + customRole: st.agentCustomRole, + isMain: !st.isSubagent, + isSideQuestion: Boolean(st.isSideQuestion), + sideIndex: st.sideIndex || 0, + index: st.agentIndex || 0, + role: st.agentRole || '', + shortLabel: st.agentLabel || '', + }); patchAttr( refs.agentBadgeEl, 'title', diff --git a/sidecars/panel/src/core/formatters.js b/sidecars/panel/src/core/formatters.js index 5a11149..5eac14e 100644 --- a/sidecars/panel/src/core/formatters.js +++ b/sidecars/panel/src/core/formatters.js @@ -217,23 +217,35 @@ export function resolveModelDisplayInfo(target, settings = {}, options = {}) { } const shortText = String( - target.activeModelShort ?? target.modelShort ?? target.shortName ?? '' + target.activeBaseModelShort ?? + target.baseModelShort ?? + target.activeModelShort ?? + target.modelShort ?? + target.shortName ?? + '' ).trim(); const labelText = String( - target.activeModelLabel ?? target.modelLabel ?? target.label ?? '' + target.activeBaseModelLabel ?? + target.baseModelLabel ?? + target.activeModelLabel ?? + target.modelLabel ?? + target.label ?? + '' ).trim(); const upstreamText = String( - target.activeModelUpstream ?? target.modelUpstream ?? target.upstreamName ?? '' + target.baseModelUpstream ?? + target.activeModelUpstream ?? + target.modelUpstream ?? + target.upstreamName ?? + '' ).trim(); + const rawCompactionText = `${target.activeModelShort ?? target.modelShort ?? ''} ${target.activeModelLabel ?? target.modelLabel ?? ''} ${target.activeModelUpstream ?? target.modelUpstream ?? ''}`; const responseText = String(target.responseModel ?? '').trim(); const modelKeyText = String(target.modelKey ?? '').trim(); const isCompaction = Boolean(target.isCompactionStep) || - /·(?:压缩|compact)\s*$/iu.test(shortText) || - /·(?:压缩|compact)\s*$/iu.test(upstreamText) || - /·(?:压缩|compact)\s*$/iu.test(labelText) || - /\[自动压缩\]\s*$/u.test(labelText); + /·(?:压缩|compact)(?=\s|$)|\[自动压缩\]/iu.test(rawCompactionText); const compactionSuffix = isCompaction ? t('fmt.compactionSuffix') : ''; @@ -470,3 +482,131 @@ export function mergeModelsByDisplayName(models = [], settings = {}, options = { }; }); } + +/** + * 根据代理索引返回对应的微边框语义徽章样式类名。 + * + * @param {number} [index=0] + * @param {boolean} [isMain=false] + * @returns {string} + */ +export function getAgentBadgeClass(index = 0, isMain = false) { + if (isMain || index <= 0) return 'badge-main'; + const slot = ((index - 1) % 3) + 1; + return `badge-sub-${slot}`; +} + +/** + * 基于结构化 `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'); + if (kind === 'all') return t('header.scopeAllShort'); + if (kind === 'main') return t('fmt.mainBadge'); + if (kind === 'side_question') { + const ord = Number(agent.agentOrdinal || agent.sideIndex || 0); + if (ord > 0) return t('fmt.sideBadge', { index: ord }); + if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText); + return t('fmt.sideBadgeShort'); + } + 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); + return t('fmt.subBadgeShort'); +} + +/** + * 基于结构化 `agentKind` / `agentOrdinal` / `customRole` 格式化代理完整显示名称(零正则反拆中文)。 + * + * @param {object|null|undefined} agent + * @returns {string} + */ +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'); + if (kind === 'all') return t('header.scopeAll'); + if (kind === 'main') return t('fmt.mainAgent'); + + const rawCustom = + agent.customRole !== undefined + ? String(agent.customRole || '').trim() + : String(agent.role || '').trim(); + if (kind === 'side_question') { + const ord = Number(agent.agentOrdinal || agent.sideIndex || 0); + const baseLabel = ord > 0 ? `${t('fmt.sideQuestion')} #${ord}` : t('fmt.sideQuestion'); + const isGeneric = + !rawCustom || + rawCustom === baseLabel || + rawCustom === agent.shortLabel || + rawCustom === t('fmt.sideQuestion') || + rawCustom === 'Side Question' || + rawCustom === 'side_question'; + return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`; + } + + const ord = Number(agent.agentOrdinal || agent.index || 0); + const baseLabel = ord > 0 ? `${t('fmt.subAgent')} #${ord}` : t('fmt.subAgent'); + const isGeneric = + !rawCustom || + rawCustom === baseLabel || + rawCustom === agent.shortLabel || + rawCustom === t('fmt.subAgent') || + rawCustom === 'Subagent'; + return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`; +} + +/** + * 基于后端结构化 `actionKey` + `waitingApproval` 渲染实时动作短标题(兼容自定义 `label` 回退)。 + * + * @param {object|null|undefined} act + * @param {string} [fallbackKey='live.thinking'] + * @returns {string} + */ +export function formatLiveActivityLabel(act, fallbackKey = 'live.thinking') { + if (!act || typeof act !== 'object') return t(fallbackKey); + let baseLabel = ''; + if (act.actionKey) { + const i18nKey = `live.act.${act.actionKey}`; + const translated = t(i18nKey); + if (translated && translated !== i18nKey) { + baseLabel = translated; + } + } + if (!baseLabel) { + baseLabel = String(act.label || '').trim() || t(fallbackKey); + } + if (act.waitingApproval) { + return t('live.act.awaitingApproval', { label: baseLabel }); + } + return baseLabel; +} + +/** + * 基于后端结构化 `detailKey` 渲染实时动作补充说明(兼容自由文本 `detail`)。 + * + * @param {object|null|undefined} act + * @returns {string} + */ +export function formatLiveActivityDetail(act) { + if (!act || typeof act !== 'object') return ''; + if (act.detailKey === 'compaction_resuming') { + return t('live.act.compactionResuming'); + } + return String(act.detail || ''); +} diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index a392bff..ff3e439 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -523,4 +523,87 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.resetConfirmBtn': 'Click Again to Confirm', 'settings.oth.resettingBtn': 'Resetting…', 'settings.oth.resetAllDone': 'All preferences restored to defaults', + + // Structured Live Activity Actions + 'live.act.run_command': 'Run Command', + 'live.act.read_file': 'Read File', + 'live.act.edit_file': 'Edit File', + 'live.act.write_file': 'Write File', + 'live.act.grep_search': 'Search Code', + 'live.act.find_file': 'Find Files', + 'live.act.read_url': 'Read Web Page', + 'live.act.search_web': 'Search Web', + 'live.act.invoke_subagent': 'Invoke Subagent', + 'live.act.send_message': 'Message Subagent', + 'live.act.manage_subagents': 'Manage Subagents', + 'live.act.manage_task': 'Manage Task', + 'live.act.schedule': 'Schedule Task', + 'live.act.ask_question': 'Waiting for User Choice', + 'live.act.search_marketplace': 'Search Plugins', + 'live.act.mcp_tool': 'Call MCP Tool', + 'live.act.tool_call': 'Call Tool', + 'live.act.thinking': 'Thinking', + 'live.act.compacting': 'Compacting Context', + 'live.act.responding': 'Responding', + 'live.act.waiting_subagent': 'Waiting for Subagent', + 'live.act.starting': 'Starting', + 'live.act.done': 'Completed', + 'live.act.awaitingApproval': 'Awaiting Approval · {label}', + 'live.act.compactionResuming': 'Compaction finished, resuming reasoning', + + // SVG Charts (SessionStepCharts & TrendAreaChart) + 'chart.step.empty': 'No plottable steps in current scope', + 'chart.step.excluded': 'Excluded', + 'chart.step.zeroSteps': '0 steps', + 'chart.step.stepAdd': 'Step +{tokens}', + 'chart.step.ioSplit': 'In {inTok} · Cache {cacheTok} · Out {outTok}', + 'chart.step.cacheShort': 'Cache {pct}%', + 'chart.step.compactionCheckpoint': 'Auto-compaction checkpoint', + 'chart.step.cacheHitOut': 'Cache hit {pct}% · Out +{outTok}', + 'chart.step.ttftShort': 'TTFT {sec}s', + 'chart.step.outAndCtx': 'Out {outTok} · Context {ctxTok}', + 'chart.step.compactionStep': 'Compaction step', + 'chart.step.noSpeedSample': 'No speed sample', + 'chart.step.ctxAndCache': 'Context {ctxTok} · Cache {pct}%', + 'chart.step.noTtftSample': 'No TTFT sample', + 'chart.step.cumCost': 'Total {cost}', + 'chart.step.cacheAndStepTok': 'Cache {pct}% · Step {tokens}', + 'chart.step.noSamples': 'No samples', + 'chart.step.peakShort': 'Peak {val}', + 'chart.step.peakPill': 'Peak {tag} · {val}', + 'chart.step.stepsCount': '{count} steps', + 'chart.step.multiPrefix': '{count} models · ', + 'chart.step.sumTokens': '{prefix}Total {tokens}', + 'chart.step.peakTokens': '{prefix}Peak {tokens}', + 'chart.step.currentCtx': 'Current {tokens}', + 'chart.step.meanTps': '{prefix}Avg {val} tok/s', + 'chart.step.meanSec': '{prefix}Avg {val}s', + 'chart.step.noValidSamples': 'No valid samples', + 'chart.step.sumCost': '{prefix}Total {cost}', + 'chart.fit.empty': 'No valid regression samples for this model', + 'chart.fit.loess': 'LOESS Fit', + 'chart.fit.olsLinear': 'OLS Linear', + 'chart.fit.olsReg': 'OLS Reg', + 'chart.fit.observed': 'Observed', + 'chart.fit.tipFit': 'Fit {val}', + 'chart.fit.tipObs': 'Obs {val}', + 'chart.fit.zeroSamples': '0 samples', + 'chart.fit.peerMean': '{label} Avg {val}', + 'chart.fit.peerCompare': 'Compare: {peers}', + 'chart.fit.curvesCount': '{count} fit curves', + 'chart.fit.multiBadge': '{steps} steps · {models} models', + 'chart.fit.singleBadge': '{steps} steps · Avg {mean}', + 'chart.fit.olsTitle': 'OLS: y = {slope}x + {intercept} · Sample SD = ±{sd}', + 'chart.trend.hmMonthYear': "{month}/{yy}", + 'chart.trend.hmMonthOnly': 'M{month}', + 'chart.trend.wdayMon': 'M', + 'chart.trend.wdayWed': 'W', + 'chart.trend.wdayFri': 'F', + 'chart.trend.wdaySun': 'S', + 'chart.trend.hmAria': 'Daily usage heatmap', + 'chart.trend.hmLess': 'Less', + 'chart.trend.hmMore': 'More', + 'chart.trend.hmActivePeak': 'Active {active}/{total}d · Peak {label} · {tokens}', + 'chart.trend.hmActiveZero': 'Active 0/{total}d', + 'chart.trend.peakPill': 'Peak {label} · {tokens}', }); diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 3c443a8..28ff4d7 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -523,4 +523,87 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.resetConfirmBtn': '再次点击确认重置', 'settings.oth.resettingBtn': '重置中…', 'settings.oth.resetAllDone': '已恢复全部默认设置', + + // Structured Live Activity Actions + 'live.act.run_command': '执行命令', + 'live.act.read_file': '读取文件', + 'live.act.edit_file': '修改文件', + 'live.act.write_file': '写入文件', + 'live.act.grep_search': '搜索代码', + 'live.act.find_file': '查找文件', + 'live.act.read_url': '读取网页', + 'live.act.search_web': '网页搜索', + 'live.act.invoke_subagent': '调用子代理', + 'live.act.send_message': '通信子代理', + 'live.act.manage_subagents': '管理子代理', + 'live.act.manage_task': '后台任务', + 'live.act.schedule': '定时任务', + 'live.act.ask_question': '等待用户选择', + 'live.act.search_marketplace': '查询插件', + 'live.act.mcp_tool': '调用 MCP', + 'live.act.tool_call': '调用工具', + 'live.act.thinking': '推理中', + 'live.act.compacting': '上下文压缩', + 'live.act.responding': '正在输出回复', + 'live.act.waiting_subagent': '等待子代理', + 'live.act.starting': '启动中', + 'live.act.done': '已完成', + 'live.act.awaitingApproval': '等待确认 · {label}', + 'live.act.compactionResuming': '已完成压缩,正在恢复推理', + + // SVG Charts (SessionStepCharts & TrendAreaChart) + 'chart.step.empty': '当前范围暂无可绘制的调用步骤', + 'chart.step.excluded': '未纳入', + 'chart.step.zeroSteps': '0 步', + 'chart.step.stepAdd': '本步 +{tokens}', + 'chart.step.ioSplit': '入 {inTok} · 缓 {cacheTok} · 出 {outTok}', + 'chart.step.cacheShort': '缓存 {pct}%', + 'chart.step.compactionCheckpoint': '上下文自动压缩检查点', + 'chart.step.cacheHitOut': '缓存命中 {pct}% · 输出 +{outTok}', + 'chart.step.ttftShort': '首字 {sec}s', + 'chart.step.outAndCtx': '输出 {outTok} · 上下文 {ctxTok}', + 'chart.step.compactionStep': '上下文压缩步', + 'chart.step.noSpeedSample': '无测速样本', + 'chart.step.ctxAndCache': '上下文 {ctxTok} · 缓存 {pct}%', + 'chart.step.noTtftSample': '无首字计时样本', + 'chart.step.cumCost': '累计 {cost}', + 'chart.step.cacheAndStepTok': '缓存 {pct}% · 本步 {tokens}', + 'chart.step.noSamples': '无样本', + 'chart.step.peakShort': '峰 {val}', + 'chart.step.peakPill': '峰值 {tag} · {val}', + 'chart.step.stepsCount': '{count}步', + 'chart.step.multiPrefix': '{count} 模型 · ', + 'chart.step.sumTokens': '{prefix}累计 {tokens}', + 'chart.step.peakTokens': '{prefix}峰值 {tokens}', + 'chart.step.currentCtx': '当前 {tokens}', + 'chart.step.meanTps': '{prefix}均值 {val} tok/s', + 'chart.step.meanSec': '{prefix}均值 {val}s', + 'chart.step.noValidSamples': '暂无有效样本', + 'chart.step.sumCost': '{prefix}累计 {cost}', + 'chart.fit.empty': '该模型暂无有效拟合样本', + 'chart.fit.loess': 'LOESS 拟合', + 'chart.fit.olsLinear': 'OLS 线性', + 'chart.fit.olsReg': 'OLS 回归', + 'chart.fit.observed': '观测值', + 'chart.fit.tipFit': '拟合 {val}', + 'chart.fit.tipObs': '观测 {val}', + 'chart.fit.zeroSamples': '0 样本', + 'chart.fit.peerMean': '{label} 均 {val}', + 'chart.fit.peerCompare': '同图对比:{peers}', + 'chart.fit.curvesCount': '{count} 条拟合线', + 'chart.fit.multiBadge': '{steps}步 · {models} 模型对比', + 'chart.fit.singleBadge': '{steps}步 · 均 {mean}', + 'chart.fit.olsTitle': 'OLS: y = {slope}x + {intercept} · 样本标准差 SD = ±{sd}', + 'chart.trend.hmMonthYear': '{yy}年{month}月', + 'chart.trend.hmMonthOnly': '{month}月', + 'chart.trend.wdayMon': '一', + 'chart.trend.wdayWed': '三', + 'chart.trend.wdayFri': '五', + 'chart.trend.wdaySun': '日', + 'chart.trend.hmAria': '每日用量热力格子图', + 'chart.trend.hmLess': '少', + 'chart.trend.hmMore': '多', + 'chart.trend.hmActivePeak': '活跃 {active}/{total} 天 · 峰值 {label} · {tokens}', + 'chart.trend.hmActiveZero': '活跃 0/{total} 天', + 'chart.trend.peakPill': '峰值 {label} · {tokens}', }); diff --git a/sidecars/panel/src/registries/metricRegistry.js b/sidecars/panel/src/registries/metricRegistry.js index 438cf1f..9e70df0 100644 --- a/sidecars/panel/src/registries/metricRegistry.js +++ b/sidecars/panel/src/registries/metricRegistry.js @@ -6,6 +6,7 @@ */ import { + formatAgentBadgeText, formatCachePct, formatMetric, formatTokens, @@ -345,15 +346,16 @@ export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumf }; } -function translateRawAgentBadge(rawBadge) { - if (!rawBadge) return ''; - if (!isEnglishLocale()) return String(rawBadge); - const str = String(rawBadge).trim(); - if (str === '主') return t('fmt.mainBadge'); - const m = str.match(/^子(\d+)$/); - if (m) return t('fmt.subBadge', { index: m[1] }); - if (str === '子') return t('fmt.subBadgeShort'); - return str; +function resolveActiveBadgeText(active) { + if (!active?.activeAgentBadge && !active?.activeAgentKind) return ''; + return formatAgentBadgeText({ + agentKind: + active.activeAgentKind || + (!active.activeAgentId || active.activeAgentId === 'main' ? 'main' : 'subagent'), + agentOrdinal: Number(active.activeAgentOrdinal || 0), + isMain: !active.activeAgentId || active.activeAgentId === 'main', + badgeText: active.activeAgentBadge, + }); } /** @@ -375,7 +377,7 @@ export function resolveOverviewMetricCell(metricKey, cellCtx = {}) { fallback: t('fmt.unknownModel'), }).text; const reason = speedReasonText(active.latestSpeedReason); - const badgeStr = translateRawAgentBadge(active.activeAgentBadge); + const badgeStr = resolveActiveBadgeText(active); const modelAndAgent = hasSubagents && badgeStr ? `[${badgeStr}] ${activeModelDisplay}` : activeModelDisplay; const hasSpeed = Number.isFinite(active.latestTokPerSec) && Number(active.latestTokPerSec) > 0; diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index 15f5901..7f59d6c 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -5,7 +5,14 @@ import { createReactiveStore } from '../core/reactive.js'; import { callSidecarApi, getWindowBridgeConfig, isWindowOverlayMode } from '../core/httpClient.js'; -import { isEnglishLocale, normalizeI18nLanguage, t } from '../i18n/index.js'; +import { + formatAgentBadgeText, + formatAgentLabel, + formatLiveActivityDetail, + formatLiveActivityLabel, + getAgentBadgeClass, +} from '../core/formatters.js'; +import { normalizeI18nLanguage, t } from '../i18n/index.js'; import { normalizeClientFontScale, normalizeClientThemeAccent } from '../core/appearance.js'; import { DEFAULT_HOVER_MODULES, @@ -1053,101 +1060,13 @@ export function stopAsyncTelemetryLoop() { } } -/** - * 根据代理索引返回对应的微边框语义徽章样式类名。 - * - * @param {number} [index=0] - * @param {boolean} [isMain=false] - * @returns {string} - */ -export function getAgentBadgeClass(index = 0, isMain = false) { - if (isMain || index <= 0) return 'badge-main'; - const slot = ((index - 1) % 3) + 1; - return `badge-sub-${slot}`; -} - -/** - * 格式化主/子代理的紧凑短徽章文本(中文如 `主` / `子1`,英文如 `Main` / `S1`)。 - * - * @param {object|null|undefined} agent - * @returns {string} - */ -export function formatAgentBadgeText(agent) { - const isSideQ = Boolean( - agent?.isSideQuestion || - agent?.typeName === 'side_question' || - /^旁\d*$/.test(String(agent?.badgeText || '')) - ); - if (!isEnglishLocale()) { - if (!agent || agent.isMain) return agent?.badgeText || '主'; - if (isSideQ) { - const sIdx = Number(agent.sideIndex || 0); - return agent.badgeText || (sIdx > 0 ? `旁${sIdx}` : '旁'); - } - return agent.badgeText || `子${agent.index || ''}`; - } - if (!agent || agent.isMain) return t('fmt.mainBadge'); - if (isSideQ) { - const m = String(agent.badgeText || '').match(/^旁(\d+)$/); - const sIdx = Number(agent.sideIndex || (m ? m[1] : 0)); - return sIdx > 0 ? t('fmt.sideBadge', { index: sIdx }) : t('fmt.sideBadgeShort'); - } - const subMatch = String(agent.badgeText || '').match(/^子(\d+)$/); - const subOrd = Number(subMatch ? subMatch[1] : agent.index || 0); - return subOrd > 0 ? t('fmt.subBadge', { index: subOrd }) : t('fmt.subBadgeShort'); -} - -/** - * 格式化主/子代理或旁路提问的完整显示名称(如 `子代理 #1 · Codebase Researcher` / `旁路提问 #1 · ...`)。 - * - * @param {object|null|undefined} agent - * @returns {string} - */ -export function formatAgentLabel(agent) { - const isSideQ = Boolean( - agent?.isSideQuestion || - agent?.typeName === 'side_question' || - /^旁/.test(String(agent?.badgeText || agent?.shortLabel || '')) - ); - if (!isEnglishLocale()) { - if (!agent) return '主代理'; - if (agent.isMain) return agent.shortLabel || '主代理'; - if (isSideQ) { - const sIdx = Number(agent.sideIndex || 0); - const fallbackShort = sIdx > 0 ? `旁路提问 #${sIdx}` : '旁路提问'; - const rolePart = - agent.role && - agent.role !== '旁路提问' && - agent.role !== 'Side Question' && - agent.role !== agent.shortLabel - ? ` · ${agent.role}` - : ''; - return `${agent.shortLabel || fallbackShort}${rolePart}`; - } - const rolePart = agent.role && agent.role !== '子代理' ? ` · ${agent.role}` : ''; - return `${agent.shortLabel || '子代理'}${rolePart}`; - } - if (!agent || agent.isMain) return t('fmt.mainAgent'); - if (isSideQ) { - const m = String(agent.shortLabel || agent.badgeText || '').match(/(\d+)/); - const sIdx = Number(agent.sideIndex || (m ? m[1] : 0)); - const baseLabel = sIdx > 0 ? `${t('fmt.sideQuestion')} #${sIdx}` : t('fmt.sideQuestion'); - const rolePart = - agent.role && - agent.role !== '旁路提问' && - agent.role !== 'Side Question' && - agent.role !== agent.shortLabel - ? ` · ${agent.role}` - : ''; - return `${baseLabel}${rolePart}`; - } - const subMatch = String(agent.shortLabel || agent.badgeText || '').match(/(\d+)/); - const idx = Number(subMatch ? subMatch[1] : agent.index || 0); - const baseLabel = idx > 0 ? `${t('fmt.subAgent')} #${idx}` : t('fmt.subAgent'); - const rolePart = - agent.role && agent.role !== '子代理' && agent.role !== 'Subagent' ? ` · ${agent.role}` : ''; - return `${baseLabel}${rolePart}`; -} +export { + formatAgentBadgeText, + formatAgentLabel, + formatLiveActivityDetail, + formatLiveActivityLabel, + getAgentBadgeClass, +}; /** * 解析当前选中的主/子代理作用域视图数据与独立上下文窗口检视目标。 diff --git a/sidecars/panel/src/views/StepsDetailView.js b/sidecars/panel/src/views/StepsDetailView.js index f62c822..a3479fe 100644 --- a/sidecars/panel/src/views/StepsDetailView.js +++ b/sidecars/panel/src/views/StepsDetailView.js @@ -435,17 +435,20 @@ export const StepsDetailView = defineComponent({ let isDirty = false; function resolveDefaultActiveModelKey(scopedConv, chronoSteps, models, availableModelKeys) { - const activeCand = getStepModelGroupKey({ - modelLabel: scopedConv?.activeModelLabel, - modelShort: scopedConv?.activeModelShort, - }); - if ( - activeCand && - activeCand !== '模型未知' && - activeCand !== t('fmt.unknownModel') && - availableModelKeys.has(activeCand) - ) { - return activeCand; + if (scopedConv?.hasKnownModel !== false) { + const activeCand = getStepModelGroupKey({ + baseModelLabel: scopedConv?.activeBaseModelLabel, + baseModelShort: scopedConv?.activeBaseModelShort, + modelLabel: scopedConv?.activeModelLabel, + modelShort: scopedConv?.activeModelShort, + }); + if ( + activeCand && + activeCand !== t('fmt.unknownModel') && + availableModelKeys.has(activeCand) + ) { + return activeCand; + } } for (let i = chronoSteps.length - 1; i >= 0; i--) { const st = chronoSteps[i]; @@ -625,7 +628,7 @@ export const StepsDetailView = defineComponent({ if (!stepModelOptionMap.has(gk)) { const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk }); stepModelOptionMap.set(gk, { - label: disp.text.replace(/·(?:压缩|Compact)\s*$/iu, '').trim() || gk, + label: disp.baseText || disp.text || gk, calls: 0, }); } @@ -656,7 +659,7 @@ export const StepsDetailView = defineComponent({ }); perModelOptions.push({ value: gk, - label: disp.text.replace(/·(?:压缩|Compact)\s*$/iu, '').trim() || gk, + label: disp.baseText || disp.text || gk, meta: t('header.convMetaSteps', { count: Number(m.calls || 0) }), }); } diff --git a/sidecars/panel/test/backend-harness.mjs b/sidecars/panel/test/backend-harness.mjs index 0dcf522..cf1deec 100644 --- a/sidecars/panel/test/backend-harness.mjs +++ b/sidecars/panel/test/backend-harness.mjs @@ -26,6 +26,8 @@ const BACKEND_MODULE_FILES = [ '../backend/http-helpers.mjs', '../backend/settings-schema.mjs', '../backend/config.mjs', + '../backend/sqlite-client.mjs', + '../backend/proto-wire.mjs', '../backend/cli-sqlite-reader.mjs', '../backend/cli-statusline-config.mjs', '../backend/ls-discovery.mjs', diff --git a/sidecars/panel/test/cross-module-regressions.test.mjs b/sidecars/panel/test/cross-module-regressions.test.mjs index d468345..5c97c58 100644 --- a/sidecars/panel/test/cross-module-regressions.test.mjs +++ b/sidecars/panel/test/cross-module-regressions.test.mjs @@ -1183,3 +1183,195 @@ test('P1 audit fixes: shared third-party pool & route single-source, pure frozen assert.equal(appJs.includes('SettingsAccountTab.js'), false); assert.equal(appJs.includes('function renderQuotaRows('), false); }); + +test('P2 audit fixes: standalone sqlite/proto-wire primitives, structured liveActivity/agent/media i18n, full en-US SVG charts, controlled LiveActivityWidget reuse, and shared Mock DOM', async () => { + // 1. Standalone sqlite-client & proto-wire primitives (zero config/metrics imports) + const sqliteClientSrc = fs.readFileSync( + new URL('../backend/sqlite-client.mjs', import.meta.url), + 'utf8' + ); + const protoWireSrc = fs.readFileSync( + new URL('../backend/proto-wire.mjs', import.meta.url), + 'utf8' + ); + assert.doesNotMatch(sqliteClientSrc, /config\.mjs|trajectory-metrics\.mjs/); + assert.doesNotMatch(protoWireSrc, /config\.mjs|trajectory-metrics\.mjs/); + + const protoWire = await import('../backend/proto-wire.mjs'); + assert.equal(protoWire.unescapePbtxtString('\\344\\275\\240\\345\\245\\275'), '你好'); + const varState = { off: 0 }; + assert.equal(protoWire.readProtoVarint(new Uint8Array([0xac, 0x02]), varState), 300n); + + // 2. Bilingual dictionary 100% key parity + const { I18N_MESSAGES_ZH_CN } = await import('../src/i18n/zh-CN.js'); + const { I18N_MESSAGES_EN_US } = await import('../src/i18n/en-US.js'); + const zhKeys = Object.keys(I18N_MESSAGES_ZH_CN).sort(); + const enKeys = Object.keys(I18N_MESSAGES_EN_US).sort(); + assert.deepEqual(enKeys, zhKeys); + + // 3. Structured liveActivity, agent badges/labels, turn media, and en-US SVG charts (zero Chinese leakage) + const { createMockDom } = await import('./mock-dom.mjs'); + const prevDoc = globalThis.document; + const prevWin = globalThis.window; + const { document: mockDoc } = createMockDom(); + globalThis.document = mockDoc; + globalThis.window = { + innerWidth: 1280, + innerHeight: 800, + devicePixelRatio: 1, + document: mockDoc, + addEventListener() {}, + removeEventListener() {}, + getComputedStyle: () => ({ getPropertyValue: () => '' }), + }; + + try { + const { setI18nLanguage } = await import('../src/i18n/index.js'); + const { + formatAgentBadgeText, + formatAgentLabel, + formatLiveActivityDetail, + formatLiveActivityLabel, + } = await import('../src/core/formatters.js'); + const { formatTurnPromptText } = await import('../src/components/widgets/StepTableWidget.js'); + const { LiveActivityWidget } = await import('../src/components/widgets/LiveActivityWidget.js'); + const { buildCapsuleSlotContext } = await import('../src/components/widgets/CapsuleBarWidget.js'); + const { createModelFitChart, createSessionLineChart } = await import( + '../src/components/charts/SessionStepCharts.js' + ); + const { createTrendAreaChart } = await import('../src/components/charts/TrendAreaChart.js'); + + const waitCmdAct = extractLiveActivity( + [ + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + plannerResponse: { + toolCalls: [{ name: 'run_command', argumentsJson: '{"CommandLine":"npm test"}' }], + }, + }, + { type: 'CORTEX_STEP_TYPE_RUN_COMMAND', status: 'CORTEX_STEP_STATUS_WAITING' }, + ], + true + ); + assert.equal(waitCmdAct?.actionKey, 'run_command'); + assert.equal(waitCmdAct?.waitingApproval, true); + + setI18nLanguage('en-US'); + assert.equal(formatLiveActivityLabel(waitCmdAct), 'Awaiting Approval · Run Command'); + assert.equal( + formatLiveActivityDetail({ detailKey: 'compaction_resuming' }), + 'Compaction finished, resuming reasoning' + ); + assert.equal( + formatAgentBadgeText({ agentKind: 'side_question', agentOrdinal: 2 }), + 'Q2' + ); + assert.equal( + formatAgentLabel({ agentKind: 'subagent', agentOrdinal: 1, customRole: 'Auditor' }), + 'Subagent #1 · Auditor' + ); + assert.equal( + formatTurnPromptText('Check image', { hasMedia: true, mediaOnly: false }), + 'Check image [Media]' + ); + assert.equal(formatTurnPromptText('', { hasMedia: true, mediaOnly: true }), '[Media Attachment]'); + + // Controlled LiveActivityWidget auto-expands running subagents and renders session extras + let selectedCid = ''; + const controlledLive = LiveActivityWidget({ + defaultExpandRunningSubs: true, + showSessionExtras: true, + onSelectSession: (cid) => { + selectedCid = cid; + }, + }); + controlledLive.refs.update({ + hostRouteConversationId: 'conv-en-ctrl', + items: [ + { + cascadeId: 'conv-en-ctrl', + title: 'Controlled Multi Panel', + isMainRunning: true, + isRunning: true, + latestTokPerSec: 82.4, + contextUsedPct: 44, + mainActivity: waitCmdAct, + subagentCount: 1, + runningSubagentCount: 1, + subagents: [ + { + cascadeId: 'sub-ctrl-1', + index: 1, + agentKind: 'subagent', + agentOrdinal: 1, + customRole: 'Verifier', + isRunning: true, + stepCount: 2, + liveActivity: { + phase: 'compacting', + actionKey: 'compacting', + detailKey: 'compaction_resuming', + signature: 'cp:1', + }, + }, + ], + }, + ], + }); + assert.equal(controlledLive.el.querySelector('.live-sub-list').hasAttribute('hidden'), false); + assert.equal(controlledLive.el.querySelector('.wm-session-tag.is-here').hasAttribute('hidden'), false); + assert.equal(controlledLive.el.querySelector('.wm-task-metrics').textContent, '82.4 t/s · 44%'); + assert.equal(/[\u4e00-\u9fff]/.test(controlledLive.el.textContent), false); + controlledLive.el.querySelector('.live-task-title').onclick({}); + assert.equal(selectedCid, 'conv-en-ctrl'); + controlledLive.refs.stopLiveTicker(); + + // SVG charts in en-US emit zero Chinese characters + const sampleSteps = Array.from({ length: 6 }, (_, i) => ({ + stepIndex: i + 1, + baseModelLabel: 'Gemini 4 Carbon', + baseModelShort: 'carbon-4', + tokPerSec: 70 + i * 4, + ttftSec: 1.1, + cacheHitPct: 88, + inputTokens: 1000, + cacheReadTokens: 8000, + outputTokens: 300, + contextTokens: 12000, + costUsd: 0.01, + })); + const lineChart = createSessionLineChart(); + const lineRes = lineChart.update({ steps: sampleSteps, metric: 'tps' }); + assert.equal(/[\u4e00-\u9fff]/.test(lineRes.summaryBadge), false); + assert.equal(/[\u4e00-\u9fff]/.test(lineChart.el.textContent), false); + lineChart.destroy(); + + const fitChart = createModelFitChart(); + const fitRes = fitChart.update({ steps: sampleSteps, metric: 'tps' }); + assert.equal(/[\u4e00-\u9fff]/.test(fitRes.summaryBadge), false); + assert.equal(/[\u4e00-\u9fff]/.test(fitChart.el.textContent), false); + fitChart.destroy(); + + const trendChart = createTrendAreaChart(); + const hmSlots = Array.from({ length: 95 }, (_, i) => { + const iso = new Date(Date.UTC(2026, 6, 1 + i)).toISOString().slice(0, 10); + return { dateKey: iso, label: iso.slice(5), fullLabel: iso, tokens: (i + 1) * 500, calls: 2, costUsd: 0.02 }; + }); + trendChart.update(hmSlots); + assert.equal(/[\u4e00-\u9fff]/.test(trendChart.el.textContent), false); + trendChart.destroy(); + + const slotCtx = buildCapsuleSlotContext( + { activeConversation: { isRunning: true, stepCount: 2, latestTokPerSec: 64.5, context: { totalTokens: 64000, limitTokens: 256000 } } }, + {} + ); + assert.equal(slotCtx.usedPct, 25); + assert.equal(slotCtx.tps, 64.5); + + setI18nLanguage('zh-CN'); + } finally { + globalThis.document = prevDoc; + globalThis.window = prevWin; + } +}); diff --git a/sidecars/panel/test/mock-dom.mjs b/sidecars/panel/test/mock-dom.mjs new file mode 100644 index 0000000..77b7233 --- /dev/null +++ b/sidecars/panel/test/mock-dom.mjs @@ -0,0 +1,548 @@ +/** + * @fileoverview Shared lightweight W3C-compatible Mock DOM for Node `vm` UI & overlay tests. + * Replaces 6 separate copy-pasted inline mock DOM classes across `window-bridge.test.mjs`. + */ + +const ATTR_TOKEN_RE = /\[\s*([a-zA-Z0-9_:-]+)\s*(?:([*^$~|]?=)\s*(?:"([^"]*)"|'([^']*)'|([^\]]*)))?\s*\]/g; + +function matchCompoundSelector(node, rawCompound) { + if (!node || !node.tagName || String(node.tagName).startsWith('#')) return false; + let rem = String(rawCompound || '').trim(); + if (!rem) return false; + if (rem === '*') return true; + + // Match attribute clauses `[attr]`, `[attr="v"]`, `[attr^="v"]`, `[attr*="v"]`, `[attr$="v"]` + const attrs = []; + rem = rem.replace(ATTR_TOKEN_RE, (_m, name, op, dq, sq, bare) => { + attrs.push({ name, op: op || '', val: dq ?? sq ?? (bare ? bare.trim() : '') }); + return ''; + }); + + for (const a of attrs) { + if (!a.op) { + if (!node.hasAttribute(a.name)) return false; + continue; + } + const actual = node.getAttribute(a.name); + if (actual === null || actual === undefined) return false; + const str = String(actual); + if (a.op === '=' && str !== a.val) return false; + if (a.op === '^=' && !str.startsWith(a.val)) return false; + if (a.op === '*=' && !str.includes(a.val)) return false; + if (a.op === '$=' && !str.endsWith(a.val)) return false; + if (a.op === '~=' && !str.split(/\s+/).includes(a.val)) return false; + } + + // Extract `#id` and `.class` tokens + let idReq = ''; + const classReqs = []; + rem = rem.replace(/#([a-zA-Z0-9_-]+)/g, (_m, id) => { + idReq = id; + return ''; + }); + rem = rem.replace(/\.([a-zA-Z0-9_@/-]+)/g, (_m, cls) => { + classReqs.push(cls); + return ''; + }); + + if (idReq && node.id !== idReq) return false; + for (const cls of classReqs) { + if (!node.classList.contains(cls)) return false; + } + + const tag = rem.trim(); + if (tag && node.tagName.toLowerCase() !== tag.toLowerCase()) return false; + return true; +} + +function splitTopLevelCommas(selector) { + const out = []; + let depth = 0; + let quote = ''; + let start = 0; + const s = String(selector || ''); + for (let i = 0; i < s.length; i++) { + const ch = s[i]; + if (quote) { + if (ch === quote && s[i - 1] !== '\\') quote = ''; + continue; + } + if (ch === '"' || ch === "'") { + quote = ch; + } else if (ch === '[') { + depth++; + } else if (ch === ']') { + depth = Math.max(0, depth - 1); + } else if (ch === ',' && depth === 0) { + const part = s.slice(start, i).trim(); + if (part) out.push(part); + start = i + 1; + } + } + const tail = s.slice(start).trim(); + if (tail) out.push(tail); + return out; +} + +function tokenizeCombinators(singleSelector) { + const tokens = []; + let depth = 0; + let quote = ''; + let buf = ''; + let pendingDirect = false; + const s = String(singleSelector || '').trim(); + for (let i = 0; i < s.length; i++) { + const ch = s[i]; + if (quote) { + buf += ch; + if (ch === quote && s[i - 1] !== '\\') quote = ''; + continue; + } + if (ch === '"' || ch === "'") { + quote = ch; + buf += ch; + continue; + } + if (ch === '[') { + depth++; + buf += ch; + continue; + } + if (ch === ']') { + depth = Math.max(0, depth - 1); + buf += ch; + continue; + } + if (depth === 0 && (ch === '>' || /\s/.test(ch))) { + if (buf) { + tokens.push({ compound: buf, combinator: pendingDirect ? '>' : ' ' }); + buf = ''; + pendingDirect = false; + } + if (ch === '>') pendingDirect = true; + continue; + } + buf += ch; + } + if (buf) { + tokens.push({ compound: buf, combinator: pendingDirect ? '>' : ' ' }); + } + return tokens; +} + +function matchChainFromScope(node, scopeRoot, tokens, idx) { + const step = tokens[idx]; + if (step.compound === ':scope') { + return node === scopeRoot; + } + if (!matchCompoundSelector(node, step.compound)) return false; + if (idx === 0) return true; + + if (step.combinator === '>') { + const p = node.parentNode; + if (!p) return false; + return matchChainFromScope(p, scopeRoot, tokens, idx - 1); + } + + let p = node.parentNode; + while (p) { + if (matchChainFromScope(p, scopeRoot, tokens, idx - 1)) return true; + if (p === scopeRoot) break; + p = p.parentNode; + } + return false; +} + +export class MockMutationObserver { + constructor(cb, registry = null) { + this.cb = cb; + this.targets = []; + if (Array.isArray(registry)) registry.push(this); + } + observe(target, options) { + this.targets.push({ target, options }); + } + disconnect() { + this.targets = []; + } +} + +export class MockDomNode { + constructor(tag = 'div', rect = null, domOptions = null) { + this._domOptions = domOptions || null; + this.tagName = String(tag || 'div').toUpperCase(); + this.nodeName = this.tagName; + this.nodeType = this.tagName === '#TEXT' ? 3 : 1; + this.id = ''; + this.value = ''; + this._text = ''; + this._rect = null; + this._ownRect = rect || null; + this.offsetWidth = 0; + this.offsetHeight = 0; + this.clientWidth = 0; + this.scrollWidth = 0; + this.dataset = {}; + this.attributes = new Map(); + this._classes = new Set(); + this.children = []; + this.parentNode = null; + this.shadowRoot = null; + this._listeners = new Map(); + + const styleVars = new Map(); + this.style = { + width: '', + height: '', + maxHeight: '', + marginLeft: '', + top: '', + left: '', + right: '', + display: '', + visibility: '', + opacity: '', + _vars: styleVars, + setProperty(k, v) { + const s = String(v ?? ''); + styleVars.set(k, s); + this[k] = s; + }, + getPropertyValue(k) { + return styleVars.get(k) || this[k] || ''; + }, + removeProperty(k) { + styleVars.delete(k); + delete this[k]; + }, + }; + + const self = this; + this.classList = { + add(...tokens) { + for (const t of tokens) if (t) self._classes.add(t); + self._syncClassAttr(); + }, + remove(...tokens) { + for (const t of tokens) self._classes.delete(t); + self._syncClassAttr(); + }, + contains(tok) { + return self._classes.has(tok); + }, + toggle(tok, force) { + const should = force === undefined ? !self._classes.has(tok) : Boolean(force); + if (should) self._classes.add(tok); + else self._classes.delete(tok); + self._syncClassAttr(); + return should; + }, + }; + } + + _syncClassAttr() { + const joined = [...this._classes].join(' '); + if (joined) this.attributes.set('class', joined); + else this.attributes.delete('class'); + } + + get className() { + return [...this._classes].join(' '); + } + + set className(v) { + this._classes.clear(); + for (const part of String(v || '').split(/\s+/)) { + if (part) this._classes.add(part); + } + this._syncClassAttr(); + } + + get textContent() { + if (this.children.length === 0) return this._text; + return this._text + this.children.map((c) => c.textContent ?? '').join(''); + } + + set textContent(v) { + for (const c of this.children) { + if (c) c.parentNode = null; + } + this.children = []; + this._text = String(v ?? ''); + } + + get parentElement() { + return this.parentNode; + } + + set parentElement(v) { + this.parentNode = v; + } + + get firstChild() { + return this.children[0] || null; + } + + get lastChild() { + return this.children[this.children.length - 1] || null; + } + + get firstElementChild() { + return this.children[0] || null; + } + + get lastElementChild() { + return this.children[this.children.length - 1] || null; + } + + get nextSibling() { + if (!this.parentNode) return null; + const idx = this.parentNode.children.indexOf(this); + return idx >= 0 ? this.parentNode.children[idx + 1] || null : null; + } + + get nextElementSibling() { + return this.nextSibling; + } + + get isConnected() { + let cur = this; + while (cur) { + if (cur.isDocumentRoot) return true; + cur = cur.parentNode || cur.host || null; + } + return false; + } + + setAttribute(k, v) { + const s = String(v); + if (k === 'class') { + this.className = s; + return; + } + this.attributes.set(k, s); + if (k === 'id') this.id = s; + } + + getAttribute(k) { + if (k === 'class') return this.attributes.has('class') ? this.className : null; + return this.attributes.has(k) ? this.attributes.get(k) : null; + } + + hasAttribute(k) { + return this.attributes.has(k); + } + + removeAttribute(k) { + if (k === 'class') { + this._classes.clear(); + } + this.attributes.delete(k); + } + + appendChild(child) { + if (!child) return child; + if (child.parentNode?.removeChild) child.parentNode.removeChild(child); + child.parentNode = this; + this.children.push(child); + return child; + } + + insertBefore(node, refNode) { + if (!refNode) return this.appendChild(node); + if (node.parentNode?.removeChild) node.parentNode.removeChild(node); + const idx = this.children.indexOf(refNode); + node.parentNode = this; + if (idx < 0) this.children.push(node); + else this.children.splice(idx, 0, node); + return node; + } + + removeChild(child) { + const idx = this.children.indexOf(child); + if (idx >= 0) { + this.children.splice(idx, 1); + child.parentNode = null; + } + return child; + } + + remove() { + if (this.parentNode?.removeChild) this.parentNode.removeChild(this); + } + + attachShadow() { + const sr = new MockDomNode('#shadow-root', null, this._domOptions); + sr.host = this; + this.shadowRoot = sr; + return sr; + } + + contains(other) { + let cur = other; + while (cur) { + if (cur === this) return true; + cur = cur.parentNode; + } + return false; + } + + closest(sel) { + let cur = this; + while (cur && cur.nodeType === 1) { + if (cur.matches(sel)) return cur; + cur = cur.parentNode; + } + return null; + } + + addEventListener(type, fn) { + if (!this._listeners.has(type)) this._listeners.set(type, []); + this._listeners.get(type).push(fn); + } + + removeEventListener(type, fn) { + const arr = this._listeners.get(type); + if (!arr) return; + const idx = arr.indexOf(fn); + if (idx >= 0) arr.splice(idx, 1); + } + + dispatchEvent(ev) { + for (const fn of [...(this._listeners.get(ev.type) || [])]) fn(ev); + } + + setRect(rect) { + this._ownRect = rect; + } + + getBoundingClientRect() { + if (typeof this._domOptions?.resolveRect === 'function') { + const custom = this._domOptions.resolveRect(this); + if (custom) return custom; + } + if (this._ownRect) return this._ownRect; + if (this._rect) return this._rect; + if (this._domOptions?.inheritAncestorRect) { + let cur = this.parentNode || this.host || null; + while (cur) { + if (cur._ownRect) return cur._ownRect; + if (cur._rect) return cur._rect; + cur = cur.parentNode || cur.host || null; + } + } + return ( + this._domOptions?.defaultRect || { + left: 900, + right: 1080, + top: 6, + bottom: 32, + width: 180, + height: 26, + } + ); + } + + matches(selector) { + const groups = splitTopLevelCommas(selector); + if (groups.length === 0) return false; + return groups.some((g) => { + const tokens = tokenizeCombinators(g); + if (tokens.length === 0) return false; + return matchChainFromScope(this, null, tokens, tokens.length - 1); + }); + } + + querySelectorAll(selector) { + const groups = splitTopLevelCommas(selector); + if (groups.length === 0) return []; + const parsedGroups = groups.map(tokenizeCombinators).filter((t) => t.length > 0); + if (parsedGroups.length === 0) return []; + + const out = []; + const walk = (root) => { + for (const child of root.children || []) { + if ( + parsedGroups.some((tokens) => + matchChainFromScope(child, this, tokens, tokens.length - 1) + ) + ) { + out.push(child); + } + walk(child); + } + }; + walk(this); + return out; + } + + querySelector(selector) { + return this.querySelectorAll(selector)[0] || null; + } + + _find(pred) { + for (const c of this.children) { + if (pred(c)) return c; + const hit = c._find?.(pred); + if (hit) return hit; + } + return null; + } +} + +export function createMockDom({ + rootRect = null, + defaultRect = null, + inheritAncestorRect = false, + resolveRect = null, + onCreateElement = null, +} = {}) { + const domOptions = { defaultRect, inheritAncestorRect, resolveRect }; + const makeElement = (tag, rect = null) => { + const node = new MockDomNode(tag, rect, domOptions); + if (typeof onCreateElement === 'function') onCreateElement(node, tag); + return node; + }; + + const docRoot = makeElement('html', rootRect); + docRoot.isDocumentRoot = true; + const head = makeElement('head'); + const body = makeElement('body', rootRect); + docRoot.appendChild(head); + docRoot.appendChild(body); + + const docListeners = new Map(); + const document = { + readyState: 'complete', + hidden: false, + activeElement: null, + documentElement: docRoot, + head, + body, + createElement: (tag) => makeElement(tag), + createElementNS: (_ns, tag) => makeElement(tag), + createTextNode: (txt) => { + const t = new MockDomNode('#text', null, domOptions); + t.textContent = String(txt ?? ''); + return t; + }, + getElementById: (id) => docRoot._find((n) => n.id === id), + querySelector: (sel) => docRoot.querySelector(sel), + querySelectorAll: (sel) => docRoot.querySelectorAll(sel), + addEventListener(type, fn) { + if (!docListeners.has(type)) docListeners.set(type, []); + docListeners.get(type).push(fn); + }, + removeEventListener(type, fn) { + const arr = docListeners.get(type); + if (!arr) return; + const idx = arr.indexOf(fn); + if (idx >= 0) arr.splice(idx, 1); + }, + dispatchEvent(ev) { + for (const fn of [...(docListeners.get(ev.type) || [])]) fn(ev); + }, + }; + + return { docRoot, head, body, document, docListeners, makeElement }; +} diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index 6da67df..13a8208 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -6,6 +6,7 @@ import http from 'node:http'; import os from 'node:os'; import path from 'node:path'; import vm from 'node:vm'; +import { MockMutationObserver, createMockDom } from './mock-dom.mjs'; import { associateIdeIframeRoutes, createWindowBridgeController, @@ -554,197 +555,6 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro const appJs = fs.readFileSync(appJsPath, 'utf8'); const stylesCss = fs.readFileSync(stylesCssPath, 'utf8'); - // Minimal DOM mock supporting ShadowRoot, querySelector, attributes, classes, and composedPath - class MockNode { - constructor(tag = 'div') { - this.tagName = String(tag).toUpperCase(); - this.id = ''; - this.className = ''; - this.textContent = ''; - this.style = { - _vars: new Map(), - setProperty(k, v) { this._vars.set(k, String(v)); }, - getPropertyValue(k) { return this._vars.get(k) || ''; }, - removeProperty(k) { this._vars.delete(k); }, - }; - this.dataset = {}; - this.attributes = new Map(); - this.children = []; - this.parentNode = null; - this.shadowRoot = null; - this._listeners = new Map(); - const self = this; - this.classList = { - _set() { - return new Set(String(self.className || '').split(/\s+/).filter(Boolean)); - }, - add(...tokens) { - const s = this._set(); - for (const t of tokens) if (t) s.add(t); - self.className = Array.from(s).join(' '); - }, - contains(tok) { - return this._set().has(tok); - }, - toggle(tok, force) { - const s = this._set(); - const should = force === undefined ? !s.has(tok) : Boolean(force); - if (should) s.add(tok); - else s.delete(tok); - self.className = Array.from(s).join(' '); - }, - }; - } - get parentElement() { return this.parentNode; } - get firstChild() { return this.children[0] || null; } - get firstElementChild() { return this.children[0] || null; } - get lastElementChild() { return this.children[this.children.length - 1] || null; } - get nextSibling() { - if (!this.parentNode) return null; - const idx = this.parentNode.children.indexOf(this); - return idx >= 0 ? this.parentNode.children[idx + 1] || null : null; - } - get isConnected() { - let cur = this; - while (cur) { - if (cur.isDocumentRoot) return true; - cur = cur.parentNode || cur.host || null; - } - return false; - } - setAttribute(k, v) { - const s = String(v); - this.attributes.set(k, s); - if (k === 'id') this.id = s; - if (k === 'class') this.className = s; - } - getAttribute(k) { return this.attributes.has(k) ? this.attributes.get(k) : null; } - hasAttribute(k) { return this.attributes.has(k); } - removeAttribute(k) { this.attributes.delete(k); } - appendChild(child) { - if (child.parentNode) child.parentNode.removeChild(child); - child.parentNode = this; - this.children.push(child); - return child; - } - insertBefore(node, refNode) { - if (!refNode) return this.appendChild(node); - if (node.parentNode) node.parentNode.removeChild(node); - const idx = this.children.indexOf(refNode); - node.parentNode = this; - if (idx < 0) this.children.push(node); - else this.children.splice(idx, 0, node); - return node; - } - removeChild(child) { - const idx = this.children.indexOf(child); - if (idx >= 0) { - this.children.splice(idx, 1); - child.parentNode = null; - } - return child; - } - remove() { - if (this.parentNode) this.parentNode.removeChild(this); - } - attachShadow() { - const sr = new MockNode('#shadow-root'); - sr.host = this; - this.shadowRoot = sr; - return sr; - } - contains(other) { - let cur = other; - while (cur) { - if (cur === this) return true; - cur = cur.parentNode; - } - return false; - } - addEventListener(type, fn) { - if (!this._listeners.has(type)) this._listeners.set(type, []); - this._listeners.get(type).push(fn); - } - removeEventListener(type, fn) { - const arr = this._listeners.get(type); - if (!arr) return; - const idx = arr.indexOf(fn); - if (idx >= 0) arr.splice(idx, 1); - } - dispatchEvent(ev) { - for (const fn of [...(this._listeners.get(ev.type) || [])]) fn(ev); - } - getBoundingClientRect() { - return { left: 900, right: 1080, top: 6, bottom: 32, width: 180, height: 26 }; - } - querySelector(sel) { - if (sel === ':scope > div.shrink-0') { - return this.children.find((c) => c.classList.contains('shrink-0')) || null; - } - return this._find((n) => { - if (sel === '[class*="@container/titlebar"]') { - return String(n.className || '').includes('@container/titlebar'); - } - if (sel.startsWith('.')) { - return n.classList.contains(sel.slice(1)); - } - return false; - }); - } - querySelectorAll(sel) { - const s = String(sel || '').trim(); - if (!s || s.includes(',')) return []; - if (s.includes(' ')) { - const [first, ...rest] = s.split(/\s+/); - const roots = this.querySelectorAll(first); - const out = []; - for (const r of roots) { - for (const item of r.querySelectorAll(rest.join(' '))) { - if (!out.includes(item)) out.push(item); - } - } - return out; - } - if (!s.startsWith('.')) return []; - const cls = s.slice(1); - const out = []; - const walk = (node) => { - for (const c of node.children) { - if (c.classList.contains(cls)) out.push(c); - walk(c); - } - }; - walk(this); - return out; - } - _find(pred) { - for (const c of this.children) { - if (pred(c)) return c; - const hit = c._find(pred); - if (hit) return hit; - } - return null; - } - } - - const docRoot = new MockNode('html'); - docRoot.isDocumentRoot = true; - const body = new MockNode('body'); - docRoot.appendChild(body); - - // Build simulated Antigravity titlebar - const titlebar = new MockNode('div'); - titlebar.className = 'flex items-center @container/titlebar'; - const titleLeft = new MockNode('div'); - titleLeft.textContent = 'Chat Title'; - const titleRight = new MockNode('div'); - titleRight.className = 'shrink-0 flex items-center'; - const nativeBtn = new MockNode('button'); - titleRight.appendChild(nativeBtn); - titlebar.appendChild(titleLeft); - titlebar.appendChild(titleRight); - body.appendChild(titlebar); - let reloadCalled = false; let currentBundleVer = 'ver-100'; let currentAccountEmail = 'test@example.com'; @@ -752,43 +562,33 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro const fetchedUrls = []; const fetchedHeaders = []; const createdForms = []; - - const docListeners = new Map(); const winListeners = new Map(); - const mockDocument = { - readyState: 'complete', - hidden: false, - documentElement: docRoot, + const { + docRoot, body, - createElement: (tag) => { - const node = new MockNode(tag); + document: mockDocument, + docListeners, + makeElement, + } = createMockDom({ + defaultRect: { left: 900, right: 1080, top: 6, bottom: 32, width: 180, height: 26 }, + onCreateElement: (node, tag) => { if (tag === 'form') createdForms.push(node); - return node; }, - createElementNS: (_ns, tag) => new MockNode(tag), - createTextNode: (txt) => { - const t = new MockNode('#text'); - t.textContent = String(txt); - return t; - }, - getElementById: (id) => docRoot._find((n) => n.id === id), - querySelector: (sel) => docRoot.querySelector(sel), - querySelectorAll: () => [], - addEventListener(type, fn) { - if (!docListeners.has(type)) docListeners.set(type, []); - docListeners.get(type).push(fn); - }, - removeEventListener(type, fn) { - const arr = docListeners.get(type); - if (!arr) return; - const i = arr.indexOf(fn); - if (i >= 0) arr.splice(i, 1); - }, - dispatchEvent(ev) { - for (const fn of [...(docListeners.get(ev.type) || [])]) fn(ev); - }, - }; + }); + + // Build simulated Antigravity titlebar + const titlebar = makeElement('div'); + titlebar.className = 'flex items-center @container/titlebar'; + const titleLeft = makeElement('div'); + titleLeft.textContent = 'Chat Title'; + const titleRight = makeElement('div'); + titleRight.className = 'shrink-0 flex items-center'; + const nativeBtn = makeElement('button'); + titleRight.appendChild(nativeBtn); + titlebar.appendChild(titleLeft); + titlebar.appendChild(titleRight); + body.appendChild(titlebar); const mockLocation = { pathname: '/c/aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb', @@ -3101,245 +2901,37 @@ test('Compiled app.js in Antigravity IDE workbench.html docks into .part.titleba const appJs = fs.readFileSync(new URL('../app.js', import.meta.url), 'utf8'); const stylesCss = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8'); - class IdeMockNode { - constructor(tag = 'div') { - this.tagName = String(tag).toUpperCase(); - this.id = ''; - this.className = ''; - this.textContent = ''; - this._rect = { left: 0, right: 1440, top: 0, bottom: 35, width: 1440, height: 35 }; - this.dataset = {}; - const vars = new Map(); - this.style = { - marginLeft: '', - top: '', - right: '', - left: '', - maxHeight: '', - _vars: vars, - setProperty(k, v) { - vars.set(k, String(v)); - }, - removeProperty(k) { - vars.delete(k); - }, - getPropertyValue(k) { - return vars.get(k) || ''; - }, - }; - this.attributes = new Map(); - this.children = []; - this.parentNode = null; - this.shadowRoot = null; - this._listeners = new Map(); - const self = this; - this.classList = { - _set() { - return new Set(String(self.className || '').split(/\s+/).filter(Boolean)); - }, - add(...tokens) { - const s = this._set(); - for (const t of tokens) if (t) s.add(t); - self.className = Array.from(s).join(' '); - }, - contains(tok) { - return this._set().has(tok); - }, - toggle(tok, force) { - const s = this._set(); - const should = force === undefined ? !s.has(tok) : Boolean(force); - if (should) s.add(tok); - else s.delete(tok); - self.className = Array.from(s).join(' '); - }, - }; - } - get parentElement() { - return this.parentNode; - } - get firstChild() { - return this.children[0] || null; - } - get firstElementChild() { - return this.children[0] || null; - } - get lastElementChild() { - return this.children[this.children.length - 1] || null; - } - get isConnected() { - let cur = this; - while (cur) { - if (cur.isDocumentRoot) return true; - cur = cur.parentNode || cur.host || null; - } - return false; - } - setAttribute(k, v) { - const s = String(v); - this.attributes.set(k, s); - if (k === 'id') this.id = s; - if (k === 'class') this.className = s; - } - getAttribute(k) { - return this.attributes.has(k) ? this.attributes.get(k) : null; - } - hasAttribute(k) { - return this.attributes.has(k); - } - removeAttribute(k) { - this.attributes.delete(k); - } - appendChild(child) { - if (child.parentNode) child.parentNode.removeChild(child); - child.parentNode = this; - this.children.push(child); - return child; - } - insertBefore(node, refNode) { - if (!refNode) return this.appendChild(node); - if (node.parentNode) node.parentNode.removeChild(node); - const idx = this.children.indexOf(refNode); - node.parentNode = this; - if (idx < 0) this.children.push(node); - else this.children.splice(idx, 0, node); - return node; - } - removeChild(child) { - const idx = this.children.indexOf(child); - if (idx >= 0) { - this.children.splice(idx, 1); - child.parentNode = null; - } - return child; - } - remove() { - if (this.parentNode) this.parentNode.removeChild(this); - } - attachShadow() { - const sr = new IdeMockNode('#shadow-root'); - sr.host = this; - this.shadowRoot = sr; - return sr; - } - contains(other) { - let cur = other; - while (cur) { - if (cur === this) return true; - cur = cur.parentNode; - } - return false; - } - addEventListener(type, fn) { - if (!this._listeners.has(type)) this._listeners.set(type, []); - this._listeners.get(type).push(fn); - } - removeEventListener(type, fn) { - const arr = this._listeners.get(type); - if (!arr) return; - const idx = arr.indexOf(fn); - if (idx >= 0) arr.splice(idx, 1); - } - dispatchEvent(ev) { - for (const fn of [...(this._listeners.get(ev.type) || [])]) fn(ev); - } - getBoundingClientRect() { - if (this._rect) return this._rect; - if (this._ownRect) return this._ownRect; - let cur = this.parentNode || this.host || null; - while (cur) { - if (cur._rect) return cur._rect; - if (cur._ownRect) return cur._ownRect; - cur = cur.parentNode || cur.host || null; - } - return { left: 820, right: 946, top: 810, bottom: 836, width: 126, height: 26 }; - } - matchesNode(sel) { - if (sel === '[class*="@container/titlebar"]') { - return String(this.className || '').includes('@container/titlebar'); - } - if (sel === '[data-testid="conversation-view"][data-cascade-id]') { - return ( - this.getAttribute('data-testid') === 'conversation-view' && - this.hasAttribute('data-cascade-id') - ); - } - if (sel === '[data-testid^="conversation-row-"][data-selected="true"][data-cascade-id]') { - return ( - String(this.getAttribute('data-testid') || '').startsWith('conversation-row-') && - this.getAttribute('data-selected') === 'true' && - this.hasAttribute('data-cascade-id') - ); - } - if (sel.startsWith('.')) { - const classes = sel.slice(1).split('.').filter(Boolean); - return classes.every((c) => this.classList.contains(c)); - } - return false; - } - querySelector(sel) { - if (sel.startsWith(':scope > ')) { - const rest = sel.slice(':scope > '.length).trim(); - if (rest === 'div.shrink-0') { - return this.children.find((c) => c.classList.contains('shrink-0')) || null; - } - return this.children.find((c) => c.matchesNode(rest)) || null; - } - return this._find((n) => n.matchesNode(sel)); - } - querySelectorAll(sel) { - const out = []; - const walk = (node) => { - for (const c of node.children) { - if (c.matchesNode(sel)) out.push(c); - walk(c); - } - }; - walk(this); - return out; - } - _find(pred) { - for (const c of this.children) { - if (pred(c)) return c; - const hit = c._find(pred); - if (hit) return hit; - } - return null; - } - } - - const docRoot = new IdeMockNode('html'); - docRoot.isDocumentRoot = true; - const head = new IdeMockNode('head'); - const body = new IdeMockNode('body'); - docRoot.appendChild(head); - docRoot.appendChild(body); + const { + docRoot, + body, + document: mockDocument, + makeElement: makeIdeNode, + } = createMockDom({ + defaultRect: { left: 0, right: 1440, top: 0, bottom: 35, width: 1440, height: 35 }, + inheritAncestorRect: true, + }); // Build Antigravity IDE .monaco-workbench with BOTH top window .part.titlebar AND inner chat @container/titlebar - const workbench = new IdeMockNode('div'); + const workbench = makeIdeNode('div'); workbench.className = 'monaco-workbench vs-dark'; - const partTitlebar = new IdeMockNode('div'); + const partTitlebar = makeIdeNode('div'); partTitlebar.className = 'part titlebar'; - const tbContainer = new IdeMockNode('div'); + const tbContainer = makeIdeNode('div'); tbContainer.className = 'titlebar-container has-center'; - const tbLeft = new IdeMockNode('div'); + const tbLeft = makeIdeNode('div', { left: 0, right: 60, top: 0, bottom: 35, width: 60, height: 35 }); tbLeft.className = 'titlebar-left'; - tbLeft._rect = { left: 0, right: 60, top: 0, bottom: 35, width: 60, height: 35 }; - const tbCenter = new IdeMockNode('div'); + const tbCenter = makeIdeNode('div', { left: 540, right: 900, top: 0, bottom: 35, width: 360, height: 35 }); tbCenter.className = 'titlebar-center'; - tbCenter._rect = { left: 540, right: 900, top: 0, bottom: 35, width: 360, height: 35 }; - const tbRight = new IdeMockNode('div'); + const tbRight = makeIdeNode('div', { left: 900, right: 1440, top: 0, bottom: 35, width: 540, height: 35 }); tbRight.className = 'titlebar-right'; - tbRight._rect = { left: 900, right: 1440, top: 0, bottom: 35, width: 540, height: 35 }; - const actionToolbar = new IdeMockNode('div'); + const actionToolbar = makeIdeNode('div', { left: 1170, right: 1300, top: 0, bottom: 35, width: 130, height: 35 }); actionToolbar.className = 'action-toolbar-container'; actionToolbar.style.marginLeft = 'auto'; - actionToolbar._rect = { left: 1170, right: 1300, top: 0, bottom: 35, width: 130, height: 35 }; - const winControls = new IdeMockNode('div'); + const winControls = makeIdeNode('div', { left: 1300, right: 1440, top: 0, bottom: 35, width: 140, height: 35 }); winControls.className = 'window-controls-container'; - winControls._rect = { left: 1300, right: 1440, top: 0, bottom: 35, width: 140, height: 35 }; tbRight.appendChild(actionToolbar); tbRight.appendChild(winControls); @@ -3350,15 +2942,15 @@ test('Compiled app.js in Antigravity IDE workbench.html docks into .part.titleba workbench.appendChild(partTitlebar); // Inner chat pane header + conversation view - const innerChatHeader = new IdeMockNode('div'); + const innerChatHeader = makeIdeNode('div'); innerChatHeader.className = 'flex items-center @container/titlebar'; - const innerChatRight = new IdeMockNode('div'); + const innerChatRight = makeIdeNode('div'); innerChatRight.className = 'shrink-0 flex items-center'; - innerChatHeader.appendChild(new IdeMockNode('div')); + innerChatHeader.appendChild(makeIdeNode('div')); innerChatHeader.appendChild(innerChatRight); workbench.appendChild(innerChatHeader); - const convView = new IdeMockNode('div'); + const convView = makeIdeNode('div'); convView.setAttribute('data-testid', 'conversation-view'); convView.setAttribute('data-cascade-id', '12345678-aaaa-bbbb-cccc-1234567890ab'); workbench.appendChild(convView); @@ -3376,41 +2968,12 @@ test('Compiled app.js in Antigravity IDE workbench.html docks into .part.titleba ]); const mutationObservers = []; - class MockMutationObserver { + class IdeMutationObserver extends MockMutationObserver { constructor(cb) { - this.cb = cb; - this.targets = []; - mutationObservers.push(this); - } - observe(target, options) { - this.targets.push({ target, options }); - } - disconnect() { - this.targets = []; + super(cb, mutationObservers); } } - const fetchedUrls = []; - const mockDocument = { - readyState: 'complete', - hidden: false, - activeElement: null, - documentElement: docRoot, - head, - body, - createElement: (tag) => new IdeMockNode(tag), - createElementNS: (_ns, tag) => new IdeMockNode(tag), - createTextNode: (txt) => { - const t = new IdeMockNode('#text'); - t.textContent = String(txt); - return t; - }, - getElementById: (id) => docRoot._find((n) => n.id === id), - querySelector: (sel) => docRoot.querySelector(sel), - querySelectorAll: (sel) => docRoot.querySelectorAll(sel), - addEventListener() {}, - removeEventListener() {}, - }; const mockWindow = { innerWidth: 1440, @@ -3479,7 +3042,7 @@ test('Compiled app.js in Antigravity IDE workbench.html docks into .part.titleba document: mockDocument, location: mockWindow.location, navigator: {}, - MutationObserver: MockMutationObserver, + MutationObserver: IdeMutationObserver, URLSearchParams, AbortController, setTimeout, @@ -3776,261 +3339,65 @@ test('Composer mount mode (输入框挂载) docks capsule immediately left of Au const appJs = fs.readFileSync(new URL('../app.js', import.meta.url), 'utf8'); const stylesCss = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8'); - class ComposerMockNode { - constructor(tag, rect = null) { - this.tagName = String(tag || 'div').toUpperCase(); - this.nodeName = this.tagName; - this.id = ''; - this.className = ''; - this._text = ''; - this._ownRect = rect || null; - this.style = { - marginLeft: '', - top: '', - left: '', - right: '', - height: '', - maxHeight: '', - _vars: new Map(), - setProperty(k, v) { - this._vars.set(k, String(v)); - }, - getPropertyValue(k) { - return this._vars.get(k) || ''; - }, - }; - this.dataset = {}; - this.attributes = new Map(); - this.children = []; - this.parentNode = null; - this.shadowRoot = null; - this._listeners = new Map(); - const self = this; - this.classList = { - _set() { - return new Set(String(self.className || '').split(/\s+/).filter(Boolean)); - }, - add(...tokens) { - const s = this._set(); - for (const t of tokens) if (t) s.add(t); - self.className = Array.from(s).join(' '); - }, - contains(tok) { - return this._set().has(tok); - }, - toggle(tok, force) { - const s = this._set(); - const should = force === undefined ? !s.has(tok) : Boolean(force); - if (should) s.add(tok); - else s.delete(tok); - self.className = Array.from(s).join(' '); - }, - }; - } - get textContent() { - if (this.children.length === 0) return this._text; - return this._text + this.children.map((c) => c.textContent).join(''); - } - set textContent(v) { - this._text = String(v ?? ''); - this.children = []; - } - get parentElement() { - return this.parentNode; - } - get firstChild() { - return this.children[0] || null; - } - get firstElementChild() { - return this.children[0] || null; - } - get lastElementChild() { - return this.children[this.children.length - 1] || null; - } - get nextElementSibling() { - if (!this.parentNode) return null; - const idx = this.parentNode.children.indexOf(this); - return idx >= 0 ? this.parentNode.children[idx + 1] || null : null; - } - get isConnected() { - let cur = this; - while (cur) { - if (cur.isDocumentRoot) return true; - cur = cur.parentNode || cur.host || null; - } - return false; - } - setAttribute(k, v) { - const s = String(v); - this.attributes.set(k, s); - if (k === 'id') this.id = s; - if (k === 'class') this.className = s; - } - getAttribute(k) { - return this.attributes.has(k) ? this.attributes.get(k) : null; - } - hasAttribute(k) { - return this.attributes.has(k); - } - removeAttribute(k) { - this.attributes.delete(k); - } - appendChild(child) { - if (child.parentNode) child.parentNode.removeChild(child); - child.parentNode = this; - this.children.push(child); - return child; - } - insertBefore(node, refNode) { - if (!refNode) return this.appendChild(node); - if (node.parentNode) node.parentNode.removeChild(node); - const idx = this.children.indexOf(refNode); - node.parentNode = this; - if (idx < 0) this.children.push(node); - else this.children.splice(idx, 0, node); - return node; - } - removeChild(child) { - const idx = this.children.indexOf(child); - if (idx >= 0) { - this.children.splice(idx, 1); - child.parentNode = null; - } - return child; - } - remove() { - if (this.parentNode) this.parentNode.removeChild(this); - } - attachShadow() { - const sr = new ComposerMockNode('#shadow-root'); - sr.host = this; - this.shadowRoot = sr; - return sr; - } - contains(other) { - let cur = other; - while (cur) { - if (cur === this) return true; - cur = cur.parentNode; - } - return false; - } - addEventListener(type, fn) { - if (!this._listeners.has(type)) this._listeners.set(type, []); - this._listeners.get(type).push(fn); - } - removeEventListener(type, fn) { - const arr = this._listeners.get(type); - if (!arr) return; - const i = arr.indexOf(fn); - if (i >= 0) arr.splice(i, 1); - } - dispatchEvent(ev) { - for (const fn of [...(this._listeners.get(ev.type) || [])]) fn(ev); - } - getBoundingClientRect() { - if (this._rect) return this._rect; - if (this._ownRect) return this._ownRect; - let cur = this.parentNode || this.host || null; - while (cur) { - if (cur._rect) return cur._rect; - if (cur._ownRect) return cur._ownRect; - cur = cur.parentNode || cur.host || null; - } - return { left: 820, right: 946, top: 810, bottom: 836, width: 126, height: 26 }; - } - _matchesSingle(sel) { - const s = String(sel || '').trim(); - if (!s) return false; - if (s === '[class*="@container/titlebar"]') { - return String(this.className || '').includes('@container/titlebar'); - } - if (s.startsWith('.')) return this.classList.contains(s.slice(1)); - if (s.startsWith('[') && s.endsWith(']')) { - const inner = s.slice(1, -1); - const eqIdx = inner.indexOf('='); - if (eqIdx < 0) return this.hasAttribute(inner); - const attr = inner.slice(0, eqIdx).trim(); - const val = inner.slice(eqIdx + 1).trim().replace(/^['"]|['"]$/g, ''); - return this.getAttribute(attr) === val; - } - return this.tagName.toLowerCase() === s.toLowerCase(); - } - querySelector(sel) { - if (sel === ':scope > div.shrink-0') { - return this.children.find((c) => c.classList.contains('shrink-0')) || null; - } - return this.querySelectorAll(sel)[0] || null; - } - querySelectorAll(sel) { - const s = String(sel || '').trim(); - if (!s) return []; - const out = []; - const walk = (node) => { - for (const c of node.children) { - if (c._matchesSingle(s)) out.push(c); - walk(c); - } - }; - walk(this); - return out; - } - } - - const docRoot = new ComposerMockNode('html', { left: 0, right: 1440, top: 0, bottom: 900, width: 1440, height: 900 }); - docRoot.isDocumentRoot = true; - const body = new ComposerMockNode('body', { left: 0, right: 1440, top: 0, bottom: 900, width: 1440, height: 900 }); - docRoot.appendChild(body); + const { + body, + document: mockDocument, + makeElement: makeCompNode, + } = createMockDom({ + rootRect: { left: 0, right: 1440, top: 0, bottom: 900, width: 1440, height: 900 }, + defaultRect: { left: 820, right: 946, top: 810, bottom: 836, width: 126, height: 26 }, + inheritAncestorRect: true, + }); // 1. Topbar - const titlebar = new ComposerMockNode('div', { left: 0, right: 1440, top: 0, bottom: 38, width: 1440, height: 38 }); + const titlebar = makeCompNode('div', { left: 0, right: 1440, top: 0, bottom: 38, width: 1440, height: 38 }); titlebar.className = 'flex items-center @container/titlebar'; - const titleLeft = new ComposerMockNode('div', { left: 16, right: 220, top: 6, bottom: 32, width: 204, height: 26 }); + const titleLeft = makeCompNode('div', { left: 16, right: 220, top: 6, bottom: 32, width: 204, height: 26 }); titleLeft.textContent = 'Chat Title'; - const titleRight = new ComposerMockNode('div', { left: 1200, right: 1420, top: 6, bottom: 32, width: 220, height: 26 }); + const titleRight = makeCompNode('div', { left: 1200, right: 1420, top: 6, bottom: 32, width: 220, height: 26 }); titleRight.className = 'shrink-0 flex items-center'; - titleRight.appendChild(new ComposerMockNode('button', { left: 1380, right: 1412, top: 6, bottom: 32, width: 32, height: 26 })); + titleRight.appendChild(makeCompNode('button', { left: 1380, right: 1412, top: 6, bottom: 32, width: 32, height: 26 })); titlebar.appendChild(titleLeft); titlebar.appendChild(titleRight); body.appendChild(titlebar); // 2. Chat composer card at bottom: [+] [Gemini 4 Carbon High ^] ... [🛡️ Auto ^] [🎤] [→] - const composerCard = new ComposerMockNode('div', { left: 220, right: 1120, top: 700, bottom: 848, width: 900, height: 148 }); + const composerCard = makeCompNode('div', { left: 220, right: 1120, top: 700, bottom: 848, width: 900, height: 148 }); composerCard.className = 'rounded-2xl border p-3'; - const editorEl = new ComposerMockNode('textarea', { left: 236, right: 1104, top: 712, bottom: 796, width: 868, height: 84 }); + const editorEl = makeCompNode('textarea', { left: 236, right: 1104, top: 712, bottom: 796, width: 868, height: 84 }); editorEl.setAttribute('role', 'textbox'); - const toolbarRow = new ComposerMockNode('div', { left: 236, right: 1104, top: 808, bottom: 838, width: 868, height: 30 }); + const toolbarRow = makeCompNode('div', { left: 236, right: 1104, top: 808, bottom: 838, width: 868, height: 30 }); toolbarRow.className = 'flex items-center justify-between'; - const leftCluster = new ComposerMockNode('div', { left: 236, right: 446, top: 808, bottom: 838, width: 210, height: 30 }); + const leftCluster = makeCompNode('div', { left: 236, right: 446, top: 808, bottom: 838, width: 210, height: 30 }); leftCluster.className = 'flex items-center gap-1'; - const plusBtn = new ComposerMockNode('button', { left: 236, right: 264, top: 810, bottom: 836, width: 28, height: 26 }); + const plusBtn = makeCompNode('button', { left: 236, right: 264, top: 810, bottom: 836, width: 28, height: 26 }); plusBtn.textContent = '+'; - const modelBtn = new ComposerMockNode('button', { left: 270, right: 446, top: 810, bottom: 836, width: 176, height: 26 }); + const modelBtn = makeCompNode('button', { left: 270, right: 446, top: 810, bottom: 836, width: 176, height: 26 }); modelBtn.textContent = 'Gemini 4 Carbon High ^'; leftCluster.appendChild(plusBtn); leftCluster.appendChild(modelBtn); - const rightCluster = new ComposerMockNode('div', { left: 950, right: 1104, top: 808, bottom: 838, width: 154, height: 30 }); + const rightCluster = makeCompNode('div', { left: 950, right: 1104, top: 808, bottom: 838, width: 154, height: 30 }); rightCluster.className = 'flex items-center gap-1.5'; - const autoWrap = new ComposerMockNode('div', { left: 950, right: 1028, top: 810, bottom: 836, width: 78, height: 26 }); + const autoWrap = makeCompNode('div', { left: 950, right: 1028, top: 810, bottom: 836, width: 78, height: 26 }); autoWrap.className = 'relative'; - const autoBtn = new ComposerMockNode('button', { left: 950, right: 1028, top: 810, bottom: 836, width: 78, height: 26 }); - const shieldSvg = new ComposerMockNode('svg'); - const shieldTitle = new ComposerMockNode('title'); + const autoBtn = makeCompNode('button', { left: 950, right: 1028, top: 810, bottom: 836, width: 78, height: 26 }); + const shieldSvg = makeCompNode('svg'); + const shieldTitle = makeCompNode('title'); shieldTitle.textContent = 'Shield Icon'; shieldSvg.appendChild(shieldTitle); - const autoLabel = new ComposerMockNode('span'); + const autoLabel = makeCompNode('span'); autoLabel.textContent = 'Auto'; - const chevronSvg = new ComposerMockNode('svg'); + const chevronSvg = makeCompNode('svg'); autoBtn.appendChild(shieldSvg); autoBtn.appendChild(autoLabel); autoBtn.appendChild(chevronSvg); autoWrap.appendChild(autoBtn); - const micBtn = new ComposerMockNode('button', { left: 1034, right: 1062, top: 810, bottom: 836, width: 28, height: 26 }); + const micBtn = makeCompNode('button', { left: 1034, right: 1062, top: 810, bottom: 836, width: 28, height: 26 }); micBtn.setAttribute('aria-label', 'Voice input'); - const sendBtn = new ComposerMockNode('button', { left: 1068, right: 1100, top: 808, bottom: 838, width: 32, height: 30 }); + const sendBtn = makeCompNode('button', { left: 1068, right: 1100, top: 808, bottom: 838, width: 32, height: 30 }); sendBtn.setAttribute('aria-label', 'Send message'); rightCluster.appendChild(autoWrap); @@ -4056,35 +3423,6 @@ test('Composer mount mode (输入框挂载) docks capsule immediately left of Au topbarCapsuleSlots: ['context', 'tps', 'quota_auto'], }; - const mockDocument = { - readyState: 'complete', - hidden: false, - documentElement: docRoot, - body, - createElement: (tag) => new ComposerMockNode(tag), - createElementNS: (_ns, tag) => new ComposerMockNode(tag), - createTextNode: (txt) => { - const t = new ComposerMockNode('#text'); - t.textContent = String(txt); - return t; - }, - getElementById: (id) => { - const walk = (n) => { - if (n.id === id) return n; - for (const c of n.children) { - const hit = walk(c); - if (hit) return hit; - } - return null; - }; - return walk(docRoot); - }, - querySelector: (sel) => docRoot.querySelector(sel), - querySelectorAll: (sel) => docRoot.querySelectorAll(sel), - addEventListener() {}, - removeEventListener() {}, - }; - const mockWindow = { innerWidth: 1440, innerHeight: 900, @@ -4274,233 +3612,45 @@ test('Antigravity IDE composer mount mode (输入框挂载) docks inside extensi const appJs = fs.readFileSync(new URL('../app.js', import.meta.url), 'utf8'); const stylesCss = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8'); - class IdeChatMockNode { - constructor(tag = 'div', rect = null) { - this.tagName = String(tag).toUpperCase(); - this.id = ''; - this.className = ''; - this._text = ''; - this._rect = rect || { left: 0, right: 0, top: 0, bottom: 0, width: 0, height: 0 }; - this.dataset = {}; - const vars = new Map(); - this.style = { - display: '', - visibility: '', - opacity: '', - marginLeft: '', - top: '', - right: '', - left: '', - height: '', - maxHeight: '', - setProperty(k, v) { - vars.set(k, String(v)); - }, - removeProperty(k) { - vars.delete(k); - }, - getPropertyValue(k) { - return vars.get(k) || ''; - }, - }; - this.attributes = new Map(); - this.children = []; - this.parentNode = null; - this.shadowRoot = null; - this._listeners = new Map(); - const self = this; - this.classList = { - _set() { - return new Set(String(self.className || '').split(/\s+/).filter(Boolean)); - }, - add(...tokens) { - const s = this._set(); - for (const t of tokens) if (t) s.add(t); - self.className = Array.from(s).join(' '); - }, - contains(tok) { - return this._set().has(tok); - }, - toggle(tok, force) { - const s = this._set(); - const should = force === undefined ? !s.has(tok) : Boolean(force); - if (should) s.add(tok); - else s.delete(tok); - self.className = Array.from(s).join(' '); - }, - }; - } - get textContent() { - if (this.children.length === 0) return this._text; - return this._text + this.children.map((c) => c.textContent).join(''); - } - set textContent(v) { - this._text = String(v ?? ''); - this.children = []; - } - get parentElement() { - return this.parentNode; - } - get firstChild() { - return this.children[0] || null; - } - get firstElementChild() { - return this.children[0] || null; - } - get lastChild() { - return this.children[this.children.length - 1] || null; - } - get lastElementChild() { - return this.children[this.children.length - 1] || null; - } - get nextElementSibling() { - if (!this.parentNode) return null; - const idx = this.parentNode.children.indexOf(this); - return idx >= 0 ? this.parentNode.children[idx + 1] || null : null; - } - get isConnected() { - let cur = this; - while (cur) { - if (cur.isDocumentRoot) return true; - cur = cur.parentNode || cur.host || null; - } - return false; - } - setAttribute(k, v) { - const s = String(v); - this.attributes.set(k, s); - if (k === 'id') this.id = s; - if (k === 'class') this.className = s; - } - getAttribute(k) { - return this.attributes.has(k) ? this.attributes.get(k) : null; - } - hasAttribute(k) { - return this.attributes.has(k); - } - removeAttribute(k) { - this.attributes.delete(k); - } - appendChild(child) { - if (child.parentNode) child.parentNode.removeChild(child); - child.parentNode = this; - this.children.push(child); - return child; - } - insertBefore(node, refNode) { - if (!refNode) return this.appendChild(node); - if (node.parentNode) node.parentNode.removeChild(node); - const idx = this.children.indexOf(refNode); - node.parentNode = this; - if (idx < 0) this.children.push(node); - else this.children.splice(idx, 0, node); - return node; - } - removeChild(child) { - const idx = this.children.indexOf(child); - if (idx >= 0) { - this.children.splice(idx, 1); - child.parentNode = null; - } - return child; - } - remove() { - if (this.parentNode) this.parentNode.removeChild(this); - } - attachShadow() { - const sr = new IdeChatMockNode('#shadow-root'); - sr.host = this; - this.shadowRoot = sr; - return sr; - } - contains(other) { - let cur = other; - while (cur) { - if (cur === this) return true; - cur = cur.parentNode; - } - return false; - } - addEventListener(type, fn) { - if (!this._listeners.has(type)) this._listeners.set(type, []); - this._listeners.get(type).push(fn); - } - removeEventListener(type, fn) { - const arr = this._listeners.get(type); - if (!arr) return; - const i = arr.indexOf(fn); - if (i >= 0) arr.splice(i, 1); - } - dispatchEvent(ev) { - for (const fn of [...(this._listeners.get(ev.type) || [])]) fn(ev); - } - getBoundingClientRect() { - if (this.id === 'ag-usage-monitor-capsule' || this.classList.contains('wm-capsule-btn')) { - return { left: 680, right: 830, top: 824, bottom: 850, width: 150, height: 26 }; - } - return this._rect; - } - matches(sel) { - if (sel === 'button') return this.tagName === 'BUTTON'; - if (sel === 'textarea') return this.tagName === 'TEXTAREA'; - if (sel === '[contenteditable]') return this.hasAttribute('contenteditable'); - if (sel === '[role="button"]') return this.getAttribute('role') === 'button'; - if (sel === '[role="textbox"]') return this.getAttribute('role') === 'textbox'; - if (sel === '[aria-haspopup]') return this.hasAttribute('aria-haspopup'); - if (sel === '[data-lexical-editor]') return this.hasAttribute('data-lexical-editor'); - if (sel.startsWith('.')) return this.classList.contains(sel.slice(1)); - return false; - } - querySelectorAll(sel) { - const parts = sel.split(',').map((s) => s.trim()).filter(Boolean); - const out = []; - const walk = (n) => { - for (const c of n.children) { - if (parts.some((p) => c.matches(p))) out.push(c); - walk(c); - } - }; - walk(this); - return out; - } - querySelector(sel) { - return this.querySelectorAll(sel)[0] || null; - } - } - - const docRoot = new IdeChatMockNode('html', { left: 0, right: 980, top: 0, bottom: 900, width: 980, height: 900 }); - docRoot.isDocumentRoot = true; - const head = new IdeChatMockNode('head'); - const body = new IdeChatMockNode('body', { left: 0, right: 980, top: 0, bottom: 900, width: 980, height: 900 }); - docRoot.appendChild(head); - docRoot.appendChild(body); + const { + body, + document: mockDoc, + makeElement: makeChatNode, + } = createMockDom({ + rootRect: { left: 0, right: 980, top: 0, bottom: 900, width: 980, height: 900 }, + defaultRect: { left: 0, right: 0, top: 0, bottom: 0, width: 0, height: 0 }, + resolveRect: (node) => + node.id === 'ag-usage-monitor-capsule' || node.classList.contains('wm-capsule-btn') + ? { left: 680, right: 830, top: 824, bottom: 850, width: 150, height: 26 } + : null, + }); // Header inside IDE chat pane (must NEVER be docked into inside extensionView iframe!) - const paneHeader = new IdeChatMockNode('header', { left: 0, right: 980, top: 0, bottom: 36, width: 980, height: 36 }); + const paneHeader = makeChatNode('header', { left: 0, right: 980, top: 0, bottom: 36, width: 980, height: 36 }); paneHeader.className = '@container/titlebar flex h-9 w-full items-center justify-between'; body.appendChild(paneHeader); // Antigravity IDE Composer Card: outer role="button" focus wrapper + Lexical/Monaco editor + [+] [Gemini 4 Carbon High ^] ... [->] - const outerFocusCard = new IdeChatMockNode('div', { left: 130, right: 882, top: 770, bottom: 862, width: 752, height: 92 }); + const outerFocusCard = makeChatNode('div', { left: 130, right: 882, top: 770, bottom: 862, width: 752, height: 92 }); outerFocusCard.setAttribute('role', 'button'); - const editorEl = new IdeChatMockNode('div', { left: 146, right: 866, top: 782, bottom: 816, width: 720, height: 34 }); + const editorEl = makeChatNode('div', { left: 146, right: 866, top: 782, bottom: 816, width: 720, height: 34 }); editorEl.setAttribute('contenteditable', 'true'); editorEl.setAttribute('data-lexical-editor', 'true'); - const toolbarRow = new IdeChatMockNode('div', { left: 146, right: 866, top: 822, bottom: 852, width: 720, height: 30 }); + const toolbarRow = makeChatNode('div', { left: 146, right: 866, top: 822, bottom: 852, width: 720, height: 30 }); toolbarRow.className = 'flex items-center justify-between'; - const leftCluster = new IdeChatMockNode('div', { left: 146, right: 340, top: 822, bottom: 852, width: 194, height: 30 }); - const plusBtn = new IdeChatMockNode('button', { left: 146, right: 172, top: 824, bottom: 850, width: 26, height: 26 }); + const leftCluster = makeChatNode('div', { left: 146, right: 340, top: 822, bottom: 852, width: 194, height: 30 }); + const plusBtn = makeChatNode('button', { left: 146, right: 172, top: 824, bottom: 850, width: 26, height: 26 }); plusBtn.textContent = '+'; - const modelBtn = new IdeChatMockNode('div', { left: 178, right: 336, top: 824, bottom: 850, width: 158, height: 26 }); + const modelBtn = makeChatNode('div', { left: 178, right: 336, top: 824, bottom: 850, width: 158, height: 26 }); modelBtn.setAttribute('aria-haspopup', 'menu'); modelBtn.textContent = 'Gemini 4 Carbon High'; leftCluster.appendChild(plusBtn); leftCluster.appendChild(modelBtn); - const rightCluster = new IdeChatMockNode('div', { left: 836, right: 866, top: 822, bottom: 852, width: 30, height: 30 }); - const sendBtn = new IdeChatMockNode('button', { left: 838, right: 866, top: 823, bottom: 851, width: 28, height: 28 }); - const arrowIcon = new IdeChatMockNode('span'); + const rightCluster = makeChatNode('div', { left: 836, right: 866, top: 822, bottom: 852, width: 30, height: 30 }); + const sendBtn = makeChatNode('button', { left: 838, right: 866, top: 823, bottom: 851, width: 28, height: 28 }); + const arrowIcon = makeChatNode('span'); arrowIcon.className = 'codicon codicon-arrow-right'; arrowIcon.textContent = 'arrow_forward'; sendBtn.appendChild(arrowIcon); @@ -4519,36 +3669,6 @@ test('Antigravity IDE composer mount mode (输入框挂载) docks inside extensi topbarCapsuleSlots: ['context', 'tps', 'quota_auto'], }; - const mockDoc = { - readyState: 'complete', - hidden: false, - documentElement: docRoot, - head, - body, - createElement: (tag) => new IdeChatMockNode(tag), - createElementNS: (_ns, tag) => new IdeChatMockNode(tag), - createTextNode: (txt) => { - const t = new IdeChatMockNode('#text'); - t.textContent = String(txt); - return t; - }, - getElementById: (id) => { - const walk = (n) => { - if (n.id === id) return n; - for (const c of n.children) { - const hit = walk(c); - if (hit) return hit; - } - return null; - }; - return walk(docRoot); - }, - querySelector: (sel) => docRoot.querySelector(sel), - querySelectorAll: (sel) => docRoot.querySelectorAll(sel), - addEventListener() {}, - removeEventListener() {}, - }; - const chatConvId = 'a4206937-54dd-4d4e-a161-813719bf7107'; const buildIdeChatTelemetry = () => ({ uiBundleVersion: 'ver-ide-comp-1', @@ -5449,163 +4569,15 @@ test('v1.5 feedback E2E: sticky bridge port/token across hot-reloads, CDP->HTTP modelBreakdown: [], }); - function makeLiteElem(tag) { - const attrs = new Map(); - const classes = new Set(); - const styleProps = new Map(); - const listeners = new Map(); - let ownText = ''; - const el = { - tagName: String(tag || 'div').toUpperCase(), - nodeType: 1, - id: '', - value: '', - dataset: {}, - children: [], - parentNode: null, - parentElement: null, - shadowRoot: null, - clientWidth: 0, - offsetWidth: 0, - scrollWidth: 0, - get firstChild() { return el.children[0] || null; }, - get lastChild() { return el.children[el.children.length - 1] || null; }, - get textContent() { - if (el.children.length === 0) return ownText; - return el.children.map((c) => c.textContent ?? '').join(''); - }, - set textContent(v) { - el.children = []; - ownText = String(v ?? ''); - }, - style: { - width: '', - height: '', - maxHeight: '', - top: '', - left: '', - right: '', - display: '', - setProperty(k, v) { styleProps.set(k, String(v)); }, - getPropertyValue(k) { return styleProps.get(k) || ''; }, - removeProperty(k) { styleProps.delete(k); }, - }, - classList: { - add(...names) { for (const n of names) if (n) classes.add(n); }, - remove(...names) { for (const n of names) classes.delete(n); }, - toggle(n, force) { - const add = force === undefined ? !classes.has(n) : Boolean(force); - if (add) classes.add(n); else classes.delete(n); - return add; - }, - contains(n) { return classes.has(n); }, - }, - get className() { return [...classes].join(' '); }, - set className(v) { - classes.clear(); - for (const p of String(v || '').split(/\s+/)) if (p) classes.add(p); - }, - setAttribute(k, v) { - attrs.set(k, String(v)); - if (k === 'id') el.id = String(v); - if (k === 'class') el.className = String(v); - }, - getAttribute(k) { return attrs.has(k) ? attrs.get(k) : null; }, - removeAttribute(k) { attrs.delete(k); }, - hasAttribute(k) { return attrs.has(k); }, - appendChild(child) { - if (!child) return child; - if (child.parentNode?.removeChild) child.parentNode.removeChild(child); - child.parentNode = el; - child.parentElement = el; - el.children.push(child); - return child; - }, - insertBefore(child, ref) { - if (!ref) return el.appendChild(child); - if (child.parentNode?.removeChild) child.parentNode.removeChild(child); - const idx = el.children.indexOf(ref); - child.parentNode = el; - child.parentElement = el; - if (idx >= 0) el.children.splice(idx, 0, child); - else el.children.push(child); - return child; - }, - removeChild(child) { - const idx = el.children.indexOf(child); - if (idx >= 0) { - el.children.splice(idx, 1); - child.parentNode = null; - child.parentElement = null; - } - return child; - }, - remove() { - if (el.parentNode?.removeChild) el.parentNode.removeChild(el); - }, - contains(target) { - let cur = target; - while (cur) { - if (cur === el) return true; - cur = cur.parentNode; - } - return false; - }, - attachShadow() { - const sr = makeLiteElem('shadow-root'); - el.shadowRoot = sr; - return sr; - }, - addEventListener(type, fn) { - if (!listeners.has(type)) listeners.set(type, []); - listeners.get(type).push(fn); - }, - removeEventListener() {}, - dispatchEvent(ev) { - for (const fn of listeners.get(ev.type) || []) fn(ev); - }, - getBoundingClientRect() { - const w = Number.parseFloat(el.style.width) || el.offsetWidth || 120; - return { left: 900, right: 900 + w, top: 8, bottom: 36, width: w, height: 28 }; - }, - querySelectorAll(sel) { - const out = []; - const parts = String(sel).trim().split(/\s+/); - const matchesSimple = (node, s) => { - if (s.startsWith('#')) return node.id === s.slice(1); - if (s.startsWith('.')) { - return s.slice(1).split('.').filter(Boolean).every((c) => node.classList.contains(c)); - } - return node.tagName.toLowerCase() === s.toLowerCase(); - }; - const matchesChain = (node, idx) => { - if (!matchesSimple(node, parts[idx])) return false; - if (idx === 0) return true; - let p = node.parentElement; - while (p) { - if (matchesChain(p, idx - 1)) return true; - p = p.parentElement; - } - return false; - }; - const walk = (root) => { - for (const ch of root.children || []) { - if (matchesChain(ch, parts.length - 1)) out.push(ch); - walk(ch); - } - }; - walk(el); - return out; - }, - querySelector(sel) { - return el.querySelectorAll(sel)[0] || null; - }, - }; - return el; - } - - const body = makeLiteElem('body'); - const head = makeLiteElem('head'); + const { + body, + document: mockDoc, + } = createMockDom({ + resolveRect: (el) => { + const w = Number.parseFloat(el.style.width) || el.offsetWidth || 120; + return { left: 900, right: 900 + w, top: 8, bottom: 36, width: w, height: 28 }; + }, + }); let failHttpOnce = false; const mockWin = { innerWidth: 1280, @@ -5632,21 +4604,6 @@ test('v1.5 feedback E2E: sticky bridge port/token across hot-reloads, CDP->HTTP return { ok: true, status: 200, json: async () => buildMockPayload() }; }, }; - const mockDoc = { - hidden: false, - body, - head, - documentElement: makeLiteElem('html'), - activeElement: null, - createElement: (t) => makeLiteElem(t), - createElementNS: (_ns, t) => makeLiteElem(t), - createTextNode: (txt) => ({ nodeType: 3, textContent: String(txt ?? ''), parentNode: null }), - getElementById: (id) => body.children.find((c) => c.id === id) || null, - querySelector: (s) => body.querySelector(s), - querySelectorAll: (s) => body.querySelectorAll(s), - addEventListener() {}, - removeEventListener() {}, - }; const sandbox = { window: mockWin, @@ -5758,134 +4715,13 @@ test('WindowOverlayShell macOS (darwin) adaptation: sets data-os="mac", uses 12p assert.match(stylesCss, /:host\(\.wm-capsule-host\[data-dock="fixed"\]\[data-os="mac"\]\)\s*\{\s*right:\s*12px;/); function runOverlayForPlatform(platformKey, { withTitlebar = false, auxLeft = 0, winWidth = 1280 } = {}) { - function makeNode(tag) { - const attrs = new Map(); - const clsSet = new Set(); - const listeners = new Map(); - let rectOverride = null; - const el = { - tagName: String(tag || 'DIV').toUpperCase(), - id: '', - textContent: '', - dataset: {}, - offsetWidth: 0, - offsetHeight: 0, - clientWidth: 0, - scrollWidth: 0, - parentNode: null, - parentElement: null, - shadowRoot: null, - children: [], - style: { - setProperty(k, v) { this[k] = String(v); }, - removeProperty(k) { delete this[k]; }, - getPropertyValue(k) { return this[k] || ''; }, - }, - get isConnected() { - let cur = el; - while (cur) { - if (cur === body || cur === docEl) return true; - cur = cur.parentNode; - } - return false; - }, - get firstChild() { return el.children[0] || null; }, - get firstElementChild() { return el.children[0] || null; }, - get lastElementChild() { return el.children[el.children.length - 1] || null; }, - get className() { return [...clsSet].join(' '); }, - set className(v) { - clsSet.clear(); - for (const c of String(v || '').split(/\s+/).filter(Boolean)) clsSet.add(c); - attrs.set('class', [...clsSet].join(' ')); - }, - classList: { - add: (...cs) => cs.forEach((c) => c && clsSet.add(c)), - remove: (...cs) => cs.forEach((c) => clsSet.delete(c)), - contains: (c) => clsSet.has(c), - toggle(c, force) { - const on = force !== undefined ? Boolean(force) : !clsSet.has(c); - if (on) clsSet.add(c); - else clsSet.delete(c); - return on; - }, - }, - setAttribute(k, v) { - if (k === 'class') { el.className = v; return; } - attrs.set(k, String(v)); - if (k === 'id') el.id = String(v); - }, - getAttribute: (k) => (k === 'class' ? el.className : attrs.has(k) ? attrs.get(k) : null), - hasAttribute: (k) => attrs.has(k), - removeAttribute: (k) => attrs.delete(k), - appendChild(ch) { - if (!ch) return ch; - if (ch.parentNode?.removeChild) ch.parentNode.removeChild(ch); - ch.parentNode = el; - ch.parentElement = el; - el.children.push(ch); - return ch; - }, - insertBefore(ch, ref) { - if (!ref) return el.appendChild(ch); - if (ch.parentNode?.removeChild) ch.parentNode.removeChild(ch); - ch.parentNode = el; - ch.parentElement = el; - const i = el.children.indexOf(ref); - if (i < 0) el.children.push(ch); - else el.children.splice(i, 0, ch); - return ch; - }, - removeChild(ch) { - const i = el.children.indexOf(ch); - if (i >= 0) { - el.children.splice(i, 1); - ch.parentNode = null; - ch.parentElement = null; - } - return ch; - }, - remove() { if (el.parentNode?.removeChild) el.parentNode.removeChild(el); }, - closest: () => null, - contains(t) { - let cur = t; - while (cur) { if (cur === el) return true; cur = cur.parentNode; } - return false; - }, - attachShadow() { - const sr = makeNode('shadow-root'); - el.shadowRoot = sr; - return sr; - }, - addEventListener(type, fn) { - if (!listeners.has(type)) listeners.set(type, []); - listeners.get(type).push(fn); - }, - removeEventListener() {}, - setRect(r) { rectOverride = r; }, - getBoundingClientRect() { - return rectOverride || { left: 0, right: 64, top: 6, bottom: 34, width: 64, height: 28 }; - }, - querySelectorAll(sel) { - const out = []; - const walk = (n) => { - for (const c of n.children || []) { - if (sel === '[class*="@container/titlebar"]' && c.className.includes('@container/titlebar')) out.push(c); - else if (sel === '[data-testid="toggle-aux-sidebar"]' && c.getAttribute('data-testid') === 'toggle-aux-sidebar') out.push(c); - else if (sel === ':scope > div.shrink-0' && n === el && c.classList.contains('shrink-0')) out.push(c); - walk(c); - } - }; - walk(el); - return out; - }, - querySelector(sel) { return el.querySelectorAll(sel)[0] || null; }, - }; - return el; - } - - const docEl = makeNode('html'); - const body = makeNode('body'); - docEl.appendChild(body); + const { + body, + document: mockDoc, + makeElement: makeNode, + } = createMockDom({ + defaultRect: { left: 0, right: 64, top: 6, bottom: 34, width: 64, height: 28 }, + }); if (withTitlebar) { const tb = makeNode('div'); @@ -5936,20 +4772,6 @@ test('WindowOverlayShell macOS (darwin) adaptation: sets data-os="mac", uses 12p getComputedStyle: () => ({ paddingRight: '8px', getPropertyValue: () => '' }), fetch: async () => ({ ok: true, status: 200, json: async () => payload }), }; - const mockDoc = { - hidden: false, - body, - head: makeNode('head'), - documentElement: docEl, - createElement: makeNode, - createElementNS: (_ns, t) => makeNode(t), - createTextNode: (txt) => ({ nodeType: 3, textContent: String(txt ?? ''), parentNode: null }), - getElementById: (id) => body.children.find((c) => c.id === id) || null, - querySelector: (s) => body.querySelector(s), - querySelectorAll: (s) => body.querySelectorAll(s), - addEventListener() {}, - removeEventListener() {}, - }; const sb = { window: mockWin, document: mockDoc, diff --git a/sidecars/panel/trajectory-metrics.mjs b/sidecars/panel/trajectory-metrics.mjs index 11d411c..58f9c73 100644 --- a/sidecars/panel/trajectory-metrics.mjs +++ b/sidecars/panel/trajectory-metrics.mjs @@ -667,6 +667,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { let turnCounter = 0; let activeTurnIndex = null; let pendingTurnPrompts = []; + let pendingTurnHasMedia = false; let hasUnconsumedTurn = false; const isUserTurnBoundary = (step) => { @@ -678,7 +679,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { return Boolean(step.userInput && typeof step.userInput === 'object'); }; - const extractUserTurnPrompt = (step) => { + const extractUserTurnInfo = (step) => { const ui = step?.userInput; let raw = ''; if (typeof ui?.userResponse === 'string' && ui.userResponse.trim()) { @@ -709,24 +710,35 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { ? step.media : []; const hasMedia = mediaArr.length > 0; - if (!cleaned) { - return hasMedia ? '[图片/附件提问]' : ''; - } - const withMedia = hasMedia ? `${cleaned} [附图]` : cleaned; - return withMedia.length > 180 ? `${withMedia.slice(0, 179)}…` : withMedia; + const cleanText = cleaned.length > 180 ? `${cleaned.slice(0, 179)}…` : cleaned; + const legacyRaw = !cleaned ? (hasMedia ? '[图片/附件提问]' : '') : hasMedia ? `${cleaned} [附图]` : cleaned; + const legacyPrompt = legacyRaw.length > 180 ? `${legacyRaw.slice(0, 179)}…` : legacyRaw; + return { cleanText, legacyPrompt, hasMedia }; }; + let pendingTurnCleanPrompts = []; rawSteps.forEach((s, index) => { if (isUserTurnBoundary(s)) { - const promptText = extractUserTurnPrompt(s); + const { cleanText, legacyPrompt, hasMedia } = extractUserTurnInfo(s); if (!hasUnconsumedTurn) { hasUnconsumedTurn = true; - pendingTurnPrompts = promptText ? [promptText] : []; - } else if ( - promptText && - pendingTurnPrompts[pendingTurnPrompts.length - 1] !== promptText - ) { - pendingTurnPrompts.push(promptText); + pendingTurnPrompts = legacyPrompt ? [legacyPrompt] : []; + pendingTurnCleanPrompts = cleanText ? [cleanText] : []; + pendingTurnHasMedia = hasMedia; + } else { + if ( + legacyPrompt && + pendingTurnPrompts[pendingTurnPrompts.length - 1] !== legacyPrompt + ) { + pendingTurnPrompts.push(legacyPrompt); + } + if ( + cleanText && + pendingTurnCleanPrompts[pendingTurnCleanPrompts.length - 1] !== cleanText + ) { + pendingTurnCleanPrompts.push(cleanText); + } + if (hasMedia) pendingTurnHasMedia = true; } } @@ -738,15 +750,25 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { let stepIsTurnStart = false; let stepTurnPrompt = ''; + let stepTurnPromptClean = ''; + let stepTurnHasMedia = false; + let stepTurnMediaOnly = false; if (hasUnconsumedTurn) { turnCounter += 1; activeTurnIndex = turnCounter; stepIsTurnStart = true; const joinedPrompt = pendingTurnPrompts.join('\n').trim(); + const joinedClean = pendingTurnCleanPrompts.join('\n').trim(); stepTurnPrompt = joinedPrompt.length > 180 ? `${joinedPrompt.slice(0, 179)}…` : joinedPrompt; + stepTurnPromptClean = + joinedClean.length > 180 ? `${joinedClean.slice(0, 179)}…` : joinedClean; + stepTurnHasMedia = pendingTurnHasMedia; + stepTurnMediaOnly = Boolean(pendingTurnHasMedia && !stepTurnPromptClean); hasUnconsumedTurn = false; pendingTurnPrompts = []; + pendingTurnCleanPrompts = []; + pendingTurnHasMedia = false; } const stepIndex = m.sourceTrajectoryStepInfo?.stepIndex ?? index; @@ -917,6 +939,8 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { turnIndex: activeTurnIndex, isTurnStart: stepIsTurnStart, ...(stepIsTurnStart && stepTurnPrompt ? { turnPrompt: stepTurnPrompt } : {}), + ...(stepIsTurnStart && stepTurnPromptClean ? { turnPromptClean: stepTurnPromptClean } : {}), + ...(stepIsTurnStart ? { turnHasMedia: stepTurnHasMedia, turnMediaOnly: stepTurnMediaOnly } : {}), }); }); @@ -1678,6 +1702,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { : summary || cmdSnippet || ''; return { toolName: nameLower, + actionKey: 'run_command', isAskUser: false, label: '执行命令', detail, @@ -1704,6 +1729,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { : ''; return { toolName: nameLower, + actionKey: 'read_file', isAskUser: false, label: '读取文件', detail: file ? `${file}${rangeSuffix}` : '', @@ -1721,6 +1747,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { ); return { toolName: nameLower, + actionKey: 'edit_file', isAskUser: false, label: '修改文件', detail: file || '', @@ -1733,6 +1760,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { ); return { toolName: nameLower, + actionKey: 'write_file', isAskUser: false, label: '写入文件', detail: file || '', @@ -1748,6 +1776,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { : cleanSingleLineSnippet(query, 48) || searchPath || ''; return { toolName: nameLower, + actionKey: 'grep_search', isAskUser: false, label: '搜索代码', detail, @@ -1759,6 +1788,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { const dir = shortBasename(pickField(['SearchDirectory', 'DirectoryPath', 'Path'])); return { toolName: nameLower, + actionKey: 'find_file', isAskUser: false, label: '查找文件', detail: pattern && dir ? `${pattern} (${dir})` : pattern || dir || '', @@ -1770,6 +1800,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { const target = pickField(['query', 'Query', 'Url', 'url']); return { toolName: nameLower, + actionKey: isUrl ? 'read_url' : 'search_web', isAskUser: false, label: isUrl ? '读取网页' : '网页搜索', detail: cleanSingleLineSnippet(target, 52) || '', @@ -1785,6 +1816,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { String(subSpec.typeName || '').trim(); return { toolName: nameLower, + actionKey: 'invoke_subagent', isAskUser: false, label: '调用子代理', detail: role || '', @@ -1795,6 +1827,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { const recipient = pickField(['Recipient', 'recipient']); return { toolName: nameLower, + actionKey: 'send_message', isAskUser: false, label: '通信子代理', detail: recipient ? recipient.slice(0, 8) : '', @@ -1805,6 +1838,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { const subName = pickField(['Name', 'Action', 'action']); return { toolName: nameLower, + actionKey: 'manage_subagents', isAskUser: false, label: '管理子代理', detail: subName || '', @@ -1816,6 +1850,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { const taskId = pickField(['TaskId', 'taskId']); return { toolName: nameLower, + actionKey: 'manage_task', isAskUser: false, label: '后台任务', detail: taskId ? `${action || 'status'} (${taskId})` : action || '', @@ -1827,6 +1862,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { const cron = pickField(['CronExpression']); return { toolName: nameLower, + actionKey: 'schedule', isAskUser: false, label: '定时任务', detail: dur ? `${dur}s` : cron || '', @@ -1843,6 +1879,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { ); return { toolName: nameLower, + actionKey: 'ask_question', isAskUser: true, label: '等待用户选择', detail: cleanSingleLineSnippet(qText, 50) || '', @@ -1854,6 +1891,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { const q = Array.isArray(rawQueries) ? rawQueries.join(', ') : ''; return { toolName: nameLower, + actionKey: 'search_marketplace', isAskUser: false, label: '查询插件', detail: cleanSingleLineSnippet(q, 48) || '', @@ -1864,6 +1902,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { const mcpClean = nameLower.replace(/^mcp[_-]/i, '').replace(/_/g, ' · '); return { toolName: nameLower, + actionKey: 'mcp_tool', isAskUser: false, label: '调用 MCP', detail: mcpClean || '', @@ -1872,6 +1911,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { return { toolName: nameLower || 'tool', + actionKey: 'tool_call', isAskUser: false, label: '调用工具', detail: nameLower || '', @@ -1919,6 +1959,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt const startMs = Math.floor(fallbackStartMs || 0); return { phase: 'thinking', + actionKey: 'thinking', + waitingApproval: false, + detailKey: '', label: '推理中', detail: '', stepProgress: '', @@ -1968,6 +2011,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt if (isCheckpointStep(lastStep)) { return { phase: 'compacting', + actionKey: 'compacting', + waitingApproval: false, + detailKey: '', label: '上下文压缩', detail: '', stepProgress: '', @@ -1989,11 +2035,15 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt const phase = info.isAskUser ? 'waiting' : 'tool'; return { phase, + toolName: info.toolName, + actionKey: info.actionKey, + waitingApproval: false, + detailKey: '', label: info.label, detail: info.detail, stepProgress, startedAtMs: startMs, - signature: `planner-tool:${lastStepId}:${tools.length}:${info.label}:${info.detail}`, + signature: `planner-tool:${lastStepId}:${tools.length}:${info.actionKey}:${info.detail}`, }; } @@ -2001,6 +2051,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt const snippet = cleanSingleLineSnippet(respText, 52, true); return { phase: 'responding', + actionKey: 'responding', + waitingApproval: false, + detailKey: '', label: '正在输出回复', detail: snippet, stepProgress: '', @@ -2013,6 +2066,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt const snippet = cleanSingleLineSnippet(thinkText, 52, true); return { phase: 'thinking', + actionKey: 'thinking', + waitingApproval: false, + detailKey: '', label: '推理中', detail: snippet, stepProgress: '', @@ -2023,6 +2079,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt return { phase: 'thinking', + actionKey: 'thinking', + waitingApproval: false, + detailKey: '', label: '推理中', detail: '', stepProgress: '', @@ -2057,16 +2116,21 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt stepProgress = ''; } const waiting = isWaitingStepStatus(lastStep?.status) || info.isAskUser; + const waitingApproval = Boolean(waiting && !info.isAskUser); const resolvedStartMs = startMs || prevStepEndMs || 0; - const label = waiting && !info.isAskUser ? `等待确认 · ${info.label}` : info.label; + const label = waitingApproval ? `等待确认 · ${info.label}` : info.label; return { phase: waiting ? 'waiting' : 'tool', + toolName: info.toolName, + actionKey: info.actionKey, + waitingApproval, + detailKey: '', label, detail: info.detail, stepProgress, startedAtMs: resolvedStartMs, - signature: `step-run:${lastStepId}:${waiting}:${label}:${stepProgress}:${info.detail}`, + signature: `step-run:${lastStepId}:${waiting}:${info.actionKey}:${stepProgress}:${info.detail}`, }; } @@ -2102,6 +2166,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt Math.floor(fallbackStartMs || 0); return { phase: 'compacting', + actionKey: 'compacting', + waitingApproval: false, + detailKey: cpFinishMs > 0 ? 'compaction_resuming' : '', label: '上下文压缩', detail: cpFinishMs > 0 ? '已完成压缩,正在恢复推理' : '', stepProgress: '', @@ -2144,11 +2211,15 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt return { phase, + toolName: info.toolName, + actionKey: info.actionKey, + waitingApproval: false, + detailKey: '', label: info.label, detail: info.detail, stepProgress, startedAtMs: startMs, - signature: `pending-tool:${plannerStepId}:${completedAfterPlanner}:${info.label}:${stepProgress}:${info.detail}`, + signature: `pending-tool:${plannerStepId}:${completedAfterPlanner}:${info.actionKey}:${stepProgress}:${info.detail}`, }; } @@ -2158,7 +2229,7 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt summarizeToolCall(t, toolStepsAfterPlanner[idx] || lastStep) ); const lastToolInfo = infos[infos.length - 1]; - const allSameLabel = infos.every((x) => x.label === lastToolInfo.label); + const allSameLabel = infos.every((x) => x.actionKey === lastToolInfo.actionKey); const detailsList = infos.map((x) => x.detail).filter(Boolean); const combinedDetail = infos.length > 1 && allSameLabel @@ -2171,11 +2242,15 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt const startMs = getRawStepFinishMs(lastStep) || getRawStepEndMs(lastStep) || 0; return { phase: 'thinking', + toolName: lastToolInfo.toolName, + actionKey: lastToolInfo.actionKey, + waitingApproval: false, + detailKey: '', label: lastToolInfo.label, detail: combinedDetail, stepProgress, startedAtMs: startMs, - signature: `post-tool-think:${lastStepId}:${lastToolInfo.label}:${combinedDetail}`, + signature: `post-tool-think:${lastStepId}:${lastToolInfo.actionKey}:${combinedDetail}`, }; } @@ -2188,11 +2263,15 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt const startMs = getRawStepFinishMs(lastStep) || getRawStepEndMs(lastStep) || 0; return { phase: 'thinking', + toolName: lastInfo.toolName, + actionKey: lastInfo.actionKey, + waitingApproval: false, + detailKey: '', label: lastInfo.label, detail: lastInfo.detail, stepProgress: '', startedAtMs: startMs, - signature: `post-step-tool:${lastStepId}:${lastInfo.label}:${lastInfo.detail}`, + signature: `post-step-tool:${lastStepId}:${lastInfo.actionKey}:${lastInfo.detail}`, }; } } @@ -2208,6 +2287,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt if (snippet) { return { phase: 'responding', + actionKey: 'responding', + waitingApproval: false, + detailKey: '', label: '正在输出回复', detail: snippet, stepProgress: '', @@ -2221,6 +2303,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt if (snippet) { return { phase: 'thinking', + actionKey: 'thinking', + waitingApproval: false, + detailKey: '', label: '推理中', detail: snippet, stepProgress: '', @@ -2236,6 +2321,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt const startMs = getRawStepFinishMs(lastStep) || getRawStepStartMs(lastStep) || 0; return { phase: 'thinking', + actionKey: 'thinking', + waitingApproval: false, + detailKey: '', label: '推理中', detail: '', stepProgress: '',