From 253da45607e68379bb76b1743b459e6b836c6f97 Mon Sep 17 00:00:00 2001 From: hejun01 Date: Thu, 19 Nov 2026 18:06:12 +0800 Subject: [PATCH 1/8] feat(panel): support SSH remote windows with per-endpoint isolation and context window overrides - Add per-endpoint registry and isolated caches (endpoint-registry.mjs, multi-path trajectory-cache-file.mjs) so local and SSH remote windows maintain independent conversations, telemetry, quotas, and consumption analytics (Antigravity SSH) without remote plugin installation - Classify local vs. SSH Desktop targets via two-pass hub port and metadata probing in window-bridge.mjs and ls-discovery.mjs, routing HTTP/CDP requests with authoritative X-Usage-Monitor-Endpoint headers and preventing local data leaks or 503-triggered CDP downgrades - Implement two-tier read-only remote LS RPC transport in ls-rpc.mjs (loopback HTTP/HTTPS with size/wall-clock limits and 60s circuit breaker falling back to stateless same-origin window.fetch / connect-websocket via CDP) - Enable per-endpoint verified context window overrides in SSH Desktop windows (context-windows.mjs, window-bridge.mjs, api-actions.mjs) without double-wrapping window.fetch - Surface an SSH badge in TopSessionHeader, cleanly flush stale requests/queues on endpoint rebind, rebuild app.js/styles.css, and add 13 unit/E2E tests in test/ssh-remote-endpoints.test.mjs (157/157 passing) --- sidecars/panel/app.js | 169 +- sidecars/panel/backend/api-actions.mjs | 169 +- sidecars/panel/backend/context-windows.mjs | 31 +- sidecars/panel/backend/endpoint-registry.mjs | 603 ++++++ sidecars/panel/backend/local-scanner.mjs | 198 +- sidecars/panel/backend/ls-discovery.mjs | 94 + sidecars/panel/backend/ls-rpc.mjs | 326 +++- sidecars/panel/backend/telemetry-builder.mjs | 191 +- .../panel/backend/trajectory-cache-file.mjs | 14 +- sidecars/panel/backend/usage-aggregator.mjs | 65 +- sidecars/panel/backend/window-bridge.mjs | 683 ++++++- sidecars/panel/index.html | 4 +- .../panel/shared/window-bridge-protocol.mjs | 3 + .../src/components/layout/TopSessionHeader.js | 16 +- .../components/layout/WindowOverlayShell.js | 52 +- sidecars/panel/src/core/httpClient.js | 44 +- sidecars/panel/src/store/telemetryStore.js | 63 +- sidecars/panel/src/styles/controls.css | 17 + sidecars/panel/src/styles/modern-ui.css | 1 + sidecars/panel/styles.css | 18 + sidecars/panel/test/backend-harness.mjs | 7 +- .../panel/test/ssh-remote-endpoints.test.mjs | 1637 +++++++++++++++++ 22 files changed, 4095 insertions(+), 310 deletions(-) create mode 100644 sidecars/panel/backend/endpoint-registry.mjs create mode 100644 sidecars/panel/test/ssh-remote-endpoints.test.mjs diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index a512d4d..930c2c4 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -717,9 +717,12 @@ return { THIRD_PARTY_POOL_RE, isThirdPartyPoolText, classifySpeedTier, classifyC })(); // --- shared/window-bridge-protocol.mjs --- -const { WINDOW_BRIDGE_KEY, WINDOW_BRIDGE_ROUTE_KEY, WINDOW_OVERLAY_KEY, CONTEXT_WINDOWS_GLOBAL_KEY, WINDOW_OVERLAY_METHODS, BRIDGE_API_ROUTE_DEFS, BRIDGE_API_PATHS, readInjectedWindowBridge } = (() => { +const { WINDOW_BRIDGE_KEY, WINDOW_BRIDGE_ROUTE_KEY, WINDOW_BRIDGE_ENDPOINT_KEY, WINDOW_BRIDGE_ENDPOINT_HEADER, LOCAL_ENDPOINT_ID, WINDOW_OVERLAY_KEY, CONTEXT_WINDOWS_GLOBAL_KEY, WINDOW_OVERLAY_METHODS, BRIDGE_API_ROUTE_DEFS, BRIDGE_API_PATHS, readInjectedWindowBridge } = (() => { const WINDOW_BRIDGE_KEY = '__AGUsageMonitorBridge'; const WINDOW_BRIDGE_ROUTE_KEY = 'hostRouteCascadeId'; +const WINDOW_BRIDGE_ENDPOINT_KEY = 'endpointId'; +const WINDOW_BRIDGE_ENDPOINT_HEADER = 'X-Usage-Monitor-Endpoint'; +const LOCAL_ENDPOINT_ID = 'local'; const WINDOW_OVERLAY_KEY = '__AGUsageMonitorOverlay'; const CONTEXT_WINDOWS_GLOBAL_KEY = '__AGUsageMonitorContextWindows'; @@ -752,7 +755,7 @@ const BRIDGE_API_PATHS = Object.freeze(BRIDGE_API_ROUTE_DEFS.map((r) => r.path)) function readInjectedWindowBridge() { return typeof window === 'undefined' ? undefined : window[WINDOW_BRIDGE_KEY]; } -return { WINDOW_BRIDGE_KEY, WINDOW_BRIDGE_ROUTE_KEY, WINDOW_OVERLAY_KEY, CONTEXT_WINDOWS_GLOBAL_KEY, WINDOW_OVERLAY_METHODS, BRIDGE_API_ROUTE_DEFS, BRIDGE_API_PATHS, readInjectedWindowBridge }; +return { WINDOW_BRIDGE_KEY, WINDOW_BRIDGE_ROUTE_KEY, WINDOW_BRIDGE_ENDPOINT_KEY, WINDOW_BRIDGE_ENDPOINT_HEADER, LOCAL_ENDPOINT_ID, WINDOW_OVERLAY_KEY, CONTEXT_WINDOWS_GLOBAL_KEY, WINDOW_OVERLAY_METHODS, BRIDGE_API_ROUTE_DEFS, BRIDGE_API_PATHS, readInjectedWindowBridge }; })(); // --- src/icons/svgRegistry.js --- @@ -4543,7 +4546,10 @@ function callViaCdpBridge(bridge, path, { method, body, signal, cdpTimeoutMs }) async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTimeoutMs = 3500 } = {}) { const upperMethod = method.toUpperCase(); - const dedupKey = upperMethod === 'GET' && !abortKey ? path : ''; + const activeEndpointId = + String(getWindowBridgeConfig()?.[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID).trim() || + LOCAL_ENDPOINT_ID; + const dedupKey = upperMethod === 'GET' && !abortKey ? `${activeEndpointId}::${path}` : ''; if (dedupKey && inFlightGets.has(dedupKey)) { return inFlightGets.get(dedupKey); @@ -4561,7 +4567,20 @@ async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTi signal = requestController.signal; } + const ensureEndpointUnchanged = (targetBridge) => { + if (!targetBridge) return; + const currentEndpointId = + String(targetBridge[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID).trim() || + LOCAL_ENDPOINT_ID; + if (currentEndpointId !== activeEndpointId) { + const switchErr = new Error('Bridge endpoint switched'); + switchErr.name = 'AbortError'; + throw switchErr; + } + }; + const execHttpOnce = async (activeBridge) => { + ensureEndpointUnchanged(activeBridge); const sidecar = typeof window !== 'undefined' ? window.sidecar : null; const fetchFn = sidecar?.fetch ? sidecar.fetch.bind(sidecar) @@ -4575,6 +4594,10 @@ async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTi } if (activeBridge) { headers['X-Usage-Monitor-Token'] = activeBridge.token; + const epId = String(activeBridge[WINDOW_BRIDGE_ENDPOINT_KEY] || '').trim(); + if (epId && epId !== LOCAL_ENDPOINT_ID) { + headers[WINDOW_BRIDGE_ENDPOINT_HEADER] = epId; + } } const res = await fetchFn(requestUrl, { method: upperMethod, @@ -4594,7 +4617,10 @@ async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTi throw abortErr; } if (!res.ok) { - throw new Error(data.error || `HTTP ${res.status}`); + const httpErr = new Error(data.error || `HTTP ${res.status}`); + httpErr.httpStatus = res.status; + httpErr.retryable = Boolean(data?.retryable); + throw httpErr; } if (activeBridge) { activeBridge.transportMode = 'http'; @@ -4615,8 +4641,10 @@ async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTi if (signal?.aborted || cdpErr?.name === 'AbortError') { throw cdpErr; } - // 热更新或守护重启期间若 CDP 尚未轮询投递,自动重置回 HTTP 并用最新桥接端口重试一次 + // 热更新或守护重启期间若 CDP 尚未轮询投递,自动重置回 HTTP 并用最新桥接端口重试一次; + // 但若端点已切换(例如本地 <-> SSH),绝不将旧端点请求重放至新端点 const latestBridge = getWindowBridgeConfig() || initialBridge; + ensureEndpointUnchanged(latestBridge); latestBridge.transportMode = 'http'; return execHttpOnce(latestBridge); } @@ -4645,7 +4673,11 @@ async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTi } throw fetchErr; } - // 当宿主环境的 CSP connect-src、混合内容策略或瞬态端口切换阻断直连时,切至带 HTTP 自愈恢复的 CDP 通道 + // 仅在网络/CORS 阻断(无 HTTP 状态码)或桥接令牌失配(403)时切换至 CDP 兜底; + // 业务/初始化状态码(如 503 Remote endpoint initializing、400、500)保持 HTTP 通道等待正常重试。 + if (fetchErr?.httpStatus && fetchErr.httpStatus !== 403) { + throw fetchErr; + } return fallbackViaCdpWithRecovery(bridge); } }; @@ -4700,7 +4732,7 @@ return { getViewTabs, uiStore, getVisibleMonitorView }; })(); // --- src/store/telemetryStore.js --- -const { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform } = (() => { +const { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform } = (() => { /** * @fileoverview Reactive telemetry store with async non-overlapping poll scheduler * and granular slice updates. @@ -4801,6 +4833,7 @@ let activeBundleVersion = 0; let latestRequestSeq = 0; let latestConsumptionReqSeq = 0; let latestConversationSwitchSeq = 0; +let endpointSwitchEpoch = 0; let activeForceCount = 0; let consecutivePollFailures = 0; let inFlightTelemetryPoll = null; @@ -4853,10 +4886,11 @@ function clearConversationViewCache() { function buildConsumptionScopeSig(payload) { if (!payload || typeof payload !== 'object') return ''; + const ep = payload.endpoint || {}; const acct = payload.account || {}; const set = payload.settings || {}; const cloud = payload.cloudStatus || {}; - return `${String(acct.status || '')}|${String(acct.email || acct.name || '').toLowerCase()}|${String(set.weeklyLimitMode || '')}|${String(cloud.catalogVersion || '')}`; + return `${String(ep.id || LOCAL_ENDPOINT_ID)}|${String(acct.status || '')}|${String(acct.email || acct.name || '').toLowerCase()}|${String(set.weeklyLimitMode || '')}|${String(cloud.catalogVersion || '')}`; } function syncConsumptionCacheScope(payload) { @@ -5128,6 +5162,13 @@ function isEquivalentTelemetry(prev, next) { if ((pSet?.fontScale ?? 'md') !== (nSet?.fontScale ?? 'md')) return false; if (Boolean(pSet?.experimentalModernUi) !== Boolean(nSet?.experimentalModernUi)) return false; if ((prev.hostPlatform || '') !== (next.hostPlatform || '')) return false; + if ( + (prev.endpoint?.id || LOCAL_ENDPOINT_ID) !== (next.endpoint?.id || LOCAL_ENDPOINT_ID) || + Boolean(prev.endpoint?.isRemote) !== Boolean(next.endpoint?.isRemote) || + (prev.endpoint?.label || '') !== (next.endpoint?.label || '') + ) { + return false; + } if (Boolean(pSet?.contextWindowRiskAccepted) !== Boolean(nSet?.contextWindowRiskAccepted)) { return false; } @@ -5666,6 +5707,33 @@ function isEquivalentTelemetry(prev, next) { return true; } +function resetTelemetryForEndpointSwitch() { + endpointSwitchEpoch += 1; + latestRequestSeq += 1; + latestConsumptionReqSeq += 1; + latestConversationSwitchSeq += 1; + lastReceivedSteps = null; + inFlightTelemetryPoll = null; + consecutivePollFailures = 0; + consumptionCacheScopeSig = ''; + abortSidecarApiKey('telemetry-poll'); + abortSidecarApiKey('telemetry-force'); + abortSidecarApiKey('consumption-range'); + abortSidecarApiKey('consumption-presets'); + abortSidecarApiKey('conversation-switch'); + clearConsumptionRangeCache(); + clearConversationViewCache(); + if (feedbackTimer) { + clearTimeout(feedbackTimer); + feedbackTimer = null; + } + telemetryStore.setState({ + selectedConversationId: '', + telemetry: null, + syncState: 'idle', + }); +} + async function fetchTelemetry({ force = false } = {}) { if (!force && activeForceCount > 0) { return telemetryStore.getState().telemetry; @@ -5701,11 +5769,17 @@ async function fetchTelemetry({ force = false } = {}) { } const query = params.toString(); const bridge = overlay ? getWindowBridgeConfig() : null; + const endpointId = bridge?.[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID; const existing = inFlightTelemetryPoll; - if (existing?.query === query && existing.port === bridge?.port && existing.token === bridge?.token) { + if ( + existing?.query === query && + existing.port === bridge?.port && + existing.token === bridge?.token && + existing.endpointId === endpointId + ) { return existing.promise; } - const poll = { query, port: bridge?.port, token: bridge?.token, promise: null }; + const poll = { query, port: bridge?.port, token: bridge?.token, endpointId, promise: null }; poll.promise = requestTelemetry(params, false).finally(() => { if (inFlightTelemetryPoll === poll) inFlightTelemetryPoll = null; }); @@ -5892,6 +5966,7 @@ async function fetchConsumptionRangeSlice({ customStartMs = 0, customEndMs = 0, } = {}) { + const reqEpoch = endpointSwitchEpoch; const reqSeq = ++latestConsumptionReqSeq; const targetRange = String(range || 'today'); const current = telemetryStore.getState(); @@ -5910,7 +5985,7 @@ async function fetchConsumptionRangeSlice({ method: 'GET', abortKey: 'consumption-range', }); - if (!payload || typeof payload !== 'object') return null; + if (!payload || typeof payload !== 'object' || reqEpoch !== endpointSwitchEpoch) return null; if (payload.scope === 'consumption' && payload.consumption) { const usageRev = Number(payload.usageRevision ?? payload.consumption.revision ?? 0); @@ -6037,13 +6112,14 @@ async function selectConversation( params.set('stepRevision', cachedSteps?.revision || ''); params.set('scope', 'conversation'); + const reqEpoch = endpointSwitchEpoch; const reqSettingsRev = settingsRevision; try { const payload = await callSidecarApi(`/api/telemetry?${params}`, { method: 'GET', abortKey: 'conversation-switch', }); - if (!payload || typeof payload !== 'object') return null; + if (!payload || typeof payload !== 'object' || reqEpoch !== endpointSwitchEpoch) return null; if (switchSeq !== latestConversationSwitchSeq) return payload; const latestSt = telemetryStore.getState(); @@ -6202,11 +6278,13 @@ function prefetchConsumptionPresets() { if (effectiveConvId) params.set('conversationId', effectiveConvId); params.set('scope', 'consumption-presets'); + const reqEpoch = endpointSwitchEpoch; const task = callSidecarApi(`/api/telemetry?${params}`, { method: 'GET', abortKey: 'consumption-presets', }) .then((payload) => { + if (reqEpoch !== endpointSwitchEpoch) return false; if (payload?.scope === 'consumption-presets' && payload.ranges && typeof payload.ranges === 'object') { const rev = Number(payload.usageRevision || currentRev || 0); for (const [rangeKey, entry] of Object.entries(payload.ranges)) { @@ -6772,7 +6850,7 @@ function isMacHostPlatform(telemetry) { } return false; } -return { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform }; +return { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform }; })(); // --- src/components/ui/TopLongPillNav.js --- @@ -20966,6 +21044,12 @@ const TopSessionHeader = defineComponent({ [updateBtnIcon, updateBtnText] ); + const sshBadge = h('span', { + className: 'endpoint-ssh-badge', + hidden: true, + text: 'SSH', + }); + const statusIcon = createSvgIcon('pulse', { size: 12 }); const statusText = h('span', { text: t('header.statusLive') }); const statusTag = h('span', { className: 'status-tag' }, [statusIcon, statusText]); @@ -20983,7 +21067,7 @@ const TopSessionHeader = defineComponent({ const headerRowEl = h('div', { className: 'session-header' }, [ h('div', { className: 'session-left' }, [convSelect.el]), - h('div', { className: 'session-right' }, [updateBtn, statusTag, refreshBtn]), + h('div', { className: 'session-right' }, [sshBadge, updateBtn, statusTag, refreshBtn]), ]); const headerEl = h('header', { className: 'top-session-stack' }, [headerRowEl]); @@ -21052,6 +21136,14 @@ const TopSessionHeader = defineComponent({ patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate')); patchAttr(refreshBtn, 'aria-label', t('header.ariaRefresh')); + const ep = telemetry?.endpoint; + const isRemoteEndpoint = Boolean(ep?.isRemote); + patchAttr(sshBadge, 'hidden', !isRemoteEndpoint); + if (isRemoteEndpoint) { + const epLabel = String(ep?.label || 'SSH').trim(); + patchAttr(sshBadge, 'title', epLabel && epLabel !== 'SSH' ? `SSH · ${epLabel}` : 'SSH'); + } + const actConv = telemetry?.activeConversation; const convs = telemetry?.conversations || []; const hostRouteId = telSt.hostRouteConversationId || ''; @@ -25497,10 +25589,18 @@ function mountWindowOverlay() { const bridgeConfig = getWindowBridgeConfig(); const bundleVersion = String(bridgeConfig?.bundleVersion || ''); const stylesCss = String(bridgeConfig?.stylesCss || ''); + const activeBridgeEndpointId = String( + bridgeConfig?.[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID + ); + const reusableCarryOver = + carryOverTelemetry && + String(carryOverTelemetry?.endpoint?.id || LOCAL_ENDPOINT_ID) === activeBridgeEndpointId + ? carryOverTelemetry + : null; const seedTelemetry = (bridgeConfig?.initialTelemetry && typeof bridgeConfig.initialTelemetry === 'object' ? bridgeConfig.initialTelemetry - : null) || carryOverTelemetry; + : null) || reusableCarryOver; if (bridgeConfig?.initialTelemetry) { delete bridgeConfig.initialTelemetry; } @@ -27280,14 +27380,49 @@ function mountWindowOverlay() { const token = String(nextBridge.token || ''); if (!Number.isInteger(port) || port <= 0 || !token) return false; const cur = readInjectedWindowBridge() || {}; + const prevEndpointId = String(cur[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID); + const nextEndpointId = + nextBridge[WINDOW_BRIDGE_ENDPOINT_KEY] !== undefined + ? String(nextBridge[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID) + : prevEndpointId; const portChanged = Number(cur.port || 0) !== port || String(cur.token || '') !== token; + const endpointChanged = prevEndpointId !== nextEndpointId; cur.port = port; cur.token = token; - if (portChanged) { + cur[WINDOW_BRIDGE_ENDPOINT_KEY] = nextEndpointId; + if (nextBridge.isRemoteEndpoint !== undefined) { + cur.isRemoteEndpoint = Boolean(nextBridge.isRemoteEndpoint); + } + if (nextBridge.endpointLabel !== undefined) { + cur.endpointLabel = String(nextBridge.endpointLabel || ''); + } + if (portChanged || endpointChanged) { cur.transportMode = 'http'; } + if (endpointChanged) { + if (Array.isArray(cur.rpcQueue)) { + cur.rpcQueue.length = 0; + } + if (cur.rpcPending instanceof Map) { + for (const pending of cur.rpcPending.values()) { + try { + const switchErr = new Error('Bridge endpoint switched'); + switchErr.name = 'AbortError'; + pending?.reject?.(switchErr); + } catch { + // 忽略旧端点回调异常 + } + } + cur.rpcPending.clear(); + } + } window[WINDOW_BRIDGE_KEY] = cur; - void fetchTelemetry({ force: false }); + if (endpointChanged) { + resetTelemetryForEndpointSwitch(); + void fetchTelemetry({ force: true }); + } else { + void fetchTelemetry({ force: false }); + } return true; }, getTelemetrySnapshot() { diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index f409d2b..b5c22df 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -8,8 +8,14 @@ import { randomUUID } from 'node:crypto'; import { isDeepStrictEqual } from 'node:util'; -import { BRIDGE_API_ROUTE_DEFS } from '../shared/window-bridge-protocol.mjs'; +import { BRIDGE_API_ROUTE_DEFS, LOCAL_ENDPOINT_ID } from '../shared/window-bridge-protocol.mjs'; import { handleAccountCredentialAction } from './account-switch.mjs'; +import { + clearRemoteEndpointCaches, + resolveEndpointContext, + trackEndpointRequestEnd, + trackEndpointRequestStart, +} from './endpoint-registry.mjs'; import { isLocalHostRequest, readLocalAsync } from './http-helpers.mjs'; import { clearScannerRuntimeMemos } from './local-scanner.mjs'; import { @@ -104,12 +110,42 @@ function projectDisplayStep(st) { }; } -const MAX_DISPLAY_STEP_CACHE_ENTRIES = 8; +const MAX_DISPLAY_STEP_CACHE_ENTRIES = 16; const displayStepsCache = new Map(); const displayStepFields = Object.keys(projectDisplayStep({ anomaly: true, anomalySig: '' })).filter( (k) => k !== 'anomaly' ); +function buildEndpointErrorResponse(epCtx) { + return { + status: Number(epCtx?.status || 400), + contentType: 'application/json', + headers: { 'Cache-Control': 'no-store' }, + body: JSON.stringify({ + error: epCtx?.error || 'Invalid endpointId', + ...(epCtx?.retryable ? { retryable: true } : {}), + }), + }; +} + +function resolveActionEndpoint(data, opts) { + const rawId = + opts && opts.endpointId !== undefined + ? opts.endpointId + : isPlainObject(data) && data.endpointId !== undefined + ? data.endpointId + : undefined; + return resolveEndpointContext(rawId); +} + +function stripEndpointField(data) { + if (!isPlainObject(data) || !Object.prototype.hasOwnProperty.call(data, 'endpointId')) { + return data; + } + const { endpointId: _ignored, ...rest } = data; + return rest; +} + function haveSameDisplaySteps(previous, current) { if (!previous || !current) return previous === current; if (previous.length !== current.length) return false; @@ -126,12 +162,14 @@ function haveSameDisplaySteps(previous, current) { function projectDisplayTelemetry(payload, requestedRevision) { const active = payload.activeConversation; const agents = active.agents; + const endpointKey = payload.endpoint?.id || LOCAL_ENDPOINT_ID; const sourceSteps = [active.recentSteps, ...agents.map((agent) => agent.recentSteps)]; let projected; let revision; if (typeof requestedRevision === 'string') { - const cacheKey = active.cascadeId || '__empty__'; + const cacheKey = `${endpointKey}::${active.cascadeId || '__empty__'}`; const scope = [ + endpointKey, payload.account?.status, payload.account?.email || payload.account?.name || '', active.cascadeId, @@ -175,17 +213,23 @@ function projectDisplayTelemetry(payload, requestedRevision) { }; } -export async function executeTelemetryAction(data, { onRestart = null } = {}) { +export async function executeTelemetryAction(data, opts = {}) { + const { onRestart = null } = opts || {}; + const epCtx = resolveActionEndpoint(data, opts); + if (!epCtx.ok) { + return buildEndpointErrorResponse(epCtx); + } + const isRemote = epCtx.isRemote; const rawConvId = String( - data?.conversationId || process.env.ANTIGRAVITY_CONVERSATION_ID || '' + data?.conversationId || (isRemote ? '' : process.env.ANTIGRAVITY_CONVERSATION_ID || '') ).trim(); const convId = rawConvId && !/[\\/]|\.\./.test(rawConvId) ? rawConvId : ''; const force = data?.force === '1' || data?.force === true; if (lsRuntimeEndpoint.addr !== 'test.invalid') { - if (!lsRuntimeEndpoint.baseUrl) { + if (!isRemote && !lsRuntimeEndpoint.baseUrl) { await ensureLsEndpointDiscovered({ force: false }); } - if (lsRuntimeEndpoint.baseUrl) { + if (isRemote || lsRuntimeEndpoint.baseUrl) { if (force && Date.now() - cloudSyncState.lastAttemptMs > 15_000) { await Promise.race([ syncCloudCatalog({ force: true }).catch(() => {}), @@ -208,8 +252,10 @@ export async function executeTelemetryAction(data, { onRestart = null } = {}) { startMs: sanitizePositiveFiniteMs(data?.startMs), endMs: sanitizePositiveFiniteMs(data?.endMs), ...(scope ? { scope } : {}), + endpoint: epCtx.endpoint, }; let payload; + trackEndpointRequestStart(epCtx.endpoint); try { payload = await buildTelemetryPayload(convId, force, filterOpts); } catch (err) { @@ -225,6 +271,8 @@ export async function executeTelemetryAction(data, { onRestart = null } = {}) { } } throw err; + } finally { + trackEndpointRequestEnd(epCtx.endpoint); } if ( bootBundleVersion && @@ -258,7 +306,7 @@ function sanitizePositiveSettingNumber(val, fallback) { export function executeSettingsAction(data) { const current = loadSettings(); - const payload = isPlainObject(data) ? data : {}; + const payload = isPlainObject(data) ? stripEndpointField(data) : {}; const nextPluginUpdateMode = payload.pluginUpdateMode !== undefined ? normalizePluginUpdateMode(payload.pluginUpdateMode) @@ -353,7 +401,11 @@ export function executeSettingsAction(data) { }; } -export async function executeModelContextWindowAction(data) { +export async function executeModelContextWindowAction(data, opts = {}) { + const epCtx = resolveActionEndpoint(data, opts); + if (!epCtx.ok) { + return buildEndpointErrorResponse(epCtx); + } const { modelId, option } = data || {}; const respond = (status, payload) => ({ status, @@ -364,12 +416,44 @@ export async function executeModelContextWindowAction(data) { if (!isContextWindowSettingId(modelId) || (option !== null && !isContextWindowOption(option))) { return respond(400, { error: 'Invalid model context window' }); } + + async function loadGroupsForEndpoint(targetEndpoint) { + const [{ userStatus }, catalog] = await Promise.all([ + callLsRpc('GetUserStatus', {}, 5000, targetEndpoint), + getContextModelCatalog(targetEndpoint), + ]); + const configs = userStatus?.cascadeModelConfigData?.clientModelConfigs; + if (!Array.isArray(configs) || configs.length === 0) return null; + const models = getContextWindowModels(configs, catalog); + return getContextWindowGroups(models); + } + let group; + let verifiedHostConfigs = false; + trackEndpointRequestStart(epCtx.endpoint); try { - const [{ userStatus }, catalog] = await Promise.all([callLsRpc('GetUserStatus'), getContextModelCatalog()]); - const models = getContextWindowModels(userStatus?.cascadeModelConfigData?.clientModelConfigs, catalog); - group = getContextWindowGroups(models).find(({ id }) => id === modelId); - } catch { + let groups = null; + try { + groups = await loadGroupsForEndpoint(epCtx.endpoint); + } catch { + groups = null; + } + if (epCtx.isRemote && !groups) { + // 仅在远端 RPC 异常或未返回模型配置时安全回退本机校验;远端已成功返回时绝不放宽其档位限制 + try { + groups = await loadGroupsForEndpoint(null); + } catch { + groups = null; + } + } + if (Array.isArray(groups)) { + verifiedHostConfigs = true; + group = groups.find(({ id }) => id === modelId); + } + } finally { + trackEndpointRequestEnd(epCtx.endpoint); + } + if (!verifiedHostConfigs) { if (option !== null || modelId.startsWith('model:')) { return respond(503, { error: 'Unable to verify the host model configuration' }); } @@ -442,8 +526,14 @@ export function executeResetSettingsAction() { }; } -export function executeRebuildCacheAction() { - const ok = clearRuntimeCaches(); +export function executeRebuildCacheAction(data = undefined, opts = {}) { + const epCtx = resolveActionEndpoint(data, opts); + if (!epCtx.ok) { + return buildEndpointErrorResponse(epCtx); + } + const ok = epCtx.isRemote + ? clearRemoteEndpointCaches(epCtx.id) + : clearRuntimeCaches(); if (!ok) { return { ok: false, @@ -453,15 +543,20 @@ export function executeRebuildCacheAction() { body: JSON.stringify({ ok: false, error: 'Failed to clear trajectory cache' }), }; } - displayStepsCache.clear(); - clearScannerRuntimeMemos(); - clearTelemetryBuilderMemo(); + const cachePrefix = `${epCtx.id}::`; + for (const key of Array.from(displayStepsCache.keys())) { + if (key.startsWith(cachePrefix)) { + displayStepsCache.delete(key); + } + } + clearScannerRuntimeMemos(epCtx.isRemote ? epCtx.id : null); + clearTelemetryBuilderMemo(epCtx.id); return { ok: true, status: 200, contentType: 'application/json', headers: { 'Cache-Control': 'no-store' }, - body: JSON.stringify({ ok: true, clearedAt: Date.now() }), + body: JSON.stringify({ ok: true, endpointId: epCtx.id, clearedAt: Date.now() }), }; } @@ -486,10 +581,23 @@ export async function executePluginUpdateAction() { }; } -export async function executeAccountCredentialAction(data) { - const result = await handleAccountCredentialAction(data); - if (data?.action === 'switch') { - clearTelemetryBuilderMemo(); +export async function executeAccountCredentialAction(data, opts = {}) { + const epCtx = resolveActionEndpoint(data, opts); + if (!epCtx.ok) { + return buildEndpointErrorResponse(epCtx); + } + if (epCtx.isRemote) { + return { + status: 200, + contentType: 'application/json', + headers: { 'Cache-Control': 'no-store' }, + body: JSON.stringify({ supported: false, accounts: [], error: 'unsupported' }), + }; + } + const cleanData = stripEndpointField(data); + const result = await handleAccountCredentialAction(cleanData); + if (cleanData?.action === 'switch') { + clearTelemetryBuilderMemo(LOCAL_ENDPOINT_ID); } return { status: 200, @@ -531,15 +639,15 @@ export async function dispatchBridgeApiRequest(pathname, method, data, opts = un } return executeSettingsAction(data); case 'accounts_get': - return executeAccountCredentialAction(); + return executeAccountCredentialAction(undefined, opts); case 'accounts_update': - return executeAccountCredentialAction(data); + return executeAccountCredentialAction(data, opts); case 'context_window': - return executeModelContextWindowAction(data); + return executeModelContextWindowAction(data, opts); case 'settings_reset': return executeResetSettingsAction(); case 'cache_rebuild': - return executeRebuildCacheAction(); + return executeRebuildCacheAction(data, opts); case 'cloud_sync': return executeCloudSyncAction(); case 'plugin_update': @@ -585,8 +693,11 @@ export function bootWindowBridgeRuntime({ allowDynamicLs = false, onRestart = nu } return startDefaultWindowBridge({ - handleApiRequest: (pathname, method, data) => - dispatchBridgeApiRequest(pathname, method, data, { onRestart: triggerRestart }), + handleApiRequest: (pathname, method, data, ctx) => + dispatchBridgeApiRequest(pathname, method, data, { + onRestart: triggerRestart, + ...(ctx?.endpointId !== undefined ? { endpointId: ctx.endpointId } : {}), + }), readAssetFn: readLocalAsync, bootBundleVersion, onVersionDrift: triggerRestart, diff --git a/sidecars/panel/backend/context-windows.mjs b/sidecars/panel/backend/context-windows.mjs index 7341de1..eb806f9 100644 --- a/sidecars/panel/backend/context-windows.mjs +++ b/sidecars/panel/backend/context-windows.mjs @@ -121,18 +121,19 @@ export async function syncHostContextWindows( rules, bootId, key = '__AGUsageMonitorContextWindows', - fallbackRules = {} + fallbackRules = {}, + allowRemoteHost = false ) { let state = window[key]; const appConfig = window.__APP_CONFIG__; - const csrfToken = appConfig?.csrfToken; + const csrfToken = appConfig?.csrfToken || state?.observedCsrfToken || ''; const hasPrefs = Boolean(rules && Object.keys(rules).length > 0); const safeFallback = fallbackRules && typeof fallbackRules === 'object' && !Array.isArray(fallbackRules) ? fallbackRules : {}; const hasFallback = Object.keys(safeFallback).length > 0; - if (!hasPrefs || appConfig?.isRemoteControl || (!csrfToken && !hasFallback)) { + if (!hasPrefs || (!allowRemoteHost && appConfig?.isRemoteControl) || (!csrfToken && !hasFallback)) { state?.dispose(); return { attached: false, ruleCount: 0 }; } @@ -207,10 +208,17 @@ export async function syncHostContextWindows( : ''; if (rawUrl && init?.method === 'POST') { const url = new URL(rawUrl, window.location.href); - if (url.origin === window.location.origin && isTargetProcedure(url.pathname)) { - const type = new Headers(init.headers).get('content-type')?.split(';')[0].trim(); - const body = rewriteBody(init.body, type); - if (body !== init.body) nextInit = { ...init, body }; + if (url.origin === window.location.origin && url.pathname.startsWith(servicePath)) { + const hdrs = new Headers(init.headers); + const seenCsrf = hdrs.get('x-codeium-csrf-token')?.trim(); + if (seenCsrf && state) { + state.observedCsrfToken = seenCsrf; + } + if (isTargetProcedure(url.pathname)) { + const type = hdrs.get('content-type')?.split(';')[0].trim(); + const body = rewriteBody(init.body, type); + if (body !== init.body) nextInit = { ...init, body }; + } } } } catch { @@ -312,7 +320,12 @@ export async function syncHostContextWindows( return { attached: Boolean(state.isAttached?.()), ruleCount: Object.keys(state.rules).length }; } -export function createContextWindowSyncExpression(preferences, bootId, fallbackRules = {}) { +export function createContextWindowSyncExpression( + preferences, + bootId, + fallbackRules = {}, + allowRemoteHost = false +) { return `(() => { ${isContextWindowModelId.toString()} ${isContextWindowSettingId.toString()} @@ -321,6 +334,6 @@ export function createContextWindowSyncExpression(preferences, bootId, fallbackR ${getContextWindowGroups.toString()} ${resolveContextWindowOption.toString()} ${resolveContextWindowRules.toString()} - return (${syncHostContextWindows.toString()})(${JSON.stringify(preferences)}, ${JSON.stringify(bootId)}, ${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}, ${JSON.stringify(fallbackRules || {})}); + return (${syncHostContextWindows.toString()})(${JSON.stringify(preferences)}, ${JSON.stringify(bootId)}, ${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}, ${JSON.stringify(fallbackRules || {})}, ${JSON.stringify(Boolean(allowRemoteHost))}); })()`; } diff --git a/sidecars/panel/backend/endpoint-registry.mjs b/sidecars/panel/backend/endpoint-registry.mjs new file mode 100644 index 0000000..732c767 --- /dev/null +++ b/sidecars/panel/backend/endpoint-registry.mjs @@ -0,0 +1,603 @@ +/** + * @fileoverview 多窗口 / SSH 远端端点注册表与按端点隔离的运行时状态存储。 + * + * 职责: + * 1. 管理 `'local'`(委托既有本机全局状态,100% 向后兼容)与每个 SSH/远端窗口的独立端点上下文; + * 2. 为每个远端端点维护隔离的轨迹缓存、配额缓存、模型目录缓存、扫描冷却表与实时活动缓存; + * 3. 对具备稳定主机标识的 SSH 端点按 `-.json` 原子持久化至 `DATA_DIR/remote_caches/`, + * 临时端口端点仅驻留内存,防止磁盘残留垃圾文件; + * 4. 维护同一远端主机的多窗口 CDP `targets` 映射、Tier-1 失败熔断器与 `inFlightCount` 防误回收保护。 + */ + +import { createHash } from 'node:crypto'; +import { mkdirSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { LOCAL_ENDPOINT_ID } from '../shared/window-bridge-protocol.mjs'; +import { inferCompactionStepModels, normalizeCachedStep } from '../trajectory-metrics.mjs'; +import { + CACHE_RUNNING_SAVE_INTERVAL_MS, + DATA_DIR, + clearRuntimeCaches, + flushTrajectoryCacheNow, + getCachedTrajectory, + hasPendingTrajectoryCacheSave, + isPlainObject, + listCachedTrajectoryEntries, + loadJson, + lsRuntimeEndpoint, + persistTrajectoryCacheIfNeeded, + quotaSummaryCache, + removeCachedTrajectory, + setCachedTrajectory, +} from './config.mjs'; +import { writeTrajectoryCacheFile } from './trajectory-cache-file.mjs'; + +const ENDPOINT_ID_REMOTE_RE = /^remote:[a-zA-Z0-9._:@-]{1,120}$/; +const ENDPOINT_STALE_TTL_MS = 60_000; +const ENDPOINT_TIER2_COOLDOWN_MS = 60_000; +const ENDPOINT_REMOTE_CACHE_DIR = join(DATA_DIR, 'remote_caches'); + +const remoteEndpointRegistry = new Map(); +let nextEndpointInstanceId = 0; +let registeredWindowRpcInvoker = null; + +/** + * 校验并归一化 `endpointId`;空值默认回退 `'local'`,非法格式返回 `null`。 + * + * @param {unknown} rawId + * @returns {string|null} + */ +export function normalizeEndpointId(rawId) { + if (rawId === undefined || rawId === null || rawId === '') { + return LOCAL_ENDPOINT_ID; + } + const text = String(rawId).trim(); + if (!text || text === LOCAL_ENDPOINT_ID) { + return LOCAL_ENDPOINT_ID; + } + if (!ENDPOINT_ID_REMOTE_RE.test(text)) { + return null; + } + return text; +} + +/** + * 根据稳定主机名或回环 origin 构造确定性的远端 `endpointId` 与磁盘持久化标识。 + * + * @param {{ origin?: string, hostLabel?: string, stableHostKey?: string }} info + * @returns {{ id: string, label: string, stableHostKey: string, hasStableHostKey: boolean }} + */ +export function buildRemoteEndpointIdentity({ origin = '', hostLabel = '', stableHostKey = '' } = {}) { + const cleanStable = String(stableHostKey || '').trim(); + const cleanLabel = String(hostLabel || cleanStable || '').trim(); + const cleanOrigin = String(origin || '').trim(); + + let parsedHostPort = ''; + if (cleanOrigin) { + try { + const parsed = new URL(cleanOrigin); + parsedHostPort = parsed.host; + } catch { + // 忽略非法 URL + } + } + + if (cleanStable) { + const safePrefix = cleanStable + .toLowerCase() + .replace(/[^a-z0-9._-]+/g, '-') + .replace(/^-+|-+$/g, '') + .slice(0, 48) || 'ssh'; + const hash = createHash('sha256').update(cleanStable.toLowerCase()).digest('hex').slice(0, 12); + return { + id: `remote:ssh-${safePrefix}-${hash}`, + label: cleanLabel || cleanStable, + stableHostKey: cleanStable.toLowerCase(), + hasStableHostKey: true, + }; + } + + const originBasis = (parsedHostPort || cleanOrigin || 'unknown').toLowerCase(); + const safeOrigin = originBasis + .replace(/[^a-z0-9._:-]+/g, '-') + .replace(/^-+|-+$/g, '') + .slice(0, 64) || 'unknown'; + const hash = createHash('sha256').update(originBasis).digest('hex').slice(0, 8); + return { + id: `remote:${safeOrigin}-${hash}`, + label: cleanLabel || parsedHostPort || 'SSH', + stableHostKey: '', + hasStableHostKey: false, + }; +} + +function buildRemoteCacheFilePath(stableHostKey) { + if (!stableHostKey) return ''; + const safePrefix = stableHostKey + .toLowerCase() + .replace(/[^a-z0-9._-]+/g, '_') + .replace(/^_+|_+$/g, '') + .slice(0, 32) || 'ssh'; + const hash = createHash('sha256').update(stableHostKey.toLowerCase()).digest('hex').slice(0, 12); + // 前缀加上 `ssh-` 可彻底规避 Windows 保留文件名(CON/NUL/PRN/AUX/COM1 等) + return join(ENDPOINT_REMOTE_CACHE_DIR, `ssh-${safePrefix}-${hash}.json`); +} + +function hydrateTrajectoryCacheObject(rawLoaded) { + const cacheObj = Object.create(null); + let migrated = + rawLoaded !== null && rawLoaded !== undefined && !isPlainObject(rawLoaded); + if (isPlainObject(rawLoaded)) { + for (const [id, entry] of Object.entries(rawLoaded)) { + if (!id || !isPlainObject(entry)) { + migrated = true; + continue; + } + const rawSteps = Array.isArray(entry.steps) ? entry.steps : []; + if (!Array.isArray(entry.steps)) migrated = true; + const objectSteps = rawSteps.filter((s) => isPlainObject(s)); + if (objectSteps.length !== rawSteps.length) migrated = true; + const normalizedSteps = objectSteps.map((s) => { + const norm = normalizeCachedStep(s); + if (norm !== s) migrated = true; + return norm; + }); + const finalSteps = inferCompactionStepModels(normalizedSteps); + for (let i = 0; i < finalSteps.length; i++) { + if (finalSteps[i] !== normalizedSteps[i]) { + migrated = true; + break; + } + } + cacheObj[id] = { ...entry, steps: finalSteps }; + } + } + return { cacheObj, migrated }; +} + +function createRemoteQuotaCache() { + return { + ts: 0, + lastAttemptTs: 0, + accountName: '', + accountGeneration: 0, + data: null, + error: null, + }; +} + +function createRemoteEndpointStore(cacheFilePath) { + const loaded = cacheFilePath ? loadJson(cacheFilePath, {}) : {}; + const { cacheObj, migrated } = hydrateTrajectoryCacheObject(loaded); + const state = { + needsSave: Boolean(cacheFilePath && migrated), + lastSavedAtMs: 0, + flushTimer: null, + }; + + function cancelFlushTimer() { + if (state.flushTimer) { + try { + clearTimeout(state.flushTimer); + } catch { + // 忽略沙箱异常 + } + state.flushTimer = null; + } + } + + function writeCacheNow() { + cancelFlushTimer(); + if (!cacheFilePath) { + state.needsSave = false; + return true; + } + try { + mkdirSync(dirname(cacheFilePath), { recursive: true }); + writeTrajectoryCacheFile(cacheFilePath, cacheObj); + state.needsSave = false; + state.lastSavedAtMs = Date.now(); + return true; + } catch (err) { + console.error(`Failed writing remote cache ${cacheFilePath}: ${err.message}`); + state.needsSave = true; + return false; + } + } + + function persistIfNeeded({ hasRunningSessions = false } = {}) { + if (!cacheFilePath) { + state.needsSave = false; + return; + } + if (lsRuntimeEndpoint.addr === 'test.invalid' || typeof setTimeout !== 'function') { + writeCacheNow(); + return; + } + const nowMs = Date.now(); + const elapsedMs = nowMs - (state.lastSavedAtMs || 0); + if (!hasRunningSessions || state.lastSavedAtMs === 0 || elapsedMs >= CACHE_RUNNING_SAVE_INTERVAL_MS) { + writeCacheNow(); + return; + } + state.needsSave = true; + if (!state.flushTimer) { + const delayMs = Math.max(100, CACHE_RUNNING_SAVE_INTERVAL_MS - elapsedMs); + const timer = setTimeout(() => { + state.flushTimer = null; + if (state.needsSave) { + writeCacheNow(); + } + }, delayMs); + timer?.unref?.(); + state.flushTimer = timer; + } + } + + function clearCache() { + cancelFlushTimer(); + if (cacheFilePath) { + try { + mkdirSync(dirname(cacheFilePath), { recursive: true }); + writeTrajectoryCacheFile(cacheFilePath, {}); + } catch { + return false; + } + } + for (const key of Object.keys(cacheObj)) { + delete cacheObj[key]; + } + state.needsSave = false; + state.lastSavedAtMs = 0; + return true; + } + + return { + cacheFilePath, + cacheState: state, + cancelFlushTimer, + getCachedTrajectory: (cascadeId) => cacheObj[cascadeId], + listCachedTrajectoryEntries: () => Object.entries(cacheObj), + setCachedTrajectory: (cascadeId, entry) => { + cacheObj[cascadeId] = entry; + }, + removeCachedTrajectory: (cascadeId) => { + delete cacheObj[cascadeId]; + }, + hasPendingTrajectoryCacheSave: () => state.needsSave, + persistTrajectoryCacheIfNeeded: persistIfNeeded, + flushTrajectoryCacheNow: writeCacheNow, + clearCache, + }; +} + +/** + * 注册或更新一个 SSH / 远端窗口端点(幂等;同一远端主机多窗口共享端点并保留独立 `wsUrl` 列表)。 + * + * @param {{ + * id?: string, + * origin?: string, + * baseUrl?: string, + * csrfToken?: string, + * wsUrl?: string, + * label?: string, + * stableHostKey?: string, + * }} info + */ +export function registerRemoteEndpoint(info = {}) { + const identity = info.id && ENDPOINT_ID_REMOTE_RE.test(info.id) + ? { + id: info.id, + label: String(info.label || info.stableHostKey || 'SSH').trim() || 'SSH', + stableHostKey: String(info.stableHostKey || '').trim().toLowerCase(), + hasStableHostKey: Boolean(String(info.stableHostKey || '').trim()), + } + : buildRemoteEndpointIdentity({ + origin: info.origin || info.baseUrl, + hostLabel: info.label, + stableHostKey: info.stableHostKey, + }); + + const nowMs = Date.now(); + const cleanOrigin = String(info.origin || '').trim().replace(/\/+$/, ''); + const cleanBaseUrl = String(info.baseUrl || cleanOrigin).trim().replace(/\/+$/, ''); + const cleanCsrf = String(info.csrfToken || '').trim(); + const cleanWsUrl = String(info.wsUrl || '').trim(); + + let entry = remoteEndpointRegistry.get(identity.id); + if (!entry) { + const cacheFilePath = identity.hasStableHostKey + ? buildRemoteCacheFilePath(identity.stableHostKey) + : ''; + entry = { + id: identity.id, + instanceId: ++nextEndpointInstanceId, + isRemote: true, + label: identity.label, + stableHostKey: identity.stableHostKey, + hasStableHostKey: identity.hasStableHostKey, + origin: cleanOrigin, + baseUrl: cleanBaseUrl, + csrfToken: cleanCsrf, + targets: new Map(), + lastSeenMs: nowMs, + preferTier2UntilMs: 0, + inFlightCount: 0, + store: createRemoteEndpointStore(cacheFilePath), + quotaSummaryCache: createRemoteQuotaCache(), + contextModelCatalog: null, + failedFetchCooldownMap: new Map(), + liveActivityMemo: new Map(), + }; + remoteEndpointRegistry.set(identity.id, entry); + } else { + entry.lastSeenMs = nowMs; + if (identity.label) entry.label = identity.label; + if (cleanOrigin) entry.origin = cleanOrigin; + + const existingTarget = cleanWsUrl ? entry.targets.get(cleanWsUrl) : null; + const isAlreadyKnownPair = Array.from(entry.targets.values()).some( + (t) => + (!cleanBaseUrl || t.baseUrl === cleanBaseUrl) && + (!cleanCsrf || t.csrfToken === cleanCsrf) + ); + const baseUrlChanged = Boolean(cleanBaseUrl && entry.baseUrl && entry.baseUrl !== cleanBaseUrl); + + if (cleanBaseUrl) { + if (baseUrlChanged && !isAlreadyKnownPair) { + entry.preferTier2UntilMs = 0; + if (!cleanCsrf) { + // 远端隧道换端口重连且 2.33.0+ 未暴露 csrfToken 时清除旧端口残留令牌 + entry.csrfToken = ''; + } + } + entry.baseUrl = cleanBaseUrl; + } + if (cleanCsrf) { + if (entry.csrfToken !== cleanCsrf && !isAlreadyKnownPair) { + entry.preferTier2UntilMs = 0; + } + entry.csrfToken = cleanCsrf; + } else if (existingTarget && baseUrlChanged && !isAlreadyKnownPair) { + entry.csrfToken = ''; + } + } + + if (cleanWsUrl) { + entry.targets.set(cleanWsUrl, { + wsUrl: cleanWsUrl, + origin: cleanOrigin || entry.origin, + baseUrl: cleanBaseUrl || entry.baseUrl, + csrfToken: cleanCsrf, + lastSeenMs: nowMs, + }); + } + + return entry; +} + +/** + * 获取已注册的远端端点对象;`'local'` 或未注册时返回 `null`。 + * + * @param {string} endpointId + */ +export function getRegisteredRemoteEndpoint(endpointId) { + const norm = normalizeEndpointId(endpointId); + if (!norm || norm === LOCAL_ENDPOINT_ID) return null; + return remoteEndpointRegistry.get(norm) || null; +} + +/** + * 解析并校验请求目标端点: + * - `'local'` 返回 `{ ok: true, isRemote: false, id: 'local', endpoint: null }`; + * - 已注册远端返回 `{ ok: true, isRemote: true, id, endpoint }`; + * - 非法格式返回 `{ ok: false, status: 400, error: 'Invalid endpointId' }`; + * - 合法但暂未注册的远端返回 `{ ok: false, status: 503, retryable: true, error: 'Remote endpoint initializing' }`。 + * + * @param {unknown} rawEndpointId + */ +export function resolveEndpointContext(rawEndpointId) { + const norm = normalizeEndpointId(rawEndpointId); + if (norm === null) { + return { ok: false, status: 400, retryable: false, error: 'Invalid endpointId' }; + } + if (norm === LOCAL_ENDPOINT_ID) { + return { ok: true, isRemote: false, id: LOCAL_ENDPOINT_ID, label: '', endpoint: null }; + } + const entry = remoteEndpointRegistry.get(norm); + if (!entry) { + return { + ok: false, + status: 503, + retryable: true, + error: 'Remote endpoint initializing', + }; + } + return { + ok: true, + isRemote: true, + id: entry.id, + label: entry.label || 'SSH', + endpoint: entry, + }; +} + +/** + * 返回目标端点对应的统一轨迹缓存读写适配器(`'local'` 委托给 `config.mjs` 原生缓存)。 + * + * @param {object|string|null} [endpointOrId=null] + */ +export function getEndpointCacheStore(endpointOrId = null) { + const ep = + typeof endpointOrId === 'string' + ? getRegisteredRemoteEndpoint(endpointOrId) + : endpointOrId && typeof endpointOrId === 'object' && endpointOrId.isRemote + ? endpointOrId + : null; + if (ep?.store) { + return { + isRemote: true, + endpointId: ep.id, + ...ep.store, + }; + } + return { + isRemote: false, + endpointId: LOCAL_ENDPOINT_ID, + getCachedTrajectory, + listCachedTrajectoryEntries, + setCachedTrajectory, + removeCachedTrajectory, + hasPendingTrajectoryCacheSave, + persistTrajectoryCacheIfNeeded, + flushTrajectoryCacheNow, + clearCache: clearRuntimeCaches, + }; +} + +/** + * 返回目标端点对应的配额缓存容器。 + * + * @param {object|string|null} [endpointOrId=null] + */ +export function getEndpointQuotaCache(endpointOrId = null) { + const ep = + typeof endpointOrId === 'string' + ? getRegisteredRemoteEndpoint(endpointOrId) + : endpointOrId && typeof endpointOrId === 'object' && endpointOrId.isRemote + ? endpointOrId + : null; + return ep?.quotaSummaryCache || quotaSummaryCache; +} + +/** + * 清空目标远端端点的内存与持久化缓存(包含配额、模型目录、扫描冷却表与实时活动缓存)。 + * + * @param {string} endpointId + * @returns {boolean} + */ +export function clearRemoteEndpointCaches(endpointId) { + const ep = getRegisteredRemoteEndpoint(endpointId); + if (!ep) return false; + const ok = ep.store.clearCache(); + if (!ok) return false; + ep.failedFetchCooldownMap.clear(); + ep.liveActivityMemo.clear(); + ep.contextModelCatalog = null; + ep.quotaSummaryCache.ts = 0; + ep.quotaSummaryCache.lastAttemptTs = 0; + ep.quotaSummaryCache.accountName = ''; + ep.quotaSummaryCache.accountGeneration += 1; + ep.quotaSummaryCache.data = null; + ep.quotaSummaryCache.error = null; + return true; +} + +/** + * 为远端端点挑选存活的 CDP `wsUrl` 列表(按最近活跃时间倒序,便于多窗口故障转移)。 + * + * @param {object|null} endpoint + * @returns {string[]} + */ +export function getRemoteEndpointTargetWsUrls(endpoint) { + if (!endpoint?.targets || !(endpoint.targets instanceof Map)) return []; + return Array.from(endpoint.targets.values()) + .sort((a, b) => (b.lastSeenMs || 0) - (a.lastSeenMs || 0)) + .map((t) => t.wsUrl) + .filter(Boolean); +} + +/** + * 当 Tier-1 回环直连失败(如 401/403/TLS/连接错误)时启用 60 秒熔断,优先改走 Tier-2 窗口同源通道。 + */ +export function markRemoteEndpointPreferTier2(endpoint, cooldownMs = ENDPOINT_TIER2_COOLDOWN_MS) { + if (endpoint && typeof endpoint === 'object') { + endpoint.preferTier2UntilMs = Date.now() + Math.max(1000, Number(cooldownMs) || ENDPOINT_TIER2_COOLDOWN_MS); + } +} + +export function shouldRemoteEndpointPreferTier2(endpoint) { + return Boolean(endpoint && Number(endpoint.preferTier2UntilMs || 0) > Date.now()); +} + +/** + * 标记端点正在执行请求,避免并发 pruning 期间提前销毁。 + */ +export function trackEndpointRequestStart(endpoint) { + if (endpoint && typeof endpoint === 'object') { + endpoint.inFlightCount = Math.max(0, Number(endpoint.inFlightCount || 0)) + 1; + } +} + +export function trackEndpointRequestEnd(endpoint) { + if (endpoint && typeof endpoint === 'object') { + endpoint.inFlightCount = Math.max(0, Number(endpoint.inFlightCount || 0) - 1); + } +} + +/** + * 清理已关闭且超过宽限期(默认 60 秒)且无在途请求的远端端点;清理前刷盘并取消定时器。 + * + * @param {Set} activeRemoteWsUrls + * @param {number} [ttlMs=60000] + */ +export function pruneStaleRemoteEndpoints(activeRemoteWsUrls, ttlMs = ENDPOINT_STALE_TTL_MS) { + const nowMs = Date.now(); + const activeSet = activeRemoteWsUrls instanceof Set ? activeRemoteWsUrls : new Set(); + + for (const [id, ep] of remoteEndpointRegistry.entries()) { + for (const [wsUrl, tInfo] of ep.targets.entries()) { + if (!activeSet.has(wsUrl) && nowMs - (tInfo.lastSeenMs || 0) >= ttlMs) { + ep.targets.delete(wsUrl); + } + } + const stillActive = Array.from(ep.targets.keys()).some((wsUrl) => activeSet.has(wsUrl)); + if (stillActive) { + ep.lastSeenMs = nowMs; + continue; + } + if (ep.inFlightCount > 0) continue; + if (nowMs - (ep.lastSeenMs || 0) >= ttlMs) { + if (ep.store.hasPendingTrajectoryCacheSave()) { + ep.store.flushTrajectoryCacheNow(); + } + ep.store.cancelFlushTimer(); + remoteEndpointRegistry.delete(id); + } + } +} + +export function listRegisteredRemoteEndpoints() { + return Array.from(remoteEndpointRegistry.values()); +} + +export function clearRemoteEndpointRegistry() { + for (const ep of remoteEndpointRegistry.values()) { + ep.store.cancelFlushTimer(); + } + remoteEndpointRegistry.clear(); +} + +/** + * 注册 Tier-2 窗口同源 RPC 执行器(由 `window-bridge.mjs` 绑定 CDP `evaluateOnTarget`)。 + * + * @param {((endpoint: object, method: string, body: object, timeoutMs: number) => Promise)|null} invoker + */ +export function setRemoteWindowRpcInvoker(invoker) { + registeredWindowRpcInvoker = typeof invoker === 'function' ? invoker : null; +} + +export function getRemoteWindowRpcInvoker() { + return registeredWindowRpcInvoker; +} + +if (typeof process !== 'undefined' && typeof process?.once === 'function') { + process.once('exit', () => { + for (const ep of remoteEndpointRegistry.values()) { + if (ep.store.hasPendingTrajectoryCacheSave()) { + ep.store.flushTrajectoryCacheNow(); + } + ep.store.cancelFlushTimer(); + } + }); +} diff --git a/sidecars/panel/backend/local-scanner.mjs b/sidecars/panel/backend/local-scanner.mjs index 31d5d58..e15aa67 100644 --- a/sidecars/panel/backend/local-scanner.mjs +++ b/sidecars/panel/backend/local-scanner.mjs @@ -27,15 +27,10 @@ import { CONVERSATIONS_DIR, CONVERSATION_DIRS, DEEP_STATS_CACHE_CANDIDATES, - getCachedTrajectory, - hasPendingTrajectoryCacheSave, - listCachedTrajectoryEntries, externalDeepStatsMemo, loadJson, - persistTrajectoryCacheIfNeeded, - removeCachedTrajectory, - setCachedTrajectory, } from './config.mjs'; +import { getEndpointCacheStore, getRegisteredRemoteEndpoint } from './endpoint-registry.mjs'; import { computeSqliteWalSig, hasBuiltinNodeSqlite, @@ -364,7 +359,15 @@ const liveActivityMemo = new Map(); const transcriptTailMemo = new Map(); const swarmManifestMemo = new Map(); -export function clearScannerRuntimeMemos() { +export function clearScannerRuntimeMemos(endpointId = null) { + if (endpointId && endpointId !== 'local') { + const ep = getRegisteredRemoteEndpoint(endpointId); + if (ep) { + ep.failedFetchCooldownMap.clear(); + ep.liveActivityMemo.clear(); + } + return; + } failedFetchCooldownMap.clear(); liveActivityMemo.clear(); transcriptTailMemo.clear(); @@ -1192,11 +1195,17 @@ function scoreLiveActivitySpecificity(act) { return 1; } -function resolveBestLiveActivity(cascadeId, rpcRawSteps, isRunning, fallbackMs) { +function resolveBestLiveActivity( + cascadeId, + rpcRawSteps, + isRunning, + fallbackMs, + { isRemote = false, liveActivityMemoMap = liveActivityMemo } = {} +) { if (!isRunning) return null; const hasRpcSteps = Array.isArray(rpcRawSteps) && rpcRawSteps.length > 0; const rpcAct = hasRpcSteps ? extractLiveActivity(rpcRawSteps, true, fallbackMs) : null; - const transcriptSteps = readTranscriptTailSteps(cascadeId); + const transcriptSteps = isRemote ? [] : readTranscriptTailSteps(cascadeId); const transcriptAct = transcriptSteps.length > 0 ? extractLiveActivity(transcriptSteps, true, fallbackMs) : null; @@ -1226,7 +1235,7 @@ function resolveBestLiveActivity(cascadeId, rpcRawSteps, isRunning, fallbackMs) return ( transcriptAct || rpcAct || - liveActivityMemo.get(String(cascadeId || '').toLowerCase()) || + liveActivityMemoMap.get(String(cascadeId || '').toLowerCase()) || extractLiveActivity([], true, fallbackMs) ); } @@ -1385,22 +1394,35 @@ export async function enumerateAndSyncConversations({ currentAccountName = '', requestedConvId = '', forceRefresh = false, + endpoint = null, }) { + const isRemote = Boolean(endpoint && endpoint.isRemote); + const cacheStore = getEndpointCacheStore(endpoint); + const getEntry = cacheStore.getCachedTrajectory; + const setEntry = cacheStore.setCachedTrajectory; + const removeEntry = cacheStore.removeCachedTrajectory; + const listEntries = cacheStore.listCachedTrajectoryEntries; + const hasPendingSave = cacheStore.hasPendingTrajectoryCacheSave; + const persistCacheIfNeeded = cacheStore.persistTrajectoryCacheIfNeeded; + const activeCooldownMap = isRemote ? endpoint.failedFetchCooldownMap : failedFetchCooldownMap; + const activeLiveActivityMemo = isRemote ? endpoint.liveActivityMemo : liveActivityMemo; + const maxConcurrentRpc = isRemote ? 2 : MAX_CONCURRENT_RPC; + const nowSweepMs = Date.now(); if (forceRefresh) { - failedFetchCooldownMap.clear(); + activeCooldownMap.clear(); } else { - for (const [k, rec] of failedFetchCooldownMap.entries()) { + for (const [k, rec] of activeCooldownMap.entries()) { const failedAt = typeof rec === 'number' ? rec : rec?.failedAt || 0; const cooldownMs = typeof rec === 'number' ? FAILED_RPC_COOLDOWN_MS : rec?.cooldownMs || FAILED_RPC_COOLDOWN_MS; if (nowSweepMs - failedAt >= cooldownMs) { - failedFetchCooldownMap.delete(k); + activeCooldownMap.delete(k); } } } - let cacheDirty = hasPendingTrajectoryCacheSave(); - const diskConvMap = discoverLocalConversationFiles(); + let cacheDirty = hasPendingSave(); + const diskConvMap = isRemote ? new Map() : discoverLocalConversationFiles(); // 构建大小写不敏感索引,将同一会话的不同大小写键合并至唯一规范键(优先保留 summariesObj 中的原始键以兼容 RPC) const mergedSideQuestionParents = { ...(sideQuestionParents || {}) }; @@ -1449,7 +1471,7 @@ export async function enumerateAndSyncConversations({ } } - for (const [rawCacheKey] of listCachedTrajectoryEntries()) { + for (const [rawCacheKey] of listEntries()) { const lower = String(rawCacheKey || '').trim().toLowerCase(); if (!lower) continue; const existingCanon = canonicalIdByLower.get(lower); @@ -1457,18 +1479,18 @@ export async function enumerateAndSyncConversations({ // 标准 UUID 统一收敛为小写键,避免大小写分裂产生双份条目 const normalizedKey = UUID_RE.test(rawCacheKey) ? lower : rawCacheKey; if (normalizedKey !== rawCacheKey) { - setCachedTrajectory(normalizedKey, getCachedTrajectory(rawCacheKey)); - removeCachedTrajectory(rawCacheKey); + setEntry(normalizedKey, getEntry(rawCacheKey)); + removeEntry(rawCacheKey); cacheDirty = true; } canonicalIdByLower.set(lower, normalizedKey); } else if (existingCanon !== rawCacheKey) { - const targetEntry = getCachedTrajectory(existingCanon); - const dupEntry = getCachedTrajectory(rawCacheKey); + const targetEntry = getEntry(existingCanon); + const dupEntry = getEntry(rawCacheKey); if (!targetEntry || (dupEntry?.steps?.length || 0) > (targetEntry?.steps?.length || 0)) { - setCachedTrajectory(existingCanon, dupEntry); + setEntry(existingCanon, dupEntry); } - removeCachedTrajectory(rawCacheKey); + removeEntry(rawCacheKey); cacheDirty = true; } } @@ -1480,7 +1502,7 @@ export async function enumerateAndSyncConversations({ } // 从所有本地缓存会话收集 subagentRefs,确保跨账号切换时历史会话与派生子代理均不丢失 - for (const [, entry] of listCachedTrajectoryEntries()) { + for (const [, entry] of listEntries()) { for (const ref of entry?.subagentRefs || []) { const refCid = String(ref?.cascadeId || '').trim().toLowerCase(); if (refCid && !canonicalIdByLower.has(refCid)) { @@ -1489,15 +1511,15 @@ export async function enumerateAndSyncConversations({ } } - const localSummaryByLower = readLocalSummaryIndex(); - const sqliteAvailable = hasBuiltinNodeSqlite(); + const localSummaryByLower = isRemote ? new Map() : readLocalSummaryIndex(); + const sqliteAvailable = isRemote ? false : hasBuiltinNodeSqlite(); const STALE_LOCAL_RUNNING_MAX_AGE_MS = 10 * 60_000; const reqLower = String(requestedConvId || '').trim().toLowerCase(); const rawConversations = []; for (const [cidLower, cascadeId] of canonicalIdByLower.entries()) { const item = summariesByLower.get(cidLower); const localSum = item ? null : localSummaryByLower.get(cidLower) || null; - const cached = getCachedTrajectory(cascadeId); + const cached = getEntry(cascadeId); const diskFiles = diskConvMap.get(cidLower) || []; const sqliteDbInfo = sqliteAvailable ? resolveBestSqliteDbInfo(diskFiles) : null; const dbPath = sqliteDbInfo?.dbPath || ''; @@ -1508,11 +1530,13 @@ export async function enumerateAndSyncConversations({ const diskMtimeMs = sqliteDbInfo ? Math.max(rawDiskMtimeMs || 0, sqliteDbInfo.mtimeMs || 0) : rawDiskMtimeMs; - const appSource = inferAppSourceFromSummary( - item?.source || '', - diskFiles, - cached?.appSource || 'standalone' - ); + const appSource = isRemote + ? 'ssh' + : inferAppSourceFromSummary( + item?.source || '', + diskFiles, + cached?.appSource || 'standalone' + ); const sqParentInfo = mergedSideQuestionParents[cidLower] || null; const isSideQuestion = Boolean( @@ -1707,12 +1731,12 @@ export async function enumerateAndSyncConversations({ function isFetchInCooldown(conv, sig) { if (forceRefresh) return false; const key = `${conv.cascadeId.toLowerCase()}::${sig}`; - const rec = failedFetchCooldownMap.get(key); + const rec = activeCooldownMap.get(key); if (!rec) return false; const failedAt = typeof rec === 'number' ? rec : rec.failedAt; const cooldownMs = typeof rec === 'number' ? FAILED_RPC_COOLDOWN_MS : rec.cooldownMs; if (nowPollMs - failedAt >= cooldownMs) { - failedFetchCooldownMap.delete(key); + activeCooldownMap.delete(key); return false; } return true; @@ -1765,15 +1789,15 @@ export async function enumerateAndSyncConversations({ for (const c of targetConvs) { attemptedFetchIds.add(c.cascadeId.toLowerCase()); } - for (let i = 0; i < targetConvs.length; i += MAX_CONCURRENT_RPC) { - const batch = targetConvs.slice(i, i + MAX_CONCURRENT_RPC); + for (let i = 0; i < targetConvs.length; i += maxConcurrentRpc) { + const batch = targetConvs.slice(i, i + maxConcurrentRpc); await Promise.all( batch.map(async (conv) => { const sig = buildConvSig(conv); const cooldownKey = `${conv.cascadeId.toLowerCase()}::${sig}`; const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING'; const isReq = Boolean(reqLower && conv.cascadeId.toLowerCase() === reqLower); - const prev = getCachedTrajectory(conv.cascadeId); + const prev = getEntry(conv.cascadeId); let partialTailSteps = []; let hasTailStepInfo = false; try { @@ -1781,7 +1805,7 @@ export async function enumerateAndSyncConversations({ let trajRes = null; let loadedViaSqlite = false; let transcriptFirstTitle = ''; - if (conv.dbPath && sqliteAvailable) { + if (!isRemote && conv.dbPath && sqliteAvailable) { const sqlRes = readLocalSqliteTrajectory(conv.dbPath, { cascadeId: conv.cascadeId, isRunning, @@ -1797,7 +1821,12 @@ export async function enumerateAndSyncConversations({ } } if (!trajRes) { - trajRes = await callLsRpc('GetCascadeTrajectory', { cascadeId: conv.cascadeId }); + trajRes = await callLsRpc( + 'GetCascadeTrajectory', + { cascadeId: conv.cascadeId }, + 5000, + endpoint + ); } if (!Array.isArray(trajRes?.trajectory?.steps)) { throw new Error('Trajectory steps unavailable'); @@ -1813,7 +1842,7 @@ export async function enumerateAndSyncConversations({ } throw new Error('Incomplete trajectory; retaining cached usage'); } - failedFetchCooldownMap.delete(cooldownKey); + activeCooldownMap.delete(cooldownKey); const rawGenMeta = trajRes?.trajectory?.generatorMetadata || []; const { steps: rawSteps, generatorMeta } = loadedViaSqlite ? { steps: rawStepsUnfiltered, generatorMeta: rawGenMeta } @@ -1885,7 +1914,7 @@ export async function enumerateAndSyncConversations({ Boolean( conv.rootConversationId && conv.rootConversationId !== cidLower ); - if (!nonShortTitle(conv.title)) { + if (!isRemote && !nonShortTitle(conv.title)) { const annTitle = nonShortTitle(readAnnotationTitleForCascade(cidLower)); const resolvedFallbackTitle = annTitle || trajRes?.firstOwnUserPrompt || transcriptFirstTitle; @@ -1899,7 +1928,8 @@ export async function enumerateAndSyncConversations({ } const subagentRefs = extractSubagentRefsFromSteps(rawSteps); - const ownSwarmManifest = !conv.isSubagent ? readSwarmManifestForCascade(cidLower) : null; + const ownSwarmManifest = + !isRemote && !conv.isSubagent ? readSwarmManifestForCascade(cidLower) : null; if (ownSwarmManifest?.workerRefs?.length) { const seenRefCids = new Set(subagentRefs.map((r) => r.cascadeId)); for (const wRef of ownSwarmManifest.workerRefs) { @@ -1929,17 +1959,18 @@ export async function enumerateAndSyncConversations({ conv.cascadeId, rawSteps, effectiveIsRunning, - resolvedLastModMs || conv.createdTimeMs || 0 + resolvedLastModMs || conv.createdTimeMs || 0, + { isRemote, liveActivityMemoMap: activeLiveActivityMemo } ); if (liveAct && liveAct.actionKey !== 'swarm_wait') { conv.liveActivity = liveAct; - liveActivityMemo.set(cidLower, liveAct); + activeLiveActivityMemo.set(cidLower, liveAct); } else { if (liveAct?.actionKey === 'swarm_wait') { conv.status = 'IDLE'; } conv.liveActivity = null; - liveActivityMemo.delete(cidLower); + activeLiveActivityMemo.delete(cidLower); } const entryAccountName = prev ? prev.accountName || '' : currentAccountName || ''; @@ -2002,13 +2033,13 @@ export async function enumerateAndSyncConversations({ !isDeepStrictEqual(prev.steps, stepsWithOwners); if (!stepsChanged) cacheEntry.steps = prev.steps; - setCachedTrajectory(conv.cascadeId, cacheEntry); + setEntry(conv.cascadeId, cacheEntry); if (stepsChanged) { cacheDirty = true; } } catch (err) { let offlineRecovered = false; - if (!conv.inSummaries && (!prev || prev.offlineTranscriptFallback)) { + if (!isRemote && !conv.inSummaries && (!prev || prev.offlineTranscriptFallback)) { if (!lazyExternalByLower) { lazyExternalByLower = new Map(); for (const ext of loadExternalDeepStatsCache().values()) { @@ -2087,7 +2118,7 @@ export async function enumerateAndSyncConversations({ Boolean(prev.offlineSqliteTelemetry) !== Boolean(offlineEntry.offlineSqliteTelemetry) || !isDeepStrictEqual(prev.steps, offlineEntry.steps); if (!changed) offlineEntry.steps = prev.steps; - setCachedTrajectory(conv.cascadeId, offlineEntry); + setEntry(conv.cascadeId, offlineEntry); if (changed) { cacheDirty = true; } @@ -2107,30 +2138,31 @@ export async function enumerateAndSyncConversations({ if (!(isRunning && (hasTailStepInfo || offlineRecovered))) { const cooldownMs = isRunning || isReq ? ACTIVE_FAILED_RPC_COOLDOWN_MS : FAILED_RPC_COOLDOWN_MS; - failedFetchCooldownMap.set(cooldownKey, { failedAt: nowPollMs, cooldownMs }); + activeCooldownMap.set(cooldownKey, { failedAt: nowPollMs, cooldownMs }); } if (!isRunning) { - liveActivityMemo.delete(conv.cascadeId.toLowerCase()); + activeLiveActivityMemo.delete(conv.cascadeId.toLowerCase()); } else { const fallbackLive = resolveBestLiveActivity( conv.cascadeId, partialTailSteps, true, - conv.lastModifiedMs || conv.createdTimeMs || 0 + conv.lastModifiedMs || conv.createdTimeMs || 0, + { isRemote, liveActivityMemoMap: activeLiveActivityMemo } ); conv.liveActivity = fallbackLive; if (fallbackLive) { - liveActivityMemo.set(conv.cascadeId.toLowerCase(), fallbackLive); + activeLiveActivityMemo.set(conv.cascadeId.toLowerCase(), fallbackLive); } } if ( !offlineRecovered && prev && - getCachedTrajectory(conv.cascadeId) === prev && + getEntry(conv.cascadeId) === prev && String(prev.signature || '').startsWith(`${CACHE_SCHEMA_VERSION}:`) && !Array.isArray(prev.subagentRefs) ) { - setCachedTrajectory(conv.cascadeId, { ...prev, subagentRefs: [] }); + setEntry(conv.cascadeId, { ...prev, subagentRefs: [] }); cacheDirty = true; } } @@ -2188,7 +2220,7 @@ export async function enumerateAndSyncConversations({ const sig = buildConvSig(conv); if (isFetchInCooldown(conv, sig)) return false; const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING'; - const cached = getCachedTrajectory(conv.cascadeId); + const cached = getEntry(conv.cascadeId); if (!cached || conv.needsInitialLoad) return true; const lowerCid = conv.cascadeId.toLowerCase(); const isSelectedFamily = @@ -2277,11 +2309,12 @@ export async function enumerateAndSyncConversations({ const missingSubagentsToFetch = []; for (const parentConv of [...rawConversations]) { - const parentCached = getCachedTrajectory(parentConv.cascadeId); + const parentCached = getEntry(parentConv.cascadeId); const baseRefs = parentConv.subagentRefs || parentCached?.subagentRefs || []; - const swarmManifest = !parentConv.isSubagent - ? readSwarmManifestForCascade(parentConv.cascadeId) - : null; + const swarmManifest = + !isRemote && !parentConv.isSubagent + ? readSwarmManifestForCascade(parentConv.cascadeId) + : null; let refs = baseRefs; if (swarmManifest?.workerRefs?.length) { const merged = Array.isArray(baseRefs) ? baseRefs.slice() : []; @@ -2310,7 +2343,7 @@ export async function enumerateAndSyncConversations({ const canonSubId = canonicalIdByLower.get(subCid) || subCid; canonicalIdByLower.set(subCid, canonSubId); let subConv = byLowerId.get(subCid); - const subCached = getCachedTrajectory(subConv?.cascadeId || canonSubId); + const subCached = getEntry(subConv?.cascadeId || canonSubId); if (!subConv) { const subDiskFiles = diskConvMap.get(subCid) || []; const subDbInfo = sqliteAvailable ? resolveBestSqliteDbInfo(subDiskFiles) : null; @@ -2336,7 +2369,9 @@ export async function enumerateAndSyncConversations({ diskMtimeMs, dbPath: subDbInfo?.dbPath || '', diskFileSig: subDbInfo?.sig || '', - appSource: inferAppSourceFromSummary('', subDiskFiles, subCached?.appSource || 'standalone'), + appSource: isRemote + ? 'ssh' + : inferAppSourceFromSummary('', subDiskFiles, subCached?.appSource || 'standalone'), inSummaries: false, needsInitialLoad: !subCached, isSubagent: true, @@ -2368,7 +2403,7 @@ export async function enumerateAndSyncConversations({ } const targetCacheKey = subConv.cascadeId; - const existingSubCache = getCachedTrajectory(targetCacheKey); + const existingSubCache = getEntry(targetCacheKey); const isSelectedSubFamily = rootId === selectedRootId; const hasValidSubCache = existingSubCache && @@ -2417,7 +2452,7 @@ export async function enumerateAndSyncConversations({ updatedMetadata.subagentRefs = []; } if (Object.keys(updatedMetadata).length > 0) { - setCachedTrajectory(targetCacheKey, { ...existingSubCache, ...updatedMetadata }); + setEntry(targetCacheKey, { ...existingSubCache, ...updatedMetadata }); cacheDirty = true; } } else { @@ -2443,7 +2478,7 @@ export async function enumerateAndSyncConversations({ if (attemptedFetchIds.has(c.cascadeId.toLowerCase()) || isFetchInCooldown(c, sig)) { return false; } - const cached = getCachedTrajectory(c.cascadeId); + const cached = getEntry(c.cascadeId); return cached && !Array.isArray(cached.subagentRefs); }) .slice(0, LEGACY_MIGRATION_BATCH_SIZE); @@ -2477,9 +2512,9 @@ export async function enumerateAndSyncConversations({ } if (candidate && candidate !== conv.rootConversationId) { conv.rootConversationId = candidate; - const cached = getCachedTrajectory(conv.cascadeId); + const cached = getEntry(conv.cascadeId); if (cached && cached.rootConversationId !== candidate) { - setCachedTrajectory(conv.cascadeId, { ...cached, rootConversationId: candidate }); + setEntry(conv.cascadeId, { ...cached, rootConversationId: candidate }); cacheDirty = true; } } @@ -2488,41 +2523,44 @@ export async function enumerateAndSyncConversations({ const hasRunningSessions = rawConversations.some( (c) => c.status === 'CASCADE_RUN_STATUS_RUNNING' ); - if (cacheDirty || (hasPendingTrajectoryCacheSave() && !hasRunningSessions)) { - persistTrajectoryCacheIfNeeded({ hasRunningSessions }); + if (cacheDirty || (hasPendingSave() && !hasRunningSessions)) { + persistCacheIfNeeded({ hasRunningSessions }); } // 确保所有处于 RUNNING 状态的会话(含本轮未触发 RPC 拉取的会话)都同步了最新的实时动作摘要,并剔除已进入 swarm_wait 待命的假运行态 for (const conv of rawConversations) { if (conv.status === 'CASCADE_RUN_STATUS_RUNNING') { if (!conv.liveActivity) { - const tailSteps = readTranscriptTailSteps(conv.cascadeId); + const tailSteps = isRemote ? [] : readTranscriptTailSteps(conv.cascadeId); if (isParkedOnSwarmWait(tailSteps)) { conv.status = 'IDLE'; conv.liveActivity = null; - liveActivityMemo.delete(conv.cascadeId.toLowerCase()); + activeLiveActivityMemo.delete(conv.cascadeId.toLowerCase()); continue; } const fallbackMs = conv.lastModifiedMs || conv.createdTimeMs || 0; - const resolved = resolveBestLiveActivity(conv.cascadeId, [], true, fallbackMs); + const resolved = resolveBestLiveActivity(conv.cascadeId, [], true, fallbackMs, { + isRemote, + liveActivityMemoMap: activeLiveActivityMemo, + }); if (resolved?.actionKey === 'swarm_wait') { conv.status = 'IDLE'; conv.liveActivity = null; - liveActivityMemo.delete(conv.cascadeId.toLowerCase()); + activeLiveActivityMemo.delete(conv.cascadeId.toLowerCase()); continue; } conv.liveActivity = resolved; if (resolved) { - liveActivityMemo.set(conv.cascadeId.toLowerCase(), resolved); + activeLiveActivityMemo.set(conv.cascadeId.toLowerCase(), resolved); } } else if (conv.liveActivity.actionKey === 'swarm_wait') { conv.status = 'IDLE'; conv.liveActivity = null; - liveActivityMemo.delete(conv.cascadeId.toLowerCase()); + activeLiveActivityMemo.delete(conv.cascadeId.toLowerCase()); } } else { conv.liveActivity = null; - liveActivityMemo.delete(conv.cascadeId.toLowerCase()); + activeLiveActivityMemo.delete(conv.cascadeId.toLowerCase()); } } @@ -2564,7 +2602,7 @@ export async function enumerateAndSyncConversations({ for (const rootConv of conversations) { const cid = rootConv.cascadeId.toLowerCase(); - const swarmManifest = readSwarmManifestForCascade(cid); + const swarmManifest = isRemote ? null : readSwarmManifestForCascade(cid); const swarmTitle = String(swarmManifest?.title || '').trim(); if (swarmTitle) { rootConv.swarmTitle = swarmTitle; @@ -2583,7 +2621,7 @@ export async function enumerateAndSyncConversations({ for (const s of subs) { const subLower = s.cascadeId.toLowerCase(); const mEntry = swarmManifest?.membersByCid.get(subLower) || null; - const subCached = getCachedTrajectory(s.cascadeId); + const subCached = getEntry(s.cascadeId); const parsedSwarm = !s.isSideQuestion ? parseSwarmWorkerRole({ role: s.subagentSpec?.role || subCached?.subagentSpec?.role || '', @@ -2601,7 +2639,7 @@ export async function enumerateAndSyncConversations({ if (s.killed) { s.status = 'IDLE'; s.liveActivity = null; - liveActivityMemo.delete(subLower); + activeLiveActivityMemo.delete(subLower); s.swarmState = 'killed'; } else if (s.status === 'CASCADE_RUN_STATUS_RUNNING') { const parkedInManifest = @@ -2611,7 +2649,7 @@ export async function enumerateAndSyncConversations({ if (s.liveActivity?.actionKey === 'swarm_wait' || parkedInManifest) { s.status = 'IDLE'; s.liveActivity = null; - liveActivityMemo.delete(subLower); + activeLiveActivityMemo.delete(subLower); s.swarmState = 'waiting'; } else { s.swarmState = 'working'; @@ -2639,12 +2677,12 @@ export async function enumerateAndSyncConversations({ } const aStart = a.createdTimeMs || - getCachedTrajectory(a.cascadeId)?.steps?.[0]?.createdAtMs || + getEntry(a.cascadeId)?.steps?.[0]?.createdAtMs || a.lastModifiedMs || 0; const bStart = b.createdTimeMs || - getCachedTrajectory(b.cascadeId)?.steps?.[0]?.createdAtMs || + getEntry(b.cascadeId)?.steps?.[0]?.createdAtMs || b.lastModifiedMs || 0; return aStart - bStart || String(a.cascadeId).localeCompare(String(b.cascadeId)); diff --git a/sidecars/panel/backend/ls-discovery.mjs b/sidecars/panel/backend/ls-discovery.mjs index f9db480..163a2f7 100644 --- a/sidecars/panel/backend/ls-discovery.mjs +++ b/sidecars/panel/backend/ls-discovery.mjs @@ -552,3 +552,97 @@ export async function ensureLsEndpointDiscovered({ return lsDiscoveryState.inFlight; } +const LOCAL_HUB_PORTS_TTL_MS = 4000; +const localHubPortsCache = { + ts: 0, + key: '', + value: null, +}; + +/** + * 收集本机活跃 Hub / Language Server 占用的回环端口集合(含 `httpPort`、`httpsPort` 与当前 `lsRuntimeEndpoint`), + * 不跳过缺少 `csrfToken` 的存活 `hub_*.json` 文件,供 `window-bridge.mjs` 准确区分本地窗口与 SSH 远端窗口。 + * + * @param {{ daemonDirs?: string[], isPidAliveFn?: (pid: number) => boolean, force?: boolean }} [options] + * @returns {{ allPorts: Set, httpPorts: Set, httpsPorts: Set, csrfTokens: Set }} + */ +export function getLocalHubPorts({ + daemonDirs = DAEMON_DIRS, + isPidAliveFn = defaultIsLsPidAlive, + force = false, +} = {}) { + const dirs = Array.isArray(daemonDirs) ? daemonDirs : []; + const cacheKey = `${dirs.join('|')}::${lsRuntimeEndpoint.baseUrl || ''}::${lsRuntimeEndpoint.csrfToken || ''}`; + const now = Date.now(); + if ( + !force && + localHubPortsCache.value && + localHubPortsCache.key === cacheKey && + now - localHubPortsCache.ts < LOCAL_HUB_PORTS_TTL_MS + ) { + return localHubPortsCache.value; + } + + const allPorts = new Set(); + const httpPorts = new Set(); + const httpsPorts = new Set(); + const csrfTokens = new Set(); + + if (lsRuntimeEndpoint.csrfToken) { + csrfTokens.add(String(lsRuntimeEndpoint.csrfToken).trim()); + } + if (lsRuntimeEndpoint.baseUrl) { + try { + const parsed = new URL(lsRuntimeEndpoint.baseUrl); + const port = Number(parsed.port || 0); + if (Number.isInteger(port) && port > 0 && port <= 65535) { + allPorts.add(port); + if (parsed.protocol === 'https:') httpsPorts.add(port); + else httpPorts.add(port); + } + } catch { + // 忽略非法 URL + } + } + + for (const dir of dirs) { + if (!dir || !existsSync(dir)) continue; + let names = []; + try { + names = readdirSync(dir); + } catch { + continue; + } + for (const name of names) { + if (!/^hub_.*\.json$/i.test(name)) continue; + const fullPath = join(dir, name); + try { + const parsed = JSON.parse(readFileSync(fullPath, 'utf8')); + const pid = Number(parsed?.pid) || 0; + if (pid > 0 && !isPidAliveFn(pid)) continue; + const csrf = String(parsed?.csrfToken || parsed?.csrf_token || '').trim(); + if (csrf) csrfTokens.add(csrf); + const hPort = Number(parsed?.httpPort || parsed?.port) || 0; + const sPort = Number(parsed?.httpsPort) || 0; + if (Number.isInteger(hPort) && hPort > 0 && hPort <= 65535) { + allPorts.add(hPort); + httpPorts.add(hPort); + } + if (Number.isInteger(sPort) && sPort > 0 && sPort <= 65535) { + allPorts.add(sPort); + httpsPorts.add(sPort); + } + } catch { + // 忽略损坏或瞬态 daemon 文件 + } + } + } + + const snapshot = { allPorts, httpPorts, httpsPorts, csrfTokens }; + localHubPortsCache.ts = now; + localHubPortsCache.key = cacheKey; + localHubPortsCache.value = snapshot; + return snapshot; +} + + diff --git a/sidecars/panel/backend/ls-rpc.mjs b/sidecars/panel/backend/ls-rpc.mjs index 76170b1..b80f8ac 100644 --- a/sidecars/panel/backend/ls-rpc.mjs +++ b/sidecars/panel/backend/ls-rpc.mjs @@ -2,27 +2,203 @@ * @fileoverview Antigravity Language Server Connect RPC 客户端与官方配额摘要缓存。 * * 负责: - * 1. 向本地 Language Server 发起带 CSRF 鉴权与超时保护的 Connect RPC 调用 (`callLsRpc`); - * 2. 拉取并缓存 `RetrieveUserQuotaSummary` 官方实时配额摘要(常规轮询使用 10 秒短期缓存与失败退避冷却, - * 并在缓存过期或强制刷新时穿透 `language_server.exe` 内部 3 分钟陈旧缓存)。 + * 1. 向本地或 SSH 远端窗口对应的 Language Server 发起带 CSRF 鉴权与超时保护的 Connect RPC 调用 (`callLsRpc`); + * 2. 对远端 SSH 端点采用双层传输: + * - Tier-1:严格限定回环地址 (`127.0.0.1`/`localhost`/`::1`) 的 HTTP/HTTPS 直连(HTTPS 仅对回环允许宿主自签证书); + * - Tier-2:Tier-1 不可用或鉴权依赖 Electron Partition Cookie / 2.33.0+ 省略 `csrfToken` 时, + * 自动熔断并回退至窗口内同源 `window.fetch` / `/connect-websocket`(通过 CDP 按需执行); + * 3. 拉取并按端点隔离缓存 `RetrieveUserQuotaSummary` 官方实时配额摘要与 `GetAvailableModels` 模型目录。 */ -import { lsRuntimeEndpoint, quotaSummaryCache } from './config.mjs'; +import { lsRuntimeEndpoint } from './config.mjs'; +import { + getEndpointQuotaCache, + getRemoteWindowRpcInvoker, + markRemoteEndpointPreferTier2, + shouldRemoteEndpointPreferTier2, +} from './endpoint-registry.mjs'; import { ensureLsEndpointDiscovered } from './ls-discovery.mjs'; const QUOTA_CACHE_TTL_MS = 10_000; const QUOTA_RETRY_COOLDOWN_MS = 5_000; +const REMOTE_HTTPS_MAX_RESPONSE_BYTES = 32 * 1024 * 1024; +const REMOTE_ALLOWED_LS_METHODS = new Set([ + 'GetUserStatus', + 'GetAvailableModels', + 'GetAllCascadeTrajectories', + 'GetCascadeTrajectory', + 'RetrieveUserQuotaSummary', +]); + let contextModelCatalog = null; +let loopbackHttpsModulePromise = null; +let customLoopbackHttpsRequester = null; + +export function setLoopbackHttpsRequester(requester) { + customLoopbackHttpsRequester = typeof requester === 'function' ? requester : null; +} + +function isStrictLoopbackUrl(rawUrl) { + try { + const parsed = new URL(String(rawUrl || '')); + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false; + const host = parsed.hostname.toLowerCase(); + return host === '127.0.0.1' || host === 'localhost' || host === '::1' || host === '[::1]'; + } catch { + return false; + } +} + +async function getLoopbackHttpsRequestFn() { + if (customLoopbackHttpsRequester) return customLoopbackHttpsRequester; + if (typeof globalThis !== 'undefined' && typeof globalThis.__agLoopbackHttpsRequest === 'function') { + return globalThis.__agLoopbackHttpsRequest; + } + if (!loopbackHttpsModulePromise) { + loopbackHttpsModulePromise = import('node:https') + .then((mod) => (mod.default || mod)?.request || null) + .catch(() => null); + } + return loopbackHttpsModulePromise; +} + +async function postLoopbackHttpsJson(urlStr, csrfToken, bodyText, timeoutMs) { + const parsed = new URL(urlStr); + if (!isStrictLoopbackUrl(urlStr) || parsed.protocol !== 'https:') { + throw new Error('Refusing non-loopback HTTPS request'); + } + const requestFn = await getLoopbackHttpsRequestFn(); + if (typeof requestFn !== 'function') { + return fetch(urlStr, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...(csrfToken ? { 'x-codeium-csrf-token': csrfToken } : {}), + }, + body: bodyText, + signal: AbortSignal.timeout(timeoutMs), + }); + } + + return new Promise((resolve, reject) => { + let settled = false; + let wallTimer = null; + const clearWallTimer = () => { + if (wallTimer) { + clearTimeout(wallTimer); + wallTimer = null; + } + }; + const finishErr = (err) => { + if (settled) return; + settled = true; + clearWallTimer(); + reject(err); + }; + const bodyBuf = Buffer.from(bodyText, 'utf8'); + const req = requestFn( + { + hostname: parsed.hostname.replace(/^\[|\]$/g, ''), + port: Number(parsed.port || 443), + path: `${parsed.pathname}${parsed.search}`, + method: 'POST', + rejectUnauthorized: false, + headers: { + 'Content-Type': 'application/json', + 'Content-Length': bodyBuf.length, + ...(csrfToken ? { 'x-codeium-csrf-token': csrfToken } : {}), + }, + }, + (res) => { + const chunks = []; + let totalBytes = 0; + res.on('data', (chunk) => { + if (settled) return; + totalBytes += chunk.length; + if (totalBytes > REMOTE_HTTPS_MAX_RESPONSE_BYTES) { + const sizeErr = new Error('Remote LS response exceeded size limit'); + finishErr(sizeErr); + req.destroy(sizeErr); + return; + } + chunks.push(chunk); + }); + res.on('aborted', () => { + finishErr(new Error('Remote LS HTTPS response aborted')); + }); + res.on('end', () => { + if (settled) return; + settled = true; + clearWallTimer(); + const status = Number(res.statusCode || 0); + const rawText = Buffer.concat(chunks).toString('utf8'); + resolve({ + ok: status >= 200 && status < 300, + status, + json: async () => JSON.parse(rawText || '{}'), + text: async () => rawText, + }); + }); + res.on('error', finishErr); + } + ); + + wallTimer = setTimeout(() => { + const timeoutErr = new Error(`Remote LS HTTPS timeout (${timeoutMs}ms)`); + finishErr(timeoutErr); + req.destroy(timeoutErr); + }, timeoutMs); + wallTimer?.unref?.(); + + req.setTimeout(timeoutMs, () => { + const timeoutErr = new Error(`Remote LS HTTPS timeout (${timeoutMs}ms)`); + finishErr(timeoutErr); + req.destroy(timeoutErr); + }); + req.on('error', finishErr); + req.write(bodyBuf); + req.end(); + }); +} + +export function getContextModelCatalog(endpoint = null) { + const isRemote = Boolean(endpoint && endpoint.isRemote); + if (isRemote) { + const baseUrl = endpoint.baseUrl || endpoint.origin || ''; + const csrfToken = endpoint.csrfToken || ''; + const cached = endpoint.contextModelCatalog; + if ( + !cached || + cached.baseUrl !== baseUrl || + cached.csrfToken !== csrfToken || + Date.now() >= cached.expiresAt + ) { + endpoint.contextModelCatalog = { + baseUrl, + csrfToken, + expiresAt: Date.now() + 30000, + promise: callLsRpc('GetAvailableModels', {}, 2500, endpoint) + .then((data) => data?.response?.models) + .catch(() => null), + }; + } + return endpoint.contextModelCatalog.promise; + } -export function getContextModelCatalog() { const { baseUrl, csrfToken } = lsRuntimeEndpoint; - if (!contextModelCatalog || contextModelCatalog.baseUrl !== baseUrl || contextModelCatalog.csrfToken !== csrfToken || - Date.now() >= contextModelCatalog.expiresAt) { + if ( + !contextModelCatalog || + contextModelCatalog.baseUrl !== baseUrl || + contextModelCatalog.csrfToken !== csrfToken || + Date.now() >= contextModelCatalog.expiresAt + ) { contextModelCatalog = { baseUrl, csrfToken, expiresAt: Date.now() + 30000, - promise: callLsRpc('GetAvailableModels', {}, 1500).then((data) => data?.response?.models).catch(() => null), + promise: callLsRpc('GetAvailableModels', {}, 1500) + .then((data) => data?.response?.models) + .catch(() => null), }; } return contextModelCatalog.promise; @@ -40,15 +216,77 @@ async function postLsRpcOnce(baseUrl, csrfToken, method, body, timeoutMs) { }); } +async function callRemoteEndpointLsRpc(endpoint, method, body, timeoutMs) { + if (!REMOTE_ALLOWED_LS_METHODS.has(method)) { + throw new Error(`RPC method ${method} is not allowed on remote endpoints`); + } + const baseUrl = String(endpoint.baseUrl || endpoint.origin || '').trim().replace(/\/+$/, ''); + const csrfToken = String(endpoint.csrfToken || '').trim(); + const windowInvoker = getRemoteWindowRpcInvoker(); + const canTryTier1 = + Boolean(baseUrl) && + isStrictLoopbackUrl(baseUrl) && + Boolean(csrfToken) && + !shouldRemoteEndpointPreferTier2(endpoint); + + let tier1Err = null; + if (canTryTier1) { + try { + const urlStr = `${baseUrl}/exa.language_server_pb.LanguageServerService/${method}`; + const bodyText = JSON.stringify(body || {}); + const res = urlStr.startsWith('https://') + ? await postLoopbackHttpsJson(urlStr, csrfToken, bodyText, timeoutMs) + : await postLsRpcOnce(baseUrl, csrfToken, method, body || {}, timeoutMs); + if (res?.ok) { + return await res.json(); + } + const status = Number(res?.status || 0); + const text = await res?.text?.().catch(() => '') || ''; + tier1Err = new Error(`Remote RPC ${method} failed (${status}): ${text}`); + const isTransportAuthOrRouteMiss = + status === 0 || + status === 401 || + status === 403 || + (status === 404 && method !== 'GetCascadeTrajectory'); + if (isTransportAuthOrRouteMiss) { + markRemoteEndpointPreferTier2(endpoint); + } else { + // 业务级 4xx(如单个会话已被删除导致的 GetCascadeTrajectory 404)直接上抛,不误触熔断 + throw tier1Err; + } + } catch (err) { + if (err === tier1Err) { + throw err; + } + tier1Err = err; + markRemoteEndpointPreferTier2(endpoint); + } + } + + if (typeof windowInvoker === 'function') { + return windowInvoker(endpoint, method, body || {}, timeoutMs); + } + + if (tier1Err) { + throw tier1Err; + } + throw new Error(`Remote LS transport unavailable for endpoint ${endpoint.id}`); +} + /** - * 调用本地 `LanguageServerService` 的指定 RPC 方法(支持按需发现与宿主重启重连)。 + * 调用本地或远端 SSH `LanguageServerService` 的指定 RPC 方法(本地支持按需发现与宿主重启重连)。 * * @param {string} method RPC 方法名(如 `'GetUserStatus'`、`'GetCascadeTrajectory'`) * @param {object} [body={}] 请求 JSON 载荷 * @param {number} [timeoutMs=5000] 超时时间(毫秒) + * @param {object|null} [endpoint=null] 可选远端端点对象;缺省调用本机 LS * @returns {Promise} */ -export async function callLsRpc(method, body = {}, timeoutMs = 5000) { +export async function callLsRpc(method, body = {}, timeoutMs = 5000, endpoint = null) { + if (endpoint && endpoint.isRemote) { + return callRemoteEndpointLsRpc(endpoint, method, body, timeoutMs); + } + if (!lsRuntimeEndpoint.baseUrl && lsRuntimeEndpoint.addr !== 'test.invalid') { await ensureLsEndpointDiscovered({ force: false }); } @@ -113,35 +351,31 @@ export async function callLsRpc(method, body = {}, timeoutMs = 5000) { } /** - * 获取官方实时配额摘要(`RetrieveUserQuotaSummary`)。 - * - * 缓存策略: - * - 常规轮询在 10 秒内直接复用内存缓存,避免高频打满上游接口; - * - 常规轮询发生网络失败或空载荷时进入 5 秒冷却退避,避免每 2 秒重复超时阻塞; - * - 当超过 TTL 或传入 `forceRefresh = true`(如手动刷新或检测到账号切换)时, - * 向 LS 传递 `{ forceRefresh: true }`,绕过 `language_server.exe` 自身的 3 分钟缓存。 + * 获取官方实时配额摘要(`RetrieveUserQuotaSummary`),按端点与账号隔离短期缓存。 * * @param {boolean} [forceRefresh=false] 是否强制穿透本地缓存与失败冷却 * @param {string} [accountName=''] 发起查询时宿主报告的账号,用于隔离配额缓存 + * @param {object|null} [endpoint=null] 可选远端端点对象 * @returns {Promise<{data: object|null, fetchedAtMs: number, isStale: boolean, refreshFailed: boolean, error: string|null, fromCache: boolean}>} */ -export async function getOfficialQuotaSummary(forceRefresh = false, accountName = '') { - if (quotaSummaryCache.accountName !== accountName) { - Object.assign(quotaSummaryCache, { +export async function getOfficialQuotaSummary(forceRefresh = false, accountName = '', endpoint = null) { + const qCache = getEndpointQuotaCache(endpoint); + if (qCache.accountName !== accountName) { + Object.assign(qCache, { accountName, - accountGeneration: quotaSummaryCache.accountGeneration + 1, + accountGeneration: qCache.accountGeneration + 1, ts: 0, lastAttemptTs: 0, data: null, error: null, }); } - const generation = quotaSummaryCache.accountGeneration; + const generation = qCache.accountGeneration; const now = Date.now(); - if (!forceRefresh && quotaSummaryCache.data && now - quotaSummaryCache.ts < QUOTA_CACHE_TTL_MS) { + if (!forceRefresh && qCache.data && now - qCache.ts < QUOTA_CACHE_TTL_MS) { return { - data: quotaSummaryCache.data, - fetchedAtMs: quotaSummaryCache.ts, + data: qCache.data, + fetchedAtMs: qCache.ts, isStale: false, refreshFailed: false, error: null, @@ -150,35 +384,35 @@ export async function getOfficialQuotaSummary(forceRefresh = false, accountName } if ( !forceRefresh && - quotaSummaryCache.lastAttemptTs > 0 && - now - quotaSummaryCache.lastAttemptTs < QUOTA_RETRY_COOLDOWN_MS && - quotaSummaryCache.error + qCache.lastAttemptTs > 0 && + now - qCache.lastAttemptTs < QUOTA_RETRY_COOLDOWN_MS && + qCache.error ) { return { - data: quotaSummaryCache.data, - fetchedAtMs: quotaSummaryCache.ts || 0, - isStale: Boolean(quotaSummaryCache.data), + data: qCache.data, + fetchedAtMs: qCache.ts || 0, + isStale: Boolean(qCache.data), refreshFailed: true, - error: quotaSummaryCache.error, + error: qCache.error, fromCache: true, }; } - quotaSummaryCache.lastAttemptTs = now; + qCache.lastAttemptTs = now; try { - const res = await callLsRpc('RetrieveUserQuotaSummary', { forceRefresh: true }, 6000); - const { userStatus } = await callLsRpc('GetUserStatus', {}, 2000); + const res = await callLsRpc('RetrieveUserQuotaSummary', { forceRefresh: true }, 6000, endpoint); + const { userStatus } = await callLsRpc('GetUserStatus', {}, 2500, endpoint); if ((userStatus?.email || userStatus?.name || '') !== accountName) return {}; - if (generation !== quotaSummaryCache.accountGeneration) return {}; + if (generation !== qCache.accountGeneration) return {}; const payload = res?.response !== undefined ? res.response : res; if (payload && typeof payload === 'object' && !Array.isArray(payload)) { const normalized = Array.isArray(payload.groups) || Array.isArray(payload.buckets) ? payload : { ...payload, groups: [] }; - quotaSummaryCache.ts = now; - quotaSummaryCache.data = normalized; - quotaSummaryCache.error = null; + qCache.ts = now; + qCache.data = normalized; + qCache.error = null; return { data: normalized, fetchedAtMs: now, @@ -188,18 +422,18 @@ export async function getOfficialQuotaSummary(forceRefresh = false, accountName fromCache: false, }; } - quotaSummaryCache.error = 'Quota summary empty'; + qCache.error = 'Quota summary empty'; } catch (err) { - if (generation !== quotaSummaryCache.accountGeneration) return {}; + if (generation !== qCache.accountGeneration) return {}; console.error(`RetrieveUserQuotaSummary failed: ${err.message}`); - quotaSummaryCache.error = err.message; + qCache.error = err.message; } return { - data: quotaSummaryCache.data, - fetchedAtMs: quotaSummaryCache.ts || 0, - isStale: Boolean(quotaSummaryCache.data), + data: qCache.data, + fetchedAtMs: qCache.ts || 0, + isStale: Boolean(qCache.data), refreshFailed: true, - error: quotaSummaryCache.error || 'Quota RPC unavailable', + error: qCache.error || 'Quota RPC unavailable', fromCache: false, }; } diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index 0f94893..5cdbf3d 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -10,6 +10,7 @@ */ import { isDeepStrictEqual } from 'node:util'; +import { LOCAL_ENDPOINT_ID } from '../shared/window-bridge-protocol.mjs'; import { scaleBucketsExact } from '../shared/telemetry-display-rules.mjs'; import { extractLiveActivity, @@ -22,14 +23,13 @@ import { import { CLI_STATUS_SNAPSHOT_FILE, computeRuntimeCodeVersion, - getCachedTrajectory, inFlightRequests, - listCachedTrajectoryEntries, loadSettings, lsRuntimeEndpoint, roundMetric, saveJson, } from './config.mjs'; +import { getEndpointCacheStore } from './endpoint-registry.mjs'; import { getContextWindowGroups, getContextWindowModels } from './context-windows.mjs'; import { readLocalSummarySnapshot } from './cli-sqlite-reader.mjs'; import { enumerateAndSyncConversations } from './local-scanner.mjs'; @@ -57,17 +57,30 @@ import { const MAX_RECENT_CONVERSATIONS = 30; const MAX_CONVERSATION_ASSEMBLY_CACHE = 8; +const MAX_TELEMETRY_SNAPSHOT_ENDPOINTS = 8; const POOL_PRIORITY_ORDER = ['Gemini', 'Argon', 'Carbon', 'Claude & GPT']; const inFlightTelemetrySources = new Map(); const trajectoryModelFacts = new WeakMap(); let agentStepPrepCache = new WeakMap(); const conversationAssemblyCache = new Map(); -let lastCompletedTelemetrySnapshot = null; +const lastCompletedTelemetrySnapshotsByEndpoint = new Map(); -export function clearTelemetryBuilderMemo() { +export function clearTelemetryBuilderMemo(endpointId = null) { + if (endpointId) { + const epKey = String(endpointId); + lastCompletedTelemetrySnapshotsByEndpoint.delete(epKey); + const prefix = `${epKey}::`; + for (const key of Array.from(conversationAssemblyCache.keys())) { + if (key.startsWith(prefix)) { + conversationAssemblyCache.delete(key); + } + } + clearUsageAggregatorMemo(epKey); + return; + } agentStepPrepCache = new WeakMap(); conversationAssemblyCache.clear(); - lastCompletedTelemetrySnapshot = null; + lastCompletedTelemetrySnapshotsByEndpoint.clear(); clearUsageAggregatorMemo(); } @@ -76,12 +89,13 @@ function roundSessionCost(val) { return val < 0.01 ? +val.toFixed(4) : +val.toFixed(2); } -function findTrajectoryCacheEntry(cascadeId) { +function findTrajectoryCacheEntry(cascadeId, cacheStore = null) { if (!cascadeId) return null; - const entry = getCachedTrajectory(cascadeId); + const store = cacheStore || getEndpointCacheStore(null); + const entry = store.getCachedTrajectory(cascadeId); if (entry) return entry; const targetLower = String(cascadeId).toLowerCase(); - for (const [k, v] of listCachedTrajectoryEntries()) { + for (const [k, v] of store.listCachedTrajectoryEntries()) { if (k.toLowerCase() === targetLower) return v; } return null; @@ -120,9 +134,10 @@ function readTrajectoryModelFacts(steps) { } /** 合并各会话的上游模型与上下文上限,步骤数组更新后重新提取对应会话的数据。 */ -function buildKnownUpstreamModelMap(contextLimits) { +function buildKnownUpstreamModelMap(contextLimits, cacheStore = null) { + const store = cacheStore || getEndpointCacheStore(null); const knownUpstreamByModelKey = new Map(); - for (const [, entry] of listCachedTrajectoryEntries()) { + for (const [, entry] of store.listCachedTrajectoryEntries()) { if (!entry?.steps?.length) continue; const facts = readTrajectoryModelFacts(entry.steps); for (const [key, model] of facts.upstream) knownUpstreamByModelKey.set(key, model); @@ -736,14 +751,24 @@ export function buildAgentUnitTelemetry({ }; } -async function readTelemetrySources(requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus) { - const localSummaries = readLocalSummarySnapshot(undefined, { forceRefresh: forceQuotaRefresh }); +async function readTelemetrySources( + requestedConvId, + forceQuotaRefresh, + currentAccountName, + accountScope, + userStatus, + endpoint = null +) { + const isRemote = Boolean(endpoint && endpoint.isRemote); + const localSummaries = isRemote + ? { available: false, summariesObj: {}, sideQuestionParents: {} } + : readLocalSummarySnapshot(undefined, { forceRefresh: forceQuotaRefresh }); const [allTrajRes, officialQuotaInfo, contextModelCatalog] = await Promise.all([ localSummaries.available ? Promise.resolve(null) - : callLsRpc('GetAllCascadeTrajectories', {}).catch(() => ({})), - userStatus ? getOfficialQuotaSummary(forceQuotaRefresh, currentAccountName) : null, - getContextModelCatalog(), + : callLsRpc('GetAllCascadeTrajectories', {}, 5000, endpoint).catch(() => ({})), + userStatus ? getOfficialQuotaSummary(forceQuotaRefresh, currentAccountName, endpoint) : null, + getContextModelCatalog(endpoint), ]); const sessions = await enumerateAndSyncConversations({ @@ -754,16 +779,25 @@ async function readTelemetrySources(requestedConvId, forceQuotaRefresh, currentA currentAccountName: accountScope, requestedConvId, forceRefresh: forceQuotaRefresh, + endpoint, }); return { officialQuotaInfo, contextModelCatalog, sessions }; } -function getTelemetrySources(requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus) { +function getTelemetrySources( + requestedConvId, + forceQuotaRefresh, + currentAccountName, + accountScope, + userStatus, + endpoint = null +) { + const endpointKey = endpoint?.isRemote ? String(endpoint.id || 'remote') : LOCAL_ENDPOINT_ID; const read = () => readTelemetrySources( - requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus + requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus, endpoint ); if (forceQuotaRefresh) return read(); - const key = JSON.stringify([requestedConvId || '', accountScope, Boolean(userStatus)]); + const key = JSON.stringify([endpointKey, requestedConvId || '', accountScope, Boolean(userStatus)]); const existing = inFlightTelemetrySources.get(key); if (existing) return existing; const pending = read().finally(() => { @@ -781,12 +815,17 @@ function buildActiveConversationAssembly({ knownUpstreamByModelKey, modelInputs, accountScope, + endpointId = LOCAL_ENDPOINT_ID, + cacheStore = null, }) { const activeSteps = activeEntry?.steps || []; const subagentSummaries = activeConvSummary?.subagents || []; - const cacheKey = String(activeCascadeId || '__empty__').toLowerCase(); + const epKey = String(endpointId || LOCAL_ENDPOINT_ID); + const cacheKey = `${epKey}::${String(activeCascadeId || '__empty__').toLowerCase()}`; - const subEntries = subagentSummaries.map((subSum) => findTrajectoryCacheEntry(subSum.cascadeId)); + const subEntries = subagentSummaries.map((subSum) => + findTrajectoryCacheEntry(subSum.cascadeId, cacheStore) + ); const subRawStepsList = subEntries.map((entry) => entry?.steps || []); const combinedFallbackKeys = new Set(); for (const k of readTrajectoryModelFacts(activeSteps).fallbackModelKeys) { @@ -849,7 +888,7 @@ function buildActiveConversationAssembly({ return cachedAssembly.result; } - const agentReuseInputs = { ...modelInputs, activeCascadeId, accountScope }; + const agentReuseInputs = { ...modelInputs, endpointId: epKey, activeCascadeId, accountScope }; const mainUnit = buildAgentUnitTelemetry({ agentId: 'main', cascadeId: activeCascadeId, @@ -1492,7 +1531,7 @@ function buildActivePoolAndWeeklyQuotas({ * * @param {string} requestedConvId 请求指定的会话 ID(为空时自动选定最近活跃会话) * @param {boolean} [forceQuotaRefresh=false] 是否强制穿透官方配额缓存与失败退避 - * @param {{ range?: string, startMs?: number, endMs?: number }} [filterOpts={}] 时间范围筛选选项 + * @param {{ range?: string, startMs?: number, endMs?: number, endpoint?: object|null }} [filterOpts={}] 时间范围筛选选项与可选远端端点 * @returns {Promise} */ export async function buildTelemetryPayloadInternal( @@ -1500,11 +1539,18 @@ export async function buildTelemetryPayloadInternal( forceQuotaRefresh = false, filterOpts = {} ) { + const endpoint = filterOpts?.endpoint && filterOpts.endpoint.isRemote ? filterOpts.endpoint : null; + const isRemote = Boolean(endpoint); + const endpointId = isRemote ? String(endpoint.id || 'remote') : LOCAL_ENDPOINT_ID; + const endpointLabel = isRemote ? String(endpoint.label || 'SSH') : ''; + const cacheStore = getEndpointCacheStore(endpoint); + const settings = loadSettings(); - let userStatus = await callLsRpc('GetUserStatus', {}) + let userStatus = await callLsRpc('GetUserStatus', {}, 5000, endpoint) .then((data) => data?.userStatus) .catch(() => null); if ( + !isRemote && !userStatus && lsRuntimeEndpoint.addr !== 'test.invalid' && (!lsRuntimeEndpoint.baseUrl || lsRuntimeEndpoint.isDynamic) @@ -1529,7 +1575,7 @@ export async function buildTelemetryPayloadInternal( userStatus && !userStatus.userTier && !userStatus.planStatus ? 'signedOut' : 'unknown'; const accountScope = accountStatus === 'signedOut' ? null : currentAccountName; const { officialQuotaInfo, contextModelCatalog, sessions } = await getTelemetrySources( - requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus + requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus, endpoint ); const { conversations, activeConvSummary, activeCascadeId } = sessions; @@ -1546,8 +1592,8 @@ export async function buildTelemetryPayloadInternal( // 3. 计算当前活跃根会话及其子代理的步骤指标、10 通道上下文拆解与按模型汇总 const reportedContextLimits = new Map(); - const knownUpstreamByModelKey = buildKnownUpstreamModelMap(reportedContextLimits); - const activeEntry = findTrajectoryCacheEntry(activeCascadeId); + const knownUpstreamByModelKey = buildKnownUpstreamModelMap(reportedContextLimits, cacheStore); + const activeEntry = findTrajectoryCacheEntry(activeCascadeId, cacheStore); const modelInputs = { catalogRevision: pricingCatalogRevision, phaseEpoch: getPricingPhaseEpoch(), @@ -1565,6 +1611,8 @@ export async function buildTelemetryPayloadInternal( knownUpstreamByModelKey, modelInputs, accountScope, + endpointId, + cacheStore, }); // 4. 识别当前活跃会话家族绑定的模型池(与 quota-pools.mjs 保持一致,将 Other 第三方模型归入 Claude & GPT) @@ -1623,6 +1671,7 @@ export async function buildTelemetryPayloadInternal( resolveStepModel, quotaPoolsMap, modelInputs, + endpoint, }); for (const [pk, poolObj] of quotaPoolsMap.entries()) { @@ -1665,7 +1714,7 @@ export async function buildTelemetryPayloadInternal( if (cidKey && quickStatsMemo.has(cidKey)) { return quickStatsMemo.get(cidKey); } - const rootEntry = findTrajectoryCacheEntry(rootConv?.cascadeId); + const rootEntry = findTrajectoryCacheEntry(rootConv?.cascadeId, cacheStore); const rootSteps = rootEntry?.steps || []; const rawSubs = Array.isArray(rootConv?.subagents) ? rootConv.subagents : []; @@ -1686,7 +1735,7 @@ export async function buildTelemetryPayloadInternal( let bestMetricRunning = rootConv?.status === 'CASCADE_RUN_STATUS_RUNNING' && Boolean(lastRootStep); for (const subSum of rawSubs) { - const subEntry = findTrajectoryCacheEntry(subSum?.cascadeId); + const subEntry = findTrajectoryCacheEntry(subSum?.cascadeId, cacheStore); const subSteps = subEntry?.steps || []; if (subSteps.length === 0) continue; accumulateStepsCost(subSteps); @@ -1752,7 +1801,7 @@ export async function buildTelemetryPayloadInternal( continue; } - const rootEntry = findTrajectoryCacheEntry(rootConv.cascadeId); + const rootEntry = findTrajectoryCacheEntry(rootConv.cascadeId, cacheStore); const rootFallbackMs = rootConv.lastModifiedMs || rootEntry?.lastModifiedMs || rootConv.createdTimeMs || 0; @@ -1761,7 +1810,7 @@ export async function buildTelemetryPayloadInternal( let runSideIdx = 0; const subItems = rawSubs.map((subSum, idx) => { const subCid = subSum.cascadeId; - const subEntry = findTrajectoryCacheEntry(subCid); + const subEntry = findTrajectoryCacheEntry(subCid, cacheStore); const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null; const isSideQ = Boolean( subSum.isSideQuestion || subEntry?.isSideQuestion || subSpec?.typeName === 'side_question' @@ -2016,6 +2065,11 @@ export async function buildTelemetryPayloadInternal( const finalPayload = { timestamp: new Date().toISOString(), hostPlatform: process.platform || 'unknown', + endpoint: { + id: endpointId, + isRemote, + label: endpointLabel, + }, uiBundleVersion, windowBridge: getDefaultWindowBridgeStatus(), settings: loadSettings(), @@ -2104,8 +2158,20 @@ export async function buildTelemetryPayloadInternal( modelBreakdown, }; - lastCompletedTelemetrySnapshot = { - lsAddr: String(lsRuntimeEndpoint.addr || ''), + const endpointSig = isRemote + ? `${Number(endpoint?.instanceId || 0)}|${String(endpoint?.baseUrl || '')}|${String(endpoint?.csrfToken || '')}` + : String(lsRuntimeEndpoint.addr || ''); + lastCompletedTelemetrySnapshotsByEndpoint.delete(endpointId); + if (lastCompletedTelemetrySnapshotsByEndpoint.size >= MAX_TELEMETRY_SNAPSHOT_ENDPOINTS) { + const oldestKey = lastCompletedTelemetrySnapshotsByEndpoint.keys().next().value; + if (oldestKey !== undefined) { + lastCompletedTelemetrySnapshotsByEndpoint.delete(oldestKey); + } + } + lastCompletedTelemetrySnapshotsByEndpoint.set(endpointId, { + endpointId, + isRemote, + endpointSig, weeklyLimitMode: settings.weeklyLimitMode, weeklyTokenBudget: settings.weeklyTokenBudget, weeklyCostBudget: settings.weeklyCostBudget, @@ -2132,10 +2198,11 @@ export async function buildTelemetryPayloadInternal( resolveStepModel, quotaPoolsMap, modelInputs, + endpoint, }, - }; + }); - if (lsRuntimeEndpoint.addr !== 'test.invalid') { + if (!isRemote && lsRuntimeEndpoint.addr !== 'test.invalid') { try { saveJson(CLI_STATUS_SNAPSHOT_FILE, buildCliStatusSnapshot(finalPayload, Date.now())); } catch { @@ -2146,10 +2213,15 @@ export async function buildTelemetryPayloadInternal( return finalPayload; } -function resolveValidFastSnapshot() { - const snap = lastCompletedTelemetrySnapshot; +function resolveValidFastSnapshot(endpoint = null) { + const isRemote = Boolean(endpoint?.isRemote); + const endpointId = isRemote ? String(endpoint.id || 'remote') : LOCAL_ENDPOINT_ID; + const snap = lastCompletedTelemetrySnapshotsByEndpoint.get(endpointId); if (!snap || !snap.basePayload || !snap.aggContext) return null; - if (snap.lsAddr !== String(lsRuntimeEndpoint.addr || '')) return null; + const expectedSig = isRemote + ? `${Number(endpoint?.instanceId || 0)}|${String(endpoint?.baseUrl || '')}|${String(endpoint?.csrfToken || '')}` + : String(lsRuntimeEndpoint.addr || ''); + if (snap.endpointSig !== expectedSig) return null; if ( snap.catalogRevision !== pricingCatalogRevision || snap.phaseEpoch !== getPricingPhaseEpoch() @@ -2177,7 +2249,10 @@ function entryNeedsLazyTelemetryUpgrade(entry) { } function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) { - const snap = resolveValidFastSnapshot(); + const endpoint = filterOpts?.endpoint && filterOpts.endpoint.isRemote ? filterOpts.endpoint : null; + const endpointId = endpoint ? String(endpoint.id || 'remote') : LOCAL_ENDPOINT_ID; + const cacheStore = getEndpointCacheStore(endpoint); + const snap = resolveValidFastSnapshot(endpoint); if (!snap || !Array.isArray(snap.sessions?.conversations)) return null; const convList = snap.sessions.conversations; @@ -2192,7 +2267,7 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) { if (!activeConvSummary?.cascadeId) return null; const activeCascadeId = activeConvSummary.cascadeId; - const activeEntry = findTrajectoryCacheEntry(activeCascadeId); + const activeEntry = findTrajectoryCacheEntry(activeCascadeId, cacheStore); if (!activeEntry) return null; const subagentSummaries = Array.isArray(activeConvSummary.subagents) @@ -2207,7 +2282,7 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) { needsBackgroundSync = true; break; } - const subEntry = findTrajectoryCacheEntry(subSum?.cascadeId); + const subEntry = findTrajectoryCacheEntry(subSum?.cascadeId, cacheStore); if (!subEntry || entryNeedsLazyTelemetryUpgrade(subEntry)) { needsBackgroundSync = true; break; @@ -2228,6 +2303,8 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) { knownUpstreamByModelKey: snap.knownUpstreamByModelKey, modelInputs: snap.aggContext.modelInputs, accountScope: snap.aggContext.currentAccountName, + endpointId, + cacheStore, }); const { activePoolKey, activeLive5h, activeLiveWeekly } = resolveActivePoolKeyFromStep( @@ -2255,11 +2332,13 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) { activeFamilyCascadeIds, resolveStepModel: snap.aggContext.resolveStepModel, quotaPoolsMap: snap.quotaContext.quotaPoolsMap, + endpoint, }); return { scope: 'conversation', timestamp: new Date().toISOString(), + endpoint: snap.basePayload.endpoint, uiBundleVersion: snap.basePayload.uiBundleVersion || computeRuntimeCodeVersion(), account: snap.basePayload.account, activeCascadeId, @@ -2277,15 +2356,18 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) { } function tryBuildFastConsumptionPayload(filterOpts = {}) { - const snap = resolveValidFastSnapshot(); + const endpoint = filterOpts?.endpoint && filterOpts.endpoint.isRemote ? filterOpts.endpoint : null; + const snap = resolveValidFastSnapshot(endpoint); if (!snap) return null; const agg = aggregateSelectedWindowUsage({ filterOpts, ...snap.aggContext, + endpoint, }); return { scope: 'consumption', timestamp: new Date().toISOString(), + endpoint: snap.basePayload.endpoint, uiBundleVersion: snap.basePayload.uiBundleVersion || computeRuntimeCodeVersion(), usageRevision: agg.usageRevision, consumption: { @@ -2305,13 +2387,18 @@ function tryBuildFastConsumptionPayload(filterOpts = {}) { }; } -function tryBuildConsumptionPresetsPayload() { - const snap = resolveValidFastSnapshot(); +function tryBuildConsumptionPresetsPayload(filterOpts = {}) { + const endpoint = filterOpts?.endpoint && filterOpts.endpoint.isRemote ? filterOpts.endpoint : null; + const snap = resolveValidFastSnapshot(endpoint); if (!snap) return null; - const bundle = aggregateConsumptionPresetBundle(snap.aggContext); + const bundle = aggregateConsumptionPresetBundle({ + ...snap.aggContext, + endpoint, + }); return { scope: 'consumption-presets', timestamp: new Date().toISOString(), + endpoint: snap.basePayload.endpoint, uiBundleVersion: snap.basePayload.uiBundleVersion || computeRuntimeCodeVersion(), usageRevision: bundle.usageRevision, ranges: bundle.ranges, @@ -2370,6 +2457,9 @@ export function buildTelemetryPayload( forceQuotaRefresh = false, filterOpts = {} ) { + const endpointKey = filterOpts?.endpoint?.isRemote + ? String(filterOpts.endpoint.id || 'remote') + : LOCAL_ENDPOINT_ID; if (!forceQuotaRefresh) { if (filterOpts?.scope === 'conversation') { const convPayload = tryBuildFastConversationPayload(requestedConvId, filterOpts); @@ -2378,16 +2468,19 @@ export function buildTelemetryPayload( } } if (filterOpts?.scope === 'consumption-presets') { - const presetsPayload = tryBuildConsumptionPresetsPayload(); + const presetsPayload = tryBuildConsumptionPresetsPayload(filterOpts); if (presetsPayload) { return Promise.resolve(presetsPayload); } - const key = `${requestedConvId || '__auto__'}::presets-cold`; + const key = `${endpointKey}::${requestedConvId || '__auto__'}::presets-cold`; if (inFlightRequests.has(key)) { return inFlightRequests.get(key); } - const p = buildTelemetryPayloadInternal(requestedConvId, false, { range: 'today' }) - .then(() => tryBuildConsumptionPresetsPayload()) + const coldFilterOpts = filterOpts?.endpoint + ? { range: 'today', endpoint: filterOpts.endpoint } + : { range: 'today' }; + const p = buildTelemetryPayloadInternal(requestedConvId, false, coldFilterOpts) + .then(() => tryBuildConsumptionPresetsPayload(filterOpts)) .finally(() => { inFlightRequests.delete(key); }); @@ -2402,7 +2495,7 @@ export function buildTelemetryPayload( } } const rangeSig = `${filterOpts.range || 'all'}:${filterOpts.startMs || 0}:${filterOpts.endMs || 0}`; - const key = `${requestedConvId || '__auto__'}::${forceQuotaRefresh ? 'force' : 'normal'}::${rangeSig}`; + const key = `${endpointKey}::${requestedConvId || '__auto__'}::${forceQuotaRefresh ? 'force' : 'normal'}::${rangeSig}`; if (inFlightRequests.has(key)) { return inFlightRequests.get(key); } diff --git a/sidecars/panel/backend/trajectory-cache-file.mjs b/sidecars/panel/backend/trajectory-cache-file.mjs index 58fbdeb..70c33ae 100644 --- a/sidecars/panel/backend/trajectory-cache-file.mjs +++ b/sidecars/panel/backend/trajectory-cache-file.mjs @@ -3,7 +3,8 @@ import { } from 'node:fs'; import { randomUUID } from 'node:crypto'; -let lastWrite = null; +const MAX_TRACKED_CACHE_FILES = 16; +const lastWritesByPath = new Map(); function isSameFile(a, b) { return b.ino !== 0n && a.dev === b.dev && a.ino === b.ino && @@ -29,7 +30,7 @@ function readReusableBytes(filePath, expected) { // 只复用上次确认写入的步骤字节。扫描器用新数组替换变更步骤,每次仍重新序列化会话元数据。 export function writeTrajectoryCacheFile(filePath, data) { - const previous = lastWrite?.filePath === filePath ? lastWrite : null; + const previous = lastWritesByPath.get(filePath) || null; const bytes = previous ? readReusableBytes(filePath, previous.file) : null; const ranges = new WeakMap(); const parts = []; @@ -72,7 +73,14 @@ export function writeTrajectoryCacheFile(filePath, data) { const written = statSync(temporaryPath, { bigint: true }); renameSync(temporaryPath, filePath); const file = statSync(filePath, { bigint: true }); - lastWrite = isSameFile(written, file) ? { filePath, file, ranges } : null; + lastWritesByPath.delete(filePath); + if (isSameFile(written, file)) { + if (lastWritesByPath.size >= MAX_TRACKED_CACHE_FILES) { + const oldestPath = lastWritesByPath.keys().next().value; + if (oldestPath !== undefined) lastWritesByPath.delete(oldestPath); + } + lastWritesByPath.set(filePath, { filePath, file, ranges }); + } } finally { try { unlinkSync(temporaryPath); } catch {} } diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs index d196032..824f8b5 100644 --- a/sidecars/panel/backend/usage-aggregator.mjs +++ b/sidecars/panel/backend/usage-aggregator.mjs @@ -14,7 +14,8 @@ import { finishSpeed, parseIsoMs, } from '../trajectory-metrics.mjs'; -import { listCachedTrajectoryEntries, roundMetric } from './config.mjs'; +import { roundMetric } from './config.mjs'; +import { getEndpointCacheStore } from './endpoint-registry.mjs'; import { loadExternalDeepStatsCache } from './local-scanner.mjs'; import { computeStepCost, @@ -430,7 +431,8 @@ export function buildScopedModelBreakdown(steps, resolveStepModel) { return finalizeModelBreakdownMap(perModelStats); } -let lastUsageSnapshot = null; +const MAX_USAGE_SNAPSHOT_ENDPOINTS = 8; +const lastUsageSnapshotsByEndpoint = new Map(); let usageSnapshotRevisionSeq = 0; const stepsTimeBoundsCache = new WeakMap(); const MAX_TREND_TIMESTAMP_MS = 8_640_000_000_000_000; @@ -439,10 +441,15 @@ const USAGE_SOURCE_LABELS = { standalone: 'Antigravity App', ide: 'Antigravity IDE', cli: 'Antigravity CLI', + ssh: 'Antigravity SSH', }; -export function clearUsageAggregatorMemo() { - lastUsageSnapshot = null; +export function clearUsageAggregatorMemo(endpointId = null) { + if (endpointId) { + lastUsageSnapshotsByEndpoint.delete(String(endpointId)); + } else { + lastUsageSnapshotsByEndpoint.clear(); + } usageSnapshotRevisionSeq += 1; } @@ -466,12 +473,14 @@ function getStepsTimeBounds(steps) { return bounds; } -function collectUsageEntriesToAggregate(familySet) { - const externalConvos = loadExternalDeepStatsCache(); +function collectUsageEntriesToAggregate(familySet, endpoint = null) { + const isRemote = Boolean(endpoint && endpoint.isRemote); + const cacheStore = getEndpointCacheStore(endpoint); + const externalConvos = isRemote ? new Map() : loadExternalDeepStatsCache(); // 构建大小写归一化的内存缓存与跨端深层缓存索引,彻底杜绝 `${appSource}:${cascadeId}` 键不匹配导致的双倍重复计费 const allLiveByLower = new Map(); - for (const [rawId, entry] of listCachedTrajectoryEntries()) { + for (const [rawId, entry] of cacheStore.listCachedTrajectoryEntries()) { const cidLower = String(rawId || '').toLowerCase(); if (!cidLower || !entry || typeof entry !== 'object') continue; const prev = allLiveByLower.get(cidLower); @@ -502,7 +511,7 @@ function collectUsageEntriesToAggregate(familySet) { ).toLowerCase(); allEntriesToAggregate.push({ cascadeId: groupCascadeId, - appSource: entry?.appSource || 'standalone', + appSource: isRemote ? 'ssh' : entry?.appSource || 'standalone', accountName: entry?.accountName || extMatch?.accountName || '', steps: entry?.steps || [], isCurrentConv: familySet.has(cidLower), @@ -1051,7 +1060,10 @@ export function aggregateMultiWindowUsage({ resolveStepModel, quotaPoolsMap = null, modelInputs = null, + endpoint = null, }) { + const isRemote = Boolean(endpoint && endpoint.isRemote); + const endpointKey = isRemote ? String(endpoint.id || 'remote') : 'local'; const rawFamilyIds = activeFamilyCascadeIds instanceof Set ? Array.from(activeFamilyCascadeIds) @@ -1117,7 +1129,7 @@ export function aggregateMultiWindowUsage({ })); const perSourceStats = new Map(); - const allEntriesToAggregate = collectUsageEntriesToAggregate(familySet); + const allEntriesToAggregate = collectUsageEntriesToAggregate(familySet, endpoint); const familySig = buildFamilySig(familySet); const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : ''; @@ -1126,7 +1138,7 @@ export function aggregateMultiWindowUsage({ { key: `${key}:week`, startMs: startWkMs, endMs: nowMs }, ]).flat(); const windows = [selectedWindow, ...Object.values(presetWindows), ...quotaWindows]; - const snapshot = lastUsageSnapshot; + const snapshot = lastUsageSnapshotsByEndpoint.get(endpointKey) || null; const sameSnapshot = modelInputs && snapshot && timeZone === snapshot.timeZone && currentYear === snapshot.currentYear && Boolean(isCustomWeeklyMode) === Boolean(snapshot.isCustomWeeklyMode) && @@ -1459,10 +1471,11 @@ export function aggregateMultiWindowUsage({ : null; let resolvedUsageRevision = usageSnapshotRevisionSeq; + let activeSnap = snapshot; if (modelInputs) { if (!sameSnapshot) { resolvedUsageRevision = ++usageSnapshotRevisionSeq; - lastUsageSnapshot = { + activeSnap = { revision: resolvedUsageRevision, timeZone, modelInputs, @@ -1474,8 +1487,14 @@ export function aggregateMultiWindowUsage({ ranges: new Map(), selectedRanges: new Map(), }; + lastUsageSnapshotsByEndpoint.delete(endpointKey); + if (lastUsageSnapshotsByEndpoint.size >= MAX_USAGE_SNAPSHOT_ENDPOINTS) { + const oldestKey = lastUsageSnapshotsByEndpoint.keys().next().value; + if (oldestKey !== undefined) lastUsageSnapshotsByEndpoint.delete(oldestKey); + } + lastUsageSnapshotsByEndpoint.set(endpointKey, activeSnap); } else { - resolvedUsageRevision = lastUsageSnapshot.revision; + resolvedUsageRevision = activeSnap.revision; } } else { resolvedUsageRevision = ++usageSnapshotRevisionSeq; @@ -1500,8 +1519,8 @@ export function aggregateMultiWindowUsage({ poolCycleStats, poolsWeeklySummary, }; - if (modelInputs && lastUsageSnapshot) { - const { ranges } = lastUsageSnapshot; + if (modelInputs && activeSnap) { + const { ranges } = activeSnap; ranges.delete(selectedWindow.key); ranges.set(selectedWindow.key, { familySig, @@ -1536,7 +1555,10 @@ export function aggregateSelectedWindowUsage({ quotaPoolsMap = null, modelInputs = null, precollectedEntries = null, + endpoint = null, }) { + const isRemote = Boolean(endpoint && endpoint.isRemote); + const endpointKey = isRemote ? String(endpoint.id || 'remote') : 'local'; const rawFamilyIds = activeFamilyCascadeIds instanceof Set ? Array.from(activeFamilyCascadeIds) @@ -1567,12 +1589,12 @@ export function aggregateSelectedWindowUsage({ const allEntriesToAggregate = Array.isArray(precollectedEntries) ? precollectedEntries - : collectUsageEntriesToAggregate(familySet); + : collectUsageEntriesToAggregate(familySet, endpoint); const familySig = buildFamilySig(familySet); const currentYear = new Date(nowMs).getFullYear(); const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : ''; - const snapshot = lastUsageSnapshot; + const snapshot = lastUsageSnapshotsByEndpoint.get(endpointKey) || null; const sameSnapshot = Boolean( modelInputs && snapshot && @@ -1885,7 +1907,10 @@ export function aggregateSessionUsageForFamily({ activeFamilyCascadeIds = null, resolveStepModel, quotaPoolsMap = null, + endpoint = null, }) { + const isRemote = Boolean(endpoint && endpoint.isRemote); + const cacheStore = getEndpointCacheStore(endpoint); const rawFamilyIds = activeFamilyCascadeIds instanceof Set ? Array.from(activeFamilyCascadeIds) @@ -1912,13 +1937,13 @@ export function aggregateSessionUsageForFamily({ currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName); const familyEntries = []; - for (const [cid, entry] of listCachedTrajectoryEntries()) { + for (const [cid, entry] of cacheStore.listCachedTrajectoryEntries()) { if (!entry || !Array.isArray(entry.steps) || entry.steps.length === 0) continue; const cidLower = String(cid || '').toLowerCase(); if (!familySet.has(cidLower)) continue; familyEntries.push({ cascadeId: cid, - appSource: entry.appSource || 'standalone', + appSource: isRemote ? 'ssh' : entry.appSource || 'standalone', accountName: entry.accountName || '', steps: entry.steps, isCurrentConv: true, @@ -1943,7 +1968,7 @@ export function aggregateSessionUsageForFamily({ * 批量预聚合全部 7 个用量页预设区间(复用同一次条目收集与时间剪枝),供前端进入「用量统计」时静默预取实现 0ms 瞬切。 */ export function aggregateConsumptionPresetBundle(params) { - const { activeCascadeId = null, activeFamilyCascadeIds = null } = params || {}; + const { activeCascadeId = null, activeFamilyCascadeIds = null, endpoint = null } = params || {}; const rawFamilyIds = activeFamilyCascadeIds instanceof Set ? Array.from(activeFamilyCascadeIds) @@ -1951,7 +1976,7 @@ export function aggregateConsumptionPresetBundle(params) { ? [activeCascadeId] : []; const familySet = new Set(rawFamilyIds.map((id) => String(id || '').toLowerCase())); - const precollectedEntries = collectUsageEntriesToAggregate(familySet); + const precollectedEntries = collectUsageEntriesToAggregate(familySet, endpoint); const ranges = {}; let usageRevision = usageSnapshotRevisionSeq; diff --git a/sidecars/panel/backend/window-bridge.mjs b/sidecars/panel/backend/window-bridge.mjs index eddc4b5..d427d2c 100644 --- a/sidecars/panel/backend/window-bridge.mjs +++ b/sidecars/panel/backend/window-bridge.mjs @@ -24,6 +24,9 @@ import { dirname, join } from 'node:path'; import { BRIDGE_API_PATHS, CONTEXT_WINDOWS_GLOBAL_KEY, + LOCAL_ENDPOINT_ID, + WINDOW_BRIDGE_ENDPOINT_HEADER, + WINDOW_BRIDGE_ENDPOINT_KEY, WINDOW_BRIDGE_KEY, WINDOW_BRIDGE_ROUTE_KEY, WINDOW_OVERLAY_KEY, @@ -47,12 +50,22 @@ import { ensureDesktopLaunchEntriesConfigured, resolveDesktopHostExecutable, } from './desktop-launcher-config.mjs'; +import { + getRegisteredRemoteEndpoint, + getRemoteEndpointTargetWsUrls, + normalizeEndpointId, + pruneStaleRemoteEndpoints, + registerRemoteEndpoint, + setRemoteWindowRpcInvoker, +} from './endpoint-registry.mjs'; +import { getLocalHubPorts } from './ls-discovery.mjs'; import { callLsRpc, getContextModelCatalog } from './ls-rpc.mjs'; const windowBridgeRef = `window[${JSON.stringify(WINDOW_BRIDGE_KEY)}]`; const windowOverlayRef = `window[${JSON.stringify(WINDOW_OVERLAY_KEY)}]`; const windowContextWindowsRef = `window[${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}]`; const windowBridgeRouteKey = JSON.stringify(WINDOW_BRIDGE_ROUTE_KEY); +const windowBridgeEndpointKey = JSON.stringify(WINDOW_BRIDGE_ENDPOINT_KEY); const overlayMethods = Object.fromEntries( Object.entries(WINDOW_OVERLAY_METHODS).map(([method, key]) => [method, JSON.stringify(key)]) ); @@ -719,6 +732,290 @@ export function associateIdeIframeRoutes(rawTargets, mainTargets, options = unde }); } +/** + * 从窗口内的 `window.__APP_CONFIG__` 与标题提取远端 / SSH 主机标识元数据。 + * + * @param {object|null|undefined} appConfig + * @param {string} [title=''] + * @returns {{ hasExplicitRemoteFlag: boolean, stableHostKey: string, hostLabel: string }} + */ +export function extractRemoteHostMetadata(appConfig, title = '') { + const cfg = appConfig && typeof appConfig === 'object' ? appConfig : {}; + const rawHost = String( + cfg.sshHost || + cfg.sshHostName || + cfg.sshAlias || + cfg.sshTarget || + cfg.remoteHost || + cfg.remoteAuthority || + cfg.remoteName || + '' + ).trim(); + const cleanHost = rawHost.replace(/^ssh(?:-remote)?\+/i, '').trim(); + const hasExplicitRemoteFlag = Boolean( + cfg.isRemoteControl === true || + cfg.isRemote === true || + cfg.isSsh === true || + /^ssh/i.test(String(cfg.connectionType || cfg.windowMode || '').trim()) || + cleanHost + ); + + let bracketedTitleHost = ''; + const titleText = String(title || '').trim(); + if (titleText) { + const m = titleText.match(/\[SSH:\s*([^\]\r\n]+)\]/i); + if (m && m[1]) { + bracketedTitleHost = String(m[1]).trim(); + } + } + + const stableHostKey = cleanHost || bracketedTitleHost || ''; + const hostLabel = cleanHost || bracketedTitleHost || ''; + return { hasExplicitRemoteFlag, stableHostKey, hostLabel, bracketedTitleHost }; +} + +/** + * 依据三级优先级严格区分本地窗口与 SSH / 远端窗口,避免 2.33.0+ 无 `csrfToken` 或无 `hub_*.json` 时误判本地桌面窗口。 + * + * @param {{ + * target: object, + * probedInfo?: { origin?: string, csrfToken?: string, observedCsrfToken?: string, appConfig?: object, title?: string }|null, + * localHubInfo?: { allPorts?: Set, httpsPorts?: Set, csrfTokens?: Set }|null, + * confirmedLocalPorts?: Set|null, + * }} params + */ +export function classifyWindowTargetEndpoint({ + target, + probedInfo = null, + localHubInfo = null, + confirmedLocalPorts = null, +}) { + if (!target || target.isIdeWorkbench) { + return { isRemote: false, endpointId: LOCAL_ENDPOINT_ID, label: '', origin: '', csrfToken: '' }; + } + + let origin = String(probedInfo?.origin || '').trim(); + if (!origin) { + try { + const parsed = new URL(String(target.url || '')); + if (parsed.protocol === 'https:' || parsed.protocol === 'http:') { + origin = parsed.origin; + } + } catch { + origin = ''; + } + } + + let originPort = 0; + if (origin) { + try { + originPort = Number(new URL(origin).port || 0); + } catch { + originPort = 0; + } + } + + const allLocalPorts = localHubInfo?.allPorts instanceof Set ? localHubInfo.allPorts : new Set(); + const localHttpsPorts = localHubInfo?.httpsPorts instanceof Set ? localHubInfo.httpsPorts : new Set(); + const localCsrfTokens = localHubInfo?.csrfTokens instanceof Set ? localHubInfo.csrfTokens : new Set(); + const knownLocalPorts = confirmedLocalPorts instanceof Set ? confirmedLocalPorts : new Set(); + + const csrfToken = String(probedInfo?.csrfToken || probedInfo?.observedCsrfToken || '').trim(); + const remoteMeta = extractRemoteHostMetadata(probedInfo?.appConfig, probedInfo?.title || target.title || ''); + + // 1. 明确命中本机特征(端口或 CSRF 令牌匹配本机 Hub)且无显式远程标记 -> 本地窗口 + const matchesLocalPort = originPort > 0 && (allLocalPorts.has(originPort) || knownLocalPorts.has(originPort)); + const matchesLocalCsrf = Boolean(csrfToken && localCsrfTokens.has(csrfToken)); + if ((matchesLocalPort || matchesLocalCsrf) && !remoteMeta.hasExplicitRemoteFlag) { + return { + isRemote: false, + endpointId: LOCAL_ENDPOINT_ID, + label: '', + origin, + originPort, + csrfToken, + }; + } + + // 2. 明确命中远端 / SSH 特征(显式 SSH/Remote 标记,或携带与本机不同的非空 CSRF 令牌) + const hasDifferentCsrf = Boolean(csrfToken && localCsrfTokens.size > 0 && !localCsrfTokens.has(csrfToken)); + if (remoteMeta.hasExplicitRemoteFlag || hasDifferentCsrf) { + return { + isRemote: true, + origin, + originPort, + csrfToken, + stableHostKey: remoteMeta.stableHostKey, + hostLabel: remoteMeta.hostLabel || (originPort > 0 ? `SSH:${originPort}` : 'SSH'), + }; + } + + // 3. 2.33.0+ 省略 csrfToken 时的端口不匹配兜底:仅当存在已确认的本机 HTTPS 端口或已确认本地窗口端口时启用 + const hasConfirmedLocalDesktopPort = localHttpsPorts.size > 0 || knownLocalPorts.size > 0; + if (originPort > 0 && hasConfirmedLocalDesktopPort && !matchesLocalPort) { + return { + isRemote: true, + origin, + originPort, + csrfToken, + stableHostKey: remoteMeta.stableHostKey, + hostLabel: remoteMeta.hostLabel || `SSH:${originPort}`, + }; + } + + return { + isRemote: false, + endpointId: LOCAL_ENDPOINT_ID, + label: '', + origin, + originPort, + csrfToken, + }; +} + +/** + * 构建无状态、按需执行的窗口内同源 LS RPC 表达式(Tier-2 传输,不常驻修改 `window.fetch`)。 + * 优先使用同源 `window.fetch` (`credentials: 'same-origin'`);若被鉴权或协议阻断,防御性回退至同源 `/connect-websocket`。 + * + * @param {string} method + * @param {object} [body={}] + * @param {number} [timeoutMs=5000] + * @returns {string} + */ +export function buildWindowRemoteRpcExpression(method, body = {}, timeoutMs = 5000) { + const safeTimeout = Math.max(1000, Math.min(30000, Number(timeoutMs) || 5000)); + return `(async () => { + const methodName = ${JSON.stringify(String(method || ''))}; + const payloadObj = ${JSON.stringify(body && typeof body === 'object' ? body : {})}; + const timeoutMs = ${JSON.stringify(safeTimeout)}; + const servicePath = '/exa.language_server_pb.LanguageServerService/'; + const procedure = servicePath + methodName; + const origin = String(window.location?.origin || '').replace(/\\/+$/, ''); + if (!origin || !/^https?:\\/\\/(127\\.0\\.0\\.1|localhost|\\[::1\\]):\\d+$/i.test(origin)) { + return { ok: false, status: 0, error: 'Non-loopback window origin' }; + } + const csrfToken = String( + window.__APP_CONFIG__?.csrfToken || + window[${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}]?.observedCsrfToken || + '' + ).trim(); + const deadlineMs = Date.now() + timeoutMs; + + let fetchErrMsg = ''; + let fetchStatus = 0; + if (typeof window.fetch === 'function') { + try { + const headers = { 'Content-Type': 'application/json' }; + if (csrfToken) headers['x-codeium-csrf-token'] = csrfToken; + const fetchBudgetMs = Math.max(200, deadlineMs - Date.now()); + const init = { + method: 'POST', + credentials: 'same-origin', + headers, + body: JSON.stringify(payloadObj), + }; + if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') { + init.signal = AbortSignal.timeout(fetchBudgetMs); + } + const res = await window.fetch(origin + procedure, init); + fetchStatus = Number(res?.status || 0); + if (res?.ok) { + const data = await res.json(); + return { ok: true, status: fetchStatus, transport: 'fetch', data }; + } + fetchErrMsg = (await res?.text?.().catch(() => '')) || ('HTTP ' + fetchStatus); + } catch (err) { + fetchErrMsg = err?.message || 'fetch failed'; + } + } + + const wsRemainingMs = deadlineMs - Date.now(); + if (wsRemainingMs >= 300 && typeof window.WebSocket === 'function' && window.location?.host) { + try { + const wsProto = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; + const wsUrl = wsProto + '//' + window.location.host + '/connect-websocket'; + const streamId = 'um_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2, 8); + const wsResult = await new Promise((resolve, reject) => { + let ws = null; + let timer = null; + let done = false; + const finish = (ok, val) => { + if (done) return; + done = true; + if (timer) clearTimeout(timer); + try { ws?.close?.(); } catch {} + if (ok) resolve(val); + else reject(val instanceof Error ? val : new Error(String(val || 'ws failed'))); + }; + timer = setTimeout(() => finish(false, new Error('connect-websocket timeout')), wsRemainingMs); + try { + ws = new window.WebSocket(wsUrl); + } catch (err) { + finish(false, err); + return; + } + ws.addEventListener('open', () => { + try { + ws.send(JSON.stringify({ + type: 'start', + stream: false, + procedure, + streamId, + payload: payloadObj, + })); + } catch (err) { + finish(false, err); + } + }, { once: true }); + ws.addEventListener('message', (ev) => { + try { + const raw = typeof ev?.data === 'string' ? ev.data : String(ev?.data || ''); + const frame = JSON.parse(raw); + if (!frame || typeof frame !== 'object') return; + if (frame.streamId && frame.streamId !== streamId) return; + if (frame.type === 'error' || frame.error) { + const msg = typeof frame.error === 'string' + ? frame.error + : frame.error?.message || frame.message || 'connect-websocket error'; + finish(false, new Error(msg)); + return; + } + if (frame.payload !== undefined) { + finish(true, frame.payload); + return; + } + if (frame.response !== undefined) { + finish(true, frame.response); + return; + } + if (frame.data !== undefined && frame.type !== 'ping' && frame.type !== 'pong') { + finish(true, frame.data); + return; + } + if (frame.type === 'end') { + finish(true, {}); + } + } catch { + // 忽略非 JSON 或无关帧 + } + }); + ws.addEventListener('error', () => finish(false, new Error('connect-websocket error')), { once: true }); + ws.addEventListener('close', () => finish(false, new Error('connect-websocket closed')), { once: true }); + }); + return { ok: true, status: 200, transport: 'ws', data: wsResult }; + } catch (wsErr) { + return { + ok: false, + status: fetchStatus, + error: fetchErrMsg || wsErr?.message || 'Remote window RPC failed', + }; + } + } + + return { ok: false, status: fetchStatus, error: fetchErrMsg || 'Remote window RPC failed' }; + })()`; +} + /** * 校验桥接请求的 `Origin` 是否来自本机 Antigravity 2.0 HTTPS 回环源或 Antigravity IDE `vscode-file` 源。 * @@ -792,6 +1089,8 @@ export function createWindowBridgeController(options) { allowDesktopLauncherInTest = false, existsHostFn = existsSync, WebSocketImpl = globalThis.WebSocket, + bindRemoteRpcInvoker = false, + getLocalHubPortsFn = getLocalHubPorts, } = options || {}; function isPidAlive(pid) { @@ -849,7 +1148,8 @@ export function createWindowBridgeController(options) { }; let hadContextWindows = false; let contextWindowBootId = `${process.pid}:${Date.now()}`; - let cachedBackendCtxModels = { expiresAt: 0, models: [] }; + const cachedBackendCtxModelsByEndpoint = new Map(); + const targetClassifyCache = new Map(); let nodeDepsPromise = null; const allowedDynamicOrigins = new Set(); @@ -868,14 +1168,22 @@ export function createWindowBridgeController(options) { function applyCorsHeaders(res, origin) { res.setHeader('Access-Control-Allow-Origin', origin); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); - res.setHeader('Access-Control-Allow-Headers', 'Content-Type, X-Usage-Monitor-Token'); + res.setHeader( + 'Access-Control-Allow-Headers', + `Content-Type, X-Usage-Monitor-Token, ${WINDOW_BRIDGE_ENDPOINT_HEADER}` + ); res.setHeader('Access-Control-Allow-Private-Network', 'true'); res.setHeader('Access-Control-Max-Age', '600'); res.setHeader('Vary', 'Origin'); res.setHeader('Cache-Control', 'no-store'); } - async function executeRpcBatch(rpcBatch) { + function invokeApiHandler(pathname, method, data, endpointId) { + const authoritativeEndpointId = endpointId || LOCAL_ENDPOINT_ID; + return handleApiRequest(pathname, method, data, { endpointId: authoritativeEndpointId }); + } + + async function executeRpcBatch(rpcBatch, authoritativeEndpointId = LOCAL_ENDPOINT_ID) { const responses = []; for (const item of rpcBatch) { const reqId = String(item?.id || ''); @@ -893,7 +1201,12 @@ export function createWindowBridgeController(options) { : item.body && typeof item.body === 'object' ? item.body : {}; - const out = await handleApiRequest(parsedUrl.pathname, method, reqData); + const out = await invokeApiHandler( + parsedUrl.pathname, + method, + reqData, + authoritativeEndpointId + ); const status = Number(out?.status || 200); const parsedBody = out?.body ? JSON.parse(out.body) : {}; if (status >= 200 && status < 300) { @@ -989,9 +1302,23 @@ export function createWindowBridgeController(options) { return; } + const headerEndpointRaw = String( + req.headers[WINDOW_BRIDGE_ENDPOINT_HEADER.toLowerCase()] || '' + ).trim(); + const queryEndpointRaw = String(parsedUrl.searchParams.get('endpointId') || '').trim(); + const requestedEndpointRaw = headerEndpointRaw || queryEndpointRaw; + const normalizedReqEndpoint = requestedEndpointRaw + ? normalizeEndpointId(requestedEndpointRaw) + : LOCAL_ENDPOINT_ID; + if (normalizedReqEndpoint === null) { + res.writeHead(400, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Invalid endpointId' })); + return; + } + if (method === 'GET') { const queryData = Object.fromEntries(parsedUrl.searchParams.entries()); - Promise.resolve(handleApiRequest(parsedUrl.pathname, 'GET', queryData)) + Promise.resolve(invokeApiHandler(parsedUrl.pathname, 'GET', queryData, normalizedReqEndpoint)) .then((out) => { const hdrs = { 'Content-Type': out.contentType || 'application/json', @@ -1040,7 +1367,7 @@ export function createWindowBridgeController(options) { res.end(JSON.stringify({ error: 'Invalid JSON body' })); return; } - Promise.resolve(handleApiRequest(parsedUrl.pathname, 'POST', bodyObj)) + Promise.resolve(invokeApiHandler(parsedUrl.pathname, 'POST', bodyObj, normalizedReqEndpoint)) .then((out) => { const hdrs = { 'Content-Type': out.contentType || 'application/json', @@ -1211,11 +1538,12 @@ export function createWindowBridgeController(options) { return { reachableCount, targets: merged }; } - async function evaluateOnTarget(wsUrl, expression) { + async function evaluateOnTarget(wsUrl, expression, timeoutMsOverride = 0) { const WS = WebSocketImpl || globalThis.WebSocket; if (typeof WS !== 'function') { throw new Error('WebSocket runtime unavailable'); } + const effectiveTimeoutMs = Math.max(500, Number(timeoutMsOverride) || cdpTimeoutMs); let ws = null; let timer = null; try { @@ -1223,7 +1551,7 @@ export function createWindowBridgeController(options) { const evalResult = await new Promise((resolve, reject) => { timer = setTimeout(() => { reject(new Error('CDP Runtime.evaluate timeout')); - }, cdpTimeoutMs); + }, effectiveTimeoutMs); const onOpen = () => { try { @@ -1423,6 +1751,7 @@ export function createWindowBridgeController(options) { const cdpPorts = findActiveDevToolsPorts(); if (!cdpPorts.length) { + pruneStaleRemoteEndpoints(new Set()); const provPending = shouldCheckLaunchers ? provisionHostLaunchersOnce({ fastCheckIfActive: !isInitialLauncherPass }) : hostLauncherPromise; @@ -1440,6 +1769,7 @@ export function createWindowBridgeController(options) { const { reachableCount, targets } = await collectAllMainWindowTargets(cdpPorts); if (reachableCount === 0) { + pruneStaleRemoteEndpoints(new Set()); const provPending = shouldCheckLaunchers ? provisionHostLaunchersOnce({ fastCheckIfActive: !isInitialLauncherPass }) : hostLauncherPromise; @@ -1460,6 +1790,7 @@ export function createWindowBridgeController(options) { void provisionHostLaunchersOnce({ fastCheckIfActive: true }).catch(() => {}); } if (!targets.length) { + pruneStaleRemoteEndpoints(new Set()); updateBridgeStatus(enabled ? 'no_targets' : 'disabled', { enabled, leasedBySelf, @@ -1469,44 +1800,250 @@ export function createWindowBridgeController(options) { return { ok: true, enabled, reason: 'no_targets', injected: 0 }; } - if (hasContextWindows || hadContextWindows) { - let fallbackRules = {}; + if ( + !enabled && + !hasContextWindows && + !hadContextWindows && + !hadInjectedTargets && + !hadInjectedChatFrames && + !forceReinject + ) { + pruneStaleRemoteEndpoints(new Set()); + updateBridgeStatus('disabled', { + enabled: false, + targets: targets.length, + leasedBySelf, + bundleVersion, + prevLease: currentLease, + }); + return { ok: true, enabled: false, removed: 0 }; + } + + const classifyExpr = `(() => { + try { + const cfg = typeof window !== 'undefined' && window.__APP_CONFIG__ && typeof window.__APP_CONFIG__ === 'object' + ? window.__APP_CONFIG__ + : null; + const observedCsrf = String( + (typeof window !== 'undefined' && window[${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}]?.observedCsrfToken) || '' + ).trim(); + return { + origin: String((typeof window !== 'undefined' && window.location?.origin) || '').trim(), + title: String((typeof document !== 'undefined' && document?.title) || '').trim(), + csrfToken: String(cfg?.csrfToken || '').trim(), + observedCsrfToken: observedCsrf, + appConfig: cfg ? { + isRemoteControl: cfg.isRemoteControl === true, + isRemote: cfg.isRemote === true, + isSsh: cfg.isSsh === true, + connectionType: String(cfg.connectionType || ''), + windowMode: String(cfg.windowMode || ''), + sshHost: String(cfg.sshHost || ''), + sshHostName: String(cfg.sshHostName || ''), + sshAlias: String(cfg.sshAlias || ''), + sshTarget: String(cfg.sshTarget || ''), + remoteHost: String(cfg.remoteHost || ''), + remoteAuthority: String(cfg.remoteAuthority || ''), + remoteName: String(cfg.remoteName || ''), + } : null, + }; + } catch { + return { origin: '', title: '', csrfToken: '', observedCsrfToken: '', appConfig: null }; + } + })()`; + + const nowClassifyMs = Date.now(); + const localHubInfo = + typeof getLocalHubPortsFn === 'function' ? getLocalHubPortsFn() : { allPorts: new Set(), httpsPorts: new Set(), csrfTokens: new Set() }; + const probedByWsUrl = new Map(); + const desktopTargets = targets.filter((t) => !t.isIdeWorkbench && t.webSocketDebuggerUrl); + + await Promise.allSettled( + desktopTargets.map(async (target) => { + const wsUrl = String(target.webSocketDebuggerUrl || ''); + let targetOriginKey = ''; + try { + targetOriginKey = new URL(String(target.url || '')).origin; + } catch { + targetOriginKey = String(target.url || ''); + } + const cacheKey = `${wsUrl}::${targetOriginKey}`; + const cached = targetClassifyCache.get(cacheKey); + if (cached && nowClassifyMs - cached.ts < 4000) { + probedByWsUrl.set(wsUrl, cached.info); + return; + } + try { + const res = await evaluateOnTarget(wsUrl, classifyExpr, 1800); + const info = res?.result?.result?.value; + if (info && typeof info === 'object') { + probedByWsUrl.set(wsUrl, info); + targetClassifyCache.set(cacheKey, { ts: nowClassifyMs, info }); + } + } catch { + if (cached?.info) probedByWsUrl.set(wsUrl, cached.info); + } + }) + ); + + if (targetClassifyCache.size > 64) { + for (const [k, rec] of targetClassifyCache.entries()) { + if (nowClassifyMs - rec.ts > 30_000) targetClassifyCache.delete(k); + } + } + + // 两趟分类:第一趟确认明确归属本机的 Desktop 窗口端口,第二趟据此精准识别 SSH 远端窗口 + const confirmedLocalPorts = new Set(); + for (const target of desktopTargets) { + const probedInfo = probedByWsUrl.get(String(target.webSocketDebuggerUrl || '')) || null; + const firstPass = classifyWindowTargetEndpoint({ + target, + probedInfo, + localHubInfo, + confirmedLocalPorts: null, + }); if ( - hasContextWindows && - lsRuntimeEndpoint.baseUrl && - lsRuntimeEndpoint.addr !== 'test.invalid' + !firstPass.isRemote && + firstPass.originPort > 0 && + (localHubInfo?.allPorts?.has(firstPass.originPort) || + (firstPass.csrfToken && localHubInfo?.csrfTokens?.has(firstPass.csrfToken))) ) { - if (Date.now() >= cachedBackendCtxModels.expiresAt) { + confirmedLocalPorts.add(firstPass.originPort); + } + } + + const activeRemoteWsUrls = new Set(); + for (const target of targets) { + const wsUrl = String(target.webSocketDebuggerUrl || ''); + const probedInfo = probedByWsUrl.get(wsUrl) || null; + const cls = classifyWindowTargetEndpoint({ + target, + probedInfo, + localHubInfo, + confirmedLocalPorts, + }); + if (cls.isRemote && wsUrl) { + const ep = registerRemoteEndpoint({ + origin: cls.origin, + baseUrl: cls.origin, + csrfToken: cls.csrfToken, + wsUrl, + label: cls.hostLabel, + stableHostKey: cls.stableHostKey, + }); + target.endpointId = ep.id; + target.isRemoteEndpoint = true; + target.endpointLabel = ep.label; + activeRemoteWsUrls.add(wsUrl); + } else { + target.endpointId = LOCAL_ENDPOINT_ID; + target.isRemoteEndpoint = false; + target.endpointLabel = ''; + } + } + + if (hasContextWindows || hadContextWindows) { + async function resolveFallbackRulesForEndpoint(endpointId) { + if (!hasContextWindows) return { verified: false, rules: {} }; + const epObj = endpointId && endpointId !== LOCAL_ENDPOINT_ID + ? getRegisteredRemoteEndpoint(endpointId) + : null; + if (!epObj && (!lsRuntimeEndpoint.baseUrl || lsRuntimeEndpoint.addr === 'test.invalid')) { + return { verified: false, rules: {} }; + } + const cacheKey = epObj ? epObj.id : LOCAL_ENDPOINT_ID; + let cached = cachedBackendCtxModelsByEndpoint.get(cacheKey) || { + expiresAt: 0, + verified: false, + models: [], + }; + if (Date.now() >= cached.expiresAt) { try { const [stRes, cat] = await Promise.all([ - callLsRpc('GetUserStatus', {}, 1500), - getContextModelCatalog(), + callLsRpc('GetUserStatus', {}, 2000, epObj), + getContextModelCatalog(epObj), ]); const cfgs = stRes?.userStatus?.cascadeModelConfigData?.clientModelConfigs; if (Array.isArray(cfgs)) { - cachedBackendCtxModels = { + cached = { expiresAt: Date.now() + 10_000, + verified: true, models: getContextWindowModels(cfgs, cat), }; + cachedBackendCtxModelsByEndpoint.delete(cacheKey); + if (cachedBackendCtxModelsByEndpoint.size >= 16) { + const oldestKey = cachedBackendCtxModelsByEndpoint.keys().next().value; + if (oldestKey !== undefined) cachedBackendCtxModelsByEndpoint.delete(oldestKey); + } + cachedBackendCtxModelsByEndpoint.set(cacheKey, cached); } } catch { - // 忽略瞬态 LS 查询失败,保留上次缓存或交由窗口端解析 + // 忽略瞬态 LS 查询失败,保留上次缓存或交由调用方回退 } } - if (cachedBackendCtxModels.models.length > 0) { - fallbackRules = resolveContextWindowRules(cachedBackendCtxModels.models, contextWindows); + if (cached.verified) { + return { + verified: true, + rules: cached.models.length > 0 + ? resolveContextWindowRules(cached.models, contextWindows) + : {}, + }; + } + return { verified: false, rules: {} }; + } + + const localFallbackRes = await resolveFallbackRulesForEndpoint(LOCAL_ENDPOINT_ID); + const localFallbackRules = localFallbackRes.rules; + const remoteFallbackRulesById = new Map(); + const uniqueRemoteIds = new Set( + targets + .filter((t) => !t.isIdeWorkbench && t.isRemoteEndpoint && t.endpointId) + .map((t) => t.endpointId) + ); + for (const cachedKey of Array.from(cachedBackendCtxModelsByEndpoint.keys())) { + if (cachedKey !== LOCAL_ENDPOINT_ID && !getRegisteredRemoteEndpoint(cachedKey)) { + cachedBackendCtxModelsByEndpoint.delete(cachedKey); } } - const chatUrls = [ - ...targets.filter((target) => !target.isIdeWorkbench).map((target) => target.webSocketDebuggerUrl), - ...collectAllChatDebuggerUrls(targets), - ]; - const expression = createContextWindowSyncExpression( + await Promise.allSettled( + Array.from(uniqueRemoteIds).map(async (epId) => { + const res = await resolveFallbackRulesForEndpoint(epId); + // 仅在远端未能验证模型目录时安全回退本机规则;远端已验证但返回空规则时绝不套用本机高配规则 + remoteFallbackRulesById.set(epId, res.verified ? res.rules : localFallbackRules); + }) + ); + + const ctxEvalTasks = []; + const seenCtxUrls = new Set(); + for (const target of targets) { + if (target.isIdeWorkbench) continue; + const wsUrl = String(target.webSocketDebuggerUrl || '').trim(); + if (!wsUrl || seenCtxUrls.has(wsUrl)) continue; + seenCtxUrls.add(wsUrl); + const epFallback = + target.isRemoteEndpoint && target.endpointId + ? remoteFallbackRulesById.get(target.endpointId) || localFallbackRules + : localFallbackRules; + const expr = createContextWindowSyncExpression( + contextWindows, + contextWindowBootId, + epFallback, + true + ); + ctxEvalTasks.push(evaluateOnTarget(wsUrl, expr)); + } + const ideChatExpr = createContextWindowSyncExpression( contextWindows, contextWindowBootId, - fallbackRules + localFallbackRules, + false ); - await Promise.allSettled([...new Set(chatUrls)].map((url) => evaluateOnTarget(url, expression))); + for (const chatUrl of collectAllChatDebuggerUrls(targets)) { + if (!chatUrl || seenCtxUrls.has(chatUrl)) continue; + seenCtxUrls.add(chatUrl); + ctxEvalTasks.push(evaluateOnTarget(chatUrl, ideChatExpr)); + } + await Promise.allSettled(ctxEvalTasks); hadContextWindows = hasContextWindows; } @@ -1533,6 +2070,7 @@ export function createWindowBridgeController(options) { } if (!enabled) { + pruneStaleRemoteEndpoints(activeRemoteWsUrls); if (!hadInjectedTargets && !hadInjectedChatFrames && !forceReinject) { updateBridgeStatus('disabled', { enabled: false, @@ -1602,12 +2140,14 @@ export function createWindowBridgeController(options) { bridgePort: Number(br?.port || 0), hasToken: Boolean(br?.token), transportMode: String(br?.transportMode || 'http'), + endpointId: String(br?.[${windowBridgeEndpointKey}] || ${JSON.stringify(LOCAL_ENDPOINT_ID)}), + endpointLabel: String(br?.endpointLabel || ''), hostRouteCascadeId: String(br?.[${windowBridgeRouteKey}] || ''), routeCascadeId, rpcBatch, }; } catch { - return { alive: false, dockKind: '', visible: true, bundleVersion: '', bridgePort: 0, hasToken: false, transportMode: 'http', hostRouteCascadeId: '', routeCascadeId: '', rpcBatch: [] }; + return { alive: false, dockKind: '', visible: true, bundleVersion: '', bridgePort: 0, hasToken: false, transportMode: 'http', endpointId: ${JSON.stringify(LOCAL_ENDPOINT_ID)}, endpointLabel: '', hostRouteCascadeId: '', routeCascadeId: '', rpcBatch: [] }; } })()`; @@ -1622,6 +2162,10 @@ export function createWindowBridgeController(options) { if (!wsUrl) return { alive: false, dockKind: '', visible: false }; let probedRouteId = ''; const ideRouteId = String(ideRouteOverride || targetObj.ideRouteCascadeId || '').trim(); + const targetEndpointId = String(targetObj.endpointId || LOCAL_ENDPOINT_ID); + const targetIsRemote = Boolean(targetObj.isRemoteEndpoint && targetEndpointId !== LOCAL_ENDPOINT_ID); + const targetEndpointLabel = targetIsRemote ? String(targetObj.endpointLabel || 'SSH') : ''; + if (!forceReinject) { const probeRes = await evaluateOnTarget(wsUrl, probeExpr); const snap = probeRes?.result?.result?.value; @@ -1639,8 +2183,21 @@ export function createWindowBridgeController(options) { }; } if (snap.bundleVersion === bundleVersion) { - if (snap.bridgePort !== port || snap.hasToken !== true) { - const rebindExpr = `${windowOverlayRef}?.[${overlayMethods.updateBridge}]?.(${JSON.stringify({ port, token })})`; + const snapEndpointId = String(snap.endpointId || LOCAL_ENDPOINT_ID); + const snapEndpointLabel = String(snap.endpointLabel || ''); + if ( + snap.bridgePort !== port || + snap.hasToken !== true || + snapEndpointId !== targetEndpointId || + snapEndpointLabel !== targetEndpointLabel + ) { + const rebindExpr = `${windowOverlayRef}?.[${overlayMethods.updateBridge}]?.(${JSON.stringify({ + port, + token, + [WINDOW_BRIDGE_ENDPOINT_KEY]: targetEndpointId, + isRemoteEndpoint: targetIsRemote, + endpointLabel: targetEndpointLabel, + })})`; await evaluateOnTarget(wsUrl, rebindExpr); } let effectiveDockKind = String(snap.dockKind || ''); @@ -1678,7 +2235,7 @@ export function createWindowBridgeController(options) { } if (Array.isArray(snap.rpcBatch) && snap.rpcBatch.length > 0) { sawCdpTransport = true; - const rpcResults = await executeRpcBatch(snap.rpcBatch); + const rpcResults = await executeRpcBatch(snap.rpcBatch, targetEndpointId); relayedRpcCount += rpcResults.length; const deliverExpr = `${windowOverlayRef}?.[${overlayMethods.deliverRpc}]?.(${JSON.stringify(rpcResults)})`; await evaluateOnTarget(wsUrl, deliverExpr); @@ -1704,12 +2261,17 @@ export function createWindowBridgeController(options) { try { const routeMatch = String(targetObj.url || '').match(/\/c\/([a-f0-9-]{36})(?:[/?#]|$)/i); const targetConvId = routeMatch ? routeMatch[1] : ideRouteId || probedRouteId; - const initOut = await handleApiRequest('/api/telemetry', 'GET', { - conversationId: targetConvId, - range: 'today', - stepDetails: 'display', - stepRevision: '', - }); + const initOut = await invokeApiHandler( + '/api/telemetry', + 'GET', + { + conversationId: targetConvId, + range: 'today', + stepDetails: 'display', + stepRevision: '', + }, + targetEndpointId + ); if (Number(initOut?.status || 200) === 200 && initOut?.body) { initialTelemetry = JSON.parse(initOut.body); } @@ -1723,6 +2285,9 @@ export function createWindowBridgeController(options) { bundleVersion, platform: String(platform || ''), mountMode, + [WINDOW_BRIDGE_ENDPOINT_KEY]: targetEndpointId, + isRemoteEndpoint: targetIsRemote, + endpointLabel: targetEndpointLabel, [WINDOW_BRIDGE_ROUTE_KEY]: ideRouteId || '', isIdeChatFrame: Boolean(isIdeChatFrame), stylesCss: cachedAssets.stylesCss, @@ -1805,6 +2370,7 @@ export function createWindowBridgeController(options) { } } + pruneStaleRemoteEndpoints(activeRemoteWsUrls); cdpFallbackActive = sawCdpTransport; updateBridgeStatus(aliveCount > 0 ? 'active' : 'no_targets', { enabled: true, @@ -1825,6 +2391,41 @@ export function createWindowBridgeController(options) { }; } + async function invokeRemoteWindowRpc(endpoint, method, body, timeoutMs = 5000) { + const wsUrls = getRemoteEndpointTargetWsUrls(endpoint); + if (wsUrls.length === 0) { + throw new Error(`No live CDP target for remote endpoint ${endpoint?.id || ''}`); + } + const expr = buildWindowRemoteRpcExpression(method, body, timeoutMs); + const evalTimeoutMs = Math.max(cdpTimeoutMs, (Number(timeoutMs) || 5000) + 1500); + let lastError = null; + for (const wsUrl of wsUrls) { + try { + const res = await evaluateOnTarget(wsUrl, expr, evalTimeoutMs); + if (res?.error || res?.result?.exceptionDetails) { + lastError = new Error( + res?.error?.message || + res?.result?.exceptionDetails?.text || + 'CDP remote RPC evaluation exception' + ); + continue; + } + const val = res?.result?.result?.value; + if (val && val.ok === true) { + return val.data ?? {}; + } + lastError = new Error(val?.error || `Remote window RPC ${method} failed (${val?.status || 0})`); + } catch (err) { + lastError = err; + } + } + throw lastError || new Error(`Remote window RPC ${method} failed`); + } + + if (bindRemoteRpcInvoker) { + setRemoteWindowRpcInvoker(invokeRemoteWindowRpc); + } + function syncAllWindows(opts = {}) { if (syncInFlight) { return syncInFlight.then(() => runSyncInternal(opts)); @@ -1853,6 +2454,9 @@ export function createWindowBridgeController(options) { function start() { stopped = false; contextWindowBootId = `${process.pid}:${Date.now()}`; + if (bindRemoteRpcInvoker) { + setRemoteWindowRpcInvoker(invokeRemoteWindowRpc); + } if (initialTimer) clearTimeout(initialTimer); if (pollTimer) clearTimeout(pollTimer); @@ -1923,6 +2527,9 @@ export function createWindowBridgeController(options) { hadInjectedTargets = false; hadInjectedChatFrames = false; hadContextWindows = false; + if (bindRemoteRpcInvoker) { + setRemoteWindowRpcInvoker(null); + } if (server) { const srv = server; server = null; @@ -1985,6 +2592,7 @@ export function createWindowBridgeController(options) { return { ensureBridgeServer, syncAllWindows, + invokeRemoteWindowRpc, notifySettingChanged, notifyContextWindowsChanged, start, @@ -2026,6 +2634,7 @@ export function startDefaultWindowBridge(options) { if (!defaultBridgeController) { defaultBridgeController = createWindowBridgeController({ leaseFilePath: join(DATA_DIR, 'window-bridge-lease.json'), + bindRemoteRpcInvoker: true, ...options, }); defaultBridgeController.start(); diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 416579f..9524768 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/shared/window-bridge-protocol.mjs b/sidecars/panel/shared/window-bridge-protocol.mjs index fa9f774..42a5338 100644 --- a/sidecars/panel/shared/window-bridge-protocol.mjs +++ b/sidecars/panel/shared/window-bridge-protocol.mjs @@ -1,5 +1,8 @@ export const WINDOW_BRIDGE_KEY = '__AGUsageMonitorBridge'; export const WINDOW_BRIDGE_ROUTE_KEY = 'hostRouteCascadeId'; +export const WINDOW_BRIDGE_ENDPOINT_KEY = 'endpointId'; +export const WINDOW_BRIDGE_ENDPOINT_HEADER = 'X-Usage-Monitor-Endpoint'; +export const LOCAL_ENDPOINT_ID = 'local'; export const WINDOW_OVERLAY_KEY = '__AGUsageMonitorOverlay'; export const CONTEXT_WINDOWS_GLOBAL_KEY = '__AGUsageMonitorContextWindows'; diff --git a/sidecars/panel/src/components/layout/TopSessionHeader.js b/sidecars/panel/src/components/layout/TopSessionHeader.js index 7efcab1..26b31c5 100644 --- a/sidecars/panel/src/components/layout/TopSessionHeader.js +++ b/sidecars/panel/src/components/layout/TopSessionHeader.js @@ -76,6 +76,12 @@ export const TopSessionHeader = defineComponent({ [updateBtnIcon, updateBtnText] ); + const sshBadge = h('span', { + className: 'endpoint-ssh-badge', + hidden: true, + text: 'SSH', + }); + const statusIcon = createSvgIcon('pulse', { size: 12 }); const statusText = h('span', { text: t('header.statusLive') }); const statusTag = h('span', { className: 'status-tag' }, [statusIcon, statusText]); @@ -93,7 +99,7 @@ export const TopSessionHeader = defineComponent({ const headerRowEl = h('div', { className: 'session-header' }, [ h('div', { className: 'session-left' }, [convSelect.el]), - h('div', { className: 'session-right' }, [updateBtn, statusTag, refreshBtn]), + h('div', { className: 'session-right' }, [sshBadge, updateBtn, statusTag, refreshBtn]), ]); const headerEl = h('header', { className: 'top-session-stack' }, [headerRowEl]); @@ -162,6 +168,14 @@ export const TopSessionHeader = defineComponent({ patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate')); patchAttr(refreshBtn, 'aria-label', t('header.ariaRefresh')); + const ep = telemetry?.endpoint; + const isRemoteEndpoint = Boolean(ep?.isRemote); + patchAttr(sshBadge, 'hidden', !isRemoteEndpoint); + if (isRemoteEndpoint) { + const epLabel = String(ep?.label || 'SSH').trim(); + patchAttr(sshBadge, 'title', epLabel && epLabel !== 'SSH' ? `SSH · ${epLabel}` : 'SSH'); + } + const actConv = telemetry?.activeConversation; const convs = telemetry?.conversations || []; const hostRouteId = telSt.hostRouteConversationId || ''; diff --git a/sidecars/panel/src/components/layout/WindowOverlayShell.js b/sidecars/panel/src/components/layout/WindowOverlayShell.js index b608027..45084e5 100644 --- a/sidecars/panel/src/components/layout/WindowOverlayShell.js +++ b/sidecars/panel/src/components/layout/WindowOverlayShell.js @@ -9,6 +9,8 @@ */ import { + LOCAL_ENDPOINT_ID, + WINDOW_BRIDGE_ENDPOINT_KEY, WINDOW_BRIDGE_KEY, WINDOW_OVERLAY_KEY, WINDOW_OVERLAY_METHODS, @@ -51,6 +53,7 @@ import { normalizeClientTopbarSlots, normalizeClientUpdateMode, normalizeClientWindowMountMode, + resetTelemetryForEndpointSwitch, resolveScopedConversation, selectConversation, startAsyncTelemetryLoop, @@ -958,10 +961,18 @@ export function mountWindowOverlay() { const bridgeConfig = getWindowBridgeConfig(); const bundleVersion = String(bridgeConfig?.bundleVersion || ''); const stylesCss = String(bridgeConfig?.stylesCss || ''); + const activeBridgeEndpointId = String( + bridgeConfig?.[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID + ); + const reusableCarryOver = + carryOverTelemetry && + String(carryOverTelemetry?.endpoint?.id || LOCAL_ENDPOINT_ID) === activeBridgeEndpointId + ? carryOverTelemetry + : null; const seedTelemetry = (bridgeConfig?.initialTelemetry && typeof bridgeConfig.initialTelemetry === 'object' ? bridgeConfig.initialTelemetry - : null) || carryOverTelemetry; + : null) || reusableCarryOver; if (bridgeConfig?.initialTelemetry) { delete bridgeConfig.initialTelemetry; } @@ -2741,14 +2752,49 @@ export function mountWindowOverlay() { const token = String(nextBridge.token || ''); if (!Number.isInteger(port) || port <= 0 || !token) return false; const cur = readInjectedWindowBridge() || {}; + const prevEndpointId = String(cur[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID); + const nextEndpointId = + nextBridge[WINDOW_BRIDGE_ENDPOINT_KEY] !== undefined + ? String(nextBridge[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID) + : prevEndpointId; const portChanged = Number(cur.port || 0) !== port || String(cur.token || '') !== token; + const endpointChanged = prevEndpointId !== nextEndpointId; cur.port = port; cur.token = token; - if (portChanged) { + cur[WINDOW_BRIDGE_ENDPOINT_KEY] = nextEndpointId; + if (nextBridge.isRemoteEndpoint !== undefined) { + cur.isRemoteEndpoint = Boolean(nextBridge.isRemoteEndpoint); + } + if (nextBridge.endpointLabel !== undefined) { + cur.endpointLabel = String(nextBridge.endpointLabel || ''); + } + if (portChanged || endpointChanged) { cur.transportMode = 'http'; } + if (endpointChanged) { + if (Array.isArray(cur.rpcQueue)) { + cur.rpcQueue.length = 0; + } + if (cur.rpcPending instanceof Map) { + for (const pending of cur.rpcPending.values()) { + try { + const switchErr = new Error('Bridge endpoint switched'); + switchErr.name = 'AbortError'; + pending?.reject?.(switchErr); + } catch { + // 忽略旧端点回调异常 + } + } + cur.rpcPending.clear(); + } + } window[WINDOW_BRIDGE_KEY] = cur; - void fetchTelemetry({ force: false }); + if (endpointChanged) { + resetTelemetryForEndpointSwitch(); + void fetchTelemetry({ force: true }); + } else { + void fetchTelemetry({ force: false }); + } return true; }, getTelemetrySnapshot() { diff --git a/sidecars/panel/src/core/httpClient.js b/sidecars/panel/src/core/httpClient.js index 653a39e..685cc23 100644 --- a/sidecars/panel/src/core/httpClient.js +++ b/sidecars/panel/src/core/httpClient.js @@ -4,7 +4,12 @@ * (Sidecar Webview `window.sidecar.fetch` + Main Window Loopback Bridge). */ -import { readInjectedWindowBridge } from '../../shared/window-bridge-protocol.mjs'; +import { + LOCAL_ENDPOINT_ID, + WINDOW_BRIDGE_ENDPOINT_HEADER, + WINDOW_BRIDGE_ENDPOINT_KEY, + readInjectedWindowBridge, +} from '../../shared/window-bridge-protocol.mjs'; const inFlightGets = new Map(); const activeControllers = new Map(); @@ -130,7 +135,10 @@ function callViaCdpBridge(bridge, path, { method, body, signal, cdpTimeoutMs }) export async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTimeoutMs = 3500 } = {}) { const upperMethod = method.toUpperCase(); - const dedupKey = upperMethod === 'GET' && !abortKey ? path : ''; + const activeEndpointId = + String(getWindowBridgeConfig()?.[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID).trim() || + LOCAL_ENDPOINT_ID; + const dedupKey = upperMethod === 'GET' && !abortKey ? `${activeEndpointId}::${path}` : ''; if (dedupKey && inFlightGets.has(dedupKey)) { return inFlightGets.get(dedupKey); @@ -148,7 +156,20 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = '' signal = requestController.signal; } + const ensureEndpointUnchanged = (targetBridge) => { + if (!targetBridge) return; + const currentEndpointId = + String(targetBridge[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID).trim() || + LOCAL_ENDPOINT_ID; + if (currentEndpointId !== activeEndpointId) { + const switchErr = new Error('Bridge endpoint switched'); + switchErr.name = 'AbortError'; + throw switchErr; + } + }; + const execHttpOnce = async (activeBridge) => { + ensureEndpointUnchanged(activeBridge); const sidecar = typeof window !== 'undefined' ? window.sidecar : null; const fetchFn = sidecar?.fetch ? sidecar.fetch.bind(sidecar) @@ -162,6 +183,10 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = '' } if (activeBridge) { headers['X-Usage-Monitor-Token'] = activeBridge.token; + const epId = String(activeBridge[WINDOW_BRIDGE_ENDPOINT_KEY] || '').trim(); + if (epId && epId !== LOCAL_ENDPOINT_ID) { + headers[WINDOW_BRIDGE_ENDPOINT_HEADER] = epId; + } } const res = await fetchFn(requestUrl, { method: upperMethod, @@ -181,7 +206,10 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = '' throw abortErr; } if (!res.ok) { - throw new Error(data.error || `HTTP ${res.status}`); + const httpErr = new Error(data.error || `HTTP ${res.status}`); + httpErr.httpStatus = res.status; + httpErr.retryable = Boolean(data?.retryable); + throw httpErr; } if (activeBridge) { activeBridge.transportMode = 'http'; @@ -202,8 +230,10 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = '' if (signal?.aborted || cdpErr?.name === 'AbortError') { throw cdpErr; } - // 热更新或守护重启期间若 CDP 尚未轮询投递,自动重置回 HTTP 并用最新桥接端口重试一次 + // 热更新或守护重启期间若 CDP 尚未轮询投递,自动重置回 HTTP 并用最新桥接端口重试一次; + // 但若端点已切换(例如本地 <-> SSH),绝不将旧端点请求重放至新端点 const latestBridge = getWindowBridgeConfig() || initialBridge; + ensureEndpointUnchanged(latestBridge); latestBridge.transportMode = 'http'; return execHttpOnce(latestBridge); } @@ -232,7 +262,11 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = '' } throw fetchErr; } - // 当宿主环境的 CSP connect-src、混合内容策略或瞬态端口切换阻断直连时,切至带 HTTP 自愈恢复的 CDP 通道 + // 仅在网络/CORS 阻断(无 HTTP 状态码)或桥接令牌失配(403)时切换至 CDP 兜底; + // 业务/初始化状态码(如 503 Remote endpoint initializing、400、500)保持 HTTP 通道等待正常重试。 + if (fetchErr?.httpStatus && fetchErr.httpStatus !== 403) { + throw fetchErr; + } return fallbackViaCdpWithRecovery(bridge); } }; diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index 5ba27a6..e050d08 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -53,7 +53,12 @@ import { normalizeWindowMountMode, parseStepTokenComboSegments, } from '../../shared/settings-normalization.mjs'; -import { WINDOW_BRIDGE_ROUTE_KEY, readInjectedWindowBridge } from '../../shared/window-bridge-protocol.mjs'; +import { + LOCAL_ENDPOINT_ID, + WINDOW_BRIDGE_ENDPOINT_KEY, + WINDOW_BRIDGE_ROUTE_KEY, + readInjectedWindowBridge, +} from '../../shared/window-bridge-protocol.mjs'; const CASCADE_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; @@ -149,6 +154,7 @@ let activeBundleVersion = 0; let latestRequestSeq = 0; let latestConsumptionReqSeq = 0; let latestConversationSwitchSeq = 0; +let endpointSwitchEpoch = 0; let activeForceCount = 0; let consecutivePollFailures = 0; let inFlightTelemetryPoll = null; @@ -201,10 +207,11 @@ export function clearConversationViewCache() { function buildConsumptionScopeSig(payload) { if (!payload || typeof payload !== 'object') return ''; + const ep = payload.endpoint || {}; const acct = payload.account || {}; const set = payload.settings || {}; const cloud = payload.cloudStatus || {}; - return `${String(acct.status || '')}|${String(acct.email || acct.name || '').toLowerCase()}|${String(set.weeklyLimitMode || '')}|${String(cloud.catalogVersion || '')}`; + return `${String(ep.id || LOCAL_ENDPOINT_ID)}|${String(acct.status || '')}|${String(acct.email || acct.name || '').toLowerCase()}|${String(set.weeklyLimitMode || '')}|${String(cloud.catalogVersion || '')}`; } function syncConsumptionCacheScope(payload) { @@ -476,6 +483,13 @@ export function isEquivalentTelemetry(prev, next) { if ((pSet?.fontScale ?? 'md') !== (nSet?.fontScale ?? 'md')) return false; if (Boolean(pSet?.experimentalModernUi) !== Boolean(nSet?.experimentalModernUi)) return false; if ((prev.hostPlatform || '') !== (next.hostPlatform || '')) return false; + if ( + (prev.endpoint?.id || LOCAL_ENDPOINT_ID) !== (next.endpoint?.id || LOCAL_ENDPOINT_ID) || + Boolean(prev.endpoint?.isRemote) !== Boolean(next.endpoint?.isRemote) || + (prev.endpoint?.label || '') !== (next.endpoint?.label || '') + ) { + return false; + } if (Boolean(pSet?.contextWindowRiskAccepted) !== Boolean(nSet?.contextWindowRiskAccepted)) { return false; } @@ -1014,6 +1028,33 @@ export function isEquivalentTelemetry(prev, next) { return true; } +export function resetTelemetryForEndpointSwitch() { + endpointSwitchEpoch += 1; + latestRequestSeq += 1; + latestConsumptionReqSeq += 1; + latestConversationSwitchSeq += 1; + lastReceivedSteps = null; + inFlightTelemetryPoll = null; + consecutivePollFailures = 0; + consumptionCacheScopeSig = ''; + abortSidecarApiKey('telemetry-poll'); + abortSidecarApiKey('telemetry-force'); + abortSidecarApiKey('consumption-range'); + abortSidecarApiKey('consumption-presets'); + abortSidecarApiKey('conversation-switch'); + clearConsumptionRangeCache(); + clearConversationViewCache(); + if (feedbackTimer) { + clearTimeout(feedbackTimer); + feedbackTimer = null; + } + telemetryStore.setState({ + selectedConversationId: '', + telemetry: null, + syncState: 'idle', + }); +} + export async function fetchTelemetry({ force = false } = {}) { if (!force && activeForceCount > 0) { return telemetryStore.getState().telemetry; @@ -1049,11 +1090,17 @@ export async function fetchTelemetry({ force = false } = {}) { } const query = params.toString(); const bridge = overlay ? getWindowBridgeConfig() : null; + const endpointId = bridge?.[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID; const existing = inFlightTelemetryPoll; - if (existing?.query === query && existing.port === bridge?.port && existing.token === bridge?.token) { + if ( + existing?.query === query && + existing.port === bridge?.port && + existing.token === bridge?.token && + existing.endpointId === endpointId + ) { return existing.promise; } - const poll = { query, port: bridge?.port, token: bridge?.token, promise: null }; + const poll = { query, port: bridge?.port, token: bridge?.token, endpointId, promise: null }; poll.promise = requestTelemetry(params, false).finally(() => { if (inFlightTelemetryPoll === poll) inFlightTelemetryPoll = null; }); @@ -1240,6 +1287,7 @@ async function fetchConsumptionRangeSlice({ customStartMs = 0, customEndMs = 0, } = {}) { + const reqEpoch = endpointSwitchEpoch; const reqSeq = ++latestConsumptionReqSeq; const targetRange = String(range || 'today'); const current = telemetryStore.getState(); @@ -1258,7 +1306,7 @@ async function fetchConsumptionRangeSlice({ method: 'GET', abortKey: 'consumption-range', }); - if (!payload || typeof payload !== 'object') return null; + if (!payload || typeof payload !== 'object' || reqEpoch !== endpointSwitchEpoch) return null; if (payload.scope === 'consumption' && payload.consumption) { const usageRev = Number(payload.usageRevision ?? payload.consumption.revision ?? 0); @@ -1385,13 +1433,14 @@ export async function selectConversation( params.set('stepRevision', cachedSteps?.revision || ''); params.set('scope', 'conversation'); + const reqEpoch = endpointSwitchEpoch; const reqSettingsRev = settingsRevision; try { const payload = await callSidecarApi(`/api/telemetry?${params}`, { method: 'GET', abortKey: 'conversation-switch', }); - if (!payload || typeof payload !== 'object') return null; + if (!payload || typeof payload !== 'object' || reqEpoch !== endpointSwitchEpoch) return null; if (switchSeq !== latestConversationSwitchSeq) return payload; const latestSt = telemetryStore.getState(); @@ -1550,11 +1599,13 @@ export function prefetchConsumptionPresets() { if (effectiveConvId) params.set('conversationId', effectiveConvId); params.set('scope', 'consumption-presets'); + const reqEpoch = endpointSwitchEpoch; const task = callSidecarApi(`/api/telemetry?${params}`, { method: 'GET', abortKey: 'consumption-presets', }) .then((payload) => { + if (reqEpoch !== endpointSwitchEpoch) return false; if (payload?.scope === 'consumption-presets' && payload.ranges && typeof payload.ranges === 'object') { const rev = Number(payload.usageRevision || currentRev || 0); for (const [rangeKey, entry] of Object.entries(payload.ranges)) { diff --git a/sidecars/panel/src/styles/controls.css b/sidecars/panel/src/styles/controls.css index 4624cc7..58d8948 100644 --- a/sidecars/panel/src/styles/controls.css +++ b/sidecars/panel/src/styles/controls.css @@ -52,6 +52,23 @@ flex-shrink: 0; } +.endpoint-ssh-badge { + display: inline-flex; + align-items: center; + padding: 2px 5px; + font-family: var(--font-mono); + font-size: var(--fs-sm); + font-weight: 600; + line-height: 1.2; + letter-spacing: 0.02em; + border-radius: var(--radius-xs); + border: 1px solid var(--accent-primary-border); + background: var(--accent-primary-soft); + color: var(--accent-primary); + white-space: nowrap; + flex-shrink: 0; +} + .status-tag { display: inline-flex; align-items: center; diff --git a/sidecars/panel/src/styles/modern-ui.css b/sidecars/panel/src/styles/modern-ui.css index a7ef1b8..e759bb1 100644 --- a/sidecars/panel/src/styles/modern-ui.css +++ b/sidecars/panel/src/styles/modern-ui.css @@ -249,6 +249,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { [data-modern-ui="true"] .status-tag.state-running, [data-modern-ui="true"] .status-tag.state-synced, [data-modern-ui="true"] .status-tag.state-warn, +[data-modern-ui="true"] .endpoint-ssh-badge, [data-modern-ui="true"] .update-badge-btn, [data-modern-ui="true"] .wm-update-btn, [data-modern-ui="true"] .wm-hover-update-bar, diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index 688a6ad..daf2aac 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -442,6 +442,23 @@ html[data-standalone="true"] .app-shell { flex-shrink: 0; } +.endpoint-ssh-badge { + display: inline-flex; + align-items: center; + padding: 2px 5px; + font-family: var(--font-mono); + font-size: var(--fs-sm); + font-weight: 600; + line-height: 1.2; + letter-spacing: 0.02em; + border-radius: var(--radius-xs); + border: 1px solid var(--accent-primary-border); + background: var(--accent-primary-soft); + color: var(--accent-primary); + white-space: nowrap; + flex-shrink: 0; +} + .status-tag { display: inline-flex; align-items: center; @@ -6149,6 +6166,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { [data-modern-ui="true"] .status-tag.state-running, [data-modern-ui="true"] .status-tag.state-synced, [data-modern-ui="true"] .status-tag.state-warn, +[data-modern-ui="true"] .endpoint-ssh-badge, [data-modern-ui="true"] .update-badge-btn, [data-modern-ui="true"] .wm-update-btn, [data-modern-ui="true"] .wm-hover-update-bar, diff --git a/sidecars/panel/test/backend-harness.mjs b/sidecars/panel/test/backend-harness.mjs index 57334b1..35a8dcf 100644 --- a/sidecars/panel/test/backend-harness.mjs +++ b/sidecars/panel/test/backend-harness.mjs @@ -2,7 +2,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { pathToFileURL } from 'node:url'; import vm from 'node:vm'; -import { randomUUID } from 'node:crypto'; +import { createHash, randomUUID } from 'node:crypto'; import { isDeepStrictEqual } from 'node:util'; import * as metrics from '../trajectory-metrics.mjs'; import { stripModuleSyntax } from '../scripts/build-bundle.mjs'; @@ -26,6 +26,7 @@ const BACKEND_MODULE_FILES = [ '../backend/http-helpers.mjs', '../backend/settings-schema.mjs', '../backend/config.mjs', + '../backend/endpoint-registry.mjs', '../backend/sqlite-client.mjs', '../backend/proto-wire.mjs', '../backend/cli-sqlite-reader.mjs', @@ -85,7 +86,7 @@ export function backendHarness({ const source = stripEsmSyntax(sourceText ?? loadCombinedBackendSource(), mainUrl); const state={calls:[],errors:[],saves:[],settings,trajectories,summaries,transcripts,transcriptMtimeMs:1,swarmMembers,swarmMembersMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,gitConfigText,deepStats,deepStatsMtimeMs:1}; const ctx={ - ...metricsImplementation, URL, AbortSignal, Buffer, TextDecoder, ...timerApi, isDeepStrictEqual, randomUUID, + ...metricsImplementation, URL, AbortSignal, Buffer, TextDecoder, ...timerApi, isDeepStrictEqual, createHash, randomUUID, ...(clock ? { Date: class extends Date { constructor(...args) { super(...(args.length ? args : [clock()])); } static now() { return clock(); } @@ -206,6 +207,6 @@ export function backendHarness({ return {ok:true,json:async()=>data}; }, }; - vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,computeStepCost,resolveModelInfo,resolvePricingAt,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,getPricingPhaseEpoch,detectCustomGitForkRepo,persistTrajectoryCacheIfNeeded,flushTrajectoryCacheNow,getCachedTrajectory,listCachedTrajectoryEntries,hasPendingTrajectoryCacheSave,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStepTokenComboFormat,parseStepTokenComboSegments,normalizeModelDisplayMode,normalizePopoverWidthMode,normalizePopoverWidth,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,readLocalSummarySnapshot,readLocalSqliteTrajectory,computeSqliteWalSig,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule};',ctx); + vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,dispatchBridgeApiRequest,executeAccountCredentialAction,callLsRpc,computeStepCost,resolveModelInfo,resolvePricingAt,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,getPricingPhaseEpoch,detectCustomGitForkRepo,persistTrajectoryCacheIfNeeded,flushTrajectoryCacheNow,getCachedTrajectory,listCachedTrajectoryEntries,hasPendingTrajectoryCacheSave,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStepTokenComboFormat,parseStepTokenComboSegments,normalizeModelDisplayMode,normalizePopoverWidthMode,normalizePopoverWidth,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,readLocalSummarySnapshot,readLocalSqliteTrajectory,computeSqliteWalSig,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule,registerRemoteEndpoint,getRegisteredRemoteEndpoint,resolveEndpointContext,clearRemoteEndpointCaches,clearRemoteEndpointRegistry,setRemoteWindowRpcInvoker,setLoopbackHttpsRequester,getEndpointCacheStore,pruneStaleRemoteEndpoints,trackEndpointRequestStart,trackEndpointRequestEnd,shouldRemoteEndpointPreferTier2,markRemoteEndpointPreferTier2};',ctx); return {...ctx.api,state}; } diff --git a/sidecars/panel/test/ssh-remote-endpoints.test.mjs b/sidecars/panel/test/ssh-remote-endpoints.test.mjs new file mode 100644 index 0000000..1c566a8 --- /dev/null +++ b/sidecars/panel/test/ssh-remote-endpoints.test.mjs @@ -0,0 +1,1637 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import http from 'node:http'; +import os from 'node:os'; +import path from 'node:path'; +import test from 'node:test'; +import vm from 'node:vm'; +import { createContextWindowSyncExpression } from '../backend/context-windows.mjs'; +import { + clearRemoteEndpointRegistry, + getRegisteredRemoteEndpoint, + registerRemoteEndpoint, +} from '../backend/endpoint-registry.mjs'; +import { + buildWindowRemoteRpcExpression, + classifyWindowTargetEndpoint, + createWindowBridgeController, + extractRemoteHostMetadata, +} from '../backend/window-bridge.mjs'; +import { + LOCAL_ENDPOINT_ID, + WINDOW_BRIDGE_ENDPOINT_HEADER, + WINDOW_BRIDGE_ENDPOINT_KEY, + WINDOW_BRIDGE_KEY, +} from '../shared/window-bridge-protocol.mjs'; +import { backendHarness } from './backend-harness.mjs'; + +test('Window classification strictly distinguishes local Desktop/IDE windows from SSH remote windows (including 2.33.0+ without csrfToken)', () => { + const ideTarget = { isIdeWorkbench: true, url: 'vscode-file://vscode-app/workbench.html' }; + assert.equal( + classifyWindowTargetEndpoint({ + target: ideTarget, + probedInfo: { appConfig: { isRemoteControl: true, sshHost: 'remote-box' } }, + }).isRemote, + false + ); + + // Local window matching local hub httpsPort stays local + const localHubInfo = { + allPorts: new Set([41000, 41001]), + httpPorts: new Set([41000]), + httpsPorts: new Set([41001]), + csrfTokens: new Set(['local-csrf']), + }; + const localWin = classifyWindowTargetEndpoint({ + target: { url: 'https://127.0.0.1:41001/c/11111111-1111-1111-1111-111111111111' }, + probedInfo: { origin: 'https://127.0.0.1:41001', csrfToken: '' }, + localHubInfo, + }); + assert.equal(localWin.isRemote, false); + assert.equal(localWin.endpointId, LOCAL_ENDPOINT_ID); + + // SSH window on a different loopback port with explicit sshHost -> remote with stableHostKey + const sshWinExplicit = classifyWindowTargetEndpoint({ + target: { url: 'https://127.0.0.1:52001/c/22222222-2222-2222-2222-222222222222' }, + probedInfo: { + origin: 'https://127.0.0.1:52001', + csrfToken: 'remote-csrf', + appConfig: { sshHost: 'fuxi-office-4090-test', isRemoteControl: true }, + }, + localHubInfo, + }); + assert.equal(sshWinExplicit.isRemote, true); + assert.equal(sshWinExplicit.stableHostKey, 'fuxi-office-4090-test'); + assert.equal(sshWinExplicit.hostLabel, 'fuxi-office-4090-test'); + + // 2.33.0+ omitted csrfToken: different port when local httpsPort is known -> remote + const sshWin233 = classifyWindowTargetEndpoint({ + target: { url: 'https://127.0.0.1:52002/c/33333333-3333-3333-3333-333333333333' }, + probedInfo: { origin: 'https://127.0.0.1:52002', csrfToken: '', appConfig: {} }, + localHubInfo, + }); + assert.equal(sshWin233.isRemote, true); + assert.equal(sshWin233.hostLabel, 'SSH:52002'); + + // Guard against false positive: lone Desktop window when only httpPort is known (no hub_*.json httpsPort) + const httpOnlyHubInfo = { + allPorts: new Set([41000]), + httpPorts: new Set([41000]), + httpsPorts: new Set(), + csrfTokens: new Set(['local-csrf']), + }; + const loneLocalWin = classifyWindowTargetEndpoint({ + target: { url: 'https://127.0.0.1:41001/c/44444444-4444-4444-4444-444444444444' }, + probedInfo: { origin: 'https://127.0.0.1:41001', csrfToken: '', appConfig: {} }, + localHubInfo: httpOnlyHubInfo, + confirmedLocalPorts: new Set(), + }); + assert.equal(loneLocalWin.isRemote, false); + + // extractRemoteHostMetadata cleans ssh-remote+ prefixes and title tags safely + const meta = extractRemoteHostMetadata({ remoteAuthority: 'ssh-remote+gpu-node-1' }, 'Antigravity'); + assert.equal(meta.hasExplicitRemoteFlag, true); + assert.equal(meta.stableHostKey, 'gpu-node-1'); + assert.equal(meta.hostLabel, 'gpu-node-1'); +}); + +test('Per-endpoint backend isolation keeps local and multiple SSH windows completely independent (telemetry, analytics, quotas, cache rebuild, and 503 guard)', async () => { + const nowIso = new Date().toISOString(); + const h = backendHarness({ + userStatus: { email: 'local@example.com', userTier: { name: 'Google AI Pro' } }, + summaries: { + '11111111-1111-1111-1111-111111111111': { + annotations: { title: 'Local Session' }, + stepCount: 1, + lastModifiedTime: nowIso, + status: 'IDLE', + }, + }, + trajectories: { + '11111111-1111-1111-1111-111111111111': { + trajectory: { + steps: [ + { + metadata: { + createdAt: nowIso, + finishedGeneratingAt: nowIso, + modelUsage: { model: 'MODEL_PLACEHOLDER_M427', inputTokens: 1000, outputTokens: 200 }, + }, + plannerResponse: { response: 'local reply' }, + }, + ], + }, + }, + }, + deepStats: { + accountName: 'local@example.com', + perConvo: { + 'ide:99999999-9999-9999-9999-999999999999': { + appSource: 'ide', + entries: [{ ts: nowIso, inp: 5000, cache: 0, out: 500, model: 'MODEL_PLACEHOLDER_M427' }], + }, + }, + }, + }); + + const remoteA = h.registerRemoteEndpoint({ + origin: 'https://127.0.0.1:53001', + csrfToken: '', + wsUrl: 'ws://127.0.0.1:9222/devtools/page/ssh-a', + label: 'gpu-4090', + stableHostKey: 'gpu-4090', + }); + const remoteB = h.registerRemoteEndpoint({ + origin: 'https://127.0.0.1:53002', + csrfToken: '', + wsUrl: 'ws://127.0.0.1:9222/devtools/page/ssh-b', + label: 'cpu-node', + stableHostKey: 'cpu-node', + }); + + const remoteRpcLog = []; + h.setRemoteWindowRpcInvoker(async (endpoint, method, body) => { + remoteRpcLog.push({ id: endpoint.id, method, body }); + if (endpoint.id === remoteA.id) { + if (method === 'GetUserStatus') { + return { userStatus: { email: 'remote-a@example.com', userTier: { name: 'Google AI Ultra' } } }; + } + if (method === 'GetAvailableModels') return { response: { models: {} } }; + if (method === 'RetrieveUserQuotaSummary') return { response: { groups: [] } }; + if (method === 'GetAllCascadeTrajectories') { + return { + trajectorySummaries: { + 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa': { + annotations: { title: 'SSH-A Training Job' }, + stepCount: 1, + lastModifiedTime: nowIso, + status: 'IDLE', + }, + }, + }; + } + if (method === 'GetCascadeTrajectory') { + return { + trajectory: { + steps: [ + { + metadata: { + createdAt: nowIso, + finishedGeneratingAt: nowIso, + modelUsage: { model: 'MODEL_PLACEHOLDER_M427', inputTokens: 3000, outputTokens: 400 }, + }, + plannerResponse: { response: 'remote A reply' }, + }, + ], + }, + }; + } + } + if (endpoint.id === remoteB.id) { + if (method === 'GetUserStatus') { + return { userStatus: { email: 'remote-b@example.com', userTier: { name: 'Google AI Pro' } } }; + } + if (method === 'GetAvailableModels') return { response: { models: {} } }; + if (method === 'RetrieveUserQuotaSummary') return { response: { groups: [] } }; + if (method === 'GetAllCascadeTrajectories') { + return { + trajectorySummaries: { + 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb': { + annotations: { title: 'SSH-B Kernel Build' }, + stepCount: 1, + lastModifiedTime: nowIso, + status: 'IDLE', + }, + }, + }; + } + if (method === 'GetCascadeTrajectory') { + return { + trajectory: { + steps: [ + { + metadata: { + createdAt: nowIso, + finishedGeneratingAt: nowIso, + modelUsage: { model: 'MODEL_PLACEHOLDER_M427', inputTokens: 700, outputTokens: 100 }, + }, + plannerResponse: { response: 'remote B reply' }, + }, + ], + }, + }; + } + } + throw new Error(`Unexpected remote RPC: ${endpoint.id} ${method}`); + }); + + // 1. Unregistered valid remote endpoint -> 503 retryable (never silently leaks local data) + const pendingRes = await h.executeTelemetryAction({ range: 'today' }, { endpointId: 'remote:ssh-unregistered-1234' }); + assert.equal(pendingRes.status, 503); + assert.equal(JSON.parse(pendingRes.body).retryable, true); + + // 2. Invalid endpointId -> 400 + const invalidRes = await h.executeTelemetryAction({ range: 'today' }, { endpointId: 'remote:../evil' }); + assert.equal(invalidRes.status, 400); + + // 3. Local, Remote A, Remote B telemetry are completely isolated + const [localRes, resA, resB] = await Promise.all([ + h.executeTelemetryAction({ range: 'all' }), + h.executeTelemetryAction({ range: 'all' }, { endpointId: remoteA.id }), + h.executeTelemetryAction({ range: 'all' }, { endpointId: remoteB.id }), + ]); + assert.equal(localRes.status, 200); + assert.equal(resA.status, 200); + assert.equal(resB.status, 200); + + const localTel = JSON.parse(localRes.body); + const telA = JSON.parse(resA.body); + const telB = JSON.parse(resB.body); + + assert.equal(localTel.endpoint.id, LOCAL_ENDPOINT_ID); + assert.equal(localTel.endpoint.isRemote, false); + assert.equal(localTel.account.email, 'local@example.com'); + assert.equal(localTel.activeConversation.cascadeId, '11111111-1111-1111-1111-111111111111'); + // Local includes deepStats (5500) + local session (1200) = 6700 + assert.equal(localTel.consumption.account.totalTokens, 6700); + + assert.equal(telA.endpoint.id, remoteA.id); + assert.equal(telA.endpoint.isRemote, true); + assert.equal(telA.endpoint.label, 'gpu-4090'); + assert.equal(telA.account.email, 'remote-a@example.com'); + assert.equal(telA.activeConversation.cascadeId, 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'); + // Remote A excludes local sessions & local deepStats: strictly 3400 tokens + assert.equal(telA.consumption.account.totalTokens, 3400); + assert.equal(telA.consumption.sourcesBreakdown[0].name, 'Antigravity SSH'); + + assert.equal(telB.endpoint.id, remoteB.id); + assert.equal(telB.endpoint.isRemote, true); + assert.equal(telB.account.email, 'remote-b@example.com'); + assert.equal(telB.activeConversation.cascadeId, 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'); + assert.equal(telB.consumption.account.totalTokens, 800); + + // 4. Rebuilding cache on remoteA clears ONLY remoteA, leaving local & remoteB caches intact + assert.ok(h.getEndpointCacheStore(remoteA).getCachedTrajectory('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa')); + assert.ok(h.getEndpointCacheStore(remoteB).getCachedTrajectory('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb')); + const rebuildRes = h.executeRebuildCacheAction(undefined, { endpointId: remoteA.id }); + assert.equal(rebuildRes.status, 200); + assert.equal(h.getEndpointCacheStore(remoteA).getCachedTrajectory('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'), undefined); + assert.ok(h.getEndpointCacheStore(remoteB).getCachedTrajectory('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb')); + assert.ok(h.getCachedTrajectory('11111111-1111-1111-1111-111111111111')); + assert.ok(remoteRpcLog.some((c) => c.id === remoteA.id && c.method === 'GetAllCascadeTrajectories')); +}); + +test('Tier-1 loopback HTTPS falls back with 60s circuit breaker to Tier-2 window RPC, and stateless window RPC falls back from fetch 401 to /connect-websocket', async () => { + const h = backendHarness({}); + const ep = h.registerRemoteEndpoint({ + origin: 'https://127.0.0.1:54111', + baseUrl: 'https://127.0.0.1:54111', + csrfToken: 'stale-csrf', + wsUrl: 'ws://127.0.0.1:9222/devtools/page/ssh-fallback', + label: 'fallback-host', + stableHostKey: 'fallback-host', + }); + + let tier1Calls = 0; + let tier2Calls = 0; + h.setLoopbackHttpsRequester((_opts, cb) => { + tier1Calls += 1; + const listeners = {}; + const req = { + setTimeout() {}, + on(ev, fn) { listeners[ev] = fn; }, + write() {}, + end() { + const resListeners = {}; + const res = { + statusCode: 403, + on(ev, fn) { resListeners[ev] = fn; }, + }; + cb(res); + resListeners.data?.(Buffer.from('forbidden')); + resListeners.end?.(); + }, + destroy() {}, + }; + return req; + }); + h.setRemoteWindowRpcInvoker(async (_endpoint, method) => { + tier2Calls += 1; + if (method === 'GetUserStatus') return { userStatus: { email: 'tier2@example.com' } }; + if (method === 'GetAllCascadeTrajectories') return { trajectorySummaries: {} }; + if (method === 'RetrieveUserQuotaSummary') return { response: { groups: [] } }; + if (method === 'GetAvailableModels') return { response: { models: {} } }; + return {}; + }); + + const first = await h.executeTelemetryAction({ range: 'today' }, { endpointId: ep.id }); + assert.equal(first.status, 200); + assert.equal(JSON.parse(first.body).account.email, 'tier2@example.com'); + assert.equal(tier1Calls, 1); // Circuit breaker tripped after first 403! + assert.ok(tier2Calls >= 2); + + // Subsequent poll skips Tier-1 completely while circuit breaker is open + const prevTier1 = tier1Calls; + await h.executeTelemetryAction({ range: 'today', force: '1' }, { endpointId: ep.id }); + assert.equal(tier1Calls, prevTier1); + + // Verify stateless window RPC expression: fetch 401 -> /connect-websocket fallback with clean ws.close() + let wsClosed = false; + let sentFrame = null; + class MockConnectWebSocket { + constructor(url) { + this.url = url; + this.listeners = new Map(); + queueMicrotask(() => this._emit('open', {})); + } + addEventListener(type, fn) { + if (!this.listeners.has(type)) this.listeners.set(type, []); + this.listeners.get(type).push(fn); + } + send(raw) { + sentFrame = JSON.parse(raw); + queueMicrotask(() => + this._emit('message', { + data: JSON.stringify({ + streamId: sentFrame.streamId, + payload: { userStatus: { email: 'ws-fallback@example.com' } }, + }), + }) + ); + } + close() { + wsClosed = true; + } + _emit(type, ev) { + for (const fn of this.listeners.get(type) || []) fn(ev); + } + } + const winCtx = vm.createContext({ + window: { + location: new URL('https://127.0.0.1:54111/c/abc'), + __APP_CONFIG__: {}, + fetch: async () => ({ ok: false, status: 401, text: async () => 'unauthorized' }), + WebSocket: MockConnectWebSocket, + }, + AbortSignal, + setTimeout, + clearTimeout, + }); + const rpcRes = await vm.runInContext( + buildWindowRemoteRpcExpression('GetUserStatus', {}, 2000), + winCtx + ); + assert.equal(rpcRes.ok, true); + assert.equal(rpcRes.transport, 'ws'); + assert.equal(rpcRes.data.userStatus.email, 'ws-fallback@example.com'); + assert.equal(wsClosed, true); + assert.equal(sentFrame.procedure, '/exa.language_server_pb.LanguageServerService/GetUserStatus'); +}); + +test('Context window overrides activate in SSH windows when allowRemoteHost=true and stay disabled when allowRemoteHost=false', async () => { + const sendPath = '/exa.language_server_pb.LanguageServerService/SendUserCascadeMessage'; + const carbon = 'MODEL_PLACEHOLDER_M427'; + const host = 'https://127.0.0.1:55190'; + const nativeFetch = async (_url, init) => init; + class MockWS { + constructor(url) { this.url = url; } + send(data) { return data; } + } + const win = { + location: new URL(host), + fetch: nativeFetch, + WebSocket: MockWS, + __APP_CONFIG__: { isRemoteControl: true, sshHost: 'fuxi-office-4090-test' }, + }; + const ctx = vm.createContext({ + window: win, + URL, + TextEncoder, + TextDecoder, + Headers, + Uint8Array, + AbortSignal, + setTimeout, + clearTimeout, + }); + + const prefs = { 'model:gemini-4-carbon': '256000' }; + const fallbackRules = { [carbon]: 256000 }; + + // Default allowRemoteHost=false keeps legacy skip behavior for isRemoteControl + const skipped = await vm.runInContext( + createContextWindowSyncExpression(prefs, 'boot-ssh-1', fallbackRules, false), + ctx + ); + assert.equal(skipped.attached, false); + assert.equal(win.fetch, nativeFetch); + + // Desktop SSH loopback window with allowRemoteHost=true attaches, rewrites, and passively observes CSRF + const attached = await vm.runInContext( + createContextWindowSyncExpression(prefs, 'boot-ssh-1', fallbackRules, true), + ctx + ); + assert.equal(attached.attached, true); + assert.equal(attached.ruleCount, 1); + + const payload = { + cascadeConfig: { + plannerConfig: { planModel: carbon }, + checkpointConfig: { maxTokenLimit: 512000 }, + }, + }; + const out = await win.fetch(host + sendPath, { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'x-codeium-csrf-token': 'observed-ssh-csrf' }, + body: JSON.stringify(payload), + }); + assert.equal(JSON.parse(out.body).cascadeConfig.checkpointConfig.maxTokenLimit, 256000); + assert.equal(win.__AGUsageMonitorContextWindows.observedCsrfToken, 'observed-ssh-csrf'); + + // Clean dispose restores exact nativeFetch reference + await vm.runInContext(createContextWindowSyncExpression({}, 'boot-ssh-1', {}, true), ctx); + assert.equal(win.fetch, nativeFetch); +}); + +test('CDP bridge classifies local + SSH windows simultaneously, prefetches per-endpoint initialTelemetry, routes X-Usage-Monitor-Endpoint header, and supports SSH context windows in sidebar mode', async () => { + clearRemoteEndpointRegistry(); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ag-wm-ssh-cdp-')); + const portFile = path.join(tmpDir, 'DevToolsActivePort'); + + const localWinObj = { + location: new URL('https://127.0.0.1:61001/c/11111111-1111-1111-1111-111111111111'), + __APP_CONFIG__: { csrfToken: 'local-hub-csrf' }, + fetch: async (_u, init) => init, + WebSocket: class { constructor(u) { this.url = u; } send(d) { return d; } }, + URL, TextEncoder, TextDecoder, Headers, Uint8Array, AbortSignal, setTimeout, clearTimeout, + }; + localWinObj.window = localWinObj; + localWinObj.globalThis = localWinObj; + + const sshWinObj = { + location: new URL('https://127.0.0.1:62001/c/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'), + __APP_CONFIG__: { isRemoteControl: true, sshHost: 'fuxi-office-4090-test' }, + fetch: async (_u, init) => init, + WebSocket: class { constructor(u) { this.url = u; } send(d) { return d; } }, + URL, TextEncoder, TextDecoder, Headers, Uint8Array, AbortSignal, setTimeout, clearTimeout, + }; + sshWinObj.window = sshWinObj; + sshWinObj.globalThis = sshWinObj; + + const windowContexts = new Map([ + ['win-local', vm.createContext(localWinObj)], + ['win-ssh', vm.createContext(sshWinObj)], + ]); + + class MockCdpWebSocket { + constructor(url) { + this.url = url; + this.targetId = url.split('/').pop(); + this.listeners = new Map(); + queueMicrotask(() => this._emit('open', {})); + } + addEventListener(type, fn) { + if (!this.listeners.has(type)) this.listeners.set(type, []); + this.listeners.get(type).push(fn); + } + send(raw) { + const msg = JSON.parse(raw); + if (msg.method === 'Runtime.evaluate') { + const ctx = windowContexts.get(this.targetId); + const value = vm.runInContext(msg.params.expression, ctx); + Promise.resolve(value).then((result) => + this._emit('message', { + data: JSON.stringify({ id: msg.id, result: { result: { value: result } } }), + }) + ); + } + } + close() {} + _emit(type, ev) { + for (const fn of this.listeners.get(type) || []) fn(ev); + } + } + + const cdpHttpServer = http.createServer((req, res) => { + if (req.url === '/json/list') { + const cdpPort = cdpHttpServer.address().port; + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end( + JSON.stringify([ + { + id: 'win-local', + type: 'page', + url: 'https://127.0.0.1:61001/c/11111111-1111-1111-1111-111111111111', + webSocketDebuggerUrl: `ws://127.0.0.1:${cdpPort}/devtools/page/win-local`, + }, + { + id: 'win-ssh', + type: 'page', + url: 'https://127.0.0.1:62001/c/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', + webSocketDebuggerUrl: `ws://127.0.0.1:${cdpPort}/devtools/page/win-ssh`, + }, + ]) + ); + return; + } + res.writeHead(404); + res.end(); + }); + + await new Promise((resolve) => cdpHttpServer.listen(0, '127.0.0.1', resolve)); + fs.writeFileSync(portFile, `${cdpHttpServer.address().port}\n/devtools/browser/mock`, 'utf8'); + + const apiCalls = []; + let overlayEnabled = false; // First verify sidebar mode still registers SSH + attaches context windows! + const mockAppJs = ` + (() => { + window.__AGUsageMonitorOverlay?.dispose?.(); + const br = window.__AGUsageMonitorBridge; + let alive = true; + window.__AGUsageMonitorOverlay = { + bundleVersion: br.bundleVersion, + ensureAlive: () => alive, + updateBridge: (next) => { Object.assign(window.__AGUsageMonitorBridge, next); }, + dispose: () => { alive = false; }, + }; + })(); + `; + + const controller = createWindowBridgeController({ + handleApiRequest: async (pathname, method, data, ctx) => { + apiCalls.push({ pathname, method, data, endpointId: ctx?.endpointId || LOCAL_ENDPOINT_ID }); + return { + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + endpoint: { id: ctx?.endpointId || LOCAL_ENDPOINT_ID, isRemote: Boolean(ctx?.endpointId) }, + ok: true, + }), + }; + }, + readAssetFn: async (rel) => (rel === 'styles.css' ? ':host{}' : mockAppJs), + getSettingsFn: () => ({ + enableWindowOverlay: overlayEnabled, + windowMountMode: overlayEnabled ? 'dual' : 'sidebar', + modelContextWindows: { 'model:gemini-4-carbon': '256000' }, + }), + getBundleVersionFn: () => 'v-ssh-1', + env: { ANTIGRAVITY_DEVTOOLS_PORT_FILE: portFile }, + WebSocketImpl: MockCdpWebSocket, + getLocalHubPortsFn: () => ({ + allPorts: new Set([61000, 61001]), + httpPorts: new Set([61000]), + httpsPorts: new Set([61001]), + csrfTokens: new Set(['local-hub-csrf']), + }), + }); + + try { + // 1. Even in sidebar-only mode, SSH endpoint is classified & registered before early return + const sidebarSync = await controller.syncAllWindows(); + assert.equal(sidebarSync.enabled, false); + + // 2. Enable overlay mode -> injects both windows with separate endpointIds & initialTelemetry + overlayEnabled = true; + const dualSync = await controller.syncAllWindows(); + assert.equal(dualSync.ok, true); + assert.equal(dualSync.injected, 2); + + const localBridge = localWinObj[WINDOW_BRIDGE_KEY]; + const sshBridge = sshWinObj[WINDOW_BRIDGE_KEY]; + assert.equal(localBridge[WINDOW_BRIDGE_ENDPOINT_KEY], LOCAL_ENDPOINT_ID); + assert.equal(localBridge.isRemoteEndpoint, false); + assert.equal(localBridge.initialTelemetry.endpoint.id, LOCAL_ENDPOINT_ID); + + assert.match(sshBridge[WINDOW_BRIDGE_ENDPOINT_KEY], /^remote:ssh-fuxi-office-4090-test-/); + assert.equal(sshBridge.isRemoteEndpoint, true); + assert.equal(sshBridge.endpointLabel, 'fuxi-office-4090-test'); + assert.equal(sshBridge.initialTelemetry.endpoint.id, sshBridge[WINDOW_BRIDGE_ENDPOINT_KEY]); + assert.ok(getRegisteredRemoteEndpoint(sshBridge[WINDOW_BRIDGE_ENDPOINT_KEY])); + + // 3. HTTP bridge routes X-Usage-Monitor-Endpoint header to the remote endpoint + const { port, token } = controller.getBridgeInfo(); + const httpRes = await fetch(`http://127.0.0.1:${port}/api/telemetry?range=today`, { + headers: { + Origin: 'https://127.0.0.1:62001', + 'X-Usage-Monitor-Token': token, + [WINDOW_BRIDGE_ENDPOINT_HEADER]: sshBridge[WINDOW_BRIDGE_ENDPOINT_KEY], + }, + }); + assert.equal(httpRes.status, 200); + const body = await httpRes.json(); + assert.equal(body.endpoint.id, sshBridge[WINDOW_BRIDGE_ENDPOINT_KEY]); + assert.equal(body.endpoint.isRemote, true); + } finally { + await controller.stop(); + clearRemoteEndpointRegistry(); + cdpHttpServer.close(); + fs.rmSync(tmpDir, { recursive: true, force: true }); + } +}); + +test('httpClient attaches X-Usage-Monitor-Endpoint and does NOT downgrade to CDP on HTTP 503 retryable responses', async () => { + const { callSidecarApi } = await import('../src/core/httpClient.js'); + const prevWindow = globalThis.window; + const seenHeaders = []; + const mockBridge = { + port: 18765, + token: 'tok-123', + [WINDOW_BRIDGE_ENDPOINT_KEY]: 'remote:ssh-gpu-1234567890ab', + transportMode: 'http', + }; + globalThis.window = { + [WINDOW_BRIDGE_KEY]: mockBridge, + fetch: async (_url, init) => { + seenHeaders.push(init.headers); + return { + ok: false, + status: 503, + json: async () => ({ error: 'Remote endpoint initializing', retryable: true }), + }; + }, + }; + try { + await assert.rejects( + () => callSidecarApi('/api/telemetry?range=today', { abortKey: 'test-503' }), + (err) => err.httpStatus === 503 && err.retryable === true + ); + assert.equal(mockBridge.transportMode, 'http'); // Must NOT flip to slow CDP mode! + assert.equal(seenHeaders[0][WINDOW_BRIDGE_ENDPOINT_HEADER], 'remote:ssh-gpu-1234567890ab'); + } finally { + if (prevWindow === undefined) delete globalThis.window; + else globalThis.window = prevWindow; + } +}); + +test('Remote executeModelContextWindowAction & executeAccountCredentialAction enforce strict endpoint boundaries', async () => { + const carbon = 'MODEL_PLACEHOLDER_M427'; + const h = backendHarness({ + availableModels: { + 'gemini-4-carbon-high': { model: carbon, maxTokens: 1048576, maxOutputTokens: 262144 }, + }, + userStatus: { + cascadeModelConfigData: { + clientModelConfigs: [ + { + label: 'Gemini 4 Carbon (High)', + modelId: 'gemini-4-carbon-high', + modelOrAlias: { model: carbon }, + contextWindowOptions: [{ name: '256K' }, { name: '900K' }], + }, + ], + }, + }, + }); + + const ep = h.registerRemoteEndpoint({ + origin: 'https://127.0.0.1:56101', + wsUrl: 'ws://127.0.0.1:9222/devtools/page/ssh-ctx', + label: 'strict-remote', + stableHostKey: 'strict-remote', + }); + + let remoteShouldThrow = false; + h.setRemoteWindowRpcInvoker(async (_endpoint, method) => { + if (remoteShouldThrow) throw new Error('remote offline'); + if (method === 'GetUserStatus') { + return { + userStatus: { + cascadeModelConfigData: { + clientModelConfigs: [ + { + label: 'Gemini 4 Carbon (High)', + modelId: 'gemini-4-carbon-high', + modelOrAlias: { model: carbon }, + contextWindowOptions: [{ name: '256K' }], // Remote does NOT allow 900K! + }, + ], + }, + }, + }; + } + if (method === 'GetAvailableModels') return { response: { models: {} } }; + return {}; + }); + + // 1. Remote accepts supported 256K + const okRes = await h.executeModelContextWindowAction( + { modelId: 'model:gemini-4-carbon', option: '256K' }, + { endpointId: ep.id } + ); + assert.equal(okRes.status, 200); + + // 2. Remote rejects 900K -> MUST return 400 and NEVER fall back to more permissive local config + const rejectedRes = await h.executeModelContextWindowAction( + { modelId: 'model:gemini-4-carbon', option: '900K' }, + { endpointId: ep.id } + ); + assert.equal(rejectedRes.status, 400); + + // 3. When remote RPC fails/throws, falls back safely to local validation + remoteShouldThrow = true; + const fallbackRes = await h.executeModelContextWindowAction( + { modelId: 'model:gemini-4-carbon', option: '900K' }, + { endpointId: ep.id } + ); + assert.equal(fallbackRes.status, 200); + + // 4. Unregistered / invalid endpoints on modelContextWindow and account credentials -> 503 / 400 (zero local leak) + const pendingCtx = await h.executeModelContextWindowAction( + { modelId: 'model:gemini-4-carbon', option: '256K' }, + { endpointId: 'remote:ssh-missing-1111' } + ); + assert.equal(pendingCtx.status, 503); + + const remoteAcct = await h.executeAccountCredentialAction(undefined, { endpointId: ep.id }); + assert.equal(remoteAcct.status, 200); + assert.equal(JSON.parse(remoteAcct.body).supported, false); + + const pendingAcct = await h.executeAccountCredentialAction(undefined, { + endpointId: 'remote:ssh-missing-1111', + }); + assert.equal(pendingAcct.status, 503); + + const invalidAcct = await h.executeAccountCredentialAction(undefined, { + endpointId: 'remote:../bad', + }); + assert.equal(invalidAcct.status, 400); + + // 5. Authoritative 'local' in opts cannot be spoofed by body/query endpointId + const spoofedRes = await h.dispatchBridgeApiRequest( + '/api/telemetry', + 'GET', + { endpointId: ep.id, range: 'today' }, + { endpointId: LOCAL_ENDPOINT_ID } + ); + assert.equal(spoofedRes.status, 200); + assert.equal(JSON.parse(spoofedRes.body).endpoint.id, LOCAL_ENDPOINT_ID); +}); + +test('Multi-window same-SSH-host preserves Tier-2 circuit breaker, clears stale CSRF on port change, fails over across live wsUrls, and guards pruning during inFlightCount > 0', async () => { + const h = backendHarness({}); + const ep1 = h.registerRemoteEndpoint({ + origin: 'https://127.0.0.1:57101', + baseUrl: 'https://127.0.0.1:57101', + csrfToken: 'tok-a', + wsUrl: 'ws://127.0.0.1:9222/devtools/page/w1', + label: 'shared-ssh', + stableHostKey: 'shared-ssh', + }); + const ep2 = h.registerRemoteEndpoint({ + origin: 'https://127.0.0.1:57102', + baseUrl: 'https://127.0.0.1:57102', + csrfToken: 'tok-b', + wsUrl: 'ws://127.0.0.1:9222/devtools/page/w2', + label: 'shared-ssh', + stableHostKey: 'shared-ssh', + }); + assert.equal(ep1.id, ep2.id); + assert.equal(ep1.targets.size, 2); + + // Tripping circuit breaker stays tripped across repeated polls alternating between the two known windows + h.markRemoteEndpointPreferTier2(ep1, 60_000); + assert.equal(h.shouldRemoteEndpointPreferTier2(ep1), true); + h.registerRemoteEndpoint({ + origin: 'https://127.0.0.1:57101', + baseUrl: 'https://127.0.0.1:57101', + csrfToken: 'tok-a', + wsUrl: 'ws://127.0.0.1:9222/devtools/page/w1', + label: 'shared-ssh', + stableHostKey: 'shared-ssh', + }); + h.registerRemoteEndpoint({ + origin: 'https://127.0.0.1:57102', + baseUrl: 'https://127.0.0.1:57102', + csrfToken: 'tok-b', + wsUrl: 'ws://127.0.0.1:9222/devtools/page/w2', + label: 'shared-ssh', + stableHostKey: 'shared-ssh', + }); + assert.equal(h.shouldRemoteEndpointPreferTier2(ep1), true); + + // Reconnecting to a brand new port without CSRF clears stale csrfToken + h.registerRemoteEndpoint({ + origin: 'https://127.0.0.1:57999', + baseUrl: 'https://127.0.0.1:57999', + csrfToken: '', + wsUrl: 'ws://127.0.0.1:9222/devtools/page/w1', + label: 'shared-ssh', + stableHostKey: 'shared-ssh', + }); + assert.equal(ep1.csrfToken, ''); + + // inFlightCount > 0 blocks pruning even when TTL=0; dropping to 0 allows clean prune + h.trackEndpointRequestStart(ep1); + ep1.lastSeenMs = Date.now() - 120_000; + h.pruneStaleRemoteEndpoints(new Set(), 1000); + assert.ok(h.getRegisteredRemoteEndpoint(ep1.id)); + h.trackEndpointRequestEnd(ep1); + h.pruneStaleRemoteEndpoints(new Set(), 1000); + assert.equal(h.getRegisteredRemoteEndpoint(ep1.id), null); +}); + +test('ls-rpc security & transport guards: rejects non-allowlisted remote RPC, non-loopback HTTPS, oversized Tier-1 responses, and avoids circuit-breaking on GetCascadeTrajectory 404', async () => { + const h = backendHarness({}); + const ep = h.registerRemoteEndpoint({ + origin: 'https://127.0.0.1:58101', + baseUrl: 'https://127.0.0.1:58101', + csrfToken: 'tok-sec', + wsUrl: 'ws://127.0.0.1:9222/devtools/page/sec', + label: 'sec-host', + stableHostKey: 'sec-host', + }); + + // 1. Disallowed mutating RPC method rejected immediately + await assert.rejects( + () => h.callLsRpc('SendUserCascadeMessage', {}, 1000, ep), + /not allowed on remote endpoints/i + ); + + // 2. GetCascadeTrajectory 404 does NOT trip Tier-2 circuit breaker + let tier2Invoked = false; + h.setRemoteWindowRpcInvoker(async () => { + tier2Invoked = true; + return {}; + }); + h.setLoopbackHttpsRequester((_opts, cb) => ({ + setTimeout() {}, + on() {}, + write() {}, + end() { + const resListeners = {}; + cb({ statusCode: 404, on(ev, fn) { resListeners[ev] = fn; } }); + resListeners.data?.(Buffer.from('not found')); + resListeners.end?.(); + }, + destroy() {}, + })); + await assert.rejects( + () => h.callLsRpc('GetCascadeTrajectory', { cascadeId: 'missing' }, 1000, ep), + /failed \(404\)/i + ); + assert.equal(tier2Invoked, false); + assert.equal(h.shouldRemoteEndpointPreferTier2(ep), false); + + // 3. Oversized Tier-1 response (>32MB) rejects cleanly without resolving truncated body + h.setRemoteWindowRpcInvoker(null); + h.setLoopbackHttpsRequester((_opts, cb) => ({ + setTimeout() {}, + on() {}, + write() {}, + end() { + const resListeners = {}; + cb({ statusCode: 200, on(ev, fn) { resListeners[ev] = fn; } }); + resListeners.data?.(Buffer.alloc(33 * 1024 * 1024)); + resListeners.end?.(); + }, + destroy() {}, + })); + await assert.rejects( + () => h.callLsRpc('GetUserStatus', {}, 1000, ep), + /exceeded size limit/i + ); +}); + +test('Multi-window Tier-2 failover switches from a dead wsUrl to a live wsUrl on the same SSH host', async () => { + clearRemoteEndpointRegistry(); + const ep = registerRemoteEndpoint({ + origin: 'https://127.0.0.1:59101', + wsUrl: 'ws://127.0.0.1:9222/devtools/page/dead-win', + label: 'failover-ssh', + stableHostKey: 'failover-ssh', + }); + // Register second live window slightly later (or higher lastSeenMs); simulate first attempt failing + registerRemoteEndpoint({ + origin: 'https://127.0.0.1:59101', + wsUrl: 'ws://127.0.0.1:9222/devtools/page/live-win', + label: 'failover-ssh', + stableHostKey: 'failover-ssh', + }); + ep.targets.get('ws://127.0.0.1:9222/devtools/page/dead-win').lastSeenMs = Date.now() + 1000; + + const attemptedTargets = []; + class FailoverMockWS { + constructor(url) { + this.url = url; + this.targetId = url.split('/').pop(); + this.listeners = new Map(); + attemptedTargets.push(this.targetId); + queueMicrotask(() => { + if (this.targetId === 'dead-win') { + this._emit('error', new Error('target closed')); + } else { + this._emit('open', {}); + } + }); + } + addEventListener(type, fn) { + if (!this.listeners.has(type)) this.listeners.set(type, []); + this.listeners.get(type).push(fn); + } + send(raw) { + const msg = JSON.parse(raw); + queueMicrotask(() => + this._emit('message', { + data: JSON.stringify({ + id: msg.id, + result: { + result: { value: { ok: true, status: 200, data: { userStatus: { email: 'live@ssh' } } } }, + }, + }), + }) + ); + } + close() {} + _emit(type, ev) { + for (const fn of this.listeners.get(type) || []) fn(ev); + } + } + + const controller = createWindowBridgeController({ + handleApiRequest: async () => ({ status: 200, body: '{}' }), + readAssetFn: async () => '', + WebSocketImpl: FailoverMockWS, + }); + try { + const out = await controller.invokeRemoteWindowRpc(ep, 'GetUserStatus', {}, 1500); + assert.deepEqual(attemptedTargets, ['dead-win', 'live-win']); + assert.equal(out.userStatus.email, 'live@ssh'); + } finally { + await controller.stop(); + clearRemoteEndpointRegistry(); + } +}); + +test('Multi-file atomic cache writes preserve independent local and remote_caches files without clobbering byte reuse', async () => { + const { writeTrajectoryCacheFile } = await import('../backend/trajectory-cache-file.mjs'); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ag-wm-multicache-')); + const localFile = path.join(tmpDir, 'trajectory_usage_cache.json'); + const remoteFile = path.join(tmpDir, 'ssh-gpu-abcdef123456.json'); + try { + const localSteps = [{ stepIndex: 1, inputTokens: 111, outputTokens: 22 }]; + const remoteSteps = [{ stepIndex: 1, inputTokens: 999, outputTokens: 88 }]; + writeTrajectoryCacheFile(localFile, { c1: { title: 'local', steps: localSteps } }); + writeTrajectoryCacheFile(remoteFile, { r1: { title: 'remote', steps: remoteSteps } }); + // Interleaved second writes keep exact data integrity in both files + writeTrajectoryCacheFile(localFile, { c1: { title: 'local-v2', steps: localSteps } }); + writeTrajectoryCacheFile(remoteFile, { r1: { title: 'remote-v2', steps: remoteSteps } }); + + const parsedLocal = JSON.parse(fs.readFileSync(localFile, 'utf8')); + const parsedRemote = JSON.parse(fs.readFileSync(remoteFile, 'utf8')); + assert.equal(parsedLocal.c1.title, 'local-v2'); + assert.equal(parsedLocal.c1.steps[0].inputTokens, 111); + assert.equal(parsedRemote.r1.title, 'remote-v2'); + assert.equal(parsedRemote.r1.steps[0].inputTokens, 999); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } +}); + +test('WindowOverlayShell updateBridge rejects stale CDP rpcQueue on endpoint switch and TopSessionHeader renders SSH badge', async () => { + const { createMockDom } = await import('./mock-dom.mjs'); + const bundleCode = fs.readFileSync(new URL('../app.js', import.meta.url), 'utf8'); + const { document } = createMockDom(); + let fetchSeq = 0; + let staleRejected = false; + const staleRpcPending = new Map([ + ['old-req-1', { resolve: () => {}, reject: () => { staleRejected = true; } }], + ]); + const mockWin = { + innerWidth: 1280, + innerHeight: 820, + location: { pathname: '/c/11111111-2222-3333-4444-555555555555', search: '' }, + addEventListener() {}, + removeEventListener() {}, + getComputedStyle: () => ({ getPropertyValue: () => '', display: 'flex', flexDirection: 'row' }), + [WINDOW_BRIDGE_KEY]: { + port: 19001, + token: 'tok-overlay', + bundleVersion: 'v-ui-1', + mountMode: 'dual', + [WINDOW_BRIDGE_ENDPOINT_KEY]: LOCAL_ENDPOINT_ID, + isRemoteEndpoint: false, + endpointLabel: '', + stylesCss: ':host{}', + rpcQueue: [{ id: 'old-req-1', path: '/api/telemetry', method: 'GET' }], + rpcPending: staleRpcPending, + }, + fetch: async (_url, init) => { + const seq = ++fetchSeq; + const epHeader = init?.headers?.[WINDOW_BRIDGE_ENDPOINT_HEADER] || LOCAL_ENDPOINT_ID; + return { + ok: true, + status: 200, + json: async () => ({ + endpoint: { + id: epHeader, + isRemote: epHeader !== LOCAL_ENDPOINT_ID, + label: epHeader !== LOCAL_ENDPOINT_ID ? 'gpu-4090' : '', + }, + account: { status: 'signedIn', email: `${epHeader}@example.com` }, + conversations: [], + runningConversations: [], + activeConversation: { cascadeId: `conv-${seq}`, title: `Title-${epHeader}`, steps: [], agents: [] }, + quotas: { pools: [], meta: {} }, + consumption: { selectedRange: { key: 'today' }, session: {}, account: {}, presets: {}, trendSeries: [], sourcesBreakdown: [], monthlySeries: [] }, + settings: { language: 'zh-CN', windowMountMode: 'dual', enableWindowOverlay: true }, + }), + }; + }, + }; + + const sandbox = vm.createContext({ + window: mockWin, + document, + navigator: { language: 'zh-CN' }, + globalThis: mockWin, + console, + URL, + URLSearchParams, + AbortController, + queueMicrotask, + setTimeout, + clearTimeout, + setInterval, + clearInterval, + requestAnimationFrame: (fn) => setTimeout(fn, 0), + cancelAnimationFrame: (id) => clearTimeout(id), + Date, + Math, + JSON, + Map, + Set, + WeakMap, + Promise, + Number, + String, + Boolean, + Array, + Object, + RegExp, + Error, + }); + vm.runInContext(bundleCode, sandbox); + const overlay = mockWin.__AGUsageMonitorOverlay; + assert.ok(overlay); + + // Switch endpoint from local -> SSH remote via updateBridge + overlay.updateBridge({ + port: 19001, + token: 'tok-overlay', + [WINDOW_BRIDGE_ENDPOINT_KEY]: 'remote:ssh-gpu-4090-1234567890ab', + isRemoteEndpoint: true, + endpointLabel: 'gpu-4090', + }); + assert.equal(staleRejected, true); + assert.equal(mockWin[WINDOW_BRIDGE_KEY].rpcQueue.length, 0); + assert.equal(mockWin[WINDOW_BRIDGE_KEY].rpcPending.size, 0); + + // Allow force fetch to resolve and verify SSH badge renders in TopSessionHeader + await new Promise((r) => setTimeout(r, 260)); + overlay.open(); + await new Promise((r) => setTimeout(r, 30)); + const portalHost = document.getElementById('ag-usage-monitor-portal'); + const sshBadge = portalHost?.shadowRoot?.querySelector?.('.endpoint-ssh-badge'); + assert.ok(sshBadge, 'Expected .endpoint-ssh-badge inside mounted portal'); + assert.equal(sshBadge.getAttribute('hidden'), null); + assert.equal(sshBadge.getAttribute('title'), 'SSH · gpu-4090'); + + overlay.dispose(); +}); + +test('window-bridge does NOT leak localFallbackRules into SSH window when remote host verifies its models and rejects the override', async () => { + clearRemoteEndpointRegistry(); + const { setRemoteWindowRpcInvoker } = await import('../backend/endpoint-registry.mjs'); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ag-wm-ssh-ctx-iso-')); + const portFile = path.join(tmpDir, 'DevToolsActivePort'); + const carbon = 'MODEL_PLACEHOLDER_M427'; + + const sshWinObj = { + location: new URL('https://127.0.0.1:63001/c/cccccccc-cccc-cccc-cccc-cccccccccccc'), + __APP_CONFIG__: { isRemoteControl: true, sshHost: 'small-tier-ssh' }, + fetch: async (_u, init) => init, + WebSocket: class { constructor(u) { this.url = u; } send(d) { return d; } }, + URL, TextEncoder, TextDecoder, Headers, Uint8Array, AbortSignal, setTimeout, clearTimeout, + }; + sshWinObj.window = sshWinObj; + sshWinObj.globalThis = sshWinObj; + const sshCtx = vm.createContext(sshWinObj); + + class MockWS { + constructor(url) { + this.url = url; + this.listeners = new Map(); + queueMicrotask(() => this._emit('open', {})); + } + addEventListener(type, fn) { + if (!this.listeners.has(type)) this.listeners.set(type, []); + this.listeners.get(type).push(fn); + } + send(raw) { + const msg = JSON.parse(raw); + const value = vm.runInContext(msg.params.expression, sshCtx); + Promise.resolve(value).then((result) => + this._emit('message', { + data: JSON.stringify({ id: msg.id, result: { result: { value: result } } }), + }) + ); + } + close() {} + _emit(type, ev) { + for (const fn of this.listeners.get(type) || []) fn(ev); + } + } + + const cdpServer = http.createServer((req, res) => { + if (req.url === '/json/list') { + const p = cdpServer.address().port; + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end( + JSON.stringify([ + { + id: 'ssh-small', + type: 'page', + url: 'https://127.0.0.1:63001/c/cccccccc-cccc-cccc-cccc-cccccccccccc', + webSocketDebuggerUrl: `ws://127.0.0.1:${p}/devtools/page/ssh-small`, + }, + ]) + ); + return; + } + res.writeHead(404); + res.end(); + }); + await new Promise((resolve) => cdpServer.listen(0, '127.0.0.1', resolve)); + fs.writeFileSync(portFile, `${cdpServer.address().port}\n/devtools/browser/mock`, 'utf8'); + + // Remote host returns valid configs that do NOT include 900K option -> verified empty rules {} + setRemoteWindowRpcInvoker(async (_ep, method) => { + if (method === 'GetUserStatus') { + return { + userStatus: { + cascadeModelConfigData: { + clientModelConfigs: [ + { + label: 'Gemini 4 Carbon (High)', + modelId: 'gemini-4-carbon-high', + modelOrAlias: { model: carbon }, + contextWindowOptions: [{ name: '256K' }], + }, + ], + }, + }, + }; + } + return { response: { models: {} } }; + }); + + const controller = createWindowBridgeController({ + handleApiRequest: async () => ({ status: 200, body: '{}' }), + readAssetFn: async () => '', + getSettingsFn: () => ({ + enableWindowOverlay: false, + windowMountMode: 'sidebar', + modelContextWindows: { 'model:gemini-4-carbon': '900K' }, + }), + getBundleVersionFn: () => 'v-iso', + env: { ANTIGRAVITY_DEVTOOLS_PORT_FILE: portFile }, + WebSocketImpl: MockWS, + }); + + try { + await controller.syncAllWindows(); + // Because remote verified its models and rejected 900K, fallbackRules is {} and no override is attached + assert.equal(sshWinObj.__AGUsageMonitorContextWindows, undefined); + } finally { + setRemoteWindowRpcInvoker(null); + await controller.stop(); + clearRemoteEndpointRegistry(); + cdpServer.close(); + fs.rmSync(tmpDir, { recursive: true, force: true }); + } +}); + +test('SSH remote endpoints isolate v1.5.2 fast paths (scope=consumption, consumption-presets cold/warm, conversation) and local Swarm manifests/transcripts', async () => { + const nowIso = new Date().toISOString(); + const sharedCid = 'eeeeeeee-1111-2222-3333-444444444444'; + const remoteCid2 = 'ffffffff-1111-2222-3333-444444444444'; + + const makeStep = (inputTokens, outputTokens) => ({ + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: nowIso, + generatorModel: 'MODEL_PLACEHOLDER_M37', + modelUsage: { + model: 'gemini-2.5-pro', + inputTokens: String(inputTokens), + outputTokens: String(outputTokens), + cacheReadTokens: '0', + }, + }, + plannerResponse: { response: 'ok' }, + }); + + const h = backendHarness({ + userStatus: { email: 'shared@example.com', name: 'Shared User' }, + summaries: { + [sharedCid]: { + summary: 'Local Session With Same ID', + stepCount: 1, + status: 'CASCADE_RUN_STATUS_IDLE', + lastModifiedTime: nowIso, + }, + }, + trajectories: { + [sharedCid]: { trajectory: { steps: [makeStep(9000, 1000)] } }, + }, + swarmMembers: { + [sharedCid]: { + title: 'Local Swarm Should Not Leak To SSH', + coordinator: { cascadeId: sharedCid, killed: false }, + members: { + w1: { cascadeId: '11111111-2222-3333-4444-555555555555', memberName: 'local-bee' }, + }, + }, + }, + transcripts: { + [sharedCid]: [ + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + content: 'local transcript should not leak', + created_at: nowIso, + }, + ], + }, + }); + + const ep = h.registerRemoteEndpoint({ + origin: 'https://127.0.0.1:64101', + baseUrl: 'https://127.0.0.1:64101', + csrfToken: '', + wsUrl: 'ws://127.0.0.1:9222/devtools/page/fast', + label: 'gpu-fast', + stableHostKey: 'gpu-fast', + }); + + let remoteRpcCount = 0; + h.setRemoteWindowRpcInvoker(async (_ep, method, body) => { + remoteRpcCount += 1; + if (method === 'GetUserStatus') { + return { userStatus: { email: 'shared@example.com', name: 'Shared User' } }; + } + if (method === 'RetrieveUserQuotaSummary') { + return { response: { groups: [] } }; + } + if (method === 'GetAllCascadeTrajectories') { + return { + trajectorySummaries: { + [sharedCid]: { + summary: 'Remote Primary Session', + stepCount: 1, + status: 'CASCADE_RUN_STATUS_IDLE', + lastModifiedTime: nowIso, + }, + [remoteCid2]: { + summary: 'Remote Secondary Session', + stepCount: 1, + status: 'CASCADE_RUN_STATUS_IDLE', + lastModifiedTime: nowIso, + }, + }, + }; + } + if (method === 'GetCascadeTrajectory') { + if (body?.cascadeId === sharedCid) { + return { trajectory: { steps: [makeStep(200, 50)] } }; + } + if (body?.cascadeId === remoteCid2) { + return { trajectory: { steps: [makeStep(500, 100)] } }; + } + } + return {}; + }); + + // 1. Populate local fast snapshot first (10,000 tokens + local swarm title) + const localFullRes = await h.executeTelemetryAction( + { conversationId: sharedCid, range: 'today' }, + { endpointId: LOCAL_ENDPOINT_ID } + ); + assert.equal(localFullRes.status, 200); + const localFull = JSON.parse(localFullRes.body); + assert.equal(localFull.consumption.account.totalTokens, 10000); + assert.equal(localFull.activeConversation.swarmTitle, 'Local Swarm Should Not Leak To SSH'); + + // 2. Cold scope=consumption-presets on remote endpoint MUST build remote snapshot (850 tokens, SSH source), NOT read local snapshot! + const remoteColdPresetsRes = await h.executeTelemetryAction( + { scope: 'consumption-presets', conversationId: sharedCid }, + { endpointId: ep.id } + ); + assert.equal(remoteColdPresetsRes.status, 200); + const remoteColdPresets = JSON.parse(remoteColdPresetsRes.body); + assert.equal(remoteColdPresets.scope, 'consumption-presets'); + assert.equal(remoteColdPresets.endpoint.id, ep.id); + assert.equal(remoteColdPresets.ranges.today.account.totalTokens, 850); + assert.equal(remoteColdPresets.ranges.today.sourcesBreakdown.length, 1); + assert.equal(remoteColdPresets.ranges.today.sourcesBreakdown[0].name, 'Antigravity SSH'); + + // 3. Warm scope=consumption on remote endpoint returns ONLY remote tokens (850), local still returns 10000 + const remoteConsRes = await h.executeTelemetryAction( + { scope: 'consumption', range: '7d' }, + { endpointId: ep.id } + ); + const remoteCons = JSON.parse(remoteConsRes.body); + assert.equal(remoteCons.scope, 'consumption'); + assert.equal(remoteCons.endpoint.id, ep.id); + assert.equal(remoteCons.consumption.account.totalTokens, 850); + assert.equal(remoteCons.consumption.sourcesBreakdown[0].name, 'Antigravity SSH'); + + const localConsRes = await h.executeTelemetryAction( + { scope: 'consumption', range: '7d' }, + { endpointId: LOCAL_ENDPOINT_ID } + ); + const localCons = JSON.parse(localConsRes.body); + assert.equal(localCons.consumption.account.totalTokens, 10000); + + // 4. Remote scope=conversation switches to remoteCid2 with ZERO remote LS RPCs and NO local swarmTitle leakage + const rpcBeforeConvSwitch = remoteRpcCount; + const remoteConvRes = await h.executeTelemetryAction( + { scope: 'conversation', conversationId: remoteCid2, range: 'today' }, + { endpointId: ep.id } + ); + assert.equal(remoteConvRes.status, 200); + const remoteConv = JSON.parse(remoteConvRes.body); + assert.equal(remoteConv.scope, 'conversation'); + assert.equal(remoteConv.endpoint.id, ep.id); + assert.equal(remoteConv.activeCascadeId, remoteCid2); + assert.equal(remoteConv.activeConversation.title, 'Remote Secondary Session'); + assert.equal(remoteConv.activeConversation.totalTokens, 600); + assert.equal(remoteConv.consumption.session.totalTokens, 600); + assert.equal(remoteRpcCount, rpcBeforeConvSwitch); + + // 5. Remote scope=conversation for sharedCid does NOT inherit local swarmTitle or local 10000 tokens + const remoteSharedConvRes = await h.executeTelemetryAction( + { scope: 'conversation', conversationId: sharedCid, range: 'today' }, + { endpointId: ep.id } + ); + const remoteSharedConv = JSON.parse(remoteSharedConvRes.body); + assert.equal(remoteSharedConv.activeConversation.title, 'Remote Primary Session'); + assert.equal(remoteSharedConv.activeConversation.swarmTitle, undefined); + assert.equal(remoteSharedConv.activeConversation.totalTokens, 250); +}); + +test('Frontend resetTelemetryForEndpointSwitch clears consumption/conversation caches and discards late in-flight fast-scope responses', async () => { + const { + telemetryStore, + resetTelemetryForEndpointSwitch, + prefetchConsumptionPresets, + selectConsumptionTimeRange, + fetchTelemetry, + } = await import('../src/store/telemetryStore.js'); + + const prevWindow = globalThis.window; + const prevFetch = globalThis.fetch; + let resolveLatePresets; + let apiCalls = 0; + + globalThis.window = { + location: { pathname: '/' }, + fetch: async (url) => { + apiCalls += 1; + const u = String(url); + if (u.includes('scope=consumption-presets')) { + return new Promise((resolve) => { + resolveLatePresets = () => + resolve({ + ok: true, + status: 200, + json: async () => ({ + scope: 'consumption-presets', + usageRevision: 9, + ranges: { + '7d': { + selectedRange: { key: '7d', label: '7天' }, + account: { totalTokens: 999999 }, + session: { totalTokens: 999999 }, + trendSeries: [], + sourcesBreakdown: [{ name: 'Stale Local' }], + modelBreakdown: [], + }, + }, + }), + }); + }); + } + if (u.includes('scope=consumption')) { + return { + ok: true, + status: 200, + json: async () => ({ + scope: 'consumption', + usageRevision: 2, + consumption: { + revision: 2, + selectedRange: { key: '7d', label: '7天' }, + account: { totalTokens: 42 }, + session: { totalTokens: 42 }, + trendSeries: [], + sourcesBreakdown: [{ name: 'Antigravity SSH' }], + }, + modelBreakdown: [], + }), + }; + } + return { + ok: true, + status: 200, + json: async () => ({ + endpoint: { id: 'remote:ssh-clean', isRemote: true, label: 'ssh-clean' }, + account: { status: 'signedIn', email: 'u@example.com' }, + settings: { weeklyLimitMode: 'official' }, + activeConversation: { cascadeId: 'c1', recentSteps: [], agents: [] }, + consumption: { + revision: 2, + selectedRange: { key: 'today', label: '今天' }, + account: { totalTokens: 42 }, + session: { totalTokens: 42 }, + trendSeries: [], + sourcesBreakdown: [{ name: 'Antigravity SSH' }], + }, + modelBreakdown: [], + }), + }; + }, + }; + globalThis.fetch = globalThis.window.fetch; + + try { + resetTelemetryForEndpointSwitch(); + const latePrefetchPromise = prefetchConsumptionPresets(); + // Switch endpoints BEFORE the previous endpoint's presets prefetch resolves + resetTelemetryForEndpointSwitch(); + resolveLatePresets?.(); + const prefetchRes = await latePrefetchPromise; + assert.equal(prefetchRes, false); + + // Load fresh remote endpoint telemetry, then switch to '7d' — MUST NOT hit stale 999999 cache! + await fetchTelemetry({ force: false }); + const callsBeforeRangeSwitch = apiCalls; + await selectConsumptionTimeRange('7d'); + assert.ok(apiCalls > callsBeforeRangeSwitch); + assert.equal(telemetryStore.getState().telemetry.consumption.account.totalTokens, 42); + } finally { + resetTelemetryForEndpointSwitch(); + globalThis.window = prevWindow; + globalThis.fetch = prevFetch; + } +}); + +test('httpClient does NOT replay rejected or timed-out CDP requests over HTTP after bridge endpoint switch', async () => { + const { callSidecarApi } = await import('../src/core/httpClient.js'); + const prevWindow = globalThis.window; + const prevFetch = globalThis.fetch; + let httpReplays = 0; + + const bridge = { + port: 49901, + token: 'tok-cdp-switch', + transportMode: 'cdp', + [WINDOW_BRIDGE_ENDPOINT_KEY]: 'remote:ssh-old', + rpcQueue: [], + rpcPending: new Map(), + }; + + globalThis.window = { + [WINDOW_BRIDGE_KEY]: bridge, + fetch: async () => { + httpReplays += 1; + return { ok: true, status: 200, json: async () => ({ ok: true }) }; + }, + }; + globalThis.fetch = globalThis.window.fetch; + + try { + // Case 1: Mutating POST with NO abortKey rejected by updateBridge switch -> must NOT replay over HTTP to new endpoint + const postPromise = callSidecarApi('/api/cache/rebuild', { + method: 'POST', + body: {}, + cdpTimeoutMs: 500, + }); + assert.equal(bridge.rpcQueue.length, 1); + bridge[WINDOW_BRIDGE_ENDPOINT_KEY] = 'remote:ssh-new'; + for (const pending of bridge.rpcPending.values()) { + const err = new Error('Bridge endpoint switched'); + err.name = 'AbortError'; + pending.reject(err); + } + bridge.rpcPending.clear(); + bridge.rpcQueue.length = 0; + await assert.rejects(() => postPromise, (err) => err?.name === 'AbortError'); + assert.equal(httpReplays, 0); + + // Case 2: Even if a CDP request times out (plain Error) after endpoint changed, fallbackViaCdpWithRecovery must NOT replay over HTTP + bridge.transportMode = 'cdp'; + bridge[WINDOW_BRIDGE_ENDPOINT_KEY] = 'remote:ssh-old-2'; + const timeoutPromise = callSidecarApi('/api/context-window', { + method: 'POST', + body: { modelId: 'm1', option: '500K' }, + cdpTimeoutMs: 30, + }); + bridge[WINDOW_BRIDGE_ENDPOINT_KEY] = LOCAL_ENDPOINT_ID; + await assert.rejects(() => timeoutPromise, (err) => err?.name === 'AbortError'); + assert.equal(httpReplays, 0); + } finally { + globalThis.window = prevWindow; + globalThis.fetch = prevFetch; + } +}); + +test('Fast snapshot invalidates when a remote endpoint is pruned and re-registered on the same baseUrl', async () => { + const nowIso = new Date().toISOString(); + const cid = 'abababab-1111-2222-3333-444444444444'; + let currentRemoteTokens = 250; + + const h = backendHarness({ + userStatus: { email: 'u@example.com' }, + }); + + const makeRemoteStep = (total) => ({ + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: nowIso, + generatorModel: 'MODEL_PLACEHOLDER_M37', + modelUsage: { + model: 'gemini-2.5-pro', + inputTokens: String(total - 50), + outputTokens: '50', + cacheReadTokens: '0', + }, + }, + plannerResponse: { response: 'ok' }, + }); + + h.setRemoteWindowRpcInvoker(async (_ep, method) => { + if (method === 'GetUserStatus') return { userStatus: { email: 'u@example.com' } }; + if (method === 'RetrieveUserQuotaSummary') return { response: { groups: [] } }; + if (method === 'GetAllCascadeTrajectories') { + return { + trajectorySummaries: { + [cid]: { + summary: 'Static Forward SSH', + stepCount: 1, + status: 'CASCADE_RUN_STATUS_IDLE', + lastModifiedTime: nowIso, + }, + }, + }; + } + if (method === 'GetCascadeTrajectory') { + return { trajectory: { steps: [makeRemoteStep(currentRemoteTokens)] } }; + } + return {}; + }); + + const ep1 = h.registerRemoteEndpoint({ + origin: 'https://127.0.0.1:64201', + baseUrl: 'https://127.0.0.1:64201', + csrfToken: '', + wsUrl: 'ws://127.0.0.1:9222/devtools/page/static1', + label: 'static-ssh', + stableHostKey: 'static-ssh', + }); + + const firstRes = await h.executeTelemetryAction( + { conversationId: cid, range: 'today' }, + { endpointId: ep1.id } + ); + assert.equal(JSON.parse(firstRes.body).consumption.account.totalTokens, 250); + + // Prune endpoint, change remote data, and re-register on the exact same baseUrl + ep1.lastSeenMs = Date.now() - 120_000; + h.pruneStaleRemoteEndpoints(new Set(), 1000); + assert.equal(h.getRegisteredRemoteEndpoint(ep1.id), null); + + currentRemoteTokens = 900; + const ep2 = h.registerRemoteEndpoint({ + origin: 'https://127.0.0.1:64201', + baseUrl: 'https://127.0.0.1:64201', + csrfToken: '', + wsUrl: 'ws://127.0.0.1:9222/devtools/page/static2', + label: 'static-ssh', + stableHostKey: 'static-ssh', + }); + assert.equal(ep2.id, ep1.id); + assert.notEqual(ep2.instanceId, ep1.instanceId); + + // Fast-path scope=consumption MUST NOT serve stale 250-token snapshot from ep1! + const afterReRegRes = await h.executeTelemetryAction( + { scope: 'consumption', range: 'today' }, + { endpointId: ep2.id } + ); + const afterReReg = JSON.parse(afterReRegRes.body); + assert.equal(afterReReg.consumption.account.totalTokens, 900); +}); + + From a12de91bb102184255c35563ee02e60986525a13 Mon Sep 17 00:00:00 2001 From: hejun01 Date: Fri, 20 Nov 2026 11:58:39 +0800 Subject: [PATCH 2/8] feat(panel): extract Swarm title, kill state, and parked status via pure RPC for SSH windows --- sidecars/panel/backend/local-scanner.mjs | 82 ++- .../panel/test/ssh-remote-endpoints.test.mjs | 631 ++++++++++++++++++ sidecars/panel/trajectory-metrics.mjs | 196 ++++++ 3 files changed, 900 insertions(+), 9 deletions(-) diff --git a/sidecars/panel/backend/local-scanner.mjs b/sidecars/panel/backend/local-scanner.mjs index e15aa67..45bf769 100644 --- a/sidecars/panel/backend/local-scanner.mjs +++ b/sidecars/panel/backend/local-scanner.mjs @@ -14,6 +14,7 @@ import { isDeepStrictEqual } from 'node:util'; import { extractLiveActivity, extractModelSteps, + extractSwarmMetaFromSteps, getMaxMeaningfulStepIndex, isParkedOnSwarmWait, parseIsoMs, @@ -1928,6 +1929,7 @@ export async function enumerateAndSyncConversations({ } const subagentRefs = extractSubagentRefsFromSteps(rawSteps); + const rpcSwarmMeta = extractSwarmMetaFromSteps(rawSteps); const ownSwarmManifest = !isRemote && !conv.isSubagent ? readSwarmManifestForCascade(cidLower) : null; if (ownSwarmManifest?.workerRefs?.length) { @@ -1938,9 +1940,12 @@ export async function enumerateAndSyncConversations({ subagentRefs.push(wRef); } } - if (!nonShortTitle(conv.title) && ownSwarmManifest.title) { - conv.title = ownSwarmManifest.title; - } + } + const resolvedSwarmTitle = !conv.isSubagent + ? String(ownSwarmManifest?.title || rpcSwarmMeta?.title || '').trim() + : ''; + if (!nonShortTitle(conv.title) && resolvedSwarmTitle) { + conv.title = resolvedSwarmTitle; } conv.subagentRefs = subagentRefs; @@ -1950,7 +1955,8 @@ export async function enumerateAndSyncConversations({ conv.stepCount = steps.length; const finalSig = buildConvSig(conv); - const effectiveIsRunning = isRunning && !isParkedOnSwarmWait(rawSteps); + const isParkedSwarm = isParkedOnSwarmWait(rawSteps); + const effectiveIsRunning = isRunning && !isParkedSwarm; if (!effectiveIsRunning && conv.status === 'CASCADE_RUN_STATUS_RUNNING') { conv.status = 'IDLE'; } @@ -1998,6 +2004,8 @@ export async function enumerateAndSyncConversations({ steps: stepsWithOwners, subagentRefs, }; + if (rpcSwarmMeta) cacheEntry.swarmMeta = rpcSwarmMeta; + if (isParkedSwarm) cacheEntry.parkedOnSwarmWait = true; if (conv.diskFileSig) cacheEntry.diskFileSig = conv.diskFileSig; if (conv.appSource && conv.appSource !== 'standalone') { cacheEntry.appSource = conv.appSource; @@ -2017,13 +2025,15 @@ export async function enumerateAndSyncConversations({ const metaChanged = !Array.isArray(prev?.subagentRefs) || JSON.stringify(prev?.subagentRefs) !== JSON.stringify(subagentRefs) || + !isDeepStrictEqual(prev?.swarmMeta || null, cacheEntry.swarmMeta || null) || + Boolean(prev?.parkedOnSwarmWait) !== Boolean(cacheEntry.parkedOnSwarmWait) || (prev?.rootConversationId || '') !== (cacheEntry.rootConversationId || '') || Boolean(prev?.isSideQuestion) !== Boolean(cacheEntry.isSideQuestion); const stepsChanged = !prev || Boolean(prev.offlineTranscriptFallback) || prev.signature !== finalSig || - Boolean(prev.wasRunning) !== isRunning || + Boolean(prev.wasRunning) !== Boolean(cacheEntry.wasRunning) || !prev.contextLimitTelemetry || !prev.speedClearedTelemetry || !prev.turnRailTelemetry || @@ -2140,7 +2150,21 @@ export async function enumerateAndSyncConversations({ isRunning || isReq ? ACTIVE_FAILED_RPC_COOLDOWN_MS : FAILED_RPC_COOLDOWN_MS; activeCooldownMap.set(cooldownKey, { failedAt: nowPollMs, cooldownMs }); } - if (!isRunning) { + const tailStepsOnErr = + partialTailSteps.length > 0 + ? partialTailSteps + : isRemote + ? [] + : readTranscriptTailSteps(conv.cascadeId); + const parkedOnErr = + tailStepsOnErr.length > 0 + ? isParkedOnSwarmWait(tailStepsOnErr) + : Boolean(prev?.parkedOnSwarmWait) && prev.signature === sig; + if (!isRunning || (!offlineRecovered && parkedOnErr)) { + if (isRunning) { + conv.status = 'IDLE'; + conv.liveActivity = null; + } activeLiveActivityMemo.delete(conv.cascadeId.toLowerCase()); } else { const fallbackLive = resolveBestLiveActivity( @@ -2531,8 +2555,13 @@ export async function enumerateAndSyncConversations({ for (const conv of rawConversations) { if (conv.status === 'CASCADE_RUN_STATUS_RUNNING') { if (!conv.liveActivity) { + const cachedConv = getEntry(conv.cascadeId); + const parkedByCache = + Boolean(cachedConv?.parkedOnSwarmWait) && + cachedConv.signature === buildConvSig(conv); const tailSteps = isRemote ? [] : readTranscriptTailSteps(conv.cascadeId); - if (isParkedOnSwarmWait(tailSteps)) { + const isParked = tailSteps.length > 0 ? isParkedOnSwarmWait(tailSteps) : parkedByCache; + if (isParked) { conv.status = 'IDLE'; conv.liveActivity = null; activeLiveActivityMemo.delete(conv.cascadeId.toLowerCase()); @@ -2602,8 +2631,9 @@ export async function enumerateAndSyncConversations({ for (const rootConv of conversations) { const cid = rootConv.cascadeId.toLowerCase(); + const rootCached = getEntry(rootConv.cascadeId); const swarmManifest = isRemote ? null : readSwarmManifestForCascade(cid); - const swarmTitle = String(swarmManifest?.title || '').trim(); + const swarmTitle = String(swarmManifest?.title || rootCached?.swarmMeta?.title || '').trim(); if (swarmTitle) { rootConv.swarmTitle = swarmTitle; const curTitle = String(rootConv.title || '').trim(); @@ -2617,6 +2647,24 @@ export async function enumerateAndSyncConversations({ } const subs = subagentsByRoot.get(cid) || []; + const rpcKilledByMember = new Map(); + const mergeRpcKilled = (killedMap) => { + if (!killedMap || typeof killedMap !== 'object') return; + for (const [memberKey, killMs] of Object.entries(killedMap)) { + const normMember = String(memberKey || '').trim().toLowerCase(); + if (!normMember) continue; + const numMs = Number(killMs || 0); + const prevMs = rpcKilledByMember.get(normMember); + if (prevMs === undefined || numMs > prevMs) { + rpcKilledByMember.set(normMember, numMs); + } + } + }; + mergeRpcKilled(rootCached?.swarmMeta?.killedMembers); + for (const s of subs) { + mergeRpcKilled(getEntry(s.cascadeId)?.swarmMeta?.killedMembers); + } + let swarmCount = 0; for (const s of subs) { const subLower = s.cascadeId.toLowerCase(); @@ -2635,7 +2683,23 @@ export async function enumerateAndSyncConversations({ s.isSwarmWorker = true; s.swarmMemberName = parsedSwarm.memberName; s.isSwarmAuxiliary = Boolean(parsedSwarm.isAuxiliary); - s.killed = Boolean(s.killed || mEntry?.killed); + const memberKey = String(parsedSwarm.memberName || '').trim().toLowerCase(); + const rpcKilledAtMs = + memberKey && rpcKilledByMember.has(memberKey) + ? rpcKilledByMember.get(memberKey) + : undefined; + const subCreatedMs = + s.createdTimeMs || subCached?.createdTimeMs || subCached?.steps?.[0]?.createdAtMs || 0; + const subLastStepMs = + subCached?.steps?.[subCached.steps.length - 1]?.createdAtMs || 0; + const killedByRpc = + rpcKilledAtMs !== undefined && + !( + rpcKilledAtMs > 0 && + ((subCreatedMs > 0 && subCreatedMs > rpcKilledAtMs) || + subLastStepMs > rpcKilledAtMs) + ); + s.killed = Boolean(s.killed || (mEntry ? mEntry.killed : killedByRpc)); if (s.killed) { s.status = 'IDLE'; s.liveActivity = null; diff --git a/sidecars/panel/test/ssh-remote-endpoints.test.mjs b/sidecars/panel/test/ssh-remote-endpoints.test.mjs index 1c566a8..eb15561 100644 --- a/sidecars/panel/test/ssh-remote-endpoints.test.mjs +++ b/sidecars/panel/test/ssh-remote-endpoints.test.mjs @@ -1634,4 +1634,635 @@ test('Fast snapshot invalidates when a remote endpoint is pruned and re-register assert.equal(afterReReg.consumption.account.totalTokens, 900); }); +test('extractSwarmMetaFromSteps parses pure-RPC swarm title & kill calls and ignores failed/canceled calls', async () => { + const { extractSwarmMetaFromSteps } = await import('../trajectory-metrics.mjs'); + + assert.equal(extractSwarmMetaFromSteps([]), null); + assert.equal( + extractSwarmMetaFromSteps([ + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + plannerResponse: { toolCalls: [{ id: 't0', name: 'read_file', argumentsJson: '{}' }] }, + }, + ]), + null + ); + + const t1 = '2026-11-20T10:00:00Z'; + const t2 = '2026-11-20T10:01:00Z'; + const t3 = '2026-11-20T10:02:00Z'; + const t4 = '2026-11-20T10:03:00Z'; + const meta = extractSwarmMetaFromSteps([ + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { createdAt: t1 }, + plannerResponse: { + toolCalls: [ + { + id: 'call-title-1', + name: 'default_api:swarm', + argumentsJson: JSON.stringify({ action: 'title', title: 'Initial Swarm' }), + }, + { + id: 'call-kill-fail', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: '@survivor' }), + }, + ], + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_ERROR', + metadata: { + createdAt: t2, + toolCall: { + id: 'call-kill-fail', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: '@survivor' }), + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: t3, + toolCall: { + id: 'call-title-2', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'title', title: 'Final GPU Swarm' }), + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: t4, + toolCall: { + id: 'call-kill-ok', + name: 'default_api:swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: '@Verifier-FE' }), + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_CANCELED', + metadata: { + completedAt: t4, + toolCall: { + id: 'call-title-canceled', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'title', title: 'Canceled Title' }), + }, + }, + }, + ]); + + assert.deepEqual(meta, { + title: 'Final GPU Swarm', + killedMembers: { + 'verifier-fe': Date.parse(t4), + }, + }); +}); + +test('SSH remote Swarm recovers swarmTitle, worker killed state (including helper kills & re-added names), and parked swarm_wait across transient RPC errors without remote disk access', async () => { + const baseMs = Date.parse('2026-11-20T10:00:00Z'); + const isoAt = (sec) => new Date(baseMs + sec * 1000).toISOString(); + + const rootCid = 'aaaa1111-1111-4111-8111-111111111111'; + const deadOldCid = 'bbbb2222-2222-4222-8222-222222222222'; + const respawnedCid = 'cccc3333-3333-4333-8333-333333333333'; + const parkedCid = 'dddd4444-4444-4444-8444-444444444444'; + const parentWorkerCid = 'eeee5555-5555-4555-8555-555555555555'; + const killedHelperCid = 'ffff6666-6666-4666-8666-666666666666'; + + const makeModelStep = (idx, sec, inTok, outTok) => ({ + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: isoAt(sec), + completedAt: isoAt(sec + 1), + sourceTrajectoryStepInfo: { stepIndex: idx }, + modelUsage: { + model: 'MODEL_PLACEHOLDER_M37', + inputTokens: String(inTok), + cacheReadTokens: '0', + outputTokens: String(outTok), + }, + }, + }); + + let failParkedFetch = false; + const h = backendHarness({ + clock: () => baseMs + 120_000, + userStatus: { email: 'ssh-swarm@example.com' }, + // Intentionally put conflicting local swarmMembers for the same rootCid to ensure SSH ignores local disk + swarmMembers: { + [rootCid]: { + title: 'LOCAL DISK SWARM MUST NOT BE READ', + members: {}, + }, + }, + }); + + const ep = h.registerRemoteEndpoint({ + origin: 'https://127.0.0.1:64301', + baseUrl: 'https://127.0.0.1:64301', + csrfToken: '', + wsUrl: 'ws://127.0.0.1:9222/devtools/page/ssh-swarm', + label: 'gpu-swarm', + stableHostKey: 'gpu-swarm', + }); + + const remoteTrajectories = { + [rootCid]: { + trajectory: { + steps: [ + makeModelStep(0, 1, 500, 100), + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: isoAt(5), + toolCall: { + id: 'sw-title', + name: 'swarm', + argumentsJson: JSON.stringify({ + action: 'title', + title: 'Remote GPU Swarm Audit', + }), + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: isoAt(30), + toolCall: { + id: 'sw-kill-dead', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: 'dead-bee' }), + }, + }, + }, + ], + }, + }, + [deadOldCid]: { + trajectory: { steps: [makeModelStep(0, 10, 300, 50)] }, + }, + [respawnedCid]: { + trajectory: { steps: [makeModelStep(0, 45, 400, 80)] }, + }, + [parkedCid]: { + trajectory: { + steps: [ + makeModelStep(0, 15, 250, 40), + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: isoAt(18), + toolCall: { name: 'swarm_wait', argumentsJson: '{"since":5}' }, + }, + }, + ], + }, + }, + [parentWorkerCid]: { + trajectory: { + steps: [ + makeModelStep(0, 12, 200, 30), + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: isoAt(35), + toolCall: { + id: 'sw-kill-helper', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: 'helper-bee' }), + }, + }, + }, + ], + }, + }, + [killedHelperCid]: { + trajectory: { steps: [makeModelStep(0, 20, 150, 20)] }, + }, + }; + + h.setRemoteWindowRpcInvoker(async (_ep, method, body) => { + if (method === 'GetUserStatus') return { userStatus: { email: 'ssh-swarm@example.com' } }; + if (method === 'RetrieveUserQuotaSummary') return { response: { groups: [] } }; + if (method === 'GetAllCascadeTrajectories') { + return { + trajectorySummaries: { + [rootCid]: { + annotations: { title: '' }, + stepCount: 3, + createdTime: isoAt(0), + lastModifiedTime: isoAt(30), + status: 'CASCADE_RUN_STATUS_IDLE', + }, + [deadOldCid]: { + stepCount: 1, + createdTime: isoAt(10), + lastModifiedTime: isoAt(12), + status: 'CASCADE_RUN_STATUS_IDLE', + trajectoryMetadata: { + parentConversationId: rootCid, + subagentSpec: { typeName: 'worker', role: 'Swarm Worker (dead-bee)' }, + }, + }, + [respawnedCid]: { + stepCount: 1, + createdTime: isoAt(40), // Created AFTER kill at t=30 -> must stay alive + lastModifiedTime: isoAt(46), + status: 'CASCADE_RUN_STATUS_IDLE', + trajectoryMetadata: { + parentConversationId: rootCid, + subagentSpec: { typeName: 'worker', role: 'Swarm Worker (dead-bee)' }, + }, + }, + [parkedCid]: { + stepCount: 2, + createdTime: isoAt(14), + lastModifiedTime: isoAt(18), + status: 'CASCADE_RUN_STATUS_RUNNING', // Parked on swarm_wait -> must downgrade! + trajectoryMetadata: { + parentConversationId: rootCid, + subagentSpec: { typeName: 'worker', role: 'Swarm Worker (parked-bee)' }, + }, + }, + [parentWorkerCid]: { + stepCount: 2, + createdTime: isoAt(11), + lastModifiedTime: isoAt(35), + status: 'CASCADE_RUN_STATUS_IDLE', + trajectoryMetadata: { + parentConversationId: rootCid, + subagentSpec: { typeName: 'worker', role: 'Swarm Worker (lead-bee)' }, + }, + }, + [killedHelperCid]: { + stepCount: 1, + createdTime: isoAt(19), + lastModifiedTime: isoAt(21), + status: 'CASCADE_RUN_STATUS_IDLE', + trajectoryMetadata: { + parentConversationId: parentWorkerCid, + subagentSpec: { typeName: 'worker', role: 'Swarm Worker (helper-bee)' }, + }, + }, + }, + }; + } + if (method === 'GetCascadeTrajectory') { + if (failParkedFetch && body?.cascadeId === parkedCid) { + throw new Error('transient SSH RPC timeout'); + } + return remoteTrajectories[body?.cascadeId] || {}; + } + return {}; + }); + + // Poll 1: Full RPC fetch recovers swarmTitle, killed states, and downgrades parked-bee + const res1 = await h.executeTelemetryAction( + { conversationId: rootCid, range: 'today' }, + { endpointId: ep.id } + ); + assert.equal(res1.status, 200); + const p1 = JSON.parse(res1.body); + assert.equal(p1.activeConversation.swarmTitle, 'Remote GPU Swarm Audit'); + assert.equal(p1.activeConversation.title, 'Remote GPU Swarm Audit'); + assert.equal(p1.runningConversations.length, 0); + + const byCid = new Map(p1.activeConversation.agents.map((a) => [a.cascadeId, a])); + assert.equal(byCid.get(deadOldCid)?.swarmState, 'killed'); + assert.equal(byCid.get(respawnedCid)?.swarmState, 'waiting'); + assert.equal(byCid.get(parkedCid)?.swarmState, 'waiting'); + assert.equal(byCid.get(parkedCid)?.isRunning, false); + assert.equal(byCid.get(killedHelperCid)?.swarmState, 'killed'); + + // Poll 2: Transient RPC failure on parked-bee with unchanged signature MUST NOT flicker it back to RUNNING + failParkedFetch = true; + const res2 = await h.executeTelemetryAction( + { conversationId: rootCid, range: 'today' }, + { endpointId: ep.id } + ); + assert.equal(res2.status, 200); + const p2 = JSON.parse(res2.body); + assert.equal(p2.runningConversations.length, 0); + const byCid2 = new Map(p2.activeConversation.agents.map((a) => [a.cascadeId, a])); + assert.equal(byCid2.get(parkedCid)?.swarmState, 'waiting'); + assert.equal(byCid2.get(parkedCid)?.isRunning, false); + assert.equal(byCid2.get(deadOldCid)?.swarmState, 'killed'); + + // Poll 3: Fast scope=conversation preserves RPC-derived swarmTitle & killed states + const convRes = await h.executeTelemetryAction( + { scope: 'conversation', conversationId: rootCid, range: 'today' }, + { endpointId: ep.id } + ); + const convPayload = JSON.parse(convRes.body); + assert.equal(convPayload.scope, 'conversation'); + assert.equal(convPayload.activeConversation.swarmTitle, 'Remote GPU Swarm Audit'); + const byCid3 = new Map(convPayload.activeConversation.agents.map((a) => [a.cascadeId, a])); + assert.equal(byCid3.get(deadOldCid)?.swarmState, 'killed'); + assert.equal(byCid3.get(killedHelperCid)?.swarmState, 'killed'); +}); + +test('extractSwarmMetaFromSteps guards prototype keys, non-string args, pending/waiting calls, and ID-less failed calls', async () => { + const { isDeepStrictEqual } = await import('node:util'); + const { extractSwarmMetaFromSteps } = await import('../trajectory-metrics.mjs'); + + const t1 = '2026-11-20T11:00:00Z'; + const t2 = '2026-11-20T11:01:00Z'; + const t3 = '2026-11-20T11:02:00Z'; + const meta = extractSwarmMetaFromSteps([ + // Non-string malformed fields must be ignored (never coerced to '[object Object]') + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: t1, + toolCall: { + id: 'bad-args-1', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'title', title: { bad: 1 } }), + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: t1, + toolCall: { + id: 'bad-args-2', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: ['not-a-string'] }), + }, + }, + }, + // Pending / waiting execution steps (both with ID and without ID) must NOT be applied + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { createdAt: t1 }, + plannerResponse: { + toolCalls: [ + { + id: 'pending-id', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: 'still-running' }), + }, + { + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: 'idless-failed' }), + }, + { + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'title', title: 'Pending Title' }), + }, + ], + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_WAITING', + metadata: { + createdAt: t2, + toolCall: { + id: 'pending-id', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: 'still-running' }), + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_ERROR', + metadata: { + createdAt: t2, + toolCall: { + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: 'idless-failed' }), + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_RUNNING', + metadata: { + createdAt: t2, + toolCall: { + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'title', title: 'Pending Title' }), + }, + }, + }, + // Prototype-colliding member names ('constructor', 'toString', '__proto__') must work safely + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: t3, + toolCall: { + id: 'proto-1', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: 'constructor' }), + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: t3, + toolCall: { + id: 'proto-2', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: 'toString' }), + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: t3, + toolCall: { + id: 'proto-3', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: '__proto__' }), + }, + }, + }, + ]); + + assert.ok(meta); + assert.equal(meta.title, undefined); + assert.equal(Object.getPrototypeOf(meta.killedMembers), Object.prototype); + assert.equal(meta.killedMembers.constructor, Date.parse(t3)); + assert.equal(meta.killedMembers.tostring, Date.parse(t3)); + assert.equal(Object.getOwnPropertyDescriptor(meta.killedMembers, '__proto__')?.value, Date.parse(t3)); + assert.equal(meta.killedMembers['still-running'], undefined); + assert.equal(meta.killedMembers['idless-failed'], undefined); + // JSON round-trip preserves exact structural equality (no NaN -> null corruption) + const roundTripped = JSON.parse(JSON.stringify(meta)); + assert.equal(isDeepStrictEqual(meta, roundTripped), true); +}); + +test('Local Swarm ground truth (members.json killed=false & live transcript.jsonl wakeup) takes precedence over RPC/cache fallbacks', async () => { + const baseMs = Date.parse('2026-11-20T12:00:00Z'); + const isoAt = (sec) => new Date(baseMs + sec * 1000).toISOString(); + + const rootCid = '10101010-1111-4111-8111-111111111111'; + const aliveCid = '20202020-2222-4222-8222-222222222222'; + const wakingCid = '30303030-3333-4333-8333-333333333333'; + + const makeModelStep = (idx, sec) => ({ + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: isoAt(sec), + completedAt: isoAt(sec + 1), + sourceTrajectoryStepInfo: { stepIndex: idx }, + modelUsage: { + model: 'MODEL_PLACEHOLDER_M37', + inputTokens: '200', + cacheReadTokens: '0', + outputTokens: '50', + }, + }, + }); + + const h = backendHarness({ + clock: () => baseMs + 120_000, + userStatus: { email: 'local-swarm@example.com' }, + swarmMembers: { + [rootCid]: { + title: 'Local Manifest Title', + members: { + 'reused-bee': { + conversation_id: aliveCid, + role: 'Swarm Worker (reused-bee)', + killed: false, + }, + 'waking-bee': { + conversation_id: wakingCid, + role: 'Swarm Worker (waking-bee)', + killed: false, + }, + }, + }, + }, + summaries: { + [rootCid]: { + stepCount: 2, + createdTime: isoAt(0), + lastModifiedTime: isoAt(30), + status: 'CASCADE_RUN_STATUS_IDLE', + }, + [aliveCid]: { + stepCount: 1, + // Intentionally omit createdTime & use earlier step time to test mEntry.killed=false precedence + lastModifiedTime: isoAt(10), + status: 'CASCADE_RUN_STATUS_IDLE', + trajectoryMetadata: { + parentConversationId: rootCid, + subagentSpec: { typeName: 'worker', role: 'Swarm Worker (reused-bee)' }, + }, + }, + [wakingCid]: { + stepCount: 2, + createdTime: isoAt(12), + lastModifiedTime: isoAt(18), + status: 'CASCADE_RUN_STATUS_RUNNING', + trajectoryMetadata: { + parentConversationId: rootCid, + subagentSpec: { typeName: 'worker', role: 'Swarm Worker (waking-bee)' }, + }, + }, + }, + trajectories: { + [rootCid]: { + trajectory: { + steps: [ + makeModelStep(0, 1), + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: isoAt(30), + toolCall: { + id: 'kill-reused', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: 'reused-bee' }), + }, + }, + }, + ], + }, + }, + [aliveCid]: { trajectory: { steps: [makeModelStep(0, 5)] } }, + [wakingCid]: { + trajectory: { + steps: [ + makeModelStep(0, 15), + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: isoAt(18), + toolCall: { name: 'swarm_wait', argumentsJson: '{"since":1}' }, + }, + }, + ], + }, + }, + }, + transcripts: {}, + }); + + // Poll 1: wakingCid is parked on swarm_wait; aliveCid has mEntry.killed=false despite RPC kill + const p1 = await h.buildTelemetryPayloadInternal(rootCid, false, { range: 'today' }); + const byCid1 = new Map(p1.activeConversation.agents.map((a) => [a.cascadeId, a])); + assert.equal(p1.activeConversation.swarmTitle, 'Local Manifest Title'); + assert.equal(byCid1.get(aliveCid)?.swarmState, 'waiting'); + assert.equal(byCid1.get(wakingCid)?.swarmState, 'waiting'); + assert.equal(byCid1.get(wakingCid)?.isRunning, false); + + // Poll 2: Simulate wakingCid RPC failing (enters cooldown / skips fetch) WHILE local transcript.jsonl records a wakeup! + h.state.trajectories[wakingCid] = new Error('transient local RPC stall'); + h.state.transcripts[wakingCid] = [ + { + type: 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE', + content: '[swarm] new board message #9', + created_at: isoAt(60), + }, + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_RUNNING', + tool_calls: [{ name: 'read_file', argumentsJson: '{"Path":"main.mjs"}' }], + created_at: isoAt(61), + }, + ]; + h.state.transcriptMtimeMs = 2; + + const p2 = await h.buildTelemetryPayloadInternal(rootCid, false, { range: 'today' }); + const byCid2 = new Map(p2.activeConversation.agents.map((a) => [a.cascadeId, a])); + assert.equal(byCid2.get(wakingCid)?.isRunning, true); + assert.equal(byCid2.get(wakingCid)?.swarmState, 'working'); +}); + diff --git a/sidecars/panel/trajectory-metrics.mjs b/sidecars/panel/trajectory-metrics.mjs index 0f80bb5..9330883 100644 --- a/sidecars/panel/trajectory-metrics.mjs +++ b/sidecars/panel/trajectory-metrics.mjs @@ -3042,4 +3042,200 @@ export function isParkedOnSwarmWait(rawSteps = []) { return false; } +function parseSwarmToolArgs(rawToolCall) { + if (!rawToolCall || typeof rawToolCall !== 'object') return null; + const direct = rawToolCall.args || rawToolCall.arguments; + if (direct && typeof direct === 'object' && !Array.isArray(direct)) { + return direct; + } + const rawJson = + typeof rawToolCall.argumentsJson === 'string' + ? rawToolCall.argumentsJson + : typeof direct === 'string' + ? direct + : typeof rawToolCall.function?.arguments === 'string' + ? rawToolCall.function.arguments + : ''; + if (!rawJson.trim()) return null; + try { + const parsed = JSON.parse(rawJson); + return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null; + } catch { + return null; + } +} + +function normalizeSwarmToolName(rawToolCall) { + return String( + rawToolCall?.name || rawToolCall?.toolName || rawToolCall?.function?.name || '' + ) + .trim() + .toLowerCase() + .replace(/^default_api:/, ''); +} + +function isSwarmStepCompletedSuccess(step) { + const st = typeof step?.status === 'string' ? step.status.trim().toUpperCase() : ''; + if (st) { + if (!LIVE_TERMINAL_STATUSES.has(st)) { + return false; + } + if (st.includes('ERROR') || st.includes('CANCEL') || st.includes('FAIL')) { + return false; + } + } + const tcSt = + typeof step?.metadata?.toolCall?.status === 'string' + ? step.metadata.toolCall.status.trim().toUpperCase() + : ''; + if (tcSt) { + if ( + tcSt.includes('ERROR') || + tcSt.includes('CANCEL') || + tcSt.includes('FAIL') || + /(?:WAIT|PEND|RUN|GENERAT|IN_PROGRESS|STREAM)/i.test(tcSt) + ) { + return false; + } + } + return true; +} + +function extractSwarmCallIntent(rawToolCall) { + const args = parseSwarmToolArgs(rawToolCall); + if (!args || typeof args.action !== 'string') return null; + const action = args.action.trim().toLowerCase(); + if (action === 'title') { + if (typeof args.title !== 'string') return null; + const nextTitle = args.title.trim(); + if (!nextTitle) return null; + return { action: 'title', value: nextTitle, sig: `title:${nextTitle}` }; + } + if (action === 'kill') { + if (typeof args.name !== 'string') return null; + const member = args.name.trim().replace(/^@+/, '').toLowerCase(); + if (!member) return null; + return { action: 'kill', value: member, sig: `kill:${member}` }; + } + return null; +} + +/** + * 从原始轨迹 RPC 步骤中提取 Native Swarm 元数据(纯 RPC 解析,无需读取远端磁盘 `members.json`): + * - `title`:最后一次成功调用 `swarm(action: "title")` 设置的蜂群标题; + * - `killedMembers`:被 `swarm(action: "kill")` 终止的工蜂成员名(小写去 `@`)及其终止时间戳映射。 + * + * @param {Array} [rawSteps=[]] + * @returns {{ title?: string, killedMembers?: Record } | null} + */ +export function extractSwarmMetaFromSteps(rawSteps = []) { + if (!Array.isArray(rawSteps) || rawSteps.length === 0) return null; + + const executedToolCallIds = new Set(); + for (const st of rawSteps) { + const tc = st?.metadata?.toolCall; + if (!tc || normalizeSwarmToolName(tc) !== 'swarm') continue; + const tcId = String(tc.id || tc.toolCallId || '').trim(); + if (tcId) { + executedToolCallIds.add(tcId); + } + } + + let title = ''; + const killedMap = new Map(); + + const applyIntent = (intent, stepMs) => { + if (!intent) return; + if (intent.action === 'title') { + title = intent.value; + } else if (intent.action === 'kill') { + const prevMs = killedMap.get(intent.value); + killedMap.set(intent.value, prevMs === undefined ? stepMs : Math.max(prevMs, stepMs)); + } + }; + + for (let i = 0; i < rawSteps.length; i++) { + const st = rawSteps[i]; + if (!st || typeof st !== 'object') continue; + const stepMs = + parseIsoMs(st?.metadata?.completedAt || st?.metadata?.createdAt || st?.created_at) || 0; + + const execTc = st?.metadata?.toolCall; + if (execTc && normalizeSwarmToolName(execTc) === 'swarm') { + if (isSwarmStepCompletedSuccess(st)) { + applyIntent(extractSwarmCallIntent(execTc), stepMs); + } + continue; + } + + if (!isSwarmStepCompletedSuccess(st)) continue; + const plannerCalls = getStepPlannerToolCalls(st); + if (plannerCalls.length === 0) continue; + + // 收集同一轮次内无 toolCall.id 的执行步骤签名,防止失败或进行中的无 ID 执行步骤回落误触发 planner 提案 + let turnIdlessExecCounts = null; + for (const tc of plannerCalls) { + if (normalizeSwarmToolName(tc) !== 'swarm') continue; + const tcId = String(tc?.id || tc?.toolCallId || '').trim(); + if (tcId && executedToolCallIds.has(tcId)) { + continue; + } + const intent = extractSwarmCallIntent(tc); + if (!intent) continue; + if (!tcId) { + if (!turnIdlessExecCounts) { + turnIdlessExecCounts = new Map(); + for (let j = i + 1; j < rawSteps.length; j++) { + const nextSt = rawSteps[j]; + if (!nextSt || typeof nextSt !== 'object') continue; + const nt = String(nextSt.type || '').trim().toUpperCase(); + if ( + isPlannerStep(nextSt) || + nt.includes('USER_INPUT') || + nt.includes('SYSTEM_MESSAGE') || + isCheckpointStep(nextSt) + ) { + break; + } + const nextExecTc = nextSt?.metadata?.toolCall; + if (!nextExecTc || normalizeSwarmToolName(nextExecTc) !== 'swarm') continue; + const nextExecId = String(nextExecTc.id || nextExecTc.toolCallId || '').trim(); + if (nextExecId) continue; + const nextIntent = extractSwarmCallIntent(nextExecTc); + if (!nextIntent) continue; + turnIdlessExecCounts.set( + nextIntent.sig, + (turnIdlessExecCounts.get(nextIntent.sig) || 0) + 1 + ); + } + } + const matchedCount = turnIdlessExecCounts.get(intent.sig) || 0; + if (matchedCount > 0) { + turnIdlessExecCounts.set(intent.sig, matchedCount - 1); + continue; + } + } + applyIntent(intent, stepMs); + } + } + + if (!title && killedMap.size === 0) return null; + let killedMembers = null; + if (killedMap.size > 0) { + killedMembers = {}; + for (const [member, killMs] of killedMap.entries()) { + Object.defineProperty(killedMembers, member, { + value: killMs, + enumerable: true, + writable: true, + configurable: true, + }); + } + } + return { + ...(title ? { title } : {}), + ...(killedMembers ? { killedMembers } : {}), + }; +} + From f1222be4b3ac1e2a91a5dfaacae656efdd8bbd22 Mon Sep 17 00:00:00 2001 From: juju812 Date: Fri, 20 Nov 2026 15:25:02 +0800 Subject: [PATCH 3/8] fix(panel): include ancestor processes in macOS relaunch pgrep/pkill On macOS, BSD pgrep and pkill exclude ancestor processes by default unless -a is passed. Because the detached relaunch shell is spawned from the sidecar under Antigravity, pgrep -x and pkill -x silently missed the running host process, causing open -a --args --remote-debugging-port=0 to fire before the old instance exited (or while it was still running). Use pgrep -ax and pkill -{TERM,KILL} -ax, and add a brief 0.4s pause after process exit so LaunchServices finishes deregistering before relaunch. --- sidecars/panel/backend/desktop-launcher-config.mjs | 7 ++++--- sidecars/panel/test/window-bridge.test.mjs | 6 +++--- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/sidecars/panel/backend/desktop-launcher-config.mjs b/sidecars/panel/backend/desktop-launcher-config.mjs index 8ad0004..5c39af5 100644 --- a/sidecars/panel/backend/desktop-launcher-config.mjs +++ b/sidecars/panel/backend/desktop-launcher-config.mjs @@ -2005,10 +2005,11 @@ export async function triggerDesktopHostRelaunch({ bundleDerivedName || (hostInfo.kind === 'ide' ? 'Antigravity IDE' : 'Antigravity'); const shScript = [ 'sleep 0.45', - 'if osascript -e \'on run argv\' -e \'tell application (item 1 of argv) to quit\' -e \'end run\' -- "$AGY_APP_NAME" >/dev/null 2>&1; then i=0; while [ $i -lt 25 ] && pgrep -x "$AGY_APP_NAME" >/dev/null 2>&1; do sleep 0.2; i=$((i+1)); done; fi', - 'if pgrep -x "$AGY_APP_NAME" >/dev/null 2>&1; then pkill -TERM -x "$AGY_APP_NAME" >/dev/null 2>&1 || killall -TERM "$AGY_APP_NAME" >/dev/null 2>&1 || true; j=0; while [ $j -lt 20 ] && pgrep -x "$AGY_APP_NAME" >/dev/null 2>&1; do sleep 0.2; j=$((j+1)); done; fi', - 'if pgrep -x "$AGY_APP_NAME" >/dev/null 2>&1; then pkill -KILL -x "$AGY_APP_NAME" >/dev/null 2>&1 || killall -KILL "$AGY_APP_NAME" >/dev/null 2>&1 || true; k=0; while [ $k -lt 15 ] && pgrep -x "$AGY_APP_NAME" >/dev/null 2>&1; do sleep 0.2; k=$((k+1)); done; fi', + 'if osascript -e \'on run argv\' -e \'tell application (item 1 of argv) to quit\' -e \'end run\' -- "$AGY_APP_NAME" >/dev/null 2>&1; then i=0; while [ $i -lt 25 ] && pgrep -ax "$AGY_APP_NAME" >/dev/null 2>&1; do sleep 0.2; i=$((i+1)); done; fi', + 'if pgrep -ax "$AGY_APP_NAME" >/dev/null 2>&1; then pkill -TERM -ax "$AGY_APP_NAME" >/dev/null 2>&1 || killall -TERM "$AGY_APP_NAME" >/dev/null 2>&1 || true; j=0; while [ $j -lt 20 ] && pgrep -ax "$AGY_APP_NAME" >/dev/null 2>&1; do sleep 0.2; j=$((j+1)); done; fi', + 'if pgrep -ax "$AGY_APP_NAME" >/dev/null 2>&1; then pkill -KILL -ax "$AGY_APP_NAME" >/dev/null 2>&1 || killall -KILL "$AGY_APP_NAME" >/dev/null 2>&1 || true; k=0; while [ $k -lt 15 ] && pgrep -ax "$AGY_APP_NAME" >/dev/null 2>&1; do sleep 0.2; k=$((k+1)); done; fi', 'old_ifs="$IFS"; set -f; IFS=":"; for f in $AGY_STALE_PORT_FILES; do [ -n "$f" ] && rm -f "$f"; done; set +f; IFS="$old_ifs"', + 'sleep 0.4', 'open -a "$AGY_RELAUNCH_APP" --args --remote-debugging-port=0 >/dev/null 2>&1', ].join('; '); await spawner('/bin/sh', ['-c', shScript], { diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index 6b9ea45..2c7bbbc 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -5504,9 +5504,9 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi assert.equal(relaunchMacRes.ok, true); assert.equal(macSpawnArgs.env.AGY_RELAUNCH_APP, '/Applications/Antigravity.app'); assert.equal(macSpawnArgs.env.AGY_APP_NAME, 'Antigravity'); - assert.match(macSpawnArgs.args[1], /if osascript .* then .* fi/); - assert.match(macSpawnArgs.args[1], /pkill -TERM -x "\$AGY_APP_NAME"/); - assert.match(macSpawnArgs.args[1], /pkill -KILL -x "\$AGY_APP_NAME"/); + assert.match(macSpawnArgs.args[1], /if osascript .* then .* pgrep -ax "\$AGY_APP_NAME".* fi/); + assert.match(macSpawnArgs.args[1], /pkill -TERM -ax "\$AGY_APP_NAME"/); + assert.match(macSpawnArgs.args[1], /pkill -KILL -ax "\$AGY_APP_NAME"/); assert.match(macSpawnArgs.args[1], /open -a "\$AGY_RELAUNCH_APP" --args --remote-debugging-port=0/); // macOS TCC-blocked osascript falls back to ps -axo comm= and derives custom .app name From e1c3134e724cc9601d95f58fe553e1227b2924d5 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Fri, 20 Nov 2026 16:30:37 +0900 Subject: [PATCH 4/8] fix(panel): support Orchestrator (Neon) and prevent future variants from falling back to Carbon # Conflicts: # sidecars/panel/index.html # sidecars/panel/test/backend-harness.mjs --- pricing-catalog.json | 6 +- sidecars/panel/app.js | 82 ++++++--- sidecars/panel/backend/model-pricing.mjs | 73 +++++++- sidecars/panel/index.html | 4 +- .../components/layout/WindowOverlayShell.js | 2 +- sidecars/panel/src/core/formatters.js | 80 +++++--- sidecars/panel/test/backend-harness.mjs | 2 +- sidecars/panel/test/model-identity.test.mjs | 174 ++++++++++++++++++ sidecars/panel/trajectory-metrics.mjs | 2 +- 9 files changed, 363 insertions(+), 62 deletions(-) diff --git a/pricing-catalog.json b/pricing-catalog.json index d2d403a..46b7f8e 100644 --- a/pricing-catalog.json +++ b/pricing-catalog.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, - "catalogVersion": "2026.11.19.2", - "updatedAt": "2026-11-19T09:35:00+09:00", + "catalogVersion": "2026.11.20.1", + "updatedAt": "2026-11-20T02:00:00+09:00", "latestPluginVersion": "1.5.2", "releaseUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest", "downloadUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip", @@ -165,7 +165,9 @@ "placeholders": { "MODEL_PLACEHOLDER_M667": { "modelId": "gemini-pro-orchestrator", "label": "Orchestrator (Carbon)" }, "MODEL_PLACEHOLDER_M681": { "modelId": "gemini-pro-orchestrator-argon", "label": "Orchestrator (Argon)" }, + "MODEL_PLACEHOLDER_M537": { "modelId": "gemini-pro-orchestrator-neon", "label": "Orchestrator (Neon)" }, "MODEL_PLACEHOLDER_M669": { "modelId": "gemini-flash-worker-agy", "label": "Orchestrator Worker (Hydrogen)" }, + "MODEL_PLACEHOLDER_M535": { "modelId": "gemini-4-neon-xhigh", "label": "Gemini 4 Neon (XHigh)" }, "MODEL_PLACEHOLDER_M429": { "modelId": "gemini-4-carbon-high", "label": "Gemini 4 Carbon (High)" }, "MODEL_PLACEHOLDER_M427": { "modelId": "gemini-4-carbon-high", "label": "Gemini 4 Carbon (High)" }, "MODEL_PLACEHOLDER_M437": { "modelId": "gemini-4-carbon-medium", "label": "Gemini 4 Carbon (Medium)" }, diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 930c2c4..5ab5a05 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -3729,8 +3729,8 @@ const normalizeOrchestratorIdDisplayMode = normalizeOrchestratorIdMode; * 统一解析步骤、会话摘要或模型汇总行面向用户的模型显示文本与悬停提示。 * * 规则: - * - Orchestrator 系列(`Orchestrator (Carbon)`、`Orchestrator (Argon)`、`gemini-flash-worker-agy` / `M669`) - * 独立遵循 `orchestratorIdMode`(`'compact'` 显示 `orchestrator-carbon` / `orchestrator-argon` / `worker-agy-hydrogen`; + * - Orchestrator 系列(`Orchestrator (Carbon)`、`Orchestrator (Argon)`、`Orchestrator (Neon)`、`gemini-flash-worker-agy` / `M669`) + * 独立遵循 `orchestratorIdMode`(`'compact'` 显示 `orchestrator-carbon` / `orchestrator-argon` / `orchestrator-neon` / `worker-agy-hydrogen`; * `'full'` 显示带括号标注的完整上游 ID),不受普通模型显示模式影响; * - 其余普通模型遵循 `modelDisplayMode`(`'short'` | `'upstream_compact'` | `'upstream'`,兼容旧版布尔 `showUpstreamModel`); * - 独立拆分 `baseText` 与 `compactionSuffix`(`·压缩`),供步骤表单独保护压缩尾标永不截断。 @@ -3803,37 +3803,71 @@ function resolveModelDisplayInfo(target, settings = {}, options = {}) { /\bMODEL_PLACEHOLDER_M669\b|\b[a-z0-9.-]*worker-agy\b|\bworker-agy-hydrogen\b|\bOrchestrator\s+Worker\b/i.test( combined ); + const isKnownOrchCarbonPh = /\bMODEL_PLACEHOLDER_M667\b/i.test(combined); + const isKnownOrchArgonPh = /\bMODEL_PLACEHOLDER_M681\b/i.test(combined); + const isKnownOrchNeonPh = /\bMODEL_PLACEHOLDER_M537\b/i.test(combined); + const dynamicOrchVariantMatch = + combined.match(/\bOrchestrator\s*\(\s*([a-z0-9-]+)\s*\)/i) || + combined.match(/\bgemini-pro-orchestrator-([a-z0-9-]+)\b/i) || + combined.match(/\b(?:orchestrator|orch)-([a-z0-9]+)(?=·|\s|$)/i); + const dynamicOrchVariant = + dynamicOrchVariantMatch && dynamicOrchVariantMatch[1].toLowerCase() !== 'worker' + ? dynamicOrchVariantMatch[1].toLowerCase() + : ''; + const hasBareProOrch = /\bgemini-pro-orchestrator\b(?![-_][a-z0-9])/i.test(combined); const isOrchSeries = isOrchWorker || - /\bgemini-pro-orchestrator(?:-argon)?\b|\borchestrator-(?:carbon|argon)\b|\borch-(?:carbon|argon)(?:·压缩)?(?=\s|$)|Orchestrator\s*\((?:Carbon|Argon)\)|\bMODEL_PLACEHOLDER_M(?:667|681)\b/i.test( - combined - ); + Boolean(dynamicOrchVariant) || + isKnownOrchNeonPh || + isKnownOrchArgonPh || + isKnownOrchCarbonPh || + hasBareProOrch; if (isOrchSeries) { - let compactId = 'orchestrator-carbon'; - let fullId = 'gemini-pro-orchestrator (carbon-4)'; + let compactId = ''; + let fullId = ''; if (isOrchWorker) { compactId = 'worker-agy-hydrogen'; fullId = 'gemini-flash-worker-agy (hydrogen-4)'; - } else if (/\bargon\b|\bMODEL_PLACEHOLDER_M681\b|\borch-argon\b/i.test(combined)) { + } else if (isKnownOrchNeonPh || dynamicOrchVariant === 'neon') { + compactId = 'orchestrator-neon'; + fullId = 'gemini-pro-orchestrator-neon (neon-4)'; + } else if (isKnownOrchArgonPh || dynamicOrchVariant === 'argon') { compactId = 'orchestrator-argon'; fullId = 'gemini-pro-orchestrator-argon (argon-4)'; + } else if ( + isKnownOrchCarbonPh || + dynamicOrchVariant === 'carbon' || + (hasBareProOrch && !dynamicOrchVariant) + ) { + compactId = 'orchestrator-carbon'; + fullId = 'gemini-pro-orchestrator (carbon-4)'; + } else if (dynamicOrchVariant) { + compactId = `orchestrator-${dynamicOrchVariant}`; + const cleanUpstream = stripCompactionMarker(upstreamText || responseText || '').trim(); + fullId = cleanUpstream + ? cleanUpstream.toLowerCase().includes(dynamicOrchVariant) + ? cleanUpstream + : `${cleanUpstream} (${dynamicOrchVariant})` + : `gemini-pro-orchestrator-${dynamicOrchVariant}`; + } + if (compactId) { + const baseText = orchestratorMode === 'full' ? fullId : compactId; + const text = `${baseText}${compactionSuffix}`; + const multiUpstream = + Array.isArray(target.upstreamModels) && target.upstreamModels.length > 1 + ? target.upstreamModels.join(' / ') + : ''; + const title = multiUpstream || `${fullId}${compactionSuffix}`; + return { + text, + baseText, + compactionSuffix, + isCompaction, + title, + isOrchestratorSeries: true, + }; } - const baseText = orchestratorMode === 'full' ? fullId : compactId; - const text = `${baseText}${compactionSuffix}`; - const multiUpstream = - Array.isArray(target.upstreamModels) && target.upstreamModels.length > 1 - ? target.upstreamModels.join(' / ') - : ''; - const title = multiUpstream || `${fullId}${compactionSuffix}`; - return { - text, - baseText, - compactionSuffix, - isCompaction, - title, - isOrchestratorSeries: true, - }; } const rawSelected = @@ -24797,7 +24831,7 @@ function findHostTitlebar() { const COMPOSER_EXCLUDED_ANCESTOR_SELECTOR = '.part.titlebar, .part.statusbar, .quick-input-widget, .suggest-widget, .find-widget, .scm-editor, .search-view, [class*="@container/titlebar"]'; const COMPOSER_MODEL_LABEL_RE = - /\b(?:gemini|claude|gpt|argon|carbon|hydrogen|helix|flash|sonnet|opus|haiku|orchestrator|llama|deepseek|qwen|mistral|model_placeholder|placeholder_m\d+|o[134](?:-\w+)?)\b/i; + /\b(?:gemini|claude|gpt|argon|carbon|neon|hydrogen|helix|flash|sonnet|opus|haiku|orchestrator|llama|deepseek|qwen|mistral|model_placeholder|placeholder_m\d+|o[134](?:-\w+)?)\b/i; const COMPOSER_MODEL_ATTR_RE = /\bmodel[-_\s]?(?:select|picker|switch|selector|menu|name)\b|选择模型|切换模型/i; const COMPOSER_MODE_EXACT_RE = /^(?:auto|自动)$/i; diff --git a/sidecars/panel/backend/model-pricing.mjs b/sidecars/panel/backend/model-pricing.mjs index d8c3493..34c551d 100644 --- a/sidecars/panel/backend/model-pricing.mjs +++ b/sidecars/panel/backend/model-pricing.mjs @@ -49,6 +49,7 @@ function inferFamilyFromProviderOrKey(rawModelKey = '', modelId = '', apiProvide combined.includes('GEMINI') || combined.includes('CARBON') || combined.includes('ARGON') || + combined.includes('NEON') || combined.includes('HYDROGEN') || combined.includes('ORCHESTRATOR') || combined.includes('HELIX') || @@ -60,6 +61,23 @@ function inferFamilyFromProviderOrKey(rawModelKey = '', modelId = '', apiProvide return 'Other'; } +/** + * 判断一组模型标识字段是否指向 Gemini 4 Neon 系列模型(含 M535 及 M537 Orchestrator (Neon))。 + * + * @param {...string} parts 待检测的标识片段 + * @returns {boolean} + */ +export function isNeonModelIdentifier(...parts) { + const text = parts.filter(Boolean).join(' '); + if ( + /\bhydrogen\b|\bgemini-flash-worker-agy\b|MODEL_PLACEHOLDER_M(?:669|52[5678])\b/i.test(text) && + !/\bneon\b|MODEL_PLACEHOLDER_M53[57]\b/i.test(text) + ) { + return false; + } + return /\bneon\b|gemini-(?:4-)?neon|MODEL_PLACEHOLDER_M53[57]\b/i.test(text); +} + /** * 判断一组模型标识字段是否指向 Gemini 4 Argon 系列模型(含 M417/M418/M419 及 M681 Orchestrator (Argon))。 * @@ -77,8 +95,27 @@ export function isArgonModelIdentifier(...parts) { return /argon|MODEL_PLACEHOLDER_M(?:41[789]|681)\b/i.test(text); } +/** + * 从一组标识字段中提取显式的非通用 Orchestrator 变体代号(如 `Orchestrator (Xenon)` -> `'xenon'`、 + * `gemini-pro-orchestrator-neon` -> `'neon'`)。未命中时返回空字符串。 + * + * @param {string} text + * @returns {string} + */ +function extractExplicitOrchestratorVariant(text = '') { + const parenMatch = text.match(/\bOrchestrator\s*\(\s*([a-z0-9-]+)\s*\)/i); + if (parenMatch) return parenMatch[1].toLowerCase(); + const slugMatch = text.match(/\b(?:gemini-pro-orchestrator|orchestrator|orch)-([a-z0-9]+)\b/i); + if (slugMatch && slugMatch[1].toLowerCase() !== 'worker') { + return slugMatch[1].toLowerCase(); + } + return ''; +} + /** * 判断一组模型标识字段是否指向 Gemini 4 Carbon 系列模型(含 M427/M429/M437/M438 及 M667 Orchestrator (Carbon))。 + * 仅当显式命中 Carbon 标识,或裸 `gemini-pro-orchestrator` 不携带任何其他变体代号时才判定为 Carbon, + * 防止未来新增 `Orchestrator (<新代号>)` 被静默误判为 Carbon。 * * @param {...string} parts 待检测的标识片段 * @returns {boolean} @@ -88,15 +125,23 @@ export function isCarbonModelIdentifier(...parts) { if (/\bcarbon\b|gemini-4-carbon|MODEL_PLACEHOLDER_M(?:42[79]|43[78]|667)\b/i.test(text)) { return true; } - if (/\bhydrogen\b|\bgemini-flash-worker-agy\b|MODEL_PLACEHOLDER_M(?:669|52[5678])\b/i.test(text)) { + if ( + /\bhydrogen\b|\bgemini-flash-worker-agy\b|MODEL_PLACEHOLDER_M(?:669|52[5678])\b/i.test(text) || + /\bneon\b|gemini-(?:4-)?neon|MODEL_PLACEHOLDER_M53[57]\b/i.test(text) || + /\bargon\b|MODEL_PLACEHOLDER_M(?:41[789]|681)\b/i.test(text) + ) { return false; } - return /\bgemini-pro-orchestrator\b(?!-argon)/i.test(text); + const explicitVariant = extractExplicitOrchestratorVariant(text); + if (explicitVariant && explicitVariant !== 'carbon') { + return false; + } + return /\bgemini-pro-orchestrator\b(?![-_][a-z0-9])/i.test(text); } /** * 剥离模型展示名称末尾的思考档位后缀(如 `(XHigh)`、`(High)`、`(Medium)`、`(Thinking)`),提取基础模型族名。 - * 保留 `(Carbon)` / `(Argon)` 后缀,以便 `Orchestrator (Carbon)` 与 `Orchestrator (Argon)` 在汇总表中保持分列。 + * 保留 `(Carbon)` / `(Argon)` / `(Neon)` 后缀,以便不同 Orchestrator 系列在汇总表中保持分列。 * * @param {string} [label=''] * @returns {string} @@ -138,7 +183,7 @@ export function formatGenericModelSlug(slug = '') { if (/^gemini-3-flash-c$/i.test(s)) return 'Gemini 3 Flash'; if (/^gemini-pro-(?:default|agent|b)$/i.test(s)) return 'Gemini 3.1 Pro'; const m = s.match( - /^gemini-(\d+(?:\.\d+)?)-(pro|flash|argon|carbon|hydrogen|helix)(?:-(lite))?(?:-(xhigh|high|medium|low|extra-low|tiered|preview))?$/i + /^gemini-(\d+(?:\.\d+)?)-(pro|flash|argon|carbon|neon|hydrogen|helix)(?:-(lite))?(?:-(xhigh|high|medium|low|extra-low|tiered|preview))?$/i ); if (m) { const ver = m[1]; @@ -148,12 +193,18 @@ export function formatGenericModelSlug(slug = '') { const tierSuffix = SLUG_TIER_LABELS[suffixKey] ? ` (${SLUG_TIER_LABELS[suffixKey]})` : ''; return `Gemini ${ver} ${tier}${lite}${tierSuffix}`; } - const codenameMatch = s.match(/^gemini-(hydrogen|helix)$/i); + const codenameMatch = s.match(/^gemini-(hydrogen|helix|neon)$/i); if (codenameMatch) { const codename = codenameMatch[1].charAt(0).toUpperCase() + codenameMatch[1].slice(1).toLowerCase(); return `Gemini ${codename}`; } + const orchVariantMatch = s.match(/^gemini-pro-orchestrator-([a-z0-9]+)$/i); + if (orchVariantMatch) { + const variant = + orchVariantMatch[1].charAt(0).toUpperCase() + orchVariantMatch[1].slice(1).toLowerCase(); + return `Orchestrator (${variant})`; + } if (/^gemini-flash-worker-agy$/i.test(s)) { return 'Orchestrator Worker (Hydrogen)'; } @@ -298,6 +349,11 @@ function resolveModelCatalogEntry( const isOpaqueOrchestratorResp = Boolean( cleanResponseModel && /\borchestrator\b/i.test(cleanResponseModel) ); + const isBareOpaqueOrchestratorResp = /^gemini-pro-orchestrator$/i.test(cleanResponseModel); + const allowOpaqueOrchestratorFallback = + isOpaqueOrchestratorResp && + (!isBareOpaqueOrchestratorResp || + isCarbonModelIdentifier(rawModelKey, modelId, derivedDisplay, cleanResponseModel)); const explicitPricing = MODEL_PRICING[modelId] || MODEL_PRICING[rawModelKey] || @@ -308,9 +364,7 @@ function resolveModelCatalogEntry( MODEL_PRICING[tieredDashedSlug] || MODEL_PRICING[canonicalSlug] || MODEL_PRICING[dashedSlug] || - (cleanResponseModel && isOpaqueOrchestratorResp - ? MODEL_PRICING[cleanResponseModel] - : null); + (allowOpaqueOrchestratorFallback ? MODEL_PRICING[cleanResponseModel] : null); if (explicitPricing) { return { @@ -469,6 +523,9 @@ export function formatUpstreamModelId(rawUpstream = '', mInfo = null) { ) { return `${s} (hydrogen-4)`; } + if (isNeonModelIdentifier(mInfo?.rawModel, mInfo?.modelId, mInfo?.label, s)) { + return `${s} (neon-4)`; + } if (isArgonModelIdentifier(mInfo?.rawModel, mInfo?.modelId, mInfo?.label, s)) { return `${s} (argon-4)`; } diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 9524768..5f0132e 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/layout/WindowOverlayShell.js b/sidecars/panel/src/components/layout/WindowOverlayShell.js index 45084e5..ff87b01 100644 --- a/sidecars/panel/src/components/layout/WindowOverlayShell.js +++ b/sidecars/panel/src/components/layout/WindowOverlayShell.js @@ -169,7 +169,7 @@ function findHostTitlebar() { const COMPOSER_EXCLUDED_ANCESTOR_SELECTOR = '.part.titlebar, .part.statusbar, .quick-input-widget, .suggest-widget, .find-widget, .scm-editor, .search-view, [class*="@container/titlebar"]'; const COMPOSER_MODEL_LABEL_RE = - /\b(?:gemini|claude|gpt|argon|carbon|hydrogen|helix|flash|sonnet|opus|haiku|orchestrator|llama|deepseek|qwen|mistral|model_placeholder|placeholder_m\d+|o[134](?:-\w+)?)\b/i; + /\b(?:gemini|claude|gpt|argon|carbon|neon|hydrogen|helix|flash|sonnet|opus|haiku|orchestrator|llama|deepseek|qwen|mistral|model_placeholder|placeholder_m\d+|o[134](?:-\w+)?)\b/i; const COMPOSER_MODEL_ATTR_RE = /\bmodel[-_\s]?(?:select|picker|switch|selector|menu|name)\b|选择模型|切换模型/i; const COMPOSER_MODE_EXACT_RE = /^(?:auto|自动)$/i; diff --git a/sidecars/panel/src/core/formatters.js b/sidecars/panel/src/core/formatters.js index 8926777..f0fec3d 100644 --- a/sidecars/panel/src/core/formatters.js +++ b/sidecars/panel/src/core/formatters.js @@ -317,8 +317,8 @@ export const normalizeOrchestratorIdDisplayMode = normalizeOrchestratorIdMode; * 统一解析步骤、会话摘要或模型汇总行面向用户的模型显示文本与悬停提示。 * * 规则: - * - Orchestrator 系列(`Orchestrator (Carbon)`、`Orchestrator (Argon)`、`gemini-flash-worker-agy` / `M669`) - * 独立遵循 `orchestratorIdMode`(`'compact'` 显示 `orchestrator-carbon` / `orchestrator-argon` / `worker-agy-hydrogen`; + * - Orchestrator 系列(`Orchestrator (Carbon)`、`Orchestrator (Argon)`、`Orchestrator (Neon)`、`gemini-flash-worker-agy` / `M669`) + * 独立遵循 `orchestratorIdMode`(`'compact'` 显示 `orchestrator-carbon` / `orchestrator-argon` / `orchestrator-neon` / `worker-agy-hydrogen`; * `'full'` 显示带括号标注的完整上游 ID),不受普通模型显示模式影响; * - 其余普通模型遵循 `modelDisplayMode`(`'short'` | `'upstream_compact'` | `'upstream'`,兼容旧版布尔 `showUpstreamModel`); * - 独立拆分 `baseText` 与 `compactionSuffix`(`·压缩`),供步骤表单独保护压缩尾标永不截断。 @@ -391,37 +391,71 @@ export function resolveModelDisplayInfo(target, settings = {}, options = {}) { /\bMODEL_PLACEHOLDER_M669\b|\b[a-z0-9.-]*worker-agy\b|\bworker-agy-hydrogen\b|\bOrchestrator\s+Worker\b/i.test( combined ); + const isKnownOrchCarbonPh = /\bMODEL_PLACEHOLDER_M667\b/i.test(combined); + const isKnownOrchArgonPh = /\bMODEL_PLACEHOLDER_M681\b/i.test(combined); + const isKnownOrchNeonPh = /\bMODEL_PLACEHOLDER_M537\b/i.test(combined); + const dynamicOrchVariantMatch = + combined.match(/\bOrchestrator\s*\(\s*([a-z0-9-]+)\s*\)/i) || + combined.match(/\bgemini-pro-orchestrator-([a-z0-9-]+)\b/i) || + combined.match(/\b(?:orchestrator|orch)-([a-z0-9]+)(?=·|\s|$)/i); + const dynamicOrchVariant = + dynamicOrchVariantMatch && dynamicOrchVariantMatch[1].toLowerCase() !== 'worker' + ? dynamicOrchVariantMatch[1].toLowerCase() + : ''; + const hasBareProOrch = /\bgemini-pro-orchestrator\b(?![-_][a-z0-9])/i.test(combined); const isOrchSeries = isOrchWorker || - /\bgemini-pro-orchestrator(?:-argon)?\b|\borchestrator-(?:carbon|argon)\b|\borch-(?:carbon|argon)(?:·压缩)?(?=\s|$)|Orchestrator\s*\((?:Carbon|Argon)\)|\bMODEL_PLACEHOLDER_M(?:667|681)\b/i.test( - combined - ); + Boolean(dynamicOrchVariant) || + isKnownOrchNeonPh || + isKnownOrchArgonPh || + isKnownOrchCarbonPh || + hasBareProOrch; if (isOrchSeries) { - let compactId = 'orchestrator-carbon'; - let fullId = 'gemini-pro-orchestrator (carbon-4)'; + let compactId = ''; + let fullId = ''; if (isOrchWorker) { compactId = 'worker-agy-hydrogen'; fullId = 'gemini-flash-worker-agy (hydrogen-4)'; - } else if (/\bargon\b|\bMODEL_PLACEHOLDER_M681\b|\borch-argon\b/i.test(combined)) { + } else if (isKnownOrchNeonPh || dynamicOrchVariant === 'neon') { + compactId = 'orchestrator-neon'; + fullId = 'gemini-pro-orchestrator-neon (neon-4)'; + } else if (isKnownOrchArgonPh || dynamicOrchVariant === 'argon') { compactId = 'orchestrator-argon'; fullId = 'gemini-pro-orchestrator-argon (argon-4)'; + } else if ( + isKnownOrchCarbonPh || + dynamicOrchVariant === 'carbon' || + (hasBareProOrch && !dynamicOrchVariant) + ) { + compactId = 'orchestrator-carbon'; + fullId = 'gemini-pro-orchestrator (carbon-4)'; + } else if (dynamicOrchVariant) { + compactId = `orchestrator-${dynamicOrchVariant}`; + const cleanUpstream = stripCompactionMarker(upstreamText || responseText || '').trim(); + fullId = cleanUpstream + ? cleanUpstream.toLowerCase().includes(dynamicOrchVariant) + ? cleanUpstream + : `${cleanUpstream} (${dynamicOrchVariant})` + : `gemini-pro-orchestrator-${dynamicOrchVariant}`; + } + if (compactId) { + const baseText = orchestratorMode === 'full' ? fullId : compactId; + const text = `${baseText}${compactionSuffix}`; + const multiUpstream = + Array.isArray(target.upstreamModels) && target.upstreamModels.length > 1 + ? target.upstreamModels.join(' / ') + : ''; + const title = multiUpstream || `${fullId}${compactionSuffix}`; + return { + text, + baseText, + compactionSuffix, + isCompaction, + title, + isOrchestratorSeries: true, + }; } - const baseText = orchestratorMode === 'full' ? fullId : compactId; - const text = `${baseText}${compactionSuffix}`; - const multiUpstream = - Array.isArray(target.upstreamModels) && target.upstreamModels.length > 1 - ? target.upstreamModels.join(' / ') - : ''; - const title = multiUpstream || `${fullId}${compactionSuffix}`; - return { - text, - baseText, - compactionSuffix, - isCompaction, - title, - isOrchestratorSeries: true, - }; } const rawSelected = diff --git a/sidecars/panel/test/backend-harness.mjs b/sidecars/panel/test/backend-harness.mjs index 35a8dcf..85f2391 100644 --- a/sidecars/panel/test/backend-harness.mjs +++ b/sidecars/panel/test/backend-harness.mjs @@ -207,6 +207,6 @@ export function backendHarness({ return {ok:true,json:async()=>data}; }, }; - vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,dispatchBridgeApiRequest,executeAccountCredentialAction,callLsRpc,computeStepCost,resolveModelInfo,resolvePricingAt,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,getPricingPhaseEpoch,detectCustomGitForkRepo,persistTrajectoryCacheIfNeeded,flushTrajectoryCacheNow,getCachedTrajectory,listCachedTrajectoryEntries,hasPendingTrajectoryCacheSave,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStepTokenComboFormat,parseStepTokenComboSegments,normalizeModelDisplayMode,normalizePopoverWidthMode,normalizePopoverWidth,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,readLocalSummarySnapshot,readLocalSqliteTrajectory,computeSqliteWalSig,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule,registerRemoteEndpoint,getRegisteredRemoteEndpoint,resolveEndpointContext,clearRemoteEndpointCaches,clearRemoteEndpointRegistry,setRemoteWindowRpcInvoker,setLoopbackHttpsRequester,getEndpointCacheStore,pruneStaleRemoteEndpoints,trackEndpointRequestStart,trackEndpointRequestEnd,shouldRemoteEndpointPreferTier2,markRemoteEndpointPreferTier2};',ctx); + vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,dispatchBridgeApiRequest,executeAccountCredentialAction,callLsRpc,computeStepCost,resolveModelInfo,resolvePricingAt,inferFamilyFromProviderOrKey,isNeonModelIdentifier,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,getPricingPhaseEpoch,detectCustomGitForkRepo,persistTrajectoryCacheIfNeeded,flushTrajectoryCacheNow,getCachedTrajectory,listCachedTrajectoryEntries,hasPendingTrajectoryCacheSave,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStepTokenComboFormat,parseStepTokenComboSegments,normalizeModelDisplayMode,normalizePopoverWidthMode,normalizePopoverWidth,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,readLocalSummarySnapshot,readLocalSqliteTrajectory,computeSqliteWalSig,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule,registerRemoteEndpoint,getRegisteredRemoteEndpoint,resolveEndpointContext,clearRemoteEndpointCaches,clearRemoteEndpointRegistry,setRemoteWindowRpcInvoker,setLoopbackHttpsRequester,getEndpointCacheStore,pruneStaleRemoteEndpoints,trackEndpointRequestStart,trackEndpointRequestEnd,shouldRemoteEndpointPreferTier2,markRemoteEndpointPreferTier2};',ctx); return {...ctx.api,state}; } diff --git a/sidecars/panel/test/model-identity.test.mjs b/sidecars/panel/test/model-identity.test.mjs index 150753a..298afa4 100644 --- a/sidecars/panel/test/model-identity.test.mjs +++ b/sidecars/panel/test/model-identity.test.mjs @@ -199,6 +199,7 @@ test('frontend considers a model-only correction a real telemetry update', () => const ORCH_CARBON = 'MODEL_PLACEHOLDER_M667'; const ORCH_ARGON = 'MODEL_PLACEHOLDER_M681'; +const ORCH_NEON = 'MODEL_PLACEHOLDER_M537'; const ORCH_EXEC_HYDROGEN = 'MODEL_PLACEHOLDER_M669'; test('Orchestrator (Carbon) direct/planning and inferred compaction steps resolve to orch-carbon and annotate upstream ID', async () => { @@ -285,6 +286,148 @@ test('Orchestrator (Argon) resolves to orch-argon, annotates upstream ID, and is assert.equal(h.isCarbonModelIdentifier(ORCH_ARGON, 'gemini-pro-orchestrator-argon', 'Orchestrator (Argon)'), false); }); +test('Orchestrator (Neon) resolves to orch-neon, annotates upstream ID, uses Neon pricing, and is not misclassified as Carbon', async () => { + const rows = [step(1, ORCH_NEON), step(2, ORCH_EXEC_HYDROGEN)]; + const h = backendHarness({ + clock: () => PROMO_CLOCK_MS, + summaries: { test: { stepCount: 2 } }, + trajectories: { + test: { + trajectory: { + steps: rows, + generatorMetadata: [ + { + stepIndices: [1], + chatModel: { + model: ORCH_NEON, + responseModel: 'gemini-pro-orchestrator-neon', + modelDisplayName: 'Orchestrator (Neon)', + }, + plannerConfig: { + planModel: ORCH_NEON, + modelName: 'gemini-pro-orchestrator-neon', + planExecuteConfig: { executionModel: ORCH_EXEC_HYDROGEN }, + }, + }, + { + stepIndices: [2], + chatModel: { + model: ORCH_EXEC_HYDROGEN, + responseModel: 'gemini-flash-worker-agy', + modelDisplayName: 'Gemini Flash', + }, + }, + ], + }, + }, + }, + }); + + const p = await h.buildTelemetryPayloadInternal('test'); + const s1 = p.activeConversation.recentSteps.find((s) => s.stepIndex === 1); + const s2 = p.activeConversation.recentSteps.find((s) => s.stepIndex === 2); + assert.equal(s1.modelShort, 'orch-neon'); + assert.equal(s1.modelLabel, 'Orchestrator (Neon)'); + assert.equal(s1.modelUpstream, 'gemini-pro-orchestrator-neon (neon-4)'); + // step() fixture: 1000 input ($3/M = 0.003) + 9000 cache ($0.15/M = 0.00135) + 1000 output ($15/M = 0.015) = 0.01935 -> 0.0193 (4-decimal payload rounding) + assert.equal(s1.costUsd, 0.0193); + assert.equal(s2.modelShort, 'hydrogen-4'); + assert.equal(s2.modelLabel, 'Orchestrator Worker (Hydrogen)'); + assert.equal(s2.modelUpstream, 'gemini-flash-worker-agy (hydrogen-4)'); + + const neonRow = p.modelBreakdown.find((m) => m.label === 'Orchestrator (Neon)'); + assert.ok(neonRow, 'modelBreakdown keeps Orchestrator (Neon) separate'); + assert.equal(neonRow.upstreamName, 'gemini-pro-orchestrator-neon (neon-4)'); + assert.equal(h.isNeonModelIdentifier(ORCH_NEON, 'gemini-pro-orchestrator-neon', 'Orchestrator (Neon)'), true); + assert.equal(h.isCarbonModelIdentifier(ORCH_NEON, 'gemini-pro-orchestrator-neon', 'Orchestrator (Neon)'), false); + assert.equal(h.isCarbonModelIdentifier(ORCH_NEON, 'gemini-pro-orchestrator', 'Orchestrator (Neon)'), false); + assert.equal(h.isArgonModelIdentifier(ORCH_NEON, 'gemini-pro-orchestrator-neon', 'Orchestrator (Neon)'), false); + + // Pure placeholder lookup without modelDisplayName / responseModel + const neonOrchInfo = h.resolveModelInfo(ORCH_NEON); + assert.equal(neonOrchInfo.shortName, 'orch-neon'); + assert.equal(neonOrchInfo.label, 'Orchestrator (Neon)'); + assert.equal(neonOrchInfo.pricing.input, 3.0); + assert.equal(neonOrchInfo.pricing.output, 15.0); + + const neonXhighInfo = h.resolveModelInfo('MODEL_PLACEHOLDER_M535'); + assert.equal(neonXhighInfo.shortName, 'neon-4-xhigh'); + assert.equal(neonXhighInfo.baseLabel, 'Gemini 4 Neon'); + assert.equal(neonXhighInfo.pricing.input, 3.0); + assert.equal(neonXhighInfo.pricing.output, 15.0); +}); + +test('future uncatalogued Orchestrator variants never fall back to Carbon identity, pricing, or display', async () => { + const FUTURE_ORCH_1 = 'MODEL_PLACEHOLDER_M991'; + const FUTURE_ORCH_2 = 'MODEL_PLACEHOLDER_M992'; + const rows = [step(1, FUTURE_ORCH_1), step(2, FUTURE_ORCH_2)]; + const h = backendHarness({ + clock: () => PROMO_CLOCK_MS, + summaries: { test: { stepCount: 2 } }, + trajectories: { + test: { + trajectory: { + steps: rows, + generatorMetadata: [ + { + stepIndices: [1], + chatModel: { + model: FUTURE_ORCH_1, + responseModel: 'gemini-pro-orchestrator-xenon', + modelDisplayName: 'Orchestrator (Xenon)', + }, + }, + { + stepIndices: [2], + chatModel: { + model: FUTURE_ORCH_2, + responseModel: 'gemini-pro-orchestrator', + modelDisplayName: 'Orchestrator (Helium)', + }, + }, + ], + }, + }, + }, + }); + + const p = await h.buildTelemetryPayloadInternal('test'); + const s1 = p.activeConversation.recentSteps.find((s) => s.stepIndex === 1); + const s2 = p.activeConversation.recentSteps.find((s) => s.stepIndex === 2); + + // Neither future variant may be misclassified as Carbon, given Carbon pricing, or stamped (carbon-4) + assert.equal(h.isCarbonModelIdentifier(FUTURE_ORCH_1, 'gemini-pro-orchestrator-xenon', 'Orchestrator (Xenon)'), false); + assert.equal(h.isCarbonModelIdentifier(FUTURE_ORCH_2, 'gemini-pro-orchestrator', 'Orchestrator (Helium)'), false); + assert.equal(s1.costUsd, null); + assert.equal(s2.costUsd, null); + assert.equal(s1.modelUpstream, 'gemini-pro-orchestrator-xenon'); + assert.equal(s2.modelUpstream, 'gemini-pro-orchestrator'); + assert.notEqual(s1.modelShort, 'orch-carbon'); + assert.notEqual(s2.modelShort, 'orch-carbon'); + + // Frontend dynamically renders orchestrator- without silently falling back to orchestrator-carbon + assert.equal(resolveModelDisplayInfo(s1, { orchestratorIdMode: 'compact' }).text, 'orchestrator-xenon'); + assert.equal(resolveModelDisplayInfo(s1, { orchestratorIdMode: 'full' }).text, 'gemini-pro-orchestrator-xenon'); + assert.equal(resolveModelDisplayInfo(s2, { orchestratorIdMode: 'compact' }).text, 'orchestrator-helium'); + assert.equal(resolveModelDisplayInfo(s2, { orchestratorIdMode: 'full' }).text, 'gemini-pro-orchestrator (helium)'); + + // Direct non-Orchestrator Carbon/Argon/Neon models remain unaffected + assert.equal( + resolveModelDisplayInfo( + { modelKey: 'MODEL_PLACEHOLDER_M429', modelShort: 'carbon-4-high', modelLabel: 'Gemini 4 Carbon (High)', modelUpstream: 'gemini-4-carbon-high' }, + { showUpstreamModel: false, orchestratorIdMode: 'compact' } + ).text, + 'carbon-4-high' + ); + assert.equal( + resolveModelDisplayInfo( + { modelKey: 'MODEL_PLACEHOLDER_M535', modelShort: 'neon-4-xhigh', modelLabel: 'Gemini 4 Neon (XHigh)', modelUpstream: 'gemini-4-neon-xhigh' }, + { showUpstreamModel: false, orchestratorIdMode: 'compact' } + ).text, + 'neon-4-xhigh' + ); +}); + test('real-world M669 worker steps (responseModel gemini-flash-worker-agy, displayName Gemini Flash) and uncatalogued executionModel resolve to Hydrogen', async () => { const FUTURE_EXEC_PH = 'MODEL_PLACEHOLDER_M799'; const rows = [step(1, ORCH_CARBON), step(2, ORCH_EXEC_HYDROGEN), step(3, FUTURE_EXEC_PH)]; @@ -428,6 +571,21 @@ test('orchestratorIdMode defaults to compact, persists via settings action, and modelUpstream: 'gemini-pro-orchestrator-argon (argon-4)', responseModel: 'gemini-pro-orchestrator-argon', }; + const orchNeon = { + modelKey: ORCH_NEON, + modelShort: 'orch-neon', + modelLabel: 'Orchestrator (Neon)', + modelUpstream: 'gemini-pro-orchestrator-neon (neon-4)', + responseModel: 'gemini-pro-orchestrator-neon', + }; + const orchNeonCompaction = { + modelKey: ORCH_NEON, + modelShort: 'orch-neon·压缩', + modelLabel: 'Orchestrator (Neon) [自动压缩]', + modelUpstream: 'gemini-pro-orchestrator-neon (neon-4)·压缩', + responseModel: 'gemini-pro-orchestrator-neon', + isCompactionStep: true, + }; const orchWorkerCompaction = { modelKey: ORCH_EXEC_HYDROGEN, modelShort: 'hydrogen-4·压缩', @@ -452,6 +610,14 @@ test('orchestratorIdMode defaults to compact, persists via settings action, and resolveModelDisplayInfo(orchArgon, { showUpstreamModel, orchestratorIdMode: 'compact' }).text, 'orchestrator-argon' ); + assert.equal( + resolveModelDisplayInfo(orchNeon, { showUpstreamModel, orchestratorIdMode: 'compact' }).text, + 'orchestrator-neon' + ); + assert.equal( + resolveModelDisplayInfo(orchNeonCompaction, { showUpstreamModel, orchestratorIdMode: 'compact' }).text, + 'orchestrator-neon·压缩' + ); assert.equal( resolveModelDisplayInfo(orchWorkerCompaction, { showUpstreamModel, orchestratorIdMode: 'compact' }).text, 'worker-agy-hydrogen·压缩' @@ -464,6 +630,14 @@ test('orchestratorIdMode defaults to compact, persists via settings action, and resolveModelDisplayInfo(orchArgon, { showUpstreamModel, orchestratorIdMode: 'full' }).text, 'gemini-pro-orchestrator-argon (argon-4)' ); + assert.equal( + resolveModelDisplayInfo(orchNeon, { showUpstreamModel, orchestratorIdMode: 'full' }).text, + 'gemini-pro-orchestrator-neon (neon-4)' + ); + assert.equal( + resolveModelDisplayInfo(orchNeonCompaction, { showUpstreamModel, orchestratorIdMode: 'full' }).text, + 'gemini-pro-orchestrator-neon (neon-4)·压缩' + ); assert.equal( resolveModelDisplayInfo(orchWorkerCompaction, { showUpstreamModel, orchestratorIdMode: 'full' }).text, 'gemini-flash-worker-agy (hydrogen-4)·压缩' diff --git a/sidecars/panel/trajectory-metrics.mjs b/sidecars/panel/trajectory-metrics.mjs index 9330883..b624dc7 100644 --- a/sidecars/panel/trajectory-metrics.mjs +++ b/sidecars/panel/trajectory-metrics.mjs @@ -887,7 +887,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { if ( typeof execModel === 'string' && execModel.trim() && - /orchestrator|MODEL_PLACEHOLDER_M(?:667|681)\b/i.test( + /orchestrator|MODEL_PLACEHOLDER_M(?:667|681|537)\b/i.test( `${pc?.modelName || ''} ${pc?.planModel || ''}` ) ) { From 481f3837637f053d1a8d76245a712522d6450771 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Fri, 20 Nov 2026 16:35:18 +0900 Subject: [PATCH 5/8] feat(panel): polish compaction row popover, pill selects, steps header, scrollbar, and chart tooltips # Conflicts: # sidecars/panel/index.html --- sidecars/panel/app.js | 273 ++++++++++---- sidecars/panel/index.html | 4 +- .../components/charts/SessionStepCharts.js | 33 +- .../src/components/charts/TrendAreaChart.js | 26 +- .../panel/src/components/ui/CustomSelect.js | 19 +- .../src/components/widgets/StepTableWidget.js | 61 ++- sidecars/panel/src/core/domPatch.js | 24 +- sidecars/panel/src/core/formatters.js | 36 ++ sidecars/panel/src/i18n/en-US.js | 4 + sidecars/panel/src/i18n/zh-CN.js | 4 + .../src/registries/stepColumnRegistry.js | 17 +- sidecars/panel/src/styles/controls.css | 35 +- sidecars/panel/src/styles/modern-ui.css | 53 ++- .../panel/src/styles/views-consumption.css | 125 +++++-- sidecars/panel/src/styles/views-tables.css | 133 +++++-- sidecars/panel/src/views/ConsumptionView.js | 28 +- sidecars/panel/src/views/StepsDetailView.js | 16 +- sidecars/panel/styles.css | 346 ++++++++++++++---- sidecars/panel/test/consumption-bars.test.mjs | 10 +- .../test/cross-module-regressions.test.mjs | 4 +- sidecars/panel/test/modern-ui.test.mjs | 6 +- sidecars/panel/test/step-anomalies.test.mjs | 108 +++++- sidecars/panel/test/window-bridge.test.mjs | 18 +- 23 files changed, 1062 insertions(+), 321 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 5ab5a05..d6e10a8 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1368,6 +1368,10 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'steps.anomalyKind.canceled': '用户取消', 'steps.anomalyStepTitle': '#{step} · 异常 {count} 次', 'steps.anomalyDelayPart': '退避 {sec}s', + 'steps.compactionStepTitle': '#{step} · 自动压缩', + 'steps.compactionSummaryRow': '输入 {input} → 摘要输出 {output}', + 'steps.compactionDetailHint': '系统自动触发的上下文压缩步骤,用于折叠历史对话以释放窗口空间', + 'steps.compactionAnomalyHint': '该步骤同时为系统自动压缩步骤', 'steps.anomalyTerminalTag': '中止', 'steps.anomalyModelTitle': '{model} · 异常 {count} 次', 'steps.anomalyModelSub': '涉及 {steps} 步', @@ -2073,6 +2077,10 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'steps.anomalyKind.canceled': 'Canceled by User', 'steps.anomalyStepTitle': '#{step} · {count} Retries / Errors', 'steps.anomalyDelayPart': 'Backoff {sec}s', + 'steps.compactionStepTitle': '#{step} · Auto-Compaction', + 'steps.compactionSummaryRow': 'Input {input} → Summary {output}', + 'steps.compactionDetailHint': 'Automatic context compaction step triggered to summarize history and free window space', + 'steps.compactionAnomalyHint': 'This step is also an auto-compaction step', 'steps.anomalyTerminalTag': 'Stopped', 'steps.anomalyModelTitle': '{model} · {count} Retries / Errors', 'steps.anomalyModelSub': '{steps} steps affected', @@ -3268,7 +3276,22 @@ function positionAnchoredPopup( popupEl.style.maxHeight = ''; const availWidth = Math.max(120, Math.floor(bound.width - margin * 2)); - popupEl.style.maxWidth = `${availWidth}px`; + let cssMaxW = NaN; + if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') { + try { + const rawMaxW = window.getComputedStyle(popupEl)?.maxWidth; + if (rawMaxW && rawMaxW !== 'none') { + cssMaxW = Number.parseFloat(rawMaxW); + } + } catch { + // 忽略 Mock DOM 样式查询异常 + } + } + const effectiveMaxW = + Number.isFinite(cssMaxW) && cssMaxW > 0 + ? Math.max(120, Math.min(availWidth, Math.floor(cssMaxW))) + : availWidth; + popupEl.style.maxWidth = `${effectiveMaxW}px`; const rawRect = popupEl.getBoundingClientRect?.(); // 优先读取 offsetWidth,避免入场动画 scale(0.975) 导致测宽偏小 @@ -3276,10 +3299,13 @@ function positionAnchoredPopup( Number(popupEl.offsetWidth || 0), Math.ceil(Number(rawRect?.width || 0)) ); - if (naturalW > availWidth) { + if (naturalW > effectiveMaxW) { popupEl.style.minWidth = '0px'; } - const popupW = Math.min(availWidth, naturalW > 0 ? naturalW : Math.max(triggerRect.width, 210)); + const popupW = Math.min( + effectiveMaxW, + naturalW > 0 ? naturalW : Math.max(triggerRect.width, 210) + ); const safeLeft = bound.left + margin; const safeRight = bound.right - margin; @@ -3422,7 +3448,7 @@ return { defineComponent }; })(); // --- src/core/formatters.js --- -const { formatMetric, formatSpeedMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap } = (() => { +const { 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 } = (() => { /** * @fileoverview Pure formatting utilities for speed metrics, token counts, * USD estimates, countdown timers, and custom datetime displays. @@ -3635,6 +3661,42 @@ function buildStepAnomalyDiagnostic(st) { }; } +function buildStepCompactionDiagnostic(st, displaySettings = {}) { + if (!st || typeof st !== 'object') return null; + const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: '' }); + const promptTok = + Math.max(0, Number(st.inputTokens || 0)) + Math.max(0, Number(st.cacheReadTokens || 0)); + const outTok = Math.max(0, Number(st.outputTokens || 0)); + const title = t('steps.compactionStepTitle', { step: Number(st.stepIndex ?? 0) }); + const rows = + promptTok > 0 || outTok > 0 + ? [ + { + text: t('steps.compactionSummaryRow', { + input: formatTokens(promptTok), + output: formatTokens(outTok), + }), + detail: t('steps.compactionDetailHint'), + mono: false, + danger: false, + }, + ] + : [ + { + text: t('steps.compactionDetailHint'), + detail: '', + danger: false, + }, + ]; + return { + title, + sub: disp.baseText || '', + rows, + hint: '', + severity: 'compaction', + }; +} + function buildModelAnomalyDiagnostic(m) { const sum = resolveModelAnomalySummary(m); if (!sum) return null; @@ -4444,7 +4506,7 @@ function buildDeterministicModelColorMap(models = []) { return colorMap; } -return { formatMetric, formatSpeedMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap }; +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/httpClient.js --- @@ -7057,6 +7119,7 @@ const CustomSelect = defineComponent({ setup({ getProps, setProps, emit, onCleanup }) { let isOpen = false; let focusedIndex = -1; + let lastOpenMenuLayoutSig = ''; const initialIcon = getProps().icon; const leadIcon = createSvgIcon(initialIcon || 'bolt', { size: 13 }); @@ -7135,6 +7198,15 @@ const CustomSelect = defineComponent({ } } + function buildMenuLayoutSig(options = [], labelText = '') { + let sig = `${labelText}|${options.length}`; + for (let i = 0; i < options.length; i++) { + const o = options[i]; + sig += `|${o?.value ?? ''}:${o?.label ?? ''}:${o?.meta ?? ''}`; + } + return sig; + } + function toggleOpen(nextOpen) { isOpen = Boolean(nextOpen); if (isOpen) { @@ -7145,6 +7217,9 @@ const CustomSelect = defineComponent({ opts.findIndex((o) => selSet.has(o.value)) ); renderMenuOptions(); + lastOpenMenuLayoutSig = buildMenuLayoutSig(opts, triggerLabel.textContent || ''); + } else { + lastOpenMenuLayoutSig = ''; } patchClasses(rootEl, { 'is-open': isOpen }); patchAttr(triggerBtn, 'aria-expanded', isOpen ? 'true' : 'false'); @@ -7344,7 +7419,11 @@ const CustomSelect = defineComponent({ patchAttr(triggerBtn, 'title', titleText); if (isOpen) { renderMenuOptions(); - positionMenu(); + const nextLayoutSig = buildMenuLayoutSig(options, labelText); + if (nextLayoutSig !== lastOpenMenuLayoutSig) { + lastOpenMenuLayoutSig = nextLayoutSig; + positionMenu(); + } } } @@ -8708,7 +8787,17 @@ function createTrendAreaChart() { const tipCallsEl = h('span', { className: 'trend-tip-calls text-mono' }); const tipTokensEl = h('strong', { className: 'trend-tip-tokens text-mono' }); const tipCostEl = h('span', { className: 'trend-tip-cost text-mono' }); - const tipSubEl = h('div', { className: 'trend-tip-sub text-mono', hidden: true }); + const tipInLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legInput') }); + const tipInValEl = h('span', { className: 'trend-tip-stat-val text-mono' }); + const tipCacheLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legCache') }); + const tipCacheValEl = h('span', { className: 'trend-tip-stat-val text-mono' }); + const tipOutLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legOutput') }); + const tipOutValEl = h('span', { className: 'trend-tip-stat-val text-mono' }); + const tipSubEl = h('div', { className: 'trend-tip-sub is-grid', hidden: true }, [ + h('div', { className: 'trend-tip-stat' }, [tipInLabelEl, tipInValEl]), + h('div', { className: 'trend-tip-stat' }, [tipCacheLabelEl, tipCacheValEl]), + h('div', { className: 'trend-tip-stat' }, [tipOutLabelEl, tipOutValEl]), + ]); const tipModelsEl = h('div', { className: 'cons-pop-models', hidden: true }); const tooltipEl = h( @@ -8839,14 +8928,12 @@ function createTrendAreaChart() { slot.outputTokens !== undefined); patchAttr(tipSubEl, 'hidden', !hasSubBreakdown); if (hasSubBreakdown) { - patchText( - tipSubEl, - t('chart.step.ioSplit', { - inTok: formatTokensPrecise(safeSlotTokens(slot.inputTokens)), - cacheTok: formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens)), - outTok: formatTokensPrecise(safeSlotTokens(slot.outputTokens)), - }) - ); + patchText(tipInLabelEl, t('cons.legInput')); + patchText(tipCacheLabelEl, t('cons.legCache')); + patchText(tipOutLabelEl, t('cons.legOutput')); + patchText(tipInValEl, formatTokensPrecise(safeSlotTokens(slot.inputTokens))); + patchText(tipCacheValEl, formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens))); + patchText(tipOutValEl, formatTokensPrecise(safeSlotTokens(slot.outputTokens))); } const modelSegs = Array.isArray(slot.modelSegments) ? slot.modelSegments : []; @@ -10251,11 +10338,23 @@ function createSessionLineChart() { const tipHeadRight = h('span', { className: 'trend-tip-calls text-mono' }); const tipMainLeft = h('strong', { className: 'trend-tip-tokens text-mono' }); const tipMainRight = h('span', { className: 'trend-tip-cost text-mono' }); + const tipInLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legInput') }); + const tipInValEl = h('span', { className: 'trend-tip-stat-val text-mono' }); + const tipCacheLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legCache') }); + const tipCacheValEl = h('span', { className: 'trend-tip-stat-val text-mono' }); + const tipOutLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legOutput') }); + const tipOutValEl = h('span', { className: 'trend-tip-stat-val text-mono' }); + const tipIoGrid = h('div', { className: 'trend-tip-sub is-grid', hidden: true }, [ + h('div', { className: 'trend-tip-stat' }, [tipInLabelEl, tipInValEl]), + h('div', { className: 'trend-tip-stat' }, [tipCacheLabelEl, tipCacheValEl]), + h('div', { className: 'trend-tip-stat' }, [tipOutLabelEl, tipOutValEl]), + ]); const tipSub = h('div', { className: 'trend-tip-sub text-mono', hidden: true }); const tipAnomaly = h('div', { className: 'trend-tip-anomaly text-mono', hidden: true }); const tooltipEl = h('div', { className: 'trend-tooltip', hidden: true }, [ h('div', { className: 'trend-tip-head' }, [tipHeadLeft, tipHeadRight]), h('div', { className: 'trend-tip-main' }, [tipMainLeft, tipMainRight]), + tipIoGrid, tipSub, tipAnomaly, ]); @@ -10332,8 +10431,18 @@ function createSessionLineChart() { pt.valid ? formatChartMetricValue(currentMetric, pt.value) : t('chart.step.excluded') ); patchText(tipMainRight, pt.secondaryRight || ''); - patchAttr(tipSub, 'hidden', !pt.subDetail); - if (pt.subDetail) { + const hasIoParts = Boolean(pt.ioParts); + patchAttr(tipIoGrid, 'hidden', !hasIoParts); + if (hasIoParts) { + patchText(tipInLabelEl, t('cons.legInput')); + patchText(tipCacheLabelEl, t('cons.legCache')); + patchText(tipOutLabelEl, t('cons.legOutput')); + patchText(tipInValEl, pt.ioParts.inTok); + patchText(tipCacheValEl, pt.ioParts.cacheTok); + patchText(tipOutValEl, pt.ioParts.outTok); + } + patchAttr(tipSub, 'hidden', hasIoParts || !pt.subDetail); + if (!hasIoParts && pt.subDetail) { patchText(tipSub, pt.subDetail); } patchAttr(tipAnomaly, 'hidden', !pt.anomalySummary); @@ -10576,15 +10685,17 @@ function createSessionLineChart() { let value = 0; let secondaryRight = ''; let subDetail = ''; + let ioParts = null; if (metric === 'totalTokens') { value = isMultiCompare ? modelCumTok : runningTokens; secondaryRight = t('chart.step.stepAdd', { tokens: formatTokens(stepTotalTok) }); - subDetail = t('chart.step.ioSplit', { + ioParts = { inTok: formatTokens(inTok), cacheTok: formatTokens(cacheTok), outTok: formatTokens(outTok), - }); + }; + subDetail = t('chart.step.ioSplit', ioParts); } else if (metric === 'context') { value = ctxTok; if (hasPrevCtx) { @@ -10667,6 +10778,7 @@ function createSessionLineChart() { value, secondaryRight, subDetail, + ioParts, anomalySummary, anomalySeverity: st.anomaly?.severity || '', }; @@ -14666,7 +14778,7 @@ return { OVERVIEW_WIDGET_KEYS, OVERVIEW_WIDGET_REGISTRY, getOverviewModuleOption })(); // --- src/registries/stepColumnRegistry.js --- -const { STEP_COLUMN_KEYS, DEFAULT_STEP_COLUMN_KEYS, formatCustomTokenComboHeader, STEP_COLUMN_REGISTRY, getStepColumnOptions } = (() => { +const { STEP_COLUMN_KEYS, DEFAULT_STEP_COLUMN_KEYS, formatCustomTokenComboHeader, isCompactionStepItem, STEP_COLUMN_REGISTRY, getStepColumnOptions } = (() => { /** * @fileoverview Decoupled Step Table Column Registry (`stepColumnRegistry.js`). * Defines all 12 customizable columns for `StepsDetailView` ("按步查看"), @@ -14761,6 +14873,13 @@ function formatStepClockTime(createdAtMs) { return { text: hhmmss, title: full }; } +function isCompactionStepItem(st) { + if (!st || typeof st !== 'object') return false; + if (st.isCompactionStep) return true; + const raw = `${st.activeModelShort ?? st.modelShort ?? ''} ${st.activeModelLabel ?? st.modelLabel ?? ''} ${st.activeModelUpstream ?? st.modelUpstream ?? ''}`; + return /·(?:压缩|compact)(?=\s|$)|\[自动压缩\]/iu.test(raw); +} + const STEP_COLUMN_REGISTRY = Object.freeze({ step: { key: 'step', @@ -14800,21 +14919,17 @@ const STEP_COLUMN_REGISTRY = Object.freeze({ optLabel: () => t('stepCol.model.opt'), sigPart: (st, ctx) => { const disp = resolveModelDisplayInfo(st, ctx.displaySettings, { fallback: '—' }); - return `${disp.baseText}:${disp.compactionSuffix}:${disp.title}`; + return `${disp.baseText}:${disp.title}`; }, createCell: () => { const nameEl = h('span', { className: 'step-model-name' }); - const compactEl = h('span', { className: 'step-model-compact', hidden: true }); - const wrapEl = h('span', { className: 'step-model-cell' }, [nameEl, compactEl]); + const wrapEl = h('span', { className: 'step-model-cell' }, [nameEl]); const td = h('td', {}, [wrapEl]); - return { td, refs: { td, wrapEl, nameEl, compactEl } }; + return { td, refs: { td, wrapEl, nameEl } }; }, updateCell: (refs, st, ctx) => { const modelDisplay = resolveModelDisplayInfo(st, ctx.displaySettings, { fallback: '—' }); patchText(refs.nameEl, modelDisplay.baseText); - const suffix = modelDisplay.compactionSuffix || ''; - patchText(refs.compactEl, suffix); - patchAttr(refs.compactEl, 'hidden', !suffix); patchAttr(refs.td, 'title', modelDisplay.title); }, }, @@ -15083,7 +15198,7 @@ function getStepColumnOptions( label: STEP_COLUMN_REGISTRY[key].optLabel(ctx), })); } -return { STEP_COLUMN_KEYS, DEFAULT_STEP_COLUMN_KEYS, formatCustomTokenComboHeader, STEP_COLUMN_REGISTRY, getStepColumnOptions }; +return { STEP_COLUMN_KEYS, DEFAULT_STEP_COLUMN_KEYS, formatCustomTokenComboHeader, isCompactionStepItem, STEP_COLUMN_REGISTRY, getStepColumnOptions }; })(); // --- src/components/widgets/CapsuleBarWidget.js --- @@ -15959,7 +16074,7 @@ function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) { let bestModelObj = firstStep; for (const cand of modelCandidates.values()) { const disp = resolveModelDisplayInfo(cand, cellCtx?.displaySettings, { fallback: '—' }); - const len = (disp.baseText?.length || 0) + (disp.compactionSuffix?.length || 0); + const len = disp.baseText?.length || 0; if (len > bestModelLen) { bestModelLen = len; bestModelObj = cand; @@ -16139,7 +16254,10 @@ const StepTableWidget = defineComponent({ return; } hideTurnTip(); - patchClasses(anomalyTipEl, { 'is-danger': diag.severity === 'danger' }); + patchClasses(anomalyTipEl, { + 'is-danger': diag.severity === 'danger', + 'is-compaction': diag.severity === 'compaction', + }); patchText(anomalyTipTitleEl, diag.title); patchAttr(anomalyTipSubEl, 'hidden', !diag.sub); if (diag.sub) patchText(anomalyTipSubEl, diag.sub); @@ -16157,7 +16275,10 @@ const StepTableWidget = defineComponent({ if (row.detail) { itemChildren.push( h('div', { - className: 'step-anomaly-tip-detail text-mono', + className: + row.mono === false + ? 'step-anomaly-tip-detail' + : 'step-anomaly-tip-detail text-mono', text: row.detail, }) ); @@ -16309,16 +16430,35 @@ const StepTableWidget = defineComponent({ if (event?.target === badge) hideTurnTip(); } + function buildStepRowDiagnostic(st, displaySettings, hasStepAnomaly, isCompactionRow) { + if (hasStepAnomaly) { + const diag = buildStepAnomalyDiagnostic(st); + if (diag && isCompactionRow) { + return { + ...diag, + hint: diag.hint + ? `${diag.hint} · ${t('steps.compactionAnomalyHint')}` + : t('steps.compactionAnomalyHint'), + }; + } + return diag; + } + if (isCompactionRow) { + return buildStepCompactionDiagnostic(st, displaySettings); + } + return null; + } + function moveAlongTurnRail(event) { - const { badge, prompt, anomalyStep } = hoverRows.get(this); + const { badge, prompt, rowDiagGetter } = hoverRows.get(this); const rect = this.getBoundingClientRect?.(); const relX = rect ? (event?.clientX ?? 0) - rect.left : 0; if (event?.target !== badge && relX <= 18) { showTurnTip(this, prompt); } else { hideTurnTip(); - if (anomalyStep) { - showAnomalyTip(this, buildStepAnomalyDiagnostic(anomalyStep)); + if (rowDiagGetter) { + showAnomalyTip(this, rowDiagGetter()); } } } @@ -16326,8 +16466,8 @@ const StepTableWidget = defineComponent({ function leaveStepCell(event) { const entry = hoverRows.get(this); hideTurnTip(); - if (entry?.anomalyStep && entry.tr && event?.relatedTarget && entry.tr.contains?.(event.relatedTarget)) { - showAnomalyTip(this, buildStepAnomalyDiagnostic(entry.anomalyStep)); + if (entry?.rowDiagGetter && entry.tr && event?.relatedTarget && entry.tr.contains?.(event.relatedTarget)) { + showAnomalyTip(this, entry.rowDiagGetter()); } } @@ -16621,7 +16761,8 @@ const StepTableWidget = defineComponent({ : ''; const stripeSig = isVirtualized ? (item.isStripeEven ? 'E' : 'O') : 'N'; const anomalySig = st.anomalySig || ''; - return `${locale}:${colOrderSig}:${stripeSig}:${badgeSig}:${anomalySig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`; + const compactSig = isCompactionStepItem(st) ? 'C' : ''; + return `${locale}:${colOrderSig}:${stripeSig}:${badgeSig}:${anomalySig}:${compactSig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`; }, createRow: (item) => { if (item.isSizer) { @@ -16866,14 +17007,20 @@ const StepTableWidget = defineComponent({ const hasStepAnomaly = Boolean(st?.anomaly && Number(st.anomaly.count) > 0); const isAnomalyDanger = Boolean(hasStepAnomaly && st.anomaly.severity === 'danger'); const isAnomalyWarn = Boolean(hasStepAnomaly && !isAnomalyDanger); + const isCompactionRow = isCompactionStepItem(st); + const hasRowTip = hasStepAnomaly || isCompactionRow; + const rowDiagGetter = hasRowTip + ? () => buildStepRowDiagnostic(st, cellCtx.displaySettings, hasStepAnomaly, isCompactionRow) + : null; patchClasses(tr, { + 'is-compaction': isCompactionRow, 'is-anomaly-warn': isAnomalyWarn, 'is-anomaly-danger': isAnomalyDanger, }); - if (hasStepAnomaly) { + if (hasRowTip) { const anchorEl = firstTd || tr; tr.onmouseenter = () => { - showAnomalyTip(anchorEl, buildStepAnomalyDiagnostic(st)); + showAnomalyTip(anchorEl, rowDiagGetter()); }; tr.onmouseleave = hideAnomalyTip; } else { @@ -16898,10 +17045,10 @@ const StepTableWidget = defineComponent({ hoverRows.set(hoverTd, { badge: refs.agentBadgeEl, prompt, - anomalyStep: hasStepAnomaly ? st : null, + rowDiagGetter, tr, }); - const useWholeCellTurnTip = firstColKey === 'step' && !hasStepAnomaly; + const useWholeCellTurnTip = firstColKey === 'step' && !hasRowTip; hoverTd.onmouseenter = useWholeCellTurnTip ? enterStepCell : null; hoverTd.onmousemove = useWholeCellTurnTip ? moveInStepCell : moveAlongTurnRail; hoverTd.onmouseleave = leaveStepCell; @@ -16929,6 +17076,7 @@ const StepTableWidget = defineComponent({ patchClasses(tr, { 'is-stripe-even': false, 'is-step-entering': false, + 'is-compaction': false, 'is-anomaly-warn': false, 'is-anomaly-danger': false, }); @@ -22080,12 +22228,11 @@ const ConsumptionView = defineComponent({ } /** - * 创建热门模型单行 DOM 结构(模型名称后附专属颜色圆点 + 按总占比缩放的 4 段比例条 + 底部分项脚标)。 + * 创建热门模型单行 DOM 结构(模型名称 + 按总占比缩放的 4 段比例条 + 底部分项脚标)。 */ function createBreakdownItemRow() { const nameTextEl = h('span', { className: 'cons-row-title-text' }); - const modelDotEl = h('span', { className: 'dot-swatch cons-model-dot cons-title-model-dot' }); - const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl, modelDotEl]); + const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl]); const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); const costEl = h('strong', { className: 'cons-row-cost text-mono' }); @@ -22146,7 +22293,6 @@ const ConsumptionView = defineComponent({ refs: { nameEl, nameTextEl, - modelDotEl, pctBadge, totalTokEl, costEl, @@ -22166,9 +22312,9 @@ const ConsumptionView = defineComponent({ } /** - * 增量更新热门模型单行的指标文本、名称后的专属颜色圆点与按总占比缩放的 4 段比例条宽度。 + * 增量更新热门模型单行的指标文本与按总占比缩放的 4 段比例条宽度。 */ - function updateBreakdownItemRow(refs, item, grandTotalTokens, modelColor = '') { + function updateBreakdownItemRow(refs, item, grandTotalTokens) { patchText(refs.inLbl, t('cons.footInput')); patchText(refs.cacheLbl, t('cons.footCache')); patchText(refs.outLbl, t('cons.footOutput')); @@ -22177,10 +22323,6 @@ const ConsumptionView = defineComponent({ const displayLabel = item.label || item.name || item.shortName || '—'; patchText(refs.nameTextEl, displayLabel); patchAttr(refs.nameEl, 'title', item.title || displayLabel); - patchAttr(refs.modelDotEl, 'hidden', !modelColor); - if (modelColor) { - patchStyleVar(refs.modelDotEl, '--dot-color', modelColor); - } const total = Number(item.totalTokens || 0); const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0; const scaleRatio = @@ -22663,23 +22805,17 @@ const ConsumptionView = defineComponent({ }); trendChart.update(enrichedTrendSeries); - // 3. 同步热门模型列表(名称后带专属颜色圆点 + 4 段条按总占比缩放长度) + // 3. 同步热门模型列表(4 段条按总占比缩放长度) patchKeyedList(modelsListEl, models, { keyFn: (m) => m.displayText || m.label || m.shortName, - sigFn: (m) => { - const seed = getCanonicalModelColorSeed(m); - const color = modelColorMap.get(seed) || resolveDeterministicModelColor(seed); - return `${localeSig}:${m.displayText}:${m.displayTitle}:${color}:${m.totalTokens}:${m.inputTokens}:${m.cacheReadTokens}:${m.responseTokens}:${m.thinkingTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`; - }, + sigFn: (m) => + `${localeSig}:${m.displayText}:${m.displayTitle}:${m.totalTokens}:${m.inputTokens}:${m.cacheReadTokens}:${m.responseTokens}:${m.thinkingTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`, createRow: createBreakdownItemRow, updateRow: (refs, m) => { - const seed = getCanonicalModelColorSeed(m); - const color = modelColorMap.get(seed) || resolveDeterministicModelColor(seed); updateBreakdownItemRow( refs, { ...m, label: m.displayText, title: m.displayTitle }, - modelsTotalTok, - color + modelsTotalTok ); }, }); @@ -23331,7 +23467,11 @@ const StepsDetailView = defineComponent({ }); modelsScroll.el.setAttribute('hidden', ''); - const panelTitleTextEl = h('span', { text: t('steps.title') }); + const headerFiltersEl = h('div', { className: 'steps-header-filters', hidden: true }, [ + inlineScopeSelect.el, + stepsModelSelect.el, + ]); + const panelEl = h( 'section', { @@ -23340,14 +23480,9 @@ const StepsDetailView = defineComponent({ }, [ h('div', { className: 'panel-header steps-panel-header' }, [ - h('span', { className: 'panel-title steps-panel-title' }, [ - createSvgIcon('table', { size: 13 }), - panelTitleTextEl, - ]), h('div', { className: 'steps-header-controls' }, [ - inlineScopeSelect.el, - stepsModelSelect.el, subTabSwitch.el, + headerFiltersEl, ]), ]), anomalyFilterBarEl, @@ -23420,7 +23555,6 @@ const StepsDetailView = defineComponent({ } function refreshStaticLocaleLabels() { - patchText(panelTitleTextEl, t('steps.title')); patchText(lineTitleEl, t('steps.lineTitle')); patchText(fitTitleEl, t('steps.fitTitle')); patchText(modelsSectionTitleEl, t('steps.modelsTitle')); @@ -23640,6 +23774,7 @@ const StepsDetailView = defineComponent({ ); const showStepsModelFilter = uiSt.stepsSubTab === 'steps' && hasMultipleModels; patchAttr(stepsModelSelect.el, 'hidden', !showStepsModelFilter); + patchAttr(headerFiltersEl, 'hidden', !hasSubagents && !showStepsModelFilter); if (hasMultipleModels) { stepsModelSelect.setProps({ modelValue: selectedTableModels, diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 5f0132e..a9b704c 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 733bad3..232ec07 100644 --- a/sidecars/panel/src/components/charts/SessionStepCharts.js +++ b/sidecars/panel/src/components/charts/SessionStepCharts.js @@ -782,11 +782,23 @@ export function createSessionLineChart() { const tipHeadRight = h('span', { className: 'trend-tip-calls text-mono' }); const tipMainLeft = h('strong', { className: 'trend-tip-tokens text-mono' }); const tipMainRight = h('span', { className: 'trend-tip-cost text-mono' }); + const tipInLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legInput') }); + const tipInValEl = h('span', { className: 'trend-tip-stat-val text-mono' }); + const tipCacheLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legCache') }); + const tipCacheValEl = h('span', { className: 'trend-tip-stat-val text-mono' }); + const tipOutLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legOutput') }); + const tipOutValEl = h('span', { className: 'trend-tip-stat-val text-mono' }); + const tipIoGrid = h('div', { className: 'trend-tip-sub is-grid', hidden: true }, [ + h('div', { className: 'trend-tip-stat' }, [tipInLabelEl, tipInValEl]), + h('div', { className: 'trend-tip-stat' }, [tipCacheLabelEl, tipCacheValEl]), + h('div', { className: 'trend-tip-stat' }, [tipOutLabelEl, tipOutValEl]), + ]); const tipSub = h('div', { className: 'trend-tip-sub text-mono', hidden: true }); const tipAnomaly = h('div', { className: 'trend-tip-anomaly text-mono', hidden: true }); const tooltipEl = h('div', { className: 'trend-tooltip', hidden: true }, [ h('div', { className: 'trend-tip-head' }, [tipHeadLeft, tipHeadRight]), h('div', { className: 'trend-tip-main' }, [tipMainLeft, tipMainRight]), + tipIoGrid, tipSub, tipAnomaly, ]); @@ -863,8 +875,18 @@ export function createSessionLineChart() { pt.valid ? formatChartMetricValue(currentMetric, pt.value) : t('chart.step.excluded') ); patchText(tipMainRight, pt.secondaryRight || ''); - patchAttr(tipSub, 'hidden', !pt.subDetail); - if (pt.subDetail) { + const hasIoParts = Boolean(pt.ioParts); + patchAttr(tipIoGrid, 'hidden', !hasIoParts); + if (hasIoParts) { + patchText(tipInLabelEl, t('cons.legInput')); + patchText(tipCacheLabelEl, t('cons.legCache')); + patchText(tipOutLabelEl, t('cons.legOutput')); + patchText(tipInValEl, pt.ioParts.inTok); + patchText(tipCacheValEl, pt.ioParts.cacheTok); + patchText(tipOutValEl, pt.ioParts.outTok); + } + patchAttr(tipSub, 'hidden', hasIoParts || !pt.subDetail); + if (!hasIoParts && pt.subDetail) { patchText(tipSub, pt.subDetail); } patchAttr(tipAnomaly, 'hidden', !pt.anomalySummary); @@ -1107,15 +1129,17 @@ export function createSessionLineChart() { let value = 0; let secondaryRight = ''; let subDetail = ''; + let ioParts = null; if (metric === 'totalTokens') { value = isMultiCompare ? modelCumTok : runningTokens; secondaryRight = t('chart.step.stepAdd', { tokens: formatTokens(stepTotalTok) }); - subDetail = t('chart.step.ioSplit', { + ioParts = { inTok: formatTokens(inTok), cacheTok: formatTokens(cacheTok), outTok: formatTokens(outTok), - }); + }; + subDetail = t('chart.step.ioSplit', ioParts); } else if (metric === 'context') { value = ctxTok; if (hasPrevCtx) { @@ -1198,6 +1222,7 @@ export function createSessionLineChart() { value, secondaryRight, subDetail, + ioParts, anomalySummary, anomalySeverity: st.anomaly?.severity || '', }; diff --git a/sidecars/panel/src/components/charts/TrendAreaChart.js b/sidecars/panel/src/components/charts/TrendAreaChart.js index aced2d2..eed3382 100644 --- a/sidecars/panel/src/components/charts/TrendAreaChart.js +++ b/sidecars/panel/src/components/charts/TrendAreaChart.js @@ -324,7 +324,17 @@ export function createTrendAreaChart() { const tipCallsEl = h('span', { className: 'trend-tip-calls text-mono' }); const tipTokensEl = h('strong', { className: 'trend-tip-tokens text-mono' }); const tipCostEl = h('span', { className: 'trend-tip-cost text-mono' }); - const tipSubEl = h('div', { className: 'trend-tip-sub text-mono', hidden: true }); + const tipInLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legInput') }); + const tipInValEl = h('span', { className: 'trend-tip-stat-val text-mono' }); + const tipCacheLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legCache') }); + const tipCacheValEl = h('span', { className: 'trend-tip-stat-val text-mono' }); + const tipOutLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legOutput') }); + const tipOutValEl = h('span', { className: 'trend-tip-stat-val text-mono' }); + const tipSubEl = h('div', { className: 'trend-tip-sub is-grid', hidden: true }, [ + h('div', { className: 'trend-tip-stat' }, [tipInLabelEl, tipInValEl]), + h('div', { className: 'trend-tip-stat' }, [tipCacheLabelEl, tipCacheValEl]), + h('div', { className: 'trend-tip-stat' }, [tipOutLabelEl, tipOutValEl]), + ]); const tipModelsEl = h('div', { className: 'cons-pop-models', hidden: true }); const tooltipEl = h( @@ -455,14 +465,12 @@ export function createTrendAreaChart() { slot.outputTokens !== undefined); patchAttr(tipSubEl, 'hidden', !hasSubBreakdown); if (hasSubBreakdown) { - patchText( - tipSubEl, - t('chart.step.ioSplit', { - inTok: formatTokensPrecise(safeSlotTokens(slot.inputTokens)), - cacheTok: formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens)), - outTok: formatTokensPrecise(safeSlotTokens(slot.outputTokens)), - }) - ); + patchText(tipInLabelEl, t('cons.legInput')); + patchText(tipCacheLabelEl, t('cons.legCache')); + patchText(tipOutLabelEl, t('cons.legOutput')); + patchText(tipInValEl, formatTokensPrecise(safeSlotTokens(slot.inputTokens))); + patchText(tipCacheValEl, formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens))); + patchText(tipOutValEl, formatTokensPrecise(safeSlotTokens(slot.outputTokens))); } const modelSegs = Array.isArray(slot.modelSegments) ? slot.modelSegments : []; diff --git a/sidecars/panel/src/components/ui/CustomSelect.js b/sidecars/panel/src/components/ui/CustomSelect.js index 377e588..0b0f2d3 100644 --- a/sidecars/panel/src/components/ui/CustomSelect.js +++ b/sidecars/panel/src/components/ui/CustomSelect.js @@ -56,6 +56,7 @@ export const CustomSelect = defineComponent({ setup({ getProps, setProps, emit, onCleanup }) { let isOpen = false; let focusedIndex = -1; + let lastOpenMenuLayoutSig = ''; const initialIcon = getProps().icon; const leadIcon = createSvgIcon(initialIcon || 'bolt', { size: 13 }); @@ -134,6 +135,15 @@ export const CustomSelect = defineComponent({ } } + function buildMenuLayoutSig(options = [], labelText = '') { + let sig = `${labelText}|${options.length}`; + for (let i = 0; i < options.length; i++) { + const o = options[i]; + sig += `|${o?.value ?? ''}:${o?.label ?? ''}:${o?.meta ?? ''}`; + } + return sig; + } + function toggleOpen(nextOpen) { isOpen = Boolean(nextOpen); if (isOpen) { @@ -144,6 +154,9 @@ export const CustomSelect = defineComponent({ opts.findIndex((o) => selSet.has(o.value)) ); renderMenuOptions(); + lastOpenMenuLayoutSig = buildMenuLayoutSig(opts, triggerLabel.textContent || ''); + } else { + lastOpenMenuLayoutSig = ''; } patchClasses(rootEl, { 'is-open': isOpen }); patchAttr(triggerBtn, 'aria-expanded', isOpen ? 'true' : 'false'); @@ -343,7 +356,11 @@ export const CustomSelect = defineComponent({ patchAttr(triggerBtn, 'title', titleText); if (isOpen) { renderMenuOptions(); - positionMenu(); + const nextLayoutSig = buildMenuLayoutSig(options, labelText); + if (nextLayoutSig !== lastOpenMenuLayoutSig) { + lastOpenMenuLayoutSig = nextLayoutSig; + positionMenu(); + } } } diff --git a/sidecars/panel/src/components/widgets/StepTableWidget.js b/sidecars/panel/src/components/widgets/StepTableWidget.js index 52e764c..d477030 100644 --- a/sidecars/panel/src/components/widgets/StepTableWidget.js +++ b/sidecars/panel/src/components/widgets/StepTableWidget.js @@ -15,6 +15,7 @@ import { } from '../../core/domPatch.js'; import { buildStepAnomalyDiagnostic, + buildStepCompactionDiagnostic, resolveModelDisplayInfo, speedReasonText, } from '../../core/formatters.js'; @@ -22,6 +23,7 @@ import { getEffectiveLocale, t } from '../../i18n/index.js'; import { DEFAULT_STEP_COLUMN_KEYS, STEP_COLUMN_REGISTRY, + isCompactionStepItem, } from '../../registries/stepColumnRegistry.js'; import { formatAgentBadgeText, @@ -329,7 +331,7 @@ function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) { let bestModelObj = firstStep; for (const cand of modelCandidates.values()) { const disp = resolveModelDisplayInfo(cand, cellCtx?.displaySettings, { fallback: '—' }); - const len = (disp.baseText?.length || 0) + (disp.compactionSuffix?.length || 0); + const len = disp.baseText?.length || 0; if (len > bestModelLen) { bestModelLen = len; bestModelObj = cand; @@ -509,7 +511,10 @@ export const StepTableWidget = defineComponent({ return; } hideTurnTip(); - patchClasses(anomalyTipEl, { 'is-danger': diag.severity === 'danger' }); + patchClasses(anomalyTipEl, { + 'is-danger': diag.severity === 'danger', + 'is-compaction': diag.severity === 'compaction', + }); patchText(anomalyTipTitleEl, diag.title); patchAttr(anomalyTipSubEl, 'hidden', !diag.sub); if (diag.sub) patchText(anomalyTipSubEl, diag.sub); @@ -527,7 +532,10 @@ export const StepTableWidget = defineComponent({ if (row.detail) { itemChildren.push( h('div', { - className: 'step-anomaly-tip-detail text-mono', + className: + row.mono === false + ? 'step-anomaly-tip-detail' + : 'step-anomaly-tip-detail text-mono', text: row.detail, }) ); @@ -679,16 +687,35 @@ export const StepTableWidget = defineComponent({ if (event?.target === badge) hideTurnTip(); } + function buildStepRowDiagnostic(st, displaySettings, hasStepAnomaly, isCompactionRow) { + if (hasStepAnomaly) { + const diag = buildStepAnomalyDiagnostic(st); + if (diag && isCompactionRow) { + return { + ...diag, + hint: diag.hint + ? `${diag.hint} · ${t('steps.compactionAnomalyHint')}` + : t('steps.compactionAnomalyHint'), + }; + } + return diag; + } + if (isCompactionRow) { + return buildStepCompactionDiagnostic(st, displaySettings); + } + return null; + } + function moveAlongTurnRail(event) { - const { badge, prompt, anomalyStep } = hoverRows.get(this); + const { badge, prompt, rowDiagGetter } = hoverRows.get(this); const rect = this.getBoundingClientRect?.(); const relX = rect ? (event?.clientX ?? 0) - rect.left : 0; if (event?.target !== badge && relX <= 18) { showTurnTip(this, prompt); } else { hideTurnTip(); - if (anomalyStep) { - showAnomalyTip(this, buildStepAnomalyDiagnostic(anomalyStep)); + if (rowDiagGetter) { + showAnomalyTip(this, rowDiagGetter()); } } } @@ -696,8 +723,8 @@ export const StepTableWidget = defineComponent({ function leaveStepCell(event) { const entry = hoverRows.get(this); hideTurnTip(); - if (entry?.anomalyStep && entry.tr && event?.relatedTarget && entry.tr.contains?.(event.relatedTarget)) { - showAnomalyTip(this, buildStepAnomalyDiagnostic(entry.anomalyStep)); + if (entry?.rowDiagGetter && entry.tr && event?.relatedTarget && entry.tr.contains?.(event.relatedTarget)) { + showAnomalyTip(this, entry.rowDiagGetter()); } } @@ -991,7 +1018,8 @@ export const StepTableWidget = defineComponent({ : ''; const stripeSig = isVirtualized ? (item.isStripeEven ? 'E' : 'O') : 'N'; const anomalySig = st.anomalySig || ''; - return `${locale}:${colOrderSig}:${stripeSig}:${badgeSig}:${anomalySig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`; + const compactSig = isCompactionStepItem(st) ? 'C' : ''; + return `${locale}:${colOrderSig}:${stripeSig}:${badgeSig}:${anomalySig}:${compactSig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`; }, createRow: (item) => { if (item.isSizer) { @@ -1236,14 +1264,20 @@ export const StepTableWidget = defineComponent({ const hasStepAnomaly = Boolean(st?.anomaly && Number(st.anomaly.count) > 0); const isAnomalyDanger = Boolean(hasStepAnomaly && st.anomaly.severity === 'danger'); const isAnomalyWarn = Boolean(hasStepAnomaly && !isAnomalyDanger); + const isCompactionRow = isCompactionStepItem(st); + const hasRowTip = hasStepAnomaly || isCompactionRow; + const rowDiagGetter = hasRowTip + ? () => buildStepRowDiagnostic(st, cellCtx.displaySettings, hasStepAnomaly, isCompactionRow) + : null; patchClasses(tr, { + 'is-compaction': isCompactionRow, 'is-anomaly-warn': isAnomalyWarn, 'is-anomaly-danger': isAnomalyDanger, }); - if (hasStepAnomaly) { + if (hasRowTip) { const anchorEl = firstTd || tr; tr.onmouseenter = () => { - showAnomalyTip(anchorEl, buildStepAnomalyDiagnostic(st)); + showAnomalyTip(anchorEl, rowDiagGetter()); }; tr.onmouseleave = hideAnomalyTip; } else { @@ -1268,10 +1302,10 @@ export const StepTableWidget = defineComponent({ hoverRows.set(hoverTd, { badge: refs.agentBadgeEl, prompt, - anomalyStep: hasStepAnomaly ? st : null, + rowDiagGetter, tr, }); - const useWholeCellTurnTip = firstColKey === 'step' && !hasStepAnomaly; + const useWholeCellTurnTip = firstColKey === 'step' && !hasRowTip; hoverTd.onmouseenter = useWholeCellTurnTip ? enterStepCell : null; hoverTd.onmousemove = useWholeCellTurnTip ? moveInStepCell : moveAlongTurnRail; hoverTd.onmouseleave = leaveStepCell; @@ -1299,6 +1333,7 @@ export const StepTableWidget = defineComponent({ patchClasses(tr, { 'is-stripe-even': false, 'is-step-entering': false, + 'is-compaction': false, 'is-anomaly-warn': false, 'is-anomaly-danger': false, }); diff --git a/sidecars/panel/src/core/domPatch.js b/sidecars/panel/src/core/domPatch.js index e55705d..3500812 100644 --- a/sidecars/panel/src/core/domPatch.js +++ b/sidecars/panel/src/core/domPatch.js @@ -322,7 +322,22 @@ export function positionAnchoredPopup( popupEl.style.maxHeight = ''; const availWidth = Math.max(120, Math.floor(bound.width - margin * 2)); - popupEl.style.maxWidth = `${availWidth}px`; + let cssMaxW = NaN; + if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') { + try { + const rawMaxW = window.getComputedStyle(popupEl)?.maxWidth; + if (rawMaxW && rawMaxW !== 'none') { + cssMaxW = Number.parseFloat(rawMaxW); + } + } catch { + // 忽略 Mock DOM 样式查询异常 + } + } + const effectiveMaxW = + Number.isFinite(cssMaxW) && cssMaxW > 0 + ? Math.max(120, Math.min(availWidth, Math.floor(cssMaxW))) + : availWidth; + popupEl.style.maxWidth = `${effectiveMaxW}px`; const rawRect = popupEl.getBoundingClientRect?.(); // 优先读取 offsetWidth,避免入场动画 scale(0.975) 导致测宽偏小 @@ -330,10 +345,13 @@ export function positionAnchoredPopup( Number(popupEl.offsetWidth || 0), Math.ceil(Number(rawRect?.width || 0)) ); - if (naturalW > availWidth) { + if (naturalW > effectiveMaxW) { popupEl.style.minWidth = '0px'; } - const popupW = Math.min(availWidth, naturalW > 0 ? naturalW : Math.max(triggerRect.width, 210)); + const popupW = Math.min( + effectiveMaxW, + naturalW > 0 ? naturalW : Math.max(triggerRect.width, 210) + ); const safeLeft = bound.left + margin; const safeRight = bound.right - margin; diff --git a/sidecars/panel/src/core/formatters.js b/sidecars/panel/src/core/formatters.js index f0fec3d..8fb7143 100644 --- a/sidecars/panel/src/core/formatters.js +++ b/sidecars/panel/src/core/formatters.js @@ -222,6 +222,42 @@ export function buildStepAnomalyDiagnostic(st) { }; } +export function buildStepCompactionDiagnostic(st, displaySettings = {}) { + if (!st || typeof st !== 'object') return null; + const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: '' }); + const promptTok = + Math.max(0, Number(st.inputTokens || 0)) + Math.max(0, Number(st.cacheReadTokens || 0)); + const outTok = Math.max(0, Number(st.outputTokens || 0)); + const title = t('steps.compactionStepTitle', { step: Number(st.stepIndex ?? 0) }); + const rows = + promptTok > 0 || outTok > 0 + ? [ + { + text: t('steps.compactionSummaryRow', { + input: formatTokens(promptTok), + output: formatTokens(outTok), + }), + detail: t('steps.compactionDetailHint'), + mono: false, + danger: false, + }, + ] + : [ + { + text: t('steps.compactionDetailHint'), + detail: '', + danger: false, + }, + ]; + return { + title, + sub: disp.baseText || '', + rows, + hint: '', + severity: 'compaction', + }; +} + export function buildModelAnomalyDiagnostic(m) { const sum = resolveModelAnomalySummary(m); if (!sum) return null; diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 039ffa0..822b2ac 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -325,6 +325,10 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'steps.anomalyKind.canceled': 'Canceled by User', 'steps.anomalyStepTitle': '#{step} · {count} Retries / Errors', 'steps.anomalyDelayPart': 'Backoff {sec}s', + 'steps.compactionStepTitle': '#{step} · Auto-Compaction', + 'steps.compactionSummaryRow': 'Input {input} → Summary {output}', + 'steps.compactionDetailHint': 'Automatic context compaction step triggered to summarize history and free window space', + 'steps.compactionAnomalyHint': 'This step is also an auto-compaction step', 'steps.anomalyTerminalTag': 'Stopped', 'steps.anomalyModelTitle': '{model} · {count} Retries / Errors', 'steps.anomalyModelSub': '{steps} steps affected', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 018a047..b2bcac0 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -325,6 +325,10 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'steps.anomalyKind.canceled': '用户取消', 'steps.anomalyStepTitle': '#{step} · 异常 {count} 次', 'steps.anomalyDelayPart': '退避 {sec}s', + 'steps.compactionStepTitle': '#{step} · 自动压缩', + 'steps.compactionSummaryRow': '输入 {input} → 摘要输出 {output}', + 'steps.compactionDetailHint': '系统自动触发的上下文压缩步骤,用于折叠历史对话以释放窗口空间', + 'steps.compactionAnomalyHint': '该步骤同时为系统自动压缩步骤', 'steps.anomalyTerminalTag': '中止', 'steps.anomalyModelTitle': '{model} · 异常 {count} 次', 'steps.anomalyModelSub': '涉及 {steps} 步', diff --git a/sidecars/panel/src/registries/stepColumnRegistry.js b/sidecars/panel/src/registries/stepColumnRegistry.js index 3ca858f..982f4ea 100644 --- a/sidecars/panel/src/registries/stepColumnRegistry.js +++ b/sidecars/panel/src/registries/stepColumnRegistry.js @@ -114,6 +114,13 @@ function formatStepClockTime(createdAtMs) { return { text: hhmmss, title: full }; } +export function isCompactionStepItem(st) { + if (!st || typeof st !== 'object') return false; + if (st.isCompactionStep) return true; + const raw = `${st.activeModelShort ?? st.modelShort ?? ''} ${st.activeModelLabel ?? st.modelLabel ?? ''} ${st.activeModelUpstream ?? st.modelUpstream ?? ''}`; + return /·(?:压缩|compact)(?=\s|$)|\[自动压缩\]/iu.test(raw); +} + export const STEP_COLUMN_REGISTRY = Object.freeze({ step: { key: 'step', @@ -153,21 +160,17 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({ optLabel: () => t('stepCol.model.opt'), sigPart: (st, ctx) => { const disp = resolveModelDisplayInfo(st, ctx.displaySettings, { fallback: '—' }); - return `${disp.baseText}:${disp.compactionSuffix}:${disp.title}`; + return `${disp.baseText}:${disp.title}`; }, createCell: () => { const nameEl = h('span', { className: 'step-model-name' }); - const compactEl = h('span', { className: 'step-model-compact', hidden: true }); - const wrapEl = h('span', { className: 'step-model-cell' }, [nameEl, compactEl]); + const wrapEl = h('span', { className: 'step-model-cell' }, [nameEl]); const td = h('td', {}, [wrapEl]); - return { td, refs: { td, wrapEl, nameEl, compactEl } }; + return { td, refs: { td, wrapEl, nameEl } }; }, updateCell: (refs, st, ctx) => { const modelDisplay = resolveModelDisplayInfo(st, ctx.displaySettings, { fallback: '—' }); patchText(refs.nameEl, modelDisplay.baseText); - const suffix = modelDisplay.compactionSuffix || ''; - patchText(refs.compactEl, suffix); - patchAttr(refs.compactEl, 'hidden', !suffix); patchAttr(refs.td, 'title', modelDisplay.title); }, }, diff --git a/sidecars/panel/src/styles/controls.css b/sidecars/panel/src/styles/controls.css index 58d8948..345c4c5 100644 --- a/sidecars/panel/src/styles/controls.css +++ b/sidecars/panel/src/styles/controls.css @@ -31,8 +31,8 @@ .steps-inline-scope-select .select-menu, .steps-inline-model-select .select-menu { - left: 0; - right: auto; + left: auto; + right: 0; min-width: 220px; max-width: min(320px, calc(100vw - 24px)); } @@ -306,7 +306,15 @@ font-size: var(--fs-base); cursor: pointer; text-align: left; - transition: background-color var(--dur-instant) var(--ease-fast); + transition: + background-color var(--dur-instant) var(--ease-fast), + border-color var(--dur-instant) var(--ease-fast), + box-shadow var(--dur-instant) var(--ease-fast); +} + +.select-trigger .svg-icon { + flex-shrink: 0; + color: var(--text-muted); } .select-trigger:hover, @@ -314,6 +322,27 @@ background: var(--surface-hover); } +.form-row > .custom-select > .select-trigger { + min-height: calc(28px * var(--ui-font-scale, 1)); + padding: 3px 12px; + background: color-mix(in srgb, var(--text-primary) 7.5%, var(--surface-panel)); + border: none; + border-radius: var(--radius-pill); +} + +.form-row > .custom-select > .select-trigger:hover { + background: color-mix(in srgb, var(--text-primary) 11.5%, var(--surface-panel)); +} + +.form-row > .custom-select.is-open > .select-trigger { + background: color-mix(in srgb, var(--text-primary) 14%, var(--surface-panel)); +} + +.form-row > .custom-select > .select-trigger:disabled { + opacity: 0.52; + cursor: not-allowed; +} + .select-label { flex: 1; min-width: 0; diff --git a/sidecars/panel/src/styles/modern-ui.css b/sidecars/panel/src/styles/modern-ui.css index e759bb1..38264af 100644 --- a/sidecars/panel/src/styles/modern-ui.css +++ b/sidecars/panel/src/styles/modern-ui.css @@ -21,6 +21,9 @@ --modern-surface-card: color-mix(in srgb, var(--surface-panel) 95.2%, #ffffff 4.8%); --modern-surface-subtle: color-mix(in srgb, var(--text-primary) 5.2%, transparent); --modern-surface-hover: color-mix(in srgb, var(--accent-primary) 11%, color-mix(in srgb, var(--text-primary) 4%, transparent)); + --modern-pill-select-bg: color-mix(in srgb, var(--text-primary) 8.5%, var(--modern-surface-card)); + --modern-pill-select-hover: color-mix(in srgb, var(--text-primary) 12.5%, var(--modern-surface-card)); + --modern-pill-select-open: color-mix(in srgb, var(--text-primary) 15%, var(--modern-surface-card)); --modern-card-shadow: none; --modern-nav-track-bg: var(--modern-surface-card); --modern-inline-track-bg: color-mix(in srgb, var(--text-primary) 4.2%, transparent); @@ -42,6 +45,9 @@ --modern-surface-card: #ffffff; --modern-surface-subtle: hsl(216 42% 97.2%); --modern-surface-hover: hsl(216 56% 94.4%); + --modern-pill-select-bg: hsl(220 14% 94%); + --modern-pill-select-hover: hsl(220 14% 90.5%); + --modern-pill-select-open: hsl(220 14% 88.5%); --modern-card-shadow: 0 1px 3px rgb(15 23 42 / 0.045), 0 4px 14px rgb(15 23 42 / 0.028); --modern-nav-track-bg: hsl(216 28% 94.2%); --modern-inline-track-bg: hsl(216 32% 96.2%); @@ -463,11 +469,16 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { border: none; } -[data-modern-ui="true"] .trend-tip-sub, -[data-modern-ui="true"] .trend-tip-anomaly, +[data-modern-ui="true"] .trend-tip-sub { + background: var(--modern-surface-subtle); +} + +[data-modern-ui="true"] .trend-tip-cost { + background: var(--modern-surface-subtle); +} + [data-modern-ui="true"] .cons-pop-models { - border-top: none; - padding-top: 3px; + border-top-color: var(--modern-surface-hover); } [data-modern-ui="true"] .cons-source-bar-hit:hover .cons-source-model-bar, @@ -525,6 +536,17 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { background: var(--modern-surface-hover); } +[data-modern-ui="true"] .data-table tbody tr.is-compaction, +[data-modern-ui="true"] .data-table:not(.is-virtualized) tbody tr.is-compaction:nth-child(even), +[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-compaction { + background: color-mix(in srgb, var(--accent-primary) 12%, transparent); +} + +[data-modern-ui="true"] .data-table tbody tr.is-compaction:hover, +[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-compaction:hover { + background: color-mix(in srgb, var(--accent-primary) 19%, transparent); +} + [data-modern-ui="true"] .data-table tbody tr.is-anomaly-warn, [data-modern-ui="true"] .data-table:not(.is-virtualized) tbody tr.is-anomaly-warn:nth-child(even), [data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-warn { @@ -547,11 +569,28 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { background: color-mix(in srgb, var(--metric-danger) 21%, transparent); } +[data-modern-ui="true"] .form-row > .custom-select > .select-trigger, [data-modern-ui="true"] .steps-inline-scope-select .select-trigger, [data-modern-ui="true"] .steps-inline-model-select .select-trigger, [data-modern-ui="true"] .sstep-fit-model-select .select-trigger { border: none; - background: var(--modern-surface-subtle); + box-shadow: none; + border-radius: var(--radius-pill); + background: var(--modern-pill-select-bg); +} + +[data-modern-ui="true"] .form-row > .custom-select > .select-trigger:hover, +[data-modern-ui="true"] .steps-inline-scope-select .select-trigger:hover, +[data-modern-ui="true"] .steps-inline-model-select .select-trigger:hover, +[data-modern-ui="true"] .sstep-fit-model-select .select-trigger:hover { + background: var(--modern-pill-select-hover); +} + +[data-modern-ui="true"] .form-row > .custom-select.is-open > .select-trigger, +[data-modern-ui="true"] .steps-inline-scope-select.is-open .select-trigger, +[data-modern-ui="true"] .steps-inline-model-select.is-open .select-trigger, +[data-modern-ui="true"] .sstep-fit-model-select.is-open .select-trigger { + background: var(--modern-pill-select-open); } [data-modern-ui="true"] .sstep-card, @@ -667,12 +706,12 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { border: none; background: var(--modern-surface-card); box-shadow: var(--shadow-popover); - animation: anim-modern-pop-in 150ms var(--ease-modern); + animation: anim-modern-tip-fade 120ms var(--ease-modern); } [data-modern-ui="true"] .select-menu.is-above, [data-modern-ui="true"] .dt-popover.is-above { - animation-name: anim-modern-pop-in-up; + transform-origin: bottom right; } [data-modern-ui="true"] .trend-tooltip, diff --git a/sidecars/panel/src/styles/views-consumption.css b/sidecars/panel/src/styles/views-consumption.css index 3e99a2b..5deb3f2 100644 --- a/sidecars/panel/src/styles/views-consumption.css +++ b/sidecars/panel/src/styles/views-consumption.css @@ -211,12 +211,6 @@ white-space: nowrap; } -.cons-title-model-dot { - width: 7px; - height: 7px; - flex-shrink: 0; -} - .cons-row-metrics { display: inline-flex; align-items: center; @@ -349,9 +343,9 @@ left: var(--tip-x, 50%); transform: translateX(var(--tip-shift, -50%)); width: max-content; - min-width: 196px; - max-width: min(320px, calc(100% - 8px)); - padding: 6px 10px; + min-width: 224px; + max-width: min(316px, calc(100% - 8px)); + padding: 9px 11px; background: var(--surface-panel); border: 1px solid var(--border-strong); border-radius: var(--radius-sm); @@ -360,27 +354,29 @@ z-index: 25; display: flex; flex-direction: column; - gap: 2px; + gap: 6px; } .trend-tip-head { display: flex; align-items: center; justify-content: space-between; - gap: 10px; - font-size: var(--fs-sm); + gap: 12px; + font-size: var(--fs-xs); + line-height: 1.25; color: var(--text-secondary); } .trend-tip-time { - font-weight: 600; - color: var(--text-primary); + font-weight: 500; + color: var(--text-secondary); white-space: nowrap; flex-shrink: 0; } .trend-tip-calls { font-size: var(--fs-xs); + font-weight: 500; color: var(--text-muted); white-space: nowrap; max-width: 190px; @@ -390,36 +386,85 @@ .trend-tip-main { display: flex; - align-items: baseline; + align-items: center; justify-content: space-between; - gap: 12px; + gap: 10px; + margin-top: -2px; } .trend-tip-tokens { - font-size: var(--fs-base); + font-size: var(--fs-lg); font-weight: 700; + line-height: 1.18; + letter-spacing: -0.02em; color: var(--accent-primary); white-space: nowrap; flex-shrink: 0; } .trend-tip-cost { - font-size: var(--fs-md); + font-size: var(--fs-sm); font-weight: 600; + line-height: 1.2; + padding: 2px 7px; + border-radius: var(--radius-xs); color: var(--text-primary); + background: color-mix(in srgb, var(--text-primary) 6%, transparent); white-space: nowrap; flex-shrink: 0; } +.trend-tip-cost:empty { + display: none; +} + .trend-tip-sub { + padding: 5px 8px; + border: none; + border-radius: var(--radius-xs); + background: color-mix(in srgb, var(--text-primary) 4.2%, transparent); font-size: var(--fs-xs); + line-height: 1.3; color: var(--text-secondary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; - border-top: 1px solid var(--border-hairline); - padding-top: 2px; - margin-top: 1px; +} + +.trend-tip-sub[hidden] { + display: none !important; +} + +.trend-tip-sub.is-grid { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 8px; + padding: 6px 8px; + white-space: normal; + overflow: visible; +} + +.trend-tip-stat { + display: flex; + flex-direction: column; + gap: 1px; + min-width: 0; +} + +.trend-tip-stat-label { + font-size: var(--fs-2xs); + font-weight: 500; + line-height: 1.2; + color: var(--text-muted); + white-space: nowrap; +} + +.trend-tip-stat-val { + font-size: var(--fs-sm); + font-weight: 600; + line-height: 1.25; + color: var(--text-primary); + white-space: nowrap; } .trend-tooltip.is-line-low { @@ -807,9 +852,9 @@ left: var(--pop-x, 8px); top: var(--pop-y, 8px); width: max-content; - min-width: 196px; - max-width: min(310px, calc(100% - 16px)); - padding: 6px 10px; + min-width: 224px; + max-width: min(316px, calc(100% - 16px)); + padding: 9px 11px; background: var(--surface-panel); border: 1px solid var(--border-strong); border-radius: var(--radius-sm); @@ -818,24 +863,34 @@ z-index: 30; display: flex; flex-direction: column; - gap: 3px; + gap: 6px; } .cons-pop-models { display: flex; flex-direction: column; - gap: 3px; - border-top: 1px solid var(--border-hairline); - padding-top: 4px; - margin-top: 2px; + gap: 4px; + border-top: 1px solid color-mix(in srgb, var(--border-hairline) 75%, transparent); + padding-top: 6px; + margin-top: 1px; +} + +.cons-pop-models[hidden] { + display: none !important; +} + +.trend-tip-sub:not([hidden]) + .cons-pop-models { + border-top: none; + padding-top: 1px; + margin-top: 0; } .cons-pop-model-row { display: flex; align-items: center; justify-content: space-between; - gap: 12px; - font-size: var(--fs-sm); + gap: 10px; + font-size: var(--fs-xs); line-height: 1.3; } @@ -849,6 +904,7 @@ .cons-pop-model-name { max-width: 156px; + font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; @@ -871,10 +927,11 @@ } .cons-pop-model-pct { - min-width: 40px; + min-width: 38px; text-align: right; - font-weight: 600; - color: var(--text-primary); + font-size: var(--fs-xs); + font-weight: 500; + color: var(--text-secondary); } /* --- 6. 12 个月垂直堆叠柱状图 (12-Month Stacked Bar Chart) --- */ diff --git a/sidecars/panel/src/styles/views-tables.css b/sidecars/panel/src/styles/views-tables.css index cb2f46b..3ba01f1 100644 --- a/sidecars/panel/src/styles/views-tables.css +++ b/sidecars/panel/src/styles/views-tables.css @@ -19,6 +19,14 @@ background: var(--surface-panel); } +.panel > .table-scroll-host { + margin-right: calc(-1 * var(--space-5) + 2px); +} + +.panel > .table-scroll-host > .custom-scroll-content { + padding-right: calc(var(--space-5) - 2px); +} + .table-viewport { flex: 1; min-height: 0; @@ -127,57 +135,69 @@ flex: 0 1 auto; } -.step-model-compact { - flex-shrink: 0; - white-space: nowrap; - color: var(--accent-primary); - font-weight: 500; -} - -.step-model-compact[hidden] { - display: none !important; -} - .steps-panel-header { flex-wrap: wrap; row-gap: 6px; } -.steps-panel-title { - flex: 0 0 auto; -} - .steps-header-controls { display: flex; align-items: center; - justify-content: flex-end; - gap: 6px; - flex: 1 1 280px; + justify-content: space-between; + flex-wrap: wrap; + gap: 6px 8px; + flex: 1 1 100%; min-width: 0; } .steps-header-controls .segmented { - flex-shrink: 0; + flex: 0 0 auto; +} + +.steps-header-filters { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 6px; + margin-left: auto; + flex: 1 1 156px; + min-width: 0; + max-width: 100%; +} + +.steps-header-filters[hidden] { + display: none !important; } .steps-inline-scope-select, .steps-inline-model-select { - flex: 0 1 165px; - min-width: 72px; - max-width: 175px; + flex: 0 1 auto; + min-width: 0; + max-width: 148px; } .steps-inline-scope-select .select-trigger, .steps-inline-model-select .select-trigger { - min-height: calc(22px * var(--ui-font-scale, 1)); + min-height: calc(25px * var(--ui-font-scale, 1)); height: auto; - padding: 2px 6px; - gap: 4px; + padding: 2px 10px; + gap: 6px; min-width: 0; overflow: hidden; font-size: var(--fs-md); - border: 1px solid var(--border-hairline); - background: var(--surface-subtle); + border: none; + border-radius: var(--radius-pill); + background: color-mix(in srgb, var(--text-primary) 7.5%, var(--surface-panel)); +} + +.steps-inline-scope-select .select-trigger:hover, +.steps-inline-model-select .select-trigger:hover { + background: color-mix(in srgb, var(--text-primary) 11.5%, var(--surface-panel)); +} + +.steps-inline-scope-select.is-open .select-trigger, +.steps-inline-model-select.is-open .select-trigger { + background: color-mix(in srgb, var(--text-primary) 14%, var(--surface-panel)); } /* --- 2.5 极简对话轮次导轨与起点圆点 (Minimalist Turn Rail & Prompt Preview) --- */ @@ -295,7 +315,24 @@ animation: anim-popover-in var(--dur-instant) var(--ease-fast); } -/* --- 2.6 单步异常整行语义着色、模型汇总微标、筛选条与悬停诊断卡 --- */ +/* --- 2.6 单步压缩 / 异常整行语义着色、模型汇总微标、筛选条与悬停诊断卡 --- */ +.data-table tbody tr.is-compaction { + background: color-mix(in srgb, var(--accent-primary) 11%, transparent); +} + +.data-table tbody tr.is-compaction:hover { + background: color-mix(in srgb, var(--accent-primary) 18%, transparent); +} + +.data-table tbody tr.is-compaction td:first-child { + box-shadow: inset 2px 0 0 var(--accent-primary); +} + +.data-table tbody tr.is-compaction td:first-child > span:not(.agent-badge):not(.turn-rail) { + color: var(--accent-primary); + font-weight: 600; +} + .data-table tbody tr.is-anomaly-warn { background: color-mix(in srgb, var(--metric-warn) 11%, transparent); } @@ -399,6 +436,10 @@ border-color: color-mix(in srgb, var(--metric-danger) 46%, var(--border-strong)); } +.step-anomaly-tip.is-compaction { + border-color: color-mix(in srgb, var(--accent-primary) 46%, var(--border-strong)); +} + .step-anomaly-tip[hidden], .step-anomaly-tip-sub[hidden], .step-anomaly-tip-list[hidden], @@ -423,6 +464,10 @@ color: var(--metric-danger); } +.step-anomaly-tip.is-compaction .step-anomaly-tip-title { + color: var(--accent-primary); +} + .step-anomaly-tip-sub { font-size: var(--fs-xs); color: var(--text-secondary); @@ -542,7 +587,9 @@ display: flex; flex-direction: column; gap: var(--space-3); - padding: var(--space-3) 0 2px; + padding-top: var(--space-3); + padding-bottom: 2px; + padding-left: 0; } .sstep-card { @@ -599,15 +646,24 @@ } .sstep-fit-model-select .select-trigger { - min-height: calc(22px * var(--ui-font-scale, 1)); + min-height: calc(24px * var(--ui-font-scale, 1)); height: auto; - padding: 2px 6px; - gap: 4px; + padding: 2px 10px; + gap: 6px; min-width: 0; overflow: hidden; font-size: var(--fs-sm); - border: 1px solid var(--border-hairline); - background: var(--surface-subtle); + border: none; + border-radius: var(--radius-pill); + background: color-mix(in srgb, var(--text-primary) 7.5%, var(--surface-panel)); +} + +.sstep-fit-model-select .select-trigger:hover { + background: color-mix(in srgb, var(--text-primary) 11.5%, var(--surface-panel)); +} + +.sstep-fit-model-select.is-open .select-trigger { + background: color-mix(in srgb, var(--text-primary) 14%, var(--surface-panel)); } .sstep-chart-wrap { @@ -783,9 +839,11 @@ } .trend-tip-anomaly { - margin-top: 3px; - padding-top: 3px; - border-top: 1px solid var(--border-hairline); + margin-top: 0; + padding: 4px 8px; + border: none; + border-radius: var(--radius-xs); + background: color-mix(in srgb, var(--metric-warn) 11%, transparent); font-size: var(--fs-xs); font-weight: 600; color: var(--metric-warn); @@ -794,6 +852,7 @@ .trend-tip-anomaly.is-danger { color: var(--metric-danger); + background: color-mix(in srgb, var(--metric-danger) 12%, transparent); } .trend-tip-anomaly[hidden] { diff --git a/sidecars/panel/src/views/ConsumptionView.js b/sidecars/panel/src/views/ConsumptionView.js index f46b6e4..3fee321 100644 --- a/sidecars/panel/src/views/ConsumptionView.js +++ b/sidecars/panel/src/views/ConsumptionView.js @@ -586,12 +586,11 @@ export const ConsumptionView = defineComponent({ } /** - * 创建热门模型单行 DOM 结构(模型名称后附专属颜色圆点 + 按总占比缩放的 4 段比例条 + 底部分项脚标)。 + * 创建热门模型单行 DOM 结构(模型名称 + 按总占比缩放的 4 段比例条 + 底部分项脚标)。 */ function createBreakdownItemRow() { const nameTextEl = h('span', { className: 'cons-row-title-text' }); - const modelDotEl = h('span', { className: 'dot-swatch cons-model-dot cons-title-model-dot' }); - const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl, modelDotEl]); + const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl]); const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); const costEl = h('strong', { className: 'cons-row-cost text-mono' }); @@ -652,7 +651,6 @@ export const ConsumptionView = defineComponent({ refs: { nameEl, nameTextEl, - modelDotEl, pctBadge, totalTokEl, costEl, @@ -672,9 +670,9 @@ export const ConsumptionView = defineComponent({ } /** - * 增量更新热门模型单行的指标文本、名称后的专属颜色圆点与按总占比缩放的 4 段比例条宽度。 + * 增量更新热门模型单行的指标文本与按总占比缩放的 4 段比例条宽度。 */ - function updateBreakdownItemRow(refs, item, grandTotalTokens, modelColor = '') { + function updateBreakdownItemRow(refs, item, grandTotalTokens) { patchText(refs.inLbl, t('cons.footInput')); patchText(refs.cacheLbl, t('cons.footCache')); patchText(refs.outLbl, t('cons.footOutput')); @@ -683,10 +681,6 @@ export const ConsumptionView = defineComponent({ const displayLabel = item.label || item.name || item.shortName || '—'; patchText(refs.nameTextEl, displayLabel); patchAttr(refs.nameEl, 'title', item.title || displayLabel); - patchAttr(refs.modelDotEl, 'hidden', !modelColor); - if (modelColor) { - patchStyleVar(refs.modelDotEl, '--dot-color', modelColor); - } const total = Number(item.totalTokens || 0); const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0; const scaleRatio = @@ -1169,23 +1163,17 @@ export const ConsumptionView = defineComponent({ }); trendChart.update(enrichedTrendSeries); - // 3. 同步热门模型列表(名称后带专属颜色圆点 + 4 段条按总占比缩放长度) + // 3. 同步热门模型列表(4 段条按总占比缩放长度) patchKeyedList(modelsListEl, models, { keyFn: (m) => m.displayText || m.label || m.shortName, - sigFn: (m) => { - const seed = getCanonicalModelColorSeed(m); - const color = modelColorMap.get(seed) || resolveDeterministicModelColor(seed); - return `${localeSig}:${m.displayText}:${m.displayTitle}:${color}:${m.totalTokens}:${m.inputTokens}:${m.cacheReadTokens}:${m.responseTokens}:${m.thinkingTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`; - }, + sigFn: (m) => + `${localeSig}:${m.displayText}:${m.displayTitle}:${m.totalTokens}:${m.inputTokens}:${m.cacheReadTokens}:${m.responseTokens}:${m.thinkingTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`, createRow: createBreakdownItemRow, updateRow: (refs, m) => { - const seed = getCanonicalModelColorSeed(m); - const color = modelColorMap.get(seed) || resolveDeterministicModelColor(seed); updateBreakdownItemRow( refs, { ...m, label: m.displayText, title: m.displayTitle }, - modelsTotalTok, - color + modelsTotalTok ); }, }); diff --git a/sidecars/panel/src/views/StepsDetailView.js b/sidecars/panel/src/views/StepsDetailView.js index 46a26b0..af2e2be 100644 --- a/sidecars/panel/src/views/StepsDetailView.js +++ b/sidecars/panel/src/views/StepsDetailView.js @@ -27,7 +27,6 @@ import { resolveModelAnomalySummary, resolveModelDisplayInfo, } from '../core/formatters.js'; -import { createSvgIcon } from '../icons/SvgIcon.js'; import { getEffectiveLocale, i18nStore, t } from '../i18n/index.js'; import { formatAgentLabel, @@ -477,7 +476,11 @@ export const StepsDetailView = defineComponent({ }); modelsScroll.el.setAttribute('hidden', ''); - const panelTitleTextEl = h('span', { text: t('steps.title') }); + const headerFiltersEl = h('div', { className: 'steps-header-filters', hidden: true }, [ + inlineScopeSelect.el, + stepsModelSelect.el, + ]); + const panelEl = h( 'section', { @@ -486,14 +489,9 @@ export const StepsDetailView = defineComponent({ }, [ h('div', { className: 'panel-header steps-panel-header' }, [ - h('span', { className: 'panel-title steps-panel-title' }, [ - createSvgIcon('table', { size: 13 }), - panelTitleTextEl, - ]), h('div', { className: 'steps-header-controls' }, [ - inlineScopeSelect.el, - stepsModelSelect.el, subTabSwitch.el, + headerFiltersEl, ]), ]), anomalyFilterBarEl, @@ -566,7 +564,6 @@ export const StepsDetailView = defineComponent({ } function refreshStaticLocaleLabels() { - patchText(panelTitleTextEl, t('steps.title')); patchText(lineTitleEl, t('steps.lineTitle')); patchText(fitTitleEl, t('steps.fitTitle')); patchText(modelsSectionTitleEl, t('steps.modelsTitle')); @@ -786,6 +783,7 @@ export const StepsDetailView = defineComponent({ ); const showStepsModelFilter = uiSt.stepsSubTab === 'steps' && hasMultipleModels; patchAttr(stepsModelSelect.el, 'hidden', !showStepsModelFilter); + patchAttr(headerFiltersEl, 'hidden', !hasSubagents && !showStepsModelFilter); if (hasMultipleModels) { stepsModelSelect.setProps({ modelValue: selectedTableModels, diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index daf2aac..fa8f22a 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -421,8 +421,8 @@ html[data-standalone="true"] .app-shell { .steps-inline-scope-select .select-menu, .steps-inline-model-select .select-menu { - left: 0; - right: auto; + left: auto; + right: 0; min-width: 220px; max-width: min(320px, calc(100vw - 24px)); } @@ -696,7 +696,15 @@ html[data-standalone="true"] .app-shell { font-size: var(--fs-base); cursor: pointer; text-align: left; - transition: background-color var(--dur-instant) var(--ease-fast); + transition: + background-color var(--dur-instant) var(--ease-fast), + border-color var(--dur-instant) var(--ease-fast), + box-shadow var(--dur-instant) var(--ease-fast); +} + +.select-trigger .svg-icon { + flex-shrink: 0; + color: var(--text-muted); } .select-trigger:hover, @@ -704,6 +712,27 @@ html[data-standalone="true"] .app-shell { background: var(--surface-hover); } +.form-row > .custom-select > .select-trigger { + min-height: calc(28px * var(--ui-font-scale, 1)); + padding: 3px 12px; + background: color-mix(in srgb, var(--text-primary) 7.5%, var(--surface-panel)); + border: none; + border-radius: var(--radius-pill); +} + +.form-row > .custom-select > .select-trigger:hover { + background: color-mix(in srgb, var(--text-primary) 11.5%, var(--surface-panel)); +} + +.form-row > .custom-select.is-open > .select-trigger { + background: color-mix(in srgb, var(--text-primary) 14%, var(--surface-panel)); +} + +.form-row > .custom-select > .select-trigger:disabled { + opacity: 0.52; + cursor: not-allowed; +} + .select-label { flex: 1; min-width: 0; @@ -2299,12 +2328,6 @@ html[data-standalone="true"] .app-shell { white-space: nowrap; } -.cons-title-model-dot { - width: 7px; - height: 7px; - flex-shrink: 0; -} - .cons-row-metrics { display: inline-flex; align-items: center; @@ -2437,9 +2460,9 @@ html[data-standalone="true"] .app-shell { left: var(--tip-x, 50%); transform: translateX(var(--tip-shift, -50%)); width: max-content; - min-width: 196px; - max-width: min(320px, calc(100% - 8px)); - padding: 6px 10px; + min-width: 224px; + max-width: min(316px, calc(100% - 8px)); + padding: 9px 11px; background: var(--surface-panel); border: 1px solid var(--border-strong); border-radius: var(--radius-sm); @@ -2448,27 +2471,29 @@ html[data-standalone="true"] .app-shell { z-index: 25; display: flex; flex-direction: column; - gap: 2px; + gap: 6px; } .trend-tip-head { display: flex; align-items: center; justify-content: space-between; - gap: 10px; - font-size: var(--fs-sm); + gap: 12px; + font-size: var(--fs-xs); + line-height: 1.25; color: var(--text-secondary); } .trend-tip-time { - font-weight: 600; - color: var(--text-primary); + font-weight: 500; + color: var(--text-secondary); white-space: nowrap; flex-shrink: 0; } .trend-tip-calls { font-size: var(--fs-xs); + font-weight: 500; color: var(--text-muted); white-space: nowrap; max-width: 190px; @@ -2478,36 +2503,85 @@ html[data-standalone="true"] .app-shell { .trend-tip-main { display: flex; - align-items: baseline; + align-items: center; justify-content: space-between; - gap: 12px; + gap: 10px; + margin-top: -2px; } .trend-tip-tokens { - font-size: var(--fs-base); + font-size: var(--fs-lg); font-weight: 700; + line-height: 1.18; + letter-spacing: -0.02em; color: var(--accent-primary); white-space: nowrap; flex-shrink: 0; } .trend-tip-cost { - font-size: var(--fs-md); + font-size: var(--fs-sm); font-weight: 600; + line-height: 1.2; + padding: 2px 7px; + border-radius: var(--radius-xs); color: var(--text-primary); + background: color-mix(in srgb, var(--text-primary) 6%, transparent); white-space: nowrap; flex-shrink: 0; } +.trend-tip-cost:empty { + display: none; +} + .trend-tip-sub { + padding: 5px 8px; + border: none; + border-radius: var(--radius-xs); + background: color-mix(in srgb, var(--text-primary) 4.2%, transparent); font-size: var(--fs-xs); + line-height: 1.3; color: var(--text-secondary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; - border-top: 1px solid var(--border-hairline); - padding-top: 2px; - margin-top: 1px; +} + +.trend-tip-sub[hidden] { + display: none !important; +} + +.trend-tip-sub.is-grid { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 8px; + padding: 6px 8px; + white-space: normal; + overflow: visible; +} + +.trend-tip-stat { + display: flex; + flex-direction: column; + gap: 1px; + min-width: 0; +} + +.trend-tip-stat-label { + font-size: var(--fs-2xs); + font-weight: 500; + line-height: 1.2; + color: var(--text-muted); + white-space: nowrap; +} + +.trend-tip-stat-val { + font-size: var(--fs-sm); + font-weight: 600; + line-height: 1.25; + color: var(--text-primary); + white-space: nowrap; } .trend-tooltip.is-line-low { @@ -2895,9 +2969,9 @@ html[data-standalone="true"] .app-shell { left: var(--pop-x, 8px); top: var(--pop-y, 8px); width: max-content; - min-width: 196px; - max-width: min(310px, calc(100% - 16px)); - padding: 6px 10px; + min-width: 224px; + max-width: min(316px, calc(100% - 16px)); + padding: 9px 11px; background: var(--surface-panel); border: 1px solid var(--border-strong); border-radius: var(--radius-sm); @@ -2906,24 +2980,34 @@ html[data-standalone="true"] .app-shell { z-index: 30; display: flex; flex-direction: column; - gap: 3px; + gap: 6px; } .cons-pop-models { display: flex; flex-direction: column; - gap: 3px; - border-top: 1px solid var(--border-hairline); - padding-top: 4px; - margin-top: 2px; + gap: 4px; + border-top: 1px solid color-mix(in srgb, var(--border-hairline) 75%, transparent); + padding-top: 6px; + margin-top: 1px; +} + +.cons-pop-models[hidden] { + display: none !important; +} + +.trend-tip-sub:not([hidden]) + .cons-pop-models { + border-top: none; + padding-top: 1px; + margin-top: 0; } .cons-pop-model-row { display: flex; align-items: center; justify-content: space-between; - gap: 12px; - font-size: var(--fs-sm); + gap: 10px; + font-size: var(--fs-xs); line-height: 1.3; } @@ -2937,6 +3021,7 @@ html[data-standalone="true"] .app-shell { .cons-pop-model-name { max-width: 156px; + font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; @@ -2959,10 +3044,11 @@ html[data-standalone="true"] .app-shell { } .cons-pop-model-pct { - min-width: 40px; + min-width: 38px; text-align: right; - font-weight: 600; - color: var(--text-primary); + font-size: var(--fs-xs); + font-weight: 500; + color: var(--text-secondary); } /* --- 6. 12 个月垂直堆叠柱状图 (12-Month Stacked Bar Chart) --- */ @@ -3079,6 +3165,14 @@ html[data-standalone="true"] .app-shell { background: var(--surface-panel); } +.panel > .table-scroll-host { + margin-right: calc(-1 * var(--space-5) + 2px); +} + +.panel > .table-scroll-host > .custom-scroll-content { + padding-right: calc(var(--space-5) - 2px); +} + .table-viewport { flex: 1; min-height: 0; @@ -3187,57 +3281,69 @@ html[data-standalone="true"] .app-shell { flex: 0 1 auto; } -.step-model-compact { - flex-shrink: 0; - white-space: nowrap; - color: var(--accent-primary); - font-weight: 500; -} - -.step-model-compact[hidden] { - display: none !important; -} - .steps-panel-header { flex-wrap: wrap; row-gap: 6px; } -.steps-panel-title { - flex: 0 0 auto; -} - .steps-header-controls { display: flex; align-items: center; - justify-content: flex-end; - gap: 6px; - flex: 1 1 280px; + justify-content: space-between; + flex-wrap: wrap; + gap: 6px 8px; + flex: 1 1 100%; min-width: 0; } .steps-header-controls .segmented { - flex-shrink: 0; + flex: 0 0 auto; +} + +.steps-header-filters { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 6px; + margin-left: auto; + flex: 1 1 156px; + min-width: 0; + max-width: 100%; +} + +.steps-header-filters[hidden] { + display: none !important; } .steps-inline-scope-select, .steps-inline-model-select { - flex: 0 1 165px; - min-width: 72px; - max-width: 175px; + flex: 0 1 auto; + min-width: 0; + max-width: 148px; } .steps-inline-scope-select .select-trigger, .steps-inline-model-select .select-trigger { - min-height: calc(22px * var(--ui-font-scale, 1)); + min-height: calc(25px * var(--ui-font-scale, 1)); height: auto; - padding: 2px 6px; - gap: 4px; + padding: 2px 10px; + gap: 6px; min-width: 0; overflow: hidden; font-size: var(--fs-md); - border: 1px solid var(--border-hairline); - background: var(--surface-subtle); + border: none; + border-radius: var(--radius-pill); + background: color-mix(in srgb, var(--text-primary) 7.5%, var(--surface-panel)); +} + +.steps-inline-scope-select .select-trigger:hover, +.steps-inline-model-select .select-trigger:hover { + background: color-mix(in srgb, var(--text-primary) 11.5%, var(--surface-panel)); +} + +.steps-inline-scope-select.is-open .select-trigger, +.steps-inline-model-select.is-open .select-trigger { + background: color-mix(in srgb, var(--text-primary) 14%, var(--surface-panel)); } /* --- 2.5 极简对话轮次导轨与起点圆点 (Minimalist Turn Rail & Prompt Preview) --- */ @@ -3355,7 +3461,24 @@ html[data-standalone="true"] .app-shell { animation: anim-popover-in var(--dur-instant) var(--ease-fast); } -/* --- 2.6 单步异常整行语义着色、模型汇总微标、筛选条与悬停诊断卡 --- */ +/* --- 2.6 单步压缩 / 异常整行语义着色、模型汇总微标、筛选条与悬停诊断卡 --- */ +.data-table tbody tr.is-compaction { + background: color-mix(in srgb, var(--accent-primary) 11%, transparent); +} + +.data-table tbody tr.is-compaction:hover { + background: color-mix(in srgb, var(--accent-primary) 18%, transparent); +} + +.data-table tbody tr.is-compaction td:first-child { + box-shadow: inset 2px 0 0 var(--accent-primary); +} + +.data-table tbody tr.is-compaction td:first-child > span:not(.agent-badge):not(.turn-rail) { + color: var(--accent-primary); + font-weight: 600; +} + .data-table tbody tr.is-anomaly-warn { background: color-mix(in srgb, var(--metric-warn) 11%, transparent); } @@ -3459,6 +3582,10 @@ html[data-standalone="true"] .app-shell { border-color: color-mix(in srgb, var(--metric-danger) 46%, var(--border-strong)); } +.step-anomaly-tip.is-compaction { + border-color: color-mix(in srgb, var(--accent-primary) 46%, var(--border-strong)); +} + .step-anomaly-tip[hidden], .step-anomaly-tip-sub[hidden], .step-anomaly-tip-list[hidden], @@ -3483,6 +3610,10 @@ html[data-standalone="true"] .app-shell { color: var(--metric-danger); } +.step-anomaly-tip.is-compaction .step-anomaly-tip-title { + color: var(--accent-primary); +} + .step-anomaly-tip-sub { font-size: var(--fs-xs); color: var(--text-secondary); @@ -3602,7 +3733,9 @@ html[data-standalone="true"] .app-shell { display: flex; flex-direction: column; gap: var(--space-3); - padding: var(--space-3) 0 2px; + padding-top: var(--space-3); + padding-bottom: 2px; + padding-left: 0; } .sstep-card { @@ -3659,15 +3792,24 @@ html[data-standalone="true"] .app-shell { } .sstep-fit-model-select .select-trigger { - min-height: calc(22px * var(--ui-font-scale, 1)); + min-height: calc(24px * var(--ui-font-scale, 1)); height: auto; - padding: 2px 6px; - gap: 4px; + padding: 2px 10px; + gap: 6px; min-width: 0; overflow: hidden; font-size: var(--fs-sm); - border: 1px solid var(--border-hairline); - background: var(--surface-subtle); + border: none; + border-radius: var(--radius-pill); + background: color-mix(in srgb, var(--text-primary) 7.5%, var(--surface-panel)); +} + +.sstep-fit-model-select .select-trigger:hover { + background: color-mix(in srgb, var(--text-primary) 11.5%, var(--surface-panel)); +} + +.sstep-fit-model-select.is-open .select-trigger { + background: color-mix(in srgb, var(--text-primary) 14%, var(--surface-panel)); } .sstep-chart-wrap { @@ -3843,9 +3985,11 @@ html[data-standalone="true"] .app-shell { } .trend-tip-anomaly { - margin-top: 3px; - padding-top: 3px; - border-top: 1px solid var(--border-hairline); + margin-top: 0; + padding: 4px 8px; + border: none; + border-radius: var(--radius-xs); + background: color-mix(in srgb, var(--metric-warn) 11%, transparent); font-size: var(--fs-xs); font-weight: 600; color: var(--metric-warn); @@ -3854,6 +3998,7 @@ html[data-standalone="true"] .app-shell { .trend-tip-anomaly.is-danger { color: var(--metric-danger); + background: color-mix(in srgb, var(--metric-danger) 12%, transparent); } .trend-tip-anomaly[hidden] { @@ -5938,6 +6083,9 @@ html[data-standalone="true"] .app-shell { --modern-surface-card: color-mix(in srgb, var(--surface-panel) 95.2%, #ffffff 4.8%); --modern-surface-subtle: color-mix(in srgb, var(--text-primary) 5.2%, transparent); --modern-surface-hover: color-mix(in srgb, var(--accent-primary) 11%, color-mix(in srgb, var(--text-primary) 4%, transparent)); + --modern-pill-select-bg: color-mix(in srgb, var(--text-primary) 8.5%, var(--modern-surface-card)); + --modern-pill-select-hover: color-mix(in srgb, var(--text-primary) 12.5%, var(--modern-surface-card)); + --modern-pill-select-open: color-mix(in srgb, var(--text-primary) 15%, var(--modern-surface-card)); --modern-card-shadow: none; --modern-nav-track-bg: var(--modern-surface-card); --modern-inline-track-bg: color-mix(in srgb, var(--text-primary) 4.2%, transparent); @@ -5959,6 +6107,9 @@ html[data-standalone="true"] .app-shell { --modern-surface-card: #ffffff; --modern-surface-subtle: hsl(216 42% 97.2%); --modern-surface-hover: hsl(216 56% 94.4%); + --modern-pill-select-bg: hsl(220 14% 94%); + --modern-pill-select-hover: hsl(220 14% 90.5%); + --modern-pill-select-open: hsl(220 14% 88.5%); --modern-card-shadow: 0 1px 3px rgb(15 23 42 / 0.045), 0 4px 14px rgb(15 23 42 / 0.028); --modern-nav-track-bg: hsl(216 28% 94.2%); --modern-inline-track-bg: hsl(216 32% 96.2%); @@ -6380,11 +6531,16 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { border: none; } -[data-modern-ui="true"] .trend-tip-sub, -[data-modern-ui="true"] .trend-tip-anomaly, +[data-modern-ui="true"] .trend-tip-sub { + background: var(--modern-surface-subtle); +} + +[data-modern-ui="true"] .trend-tip-cost { + background: var(--modern-surface-subtle); +} + [data-modern-ui="true"] .cons-pop-models { - border-top: none; - padding-top: 3px; + border-top-color: var(--modern-surface-hover); } [data-modern-ui="true"] .cons-source-bar-hit:hover .cons-source-model-bar, @@ -6442,6 +6598,17 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { background: var(--modern-surface-hover); } +[data-modern-ui="true"] .data-table tbody tr.is-compaction, +[data-modern-ui="true"] .data-table:not(.is-virtualized) tbody tr.is-compaction:nth-child(even), +[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-compaction { + background: color-mix(in srgb, var(--accent-primary) 12%, transparent); +} + +[data-modern-ui="true"] .data-table tbody tr.is-compaction:hover, +[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-compaction:hover { + background: color-mix(in srgb, var(--accent-primary) 19%, transparent); +} + [data-modern-ui="true"] .data-table tbody tr.is-anomaly-warn, [data-modern-ui="true"] .data-table:not(.is-virtualized) tbody tr.is-anomaly-warn:nth-child(even), [data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-warn { @@ -6464,11 +6631,28 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { background: color-mix(in srgb, var(--metric-danger) 21%, transparent); } +[data-modern-ui="true"] .form-row > .custom-select > .select-trigger, [data-modern-ui="true"] .steps-inline-scope-select .select-trigger, [data-modern-ui="true"] .steps-inline-model-select .select-trigger, [data-modern-ui="true"] .sstep-fit-model-select .select-trigger { border: none; - background: var(--modern-surface-subtle); + box-shadow: none; + border-radius: var(--radius-pill); + background: var(--modern-pill-select-bg); +} + +[data-modern-ui="true"] .form-row > .custom-select > .select-trigger:hover, +[data-modern-ui="true"] .steps-inline-scope-select .select-trigger:hover, +[data-modern-ui="true"] .steps-inline-model-select .select-trigger:hover, +[data-modern-ui="true"] .sstep-fit-model-select .select-trigger:hover { + background: var(--modern-pill-select-hover); +} + +[data-modern-ui="true"] .form-row > .custom-select.is-open > .select-trigger, +[data-modern-ui="true"] .steps-inline-scope-select.is-open .select-trigger, +[data-modern-ui="true"] .steps-inline-model-select.is-open .select-trigger, +[data-modern-ui="true"] .sstep-fit-model-select.is-open .select-trigger { + background: var(--modern-pill-select-open); } [data-modern-ui="true"] .sstep-card, @@ -6584,12 +6768,12 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { border: none; background: var(--modern-surface-card); box-shadow: var(--shadow-popover); - animation: anim-modern-pop-in 150ms var(--ease-modern); + animation: anim-modern-tip-fade 120ms var(--ease-modern); } [data-modern-ui="true"] .select-menu.is-above, [data-modern-ui="true"] .dt-popover.is-above { - animation-name: anim-modern-pop-in-up; + transform-origin: bottom right; } [data-modern-ui="true"] .trend-tooltip, diff --git a/sidecars/panel/test/consumption-bars.test.mjs b/sidecars/panel/test/consumption-bars.test.mjs index 4bd7f7b..9ac8931 100644 --- a/sidecars/panel/test/consumption-bars.test.mjs +++ b/sidecars/panel/test/consumption-bars.test.mjs @@ -412,11 +412,8 @@ test('ConsumptionView: Top Models color dot + % bar, clutter-free Client Sources assert.equal(modelRows.length, 6); assert.equal(sourceRows.length, 2); - // 1. Top Models: colored dot appears right after model name & 4-segment bar scales to 50% (not 100%) - const argonTitleDot = modelRows[0].querySelector('.cons-title-model-dot'); - assert.ok(argonTitleDot && !argonTitleDot.hasAttribute('hidden')); - const argonDotColor = argonTitleDot.style.getPropertyValue('--dot-color'); - assert.match(argonDotColor, /^hsl\(/); + // 1. Top Models: no color dot next to model name & 4-segment bar scales to 50% (not 100%) + assert.equal(modelRows[0].querySelector('.cons-title-model-dot'), null); const argonSegSum = modelRows[0] .querySelectorAll('.progress-seg') @@ -429,7 +426,8 @@ test('ConsumptionView: Top Models color dot + % bar, clutter-free Client Sources assert.equal(appTopItems.length, 3, 'Should show top 3 non-other models in single-line footer'); assert.equal(appTopItems[0].querySelector('.cons-source-top-name')?.textContent, '4-argon'); assert.equal(appTopItems[0].querySelector('.cons-source-top-pct')?.textContent, '50%'); - assert.equal(appTopItems[0].querySelector('.cons-source-top-dot')?.style.getPropertyValue('--dot-color'), argonDotColor); + const argonDotColor = appTopItems[0].querySelector('.cons-source-top-dot')?.style.getPropertyValue('--dot-color'); + assert.match(argonDotColor, /^hsl\(/); assert.equal(appTopItems[1].querySelector('.cons-source-top-name')?.textContent, '4-carbon'); assert.equal(appTopItems[1].querySelector('.cons-source-top-pct')?.textContent, '31%'); assert.equal(appTopItems[2].querySelector('.cons-source-top-name')?.textContent, '3.8-flash-n'); diff --git a/sidecars/panel/test/cross-module-regressions.test.mjs b/sidecars/panel/test/cross-module-regressions.test.mjs index c51ff92..bca8187 100644 --- a/sidecars/panel/test/cross-module-regressions.test.mjs +++ b/sidecars/panel/test/cross-module-regressions.test.mjs @@ -963,8 +963,8 @@ test('post-compaction context preserves static channels + checkpoint summary, ca const stylesCss = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8'); assert.match(stylesCss, /\.wm-ctx-seg\s*\{[^}]*width:\s*58px;/); assert.match(stylesCss, /\.wm-ctx-pct\s*\{[^}]*max-width:\s*none;[^}]*overflow:\s*visible;[^}]*text-overflow:\s*clip;/s); - assert.match(stylesCss, /\.step-model-compact\s*\{[^}]*color:\s*var\(--accent-primary\);/); - assert.doesNotMatch(stylesCss, /\.step-model-compact\s*\{[^}]*--metric-info/); + assert.match(stylesCss, /\.data-table\s+tbody\s+tr\.is-compaction\s*\{[^}]*var\(--accent-primary\)/); + assert.doesNotMatch(stylesCss, /\.data-table\s+tbody\s+tr\.is-compaction\s*\{[^}]*--metric-info/); assert.match(stylesCss, /\.long-pill-nav\s*\{[^}]*container-type:\s*inline-size;[^}]*minmax\(0,\s*1fr\)[^}]*overflow:\s*hidden;/s); assert.match(stylesCss, /\.pill-tab\s*\{[^}]*min-width:\s*0;/s); assert.match(stylesCss, /@container\s*\(max-width:\s*30em\)\s*\{[\s\S]*?\.pill-tab-badge\s*\{\s*display:\s*none\s*!important;/); diff --git a/sidecars/panel/test/modern-ui.test.mjs b/sidecars/panel/test/modern-ui.test.mjs index 18edb22..08dad6b 100644 --- a/sidecars/panel/test/modern-ui.test.mjs +++ b/sidecars/panel/test/modern-ui.test.mjs @@ -1147,7 +1147,11 @@ test('Capsule odometer digit rolling (0.15s) and color transition (0.1s) stay st // 4. Compiled CSS strictly scopes 150ms roll & 100ms color transition under [data-modern-ui="true"] const builtStyles = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8'); - assert.match(builtStyles, /\.steps-inline-scope-select\s+\.select-menu[\s\S]*?left:\s*0;\s*right:\s*auto;/); + assert.match(builtStyles, /\.steps-inline-scope-select\s+\.select-menu[\s\S]*?left:\s*auto;\s*right:\s*0;/); + assert.match( + builtStyles, + /\[data-modern-ui="true"\]\s+\.select-menu,[\s\S]*?animation:\s*anim-modern-tip-fade\s+120ms/ + ); assert.match(builtStyles, /\[data-modern-ui="true"\]\s+\.select-menu\.is-above/); assert.match( builtStyles, diff --git a/sidecars/panel/test/step-anomalies.test.mjs b/sidecars/panel/test/step-anomalies.test.mjs index fded8b2..aa48588 100644 --- a/sidecars/panel/test/step-anomalies.test.mjs +++ b/sidecars/panel/test/step-anomalies.test.mjs @@ -11,6 +11,7 @@ import { i18nStore } from '../src/i18n/index.js'; import { buildModelAnomalyDiagnostic, buildStepAnomalyDiagnostic, + buildStepCompactionDiagnostic, formatAnomalyTagText, formatMetric, formatSpeedMetric, @@ -420,6 +421,15 @@ test('formatSpeedMetric drops decimals at >= 100 tok/s and STEP_COLUMN_REGISTRY. STEP_COLUMN_REGISTRY.duration.updateCell(durCell.refs, { totalDurationSec: 42.3 }); assert.equal(durCell.refs.valEl.textContent, '42.3s'); + // Compaction steps keep normal TTFT formatting ("—" when null) instead of overriding the cell + const compactTtftCell = STEP_COLUMN_REGISTRY.ttft.createCell(); + i18nStore.setState({ locale: 'zh-CN' }); + STEP_COLUMN_REGISTRY.ttft.updateCell(compactTtftCell.refs, { isCompactionStep: true, ttftSec: null }); + assert.equal(compactTtftCell.refs.valEl.textContent, '—'); + assert.notEqual(compactTtftCell.refs.valEl.getAttribute('class'), 'step-ttft-compaction'); + STEP_COLUMN_REGISTRY.ttft.updateCell(compactTtftCell.refs, { isCompactionStep: false, ttftSec: 5.2 }); + assert.equal(compactTtftCell.refs.valEl.textContent, '5.2s'); + // ContextSegmentMeter renders crisp separated blocks (.ctx-segment-meter + .is-active + .has-sep) const meter = ContextSegmentMeter({ context: { @@ -509,6 +519,47 @@ test('StepTableWidget tints entire anomaly rows with zero extra column width and ttftSec: 1.4, anomalySig: '', }, + { + stepIndex: 4918, + modelShort: '4-neon', + modelLabel: '4-neon', + isCompactionStep: true, + inputTokens: 120000, + cacheReadTokens: 400000, + outputTokens: 4400, + tokPerSec: 86.6, + ttftSec: null, + anomalySig: '', + }, + { + stepIndex: 4916, + modelShort: '4-neon', + modelLabel: '4-neon', + isCompactionStep: true, + inputTokens: 100000, + cacheReadTokens: 300000, + outputTokens: 2100, + tokPerSec: null, + selectedSpeedReason: 'error', + ttftSec: null, + anomalySig: 'timeout:1:w:1.5', + anomaly: { + count: 1, + primaryKind: 'timeout', + severity: 'warn', + totalDelaySec: 1.5, + kinds: { timeout: 1 }, + events: [ + { + attempt: 1, + kind: 'timeout', + delaySec: 1.5, + terminal: false, + message: 'compaction stream idle timeout', + }, + ], + }, + }, ]; widget.refs.renderStepTable(steps, 'cid-1', colKeys, 'zh-CN', { @@ -520,7 +571,7 @@ test('StepTableWidget tints entire anomaly rows with zero extra column width and // Zero extra columns and zero inline text badges added to table cells assert.equal(widget.refs.stepsTheadRow.children.length, colKeys.length); const rows = widget.refs.stepsTbody.children; - assert.equal(rows.length, 3); + assert.equal(rows.length, 5); assert.equal(rows[0].children.length, colKeys.length); assert.equal(rows[0].querySelector('.step-anomaly-tag'), null, 'No inline tag widening the #step column'); @@ -533,16 +584,24 @@ test('StepTableWidget tints entire anomaly rows with zero extra column width and assert.equal(rows[1].classList.contains('is-anomaly-danger'), true); assert.equal(rows[1].classList.contains('is-anomaly-warn'), false); - // Row 2: normal step has NO anomaly row classes and keeps 1 decimal < 100 tok/s + // Row 2: normal step has NO anomaly/compaction row classes and keeps 1 decimal < 100 tok/s assert.equal(rows[2].classList.contains('is-anomaly-warn'), false); assert.equal(rows[2].classList.contains('is-anomaly-danger'), false); + assert.equal(rows[2].classList.contains('is-compaction'), false); assert.equal(rows[2].children[2].textContent, '65.7 tok/s'); + // Row 3: pure compaction step uses host-accent row tint, keeps TTFT as "—", and shows compaction hover popover + assert.equal(rows[3].classList.contains('is-compaction'), true); + assert.equal(rows[3].classList.contains('is-anomaly-warn'), false); + assert.equal(rows[3].classList.contains('is-anomaly-danger'), false); + assert.equal(rows[3].children[3].textContent, '—'); + // Hovering the tinted row expands the structured diagnostic popover const tipEl = widget.refs.anomalyTipEl; assert.equal(tipEl.hasAttribute('hidden'), true); rows[0].onmouseenter(); assert.equal(tipEl.hasAttribute('hidden'), false); + assert.equal(tipEl.classList.contains('is-compaction'), false); assert.match(tipEl.querySelector('.step-anomaly-tip-title').textContent, /#4924.*异常 1 次/); assert.equal(tipEl.querySelector('.step-anomaly-tip-sub').textContent, '退避 2.5s'); assert.match(tipEl.querySelector('.step-anomaly-tip-detail').textContent, /stream idle timeout/); @@ -550,19 +609,44 @@ test('StepTableWidget tints entire anomaly rows with zero extra column width and rows[0].onmouseleave(); assert.equal(tipEl.hasAttribute('hidden'), true); - // Hovering danger row sets danger style on tooltip + // Hovering compaction row displays host-accent compaction popover matching warning popover structure + rows[3].onmouseenter(); + assert.equal(tipEl.hasAttribute('hidden'), false); + assert.equal(tipEl.classList.contains('is-compaction'), true); + assert.equal(tipEl.classList.contains('is-danger'), false); + assert.match(tipEl.querySelector('.step-anomaly-tip-title').textContent, /#4918.*自动压缩/); + assert.equal(tipEl.querySelector('.step-anomaly-tip-sub').textContent, '4-neon'); + assert.match(tipEl.querySelector('.step-anomaly-tip-row').textContent, /输入 520\.0k → 摘要输出 4\.4k/); + assert.equal(tipEl.querySelector('.step-anomaly-tip-detail').classList.contains('text-mono'), false); + rows[3].onmouseleave(); + assert.equal(tipEl.hasAttribute('hidden'), true); + + // Hovering danger row sets danger style and clears compaction style on tooltip rows[1].onmouseenter(); assert.equal(tipEl.hasAttribute('hidden'), false); assert.equal(tipEl.classList.contains('is-danger'), true); + assert.equal(tipEl.classList.contains('is-compaction'), false); assert.match(tipEl.querySelector('.step-anomaly-tip-detail').textContent, /429 RESOURCE_EXHAUSTED/); rows[1].onmouseleave(); assert.equal(tipEl.hasAttribute('hidden'), true); + // Row 4: hybrid compaction + anomaly keeps anomaly diagnostic and appends compaction hint + assert.equal(rows[4].classList.contains('is-compaction'), true); + assert.equal(rows[4].classList.contains('is-anomaly-warn'), true); + rows[4].onmouseenter(); + assert.equal(tipEl.hasAttribute('hidden'), false); + assert.equal(tipEl.classList.contains('is-compaction'), false); + assert.match(tipEl.querySelector('.step-anomaly-tip-title').textContent, /#4916.*异常 1 次/); + assert.match(tipEl.querySelector('.step-anomaly-tip-hint').textContent, /自动压缩/); + rows[4].onmouseleave(); + assert.equal(tipEl.hasAttribute('hidden'), true); + // Verify helper outputs cleanly assert.equal(formatAnomalyTagText('capacity', 1), '503'); assert.equal(formatAnomalyTagText('capacity', 3), '503×3'); assert.ok(buildStepAnomalyDiagnostic(steps[0])); assert.equal(buildStepAnomalyDiagnostic(steps[2]), null); + assert.equal(buildStepCompactionDiagnostic(steps[3]).severity, 'compaction'); } finally { widget.destroy(); env.restore(); @@ -810,15 +894,31 @@ test('Compiled styles.css centers odometer capsule slot text and ships both clas 'Context percentage slot stays left-aligned next to its progress ring' ); - // Universal Classic + Modern UI anomaly styling + // Universal Classic + Modern UI compaction & anomaly styling (anomaly overrides compaction if both occur) + const classicCompactIdx = builtCss.indexOf('tr.is-compaction {'); + const classicWarnIdx = builtCss.indexOf('tr.is-anomaly-warn {'); + assert.ok(classicCompactIdx > 0 && classicWarnIdx > classicCompactIdx, 'Classic tr.is-compaction precedes tr.is-anomaly-warn'); + assert.match(builtCss, /tr\.is-compaction\s*\{[^}]*var\(--accent-primary\)/); + assert.match(builtCss, /\[data-modern-ui="true"\][\s\S]*?tr\.is-compaction[\s\S]*?var\(--accent-primary\)/); + assert.match(builtCss, /\.step-anomaly-tip\.is-compaction[\s\S]*?var\(--accent-primary\)/); + assert.doesNotMatch(builtCss, /\.step-ttft-compaction/); assert.match(builtCss, /tr\.is-anomaly-warn\s*\{/); assert.match(builtCss, /tr\.is-anomaly-danger\s*\{/); assert.match(builtCss, /\[data-modern-ui="true"\][\s\S]*?tr\.is-anomaly-warn/); + assert.match(builtCss, /\.form-row\s*>\s*\.custom-select\s*>\s*\.select-trigger\s*\{[^}]*border:\s*none;[^}]*border-radius:\s*var\(--radius-pill\)/s); + assert.match(builtCss, /\.steps-header-filters\s*\{[\s\S]*?justify-content:\s*flex-end;[\s\S]*?margin-left:\s*auto;/); + assert.match(builtCss, /\.steps-inline-scope-select,\s*\.steps-inline-model-select\s*\{[\s\S]*?flex:\s*0\s+1\s+auto;/); + assert.match(builtCss, /\.steps-inline-scope-select\s+\.select-trigger[\s\S]*?border-radius:\s*var\(--radius-pill\)/); + assert.match(builtCss, /\[data-modern-ui="true"\]\s*\.form-row\s*>\s*\.custom-select\s*>\s*\.select-trigger,[\s\S]*?\.steps-inline-scope-select\s+\.select-trigger[\s\S]*?border-radius:\s*var\(--radius-pill\)[\s\S]*?var\(--modern-pill-select-bg\)/); assert.match(builtCss, /\.step-anomaly-tag\s*\{/); assert.match(builtCss, /\.step-anomaly-tip\s*\{/); assert.match(builtCss, /\.steps-anomaly-strip\s*\{/); assert.match(builtCss, /\.steps-anomaly-filterbar\s*\{/); assert.match(builtCss, /\.sstep-anomaly-dot/); + assert.match(builtCss, /\.panel\s*>\s*\.table-scroll-host\s*\{[\s\S]*?margin-right:\s*calc\(-1\s*\*\s*var\(--space-5\)\s*\+\s*2px\)/); + assert.match(builtCss, /\.panel\s*>\s*\.table-scroll-host\s*>\s*\.custom-scroll-content\s*\{[\s\S]*?padding-right:\s*calc\(var\(--space-5\)\s*-\s*2px\)/); + assert.doesNotMatch(builtCss, /\.models-analytics-pane\s*\{[^}]*padding:\s*var\(--space-3\)\s+0\s+2px/); + assert.match(builtCss, /\.trend-tip-sub\.is-grid\s*\{[\s\S]*?grid-template-columns:\s*repeat\(3,\s*minmax\(0,\s*1fr\)\)/); assert.match(builtCss, /\.trend-tip-anomaly/); assert.match(builtCss, /\[data-modern-ui="true"\]\s*\.step-anomaly-tip/); assert.match(builtCss, /\.progress-track\.ctx-segment-meter\s*\{[\s\S]*?height:\s*6px;/); diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index 6b9ea45..72bff2f 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -2064,7 +2064,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro 'Consumption sub-label renders CNY approx instead of 步费用待定' ); assert.ok(popoverEl.querySelector('.steps-panel-header'), 'Steps header flex wrapper present'); - assert.ok(popoverEl.querySelector('.steps-panel-title'), 'Steps title non-shrinking class present'); + assert.equal(popoverEl.querySelector('.steps-panel-title'), null, 'Redundant steps header title removed'); // Verify <=90d renders flush edge-to-edge SVG line chart, while >90d ('all' = 120 days) switches to GitHub-style daily heatmap grid const plotStageEl = popoverEl.querySelector('.trend-plot-stage'); @@ -2093,8 +2093,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.match(stylesCss, /\.app-shell\s*\{[^}]*max-width:\s*none;/, 'Sidecar .app-shell removes 560px width cap'); assert.match( stylesCss, - /\.models-analytics-pane\s*\{[^}]*padding:\s*var\(--space-3\)\s+0\s+2px;/, - 'Models analytics pane eliminates nested horizontal double-padding' + /\.models-analytics-pane\s*\{[^}]*padding-left:\s*0;/, + 'Models analytics pane eliminates nested left double-padding while preserving right scrollbar clearance' ); assert.doesNotMatch( stylesCss, @@ -4526,7 +4526,7 @@ test('v1.5 feedback E2E: sticky bridge port/token across hot-reloads, CDP->HTTP // 2. Verify frontend formatters, non-truncating compaction cell, custom token combo, trimmed model ID, adaptive width & CDP recovery const appJs = fs.readFileSync(new URL('../app.js', import.meta.url), 'utf8'); const stylesCss = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8'); - assert.match(stylesCss, /\.step-model-compact\s*\{[^}]*flex-shrink:\s*0;/, 'Compaction suffix never shrinks/truncates'); + assert.match(stylesCss, /\.data-table\s+tbody\s+tr\.is-compaction\s*\{[^}]*--accent-primary/, 'Compaction row uses whole-row host accent tint'); assert.match(stylesCss, /\.wm-popover-panel\s*\{[^}]*--wm-popover-w,\s*540px/, 'Popover supports dynamic CSS width variable'); const savedSettings = { @@ -4729,20 +4729,20 @@ test('v1.5 feedback E2E: sticky bridge port/token across hot-reloads, CDP->HTTP // Adaptive width expands popover to fit wide 660px table (+ 34px chrome + 4px buffer = 698px) assert.equal(popEl.style.width, '698px', 'Popover adaptively widens on wide step table to eliminate horizontal scroll'); - // Verify trimmed raw IDs (hiding gemini-, claude-, gpt-) AND non-truncating compaction suffix + // Verify trimmed raw IDs (hiding gemini-, claude-, gpt-) AND whole-row compaction tint (no inline ·压缩) const bodyRows = stepTable.querySelector('tbody').querySelectorAll('tr'); assert.equal(bodyRows.length, 3); const row0ModelName = bodyRows[0].querySelector('.step-model-name').textContent; - const row0Compact = bodyRows[0].querySelector('.step-model-compact'); assert.equal(row0ModelName, '4-hydrogen', 'Strips gemini- prefix from gemini-4-hydrogen'); - assert.equal(row0Compact.hasAttribute('hidden'), false, 'Compaction badge visible as dedicated flex-shrink:0 span'); - assert.equal(row0Compact.textContent, '·压缩', 'Compaction suffix never merged into ellipsized span'); + assert.equal(bodyRows[0].querySelector('.step-model-compact'), null, 'No inline ·压缩 span inside model cell'); + assert.equal(bodyRows[0].classList.contains('is-compaction'), true, 'Compaction step receives whole-row is-compaction class'); assert.equal(bodyRows[0].children[1].getAttribute('title'), 'gemini-4-hydrogen·压缩', 'Hover title keeps full upstream ID'); assert.equal(bodyRows[1].querySelector('.step-model-name').textContent, 'sonnet-4-6', 'Strips claude- prefix'); - assert.equal(bodyRows[1].querySelector('.step-model-compact').hasAttribute('hidden'), true); + assert.equal(bodyRows[1].classList.contains('is-compaction'), false); assert.equal(bodyRows[2].querySelector('.step-model-name').textContent, '5.4-mini', 'Strips gpt- prefix'); + assert.equal(bodyRows[2].classList.contains('is-compaction'), false); // Verify In / Out / Cache column & Custom Combo column ('context:in:cache') const ths = stepTable.querySelector('thead').querySelectorAll('th'); From 55320df9b7061804f9518a8f720e65e07f69dd9f Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Fri, 20 Nov 2026 23:29:56 +0900 Subject: [PATCH 6/8] feat(panel): graduate Modern UI as default, default language to system, and fix 5h quota boundary --- sidecars/panel/app.js | 141 ++++++++++++----- sidecars/panel/backend/api-actions.mjs | 8 + .../panel/backend/cli-statusline-config.mjs | 20 ++- sidecars/panel/backend/config.mjs | 1 + sidecars/panel/backend/local-scanner.mjs | 7 +- sidecars/panel/backend/settings-schema.mjs | 12 +- sidecars/panel/backend/usage-aggregator.mjs | 144 ++++++++++++++---- sidecars/panel/index.html | 4 +- .../panel/shared/settings-normalization.mjs | 25 ++- .../components/layout/WindowOverlayShell.js | 4 +- .../components/widgets/CapsuleBarWidget.js | 6 +- sidecars/panel/src/core/appearance.js | 18 ++- sidecars/panel/src/i18n/en-US.js | 4 +- sidecars/panel/src/i18n/index.js | 4 +- sidecars/panel/src/i18n/zh-CN.js | 6 +- sidecars/panel/src/store/telemetryStore.js | 11 +- sidecars/panel/src/views/ConsumptionView.js | 37 ++++- sidecars/panel/src/views/StepsDetailView.js | 3 +- .../src/views/settings/SettingsGeneralTab.js | 19 +-- .../src/views/settings/SettingsOtherTab.js | 2 +- sidecars/panel/test/backend.test.mjs | 19 ++- .../test/cross-module-regressions.test.mjs | 116 ++++++++++++++ sidecars/panel/test/modern-ui.test.mjs | 72 ++++++--- sidecars/panel/test/window-bridge.test.mjs | 72 +++++---- 24 files changed, 590 insertions(+), 165 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index d6e10a8..45539d0 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -2,7 +2,7 @@ 'use strict'; // --- shared/settings-normalization.mjs --- -const { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort, normalizeExperimentalModernUi } = (() => { +const { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort, normalizeModernUi, normalizeExperimentalModernUi } = (() => { /** * @fileoverview 前后端与 CLI 共用的偏好设置枚举常量、默认值与无状态纯函数归一化规则。 */ @@ -147,19 +147,19 @@ const MAX_POPOVER_WIDTH = 1080; const DEFAULT_POPOVER_WIDTH = 580; /** - * 归一化界面语言枚举(默认 `'zh-CN'`,支持 `'auto'`/`'system'` 与 `'en-US'`)。 + * 归一化界面语言枚举(默认 `'auto'`,支持 `'zh-CN'` 及 `'en-US'`)。 * * @param {unknown} lang * @returns {'auto'|'zh-CN'|'en-US'} */ function normalizeLanguageSetting(lang) { const raw = String(lang ?? '').trim(); - if (!raw) return 'zh-CN'; + if (!raw) return 'auto'; const lower = raw.toLowerCase(); if (lower === 'auto' || lower === 'system') return 'auto'; if (lower === 'en' || lower === 'en-us' || lower.startsWith('en-')) return 'en-US'; if (lower === 'zh' || lower === 'zh-cn' || lower.startsWith('zh')) return 'zh-CN'; - return 'zh-CN'; + return 'auto'; } /** @@ -453,7 +453,24 @@ function normalizeStandalonePort(port) { } /** - * 归一化实验性现代化新 UI 开关(默认 `false`)。 + * 归一化现代化 UI 开关(默认 `true`)。 + * + * @param {unknown} val + * @returns {boolean} + */ +function normalizeModernUi(val) { + if (val === undefined || val === null || val === '') return true; + if (typeof val === 'string') { + const lower = val.trim().toLowerCase(); + if (lower === 'false' || lower === '0' || lower === 'off') return false; + if (lower === 'true' || lower === '1' || lower === 'on') return true; + return true; + } + return Boolean(val); +} + +/** + * 归一化旧版实验性新 UI 字段(保留兼容,缺省返回 `false`)。 * * @param {unknown} val * @returns {boolean} @@ -465,7 +482,7 @@ function normalizeExperimentalModernUi(val) { } return Boolean(val); } -return { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort, normalizeExperimentalModernUi }; +return { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort, normalizeModernUi, normalizeExperimentalModernUi }; })(); // --- shared/telemetry-display-rules.mjs --- @@ -1074,7 +1091,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'header.statusGenerating': '生成中{suffix}', 'header.statusQuotaCached': '额度缓存', 'header.statusQuotaOffline': '额度离线', - 'header.statusLive': '实时 2s', + 'header.statusLive': '监控中', // Formatters & Common Labels 'fmt.pending': '待定', @@ -1488,10 +1505,10 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.gen.fontLg': '大', 'settings.gen.fontXl': '特大', 'settings.gen.fontHint': '等比缩放侧边栏与展开面板字号,顶栏及输入框内嵌胶囊保持紧凑定高', - 'settings.gen.modernUi': '新 UI(实验性)', + 'settings.gen.modernUi': '现代化 UI', 'settings.gen.modernUiOff': '关闭', 'settings.gen.modernUiOn': '开启', - 'settings.gen.modernUiHint': '去除大部分线框,采用柔和分层底色与更流畅的现代过渡动画', + 'settings.gen.modernUiHint': '去除大部分线框,采用柔和分层底色及更流畅的现代过渡动画', 'settings.gen.updateTitle': '版本更新', 'settings.gen.updateMode': '更新方式', 'settings.gen.updateManual': '仅提示新版本,手动更新', @@ -1783,7 +1800,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'header.statusGenerating': 'Running{suffix}', 'header.statusQuotaCached': 'Quota Cached', 'header.statusQuotaOffline': 'Quota Offline', - 'header.statusLive': 'Live 2s', + 'header.statusLive': 'Monitoring', // Formatters & Common Labels 'fmt.pending': 'N/A', @@ -2197,7 +2214,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.gen.fontLg': 'Large', 'settings.gen.fontXl': 'XL', 'settings.gen.fontHint': 'Scales sidebar and popover typography while keeping the inline capsule compact', - 'settings.gen.modernUi': 'Modern UI (Experimental)', + 'settings.gen.modernUi': 'Modern UI', 'settings.gen.modernUiOff': 'Off', 'settings.gen.modernUiOn': 'On', 'settings.gen.modernUiHint': 'Removes most borders in favor of soft tonal surfaces and smoother animations', @@ -2486,8 +2503,8 @@ function detectHostSystemLocale() { } const i18nStore = createReactiveStore({ - language: 'zh-CN', - locale: 'zh-CN', + language: 'auto', + locale: detectHostSystemLocale(), }); function setI18nLanguage(rawLang) { @@ -2528,7 +2545,7 @@ return { I18N_DICTIONARIES, normalizeI18nLanguage, detectHostSystemLocale, i18nS })(); // --- src/core/appearance.js --- -const { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normalizeClientThemeAccent, normalizeClientFontScale, normalizeClientModernUi, isModernUiActiveForElement, parseCssColorLuminance, detectHostColorScheme, applyAppearanceToRoot } = (() => { +const { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normalizeClientThemeAccent, normalizeClientFontScale, normalizeClientModernUi, resolveSettingsModernUi, isModernUiActiveForElement, parseCssColorLuminance, detectHostColorScheme, applyAppearanceToRoot } = (() => { /** * @fileoverview Theme accent palette & panel font-scale appearance engine. * Applies CSS custom properties cleanly to Sidebar `:root` and Shadow DOM hosts, @@ -2570,13 +2587,27 @@ function normalizeClientFontScale(raw) { } function normalizeClientModernUi(raw) { + if (raw === undefined || raw === null || raw === '') return true; if (typeof raw === 'string') { const lower = raw.trim().toLowerCase(); - return lower === 'true' || lower === '1' || lower === 'on'; + if (lower === 'false' || lower === '0' || lower === 'off') return false; + if (lower === 'true' || lower === '1' || lower === 'on') return true; + return true; } return Boolean(raw); } +function resolveSettingsModernUi(settings) { + if (!settings || typeof settings !== 'object') return true; + if (settings.modernUi !== undefined) { + return normalizeClientModernUi(settings.modernUi); + } + if (settings.experimentalModernUi !== undefined) { + return normalizeClientModernUi(settings.experimentalModernUi); + } + return true; +} + /** * Check whether `el` (or its Shadow DOM host / document root) is currently under `[data-modern-ui="true"]`. * @@ -2927,7 +2958,7 @@ function applyAppearanceToRoot(targetEl, settings, { includeFontScale = true } = const colorScheme = detectHostColorScheme(targetEl); setAttrIfChanged(targetEl, 'data-color-scheme', colorScheme); - const isModernUi = normalizeClientModernUi(settings?.experimentalModernUi); + const isModernUi = resolveSettingsModernUi(settings); if (isModernUi) { setAttrIfChanged(targetEl, 'data-modern-ui', 'true'); } else { @@ -2947,7 +2978,7 @@ function applyAppearanceToRoot(targetEl, settings, { includeFontScale = true } = removeAttrIfPresent(targetEl, 'data-font-scale'); } } -return { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normalizeClientThemeAccent, normalizeClientFontScale, normalizeClientModernUi, isModernUiActiveForElement, parseCssColorLuminance, detectHostColorScheme, applyAppearanceToRoot }; +return { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normalizeClientThemeAccent, normalizeClientFontScale, normalizeClientModernUi, resolveSettingsModernUi, isModernUiActiveForElement, parseCssColorLuminance, detectHostColorScheme, applyAppearanceToRoot }; })(); // --- src/core/domPatch.js --- @@ -5253,10 +5284,10 @@ function isEquivalentTelemetry(prev, next) { const pSet = prev.settings; const nSet = next.settings; - if ((pSet?.language ?? 'zh-CN') !== (nSet?.language ?? 'zh-CN')) return false; + if ((pSet?.language ?? 'auto') !== (nSet?.language ?? 'auto')) return false; if ((pSet?.themeAccent ?? 'host') !== (nSet?.themeAccent ?? 'host')) return false; if ((pSet?.fontScale ?? 'md') !== (nSet?.fontScale ?? 'md')) return false; - if (Boolean(pSet?.experimentalModernUi) !== Boolean(nSet?.experimentalModernUi)) return false; + if (resolveSettingsModernUi(pSet) !== resolveSettingsModernUi(nSet)) return false; if ((prev.hostPlatform || '') !== (next.hostPlatform || '')) return false; if ( (prev.endpoint?.id || LOCAL_ENDPOINT_ID) !== (next.endpoint?.id || LOCAL_ENDPOINT_ID) || @@ -6420,7 +6451,11 @@ async function saveSettingsPatch(patch) { if (Object.prototype.hasOwnProperty.call(safePatch, 'fontScale')) { safePatch.fontScale = normalizeClientFontScale(safePatch.fontScale); } - if (Object.prototype.hasOwnProperty.call(safePatch, 'experimentalModernUi')) { + if (Object.prototype.hasOwnProperty.call(safePatch, 'modernUi')) { + const normModern = normalizeClientModernUi(safePatch.modernUi); + safePatch.modernUi = normModern; + safePatch.experimentalModernUi = normModern; + } else if (Object.prototype.hasOwnProperty.call(safePatch, 'experimentalModernUi')) { safePatch.experimentalModernUi = normalizeClientModernUi(safePatch.experimentalModernUi); } if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) { @@ -15291,6 +15326,7 @@ function patchCapsuleOdometerText( if (!isModern || !/\d/.test(nextStr)) { if (prev?.active) { + el.textContent = ''; while (el.firstChild) el.removeChild(el.firstChild); patchAttr(el, 'data-od-active', null); patchAttr(el, 'data-od-value', null); @@ -15307,6 +15343,7 @@ function patchCapsuleOdometerText( let nodes; if (!prev?.active || prev.resetKey !== resetKey || !(prev.nodes instanceof Map)) { + el.textContent = ''; while (el.firstChild) el.removeChild(el.firstChild); nodes = new Map(); } else { @@ -15665,10 +15702,6 @@ const CapsuleBarWidget = defineComponent({ 'div', { className: 'preview-host-left is-composer', hidden: true }, [ - h('span', { className: 'preview-composer-chip' }, [ - h('span', { text: 'Auto' }), - createSvgIcon('chevron-down', { size: 10 }), - ]), h('span', { className: 'preview-composer-chip' }, [ h('span', { text: 'Carbon (High)' }), createSvgIcon('chevron-down', { size: 10 }), @@ -18890,9 +18923,9 @@ const { SettingsGeneralTab } = (() => { function getLanguageOptions() { return [ + { value: 'auto', label: t('settings.gen.langAuto') }, { value: 'zh-CN', label: t('settings.gen.langZh') }, { value: 'en-US', label: t('settings.gen.langEn') }, - { value: 'auto', label: t('settings.gen.langAuto') }, ]; } @@ -18907,8 +18940,8 @@ function getFontScaleOptions() { function getModernUiOptions() { return [ - { value: 'off', label: t('settings.gen.modernUiOff') }, { value: 'on', label: t('settings.gen.modernUiOn') }, + { value: 'off', label: t('settings.gen.modernUiOff') }, ]; } @@ -18936,10 +18969,10 @@ function formatCloudSyncTimeText(tsMs, updatedAt) { const SettingsGeneralTab = defineComponent({ name: 'SettingsGeneralTab', setup({ props, onCleanup }) { - let draftLanguage = 'zh-CN'; + let draftLanguage = 'auto'; let draftThemeAccent = 'host'; let draftFontScale = 'md'; - let draftModernUi = false; + let draftModernUi = true; let draftPluginUpdateMode = 'manual'; let latestSettings = null; let latestCloudStatus = null; @@ -19081,10 +19114,10 @@ const SettingsGeneralTab = defineComponent({ const modernUiSwitch = SegmentedControl({ ariaLabel: t('settings.gen.modernUi'), - modelValue: 'off', + modelValue: 'on', options: getModernUiOptions(), onUpdateModelValue: async (val) => { - const nextModernUi = val === 'on'; + const nextModernUi = val !== 'off'; draftModernUi = nextModernUi; modernUiSwitch.setValue(nextModernUi ? 'on' : 'off'); if (!isWindowOverlayMode() && typeof document !== 'undefined' && document.documentElement) { @@ -19094,6 +19127,7 @@ const SettingsGeneralTab = defineComponent({ ...(latestSettings || {}), themeAccent: draftThemeAccent, fontScale: draftFontScale, + modernUi: nextModernUi, experimentalModernUi: nextModernUi, }, { includeFontScale: true } @@ -19102,7 +19136,7 @@ const SettingsGeneralTab = defineComponent({ const saveToken = ++appearanceSaveSeq; showAppearanceFeedback(t('settings.saving'), 0); try { - await saveSettingsPatch({ experimentalModernUi: nextModernUi }); + await saveSettingsPatch({ modernUi: nextModernUi }); if (saveToken === appearanceSaveSeq) { showAppearanceFeedback(t('settings.saved'), 1500); } @@ -19286,7 +19320,7 @@ const SettingsGeneralTab = defineComponent({ draftLanguage = normalizeI18nLanguage(settings.language); draftThemeAccent = normalizeClientThemeAccent(settings.themeAccent); draftFontScale = normalizeClientFontScale(settings.fontScale); - draftModernUi = normalizeClientModernUi(settings.experimentalModernUi); + draftModernUi = resolveSettingsModernUi(settings); draftPluginUpdateMode = normalizeClientUpdateMode( settings.pluginUpdateMode, settings.autoUpdatePlugin @@ -21032,7 +21066,7 @@ const SettingsOtherTab = defineComponent({ showMaintFeedback(t('settings.oth.resettingBtn'), 0); try { const res = await resetAllSettings(); - setI18nLanguage(res?.settings?.language || 'zh-CN'); + setI18nLanguage(res?.settings?.language || 'auto'); showMaintFeedback(t('settings.oth.resetAllDone'), 2800); } catch { showMaintFeedback(t('settings.saveFailed'), 2800); @@ -21704,6 +21738,22 @@ function getConsumptionTimeRangeOptions() { ]; } +function floorToStartOfMinuteMs(ms) { + const n = Number(ms); + if (!(n > 0)) return 0; + const d = new Date(n); + d.setSeconds(0, 0); + return d.getTime(); +} + +function ceilToEndOfMinuteMs(ms) { + const n = Number(ms); + if (!(n > 0)) return 0; + const d = new Date(n); + d.setSeconds(59, 999); + return d.getTime(); +} + const ConsumptionView = defineComponent({ name: 'ConsumptionView', setup({ onCleanup }) { @@ -21711,6 +21761,7 @@ const ConsumptionView = defineComponent({ let draftStartMs = telemetryStore.getState().customStartMs; let draftEndMs = telemetryStore.getState().customEndMs; let hasUncommittedCustomDraft = false; + let hasCommittedCustomRange = false; const timeFilterSwitch = SegmentedControl({ ariaLabel: t('cons.rangeAria'), @@ -21719,6 +21770,19 @@ const ConsumptionView = defineComponent({ onUpdateModelValue: (nextRange) => { if (nextRange === 'custom') { const st = telemetryStore.getState(); + if (!hasCommittedCustomRange && st.selectedTimeRange !== 'custom') { + const nowMs = Date.now(); + draftStartMs = floorToStartOfMinuteMs(nowMs - 24 * 3600 * 1000); + draftEndMs = ceilToEndOfMinuteMs(nowMs); + hasUncommittedCustomDraft = false; + startPicker.setValue(draftStartMs); + endPicker.setValue(draftEndMs); + selectConsumptionTimeRange('custom', { + customStartMs: draftStartMs, + customEndMs: draftEndMs, + }); + return; + } draftStartMs = st.customStartMs; draftEndMs = st.customEndMs; hasUncommittedCustomDraft = false; @@ -21759,11 +21823,14 @@ const ConsumptionView = defineComponent({ onClick: () => { const sMs = Number(draftStartMs || 0); const eMs = Number(draftEndMs || 0); - const minMs = sMs > 0 && eMs > 0 ? Math.min(sMs, eMs) : sMs; - const maxMs = sMs > 0 && eMs > 0 ? Math.max(sMs, eMs) : eMs; + const rawMinMs = sMs > 0 && eMs > 0 ? Math.min(sMs, eMs) : sMs; + const rawMaxMs = sMs > 0 && eMs > 0 ? Math.max(sMs, eMs) : eMs; + const minMs = floorToStartOfMinuteMs(rawMinMs); + const maxMs = ceilToEndOfMinuteMs(rawMaxMs); draftStartMs = minMs; draftEndMs = maxMs; hasUncommittedCustomDraft = false; + hasCommittedCustomRange = true; startPicker.setValue(minMs); endPicker.setValue(maxMs); selectConsumptionTimeRange('custom', { @@ -24363,7 +24430,7 @@ const StepsDetailView = defineComponent({ st.telemetry?.settings?.stepTokenComboFormat ), stepTableColumns: st.telemetry?.settings?.stepTableColumns, - experimentalModernUi: Boolean(st.telemetry?.settings?.experimentalModernUi), + experimentalModernUi: resolveSettingsModernUi(st.telemetry?.settings), }), (slice) => { latestSlice = slice; @@ -26265,7 +26332,7 @@ function mountWindowOverlay() { applyAppearanceToRoot(capsuleHost, settings, { includeFontScale: false }); applyAppearanceToRoot(portalHost, settings, { includeFontScale: true }); const scaleKey = normalizeClientFontScale(settings?.fontScale); - const isModernUi = normalizeClientModernUi(settings?.experimentalModernUi); + const isModernUi = resolveSettingsModernUi(settings); const colorScheme = portalHost.getAttribute?.('data-color-scheme') || 'light'; for (const el of [popoverEl, hoverTipEl, multiPanelEl]) { if (el.getAttribute?.('data-font-scale') !== scaleKey) { diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index b5c22df..bb233c0 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -30,6 +30,7 @@ import { lsRuntimeEndpoint, normalizeFullSettings, normalizeModelDisplayMode, + normalizeModernUi, normalizePluginUpdateMode, normalizeWindowMountMode, saveJson, @@ -333,9 +334,16 @@ export function executeSettingsAction(data) { ? 'upstream' : 'short' : normalizeModelDisplayMode(current.modelDisplayMode, current.showUpstreamModel); + const nextModernUi = + payload.modernUi !== undefined + ? normalizeModernUi(payload.modernUi) + : payload.experimentalModernUi !== undefined + ? normalizeModernUi(payload.experimentalModernUi) + : normalizeModernUi(current.modernUi); const updated = normalizeFullSettings({ ...current, ...payload, + modernUi: nextModernUi, modelContextWindows: current.modelContextWindows, weeklyTokenBudget: sanitizePositiveSettingNumber( payload.weeklyTokenBudget ?? payload.weeklyTokenLimit, diff --git a/sidecars/panel/backend/cli-statusline-config.mjs b/sidecars/panel/backend/cli-statusline-config.mjs index 3571cfd..d6fa436 100644 --- a/sidecars/panel/backend/cli-statusline-config.mjs +++ b/sidecars/panel/backend/cli-statusline-config.mjs @@ -749,11 +749,29 @@ function cliRenderSingleSlot(metricKey, slotCtx, { isEn = false, useColor = true * }} [options] * @returns {string} */ +function detectCliHostLanguageIsEn() { + const envLang = String( + process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || '' + ).trim(); + if (envLang) { + return !envLang.toLowerCase().startsWith('zh'); + } + try { + const navLang = globalThis.navigator?.language; + if (navLang) { + return !String(navLang).toLowerCase().startsWith('zh'); + } + } catch { + // 忽略无 navigator 环境 + } + return false; +} + export function formatCliStatusLineCapsule(slotCtx = {}, options = {}) { const slots = normalizeTopbarCapsuleSlots(options.slots); const showMulti = options.showMultiSession !== false; const normLang = normalizeLanguageSetting(options.language); - const isEn = normLang === 'en-US'; + const isEn = normLang === 'auto' ? detectCliHostLanguageIsEn() : normLang === 'en-US'; const useColor = options.color !== false; const slotSet = new Set(slots); diff --git a/sidecars/panel/backend/config.mjs b/sidecars/panel/backend/config.mjs index 8e8a430..f51465e 100644 --- a/sidecars/panel/backend/config.mjs +++ b/sidecars/panel/backend/config.mjs @@ -42,6 +42,7 @@ export { normalizeHoverModules, normalizeLanguageSetting, normalizeModelDisplayMode, + normalizeModernUi, normalizeOrchestratorIdMode, normalizeOverviewMetrics, normalizeOverviewModules, diff --git a/sidecars/panel/backend/local-scanner.mjs b/sidecars/panel/backend/local-scanner.mjs index 45bf769..0ada7fa 100644 --- a/sidecars/panel/backend/local-scanner.mjs +++ b/sidecars/panel/backend/local-scanner.mjs @@ -1979,7 +1979,7 @@ export async function enumerateAndSyncConversations({ activeLiveActivityMemo.delete(cidLower); } - const entryAccountName = prev ? prev.accountName || '' : currentAccountName || ''; + const entryAccountName = prev?.accountName || currentAccountName || ''; const stepsWithOwners = attachStepAccountOwners( steps, prev, @@ -2085,9 +2085,8 @@ export async function enumerateAndSyncConversations({ Boolean(conv.parentConversationId) || Boolean(conv.rootConversationId && conv.rootConversationId !== cidLower); const resolvedDiskMtime = conv.diskMtimeMs ?? readConversationMtime(diskFiles); - const offlineAccountName = prev - ? prev.accountName || offlineFallback.accountName || '' - : offlineFallback.accountName || currentAccountName || ''; + const offlineAccountName = + prev?.accountName || offlineFallback.accountName || currentAccountName || ''; const offlineStepsWithOwners = attachStepAccountOwners( offlineFallback.steps, prev, diff --git a/sidecars/panel/backend/settings-schema.mjs b/sidecars/panel/backend/settings-schema.mjs index 6500ce5..3942b69 100644 --- a/sidecars/panel/backend/settings-schema.mjs +++ b/sidecars/panel/backend/settings-schema.mjs @@ -31,6 +31,7 @@ import { normalizeHoverModules, normalizeLanguageSetting, normalizeModelDisplayMode, + normalizeModernUi, normalizeOrchestratorIdMode, normalizeOverviewMetrics, normalizeOverviewModules, @@ -73,6 +74,7 @@ export { normalizeHoverModules, normalizeLanguageSetting, normalizeModelDisplayMode, + normalizeModernUi, normalizeOrchestratorIdMode, normalizeOverviewMetrics, normalizeOverviewModules, @@ -107,10 +109,11 @@ export function normalizeModelContextWindows(value) { } export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({ - language: 'zh-CN', + language: 'auto', themeAccent: 'host', fontScale: 'md', - experimentalModernUi: false, + modernUi: true, + experimentalModernUi: true, weeklyTokenBudget: 150000000, weeklyCostBudget: 100, weeklyLimitMode: 'official', @@ -173,11 +176,14 @@ export function normalizeFullSettings(rawInput) { safeRaw.modelDisplayMode, safeRaw.showUpstreamModel ); + const modernUi = + safeRaw.modernUi !== undefined ? normalizeModernUi(safeRaw.modernUi) : true; return { language: normalizeLanguageSetting(safeRaw.language), themeAccent: normalizeThemeAccent(safeRaw.themeAccent), fontScale: normalizeFontScale(safeRaw.fontScale), - experimentalModernUi: normalizeExperimentalModernUi(safeRaw.experimentalModernUi), + modernUi, + experimentalModernUi: modernUi, weeklyTokenBudget: schemaSanitizePositiveNum( safeRaw.weeklyTokenBudget ?? safeRaw.weeklyTokenLimit, DEFAULT_SETTINGS_SCHEMA.weeklyTokenBudget diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs index 824f8b5..ad2a244 100644 --- a/sidecars/panel/backend/usage-aggregator.mjs +++ b/sidecars/panel/backend/usage-aggregator.mjs @@ -35,6 +35,29 @@ function normalizeOwnerAccount(val) { return typeof val === 'string' ? val.trim().toLowerCase() : ''; } +const COMPACTION_QUOTA_SETTLE_MAX_MS = 180_000; +const STEP_QUOTA_DURATION_CAP_SEC = 600; + +/** + * 解析单步用于官方配额周期窗口(`5h` / `weekly` / `cycle`)边界比对的结算时间戳: + * 服务端配额桶的 `resetTime` 锚定在周期内首笔请求完成扣费时刻(而非 `createdAt` 发起时刻), + * 使用完成时刻(无流式计时的自动压缩 `CHECKPOINT` 步按合理结算上限及下一步发起时刻封顶)避免漏计开启新周期的首步。 + */ +function resolveStepQuotaBillingMs(st, nextStep, nowMs) { + const tMs = Number(st?.createdAtMs) > 0 ? Number(st.createdAtMs) : 0; + if (!(tMs > 0) || tMs > nowMs) return tMs; + const durSec = Number(st?.totalDurationSec); + if (Number.isFinite(durSec) && durSec > 0) { + const endMs = tMs + Math.round(Math.min(durSec, STEP_QUOTA_DURATION_CAP_SEC) * 1000); + return Math.min(nowMs, endMs); + } + if (st?.isCompactionStep) { + const nextMs = Number(nextStep?.createdAtMs) > tMs ? Number(nextStep.createdAtMs) : Infinity; + return Math.min(nowMs, nextMs, tMs + COMPACTION_QUOTA_SETTLE_MAX_MS); + } + return tMs; +} + /** * 获取本地当日 00:00:00.000 的毫秒时间戳。 * @@ -900,13 +923,16 @@ function computeFamilySessionBuckets({ const cidLower = String(entry?.cascadeId || '').toLowerCase(); if (!cidLower || !familySet.has(cidLower)) continue; const entryOwner = normalizeOwnerAccount(entry.accountName); - for (const st of entry.steps || []) { + const entrySteps = entry.steps || []; + for (let sIdx = 0; sIdx < entrySteps.length; sIdx++) { + const st = entrySteps[sIdx]; if (!st || typeof st !== 'object') continue; + const nextSt = entrySteps[sIdx + 1] || null; const stepOwner = normalizeOwnerAccount(st.accountName) || entryOwner; const includeInQuotaPools = normalizedQuotaAccount === null ? false - : normalizedQuotaAccount === '' + : normalizedQuotaAccount === '' || stepOwner === '' ? true : stepOwner === normalizedQuotaAccount; const mInfo = resolveStepModel(st); @@ -923,6 +949,7 @@ function computeFamilySessionBuckets({ const resolvedCost = Number.isFinite(stepCost) ? stepCost : 0; const unpriced = stepCost === null ? 1 : 0; const tMs = Number(st.createdAtMs) > 0 ? Number(st.createdAtMs) : 0; + const qMs = resolveStepQuotaBillingMs(st, nextSt, nowMs); const savedCost = mInfo.pricing ? (cacheTok / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache) : 0; @@ -951,39 +978,42 @@ function computeFamilySessionBuckets({ : null; let inCurrentCycle = false; - if (tMs > 0 && tMs <= nowMs) { + if (qMs > 0 && qMs <= nowMs) { if (isCustomWeeklyMode) { inCurrentCycle = tMs >= effectiveWeekStartMs; } else if (poolCycleBuckets.size > 0) { const effCycleStartMs = poolBucketEntry ? poolBucketEntry.startWkMs : cycleStartFallbackMs; - inCurrentCycle = includeInQuotaPools && tMs >= effCycleStartMs; + inCurrentCycle = includeInQuotaPools && qMs >= effCycleStartMs; } else { - inCurrentCycle = includeInQuotaPools && tMs >= cycleStartFallbackMs; + inCurrentCycle = includeInQuotaPools && qMs >= cycleStartFallbackMs; } } for (const k of presetKeys) { const w = presetWindows[k]; + const cmpMs = k === '5h' || k === 'week' ? qMs : tMs; const matchesPreset = k === 'all' ? true : k === 'cycle' ? inCurrentCycle - : tMs > 0 && tMs >= w.startMs && tMs <= w.endMs; + : cmpMs > 0 && cmpMs >= w.startMs && cmpMs <= w.endMs; if (matchesPreset) { accumulateStepIntoBucket(sessionBuckets[k], stepUsage, entry.cascadeId); } } if (selectedWindow && (!sessionBuckets[selectedWindow.key] || selectedWindow.key === 'custom')) { + const selCmpMs = + selectedWindow.key === '5h' || selectedWindow.key === 'week' ? qMs : tMs; const inSelectedWindow = selectedWindow.key === 'all' ? true : selectedWindow.key === 'cycle' ? inCurrentCycle - : tMs > 0 && tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs; + : selCmpMs > 0 && selCmpMs >= selectedWindow.startMs && selCmpMs <= selectedWindow.endMs; if (inSelectedWindow) { accumulateStepIntoBucket(selectedSessionBucket, stepUsage, entry.cascadeId); } @@ -1024,16 +1054,33 @@ function usageTimestampBoundary(dates, value, inclusive) { return start; } -function sameUsageWindows(previous, current, dates) { +function sortedQuotaBillingTimestamps(entries, nowMs) { + const dates = new Float64Array(entries.reduce((sum, entry) => sum + entry.steps.length, 0)); + let count = 0; + for (const { steps } of entries) { + for (let i = 0; i < steps.length; i++) { + const qMs = resolveStepQuotaBillingMs(steps[i], steps[i + 1] || null, nowMs); + if (qMs > 0) dates[count++] = qMs; + } + } + return dates.subarray(0, count).sort(); +} + +function isQuotaAnchoredWindowKey(key) { + return key === '5h' || key === 'week' || key === 'cycle' || String(key || '').includes(':'); +} + +function sameUsageWindows(previous, current, dates, quotaDates = dates) { return previous.length === current.length && current.every((window, index) => { const before = previous[index]; + const refDates = isQuotaAnchoredWindowKey(window.key) ? quotaDates : dates; return before.key === window.key && before.label === window.label && (before.startMs === window.startMs || - usageTimestampBoundary(dates, before.startMs, false) === - usageTimestampBoundary(dates, window.startMs, false)) && + usageTimestampBoundary(refDates, before.startMs, false) === + usageTimestampBoundary(refDates, window.startMs, false)) && (before.endMs === window.endMs || - usageTimestampBoundary(dates, before.endMs, true) === - usageTimestampBoundary(dates, window.endMs, true)); + usageTimestampBoundary(refDates, before.endMs, true) === + usageTimestampBoundary(refDates, window.endMs, true)); }); } @@ -1157,8 +1204,12 @@ export function aggregateMultiWindowUsage({ if ( trend.hourly === previous.trend.hourly && trend.first === previous.trend.first && trend.last === previous.trend.last && - sameUsageWindows(previous.windows, windows, - snapshot.dates ??= sortedUsageTimestamps(allEntriesToAggregate)) + sameUsageWindows( + previous.windows, + windows, + (snapshot.dates ??= sortedUsageTimestamps(allEntriesToAggregate)), + (snapshot.quotaDates ??= sortedQuotaBillingTimestamps(allEntriesToAggregate, nowMs)) + ) ) { snapshot.ranges.delete(selectedWindow.key); snapshot.ranges.set(selectedWindow.key, previous); @@ -1210,13 +1261,16 @@ export function aggregateMultiWindowUsage({ const srcKey = entry.appSource || 'standalone'; const srcName = USAGE_SOURCE_LABELS[srcKey] || `Antigravity (${srcKey})`; - for (const st of entry.steps || []) { + const entrySteps = entry.steps || []; + for (let sIdx = 0; sIdx < entrySteps.length; sIdx++) { + const st = entrySteps[sIdx]; if (!st || typeof st !== 'object') continue; + const nextSt = entrySteps[sIdx + 1] || null; const stepOwner = normalizeOwnerAccount(st.accountName) || entryOwner; const includeInQuotaPools = normalizedQuotaAccount === null ? false - : normalizedQuotaAccount === '' + : normalizedQuotaAccount === '' || stepOwner === '' ? true : stepOwner === normalizedQuotaAccount; const mInfo = resolveStepModel(st); @@ -1233,6 +1287,7 @@ export function aggregateMultiWindowUsage({ const resolvedCost = Number.isFinite(stepCost) ? stepCost : 0; const unpriced = stepCost === null ? 1 : 0; const tMs = Number(st.createdAtMs) > 0 ? Number(st.createdAtMs) : 0; + const qMs = resolveStepQuotaBillingMs(st, nextSt, nowMs); const savedCost = mInfo.pricing ? (cacheTok / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache) : 0; @@ -1270,37 +1325,38 @@ export function aggregateMultiWindowUsage({ hasDedicatedArgonPool ); - if (includeInQuotaPools && poolBucketEntry && tMs > 0 && tMs <= nowMs) { - if (tMs >= poolBucketEntry.start5hMs) { + if (includeInQuotaPools && poolBucketEntry && qMs > 0 && qMs <= nowMs) { + if (qMs >= poolBucketEntry.start5hMs) { accumulateStepIntoBucket(poolBucketEntry.b5h, stepUsage, cascadeId); } - if (tMs >= poolBucketEntry.startWkMs) { + if (qMs >= poolBucketEntry.startWkMs) { accumulateStepIntoBucket(poolBucketEntry.bWk, stepUsage, cascadeId); } } let inCurrentCycle = false; - if (tMs > 0 && tMs <= nowMs) { + if (qMs > 0 && qMs <= nowMs) { if (isCustomWeeklyMode) { inCurrentCycle = tMs >= presetWindows.week.startMs; } else if (poolCycleBuckets.size > 0) { const effCycleStartMs = poolBucketEntry ? poolBucketEntry.startWkMs : presetWindows.cycle.startMs; - inCurrentCycle = includeInQuotaPools && tMs >= effCycleStartMs; + inCurrentCycle = includeInQuotaPools && qMs >= effCycleStartMs; } else { - inCurrentCycle = includeInQuotaPools && tMs >= presetWindows.cycle.startMs; + inCurrentCycle = includeInQuotaPools && qMs >= presetWindows.cycle.startMs; } } for (const k of presetKeys) { const w = presetWindows[k]; + const cmpMs = k === '5h' || k === 'week' ? qMs : tMs; const matchesPreset = k === 'all' ? true : k === 'cycle' ? inCurrentCycle - : tMs > 0 && tMs >= w.startMs && tMs <= w.endMs; + : cmpMs > 0 && cmpMs >= w.startMs && cmpMs <= w.endMs; if (matchesPreset) { accumulateStepIntoBucket(accountBuckets[k], stepUsage, cascadeId); if (isCurrentConv) { @@ -1312,12 +1368,14 @@ export function aggregateMultiWindowUsage({ } } + const selCmpMs = + selectedWindow.key === '5h' || selectedWindow.key === 'week' ? qMs : tMs; const inSelectedWindow = selectedWindow.key === 'all' ? true : selectedWindow.key === 'cycle' ? inCurrentCycle - : tMs > 0 && tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs; + : selCmpMs > 0 && selCmpMs >= selectedWindow.startMs && selCmpMs <= selectedWindow.endMs; if (inSelectedWindow) { if ( @@ -1626,7 +1684,8 @@ export function aggregateSelectedWindowUsage({ sameUsageWindows( [prevWin], [selectedWindow], - (snapshot.dates ??= sortedUsageTimestamps(allEntriesToAggregate)) + (snapshot.dates ??= sortedUsageTimestamps(allEntriesToAggregate)), + (snapshot.quotaDates ??= sortedQuotaBillingTimestamps(allEntriesToAggregate, nowMs)) ) ) { const res = candidate.result; @@ -1661,6 +1720,10 @@ export function aggregateSelectedWindowUsage({ } } + const maxSettlementSlackMs = Math.max( + COMPACTION_QUOTA_SETTLE_MAX_MS, + STEP_QUOTA_DURATION_CAP_SEC * 1000 + ); let minCutoffMs = 0; let maxCutoffMs = Infinity; let canPruneByTime = false; @@ -1674,9 +1737,14 @@ export function aggregateSelectedWindowUsage({ for (const entry of poolCycleBuckets.values()) { if (entry.startWkMs < minCutoffMs) minCutoffMs = entry.startWkMs; } + minCutoffMs = Math.max(0, minCutoffMs - maxSettlementSlackMs); } else { - minCutoffMs = selectedWindow.startMs; + minCutoffMs = Math.max(0, selectedWindow.startMs - maxSettlementSlackMs); } + } else if (selectedWindow.key === '5h' || selectedWindow.key === 'week') { + canPruneByTime = true; + minCutoffMs = Math.max(0, selectedWindow.startMs - maxSettlementSlackMs); + maxCutoffMs = selectedWindow.endMs; } else if (selectedWindow.key !== 'all') { canPruneByTime = true; minCutoffMs = selectedWindow.startMs; @@ -1706,10 +1774,24 @@ export function aggregateSelectedWindowUsage({ const srcKey = entry.appSource || 'standalone'; const srcName = USAGE_SOURCE_LABELS[srcKey] || `Antigravity (${srcKey})`; - for (const st of steps) { + for (let sIdx = 0; sIdx < steps.length; sIdx++) { + const st = steps[sIdx]; if (!st || typeof st !== 'object') continue; + const nextSt = steps[sIdx + 1] || null; const tMs = Number(st.createdAtMs) > 0 ? Number(st.createdAtMs) : 0; - if (canPruneByTime && (tMs <= 0 || tMs < minCutoffMs || tMs > maxCutoffMs)) { + const qMs = resolveStepQuotaBillingMs(st, nextSt, nowMs); + const isQuotaWin = + selectedWindow.key === 'cycle' || + selectedWindow.key === '5h' || + selectedWindow.key === 'week'; + const effStepMs = isQuotaWin && !(selectedWindow.key === 'cycle' && isCustomWeeklyMode) ? qMs : tMs; + if (canPruneByTime && (effStepMs <= 0 || effStepMs < minCutoffMs || effStepMs > maxCutoffMs)) { + continue; + } + if ( + (selectedWindow.key === '5h' || selectedWindow.key === 'week') && + effStepMs < selectedWindow.startMs + ) { continue; } @@ -1720,7 +1802,7 @@ export function aggregateSelectedWindowUsage({ const includeInQuotaPools = normalizedQuotaAccount === null ? false - : normalizedQuotaAccount === '' + : normalizedQuotaAccount === '' || stepOwner === '' ? true : stepOwner === normalizedQuotaAccount; let inCurrentCycle = false; @@ -1740,9 +1822,9 @@ export function aggregateSelectedWindowUsage({ const effCycleStartMs = poolBucketEntry ? poolBucketEntry.startWkMs : selectedWindow.startMs; - inCurrentCycle = tMs >= effCycleStartMs; + inCurrentCycle = qMs >= effCycleStartMs; } else { - inCurrentCycle = includeInQuotaPools && tMs >= selectedWindow.startMs; + inCurrentCycle = includeInQuotaPools && qMs >= selectedWindow.startMs; } if (!inCurrentCycle) continue; if ( diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index a9b704c..846e030 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/shared/settings-normalization.mjs b/sidecars/panel/shared/settings-normalization.mjs index 07fdfde..99d077f 100644 --- a/sidecars/panel/shared/settings-normalization.mjs +++ b/sidecars/panel/shared/settings-normalization.mjs @@ -142,19 +142,19 @@ export const MAX_POPOVER_WIDTH = 1080; export const DEFAULT_POPOVER_WIDTH = 580; /** - * 归一化界面语言枚举(默认 `'zh-CN'`,支持 `'auto'`/`'system'` 与 `'en-US'`)。 + * 归一化界面语言枚举(默认 `'auto'`,支持 `'zh-CN'` 及 `'en-US'`)。 * * @param {unknown} lang * @returns {'auto'|'zh-CN'|'en-US'} */ export function normalizeLanguageSetting(lang) { const raw = String(lang ?? '').trim(); - if (!raw) return 'zh-CN'; + if (!raw) return 'auto'; const lower = raw.toLowerCase(); if (lower === 'auto' || lower === 'system') return 'auto'; if (lower === 'en' || lower === 'en-us' || lower.startsWith('en-')) return 'en-US'; if (lower === 'zh' || lower === 'zh-cn' || lower.startsWith('zh')) return 'zh-CN'; - return 'zh-CN'; + return 'auto'; } /** @@ -448,7 +448,24 @@ export function normalizeStandalonePort(port) { } /** - * 归一化实验性现代化新 UI 开关(默认 `false`)。 + * 归一化现代化 UI 开关(默认 `true`)。 + * + * @param {unknown} val + * @returns {boolean} + */ +export function normalizeModernUi(val) { + if (val === undefined || val === null || val === '') return true; + if (typeof val === 'string') { + const lower = val.trim().toLowerCase(); + if (lower === 'false' || lower === '0' || lower === 'off') return false; + if (lower === 'true' || lower === '1' || lower === 'on') return true; + return true; + } + return Boolean(val); +} + +/** + * 归一化旧版实验性新 UI 字段(保留兼容,缺省返回 `false`)。 * * @param {unknown} val * @returns {boolean} diff --git a/sidecars/panel/src/components/layout/WindowOverlayShell.js b/sidecars/panel/src/components/layout/WindowOverlayShell.js index ff87b01..2abcbea 100644 --- a/sidecars/panel/src/components/layout/WindowOverlayShell.js +++ b/sidecars/panel/src/components/layout/WindowOverlayShell.js @@ -21,7 +21,7 @@ import { PANEL_SCALE_FACTORS, applyAppearanceToRoot, normalizeClientFontScale, - normalizeClientModernUi, + resolveSettingsModernUi, } from '../../core/appearance.js'; import { h, @@ -1468,7 +1468,7 @@ export function mountWindowOverlay() { applyAppearanceToRoot(capsuleHost, settings, { includeFontScale: false }); applyAppearanceToRoot(portalHost, settings, { includeFontScale: true }); const scaleKey = normalizeClientFontScale(settings?.fontScale); - const isModernUi = normalizeClientModernUi(settings?.experimentalModernUi); + const isModernUi = resolveSettingsModernUi(settings); const colorScheme = portalHost.getAttribute?.('data-color-scheme') || 'light'; for (const el of [popoverEl, hoverTipEl, multiPanelEl]) { if (el.getAttribute?.('data-font-scale') !== scaleKey) { diff --git a/sidecars/panel/src/components/widgets/CapsuleBarWidget.js b/sidecars/panel/src/components/widgets/CapsuleBarWidget.js index fe78488..e2eaf0d 100644 --- a/sidecars/panel/src/components/widgets/CapsuleBarWidget.js +++ b/sidecars/panel/src/components/widgets/CapsuleBarWidget.js @@ -98,6 +98,7 @@ export function patchCapsuleOdometerText( if (!isModern || !/\d/.test(nextStr)) { if (prev?.active) { + el.textContent = ''; while (el.firstChild) el.removeChild(el.firstChild); patchAttr(el, 'data-od-active', null); patchAttr(el, 'data-od-value', null); @@ -114,6 +115,7 @@ export function patchCapsuleOdometerText( let nodes; if (!prev?.active || prev.resetKey !== resetKey || !(prev.nodes instanceof Map)) { + el.textContent = ''; while (el.firstChild) el.removeChild(el.firstChild); nodes = new Map(); } else { @@ -472,10 +474,6 @@ export const CapsuleBarWidget = defineComponent({ 'div', { className: 'preview-host-left is-composer', hidden: true }, [ - h('span', { className: 'preview-composer-chip' }, [ - h('span', { text: 'Auto' }), - createSvgIcon('chevron-down', { size: 10 }), - ]), h('span', { className: 'preview-composer-chip' }, [ h('span', { text: 'Carbon (High)' }), createSvgIcon('chevron-down', { size: 10 }), diff --git a/sidecars/panel/src/core/appearance.js b/sidecars/panel/src/core/appearance.js index 4957014..607e57e 100644 --- a/sidecars/panel/src/core/appearance.js +++ b/sidecars/panel/src/core/appearance.js @@ -39,13 +39,27 @@ export function normalizeClientFontScale(raw) { } export function normalizeClientModernUi(raw) { + if (raw === undefined || raw === null || raw === '') return true; if (typeof raw === 'string') { const lower = raw.trim().toLowerCase(); - return lower === 'true' || lower === '1' || lower === 'on'; + if (lower === 'false' || lower === '0' || lower === 'off') return false; + if (lower === 'true' || lower === '1' || lower === 'on') return true; + return true; } return Boolean(raw); } +export function resolveSettingsModernUi(settings) { + if (!settings || typeof settings !== 'object') return true; + if (settings.modernUi !== undefined) { + return normalizeClientModernUi(settings.modernUi); + } + if (settings.experimentalModernUi !== undefined) { + return normalizeClientModernUi(settings.experimentalModernUi); + } + return true; +} + /** * Check whether `el` (or its Shadow DOM host / document root) is currently under `[data-modern-ui="true"]`. * @@ -396,7 +410,7 @@ export function applyAppearanceToRoot(targetEl, settings, { includeFontScale = t const colorScheme = detectHostColorScheme(targetEl); setAttrIfChanged(targetEl, 'data-color-scheme', colorScheme); - const isModernUi = normalizeClientModernUi(settings?.experimentalModernUi); + const isModernUi = resolveSettingsModernUi(settings); if (isModernUi) { setAttrIfChanged(targetEl, 'data-modern-ui', 'true'); } else { diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 822b2ac..8ce9b07 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -31,7 +31,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'header.statusGenerating': 'Running{suffix}', 'header.statusQuotaCached': 'Quota Cached', 'header.statusQuotaOffline': 'Quota Offline', - 'header.statusLive': 'Live 2s', + 'header.statusLive': 'Monitoring', // Formatters & Common Labels 'fmt.pending': 'N/A', @@ -445,7 +445,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.gen.fontLg': 'Large', 'settings.gen.fontXl': 'XL', 'settings.gen.fontHint': 'Scales sidebar and popover typography while keeping the inline capsule compact', - 'settings.gen.modernUi': 'Modern UI (Experimental)', + 'settings.gen.modernUi': 'Modern UI', 'settings.gen.modernUiOff': 'Off', 'settings.gen.modernUiOn': 'On', 'settings.gen.modernUiHint': 'Removes most borders in favor of soft tonal surfaces and smoother animations', diff --git a/sidecars/panel/src/i18n/index.js b/sidecars/panel/src/i18n/index.js index b8088a7..c417110 100644 --- a/sidecars/panel/src/i18n/index.js +++ b/sidecars/panel/src/i18n/index.js @@ -29,8 +29,8 @@ export function detectHostSystemLocale() { } export const i18nStore = createReactiveStore({ - language: 'zh-CN', - locale: 'zh-CN', + language: 'auto', + locale: detectHostSystemLocale(), }); export function setI18nLanguage(rawLang) { diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index b2bcac0..5a40499 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -31,7 +31,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'header.statusGenerating': '生成中{suffix}', 'header.statusQuotaCached': '额度缓存', 'header.statusQuotaOffline': '额度离线', - 'header.statusLive': '实时 2s', + 'header.statusLive': '监控中', // Formatters & Common Labels 'fmt.pending': '待定', @@ -445,10 +445,10 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.gen.fontLg': '大', 'settings.gen.fontXl': '特大', 'settings.gen.fontHint': '等比缩放侧边栏与展开面板字号,顶栏及输入框内嵌胶囊保持紧凑定高', - 'settings.gen.modernUi': '新 UI(实验性)', + 'settings.gen.modernUi': '现代化 UI', 'settings.gen.modernUiOff': '关闭', 'settings.gen.modernUiOn': '开启', - 'settings.gen.modernUiHint': '去除大部分线框,采用柔和分层底色与更流畅的现代过渡动画', + 'settings.gen.modernUiHint': '去除大部分线框,采用柔和分层底色及更流畅的现代过渡动画', 'settings.gen.updateTitle': '版本更新', 'settings.gen.updateMode': '更新方式', 'settings.gen.updateManual': '仅提示新版本,手动更新', diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index e050d08..af21d05 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -23,6 +23,7 @@ import { normalizeClientFontScale, normalizeClientModernUi, normalizeClientThemeAccent, + resolveSettingsModernUi, } from '../core/appearance.js'; import { DEFAULT_HOVER_MODULES, @@ -478,10 +479,10 @@ export function isEquivalentTelemetry(prev, next) { const pSet = prev.settings; const nSet = next.settings; - if ((pSet?.language ?? 'zh-CN') !== (nSet?.language ?? 'zh-CN')) return false; + if ((pSet?.language ?? 'auto') !== (nSet?.language ?? 'auto')) return false; if ((pSet?.themeAccent ?? 'host') !== (nSet?.themeAccent ?? 'host')) return false; if ((pSet?.fontScale ?? 'md') !== (nSet?.fontScale ?? 'md')) return false; - if (Boolean(pSet?.experimentalModernUi) !== Boolean(nSet?.experimentalModernUi)) return false; + if (resolveSettingsModernUi(pSet) !== resolveSettingsModernUi(nSet)) return false; if ((prev.hostPlatform || '') !== (next.hostPlatform || '')) return false; if ( (prev.endpoint?.id || LOCAL_ENDPOINT_ID) !== (next.endpoint?.id || LOCAL_ENDPOINT_ID) || @@ -1645,7 +1646,11 @@ export async function saveSettingsPatch(patch) { if (Object.prototype.hasOwnProperty.call(safePatch, 'fontScale')) { safePatch.fontScale = normalizeClientFontScale(safePatch.fontScale); } - if (Object.prototype.hasOwnProperty.call(safePatch, 'experimentalModernUi')) { + if (Object.prototype.hasOwnProperty.call(safePatch, 'modernUi')) { + const normModern = normalizeClientModernUi(safePatch.modernUi); + safePatch.modernUi = normModern; + safePatch.experimentalModernUi = normModern; + } else if (Object.prototype.hasOwnProperty.call(safePatch, 'experimentalModernUi')) { safePatch.experimentalModernUi = normalizeClientModernUi(safePatch.experimentalModernUi); } if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) { diff --git a/sidecars/panel/src/views/ConsumptionView.js b/sidecars/panel/src/views/ConsumptionView.js index 3fee321..e3cbaf7 100644 --- a/sidecars/panel/src/views/ConsumptionView.js +++ b/sidecars/panel/src/views/ConsumptionView.js @@ -62,6 +62,22 @@ function getConsumptionTimeRangeOptions() { ]; } +function floorToStartOfMinuteMs(ms) { + const n = Number(ms); + if (!(n > 0)) return 0; + const d = new Date(n); + d.setSeconds(0, 0); + return d.getTime(); +} + +function ceilToEndOfMinuteMs(ms) { + const n = Number(ms); + if (!(n > 0)) return 0; + const d = new Date(n); + d.setSeconds(59, 999); + return d.getTime(); +} + export const ConsumptionView = defineComponent({ name: 'ConsumptionView', setup({ onCleanup }) { @@ -69,6 +85,7 @@ export const ConsumptionView = defineComponent({ let draftStartMs = telemetryStore.getState().customStartMs; let draftEndMs = telemetryStore.getState().customEndMs; let hasUncommittedCustomDraft = false; + let hasCommittedCustomRange = false; const timeFilterSwitch = SegmentedControl({ ariaLabel: t('cons.rangeAria'), @@ -77,6 +94,19 @@ export const ConsumptionView = defineComponent({ onUpdateModelValue: (nextRange) => { if (nextRange === 'custom') { const st = telemetryStore.getState(); + if (!hasCommittedCustomRange && st.selectedTimeRange !== 'custom') { + const nowMs = Date.now(); + draftStartMs = floorToStartOfMinuteMs(nowMs - 24 * 3600 * 1000); + draftEndMs = ceilToEndOfMinuteMs(nowMs); + hasUncommittedCustomDraft = false; + startPicker.setValue(draftStartMs); + endPicker.setValue(draftEndMs); + selectConsumptionTimeRange('custom', { + customStartMs: draftStartMs, + customEndMs: draftEndMs, + }); + return; + } draftStartMs = st.customStartMs; draftEndMs = st.customEndMs; hasUncommittedCustomDraft = false; @@ -117,11 +147,14 @@ export const ConsumptionView = defineComponent({ onClick: () => { const sMs = Number(draftStartMs || 0); const eMs = Number(draftEndMs || 0); - const minMs = sMs > 0 && eMs > 0 ? Math.min(sMs, eMs) : sMs; - const maxMs = sMs > 0 && eMs > 0 ? Math.max(sMs, eMs) : eMs; + const rawMinMs = sMs > 0 && eMs > 0 ? Math.min(sMs, eMs) : sMs; + const rawMaxMs = sMs > 0 && eMs > 0 ? Math.max(sMs, eMs) : eMs; + const minMs = floorToStartOfMinuteMs(rawMinMs); + const maxMs = ceilToEndOfMinuteMs(rawMaxMs); draftStartMs = minMs; draftEndMs = maxMs; hasUncommittedCustomDraft = false; + hasCommittedCustomRange = true; startPicker.setValue(minMs); endPicker.setValue(maxMs); selectConsumptionTimeRange('custom', { diff --git a/sidecars/panel/src/views/StepsDetailView.js b/sidecars/panel/src/views/StepsDetailView.js index af2e2be..ae61f48 100644 --- a/sidecars/panel/src/views/StepsDetailView.js +++ b/sidecars/panel/src/views/StepsDetailView.js @@ -5,6 +5,7 @@ * - 总汇总视图提供会话线性走势图、多模型同图趋势拟合曲线与极简高密度模型总览卡片。 */ +import { resolveSettingsModernUi } from '../core/appearance.js'; import { defineComponent } from '../core/component.js'; import { h, @@ -1372,7 +1373,7 @@ export const StepsDetailView = defineComponent({ st.telemetry?.settings?.stepTokenComboFormat ), stepTableColumns: st.telemetry?.settings?.stepTableColumns, - experimentalModernUi: Boolean(st.telemetry?.settings?.experimentalModernUi), + experimentalModernUi: resolveSettingsModernUi(st.telemetry?.settings), }), (slice) => { latestSlice = slice; diff --git a/sidecars/panel/src/views/settings/SettingsGeneralTab.js b/sidecars/panel/src/views/settings/SettingsGeneralTab.js index 2983f8c..ff88cda 100644 --- a/sidecars/panel/src/views/settings/SettingsGeneralTab.js +++ b/sidecars/panel/src/views/settings/SettingsGeneralTab.js @@ -8,8 +8,8 @@ import { defineComponent } from '../../core/component.js'; import { applyAppearanceToRoot, normalizeClientFontScale, - normalizeClientModernUi, normalizeClientThemeAccent, + resolveSettingsModernUi, } from '../../core/appearance.js'; import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js'; import { isWindowOverlayMode } from '../../core/httpClient.js'; @@ -27,9 +27,9 @@ import { SegmentedControl } from '../../components/ui/SegmentedControl.js'; function getLanguageOptions() { return [ + { value: 'auto', label: t('settings.gen.langAuto') }, { value: 'zh-CN', label: t('settings.gen.langZh') }, { value: 'en-US', label: t('settings.gen.langEn') }, - { value: 'auto', label: t('settings.gen.langAuto') }, ]; } @@ -44,8 +44,8 @@ function getFontScaleOptions() { function getModernUiOptions() { return [ - { value: 'off', label: t('settings.gen.modernUiOff') }, { value: 'on', label: t('settings.gen.modernUiOn') }, + { value: 'off', label: t('settings.gen.modernUiOff') }, ]; } @@ -73,10 +73,10 @@ function formatCloudSyncTimeText(tsMs, updatedAt) { export const SettingsGeneralTab = defineComponent({ name: 'SettingsGeneralTab', setup({ props, onCleanup }) { - let draftLanguage = 'zh-CN'; + let draftLanguage = 'auto'; let draftThemeAccent = 'host'; let draftFontScale = 'md'; - let draftModernUi = false; + let draftModernUi = true; let draftPluginUpdateMode = 'manual'; let latestSettings = null; let latestCloudStatus = null; @@ -218,10 +218,10 @@ export const SettingsGeneralTab = defineComponent({ const modernUiSwitch = SegmentedControl({ ariaLabel: t('settings.gen.modernUi'), - modelValue: 'off', + modelValue: 'on', options: getModernUiOptions(), onUpdateModelValue: async (val) => { - const nextModernUi = val === 'on'; + const nextModernUi = val !== 'off'; draftModernUi = nextModernUi; modernUiSwitch.setValue(nextModernUi ? 'on' : 'off'); if (!isWindowOverlayMode() && typeof document !== 'undefined' && document.documentElement) { @@ -231,6 +231,7 @@ export const SettingsGeneralTab = defineComponent({ ...(latestSettings || {}), themeAccent: draftThemeAccent, fontScale: draftFontScale, + modernUi: nextModernUi, experimentalModernUi: nextModernUi, }, { includeFontScale: true } @@ -239,7 +240,7 @@ export const SettingsGeneralTab = defineComponent({ const saveToken = ++appearanceSaveSeq; showAppearanceFeedback(t('settings.saving'), 0); try { - await saveSettingsPatch({ experimentalModernUi: nextModernUi }); + await saveSettingsPatch({ modernUi: nextModernUi }); if (saveToken === appearanceSaveSeq) { showAppearanceFeedback(t('settings.saved'), 1500); } @@ -423,7 +424,7 @@ export const SettingsGeneralTab = defineComponent({ draftLanguage = normalizeI18nLanguage(settings.language); draftThemeAccent = normalizeClientThemeAccent(settings.themeAccent); draftFontScale = normalizeClientFontScale(settings.fontScale); - draftModernUi = normalizeClientModernUi(settings.experimentalModernUi); + draftModernUi = resolveSettingsModernUi(settings); draftPluginUpdateMode = normalizeClientUpdateMode( settings.pluginUpdateMode, settings.autoUpdatePlugin diff --git a/sidecars/panel/src/views/settings/SettingsOtherTab.js b/sidecars/panel/src/views/settings/SettingsOtherTab.js index ca8c187..dbcbdc8 100644 --- a/sidecars/panel/src/views/settings/SettingsOtherTab.js +++ b/sidecars/panel/src/views/settings/SettingsOtherTab.js @@ -458,7 +458,7 @@ export const SettingsOtherTab = defineComponent({ showMaintFeedback(t('settings.oth.resettingBtn'), 0); try { const res = await resetAllSettings(); - setI18nLanguage(res?.settings?.language || 'zh-CN'); + setI18nLanguage(res?.settings?.language || 'auto'); showMaintFeedback(t('settings.oth.resetAllDone'), 2800); } catch { showMaintFeedback(t('settings.saveFailed'), 2800); diff --git a/sidecars/panel/test/backend.test.mjs b/sidecars/panel/test/backend.test.mjs index 1fde589..ee4f6cc 100644 --- a/sidecars/panel/test/backend.test.mjs +++ b/sidecars/panel/test/backend.test.mjs @@ -1054,12 +1054,24 @@ test('saving preferences sends the same legacy values normalized by the backend' }); test('preferences schema defaults match pre-refactor UI, migrate legacy none slots, and support reset & cache rebuild', async () => { - // 1. Default schema matches pre-refactor out-of-box UI 100% + // 1. Default schema matches v1.5.3 out-of-box UI (language='auto', modernUi=true) const hDefault = backendHarness({}); const def = hDefault.loadSettings(); - assert.equal(def.language, 'zh-CN'); + assert.equal(def.language, 'auto'); assert.equal(def.themeAccent, 'host'); assert.equal(def.fontScale, 'md'); + assert.equal(def.modernUi, true); + assert.equal(def.experimentalModernUi, true); + + // Upgrading from v1.5.2 settings.json (with experimentalModernUi: false and no modernUi key) enables modernUi=true + const hFrom152 = backendHarness({ settings: { language: 'zh-CN', experimentalModernUi: false } }); + const loadedFrom152 = hFrom152.loadSettings(); + assert.equal(loadedFrom152.modernUi, true); + assert.equal(loadedFrom152.experimentalModernUi, true); + const optOutRes = hFrom152.executeSettingsAction({ modernUi: false }); + assert.equal(optOutRes.ok, true); + assert.equal(optOutRes.updated.modernUi, false); + assert.equal(hFrom152.loadSettings().modernUi, false); assert.equal(def.pluginUpdateMode, 'manual'); assert.equal(def.windowMountMode, 'dual'); assert.equal(def.enableWindowOverlay, true); @@ -1147,7 +1159,8 @@ test('preferences schema defaults match pre-refactor UI, migrate legacy none slo // 6. executeResetSettingsAction restores full defaults cleanly const resetRes = hDefault.executeResetSettingsAction(); assert.equal(resetRes.ok, true); - assert.equal(resetRes.updated.language, 'zh-CN'); + assert.equal(resetRes.updated.language, 'auto'); + assert.equal(resetRes.updated.modernUi, true); assert.equal(resetRes.updated.themeAccent, 'host'); assert.equal(resetRes.updated.enableCliStatusLine, true); assert.equal(resetRes.updated.showStepTurnRail, false); diff --git a/sidecars/panel/test/cross-module-regressions.test.mjs b/sidecars/panel/test/cross-module-regressions.test.mjs index bca8187..62e5ee1 100644 --- a/sidecars/panel/test/cross-module-regressions.test.mjs +++ b/sidecars/panel/test/cross-module-regressions.test.mjs @@ -1376,3 +1376,119 @@ test('P2 audit fixes: standalone sqlite/proto-wire primitives, structured liveAc globalThis.window = prevWin; } }); + +test('5h quota cycle includes cycle-opening compaction CHECKPOINT and cross-boundary steps plus unattributed cold-boot cache entries', async () => { + const nowMs = Date.now(); + const start5hMs = nowMs - 2 * 3600_000; + const reset5hIso = new Date(start5hMs + 5 * 3600_000).toISOString(); + const resetWkIso = new Date(nowMs + 5 * 24 * 3600_000).toISOString(); + + // 1. Old step from expired previous cycle (2.5h before start5hMs) -> must be excluded from 5h + const oldCycleStep = { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 1 }, + createdAt: new Date(start5hMs - 2.5 * 3600_000).toISOString(), + completedAt: new Date(start5hMs - 2.5 * 3600_000 + 8_000).toISOString(), + modelUsage: { + model: 'MODEL_PLACEHOLDER_M429', + inputTokens: '100000', + cacheReadTokens: '0', + outputTokens: '5000', + }, + }, + }; + + // 2. Untimed /compact CHECKPOINT started 70s BEFORE start5hMs that settled & opened the 5h bucket -> must be included! + const compactOpeningStep = { + type: 'CORTEX_STEP_TYPE_CHECKPOINT', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 2 }, + createdAt: new Date(start5hMs - 70_000).toISOString(), + modelUsage: { + model: 'MODEL_PLACEHOLDER_M429', + inputTokens: '300000', + cacheReadTokens: '0', + outputTokens: '4000', + }, + }, + }; + + // 3. Normal step after compaction inside 5h window + const postCompactStep = { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 3 }, + createdAt: new Date(start5hMs + 120_000).toISOString(), + completedAt: new Date(start5hMs + 135_000).toISOString(), + modelUsage: { + model: 'MODEL_PLACEHOLDER_M429', + inputTokens: '6000', + cacheReadTokens: '80000', + outputTokens: '2000', + }, + }, + }; + + // 4. Cold-boot cached conversation initially saved with accountName: '' before email loaded -> included for Alice, while Bob stays excluded + const coldBootStep = { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 1 }, + createdAt: new Date(start5hMs - 40_000).toISOString(), + completedAt: new Date(start5hMs + 10_000).toISOString(), + modelUsage: { + model: 'MODEL_PLACEHOLDER_M429', + inputTokens: '10000', + cacheReadTokens: '0', + outputTokens: '1000', + }, + }, + }; + + const h = backendHarness({ + userStatus: { email: 'alice@example.com', userTier: { name: 'Google AI Ultra' } }, + quotaSummary: { + groups: [ + { + displayName: 'Gemini Models', + buckets: [ + { bucketId: 'gemini-5h', window: '5h', remainingFraction: 0.929, resetTime: reset5hIso }, + { bucketId: 'gemini-weekly', window: 'weekly', remainingFraction: 0.395, resetTime: resetWkIso }, + ], + }, + ], + }, + cache: { + 'cold-boot-conv': { + accountName: '', + signature: 'v10-model-identity:cold', + steps: extractModelSteps([coldBootStep]), + }, + 'bob-conv': { + accountName: 'bob@example.com', + signature: 'v10-model-identity:bob', + steps: extractModelSteps([postCompactStep]), + }, + }, + summaries: { + 'main-conv': { stepCount: 3, lastModifiedTime: new Date(nowMs - 10_000).toISOString(), status: 'IDLE' }, + }, + trajectories: { + 'main-conv': { trajectory: { steps: [oldCycleStep, compactOpeningStep, postCompactStep] } }, + }, + }); + + const payload = await h.buildTelemetryPayloadInternal('main-conv', false, { range: '5h' }); + const geminiPool = payload.quotas.pools.find((p) => p.poolKey === 'Gemini'); + // Includes compactOpeningStep (304,000) + postCompactStep (88,000) + coldBootStep (11,000) = 403,000 tokens (3 calls) + assert.equal(geminiPool.cycle5h.calls, 3); + assert.equal(geminiPool.cycle5h.tokens, 403_000); + // Preset 5h account bucket includes Alice's 3 calls (403k) + Bob's 1 call (88k), excluding oldCycleStep (105k) + assert.equal(payload.consumption.account.calls, 4); + assert.equal(payload.consumption.account.totalTokens, 491_000); +}); diff --git a/sidecars/panel/test/modern-ui.test.mjs b/sidecars/panel/test/modern-ui.test.mjs index 08dad6b..c33c520 100644 --- a/sidecars/panel/test/modern-ui.test.mjs +++ b/sidecars/panel/test/modern-ui.test.mjs @@ -6,6 +6,7 @@ import { DEFAULT_SETTINGS_SCHEMA, normalizeExperimentalModernUi, normalizeFullSettings, + normalizeModernUi, } from '../backend/settings-schema.mjs'; import { applyAppearanceToRoot, @@ -38,27 +39,44 @@ import { StepsDetailView } from '../src/views/StepsDetailView.js'; import { SettingsGeneralTab } from '../src/views/settings/SettingsGeneralTab.js'; import { SettingsStructureTab } from '../src/views/settings/SettingsStructureTab.js'; -test('experimentalModernUi schema normalization defaults to false and coerces boolean/string values cleanly', () => { - assert.equal(DEFAULT_SETTINGS_SCHEMA.experimentalModernUi, false); +test('modernUi schema normalization defaults to true, upgrades 1.5.2 settings without modernUi key to true, and respects explicit false', () => { + assert.equal(DEFAULT_SETTINGS_SCHEMA.language, 'auto'); + assert.equal(DEFAULT_SETTINGS_SCHEMA.modernUi, true); + assert.equal(DEFAULT_SETTINGS_SCHEMA.experimentalModernUi, true); + assert.equal(normalizeModernUi(undefined), true); + assert.equal(normalizeModernUi(false), false); + assert.equal(normalizeModernUi('off'), false); + assert.equal(normalizeModernUi(true), true); + assert.equal(normalizeModernUi('true'), true); + assert.equal(normalizeModernUi('on'), true); assert.equal(normalizeExperimentalModernUi(undefined), false); - assert.equal(normalizeExperimentalModernUi(false), false); - assert.equal(normalizeExperimentalModernUi('off'), false); - assert.equal(normalizeExperimentalModernUi(true), true); - assert.equal(normalizeExperimentalModernUi('true'), true); - assert.equal(normalizeExperimentalModernUi('on'), true); + assert.equal(normalizeClientModernUi(undefined), true); assert.equal(normalizeClientModernUi('on'), true); assert.equal(normalizeClientModernUi(false), false); + assert.equal(normalizeClientModernUi('off'), false); - assert.equal(normalizeFullSettings({}).experimentalModernUi, false); - assert.equal(normalizeFullSettings({ experimentalModernUi: true }).experimentalModernUi, true); + // Fresh 1.5.3 install -> language='auto', modernUi=true + assert.equal(normalizeFullSettings({}).language, 'auto'); + assert.equal(normalizeFullSettings({}).modernUi, true); + assert.equal(normalizeFullSettings({}).experimentalModernUi, true); + + // 1.5.2 persisted settings.json (where experimentalModernUi: false was written by default, no modernUi key) -> upgrades to true! + const upgradedFrom152 = normalizeFullSettings({ experimentalModernUi: false }); + assert.equal(upgradedFrom152.modernUi, true); + assert.equal(upgradedFrom152.experimentalModernUi, true); + + // Explicit 1.5.3 user opt-out (`modernUi: false`) -> stays false! + const explicitOff153 = normalizeFullSettings({ modernUi: false, experimentalModernUi: true }); + assert.equal(explicitOff153.modernUi, false); + assert.equal(explicitOff153.experimentalModernUi, false); assert.equal( isEquivalentTelemetry( - { settings: { experimentalModernUi: false } }, - { settings: { experimentalModernUi: true } } + { settings: { modernUi: false } }, + { settings: { modernUi: true } } ), false, - 'isEquivalentTelemetry must detect experimentalModernUi changes' + 'isEquivalentTelemetry must detect modernUi changes' ); }); @@ -182,29 +200,41 @@ test('applyAppearanceToRoot and SettingsGeneralTab toggle data-modern-ui + data- assert.equal(document.documentElement.hasAttribute('data-modern-ui'), false); assert.equal(document.documentElement.getAttribute('data-color-scheme'), 'light'); - // 2. SettingsGeneralTab renders '新 UI(实验性)' switch and toggles data-modern-ui immediately + // 2. SettingsGeneralTab renders '现代化 UI' (开启 / 关闭) and Language (跟随系统 / 简体中文 / English) tab = SettingsGeneralTab({}); document.body.appendChild(tab.el); tab.refs.renderSettings({ - language: 'zh-CN', + language: 'auto', themeAccent: 'host', fontScale: 'md', + modernUi: false, experimentalModernUi: false, pluginUpdateMode: 'manual', }); - assert.match(tab.el.textContent, /新 UI(实验性)/); - const modernBtns = tab.refs.modernUiSwitch.el.querySelectorAll('.seg-btn'); - assert.equal(modernBtns.length, 2); - assert.equal(modernBtns[0].classList.contains('is-active'), true); + assert.match(tab.el.textContent, /现代化 UI/); + assert.doesNotMatch(tab.el.textContent, /实验性/); + const langSegBtns = tab.refs.languageSwitch.el.querySelectorAll('.seg-btn'); + assert.deepEqual( + langSegBtns.map((b) => b.textContent), + ['跟随系统', '简体中文', 'English'] + ); + assert.equal(langSegBtns[0].classList.contains('is-active'), true); - // Click '开启' (index 1) - modernBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} }); + const modernBtns = tab.refs.modernUiSwitch.el.querySelectorAll('.seg-btn'); + assert.deepEqual( + modernBtns.map((b) => b.textContent), + ['开启', '关闭'] + ); + assert.equal(modernBtns[1].classList.contains('is-active'), true); + + // Click '开启' (index 0) + modernBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 15)); assert.equal(document.documentElement.getAttribute('data-modern-ui'), 'true'); assert.equal(savedPatches.length, 1); - assert.equal(savedPatches[0].experimentalModernUi, true); + assert.equal(savedPatches[0].modernUi, true); // 3. Built styles.css contains modern-ui borderless, sliding glider, and crisp pure-white light-mode rules const builtStyles = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8'); diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index 764bee0..fc39f29 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -1234,10 +1234,12 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro capsuleHost.shadowRoot.children.indexOf(capsuleBtn), 'Multi-session button sits immediately to the left of telemetry capsule' ); + assert.equal(capsuleHost.getAttribute('data-modern-ui'), 'true', 'Modern UI enabled out-of-the-box'); + const readCapVal = (el) => el.getAttribute('data-od-value') ?? el.textContent; assert.equal(multiBtn.querySelector('.svg-icon'), null, 'Multi-session button has zero SVG clutter'); assert.equal(multiBtn.classList.contains('is-running'), true); const multiLabelEl = multiBtn.querySelector('.wm-multi-label'); - assert.equal(multiLabelEl.textContent, '2 运行 · 1 子'); + assert.equal(readCapVal(multiLabelEl), '2 运行 · 1 子'); // Verify capsule reactive text (default order: 92.4 t/s without bolt SVG, 0.85s TTFT, 50% context) const defaultCapSlots = capsuleHost.shadowRoot.querySelectorAll('.wm-cap-slot'); @@ -1248,9 +1250,9 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.equal(defaultCapSlots[2].getAttribute('data-metric'), 'context'); assert.equal(speedSegEl.children.length, 1, 'Speed segment has no lightning bolt SVG'); assert.equal(speedSegEl.querySelector('.svg-icon'), null); - assert.ok(speedSegEl.children[0].textContent.includes('92.4 t/s')); - assert.equal(defaultCapSlots[1].children[0].textContent, '0.85s'); - assert.equal(ctxPctEl.textContent, '50%'); + assert.ok(readCapVal(speedSegEl.children[0]).includes('92.4 t/s')); + assert.equal(readCapVal(defaultCapSlots[1].children[0]), '0.85s'); + assert.equal(readCapVal(ctxPctEl), '50%'); // Verify hovering left multi-session button opens .wm-multi-panel with live tasks, subagents, and recent sessions const multiPanelEl = portalHost.shadowRoot.querySelector('.wm-multi-panel'); @@ -1411,22 +1413,28 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro const langBtns = generalSegControls[0].querySelectorAll('.seg-btn'); const fontScaleBtns = generalSegControls[1].querySelectorAll('.seg-btn'); const modernUiBtns = generalSegControls[2].querySelectorAll('.seg-btn'); - assert.equal(modernUiBtns.length, 2, 'Experimental Modern UI switch has 关闭 / 开启'); + assert.equal(modernUiBtns.length, 2, 'Modern UI switch has 开启 / 关闭'); + assert.equal(modernUiBtns[0].textContent, '开启'); + assert.equal(modernUiBtns[1].textContent, '关闭'); modernUiBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 30)); + assert.equal(mockSettings.modernUi, false); + assert.equal(mockSettings.experimentalModernUi, false); + assert.equal(portalHost.hasAttribute('data-modern-ui'), false); + assert.equal(popoverEl.hasAttribute('data-modern-ui'), false); + modernUiBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 30)); + assert.equal(mockSettings.modernUi, true); assert.equal(mockSettings.experimentalModernUi, true); assert.equal(portalHost.getAttribute('data-modern-ui'), 'true'); assert.equal(capsuleHost.getAttribute('data-modern-ui'), 'true'); assert.equal(popoverEl.getAttribute('data-modern-ui'), 'true'); - modernUiBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} }); - await new Promise((r) => setTimeout(r, 30)); - assert.equal(mockSettings.experimentalModernUi, false); - assert.equal(portalHost.hasAttribute('data-modern-ui'), false); - assert.equal(popoverEl.hasAttribute('data-modern-ui'), false); - assert.equal(langBtns.length, 3, 'Language switch has 简体中文 / English / 跟随宿主'); - assert.equal(langBtns[0].textContent, '简体中文'); - assert.equal(langBtns[0].classList.contains('is-active'), true, 'Default language is zh-CN'); + assert.equal(langBtns.length, 3, 'Language switch has 跟随系统 / 简体中文 / English'); + assert.equal(langBtns[0].textContent, '跟随系统'); + assert.equal(langBtns[1].textContent, '简体中文'); + assert.equal(langBtns[2].textContent, 'English'); + assert.equal(langBtns[1].classList.contains('is-active'), true, 'mockSettings language zh-CN selects index 1'); const generalSelects = generalPane.querySelectorAll('.custom-select'); assert.equal(generalSelects.length, 1, 'General tab has Update Mode select'); const updateModeSelectEl = generalSelects[0]; @@ -1466,8 +1474,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.equal(portalHost.getAttribute('data-font-scale'), 'md'); assert.equal(popoverEl.getAttribute('data-font-scale'), 'md'); - // Live i18n switch: zh-CN -> en-US -> zh-CN without page reload - langBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} }); + // Live i18n switch: zh-CN -> en-US (index 2) -> auto (index 0) -> zh-CN (index 1) without page reload + langBtns[2].dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 30)); assert.equal(mockSettings.language, 'en-US'); assert.equal(pillTabs[0].querySelector('.pill-tab-label').textContent, 'Live'); @@ -1477,6 +1485,9 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.equal(subNavBtns[2].textContent, 'Other'); langBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 30)); + assert.equal(mockSettings.language, 'auto'); + langBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 30)); assert.equal(mockSettings.language, 'zh-CN'); assert.equal(pillTabs[0].querySelector('.pill-tab-label').textContent, '实时监控'); assert.equal(subNavBtns[0].textContent, '常规'); @@ -1570,10 +1581,15 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.ok(previewCapsuleBar, 'Pane 0 mounts real CapsuleBarWidget preview'); assert.equal(previewCapsuleBar.querySelector('.preview-win-controls'), null, 'No redundant 3 window dots after capsule'); assert.equal(previewCapsuleSlots.length, 5, 'Preview CapsuleBarWidget mounts real 5 capsule slots'); - assert.equal(previewCapsuleSlots[0].children[0].textContent, '68.4 t/s', 'Preview slot 0 renders simulated speed'); + assert.equal(readCapVal(previewCapsuleSlots[0].children[0]), '68.4 t/s', 'Preview slot 0 renders simulated speed'); assert.equal(previewCapsuleSlots[0].classList.contains('tone-good'), true, 'Preview capsule 68.4 t/s shares tone-good green with cards'); - assert.equal(previewCapsuleSlots[1].children[0].textContent, '1.1s', 'Preview slot 1 renders simulated TTFT'); - assert.equal(previewCapsuleSlots[2].querySelector('.wm-ctx-pct').textContent, '56%', 'Preview slot 2 renders simulated context %'); + assert.equal(readCapVal(previewCapsuleSlots[1].children[0]), '1.1s', 'Preview slot 1 renders simulated TTFT'); + assert.equal(readCapVal(previewCapsuleSlots[2].querySelector('.wm-ctx-pct')), '56%', 'Preview slot 2 renders simulated context %'); + assert.deepEqual( + previewCapsuleBar.querySelectorAll('.preview-composer-chip').map((c) => c.textContent.trim()), + ['Carbon (High)'], + 'Composer preview bar shows only Carbon (High) chip without Auto' + ); const mountSelectEl = sec0.querySelectorAll('.custom-select')[0]; // Toggle windowMountSelect: dual -> composer -> sidebar -> dual (updating both live host & preview bar) @@ -1664,26 +1680,26 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro capRowSelects[0].querySelectorAll('.select-option')[9].dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 30)); assert.equal(capSlots[0].getAttribute('data-metric'), 'gemini_5h'); - assert.equal(capSlots[0].children[0].textContent, '余 44%'); + assert.equal(readCapVal(capSlots[0].children[0]), '余 44%'); assert.equal(previewCapsuleSlots[0].getAttribute('data-metric'), 'gemini_5h', 'Preview slot 0 mirrors gemini_5h'); - assert.equal(previewCapsuleSlots[0].children[0].textContent, '余 64%', 'Preview slot 0 renders simulated gemini_5h'); + assert.equal(readCapVal(previewCapsuleSlots[0].children[0]), '余 64%', 'Preview slot 0 renders simulated gemini_5h'); assert.equal(capSlots[1].getAttribute('data-metric'), 'ttft'); - assert.equal(capSlots[1].children[0].textContent, '0.85s'); + assert.equal(readCapVal(capSlots[1].children[0]), '0.85s'); capRowSelects[2].querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} }); capRowSelects[2].querySelectorAll('.select-option')[4].dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 30)); assert.equal(capSlots[2].getAttribute('data-metric'), 'cost'); assert.equal(capSlots[2].children.length, 1, 'Ring SVG detached cleanly when slot leaves context'); - assert.equal(capSlots[2].children[0].textContent, '$0.040'); + assert.equal(readCapVal(capSlots[2].children[0]), '$0.040'); assert.deepEqual(mockSettings.topbarCapsuleSlots, ['gemini_5h', 'ttft', 'cost']); // Move Row 1 up (left): each row has [up, down, remove], so Row 1 up is index 3 capSlotWrap.querySelectorAll('.slot-move-btn')[3].dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 30)); assert.deepEqual(mockSettings.topbarCapsuleSlots, ['ttft', 'gemini_5h', 'cost']); - assert.equal(capSlots[0].children[0].textContent, '0.85s'); - assert.equal(capSlots[1].children[0].textContent, '余 44%'); + assert.equal(readCapVal(capSlots[0].children[0]), '0.85s'); + assert.equal(readCapVal(capSlots[1].children[0]), '余 44%'); // Mouse drag-and-drop reorder: drag Row 0 ('ttft') down below Row 2 ('cost') -> ['gemini_5h', 'cost', 'ttft'] const capSlotListEl = capSlotWrap.querySelector('.editable-slot-list'); @@ -1755,7 +1771,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.equal(capSlots[1].getAttribute('data-metric'), 'ttft'); assert.equal(capSlots[2].getAttribute('data-metric'), 'context'); assert.equal(capSlots[2].children.length, 2, 'Ring SVG re-attached on Slot 2'); - assert.equal(capSlots[2].querySelector('.wm-ctx-pct').textContent, '50%'); + assert.equal(readCapVal(capSlots[2].querySelector('.wm-ctx-pct')), '50%'); // Pane 1 (3rd-level tab 'hover'): Hover Popup Modules (0..4) + real hover UI preview const sec1 = accordionSections[1]; @@ -2644,13 +2660,13 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.equal(delivered, 1); await new Promise((r) => setTimeout(r, 20)); assert.equal( - defaultCapSlots[2].querySelector('.wm-ctx-pct').textContent, + readCapVal(defaultCapSlots[2].querySelector('.wm-ctx-pct')), '25%', 'CDP relay delivered live telemetry without HTTP' ); - assert.equal(defaultCapSlots[0].children[0].textContent, '121 t/s'); + assert.equal(readCapVal(defaultCapSlots[0].children[0]), '121 t/s'); assert.equal(defaultCapSlots[1].hasAttribute('hidden'), false, 'TTFT slot stays pre-reserved even when latestTtftSec is absent'); - assert.equal(defaultCapSlots[1].children[0].textContent, '--s'); + assert.equal(readCapVal(defaultCapSlots[1].children[0]), '--s'); assert.equal( hoverLegendGrid.children[0], firstLegendSlotBefore, From 6411e49ac480a609a725084810ab3336101b3884 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Sat, 21 Nov 2026 00:41:53 +0900 Subject: [PATCH 7/8] feat(panel): unify token breakdown order and flatten tooltip cards --- sidecars/panel/app.js | 87 +++++++++++++------ .../panel/src/components/ui/FourSegmentBar.js | 10 +-- sidecars/panel/src/i18n/en-US.js | 2 +- sidecars/panel/src/i18n/zh-CN.js | 4 +- sidecars/panel/src/styles/modern-ui.css | 7 +- .../panel/src/styles/views-consumption.css | 20 ++--- sidecars/panel/src/styles/views-tables.css | 24 +++-- sidecars/panel/src/views/ConsumptionView.js | 10 +-- sidecars/panel/src/views/StepsDetailView.js | 62 ++++++++++--- sidecars/panel/styles.css | 51 ++++++----- sidecars/panel/test/consumption-bars.test.mjs | 4 + sidecars/panel/test/modern-ui.test.mjs | 12 +++ sidecars/panel/test/window-bridge.test.mjs | 2 +- 13 files changed, 200 insertions(+), 95 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 45539d0..3beaf73 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1291,7 +1291,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'cons.cacheRead': '缓存读取', 'cons.savedCost': '节省 {cost}', 'cons.outputUsage': '输出用量', - 'cons.replyAndThink': '回复 {resp} · 思考 {think}', + 'cons.replyAndThink': '思考 {think} · 回复 {resp}', 'cons.trendTitle': '用量趋势', 'cons.allTime': '全部时间', 'cons.trendHeatmapHint': '按日 ({days}天) · 悬停查看', @@ -1356,7 +1356,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'steps.modelCallsOnly': '{calls}次', 'steps.modelsSummaryPrefix': '{count} 模型 · ', 'steps.modelPerfFoot': '均速 {tps} · 首字 {ttft} · 缓存 {cache}%', - 'steps.modelSplitFoot': '入 {inTok} · 缓 {cacheTok} · 思 {thinkTok} · 正 {respTok}', + 'steps.modelSplitFoot': '输入 {inTok} · 缓存 {cacheTok} · 思考 {thinkTok} · 输出 {respTok}', 'steps.fitActiveCardTitle': '{title}(已纳入上方趋势拟合,按住 Ctrl/Shift 点击可多选对比)', 'steps.fitInactiveCardTitle': '点击在上方拟合图查看 {text}(按住 Ctrl/Shift 点击可多选同图对比)', 'steps.turnMediaOnly': '[图片/附件提问]', @@ -2000,7 +2000,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'cons.cacheRead': 'Cache Read', 'cons.savedCost': 'Saved {cost}', 'cons.outputUsage': 'Output', - 'cons.replyAndThink': 'Reply {resp} · Think {think}', + 'cons.replyAndThink': 'Think {think} · Reply {resp}', 'cons.trendTitle': 'Usage Trend', 'cons.allTime': 'All Time', 'cons.trendHeatmapHint': 'Daily ({days}d) · Hover for details', @@ -8442,8 +8442,8 @@ return { ContextSegmentMeter }; const { createFourSegmentBar } = (() => { /** * @fileoverview 通用 4 段式 Token 构成比例条组件 (FourSegmentBar). - * 用于在消费概览、热门模型明细及数据来源明细中直观展示: - * 直接输入 (Input)、缓存读取 (Cached)、内容生成 (Output) 与思考推理 (Thinking) 的 Token 占比。 + * 用于在消费概览、热门模型明细及模型总览卡片中直观展示: + * 直接输入 (Input)、缓存读取 (Cached)、思考推理 (Thinking)、内容生成 (Output) 的 Token 占比。 */ @@ -8459,18 +8459,18 @@ const { createFourSegmentBar } = (() => { * responseTokens?: number, * thinkingTokens?: number * }) => void - * }} 组件根元素与增量更新方法 + * }} 组件根元素及增量更新方法 */ function createFourSegmentBar() { const segInput = h('div', { className: 'progress-seg seg-input' }); const segCached = h('div', { className: 'progress-seg seg-cached' }); - const segOutput = h('div', { className: 'progress-seg seg-output' }); const segThinking = h('div', { className: 'progress-seg seg-thinking' }); + const segOutput = h('div', { className: 'progress-seg seg-output' }); const el = h('div', { className: 'progress-track cons-seg-bar' }, [ segInput, segCached, - segOutput, segThinking, + segOutput, ]); /** @@ -22338,16 +22338,16 @@ const ConsumptionView = defineComponent({ cacheLbl, cacheVal, ]), - h('span', { className: 'legend-left' }, [ - h('span', { className: 'dot-swatch seg-output' }), - outLbl, - outVal, - ]), h('span', { className: 'legend-left' }, [ h('span', { className: 'dot-swatch seg-thinking' }), thinkLbl, thinkVal, ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-output' }), + outLbl, + outVal, + ]), h('span', { className: 'legend-left' }, [ callsLbl, callsVal, @@ -24208,8 +24208,37 @@ const StepsDetailView = defineComponent({ const segBar = createFourSegmentBar(); segBar.el.classList.add('smodel-seg-bar'); + const inLbl = h('span', { text: t('cons.footInput') }); + const cacheLbl = h('span', { text: t('cons.footCache') }); + const thinkLbl = h('span', { text: t('cons.footThinking') }); + const outLbl = h('span', { text: t('cons.footOutput') }); + const inVal = h('strong', { className: 'text-mono' }); + const cacheVal = h('strong', { className: 'text-mono' }); + const thinkVal = h('strong', { className: 'text-mono' }); + const outVal = h('strong', { className: 'text-mono' }); + const splitEl = h('div', { className: 'smodel-split' }, [ + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-input' }), + inLbl, + inVal, + ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-cached' }), + cacheLbl, + cacheVal, + ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-thinking' }), + thinkLbl, + thinkVal, + ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-output' }), + outLbl, + outVal, + ]), + ]); const perfEl = h('span', { className: 'smodel-perf text-mono' }); - const splitEl = h('span', { className: 'smodel-split text-mono' }); const cardEl = h('div', { className: 'smodel-card' }, [ h('div', { className: 'smodel-head' }, [ @@ -24217,7 +24246,7 @@ const StepsDetailView = defineComponent({ h('div', { className: 'smodel-totals' }, [tokEl, costEl]), ]), segBar.el, - h('div', { className: 'smodel-foot' }, [perfEl, splitEl]), + h('div', { className: 'smodel-foot' }, [splitEl, perfEl]), ]); return { @@ -24231,6 +24260,14 @@ const StepsDetailView = defineComponent({ segBar, perfEl, splitEl, + inLbl, + cacheLbl, + thinkLbl, + outLbl, + inVal, + cacheVal, + thinkVal, + outVal, cardTitle: '', isHoveringAnomaly: false, }, @@ -24301,7 +24338,7 @@ const StepsDetailView = defineComponent({ ? Math.max(0, Number(m.responseTokens)) : Math.max(0, outTok - thinkTok); - patchText(refs.tokEl, formatTokens(m.totalTokens || 0)); + patchText(refs.tokEl, formatTokensPrecise(m.totalTokens || 0)); const costNum = Number(m.costUsd || 0); const isAllUnpriced = calls > 0 && Number(m.unpricedCalls || 0) >= calls && !(costNum > 0); @@ -24332,6 +24369,15 @@ const StepsDetailView = defineComponent({ ? +((cacheTok / promptTok) * 100).toFixed(1) : 0; + patchText(refs.inLbl, t('cons.footInput')); + patchText(refs.cacheLbl, t('cons.footCache')); + patchText(refs.thinkLbl, t('cons.footThinking')); + patchText(refs.outLbl, t('cons.footOutput')); + patchText(refs.inVal, formatTokensPrecise(inTok)); + patchText(refs.cacheVal, formatTokensPrecise(cacheTok)); + patchText(refs.thinkVal, formatTokensPrecise(thinkTok)); + patchText(refs.outVal, formatTokensPrecise(respTok)); + patchText( refs.perfEl, t('steps.modelPerfFoot', { @@ -24340,15 +24386,6 @@ const StepsDetailView = defineComponent({ cache: resolvedCachePct, }) ); - patchText( - refs.splitEl, - t('steps.modelSplitFoot', { - inTok: formatTokens(inTok), - cacheTok: formatTokens(cacheTok), - thinkTok: formatTokens(thinkTok), - respTok: formatTokens(respTok), - }) - ); const isActiveFit = hasMultipleModels && cardGroupKeys.some((k) => fitActiveKeySet.has(k)); diff --git a/sidecars/panel/src/components/ui/FourSegmentBar.js b/sidecars/panel/src/components/ui/FourSegmentBar.js index 31f7566..e8f281f 100644 --- a/sidecars/panel/src/components/ui/FourSegmentBar.js +++ b/sidecars/panel/src/components/ui/FourSegmentBar.js @@ -1,7 +1,7 @@ /** * @fileoverview 通用 4 段式 Token 构成比例条组件 (FourSegmentBar). - * 用于在消费概览、热门模型明细及数据来源明细中直观展示: - * 直接输入 (Input)、缓存读取 (Cached)、内容生成 (Output) 与思考推理 (Thinking) 的 Token 占比。 + * 用于在消费概览、热门模型明细及模型总览卡片中直观展示: + * 直接输入 (Input)、缓存读取 (Cached)、思考推理 (Thinking)、内容生成 (Output) 的 Token 占比。 */ import { h, patchStyleVar } from '../../core/domPatch.js'; @@ -18,18 +18,18 @@ import { h, patchStyleVar } from '../../core/domPatch.js'; * responseTokens?: number, * thinkingTokens?: number * }) => void - * }} 组件根元素与增量更新方法 + * }} 组件根元素及增量更新方法 */ export function createFourSegmentBar() { const segInput = h('div', { className: 'progress-seg seg-input' }); const segCached = h('div', { className: 'progress-seg seg-cached' }); - const segOutput = h('div', { className: 'progress-seg seg-output' }); const segThinking = h('div', { className: 'progress-seg seg-thinking' }); + const segOutput = h('div', { className: 'progress-seg seg-output' }); const el = h('div', { className: 'progress-track cons-seg-bar' }, [ segInput, segCached, - segOutput, segThinking, + segOutput, ]); /** diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 8ce9b07..34788a1 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -231,7 +231,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'cons.cacheRead': 'Cache Read', 'cons.savedCost': 'Saved {cost}', 'cons.outputUsage': 'Output', - 'cons.replyAndThink': 'Reply {resp} · Think {think}', + 'cons.replyAndThink': 'Think {think} · Reply {resp}', 'cons.trendTitle': 'Usage Trend', 'cons.allTime': 'All Time', 'cons.trendHeatmapHint': 'Daily ({days}d) · Hover for details', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 5a40499..53e888c 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -231,7 +231,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'cons.cacheRead': '缓存读取', 'cons.savedCost': '节省 {cost}', 'cons.outputUsage': '输出用量', - 'cons.replyAndThink': '回复 {resp} · 思考 {think}', + 'cons.replyAndThink': '思考 {think} · 回复 {resp}', 'cons.trendTitle': '用量趋势', 'cons.allTime': '全部时间', 'cons.trendHeatmapHint': '按日 ({days}天) · 悬停查看', @@ -296,7 +296,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'steps.modelCallsOnly': '{calls}次', 'steps.modelsSummaryPrefix': '{count} 模型 · ', 'steps.modelPerfFoot': '均速 {tps} · 首字 {ttft} · 缓存 {cache}%', - 'steps.modelSplitFoot': '入 {inTok} · 缓 {cacheTok} · 思 {thinkTok} · 正 {respTok}', + 'steps.modelSplitFoot': '输入 {inTok} · 缓存 {cacheTok} · 思考 {thinkTok} · 输出 {respTok}', 'steps.fitActiveCardTitle': '{title}(已纳入上方趋势拟合,按住 Ctrl/Shift 点击可多选对比)', 'steps.fitInactiveCardTitle': '点击在上方拟合图查看 {text}(按住 Ctrl/Shift 点击可多选同图对比)', 'steps.turnMediaOnly': '[图片/附件提问]', diff --git a/sidecars/panel/src/styles/modern-ui.css b/sidecars/panel/src/styles/modern-ui.css index 38264af..b99dcec 100644 --- a/sidecars/panel/src/styles/modern-ui.css +++ b/sidecars/panel/src/styles/modern-ui.css @@ -469,12 +469,9 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { border: none; } -[data-modern-ui="true"] .trend-tip-sub { - background: var(--modern-surface-subtle); -} - +[data-modern-ui="true"] .trend-tip-sub, [data-modern-ui="true"] .trend-tip-cost { - background: var(--modern-surface-subtle); + background: transparent; } [data-modern-ui="true"] .cons-pop-models { diff --git a/sidecars/panel/src/styles/views-consumption.css b/sidecars/panel/src/styles/views-consumption.css index 5deb3f2..b41d55a 100644 --- a/sidecars/panel/src/styles/views-consumption.css +++ b/sidecars/panel/src/styles/views-consumption.css @@ -403,13 +403,13 @@ } .trend-tip-cost { - font-size: var(--fs-sm); + font-size: var(--fs-md); font-weight: 600; line-height: 1.2; - padding: 2px 7px; - border-radius: var(--radius-xs); + padding: 0; + border-radius: 0; color: var(--text-primary); - background: color-mix(in srgb, var(--text-primary) 6%, transparent); + background: transparent; white-space: nowrap; flex-shrink: 0; } @@ -419,10 +419,10 @@ } .trend-tip-sub { - padding: 5px 8px; + padding: 2px 0; border: none; - border-radius: var(--radius-xs); - background: color-mix(in srgb, var(--text-primary) 4.2%, transparent); + border-radius: 0; + background: transparent; font-size: var(--fs-xs); line-height: 1.3; color: var(--text-secondary); @@ -438,8 +438,8 @@ .trend-tip-sub.is-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); - gap: 8px; - padding: 6px 8px; + gap: 10px; + padding: 2px 0; white-space: normal; overflow: visible; } @@ -881,7 +881,7 @@ .trend-tip-sub:not([hidden]) + .cons-pop-models { border-top: none; - padding-top: 1px; + padding-top: 2px; margin-top: 0; } diff --git a/sidecars/panel/src/styles/views-tables.css b/sidecars/panel/src/styles/views-tables.css index 3ba01f1..3f0ad24 100644 --- a/sidecars/panel/src/styles/views-tables.css +++ b/sidecars/panel/src/styles/views-tables.css @@ -1093,17 +1093,27 @@ align-items: center; justify-content: space-between; flex-wrap: wrap; - gap: 2px 10px; - font-size: var(--fs-sm); + gap: 4px 10px; + font-size: var(--fs-md); color: var(--text-secondary); } -.smodel-perf { - color: var(--text-secondary); - white-space: nowrap; -} - .smodel-split { + display: inline-flex; + align-items: center; + flex-wrap: wrap; + gap: 4px 10px; + color: var(--text-secondary); +} + +.smodel-split strong { + color: var(--text-primary); + font-weight: 600; +} + +.smodel-perf { + margin-left: auto; + font-size: var(--fs-sm); color: var(--text-muted); white-space: nowrap; } diff --git a/sidecars/panel/src/views/ConsumptionView.js b/sidecars/panel/src/views/ConsumptionView.js index e3cbaf7..f75a9b6 100644 --- a/sidecars/panel/src/views/ConsumptionView.js +++ b/sidecars/panel/src/views/ConsumptionView.js @@ -662,16 +662,16 @@ export const ConsumptionView = defineComponent({ cacheLbl, cacheVal, ]), - h('span', { className: 'legend-left' }, [ - h('span', { className: 'dot-swatch seg-output' }), - outLbl, - outVal, - ]), h('span', { className: 'legend-left' }, [ h('span', { className: 'dot-swatch seg-thinking' }), thinkLbl, thinkVal, ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-output' }), + outLbl, + outVal, + ]), h('span', { className: 'legend-left' }, [ callsLbl, callsVal, diff --git a/sidecars/panel/src/views/StepsDetailView.js b/sidecars/panel/src/views/StepsDetailView.js index ae61f48..e31a4d5 100644 --- a/sidecars/panel/src/views/StepsDetailView.js +++ b/sidecars/panel/src/views/StepsDetailView.js @@ -21,6 +21,7 @@ import { formatMetric, formatSpeedMetric, formatTokens, + formatTokensPrecise, formatUsd, mergeModelsByDisplayName, normalizeModelDisplayMode, @@ -1151,8 +1152,37 @@ export const StepsDetailView = defineComponent({ const segBar = createFourSegmentBar(); segBar.el.classList.add('smodel-seg-bar'); + const inLbl = h('span', { text: t('cons.footInput') }); + const cacheLbl = h('span', { text: t('cons.footCache') }); + const thinkLbl = h('span', { text: t('cons.footThinking') }); + const outLbl = h('span', { text: t('cons.footOutput') }); + const inVal = h('strong', { className: 'text-mono' }); + const cacheVal = h('strong', { className: 'text-mono' }); + const thinkVal = h('strong', { className: 'text-mono' }); + const outVal = h('strong', { className: 'text-mono' }); + const splitEl = h('div', { className: 'smodel-split' }, [ + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-input' }), + inLbl, + inVal, + ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-cached' }), + cacheLbl, + cacheVal, + ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-thinking' }), + thinkLbl, + thinkVal, + ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-output' }), + outLbl, + outVal, + ]), + ]); const perfEl = h('span', { className: 'smodel-perf text-mono' }); - const splitEl = h('span', { className: 'smodel-split text-mono' }); const cardEl = h('div', { className: 'smodel-card' }, [ h('div', { className: 'smodel-head' }, [ @@ -1160,7 +1190,7 @@ export const StepsDetailView = defineComponent({ h('div', { className: 'smodel-totals' }, [tokEl, costEl]), ]), segBar.el, - h('div', { className: 'smodel-foot' }, [perfEl, splitEl]), + h('div', { className: 'smodel-foot' }, [splitEl, perfEl]), ]); return { @@ -1174,6 +1204,14 @@ export const StepsDetailView = defineComponent({ segBar, perfEl, splitEl, + inLbl, + cacheLbl, + thinkLbl, + outLbl, + inVal, + cacheVal, + thinkVal, + outVal, cardTitle: '', isHoveringAnomaly: false, }, @@ -1244,7 +1282,7 @@ export const StepsDetailView = defineComponent({ ? Math.max(0, Number(m.responseTokens)) : Math.max(0, outTok - thinkTok); - patchText(refs.tokEl, formatTokens(m.totalTokens || 0)); + patchText(refs.tokEl, formatTokensPrecise(m.totalTokens || 0)); const costNum = Number(m.costUsd || 0); const isAllUnpriced = calls > 0 && Number(m.unpricedCalls || 0) >= calls && !(costNum > 0); @@ -1275,6 +1313,15 @@ export const StepsDetailView = defineComponent({ ? +((cacheTok / promptTok) * 100).toFixed(1) : 0; + patchText(refs.inLbl, t('cons.footInput')); + patchText(refs.cacheLbl, t('cons.footCache')); + patchText(refs.thinkLbl, t('cons.footThinking')); + patchText(refs.outLbl, t('cons.footOutput')); + patchText(refs.inVal, formatTokensPrecise(inTok)); + patchText(refs.cacheVal, formatTokensPrecise(cacheTok)); + patchText(refs.thinkVal, formatTokensPrecise(thinkTok)); + patchText(refs.outVal, formatTokensPrecise(respTok)); + patchText( refs.perfEl, t('steps.modelPerfFoot', { @@ -1283,15 +1330,6 @@ export const StepsDetailView = defineComponent({ cache: resolvedCachePct, }) ); - patchText( - refs.splitEl, - t('steps.modelSplitFoot', { - inTok: formatTokens(inTok), - cacheTok: formatTokens(cacheTok), - thinkTok: formatTokens(thinkTok), - respTok: formatTokens(respTok), - }) - ); const isActiveFit = hasMultipleModels && cardGroupKeys.some((k) => fitActiveKeySet.has(k)); diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index fa8f22a..e0d8a19 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -2520,13 +2520,13 @@ html[data-standalone="true"] .app-shell { } .trend-tip-cost { - font-size: var(--fs-sm); + font-size: var(--fs-md); font-weight: 600; line-height: 1.2; - padding: 2px 7px; - border-radius: var(--radius-xs); + padding: 0; + border-radius: 0; color: var(--text-primary); - background: color-mix(in srgb, var(--text-primary) 6%, transparent); + background: transparent; white-space: nowrap; flex-shrink: 0; } @@ -2536,10 +2536,10 @@ html[data-standalone="true"] .app-shell { } .trend-tip-sub { - padding: 5px 8px; + padding: 2px 0; border: none; - border-radius: var(--radius-xs); - background: color-mix(in srgb, var(--text-primary) 4.2%, transparent); + border-radius: 0; + background: transparent; font-size: var(--fs-xs); line-height: 1.3; color: var(--text-secondary); @@ -2555,8 +2555,8 @@ html[data-standalone="true"] .app-shell { .trend-tip-sub.is-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); - gap: 8px; - padding: 6px 8px; + gap: 10px; + padding: 2px 0; white-space: normal; overflow: visible; } @@ -2998,7 +2998,7 @@ html[data-standalone="true"] .app-shell { .trend-tip-sub:not([hidden]) + .cons-pop-models { border-top: none; - padding-top: 1px; + padding-top: 2px; margin-top: 0; } @@ -4239,17 +4239,27 @@ html[data-standalone="true"] .app-shell { align-items: center; justify-content: space-between; flex-wrap: wrap; - gap: 2px 10px; - font-size: var(--fs-sm); + gap: 4px 10px; + font-size: var(--fs-md); color: var(--text-secondary); } -.smodel-perf { - color: var(--text-secondary); - white-space: nowrap; -} - .smodel-split { + display: inline-flex; + align-items: center; + flex-wrap: wrap; + gap: 4px 10px; + color: var(--text-secondary); +} + +.smodel-split strong { + color: var(--text-primary); + font-weight: 600; +} + +.smodel-perf { + margin-left: auto; + font-size: var(--fs-sm); color: var(--text-muted); white-space: nowrap; } @@ -6531,12 +6541,9 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { border: none; } -[data-modern-ui="true"] .trend-tip-sub { - background: var(--modern-surface-subtle); -} - +[data-modern-ui="true"] .trend-tip-sub, [data-modern-ui="true"] .trend-tip-cost { - background: var(--modern-surface-subtle); + background: transparent; } [data-modern-ui="true"] .cons-pop-models { diff --git a/sidecars/panel/test/consumption-bars.test.mjs b/sidecars/panel/test/consumption-bars.test.mjs index 9ac8931..edc543b 100644 --- a/sidecars/panel/test/consumption-bars.test.mjs +++ b/sidecars/panel/test/consumption-bars.test.mjs @@ -103,6 +103,10 @@ test('FourSegmentBar supports percentage scaling while keeping 100% default for thinkingTokens: 100, }); const segsFull = barFull.el.querySelectorAll('.progress-seg'); + assert.deepEqual( + segsFull.map((el) => el.className.split(/\s+/).find((c) => c.startsWith('seg-'))), + ['seg-input', 'seg-cached', 'seg-thinking', 'seg-output'] + ); const sumFull = segsFull.reduce((acc, el) => acc + parsePctVar(el), 0); assert.ok(Math.abs(sumFull - 100) < 0.05); diff --git a/sidecars/panel/test/modern-ui.test.mjs b/sidecars/panel/test/modern-ui.test.mjs index c33c520..dfe111e 100644 --- a/sidecars/panel/test/modern-ui.test.mjs +++ b/sidecars/panel/test/modern-ui.test.mjs @@ -279,6 +279,18 @@ test('applyAppearanceToRoot and SettingsGeneralTab toggle data-modern-ui + data- builtStyles, /\[data-modern-ui="true"\]\s+\.trend-tooltip\.is-tracking\s*\{[^}]*150ms/ ); + assert.match( + builtStyles, + /\.trend-tip-sub\s*\{[^}]*background:\s*transparent;/ + ); + assert.match( + builtStyles, + /\.trend-tip-cost\s*\{[^}]*background:\s*transparent;/ + ); + assert.match( + builtStyles, + /\[data-modern-ui="true"\]\s+\.trend-tip-sub,\s*\[data-modern-ui="true"\]\s+\.trend-tip-cost\s*\{[^}]*background:\s*transparent;/ + ); assert.match( builtStyles, /\[data-modern-ui="true"\]\.wm-multi-panel\s+\.live-task-card[\s\S]*?background:\s*transparent;/ diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index fc39f29..35e949a 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -2341,7 +2341,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.equal(smodelCards[0].querySelector('.smodel-name').textContent, 'gemini-4-hydrogen'); assert.equal(smodelCards[0].querySelector('.smodel-calls-pill').textContent, '1次 · 50%'); assert.match(smodelCards[0].querySelector('.smodel-perf').textContent, /均速 92\.3 tok\/s · 首字 5\.6s · 缓存 93\.3%/); - assert.match(smodelCards[0].querySelector('.smodel-split').textContent, /入 2\.5k · 缓 34\.6k · 思 420 · 正 265/); + assert.match(smodelCards[0].querySelector('.smodel-split').textContent, /输入 2\.5k.*缓存 34\.6k.*思考 420.*输出 265/); // Simulate live telemetry poll where a subagent spawns on 'Gemini 3 Flash' (changing activeModelLabel) // while the user remains inside 总汇总 -> fit model MUST NOT jump! From b87541e56061bc659ccc818f116aae9b6c8265a6 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Sat, 21 Nov 2026 00:44:12 +0900 Subject: [PATCH 8/8] chore(release): bump version to v1.5.3 --- plugin.json | 2 +- pricing-catalog.json | 6 +++--- sidecars/panel/index.html | 4 ++-- sidecars/panel/package.json | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/plugin.json b/plugin.json index ca8c3bd..a65a10c 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "name": "usage-monitor", "displayName": "Usage & Speed Monitor", - "version": "1.5.2", + "version": "1.5.3", "description": "实时查看生成速度、首字延迟、上下文占用、可用额度及历史用量。", "logo": "assets/logo.svg", "suggestedPrompts": [ diff --git a/pricing-catalog.json b/pricing-catalog.json index 46b7f8e..3c9697f 100644 --- a/pricing-catalog.json +++ b/pricing-catalog.json @@ -1,8 +1,8 @@ { "schemaVersion": 1, - "catalogVersion": "2026.11.20.1", - "updatedAt": "2026-11-20T02:00:00+09:00", - "latestPluginVersion": "1.5.2", + "catalogVersion": "2026.11.21.1", + "updatedAt": "2026-11-21T00:35:00+09:00", + "latestPluginVersion": "1.5.3", "releaseUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest", "downloadUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip", "archiveFallbackUrl": "https://codeload.github.com/yuhuan-dev/antigravity-usage-monitor/zip/refs/heads/main", diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 846e030..f845963 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/package.json b/sidecars/panel/package.json index 9339e4e..c7d74e6 100644 --- a/sidecars/panel/package.json +++ b/sidecars/panel/package.json @@ -1,6 +1,6 @@ { "name": "usage-monitor-panel", - "version": "1.5.2", + "version": "1.5.3", "private": true, "type": "module", "description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor.",