mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
Merge pull request #29 from juju812/main
feat(panel): support SSH remote windows with per-endpoint isolation a…
This commit is contained in:
+152
-17
@@ -717,9 +717,12 @@ return { THIRD_PARTY_POOL_RE, isThirdPartyPoolText, classifySpeedTier, classifyC
|
|||||||
})();
|
})();
|
||||||
|
|
||||||
// --- shared/window-bridge-protocol.mjs ---
|
// --- 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_KEY = '__AGUsageMonitorBridge';
|
||||||
const WINDOW_BRIDGE_ROUTE_KEY = 'hostRouteCascadeId';
|
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 WINDOW_OVERLAY_KEY = '__AGUsageMonitorOverlay';
|
||||||
const CONTEXT_WINDOWS_GLOBAL_KEY = '__AGUsageMonitorContextWindows';
|
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() {
|
function readInjectedWindowBridge() {
|
||||||
return typeof window === 'undefined' ? undefined : window[WINDOW_BRIDGE_KEY];
|
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 ---
|
// --- 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 } = {}) {
|
async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTimeoutMs = 3500 } = {}) {
|
||||||
const upperMethod = method.toUpperCase();
|
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)) {
|
if (dedupKey && inFlightGets.has(dedupKey)) {
|
||||||
return inFlightGets.get(dedupKey);
|
return inFlightGets.get(dedupKey);
|
||||||
@@ -4561,7 +4567,20 @@ async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTi
|
|||||||
signal = requestController.signal;
|
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) => {
|
const execHttpOnce = async (activeBridge) => {
|
||||||
|
ensureEndpointUnchanged(activeBridge);
|
||||||
const sidecar = typeof window !== 'undefined' ? window.sidecar : null;
|
const sidecar = typeof window !== 'undefined' ? window.sidecar : null;
|
||||||
const fetchFn = sidecar?.fetch
|
const fetchFn = sidecar?.fetch
|
||||||
? sidecar.fetch.bind(sidecar)
|
? sidecar.fetch.bind(sidecar)
|
||||||
@@ -4575,6 +4594,10 @@ async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTi
|
|||||||
}
|
}
|
||||||
if (activeBridge) {
|
if (activeBridge) {
|
||||||
headers['X-Usage-Monitor-Token'] = activeBridge.token;
|
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, {
|
const res = await fetchFn(requestUrl, {
|
||||||
method: upperMethod,
|
method: upperMethod,
|
||||||
@@ -4594,7 +4617,10 @@ async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTi
|
|||||||
throw abortErr;
|
throw abortErr;
|
||||||
}
|
}
|
||||||
if (!res.ok) {
|
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) {
|
if (activeBridge) {
|
||||||
activeBridge.transportMode = 'http';
|
activeBridge.transportMode = 'http';
|
||||||
@@ -4615,8 +4641,10 @@ async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTi
|
|||||||
if (signal?.aborted || cdpErr?.name === 'AbortError') {
|
if (signal?.aborted || cdpErr?.name === 'AbortError') {
|
||||||
throw cdpErr;
|
throw cdpErr;
|
||||||
}
|
}
|
||||||
// 热更新或守护重启期间若 CDP 尚未轮询投递,自动重置回 HTTP 并用最新桥接端口重试一次
|
// 热更新或守护重启期间若 CDP 尚未轮询投递,自动重置回 HTTP 并用最新桥接端口重试一次;
|
||||||
|
// 但若端点已切换(例如本地 <-> SSH),绝不将旧端点请求重放至新端点
|
||||||
const latestBridge = getWindowBridgeConfig() || initialBridge;
|
const latestBridge = getWindowBridgeConfig() || initialBridge;
|
||||||
|
ensureEndpointUnchanged(latestBridge);
|
||||||
latestBridge.transportMode = 'http';
|
latestBridge.transportMode = 'http';
|
||||||
return execHttpOnce(latestBridge);
|
return execHttpOnce(latestBridge);
|
||||||
}
|
}
|
||||||
@@ -4645,7 +4673,11 @@ async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTi
|
|||||||
}
|
}
|
||||||
throw fetchErr;
|
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);
|
return fallbackViaCdpWithRecovery(bridge);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -4700,7 +4732,7 @@ return { getViewTabs, uiStore, getVisibleMonitorView };
|
|||||||
})();
|
})();
|
||||||
|
|
||||||
// --- src/store/telemetryStore.js ---
|
// --- 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
|
* @fileoverview Reactive telemetry store with async non-overlapping poll scheduler
|
||||||
* and granular slice updates.
|
* and granular slice updates.
|
||||||
@@ -4801,6 +4833,7 @@ let activeBundleVersion = 0;
|
|||||||
let latestRequestSeq = 0;
|
let latestRequestSeq = 0;
|
||||||
let latestConsumptionReqSeq = 0;
|
let latestConsumptionReqSeq = 0;
|
||||||
let latestConversationSwitchSeq = 0;
|
let latestConversationSwitchSeq = 0;
|
||||||
|
let endpointSwitchEpoch = 0;
|
||||||
let activeForceCount = 0;
|
let activeForceCount = 0;
|
||||||
let consecutivePollFailures = 0;
|
let consecutivePollFailures = 0;
|
||||||
let inFlightTelemetryPoll = null;
|
let inFlightTelemetryPoll = null;
|
||||||
@@ -4853,10 +4886,11 @@ function clearConversationViewCache() {
|
|||||||
|
|
||||||
function buildConsumptionScopeSig(payload) {
|
function buildConsumptionScopeSig(payload) {
|
||||||
if (!payload || typeof payload !== 'object') return '';
|
if (!payload || typeof payload !== 'object') return '';
|
||||||
|
const ep = payload.endpoint || {};
|
||||||
const acct = payload.account || {};
|
const acct = payload.account || {};
|
||||||
const set = payload.settings || {};
|
const set = payload.settings || {};
|
||||||
const cloud = payload.cloudStatus || {};
|
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) {
|
function syncConsumptionCacheScope(payload) {
|
||||||
@@ -5128,6 +5162,13 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
if ((pSet?.fontScale ?? 'md') !== (nSet?.fontScale ?? 'md')) return false;
|
if ((pSet?.fontScale ?? 'md') !== (nSet?.fontScale ?? 'md')) return false;
|
||||||
if (Boolean(pSet?.experimentalModernUi) !== Boolean(nSet?.experimentalModernUi)) return false;
|
if (Boolean(pSet?.experimentalModernUi) !== Boolean(nSet?.experimentalModernUi)) return false;
|
||||||
if ((prev.hostPlatform || '') !== (next.hostPlatform || '')) 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)) {
|
if (Boolean(pSet?.contextWindowRiskAccepted) !== Boolean(nSet?.contextWindowRiskAccepted)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -5666,6 +5707,33 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
return true;
|
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 } = {}) {
|
async function fetchTelemetry({ force = false } = {}) {
|
||||||
if (!force && activeForceCount > 0) {
|
if (!force && activeForceCount > 0) {
|
||||||
return telemetryStore.getState().telemetry;
|
return telemetryStore.getState().telemetry;
|
||||||
@@ -5701,11 +5769,17 @@ async function fetchTelemetry({ force = false } = {}) {
|
|||||||
}
|
}
|
||||||
const query = params.toString();
|
const query = params.toString();
|
||||||
const bridge = overlay ? getWindowBridgeConfig() : null;
|
const bridge = overlay ? getWindowBridgeConfig() : null;
|
||||||
|
const endpointId = bridge?.[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID;
|
||||||
const existing = inFlightTelemetryPoll;
|
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;
|
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(() => {
|
poll.promise = requestTelemetry(params, false).finally(() => {
|
||||||
if (inFlightTelemetryPoll === poll) inFlightTelemetryPoll = null;
|
if (inFlightTelemetryPoll === poll) inFlightTelemetryPoll = null;
|
||||||
});
|
});
|
||||||
@@ -5892,6 +5966,7 @@ async function fetchConsumptionRangeSlice({
|
|||||||
customStartMs = 0,
|
customStartMs = 0,
|
||||||
customEndMs = 0,
|
customEndMs = 0,
|
||||||
} = {}) {
|
} = {}) {
|
||||||
|
const reqEpoch = endpointSwitchEpoch;
|
||||||
const reqSeq = ++latestConsumptionReqSeq;
|
const reqSeq = ++latestConsumptionReqSeq;
|
||||||
const targetRange = String(range || 'today');
|
const targetRange = String(range || 'today');
|
||||||
const current = telemetryStore.getState();
|
const current = telemetryStore.getState();
|
||||||
@@ -5910,7 +5985,7 @@ async function fetchConsumptionRangeSlice({
|
|||||||
method: 'GET',
|
method: 'GET',
|
||||||
abortKey: 'consumption-range',
|
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) {
|
if (payload.scope === 'consumption' && payload.consumption) {
|
||||||
const usageRev = Number(payload.usageRevision ?? payload.consumption.revision ?? 0);
|
const usageRev = Number(payload.usageRevision ?? payload.consumption.revision ?? 0);
|
||||||
@@ -6037,13 +6112,14 @@ async function selectConversation(
|
|||||||
params.set('stepRevision', cachedSteps?.revision || '');
|
params.set('stepRevision', cachedSteps?.revision || '');
|
||||||
params.set('scope', 'conversation');
|
params.set('scope', 'conversation');
|
||||||
|
|
||||||
|
const reqEpoch = endpointSwitchEpoch;
|
||||||
const reqSettingsRev = settingsRevision;
|
const reqSettingsRev = settingsRevision;
|
||||||
try {
|
try {
|
||||||
const payload = await callSidecarApi(`/api/telemetry?${params}`, {
|
const payload = await callSidecarApi(`/api/telemetry?${params}`, {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
abortKey: 'conversation-switch',
|
abortKey: 'conversation-switch',
|
||||||
});
|
});
|
||||||
if (!payload || typeof payload !== 'object') return null;
|
if (!payload || typeof payload !== 'object' || reqEpoch !== endpointSwitchEpoch) return null;
|
||||||
if (switchSeq !== latestConversationSwitchSeq) return payload;
|
if (switchSeq !== latestConversationSwitchSeq) return payload;
|
||||||
|
|
||||||
const latestSt = telemetryStore.getState();
|
const latestSt = telemetryStore.getState();
|
||||||
@@ -6202,11 +6278,13 @@ function prefetchConsumptionPresets() {
|
|||||||
if (effectiveConvId) params.set('conversationId', effectiveConvId);
|
if (effectiveConvId) params.set('conversationId', effectiveConvId);
|
||||||
params.set('scope', 'consumption-presets');
|
params.set('scope', 'consumption-presets');
|
||||||
|
|
||||||
|
const reqEpoch = endpointSwitchEpoch;
|
||||||
const task = callSidecarApi(`/api/telemetry?${params}`, {
|
const task = callSidecarApi(`/api/telemetry?${params}`, {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
abortKey: 'consumption-presets',
|
abortKey: 'consumption-presets',
|
||||||
})
|
})
|
||||||
.then((payload) => {
|
.then((payload) => {
|
||||||
|
if (reqEpoch !== endpointSwitchEpoch) return false;
|
||||||
if (payload?.scope === 'consumption-presets' && payload.ranges && typeof payload.ranges === 'object') {
|
if (payload?.scope === 'consumption-presets' && payload.ranges && typeof payload.ranges === 'object') {
|
||||||
const rev = Number(payload.usageRevision || currentRev || 0);
|
const rev = Number(payload.usageRevision || currentRev || 0);
|
||||||
for (const [rangeKey, entry] of Object.entries(payload.ranges)) {
|
for (const [rangeKey, entry] of Object.entries(payload.ranges)) {
|
||||||
@@ -6772,7 +6850,7 @@ function isMacHostPlatform(telemetry) {
|
|||||||
}
|
}
|
||||||
return false;
|
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 ---
|
// --- src/components/ui/TopLongPillNav.js ---
|
||||||
@@ -20966,6 +21044,12 @@ const TopSessionHeader = defineComponent({
|
|||||||
[updateBtnIcon, updateBtnText]
|
[updateBtnIcon, updateBtnText]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const sshBadge = h('span', {
|
||||||
|
className: 'endpoint-ssh-badge',
|
||||||
|
hidden: true,
|
||||||
|
text: 'SSH',
|
||||||
|
});
|
||||||
|
|
||||||
const statusIcon = createSvgIcon('pulse', { size: 12 });
|
const statusIcon = createSvgIcon('pulse', { size: 12 });
|
||||||
const statusText = h('span', { text: t('header.statusLive') });
|
const statusText = h('span', { text: t('header.statusLive') });
|
||||||
const statusTag = h('span', { className: 'status-tag' }, [statusIcon, statusText]);
|
const statusTag = h('span', { className: 'status-tag' }, [statusIcon, statusText]);
|
||||||
@@ -20983,7 +21067,7 @@ const TopSessionHeader = defineComponent({
|
|||||||
|
|
||||||
const headerRowEl = h('div', { className: 'session-header' }, [
|
const headerRowEl = h('div', { className: 'session-header' }, [
|
||||||
h('div', { className: 'session-left' }, [convSelect.el]),
|
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]);
|
const headerEl = h('header', { className: 'top-session-stack' }, [headerRowEl]);
|
||||||
@@ -21052,6 +21136,14 @@ const TopSessionHeader = defineComponent({
|
|||||||
patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate'));
|
patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate'));
|
||||||
patchAttr(refreshBtn, 'aria-label', t('header.ariaRefresh'));
|
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 actConv = telemetry?.activeConversation;
|
||||||
const convs = telemetry?.conversations || [];
|
const convs = telemetry?.conversations || [];
|
||||||
const hostRouteId = telSt.hostRouteConversationId || '';
|
const hostRouteId = telSt.hostRouteConversationId || '';
|
||||||
@@ -25497,10 +25589,18 @@ function mountWindowOverlay() {
|
|||||||
const bridgeConfig = getWindowBridgeConfig();
|
const bridgeConfig = getWindowBridgeConfig();
|
||||||
const bundleVersion = String(bridgeConfig?.bundleVersion || '');
|
const bundleVersion = String(bridgeConfig?.bundleVersion || '');
|
||||||
const stylesCss = String(bridgeConfig?.stylesCss || '');
|
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 =
|
const seedTelemetry =
|
||||||
(bridgeConfig?.initialTelemetry && typeof bridgeConfig.initialTelemetry === 'object'
|
(bridgeConfig?.initialTelemetry && typeof bridgeConfig.initialTelemetry === 'object'
|
||||||
? bridgeConfig.initialTelemetry
|
? bridgeConfig.initialTelemetry
|
||||||
: null) || carryOverTelemetry;
|
: null) || reusableCarryOver;
|
||||||
if (bridgeConfig?.initialTelemetry) {
|
if (bridgeConfig?.initialTelemetry) {
|
||||||
delete bridgeConfig.initialTelemetry;
|
delete bridgeConfig.initialTelemetry;
|
||||||
}
|
}
|
||||||
@@ -27280,14 +27380,49 @@ function mountWindowOverlay() {
|
|||||||
const token = String(nextBridge.token || '');
|
const token = String(nextBridge.token || '');
|
||||||
if (!Number.isInteger(port) || port <= 0 || !token) return false;
|
if (!Number.isInteger(port) || port <= 0 || !token) return false;
|
||||||
const cur = readInjectedWindowBridge() || {};
|
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 portChanged = Number(cur.port || 0) !== port || String(cur.token || '') !== token;
|
||||||
|
const endpointChanged = prevEndpointId !== nextEndpointId;
|
||||||
cur.port = port;
|
cur.port = port;
|
||||||
cur.token = token;
|
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';
|
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;
|
window[WINDOW_BRIDGE_KEY] = cur;
|
||||||
void fetchTelemetry({ force: false });
|
if (endpointChanged) {
|
||||||
|
resetTelemetryForEndpointSwitch();
|
||||||
|
void fetchTelemetry({ force: true });
|
||||||
|
} else {
|
||||||
|
void fetchTelemetry({ force: false });
|
||||||
|
}
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
getTelemetrySnapshot() {
|
getTelemetrySnapshot() {
|
||||||
|
|||||||
@@ -8,8 +8,14 @@
|
|||||||
|
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
import { isDeepStrictEqual } from 'node:util';
|
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 { handleAccountCredentialAction } from './account-switch.mjs';
|
||||||
|
import {
|
||||||
|
clearRemoteEndpointCaches,
|
||||||
|
resolveEndpointContext,
|
||||||
|
trackEndpointRequestEnd,
|
||||||
|
trackEndpointRequestStart,
|
||||||
|
} from './endpoint-registry.mjs';
|
||||||
import { isLocalHostRequest, readLocalAsync } from './http-helpers.mjs';
|
import { isLocalHostRequest, readLocalAsync } from './http-helpers.mjs';
|
||||||
import { clearScannerRuntimeMemos } from './local-scanner.mjs';
|
import { clearScannerRuntimeMemos } from './local-scanner.mjs';
|
||||||
import {
|
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 displayStepsCache = new Map();
|
||||||
const displayStepFields = Object.keys(projectDisplayStep({ anomaly: true, anomalySig: '' })).filter(
|
const displayStepFields = Object.keys(projectDisplayStep({ anomaly: true, anomalySig: '' })).filter(
|
||||||
(k) => k !== 'anomaly'
|
(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) {
|
function haveSameDisplaySteps(previous, current) {
|
||||||
if (!previous || !current) return previous === current;
|
if (!previous || !current) return previous === current;
|
||||||
if (previous.length !== current.length) return false;
|
if (previous.length !== current.length) return false;
|
||||||
@@ -126,12 +162,14 @@ function haveSameDisplaySteps(previous, current) {
|
|||||||
function projectDisplayTelemetry(payload, requestedRevision) {
|
function projectDisplayTelemetry(payload, requestedRevision) {
|
||||||
const active = payload.activeConversation;
|
const active = payload.activeConversation;
|
||||||
const agents = active.agents;
|
const agents = active.agents;
|
||||||
|
const endpointKey = payload.endpoint?.id || LOCAL_ENDPOINT_ID;
|
||||||
const sourceSteps = [active.recentSteps, ...agents.map((agent) => agent.recentSteps)];
|
const sourceSteps = [active.recentSteps, ...agents.map((agent) => agent.recentSteps)];
|
||||||
let projected;
|
let projected;
|
||||||
let revision;
|
let revision;
|
||||||
if (typeof requestedRevision === 'string') {
|
if (typeof requestedRevision === 'string') {
|
||||||
const cacheKey = active.cascadeId || '__empty__';
|
const cacheKey = `${endpointKey}::${active.cascadeId || '__empty__'}`;
|
||||||
const scope = [
|
const scope = [
|
||||||
|
endpointKey,
|
||||||
payload.account?.status,
|
payload.account?.status,
|
||||||
payload.account?.email || payload.account?.name || '',
|
payload.account?.email || payload.account?.name || '',
|
||||||
active.cascadeId,
|
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(
|
const rawConvId = String(
|
||||||
data?.conversationId || process.env.ANTIGRAVITY_CONVERSATION_ID || ''
|
data?.conversationId || (isRemote ? '' : process.env.ANTIGRAVITY_CONVERSATION_ID || '')
|
||||||
).trim();
|
).trim();
|
||||||
const convId = rawConvId && !/[\\/]|\.\./.test(rawConvId) ? rawConvId : '';
|
const convId = rawConvId && !/[\\/]|\.\./.test(rawConvId) ? rawConvId : '';
|
||||||
const force = data?.force === '1' || data?.force === true;
|
const force = data?.force === '1' || data?.force === true;
|
||||||
if (lsRuntimeEndpoint.addr !== 'test.invalid') {
|
if (lsRuntimeEndpoint.addr !== 'test.invalid') {
|
||||||
if (!lsRuntimeEndpoint.baseUrl) {
|
if (!isRemote && !lsRuntimeEndpoint.baseUrl) {
|
||||||
await ensureLsEndpointDiscovered({ force: false });
|
await ensureLsEndpointDiscovered({ force: false });
|
||||||
}
|
}
|
||||||
if (lsRuntimeEndpoint.baseUrl) {
|
if (isRemote || lsRuntimeEndpoint.baseUrl) {
|
||||||
if (force && Date.now() - cloudSyncState.lastAttemptMs > 15_000) {
|
if (force && Date.now() - cloudSyncState.lastAttemptMs > 15_000) {
|
||||||
await Promise.race([
|
await Promise.race([
|
||||||
syncCloudCatalog({ force: true }).catch(() => {}),
|
syncCloudCatalog({ force: true }).catch(() => {}),
|
||||||
@@ -208,8 +252,10 @@ export async function executeTelemetryAction(data, { onRestart = null } = {}) {
|
|||||||
startMs: sanitizePositiveFiniteMs(data?.startMs),
|
startMs: sanitizePositiveFiniteMs(data?.startMs),
|
||||||
endMs: sanitizePositiveFiniteMs(data?.endMs),
|
endMs: sanitizePositiveFiniteMs(data?.endMs),
|
||||||
...(scope ? { scope } : {}),
|
...(scope ? { scope } : {}),
|
||||||
|
endpoint: epCtx.endpoint,
|
||||||
};
|
};
|
||||||
let payload;
|
let payload;
|
||||||
|
trackEndpointRequestStart(epCtx.endpoint);
|
||||||
try {
|
try {
|
||||||
payload = await buildTelemetryPayload(convId, force, filterOpts);
|
payload = await buildTelemetryPayload(convId, force, filterOpts);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -225,6 +271,8 @@ export async function executeTelemetryAction(data, { onRestart = null } = {}) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
throw err;
|
throw err;
|
||||||
|
} finally {
|
||||||
|
trackEndpointRequestEnd(epCtx.endpoint);
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
bootBundleVersion &&
|
bootBundleVersion &&
|
||||||
@@ -258,7 +306,7 @@ function sanitizePositiveSettingNumber(val, fallback) {
|
|||||||
|
|
||||||
export function executeSettingsAction(data) {
|
export function executeSettingsAction(data) {
|
||||||
const current = loadSettings();
|
const current = loadSettings();
|
||||||
const payload = isPlainObject(data) ? data : {};
|
const payload = isPlainObject(data) ? stripEndpointField(data) : {};
|
||||||
const nextPluginUpdateMode =
|
const nextPluginUpdateMode =
|
||||||
payload.pluginUpdateMode !== undefined
|
payload.pluginUpdateMode !== undefined
|
||||||
? normalizePluginUpdateMode(payload.pluginUpdateMode)
|
? 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 { modelId, option } = data || {};
|
||||||
const respond = (status, payload) => ({
|
const respond = (status, payload) => ({
|
||||||
status,
|
status,
|
||||||
@@ -364,12 +416,44 @@ export async function executeModelContextWindowAction(data) {
|
|||||||
if (!isContextWindowSettingId(modelId) || (option !== null && !isContextWindowOption(option))) {
|
if (!isContextWindowSettingId(modelId) || (option !== null && !isContextWindowOption(option))) {
|
||||||
return respond(400, { error: 'Invalid model context window' });
|
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 group;
|
||||||
|
let verifiedHostConfigs = false;
|
||||||
|
trackEndpointRequestStart(epCtx.endpoint);
|
||||||
try {
|
try {
|
||||||
const [{ userStatus }, catalog] = await Promise.all([callLsRpc('GetUserStatus'), getContextModelCatalog()]);
|
let groups = null;
|
||||||
const models = getContextWindowModels(userStatus?.cascadeModelConfigData?.clientModelConfigs, catalog);
|
try {
|
||||||
group = getContextWindowGroups(models).find(({ id }) => id === modelId);
|
groups = await loadGroupsForEndpoint(epCtx.endpoint);
|
||||||
} catch {
|
} 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:')) {
|
if (option !== null || modelId.startsWith('model:')) {
|
||||||
return respond(503, { error: 'Unable to verify the host model configuration' });
|
return respond(503, { error: 'Unable to verify the host model configuration' });
|
||||||
}
|
}
|
||||||
@@ -442,8 +526,14 @@ export function executeResetSettingsAction() {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function executeRebuildCacheAction() {
|
export function executeRebuildCacheAction(data = undefined, opts = {}) {
|
||||||
const ok = clearRuntimeCaches();
|
const epCtx = resolveActionEndpoint(data, opts);
|
||||||
|
if (!epCtx.ok) {
|
||||||
|
return buildEndpointErrorResponse(epCtx);
|
||||||
|
}
|
||||||
|
const ok = epCtx.isRemote
|
||||||
|
? clearRemoteEndpointCaches(epCtx.id)
|
||||||
|
: clearRuntimeCaches();
|
||||||
if (!ok) {
|
if (!ok) {
|
||||||
return {
|
return {
|
||||||
ok: false,
|
ok: false,
|
||||||
@@ -453,15 +543,20 @@ export function executeRebuildCacheAction() {
|
|||||||
body: JSON.stringify({ ok: false, error: 'Failed to clear trajectory cache' }),
|
body: JSON.stringify({ ok: false, error: 'Failed to clear trajectory cache' }),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
displayStepsCache.clear();
|
const cachePrefix = `${epCtx.id}::`;
|
||||||
clearScannerRuntimeMemos();
|
for (const key of Array.from(displayStepsCache.keys())) {
|
||||||
clearTelemetryBuilderMemo();
|
if (key.startsWith(cachePrefix)) {
|
||||||
|
displayStepsCache.delete(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
clearScannerRuntimeMemos(epCtx.isRemote ? epCtx.id : null);
|
||||||
|
clearTelemetryBuilderMemo(epCtx.id);
|
||||||
return {
|
return {
|
||||||
ok: true,
|
ok: true,
|
||||||
status: 200,
|
status: 200,
|
||||||
contentType: 'application/json',
|
contentType: 'application/json',
|
||||||
headers: { 'Cache-Control': 'no-store' },
|
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) {
|
export async function executeAccountCredentialAction(data, opts = {}) {
|
||||||
const result = await handleAccountCredentialAction(data);
|
const epCtx = resolveActionEndpoint(data, opts);
|
||||||
if (data?.action === 'switch') {
|
if (!epCtx.ok) {
|
||||||
clearTelemetryBuilderMemo();
|
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 {
|
return {
|
||||||
status: 200,
|
status: 200,
|
||||||
@@ -531,15 +639,15 @@ export async function dispatchBridgeApiRequest(pathname, method, data, opts = un
|
|||||||
}
|
}
|
||||||
return executeSettingsAction(data);
|
return executeSettingsAction(data);
|
||||||
case 'accounts_get':
|
case 'accounts_get':
|
||||||
return executeAccountCredentialAction();
|
return executeAccountCredentialAction(undefined, opts);
|
||||||
case 'accounts_update':
|
case 'accounts_update':
|
||||||
return executeAccountCredentialAction(data);
|
return executeAccountCredentialAction(data, opts);
|
||||||
case 'context_window':
|
case 'context_window':
|
||||||
return executeModelContextWindowAction(data);
|
return executeModelContextWindowAction(data, opts);
|
||||||
case 'settings_reset':
|
case 'settings_reset':
|
||||||
return executeResetSettingsAction();
|
return executeResetSettingsAction();
|
||||||
case 'cache_rebuild':
|
case 'cache_rebuild':
|
||||||
return executeRebuildCacheAction();
|
return executeRebuildCacheAction(data, opts);
|
||||||
case 'cloud_sync':
|
case 'cloud_sync':
|
||||||
return executeCloudSyncAction();
|
return executeCloudSyncAction();
|
||||||
case 'plugin_update':
|
case 'plugin_update':
|
||||||
@@ -585,8 +693,11 @@ export function bootWindowBridgeRuntime({ allowDynamicLs = false, onRestart = nu
|
|||||||
}
|
}
|
||||||
|
|
||||||
return startDefaultWindowBridge({
|
return startDefaultWindowBridge({
|
||||||
handleApiRequest: (pathname, method, data) =>
|
handleApiRequest: (pathname, method, data, ctx) =>
|
||||||
dispatchBridgeApiRequest(pathname, method, data, { onRestart: triggerRestart }),
|
dispatchBridgeApiRequest(pathname, method, data, {
|
||||||
|
onRestart: triggerRestart,
|
||||||
|
...(ctx?.endpointId !== undefined ? { endpointId: ctx.endpointId } : {}),
|
||||||
|
}),
|
||||||
readAssetFn: readLocalAsync,
|
readAssetFn: readLocalAsync,
|
||||||
bootBundleVersion,
|
bootBundleVersion,
|
||||||
onVersionDrift: triggerRestart,
|
onVersionDrift: triggerRestart,
|
||||||
|
|||||||
@@ -121,18 +121,19 @@ export async function syncHostContextWindows(
|
|||||||
rules,
|
rules,
|
||||||
bootId,
|
bootId,
|
||||||
key = '__AGUsageMonitorContextWindows',
|
key = '__AGUsageMonitorContextWindows',
|
||||||
fallbackRules = {}
|
fallbackRules = {},
|
||||||
|
allowRemoteHost = false
|
||||||
) {
|
) {
|
||||||
let state = window[key];
|
let state = window[key];
|
||||||
const appConfig = window.__APP_CONFIG__;
|
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 hasPrefs = Boolean(rules && Object.keys(rules).length > 0);
|
||||||
const safeFallback =
|
const safeFallback =
|
||||||
fallbackRules && typeof fallbackRules === 'object' && !Array.isArray(fallbackRules)
|
fallbackRules && typeof fallbackRules === 'object' && !Array.isArray(fallbackRules)
|
||||||
? fallbackRules
|
? fallbackRules
|
||||||
: {};
|
: {};
|
||||||
const hasFallback = Object.keys(safeFallback).length > 0;
|
const hasFallback = Object.keys(safeFallback).length > 0;
|
||||||
if (!hasPrefs || appConfig?.isRemoteControl || (!csrfToken && !hasFallback)) {
|
if (!hasPrefs || (!allowRemoteHost && appConfig?.isRemoteControl) || (!csrfToken && !hasFallback)) {
|
||||||
state?.dispose();
|
state?.dispose();
|
||||||
return { attached: false, ruleCount: 0 };
|
return { attached: false, ruleCount: 0 };
|
||||||
}
|
}
|
||||||
@@ -207,10 +208,17 @@ export async function syncHostContextWindows(
|
|||||||
: '';
|
: '';
|
||||||
if (rawUrl && init?.method === 'POST') {
|
if (rawUrl && init?.method === 'POST') {
|
||||||
const url = new URL(rawUrl, window.location.href);
|
const url = new URL(rawUrl, window.location.href);
|
||||||
if (url.origin === window.location.origin && isTargetProcedure(url.pathname)) {
|
if (url.origin === window.location.origin && url.pathname.startsWith(servicePath)) {
|
||||||
const type = new Headers(init.headers).get('content-type')?.split(';')[0].trim();
|
const hdrs = new Headers(init.headers);
|
||||||
const body = rewriteBody(init.body, type);
|
const seenCsrf = hdrs.get('x-codeium-csrf-token')?.trim();
|
||||||
if (body !== init.body) nextInit = { ...init, body };
|
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 {
|
} catch {
|
||||||
@@ -312,7 +320,12 @@ export async function syncHostContextWindows(
|
|||||||
return { attached: Boolean(state.isAttached?.()), ruleCount: Object.keys(state.rules).length };
|
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 `(() => {
|
return `(() => {
|
||||||
${isContextWindowModelId.toString()}
|
${isContextWindowModelId.toString()}
|
||||||
${isContextWindowSettingId.toString()}
|
${isContextWindowSettingId.toString()}
|
||||||
@@ -321,6 +334,6 @@ export function createContextWindowSyncExpression(preferences, bootId, fallbackR
|
|||||||
${getContextWindowGroups.toString()}
|
${getContextWindowGroups.toString()}
|
||||||
${resolveContextWindowOption.toString()}
|
${resolveContextWindowOption.toString()}
|
||||||
${resolveContextWindowRules.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();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ import { isDeepStrictEqual } from 'node:util';
|
|||||||
import {
|
import {
|
||||||
extractLiveActivity,
|
extractLiveActivity,
|
||||||
extractModelSteps,
|
extractModelSteps,
|
||||||
|
extractSwarmMetaFromSteps,
|
||||||
getMaxMeaningfulStepIndex,
|
getMaxMeaningfulStepIndex,
|
||||||
isParkedOnSwarmWait,
|
isParkedOnSwarmWait,
|
||||||
parseIsoMs,
|
parseIsoMs,
|
||||||
@@ -27,15 +28,10 @@ import {
|
|||||||
CONVERSATIONS_DIR,
|
CONVERSATIONS_DIR,
|
||||||
CONVERSATION_DIRS,
|
CONVERSATION_DIRS,
|
||||||
DEEP_STATS_CACHE_CANDIDATES,
|
DEEP_STATS_CACHE_CANDIDATES,
|
||||||
getCachedTrajectory,
|
|
||||||
hasPendingTrajectoryCacheSave,
|
|
||||||
listCachedTrajectoryEntries,
|
|
||||||
externalDeepStatsMemo,
|
externalDeepStatsMemo,
|
||||||
loadJson,
|
loadJson,
|
||||||
persistTrajectoryCacheIfNeeded,
|
|
||||||
removeCachedTrajectory,
|
|
||||||
setCachedTrajectory,
|
|
||||||
} from './config.mjs';
|
} from './config.mjs';
|
||||||
|
import { getEndpointCacheStore, getRegisteredRemoteEndpoint } from './endpoint-registry.mjs';
|
||||||
import {
|
import {
|
||||||
computeSqliteWalSig,
|
computeSqliteWalSig,
|
||||||
hasBuiltinNodeSqlite,
|
hasBuiltinNodeSqlite,
|
||||||
@@ -364,7 +360,15 @@ const liveActivityMemo = new Map();
|
|||||||
const transcriptTailMemo = new Map();
|
const transcriptTailMemo = new Map();
|
||||||
const swarmManifestMemo = 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();
|
failedFetchCooldownMap.clear();
|
||||||
liveActivityMemo.clear();
|
liveActivityMemo.clear();
|
||||||
transcriptTailMemo.clear();
|
transcriptTailMemo.clear();
|
||||||
@@ -1192,11 +1196,17 @@ function scoreLiveActivitySpecificity(act) {
|
|||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolveBestLiveActivity(cascadeId, rpcRawSteps, isRunning, fallbackMs) {
|
function resolveBestLiveActivity(
|
||||||
|
cascadeId,
|
||||||
|
rpcRawSteps,
|
||||||
|
isRunning,
|
||||||
|
fallbackMs,
|
||||||
|
{ isRemote = false, liveActivityMemoMap = liveActivityMemo } = {}
|
||||||
|
) {
|
||||||
if (!isRunning) return null;
|
if (!isRunning) return null;
|
||||||
const hasRpcSteps = Array.isArray(rpcRawSteps) && rpcRawSteps.length > 0;
|
const hasRpcSteps = Array.isArray(rpcRawSteps) && rpcRawSteps.length > 0;
|
||||||
const rpcAct = hasRpcSteps ? extractLiveActivity(rpcRawSteps, true, fallbackMs) : null;
|
const rpcAct = hasRpcSteps ? extractLiveActivity(rpcRawSteps, true, fallbackMs) : null;
|
||||||
const transcriptSteps = readTranscriptTailSteps(cascadeId);
|
const transcriptSteps = isRemote ? [] : readTranscriptTailSteps(cascadeId);
|
||||||
const transcriptAct =
|
const transcriptAct =
|
||||||
transcriptSteps.length > 0 ? extractLiveActivity(transcriptSteps, true, fallbackMs) : null;
|
transcriptSteps.length > 0 ? extractLiveActivity(transcriptSteps, true, fallbackMs) : null;
|
||||||
|
|
||||||
@@ -1226,7 +1236,7 @@ function resolveBestLiveActivity(cascadeId, rpcRawSteps, isRunning, fallbackMs)
|
|||||||
return (
|
return (
|
||||||
transcriptAct ||
|
transcriptAct ||
|
||||||
rpcAct ||
|
rpcAct ||
|
||||||
liveActivityMemo.get(String(cascadeId || '').toLowerCase()) ||
|
liveActivityMemoMap.get(String(cascadeId || '').toLowerCase()) ||
|
||||||
extractLiveActivity([], true, fallbackMs)
|
extractLiveActivity([], true, fallbackMs)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1385,22 +1395,35 @@ export async function enumerateAndSyncConversations({
|
|||||||
currentAccountName = '',
|
currentAccountName = '',
|
||||||
requestedConvId = '',
|
requestedConvId = '',
|
||||||
forceRefresh = false,
|
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();
|
const nowSweepMs = Date.now();
|
||||||
if (forceRefresh) {
|
if (forceRefresh) {
|
||||||
failedFetchCooldownMap.clear();
|
activeCooldownMap.clear();
|
||||||
} else {
|
} 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 failedAt = typeof rec === 'number' ? rec : rec?.failedAt || 0;
|
||||||
const cooldownMs = typeof rec === 'number' ? FAILED_RPC_COOLDOWN_MS : rec?.cooldownMs || FAILED_RPC_COOLDOWN_MS;
|
const cooldownMs = typeof rec === 'number' ? FAILED_RPC_COOLDOWN_MS : rec?.cooldownMs || FAILED_RPC_COOLDOWN_MS;
|
||||||
if (nowSweepMs - failedAt >= cooldownMs) {
|
if (nowSweepMs - failedAt >= cooldownMs) {
|
||||||
failedFetchCooldownMap.delete(k);
|
activeCooldownMap.delete(k);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let cacheDirty = hasPendingTrajectoryCacheSave();
|
let cacheDirty = hasPendingSave();
|
||||||
const diskConvMap = discoverLocalConversationFiles();
|
const diskConvMap = isRemote ? new Map() : discoverLocalConversationFiles();
|
||||||
|
|
||||||
// 构建大小写不敏感索引,将同一会话的不同大小写键合并至唯一规范键(优先保留 summariesObj 中的原始键以兼容 RPC)
|
// 构建大小写不敏感索引,将同一会话的不同大小写键合并至唯一规范键(优先保留 summariesObj 中的原始键以兼容 RPC)
|
||||||
const mergedSideQuestionParents = { ...(sideQuestionParents || {}) };
|
const mergedSideQuestionParents = { ...(sideQuestionParents || {}) };
|
||||||
@@ -1449,7 +1472,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const [rawCacheKey] of listCachedTrajectoryEntries()) {
|
for (const [rawCacheKey] of listEntries()) {
|
||||||
const lower = String(rawCacheKey || '').trim().toLowerCase();
|
const lower = String(rawCacheKey || '').trim().toLowerCase();
|
||||||
if (!lower) continue;
|
if (!lower) continue;
|
||||||
const existingCanon = canonicalIdByLower.get(lower);
|
const existingCanon = canonicalIdByLower.get(lower);
|
||||||
@@ -1457,18 +1480,18 @@ export async function enumerateAndSyncConversations({
|
|||||||
// 标准 UUID 统一收敛为小写键,避免大小写分裂产生双份条目
|
// 标准 UUID 统一收敛为小写键,避免大小写分裂产生双份条目
|
||||||
const normalizedKey = UUID_RE.test(rawCacheKey) ? lower : rawCacheKey;
|
const normalizedKey = UUID_RE.test(rawCacheKey) ? lower : rawCacheKey;
|
||||||
if (normalizedKey !== rawCacheKey) {
|
if (normalizedKey !== rawCacheKey) {
|
||||||
setCachedTrajectory(normalizedKey, getCachedTrajectory(rawCacheKey));
|
setEntry(normalizedKey, getEntry(rawCacheKey));
|
||||||
removeCachedTrajectory(rawCacheKey);
|
removeEntry(rawCacheKey);
|
||||||
cacheDirty = true;
|
cacheDirty = true;
|
||||||
}
|
}
|
||||||
canonicalIdByLower.set(lower, normalizedKey);
|
canonicalIdByLower.set(lower, normalizedKey);
|
||||||
} else if (existingCanon !== rawCacheKey) {
|
} else if (existingCanon !== rawCacheKey) {
|
||||||
const targetEntry = getCachedTrajectory(existingCanon);
|
const targetEntry = getEntry(existingCanon);
|
||||||
const dupEntry = getCachedTrajectory(rawCacheKey);
|
const dupEntry = getEntry(rawCacheKey);
|
||||||
if (!targetEntry || (dupEntry?.steps?.length || 0) > (targetEntry?.steps?.length || 0)) {
|
if (!targetEntry || (dupEntry?.steps?.length || 0) > (targetEntry?.steps?.length || 0)) {
|
||||||
setCachedTrajectory(existingCanon, dupEntry);
|
setEntry(existingCanon, dupEntry);
|
||||||
}
|
}
|
||||||
removeCachedTrajectory(rawCacheKey);
|
removeEntry(rawCacheKey);
|
||||||
cacheDirty = true;
|
cacheDirty = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1480,7 +1503,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 从所有本地缓存会话收集 subagentRefs,确保跨账号切换时历史会话与派生子代理均不丢失
|
// 从所有本地缓存会话收集 subagentRefs,确保跨账号切换时历史会话与派生子代理均不丢失
|
||||||
for (const [, entry] of listCachedTrajectoryEntries()) {
|
for (const [, entry] of listEntries()) {
|
||||||
for (const ref of entry?.subagentRefs || []) {
|
for (const ref of entry?.subagentRefs || []) {
|
||||||
const refCid = String(ref?.cascadeId || '').trim().toLowerCase();
|
const refCid = String(ref?.cascadeId || '').trim().toLowerCase();
|
||||||
if (refCid && !canonicalIdByLower.has(refCid)) {
|
if (refCid && !canonicalIdByLower.has(refCid)) {
|
||||||
@@ -1489,15 +1512,15 @@ export async function enumerateAndSyncConversations({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const localSummaryByLower = readLocalSummaryIndex();
|
const localSummaryByLower = isRemote ? new Map() : readLocalSummaryIndex();
|
||||||
const sqliteAvailable = hasBuiltinNodeSqlite();
|
const sqliteAvailable = isRemote ? false : hasBuiltinNodeSqlite();
|
||||||
const STALE_LOCAL_RUNNING_MAX_AGE_MS = 10 * 60_000;
|
const STALE_LOCAL_RUNNING_MAX_AGE_MS = 10 * 60_000;
|
||||||
const reqLower = String(requestedConvId || '').trim().toLowerCase();
|
const reqLower = String(requestedConvId || '').trim().toLowerCase();
|
||||||
const rawConversations = [];
|
const rawConversations = [];
|
||||||
for (const [cidLower, cascadeId] of canonicalIdByLower.entries()) {
|
for (const [cidLower, cascadeId] of canonicalIdByLower.entries()) {
|
||||||
const item = summariesByLower.get(cidLower);
|
const item = summariesByLower.get(cidLower);
|
||||||
const localSum = item ? null : localSummaryByLower.get(cidLower) || null;
|
const localSum = item ? null : localSummaryByLower.get(cidLower) || null;
|
||||||
const cached = getCachedTrajectory(cascadeId);
|
const cached = getEntry(cascadeId);
|
||||||
const diskFiles = diskConvMap.get(cidLower) || [];
|
const diskFiles = diskConvMap.get(cidLower) || [];
|
||||||
const sqliteDbInfo = sqliteAvailable ? resolveBestSqliteDbInfo(diskFiles) : null;
|
const sqliteDbInfo = sqliteAvailable ? resolveBestSqliteDbInfo(diskFiles) : null;
|
||||||
const dbPath = sqliteDbInfo?.dbPath || '';
|
const dbPath = sqliteDbInfo?.dbPath || '';
|
||||||
@@ -1508,11 +1531,13 @@ export async function enumerateAndSyncConversations({
|
|||||||
const diskMtimeMs = sqliteDbInfo
|
const diskMtimeMs = sqliteDbInfo
|
||||||
? Math.max(rawDiskMtimeMs || 0, sqliteDbInfo.mtimeMs || 0)
|
? Math.max(rawDiskMtimeMs || 0, sqliteDbInfo.mtimeMs || 0)
|
||||||
: rawDiskMtimeMs;
|
: rawDiskMtimeMs;
|
||||||
const appSource = inferAppSourceFromSummary(
|
const appSource = isRemote
|
||||||
item?.source || '',
|
? 'ssh'
|
||||||
diskFiles,
|
: inferAppSourceFromSummary(
|
||||||
cached?.appSource || 'standalone'
|
item?.source || '',
|
||||||
);
|
diskFiles,
|
||||||
|
cached?.appSource || 'standalone'
|
||||||
|
);
|
||||||
|
|
||||||
const sqParentInfo = mergedSideQuestionParents[cidLower] || null;
|
const sqParentInfo = mergedSideQuestionParents[cidLower] || null;
|
||||||
const isSideQuestion = Boolean(
|
const isSideQuestion = Boolean(
|
||||||
@@ -1707,12 +1732,12 @@ export async function enumerateAndSyncConversations({
|
|||||||
function isFetchInCooldown(conv, sig) {
|
function isFetchInCooldown(conv, sig) {
|
||||||
if (forceRefresh) return false;
|
if (forceRefresh) return false;
|
||||||
const key = `${conv.cascadeId.toLowerCase()}::${sig}`;
|
const key = `${conv.cascadeId.toLowerCase()}::${sig}`;
|
||||||
const rec = failedFetchCooldownMap.get(key);
|
const rec = activeCooldownMap.get(key);
|
||||||
if (!rec) return false;
|
if (!rec) return false;
|
||||||
const failedAt = typeof rec === 'number' ? rec : rec.failedAt;
|
const failedAt = typeof rec === 'number' ? rec : rec.failedAt;
|
||||||
const cooldownMs = typeof rec === 'number' ? FAILED_RPC_COOLDOWN_MS : rec.cooldownMs;
|
const cooldownMs = typeof rec === 'number' ? FAILED_RPC_COOLDOWN_MS : rec.cooldownMs;
|
||||||
if (nowPollMs - failedAt >= cooldownMs) {
|
if (nowPollMs - failedAt >= cooldownMs) {
|
||||||
failedFetchCooldownMap.delete(key);
|
activeCooldownMap.delete(key);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
@@ -1765,15 +1790,15 @@ export async function enumerateAndSyncConversations({
|
|||||||
for (const c of targetConvs) {
|
for (const c of targetConvs) {
|
||||||
attemptedFetchIds.add(c.cascadeId.toLowerCase());
|
attemptedFetchIds.add(c.cascadeId.toLowerCase());
|
||||||
}
|
}
|
||||||
for (let i = 0; i < targetConvs.length; i += MAX_CONCURRENT_RPC) {
|
for (let i = 0; i < targetConvs.length; i += maxConcurrentRpc) {
|
||||||
const batch = targetConvs.slice(i, i + MAX_CONCURRENT_RPC);
|
const batch = targetConvs.slice(i, i + maxConcurrentRpc);
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
batch.map(async (conv) => {
|
batch.map(async (conv) => {
|
||||||
const sig = buildConvSig(conv);
|
const sig = buildConvSig(conv);
|
||||||
const cooldownKey = `${conv.cascadeId.toLowerCase()}::${sig}`;
|
const cooldownKey = `${conv.cascadeId.toLowerCase()}::${sig}`;
|
||||||
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
|
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||||
const isReq = Boolean(reqLower && conv.cascadeId.toLowerCase() === reqLower);
|
const isReq = Boolean(reqLower && conv.cascadeId.toLowerCase() === reqLower);
|
||||||
const prev = getCachedTrajectory(conv.cascadeId);
|
const prev = getEntry(conv.cascadeId);
|
||||||
let partialTailSteps = [];
|
let partialTailSteps = [];
|
||||||
let hasTailStepInfo = false;
|
let hasTailStepInfo = false;
|
||||||
try {
|
try {
|
||||||
@@ -1781,7 +1806,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
let trajRes = null;
|
let trajRes = null;
|
||||||
let loadedViaSqlite = false;
|
let loadedViaSqlite = false;
|
||||||
let transcriptFirstTitle = '';
|
let transcriptFirstTitle = '';
|
||||||
if (conv.dbPath && sqliteAvailable) {
|
if (!isRemote && conv.dbPath && sqliteAvailable) {
|
||||||
const sqlRes = readLocalSqliteTrajectory(conv.dbPath, {
|
const sqlRes = readLocalSqliteTrajectory(conv.dbPath, {
|
||||||
cascadeId: conv.cascadeId,
|
cascadeId: conv.cascadeId,
|
||||||
isRunning,
|
isRunning,
|
||||||
@@ -1797,7 +1822,12 @@ export async function enumerateAndSyncConversations({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!trajRes) {
|
if (!trajRes) {
|
||||||
trajRes = await callLsRpc('GetCascadeTrajectory', { cascadeId: conv.cascadeId });
|
trajRes = await callLsRpc(
|
||||||
|
'GetCascadeTrajectory',
|
||||||
|
{ cascadeId: conv.cascadeId },
|
||||||
|
5000,
|
||||||
|
endpoint
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (!Array.isArray(trajRes?.trajectory?.steps)) {
|
if (!Array.isArray(trajRes?.trajectory?.steps)) {
|
||||||
throw new Error('Trajectory steps unavailable');
|
throw new Error('Trajectory steps unavailable');
|
||||||
@@ -1813,7 +1843,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
}
|
}
|
||||||
throw new Error('Incomplete trajectory; retaining cached usage');
|
throw new Error('Incomplete trajectory; retaining cached usage');
|
||||||
}
|
}
|
||||||
failedFetchCooldownMap.delete(cooldownKey);
|
activeCooldownMap.delete(cooldownKey);
|
||||||
const rawGenMeta = trajRes?.trajectory?.generatorMetadata || [];
|
const rawGenMeta = trajRes?.trajectory?.generatorMetadata || [];
|
||||||
const { steps: rawSteps, generatorMeta } = loadedViaSqlite
|
const { steps: rawSteps, generatorMeta } = loadedViaSqlite
|
||||||
? { steps: rawStepsUnfiltered, generatorMeta: rawGenMeta }
|
? { steps: rawStepsUnfiltered, generatorMeta: rawGenMeta }
|
||||||
@@ -1885,7 +1915,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
Boolean(
|
Boolean(
|
||||||
conv.rootConversationId && conv.rootConversationId !== cidLower
|
conv.rootConversationId && conv.rootConversationId !== cidLower
|
||||||
);
|
);
|
||||||
if (!nonShortTitle(conv.title)) {
|
if (!isRemote && !nonShortTitle(conv.title)) {
|
||||||
const annTitle = nonShortTitle(readAnnotationTitleForCascade(cidLower));
|
const annTitle = nonShortTitle(readAnnotationTitleForCascade(cidLower));
|
||||||
const resolvedFallbackTitle =
|
const resolvedFallbackTitle =
|
||||||
annTitle || trajRes?.firstOwnUserPrompt || transcriptFirstTitle;
|
annTitle || trajRes?.firstOwnUserPrompt || transcriptFirstTitle;
|
||||||
@@ -1899,7 +1929,9 @@ export async function enumerateAndSyncConversations({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const subagentRefs = extractSubagentRefsFromSteps(rawSteps);
|
const subagentRefs = extractSubagentRefsFromSteps(rawSteps);
|
||||||
const ownSwarmManifest = !conv.isSubagent ? readSwarmManifestForCascade(cidLower) : null;
|
const rpcSwarmMeta = extractSwarmMetaFromSteps(rawSteps);
|
||||||
|
const ownSwarmManifest =
|
||||||
|
!isRemote && !conv.isSubagent ? readSwarmManifestForCascade(cidLower) : null;
|
||||||
if (ownSwarmManifest?.workerRefs?.length) {
|
if (ownSwarmManifest?.workerRefs?.length) {
|
||||||
const seenRefCids = new Set(subagentRefs.map((r) => r.cascadeId));
|
const seenRefCids = new Set(subagentRefs.map((r) => r.cascadeId));
|
||||||
for (const wRef of ownSwarmManifest.workerRefs) {
|
for (const wRef of ownSwarmManifest.workerRefs) {
|
||||||
@@ -1908,9 +1940,12 @@ export async function enumerateAndSyncConversations({
|
|||||||
subagentRefs.push(wRef);
|
subagentRefs.push(wRef);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!nonShortTitle(conv.title) && ownSwarmManifest.title) {
|
}
|
||||||
conv.title = ownSwarmManifest.title;
|
const resolvedSwarmTitle = !conv.isSubagent
|
||||||
}
|
? String(ownSwarmManifest?.title || rpcSwarmMeta?.title || '').trim()
|
||||||
|
: '';
|
||||||
|
if (!nonShortTitle(conv.title) && resolvedSwarmTitle) {
|
||||||
|
conv.title = resolvedSwarmTitle;
|
||||||
}
|
}
|
||||||
conv.subagentRefs = subagentRefs;
|
conv.subagentRefs = subagentRefs;
|
||||||
|
|
||||||
@@ -1920,7 +1955,8 @@ export async function enumerateAndSyncConversations({
|
|||||||
conv.stepCount = steps.length;
|
conv.stepCount = steps.length;
|
||||||
const finalSig = buildConvSig(conv);
|
const finalSig = buildConvSig(conv);
|
||||||
|
|
||||||
const effectiveIsRunning = isRunning && !isParkedOnSwarmWait(rawSteps);
|
const isParkedSwarm = isParkedOnSwarmWait(rawSteps);
|
||||||
|
const effectiveIsRunning = isRunning && !isParkedSwarm;
|
||||||
if (!effectiveIsRunning && conv.status === 'CASCADE_RUN_STATUS_RUNNING') {
|
if (!effectiveIsRunning && conv.status === 'CASCADE_RUN_STATUS_RUNNING') {
|
||||||
conv.status = 'IDLE';
|
conv.status = 'IDLE';
|
||||||
}
|
}
|
||||||
@@ -1929,17 +1965,18 @@ export async function enumerateAndSyncConversations({
|
|||||||
conv.cascadeId,
|
conv.cascadeId,
|
||||||
rawSteps,
|
rawSteps,
|
||||||
effectiveIsRunning,
|
effectiveIsRunning,
|
||||||
resolvedLastModMs || conv.createdTimeMs || 0
|
resolvedLastModMs || conv.createdTimeMs || 0,
|
||||||
|
{ isRemote, liveActivityMemoMap: activeLiveActivityMemo }
|
||||||
);
|
);
|
||||||
if (liveAct && liveAct.actionKey !== 'swarm_wait') {
|
if (liveAct && liveAct.actionKey !== 'swarm_wait') {
|
||||||
conv.liveActivity = liveAct;
|
conv.liveActivity = liveAct;
|
||||||
liveActivityMemo.set(cidLower, liveAct);
|
activeLiveActivityMemo.set(cidLower, liveAct);
|
||||||
} else {
|
} else {
|
||||||
if (liveAct?.actionKey === 'swarm_wait') {
|
if (liveAct?.actionKey === 'swarm_wait') {
|
||||||
conv.status = 'IDLE';
|
conv.status = 'IDLE';
|
||||||
}
|
}
|
||||||
conv.liveActivity = null;
|
conv.liveActivity = null;
|
||||||
liveActivityMemo.delete(cidLower);
|
activeLiveActivityMemo.delete(cidLower);
|
||||||
}
|
}
|
||||||
|
|
||||||
const entryAccountName = prev ? prev.accountName || '' : currentAccountName || '';
|
const entryAccountName = prev ? prev.accountName || '' : currentAccountName || '';
|
||||||
@@ -1967,6 +2004,8 @@ export async function enumerateAndSyncConversations({
|
|||||||
steps: stepsWithOwners,
|
steps: stepsWithOwners,
|
||||||
subagentRefs,
|
subagentRefs,
|
||||||
};
|
};
|
||||||
|
if (rpcSwarmMeta) cacheEntry.swarmMeta = rpcSwarmMeta;
|
||||||
|
if (isParkedSwarm) cacheEntry.parkedOnSwarmWait = true;
|
||||||
if (conv.diskFileSig) cacheEntry.diskFileSig = conv.diskFileSig;
|
if (conv.diskFileSig) cacheEntry.diskFileSig = conv.diskFileSig;
|
||||||
if (conv.appSource && conv.appSource !== 'standalone') {
|
if (conv.appSource && conv.appSource !== 'standalone') {
|
||||||
cacheEntry.appSource = conv.appSource;
|
cacheEntry.appSource = conv.appSource;
|
||||||
@@ -1986,13 +2025,15 @@ export async function enumerateAndSyncConversations({
|
|||||||
const metaChanged =
|
const metaChanged =
|
||||||
!Array.isArray(prev?.subagentRefs) ||
|
!Array.isArray(prev?.subagentRefs) ||
|
||||||
JSON.stringify(prev?.subagentRefs) !== JSON.stringify(subagentRefs) ||
|
JSON.stringify(prev?.subagentRefs) !== JSON.stringify(subagentRefs) ||
|
||||||
|
!isDeepStrictEqual(prev?.swarmMeta || null, cacheEntry.swarmMeta || null) ||
|
||||||
|
Boolean(prev?.parkedOnSwarmWait) !== Boolean(cacheEntry.parkedOnSwarmWait) ||
|
||||||
(prev?.rootConversationId || '') !== (cacheEntry.rootConversationId || '') ||
|
(prev?.rootConversationId || '') !== (cacheEntry.rootConversationId || '') ||
|
||||||
Boolean(prev?.isSideQuestion) !== Boolean(cacheEntry.isSideQuestion);
|
Boolean(prev?.isSideQuestion) !== Boolean(cacheEntry.isSideQuestion);
|
||||||
const stepsChanged =
|
const stepsChanged =
|
||||||
!prev ||
|
!prev ||
|
||||||
Boolean(prev.offlineTranscriptFallback) ||
|
Boolean(prev.offlineTranscriptFallback) ||
|
||||||
prev.signature !== finalSig ||
|
prev.signature !== finalSig ||
|
||||||
Boolean(prev.wasRunning) !== isRunning ||
|
Boolean(prev.wasRunning) !== Boolean(cacheEntry.wasRunning) ||
|
||||||
!prev.contextLimitTelemetry ||
|
!prev.contextLimitTelemetry ||
|
||||||
!prev.speedClearedTelemetry ||
|
!prev.speedClearedTelemetry ||
|
||||||
!prev.turnRailTelemetry ||
|
!prev.turnRailTelemetry ||
|
||||||
@@ -2002,13 +2043,13 @@ export async function enumerateAndSyncConversations({
|
|||||||
!isDeepStrictEqual(prev.steps, stepsWithOwners);
|
!isDeepStrictEqual(prev.steps, stepsWithOwners);
|
||||||
|
|
||||||
if (!stepsChanged) cacheEntry.steps = prev.steps;
|
if (!stepsChanged) cacheEntry.steps = prev.steps;
|
||||||
setCachedTrajectory(conv.cascadeId, cacheEntry);
|
setEntry(conv.cascadeId, cacheEntry);
|
||||||
if (stepsChanged) {
|
if (stepsChanged) {
|
||||||
cacheDirty = true;
|
cacheDirty = true;
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
let offlineRecovered = false;
|
let offlineRecovered = false;
|
||||||
if (!conv.inSummaries && (!prev || prev.offlineTranscriptFallback)) {
|
if (!isRemote && !conv.inSummaries && (!prev || prev.offlineTranscriptFallback)) {
|
||||||
if (!lazyExternalByLower) {
|
if (!lazyExternalByLower) {
|
||||||
lazyExternalByLower = new Map();
|
lazyExternalByLower = new Map();
|
||||||
for (const ext of loadExternalDeepStatsCache().values()) {
|
for (const ext of loadExternalDeepStatsCache().values()) {
|
||||||
@@ -2087,7 +2128,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
Boolean(prev.offlineSqliteTelemetry) !== Boolean(offlineEntry.offlineSqliteTelemetry) ||
|
Boolean(prev.offlineSqliteTelemetry) !== Boolean(offlineEntry.offlineSqliteTelemetry) ||
|
||||||
!isDeepStrictEqual(prev.steps, offlineEntry.steps);
|
!isDeepStrictEqual(prev.steps, offlineEntry.steps);
|
||||||
if (!changed) offlineEntry.steps = prev.steps;
|
if (!changed) offlineEntry.steps = prev.steps;
|
||||||
setCachedTrajectory(conv.cascadeId, offlineEntry);
|
setEntry(conv.cascadeId, offlineEntry);
|
||||||
if (changed) {
|
if (changed) {
|
||||||
cacheDirty = true;
|
cacheDirty = true;
|
||||||
}
|
}
|
||||||
@@ -2107,30 +2148,45 @@ export async function enumerateAndSyncConversations({
|
|||||||
if (!(isRunning && (hasTailStepInfo || offlineRecovered))) {
|
if (!(isRunning && (hasTailStepInfo || offlineRecovered))) {
|
||||||
const cooldownMs =
|
const cooldownMs =
|
||||||
isRunning || isReq ? ACTIVE_FAILED_RPC_COOLDOWN_MS : FAILED_RPC_COOLDOWN_MS;
|
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) {
|
const tailStepsOnErr =
|
||||||
liveActivityMemo.delete(conv.cascadeId.toLowerCase());
|
partialTailSteps.length > 0
|
||||||
|
? partialTailSteps
|
||||||
|
: isRemote
|
||||||
|
? []
|
||||||
|
: readTranscriptTailSteps(conv.cascadeId);
|
||||||
|
const parkedOnErr =
|
||||||
|
tailStepsOnErr.length > 0
|
||||||
|
? isParkedOnSwarmWait(tailStepsOnErr)
|
||||||
|
: Boolean(prev?.parkedOnSwarmWait) && prev.signature === sig;
|
||||||
|
if (!isRunning || (!offlineRecovered && parkedOnErr)) {
|
||||||
|
if (isRunning) {
|
||||||
|
conv.status = 'IDLE';
|
||||||
|
conv.liveActivity = null;
|
||||||
|
}
|
||||||
|
activeLiveActivityMemo.delete(conv.cascadeId.toLowerCase());
|
||||||
} else {
|
} else {
|
||||||
const fallbackLive = resolveBestLiveActivity(
|
const fallbackLive = resolveBestLiveActivity(
|
||||||
conv.cascadeId,
|
conv.cascadeId,
|
||||||
partialTailSteps,
|
partialTailSteps,
|
||||||
true,
|
true,
|
||||||
conv.lastModifiedMs || conv.createdTimeMs || 0
|
conv.lastModifiedMs || conv.createdTimeMs || 0,
|
||||||
|
{ isRemote, liveActivityMemoMap: activeLiveActivityMemo }
|
||||||
);
|
);
|
||||||
conv.liveActivity = fallbackLive;
|
conv.liveActivity = fallbackLive;
|
||||||
if (fallbackLive) {
|
if (fallbackLive) {
|
||||||
liveActivityMemo.set(conv.cascadeId.toLowerCase(), fallbackLive);
|
activeLiveActivityMemo.set(conv.cascadeId.toLowerCase(), fallbackLive);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
!offlineRecovered &&
|
!offlineRecovered &&
|
||||||
prev &&
|
prev &&
|
||||||
getCachedTrajectory(conv.cascadeId) === prev &&
|
getEntry(conv.cascadeId) === prev &&
|
||||||
String(prev.signature || '').startsWith(`${CACHE_SCHEMA_VERSION}:`) &&
|
String(prev.signature || '').startsWith(`${CACHE_SCHEMA_VERSION}:`) &&
|
||||||
!Array.isArray(prev.subagentRefs)
|
!Array.isArray(prev.subagentRefs)
|
||||||
) {
|
) {
|
||||||
setCachedTrajectory(conv.cascadeId, { ...prev, subagentRefs: [] });
|
setEntry(conv.cascadeId, { ...prev, subagentRefs: [] });
|
||||||
cacheDirty = true;
|
cacheDirty = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2188,7 +2244,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
const sig = buildConvSig(conv);
|
const sig = buildConvSig(conv);
|
||||||
if (isFetchInCooldown(conv, sig)) return false;
|
if (isFetchInCooldown(conv, sig)) return false;
|
||||||
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
|
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||||
const cached = getCachedTrajectory(conv.cascadeId);
|
const cached = getEntry(conv.cascadeId);
|
||||||
if (!cached || conv.needsInitialLoad) return true;
|
if (!cached || conv.needsInitialLoad) return true;
|
||||||
const lowerCid = conv.cascadeId.toLowerCase();
|
const lowerCid = conv.cascadeId.toLowerCase();
|
||||||
const isSelectedFamily =
|
const isSelectedFamily =
|
||||||
@@ -2277,11 +2333,12 @@ export async function enumerateAndSyncConversations({
|
|||||||
const missingSubagentsToFetch = [];
|
const missingSubagentsToFetch = [];
|
||||||
|
|
||||||
for (const parentConv of [...rawConversations]) {
|
for (const parentConv of [...rawConversations]) {
|
||||||
const parentCached = getCachedTrajectory(parentConv.cascadeId);
|
const parentCached = getEntry(parentConv.cascadeId);
|
||||||
const baseRefs = parentConv.subagentRefs || parentCached?.subagentRefs || [];
|
const baseRefs = parentConv.subagentRefs || parentCached?.subagentRefs || [];
|
||||||
const swarmManifest = !parentConv.isSubagent
|
const swarmManifest =
|
||||||
? readSwarmManifestForCascade(parentConv.cascadeId)
|
!isRemote && !parentConv.isSubagent
|
||||||
: null;
|
? readSwarmManifestForCascade(parentConv.cascadeId)
|
||||||
|
: null;
|
||||||
let refs = baseRefs;
|
let refs = baseRefs;
|
||||||
if (swarmManifest?.workerRefs?.length) {
|
if (swarmManifest?.workerRefs?.length) {
|
||||||
const merged = Array.isArray(baseRefs) ? baseRefs.slice() : [];
|
const merged = Array.isArray(baseRefs) ? baseRefs.slice() : [];
|
||||||
@@ -2310,7 +2367,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
const canonSubId = canonicalIdByLower.get(subCid) || subCid;
|
const canonSubId = canonicalIdByLower.get(subCid) || subCid;
|
||||||
canonicalIdByLower.set(subCid, canonSubId);
|
canonicalIdByLower.set(subCid, canonSubId);
|
||||||
let subConv = byLowerId.get(subCid);
|
let subConv = byLowerId.get(subCid);
|
||||||
const subCached = getCachedTrajectory(subConv?.cascadeId || canonSubId);
|
const subCached = getEntry(subConv?.cascadeId || canonSubId);
|
||||||
if (!subConv) {
|
if (!subConv) {
|
||||||
const subDiskFiles = diskConvMap.get(subCid) || [];
|
const subDiskFiles = diskConvMap.get(subCid) || [];
|
||||||
const subDbInfo = sqliteAvailable ? resolveBestSqliteDbInfo(subDiskFiles) : null;
|
const subDbInfo = sqliteAvailable ? resolveBestSqliteDbInfo(subDiskFiles) : null;
|
||||||
@@ -2336,7 +2393,9 @@ export async function enumerateAndSyncConversations({
|
|||||||
diskMtimeMs,
|
diskMtimeMs,
|
||||||
dbPath: subDbInfo?.dbPath || '',
|
dbPath: subDbInfo?.dbPath || '',
|
||||||
diskFileSig: subDbInfo?.sig || '',
|
diskFileSig: subDbInfo?.sig || '',
|
||||||
appSource: inferAppSourceFromSummary('', subDiskFiles, subCached?.appSource || 'standalone'),
|
appSource: isRemote
|
||||||
|
? 'ssh'
|
||||||
|
: inferAppSourceFromSummary('', subDiskFiles, subCached?.appSource || 'standalone'),
|
||||||
inSummaries: false,
|
inSummaries: false,
|
||||||
needsInitialLoad: !subCached,
|
needsInitialLoad: !subCached,
|
||||||
isSubagent: true,
|
isSubagent: true,
|
||||||
@@ -2368,7 +2427,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const targetCacheKey = subConv.cascadeId;
|
const targetCacheKey = subConv.cascadeId;
|
||||||
const existingSubCache = getCachedTrajectory(targetCacheKey);
|
const existingSubCache = getEntry(targetCacheKey);
|
||||||
const isSelectedSubFamily = rootId === selectedRootId;
|
const isSelectedSubFamily = rootId === selectedRootId;
|
||||||
const hasValidSubCache =
|
const hasValidSubCache =
|
||||||
existingSubCache &&
|
existingSubCache &&
|
||||||
@@ -2417,7 +2476,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
updatedMetadata.subagentRefs = [];
|
updatedMetadata.subagentRefs = [];
|
||||||
}
|
}
|
||||||
if (Object.keys(updatedMetadata).length > 0) {
|
if (Object.keys(updatedMetadata).length > 0) {
|
||||||
setCachedTrajectory(targetCacheKey, { ...existingSubCache, ...updatedMetadata });
|
setEntry(targetCacheKey, { ...existingSubCache, ...updatedMetadata });
|
||||||
cacheDirty = true;
|
cacheDirty = true;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -2443,7 +2502,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
if (attemptedFetchIds.has(c.cascadeId.toLowerCase()) || isFetchInCooldown(c, sig)) {
|
if (attemptedFetchIds.has(c.cascadeId.toLowerCase()) || isFetchInCooldown(c, sig)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
const cached = getCachedTrajectory(c.cascadeId);
|
const cached = getEntry(c.cascadeId);
|
||||||
return cached && !Array.isArray(cached.subagentRefs);
|
return cached && !Array.isArray(cached.subagentRefs);
|
||||||
})
|
})
|
||||||
.slice(0, LEGACY_MIGRATION_BATCH_SIZE);
|
.slice(0, LEGACY_MIGRATION_BATCH_SIZE);
|
||||||
@@ -2477,9 +2536,9 @@ export async function enumerateAndSyncConversations({
|
|||||||
}
|
}
|
||||||
if (candidate && candidate !== conv.rootConversationId) {
|
if (candidate && candidate !== conv.rootConversationId) {
|
||||||
conv.rootConversationId = candidate;
|
conv.rootConversationId = candidate;
|
||||||
const cached = getCachedTrajectory(conv.cascadeId);
|
const cached = getEntry(conv.cascadeId);
|
||||||
if (cached && cached.rootConversationId !== candidate) {
|
if (cached && cached.rootConversationId !== candidate) {
|
||||||
setCachedTrajectory(conv.cascadeId, { ...cached, rootConversationId: candidate });
|
setEntry(conv.cascadeId, { ...cached, rootConversationId: candidate });
|
||||||
cacheDirty = true;
|
cacheDirty = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2488,41 +2547,49 @@ export async function enumerateAndSyncConversations({
|
|||||||
const hasRunningSessions = rawConversations.some(
|
const hasRunningSessions = rawConversations.some(
|
||||||
(c) => c.status === 'CASCADE_RUN_STATUS_RUNNING'
|
(c) => c.status === 'CASCADE_RUN_STATUS_RUNNING'
|
||||||
);
|
);
|
||||||
if (cacheDirty || (hasPendingTrajectoryCacheSave() && !hasRunningSessions)) {
|
if (cacheDirty || (hasPendingSave() && !hasRunningSessions)) {
|
||||||
persistTrajectoryCacheIfNeeded({ hasRunningSessions });
|
persistCacheIfNeeded({ hasRunningSessions });
|
||||||
}
|
}
|
||||||
|
|
||||||
// 确保所有处于 RUNNING 状态的会话(含本轮未触发 RPC 拉取的会话)都同步了最新的实时动作摘要,并剔除已进入 swarm_wait 待命的假运行态
|
// 确保所有处于 RUNNING 状态的会话(含本轮未触发 RPC 拉取的会话)都同步了最新的实时动作摘要,并剔除已进入 swarm_wait 待命的假运行态
|
||||||
for (const conv of rawConversations) {
|
for (const conv of rawConversations) {
|
||||||
if (conv.status === 'CASCADE_RUN_STATUS_RUNNING') {
|
if (conv.status === 'CASCADE_RUN_STATUS_RUNNING') {
|
||||||
if (!conv.liveActivity) {
|
if (!conv.liveActivity) {
|
||||||
const tailSteps = readTranscriptTailSteps(conv.cascadeId);
|
const cachedConv = getEntry(conv.cascadeId);
|
||||||
if (isParkedOnSwarmWait(tailSteps)) {
|
const parkedByCache =
|
||||||
|
Boolean(cachedConv?.parkedOnSwarmWait) &&
|
||||||
|
cachedConv.signature === buildConvSig(conv);
|
||||||
|
const tailSteps = isRemote ? [] : readTranscriptTailSteps(conv.cascadeId);
|
||||||
|
const isParked = tailSteps.length > 0 ? isParkedOnSwarmWait(tailSteps) : parkedByCache;
|
||||||
|
if (isParked) {
|
||||||
conv.status = 'IDLE';
|
conv.status = 'IDLE';
|
||||||
conv.liveActivity = null;
|
conv.liveActivity = null;
|
||||||
liveActivityMemo.delete(conv.cascadeId.toLowerCase());
|
activeLiveActivityMemo.delete(conv.cascadeId.toLowerCase());
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const fallbackMs = conv.lastModifiedMs || conv.createdTimeMs || 0;
|
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') {
|
if (resolved?.actionKey === 'swarm_wait') {
|
||||||
conv.status = 'IDLE';
|
conv.status = 'IDLE';
|
||||||
conv.liveActivity = null;
|
conv.liveActivity = null;
|
||||||
liveActivityMemo.delete(conv.cascadeId.toLowerCase());
|
activeLiveActivityMemo.delete(conv.cascadeId.toLowerCase());
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
conv.liveActivity = resolved;
|
conv.liveActivity = resolved;
|
||||||
if (resolved) {
|
if (resolved) {
|
||||||
liveActivityMemo.set(conv.cascadeId.toLowerCase(), resolved);
|
activeLiveActivityMemo.set(conv.cascadeId.toLowerCase(), resolved);
|
||||||
}
|
}
|
||||||
} else if (conv.liveActivity.actionKey === 'swarm_wait') {
|
} else if (conv.liveActivity.actionKey === 'swarm_wait') {
|
||||||
conv.status = 'IDLE';
|
conv.status = 'IDLE';
|
||||||
conv.liveActivity = null;
|
conv.liveActivity = null;
|
||||||
liveActivityMemo.delete(conv.cascadeId.toLowerCase());
|
activeLiveActivityMemo.delete(conv.cascadeId.toLowerCase());
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
conv.liveActivity = null;
|
conv.liveActivity = null;
|
||||||
liveActivityMemo.delete(conv.cascadeId.toLowerCase());
|
activeLiveActivityMemo.delete(conv.cascadeId.toLowerCase());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2564,8 +2631,9 @@ export async function enumerateAndSyncConversations({
|
|||||||
|
|
||||||
for (const rootConv of conversations) {
|
for (const rootConv of conversations) {
|
||||||
const cid = rootConv.cascadeId.toLowerCase();
|
const cid = rootConv.cascadeId.toLowerCase();
|
||||||
const swarmManifest = readSwarmManifestForCascade(cid);
|
const rootCached = getEntry(rootConv.cascadeId);
|
||||||
const swarmTitle = String(swarmManifest?.title || '').trim();
|
const swarmManifest = isRemote ? null : readSwarmManifestForCascade(cid);
|
||||||
|
const swarmTitle = String(swarmManifest?.title || rootCached?.swarmMeta?.title || '').trim();
|
||||||
if (swarmTitle) {
|
if (swarmTitle) {
|
||||||
rootConv.swarmTitle = swarmTitle;
|
rootConv.swarmTitle = swarmTitle;
|
||||||
const curTitle = String(rootConv.title || '').trim();
|
const curTitle = String(rootConv.title || '').trim();
|
||||||
@@ -2579,11 +2647,29 @@ export async function enumerateAndSyncConversations({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const subs = subagentsByRoot.get(cid) || [];
|
const subs = subagentsByRoot.get(cid) || [];
|
||||||
|
const rpcKilledByMember = new Map();
|
||||||
|
const mergeRpcKilled = (killedMap) => {
|
||||||
|
if (!killedMap || typeof killedMap !== 'object') return;
|
||||||
|
for (const [memberKey, killMs] of Object.entries(killedMap)) {
|
||||||
|
const normMember = String(memberKey || '').trim().toLowerCase();
|
||||||
|
if (!normMember) continue;
|
||||||
|
const numMs = Number(killMs || 0);
|
||||||
|
const prevMs = rpcKilledByMember.get(normMember);
|
||||||
|
if (prevMs === undefined || numMs > prevMs) {
|
||||||
|
rpcKilledByMember.set(normMember, numMs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
mergeRpcKilled(rootCached?.swarmMeta?.killedMembers);
|
||||||
|
for (const s of subs) {
|
||||||
|
mergeRpcKilled(getEntry(s.cascadeId)?.swarmMeta?.killedMembers);
|
||||||
|
}
|
||||||
|
|
||||||
let swarmCount = 0;
|
let swarmCount = 0;
|
||||||
for (const s of subs) {
|
for (const s of subs) {
|
||||||
const subLower = s.cascadeId.toLowerCase();
|
const subLower = s.cascadeId.toLowerCase();
|
||||||
const mEntry = swarmManifest?.membersByCid.get(subLower) || null;
|
const mEntry = swarmManifest?.membersByCid.get(subLower) || null;
|
||||||
const subCached = getCachedTrajectory(s.cascadeId);
|
const subCached = getEntry(s.cascadeId);
|
||||||
const parsedSwarm = !s.isSideQuestion
|
const parsedSwarm = !s.isSideQuestion
|
||||||
? parseSwarmWorkerRole({
|
? parseSwarmWorkerRole({
|
||||||
role: s.subagentSpec?.role || subCached?.subagentSpec?.role || '',
|
role: s.subagentSpec?.role || subCached?.subagentSpec?.role || '',
|
||||||
@@ -2597,11 +2683,27 @@ export async function enumerateAndSyncConversations({
|
|||||||
s.isSwarmWorker = true;
|
s.isSwarmWorker = true;
|
||||||
s.swarmMemberName = parsedSwarm.memberName;
|
s.swarmMemberName = parsedSwarm.memberName;
|
||||||
s.isSwarmAuxiliary = Boolean(parsedSwarm.isAuxiliary);
|
s.isSwarmAuxiliary = Boolean(parsedSwarm.isAuxiliary);
|
||||||
s.killed = Boolean(s.killed || mEntry?.killed);
|
const memberKey = String(parsedSwarm.memberName || '').trim().toLowerCase();
|
||||||
|
const rpcKilledAtMs =
|
||||||
|
memberKey && rpcKilledByMember.has(memberKey)
|
||||||
|
? rpcKilledByMember.get(memberKey)
|
||||||
|
: undefined;
|
||||||
|
const subCreatedMs =
|
||||||
|
s.createdTimeMs || subCached?.createdTimeMs || subCached?.steps?.[0]?.createdAtMs || 0;
|
||||||
|
const subLastStepMs =
|
||||||
|
subCached?.steps?.[subCached.steps.length - 1]?.createdAtMs || 0;
|
||||||
|
const killedByRpc =
|
||||||
|
rpcKilledAtMs !== undefined &&
|
||||||
|
!(
|
||||||
|
rpcKilledAtMs > 0 &&
|
||||||
|
((subCreatedMs > 0 && subCreatedMs > rpcKilledAtMs) ||
|
||||||
|
subLastStepMs > rpcKilledAtMs)
|
||||||
|
);
|
||||||
|
s.killed = Boolean(s.killed || (mEntry ? mEntry.killed : killedByRpc));
|
||||||
if (s.killed) {
|
if (s.killed) {
|
||||||
s.status = 'IDLE';
|
s.status = 'IDLE';
|
||||||
s.liveActivity = null;
|
s.liveActivity = null;
|
||||||
liveActivityMemo.delete(subLower);
|
activeLiveActivityMemo.delete(subLower);
|
||||||
s.swarmState = 'killed';
|
s.swarmState = 'killed';
|
||||||
} else if (s.status === 'CASCADE_RUN_STATUS_RUNNING') {
|
} else if (s.status === 'CASCADE_RUN_STATUS_RUNNING') {
|
||||||
const parkedInManifest =
|
const parkedInManifest =
|
||||||
@@ -2611,7 +2713,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
if (s.liveActivity?.actionKey === 'swarm_wait' || parkedInManifest) {
|
if (s.liveActivity?.actionKey === 'swarm_wait' || parkedInManifest) {
|
||||||
s.status = 'IDLE';
|
s.status = 'IDLE';
|
||||||
s.liveActivity = null;
|
s.liveActivity = null;
|
||||||
liveActivityMemo.delete(subLower);
|
activeLiveActivityMemo.delete(subLower);
|
||||||
s.swarmState = 'waiting';
|
s.swarmState = 'waiting';
|
||||||
} else {
|
} else {
|
||||||
s.swarmState = 'working';
|
s.swarmState = 'working';
|
||||||
@@ -2639,12 +2741,12 @@ export async function enumerateAndSyncConversations({
|
|||||||
}
|
}
|
||||||
const aStart =
|
const aStart =
|
||||||
a.createdTimeMs ||
|
a.createdTimeMs ||
|
||||||
getCachedTrajectory(a.cascadeId)?.steps?.[0]?.createdAtMs ||
|
getEntry(a.cascadeId)?.steps?.[0]?.createdAtMs ||
|
||||||
a.lastModifiedMs ||
|
a.lastModifiedMs ||
|
||||||
0;
|
0;
|
||||||
const bStart =
|
const bStart =
|
||||||
b.createdTimeMs ||
|
b.createdTimeMs ||
|
||||||
getCachedTrajectory(b.cascadeId)?.steps?.[0]?.createdAtMs ||
|
getEntry(b.cascadeId)?.steps?.[0]?.createdAtMs ||
|
||||||
b.lastModifiedMs ||
|
b.lastModifiedMs ||
|
||||||
0;
|
0;
|
||||||
return aStart - bStart || String(a.cascadeId).localeCompare(String(b.cascadeId));
|
return aStart - bStart || String(a.cascadeId).localeCompare(String(b.cascadeId));
|
||||||
|
|||||||
@@ -552,3 +552,97 @@ export async function ensureLsEndpointDiscovered({
|
|||||||
return lsDiscoveryState.inFlight;
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -2,27 +2,203 @@
|
|||||||
* @fileoverview Antigravity Language Server Connect RPC 客户端与官方配额摘要缓存。
|
* @fileoverview Antigravity Language Server Connect RPC 客户端与官方配额摘要缓存。
|
||||||
*
|
*
|
||||||
* 负责:
|
* 负责:
|
||||||
* 1. 向本地 Language Server 发起带 CSRF 鉴权与超时保护的 Connect RPC 调用 (`callLsRpc`);
|
* 1. 向本地或 SSH 远端窗口对应的 Language Server 发起带 CSRF 鉴权与超时保护的 Connect RPC 调用 (`callLsRpc`);
|
||||||
* 2. 拉取并缓存 `RetrieveUserQuotaSummary` 官方实时配额摘要(常规轮询使用 10 秒短期缓存与失败退避冷却,
|
* 2. 对远端 SSH 端点采用双层传输:
|
||||||
* 并在缓存过期或强制刷新时穿透 `language_server.exe` 内部 3 分钟陈旧缓存)。
|
* - 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';
|
import { ensureLsEndpointDiscovered } from './ls-discovery.mjs';
|
||||||
|
|
||||||
const QUOTA_CACHE_TTL_MS = 10_000;
|
const QUOTA_CACHE_TTL_MS = 10_000;
|
||||||
const QUOTA_RETRY_COOLDOWN_MS = 5_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 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;
|
const { baseUrl, csrfToken } = lsRuntimeEndpoint;
|
||||||
if (!contextModelCatalog || contextModelCatalog.baseUrl !== baseUrl || contextModelCatalog.csrfToken !== csrfToken ||
|
if (
|
||||||
Date.now() >= contextModelCatalog.expiresAt) {
|
!contextModelCatalog ||
|
||||||
|
contextModelCatalog.baseUrl !== baseUrl ||
|
||||||
|
contextModelCatalog.csrfToken !== csrfToken ||
|
||||||
|
Date.now() >= contextModelCatalog.expiresAt
|
||||||
|
) {
|
||||||
contextModelCatalog = {
|
contextModelCatalog = {
|
||||||
baseUrl,
|
baseUrl,
|
||||||
csrfToken,
|
csrfToken,
|
||||||
expiresAt: Date.now() + 30000,
|
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;
|
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 {string} method RPC 方法名(如 `'GetUserStatus'`、`'GetCascadeTrajectory'`)
|
||||||
* @param {object} [body={}] 请求 JSON 载荷
|
* @param {object} [body={}] 请求 JSON 载荷
|
||||||
* @param {number} [timeoutMs=5000] 超时时间(毫秒)
|
* @param {number} [timeoutMs=5000] 超时时间(毫秒)
|
||||||
|
* @param {object|null} [endpoint=null] 可选远端端点对象;缺省调用本机 LS
|
||||||
* @returns {Promise<object>}
|
* @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') {
|
if (!lsRuntimeEndpoint.baseUrl && lsRuntimeEndpoint.addr !== 'test.invalid') {
|
||||||
await ensureLsEndpointDiscovered({ force: false });
|
await ensureLsEndpointDiscovered({ force: false });
|
||||||
}
|
}
|
||||||
@@ -113,35 +351,31 @@ export async function callLsRpc(method, body = {}, timeoutMs = 5000) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取官方实时配额摘要(`RetrieveUserQuotaSummary`)。
|
* 获取官方实时配额摘要(`RetrieveUserQuotaSummary`),按端点与账号隔离短期缓存。
|
||||||
*
|
|
||||||
* 缓存策略:
|
|
||||||
* - 常规轮询在 10 秒内直接复用内存缓存,避免高频打满上游接口;
|
|
||||||
* - 常规轮询发生网络失败或空载荷时进入 5 秒冷却退避,避免每 2 秒重复超时阻塞;
|
|
||||||
* - 当超过 TTL 或传入 `forceRefresh = true`(如手动刷新或检测到账号切换)时,
|
|
||||||
* 向 LS 传递 `{ forceRefresh: true }`,绕过 `language_server.exe` 自身的 3 分钟缓存。
|
|
||||||
*
|
*
|
||||||
* @param {boolean} [forceRefresh=false] 是否强制穿透本地缓存与失败冷却
|
* @param {boolean} [forceRefresh=false] 是否强制穿透本地缓存与失败冷却
|
||||||
* @param {string} [accountName=''] 发起查询时宿主报告的账号,用于隔离配额缓存
|
* @param {string} [accountName=''] 发起查询时宿主报告的账号,用于隔离配额缓存
|
||||||
|
* @param {object|null} [endpoint=null] 可选远端端点对象
|
||||||
* @returns {Promise<{data: object|null, fetchedAtMs: number, isStale: boolean, refreshFailed: boolean, error: string|null, fromCache: boolean}>}
|
* @returns {Promise<{data: object|null, fetchedAtMs: number, isStale: boolean, refreshFailed: boolean, error: string|null, fromCache: boolean}>}
|
||||||
*/
|
*/
|
||||||
export async function getOfficialQuotaSummary(forceRefresh = false, accountName = '') {
|
export async function getOfficialQuotaSummary(forceRefresh = false, accountName = '', endpoint = null) {
|
||||||
if (quotaSummaryCache.accountName !== accountName) {
|
const qCache = getEndpointQuotaCache(endpoint);
|
||||||
Object.assign(quotaSummaryCache, {
|
if (qCache.accountName !== accountName) {
|
||||||
|
Object.assign(qCache, {
|
||||||
accountName,
|
accountName,
|
||||||
accountGeneration: quotaSummaryCache.accountGeneration + 1,
|
accountGeneration: qCache.accountGeneration + 1,
|
||||||
ts: 0,
|
ts: 0,
|
||||||
lastAttemptTs: 0,
|
lastAttemptTs: 0,
|
||||||
data: null,
|
data: null,
|
||||||
error: null,
|
error: null,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const generation = quotaSummaryCache.accountGeneration;
|
const generation = qCache.accountGeneration;
|
||||||
const now = Date.now();
|
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 {
|
return {
|
||||||
data: quotaSummaryCache.data,
|
data: qCache.data,
|
||||||
fetchedAtMs: quotaSummaryCache.ts,
|
fetchedAtMs: qCache.ts,
|
||||||
isStale: false,
|
isStale: false,
|
||||||
refreshFailed: false,
|
refreshFailed: false,
|
||||||
error: null,
|
error: null,
|
||||||
@@ -150,35 +384,35 @@ export async function getOfficialQuotaSummary(forceRefresh = false, accountName
|
|||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
!forceRefresh &&
|
!forceRefresh &&
|
||||||
quotaSummaryCache.lastAttemptTs > 0 &&
|
qCache.lastAttemptTs > 0 &&
|
||||||
now - quotaSummaryCache.lastAttemptTs < QUOTA_RETRY_COOLDOWN_MS &&
|
now - qCache.lastAttemptTs < QUOTA_RETRY_COOLDOWN_MS &&
|
||||||
quotaSummaryCache.error
|
qCache.error
|
||||||
) {
|
) {
|
||||||
return {
|
return {
|
||||||
data: quotaSummaryCache.data,
|
data: qCache.data,
|
||||||
fetchedAtMs: quotaSummaryCache.ts || 0,
|
fetchedAtMs: qCache.ts || 0,
|
||||||
isStale: Boolean(quotaSummaryCache.data),
|
isStale: Boolean(qCache.data),
|
||||||
refreshFailed: true,
|
refreshFailed: true,
|
||||||
error: quotaSummaryCache.error,
|
error: qCache.error,
|
||||||
fromCache: true,
|
fromCache: true,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
quotaSummaryCache.lastAttemptTs = now;
|
qCache.lastAttemptTs = now;
|
||||||
try {
|
try {
|
||||||
const res = await callLsRpc('RetrieveUserQuotaSummary', { forceRefresh: true }, 6000);
|
const res = await callLsRpc('RetrieveUserQuotaSummary', { forceRefresh: true }, 6000, endpoint);
|
||||||
const { userStatus } = await callLsRpc('GetUserStatus', {}, 2000);
|
const { userStatus } = await callLsRpc('GetUserStatus', {}, 2500, endpoint);
|
||||||
if ((userStatus?.email || userStatus?.name || '') !== accountName) return {};
|
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;
|
const payload = res?.response !== undefined ? res.response : res;
|
||||||
if (payload && typeof payload === 'object' && !Array.isArray(payload)) {
|
if (payload && typeof payload === 'object' && !Array.isArray(payload)) {
|
||||||
const normalized =
|
const normalized =
|
||||||
Array.isArray(payload.groups) || Array.isArray(payload.buckets)
|
Array.isArray(payload.groups) || Array.isArray(payload.buckets)
|
||||||
? payload
|
? payload
|
||||||
: { ...payload, groups: [] };
|
: { ...payload, groups: [] };
|
||||||
quotaSummaryCache.ts = now;
|
qCache.ts = now;
|
||||||
quotaSummaryCache.data = normalized;
|
qCache.data = normalized;
|
||||||
quotaSummaryCache.error = null;
|
qCache.error = null;
|
||||||
return {
|
return {
|
||||||
data: normalized,
|
data: normalized,
|
||||||
fetchedAtMs: now,
|
fetchedAtMs: now,
|
||||||
@@ -188,18 +422,18 @@ export async function getOfficialQuotaSummary(forceRefresh = false, accountName
|
|||||||
fromCache: false,
|
fromCache: false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
quotaSummaryCache.error = 'Quota summary empty';
|
qCache.error = 'Quota summary empty';
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (generation !== quotaSummaryCache.accountGeneration) return {};
|
if (generation !== qCache.accountGeneration) return {};
|
||||||
console.error(`RetrieveUserQuotaSummary failed: ${err.message}`);
|
console.error(`RetrieveUserQuotaSummary failed: ${err.message}`);
|
||||||
quotaSummaryCache.error = err.message;
|
qCache.error = err.message;
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
data: quotaSummaryCache.data,
|
data: qCache.data,
|
||||||
fetchedAtMs: quotaSummaryCache.ts || 0,
|
fetchedAtMs: qCache.ts || 0,
|
||||||
isStale: Boolean(quotaSummaryCache.data),
|
isStale: Boolean(qCache.data),
|
||||||
refreshFailed: true,
|
refreshFailed: true,
|
||||||
error: quotaSummaryCache.error || 'Quota RPC unavailable',
|
error: qCache.error || 'Quota RPC unavailable',
|
||||||
fromCache: false,
|
fromCache: false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { isDeepStrictEqual } from 'node:util';
|
import { isDeepStrictEqual } from 'node:util';
|
||||||
|
import { LOCAL_ENDPOINT_ID } from '../shared/window-bridge-protocol.mjs';
|
||||||
import { scaleBucketsExact } from '../shared/telemetry-display-rules.mjs';
|
import { scaleBucketsExact } from '../shared/telemetry-display-rules.mjs';
|
||||||
import {
|
import {
|
||||||
extractLiveActivity,
|
extractLiveActivity,
|
||||||
@@ -22,14 +23,13 @@ import {
|
|||||||
import {
|
import {
|
||||||
CLI_STATUS_SNAPSHOT_FILE,
|
CLI_STATUS_SNAPSHOT_FILE,
|
||||||
computeRuntimeCodeVersion,
|
computeRuntimeCodeVersion,
|
||||||
getCachedTrajectory,
|
|
||||||
inFlightRequests,
|
inFlightRequests,
|
||||||
listCachedTrajectoryEntries,
|
|
||||||
loadSettings,
|
loadSettings,
|
||||||
lsRuntimeEndpoint,
|
lsRuntimeEndpoint,
|
||||||
roundMetric,
|
roundMetric,
|
||||||
saveJson,
|
saveJson,
|
||||||
} from './config.mjs';
|
} from './config.mjs';
|
||||||
|
import { getEndpointCacheStore } from './endpoint-registry.mjs';
|
||||||
import { getContextWindowGroups, getContextWindowModels } from './context-windows.mjs';
|
import { getContextWindowGroups, getContextWindowModels } from './context-windows.mjs';
|
||||||
import { readLocalSummarySnapshot } from './cli-sqlite-reader.mjs';
|
import { readLocalSummarySnapshot } from './cli-sqlite-reader.mjs';
|
||||||
import { enumerateAndSyncConversations } from './local-scanner.mjs';
|
import { enumerateAndSyncConversations } from './local-scanner.mjs';
|
||||||
@@ -57,17 +57,30 @@ import {
|
|||||||
|
|
||||||
const MAX_RECENT_CONVERSATIONS = 30;
|
const MAX_RECENT_CONVERSATIONS = 30;
|
||||||
const MAX_CONVERSATION_ASSEMBLY_CACHE = 8;
|
const MAX_CONVERSATION_ASSEMBLY_CACHE = 8;
|
||||||
|
const MAX_TELEMETRY_SNAPSHOT_ENDPOINTS = 8;
|
||||||
const POOL_PRIORITY_ORDER = ['Gemini', 'Argon', 'Carbon', 'Claude & GPT'];
|
const POOL_PRIORITY_ORDER = ['Gemini', 'Argon', 'Carbon', 'Claude & GPT'];
|
||||||
const inFlightTelemetrySources = new Map();
|
const inFlightTelemetrySources = new Map();
|
||||||
const trajectoryModelFacts = new WeakMap();
|
const trajectoryModelFacts = new WeakMap();
|
||||||
let agentStepPrepCache = new WeakMap();
|
let agentStepPrepCache = new WeakMap();
|
||||||
const conversationAssemblyCache = new Map();
|
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();
|
agentStepPrepCache = new WeakMap();
|
||||||
conversationAssemblyCache.clear();
|
conversationAssemblyCache.clear();
|
||||||
lastCompletedTelemetrySnapshot = null;
|
lastCompletedTelemetrySnapshotsByEndpoint.clear();
|
||||||
clearUsageAggregatorMemo();
|
clearUsageAggregatorMemo();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,12 +89,13 @@ function roundSessionCost(val) {
|
|||||||
return val < 0.01 ? +val.toFixed(4) : +val.toFixed(2);
|
return val < 0.01 ? +val.toFixed(4) : +val.toFixed(2);
|
||||||
}
|
}
|
||||||
|
|
||||||
function findTrajectoryCacheEntry(cascadeId) {
|
function findTrajectoryCacheEntry(cascadeId, cacheStore = null) {
|
||||||
if (!cascadeId) return null;
|
if (!cascadeId) return null;
|
||||||
const entry = getCachedTrajectory(cascadeId);
|
const store = cacheStore || getEndpointCacheStore(null);
|
||||||
|
const entry = store.getCachedTrajectory(cascadeId);
|
||||||
if (entry) return entry;
|
if (entry) return entry;
|
||||||
const targetLower = String(cascadeId).toLowerCase();
|
const targetLower = String(cascadeId).toLowerCase();
|
||||||
for (const [k, v] of listCachedTrajectoryEntries()) {
|
for (const [k, v] of store.listCachedTrajectoryEntries()) {
|
||||||
if (k.toLowerCase() === targetLower) return v;
|
if (k.toLowerCase() === targetLower) return v;
|
||||||
}
|
}
|
||||||
return null;
|
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();
|
const knownUpstreamByModelKey = new Map();
|
||||||
for (const [, entry] of listCachedTrajectoryEntries()) {
|
for (const [, entry] of store.listCachedTrajectoryEntries()) {
|
||||||
if (!entry?.steps?.length) continue;
|
if (!entry?.steps?.length) continue;
|
||||||
const facts = readTrajectoryModelFacts(entry.steps);
|
const facts = readTrajectoryModelFacts(entry.steps);
|
||||||
for (const [key, model] of facts.upstream) knownUpstreamByModelKey.set(key, model);
|
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) {
|
async function readTelemetrySources(
|
||||||
const localSummaries = readLocalSummarySnapshot(undefined, { forceRefresh: forceQuotaRefresh });
|
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([
|
const [allTrajRes, officialQuotaInfo, contextModelCatalog] = await Promise.all([
|
||||||
localSummaries.available
|
localSummaries.available
|
||||||
? Promise.resolve(null)
|
? Promise.resolve(null)
|
||||||
: callLsRpc('GetAllCascadeTrajectories', {}).catch(() => ({})),
|
: callLsRpc('GetAllCascadeTrajectories', {}, 5000, endpoint).catch(() => ({})),
|
||||||
userStatus ? getOfficialQuotaSummary(forceQuotaRefresh, currentAccountName) : null,
|
userStatus ? getOfficialQuotaSummary(forceQuotaRefresh, currentAccountName, endpoint) : null,
|
||||||
getContextModelCatalog(),
|
getContextModelCatalog(endpoint),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const sessions = await enumerateAndSyncConversations({
|
const sessions = await enumerateAndSyncConversations({
|
||||||
@@ -754,16 +779,25 @@ async function readTelemetrySources(requestedConvId, forceQuotaRefresh, currentA
|
|||||||
currentAccountName: accountScope,
|
currentAccountName: accountScope,
|
||||||
requestedConvId,
|
requestedConvId,
|
||||||
forceRefresh: forceQuotaRefresh,
|
forceRefresh: forceQuotaRefresh,
|
||||||
|
endpoint,
|
||||||
});
|
});
|
||||||
return { officialQuotaInfo, contextModelCatalog, sessions };
|
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(
|
const read = () => readTelemetrySources(
|
||||||
requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus
|
requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus, endpoint
|
||||||
);
|
);
|
||||||
if (forceQuotaRefresh) return read();
|
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);
|
const existing = inFlightTelemetrySources.get(key);
|
||||||
if (existing) return existing;
|
if (existing) return existing;
|
||||||
const pending = read().finally(() => {
|
const pending = read().finally(() => {
|
||||||
@@ -781,12 +815,17 @@ function buildActiveConversationAssembly({
|
|||||||
knownUpstreamByModelKey,
|
knownUpstreamByModelKey,
|
||||||
modelInputs,
|
modelInputs,
|
||||||
accountScope,
|
accountScope,
|
||||||
|
endpointId = LOCAL_ENDPOINT_ID,
|
||||||
|
cacheStore = null,
|
||||||
}) {
|
}) {
|
||||||
const activeSteps = activeEntry?.steps || [];
|
const activeSteps = activeEntry?.steps || [];
|
||||||
const subagentSummaries = activeConvSummary?.subagents || [];
|
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 subRawStepsList = subEntries.map((entry) => entry?.steps || []);
|
||||||
const combinedFallbackKeys = new Set();
|
const combinedFallbackKeys = new Set();
|
||||||
for (const k of readTrajectoryModelFacts(activeSteps).fallbackModelKeys) {
|
for (const k of readTrajectoryModelFacts(activeSteps).fallbackModelKeys) {
|
||||||
@@ -849,7 +888,7 @@ function buildActiveConversationAssembly({
|
|||||||
return cachedAssembly.result;
|
return cachedAssembly.result;
|
||||||
}
|
}
|
||||||
|
|
||||||
const agentReuseInputs = { ...modelInputs, activeCascadeId, accountScope };
|
const agentReuseInputs = { ...modelInputs, endpointId: epKey, activeCascadeId, accountScope };
|
||||||
const mainUnit = buildAgentUnitTelemetry({
|
const mainUnit = buildAgentUnitTelemetry({
|
||||||
agentId: 'main',
|
agentId: 'main',
|
||||||
cascadeId: activeCascadeId,
|
cascadeId: activeCascadeId,
|
||||||
@@ -1492,7 +1531,7 @@ function buildActivePoolAndWeeklyQuotas({
|
|||||||
*
|
*
|
||||||
* @param {string} requestedConvId 请求指定的会话 ID(为空时自动选定最近活跃会话)
|
* @param {string} requestedConvId 请求指定的会话 ID(为空时自动选定最近活跃会话)
|
||||||
* @param {boolean} [forceQuotaRefresh=false] 是否强制穿透官方配额缓存与失败退避
|
* @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>}
|
* @returns {Promise<object>}
|
||||||
*/
|
*/
|
||||||
export async function buildTelemetryPayloadInternal(
|
export async function buildTelemetryPayloadInternal(
|
||||||
@@ -1500,11 +1539,18 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
forceQuotaRefresh = false,
|
forceQuotaRefresh = false,
|
||||||
filterOpts = {}
|
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();
|
const settings = loadSettings();
|
||||||
let userStatus = await callLsRpc('GetUserStatus', {})
|
let userStatus = await callLsRpc('GetUserStatus', {}, 5000, endpoint)
|
||||||
.then((data) => data?.userStatus)
|
.then((data) => data?.userStatus)
|
||||||
.catch(() => null);
|
.catch(() => null);
|
||||||
if (
|
if (
|
||||||
|
!isRemote &&
|
||||||
!userStatus &&
|
!userStatus &&
|
||||||
lsRuntimeEndpoint.addr !== 'test.invalid' &&
|
lsRuntimeEndpoint.addr !== 'test.invalid' &&
|
||||||
(!lsRuntimeEndpoint.baseUrl || lsRuntimeEndpoint.isDynamic)
|
(!lsRuntimeEndpoint.baseUrl || lsRuntimeEndpoint.isDynamic)
|
||||||
@@ -1529,7 +1575,7 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
userStatus && !userStatus.userTier && !userStatus.planStatus ? 'signedOut' : 'unknown';
|
userStatus && !userStatus.userTier && !userStatus.planStatus ? 'signedOut' : 'unknown';
|
||||||
const accountScope = accountStatus === 'signedOut' ? null : currentAccountName;
|
const accountScope = accountStatus === 'signedOut' ? null : currentAccountName;
|
||||||
const { officialQuotaInfo, contextModelCatalog, sessions } = await getTelemetrySources(
|
const { officialQuotaInfo, contextModelCatalog, sessions } = await getTelemetrySources(
|
||||||
requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus
|
requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus, endpoint
|
||||||
);
|
);
|
||||||
const { conversations, activeConvSummary, activeCascadeId } = sessions;
|
const { conversations, activeConvSummary, activeCascadeId } = sessions;
|
||||||
|
|
||||||
@@ -1546,8 +1592,8 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
|
|
||||||
// 3. 计算当前活跃根会话及其子代理的步骤指标、10 通道上下文拆解与按模型汇总
|
// 3. 计算当前活跃根会话及其子代理的步骤指标、10 通道上下文拆解与按模型汇总
|
||||||
const reportedContextLimits = new Map();
|
const reportedContextLimits = new Map();
|
||||||
const knownUpstreamByModelKey = buildKnownUpstreamModelMap(reportedContextLimits);
|
const knownUpstreamByModelKey = buildKnownUpstreamModelMap(reportedContextLimits, cacheStore);
|
||||||
const activeEntry = findTrajectoryCacheEntry(activeCascadeId);
|
const activeEntry = findTrajectoryCacheEntry(activeCascadeId, cacheStore);
|
||||||
const modelInputs = {
|
const modelInputs = {
|
||||||
catalogRevision: pricingCatalogRevision,
|
catalogRevision: pricingCatalogRevision,
|
||||||
phaseEpoch: getPricingPhaseEpoch(),
|
phaseEpoch: getPricingPhaseEpoch(),
|
||||||
@@ -1565,6 +1611,8 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
knownUpstreamByModelKey,
|
knownUpstreamByModelKey,
|
||||||
modelInputs,
|
modelInputs,
|
||||||
accountScope,
|
accountScope,
|
||||||
|
endpointId,
|
||||||
|
cacheStore,
|
||||||
});
|
});
|
||||||
|
|
||||||
// 4. 识别当前活跃会话家族绑定的模型池(与 quota-pools.mjs 保持一致,将 Other 第三方模型归入 Claude & GPT)
|
// 4. 识别当前活跃会话家族绑定的模型池(与 quota-pools.mjs 保持一致,将 Other 第三方模型归入 Claude & GPT)
|
||||||
@@ -1623,6 +1671,7 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
resolveStepModel,
|
resolveStepModel,
|
||||||
quotaPoolsMap,
|
quotaPoolsMap,
|
||||||
modelInputs,
|
modelInputs,
|
||||||
|
endpoint,
|
||||||
});
|
});
|
||||||
|
|
||||||
for (const [pk, poolObj] of quotaPoolsMap.entries()) {
|
for (const [pk, poolObj] of quotaPoolsMap.entries()) {
|
||||||
@@ -1665,7 +1714,7 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
if (cidKey && quickStatsMemo.has(cidKey)) {
|
if (cidKey && quickStatsMemo.has(cidKey)) {
|
||||||
return quickStatsMemo.get(cidKey);
|
return quickStatsMemo.get(cidKey);
|
||||||
}
|
}
|
||||||
const rootEntry = findTrajectoryCacheEntry(rootConv?.cascadeId);
|
const rootEntry = findTrajectoryCacheEntry(rootConv?.cascadeId, cacheStore);
|
||||||
const rootSteps = rootEntry?.steps || [];
|
const rootSteps = rootEntry?.steps || [];
|
||||||
const rawSubs = Array.isArray(rootConv?.subagents) ? rootConv.subagents : [];
|
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);
|
let bestMetricRunning = rootConv?.status === 'CASCADE_RUN_STATUS_RUNNING' && Boolean(lastRootStep);
|
||||||
|
|
||||||
for (const subSum of rawSubs) {
|
for (const subSum of rawSubs) {
|
||||||
const subEntry = findTrajectoryCacheEntry(subSum?.cascadeId);
|
const subEntry = findTrajectoryCacheEntry(subSum?.cascadeId, cacheStore);
|
||||||
const subSteps = subEntry?.steps || [];
|
const subSteps = subEntry?.steps || [];
|
||||||
if (subSteps.length === 0) continue;
|
if (subSteps.length === 0) continue;
|
||||||
accumulateStepsCost(subSteps);
|
accumulateStepsCost(subSteps);
|
||||||
@@ -1752,7 +1801,7 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const rootEntry = findTrajectoryCacheEntry(rootConv.cascadeId);
|
const rootEntry = findTrajectoryCacheEntry(rootConv.cascadeId, cacheStore);
|
||||||
const rootFallbackMs =
|
const rootFallbackMs =
|
||||||
rootConv.lastModifiedMs || rootEntry?.lastModifiedMs || rootConv.createdTimeMs || 0;
|
rootConv.lastModifiedMs || rootEntry?.lastModifiedMs || rootConv.createdTimeMs || 0;
|
||||||
|
|
||||||
@@ -1761,7 +1810,7 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
let runSideIdx = 0;
|
let runSideIdx = 0;
|
||||||
const subItems = rawSubs.map((subSum, idx) => {
|
const subItems = rawSubs.map((subSum, idx) => {
|
||||||
const subCid = subSum.cascadeId;
|
const subCid = subSum.cascadeId;
|
||||||
const subEntry = findTrajectoryCacheEntry(subCid);
|
const subEntry = findTrajectoryCacheEntry(subCid, cacheStore);
|
||||||
const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null;
|
const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null;
|
||||||
const isSideQ = Boolean(
|
const isSideQ = Boolean(
|
||||||
subSum.isSideQuestion || subEntry?.isSideQuestion || subSpec?.typeName === 'side_question'
|
subSum.isSideQuestion || subEntry?.isSideQuestion || subSpec?.typeName === 'side_question'
|
||||||
@@ -2016,6 +2065,11 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
const finalPayload = {
|
const finalPayload = {
|
||||||
timestamp: new Date().toISOString(),
|
timestamp: new Date().toISOString(),
|
||||||
hostPlatform: process.platform || 'unknown',
|
hostPlatform: process.platform || 'unknown',
|
||||||
|
endpoint: {
|
||||||
|
id: endpointId,
|
||||||
|
isRemote,
|
||||||
|
label: endpointLabel,
|
||||||
|
},
|
||||||
uiBundleVersion,
|
uiBundleVersion,
|
||||||
windowBridge: getDefaultWindowBridgeStatus(),
|
windowBridge: getDefaultWindowBridgeStatus(),
|
||||||
settings: loadSettings(),
|
settings: loadSettings(),
|
||||||
@@ -2104,8 +2158,20 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
modelBreakdown,
|
modelBreakdown,
|
||||||
};
|
};
|
||||||
|
|
||||||
lastCompletedTelemetrySnapshot = {
|
const endpointSig = isRemote
|
||||||
lsAddr: String(lsRuntimeEndpoint.addr || ''),
|
? `${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,
|
weeklyLimitMode: settings.weeklyLimitMode,
|
||||||
weeklyTokenBudget: settings.weeklyTokenBudget,
|
weeklyTokenBudget: settings.weeklyTokenBudget,
|
||||||
weeklyCostBudget: settings.weeklyCostBudget,
|
weeklyCostBudget: settings.weeklyCostBudget,
|
||||||
@@ -2132,10 +2198,11 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
resolveStepModel,
|
resolveStepModel,
|
||||||
quotaPoolsMap,
|
quotaPoolsMap,
|
||||||
modelInputs,
|
modelInputs,
|
||||||
|
endpoint,
|
||||||
},
|
},
|
||||||
};
|
});
|
||||||
|
|
||||||
if (lsRuntimeEndpoint.addr !== 'test.invalid') {
|
if (!isRemote && lsRuntimeEndpoint.addr !== 'test.invalid') {
|
||||||
try {
|
try {
|
||||||
saveJson(CLI_STATUS_SNAPSHOT_FILE, buildCliStatusSnapshot(finalPayload, Date.now()));
|
saveJson(CLI_STATUS_SNAPSHOT_FILE, buildCliStatusSnapshot(finalPayload, Date.now()));
|
||||||
} catch {
|
} catch {
|
||||||
@@ -2146,10 +2213,15 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
return finalPayload;
|
return finalPayload;
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolveValidFastSnapshot() {
|
function resolveValidFastSnapshot(endpoint = null) {
|
||||||
const snap = lastCompletedTelemetrySnapshot;
|
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 || !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 (
|
if (
|
||||||
snap.catalogRevision !== pricingCatalogRevision ||
|
snap.catalogRevision !== pricingCatalogRevision ||
|
||||||
snap.phaseEpoch !== getPricingPhaseEpoch()
|
snap.phaseEpoch !== getPricingPhaseEpoch()
|
||||||
@@ -2177,7 +2249,10 @@ function entryNeedsLazyTelemetryUpgrade(entry) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) {
|
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;
|
if (!snap || !Array.isArray(snap.sessions?.conversations)) return null;
|
||||||
|
|
||||||
const convList = snap.sessions.conversations;
|
const convList = snap.sessions.conversations;
|
||||||
@@ -2192,7 +2267,7 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) {
|
|||||||
if (!activeConvSummary?.cascadeId) return null;
|
if (!activeConvSummary?.cascadeId) return null;
|
||||||
|
|
||||||
const activeCascadeId = activeConvSummary.cascadeId;
|
const activeCascadeId = activeConvSummary.cascadeId;
|
||||||
const activeEntry = findTrajectoryCacheEntry(activeCascadeId);
|
const activeEntry = findTrajectoryCacheEntry(activeCascadeId, cacheStore);
|
||||||
if (!activeEntry) return null;
|
if (!activeEntry) return null;
|
||||||
|
|
||||||
const subagentSummaries = Array.isArray(activeConvSummary.subagents)
|
const subagentSummaries = Array.isArray(activeConvSummary.subagents)
|
||||||
@@ -2207,7 +2282,7 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) {
|
|||||||
needsBackgroundSync = true;
|
needsBackgroundSync = true;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
const subEntry = findTrajectoryCacheEntry(subSum?.cascadeId);
|
const subEntry = findTrajectoryCacheEntry(subSum?.cascadeId, cacheStore);
|
||||||
if (!subEntry || entryNeedsLazyTelemetryUpgrade(subEntry)) {
|
if (!subEntry || entryNeedsLazyTelemetryUpgrade(subEntry)) {
|
||||||
needsBackgroundSync = true;
|
needsBackgroundSync = true;
|
||||||
break;
|
break;
|
||||||
@@ -2228,6 +2303,8 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) {
|
|||||||
knownUpstreamByModelKey: snap.knownUpstreamByModelKey,
|
knownUpstreamByModelKey: snap.knownUpstreamByModelKey,
|
||||||
modelInputs: snap.aggContext.modelInputs,
|
modelInputs: snap.aggContext.modelInputs,
|
||||||
accountScope: snap.aggContext.currentAccountName,
|
accountScope: snap.aggContext.currentAccountName,
|
||||||
|
endpointId,
|
||||||
|
cacheStore,
|
||||||
});
|
});
|
||||||
|
|
||||||
const { activePoolKey, activeLive5h, activeLiveWeekly } = resolveActivePoolKeyFromStep(
|
const { activePoolKey, activeLive5h, activeLiveWeekly } = resolveActivePoolKeyFromStep(
|
||||||
@@ -2255,11 +2332,13 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) {
|
|||||||
activeFamilyCascadeIds,
|
activeFamilyCascadeIds,
|
||||||
resolveStepModel: snap.aggContext.resolveStepModel,
|
resolveStepModel: snap.aggContext.resolveStepModel,
|
||||||
quotaPoolsMap: snap.quotaContext.quotaPoolsMap,
|
quotaPoolsMap: snap.quotaContext.quotaPoolsMap,
|
||||||
|
endpoint,
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
scope: 'conversation',
|
scope: 'conversation',
|
||||||
timestamp: new Date().toISOString(),
|
timestamp: new Date().toISOString(),
|
||||||
|
endpoint: snap.basePayload.endpoint,
|
||||||
uiBundleVersion: snap.basePayload.uiBundleVersion || computeRuntimeCodeVersion(),
|
uiBundleVersion: snap.basePayload.uiBundleVersion || computeRuntimeCodeVersion(),
|
||||||
account: snap.basePayload.account,
|
account: snap.basePayload.account,
|
||||||
activeCascadeId,
|
activeCascadeId,
|
||||||
@@ -2277,15 +2356,18 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function tryBuildFastConsumptionPayload(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;
|
if (!snap) return null;
|
||||||
const agg = aggregateSelectedWindowUsage({
|
const agg = aggregateSelectedWindowUsage({
|
||||||
filterOpts,
|
filterOpts,
|
||||||
...snap.aggContext,
|
...snap.aggContext,
|
||||||
|
endpoint,
|
||||||
});
|
});
|
||||||
return {
|
return {
|
||||||
scope: 'consumption',
|
scope: 'consumption',
|
||||||
timestamp: new Date().toISOString(),
|
timestamp: new Date().toISOString(),
|
||||||
|
endpoint: snap.basePayload.endpoint,
|
||||||
uiBundleVersion: snap.basePayload.uiBundleVersion || computeRuntimeCodeVersion(),
|
uiBundleVersion: snap.basePayload.uiBundleVersion || computeRuntimeCodeVersion(),
|
||||||
usageRevision: agg.usageRevision,
|
usageRevision: agg.usageRevision,
|
||||||
consumption: {
|
consumption: {
|
||||||
@@ -2305,13 +2387,18 @@ function tryBuildFastConsumptionPayload(filterOpts = {}) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function tryBuildConsumptionPresetsPayload() {
|
function tryBuildConsumptionPresetsPayload(filterOpts = {}) {
|
||||||
const snap = resolveValidFastSnapshot();
|
const endpoint = filterOpts?.endpoint && filterOpts.endpoint.isRemote ? filterOpts.endpoint : null;
|
||||||
|
const snap = resolveValidFastSnapshot(endpoint);
|
||||||
if (!snap) return null;
|
if (!snap) return null;
|
||||||
const bundle = aggregateConsumptionPresetBundle(snap.aggContext);
|
const bundle = aggregateConsumptionPresetBundle({
|
||||||
|
...snap.aggContext,
|
||||||
|
endpoint,
|
||||||
|
});
|
||||||
return {
|
return {
|
||||||
scope: 'consumption-presets',
|
scope: 'consumption-presets',
|
||||||
timestamp: new Date().toISOString(),
|
timestamp: new Date().toISOString(),
|
||||||
|
endpoint: snap.basePayload.endpoint,
|
||||||
uiBundleVersion: snap.basePayload.uiBundleVersion || computeRuntimeCodeVersion(),
|
uiBundleVersion: snap.basePayload.uiBundleVersion || computeRuntimeCodeVersion(),
|
||||||
usageRevision: bundle.usageRevision,
|
usageRevision: bundle.usageRevision,
|
||||||
ranges: bundle.ranges,
|
ranges: bundle.ranges,
|
||||||
@@ -2370,6 +2457,9 @@ export function buildTelemetryPayload(
|
|||||||
forceQuotaRefresh = false,
|
forceQuotaRefresh = false,
|
||||||
filterOpts = {}
|
filterOpts = {}
|
||||||
) {
|
) {
|
||||||
|
const endpointKey = filterOpts?.endpoint?.isRemote
|
||||||
|
? String(filterOpts.endpoint.id || 'remote')
|
||||||
|
: LOCAL_ENDPOINT_ID;
|
||||||
if (!forceQuotaRefresh) {
|
if (!forceQuotaRefresh) {
|
||||||
if (filterOpts?.scope === 'conversation') {
|
if (filterOpts?.scope === 'conversation') {
|
||||||
const convPayload = tryBuildFastConversationPayload(requestedConvId, filterOpts);
|
const convPayload = tryBuildFastConversationPayload(requestedConvId, filterOpts);
|
||||||
@@ -2378,16 +2468,19 @@ export function buildTelemetryPayload(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (filterOpts?.scope === 'consumption-presets') {
|
if (filterOpts?.scope === 'consumption-presets') {
|
||||||
const presetsPayload = tryBuildConsumptionPresetsPayload();
|
const presetsPayload = tryBuildConsumptionPresetsPayload(filterOpts);
|
||||||
if (presetsPayload) {
|
if (presetsPayload) {
|
||||||
return Promise.resolve(presetsPayload);
|
return Promise.resolve(presetsPayload);
|
||||||
}
|
}
|
||||||
const key = `${requestedConvId || '__auto__'}::presets-cold`;
|
const key = `${endpointKey}::${requestedConvId || '__auto__'}::presets-cold`;
|
||||||
if (inFlightRequests.has(key)) {
|
if (inFlightRequests.has(key)) {
|
||||||
return inFlightRequests.get(key);
|
return inFlightRequests.get(key);
|
||||||
}
|
}
|
||||||
const p = buildTelemetryPayloadInternal(requestedConvId, false, { range: 'today' })
|
const coldFilterOpts = filterOpts?.endpoint
|
||||||
.then(() => tryBuildConsumptionPresetsPayload())
|
? { range: 'today', endpoint: filterOpts.endpoint }
|
||||||
|
: { range: 'today' };
|
||||||
|
const p = buildTelemetryPayloadInternal(requestedConvId, false, coldFilterOpts)
|
||||||
|
.then(() => tryBuildConsumptionPresetsPayload(filterOpts))
|
||||||
.finally(() => {
|
.finally(() => {
|
||||||
inFlightRequests.delete(key);
|
inFlightRequests.delete(key);
|
||||||
});
|
});
|
||||||
@@ -2402,7 +2495,7 @@ export function buildTelemetryPayload(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
const rangeSig = `${filterOpts.range || 'all'}:${filterOpts.startMs || 0}:${filterOpts.endMs || 0}`;
|
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)) {
|
if (inFlightRequests.has(key)) {
|
||||||
return inFlightRequests.get(key);
|
return inFlightRequests.get(key);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,8 @@ import {
|
|||||||
} from 'node:fs';
|
} from 'node:fs';
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
|
|
||||||
let lastWrite = null;
|
const MAX_TRACKED_CACHE_FILES = 16;
|
||||||
|
const lastWritesByPath = new Map();
|
||||||
|
|
||||||
function isSameFile(a, b) {
|
function isSameFile(a, b) {
|
||||||
return b.ino !== 0n && a.dev === b.dev && a.ino === b.ino &&
|
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) {
|
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 bytes = previous ? readReusableBytes(filePath, previous.file) : null;
|
||||||
const ranges = new WeakMap();
|
const ranges = new WeakMap();
|
||||||
const parts = [];
|
const parts = [];
|
||||||
@@ -72,7 +73,14 @@ export function writeTrajectoryCacheFile(filePath, data) {
|
|||||||
const written = statSync(temporaryPath, { bigint: true });
|
const written = statSync(temporaryPath, { bigint: true });
|
||||||
renameSync(temporaryPath, filePath);
|
renameSync(temporaryPath, filePath);
|
||||||
const file = statSync(filePath, { bigint: true });
|
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 {
|
} finally {
|
||||||
try { unlinkSync(temporaryPath); } catch {}
|
try { unlinkSync(temporaryPath); } catch {}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,8 @@ import {
|
|||||||
finishSpeed,
|
finishSpeed,
|
||||||
parseIsoMs,
|
parseIsoMs,
|
||||||
} from '../trajectory-metrics.mjs';
|
} 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 { loadExternalDeepStatsCache } from './local-scanner.mjs';
|
||||||
import {
|
import {
|
||||||
computeStepCost,
|
computeStepCost,
|
||||||
@@ -430,7 +431,8 @@ export function buildScopedModelBreakdown(steps, resolveStepModel) {
|
|||||||
return finalizeModelBreakdownMap(perModelStats);
|
return finalizeModelBreakdownMap(perModelStats);
|
||||||
}
|
}
|
||||||
|
|
||||||
let lastUsageSnapshot = null;
|
const MAX_USAGE_SNAPSHOT_ENDPOINTS = 8;
|
||||||
|
const lastUsageSnapshotsByEndpoint = new Map();
|
||||||
let usageSnapshotRevisionSeq = 0;
|
let usageSnapshotRevisionSeq = 0;
|
||||||
const stepsTimeBoundsCache = new WeakMap();
|
const stepsTimeBoundsCache = new WeakMap();
|
||||||
const MAX_TREND_TIMESTAMP_MS = 8_640_000_000_000_000;
|
const MAX_TREND_TIMESTAMP_MS = 8_640_000_000_000_000;
|
||||||
@@ -439,10 +441,15 @@ const USAGE_SOURCE_LABELS = {
|
|||||||
standalone: 'Antigravity App',
|
standalone: 'Antigravity App',
|
||||||
ide: 'Antigravity IDE',
|
ide: 'Antigravity IDE',
|
||||||
cli: 'Antigravity CLI',
|
cli: 'Antigravity CLI',
|
||||||
|
ssh: 'Antigravity SSH',
|
||||||
};
|
};
|
||||||
|
|
||||||
export function clearUsageAggregatorMemo() {
|
export function clearUsageAggregatorMemo(endpointId = null) {
|
||||||
lastUsageSnapshot = null;
|
if (endpointId) {
|
||||||
|
lastUsageSnapshotsByEndpoint.delete(String(endpointId));
|
||||||
|
} else {
|
||||||
|
lastUsageSnapshotsByEndpoint.clear();
|
||||||
|
}
|
||||||
usageSnapshotRevisionSeq += 1;
|
usageSnapshotRevisionSeq += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -466,12 +473,14 @@ function getStepsTimeBounds(steps) {
|
|||||||
return bounds;
|
return bounds;
|
||||||
}
|
}
|
||||||
|
|
||||||
function collectUsageEntriesToAggregate(familySet) {
|
function collectUsageEntriesToAggregate(familySet, endpoint = null) {
|
||||||
const externalConvos = loadExternalDeepStatsCache();
|
const isRemote = Boolean(endpoint && endpoint.isRemote);
|
||||||
|
const cacheStore = getEndpointCacheStore(endpoint);
|
||||||
|
const externalConvos = isRemote ? new Map() : loadExternalDeepStatsCache();
|
||||||
|
|
||||||
// 构建大小写归一化的内存缓存与跨端深层缓存索引,彻底杜绝 `${appSource}:${cascadeId}` 键不匹配导致的双倍重复计费
|
// 构建大小写归一化的内存缓存与跨端深层缓存索引,彻底杜绝 `${appSource}:${cascadeId}` 键不匹配导致的双倍重复计费
|
||||||
const allLiveByLower = new Map();
|
const allLiveByLower = new Map();
|
||||||
for (const [rawId, entry] of listCachedTrajectoryEntries()) {
|
for (const [rawId, entry] of cacheStore.listCachedTrajectoryEntries()) {
|
||||||
const cidLower = String(rawId || '').toLowerCase();
|
const cidLower = String(rawId || '').toLowerCase();
|
||||||
if (!cidLower || !entry || typeof entry !== 'object') continue;
|
if (!cidLower || !entry || typeof entry !== 'object') continue;
|
||||||
const prev = allLiveByLower.get(cidLower);
|
const prev = allLiveByLower.get(cidLower);
|
||||||
@@ -502,7 +511,7 @@ function collectUsageEntriesToAggregate(familySet) {
|
|||||||
).toLowerCase();
|
).toLowerCase();
|
||||||
allEntriesToAggregate.push({
|
allEntriesToAggregate.push({
|
||||||
cascadeId: groupCascadeId,
|
cascadeId: groupCascadeId,
|
||||||
appSource: entry?.appSource || 'standalone',
|
appSource: isRemote ? 'ssh' : entry?.appSource || 'standalone',
|
||||||
accountName: entry?.accountName || extMatch?.accountName || '',
|
accountName: entry?.accountName || extMatch?.accountName || '',
|
||||||
steps: entry?.steps || [],
|
steps: entry?.steps || [],
|
||||||
isCurrentConv: familySet.has(cidLower),
|
isCurrentConv: familySet.has(cidLower),
|
||||||
@@ -1051,7 +1060,10 @@ export function aggregateMultiWindowUsage({
|
|||||||
resolveStepModel,
|
resolveStepModel,
|
||||||
quotaPoolsMap = null,
|
quotaPoolsMap = null,
|
||||||
modelInputs = null,
|
modelInputs = null,
|
||||||
|
endpoint = null,
|
||||||
}) {
|
}) {
|
||||||
|
const isRemote = Boolean(endpoint && endpoint.isRemote);
|
||||||
|
const endpointKey = isRemote ? String(endpoint.id || 'remote') : 'local';
|
||||||
const rawFamilyIds =
|
const rawFamilyIds =
|
||||||
activeFamilyCascadeIds instanceof Set
|
activeFamilyCascadeIds instanceof Set
|
||||||
? Array.from(activeFamilyCascadeIds)
|
? Array.from(activeFamilyCascadeIds)
|
||||||
@@ -1117,7 +1129,7 @@ export function aggregateMultiWindowUsage({
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
const perSourceStats = new Map();
|
const perSourceStats = new Map();
|
||||||
const allEntriesToAggregate = collectUsageEntriesToAggregate(familySet);
|
const allEntriesToAggregate = collectUsageEntriesToAggregate(familySet, endpoint);
|
||||||
const familySig = buildFamilySig(familySet);
|
const familySig = buildFamilySig(familySet);
|
||||||
|
|
||||||
const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : '';
|
const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : '';
|
||||||
@@ -1126,7 +1138,7 @@ export function aggregateMultiWindowUsage({
|
|||||||
{ key: `${key}:week`, startMs: startWkMs, endMs: nowMs },
|
{ key: `${key}:week`, startMs: startWkMs, endMs: nowMs },
|
||||||
]).flat();
|
]).flat();
|
||||||
const windows = [selectedWindow, ...Object.values(presetWindows), ...quotaWindows];
|
const windows = [selectedWindow, ...Object.values(presetWindows), ...quotaWindows];
|
||||||
const snapshot = lastUsageSnapshot;
|
const snapshot = lastUsageSnapshotsByEndpoint.get(endpointKey) || null;
|
||||||
const sameSnapshot = modelInputs && snapshot && timeZone === snapshot.timeZone &&
|
const sameSnapshot = modelInputs && snapshot && timeZone === snapshot.timeZone &&
|
||||||
currentYear === snapshot.currentYear &&
|
currentYear === snapshot.currentYear &&
|
||||||
Boolean(isCustomWeeklyMode) === Boolean(snapshot.isCustomWeeklyMode) &&
|
Boolean(isCustomWeeklyMode) === Boolean(snapshot.isCustomWeeklyMode) &&
|
||||||
@@ -1459,10 +1471,11 @@ export function aggregateMultiWindowUsage({
|
|||||||
: null;
|
: null;
|
||||||
|
|
||||||
let resolvedUsageRevision = usageSnapshotRevisionSeq;
|
let resolvedUsageRevision = usageSnapshotRevisionSeq;
|
||||||
|
let activeSnap = snapshot;
|
||||||
if (modelInputs) {
|
if (modelInputs) {
|
||||||
if (!sameSnapshot) {
|
if (!sameSnapshot) {
|
||||||
resolvedUsageRevision = ++usageSnapshotRevisionSeq;
|
resolvedUsageRevision = ++usageSnapshotRevisionSeq;
|
||||||
lastUsageSnapshot = {
|
activeSnap = {
|
||||||
revision: resolvedUsageRevision,
|
revision: resolvedUsageRevision,
|
||||||
timeZone,
|
timeZone,
|
||||||
modelInputs,
|
modelInputs,
|
||||||
@@ -1474,8 +1487,14 @@ export function aggregateMultiWindowUsage({
|
|||||||
ranges: new Map(),
|
ranges: new Map(),
|
||||||
selectedRanges: 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 {
|
} else {
|
||||||
resolvedUsageRevision = lastUsageSnapshot.revision;
|
resolvedUsageRevision = activeSnap.revision;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
resolvedUsageRevision = ++usageSnapshotRevisionSeq;
|
resolvedUsageRevision = ++usageSnapshotRevisionSeq;
|
||||||
@@ -1500,8 +1519,8 @@ export function aggregateMultiWindowUsage({
|
|||||||
poolCycleStats,
|
poolCycleStats,
|
||||||
poolsWeeklySummary,
|
poolsWeeklySummary,
|
||||||
};
|
};
|
||||||
if (modelInputs && lastUsageSnapshot) {
|
if (modelInputs && activeSnap) {
|
||||||
const { ranges } = lastUsageSnapshot;
|
const { ranges } = activeSnap;
|
||||||
ranges.delete(selectedWindow.key);
|
ranges.delete(selectedWindow.key);
|
||||||
ranges.set(selectedWindow.key, {
|
ranges.set(selectedWindow.key, {
|
||||||
familySig,
|
familySig,
|
||||||
@@ -1536,7 +1555,10 @@ export function aggregateSelectedWindowUsage({
|
|||||||
quotaPoolsMap = null,
|
quotaPoolsMap = null,
|
||||||
modelInputs = null,
|
modelInputs = null,
|
||||||
precollectedEntries = null,
|
precollectedEntries = null,
|
||||||
|
endpoint = null,
|
||||||
}) {
|
}) {
|
||||||
|
const isRemote = Boolean(endpoint && endpoint.isRemote);
|
||||||
|
const endpointKey = isRemote ? String(endpoint.id || 'remote') : 'local';
|
||||||
const rawFamilyIds =
|
const rawFamilyIds =
|
||||||
activeFamilyCascadeIds instanceof Set
|
activeFamilyCascadeIds instanceof Set
|
||||||
? Array.from(activeFamilyCascadeIds)
|
? Array.from(activeFamilyCascadeIds)
|
||||||
@@ -1567,12 +1589,12 @@ export function aggregateSelectedWindowUsage({
|
|||||||
|
|
||||||
const allEntriesToAggregate = Array.isArray(precollectedEntries)
|
const allEntriesToAggregate = Array.isArray(precollectedEntries)
|
||||||
? precollectedEntries
|
? precollectedEntries
|
||||||
: collectUsageEntriesToAggregate(familySet);
|
: collectUsageEntriesToAggregate(familySet, endpoint);
|
||||||
const familySig = buildFamilySig(familySet);
|
const familySig = buildFamilySig(familySet);
|
||||||
const currentYear = new Date(nowMs).getFullYear();
|
const currentYear = new Date(nowMs).getFullYear();
|
||||||
const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : '';
|
const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : '';
|
||||||
|
|
||||||
const snapshot = lastUsageSnapshot;
|
const snapshot = lastUsageSnapshotsByEndpoint.get(endpointKey) || null;
|
||||||
const sameSnapshot = Boolean(
|
const sameSnapshot = Boolean(
|
||||||
modelInputs &&
|
modelInputs &&
|
||||||
snapshot &&
|
snapshot &&
|
||||||
@@ -1885,7 +1907,10 @@ export function aggregateSessionUsageForFamily({
|
|||||||
activeFamilyCascadeIds = null,
|
activeFamilyCascadeIds = null,
|
||||||
resolveStepModel,
|
resolveStepModel,
|
||||||
quotaPoolsMap = null,
|
quotaPoolsMap = null,
|
||||||
|
endpoint = null,
|
||||||
}) {
|
}) {
|
||||||
|
const isRemote = Boolean(endpoint && endpoint.isRemote);
|
||||||
|
const cacheStore = getEndpointCacheStore(endpoint);
|
||||||
const rawFamilyIds =
|
const rawFamilyIds =
|
||||||
activeFamilyCascadeIds instanceof Set
|
activeFamilyCascadeIds instanceof Set
|
||||||
? Array.from(activeFamilyCascadeIds)
|
? Array.from(activeFamilyCascadeIds)
|
||||||
@@ -1912,13 +1937,13 @@ export function aggregateSessionUsageForFamily({
|
|||||||
currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName);
|
currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName);
|
||||||
|
|
||||||
const familyEntries = [];
|
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;
|
if (!entry || !Array.isArray(entry.steps) || entry.steps.length === 0) continue;
|
||||||
const cidLower = String(cid || '').toLowerCase();
|
const cidLower = String(cid || '').toLowerCase();
|
||||||
if (!familySet.has(cidLower)) continue;
|
if (!familySet.has(cidLower)) continue;
|
||||||
familyEntries.push({
|
familyEntries.push({
|
||||||
cascadeId: cid,
|
cascadeId: cid,
|
||||||
appSource: entry.appSource || 'standalone',
|
appSource: isRemote ? 'ssh' : entry.appSource || 'standalone',
|
||||||
accountName: entry.accountName || '',
|
accountName: entry.accountName || '',
|
||||||
steps: entry.steps,
|
steps: entry.steps,
|
||||||
isCurrentConv: true,
|
isCurrentConv: true,
|
||||||
@@ -1943,7 +1968,7 @@ export function aggregateSessionUsageForFamily({
|
|||||||
* 批量预聚合全部 7 个用量页预设区间(复用同一次条目收集与时间剪枝),供前端进入「用量统计」时静默预取实现 0ms 瞬切。
|
* 批量预聚合全部 7 个用量页预设区间(复用同一次条目收集与时间剪枝),供前端进入「用量统计」时静默预取实现 0ms 瞬切。
|
||||||
*/
|
*/
|
||||||
export function aggregateConsumptionPresetBundle(params) {
|
export function aggregateConsumptionPresetBundle(params) {
|
||||||
const { activeCascadeId = null, activeFamilyCascadeIds = null } = params || {};
|
const { activeCascadeId = null, activeFamilyCascadeIds = null, endpoint = null } = params || {};
|
||||||
const rawFamilyIds =
|
const rawFamilyIds =
|
||||||
activeFamilyCascadeIds instanceof Set
|
activeFamilyCascadeIds instanceof Set
|
||||||
? Array.from(activeFamilyCascadeIds)
|
? Array.from(activeFamilyCascadeIds)
|
||||||
@@ -1951,7 +1976,7 @@ export function aggregateConsumptionPresetBundle(params) {
|
|||||||
? [activeCascadeId]
|
? [activeCascadeId]
|
||||||
: [];
|
: [];
|
||||||
const familySet = new Set(rawFamilyIds.map((id) => String(id || '').toLowerCase()));
|
const familySet = new Set(rawFamilyIds.map((id) => String(id || '').toLowerCase()));
|
||||||
const precollectedEntries = collectUsageEntriesToAggregate(familySet);
|
const precollectedEntries = collectUsageEntriesToAggregate(familySet, endpoint);
|
||||||
const ranges = {};
|
const ranges = {};
|
||||||
let usageRevision = usageSnapshotRevisionSeq;
|
let usageRevision = usageSnapshotRevisionSeq;
|
||||||
|
|
||||||
|
|||||||
@@ -24,6 +24,9 @@ import { dirname, join } from 'node:path';
|
|||||||
import {
|
import {
|
||||||
BRIDGE_API_PATHS,
|
BRIDGE_API_PATHS,
|
||||||
CONTEXT_WINDOWS_GLOBAL_KEY,
|
CONTEXT_WINDOWS_GLOBAL_KEY,
|
||||||
|
LOCAL_ENDPOINT_ID,
|
||||||
|
WINDOW_BRIDGE_ENDPOINT_HEADER,
|
||||||
|
WINDOW_BRIDGE_ENDPOINT_KEY,
|
||||||
WINDOW_BRIDGE_KEY,
|
WINDOW_BRIDGE_KEY,
|
||||||
WINDOW_BRIDGE_ROUTE_KEY,
|
WINDOW_BRIDGE_ROUTE_KEY,
|
||||||
WINDOW_OVERLAY_KEY,
|
WINDOW_OVERLAY_KEY,
|
||||||
@@ -47,12 +50,22 @@ import {
|
|||||||
ensureDesktopLaunchEntriesConfigured,
|
ensureDesktopLaunchEntriesConfigured,
|
||||||
resolveDesktopHostExecutable,
|
resolveDesktopHostExecutable,
|
||||||
} from './desktop-launcher-config.mjs';
|
} 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';
|
import { callLsRpc, getContextModelCatalog } from './ls-rpc.mjs';
|
||||||
|
|
||||||
const windowBridgeRef = `window[${JSON.stringify(WINDOW_BRIDGE_KEY)}]`;
|
const windowBridgeRef = `window[${JSON.stringify(WINDOW_BRIDGE_KEY)}]`;
|
||||||
const windowOverlayRef = `window[${JSON.stringify(WINDOW_OVERLAY_KEY)}]`;
|
const windowOverlayRef = `window[${JSON.stringify(WINDOW_OVERLAY_KEY)}]`;
|
||||||
const windowContextWindowsRef = `window[${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}]`;
|
const windowContextWindowsRef = `window[${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}]`;
|
||||||
const windowBridgeRouteKey = JSON.stringify(WINDOW_BRIDGE_ROUTE_KEY);
|
const windowBridgeRouteKey = JSON.stringify(WINDOW_BRIDGE_ROUTE_KEY);
|
||||||
|
const windowBridgeEndpointKey = JSON.stringify(WINDOW_BRIDGE_ENDPOINT_KEY);
|
||||||
const overlayMethods = Object.fromEntries(
|
const overlayMethods = Object.fromEntries(
|
||||||
Object.entries(WINDOW_OVERLAY_METHODS).map(([method, key]) => [method, JSON.stringify(key)])
|
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` 源。
|
* 校验桥接请求的 `Origin` 是否来自本机 Antigravity 2.0 HTTPS 回环源或 Antigravity IDE `vscode-file` 源。
|
||||||
*
|
*
|
||||||
@@ -792,6 +1089,8 @@ export function createWindowBridgeController(options) {
|
|||||||
allowDesktopLauncherInTest = false,
|
allowDesktopLauncherInTest = false,
|
||||||
existsHostFn = existsSync,
|
existsHostFn = existsSync,
|
||||||
WebSocketImpl = globalThis.WebSocket,
|
WebSocketImpl = globalThis.WebSocket,
|
||||||
|
bindRemoteRpcInvoker = false,
|
||||||
|
getLocalHubPortsFn = getLocalHubPorts,
|
||||||
} = options || {};
|
} = options || {};
|
||||||
|
|
||||||
function isPidAlive(pid) {
|
function isPidAlive(pid) {
|
||||||
@@ -849,7 +1148,8 @@ export function createWindowBridgeController(options) {
|
|||||||
};
|
};
|
||||||
let hadContextWindows = false;
|
let hadContextWindows = false;
|
||||||
let contextWindowBootId = `${process.pid}:${Date.now()}`;
|
let contextWindowBootId = `${process.pid}:${Date.now()}`;
|
||||||
let cachedBackendCtxModels = { expiresAt: 0, models: [] };
|
const cachedBackendCtxModelsByEndpoint = new Map();
|
||||||
|
const targetClassifyCache = new Map();
|
||||||
let nodeDepsPromise = null;
|
let nodeDepsPromise = null;
|
||||||
const allowedDynamicOrigins = new Set();
|
const allowedDynamicOrigins = new Set();
|
||||||
|
|
||||||
@@ -868,14 +1168,22 @@ export function createWindowBridgeController(options) {
|
|||||||
function applyCorsHeaders(res, origin) {
|
function applyCorsHeaders(res, origin) {
|
||||||
res.setHeader('Access-Control-Allow-Origin', origin);
|
res.setHeader('Access-Control-Allow-Origin', origin);
|
||||||
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
|
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-Allow-Private-Network', 'true');
|
||||||
res.setHeader('Access-Control-Max-Age', '600');
|
res.setHeader('Access-Control-Max-Age', '600');
|
||||||
res.setHeader('Vary', 'Origin');
|
res.setHeader('Vary', 'Origin');
|
||||||
res.setHeader('Cache-Control', 'no-store');
|
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 = [];
|
const responses = [];
|
||||||
for (const item of rpcBatch) {
|
for (const item of rpcBatch) {
|
||||||
const reqId = String(item?.id || '');
|
const reqId = String(item?.id || '');
|
||||||
@@ -893,7 +1201,12 @@ export function createWindowBridgeController(options) {
|
|||||||
: item.body && typeof item.body === 'object'
|
: item.body && typeof item.body === 'object'
|
||||||
? item.body
|
? 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 status = Number(out?.status || 200);
|
||||||
const parsedBody = out?.body ? JSON.parse(out.body) : {};
|
const parsedBody = out?.body ? JSON.parse(out.body) : {};
|
||||||
if (status >= 200 && status < 300) {
|
if (status >= 200 && status < 300) {
|
||||||
@@ -989,9 +1302,23 @@ export function createWindowBridgeController(options) {
|
|||||||
return;
|
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') {
|
if (method === 'GET') {
|
||||||
const queryData = Object.fromEntries(parsedUrl.searchParams.entries());
|
const queryData = Object.fromEntries(parsedUrl.searchParams.entries());
|
||||||
Promise.resolve(handleApiRequest(parsedUrl.pathname, 'GET', queryData))
|
Promise.resolve(invokeApiHandler(parsedUrl.pathname, 'GET', queryData, normalizedReqEndpoint))
|
||||||
.then((out) => {
|
.then((out) => {
|
||||||
const hdrs = {
|
const hdrs = {
|
||||||
'Content-Type': out.contentType || 'application/json',
|
'Content-Type': out.contentType || 'application/json',
|
||||||
@@ -1040,7 +1367,7 @@ export function createWindowBridgeController(options) {
|
|||||||
res.end(JSON.stringify({ error: 'Invalid JSON body' }));
|
res.end(JSON.stringify({ error: 'Invalid JSON body' }));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Promise.resolve(handleApiRequest(parsedUrl.pathname, 'POST', bodyObj))
|
Promise.resolve(invokeApiHandler(parsedUrl.pathname, 'POST', bodyObj, normalizedReqEndpoint))
|
||||||
.then((out) => {
|
.then((out) => {
|
||||||
const hdrs = {
|
const hdrs = {
|
||||||
'Content-Type': out.contentType || 'application/json',
|
'Content-Type': out.contentType || 'application/json',
|
||||||
@@ -1211,11 +1538,12 @@ export function createWindowBridgeController(options) {
|
|||||||
return { reachableCount, targets: merged };
|
return { reachableCount, targets: merged };
|
||||||
}
|
}
|
||||||
|
|
||||||
async function evaluateOnTarget(wsUrl, expression) {
|
async function evaluateOnTarget(wsUrl, expression, timeoutMsOverride = 0) {
|
||||||
const WS = WebSocketImpl || globalThis.WebSocket;
|
const WS = WebSocketImpl || globalThis.WebSocket;
|
||||||
if (typeof WS !== 'function') {
|
if (typeof WS !== 'function') {
|
||||||
throw new Error('WebSocket runtime unavailable');
|
throw new Error('WebSocket runtime unavailable');
|
||||||
}
|
}
|
||||||
|
const effectiveTimeoutMs = Math.max(500, Number(timeoutMsOverride) || cdpTimeoutMs);
|
||||||
let ws = null;
|
let ws = null;
|
||||||
let timer = null;
|
let timer = null;
|
||||||
try {
|
try {
|
||||||
@@ -1223,7 +1551,7 @@ export function createWindowBridgeController(options) {
|
|||||||
const evalResult = await new Promise((resolve, reject) => {
|
const evalResult = await new Promise((resolve, reject) => {
|
||||||
timer = setTimeout(() => {
|
timer = setTimeout(() => {
|
||||||
reject(new Error('CDP Runtime.evaluate timeout'));
|
reject(new Error('CDP Runtime.evaluate timeout'));
|
||||||
}, cdpTimeoutMs);
|
}, effectiveTimeoutMs);
|
||||||
|
|
||||||
const onOpen = () => {
|
const onOpen = () => {
|
||||||
try {
|
try {
|
||||||
@@ -1423,6 +1751,7 @@ export function createWindowBridgeController(options) {
|
|||||||
|
|
||||||
const cdpPorts = findActiveDevToolsPorts();
|
const cdpPorts = findActiveDevToolsPorts();
|
||||||
if (!cdpPorts.length) {
|
if (!cdpPorts.length) {
|
||||||
|
pruneStaleRemoteEndpoints(new Set());
|
||||||
const provPending = shouldCheckLaunchers
|
const provPending = shouldCheckLaunchers
|
||||||
? provisionHostLaunchersOnce({ fastCheckIfActive: !isInitialLauncherPass })
|
? provisionHostLaunchersOnce({ fastCheckIfActive: !isInitialLauncherPass })
|
||||||
: hostLauncherPromise;
|
: hostLauncherPromise;
|
||||||
@@ -1440,6 +1769,7 @@ export function createWindowBridgeController(options) {
|
|||||||
|
|
||||||
const { reachableCount, targets } = await collectAllMainWindowTargets(cdpPorts);
|
const { reachableCount, targets } = await collectAllMainWindowTargets(cdpPorts);
|
||||||
if (reachableCount === 0) {
|
if (reachableCount === 0) {
|
||||||
|
pruneStaleRemoteEndpoints(new Set());
|
||||||
const provPending = shouldCheckLaunchers
|
const provPending = shouldCheckLaunchers
|
||||||
? provisionHostLaunchersOnce({ fastCheckIfActive: !isInitialLauncherPass })
|
? provisionHostLaunchersOnce({ fastCheckIfActive: !isInitialLauncherPass })
|
||||||
: hostLauncherPromise;
|
: hostLauncherPromise;
|
||||||
@@ -1460,6 +1790,7 @@ export function createWindowBridgeController(options) {
|
|||||||
void provisionHostLaunchersOnce({ fastCheckIfActive: true }).catch(() => {});
|
void provisionHostLaunchersOnce({ fastCheckIfActive: true }).catch(() => {});
|
||||||
}
|
}
|
||||||
if (!targets.length) {
|
if (!targets.length) {
|
||||||
|
pruneStaleRemoteEndpoints(new Set());
|
||||||
updateBridgeStatus(enabled ? 'no_targets' : 'disabled', {
|
updateBridgeStatus(enabled ? 'no_targets' : 'disabled', {
|
||||||
enabled,
|
enabled,
|
||||||
leasedBySelf,
|
leasedBySelf,
|
||||||
@@ -1469,44 +1800,250 @@ export function createWindowBridgeController(options) {
|
|||||||
return { ok: true, enabled, reason: 'no_targets', injected: 0 };
|
return { ok: true, enabled, reason: 'no_targets', injected: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
if (hasContextWindows || hadContextWindows) {
|
if (
|
||||||
let fallbackRules = {};
|
!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 (
|
if (
|
||||||
hasContextWindows &&
|
!firstPass.isRemote &&
|
||||||
lsRuntimeEndpoint.baseUrl &&
|
firstPass.originPort > 0 &&
|
||||||
lsRuntimeEndpoint.addr !== 'test.invalid'
|
(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 {
|
try {
|
||||||
const [stRes, cat] = await Promise.all([
|
const [stRes, cat] = await Promise.all([
|
||||||
callLsRpc('GetUserStatus', {}, 1500),
|
callLsRpc('GetUserStatus', {}, 2000, epObj),
|
||||||
getContextModelCatalog(),
|
getContextModelCatalog(epObj),
|
||||||
]);
|
]);
|
||||||
const cfgs = stRes?.userStatus?.cascadeModelConfigData?.clientModelConfigs;
|
const cfgs = stRes?.userStatus?.cascadeModelConfigData?.clientModelConfigs;
|
||||||
if (Array.isArray(cfgs)) {
|
if (Array.isArray(cfgs)) {
|
||||||
cachedBackendCtxModels = {
|
cached = {
|
||||||
expiresAt: Date.now() + 10_000,
|
expiresAt: Date.now() + 10_000,
|
||||||
|
verified: true,
|
||||||
models: getContextWindowModels(cfgs, cat),
|
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 {
|
} catch {
|
||||||
// 忽略瞬态 LS 查询失败,保留上次缓存或交由窗口端解析
|
// 忽略瞬态 LS 查询失败,保留上次缓存或交由调用方回退
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (cachedBackendCtxModels.models.length > 0) {
|
if (cached.verified) {
|
||||||
fallbackRules = resolveContextWindowRules(cachedBackendCtxModels.models, contextWindows);
|
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 = [
|
await Promise.allSettled(
|
||||||
...targets.filter((target) => !target.isIdeWorkbench).map((target) => target.webSocketDebuggerUrl),
|
Array.from(uniqueRemoteIds).map(async (epId) => {
|
||||||
...collectAllChatDebuggerUrls(targets),
|
const res = await resolveFallbackRulesForEndpoint(epId);
|
||||||
];
|
// 仅在远端未能验证模型目录时安全回退本机规则;远端已验证但返回空规则时绝不套用本机高配规则
|
||||||
const expression = createContextWindowSyncExpression(
|
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,
|
contextWindows,
|
||||||
contextWindowBootId,
|
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;
|
hadContextWindows = hasContextWindows;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1533,6 +2070,7 @@ export function createWindowBridgeController(options) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!enabled) {
|
if (!enabled) {
|
||||||
|
pruneStaleRemoteEndpoints(activeRemoteWsUrls);
|
||||||
if (!hadInjectedTargets && !hadInjectedChatFrames && !forceReinject) {
|
if (!hadInjectedTargets && !hadInjectedChatFrames && !forceReinject) {
|
||||||
updateBridgeStatus('disabled', {
|
updateBridgeStatus('disabled', {
|
||||||
enabled: false,
|
enabled: false,
|
||||||
@@ -1602,12 +2140,14 @@ export function createWindowBridgeController(options) {
|
|||||||
bridgePort: Number(br?.port || 0),
|
bridgePort: Number(br?.port || 0),
|
||||||
hasToken: Boolean(br?.token),
|
hasToken: Boolean(br?.token),
|
||||||
transportMode: String(br?.transportMode || 'http'),
|
transportMode: String(br?.transportMode || 'http'),
|
||||||
|
endpointId: String(br?.[${windowBridgeEndpointKey}] || ${JSON.stringify(LOCAL_ENDPOINT_ID)}),
|
||||||
|
endpointLabel: String(br?.endpointLabel || ''),
|
||||||
hostRouteCascadeId: String(br?.[${windowBridgeRouteKey}] || ''),
|
hostRouteCascadeId: String(br?.[${windowBridgeRouteKey}] || ''),
|
||||||
routeCascadeId,
|
routeCascadeId,
|
||||||
rpcBatch,
|
rpcBatch,
|
||||||
};
|
};
|
||||||
} catch {
|
} 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 };
|
if (!wsUrl) return { alive: false, dockKind: '', visible: false };
|
||||||
let probedRouteId = '';
|
let probedRouteId = '';
|
||||||
const ideRouteId = String(ideRouteOverride || targetObj.ideRouteCascadeId || '').trim();
|
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) {
|
if (!forceReinject) {
|
||||||
const probeRes = await evaluateOnTarget(wsUrl, probeExpr);
|
const probeRes = await evaluateOnTarget(wsUrl, probeExpr);
|
||||||
const snap = probeRes?.result?.result?.value;
|
const snap = probeRes?.result?.result?.value;
|
||||||
@@ -1639,8 +2183,21 @@ export function createWindowBridgeController(options) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
if (snap.bundleVersion === bundleVersion) {
|
if (snap.bundleVersion === bundleVersion) {
|
||||||
if (snap.bridgePort !== port || snap.hasToken !== true) {
|
const snapEndpointId = String(snap.endpointId || LOCAL_ENDPOINT_ID);
|
||||||
const rebindExpr = `${windowOverlayRef}?.[${overlayMethods.updateBridge}]?.(${JSON.stringify({ port, token })})`;
|
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);
|
await evaluateOnTarget(wsUrl, rebindExpr);
|
||||||
}
|
}
|
||||||
let effectiveDockKind = String(snap.dockKind || '');
|
let effectiveDockKind = String(snap.dockKind || '');
|
||||||
@@ -1678,7 +2235,7 @@ export function createWindowBridgeController(options) {
|
|||||||
}
|
}
|
||||||
if (Array.isArray(snap.rpcBatch) && snap.rpcBatch.length > 0) {
|
if (Array.isArray(snap.rpcBatch) && snap.rpcBatch.length > 0) {
|
||||||
sawCdpTransport = true;
|
sawCdpTransport = true;
|
||||||
const rpcResults = await executeRpcBatch(snap.rpcBatch);
|
const rpcResults = await executeRpcBatch(snap.rpcBatch, targetEndpointId);
|
||||||
relayedRpcCount += rpcResults.length;
|
relayedRpcCount += rpcResults.length;
|
||||||
const deliverExpr = `${windowOverlayRef}?.[${overlayMethods.deliverRpc}]?.(${JSON.stringify(rpcResults)})`;
|
const deliverExpr = `${windowOverlayRef}?.[${overlayMethods.deliverRpc}]?.(${JSON.stringify(rpcResults)})`;
|
||||||
await evaluateOnTarget(wsUrl, deliverExpr);
|
await evaluateOnTarget(wsUrl, deliverExpr);
|
||||||
@@ -1704,12 +2261,17 @@ export function createWindowBridgeController(options) {
|
|||||||
try {
|
try {
|
||||||
const routeMatch = String(targetObj.url || '').match(/\/c\/([a-f0-9-]{36})(?:[/?#]|$)/i);
|
const routeMatch = String(targetObj.url || '').match(/\/c\/([a-f0-9-]{36})(?:[/?#]|$)/i);
|
||||||
const targetConvId = routeMatch ? routeMatch[1] : ideRouteId || probedRouteId;
|
const targetConvId = routeMatch ? routeMatch[1] : ideRouteId || probedRouteId;
|
||||||
const initOut = await handleApiRequest('/api/telemetry', 'GET', {
|
const initOut = await invokeApiHandler(
|
||||||
conversationId: targetConvId,
|
'/api/telemetry',
|
||||||
range: 'today',
|
'GET',
|
||||||
stepDetails: 'display',
|
{
|
||||||
stepRevision: '',
|
conversationId: targetConvId,
|
||||||
});
|
range: 'today',
|
||||||
|
stepDetails: 'display',
|
||||||
|
stepRevision: '',
|
||||||
|
},
|
||||||
|
targetEndpointId
|
||||||
|
);
|
||||||
if (Number(initOut?.status || 200) === 200 && initOut?.body) {
|
if (Number(initOut?.status || 200) === 200 && initOut?.body) {
|
||||||
initialTelemetry = JSON.parse(initOut.body);
|
initialTelemetry = JSON.parse(initOut.body);
|
||||||
}
|
}
|
||||||
@@ -1723,6 +2285,9 @@ export function createWindowBridgeController(options) {
|
|||||||
bundleVersion,
|
bundleVersion,
|
||||||
platform: String(platform || ''),
|
platform: String(platform || ''),
|
||||||
mountMode,
|
mountMode,
|
||||||
|
[WINDOW_BRIDGE_ENDPOINT_KEY]: targetEndpointId,
|
||||||
|
isRemoteEndpoint: targetIsRemote,
|
||||||
|
endpointLabel: targetEndpointLabel,
|
||||||
[WINDOW_BRIDGE_ROUTE_KEY]: ideRouteId || '',
|
[WINDOW_BRIDGE_ROUTE_KEY]: ideRouteId || '',
|
||||||
isIdeChatFrame: Boolean(isIdeChatFrame),
|
isIdeChatFrame: Boolean(isIdeChatFrame),
|
||||||
stylesCss: cachedAssets.stylesCss,
|
stylesCss: cachedAssets.stylesCss,
|
||||||
@@ -1805,6 +2370,7 @@ export function createWindowBridgeController(options) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pruneStaleRemoteEndpoints(activeRemoteWsUrls);
|
||||||
cdpFallbackActive = sawCdpTransport;
|
cdpFallbackActive = sawCdpTransport;
|
||||||
updateBridgeStatus(aliveCount > 0 ? 'active' : 'no_targets', {
|
updateBridgeStatus(aliveCount > 0 ? 'active' : 'no_targets', {
|
||||||
enabled: true,
|
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 = {}) {
|
function syncAllWindows(opts = {}) {
|
||||||
if (syncInFlight) {
|
if (syncInFlight) {
|
||||||
return syncInFlight.then(() => runSyncInternal(opts));
|
return syncInFlight.then(() => runSyncInternal(opts));
|
||||||
@@ -1853,6 +2454,9 @@ export function createWindowBridgeController(options) {
|
|||||||
function start() {
|
function start() {
|
||||||
stopped = false;
|
stopped = false;
|
||||||
contextWindowBootId = `${process.pid}:${Date.now()}`;
|
contextWindowBootId = `${process.pid}:${Date.now()}`;
|
||||||
|
if (bindRemoteRpcInvoker) {
|
||||||
|
setRemoteWindowRpcInvoker(invokeRemoteWindowRpc);
|
||||||
|
}
|
||||||
if (initialTimer) clearTimeout(initialTimer);
|
if (initialTimer) clearTimeout(initialTimer);
|
||||||
if (pollTimer) clearTimeout(pollTimer);
|
if (pollTimer) clearTimeout(pollTimer);
|
||||||
|
|
||||||
@@ -1923,6 +2527,9 @@ export function createWindowBridgeController(options) {
|
|||||||
hadInjectedTargets = false;
|
hadInjectedTargets = false;
|
||||||
hadInjectedChatFrames = false;
|
hadInjectedChatFrames = false;
|
||||||
hadContextWindows = false;
|
hadContextWindows = false;
|
||||||
|
if (bindRemoteRpcInvoker) {
|
||||||
|
setRemoteWindowRpcInvoker(null);
|
||||||
|
}
|
||||||
if (server) {
|
if (server) {
|
||||||
const srv = server;
|
const srv = server;
|
||||||
server = null;
|
server = null;
|
||||||
@@ -1985,6 +2592,7 @@ export function createWindowBridgeController(options) {
|
|||||||
return {
|
return {
|
||||||
ensureBridgeServer,
|
ensureBridgeServer,
|
||||||
syncAllWindows,
|
syncAllWindows,
|
||||||
|
invokeRemoteWindowRpc,
|
||||||
notifySettingChanged,
|
notifySettingChanged,
|
||||||
notifyContextWindowsChanged,
|
notifyContextWindowsChanged,
|
||||||
start,
|
start,
|
||||||
@@ -2026,6 +2634,7 @@ export function startDefaultWindowBridge(options) {
|
|||||||
if (!defaultBridgeController) {
|
if (!defaultBridgeController) {
|
||||||
defaultBridgeController = createWindowBridgeController({
|
defaultBridgeController = createWindowBridgeController({
|
||||||
leaseFilePath: join(DATA_DIR, 'window-bridge-lease.json'),
|
leaseFilePath: join(DATA_DIR, 'window-bridge-lease.json'),
|
||||||
|
bindRemoteRpcInvoker: true,
|
||||||
...options,
|
...options,
|
||||||
});
|
});
|
||||||
defaultBridgeController.start();
|
defaultBridgeController.start();
|
||||||
|
|||||||
@@ -4,11 +4,11 @@
|
|||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>用量监控</title>
|
<title>用量监控</title>
|
||||||
<link rel="stylesheet" href="/styles.css?v=1795098443766">
|
<link rel="stylesheet" href="/styles.css?v=1795146059865">
|
||||||
<script src="/preload.js"></script>
|
<script src="/preload.js"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app-root"></div>
|
<div id="app-root"></div>
|
||||||
<script src="/app.js?v=1795098443766"></script>
|
<script src="/app.js?v=1795146059865"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
export const WINDOW_BRIDGE_KEY = '__AGUsageMonitorBridge';
|
export const WINDOW_BRIDGE_KEY = '__AGUsageMonitorBridge';
|
||||||
export const WINDOW_BRIDGE_ROUTE_KEY = 'hostRouteCascadeId';
|
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 WINDOW_OVERLAY_KEY = '__AGUsageMonitorOverlay';
|
||||||
export const CONTEXT_WINDOWS_GLOBAL_KEY = '__AGUsageMonitorContextWindows';
|
export const CONTEXT_WINDOWS_GLOBAL_KEY = '__AGUsageMonitorContextWindows';
|
||||||
|
|
||||||
|
|||||||
@@ -76,6 +76,12 @@ export const TopSessionHeader = defineComponent({
|
|||||||
[updateBtnIcon, updateBtnText]
|
[updateBtnIcon, updateBtnText]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const sshBadge = h('span', {
|
||||||
|
className: 'endpoint-ssh-badge',
|
||||||
|
hidden: true,
|
||||||
|
text: 'SSH',
|
||||||
|
});
|
||||||
|
|
||||||
const statusIcon = createSvgIcon('pulse', { size: 12 });
|
const statusIcon = createSvgIcon('pulse', { size: 12 });
|
||||||
const statusText = h('span', { text: t('header.statusLive') });
|
const statusText = h('span', { text: t('header.statusLive') });
|
||||||
const statusTag = h('span', { className: 'status-tag' }, [statusIcon, statusText]);
|
const statusTag = h('span', { className: 'status-tag' }, [statusIcon, statusText]);
|
||||||
@@ -93,7 +99,7 @@ export const TopSessionHeader = defineComponent({
|
|||||||
|
|
||||||
const headerRowEl = h('div', { className: 'session-header' }, [
|
const headerRowEl = h('div', { className: 'session-header' }, [
|
||||||
h('div', { className: 'session-left' }, [convSelect.el]),
|
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]);
|
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(updateBtn, 'aria-label', t('header.ariaUpdate'));
|
||||||
patchAttr(refreshBtn, 'aria-label', t('header.ariaRefresh'));
|
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 actConv = telemetry?.activeConversation;
|
||||||
const convs = telemetry?.conversations || [];
|
const convs = telemetry?.conversations || [];
|
||||||
const hostRouteId = telSt.hostRouteConversationId || '';
|
const hostRouteId = telSt.hostRouteConversationId || '';
|
||||||
|
|||||||
@@ -9,6 +9,8 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import {
|
import {
|
||||||
|
LOCAL_ENDPOINT_ID,
|
||||||
|
WINDOW_BRIDGE_ENDPOINT_KEY,
|
||||||
WINDOW_BRIDGE_KEY,
|
WINDOW_BRIDGE_KEY,
|
||||||
WINDOW_OVERLAY_KEY,
|
WINDOW_OVERLAY_KEY,
|
||||||
WINDOW_OVERLAY_METHODS,
|
WINDOW_OVERLAY_METHODS,
|
||||||
@@ -51,6 +53,7 @@ import {
|
|||||||
normalizeClientTopbarSlots,
|
normalizeClientTopbarSlots,
|
||||||
normalizeClientUpdateMode,
|
normalizeClientUpdateMode,
|
||||||
normalizeClientWindowMountMode,
|
normalizeClientWindowMountMode,
|
||||||
|
resetTelemetryForEndpointSwitch,
|
||||||
resolveScopedConversation,
|
resolveScopedConversation,
|
||||||
selectConversation,
|
selectConversation,
|
||||||
startAsyncTelemetryLoop,
|
startAsyncTelemetryLoop,
|
||||||
@@ -958,10 +961,18 @@ export function mountWindowOverlay() {
|
|||||||
const bridgeConfig = getWindowBridgeConfig();
|
const bridgeConfig = getWindowBridgeConfig();
|
||||||
const bundleVersion = String(bridgeConfig?.bundleVersion || '');
|
const bundleVersion = String(bridgeConfig?.bundleVersion || '');
|
||||||
const stylesCss = String(bridgeConfig?.stylesCss || '');
|
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 =
|
const seedTelemetry =
|
||||||
(bridgeConfig?.initialTelemetry && typeof bridgeConfig.initialTelemetry === 'object'
|
(bridgeConfig?.initialTelemetry && typeof bridgeConfig.initialTelemetry === 'object'
|
||||||
? bridgeConfig.initialTelemetry
|
? bridgeConfig.initialTelemetry
|
||||||
: null) || carryOverTelemetry;
|
: null) || reusableCarryOver;
|
||||||
if (bridgeConfig?.initialTelemetry) {
|
if (bridgeConfig?.initialTelemetry) {
|
||||||
delete bridgeConfig.initialTelemetry;
|
delete bridgeConfig.initialTelemetry;
|
||||||
}
|
}
|
||||||
@@ -2741,14 +2752,49 @@ export function mountWindowOverlay() {
|
|||||||
const token = String(nextBridge.token || '');
|
const token = String(nextBridge.token || '');
|
||||||
if (!Number.isInteger(port) || port <= 0 || !token) return false;
|
if (!Number.isInteger(port) || port <= 0 || !token) return false;
|
||||||
const cur = readInjectedWindowBridge() || {};
|
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 portChanged = Number(cur.port || 0) !== port || String(cur.token || '') !== token;
|
||||||
|
const endpointChanged = prevEndpointId !== nextEndpointId;
|
||||||
cur.port = port;
|
cur.port = port;
|
||||||
cur.token = token;
|
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';
|
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;
|
window[WINDOW_BRIDGE_KEY] = cur;
|
||||||
void fetchTelemetry({ force: false });
|
if (endpointChanged) {
|
||||||
|
resetTelemetryForEndpointSwitch();
|
||||||
|
void fetchTelemetry({ force: true });
|
||||||
|
} else {
|
||||||
|
void fetchTelemetry({ force: false });
|
||||||
|
}
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
getTelemetrySnapshot() {
|
getTelemetrySnapshot() {
|
||||||
|
|||||||
@@ -4,7 +4,12 @@
|
|||||||
* (Sidecar Webview `window.sidecar.fetch` + Main Window Loopback Bridge).
|
* (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 inFlightGets = new Map();
|
||||||
const activeControllers = 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 } = {}) {
|
export async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTimeoutMs = 3500 } = {}) {
|
||||||
const upperMethod = method.toUpperCase();
|
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)) {
|
if (dedupKey && inFlightGets.has(dedupKey)) {
|
||||||
return inFlightGets.get(dedupKey);
|
return inFlightGets.get(dedupKey);
|
||||||
@@ -148,7 +156,20 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
|
|||||||
signal = requestController.signal;
|
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) => {
|
const execHttpOnce = async (activeBridge) => {
|
||||||
|
ensureEndpointUnchanged(activeBridge);
|
||||||
const sidecar = typeof window !== 'undefined' ? window.sidecar : null;
|
const sidecar = typeof window !== 'undefined' ? window.sidecar : null;
|
||||||
const fetchFn = sidecar?.fetch
|
const fetchFn = sidecar?.fetch
|
||||||
? sidecar.fetch.bind(sidecar)
|
? sidecar.fetch.bind(sidecar)
|
||||||
@@ -162,6 +183,10 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
|
|||||||
}
|
}
|
||||||
if (activeBridge) {
|
if (activeBridge) {
|
||||||
headers['X-Usage-Monitor-Token'] = activeBridge.token;
|
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, {
|
const res = await fetchFn(requestUrl, {
|
||||||
method: upperMethod,
|
method: upperMethod,
|
||||||
@@ -181,7 +206,10 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
|
|||||||
throw abortErr;
|
throw abortErr;
|
||||||
}
|
}
|
||||||
if (!res.ok) {
|
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) {
|
if (activeBridge) {
|
||||||
activeBridge.transportMode = 'http';
|
activeBridge.transportMode = 'http';
|
||||||
@@ -202,8 +230,10 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
|
|||||||
if (signal?.aborted || cdpErr?.name === 'AbortError') {
|
if (signal?.aborted || cdpErr?.name === 'AbortError') {
|
||||||
throw cdpErr;
|
throw cdpErr;
|
||||||
}
|
}
|
||||||
// 热更新或守护重启期间若 CDP 尚未轮询投递,自动重置回 HTTP 并用最新桥接端口重试一次
|
// 热更新或守护重启期间若 CDP 尚未轮询投递,自动重置回 HTTP 并用最新桥接端口重试一次;
|
||||||
|
// 但若端点已切换(例如本地 <-> SSH),绝不将旧端点请求重放至新端点
|
||||||
const latestBridge = getWindowBridgeConfig() || initialBridge;
|
const latestBridge = getWindowBridgeConfig() || initialBridge;
|
||||||
|
ensureEndpointUnchanged(latestBridge);
|
||||||
latestBridge.transportMode = 'http';
|
latestBridge.transportMode = 'http';
|
||||||
return execHttpOnce(latestBridge);
|
return execHttpOnce(latestBridge);
|
||||||
}
|
}
|
||||||
@@ -232,7 +262,11 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
|
|||||||
}
|
}
|
||||||
throw fetchErr;
|
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);
|
return fallbackViaCdpWithRecovery(bridge);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -53,7 +53,12 @@ import {
|
|||||||
normalizeWindowMountMode,
|
normalizeWindowMountMode,
|
||||||
parseStepTokenComboSegments,
|
parseStepTokenComboSegments,
|
||||||
} from '../../shared/settings-normalization.mjs';
|
} 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;
|
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 latestRequestSeq = 0;
|
||||||
let latestConsumptionReqSeq = 0;
|
let latestConsumptionReqSeq = 0;
|
||||||
let latestConversationSwitchSeq = 0;
|
let latestConversationSwitchSeq = 0;
|
||||||
|
let endpointSwitchEpoch = 0;
|
||||||
let activeForceCount = 0;
|
let activeForceCount = 0;
|
||||||
let consecutivePollFailures = 0;
|
let consecutivePollFailures = 0;
|
||||||
let inFlightTelemetryPoll = null;
|
let inFlightTelemetryPoll = null;
|
||||||
@@ -201,10 +207,11 @@ export function clearConversationViewCache() {
|
|||||||
|
|
||||||
function buildConsumptionScopeSig(payload) {
|
function buildConsumptionScopeSig(payload) {
|
||||||
if (!payload || typeof payload !== 'object') return '';
|
if (!payload || typeof payload !== 'object') return '';
|
||||||
|
const ep = payload.endpoint || {};
|
||||||
const acct = payload.account || {};
|
const acct = payload.account || {};
|
||||||
const set = payload.settings || {};
|
const set = payload.settings || {};
|
||||||
const cloud = payload.cloudStatus || {};
|
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) {
|
function syncConsumptionCacheScope(payload) {
|
||||||
@@ -476,6 +483,13 @@ export function isEquivalentTelemetry(prev, next) {
|
|||||||
if ((pSet?.fontScale ?? 'md') !== (nSet?.fontScale ?? 'md')) return false;
|
if ((pSet?.fontScale ?? 'md') !== (nSet?.fontScale ?? 'md')) return false;
|
||||||
if (Boolean(pSet?.experimentalModernUi) !== Boolean(nSet?.experimentalModernUi)) return false;
|
if (Boolean(pSet?.experimentalModernUi) !== Boolean(nSet?.experimentalModernUi)) return false;
|
||||||
if ((prev.hostPlatform || '') !== (next.hostPlatform || '')) 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)) {
|
if (Boolean(pSet?.contextWindowRiskAccepted) !== Boolean(nSet?.contextWindowRiskAccepted)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -1014,6 +1028,33 @@ export function isEquivalentTelemetry(prev, next) {
|
|||||||
return true;
|
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 } = {}) {
|
export async function fetchTelemetry({ force = false } = {}) {
|
||||||
if (!force && activeForceCount > 0) {
|
if (!force && activeForceCount > 0) {
|
||||||
return telemetryStore.getState().telemetry;
|
return telemetryStore.getState().telemetry;
|
||||||
@@ -1049,11 +1090,17 @@ export async function fetchTelemetry({ force = false } = {}) {
|
|||||||
}
|
}
|
||||||
const query = params.toString();
|
const query = params.toString();
|
||||||
const bridge = overlay ? getWindowBridgeConfig() : null;
|
const bridge = overlay ? getWindowBridgeConfig() : null;
|
||||||
|
const endpointId = bridge?.[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID;
|
||||||
const existing = inFlightTelemetryPoll;
|
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;
|
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(() => {
|
poll.promise = requestTelemetry(params, false).finally(() => {
|
||||||
if (inFlightTelemetryPoll === poll) inFlightTelemetryPoll = null;
|
if (inFlightTelemetryPoll === poll) inFlightTelemetryPoll = null;
|
||||||
});
|
});
|
||||||
@@ -1240,6 +1287,7 @@ async function fetchConsumptionRangeSlice({
|
|||||||
customStartMs = 0,
|
customStartMs = 0,
|
||||||
customEndMs = 0,
|
customEndMs = 0,
|
||||||
} = {}) {
|
} = {}) {
|
||||||
|
const reqEpoch = endpointSwitchEpoch;
|
||||||
const reqSeq = ++latestConsumptionReqSeq;
|
const reqSeq = ++latestConsumptionReqSeq;
|
||||||
const targetRange = String(range || 'today');
|
const targetRange = String(range || 'today');
|
||||||
const current = telemetryStore.getState();
|
const current = telemetryStore.getState();
|
||||||
@@ -1258,7 +1306,7 @@ async function fetchConsumptionRangeSlice({
|
|||||||
method: 'GET',
|
method: 'GET',
|
||||||
abortKey: 'consumption-range',
|
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) {
|
if (payload.scope === 'consumption' && payload.consumption) {
|
||||||
const usageRev = Number(payload.usageRevision ?? payload.consumption.revision ?? 0);
|
const usageRev = Number(payload.usageRevision ?? payload.consumption.revision ?? 0);
|
||||||
@@ -1385,13 +1433,14 @@ export async function selectConversation(
|
|||||||
params.set('stepRevision', cachedSteps?.revision || '');
|
params.set('stepRevision', cachedSteps?.revision || '');
|
||||||
params.set('scope', 'conversation');
|
params.set('scope', 'conversation');
|
||||||
|
|
||||||
|
const reqEpoch = endpointSwitchEpoch;
|
||||||
const reqSettingsRev = settingsRevision;
|
const reqSettingsRev = settingsRevision;
|
||||||
try {
|
try {
|
||||||
const payload = await callSidecarApi(`/api/telemetry?${params}`, {
|
const payload = await callSidecarApi(`/api/telemetry?${params}`, {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
abortKey: 'conversation-switch',
|
abortKey: 'conversation-switch',
|
||||||
});
|
});
|
||||||
if (!payload || typeof payload !== 'object') return null;
|
if (!payload || typeof payload !== 'object' || reqEpoch !== endpointSwitchEpoch) return null;
|
||||||
if (switchSeq !== latestConversationSwitchSeq) return payload;
|
if (switchSeq !== latestConversationSwitchSeq) return payload;
|
||||||
|
|
||||||
const latestSt = telemetryStore.getState();
|
const latestSt = telemetryStore.getState();
|
||||||
@@ -1550,11 +1599,13 @@ export function prefetchConsumptionPresets() {
|
|||||||
if (effectiveConvId) params.set('conversationId', effectiveConvId);
|
if (effectiveConvId) params.set('conversationId', effectiveConvId);
|
||||||
params.set('scope', 'consumption-presets');
|
params.set('scope', 'consumption-presets');
|
||||||
|
|
||||||
|
const reqEpoch = endpointSwitchEpoch;
|
||||||
const task = callSidecarApi(`/api/telemetry?${params}`, {
|
const task = callSidecarApi(`/api/telemetry?${params}`, {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
abortKey: 'consumption-presets',
|
abortKey: 'consumption-presets',
|
||||||
})
|
})
|
||||||
.then((payload) => {
|
.then((payload) => {
|
||||||
|
if (reqEpoch !== endpointSwitchEpoch) return false;
|
||||||
if (payload?.scope === 'consumption-presets' && payload.ranges && typeof payload.ranges === 'object') {
|
if (payload?.scope === 'consumption-presets' && payload.ranges && typeof payload.ranges === 'object') {
|
||||||
const rev = Number(payload.usageRevision || currentRev || 0);
|
const rev = Number(payload.usageRevision || currentRev || 0);
|
||||||
for (const [rangeKey, entry] of Object.entries(payload.ranges)) {
|
for (const [rangeKey, entry] of Object.entries(payload.ranges)) {
|
||||||
|
|||||||
@@ -52,6 +52,23 @@
|
|||||||
flex-shrink: 0;
|
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 {
|
.status-tag {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
|||||||
@@ -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-running,
|
||||||
[data-modern-ui="true"] .status-tag.state-synced,
|
[data-modern-ui="true"] .status-tag.state-synced,
|
||||||
[data-modern-ui="true"] .status-tag.state-warn,
|
[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"] .update-badge-btn,
|
||||||
[data-modern-ui="true"] .wm-update-btn,
|
[data-modern-ui="true"] .wm-update-btn,
|
||||||
[data-modern-ui="true"] .wm-hover-update-bar,
|
[data-modern-ui="true"] .wm-hover-update-bar,
|
||||||
|
|||||||
@@ -442,6 +442,23 @@ html[data-standalone="true"] .app-shell {
|
|||||||
flex-shrink: 0;
|
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 {
|
.status-tag {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
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-running,
|
||||||
[data-modern-ui="true"] .status-tag.state-synced,
|
[data-modern-ui="true"] .status-tag.state-synced,
|
||||||
[data-modern-ui="true"] .status-tag.state-warn,
|
[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"] .update-badge-btn,
|
||||||
[data-modern-ui="true"] .wm-update-btn,
|
[data-modern-ui="true"] .wm-update-btn,
|
||||||
[data-modern-ui="true"] .wm-hover-update-bar,
|
[data-modern-ui="true"] .wm-hover-update-bar,
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import fs from 'node:fs';
|
|||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import { pathToFileURL } from 'node:url';
|
import { pathToFileURL } from 'node:url';
|
||||||
import vm from 'node:vm';
|
import vm from 'node:vm';
|
||||||
import { randomUUID } from 'node:crypto';
|
import { createHash, randomUUID } from 'node:crypto';
|
||||||
import { isDeepStrictEqual } from 'node:util';
|
import { isDeepStrictEqual } from 'node:util';
|
||||||
import * as metrics from '../trajectory-metrics.mjs';
|
import * as metrics from '../trajectory-metrics.mjs';
|
||||||
import { stripModuleSyntax } from '../scripts/build-bundle.mjs';
|
import { stripModuleSyntax } from '../scripts/build-bundle.mjs';
|
||||||
@@ -26,6 +26,7 @@ const BACKEND_MODULE_FILES = [
|
|||||||
'../backend/http-helpers.mjs',
|
'../backend/http-helpers.mjs',
|
||||||
'../backend/settings-schema.mjs',
|
'../backend/settings-schema.mjs',
|
||||||
'../backend/config.mjs',
|
'../backend/config.mjs',
|
||||||
|
'../backend/endpoint-registry.mjs',
|
||||||
'../backend/sqlite-client.mjs',
|
'../backend/sqlite-client.mjs',
|
||||||
'../backend/proto-wire.mjs',
|
'../backend/proto-wire.mjs',
|
||||||
'../backend/cli-sqlite-reader.mjs',
|
'../backend/cli-sqlite-reader.mjs',
|
||||||
@@ -85,7 +86,7 @@ export function backendHarness({
|
|||||||
const source = stripEsmSyntax(sourceText ?? loadCombinedBackendSource(), mainUrl);
|
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 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={
|
const ctx={
|
||||||
...metricsImplementation, URL, AbortSignal, Buffer, TextDecoder, ...timerApi, isDeepStrictEqual, randomUUID,
|
...metricsImplementation, URL, AbortSignal, Buffer, TextDecoder, ...timerApi, isDeepStrictEqual, createHash, randomUUID,
|
||||||
...(clock ? { Date: class extends Date {
|
...(clock ? { Date: class extends Date {
|
||||||
constructor(...args) { super(...(args.length ? args : [clock()])); }
|
constructor(...args) { super(...(args.length ? args : [clock()])); }
|
||||||
static now() { return clock(); }
|
static now() { return clock(); }
|
||||||
@@ -206,6 +207,6 @@ export function backendHarness({
|
|||||||
return {ok:true,json:async()=>data};
|
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};
|
return {...ctx.api,state};
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -3042,4 +3042,200 @@ export function isParkedOnSwarmWait(rawSteps = []) {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function parseSwarmToolArgs(rawToolCall) {
|
||||||
|
if (!rawToolCall || typeof rawToolCall !== 'object') return null;
|
||||||
|
const direct = rawToolCall.args || rawToolCall.arguments;
|
||||||
|
if (direct && typeof direct === 'object' && !Array.isArray(direct)) {
|
||||||
|
return direct;
|
||||||
|
}
|
||||||
|
const rawJson =
|
||||||
|
typeof rawToolCall.argumentsJson === 'string'
|
||||||
|
? rawToolCall.argumentsJson
|
||||||
|
: typeof direct === 'string'
|
||||||
|
? direct
|
||||||
|
: typeof rawToolCall.function?.arguments === 'string'
|
||||||
|
? rawToolCall.function.arguments
|
||||||
|
: '';
|
||||||
|
if (!rawJson.trim()) return null;
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(rawJson);
|
||||||
|
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeSwarmToolName(rawToolCall) {
|
||||||
|
return String(
|
||||||
|
rawToolCall?.name || rawToolCall?.toolName || rawToolCall?.function?.name || ''
|
||||||
|
)
|
||||||
|
.trim()
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/^default_api:/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSwarmStepCompletedSuccess(step) {
|
||||||
|
const st = typeof step?.status === 'string' ? step.status.trim().toUpperCase() : '';
|
||||||
|
if (st) {
|
||||||
|
if (!LIVE_TERMINAL_STATUSES.has(st)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (st.includes('ERROR') || st.includes('CANCEL') || st.includes('FAIL')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const tcSt =
|
||||||
|
typeof step?.metadata?.toolCall?.status === 'string'
|
||||||
|
? step.metadata.toolCall.status.trim().toUpperCase()
|
||||||
|
: '';
|
||||||
|
if (tcSt) {
|
||||||
|
if (
|
||||||
|
tcSt.includes('ERROR') ||
|
||||||
|
tcSt.includes('CANCEL') ||
|
||||||
|
tcSt.includes('FAIL') ||
|
||||||
|
/(?:WAIT|PEND|RUN|GENERAT|IN_PROGRESS|STREAM)/i.test(tcSt)
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractSwarmCallIntent(rawToolCall) {
|
||||||
|
const args = parseSwarmToolArgs(rawToolCall);
|
||||||
|
if (!args || typeof args.action !== 'string') return null;
|
||||||
|
const action = args.action.trim().toLowerCase();
|
||||||
|
if (action === 'title') {
|
||||||
|
if (typeof args.title !== 'string') return null;
|
||||||
|
const nextTitle = args.title.trim();
|
||||||
|
if (!nextTitle) return null;
|
||||||
|
return { action: 'title', value: nextTitle, sig: `title:${nextTitle}` };
|
||||||
|
}
|
||||||
|
if (action === 'kill') {
|
||||||
|
if (typeof args.name !== 'string') return null;
|
||||||
|
const member = args.name.trim().replace(/^@+/, '').toLowerCase();
|
||||||
|
if (!member) return null;
|
||||||
|
return { action: 'kill', value: member, sig: `kill:${member}` };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从原始轨迹 RPC 步骤中提取 Native Swarm 元数据(纯 RPC 解析,无需读取远端磁盘 `members.json`):
|
||||||
|
* - `title`:最后一次成功调用 `swarm(action: "title")` 设置的蜂群标题;
|
||||||
|
* - `killedMembers`:被 `swarm(action: "kill")` 终止的工蜂成员名(小写去 `@`)及其终止时间戳映射。
|
||||||
|
*
|
||||||
|
* @param {Array<object>} [rawSteps=[]]
|
||||||
|
* @returns {{ title?: string, killedMembers?: Record<string, number> } | null}
|
||||||
|
*/
|
||||||
|
export function extractSwarmMetaFromSteps(rawSteps = []) {
|
||||||
|
if (!Array.isArray(rawSteps) || rawSteps.length === 0) return null;
|
||||||
|
|
||||||
|
const executedToolCallIds = new Set();
|
||||||
|
for (const st of rawSteps) {
|
||||||
|
const tc = st?.metadata?.toolCall;
|
||||||
|
if (!tc || normalizeSwarmToolName(tc) !== 'swarm') continue;
|
||||||
|
const tcId = String(tc.id || tc.toolCallId || '').trim();
|
||||||
|
if (tcId) {
|
||||||
|
executedToolCallIds.add(tcId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let title = '';
|
||||||
|
const killedMap = new Map();
|
||||||
|
|
||||||
|
const applyIntent = (intent, stepMs) => {
|
||||||
|
if (!intent) return;
|
||||||
|
if (intent.action === 'title') {
|
||||||
|
title = intent.value;
|
||||||
|
} else if (intent.action === 'kill') {
|
||||||
|
const prevMs = killedMap.get(intent.value);
|
||||||
|
killedMap.set(intent.value, prevMs === undefined ? stepMs : Math.max(prevMs, stepMs));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
for (let i = 0; i < rawSteps.length; i++) {
|
||||||
|
const st = rawSteps[i];
|
||||||
|
if (!st || typeof st !== 'object') continue;
|
||||||
|
const stepMs =
|
||||||
|
parseIsoMs(st?.metadata?.completedAt || st?.metadata?.createdAt || st?.created_at) || 0;
|
||||||
|
|
||||||
|
const execTc = st?.metadata?.toolCall;
|
||||||
|
if (execTc && normalizeSwarmToolName(execTc) === 'swarm') {
|
||||||
|
if (isSwarmStepCompletedSuccess(st)) {
|
||||||
|
applyIntent(extractSwarmCallIntent(execTc), stepMs);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isSwarmStepCompletedSuccess(st)) continue;
|
||||||
|
const plannerCalls = getStepPlannerToolCalls(st);
|
||||||
|
if (plannerCalls.length === 0) continue;
|
||||||
|
|
||||||
|
// 收集同一轮次内无 toolCall.id 的执行步骤签名,防止失败或进行中的无 ID 执行步骤回落误触发 planner 提案
|
||||||
|
let turnIdlessExecCounts = null;
|
||||||
|
for (const tc of plannerCalls) {
|
||||||
|
if (normalizeSwarmToolName(tc) !== 'swarm') continue;
|
||||||
|
const tcId = String(tc?.id || tc?.toolCallId || '').trim();
|
||||||
|
if (tcId && executedToolCallIds.has(tcId)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const intent = extractSwarmCallIntent(tc);
|
||||||
|
if (!intent) continue;
|
||||||
|
if (!tcId) {
|
||||||
|
if (!turnIdlessExecCounts) {
|
||||||
|
turnIdlessExecCounts = new Map();
|
||||||
|
for (let j = i + 1; j < rawSteps.length; j++) {
|
||||||
|
const nextSt = rawSteps[j];
|
||||||
|
if (!nextSt || typeof nextSt !== 'object') continue;
|
||||||
|
const nt = String(nextSt.type || '').trim().toUpperCase();
|
||||||
|
if (
|
||||||
|
isPlannerStep(nextSt) ||
|
||||||
|
nt.includes('USER_INPUT') ||
|
||||||
|
nt.includes('SYSTEM_MESSAGE') ||
|
||||||
|
isCheckpointStep(nextSt)
|
||||||
|
) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const nextExecTc = nextSt?.metadata?.toolCall;
|
||||||
|
if (!nextExecTc || normalizeSwarmToolName(nextExecTc) !== 'swarm') continue;
|
||||||
|
const nextExecId = String(nextExecTc.id || nextExecTc.toolCallId || '').trim();
|
||||||
|
if (nextExecId) continue;
|
||||||
|
const nextIntent = extractSwarmCallIntent(nextExecTc);
|
||||||
|
if (!nextIntent) continue;
|
||||||
|
turnIdlessExecCounts.set(
|
||||||
|
nextIntent.sig,
|
||||||
|
(turnIdlessExecCounts.get(nextIntent.sig) || 0) + 1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const matchedCount = turnIdlessExecCounts.get(intent.sig) || 0;
|
||||||
|
if (matchedCount > 0) {
|
||||||
|
turnIdlessExecCounts.set(intent.sig, matchedCount - 1);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
applyIntent(intent, stepMs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!title && killedMap.size === 0) return null;
|
||||||
|
let killedMembers = null;
|
||||||
|
if (killedMap.size > 0) {
|
||||||
|
killedMembers = {};
|
||||||
|
for (const [member, killMs] of killedMap.entries()) {
|
||||||
|
Object.defineProperty(killedMembers, member, {
|
||||||
|
value: killMs,
|
||||||
|
enumerable: true,
|
||||||
|
writable: true,
|
||||||
|
configurable: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...(title ? { title } : {}),
|
||||||
|
...(killedMembers ? { killedMembers } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user