From 13b84bfa8648fd98f9012a8a20cb21694f21477b Mon Sep 17 00:00:00 2001 From: yangwolves Date: Thu, 26 Nov 2026 17:40:15 +0800 Subject: [PATCH] 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 --- README.md | 10 +- README.zh-CN.md | 10 +- sidecars/panel/app.js | 120 ++- sidecars/panel/backend/api-actions.mjs | 6 +- sidecars/panel/backend/endpoint-registry.mjs | 2 + sidecars/panel/backend/ls-rpc.mjs | 13 +- sidecars/panel/backend/remote-cli-bridge.mjs | 542 ++++++++++ sidecars/panel/backend/settings-schema.mjs | 2 + sidecars/panel/backend/window-bridge.mjs | 928 ++++++++++++++++-- sidecars/panel/index.html | 4 +- .../panel/shared/window-bridge-protocol.mjs | 14 + .../components/layout/WindowOverlayShell.js | 28 +- .../components/layout/overlayHostAnchors.js | 28 +- sidecars/panel/src/i18n/en-US.js | 2 + sidecars/panel/src/i18n/zh-CN.js | 2 + sidecars/panel/src/store/telemetryStore.js | 12 +- .../views/settings/SettingsStructureTab.js | 37 +- .../test/vscode-extension-support.test.mjs | 363 +++++++ 18 files changed, 1953 insertions(+), 170 deletions(-) create mode 100644 sidecars/panel/backend/remote-cli-bridge.mjs create mode 100644 sidecars/panel/test/vscode-extension-support.test.mjs diff --git a/README.md b/README.md index 495a55b..265eb8f 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ # Antigravity Usage & Speed Monitor -Local usage, speed, context, and quota monitor for Google Antigravity 2.0, Antigravity IDE, and Antigravity CLI, with no external npm dependencies. +Local usage, speed, context, and quota monitor for Google Antigravity 2.0, Antigravity IDE, VS Code (official extension), and Antigravity CLI, with no external npm dependencies. [![Release](https://img.shields.io/github/v/release/yuhuan-dev/antigravity-usage-monitor?style=flat-square&color=2A5E76&label=release)](https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest) [![Downloads](https://img.shields.io/github/downloads/yuhuan-dev/antigravity-usage-monitor/total?style=flat-square&color=0ea5e9)](https://github.com/yuhuan-dev/antigravity-usage-monitor/releases) @@ -41,6 +41,7 @@ English · [简体中文](README.zh-CN.md) - **Native `.xlsx` / Markdown Exports & Settings Backup**: Exports multi-sheet localized Excel (`.xlsx`) workbooks and Markdown summaries for both Usage Statistics and Call Details directly to `~/Downloads` with an in-app reveal toast, plus portable JSON preference backup/import. - **Cross-Client Session Migration**: Built-in opt-in session migrator (`Preferences → Other`) moves or clones conversations across `Antigravity CLI` ↔ `Desktop App / IDE` and `Legacy IDE (.db)` with isolated UUID rewriting to prevent cross-client mirror collisions or double billing. - **Multi-Client Capsules & CLI `statusLine` Modes**: Integrates as a titlebar or composer capsule (with ring quota gauges and main-agent context lock) and auxiliary sidebar in Antigravity 2.0, a titlebar/composer capsule in Antigravity IDE, a single-line 24-bit ANSI `statusLine` in Antigravity CLI (`--style pill|bar|compact`, `--preset compact|balanced|full`, `--json`), and a standalone local web UI. +- **VS Code Extension & Remote-SSH Support**: Auto-provisions `~/.vscode/argv.json` and mounts inside the chat input box by default via an independent setting (switchable to Top Bar, without Sidebar Only); supports local and Remote-SSH endpoint isolation, instant conversation following, and remote `agy` CLI plugin fallback on the top bar while skipping hosts without Antigravity plugins. - **No `app.asar` Modification & Desktop 2.33.0+ Auto-Provisioning**: Titlebar/composer injection and context hooks run in memory over local CDP (`DevToolsActivePort`). Automatically provisions Desktop `2.33.0+` user shortcuts/launchers (with one-click out-of-job host relaunch) and `~/.antigravity-ide/argv.json` without touching installation binaries or `app.asar`. - **Per-Model Context Windows (Main & Subagent/Swarm)**: Sets context window limits per model series or follows host defaults, with independent toggles for the main agent (CDP request hook), spawned subagents / Swarm workers (local loopback CloudCode proxy), and CLI (`AGY_CLI_AUTO_COMPACT_OVERRIDE`). - **Appearance, Offline Storage & Cloud Updates**: Supports `zh-CN` / `en-US` / host language, borderless Modern UI, `sm / md / lg / xl` font scaling, 6 theme accents plus host matching, offline reading from CLI SQLite + WAL, `annotations/*.pbtxt`, `transcript.jsonl`, and `.deep_stats_cache.json`, GitHub [`pricing-catalog.json`](pricing-catalog.json) sync, and in-panel release updates (`manual` / `auto` / `off`). @@ -108,6 +109,7 @@ English · [简体中文](README.zh-CN.md) | :--- | :---: | :---: | :---: | :---: | :---: | | **Antigravity 2.0 (Desktop)** | Titlebar / Composer | Popover + Right Sidebar | Yes | CDP Hook + Local CloudCode Proxy | No | | **Antigravity IDE** | Titlebar / Composer | Capsule Popover | Yes | CDP Hook + Local CloudCode Proxy | No | +| **VS Code (Extension / Remote-SSH)** | Input Box (Default) / Top Bar | Capsule Popover | Yes | Per-Host / Endpoint | No | | **Antigravity CLI (`agy`)** | Native ANSI `statusLine` | Standalone Web (`--port`) | Yes (`node:sqlite` + `.pbtxt`) | `AGY_CLI_AUTO_COMPACT_OVERRIDE` | No | | **SSH Remote / Headless Linux** | Per-Endpoint Capsule / ANSI `statusLine` | SSH Overlay / `--token` Web | Yes | Per-Endpoint Hook / Env | No | @@ -163,10 +165,12 @@ Clone https://github.com/yuhuan-dev/antigravity-usage-monitor with --filter=blob - Mounts a capsule in the top-right titlebar (**hover** for summary, **click** for the 4-tab popover, **right-click** to refresh), alongside the right auxiliary sidebar pane. 3. **Antigravity IDE**: - **Restart Antigravity IDE once** after enabling for the first time. Keep **Mount Mode** on **Dual-mount** and click the top-bar capsule to open the panel. -4. **Antigravity CLI (`agy`)**: +4. **VS Code (Extension / Remote-SSH)**: + - **Restart VS Code once** after first activation (`~/.vscode/argv.json` is auto-configured). Mounts in the chat input box by default (switchable to **Top Bar**); when only the local or remote `agy` CLI plugin is installed (requires passwordless SSH for remote hosts), it mounts on the top bar automatically. +5. **Antigravity CLI (`agy`)**: - When `~/.gemini/antigravity-cli` exists, `statusLine` in `settings.json` is configured automatically (existing third-party `statusLine.command` entries are left untouched) to render a single-line ANSI bar (`● 1 active 38.1 t/s | 0.85s | ◎ 17%`). - Toggle via `/statusline` in `agy` or **Preferences → Structure → Mount & Capsule Bar**. -5. **Standalone Web Server (Headless / Remote)**: +6. **Standalone Web Server (Headless / Remote)**: ```bash # 1. Start on the host (listens on 127.0.0.1:8787 by default) diff --git a/README.zh-CN.md b/README.zh-CN.md index 847a489..50a0fd8 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -4,7 +4,7 @@ # Antigravity Usage & Speed Monitor -Google Antigravity 2.0、Antigravity IDE 与 Antigravity CLI 的本地用量、速率、上下文与配额监控插件,无外部 npm 依赖。 +Google Antigravity 2.0、Antigravity IDE、VS Code(官方扩展)与 Antigravity CLI 的本地用量、速率、上下文与配额监控插件,无外部 npm 依赖。 [![Release](https://img.shields.io/github/v/release/yuhuan-dev/antigravity-usage-monitor?style=flat-square&color=2A5E76&label=release)](https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest) [![Downloads](https://img.shields.io/github/downloads/yuhuan-dev/antigravity-usage-monitor/total?style=flat-square&color=0ea5e9)](https://github.com/yuhuan-dev/antigravity-usage-monitor/releases) @@ -41,6 +41,7 @@ Google Antigravity 2.0、Antigravity IDE 与 Antigravity CLI 的本地用量、 - **原生多表 `.xlsx` 报表导出及配置备份**:支持将用量统计及调用明细直接导出为多工作表双语 Excel(`.xlsx`)工作簿或复制 Markdown 汇总报告(落盘至 `~/Downloads` 并弹出「打开位置」定位提示),同时支持便携 JSON 偏好配置备份导入导出。 - **跨客户端会话无损迁移**:在「偏好设置 → 其他」提供 `CLI ↔ 桌面端 / 新版 IDE` 及 `旧版 IDE (.db)` 按需会话迁移及克隆副本工具,自动重写独立 UUID 防止跨端镜像互删及重复计费。 - **多端胶囊及 CLI `statusLine` 多模式**:支持 Antigravity 2.0 顶栏/输入框胶囊(含环形额度指示及主代理上下文锁定)及右侧辅助栏、Antigravity IDE 顶栏/输入框胶囊、Antigravity CLI(`agy`)单行 24-bit ANSI `statusLine`(支持 `--style pill|bar|compact`、`--preset compact|balanced|full` 及 `--json` 快照输出)以及独立 Web 页面。 +- **VS Code 官方扩展与 Remote-SSH 适配**:自动补齐 `~/.vscode/argv.json`,默认以独立设置挂载在聊天输入框(支持切换为顶部栏,不提供仅侧边栏);支持本地与 Remote-SSH 远端扩展及远端 `agy` CLI 插件的自动识别、端点隔离与实时会话跟随,未安装对应插件的窗口自动静默跳过。 - **不修改 `app.asar` 及 Desktop 2.33.0+ 自动补齐**:桌面端和 IDE 的胶囊挂载及上下文改写均通过本地 CDP 内存注入完成;自动补齐 Desktop `2.33.0+` 用户快捷方式/启动项(支持面板内一键脱离作业树带参重拉)及 `~/.antigravity-ide/argv.json`,绝不触碰宿主安装包及 `app.asar`。 - **按模型设置上下文窗口(主代理 + 子代理/Swarm)**:支持按模型系列指定上下文上限或跟随宿主默认,提供独立的主代理开关(CDP 请求钩子)及子代理 / Swarm Worker 同步开关(本机回环 CloudCode 透明反代),CLI 端通过 `AGY_CLI_AUTO_COMPACT_OVERRIDE` 控制。 - **外观定制、离线读取及云端同步**:提供简体中文 / English / 跟随宿主语言、无边框 Modern UI、`sm / md / lg / xl` 字号、6 种主题强调色;离线直读 CLI SQLite + WAL、`annotations/*.pbtxt`、`transcript.jsonl` 及 `.deep_stats_cache.json`;内置 GitHub [`pricing-catalog.json`](pricing-catalog.json) 同步及面板内更新(手动 / 自动 / 关闭)。 @@ -108,6 +109,7 @@ Google Antigravity 2.0、Antigravity IDE 与 Antigravity CLI 的本地用量、 | :--- | :---: | :---: | :---: | :---: | :---: | | **Antigravity 2.0 桌面端** | 顶栏 / 输入框停靠 | 悬浮窗 + 右侧辅助栏 | 支持 | CDP 钩子 + 本机 CloudCode 反代 | 否 | | **Antigravity IDE** | 顶栏 / 输入框停靠 | 点击胶囊展开面板 | 支持 | CDP 钩子 + 本机 CloudCode 反代 | 否 | +| **VS Code(官方扩展 / Remote-SSH)** | 输入框(默认)/ 顶部栏 | 点击胶囊展开面板 | 支持 | 按宿主 / 端点同步 | 否 | | **Antigravity CLI (`agy`)** | 终端底栏 `statusLine` | 独立 Web (`--port`) | 支持(`node:sqlite` + `.pbtxt`) | `AGY_CLI_AUTO_COMPACT_OVERRIDE` | 否 | | **无头服务器 / SSH 远程** | 按端点胶囊 / ANSI `statusLine` | SSH 悬浮窗 / `--token` Web | 支持 | 按端点钩子 / 环境变量 | 否 | @@ -163,10 +165,12 @@ git clone --filter=blob:none --single-branch https://github.com/yuhuan-dev/antig - 主窗口右上角挂载悬浮胶囊(**悬停**查看速览,**左键**打开四标签面板,**右键**强制刷新),同时可在右侧辅助栏打开「用量监控」。 3. **Antigravity IDE**: - 首次启用后**重启一次 Antigravity IDE**,保持挂载方式为「双栖挂载」,点击顶栏胶囊即可打开面板。 -4. **Antigravity CLI (`agy`) 底部胶囊**: +4. **VS Code(官方扩展 / Remote-SSH)**: + - 首次启用后**重启一次 VS Code**(自动写入 `~/.vscode/argv.json`);默认挂载在 Antigravity 聊天输入框,可在设置中切换为「顶部栏」。若未安装 VS Code 扩展、仅安装本机或远端(需免密 SSH)的 `agy` CLI 插件,将自动显示于顶部栏。 +5. **Antigravity CLI (`agy`) 底部胶囊**: - 检测到 `~/.gemini/antigravity-cli` 时自动写入原生 `statusLine` 配置(保留已有自定义 `statusLine.command`),在终端底栏单行显示当前活跃状态、输出速率、首字延迟与上下文占比(如 `● 1 运行中 38.1 t/s | 0.85s | ◎ 17%`)。 - 可在 `agy` 中通过 `/statusline` 或在面板 **偏好设置 → 界面编排 → 挂载胶囊** 开关及调整显示顺序。 -5. **独立 Web 服务(纯终端 / 远程服务器)**: +6. **独立 Web 服务(纯终端 / 远程服务器)**: ```bash # 1. 在远程服务器上启动(默认监听 127.0.0.1:8787) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index d14f2b6..6dcc7f1 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -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) { diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index 2a2ea0e..bc13d94 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -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 ( diff --git a/sidecars/panel/backend/endpoint-registry.mjs b/sidecars/panel/backend/endpoint-registry.mjs index 71e90b2..f24b6b7 100644 --- a/sidecars/panel/backend/endpoint-registry.mjs +++ b/sidecars/panel/backend/endpoint-registry.mjs @@ -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; diff --git a/sidecars/panel/backend/ls-rpc.mjs b/sidecars/panel/backend/ls-rpc.mjs index 619f520..9bec56e 100644 --- a/sidecars/panel/backend/ls-rpc.mjs +++ b/sidecars/panel/backend/ls-rpc.mjs @@ -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( diff --git a/sidecars/panel/backend/remote-cli-bridge.mjs b/sidecars/panel/backend/remote-cli-bridge.mjs new file mode 100644 index 0000000..95b399b --- /dev/null +++ b/sidecars/panel/backend/remote-cli-bridge.mjs @@ -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::127.0.0.1:`, + * 供 `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, + * waitPortReadyFn?: (port: number, timeoutMs?: number) => Promise, + * 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} */ + const cacheByHost = new Map(); + /** @type {Map>} */ + const inFlightProbes = new Map(); + /** @type {Map} */ + 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} 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, + }; +} diff --git a/sidecars/panel/backend/settings-schema.mjs b/sidecars/panel/backend/settings-schema.mjs index 2ed5ad6..bb80139 100644 --- a/sidecars/panel/backend/settings-schema.mjs +++ b/sidecars/panel/backend/settings-schema.mjs @@ -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), diff --git a/sidecars/panel/backend/window-bridge.mjs b/sidecars/panel/backend/window-bridge.mjs index 93988c7..a16946e 100644 --- a/sidecars/panel/backend/window-bridge.mjs +++ b/sidecars/panel/backend/window-bridge.mjs @@ -57,6 +57,7 @@ import { ensureDesktopLaunchEntriesConfigured, resolveDesktopHostExecutable, } from './desktop-launcher-config.mjs'; +import { createRemoteCliBridge } from './remote-cli-bridge.mjs'; import { getRegisteredRemoteEndpoint, getRemoteEndpointTargetWsUrls, @@ -106,45 +107,49 @@ const WINDOW_VISIBLE_EXPR = `Boolean( function buildDomRouteCascadeIdSnippet() { return `(() => { const uuidRe = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; - const m = String(window.location?.pathname || '').match(/^\\/c\\/([0-9a-f-]{36})(?:\\/|$)/i); - if (m && uuidRe.test(m[1])) return m[1]; - if (typeof document === 'undefined' || typeof document.querySelector !== 'function') return ''; - const selectedRow = document.querySelector( - '[data-testid^="conversation-row-"][data-selected="true"][data-cascade-id]' - ); - const selectedRowId = String(selectedRow?.getAttribute?.('data-cascade-id') || '').trim(); - if (typeof document.querySelectorAll === 'function') { - const views = document.querySelectorAll('[data-testid="conversation-view"][data-cascade-id]'); - const visibleIds = []; - let focusedId = ''; - const activeEl = document.activeElement || null; - for (const viewEl of views) { - const cid = String(viewEl?.getAttribute?.('data-cascade-id') || '').trim(); - if (!uuidRe.test(cid)) continue; - if (viewEl.hasAttribute?.('hidden')) continue; - if (viewEl.getBoundingClientRect) { - const r = viewEl.getBoundingClientRect(); - if (r.width <= 0 && r.height <= 0) continue; + const isExtView = /[?&]extension(?:View|Variant)=/i.test(String(window.location?.search || '')); + const pathMatch = String(window.location?.pathname || '').match(/^\\/c\\/([0-9a-f-]{36})(?:\\/|$)/i); + const pathId = pathMatch && uuidRe.test(pathMatch[1]) ? pathMatch[1] : ''; + if (!isExtView && pathId) return pathId; + if (typeof document !== 'undefined' && typeof document.querySelector === 'function') { + const selectedRow = document.querySelector( + '[data-testid^="conversation-row-"][data-selected="true"][data-cascade-id]' + ); + const selectedRowId = String(selectedRow?.getAttribute?.('data-cascade-id') || '').trim(); + if (typeof document.querySelectorAll === 'function') { + const views = document.querySelectorAll('[data-testid="conversation-view"][data-cascade-id]'); + const visibleIds = []; + let focusedId = ''; + const activeEl = document.activeElement || null; + for (const viewEl of views) { + const cid = String(viewEl?.getAttribute?.('data-cascade-id') || '').trim(); + if (!uuidRe.test(cid)) continue; + if (viewEl.hasAttribute?.('hidden')) continue; + if (viewEl.getBoundingClientRect) { + const r = viewEl.getBoundingClientRect(); + if (r.width <= 0 && r.height <= 0) continue; + } + visibleIds.push(cid); + if (activeEl && viewEl.contains?.(activeEl)) { + focusedId = cid; + } } - visibleIds.push(cid); - if (activeEl && viewEl.contains?.(activeEl)) { - focusedId = cid; + if (focusedId) return focusedId; + if ( + selectedRowId && + uuidRe.test(selectedRowId) && + visibleIds.some((id) => id.toLowerCase() === selectedRowId.toLowerCase()) + ) { + return selectedRowId; } + if (visibleIds.length > 0) return visibleIds[0]; } - if (focusedId) return focusedId; - if ( - selectedRowId && - uuidRe.test(selectedRowId) && - visibleIds.some((id) => id.toLowerCase() === selectedRowId.toLowerCase()) - ) { - return selectedRowId; - } - if (visibleIds.length > 0) return visibleIds[0]; + const singleView = document.querySelector('[data-testid="conversation-view"][data-cascade-id]'); + const singleViewId = String(singleView?.getAttribute?.('data-cascade-id') || '').trim(); + if (uuidRe.test(singleViewId)) return singleViewId; + if (uuidRe.test(selectedRowId)) return selectedRowId; } - const singleView = document.querySelector('[data-testid="conversation-view"][data-cascade-id]'); - const singleViewId = String(singleView?.getAttribute?.('data-cascade-id') || '').trim(); - if (uuidRe.test(singleViewId)) return singleViewId; - if (uuidRe.test(selectedRowId)) return selectedRowId; + if (pathId) return pathId; return ''; })()`; } @@ -257,6 +262,249 @@ export function resolveDevToolsPortCandidates( return out; } +const VSCODE_ANTIGRAVITY_EXT_RE = /^google\.google-antigravity(?:[-.@]|$)/i; +const VSCODE_REMOTE_SSH_EXT_RE = /^ms-vscode-remote\.remote-ssh(?:[-.@]|$)/i; + +/** + * 检查指定的 VS Code 用户配置目录(如 `~/.vscode`、`~/.vscode-insiders`)下是否已安装 + * Google Antigravity 官方扩展(`google.google-antigravity`)。 + * + * @param {string} vsCodeUserRoot + * @param {{ readdirFn?: typeof readdirSync }|null} [fsOps=null] + * @returns {boolean} + */ +export function hasVsCodeAntigravityExtension(vsCodeUserRoot, fsOps = null) { + const cleanRoot = String(vsCodeUserRoot || '').trim(); + if (!cleanRoot) return false; + const readdirFn = fsOps?.readdirFn || readdirSync; + try { + const entries = readdirFn(join(cleanRoot, 'extensions')) || []; + for (const rawEntry of entries) { + const name = typeof rawEntry === 'string' ? rawEntry : String(rawEntry?.name || ''); + if (VSCODE_ANTIGRAVITY_EXT_RE.test(name)) { + return true; + } + } + } catch { + return false; + } + return false; +} + +/** + * 检查指定的 VS Code 用户配置目录下是否安装了 Remote-SSH 扩展(远端服务器可能单独安装了 Antigravity 扩展)。 + * + * @param {string} vsCodeUserRoot + * @param {{ readdirFn?: typeof readdirSync }|null} [fsOps=null] + * @returns {boolean} + */ +export function hasVsCodeRemoteSshExtension(vsCodeUserRoot, fsOps = null) { + const cleanRoot = String(vsCodeUserRoot || '').trim(); + if (!cleanRoot) return false; + const readdirFn = fsOps?.readdirFn || readdirSync; + try { + const entries = readdirFn(join(cleanRoot, 'extensions')) || []; + for (const rawEntry of entries) { + const name = typeof rawEntry === 'string' ? rawEntry : String(rawEntry?.name || ''); + if (VSCODE_REMOTE_SSH_EXT_RE.test(name)) { + return true; + } + } + } catch { + return false; + } + return false; +} + +/** + * 检查本机是否安装了 Antigravity CLI(`agy` 二进制或 `~/.gemini/antigravity-cli` 目录)。 + * + * @param {Record} [env=process.env] + * @param {string} [homeDir=homedir()] + * @param {{ existsFn?: typeof existsSync }|null} [fsOps=null] + * @returns {boolean} + */ +export function hasLocalAgyCli(env = process.env, homeDir = homedir(), fsOps = null) { + const existsFn = fsOps?.existsFn || existsSync; + const geminiBase = String(env?.ANTIGRAVITY_GEMINI_DIR || '').trim() || join(homeDir, '.gemini'); + try { + if (existsFn(join(geminiBase, 'antigravity-cli'))) { + return true; + } + } catch { + // 忽略目录不可读 + } + const exeName = process.platform === 'win32' ? 'agy.exe' : 'agy'; + const binCandidates = + process.platform === 'win32' + ? [ + join(homeDir, '.local', 'bin', exeName), + join(env?.LOCALAPPDATA || join(homeDir, 'AppData', 'Local'), 'Programs', 'agy', exeName), + ] + : [ + join(homeDir, '.local', 'bin', exeName), + '/usr/local/bin/agy', + '/opt/homebrew/bin/agy', + ]; + for (const binPath of binCandidates) { + try { + if (existsFn(binPath)) return true; + } catch { + // 忽略异常 + } + } + const pathEnv = String(env?.PATH || ''); + if (pathEnv) { + const sep = process.platform === 'win32' ? ';' : ':'; + for (const dir of pathEnv.split(sep)) { + const cleanDir = dir.trim(); + if (!cleanDir) continue; + try { + if (existsFn(join(cleanDir, exeName))) return true; + } catch { + // 忽略不可读 PATH 目录 + } + } + } + return false; +} + +/** + * 检查本机是否安装了 `agy` CLI 及其 `usage-monitor` 插件。 + * + * @param {Record} [env=process.env] + * @param {string} [homeDir=homedir()] + * @param {{ existsFn?: typeof existsSync, readFileFn?: typeof readFileSync }|null} [fsOps=null] + * @returns {boolean} + */ +export function hasLocalAgyCliPlugin(env = process.env, homeDir = homedir(), fsOps = null) { + if (!hasLocalAgyCli(env, homeDir, fsOps)) return false; + const existsFn = fsOps?.existsFn || existsSync; + const readFileFn = fsOps?.readFileFn || readFileSync; + const geminiBase = String(env?.ANTIGRAVITY_GEMINI_DIR || '').trim() || join(homeDir, '.gemini'); + const pluginManifestCandidates = [ + join(geminiBase, 'config', 'plugins', 'usage-monitor', 'plugin.json'), + join(geminiBase, 'antigravity-cli', 'plugins', 'usage-monitor', 'plugin.json'), + ]; + for (const manifestPath of pluginManifestCandidates) { + try { + if (existsFn(manifestPath)) return true; + } catch { + // 忽略不可读路径 + } + } + try { + const cliSettingsPath = join(geminiBase, 'antigravity-cli', 'settings.json'); + if (existsFn(cliSettingsPath)) { + const raw = String(readFileFn(cliSettingsPath, 'utf8') || ''); + if (/usage-monitor|cli-statusline/i.test(raw)) return true; + } + } catch { + // 忽略配置读取异常 + } + return false; +} + +/** + * 检查本机标准 VS Code / VS Code Insiders 是否安装了 Antigravity 官方扩展。 + * + * @param {string} [homeDir=homedir()] + * @param {{ readdirFn?: typeof readdirSync }|null} [fsOps=null] + * @returns {boolean} + */ +export function hasAnyLocalVsCodeAntigravityExtension(homeDir = homedir(), fsOps = null) { + return Boolean( + hasVsCodeAntigravityExtension(join(homeDir, '.vscode'), fsOps) || + hasVsCodeAntigravityExtension(join(homeDir, '.vscode-insiders'), fsOps) + ); +} + +/** + * 判断指定的标准 VS Code 目录是否应纳入 Antigravity 探测范围: + * 满足本机已装 VS Code `google.google-antigravity` 扩展、已装 `Remote-SSH`(远端可能装了扩展或 CLI 插件) + * 或本机已装 `agy` CLI `usage-monitor` 插件任一条件即启用。 + * + * @param {string} vsCodeUserRoot + * @param {Record} [env=process.env] + * @param {string} [homeDir=homedir()] + * @param {{ readdirFn?: typeof readdirSync, existsFn?: typeof existsSync, readFileFn?: typeof readFileSync }|null} [fsOps=null] + * @returns {boolean} + */ +export function hasVsCodeAntigravitySupport( + vsCodeUserRoot, + env = process.env, + homeDir = homedir(), + fsOps = null +) { + return Boolean( + hasVsCodeAntigravityExtension(vsCodeUserRoot, fsOps) || + hasVsCodeRemoteSshExtension(vsCodeUserRoot, fsOps) || + hasLocalAgyCliPlugin(env, homeDir, fsOps) + ); +} + +/** + * 解析已安装 Antigravity 官方扩展(或 Remote-SSH / agy CLI)的标准 VS Code / VS Code Insiders 的 `DevToolsActivePort` 候选路径。 + * 与 `resolveDevToolsPortCandidates` 隔离,避免 Antigravity 桌面端重拉时误删 VS Code 的端口文件。 + * + * @param {Record} [env=process.env] + * @param {string} [platform=process.platform] + * @param {string} [homeDir=homedir()] + * @param {{ readdirFn?: typeof readdirSync, existsFn?: typeof existsSync }|null} [fsOps=null] + * @returns {string[]} + */ +export function resolveVsCodeDevToolsPortCandidates( + env = process.env, + platform = process.platform, + homeDir = homedir(), + fsOps = null +) { + if (String(env?.ANTIGRAVITY_DEVTOOLS_PORT_FILE || '').trim()) { + return []; + } + const variants = [ + { userRoot: join(homeDir, '.vscode'), dataDirName: 'Code' }, + { userRoot: join(homeDir, '.vscode-insiders'), dataDirName: 'Code - Insiders' }, + ].filter((v) => hasVsCodeAntigravitySupport(v.userRoot, env, homeDir, fsOps)); + + if (variants.length === 0) { + return []; + } + + const out = []; + const seen = new Set(); + const pushUnique = (p) => { + const clean = String(p || '').trim(); + if (clean && !seen.has(clean)) { + seen.add(clean); + out.push(clean); + } + }; + + for (const { dataDirName } of variants) { + if (platform === 'win32') { + const appData = env?.APPDATA || join(homeDir, 'AppData', 'Roaming'); + const localAppData = env?.LOCALAPPDATA || join(homeDir, 'AppData', 'Local'); + pushUnique(join(appData, dataDirName, 'DevToolsActivePort')); + pushUnique(join(localAppData, dataDirName, 'DevToolsActivePort')); + continue; + } + if (platform === 'darwin') { + pushUnique(join(homeDir, 'Library', 'Application Support', dataDirName, 'DevToolsActivePort')); + pushUnique(join(homeDir, '.config', dataDirName, 'DevToolsActivePort')); + continue; + } + const defaultConfigHome = join(homeDir, '.config'); + const configHome = env?.XDG_CONFIG_HOME || defaultConfigHome; + pushUnique(join(configHome, dataDirName, 'DevToolsActivePort')); + if (configHome !== defaultConfigHome) { + pushUnique(join(defaultConfigHome, dataDirName, 'DevToolsActivePort')); + } + } + + return out; +} + /** * 解析 Antigravity IDE 启动参数文件 `argv.json` 路径(兼容便携模式 `VSCODE_PORTABLE`)。 * @@ -564,10 +812,32 @@ export function ensureIdeRemoteDebuggingArgv({ return { checked: false, updated: false, reason: 'disabled' }; } const argvPath = resolveIdeArgvPath(env, homeDir); - return patchSingleHostArgvFile(argvPath, { + const ideRes = patchSingleHostArgvFile(argvPath, { createDir: false, missingReason: 'ide_dir_missing', }); + + const vsCodeRoots = [join(homeDir, '.vscode'), join(homeDir, '.vscode-insiders')]; + let vsCodeUpdated = false; + let vsCodeAlreadyConfigured = false; + for (const root of vsCodeRoots) { + if (!hasVsCodeAntigravitySupport(root, env, homeDir)) continue; + const res = patchSingleHostArgvFile(join(root, 'argv.json'), { + createDir: false, + missingReason: 'vscode_dir_missing', + }); + if (res.updated) vsCodeUpdated = true; + if (res.alreadyConfigured) vsCodeAlreadyConfigured = true; + } + + if (vsCodeUpdated || vsCodeAlreadyConfigured) { + return { + ...ideRes, + updated: Boolean(ideRes.updated || vsCodeUpdated), + alreadyConfigured: Boolean(ideRes.alreadyConfigured || vsCodeAlreadyConfigured), + }; + } + return ideRes; } /** @@ -710,6 +980,7 @@ export function associateIdeIframeRoutes(rawTargets, mainTargets, options = unde if (!cascadeId && !isChatFrame) continue; let matchedMainId = ''; + let ancestorRemoteAuthority = ''; let curId = String(t.parentId || '').trim(); const visited = new Set(); while (curId && !visited.has(curId)) { @@ -719,6 +990,15 @@ export function associateIdeIframeRoutes(rawTargets, mainTargets, options = unde break; } const parentTarget = byId.get(curId); + if (!ancestorRemoteAuthority && parentTarget?.url) { + try { + const parentUrl = new URL(String(parentTarget.url)); + const auth = String(parentUrl.searchParams.get('remoteAuthority') || '').trim(); + if (auth) ancestorRemoteAuthority = auth; + } catch { + // 忽略非标准父级 URL + } + } curId = parentTarget ? String(parentTarget.parentId || '').trim() : ''; } @@ -742,8 +1022,11 @@ export function associateIdeIframeRoutes(rawTargets, mainTargets, options = unde wsUrl = `ws://127.0.0.1:${cdpPort}/devtools/page/${encodeURIComponent(String(t.id))}`; } let origin = ''; + let remoteKind = ''; try { - origin = new URL(rawUrl).origin; + const parsedChatUrl = new URL(rawUrl); + origin = parsedChatUrl.origin; + remoteKind = String(parsedChatUrl.searchParams.get('remoteKind') || '').trim().toLowerCase(); } catch { // 忽略非法 URL } @@ -754,6 +1037,8 @@ export function associateIdeIframeRoutes(rawTargets, mainTargets, options = unde id: String(t.id || ''), url: rawUrl, origin, + remoteKind, + remoteAuthority: ancestorRemoteAuthority, cascadeId: cascadeId || (fallbackUuidMatch ? fallbackUuidMatch[1] : ''), webSocketDebuggerUrl: wsUrl, isIdeChatFrame: true, @@ -849,15 +1134,81 @@ export function extractRemoteHostMetadata(appConfig, title = '') { * confirmedLocalPorts?: Set|null, * }} params */ +/** + * 从 IDE / VS Code 主窗口及其关联的扩展聊天 iframe 中提取远端连接元数据(如 Remote-SSH / WSL / Dev Container)。 + * 仅在检测到显式远端标记(非 `none` 的 `remoteKind`、`remoteAuthority` 或窗口标题 `[SSH: ...]`)时返回 `isRemote: true`。 + * + * @param {object|null|undefined} target + * @param {object|null|undefined} [chatTarget=null] + */ +export function pickPrimaryIdeChatTarget(target) { + const list = Array.isArray(target?.ideChatTargets) ? target.ideChatTargets : []; + if (list.length === 0) return null; + const remoteChat = list.find( + (c) => + (c?.remoteKind && c.remoteKind !== 'none') || + Boolean(String(c?.remoteAuthority || '').trim()) + ); + if (remoteChat) return remoteChat; + return list.find((c) => c?.webSocketDebuggerUrl || c?.origin) || list[0]; +} + +export function extractIdeRemoteMetadata(target, chatTarget = null) { + const ct = chatTarget || pickPrimaryIdeChatTarget(target); + const remoteKind = String(ct?.remoteKind || '').trim().toLowerCase(); + const rawAuthority = String(ct?.remoteAuthority || '').trim(); + const cleanAuthorityHost = rawAuthority + .replace(/^(?:ssh-remote|ssh|wsl|dev-container|attached-container|tunnel|codespaces)\+/i, '') + .trim(); + const titleMeta = extractRemoteHostMetadata(null, String(target?.title || '')); + const hasRemoteKind = Boolean(remoteKind && remoteKind !== 'none'); + const isRemote = Boolean(hasRemoteKind || rawAuthority || titleMeta.bracketedTitleHost); + const stableHostKey = cleanAuthorityHost || titleMeta.stableHostKey || ''; + const hostLabel = cleanAuthorityHost || titleMeta.hostLabel || (hasRemoteKind ? remoteKind : ''); + return { + isRemote, + remoteKind, + remoteAuthority: rawAuthority, + stableHostKey, + hostLabel, + }; +} + export function classifyWindowTargetEndpoint({ target, probedInfo = null, localHubInfo = null, confirmedLocalPorts = null, }) { - if (!target || target.isIdeWorkbench) { + if (!target) { return { isRemote: false, endpointId: LOCAL_ENDPOINT_ID, label: '', origin: '', csrfToken: '' }; } + if (target.isIdeWorkbench) { + const primaryChat = pickPrimaryIdeChatTarget(target); + const ideRemote = extractIdeRemoteMetadata(target, primaryChat); + if (!ideRemote.isRemote) { + return { isRemote: false, endpointId: LOCAL_ENDPOINT_ID, label: '', origin: '', csrfToken: '' }; + } + const origin = String(probedInfo?.origin || primaryChat?.origin || '').trim(); + let originPort = 0; + if (origin) { + try { + originPort = Number(new URL(origin).port || 0); + } catch { + originPort = 0; + } + } + const csrfToken = String(probedInfo?.csrfToken || probedInfo?.observedCsrfToken || '').trim(); + return { + isRemote: true, + origin, + originPort, + csrfToken, + stableHostKey: ideRemote.stableHostKey, + hostLabel: ideRemote.hostLabel || (originPort > 0 ? `SSH:${originPort}` : 'SSH'), + remoteWsUrl: String(primaryChat?.webSocketDebuggerUrl || '').trim(), + }; + } let origin = String(probedInfo?.origin || '').trim(); if (!origin) { @@ -1141,7 +1492,7 @@ export function createWindowBridgeController(options) { env = process.env, platform = process.platform, homeDir = homedir(), - pollIntervalMs = 3000, + pollIntervalMs = 6000, fastPollIntervalMs = 1500, cdpTimeoutMs = 3500, bootBundleVersion = '', @@ -1158,6 +1509,8 @@ export function createWindowBridgeController(options) { getLocalHubPortsFn = getLocalHubPorts, cloudCodeProxy = null, manageCloudCodeProxy = false, + remoteCliBridge = null, + enableRemoteCliBridge = options?.env === undefined && options?.homeDir === undefined, resolveLocalContextRulesFn = null, getHostI18nDescriptorFn = options?.env === undefined && options?.homeDir === undefined @@ -1167,6 +1520,7 @@ export function createWindowBridgeController(options) { const activeCloudCodeProxy = cloudCodeProxy || (manageCloudCodeProxy ? getDefaultCloudCodeProxy() : null); + let activeRemoteCliBridge = remoteCliBridge || null; function isPidAlive(pid) { if (!Number.isInteger(pid) || pid <= 0) return false; @@ -1185,6 +1539,7 @@ export function createWindowBridgeController(options) { let bridgeToken = ''; let pollTimer = null; let initialTimer = null; + let routePingTimer = null; let stopped = false; let syncInFlight = null; let hadInjectedTargets = false; @@ -1368,6 +1723,28 @@ export function createWindowBridgeController(options) { return; } + if (method === 'POST' && parsedUrl.pathname === '/api/bridge-route-ping') { + const pingToken = String(req.headers['x-usage-monitor-token'] || ''); + if (!verifyBridgeToken(pingToken, bridgeToken, crypto.timingSafeEqual)) { + res.writeHead(403, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Invalid bridge token' })); + return; + } + res.writeHead(204); + res.end(); + if (!stopped) { + if (routePingTimer) clearTimeout(routePingTimer); + routePingTimer = setTimeout(() => { + routePingTimer = null; + if (!stopped) { + void syncAllWindows().catch(() => {}); + } + }, 80); + routePingTimer.unref?.(); + } + return; + } + if (!ALLOWED_BRIDGE_PATHS.has(parsedUrl.pathname)) { res.writeHead(404, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Not found' })); @@ -1557,21 +1934,28 @@ export function createWindowBridgeController(options) { } function findActiveDevToolsPorts() { - const candidates = resolveDevToolsPortCandidates(env, platform, homeDir); + const primaryCandidates = resolveDevToolsPortCandidates(env, platform, homeDir); + const vsCodeCandidates = resolveVsCodeDevToolsPortCandidates(env, platform, homeDir); const ports = []; const seen = new Set(); - for (const filePath of candidates) { - try { - if (!existsSync(filePath)) continue; - const port = parseDevToolsPortFile(readFileSync(filePath, 'utf8')); - if (port && !seen.has(port)) { - seen.add(port); - ports.push(port); + const vsCodePorts = new Set(); + const collectFrom = (filePaths, markVsCode) => { + for (const filePath of filePaths) { + try { + if (!existsSync(filePath)) continue; + const port = parseDevToolsPortFile(readFileSync(filePath, 'utf8')); + if (port && !seen.has(port)) { + seen.add(port); + ports.push(port); + if (markVsCode) vsCodePorts.add(port); + } + } catch { + // 忽略不可读候选文件 } - } catch { - // 忽略不可读候选文件 } - } + }; + collectFrom(primaryCandidates, false); + collectFrom(vsCodeCandidates, true); const rawExplicitPorts = String(env?.ANTIGRAVITY_DEVTOOLS_PORT || '').trim(); if (rawExplicitPorts) { for (const token of rawExplicitPorts.split(/[\s,]+/)) { @@ -1583,10 +1967,11 @@ export function createWindowBridgeController(options) { } } } + ports._vsCodePorts = vsCodePorts; return ports; } - async function listMainWindowTargets(cdpPort) { + async function listMainWindowTargets(cdpPort, { isVsCodeHost = false } = {}) { const { http } = await loadNodeDeps(); const rawBody = await new Promise((resolve, reject) => { const req = http.get(`http://127.0.0.1:${cdpPort}/json/list`, (res) => { @@ -1613,8 +1998,14 @@ export function createWindowBridgeController(options) { { lsAddr: lsRuntimeEndpoint.addr, cdpPort } ); for (const mainT of associated) { + const urlText = String(mainT?.url || ''); + mainT.isVsCodeHost = Boolean( + isVsCodeHost || + /(?:Visual(?:%20|\s)Studio(?:%20|\s)Code|Code(?:\s|%20)-?(?:\s|%20)Insiders)/i.test(urlText) + ); if (Array.isArray(mainT.ideChatTargets)) { for (const ct of mainT.ideChatTargets) { + ct.isVsCodeHost = mainT.isVsCodeHost; if (ct.origin && /^https?:\/\/(127\.0\.0\.1|localhost|\[::1\]):\d+$/i.test(ct.origin)) { allowedDynamicOrigins.add(ct.origin); } @@ -1641,7 +2032,10 @@ export function createWindowBridgeController(options) { } async function collectAllMainWindowTargets(cdpPorts) { - const settled = await Promise.allSettled(cdpPorts.map((p) => listMainWindowTargets(p))); + const vsCodePorts = cdpPorts?._vsCodePorts instanceof Set ? cdpPorts._vsCodePorts : new Set(); + const settled = await Promise.allSettled( + cdpPorts.map((p) => listMainWindowTargets(p, { isVsCodeHost: vsCodePorts.has(p) })) + ); let reachableCount = 0; const merged = []; const seenWs = new Set(); @@ -1988,6 +2382,7 @@ export function createWindowBridgeController(options) { const cdpPorts = findActiveDevToolsPorts(); if (!cdpPorts.length) { pruneStaleRemoteEndpoints(new Set()); + activeRemoteCliBridge?.pruneInactiveHosts?.(new Set()); const provPending = shouldCheckLaunchers ? provisionHostLaunchersOnce({ fastCheckIfActive: !isInitialLauncherPass }) : hostLauncherPromise; @@ -2009,6 +2404,7 @@ export function createWindowBridgeController(options) { const { reachableCount, targets } = await collectAllMainWindowTargets(cdpPorts); if (reachableCount === 0) { pruneStaleRemoteEndpoints(new Set()); + activeRemoteCliBridge?.pruneInactiveHosts?.(new Set()); const provPending = shouldCheckLaunchers ? provisionHostLaunchersOnce({ fastCheckIfActive: !isInitialLauncherPass }) : hostLauncherPromise; @@ -2033,6 +2429,7 @@ export function createWindowBridgeController(options) { } if (!targets.length) { pruneStaleRemoteEndpoints(new Set()); + activeRemoteCliBridge?.pruneInactiveHosts?.(new Set()); updateBridgeStatus(enabled ? 'no_targets' : 'disabled', { enabled, leasedBySelf, @@ -2042,8 +2439,10 @@ export function createWindowBridgeController(options) { return { ok: true, enabled, reason: 'no_targets', injected: 0 }; } + const hasAnyVsCodeTarget = targets.some((t) => t.isVsCodeHost); if ( !enabled && + !hasAnyVsCodeTarget && !needsAnyCdpContext && !hadContextWindows && !needsHostI18n && @@ -2101,9 +2500,25 @@ export function createWindowBridgeController(options) { 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); + const remoteIdeProbeTargets = []; + const seenRemoteIdeProbeWs = new Set(); + for (const t of targets) { + if (!t.isIdeWorkbench) continue; + const primaryChat = pickPrimaryIdeChatTarget(t); + const ideRemote = extractIdeRemoteMetadata(t, primaryChat); + const chatWs = String(primaryChat?.webSocketDebuggerUrl || '').trim(); + if (ideRemote.isRemote && chatWs && !seenRemoteIdeProbeWs.has(chatWs)) { + seenRemoteIdeProbeWs.add(chatWs); + remoteIdeProbeTargets.push({ + webSocketDebuggerUrl: chatWs, + url: primaryChat?.url || primaryChat?.origin || '', + }); + } + } + const targetsToProbe = [...desktopTargets, ...remoteIdeProbeTargets]; await Promise.allSettled( - desktopTargets.map(async (target) => { + targetsToProbe.map(async (target) => { const wsUrl = String(target.webSocketDebuggerUrl || ''); let targetOriginKey = ''; try { @@ -2113,7 +2528,7 @@ export function createWindowBridgeController(options) { } const cacheKey = `${wsUrl}::${targetOriginKey}`; const cached = targetClassifyCache.get(cacheKey); - if (cached && nowClassifyMs - cached.ts < 4000) { + if (cached && nowClassifyMs - cached.ts < 8000) { probedByWsUrl.set(wsUrl, cached.info); return; } @@ -2157,34 +2572,126 @@ export function createWindowBridgeController(options) { } const activeRemoteWsUrls = new Set(); + const activeRemoteCliHosts = new Set(); + const localHasVsCodeExt = hasAnyLocalVsCodeAntigravityExtension(homeDir); + const localHasCliPlugin = hasLocalAgyCliPlugin(env, homeDir); + if (!activeRemoteCliBridge && enableRemoteCliBridge) { + activeRemoteCliBridge = createRemoteCliBridge({ + onStateChanged: () => { + if (stopped) return; + if (routePingTimer) clearTimeout(routePingTimer); + routePingTimer = setTimeout(() => { + routePingTimer = null; + if (!stopped) { + void syncAllWindows().catch(() => {}); + } + }, 120); + routePingTimer.unref?.(); + }, + }); + } + for (const target of targets) { const wsUrl = String(target.webSocketDebuggerUrl || ''); - const probedInfo = probedByWsUrl.get(wsUrl) || null; + const primaryIdeChat = target.isIdeWorkbench ? pickPrimaryIdeChatTarget(target) : null; + const probeKeyWs = target.isIdeWorkbench + ? String(primaryIdeChat?.webSocketDebuggerUrl || '') + : wsUrl; + const probedInfo = (probeKeyWs && probedByWsUrl.get(probeKeyWs)) || null; const cls = classifyWindowTargetEndpoint({ target, probedInfo, localHubInfo, confirmedLocalPorts, }); - if (cls.isRemote && wsUrl) { + const effectiveRemoteWsUrl = String( + cls.remoteWsUrl || (target.isIdeWorkbench ? '' : wsUrl) + ).trim(); + target.forceTopbarMode = false; + if (target.isIdeWorkbench && cls.isRemote && !effectiveRemoteWsUrl) { + // Remote-SSH 目标服务器未安装/未打开 VS Code Antigravity 扩展时: + // 进一步探测远端是否安装了 `agy` CLI 的 `usage-monitor` 插件; + // 若已装 CLI 插件,则强制在 VS Code 顶部栏挂载并通过按需 SSH 隧道直连远端 CLI;否则不启用。 + const sshHost = String(cls.hostLabel || '').trim(); + const remoteCliState = + activeRemoteCliBridge && sshHost + ? activeRemoteCliBridge.getOrScheduleHost(sshHost) + : null; + if (remoteCliState?.hasCliPlugin === true) { + activeRemoteCliHosts.add(remoteCliState.host || sshHost); + target.skipOverlayInjection = false; + target.forceTopbarMode = true; + const tunOrigin = + remoteCliState.tunnelReady && remoteCliState.localPort > 0 + ? `${remoteCliState.protocol || 'http'}://127.0.0.1:${remoteCliState.localPort}` + : ''; + const ep = registerRemoteEndpoint({ + origin: tunOrigin, + baseUrl: tunOrigin, + csrfToken: remoteCliState.csrfToken || '', + wsUrl, + label: `${sshHost} (CLI)`, + stableHostKey: `ssh-cli:${sshHost}`, + tier1Only: true, + }); + target.endpointId = ep.id; + target.isRemoteEndpoint = true; + target.endpointLabel = ep.label; + if (wsUrl) activeRemoteWsUrls.add(wsUrl); + } else { + target.skipOverlayInjection = true; + target.endpointId = LOCAL_ENDPOINT_ID; + target.isRemoteEndpoint = false; + target.endpointLabel = ''; + } + } else if (cls.isRemote && effectiveRemoteWsUrl) { + target.skipOverlayInjection = false; const ep = registerRemoteEndpoint({ origin: cls.origin, baseUrl: cls.origin, csrfToken: cls.csrfToken, - wsUrl, + wsUrl: effectiveRemoteWsUrl, label: cls.hostLabel, stableHostKey: cls.stableHostKey, }); target.endpointId = ep.id; target.isRemoteEndpoint = true; target.endpointLabel = ep.label; - activeRemoteWsUrls.add(wsUrl); + activeRemoteWsUrls.add(effectiveRemoteWsUrl); + } else if (target.isVsCodeHost) { + // 本机标准 VS Code 窗口:同时检测 VS Code Antigravity 扩展与本机 `agy` CLI 插件; + // 仅装了 CLI 插件、未装 VS Code 扩展时强制显示在顶部栏;两者都未装则不启用。 + const hasLocalExt = + (Array.isArray(target.ideChatTargets) && target.ideChatTargets.length > 0) || + localHasVsCodeExt; + if (hasLocalExt) { + target.skipOverlayInjection = false; + target.forceTopbarMode = false; + } else if (localHasCliPlugin) { + target.skipOverlayInjection = false; + target.forceTopbarMode = true; + } else { + target.skipOverlayInjection = true; + target.forceTopbarMode = false; + } + target.endpointId = LOCAL_ENDPOINT_ID; + target.isRemoteEndpoint = false; + target.endpointLabel = ''; } else { + target.skipOverlayInjection = false; target.endpointId = LOCAL_ENDPOINT_ID; target.isRemoteEndpoint = false; target.endpointLabel = ''; } + if (Array.isArray(target.ideChatTargets)) { + for (const ct of target.ideChatTargets) { + ct.endpointId = target.endpointId; + ct.isRemoteEndpoint = target.isRemoteEndpoint; + ct.endpointLabel = target.endpointLabel; + } + } } + activeRemoteCliBridge?.pruneInactiveHosts?.(activeRemoteCliHosts); if (needsAnyCdpContext || hadContextWindows) { const localFallbackRes = needsAnyCdpContext @@ -2207,7 +2714,7 @@ export function createWindowBridgeController(options) { const remoteFallbackRulesById = new Map(); const uniqueRemoteIds = new Set( targets - .filter((t) => !t.isIdeWorkbench && t.isRemoteEndpoint && t.endpointId) + .filter((t) => t.isRemoteEndpoint && t.endpointId) .map((t) => t.endpointId) ); for (const cachedKey of Array.from(cachedBackendCtxModelsByEndpoint.keys())) { @@ -2261,27 +2768,40 @@ export function createWindowBridgeController(options) { } ctxEvalTasks.push(evaluateOnTarget(wsUrl, expr)); } - const ideChatExpr = !needsAnyCdpContext - ? createContextWindowSyncExpression({}, contextWindowBootId, {}, false, null) - : pinMainBackToDefaults - ? createContextWindowSyncExpression( + for (const target of targets) { + if (!Array.isArray(target?.ideChatTargets)) continue; + for (const ct of target.ideChatTargets) { + const chatUrl = String(ct?.webSocketDebuggerUrl || '').trim(); + if (!chatUrl || seenCtxUrls.has(chatUrl)) continue; + seenCtxUrls.add(chatUrl); + let chatExpr; + if (!needsAnyCdpContext) { + chatExpr = createContextWindowSyncExpression({}, contextWindowBootId, {}, false, null); + } else if (pinMainBackToDefaults) { + chatExpr = target.isRemoteEndpoint + ? createContextWindowSyncExpression({}, contextWindowBootId, {}, false, null) + : createContextWindowSyncExpression( + contextWindows, + contextWindowBootId, + pinBackRules, + false, + pinBackRules + ); + } else { + const epFallback = + target.isRemoteEndpoint && target.endpointId + ? remoteFallbackRulesById.get(target.endpointId) || localFallbackRules + : localFallbackRules; + chatExpr = createContextWindowSyncExpression( contextWindows, contextWindowBootId, - pinBackRules, - false, - pinBackRules - ) - : createContextWindowSyncExpression( - contextWindows, - contextWindowBootId, - localFallbackRules, + epFallback, false, null ); - for (const chatUrl of collectAllChatDebuggerUrls(targets)) { - if (!chatUrl || seenCtxUrls.has(chatUrl)) continue; - seenCtxUrls.add(chatUrl); - ctxEvalTasks.push(evaluateOnTarget(chatUrl, ideChatExpr)); + } + ctxEvalTasks.push(evaluateOnTarget(chatUrl, chatExpr)); + } } await Promise.allSettled(ctxEvalTasks); hadContextWindows = needsAnyCdpContext; @@ -2369,7 +2889,8 @@ export function createWindowBridgeController(options) { } } - if (!enabled) { + const hasActiveVsCodeTarget = targets.some((t) => t.isVsCodeHost && !t.skipOverlayInjection); + if (!enabled && !hasActiveVsCodeTarget) { pruneStaleRemoteEndpoints(activeRemoteWsUrls); if (!hadInjectedTargets && !hadInjectedChatFrames && !forceReinject) { updateBridgeStatus('disabled', { @@ -2437,11 +2958,121 @@ export function createWindowBridgeController(options) { const ideChatRouteProbeExpr = `(() => { try { + const readRouteId = () => ${domRouteExpr}; const visible = ${WINDOW_VISIBLE_EXPR}; const focused = Boolean( typeof document !== 'undefined' && typeof document.hasFocus === 'function' && document.hasFocus() ); - const routeCascadeId = ${domRouteExpr}; + const routeCascadeId = readRouteId(); + try { + const bridgePort = ${Number(port) || 0}; + const bridgeToken = ${JSON.stringify(String(token || ''))}; + if (bridgePort > 0 && bridgeToken && typeof window !== 'undefined' && typeof fetch === 'function') { + const existing = window.__agUsageMonitorRouteWatcher; + if (existing && typeof existing === 'object') { + existing.port = bridgePort; + existing.token = bridgeToken; + existing.lastRouteId = routeCascadeId; + } else { + const watcher = { + port: bridgePort, + token: bridgeToken, + lastRouteId: routeCascadeId, + timer: null, + ping(force = false) { + try { + const nextId = force ? null : readRouteId(); + if (!force && nextId === watcher.lastRouteId) return; + if (!force) watcher.lastRouteId = nextId; + fetch('http://127.0.0.1:' + watcher.port + '/api/bridge-route-ping', { + method: 'POST', + headers: { 'X-Usage-Monitor-Token': watcher.token }, + keepalive: true, + }).catch(() => {}); + } catch { + // 忽略路由通知异常 + } + }, + schedule(delayMs = 120) { + if (typeof setTimeout !== 'function') return; + if (watcher.timer) clearTimeout(watcher.timer); + watcher.timer = setTimeout(() => { + watcher.timer = null; + watcher.ping(false); + }, delayMs); + }, + dispose() { + if (watcher.timer) { + clearTimeout(watcher.timer); + watcher.timer = null; + } + try { watcher.observer?.disconnect?.(); } catch {} + try { + if (typeof window.removeEventListener === 'function') { + window.removeEventListener('popstate', watcher.onRoute); + window.removeEventListener('hashchange', watcher.onRoute); + window.removeEventListener('pagehide', watcher.onHide); + } + if (typeof document !== 'undefined' && typeof document.removeEventListener === 'function') { + document.removeEventListener('visibilitychange', watcher.onRoute); + } + } catch {} + delete window.__agUsageMonitorRouteWatcher; + }, + }; + watcher.onRoute = () => watcher.schedule(60); + watcher.onHide = () => watcher.ping(true); + if (typeof window.addEventListener === 'function') { + window.addEventListener('popstate', watcher.onRoute); + window.addEventListener('hashchange', watcher.onRoute); + window.addEventListener('pagehide', watcher.onHide); + } + if (typeof document !== 'undefined' && typeof document.addEventListener === 'function') { + document.addEventListener('visibilitychange', watcher.onRoute); + } + if (typeof history !== 'undefined' && history && !history.__agRouteWrapped) { + try { + const origPush = history.pushState; + const origReplace = history.replaceState; + if (typeof origPush === 'function') { + history.pushState = function (...args) { + const out = origPush.apply(this, args); + window.__agUsageMonitorRouteWatcher?.schedule?.(40); + return out; + }; + } + if (typeof origReplace === 'function') { + history.replaceState = function (...args) { + const out = origReplace.apply(this, args); + window.__agUsageMonitorRouteWatcher?.schedule?.(40); + return out; + }; + } + history.__agRouteWrapped = true; + } catch {} + } + if ( + typeof MutationObserver === 'function' && + typeof document !== 'undefined' && + document.documentElement + ) { + try { + const mo = new MutationObserver(() => watcher.schedule(140)); + mo.observe(document.documentElement, { + subtree: true, + childList: true, + attributes: true, + attributeFilter: ['data-cascade-id', 'data-selected', 'hidden'], + }); + watcher.observer = mo; + } catch {} + } + window.__agUsageMonitorRouteWatcher = watcher; + } + } + } catch { + // 忽略被动路由监听挂载异常 + } return { routeCascadeId, visible, focused }; } catch { return { routeCascadeId: '', visible: false, focused: false }; @@ -2453,29 +3084,38 @@ export function createWindowBridgeController(options) { Math.min(Number(cdpTimeoutMs) || IDE_ROUTE_PROBE_MAX_TIMEOUT_MS, IDE_ROUTE_PROBE_MAX_TIMEOUT_MS) ); - async function resolveIdeWorkbenchRouteId(targetObj) { + async function resolveIdeWorkbenchRouteState(targetObj) { const staticRouteId = sanitizeRouteCascadeId(targetObj?.ideRouteCascadeId); const chatList = Array.isArray(targetObj?.ideChatTargets) ? targetObj.ideChatTargets : []; const probeUrls = chatList .map((chatTarget) => String(chatTarget?.webSocketDebuggerUrl || '').trim()) .filter(Boolean); if (probeUrls.length === 0) { - return staticRouteId; + return { resolved: true, routeId: staticRouteId }; } if (probeUrls.length === 1) { try { const res = await evaluateOnTarget(probeUrls[0], ideChatRouteProbeExpr, ideRouteProbeTimeoutMs); - const cid = sanitizeRouteCascadeId(res?.result?.result?.value?.routeCascadeId); - return cid || staticRouteId; + const val = res?.result?.result?.value; + if (res && !res.error && !res.result?.exceptionDetails && val && typeof val === 'object') { + const rawCid = typeof val.routeCascadeId === 'string' ? val.routeCascadeId.trim() : ''; + const cid = sanitizeRouteCascadeId(rawCid); + if (cid) return { resolved: true, routeId: cid }; + if (rawCid === '' && val.routeCascadeId === '') { + return { resolved: true, routeId: '' }; + } + } + return { resolved: false, routeId: staticRouteId }; } catch { - return staticRouteId; + return { resolved: false, routeId: staticRouteId }; } } const abortCtrl = typeof AbortController === 'function' ? new AbortController() : null; const results = new Array(probeUrls.length).fill(null); let settledCount = 0; + let anyExplicitEmpty = false; let resolved = false; return new Promise((resolve) => { @@ -2490,7 +3130,12 @@ export function createWindowBridgeController(options) { if (bestRank === 3) break; } } - return bestRouteId || staticRouteId; + if (bestRouteId) { + return { resolved: true, routeId: bestRouteId }; + } + return anyExplicitEmpty + ? { resolved: true, routeId: '' } + : { resolved: false, routeId: staticRouteId }; }; const finishEarly = (routeId) => { @@ -2501,7 +3146,7 @@ export function createWindowBridgeController(options) { } catch { // 忽略中止异常 } - resolve(routeId); + resolve({ resolved: true, routeId }); }; probeUrls.forEach((chatWsUrl, idx) => { @@ -2513,12 +3158,17 @@ export function createWindowBridgeController(options) { ) .then((res) => { const val = res?.result?.result?.value; - const cid = sanitizeRouteCascadeId(val?.routeCascadeId); - if (cid) { - const rank = val?.focused && val?.visible ? 3 : val?.visible ? 2 : 1; - results[idx] = { cid, rank }; - if (rank === 3) { - finishEarly(cid); + if (res && !res.error && !res.result?.exceptionDetails && val && typeof val === 'object') { + const rawCid = typeof val.routeCascadeId === 'string' ? val.routeCascadeId.trim() : ''; + const cid = sanitizeRouteCascadeId(rawCid); + if (cid) { + const rank = val.focused && val.visible ? 3 : val.visible ? 2 : 1; + results[idx] = { cid, rank }; + if (rank === 3) { + finishEarly(cid); + } + } else if (rawCid === '' && val.routeCascadeId === '') { + anyExplicitEmpty = true; } } }) @@ -2542,14 +3192,25 @@ export function createWindowBridgeController(options) { let relayedRpcCount = 0; let sawCdpTransport = false; - async function syncSingleTarget(targetObj, { ideRouteOverride = '', isIdeChatFrame = false } = {}) { + async function syncSingleTarget( + targetObj, + { + ideRouteOverride = '', + ideRouteResolved = false, + isIdeChatFrame = false, + effectiveMountMode = mountMode, + } = {} + ) { const wsUrl = String(targetObj?.webSocketDebuggerUrl || '').trim(); if (!wsUrl) return { alive: false, dockKind: '', visible: false }; let probedRouteId = ''; - const ideRouteId = sanitizeRouteCascadeId(ideRouteOverride || targetObj.ideRouteCascadeId); + const ideRouteId = ideRouteResolved + ? sanitizeRouteCascadeId(ideRouteOverride) + : sanitizeRouteCascadeId(ideRouteOverride || targetObj.ideRouteCascadeId); const targetEndpointId = String(targetObj.endpointId || LOCAL_ENDPOINT_ID); const targetIsRemote = Boolean(targetObj.isRemoteEndpoint && targetEndpointId !== LOCAL_ENDPOINT_ID); const targetEndpointLabel = targetIsRemote ? String(targetObj.endpointLabel || 'SSH') : ''; + const targetMountMode = effectiveMountMode || mountMode; if (!forceReinject) { const probeRes = await evaluateOnTarget(wsUrl, probeExpr); @@ -2586,10 +3247,10 @@ export function createWindowBridgeController(options) { await evaluateOnTarget(wsUrl, rebindExpr); } let effectiveDockKind = String(snap.dockKind || ''); - if (snap.clientMountMode && snap.clientMountMode !== mountMode) { + if (snap.clientMountMode && snap.clientMountMode !== targetMountMode) { const modeSyncExpr = `(() => { const overlay = ${windowOverlayRef}; - overlay?.[${overlayMethods.applyMountMode}]?.(${JSON.stringify(mountMode)}); + overlay?.[${overlayMethods.applyMountMode}]?.(${JSON.stringify(targetMountMode)}); return String(overlay?.[${overlayMethods.getDockKind}]?.() || ''); })()`; const modeRes = await evaluateOnTarget(wsUrl, modeSyncExpr); @@ -2599,7 +3260,7 @@ export function createWindowBridgeController(options) { } if ( (targetObj.isIdeWorkbench || isIdeChatFrame) && - ideRouteId && + (ideRouteResolved || ideRouteId) && String(snap.hostRouteCascadeId || '') !== ideRouteId ) { const routeSyncExpr = `(() => { @@ -2669,7 +3330,9 @@ export function createWindowBridgeController(options) { token, bundleVersion, platform: String(platform || ''), - mountMode, + mountMode: targetMountMode, + isVsCodeHost: Boolean(targetObj.isVsCodeHost), + forceTopbarMode: Boolean(targetObj.forceTopbarMode), [WINDOW_BRIDGE_ENDPOINT_KEY]: targetEndpointId, isRemoteEndpoint: targetIsRemote, endpointLabel: targetEndpointLabel, @@ -2715,16 +3378,47 @@ export function createWindowBridgeController(options) { return { alive: false, dockKind: '', visible: false }; } - if (mountMode !== 'composer' && (hadInjectedChatFrames || forceReinject)) { - for (const chatWsUrl of collectAllChatDebuggerUrls(targets)) { - await disposeSingleTarget(chatWsUrl); + const vsCodeMountMode = curSettings?.vsCodeMountMode === 'dual' ? 'dual' : 'composer'; + const resolveTargetMountMode = (t) => { + // 未装 VS Code Antigravity 扩展、仅装了 agy CLI 插件时,强制挂载在顶部栏 + if (t?.forceTopbarMode) return 'dual'; + // 标准 VS Code 没有 Antigravity 2.0 辅助侧边栏,不允许进入 sidebar 模式;默认输入框挂载(Composer) + if (t?.isVsCodeHost) return vsCodeMountMode; + return mountMode; + }; + + if (hadInjectedChatFrames || forceReinject) { + let keptAnyChatFrame = false; + for (const t of targets) { + const tMode = resolveTargetMountMode(t); + if (tMode === 'composer' && !t.skipOverlayInjection && (enabled || t.isVsCodeHost)) { + if (Array.isArray(t.ideChatTargets) && t.ideChatTargets.length > 0) { + keptAnyChatFrame = true; + } + continue; + } + if (Array.isArray(t.ideChatTargets)) { + for (const ct of t.ideChatTargets) { + if (ct?.webSocketDebuggerUrl) { + await disposeSingleTarget(ct.webSocketDebuggerUrl); + } + } + } + } + if (!keptAnyChatFrame) { + hadInjectedChatFrames = false; } - hadInjectedChatFrames = false; } for (const target of targets) { try { - if (mountMode === 'composer' && target.isIdeWorkbench) { + if (target.skipOverlayInjection || (!enabled && !target.isVsCodeHost)) { + await disposeSingleTarget(target.webSocketDebuggerUrl); + continue; + } + + const targetMountMode = resolveTargetMountMode(target); + if (targetMountMode === 'composer' && target.isIdeWorkbench) { const chatList = Array.isArray(target.ideChatTargets) ? target.ideChatTargets : []; let chatComposerActive = false; for (const chatTarget of chatList) { @@ -2733,6 +3427,7 @@ export function createWindowBridgeController(options) { const chatState = await syncSingleTarget(chatTarget, { ideRouteOverride: chatTarget.cascadeId || target.ideRouteCascadeId, isIdeChatFrame: true, + effectiveMountMode: 'composer', }); if (chatState.alive && chatState.visible && chatState.dockKind === 'composer') { chatComposerActive = true; @@ -2741,19 +3436,28 @@ export function createWindowBridgeController(options) { // 单个聊天子视图异常不阻断主窗口兜底 } } - if (chatComposerActive) { + if (chatComposerActive || target.isVsCodeHost) { + // VS Code 扩展默认只在聊天输入框内挂载;扩展未打开或尚未就绪时不污染 VS Code 顶栏 await disposeSingleTarget(target.webSocketDebuggerUrl); } else { - const ideRouteOverride = await resolveIdeWorkbenchRouteId(target); - await syncSingleTarget(target, { ideRouteOverride }); + const routeState = await resolveIdeWorkbenchRouteState(target); + await syncSingleTarget(target, { + ideRouteOverride: routeState.routeId, + ideRouteResolved: routeState.resolved, + effectiveMountMode: targetMountMode, + }); } continue; } - const ideRouteOverride = target.isIdeWorkbench - ? await resolveIdeWorkbenchRouteId(target) - : ''; - await syncSingleTarget(target, { ideRouteOverride }); + const routeState = target.isIdeWorkbench + ? await resolveIdeWorkbenchRouteState(target) + : { resolved: false, routeId: '' }; + await syncSingleTarget(target, { + ideRouteOverride: routeState.routeId, + ideRouteResolved: routeState.resolved, + effectiveMountMode: targetMountMode, + }); } catch { // 单个窗口注入异常不阻断其他窗口 } @@ -2880,6 +3584,10 @@ export function createWindowBridgeController(options) { clearTimeout(pollTimer); pollTimer = null; } + if (routePingTimer) { + clearTimeout(routePingTimer); + routePingTimer = null; + } if ( disposeWindows && (hadInjectedTargets || hadInjectedChatFrames || hadContextWindows || hadHostI18n) @@ -2894,6 +3602,7 @@ export function createWindowBridgeController(options) { })); const disposeExpr = `(() => { try { + window.__agUsageMonitorRouteWatcher?.dispose?.(); ${windowHostI18nRef}?.dispose?.(); ${windowContextWindowsRef}?.dispose?.(); ${windowOverlayRef}?.[${overlayMethods.dispose}]?.(); @@ -2926,6 +3635,9 @@ export function createWindowBridgeController(options) { if (activeCloudCodeProxy) { await activeCloudCodeProxy.stop().catch(() => {}); } + if (activeRemoteCliBridge) { + activeRemoteCliBridge.stopAll?.(); + } if (bindRemoteRpcInvoker) { setRemoteWindowRpcInvoker(null); } diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index fe3baff..7cb6b1e 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/shared/window-bridge-protocol.mjs b/sidecars/panel/shared/window-bridge-protocol.mjs index 71527b6..885a4ae 100644 --- a/sidecars/panel/shared/window-bridge-protocol.mjs +++ b/sidecars/panel/shared/window-bridge-protocol.mjs @@ -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; +} diff --git a/sidecars/panel/src/components/layout/WindowOverlayShell.js b/sidecars/panel/src/components/layout/WindowOverlayShell.js index 12acb84..052d7af 100644 --- a/sidecars/panel/src/components/layout/WindowOverlayShell.js +++ b/sidecars/panel/src/components/layout/WindowOverlayShell.js @@ -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) { diff --git a/sidecars/panel/src/components/layout/overlayHostAnchors.js b/sidecars/panel/src/components/layout/overlayHostAnchors.js index 8c04fc2..7fd8de8 100644 --- a/sidecars/panel/src/components/layout/overlayHostAnchors.js +++ b/sidecars/panel/src/components/layout/overlayHostAnchors.js @@ -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( diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 83fcb67..8e3e009 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -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.', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 54fb202..974fc1b 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -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(后续通过常规快捷方式打开均自动生效)。点击下方按钮即可退出后台进程并立即生效。', diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index d9b8f5c..17710a4 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -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; }; diff --git a/sidecars/panel/src/views/settings/SettingsStructureTab.js b/sidecars/panel/src/views/settings/SettingsStructureTab.js index 51f3544..1453519 100644 --- a/sidecars/panel/src/views/settings/SettingsStructureTab.js +++ b/sidecars/panel/src/views/settings/SettingsStructureTab.js @@ -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; diff --git a/sidecars/panel/test/vscode-extension-support.test.mjs b/sidecars/panel/test/vscode-extension-support.test.mjs new file mode 100644 index 0000000..360e803 --- /dev/null +++ b/sidecars/panel/test/vscode-extension-support.test.mjs @@ -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')); +});