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

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