From 253da45607e68379bb76b1743b459e6b836c6f97 Mon Sep 17 00:00:00 2001 From: hejun01 Date: Thu, 19 Nov 2026 18:06:12 +0800 Subject: [PATCH 1/2] 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/2] 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 } : {}), + }; +} +