mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
feat(panel): support SSH remote windows with per-endpoint isolation and context window overrides
- Add per-endpoint registry and isolated caches (endpoint-registry.mjs, multi-path trajectory-cache-file.mjs) so local and SSH remote windows maintain independent conversations, telemetry, quotas, and consumption analytics (Antigravity SSH) without remote plugin installation - Classify local vs. SSH Desktop targets via two-pass hub port and metadata probing in window-bridge.mjs and ls-discovery.mjs, routing HTTP/CDP requests with authoritative X-Usage-Monitor-Endpoint headers and preventing local data leaks or 503-triggered CDP downgrades - Implement two-tier read-only remote LS RPC transport in ls-rpc.mjs (loopback HTTP/HTTPS with size/wall-clock limits and 60s circuit breaker falling back to stateless same-origin window.fetch / connect-websocket via CDP) - Enable per-endpoint verified context window overrides in SSH Desktop windows (context-windows.mjs, window-bridge.mjs, api-actions.mjs) without double-wrapping window.fetch - Surface an SSH badge in TopSessionHeader, cleanly flush stale requests/queues on endpoint rebind, rebuild app.js/styles.css, and add 13 unit/E2E tests in test/ssh-remote-endpoints.test.mjs (157/157 passing)
This commit is contained in:
@@ -76,6 +76,12 @@ export const TopSessionHeader = defineComponent({
|
||||
[updateBtnIcon, updateBtnText]
|
||||
);
|
||||
|
||||
const sshBadge = h('span', {
|
||||
className: 'endpoint-ssh-badge',
|
||||
hidden: true,
|
||||
text: 'SSH',
|
||||
});
|
||||
|
||||
const statusIcon = createSvgIcon('pulse', { size: 12 });
|
||||
const statusText = h('span', { text: t('header.statusLive') });
|
||||
const statusTag = h('span', { className: 'status-tag' }, [statusIcon, statusText]);
|
||||
@@ -93,7 +99,7 @@ export const TopSessionHeader = defineComponent({
|
||||
|
||||
const headerRowEl = h('div', { className: 'session-header' }, [
|
||||
h('div', { className: 'session-left' }, [convSelect.el]),
|
||||
h('div', { className: 'session-right' }, [updateBtn, statusTag, refreshBtn]),
|
||||
h('div', { className: 'session-right' }, [sshBadge, updateBtn, statusTag, refreshBtn]),
|
||||
]);
|
||||
|
||||
const headerEl = h('header', { className: 'top-session-stack' }, [headerRowEl]);
|
||||
@@ -162,6 +168,14 @@ export const TopSessionHeader = defineComponent({
|
||||
patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate'));
|
||||
patchAttr(refreshBtn, 'aria-label', t('header.ariaRefresh'));
|
||||
|
||||
const ep = telemetry?.endpoint;
|
||||
const isRemoteEndpoint = Boolean(ep?.isRemote);
|
||||
patchAttr(sshBadge, 'hidden', !isRemoteEndpoint);
|
||||
if (isRemoteEndpoint) {
|
||||
const epLabel = String(ep?.label || 'SSH').trim();
|
||||
patchAttr(sshBadge, 'title', epLabel && epLabel !== 'SSH' ? `SSH · ${epLabel}` : 'SSH');
|
||||
}
|
||||
|
||||
const actConv = telemetry?.activeConversation;
|
||||
const convs = telemetry?.conversations || [];
|
||||
const hostRouteId = telSt.hostRouteConversationId || '';
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
*/
|
||||
|
||||
import {
|
||||
LOCAL_ENDPOINT_ID,
|
||||
WINDOW_BRIDGE_ENDPOINT_KEY,
|
||||
WINDOW_BRIDGE_KEY,
|
||||
WINDOW_OVERLAY_KEY,
|
||||
WINDOW_OVERLAY_METHODS,
|
||||
@@ -51,6 +53,7 @@ import {
|
||||
normalizeClientTopbarSlots,
|
||||
normalizeClientUpdateMode,
|
||||
normalizeClientWindowMountMode,
|
||||
resetTelemetryForEndpointSwitch,
|
||||
resolveScopedConversation,
|
||||
selectConversation,
|
||||
startAsyncTelemetryLoop,
|
||||
@@ -958,10 +961,18 @@ export function mountWindowOverlay() {
|
||||
const bridgeConfig = getWindowBridgeConfig();
|
||||
const bundleVersion = String(bridgeConfig?.bundleVersion || '');
|
||||
const stylesCss = String(bridgeConfig?.stylesCss || '');
|
||||
const activeBridgeEndpointId = String(
|
||||
bridgeConfig?.[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID
|
||||
);
|
||||
const reusableCarryOver =
|
||||
carryOverTelemetry &&
|
||||
String(carryOverTelemetry?.endpoint?.id || LOCAL_ENDPOINT_ID) === activeBridgeEndpointId
|
||||
? carryOverTelemetry
|
||||
: null;
|
||||
const seedTelemetry =
|
||||
(bridgeConfig?.initialTelemetry && typeof bridgeConfig.initialTelemetry === 'object'
|
||||
? bridgeConfig.initialTelemetry
|
||||
: null) || carryOverTelemetry;
|
||||
: null) || reusableCarryOver;
|
||||
if (bridgeConfig?.initialTelemetry) {
|
||||
delete bridgeConfig.initialTelemetry;
|
||||
}
|
||||
@@ -2741,14 +2752,49 @@ export function mountWindowOverlay() {
|
||||
const token = String(nextBridge.token || '');
|
||||
if (!Number.isInteger(port) || port <= 0 || !token) return false;
|
||||
const cur = readInjectedWindowBridge() || {};
|
||||
const prevEndpointId = String(cur[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID);
|
||||
const nextEndpointId =
|
||||
nextBridge[WINDOW_BRIDGE_ENDPOINT_KEY] !== undefined
|
||||
? String(nextBridge[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID)
|
||||
: prevEndpointId;
|
||||
const portChanged = Number(cur.port || 0) !== port || String(cur.token || '') !== token;
|
||||
const endpointChanged = prevEndpointId !== nextEndpointId;
|
||||
cur.port = port;
|
||||
cur.token = token;
|
||||
if (portChanged) {
|
||||
cur[WINDOW_BRIDGE_ENDPOINT_KEY] = nextEndpointId;
|
||||
if (nextBridge.isRemoteEndpoint !== undefined) {
|
||||
cur.isRemoteEndpoint = Boolean(nextBridge.isRemoteEndpoint);
|
||||
}
|
||||
if (nextBridge.endpointLabel !== undefined) {
|
||||
cur.endpointLabel = String(nextBridge.endpointLabel || '');
|
||||
}
|
||||
if (portChanged || endpointChanged) {
|
||||
cur.transportMode = 'http';
|
||||
}
|
||||
if (endpointChanged) {
|
||||
if (Array.isArray(cur.rpcQueue)) {
|
||||
cur.rpcQueue.length = 0;
|
||||
}
|
||||
if (cur.rpcPending instanceof Map) {
|
||||
for (const pending of cur.rpcPending.values()) {
|
||||
try {
|
||||
const switchErr = new Error('Bridge endpoint switched');
|
||||
switchErr.name = 'AbortError';
|
||||
pending?.reject?.(switchErr);
|
||||
} catch {
|
||||
// 忽略旧端点回调异常
|
||||
}
|
||||
}
|
||||
cur.rpcPending.clear();
|
||||
}
|
||||
}
|
||||
window[WINDOW_BRIDGE_KEY] = cur;
|
||||
void fetchTelemetry({ force: false });
|
||||
if (endpointChanged) {
|
||||
resetTelemetryForEndpointSwitch();
|
||||
void fetchTelemetry({ force: true });
|
||||
} else {
|
||||
void fetchTelemetry({ force: false });
|
||||
}
|
||||
return true;
|
||||
},
|
||||
getTelemetrySnapshot() {
|
||||
|
||||
@@ -4,7 +4,12 @@
|
||||
* (Sidecar Webview `window.sidecar.fetch` + Main Window Loopback Bridge).
|
||||
*/
|
||||
|
||||
import { readInjectedWindowBridge } from '../../shared/window-bridge-protocol.mjs';
|
||||
import {
|
||||
LOCAL_ENDPOINT_ID,
|
||||
WINDOW_BRIDGE_ENDPOINT_HEADER,
|
||||
WINDOW_BRIDGE_ENDPOINT_KEY,
|
||||
readInjectedWindowBridge,
|
||||
} from '../../shared/window-bridge-protocol.mjs';
|
||||
|
||||
const inFlightGets = new Map();
|
||||
const activeControllers = new Map();
|
||||
@@ -130,7 +135,10 @@ function callViaCdpBridge(bridge, path, { method, body, signal, cdpTimeoutMs })
|
||||
|
||||
export async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTimeoutMs = 3500 } = {}) {
|
||||
const upperMethod = method.toUpperCase();
|
||||
const dedupKey = upperMethod === 'GET' && !abortKey ? path : '';
|
||||
const activeEndpointId =
|
||||
String(getWindowBridgeConfig()?.[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID).trim() ||
|
||||
LOCAL_ENDPOINT_ID;
|
||||
const dedupKey = upperMethod === 'GET' && !abortKey ? `${activeEndpointId}::${path}` : '';
|
||||
|
||||
if (dedupKey && inFlightGets.has(dedupKey)) {
|
||||
return inFlightGets.get(dedupKey);
|
||||
@@ -148,7 +156,20 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
|
||||
signal = requestController.signal;
|
||||
}
|
||||
|
||||
const ensureEndpointUnchanged = (targetBridge) => {
|
||||
if (!targetBridge) return;
|
||||
const currentEndpointId =
|
||||
String(targetBridge[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID).trim() ||
|
||||
LOCAL_ENDPOINT_ID;
|
||||
if (currentEndpointId !== activeEndpointId) {
|
||||
const switchErr = new Error('Bridge endpoint switched');
|
||||
switchErr.name = 'AbortError';
|
||||
throw switchErr;
|
||||
}
|
||||
};
|
||||
|
||||
const execHttpOnce = async (activeBridge) => {
|
||||
ensureEndpointUnchanged(activeBridge);
|
||||
const sidecar = typeof window !== 'undefined' ? window.sidecar : null;
|
||||
const fetchFn = sidecar?.fetch
|
||||
? sidecar.fetch.bind(sidecar)
|
||||
@@ -162,6 +183,10 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
|
||||
}
|
||||
if (activeBridge) {
|
||||
headers['X-Usage-Monitor-Token'] = activeBridge.token;
|
||||
const epId = String(activeBridge[WINDOW_BRIDGE_ENDPOINT_KEY] || '').trim();
|
||||
if (epId && epId !== LOCAL_ENDPOINT_ID) {
|
||||
headers[WINDOW_BRIDGE_ENDPOINT_HEADER] = epId;
|
||||
}
|
||||
}
|
||||
const res = await fetchFn(requestUrl, {
|
||||
method: upperMethod,
|
||||
@@ -181,7 +206,10 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
|
||||
throw abortErr;
|
||||
}
|
||||
if (!res.ok) {
|
||||
throw new Error(data.error || `HTTP ${res.status}`);
|
||||
const httpErr = new Error(data.error || `HTTP ${res.status}`);
|
||||
httpErr.httpStatus = res.status;
|
||||
httpErr.retryable = Boolean(data?.retryable);
|
||||
throw httpErr;
|
||||
}
|
||||
if (activeBridge) {
|
||||
activeBridge.transportMode = 'http';
|
||||
@@ -202,8 +230,10 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
|
||||
if (signal?.aborted || cdpErr?.name === 'AbortError') {
|
||||
throw cdpErr;
|
||||
}
|
||||
// 热更新或守护重启期间若 CDP 尚未轮询投递,自动重置回 HTTP 并用最新桥接端口重试一次
|
||||
// 热更新或守护重启期间若 CDP 尚未轮询投递,自动重置回 HTTP 并用最新桥接端口重试一次;
|
||||
// 但若端点已切换(例如本地 <-> SSH),绝不将旧端点请求重放至新端点
|
||||
const latestBridge = getWindowBridgeConfig() || initialBridge;
|
||||
ensureEndpointUnchanged(latestBridge);
|
||||
latestBridge.transportMode = 'http';
|
||||
return execHttpOnce(latestBridge);
|
||||
}
|
||||
@@ -232,7 +262,11 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
|
||||
}
|
||||
throw fetchErr;
|
||||
}
|
||||
// 当宿主环境的 CSP connect-src、混合内容策略或瞬态端口切换阻断直连时,切至带 HTTP 自愈恢复的 CDP 通道
|
||||
// 仅在网络/CORS 阻断(无 HTTP 状态码)或桥接令牌失配(403)时切换至 CDP 兜底;
|
||||
// 业务/初始化状态码(如 503 Remote endpoint initializing、400、500)保持 HTTP 通道等待正常重试。
|
||||
if (fetchErr?.httpStatus && fetchErr.httpStatus !== 403) {
|
||||
throw fetchErr;
|
||||
}
|
||||
return fallbackViaCdpWithRecovery(bridge);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -53,7 +53,12 @@ import {
|
||||
normalizeWindowMountMode,
|
||||
parseStepTokenComboSegments,
|
||||
} from '../../shared/settings-normalization.mjs';
|
||||
import { WINDOW_BRIDGE_ROUTE_KEY, readInjectedWindowBridge } from '../../shared/window-bridge-protocol.mjs';
|
||||
import {
|
||||
LOCAL_ENDPOINT_ID,
|
||||
WINDOW_BRIDGE_ENDPOINT_KEY,
|
||||
WINDOW_BRIDGE_ROUTE_KEY,
|
||||
readInjectedWindowBridge,
|
||||
} from '../../shared/window-bridge-protocol.mjs';
|
||||
|
||||
const CASCADE_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
@@ -149,6 +154,7 @@ let activeBundleVersion = 0;
|
||||
let latestRequestSeq = 0;
|
||||
let latestConsumptionReqSeq = 0;
|
||||
let latestConversationSwitchSeq = 0;
|
||||
let endpointSwitchEpoch = 0;
|
||||
let activeForceCount = 0;
|
||||
let consecutivePollFailures = 0;
|
||||
let inFlightTelemetryPoll = null;
|
||||
@@ -201,10 +207,11 @@ export function clearConversationViewCache() {
|
||||
|
||||
function buildConsumptionScopeSig(payload) {
|
||||
if (!payload || typeof payload !== 'object') return '';
|
||||
const ep = payload.endpoint || {};
|
||||
const acct = payload.account || {};
|
||||
const set = payload.settings || {};
|
||||
const cloud = payload.cloudStatus || {};
|
||||
return `${String(acct.status || '')}|${String(acct.email || acct.name || '').toLowerCase()}|${String(set.weeklyLimitMode || '')}|${String(cloud.catalogVersion || '')}`;
|
||||
return `${String(ep.id || LOCAL_ENDPOINT_ID)}|${String(acct.status || '')}|${String(acct.email || acct.name || '').toLowerCase()}|${String(set.weeklyLimitMode || '')}|${String(cloud.catalogVersion || '')}`;
|
||||
}
|
||||
|
||||
function syncConsumptionCacheScope(payload) {
|
||||
@@ -476,6 +483,13 @@ export function isEquivalentTelemetry(prev, next) {
|
||||
if ((pSet?.fontScale ?? 'md') !== (nSet?.fontScale ?? 'md')) return false;
|
||||
if (Boolean(pSet?.experimentalModernUi) !== Boolean(nSet?.experimentalModernUi)) return false;
|
||||
if ((prev.hostPlatform || '') !== (next.hostPlatform || '')) return false;
|
||||
if (
|
||||
(prev.endpoint?.id || LOCAL_ENDPOINT_ID) !== (next.endpoint?.id || LOCAL_ENDPOINT_ID) ||
|
||||
Boolean(prev.endpoint?.isRemote) !== Boolean(next.endpoint?.isRemote) ||
|
||||
(prev.endpoint?.label || '') !== (next.endpoint?.label || '')
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (Boolean(pSet?.contextWindowRiskAccepted) !== Boolean(nSet?.contextWindowRiskAccepted)) {
|
||||
return false;
|
||||
}
|
||||
@@ -1014,6 +1028,33 @@ export function isEquivalentTelemetry(prev, next) {
|
||||
return true;
|
||||
}
|
||||
|
||||
export function resetTelemetryForEndpointSwitch() {
|
||||
endpointSwitchEpoch += 1;
|
||||
latestRequestSeq += 1;
|
||||
latestConsumptionReqSeq += 1;
|
||||
latestConversationSwitchSeq += 1;
|
||||
lastReceivedSteps = null;
|
||||
inFlightTelemetryPoll = null;
|
||||
consecutivePollFailures = 0;
|
||||
consumptionCacheScopeSig = '';
|
||||
abortSidecarApiKey('telemetry-poll');
|
||||
abortSidecarApiKey('telemetry-force');
|
||||
abortSidecarApiKey('consumption-range');
|
||||
abortSidecarApiKey('consumption-presets');
|
||||
abortSidecarApiKey('conversation-switch');
|
||||
clearConsumptionRangeCache();
|
||||
clearConversationViewCache();
|
||||
if (feedbackTimer) {
|
||||
clearTimeout(feedbackTimer);
|
||||
feedbackTimer = null;
|
||||
}
|
||||
telemetryStore.setState({
|
||||
selectedConversationId: '',
|
||||
telemetry: null,
|
||||
syncState: 'idle',
|
||||
});
|
||||
}
|
||||
|
||||
export async function fetchTelemetry({ force = false } = {}) {
|
||||
if (!force && activeForceCount > 0) {
|
||||
return telemetryStore.getState().telemetry;
|
||||
@@ -1049,11 +1090,17 @@ export async function fetchTelemetry({ force = false } = {}) {
|
||||
}
|
||||
const query = params.toString();
|
||||
const bridge = overlay ? getWindowBridgeConfig() : null;
|
||||
const endpointId = bridge?.[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID;
|
||||
const existing = inFlightTelemetryPoll;
|
||||
if (existing?.query === query && existing.port === bridge?.port && existing.token === bridge?.token) {
|
||||
if (
|
||||
existing?.query === query &&
|
||||
existing.port === bridge?.port &&
|
||||
existing.token === bridge?.token &&
|
||||
existing.endpointId === endpointId
|
||||
) {
|
||||
return existing.promise;
|
||||
}
|
||||
const poll = { query, port: bridge?.port, token: bridge?.token, promise: null };
|
||||
const poll = { query, port: bridge?.port, token: bridge?.token, endpointId, promise: null };
|
||||
poll.promise = requestTelemetry(params, false).finally(() => {
|
||||
if (inFlightTelemetryPoll === poll) inFlightTelemetryPoll = null;
|
||||
});
|
||||
@@ -1240,6 +1287,7 @@ async function fetchConsumptionRangeSlice({
|
||||
customStartMs = 0,
|
||||
customEndMs = 0,
|
||||
} = {}) {
|
||||
const reqEpoch = endpointSwitchEpoch;
|
||||
const reqSeq = ++latestConsumptionReqSeq;
|
||||
const targetRange = String(range || 'today');
|
||||
const current = telemetryStore.getState();
|
||||
@@ -1258,7 +1306,7 @@ async function fetchConsumptionRangeSlice({
|
||||
method: 'GET',
|
||||
abortKey: 'consumption-range',
|
||||
});
|
||||
if (!payload || typeof payload !== 'object') return null;
|
||||
if (!payload || typeof payload !== 'object' || reqEpoch !== endpointSwitchEpoch) return null;
|
||||
|
||||
if (payload.scope === 'consumption' && payload.consumption) {
|
||||
const usageRev = Number(payload.usageRevision ?? payload.consumption.revision ?? 0);
|
||||
@@ -1385,13 +1433,14 @@ export async function selectConversation(
|
||||
params.set('stepRevision', cachedSteps?.revision || '');
|
||||
params.set('scope', 'conversation');
|
||||
|
||||
const reqEpoch = endpointSwitchEpoch;
|
||||
const reqSettingsRev = settingsRevision;
|
||||
try {
|
||||
const payload = await callSidecarApi(`/api/telemetry?${params}`, {
|
||||
method: 'GET',
|
||||
abortKey: 'conversation-switch',
|
||||
});
|
||||
if (!payload || typeof payload !== 'object') return null;
|
||||
if (!payload || typeof payload !== 'object' || reqEpoch !== endpointSwitchEpoch) return null;
|
||||
if (switchSeq !== latestConversationSwitchSeq) return payload;
|
||||
|
||||
const latestSt = telemetryStore.getState();
|
||||
@@ -1550,11 +1599,13 @@ export function prefetchConsumptionPresets() {
|
||||
if (effectiveConvId) params.set('conversationId', effectiveConvId);
|
||||
params.set('scope', 'consumption-presets');
|
||||
|
||||
const reqEpoch = endpointSwitchEpoch;
|
||||
const task = callSidecarApi(`/api/telemetry?${params}`, {
|
||||
method: 'GET',
|
||||
abortKey: 'consumption-presets',
|
||||
})
|
||||
.then((payload) => {
|
||||
if (reqEpoch !== endpointSwitchEpoch) return false;
|
||||
if (payload?.scope === 'consumption-presets' && payload.ranges && typeof payload.ranges === 'object') {
|
||||
const rev = Number(payload.usageRevision || currentRev || 0);
|
||||
for (const [rangeKey, entry] of Object.entries(payload.ranges)) {
|
||||
|
||||
@@ -52,6 +52,23 @@
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.endpoint-ssh-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 2px 5px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-sm);
|
||||
font-weight: 600;
|
||||
line-height: 1.2;
|
||||
letter-spacing: 0.02em;
|
||||
border-radius: var(--radius-xs);
|
||||
border: 1px solid var(--accent-primary-border);
|
||||
background: var(--accent-primary-soft);
|
||||
color: var(--accent-primary);
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.status-tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -249,6 +249,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
[data-modern-ui="true"] .status-tag.state-running,
|
||||
[data-modern-ui="true"] .status-tag.state-synced,
|
||||
[data-modern-ui="true"] .status-tag.state-warn,
|
||||
[data-modern-ui="true"] .endpoint-ssh-badge,
|
||||
[data-modern-ui="true"] .update-badge-btn,
|
||||
[data-modern-ui="true"] .wm-update-btn,
|
||||
[data-modern-ui="true"] .wm-hover-update-bar,
|
||||
|
||||
Reference in New Issue
Block a user