diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 3beaf73..ffd78c1 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -872,6 +872,18 @@ const SVG_ICON_DEFS = Object.freeze({ { tag: 'rect', attrs: { x: '5.2', y: '5.2', width: '8.3', height: '8.3', rx: '1.3' } }, { tag: 'path', attrs: { d: 'M3.5 10.8H2.8a1.3 1.3 0 0 1-1.3-1.3V3.3A1.3 1.3 0 0 1 2.8 2h6.2a1.3 1.3 0 0 1 1.3 1.3v.7' } }, ], + search: [ + { tag: 'circle', attrs: { cx: '7.2', cy: '7.2', r: '4.5' } }, + { tag: 'path', attrs: { d: 'M10.6 10.6L14 14' } }, + ], + download: [ + { tag: 'path', attrs: { d: 'M8 2.4v7.6M5 7.2L8 10.2l3-3' } }, + { tag: 'path', attrs: { d: 'M2.6 11.4v1.4a1 1 0 0 0 1 1h8.8a1 1 0 0 0 1-1v-1.4' } }, + ], + upload: [ + { tag: 'path', attrs: { d: 'M8 10.2V2.6M5 5.4L8 2.4l3 3' } }, + { tag: 'path', attrs: { d: 'M2.6 11.4v1.4a1 1 0 0 0 1 1h8.8a1 1 0 0 0 1-1v-1.4' } }, + ], grip: [ { tag: 'circle', attrs: { cx: '6', cy: '4', r: '1.05', fill: 'currentColor', stroke: 'none' } }, { tag: 'circle', attrs: { cx: '10', cy: '4', r: '1.05', fill: 'currentColor', stroke: 'none' } }, @@ -1092,6 +1104,10 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'header.statusQuotaCached': '额度缓存', 'header.statusQuotaOffline': '额度离线', 'header.statusLive': '监控中', + 'header.searchSessionPlaceholder': '搜索会话标题或 ID…', + 'select.searchPlaceholder': '输入关键词筛选…', + 'select.noMatches': '没有匹配的选项', + 'select.clearSearch': '清空搜索', // Formatters & Common Labels 'fmt.pending': '待定', @@ -1313,6 +1329,26 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'cons.footOutput': '输出 ', 'cons.footThinking': '思考 ', 'cons.footCalls': '调用 ', + 'cons.rankTabAria': '排行视图切换', + 'cons.rankTabModelsCount': '模型排行 ({count})', + 'cons.rankTabSessions': '会话排行', + 'cons.rankTabSessionsCount': '会话排行 ({count})', + 'cons.topConvsEmpty': '当前时间范围暂无会话消耗记录', + 'cons.topConvsSortAria': '会话排行排序方式', + 'cons.topConvsSortCost': '费用', + 'cons.topConvsSortTokens': 'Token', + 'cons.topConvCacheMeta': '缓存 {pct}%', + 'cons.topConvJumpTip': '点击跳转到该会话调用记录', + 'cons.modelsSortAria': '模型排行排序方式', + 'cons.modelsSortTokens': 'Token', + 'cons.modelsSortCost': '费用', + 'cons.modelsSortSpeed': '均速', + 'cons.modelsSortCalls': '调用', + 'cons.modelUnitCost': '均价 {cost}/1M', + 'cons.speedRelTip': '相对本时段最快模型的均速比例', + 'cons.focusTtft': '首字 {ttft}', + 'cons.focusSpeedMeta': '首字 {ttft} · 缓存 {cache}% · 输出 {out}', + 'cons.focusCallsMeta': '单次均耗 {avgTok} · 费用 {cost}', // Steps Detail View & Step Column Registry 'steps.title': '调用记录', @@ -1397,6 +1433,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'steps.anomalySummaryMeta': '异常 {count} 次({steps} 步)', 'steps.anomalyFilterLabel': '仅看异常 ({count})', 'steps.anomalyFilterAll': '返回全部步骤', + 'steps.sortClickTip': '点击按「{col}」排序', // Step Table Columns (Headers & Option Labels) 'stepCol.step.th': '步序', @@ -1666,6 +1703,13 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.resetConfirmBtn': '再次点击确认重置', 'settings.oth.resettingBtn': '重置中…', 'settings.oth.resetAllDone': '已恢复全部默认设置', + 'settings.oth.backupLabel': '配置备份及恢复', + 'settings.oth.backupDesc': '导出或导入外观、胶囊、列配置等便携偏好 JSON(不含账号凭证)', + 'settings.oth.exportJsonBtn': '导出 JSON', + 'settings.oth.importJsonBtn': '导入 JSON', + 'settings.oth.exportDone': '配置 JSON 已导出', + 'settings.oth.importDone': '已恢复 {count} 项偏好设置', + 'settings.oth.importInvalid': '导入失败:JSON 无效或未包含可识别的偏好项', // Structured Live Activity Actions 'live.act.run_command': '执行命令', @@ -1801,6 +1845,10 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'header.statusQuotaCached': 'Quota Cached', 'header.statusQuotaOffline': 'Quota Offline', 'header.statusLive': 'Monitoring', + 'header.searchSessionPlaceholder': 'Search sessions by title or ID…', + 'select.searchPlaceholder': 'Filter options…', + 'select.noMatches': 'No matching items', + 'select.clearSearch': 'Clear search', // Formatters & Common Labels 'fmt.pending': 'N/A', @@ -2022,6 +2070,26 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'cons.footOutput': 'Out ', 'cons.footThinking': 'Think ', 'cons.footCalls': 'Calls ', + 'cons.rankTabAria': 'Switch ranking view', + 'cons.rankTabModelsCount': 'Models ({count})', + 'cons.rankTabSessions': 'Sessions', + 'cons.rankTabSessionsCount': 'Sessions ({count})', + 'cons.topConvsEmpty': 'No session usage in this range', + 'cons.topConvsSortAria': 'Sort sessions ranking', + 'cons.topConvsSortCost': 'Cost', + 'cons.topConvsSortTokens': 'Tokens', + 'cons.topConvCacheMeta': 'Cache {pct}%', + 'cons.topConvJumpTip': 'Click to inspect this session in Steps', + 'cons.modelsSortAria': 'Sort models ranking', + 'cons.modelsSortTokens': 'Tokens', + 'cons.modelsSortCost': 'Cost', + 'cons.modelsSortSpeed': 'Speed', + 'cons.modelsSortCalls': 'Calls', + 'cons.modelUnitCost': 'Eff. {cost}/1M', + 'cons.speedRelTip': 'Speed relative to fastest model in this range', + 'cons.focusTtft': 'TTFT {ttft}', + 'cons.focusSpeedMeta': 'TTFT {ttft} · Cache {cache}% · Out {out}', + 'cons.focusCallsMeta': 'Avg {avgTok}/call · Cost {cost}', // Steps Detail View & Step Column Registry 'steps.title': 'Step Records', @@ -2106,6 +2174,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'steps.anomalySummaryMeta': '{count} retries/errors ({steps} steps)', 'steps.anomalyFilterLabel': 'Anomalies Only ({count})', 'steps.anomalyFilterAll': 'Show All Steps', + 'steps.sortClickTip': 'Click to sort by {col}', // Step Table Columns (Headers & Option Labels) 'stepCol.step.th': 'Step', @@ -2375,6 +2444,13 @@ 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', + 'settings.oth.backupLabel': 'Preferences Backup & Restore', + 'settings.oth.backupDesc': 'Export or import portable UI, capsule, and table preferences as JSON (excludes credentials)', + 'settings.oth.exportJsonBtn': 'Export JSON', + 'settings.oth.importJsonBtn': 'Import JSON', + 'settings.oth.exportDone': 'Preferences JSON exported', + 'settings.oth.importDone': 'Restored {count} preference settings', + 'settings.oth.importInvalid': 'Import failed: invalid JSON or no recognized settings', // Structured Live Activity Actions 'live.act.run_command': 'Run Command', @@ -4540,6 +4616,228 @@ function buildDeterministicModelColorMap(models = []) { return { formatMetric, formatSpeedMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap }; })(); +// --- src/core/settingsBackup.js --- +const { triggerTextFileDownload, buildExportableSettingsJson, parseImportedSettingsJson } = (() => { +/** + * @fileoverview 偏好设置便携 JSON 备份及恢复工具 (`settingsBackup.js`). + * 仅处理经过白名单归一化的用户界面偏好项,不包含账号凭证及高风险上下文窗口覆盖。 + */ + + +const SETTINGS_BACKUP_SCHEMA = 'antigravity-usage-monitor.settings'; +const MAX_SETTINGS_IMPORT_BYTES = 128 * 1024; + +function sanitizePositiveBudgetNum(val) { + const num = Number(val); + return Number.isFinite(num) && num > 0 ? num : null; +} + +/** + * 在浏览器端通过内存 Blob 触发文件下载(零本地磁盘外部写入)。 + * + * @param {string} filename + * @param {string} content + * @param {string} [mimeType] + * @returns {boolean} + */ +function triggerTextFileDownload( + filename, + content, + mimeType = 'application/json;charset=utf-8' +) { + try { + if ( + typeof Blob === 'undefined' || + typeof URL === 'undefined' || + typeof URL.createObjectURL !== 'function' || + typeof document === 'undefined' + ) { + return false; + } + const blob = new Blob([String(content ?? '')], { type: mimeType }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.setAttribute('href', url); + a.setAttribute('download', String(filename || 'export.json')); + a.style.display = 'none'; + document.body?.appendChild?.(a); + a.click?.(); + a.remove?.(); + setTimeout(() => { + try { + URL.revokeObjectURL(url); + } catch {} + }, 1000); + return true; + } catch { + return false; + } +} + +/** + * 将当前用户偏好设置序列化为跨设备可迁移的安全 JSON 备份文本(仅包含便携偏好项,不包含凭证或高风险覆盖开关)。 + * + * @param {object} [settings={}] + * @returns {string} + */ +function buildExportableSettingsJson(settings = {}) { + const src = settings && typeof settings === 'object' ? settings : {}; + const modelDisplayMode = normalizeModelDisplayMode(src.modelDisplayMode, src.showUpstreamModel); + const modernUi = src.modernUi !== undefined ? normalizeModernUi(src.modernUi) : true; + const payload = { + schema: SETTINGS_BACKUP_SCHEMA, + version: 1, + exportedAt: new Date().toISOString(), + settings: { + language: normalizeLanguageSetting(src.language), + themeAccent: normalizeThemeAccent(src.themeAccent), + fontScale: normalizeFontScale(src.fontScale), + modernUi, + weeklyLimitMode: normalizeWeeklyLimitMode(src.weeklyLimitMode), + weeklyTokenBudget: sanitizePositiveBudgetNum(src.weeklyTokenBudget) ?? 150000000, + weeklyCostBudget: sanitizePositiveBudgetNum(src.weeklyCostBudget) ?? 100, + modelDisplayMode, + showUpstreamModel: modelDisplayMode !== 'short', + orchestratorIdMode: normalizeOrchestratorIdMode(src.orchestratorIdMode), + pluginUpdateMode: normalizePluginUpdateMode(src.pluginUpdateMode, src.autoUpdatePlugin), + windowMountMode: normalizeWindowMountMode(src.windowMountMode, src.enableWindowOverlay), + popoverWidthMode: normalizePopoverWidthMode(src.popoverWidthMode), + popoverWidth: normalizePopoverWidth(src.popoverWidth), + enableCliStatusLine: src.enableCliStatusLine !== false, + standalonePort: normalizeStandalonePort(src.standalonePort), + showTopbarMultiSession: src.showTopbarMultiSession !== false, + topbarCapsuleSlots: normalizeTopbarCapsuleSlots(src.topbarCapsuleSlots), + hoverModules: normalizeHoverModules(src.hoverModules), + overviewModules: normalizeOverviewModules(src.overviewModules), + overviewMetrics: normalizeOverviewMetrics(src.overviewMetrics), + showStepTurnRail: src.showStepTurnRail === true, + showStepAgentBadge: src.showStepAgentBadge !== false, + showStepSpeedColor: src.showStepSpeedColor === true, + stepTokenComboFormat: normalizeStepTokenComboFormat(src.stepTokenComboFormat), + stepTableColumns: normalizeStepTableColumns(src.stepTableColumns), + }, + }; + return `${JSON.stringify(payload, null, 2)}\n`; +} + +/** + * 校验并解析导入的偏好设置 JSON,仅提取并归一化白名单内的便携配置项。 + * + * @param {string} rawText + * @returns {{ ok: true, patch: object, appliedCount: number } | { ok: false, errorCode: string }} + */ +function parseImportedSettingsJson(rawText) { + if (typeof rawText !== 'string' || !rawText.trim() || rawText.length > MAX_SETTINGS_IMPORT_BYTES) { + return { ok: false, errorCode: 'invalid_json' }; + } + let parsed; + try { + parsed = JSON.parse(rawText); + } catch { + return { ok: false, errorCode: 'invalid_json' }; + } + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + return { ok: false, errorCode: 'invalid_json' }; + } + + const hasWrappedSettings = + parsed.settings && typeof parsed.settings === 'object' && !Array.isArray(parsed.settings); + if (parsed.schema !== undefined && parsed.schema !== SETTINGS_BACKUP_SCHEMA) { + return { ok: false, errorCode: 'invalid_schema' }; + } + const src = hasWrappedSettings ? parsed.settings : parsed; + const hasKey = (k) => Object.prototype.hasOwnProperty.call(src, k); + const patch = {}; + + if (hasKey('language')) patch.language = normalizeLanguageSetting(src.language); + if (hasKey('themeAccent')) patch.themeAccent = normalizeThemeAccent(src.themeAccent); + if (hasKey('fontScale')) patch.fontScale = normalizeFontScale(src.fontScale); + if (hasKey('modernUi')) { + const val = normalizeModernUi(src.modernUi); + patch.modernUi = val; + patch.experimentalModernUi = val; + } + if (hasKey('weeklyLimitMode')) { + patch.weeklyLimitMode = normalizeWeeklyLimitMode(src.weeklyLimitMode); + } + if (hasKey('weeklyTokenBudget')) { + const num = sanitizePositiveBudgetNum(src.weeklyTokenBudget); + if (num !== null) patch.weeklyTokenBudget = num; + } + if (hasKey('weeklyCostBudget')) { + const num = sanitizePositiveBudgetNum(src.weeklyCostBudget); + if (num !== null) patch.weeklyCostBudget = num; + } + if (hasKey('modelDisplayMode') || hasKey('showUpstreamModel')) { + const mode = normalizeModelDisplayMode(src.modelDisplayMode, src.showUpstreamModel); + patch.modelDisplayMode = mode; + patch.showUpstreamModel = mode !== 'short'; + } + if (hasKey('orchestratorIdMode')) { + patch.orchestratorIdMode = normalizeOrchestratorIdMode(src.orchestratorIdMode); + } + if (hasKey('pluginUpdateMode') || hasKey('autoUpdatePlugin')) { + const mode = normalizePluginUpdateMode(src.pluginUpdateMode, src.autoUpdatePlugin); + patch.pluginUpdateMode = mode; + patch.autoUpdatePlugin = mode === 'auto'; + } + if (hasKey('windowMountMode') || hasKey('enableWindowOverlay')) { + const mode = normalizeWindowMountMode(src.windowMountMode, src.enableWindowOverlay); + patch.windowMountMode = mode; + patch.enableWindowOverlay = mode !== 'sidebar'; + } + if (hasKey('popoverWidthMode')) { + patch.popoverWidthMode = normalizePopoverWidthMode(src.popoverWidthMode); + } + if (hasKey('popoverWidth')) { + patch.popoverWidth = normalizePopoverWidth(src.popoverWidth); + } + if (hasKey('enableCliStatusLine') && typeof src.enableCliStatusLine === 'boolean') { + patch.enableCliStatusLine = src.enableCliStatusLine; + } + if (hasKey('standalonePort')) { + patch.standalonePort = normalizeStandalonePort(src.standalonePort); + } + if (hasKey('showTopbarMultiSession') && typeof src.showTopbarMultiSession === 'boolean') { + patch.showTopbarMultiSession = src.showTopbarMultiSession; + } + if (hasKey('topbarCapsuleSlots') && Array.isArray(src.topbarCapsuleSlots)) { + patch.topbarCapsuleSlots = normalizeTopbarCapsuleSlots(src.topbarCapsuleSlots); + } + if (hasKey('hoverModules') && Array.isArray(src.hoverModules)) { + patch.hoverModules = normalizeHoverModules(src.hoverModules); + } + if (hasKey('overviewModules') && Array.isArray(src.overviewModules)) { + patch.overviewModules = normalizeOverviewModules(src.overviewModules); + } + if (hasKey('overviewMetrics') && Array.isArray(src.overviewMetrics)) { + patch.overviewMetrics = normalizeOverviewMetrics(src.overviewMetrics); + } + if (hasKey('showStepTurnRail') && typeof src.showStepTurnRail === 'boolean') { + patch.showStepTurnRail = src.showStepTurnRail; + } + if (hasKey('showStepAgentBadge') && typeof src.showStepAgentBadge === 'boolean') { + patch.showStepAgentBadge = src.showStepAgentBadge; + } + if (hasKey('showStepSpeedColor') && typeof src.showStepSpeedColor === 'boolean') { + patch.showStepSpeedColor = src.showStepSpeedColor; + } + if (hasKey('stepTokenComboFormat')) { + patch.stepTokenComboFormat = normalizeStepTokenComboFormat(src.stepTokenComboFormat); + } + if (hasKey('stepTableColumns') && Array.isArray(src.stepTableColumns)) { + patch.stepTableColumns = normalizeStepTableColumns(src.stepTableColumns); + } + + const appliedCount = Object.keys(patch).length; + if (appliedCount === 0) { + return { ok: false, errorCode: 'empty_patch' }; + } + return { ok: true, patch, appliedCount }; +} +return { triggerTextFileDownload, buildExportableSettingsJson, parseImportedSettingsJson }; +})(); + // --- src/core/httpClient.js --- const { abortSidecarApiKey, getWindowBridgeConfig, isWindowOverlayMode, deliverCdpBridgeResponses, callSidecarApi } = (() => { /** @@ -5159,6 +5457,7 @@ function recordConsumptionSliceToCache( account: cons.account, trendSeries: Array.isArray(cons.trendSeries) ? cons.trendSeries : [], sourcesBreakdown: Array.isArray(cons.sourcesBreakdown) ? cons.sourcesBreakdown : [], + topConversations: Array.isArray(cons.topConversations) ? cons.topConversations : [], modelBreakdown: Array.isArray(modelBreakdown) ? modelBreakdown : [], }); } @@ -5176,6 +5475,9 @@ function applyCachedConsumptionSlice(baseTelemetry, cachedEntry, targetRevision account: cachedEntry.account ?? prevCons.account, trendSeries: cachedEntry.trendSeries, sourcesBreakdown: cachedEntry.sourcesBreakdown, + topConversations: Array.isArray(cachedEntry.topConversations) + ? cachedEntry.topConversations + : [], }, modelBreakdown: cachedEntry.modelBreakdown, }; @@ -5652,7 +5954,14 @@ function isEquivalentTelemetry(prev, next) { a[k]?.costUsd !== b[k]?.costUsd || a[k]?.unpricedCalls !== b[k]?.unpricedCalls || a[k]?.totalTokens !== b[k]?.totalTokens || + a[k]?.inputTokens !== b[k]?.inputTokens || + a[k]?.cacheReadTokens !== b[k]?.cacheReadTokens || + a[k]?.thinkingTokens !== b[k]?.thinkingTokens || + a[k]?.responseTokens !== b[k]?.responseTokens || a[k]?.calls !== b[k]?.calls || + (a[k]?.avgTokPerSec ?? null) !== (b[k]?.avgTokPerSec ?? null) || + (a[k]?.avgTtftSec ?? null) !== (b[k]?.avgTtftSec ?? null) || + (a[k]?.cacheHitPct ?? null) !== (b[k]?.cacheHitPct ?? null) || Number(a[k]?.anomalyCount || 0) !== Number(b[k]?.anomalyCount || 0) || Number(a[k]?.anomalySteps || 0) !== Number(b[k]?.anomalySteps || 0) ) { @@ -5668,6 +5977,10 @@ function isEquivalentTelemetry(prev, next) { for (let i = 0; i < pTrend.length; i++) { if ( pTrend[i]?.tokens !== nTrend[i]?.tokens || + pTrend[i]?.inputTokens !== nTrend[i]?.inputTokens || + pTrend[i]?.cacheReadTokens !== nTrend[i]?.cacheReadTokens || + pTrend[i]?.thinkingTokens !== nTrend[i]?.thinkingTokens || + pTrend[i]?.responseTokens !== nTrend[i]?.responseTokens || pTrend[i]?.calls !== nTrend[i]?.calls || pTrend[i]?.label !== nTrend[i]?.label || pTrend[i]?.fullLabel !== nTrend[i]?.fullLabel || @@ -5716,6 +6029,22 @@ function isEquivalentTelemetry(prev, next) { } } + const pTopConvs = prev.consumption?.topConversations || []; + const nTopConvs = next.consumption?.topConversations || []; + if (pTopConvs.length !== nTopConvs.length) return false; + for (let i = 0; i < pTopConvs.length; i++) { + if ( + pTopConvs[i]?.cascadeId !== nTopConvs[i]?.cascadeId || + pTopConvs[i]?.title !== nTopConvs[i]?.title || + pTopConvs[i]?.totalTokens !== nTopConvs[i]?.totalTokens || + pTopConvs[i]?.costUsd !== nTopConvs[i]?.costUsd || + pTopConvs[i]?.calls !== nTopConvs[i]?.calls || + !areModelSlicesEqual(pTopConvs[i]?.models, nTopConvs[i]?.models) + ) { + return false; + } + } + // 8. 比对账号订阅档位与动态多配额池 if ( prev.account?.email !== next.account?.email || @@ -6028,6 +6357,7 @@ async function requestTelemetry(params, force) { account: latestSt.telemetry.consumption.account, trendSeries: latestSt.telemetry.consumption.trendSeries, sourcesBreakdown: latestSt.telemetry.consumption.sourcesBreakdown, + topConversations: latestSt.telemetry.consumption.topConversations, }, modelBreakdown: latestSt.telemetry.modelBreakdown, }; @@ -7107,7 +7437,7 @@ return { TopLongPillNav }; })(); // --- src/components/ui/CustomSelect.js --- -const { CustomSelect } = (() => { +const { filterSelectOptionsByQuery, CustomSelect } = (() => { /** * @fileoverview Bespoke CustomSelect dropdown component replacing native