feat(panel): support SSH remote windows with per-endpoint isolation and context window overrides

- Add per-endpoint registry and isolated caches (endpoint-registry.mjs, multi-path trajectory-cache-file.mjs) so local and SSH remote windows maintain independent conversations, telemetry, quotas, and consumption analytics (Antigravity SSH) without remote plugin installation
- Classify local vs. SSH Desktop targets via two-pass hub port and metadata probing in window-bridge.mjs and ls-discovery.mjs, routing HTTP/CDP requests with authoritative X-Usage-Monitor-Endpoint headers and preventing local data leaks or 503-triggered CDP downgrades
- Implement two-tier read-only remote LS RPC transport in ls-rpc.mjs (loopback HTTP/HTTPS with size/wall-clock limits and 60s circuit breaker falling back to stateless same-origin window.fetch / connect-websocket via CDP)
- Enable per-endpoint verified context window overrides in SSH Desktop windows (context-windows.mjs, window-bridge.mjs, api-actions.mjs) without double-wrapping window.fetch
- Surface an SSH badge in TopSessionHeader, cleanly flush stale requests/queues on endpoint rebind, rebuild app.js/styles.css, and add 13 unit/E2E tests in test/ssh-remote-endpoints.test.mjs (157/157 passing)
This commit is contained in:
hejun01
2026-11-20 11:41:39 +08:00
parent d371dc1ed5
commit 253da45607
22 changed files with 4095 additions and 310 deletions
+280 -46
View File
@@ -2,27 +2,203 @@
* @fileoverview Antigravity Language Server Connect RPC 客户端与官方配额摘要缓存。
*
* 负责:
* 1. 向本地 Language Server 发起带 CSRF 鉴权与超时保护的 Connect RPC 调用 (`callLsRpc`);
* 2. 拉取并缓存 `RetrieveUserQuotaSummary` 官方实时配额摘要(常规轮询使用 10 秒短期缓存与失败退避冷却,
* 并在缓存过期或强制刷新时穿透 `language_server.exe` 内部 3 分钟陈旧缓存)。
* 1. 向本地或 SSH 远端窗口对应的 Language Server 发起带 CSRF 鉴权与超时保护的 Connect RPC 调用 (`callLsRpc`);
* 2. 对远端 SSH 端点采用双层传输:
* - Tier-1:严格限定回环地址 (`127.0.0.1`/`localhost`/`::1`) 的 HTTP/HTTPS 直连(HTTPS 仅对回环允许宿主自签证书);
* - Tier-2:Tier-1 不可用或鉴权依赖 Electron Partition Cookie / 2.33.0+ 省略 `csrfToken` 时,
* 自动熔断并回退至窗口内同源 `window.fetch` / `/connect-websocket`(通过 CDP 按需执行);
* 3. 拉取并按端点隔离缓存 `RetrieveUserQuotaSummary` 官方实时配额摘要与 `GetAvailableModels` 模型目录。
*/
import { lsRuntimeEndpoint, quotaSummaryCache } from './config.mjs';
import { lsRuntimeEndpoint } from './config.mjs';
import {
getEndpointQuotaCache,
getRemoteWindowRpcInvoker,
markRemoteEndpointPreferTier2,
shouldRemoteEndpointPreferTier2,
} from './endpoint-registry.mjs';
import { ensureLsEndpointDiscovered } from './ls-discovery.mjs';
const QUOTA_CACHE_TTL_MS = 10_000;
const QUOTA_RETRY_COOLDOWN_MS = 5_000;
const REMOTE_HTTPS_MAX_RESPONSE_BYTES = 32 * 1024 * 1024;
const REMOTE_ALLOWED_LS_METHODS = new Set([
'GetUserStatus',
'GetAvailableModels',
'GetAllCascadeTrajectories',
'GetCascadeTrajectory',
'RetrieveUserQuotaSummary',
]);
let contextModelCatalog = null;
let loopbackHttpsModulePromise = null;
let customLoopbackHttpsRequester = null;
export function setLoopbackHttpsRequester(requester) {
customLoopbackHttpsRequester = typeof requester === 'function' ? requester : null;
}
function isStrictLoopbackUrl(rawUrl) {
try {
const parsed = new URL(String(rawUrl || ''));
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false;
const host = parsed.hostname.toLowerCase();
return host === '127.0.0.1' || host === 'localhost' || host === '::1' || host === '[::1]';
} catch {
return false;
}
}
async function getLoopbackHttpsRequestFn() {
if (customLoopbackHttpsRequester) return customLoopbackHttpsRequester;
if (typeof globalThis !== 'undefined' && typeof globalThis.__agLoopbackHttpsRequest === 'function') {
return globalThis.__agLoopbackHttpsRequest;
}
if (!loopbackHttpsModulePromise) {
loopbackHttpsModulePromise = import('node:https')
.then((mod) => (mod.default || mod)?.request || null)
.catch(() => null);
}
return loopbackHttpsModulePromise;
}
async function postLoopbackHttpsJson(urlStr, csrfToken, bodyText, timeoutMs) {
const parsed = new URL(urlStr);
if (!isStrictLoopbackUrl(urlStr) || parsed.protocol !== 'https:') {
throw new Error('Refusing non-loopback HTTPS request');
}
const requestFn = await getLoopbackHttpsRequestFn();
if (typeof requestFn !== 'function') {
return fetch(urlStr, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(csrfToken ? { 'x-codeium-csrf-token': csrfToken } : {}),
},
body: bodyText,
signal: AbortSignal.timeout(timeoutMs),
});
}
return new Promise((resolve, reject) => {
let settled = false;
let wallTimer = null;
const clearWallTimer = () => {
if (wallTimer) {
clearTimeout(wallTimer);
wallTimer = null;
}
};
const finishErr = (err) => {
if (settled) return;
settled = true;
clearWallTimer();
reject(err);
};
const bodyBuf = Buffer.from(bodyText, 'utf8');
const req = requestFn(
{
hostname: parsed.hostname.replace(/^\[|\]$/g, ''),
port: Number(parsed.port || 443),
path: `${parsed.pathname}${parsed.search}`,
method: 'POST',
rejectUnauthorized: false,
headers: {
'Content-Type': 'application/json',
'Content-Length': bodyBuf.length,
...(csrfToken ? { 'x-codeium-csrf-token': csrfToken } : {}),
},
},
(res) => {
const chunks = [];
let totalBytes = 0;
res.on('data', (chunk) => {
if (settled) return;
totalBytes += chunk.length;
if (totalBytes > REMOTE_HTTPS_MAX_RESPONSE_BYTES) {
const sizeErr = new Error('Remote LS response exceeded size limit');
finishErr(sizeErr);
req.destroy(sizeErr);
return;
}
chunks.push(chunk);
});
res.on('aborted', () => {
finishErr(new Error('Remote LS HTTPS response aborted'));
});
res.on('end', () => {
if (settled) return;
settled = true;
clearWallTimer();
const status = Number(res.statusCode || 0);
const rawText = Buffer.concat(chunks).toString('utf8');
resolve({
ok: status >= 200 && status < 300,
status,
json: async () => JSON.parse(rawText || '{}'),
text: async () => rawText,
});
});
res.on('error', finishErr);
}
);
wallTimer = setTimeout(() => {
const timeoutErr = new Error(`Remote LS HTTPS timeout (${timeoutMs}ms)`);
finishErr(timeoutErr);
req.destroy(timeoutErr);
}, timeoutMs);
wallTimer?.unref?.();
req.setTimeout(timeoutMs, () => {
const timeoutErr = new Error(`Remote LS HTTPS timeout (${timeoutMs}ms)`);
finishErr(timeoutErr);
req.destroy(timeoutErr);
});
req.on('error', finishErr);
req.write(bodyBuf);
req.end();
});
}
export function getContextModelCatalog(endpoint = null) {
const isRemote = Boolean(endpoint && endpoint.isRemote);
if (isRemote) {
const baseUrl = endpoint.baseUrl || endpoint.origin || '';
const csrfToken = endpoint.csrfToken || '';
const cached = endpoint.contextModelCatalog;
if (
!cached ||
cached.baseUrl !== baseUrl ||
cached.csrfToken !== csrfToken ||
Date.now() >= cached.expiresAt
) {
endpoint.contextModelCatalog = {
baseUrl,
csrfToken,
expiresAt: Date.now() + 30000,
promise: callLsRpc('GetAvailableModels', {}, 2500, endpoint)
.then((data) => data?.response?.models)
.catch(() => null),
};
}
return endpoint.contextModelCatalog.promise;
}
export function getContextModelCatalog() {
const { baseUrl, csrfToken } = lsRuntimeEndpoint;
if (!contextModelCatalog || contextModelCatalog.baseUrl !== baseUrl || contextModelCatalog.csrfToken !== csrfToken ||
Date.now() >= contextModelCatalog.expiresAt) {
if (
!contextModelCatalog ||
contextModelCatalog.baseUrl !== baseUrl ||
contextModelCatalog.csrfToken !== csrfToken ||
Date.now() >= contextModelCatalog.expiresAt
) {
contextModelCatalog = {
baseUrl,
csrfToken,
expiresAt: Date.now() + 30000,
promise: callLsRpc('GetAvailableModels', {}, 1500).then((data) => data?.response?.models).catch(() => null),
promise: callLsRpc('GetAvailableModels', {}, 1500)
.then((data) => data?.response?.models)
.catch(() => null),
};
}
return contextModelCatalog.promise;
@@ -40,15 +216,77 @@ async function postLsRpcOnce(baseUrl, csrfToken, method, body, timeoutMs) {
});
}
async function callRemoteEndpointLsRpc(endpoint, method, body, timeoutMs) {
if (!REMOTE_ALLOWED_LS_METHODS.has(method)) {
throw new Error(`RPC method ${method} is not allowed on remote endpoints`);
}
const baseUrl = String(endpoint.baseUrl || endpoint.origin || '').trim().replace(/\/+$/, '');
const csrfToken = String(endpoint.csrfToken || '').trim();
const windowInvoker = getRemoteWindowRpcInvoker();
const canTryTier1 =
Boolean(baseUrl) &&
isStrictLoopbackUrl(baseUrl) &&
Boolean(csrfToken) &&
!shouldRemoteEndpointPreferTier2(endpoint);
let tier1Err = null;
if (canTryTier1) {
try {
const urlStr = `${baseUrl}/exa.language_server_pb.LanguageServerService/${method}`;
const bodyText = JSON.stringify(body || {});
const res = urlStr.startsWith('https://')
? await postLoopbackHttpsJson(urlStr, csrfToken, bodyText, timeoutMs)
: await postLsRpcOnce(baseUrl, csrfToken, method, body || {}, timeoutMs);
if (res?.ok) {
return await res.json();
}
const status = Number(res?.status || 0);
const text = await res?.text?.().catch(() => '') || '';
tier1Err = new Error(`Remote RPC ${method} failed (${status}): ${text}`);
const isTransportAuthOrRouteMiss =
status === 0 ||
status === 401 ||
status === 403 ||
(status === 404 && method !== 'GetCascadeTrajectory');
if (isTransportAuthOrRouteMiss) {
markRemoteEndpointPreferTier2(endpoint);
} else {
// 业务级 4xx(如单个会话已被删除导致的 GetCascadeTrajectory 404)直接上抛,不误触熔断
throw tier1Err;
}
} catch (err) {
if (err === tier1Err) {
throw err;
}
tier1Err = err;
markRemoteEndpointPreferTier2(endpoint);
}
}
if (typeof windowInvoker === 'function') {
return windowInvoker(endpoint, method, body || {}, timeoutMs);
}
if (tier1Err) {
throw tier1Err;
}
throw new Error(`Remote LS transport unavailable for endpoint ${endpoint.id}`);
}
/**
* 调用本地 `LanguageServerService` 的指定 RPC 方法(支持按需发现与宿主重启重连)。
* 调用本地或远端 SSH `LanguageServerService` 的指定 RPC 方法(本地支持按需发现与宿主重启重连)。
*
* @param {string} method RPC 方法名(如 `'GetUserStatus'`、`'GetCascadeTrajectory'`)
* @param {object} [body={}] 请求 JSON 载荷
* @param {number} [timeoutMs=5000] 超时时间(毫秒)
* @param {object|null} [endpoint=null] 可选远端端点对象;缺省调用本机 LS
* @returns {Promise<object>}
*/
export async function callLsRpc(method, body = {}, timeoutMs = 5000) {
export async function callLsRpc(method, body = {}, timeoutMs = 5000, endpoint = null) {
if (endpoint && endpoint.isRemote) {
return callRemoteEndpointLsRpc(endpoint, method, body, timeoutMs);
}
if (!lsRuntimeEndpoint.baseUrl && lsRuntimeEndpoint.addr !== 'test.invalid') {
await ensureLsEndpointDiscovered({ force: false });
}
@@ -113,35 +351,31 @@ export async function callLsRpc(method, body = {}, timeoutMs = 5000) {
}
/**
* 获取官方实时配额摘要(`RetrieveUserQuotaSummary`)。
*
* 缓存策略:
* - 常规轮询在 10 秒内直接复用内存缓存,避免高频打满上游接口;
* - 常规轮询发生网络失败或空载荷时进入 5 秒冷却退避,避免每 2 秒重复超时阻塞;
* - 当超过 TTL 或传入 `forceRefresh = true`(如手动刷新或检测到账号切换)时,
* 向 LS 传递 `{ forceRefresh: true }`,绕过 `language_server.exe` 自身的 3 分钟缓存。
* 获取官方实时配额摘要(`RetrieveUserQuotaSummary`),按端点与账号隔离短期缓存。
*
* @param {boolean} [forceRefresh=false] 是否强制穿透本地缓存与失败冷却
* @param {string} [accountName=''] 发起查询时宿主报告的账号,用于隔离配额缓存
* @param {object|null} [endpoint=null] 可选远端端点对象
* @returns {Promise<{data: object|null, fetchedAtMs: number, isStale: boolean, refreshFailed: boolean, error: string|null, fromCache: boolean}>}
*/
export async function getOfficialQuotaSummary(forceRefresh = false, accountName = '') {
if (quotaSummaryCache.accountName !== accountName) {
Object.assign(quotaSummaryCache, {
export async function getOfficialQuotaSummary(forceRefresh = false, accountName = '', endpoint = null) {
const qCache = getEndpointQuotaCache(endpoint);
if (qCache.accountName !== accountName) {
Object.assign(qCache, {
accountName,
accountGeneration: quotaSummaryCache.accountGeneration + 1,
accountGeneration: qCache.accountGeneration + 1,
ts: 0,
lastAttemptTs: 0,
data: null,
error: null,
});
}
const generation = quotaSummaryCache.accountGeneration;
const generation = qCache.accountGeneration;
const now = Date.now();
if (!forceRefresh && quotaSummaryCache.data && now - quotaSummaryCache.ts < QUOTA_CACHE_TTL_MS) {
if (!forceRefresh && qCache.data && now - qCache.ts < QUOTA_CACHE_TTL_MS) {
return {
data: quotaSummaryCache.data,
fetchedAtMs: quotaSummaryCache.ts,
data: qCache.data,
fetchedAtMs: qCache.ts,
isStale: false,
refreshFailed: false,
error: null,
@@ -150,35 +384,35 @@ export async function getOfficialQuotaSummary(forceRefresh = false, accountName
}
if (
!forceRefresh &&
quotaSummaryCache.lastAttemptTs > 0 &&
now - quotaSummaryCache.lastAttemptTs < QUOTA_RETRY_COOLDOWN_MS &&
quotaSummaryCache.error
qCache.lastAttemptTs > 0 &&
now - qCache.lastAttemptTs < QUOTA_RETRY_COOLDOWN_MS &&
qCache.error
) {
return {
data: quotaSummaryCache.data,
fetchedAtMs: quotaSummaryCache.ts || 0,
isStale: Boolean(quotaSummaryCache.data),
data: qCache.data,
fetchedAtMs: qCache.ts || 0,
isStale: Boolean(qCache.data),
refreshFailed: true,
error: quotaSummaryCache.error,
error: qCache.error,
fromCache: true,
};
}
quotaSummaryCache.lastAttemptTs = now;
qCache.lastAttemptTs = now;
try {
const res = await callLsRpc('RetrieveUserQuotaSummary', { forceRefresh: true }, 6000);
const { userStatus } = await callLsRpc('GetUserStatus', {}, 2000);
const res = await callLsRpc('RetrieveUserQuotaSummary', { forceRefresh: true }, 6000, endpoint);
const { userStatus } = await callLsRpc('GetUserStatus', {}, 2500, endpoint);
if ((userStatus?.email || userStatus?.name || '') !== accountName) return {};
if (generation !== quotaSummaryCache.accountGeneration) return {};
if (generation !== qCache.accountGeneration) return {};
const payload = res?.response !== undefined ? res.response : res;
if (payload && typeof payload === 'object' && !Array.isArray(payload)) {
const normalized =
Array.isArray(payload.groups) || Array.isArray(payload.buckets)
? payload
: { ...payload, groups: [] };
quotaSummaryCache.ts = now;
quotaSummaryCache.data = normalized;
quotaSummaryCache.error = null;
qCache.ts = now;
qCache.data = normalized;
qCache.error = null;
return {
data: normalized,
fetchedAtMs: now,
@@ -188,18 +422,18 @@ export async function getOfficialQuotaSummary(forceRefresh = false, accountName
fromCache: false,
};
}
quotaSummaryCache.error = 'Quota summary empty';
qCache.error = 'Quota summary empty';
} catch (err) {
if (generation !== quotaSummaryCache.accountGeneration) return {};
if (generation !== qCache.accountGeneration) return {};
console.error(`RetrieveUserQuotaSummary failed: ${err.message}`);
quotaSummaryCache.error = err.message;
qCache.error = err.message;
}
return {
data: quotaSummaryCache.data,
fetchedAtMs: quotaSummaryCache.ts || 0,
isStale: Boolean(quotaSummaryCache.data),
data: qCache.data,
fetchedAtMs: qCache.ts || 0,
isStale: Boolean(qCache.data),
refreshFailed: true,
error: quotaSummaryCache.error || 'Quota RPC unavailable',
error: qCache.error || 'Quota RPC unavailable',
fromCache: false,
};
}