feat(panel): add VS Code extension, Remote-SSH, and remote CLI support

- Auto-discover and provision standard VS Code / VS Code Insiders argv.json without touching Antigravity Desktop port files
- Add independent vsCodeMountMode (default: Input Box / composer, optional: Top Bar / dual; omit Sidebar Only in VS Code host)
- Support Remote-SSH endpoint isolation for VS Code Antigravity extension and instant conversation following via passive route watcher + /api/bridge-route-ping
- Add remote-cli-bridge to detect remote agy CLI usage-monitor plugin and auto-mount on Top Bar over on-demand SSH loopback tunnels (tier1Only), skipping hosts with neither plugin
- Optimize background CDP polling and remote idle polling cadence
- Update README.md / README.zh-CN.md and add regression tests
This commit is contained in:
2026-11-26 18:01:30 +08:00
parent 710b09275f
commit 13b84bfa86
18 changed files with 1953 additions and 170 deletions
+96 -24
View File
@@ -902,7 +902,7 @@ return { THIRD_PARTY_POOL_RE, isThirdPartyPoolText, classifySpeedTier, classifyC
})();
// --- shared/window-bridge-protocol.mjs ---
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, 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, isVsCodeExtensionHost } = (() => {
const WINDOW_BRIDGE_KEY = '__AGUsageMonitorBridge';
const WINDOW_BRIDGE_ROUTE_KEY = 'hostRouteCascadeId';
const WINDOW_BRIDGE_ENDPOINT_KEY = 'endpointId';
@@ -959,7 +959,21 @@ const BRIDGE_API_PATHS = Object.freeze(BRIDGE_API_ROUTE_DEFS.map((r) => r.path))
function readInjectedWindowBridge() {
return typeof window === 'undefined' ? undefined : window[WINDOW_BRIDGE_KEY];
}
return { WINDOW_BRIDGE_KEY, WINDOW_BRIDGE_ROUTE_KEY, WINDOW_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 };
function isVsCodeExtensionHost() {
const bridge = readInjectedWindowBridge();
if (bridge?.isVsCodeHost === true) return true;
if (typeof window !== 'undefined') {
const search = String(window.location?.search || '');
if (/[?&]extensionVariant=vs-code/i.test(search)) return true;
const href = String(window.location?.href || '');
if (/(?:Visual(?:%20|\s)Studio(?:%20|\s)Code|Code(?:\s|%20)-?(?:\s|%20)Insiders)/i.test(href)) {
return true;
}
}
return false;
}
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, isVsCodeExtensionHost };
})();
// --- shared/host-i18n-protocol.mjs ---
@@ -2081,6 +2095,8 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
'settings.str.mountDual': '双栖挂载 (顶部栏 + 侧边栏)',
'settings.str.mountComposer': '输入框挂载 (输入框 + 侧边栏)',
'settings.str.mountSidebar': '仅侧边栏',
'settings.str.mountVsCodeComposer': '输入框',
'settings.str.mountVsCodeTopbar': '顶部栏',
'settings.bridge.restartTitle': '已自动补齐启动参数,重启一次即可启用悬浮胶囊',
'settings.bridge.ctxRestartTitle': '已自动补齐启动参数,重启一次即可激活上下文覆写',
'settings.bridge.restartBody': '已自动为快捷方式、自启项及协议关联写入 --remote-debugging-port=0(后续通过常规快捷方式打开均自动生效)。点击下方按钮即可退出后台进程并立即生效。',
@@ -3112,6 +3128,8 @@ const I18N_MESSAGES_EN_US = Object.freeze({
'settings.str.mountDual': 'Dual Mount (Titlebar + Sidebar)',
'settings.str.mountComposer': 'Composer Mount (Input Box + Sidebar)',
'settings.str.mountSidebar': 'Sidebar Only',
'settings.str.mountVsCodeComposer': 'Input Box',
'settings.str.mountVsCodeTopbar': 'Top Bar',
'settings.bridge.restartTitle': 'Launch Flag Auto-Configured — Restart Once to Activate',
'settings.bridge.ctxRestartTitle': 'Launch Flag Auto-Configured — Restart Once for Context Override',
'settings.bridge.restartBody': 'Automatically added --remote-debugging-port=0 to your shortcuts, startup entries, and protocol handlers (subsequent shortcut launches mount automatically). Click below to close background processes and relaunch now.',
@@ -9581,6 +9599,7 @@ const TELEMETRY_RECOMPUTE_SETTING_KEYS = new Set([
'weeklyTokenBudget',
'weeklyCostBudget',
'windowMountMode',
'vsCodeMountMode',
'enableWindowOverlay',
]);
@@ -11666,7 +11685,16 @@ function startAsyncTelemetryLoop(intervalMs = 2000) {
const resolveNextDelay = () => {
if (isWindowOverlayMode() && typeof document !== 'undefined' && document.hidden) {
return Math.max(loopIntervalMs, 8000);
return Math.max(loopIntervalMs, 10000);
}
if (isWindowOverlayMode() && readInjectedWindowBridge()?.isRemoteEndpoint) {
const tel = telemetryStore.getState().telemetry;
const hasRunning =
(Array.isArray(tel?.runningConversations) && tel.runningConversations.length > 0) ||
tel?.activeConversation?.status === 'CASCADE_RUN_STATUS_RUNNING';
if (!hasRunning) {
return Math.max(loopIntervalMs, 6000);
}
}
return loopIntervalMs;
};
@@ -32289,6 +32317,12 @@ function normalizeStructureTabKey(raw) {
}
function getMountModeOptions() {
if (isVsCodeExtensionHost()) {
return [
{ value: 'composer', label: t('settings.str.mountVsCodeComposer') },
{ value: 'dual', label: t('settings.str.mountVsCodeTopbar') },
];
}
return [
{ value: 'dual', label: t('settings.str.mountDual') },
{ value: 'composer', label: t('settings.str.mountComposer') },
@@ -32668,6 +32702,16 @@ const SettingsStructureTab = defineComponent({
icon: 'dock',
options: getMountModeOptions(),
onUpdateModelValue: (val) => {
if (isVsCodeExtensionHost()) {
const nextVsMode = val === 'dual' ? 'dual' : 'composer';
draftWindowMountMode = nextVsMode;
syncMountSectionMeta();
props.onLayoutChange?.();
void persistStructurePatch(mountSection, {
vsCodeMountMode: nextVsMode,
});
return;
}
const nextMode = normalizeClientWindowMountMode(val);
draftWindowMountMode = nextMode;
syncMountSectionMeta();
@@ -32857,7 +32901,8 @@ const SettingsStructureTab = defineComponent({
title: t('settings.str.mountSection'),
badgeText: t('settings.str.mountBadge', { count: draftTopbarSlots.length }),
onReset: () => {
draftWindowMountMode = 'dual';
const vsCodeHost = isVsCodeExtensionHost();
draftWindowMountMode = vsCodeHost ? 'composer' : 'dual';
draftPopoverWidthMode = 'auto';
draftPopoverWidth = DEFAULT_CLIENT_POPOVER_WIDTH;
popoverWidthStepper.setProps({ modelValue: DEFAULT_CLIENT_POPOVER_WIDTH });
@@ -32872,8 +32917,9 @@ const SettingsStructureTab = defineComponent({
void persistStructurePatch(
mountSection,
{
windowMountMode: 'dual',
enableWindowOverlay: true,
...(vsCodeHost
? { vsCodeMountMode: 'composer' }
: { windowMountMode: 'dual', enableWindowOverlay: true }),
popoverWidthMode: 'auto',
popoverWidth: DEFAULT_CLIENT_POPOVER_WIDTH,
enableCliStatusLine: true,
@@ -33658,10 +33704,14 @@ const SettingsStructureTab = defineComponent({
if (hostPlatform) latestHostPlatform = hostPlatform;
if (cliStatusLine !== undefined) latestCliStatusLine = cliStatusLine;
if (quotas !== undefined) latestQuotas = quotas;
draftWindowMountMode = normalizeClientWindowMountMode(
settings.windowMountMode,
settings.enableWindowOverlay
);
draftWindowMountMode = isVsCodeExtensionHost()
? settings.vsCodeMountMode === 'dual'
? 'dual'
: 'composer'
: normalizeClientWindowMountMode(
settings.windowMountMode,
settings.enableWindowOverlay
);
draftPopoverWidthMode = normalizeClientPopoverWidthMode(settings.popoverWidthMode);
draftPopoverWidth = normalizeClientPopoverWidth(settings.popoverWidth);
draftEnableCliStatusLine = settings.enableCliStatusLine !== false;
@@ -41810,12 +41860,27 @@ function isIdeExtensionChatFrame() {
function resolveActiveDockTarget(options = undefined) {
const settings = telemetryStore.getState().telemetry?.settings;
const rawMode =
settings?.windowMountMode ??
readInjectedWindowBridge()?.mountMode;
const bridge = readInjectedWindowBridge();
const isVsCode = isVsCodeExtensionHost();
const forceTopbar = bridge?.forceTopbarMode === true;
const rawMode = forceTopbar
? 'dual'
: isVsCode
? settings?.vsCodeMountMode === 'dual'
? 'dual'
: bridge?.mountMode === 'dual' && settings?.vsCodeMountMode === undefined
? 'dual'
: 'composer'
: settings?.windowMountMode ?? bridge?.mountMode;
const mountMode =
options?.mountMode ||
normalizeClientWindowMountMode(rawMode, settings?.enableWindowOverlay);
(forceTopbar
? 'dual'
: isVsCode
? rawMode === 'dual'
? 'dual'
: 'composer'
: normalizeClientWindowMountMode(rawMode, settings?.enableWindowOverlay));
if (isIdeExtensionChatFrame()) {
if (mountMode !== 'composer') return null;
return findHostComposerAutoTarget(
@@ -43607,10 +43672,17 @@ function mountWindowOverlay() {
}
}
let lastAppliedMountMode = normalizeClientWindowMountMode(
telemetryStore.getState().telemetry?.settings?.windowMountMode,
telemetryStore.getState().telemetry?.settings?.enableWindowOverlay
);
const resolveShellMountMode = (settingsObj) => {
if (isVsCodeExtensionHost()) {
return settingsObj?.vsCodeMountMode === 'dual' ? 'dual' : 'composer';
}
return normalizeClientWindowMountMode(
settingsObj?.windowMountMode,
settingsObj?.enableWindowOverlay
);
};
let lastAppliedMountMode = resolveShellMountMode(telemetryStore.getState().telemetry?.settings);
const unsubStore = telemetryStore.subscribe(
(st) => ({
@@ -43620,11 +43692,11 @@ function mountWindowOverlay() {
selectedConversationId: st.selectedConversationId,
}),
(slice) => {
const nextMountMode = normalizeClientWindowMountMode(
slice.telemetry?.settings?.windowMountMode,
slice.telemetry?.settings?.enableWindowOverlay
);
if (slice.telemetry?.settings?.enableWindowOverlay === false || nextMountMode === 'sidebar') {
const nextMountMode = resolveShellMountMode(slice.telemetry?.settings);
if (
!isVsCodeExtensionHost() &&
(slice.telemetry?.settings?.enableWindowOverlay === false || nextMountMode === 'sidebar')
) {
if (popoverOpen) setPopoverOpen(false);
if (multiOpen) setMultiOpen(false);
} else if (nextMountMode !== lastAppliedMountMode) {
@@ -43698,7 +43770,7 @@ function mountWindowOverlay() {
const shouldPreserveSameSession =
!currentRouteId || isSameActiveRoot || isChildOfActiveRoot;
const nextSelectedId =
currentRouteId && st.selectedConversationId && st.selectedConversationId !== currentRouteId
st.selectedConversationId && st.selectedConversationId !== currentRouteId
? ''
: st.selectedConversationId;
if (!shouldPreserveSameSession) {
+4 -2
View File
@@ -410,7 +410,8 @@ export function executeSettingsAction(data) {
}
if (
updated.enableWindowOverlay !== (current.enableWindowOverlay !== false) ||
updated.windowMountMode !== prevMountMode
updated.windowMountMode !== prevMountMode ||
updated.vsCodeMountMode !== (current.vsCodeMountMode || 'composer')
) {
void notifyWindowOverlaySetting(updated.enableWindowOverlay);
} else if (contextWindowScopeChanged) {
@@ -535,7 +536,8 @@ export function executeResetSettingsAction() {
);
if (
updated.enableWindowOverlay !== (current.enableWindowOverlay !== false) ||
updated.windowMountMode !== prevMountMode
updated.windowMountMode !== prevMountMode ||
updated.vsCodeMountMode !== (current.vsCodeMountMode || 'composer')
) {
void notifyWindowOverlaySetting(updated.enableWindowOverlay);
} else if (
@@ -194,6 +194,7 @@ export function registerRemoteEndpoint(info = {}) {
origin: cleanOrigin,
baseUrl: cleanBaseUrl,
csrfToken: cleanCsrf,
tier1Only: info.tier1Only === true,
targets: new Map(),
lastSeenMs: nowMs,
preferTier2UntilMs: 0,
@@ -209,6 +210,7 @@ export function registerRemoteEndpoint(info = {}) {
} else {
entry.lastSeenMs = nowMs;
if (identity.label) entry.label = identity.label;
if (info.tier1Only !== undefined) entry.tier1Only = info.tier1Only === true;
if (cleanOrigin) entry.origin = cleanOrigin;
const existingTarget = cleanWsUrl ? entry.targets.get(cleanWsUrl) : null;
+8 -5
View File
@@ -227,11 +227,12 @@ async function callRemoteEndpointLsRpc(endpoint, method, body, timeoutMs) {
const baseUrl = String(endpoint.baseUrl || endpoint.origin || '').trim().replace(/\/+$/, '');
const csrfToken = String(endpoint.csrfToken || '').trim();
const windowInvoker = getRemoteWindowRpcInvoker();
const tier1Only = endpoint.tier1Only === true;
const canTryTier1 =
Boolean(baseUrl) &&
isStrictLoopbackUrl(baseUrl) &&
Boolean(csrfToken) &&
!shouldRemoteEndpointPreferTier2(endpoint);
(tier1Only || !shouldRemoteEndpointPreferTier2(endpoint));
let tier1Err = null;
if (canTryTier1) {
@@ -252,10 +253,10 @@ async function callRemoteEndpointLsRpc(endpoint, method, body, timeoutMs) {
status === 401 ||
status === 403 ||
(status === 404 && method !== 'GetCascadeTrajectory');
if (isTransportAuthOrRouteMiss) {
if (isTransportAuthOrRouteMiss && !tier1Only) {
markRemoteEndpointPreferTier2(endpoint);
} else {
// 业务级 4xx(如单个会话已被删除导致的 GetCascadeTrajectory 404)直接上抛,不误触熔断
// 业务级 4xx(如单个会话已被删除导致的 GetCascadeTrajectory 404)或纯 Tier-1 隧道端点直接上抛
throw tier1Err;
}
} catch (err) {
@@ -263,11 +264,13 @@ async function callRemoteEndpointLsRpc(endpoint, method, body, timeoutMs) {
throw err;
}
tier1Err = err;
markRemoteEndpointPreferTier2(endpoint);
if (!tier1Only) {
markRemoteEndpointPreferTier2(endpoint);
}
}
}
if (typeof windowInvoker === 'function') {
if (!tier1Only && typeof windowInvoker === 'function') {
const remainingMs = canTryTier1 ? deadlineMs - Date.now() : safeTimeoutMs;
if (!canTryTier1 || remainingMs >= REMOTE_TIER2_MIN_REMAINING_MS) {
return windowInvoker(
@@ -0,0 +1,542 @@
/**
* @fileoverview Remote-SSH 远端 `agy` CLI 插件探测与按需本地 SSH 隧道管理器 (`remote-cli-bridge.mjs`)。
*
* 适用场景:
* 当 VS Code 通过 Remote-SSH 连接远端服务器,但远端**未安装/未打开 VS Code Antigravity 扩展**、
* 仅安装了 **`agy` CLI 及其 `usage-monitor` 插件**时:
* 1. 通过单次非交互 `ssh -o BatchMode=yes` 探测远端是否存在 `agy` CLI + `usage-monitor` 插件,
* 以及当前存活的 `daemon/hub_*.json`(优先 `~/.gemini/antigravity-cli/daemon`,次选 `~/.gemini/antigravity/daemon`);
* 2. 探测结果按主机名缓存并后台异步刷新,绝不阻塞主窗口 CDP 巡检循环(无插件或不可达主机缓存 60s,几乎零开销);
* 3. 若远端检测到存活 `hub_*.json`,按需拉起单条回环端口转发 `ssh -N -L 127.0.0.1:<localPort>:127.0.0.1:<remotePort>`,
* 供 `ls-rpc.mjs` 通过 Tier-1 回环 HTTP/HTTPS 直连拉取远端 `agy` 实时遥测;
* 4. 当对应 Remote-SSH 窗口关闭或插件退出时自动终止隧道子进程,不留孤儿进程。
*/
import { execFile, spawn } from 'node:child_process';
import net from 'node:net';
const SSH_HOST_RE = /^[a-zA-Z0-9._@:+-]{1,128}$/;
const DEFAULT_NEGATIVE_TTL_MS = 60_000;
const DEFAULT_POSITIVE_IDLE_TTL_MS = 15_000;
const DEFAULT_POSITIVE_ACTIVE_TTL_MS = 30_000;
const DEFAULT_PROBE_TIMEOUT_MS = 5_000;
/**
* 严格校验 SSH Host 别名,拒绝以 `-` 开头或含空白/shell 元字符的输入。
*
* @param {unknown} rawHost
* @returns {string}
*/
export function sanitizeSshHost(rawHost) {
const clean = String(rawHost || '').trim();
if (!clean || clean.startsWith('-') || !SSH_HOST_RE.test(clean)) {
return '';
}
return clean;
}
/**
* 单次远端 POSIX `sh` 探测脚本:
* - 检测远端是否安装 `agy` CLI 与 `usage-monitor` CLI 插件;
* - 若存在,按 mtime 倒序扫描 `antigravity-cli/daemon/hub_*.json` 与 `antigravity/daemon/hub_*.json`,
* 验证 `kill -0 $pid` 存活后输出单行 JSON。
*/
export const REMOTE_CLI_PROBE_COMMAND = [
'sh -c \'',
'has_cli=0; ',
'if command -v agy >/dev/null 2>&1 || [ -x "$HOME/.local/bin/agy" ] || [ -x "$HOME/.gemini/bin/agy" ] || [ -d "$HOME/.gemini/antigravity-cli" ]; then has_cli=1; fi; ',
'has_plugin=0; ',
'if [ -f "$HOME/.gemini/config/plugins/usage-monitor/plugin.json" ] || [ -f "$HOME/.gemini/antigravity-cli/plugins/usage-monitor/plugin.json" ] || grep -qsE "usage-monitor|cli-statusline" "$HOME/.gemini/antigravity-cli/settings.json" 2>/dev/null; then has_plugin=1; fi; ',
'http_port=0; https_port=0; pid=0; csrf=""; ',
'if [ "$has_plugin" = "1" ]; then ',
' for d in "$HOME/.gemini/antigravity-cli/daemon" "$HOME/.gemini/antigravity/daemon"; do ',
' [ -d "$d" ] || continue; ',
' for f in $(ls -1t "$d"/hub_*.json 2>/dev/null); do ',
' [ -f "$f" ] || continue; ',
' p=$(sed -n "s/.*\\\"pid\\\"[[:space:]]*:[[:space:]]*\\([0-9][0-9]*\\).*/\\1/p" "$f" | head -n 1); ',
' if [ -n "$p" ] && kill -0 "$p" 2>/dev/null; then ',
' hp=$(sed -n "s/.*\\\"httpPort\\\"[[:space:]]*:[[:space:]]*\\([0-9][0-9]*\\).*/\\1/p" "$f" | head -n 1); ',
' sp=$(sed -n "s/.*\\\"httpsPort\\\"[[:space:]]*:[[:space:]]*\\([0-9][0-9]*\\).*/\\1/p" "$f" | head -n 1); ',
' tk=$(sed -n "s/.*\\\"csrfToken\\\"[[:space:]]*:[[:space:]]*\\\"\\([^\\\"]*\\)\\\".*/\\1/p" "$f" | head -n 1); ',
' if [ -n "$hp" ] || [ -n "$sp" ]; then ',
' pid="$p"; http_port="${hp:-0}"; https_port="${sp:-0}"; csrf="$tk"; break 2; ',
' fi; ',
' fi; ',
' done; ',
' done; ',
'fi; ',
'printf "{\\"hasCli\\":%s,\\"hasCliPlugin\\":%s,\\"pid\\":%s,\\"httpPort\\":%s,\\"httpsPort\\":%s,\\"csrfToken\\":\\"%s\\"}\\n" ',
'"$([ "$has_cli" = "1" ] && echo true || echo false)" ',
'"$([ "$has_plugin" = "1" ] && echo true || echo false)" ',
'"${pid:-0}" "${http_port:-0}" "${https_port:-0}" "$csrf"',
'\'',
].join('');
/**
* 解析远端 SSH 探测输出的单行 JSON。
*
* @param {string} rawStdout
* @returns {{ hasCli: boolean, hasCliPlugin: boolean, pid: number, httpPort: number, httpsPort: number, csrfToken: string } | null}
*/
export function parseRemoteCliProbeOutput(rawStdout) {
const lines = String(rawStdout || '')
.split(/\r?\n/)
.map((l) => l.trim())
.filter(Boolean);
for (let i = lines.length - 1; i >= 0; i -= 1) {
const line = lines[i];
if (!line.startsWith('{') || !line.endsWith('}')) continue;
try {
const obj = JSON.parse(line);
if (!obj || typeof obj !== 'object') continue;
const toPort = (v) => {
const n = Number(v || 0);
return Number.isInteger(n) && n > 0 && n <= 65535 ? n : 0;
};
const pidNum = Number(obj.pid || 0);
return {
hasCli: obj.hasCli === true,
hasCliPlugin: obj.hasCliPlugin === true,
pid: Number.isInteger(pidNum) && pidNum > 0 ? pidNum : 0,
httpPort: toPort(obj.httpPort),
httpsPort: toPort(obj.httpsPort),
csrfToken: String(obj.csrfToken || '').trim(),
};
} catch {
// 继续尝试前一行
}
}
return null;
}
function defaultAllocateLoopbackPort() {
return new Promise((resolve, reject) => {
const srv = net.createServer();
srv.unref?.();
srv.once('error', reject);
srv.listen(0, '127.0.0.1', () => {
const addr = srv.address();
const port = typeof addr === 'object' && addr ? Number(addr.port || 0) : 0;
srv.close(() => {
if (port > 0) resolve(port);
else reject(new Error('Failed to allocate loopback port'));
});
});
});
}
function defaultWaitForTcpPort(port, timeoutMs = 2500) {
const deadline = Date.now() + Math.max(300, timeoutMs);
return new Promise((resolve) => {
const tryOnce = () => {
if (Date.now() >= deadline) {
resolve(false);
return;
}
const sock = net.createConnection({ host: '127.0.0.1', port });
let done = false;
const finish = (ok) => {
if (done) return;
done = true;
try {
sock.destroy();
} catch {
// 忽略销毁异常
}
if (ok) {
resolve(true);
} else if (Date.now() + 120 < deadline) {
const timer = setTimeout(tryOnce, 120);
timer.unref?.();
} else {
resolve(false);
}
};
sock.setTimeout(350);
sock.once('connect', () => finish(true));
sock.once('timeout', () => finish(false));
sock.once('error', () => finish(false));
};
tryOnce();
});
}
function defaultExecFile(cmd, args, opts) {
return new Promise((resolve, reject) => {
execFile(cmd, args, opts, (err, stdout, stderr) => {
if (err) {
err.stdout = stdout;
err.stderr = stderr;
reject(err);
return;
}
resolve({ stdout: String(stdout || ''), stderr: String(stderr || '') });
});
});
}
/**
* 创建 Remote-SSH 远端 CLI 插件探测器与 SSH 回环隧道管理器。
*
* @param {{
* execFileFn?: (cmd: string, args: string[], opts: object) => Promise<{ stdout: string, stderr?: string }>,
* spawnFn?: typeof spawn,
* allocatePortFn?: () => Promise<number>,
* waitPortReadyFn?: (port: number, timeoutMs?: number) => Promise<boolean>,
* onStateChanged?: () => void,
* negativeTtlMs?: number,
* positiveIdleTtlMs?: number,
* positiveActiveTtlMs?: number,
* probeTimeoutMs?: number,
* }} [options]
*/
export function createRemoteCliBridge(options = {}) {
const execFileFn = options.execFileFn || defaultExecFile;
const spawnFn = options.spawnFn || spawn;
const allocatePortFn = options.allocatePortFn || defaultAllocateLoopbackPort;
const waitPortReadyFn = options.waitPortReadyFn || defaultWaitForTcpPort;
const onStateChanged = typeof options.onStateChanged === 'function' ? options.onStateChanged : null;
const negativeTtlMs = Math.max(5_000, Number(options.negativeTtlMs) || DEFAULT_NEGATIVE_TTL_MS);
const positiveIdleTtlMs = Math.max(
3_000,
Number(options.positiveIdleTtlMs) || DEFAULT_POSITIVE_IDLE_TTL_MS
);
const positiveActiveTtlMs = Math.max(
5_000,
Number(options.positiveActiveTtlMs) || DEFAULT_POSITIVE_ACTIVE_TTL_MS
);
const probeTimeoutMs = Math.max(1_000, Number(options.probeTimeoutMs) || DEFAULT_PROBE_TIMEOUT_MS);
/** @type {Map<string, any>} */
const cacheByHost = new Map();
/** @type {Map<string, Promise<any>>} */
const inFlightProbes = new Map();
/** @type {Map<string, { proc: any, localPort: number, remotePort: number, protocol: string, ready: boolean, closing: boolean }>} */
const tunnelsByHost = new Map();
let stopped = false;
function killTunnel(host) {
const entry = tunnelsByHost.get(host);
if (!entry) return;
entry.closing = true;
tunnelsByHost.delete(host);
try {
entry.proc?.kill?.('SIGTERM');
} catch {
// 忽略子进程清理异常
}
}
async function ensureTunnelForHost(host, remotePort, protocol) {
if (stopped || !host || !remotePort) return null;
const existing = tunnelsByHost.get(host);
if (existing && !existing.closing && existing.remotePort === remotePort && existing.protocol === protocol) {
return existing;
}
if (existing) {
killTunnel(host);
}
let localPort = 0;
try {
localPort = await allocatePortFn();
} catch {
return null;
}
if (stopped || !localPort) return null;
let proc = null;
try {
proc = spawnFn(
'ssh',
[
'-N',
'-o',
'BatchMode=yes',
'-o',
'ExitOnForwardFailure=yes',
'-o',
'ConnectTimeout=5',
'-o',
'ServerAliveInterval=15',
'-o',
'ServerAliveCountMax=3',
'-L',
`127.0.0.1:${localPort}:127.0.0.1:${remotePort}`,
'--',
host,
],
{ stdio: 'ignore' }
);
proc?.unref?.();
} catch {
return null;
}
const tunnelEntry = {
proc,
localPort,
remotePort,
protocol,
ready: false,
closing: false,
};
tunnelsByHost.set(host, tunnelEntry);
const onTunnelExit = () => {
const cur = tunnelsByHost.get(host);
if (cur === tunnelEntry) {
tunnelsByHost.delete(host);
const cached = cacheByHost.get(host);
if (cached) {
cached.localPort = 0;
cached.tunnelReady = false;
// 隧道异常断开后缩短下次重探时间,尽快重连
cached.expiresAtMs = Math.min(cached.expiresAtMs || 0, Date.now() + 2000);
}
if (!tunnelEntry.closing && !stopped) {
onStateChanged?.();
}
}
};
proc?.once?.('exit', onTunnelExit);
proc?.once?.('error', onTunnelExit);
const isReady = await waitPortReadyFn(localPort, 2500).catch(() => false);
if (stopped || tunnelEntry.closing || tunnelsByHost.get(host) !== tunnelEntry) {
return null;
}
if (!isReady) {
killTunnel(host);
return null;
}
tunnelEntry.ready = true;
return tunnelEntry;
}
function scheduleProbe(host) {
if (stopped || !host) return null;
const existingPromise = inFlightProbes.get(host);
if (existingPromise) return existingPromise;
const prev = cacheByHost.get(host) || null;
const promise = (async () => {
try {
const res = await execFileFn(
'ssh',
[
'-o',
'BatchMode=yes',
'-o',
'ConnectTimeout=3',
'-o',
'NumberOfPasswordPrompts=0',
'--',
host,
REMOTE_CLI_PROBE_COMMAND,
],
{ timeout: probeTimeoutMs, maxBuffer: 64 * 1024 }
);
const parsed = parseRemoteCliProbeOutput(res?.stdout || '');
if (!parsed) {
killTunnel(host);
const next = {
host,
status: 'error',
hasCli: false,
hasCliPlugin: false,
remotePort: 0,
protocol: 'http',
csrfToken: '',
localPort: 0,
tunnelReady: false,
updatedAtMs: Date.now(),
expiresAtMs: Date.now() + negativeTtlMs,
};
cacheByHost.set(host, next);
return next;
}
if (!parsed.hasCliPlugin) {
killTunnel(host);
const next = {
host,
status: 'absent',
hasCli: parsed.hasCli,
hasCliPlugin: false,
remotePort: 0,
protocol: 'http',
csrfToken: '',
localPort: 0,
tunnelReady: false,
updatedAtMs: Date.now(),
expiresAtMs: Date.now() + negativeTtlMs,
};
cacheByHost.set(host, next);
if (prev?.hasCliPlugin) onStateChanged?.();
return next;
}
const remotePort = parsed.httpPort || parsed.httpsPort || 0;
const protocol = parsed.httpPort ? 'http' : 'https';
let localPort = 0;
let tunnelReady = false;
if (remotePort > 0 && parsed.csrfToken) {
const tun = await ensureTunnelForHost(host, remotePort, protocol);
if (tun && tun.ready) {
localPort = tun.localPort;
tunnelReady = true;
}
} else {
killTunnel(host);
}
const next = {
host,
status: 'ready',
hasCli: parsed.hasCli,
hasCliPlugin: true,
remotePort,
protocol,
csrfToken: parsed.csrfToken,
localPort,
tunnelReady,
updatedAtMs: Date.now(),
expiresAtMs: Date.now() + (tunnelReady ? positiveActiveTtlMs : positiveIdleTtlMs),
};
cacheByHost.set(host, next);
const changed =
!prev ||
prev.hasCliPlugin !== next.hasCliPlugin ||
prev.localPort !== next.localPort ||
prev.csrfToken !== next.csrfToken ||
prev.tunnelReady !== next.tunnelReady;
if (changed && !stopped) {
onStateChanged?.();
}
return next;
} catch {
// SSH 不可达或需要交互认证时静默缓存负结果,不弹窗不刷屏
const existingTun = tunnelsByHost.get(host);
if (existingTun && existingTun.ready && prev?.hasCliPlugin) {
// 已有存活隧道时保留状态并稍后重试
prev.expiresAtMs = Date.now() + positiveIdleTtlMs;
return prev;
}
killTunnel(host);
const next = {
host,
status: 'error',
hasCli: false,
hasCliPlugin: false,
remotePort: 0,
protocol: 'http',
csrfToken: '',
localPort: 0,
tunnelReady: false,
updatedAtMs: Date.now(),
expiresAtMs: Date.now() + negativeTtlMs,
};
cacheByHost.set(host, next);
return next;
} finally {
inFlightProbes.delete(host);
}
})();
inFlightProbes.set(host, promise);
return promise;
}
/**
* 同步获取某 SSH 主机的远端 CLI 插件状态;若缓存过期则在后台异步触发单次探测。
*
* @param {string} rawHost
* @returns {{
* host: string,
* status: string,
* hasCli: boolean,
* hasCliPlugin: boolean,
* remotePort: number,
* protocol: string,
* csrfToken: string,
* localPort: number,
* tunnelReady: boolean,
* }}
*/
function getOrScheduleHost(rawHost) {
const host = sanitizeSshHost(rawHost);
if (!host) {
return {
host: '',
status: 'invalid',
hasCli: false,
hasCliPlugin: false,
remotePort: 0,
protocol: 'http',
csrfToken: '',
localPort: 0,
tunnelReady: false,
};
}
const now = Date.now();
const cached = cacheByHost.get(host);
if (!cached || now >= Number(cached.expiresAtMs || 0)) {
void scheduleProbe(host);
}
if (cached) {
const tun = tunnelsByHost.get(host);
return {
...cached,
localPort: tun && tun.ready ? tun.localPort : 0,
tunnelReady: Boolean(tun && tun.ready),
};
}
return {
host,
status: 'pending',
hasCli: false,
hasCliPlugin: false,
remotePort: 0,
protocol: 'http',
csrfToken: '',
localPort: 0,
tunnelReady: false,
};
}
/**
* 清理已不再活跃(窗口已关闭或已改用 VS Code 扩展)的 SSH 隧道。
*
* @param {Set<string>} activeHosts
*/
function pruneInactiveHosts(activeHosts) {
const keep = activeHosts instanceof Set ? activeHosts : new Set();
for (const host of Array.from(tunnelsByHost.keys())) {
if (!keep.has(host)) {
killTunnel(host);
}
}
}
function stopAll() {
stopped = true;
for (const host of Array.from(tunnelsByHost.keys())) {
killTunnel(host);
}
cacheByHost.clear();
inFlightProbes.clear();
}
return {
getOrScheduleHost,
probeHostNow: (rawHost) => {
const host = sanitizeSshHost(rawHost);
return host ? scheduleProbe(host) : Promise.resolve(null);
},
pruneInactiveHosts,
stopAll,
getActiveTunnelCount: () => tunnelsByHost.size,
};
}
@@ -149,6 +149,7 @@ export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({
pluginUpdateMode: 'manual',
autoUpdatePlugin: false,
windowMountMode: 'dual',
vsCodeMountMode: 'composer',
enableWindowOverlay: true,
popoverWidthMode: 'auto',
popoverWidth: DEFAULT_POPOVER_WIDTH,
@@ -233,6 +234,7 @@ export function normalizeFullSettings(rawInput) {
pluginUpdateMode,
autoUpdatePlugin: pluginUpdateMode === 'auto',
windowMountMode,
vsCodeMountMode: safeRaw.vsCodeMountMode === 'dual' ? 'dual' : 'composer',
enableWindowOverlay: windowMountMode !== 'sidebar',
popoverWidthMode: normalizePopoverWidthMode(safeRaw.popoverWidthMode),
popoverWidth: normalizePopoverWidth(safeRaw.popoverWidth),
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -4,11 +4,11 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>用量监控</title>
<link rel="stylesheet" href="/styles.css?v=1795584300571">
<link rel="stylesheet" href="/styles.css?v=1795685407987">
<script src="/preload.js"></script>
</head>
<body>
<div id="app-root"></div>
<script src="/app.js?v=1795584300571"></script>
<script src="/app.js?v=1795685407987"></script>
</body>
</html>
@@ -54,3 +54,17 @@ export const BRIDGE_API_PATHS = Object.freeze(BRIDGE_API_ROUTE_DEFS.map((r) => r
export function readInjectedWindowBridge() {
return typeof window === 'undefined' ? undefined : window[WINDOW_BRIDGE_KEY];
}
export function isVsCodeExtensionHost() {
const bridge = readInjectedWindowBridge();
if (bridge?.isVsCodeHost === true) return true;
if (typeof window !== 'undefined') {
const search = String(window.location?.search || '');
if (/[?&]extensionVariant=vs-code/i.test(search)) return true;
const href = String(window.location?.href || '');
if (/(?:Visual(?:%20|\s)Studio(?:%20|\s)Code|Code(?:\s|%20)-?(?:\s|%20)Insiders)/i.test(href)) {
return true;
}
}
return false;
}
@@ -14,6 +14,7 @@ import {
WINDOW_BRIDGE_KEY,
WINDOW_OVERLAY_KEY,
WINDOW_OVERLAY_METHODS,
isVsCodeExtensionHost,
readInjectedWindowBridge,
} from '../../../shared/window-bridge-protocol.mjs';
import { App } from '../../App.js';
@@ -1723,10 +1724,17 @@ export function mountWindowOverlay() {
}
}
let lastAppliedMountMode = normalizeClientWindowMountMode(
telemetryStore.getState().telemetry?.settings?.windowMountMode,
telemetryStore.getState().telemetry?.settings?.enableWindowOverlay
);
const resolveShellMountMode = (settingsObj) => {
if (isVsCodeExtensionHost()) {
return settingsObj?.vsCodeMountMode === 'dual' ? 'dual' : 'composer';
}
return normalizeClientWindowMountMode(
settingsObj?.windowMountMode,
settingsObj?.enableWindowOverlay
);
};
let lastAppliedMountMode = resolveShellMountMode(telemetryStore.getState().telemetry?.settings);
const unsubStore = telemetryStore.subscribe(
(st) => ({
@@ -1736,11 +1744,11 @@ export function mountWindowOverlay() {
selectedConversationId: st.selectedConversationId,
}),
(slice) => {
const nextMountMode = normalizeClientWindowMountMode(
slice.telemetry?.settings?.windowMountMode,
slice.telemetry?.settings?.enableWindowOverlay
);
if (slice.telemetry?.settings?.enableWindowOverlay === false || nextMountMode === 'sidebar') {
const nextMountMode = resolveShellMountMode(slice.telemetry?.settings);
if (
!isVsCodeExtensionHost() &&
(slice.telemetry?.settings?.enableWindowOverlay === false || nextMountMode === 'sidebar')
) {
if (popoverOpen) setPopoverOpen(false);
if (multiOpen) setMultiOpen(false);
} else if (nextMountMode !== lastAppliedMountMode) {
@@ -1814,7 +1822,7 @@ export function mountWindowOverlay() {
const shouldPreserveSameSession =
!currentRouteId || isSameActiveRoot || isChildOfActiveRoot;
const nextSelectedId =
currentRouteId && st.selectedConversationId && st.selectedConversationId !== currentRouteId
st.selectedConversationId && st.selectedConversationId !== currentRouteId
? ''
: st.selectedConversationId;
if (!shouldPreserveSameSession) {
@@ -4,7 +4,10 @@
* extracted from WindowOverlayShell.js.
*/
import { readInjectedWindowBridge } from '../../../shared/window-bridge-protocol.mjs';
import {
isVsCodeExtensionHost,
readInjectedWindowBridge,
} from '../../../shared/window-bridge-protocol.mjs';
import {
extractHostRouteCascadeId,
normalizeClientWindowMountMode,
@@ -781,12 +784,27 @@ export function isIdeExtensionChatFrame() {
export function resolveActiveDockTarget(options = undefined) {
const settings = telemetryStore.getState().telemetry?.settings;
const rawMode =
settings?.windowMountMode ??
readInjectedWindowBridge()?.mountMode;
const bridge = readInjectedWindowBridge();
const isVsCode = isVsCodeExtensionHost();
const forceTopbar = bridge?.forceTopbarMode === true;
const rawMode = forceTopbar
? 'dual'
: isVsCode
? settings?.vsCodeMountMode === 'dual'
? 'dual'
: bridge?.mountMode === 'dual' && settings?.vsCodeMountMode === undefined
? 'dual'
: 'composer'
: settings?.windowMountMode ?? bridge?.mountMode;
const mountMode =
options?.mountMode ||
normalizeClientWindowMountMode(rawMode, settings?.enableWindowOverlay);
(forceTopbar
? 'dual'
: isVsCode
? rawMode === 'dual'
? 'dual'
: 'composer'
: normalizeClientWindowMountMode(rawMode, settings?.enableWindowOverlay));
if (isIdeExtensionChatFrame()) {
if (mountMode !== 'composer') return null;
return findHostComposerAutoTarget(
+2
View File
@@ -727,6 +727,8 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'settings.str.mountDual': 'Dual Mount (Titlebar + Sidebar)',
'settings.str.mountComposer': 'Composer Mount (Input Box + Sidebar)',
'settings.str.mountSidebar': 'Sidebar Only',
'settings.str.mountVsCodeComposer': 'Input Box',
'settings.str.mountVsCodeTopbar': 'Top Bar',
'settings.bridge.restartTitle': 'Launch Flag Auto-Configured — Restart Once to Activate',
'settings.bridge.ctxRestartTitle': 'Launch Flag Auto-Configured — Restart Once for Context Override',
'settings.bridge.restartBody': 'Automatically added --remote-debugging-port=0 to your shortcuts, startup entries, and protocol handlers (subsequent shortcut launches mount automatically). Click below to close background processes and relaunch now.',
+2
View File
@@ -727,6 +727,8 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'settings.str.mountDual': '双栖挂载 (顶部栏 + 侧边栏)',
'settings.str.mountComposer': '输入框挂载 (输入框 + 侧边栏)',
'settings.str.mountSidebar': '仅侧边栏',
'settings.str.mountVsCodeComposer': '输入框',
'settings.str.mountVsCodeTopbar': '顶部栏',
'settings.bridge.restartTitle': '已自动补齐启动参数,重启一次即可启用悬浮胶囊',
'settings.bridge.ctxRestartTitle': '已自动补齐启动参数,重启一次即可激活上下文覆写',
'settings.bridge.restartBody': '已自动为快捷方式、自启项及协议关联写入 --remote-debugging-port=0(后续通过常规快捷方式打开均自动生效)。点击下方按钮即可退出后台进程并立即生效。',
+11 -1
View File
@@ -190,6 +190,7 @@ const TELEMETRY_RECOMPUTE_SETTING_KEYS = new Set([
'weeklyTokenBudget',
'weeklyCostBudget',
'windowMountMode',
'vsCodeMountMode',
'enableWindowOverlay',
]);
@@ -2275,7 +2276,16 @@ export function startAsyncTelemetryLoop(intervalMs = 2000) {
const resolveNextDelay = () => {
if (isWindowOverlayMode() && typeof document !== 'undefined' && document.hidden) {
return Math.max(loopIntervalMs, 8000);
return Math.max(loopIntervalMs, 10000);
}
if (isWindowOverlayMode() && readInjectedWindowBridge()?.isRemoteEndpoint) {
const tel = telemetryStore.getState().telemetry;
const hasRunning =
(Array.isArray(tel?.runningConversations) && tel.runningConversations.length > 0) ||
tel?.activeConversation?.status === 'CASCADE_RUN_STATUS_RUNNING';
if (!hasRunning) {
return Math.max(loopIntervalMs, 6000);
}
}
return loopIntervalMs;
};
@@ -51,6 +51,7 @@ import {
triggerCliStatusLineAction,
} from '../../store/telemetryStore.js';
import { getVisibleMonitorView, uiStore } from '../../store/uiStore.js';
import { isVsCodeExtensionHost } from '../../../shared/window-bridge-protocol.mjs';
import { BridgeStatusNotice } from '../../components/settings/BridgeStatusNotice.js';
import { CollapsibleSection } from '../../components/settings/CollapsibleSection.js';
import { EditableSlotList } from '../../components/settings/EditableSlotList.js';
@@ -78,6 +79,12 @@ function normalizeStructureTabKey(raw) {
}
function getMountModeOptions() {
if (isVsCodeExtensionHost()) {
return [
{ value: 'composer', label: t('settings.str.mountVsCodeComposer') },
{ value: 'dual', label: t('settings.str.mountVsCodeTopbar') },
];
}
return [
{ value: 'dual', label: t('settings.str.mountDual') },
{ value: 'composer', label: t('settings.str.mountComposer') },
@@ -457,6 +464,16 @@ export const SettingsStructureTab = defineComponent({
icon: 'dock',
options: getMountModeOptions(),
onUpdateModelValue: (val) => {
if (isVsCodeExtensionHost()) {
const nextVsMode = val === 'dual' ? 'dual' : 'composer';
draftWindowMountMode = nextVsMode;
syncMountSectionMeta();
props.onLayoutChange?.();
void persistStructurePatch(mountSection, {
vsCodeMountMode: nextVsMode,
});
return;
}
const nextMode = normalizeClientWindowMountMode(val);
draftWindowMountMode = nextMode;
syncMountSectionMeta();
@@ -646,7 +663,8 @@ export const SettingsStructureTab = defineComponent({
title: t('settings.str.mountSection'),
badgeText: t('settings.str.mountBadge', { count: draftTopbarSlots.length }),
onReset: () => {
draftWindowMountMode = 'dual';
const vsCodeHost = isVsCodeExtensionHost();
draftWindowMountMode = vsCodeHost ? 'composer' : 'dual';
draftPopoverWidthMode = 'auto';
draftPopoverWidth = DEFAULT_CLIENT_POPOVER_WIDTH;
popoverWidthStepper.setProps({ modelValue: DEFAULT_CLIENT_POPOVER_WIDTH });
@@ -661,8 +679,9 @@ export const SettingsStructureTab = defineComponent({
void persistStructurePatch(
mountSection,
{
windowMountMode: 'dual',
enableWindowOverlay: true,
...(vsCodeHost
? { vsCodeMountMode: 'composer' }
: { windowMountMode: 'dual', enableWindowOverlay: true }),
popoverWidthMode: 'auto',
popoverWidth: DEFAULT_CLIENT_POPOVER_WIDTH,
enableCliStatusLine: true,
@@ -1447,10 +1466,14 @@ export const SettingsStructureTab = defineComponent({
if (hostPlatform) latestHostPlatform = hostPlatform;
if (cliStatusLine !== undefined) latestCliStatusLine = cliStatusLine;
if (quotas !== undefined) latestQuotas = quotas;
draftWindowMountMode = normalizeClientWindowMountMode(
settings.windowMountMode,
settings.enableWindowOverlay
);
draftWindowMountMode = isVsCodeExtensionHost()
? settings.vsCodeMountMode === 'dual'
? 'dual'
: 'composer'
: normalizeClientWindowMountMode(
settings.windowMountMode,
settings.enableWindowOverlay
);
draftPopoverWidthMode = normalizeClientPopoverWidthMode(settings.popoverWidthMode);
draftPopoverWidth = normalizeClientPopoverWidth(settings.popoverWidth);
draftEnableCliStatusLine = settings.enableCliStatusLine !== false;
@@ -0,0 +1,363 @@
/**
* @fileoverview VS Code 官方扩展、Remote-SSH 端点隔离与远端 `agy` CLI 插件适配回归测试。
*/
import assert from 'node:assert/strict';
import { EventEmitter } from 'node:events';
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import http from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import test from 'node:test';
import { registerRemoteEndpoint, setRemoteWindowRpcInvoker } from '../backend/endpoint-registry.mjs';
import { callLsRpc } from '../backend/ls-rpc.mjs';
import {
createRemoteCliBridge,
parseRemoteCliProbeOutput,
sanitizeSshHost,
} from '../backend/remote-cli-bridge.mjs';
import { normalizeFullSettings } from '../backend/settings-schema.mjs';
import {
createWindowBridgeController,
hasLocalAgyCli,
hasLocalAgyCliPlugin,
} from '../backend/window-bridge.mjs';
import { isVsCodeExtensionHost } from '../shared/window-bridge-protocol.mjs';
import { I18N_MESSAGES_EN_US } from '../src/i18n/en-US.js';
import { I18N_MESSAGES_ZH_CN } from '../src/i18n/zh-CN.js';
test('VS Code settings schema defaults vsCodeMountMode to composer, rejects sidebar, and exposes Top Bar / Input Box labels', () => {
const def = normalizeFullSettings({});
assert.equal(def.vsCodeMountMode, 'composer');
assert.equal(def.windowMountMode, 'dual');
assert.equal(normalizeFullSettings({ vsCodeMountMode: 'sidebar' }).vsCodeMountMode, 'composer');
assert.equal(normalizeFullSettings({ vsCodeMountMode: 'dual' }).vsCodeMountMode, 'dual');
assert.equal(I18N_MESSAGES_ZH_CN['settings.str.mountVsCodeComposer'], '输入框');
assert.equal(I18N_MESSAGES_ZH_CN['settings.str.mountVsCodeTopbar'], '顶部栏');
assert.equal(I18N_MESSAGES_EN_US['settings.str.mountVsCodeComposer'], 'Input Box');
assert.equal(I18N_MESSAGES_EN_US['settings.str.mountVsCodeTopbar'], 'Top Bar');
const prevWindow = globalThis.window;
try {
globalThis.window = { __AGUsageMonitorBridge: { isVsCodeHost: true } };
assert.equal(isVsCodeExtensionHost(), true);
globalThis.window = { __AGUsageMonitorBridge: { isVsCodeHost: false } };
assert.equal(isVsCodeExtensionHost(), false);
} finally {
if (prevWindow === undefined) delete globalThis.window;
else globalThis.window = prevWindow;
}
});
test('hasLocalAgyCliPlugin requires both agy CLI and usage-monitor CLI plugin', () => {
const fakeOnlyCli = {
existsFn: (p) => String(p).endsWith('antigravity-cli'),
readFileFn: () => '{}',
};
assert.equal(hasLocalAgyCli({}, '/fake-home', fakeOnlyCli), true);
assert.equal(hasLocalAgyCliPlugin({}, '/fake-home', fakeOnlyCli), false);
const fakeCliWithPlugin = {
existsFn: (p) =>
String(p).endsWith('antigravity-cli') ||
String(p).endsWith(join('usage-monitor', 'plugin.json')),
readFileFn: () => '{}',
};
assert.equal(hasLocalAgyCliPlugin({}, '/fake-home', fakeCliWithPlugin), true);
});
test('remote-cli-bridge validates SSH hostnames, probes remote CLI plugin, manages tunnels, and prunes cleanly', async () => {
assert.equal(sanitizeSshHost('gpu-node'), 'gpu-node');
assert.equal(sanitizeSshHost('user@10.0.0.8'), 'user@10.0.0.8');
assert.equal(sanitizeSshHost('-oProxyCommand=bad'), '');
assert.equal(sanitizeSshHost('bad host; rm -rf /'), '');
assert.deepEqual(
parseRemoteCliProbeOutput(
'banner line\n{"hasCli":true,"hasCliPlugin":true,"pid":4321,"httpPort":51111,"httpsPort":51112,"csrfToken":"tok-cli"}\n'
),
{
hasCli: true,
hasCliPlugin: true,
pid: 4321,
httpPort: 51111,
httpsPort: 51112,
csrfToken: 'tok-cli',
}
);
const spawned = [];
let changeEvents = 0;
const cliBridge = createRemoteCliBridge({
execFileFn: async (_cmd, args) => {
const host = args[args.length - 2];
if (host === 'cli-box') {
return {
stdout:
'{"hasCli":true,"hasCliPlugin":true,"pid":999,"httpPort":54001,"httpsPort":54002,"csrfToken":"cli-csrf"}\n',
};
}
return {
stdout:
'{"hasCli":false,"hasCliPlugin":false,"pid":0,"httpPort":0,"httpsPort":0,"csrfToken":""}\n',
};
},
spawnFn: (_cmd, args) => {
const proc = new EventEmitter();
proc.killed = false;
proc.args = args;
proc.kill = () => {
proc.killed = true;
proc.emit('exit', 0);
};
proc.unref = () => {};
spawned.push(proc);
return proc;
},
allocatePortFn: async () => 61234,
waitPortReadyFn: async () => true,
onStateChanged: () => {
changeEvents += 1;
},
});
const cliState = await cliBridge.probeHostNow('cli-box');
const plainState = await cliBridge.probeHostNow('plain-box');
assert.equal(cliState.hasCliPlugin, true);
assert.equal(cliState.tunnelReady, true);
assert.equal(cliState.localPort, 61234);
assert.equal(cliState.csrfToken, 'cli-csrf');
assert.equal(plainState.hasCliPlugin, false);
assert.equal(spawned.length, 1);
assert.ok(changeEvents >= 1);
cliBridge.pruneInactiveHosts(new Set());
assert.equal(spawned[0].killed, true);
assert.equal(cliBridge.getActiveTunnelCount(), 0);
cliBridge.stopAll();
});
test('VS Code window gating: skips plain SSH, mounts remote/local CLI-only on Top Bar, mounts VS Code ext in Input Box even when Desktop is sidebar', async () => {
const tmpHome = mkdtempSync(join(tmpdir(), 'um-vscode-support-'));
mkdirSync(join(tmpHome, '.gemini', 'antigravity-cli'), { recursive: true });
mkdirSync(join(tmpHome, '.gemini', 'config', 'plugins', 'usage-monitor'), { recursive: true });
writeFileSync(join(tmpHome, '.gemini', 'config', 'plugins', 'usage-monitor', 'plugin.json'), '{}');
const spawned = [];
const cliBridge = createRemoteCliBridge({
execFileFn: async (_cmd, args) => {
const host = args[args.length - 2];
if (host === 'cli-box') {
return {
stdout:
'{"hasCli":true,"hasCliPlugin":true,"pid":888,"httpPort":54100,"httpsPort":0,"csrfToken":"cli-token"}\n',
};
}
return {
stdout:
'{"hasCli":false,"hasCliPlugin":false,"pid":0,"httpPort":0,"httpsPort":0,"csrfToken":""}\n',
};
},
spawnFn: () => {
const proc = new EventEmitter();
proc.killed = false;
proc.kill = () => {
proc.killed = true;
proc.emit('exit', 0);
};
proc.unref = () => {};
spawned.push(proc);
return proc;
},
allocatePortFn: async () => 61235,
waitPortReadyFn: async () => true,
});
await cliBridge.probeHostNow('cli-box');
await cliBridge.probeHostNow('plain-box');
const targets = [
{
id: 'page-ssh-plain',
type: 'page',
title: 'a.py — repo [SSH: plain-box]',
url: 'vscode-file://vscode-app/Applications/Visual%20Studio%20Code.app/Contents/Resources/app/out/vs/code/electron-browser/workbench/workbench.html',
webSocketDebuggerUrl: 'ws://127.0.0.1:9333/devtools/page/ssh-plain',
},
{
id: 'page-ssh-cli',
type: 'page',
title: 'b.py — repo [SSH: cli-box]',
url: 'vscode-file://vscode-app/Applications/Visual%20Studio%20Code.app/Contents/Resources/app/out/vs/code/electron-browser/workbench/workbench.html',
webSocketDebuggerUrl: 'ws://127.0.0.1:9333/devtools/page/ssh-cli',
},
{
id: 'page-ssh-ext',
type: 'page',
title: 'c.py — repo [SSH: ext-box]',
url: 'vscode-file://vscode-app/Applications/Visual%20Studio%20Code.app/Contents/Resources/app/out/vs/code/electron-browser/workbench/workbench.html',
webSocketDebuggerUrl: 'ws://127.0.0.1:9333/devtools/page/ssh-ext',
},
{
id: 'wv-ssh-ext',
type: 'iframe',
parentId: 'page-ssh-ext',
url: 'vscode-webview://1/?extensionId=google.google-antigravity&remoteAuthority=ssh-remote%2Bext-box&purpose=webviewView',
webSocketDebuggerUrl: 'ws://127.0.0.1:9333/devtools/page/wv-ext',
},
{
id: 'chat-ssh-ext',
type: 'iframe',
parentId: 'wv-ssh-ext',
url: 'http://127.0.0.1:53000/c/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee?extensionView=true&extensionVariant=vs-code&remoteKind=ssh-remote',
webSocketDebuggerUrl: 'ws://127.0.0.1:9333/devtools/page/chat-ext',
},
{
id: 'page-local-cli-only',
type: 'page',
title: 'local.py — proj',
url: 'vscode-file://vscode-app/Applications/Visual%20Studio%20Code.app/Contents/Resources/app/out/vs/code/electron-browser/workbench/workbench.html',
webSocketDebuggerUrl: 'ws://127.0.0.1:9333/devtools/page/local-cli',
},
];
const cdpSrv = http.createServer((_req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(targets));
});
await new Promise((r) => cdpSrv.listen(0, '127.0.0.1', r));
const cdpPort = cdpSrv.address().port;
const evaluated = [];
class FakeWS {
constructor(url) {
this.url = url;
this._listeners = {};
queueMicrotask(() => this._emit('open', {}));
}
addEventListener(ev, fn) {
(this._listeners[ev] ||= []).push(fn);
}
_emit(ev, data) {
for (const fn of this._listeners[ev] || []) fn(data);
}
send(raw) {
const msg = JSON.parse(raw);
const expr = String(msg?.params?.expression || '');
const isInject = expr.includes('__MOCK_APP_JS__');
evaluated.push({
wsUrl: this.url,
isInject,
mountDual: expr.includes('"mountMode":"dual"'),
mountComposer: expr.includes('"mountMode":"composer"'),
forceTopbar: expr.includes('"forceTopbarMode":true'),
isRemote: expr.includes('"isRemoteEndpoint":true'),
cliLabel: expr.includes('"endpointLabel":"cli-box (CLI)"'),
});
let val = false;
if (expr.includes('__APP_CONFIG__')) {
val = {
href: 'http://127.0.0.1:53000/c/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',
origin: 'http://127.0.0.1:53000',
port: 53000,
csrfToken: 'tok-ext',
};
} else if (isInject) {
val = {
alive: true,
dockKind: expr.includes('"mountMode":"composer"') ? 'composer' : 'ide-titlebar',
visible: true,
};
}
queueMicrotask(() =>
this._emit('message', {
data: JSON.stringify({ id: msg.id, result: { result: { value: val } } }),
})
);
}
close() {}
}
const bridge = createWindowBridgeController({
env: { ANTIGRAVITY_DEVTOOLS_PORT: String(cdpPort) },
homeDir: tmpHome,
remoteCliBridge: cliBridge,
getSettingsFn: () => ({
windowMountMode: 'sidebar',
enableWindowOverlay: false,
vsCodeMountMode: 'composer',
}),
handleApiRequest: async () => ({ status: 200, body: '{}' }),
getBundleVersionFn: () => 'test-vscode-v1',
readAssetFn: async (p) => (String(p).endsWith('app.js') ? '/* __MOCK_APP_JS__ */' : '/* css */'),
WebSocketImpl: FakeWS,
getLocalHubPortsFn: () => ({ allPorts: new Set(), csrfTokens: new Set() }),
autoConfigureIdeArgv: false,
pollIntervalMs: 60000,
});
try {
await bridge.syncAllWindows();
assert.equal(
evaluated.filter((e) => e.wsUrl.includes('ssh-plain') && e.isInject).length,
0
);
const sshCliInj = evaluated.filter((e) => e.wsUrl.includes('ssh-cli') && e.isInject);
assert.equal(sshCliInj.length, 1);
assert.equal(sshCliInj[0].mountDual, true);
assert.equal(sshCliInj[0].forceTopbar, true);
assert.equal(sshCliInj[0].isRemote, true);
assert.equal(sshCliInj[0].cliLabel, true);
const sshExtChatInj = evaluated.filter((e) => e.wsUrl.includes('chat-ext') && e.isInject);
assert.equal(sshExtChatInj.length, 1);
assert.equal(sshExtChatInj[0].mountComposer, true);
assert.equal(
evaluated.filter((e) => e.wsUrl.includes('ssh-ext') && e.isInject).length,
0
);
const localCliInj = evaluated.filter((e) => e.wsUrl.includes('local-cli') && e.isInject);
assert.equal(localCliInj.length, 1);
assert.equal(localCliInj[0].mountDual, true);
assert.equal(localCliInj[0].forceTopbar, true);
} finally {
await bridge.stop();
cdpSrv.close();
rmSync(tmpHome, { recursive: true, force: true });
}
assert.equal(spawned[0].killed, true);
});
test('tier1Only remote CLI endpoints never invoke Tier-2 CDP fallback or trip Tier-2 cooldown', async () => {
let tier2Called = false;
setRemoteWindowRpcInvoker(async () => {
tier2Called = true;
return {};
});
try {
const ep = registerRemoteEndpoint({
origin: 'http://127.0.0.1:1',
baseUrl: 'http://127.0.0.1:1',
csrfToken: 'x',
stableHostKey: 'ssh-cli:tier1only-test',
tier1Only: true,
});
await assert.rejects(() => callLsRpc('GetUserStatus', {}, 1000, ep));
assert.equal(tier2Called, false);
assert.equal(ep.preferTier2UntilMs, 0);
} finally {
setRemoteWindowRpcInvoker(null);
}
});
test('compiled app.js bundle contains VS Code host labels and forceTopbarMode support', () => {
const appJs = readFileSync(new URL('../app.js', import.meta.url), 'utf8');
assert.ok(appJs.includes('mountVsCodeComposer'));
assert.ok(appJs.includes('mountVsCodeTopbar'));
assert.ok(appJs.includes('isVsCodeExtensionHost'));
assert.ok(appJs.includes('forceTopbarMode'));
});