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)
This commit is contained in:
hejun01
2026-11-20 11:41:39 +08:00
parent d371dc1ed5
commit 253da45607
22 changed files with 4095 additions and 310 deletions
+152 -17
View File
@@ -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() {
+140 -29
View File
@@ -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,
+22 -9
View File
@@ -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))});
})()`;
}
@@ -0,0 +1,603 @@
/**
* @fileoverview 多窗口 / SSH 远端端点注册表与按端点隔离的运行时状态存储。
*
* 职责:
* 1. 管理 `'local'`(委托既有本机全局状态,100% 向后兼容)与每个 SSH/远端窗口的独立端点上下文;
* 2. 为每个远端端点维护隔离的轨迹缓存、配额缓存、模型目录缓存、扫描冷却表与实时活动缓存;
* 3. 对具备稳定主机标识的 SSH 端点按 `<prefix>-<sha256_12>.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<string>} 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<object>)|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();
}
});
}
+118 -80
View File
@@ -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));
+94
View File
@@ -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<number>, httpPorts: Set<number>, httpsPorts: Set<number>, csrfTokens: Set<string> }}
*/
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;
}
+280 -46
View File
@@ -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<object>}
*/
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,
};
}
+142 -49
View File
@@ -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<object>}
*/
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);
}
@@ -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 {}
}
+45 -20
View File
@@ -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;
+646 -37
View File
@@ -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<number>, httpsPorts?: Set<number>, csrfTokens?: Set<string> }|null,
* confirmedLocalPorts?: Set<number>|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();
+2 -2
View File
@@ -4,11 +4,11 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>用量监控</title>
<link rel="stylesheet" href="/styles.css?v=1795098443766">
<link rel="stylesheet" href="/styles.css?v=1795146059865">
<script src="/preload.js"></script>
</head>
<body>
<div id="app-root"></div>
<script src="/app.js?v=1795098443766"></script>
<script src="/app.js?v=1795146059865"></script>
</body>
</html>
@@ -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';
@@ -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 || '';
@@ -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() {
+39 -5
View File
@@ -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);
}
};
+57 -6
View File
@@ -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)) {
+17
View File
@@ -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;
+1
View File
@@ -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,
+18
View File
@@ -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,
+4 -3
View File
@@ -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};
}
File diff suppressed because it is too large Load Diff