From 76669d5cc77fd11b52a28b079c30525307edbc51 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Mon, 16 Nov 2026 02:28:34 +0900 Subject: [PATCH] feat(panel): add standalone Web monitor mode and full Antigravity CLI 1.5.9 telemetry support - Add zero-SDK standalone HTTP server (`standalone.mjs` / `standalone-server.mjs`) with responsive centered Web shell, `127.0.0.1` default loopback guard, mandatory `--token` enforcement on non-loopback binds (`HttpOnly; SameSite=Strict` cookie + `Bearer` auth), and optional background auto-hosting via `standalonePort` / `USAGE_MONITOR_STANDALONE_PORT`. - Extend multi-root data discovery across `~/.gemini/antigravity` and `~/.gemini/antigravity-cli`, plus `daemon/hub_*.json` and `/proc` + `ss` Language Server endpoint discovery on minimal headless Linux hosts without `lsof`. - Add read-only `node:sqlite` + lightweight protobuf wire reader (`cli-sqlite-reader.mjs`) to recover CLI session titles (`annotations/*.pbtxt` & `conversation_summaries.db`), nanosecond request duration/TPS, native TTFT, thinking/response token split, 10-channel context breakdown, and `Antigravity CLI` source attribution. - Add regression tests (124 passing) and bilingual CLI / SSH tunnel / `--token` documentation in `README.zh-CN.md` and `README.md`. Closes #18 --- README.md | 16 +- README.zh-CN.md | 16 +- sidecars/panel/app.js | 13 + sidecars/panel/backend/api-actions.mjs | 26 + sidecars/panel/backend/cli-sqlite-reader.mjs | 883 +++++++++++++++++++ sidecars/panel/backend/config.mjs | 100 ++- sidecars/panel/backend/local-scanner.mjs | 708 ++++++++++++++- sidecars/panel/backend/ls-discovery.mjs | 260 +++++- sidecars/panel/backend/settings-schema.mjs | 16 + sidecars/panel/backend/standalone-server.mjs | 639 ++++++++++++++ sidecars/panel/backend/telemetry-builder.mjs | 26 +- sidecars/panel/bridge-daemon.mjs | 107 ++- sidecars/panel/index.html | 4 +- sidecars/panel/package.json | 1 + sidecars/panel/src/main.js | 8 + sidecars/panel/src/store/telemetryStore.js | 5 + sidecars/panel/src/styles/base.css | 13 + sidecars/panel/src/styles/tokens.css | 12 + sidecars/panel/standalone.mjs | 123 +++ sidecars/panel/styles.css | 25 + sidecars/panel/test/backend-harness.mjs | 16 +- sidecars/panel/test/backend.test.mjs | 446 +++++++++- sidecars/panel/test/window-bridge.test.mjs | 278 ++++++ 23 files changed, 3631 insertions(+), 110 deletions(-) create mode 100644 sidecars/panel/backend/cli-sqlite-reader.mjs create mode 100644 sidecars/panel/backend/standalone-server.mjs create mode 100644 sidecars/panel/standalone.mjs diff --git a/README.md b/README.md index 8911e06..f730db3 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,8 @@ English | [简体中文](README.zh-CN.md) -**Real-time dual-mount monitor for Google Antigravity IDE.** -Track token generation speed (TPS), time-to-first-token (TTFT), context window usage, official model quotas, subagent activity, and historical token consumption — across Windows, macOS, and Linux. +**Real-time usage & speed monitor for Google Antigravity 2.0, IDE, and CLI.**
+Track token generation speed (TPS), time-to-first-token (TTFT), context window usage, official model quotas, subagent activity, and historical token consumption — across Windows, macOS, Linux, and headless CLI servers. ![Antigravity Usage Monitor Preview](assets/preview.png) @@ -103,6 +103,18 @@ Expand-Archive -Path "$env:TEMP\usage-monitor.zip" -DestinationPath $pluginsDir - **Antigravity 2.0 App**: Immediately mounts a live status & metric capsule in the top-right bar of the main chat window (hover for quick overview, left-click to expand the full 4-tab panel, right-click to force refresh) without modifying `app.asar`. - **Antigravity IDE**: On first enable, the background sidecar automatically adds `"remote-debugging-port": "0"` to `~/.antigravity-ide/argv.json` (preserving comments and existing settings). **Restart Antigravity IDE once**, and the capsule will dock into the top-right IDE window titlebar on every launch. Because Antigravity IDE does not currently expose the right-hand UI Sidecar auxiliary pane, keep **Mount Mode** set to *Dual-mount* in IDE and click the top-bar capsule to open the 4-tab dashboard. 3. **Right-Hand Sidebar Panel (Antigravity 2.0)**: Open the auxiliary sidebar menu in the chat window to dock **Usage & Speed Monitor** on the right, or switch **Mount Mode** between *Top Bar + Sidebar* and *Sidebar only* in Preferences. +4. **Headless CLI / `agy remote-control serve` Standalone Web Mode**: + - On terminal-only machines or remote Linux servers, the backend automatically discovers `~/.gemini/antigravity-cli` (`daemon/hub_*.json`, conversations, and `transcript.jsonl`). When `agy` is offline, historical sessions and token accounting still load from local transcripts/cache and automatically upgrade to full live RPC telemetry once `agy` starts. + - **Manual launch (recommended with SSH port forwarding)**: + ```bash + # On the remote server (binds strictly to 127.0.0.1:8787 by default) + node ~/.gemini/config/plugins/usage-monitor/sidecars/panel/standalone.mjs --port 8787 + + # Forward from your local machine, then open http://localhost:8787 + ssh -L 8787:127.0.0.1:8787 user@your-server + ``` + - **Auto-host alongside `agy`**: Set `USAGE_MONITOR_STANDALONE_PORT=8787` or `"standalonePort": 8787` in `~/.gemini/antigravity-cli/sidecar_data/usage-monitor/panel/data/settings.json` to host the standalone Web UI automatically whenever the plugin's MCP supervisor starts. + - **Token-protected non-loopback access**: Binding to `0.0.0.0` or a LAN IP requires `--token ` (or `USAGE_MONITOR_STANDALONE_TOKEN`); unauthenticated non-loopback startup is refused. ## Updating diff --git a/README.zh-CN.md b/README.zh-CN.md index ac12558..ebf4263 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -2,8 +2,8 @@ [English](README.md) | 简体中文 -**Google Antigravity IDE 实时双栖监控插件。** -一站式查看生成速度(TPS)、首字延迟(TTFT)、十维上下文窗口占用、官方模型配额、子代理追踪与历史 Token 消耗(支持 Windows / macOS / Linux)。 +**Google Antigravity 2.0 / IDE / CLI 实时监控插件。**
+一站式查看生成速度(TPS)、首字延迟(TTFT)、十维上下文窗口占用、官方模型配额、子代理追踪与历史 Token 消耗(支持 Windows / macOS / Linux 及无头服务器 CLI)。 ![Antigravity Usage Monitor 界面预览](assets/preview.png) @@ -103,6 +103,18 @@ Expand-Archive -Path "$env:TEMP\usage-monitor.zip" -DestinationPath $pluginsDir - **Antigravity 2.0 桌面端**:开启插件后即自动在主对话窗口右上角顶部栏挂载实时状态与指标胶囊(悬停查看速览,左键展开完整四标签面板,右键强制刷新),全程不修改宿主 `app.asar`。 - **Antigravity IDE**:首次启用插件时,后台 Sidecar 会自动在 `~/.antigravity-ide/argv.json` 中补齐 `"remote-debugging-port": "0"`(保留原有注释与配置)。**完整重启一次 Antigravity IDE** 后,胶囊会自动停靠在 IDE 窗口最上方标题栏右侧。由于 Antigravity IDE 宿主暂未开放右侧 UI Sidecar 辅助栏,在 IDE 中请保持「双栖挂载」并直接点击顶部栏胶囊打开四标签面板。 3. **右侧辅助栏面板(Antigravity 2.0)**:在 Antigravity 2.0 对话窗口点击右上角菜单打开右侧辅助栏中的 **用量监控**,或在 **偏好设置 -> 面板挂载方式** 中按需切换「顶部栏 + 侧边栏」与「仅侧边栏」。 +4. **无头 CLI / `agy remote-control serve` 独立 Web 模式**: + - 在纯终端或远程 Linux 服务器上,插件会自动扫描 `~/.gemini/antigravity-cli`(含 `daemon/hub_*.json`、对话轨迹与 `transcript.jsonl`);即使 `agy` 暂未运行,也会基于本地日志离线展示历史会话与 Token 消耗,并在 `agy` 启动后自动重连升级为完整遥测。 + - **手动启动(推荐配合 SSH 端口转发)**: + ```bash + # 在远程服务器上启动(默认仅监听 127.0.0.1:8787) + node ~/.gemini/config/plugins/usage-monitor/sidecars/panel/standalone.mjs --port 8787 + + # 在本地电脑转发端口后,浏览器打开 http://localhost:8787 + ssh -L 8787:127.0.0.1:8787 user@your-server + ``` + - **随 `agy` 后台自动托管**:设置环境变量 `USAGE_MONITOR_STANDALONE_PORT=8787`,或在 `~/.gemini/antigravity-cli/sidecar_data/usage-monitor/panel/data/settings.json` 中写入 `"standalonePort": 8787`,启用插件后即随 `agy` 自动监听该端口。 + - **非回环地址受保护访问**:若需显式绑定 `0.0.0.0` 或局域网地址,必须同时指定 `--token <密钥>`(或 `USAGE_MONITOR_STANDALONE_TOKEN`),未配置令牌时服务端会拒绝非回环启动。 ## 更新 diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index bd8398c..aa696f0 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -3392,6 +3392,11 @@ async function saveSettingsPatch(patch) { if (Object.prototype.hasOwnProperty.call(safePatch, 'orchestratorIdMode')) { safePatch.orchestratorIdMode = normalizeClientOrchestratorIdMode(safePatch.orchestratorIdMode); } + if (Object.prototype.hasOwnProperty.call(safePatch, 'standalonePort')) { + const numPort = Number(safePatch.standalonePort); + safePatch.standalonePort = + Number.isInteger(numPort) && numPort >= 1024 && numPort <= 65535 ? numPort : 0; + } if (Object.prototype.hasOwnProperty.call(safePatch, 'windowMountMode')) { const normMount = normalizeClientWindowMountMode( safePatch.windowMountMode, @@ -20182,6 +20187,14 @@ function startEntry() { mountWindowOverlay(); return; } + if ( + typeof window !== 'undefined' && + !window.sidecar?.fetch && + typeof document !== 'undefined' && + document.documentElement + ) { + document.documentElement.setAttribute('data-standalone', 'true'); + } bootstrapApp(); } diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index 9f49627..be908fb 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -50,6 +50,12 @@ import { export const bootBundleVersion = computeRuntimeCodeVersion(); +let standalonePortListener = null; + +export function setStandalonePortListener(listener) { + standalonePortListener = typeof listener === 'function' ? listener : null; +} + /** * 异步读取 `sidecars/panel` 目录下的静态资源文件(兼容单元测试同步沙箱)。 * @@ -299,6 +305,16 @@ export function executeSettingsAction(data) { ) { void notifyWindowOverlaySetting(updated.enableWindowOverlay); } + if ( + typeof standalonePortListener === 'function' && + Number(updated.standalonePort || 0) !== Number(current.standalonePort || 0) + ) { + try { + standalonePortListener(Number(updated.standalonePort || 0)); + } catch { + // 忽略独立端口热重载回调异常 + } + } return { ok: true, status: 200, @@ -371,6 +387,16 @@ export function executeResetSettingsAction() { } else if (Object.keys(current.modelContextWindows).length) { void notifyModelContextWindowsChanged(); } + if ( + typeof standalonePortListener === 'function' && + Number(updated.standalonePort || 0) !== Number(current.standalonePort || 0) + ) { + try { + standalonePortListener(Number(updated.standalonePort || 0)); + } catch { + // 忽略独立端口热重载回调异常 + } + } return { ok: true, status: 200, diff --git a/sidecars/panel/backend/cli-sqlite-reader.mjs b/sidecars/panel/backend/cli-sqlite-reader.mjs new file mode 100644 index 0000000..d4f6706 --- /dev/null +++ b/sidecars/panel/backend/cli-sqlite-reader.mjs @@ -0,0 +1,883 @@ +/** + * @fileoverview 本地 Antigravity CLI / Desktop SQLite 会话轨迹与 Protobuf 文本标题解析器。 + * + * 解决 `agy` CLI(进程内嵌随机端口 Language Server、无 `daemon/hub_*.json`、桌面 LS 无法跨目录读取 + * `~/.gemini/antigravity-cli`)下的完整遥测还原: + * 1. 解析 `/annotations/.pbtxt` 中的真实会话标题(兼容 UTF-8 直出与八进制/十六进制字节转义); + * 2. 通过 Node 22.5+ 内置 `node:sqlite` 只读扫描 `/conversation_summaries.db`,获取标题、实时运行状态与父会话归属; + * 3. 只读解码 `/conversations/.db` 的 `steps.metadata` 与 `gen_metadata.data` 轻量 Protobuf 字段 + * (跳过大体积提示词与工具载荷),完整还原纳秒级耗时、TTFT、思考/正文 Token 拆分、模型展示名与 10 通道上下文构成。 + */ + +import { existsSync, readFileSync, statSync } from 'node:fs'; +import { basename, join } from 'node:path'; +import { parseIsoMs } from '../speed-metrics.mjs'; +import { ANNOTATION_DIRS, PRODUCT_DATA_ROOTS, localSummaryMemo } from './config.mjs'; + +let sqliteResolved = false; +let sqliteDatabaseSyncCtor = null; + +/** + * 惰性获取 Node 内置 `node:sqlite` 的 `DatabaseSync` 构造器。 + * 首次加载时静默过滤 Node 22 的实验特性提示,避免污染 CLI 终端或 MCP 日志;不支持时返回 `null`。 + * + * @returns {Function | null} + */ +export function getNodeSqliteDatabaseSync() { + if (sqliteResolved) return sqliteDatabaseSyncCtor; + sqliteResolved = true; + if (typeof process === 'undefined' || typeof process.getBuiltinModule !== 'function') { + return null; + } + const origEmitWarning = process.emitWarning; + try { + if (typeof origEmitWarning === 'function') { + process.emitWarning = function filteredSqliteWarning(warning, ...rest) { + const msg = typeof warning === 'string' ? warning : String(warning?.message || ''); + if (/SQLite is an experimental feature/i.test(msg)) return; + return origEmitWarning.call(this, warning, ...rest); + }; + } + const mod = process.getBuiltinModule('node:sqlite'); + sqliteDatabaseSyncCtor = typeof mod?.DatabaseSync === 'function' ? mod.DatabaseSync : null; + } catch { + sqliteDatabaseSyncCtor = null; + } finally { + if (typeof origEmitWarning === 'function') { + process.emitWarning = origEmitWarning; + } + } + return sqliteDatabaseSyncCtor; +} + +/** + * 当前运行时是否具备内置 `node:sqlite` 读取能力。 + * + * @returns {boolean} + */ +export function hasBuiltinNodeSqlite() { + return Boolean(getNodeSqliteDatabaseSync()); +} + +/** + * 解码 Protobuf Text Format (`prototext`) 字符串字面量,兼容 UTF-8 原文与 `\ddd` / `\xHH` 字节转义。 + * + * @param {string} raw + * @returns {string} + */ +function unescapePbtxtString(raw) { + if (typeof raw !== 'string' || !raw) return ''; + if (!raw.includes('\\')) return raw; + const bytes = []; + for (let i = 0; i < raw.length; i++) { + const ch = raw[i]; + if (ch !== '\\' || i + 1 >= raw.length) { + const encoded = Buffer.from(ch, 'utf8'); + for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]); + continue; + } + const next = raw[++i]; + if (next >= '0' && next <= '7') { + let oct = next; + if (i + 1 < raw.length && raw[i + 1] >= '0' && raw[i + 1] <= '7') oct += raw[++i]; + if (i + 1 < raw.length && raw[i + 1] >= '0' && raw[i + 1] <= '7') oct += raw[++i]; + bytes.push(parseInt(oct, 8) & 0xff); + } else if ((next === 'x' || next === 'X') && i + 2 < raw.length) { + const hex = raw.slice(i + 1, i + 3); + if (/^[0-9a-fA-F]{2}$/.test(hex)) { + bytes.push(parseInt(hex, 16)); + i += 2; + } else { + bytes.push(next.charCodeAt(0)); + } + } else if (next === 'u' && i + 4 < raw.length) { + const uHex = raw.slice(i + 1, i + 5); + if (/^[0-9a-fA-F]{4}$/.test(uHex)) { + const encoded = Buffer.from(String.fromCharCode(parseInt(uHex, 16)), 'utf8'); + for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]); + i += 4; + } else { + bytes.push(next.charCodeAt(0)); + } + } else if (next === 'n') { + bytes.push(0x0a); + } else if (next === 'r') { + bytes.push(0x0d); + } else if (next === 't') { + bytes.push(0x09); + } else { + const encoded = Buffer.from(next, 'utf8'); + for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]); + } + } + return Buffer.from(bytes).toString('utf8'); +} + +/** + * 从 `annotations/.pbtxt` 文本内容中提取顶层 `title` 字段。 + * + * @param {string} rawText + * @returns {string} + */ +export function parseAnnotationPbtxtTitle(rawText) { + if (typeof rawText !== 'string' || !rawText) return ''; + const dq = rawText.match(/(?:^|\r?\n)\s*title\s*:\s*"((?:\\.|[^"\\])*)"/); + if (dq) { + return unescapePbtxtString(dq[1]).trim(); + } + const sq = rawText.match(/(?:^|\r?\n)\s*title\s*:\s*'((?:\\.|[^'\\])*)'/); + if (sq) { + return unescapePbtxtString(sq[1]).trim(); + } + return ''; +} + +/** + * 按会话 ID 在各产品目录的 `annotations/.pbtxt` 中查找标题。 + * + * @param {string} cascadeId + * @param {string[]} [annotationDirs=ANNOTATION_DIRS] + * @returns {string} + */ +export function readAnnotationTitleForCascade(cascadeId, annotationDirs = ANNOTATION_DIRS) { + const normId = String(cascadeId || '').trim().toLowerCase(); + if (!normId) return ''; + const dirs = Array.isArray(annotationDirs) ? annotationDirs : []; + for (const dir of dirs) { + if (!dir) continue; + const filePath = join(dir, `${normId}.pbtxt`); + if (!existsSync(filePath)) continue; + try { + const title = parseAnnotationPbtxtTitle(readFileSync(filePath, 'utf8')); + if (title) return title; + } catch { + // 忽略单文件读取失败 + } + } + return ''; +} + +function normalizeSqliteIsoTime(value) { + const raw = String(value || '').trim(); + if (!raw) return ''; + return raw.replace(/^(\d{4}-\d{2}-\d{2})\s+/, '$1T'); +} + +/** + * 读取并缓存各产品数据根目录下的 `conversation_summaries.db` 摘要索引。 + * 使用 `.db` 与 `.db-wal` 的 `mtimeMs + size` 组合签名做内存 Memoize,未发生写入时零 I/O 返回。 + * + * @param {string[]} [productRoots=PRODUCT_DATA_ROOTS] + * @returns {Map} + */ +export function readLocalSummaryIndex(productRoots = PRODUCT_DATA_ROOTS) { + const DatabaseSync = getNodeSqliteDatabaseSync(); + if (!DatabaseSync) return new Map(); + const roots = Array.isArray(productRoots) ? productRoots : []; + const sigParts = []; + const targets = []; + + for (const root of roots) { + if (!root) continue; + const dbPath = join(root, 'conversation_summaries.db'); + if (!existsSync(dbPath)) continue; + try { + const st = statSync(dbPath); + let walPart = '0:0'; + const walPath = `${dbPath}-wal`; + if (existsSync(walPath)) { + try { + const wst = statSync(walPath); + walPart = `${wst.mtimeMs || 0}:${wst.size || 0}`; + } catch { + // 忽略并发清理的 wal 文件 + } + } + sigParts.push(`${dbPath}:${st.mtimeMs || 0}:${st.size || 0}:${walPart}`); + targets.push({ rootName: basename(root).toLowerCase(), dbPath }); + } catch { + // 忽略不可访问的摘要库 + } + } + + if (targets.length === 0) { + localSummaryMemo.sig = ''; + localSummaryMemo.byId.clear(); + return localSummaryMemo.byId; + } + + const sig = sigParts.join('|'); + if (localSummaryMemo.sig === sig && localSummaryMemo.byId.size > 0) { + return localSummaryMemo.byId; + } + + const nextMap = new Map(); + for (const { rootName, dbPath } of targets) { + let db = null; + try { + db = new DatabaseSync(dbPath, { readOnly: true }); + const rows = db + .prepare( + `SELECT + conversation_id, + title, + status, + parent_conversation_id, + agent_name, + not_fully_idle, + killed, + step_count, + last_modified_time, + app_data_dir + FROM conversation_summaries` + ) + .all(); + for (const row of rows || []) { + const cidLower = String(row?.conversation_id || '').trim().toLowerCase(); + if (!cidLower) continue; + const appDataDir = String(row?.app_data_dir || '').trim().toLowerCase(); + const isNativeRootRow = Boolean(appDataDir && appDataDir === rootName); + const lastModifiedTime = normalizeSqliteIsoTime(row?.last_modified_time); + const lastModifiedMs = parseIsoMs(lastModifiedTime); + const rawStatus = String(row?.status || '').trim(); + const isRunning = + !Number(row?.killed) && + (rawStatus === 'CASCADE_RUN_STATUS_RUNNING' || + (Number(row?.not_fully_idle) > 0 && rawStatus !== 'CASCADE_RUN_STATUS_IDLE')); + const entry = { + cascadeId: cidLower, + title: String(row?.title || '').trim(), + status: isRunning ? 'CASCADE_RUN_STATUS_RUNNING' : rawStatus || 'CASCADE_RUN_STATUS_IDLE', + parentConversationId: String(row?.parent_conversation_id || '').trim().toLowerCase(), + agentName: String(row?.agent_name || '').trim(), + stepCount: Math.max(0, Math.floor(Number(row?.step_count) || 0)), + lastModifiedTime, + lastModifiedMs, + appDataDir, + isNativeRootRow, + }; + const prev = nextMap.get(cidLower); + if ( + !prev || + (entry.isNativeRootRow && !prev.isNativeRootRow) || + (entry.isNativeRootRow === prev.isNativeRootRow && + entry.lastModifiedMs >= prev.lastModifiedMs) + ) { + nextMap.set(cidLower, entry); + } + } + } catch { + // 忽略正在初始化或损坏的 SQLite 文件 + } finally { + if (db) { + try { + db.close(); + } catch { + // 忽略关闭异常 + } + } + } + } + + localSummaryMemo.sig = sig; + localSummaryMemo.byId = nextMap; + return nextMap; +} + +// --------------------------------------------------------------------------- +// 零依赖轻量 Protobuf Wire 解码器(仅提取指标字段,O(1) 跳过大体积 Prompt 载荷) +// --------------------------------------------------------------------------- + +function readProtoVarint(buf, state) { + let result = 0n; + let shift = 0n; + while (state.off < buf.length) { + const byte = BigInt(buf[state.off++]); + result |= (byte & 0x7fn) << shift; + if ((byte & 0x80n) === 0n) return result; + shift += 7n; + if (shift > 70n) throw new Error('Invalid protobuf varint'); + } + throw new Error('Unexpected EOF in protobuf varint'); +} + +function skipProtoField(buf, state, wireType) { + if (wireType === 0) { + readProtoVarint(buf, state); + } else if (wireType === 1) { + state.off += 8; + } else if (wireType === 2) { + const len = Number(readProtoVarint(buf, state)); + state.off += len; + } else if (wireType === 5) { + state.off += 4; + } else { + throw new Error(`Unsupported protobuf wireType: ${wireType}`); + } + if (state.off > buf.length) { + throw new Error('Protobuf field length out of bounds'); + } +} + +function decodeProtoTimestampIso(buf) { + const st = { off: 0 }; + let seconds = 0n; + let nanos = 0n; + while (st.off < buf.length) { + const tag = Number(readProtoVarint(buf, st)); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 0) { + seconds = BigInt.asIntN(64, readProtoVarint(buf, st)); + } else if (fn === 2 && wt === 0) { + nanos = BigInt.asIntN(32, readProtoVarint(buf, st)); + } else { + skipProtoField(buf, st, wt); + } + } + if (seconds <= 0n) return ''; + const baseIso = new Date(Number(seconds) * 1000).toISOString(); + const prefix = baseIso.slice(0, 19); + if (nanos > 0n && nanos < 1_000_000_000n) { + const frac = String(nanos).padStart(9, '0').replace(/0+$/, ''); + return frac ? `${prefix}.${frac}Z` : `${prefix}Z`; + } + return `${prefix}Z`; +} + +function decodeProtoDurationStr(buf) { + const st = { off: 0 }; + let seconds = 0n; + let nanos = 0n; + while (st.off < buf.length) { + const tag = Number(readProtoVarint(buf, st)); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 0) { + seconds = BigInt.asIntN(64, readProtoVarint(buf, st)); + } else if (fn === 2 && wt === 0) { + nanos = BigInt.asIntN(32, readProtoVarint(buf, st)); + } else { + skipProtoField(buf, st, wt); + } + } + if (seconds < 0n || nanos < 0n) return ''; + if (nanos === 0n) return `${seconds}s`; + const frac = String(nanos).padStart(9, '0').replace(/0+$/, ''); + return frac ? `${seconds}.${frac}s` : `${seconds}s`; +} + +function decodeProtoModelEnumInt(val) { + const n = Number(val); + if (Number.isInteger(n) && n >= 1000 && n < 10000) { + return `MODEL_PLACEHOLDER_M${n - 1000}`; + } + return ''; +} + +function decodeProtoTokenTypeEnum(val) { + switch (Number(val)) { + case 1: + return 'TOKEN_TYPE_SYSTEM_PROMPT'; + case 2: + return 'TOKEN_TYPE_TOOLS'; + case 3: + return 'TOKEN_TYPE_RULES'; + case 4: + return 'TOKEN_TYPE_MCP_TOOLS'; + case 5: + return 'TOKEN_TYPE_SKILLS'; + case 6: + return 'TOKEN_TYPE_SUBAGENTS'; + case 7: + return 'TOKEN_TYPE_CHAT_MESSAGES'; + default: + return ''; + } +} + +function decodeProtoStepTypeEnum(val) { + switch (Number(val)) { + case 14: + return 'CORTEX_STEP_TYPE_USER_INPUT'; + case 15: + return 'CORTEX_STEP_TYPE_PLANNER_RESPONSE'; + case 17: + return 'CORTEX_STEP_TYPE_ERROR_MESSAGE'; + case 23: + return 'CORTEX_STEP_TYPE_CHECKPOINT'; + case 101: + return 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE'; + default: + return 'CORTEX_STEP_TYPE_GENERIC'; + } +} + +function decodeProtoStepStatusEnum(val) { + switch (Number(val)) { + case 2: + return 'CORTEX_STEP_STATUS_RUNNING'; + case 3: + return 'CORTEX_STEP_STATUS_DONE'; + case 5: + return 'CORTEX_STEP_STATUS_CLEARED'; + case 6: + return 'CORTEX_STEP_STATUS_CANCELED'; + case 7: + return 'CORTEX_STEP_STATUS_ERROR'; + case 8: + return 'CORTEX_STEP_STATUS_GENERATING'; + default: + return 'CORTEX_STEP_STATUS_DONE'; + } +} + +function decodeProtoModelUsage(buf) { + const st = { off: 0 }; + let model = ''; + let inputTokens = 0; + let outputTokens = 0; + let cacheReadTokens = 0; + let apiProviderNum = 0; + let thinkingOutputTokens; + let responseOutputTokens; + + while (st.off < buf.length) { + const tag = Number(readProtoVarint(buf, st)); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 0) { + model = decodeProtoModelEnumInt(readProtoVarint(buf, st)); + } else if (fn === 1 && wt === 2) { + const len = Number(readProtoVarint(buf, st)); + model = buf.subarray(st.off, st.off + len).toString('utf8'); + st.off += len; + } else if (fn === 2 && wt === 0) { + inputTokens = Number(readProtoVarint(buf, st)); + } else if (fn === 3 && wt === 0) { + outputTokens = Number(readProtoVarint(buf, st)); + } else if (fn === 5 && wt === 0) { + cacheReadTokens = Number(readProtoVarint(buf, st)); + } else if (fn === 6 && wt === 0) { + apiProviderNum = Number(readProtoVarint(buf, st)); + } else if (fn === 9 && wt === 0) { + thinkingOutputTokens = Number(readProtoVarint(buf, st)); + } else if (fn === 10 && wt === 0) { + responseOutputTokens = Number(readProtoVarint(buf, st)); + } else { + skipProtoField(buf, st, wt); + } + } + + return { + ...(model ? { model } : {}), + ...(apiProviderNum === 24 ? { apiProvider: 'API_PROVIDER_GOOGLE_GEMINI' } : {}), + inputTokens, + cacheReadTokens, + outputTokens, + ...(thinkingOutputTokens !== undefined ? { thinkingOutputTokens } : {}), + ...(responseOutputTokens !== undefined ? { responseOutputTokens } : {}), + }; +} + +function decodeProtoTokenBreakdownGroup(buf, depth = 0) { + const st = { off: 0 }; + let name = ''; + let type = ''; + let numTokens = 0; + const children = []; + + while (st.off < buf.length) { + const tag = Number(readProtoVarint(buf, st)); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 2) { + const len = Number(readProtoVarint(buf, st)); + name = buf.subarray(st.off, st.off + len).toString('utf8'); + st.off += len; + } else if (fn === 2 && wt === 0) { + type = decodeProtoTokenTypeEnum(readProtoVarint(buf, st)); + } else if (fn === 4 && wt === 0) { + numTokens = Number(readProtoVarint(buf, st)); + } else if (fn === 5 && wt === 2 && depth < 2) { + const len = Number(readProtoVarint(buf, st)); + const sub = buf.subarray(st.off, st.off + len); + st.off += len; + children.push(decodeProtoTokenBreakdownGroup(sub, depth + 1)); + } else { + skipProtoField(buf, st, wt); + } + } + + return { + name, + ...(type ? { type } : {}), + numTokens, + ...(children.length > 0 ? { children } : {}), + }; +} + +function decodeProtoContextWindowMeta(buf) { + const st = { off: 0 }; + let estimatedTokensUsed = 0; + let maxContextTokens = 0; + const groups = []; + + while (st.off < buf.length) { + const tag = Number(readProtoVarint(buf, st)); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 0) { + estimatedTokensUsed = Number(readProtoVarint(buf, st)); + } else if (fn === 4 && wt === 0) { + maxContextTokens = Number(readProtoVarint(buf, st)); + } else if (fn === 3 && wt === 2) { + const len = Number(readProtoVarint(buf, st)); + const tbBuf = buf.subarray(st.off, st.off + len); + st.off += len; + const tbSt = { off: 0 }; + while (tbSt.off < tbBuf.length) { + const tbTag = Number(readProtoVarint(tbBuf, tbSt)); + const tbFn = tbTag >>> 3; + const tbWt = tbTag & 7; + if (tbFn === 1 && tbWt === 2) { + const gLen = Number(readProtoVarint(tbBuf, tbSt)); + const gBuf = tbBuf.subarray(tbSt.off, tbSt.off + gLen); + tbSt.off += gLen; + groups.push(decodeProtoTokenBreakdownGroup(gBuf, 0)); + } else { + skipProtoField(tbBuf, tbSt, tbWt); + } + } + } else { + skipProtoField(buf, st, wt); + } + } + + return { + ...(estimatedTokensUsed > 0 ? { estimatedTokensUsed } : {}), + ...(maxContextTokens > 0 ? { maxContextTokens } : {}), + ...(groups.length > 0 ? { tokenBreakdown: { groups } } : {}), + }; +} + +function decodeProtoMapStringEntry(buf) { + const st = { off: 0 }; + let key = ''; + let val = ''; + while (st.off < buf.length) { + const tag = Number(readProtoVarint(buf, st)); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 2) { + const len = Number(readProtoVarint(buf, st)); + key = buf.subarray(st.off, st.off + len).toString('utf8'); + st.off += len; + } else if (fn === 2 && wt === 2) { + const len = Number(readProtoVarint(buf, st)); + val = buf.subarray(st.off, st.off + len).toString('utf8'); + st.off += len; + } else { + skipProtoField(buf, st, wt); + } + } + return [key, val]; +} + +function decodeProtoChatModelMeta(buf) { + const st = { off: 0 }; + let model = ''; + let usage = null; + let contextWindowMetadata = null; + let timeToFirstToken = ''; + let streamingDuration = ''; + let responseModel = ''; + let modelDisplayName = ''; + const extraMeta = {}; + + while (st.off < buf.length) { + const tag = Number(readProtoVarint(buf, st)); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 3 && wt === 0) { + const enumStr = decodeProtoModelEnumInt(readProtoVarint(buf, st)); + if (enumStr && !model) model = enumStr; + } else if (fn === 4 && wt === 2) { + const len = Number(readProtoVarint(buf, st)); + usage = decodeProtoModelUsage(buf.subarray(st.off, st.off + len)); + st.off += len; + } else if (fn === 9 && wt === 2) { + const len = Number(readProtoVarint(buf, st)); + const csBuf = buf.subarray(st.off, st.off + len); + st.off += len; + const csSt = { off: 0 }; + while (csSt.off < csBuf.length) { + const csTag = Number(readProtoVarint(csBuf, csSt)); + const csFn = csTag >>> 3; + const csWt = csTag & 7; + if (csFn === 10 && csWt === 2) { + const cwLen = Number(readProtoVarint(csBuf, csSt)); + contextWindowMetadata = decodeProtoContextWindowMeta( + csBuf.subarray(csSt.off, csSt.off + cwLen) + ); + csSt.off += cwLen; + } else { + skipProtoField(csBuf, csSt, csWt); + } + } + } else if (fn === 11 && wt === 2) { + const len = Number(readProtoVarint(buf, st)); + timeToFirstToken = decodeProtoDurationStr(buf.subarray(st.off, st.off + len)); + st.off += len; + } else if (fn === 12 && wt === 2) { + const len = Number(readProtoVarint(buf, st)); + streamingDuration = decodeProtoDurationStr(buf.subarray(st.off, st.off + len)); + st.off += len; + } else if (fn === 19 && wt === 2) { + const len = Number(readProtoVarint(buf, st)); + responseModel = buf.subarray(st.off, st.off + len).toString('utf8').trim(); + st.off += len; + } else if (fn === 20 && wt === 2) { + const len = Number(readProtoVarint(buf, st)); + const [k, v] = decodeProtoMapStringEntry(buf.subarray(st.off, st.off + len)); + st.off += len; + if (k && v) extraMeta[k] = v; + } else if (fn === 21 && wt === 2) { + const len = Number(readProtoVarint(buf, st)); + modelDisplayName = buf.subarray(st.off, st.off + len).toString('utf8').trim(); + st.off += len; + } else { + skipProtoField(buf, st, wt); + } + } + + if (extraMeta.model_enum) { + model = extraMeta.model_enum.trim(); + if (usage && !usage.model) { + usage.model = model; + } + } + if (extraMeta.used_claude === 'true' && usage && !usage.apiProvider) { + usage.apiProvider = 'API_PROVIDER_ANTHROPIC'; + } + + return { + chatModel: { + ...(model ? { model } : {}), + ...(usage ? { usage } : {}), + ...(contextWindowMetadata ? { chatStartMetadata: { contextWindowMetadata } } : {}), + ...(timeToFirstToken ? { timeToFirstToken } : {}), + ...(streamingDuration ? { streamingDuration } : {}), + ...(responseModel ? { responseModel } : {}), + ...(modelDisplayName ? { modelDisplayName } : {}), + }, + extraMeta, + }; +} + +function decodeProtoGeneratorMeta(buf) { + const st = { off: 0 }; + const stepIndices = []; + let chatDecoded = null; + + while (st.off < buf.length) { + const tag = Number(readProtoVarint(buf, st)); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 2 && wt === 0) { + stepIndices.push(Number(readProtoVarint(buf, st))); + } else if (fn === 2 && wt === 2) { + const len = Number(readProtoVarint(buf, st)); + const end = st.off + len; + while (st.off < end) { + stepIndices.push(Number(readProtoVarint(buf, st))); + } + } else if (fn === 1 && wt === 2) { + const len = Number(readProtoVarint(buf, st)); + chatDecoded = decodeProtoChatModelMeta(buf.subarray(st.off, st.off + len)); + st.off += len; + } else { + skipProtoField(buf, st, wt); + } + } + + if (!chatDecoded) return null; + return { + stepIndices, + chatModel: chatDecoded.chatModel, + extraMeta: chatDecoded.extraMeta, + }; +} + +function decodeProtoStepMeta(buf, fallbackIdx) { + const st = { off: 0 }; + let createdAt = ''; + let viewableAt = ''; + let finishedGeneratingAt = ''; + let completedAt = ''; + let modelUsage = null; + let generatorModel = ''; + let stepIndex = fallbackIdx; + + while (st.off < buf.length) { + const tag = Number(readProtoVarint(buf, st)); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 2) { + const len = Number(readProtoVarint(buf, st)); + createdAt = decodeProtoTimestampIso(buf.subarray(st.off, st.off + len)); + st.off += len; + } else if (fn === 6 && wt === 2) { + const len = Number(readProtoVarint(buf, st)); + viewableAt = decodeProtoTimestampIso(buf.subarray(st.off, st.off + len)); + st.off += len; + } else if (fn === 7 && wt === 2) { + const len = Number(readProtoVarint(buf, st)); + finishedGeneratingAt = decodeProtoTimestampIso(buf.subarray(st.off, st.off + len)); + st.off += len; + } else if (fn === 32 && wt === 2) { + const len = Number(readProtoVarint(buf, st)); + completedAt = decodeProtoTimestampIso(buf.subarray(st.off, st.off + len)); + st.off += len; + } else if (fn === 9 && wt === 2) { + const len = Number(readProtoVarint(buf, st)); + modelUsage = decodeProtoModelUsage(buf.subarray(st.off, st.off + len)); + st.off += len; + } else if (fn === 11 && wt === 0) { + generatorModel = decodeProtoModelEnumInt(readProtoVarint(buf, st)); + } else if (fn === 20 && wt === 2) { + const len = Number(readProtoVarint(buf, st)); + const siBuf = buf.subarray(st.off, st.off + len); + st.off += len; + const siSt = { off: 0 }; + while (siSt.off < siBuf.length) { + const siTag = Number(readProtoVarint(siBuf, siSt)); + const siFn = siTag >>> 3; + const siWt = siTag & 7; + if (siFn === 2 && siWt === 0) { + stepIndex = Number(readProtoVarint(siBuf, siSt)); + } else { + skipProtoField(siBuf, siSt, siWt); + } + } + } else { + skipProtoField(buf, st, wt); + } + } + + return { + ...(createdAt ? { createdAt } : {}), + ...(viewableAt ? { viewableAt } : {}), + ...(finishedGeneratingAt ? { finishedGeneratingAt } : {}), + ...(completedAt ? { completedAt } : {}), + ...(generatorModel ? { generatorModel } : {}), + sourceTrajectoryStepInfo: { stepIndex }, + ...(modelUsage ? { modelUsage } : {}), + }; +} + +/** + * 从单个会话的本地 SQLite 数据库(`/conversations/.db`)提取步骤元数据与生成器元数据。 + * 严格只查询 `steps.metadata` 与 `gen_metadata.data`,不加载 `step_payload` 大字段。 + * + * @param {string} dbFilePath + * @returns {{ + * steps: Array<{ idx: number, type: string, status: string, metadata: object }>, + * generatorMetadata: Array<{ stepIndices: number[], chatModel: object }>, + * rootConversationId: string, + * parentConversationId: string + * } | null} + */ +export function readLocalSqliteTrajectory(dbFilePath) { + if (!dbFilePath || !existsSync(dbFilePath)) return null; + const DatabaseSync = getNodeSqliteDatabaseSync(); + if (!DatabaseSync) return null; + + let db = null; + try { + db = new DatabaseSync(dbFilePath, { readOnly: true }); + const genRows = db.prepare('SELECT idx, data FROM gen_metadata ORDER BY idx ASC').all(); + const generatorMetadata = []; + const genByStep = new Map(); + let rootConversationId = ''; + let parentConversationId = ''; + + for (const row of genRows || []) { + if (!row?.data) continue; + try { + const decoded = decodeProtoGeneratorMeta(Buffer.from(row.data)); + if (!decoded) continue; + const gmItem = { + stepIndices: decoded.stepIndices, + chatModel: decoded.chatModel, + }; + generatorMetadata.push(gmItem); + for (const sIdx of decoded.stepIndices) { + genByStep.set(Number(sIdx), gmItem); + } + if (!rootConversationId && decoded.extraMeta?.root_cascade_id) { + rootConversationId = String(decoded.extraMeta.root_cascade_id).trim().toLowerCase(); + } + if (!parentConversationId && decoded.extraMeta?.parent_cascade_id) { + parentConversationId = String(decoded.extraMeta.parent_cascade_id).trim().toLowerCase(); + } + } catch { + // 忽略单条损坏的 generatorMetadata + } + } + + const stepRows = db + .prepare('SELECT idx, step_type, status, metadata FROM steps ORDER BY idx ASC') + .all(); + const steps = []; + for (const row of stepRows || []) { + const idx = Number.isFinite(Number(row?.idx)) ? Number(row.idx) : steps.length; + const type = decodeProtoStepTypeEnum(row?.step_type); + const status = decodeProtoStepStatusEnum(row?.status); + let metadata = { sourceTrajectoryStepInfo: { stepIndex: idx } }; + if (row?.metadata && row.metadata.byteLength > 0) { + try { + metadata = decodeProtoStepMeta(Buffer.from(row.metadata), idx); + } catch { + // 忽略单步元数据解码异常 + } + } + const stepIdx = metadata.sourceTrajectoryStepInfo?.stepIndex ?? idx; + const gm = genByStep.get(Number(stepIdx)); + if (metadata.modelUsage && gm?.chatModel?.model && !metadata.modelUsage.model) { + metadata.modelUsage.model = gm.chatModel.model; + } + steps.push({ idx, type, status, metadata }); + } + + if (steps.length === 0 && generatorMetadata.length === 0) { + return null; + } + return { + steps, + generatorMetadata, + rootConversationId, + parentConversationId, + }; + } catch { + return null; + } finally { + if (db) { + try { + db.close(); + } catch { + // 忽略关闭异常 + } + } + } +} diff --git a/sidecars/panel/backend/config.mjs b/sidecars/panel/backend/config.mjs index 387248f..410f42a 100644 --- a/sidecars/panel/backend/config.mjs +++ b/sidecars/panel/backend/config.mjs @@ -42,6 +42,7 @@ import { normalizeOverviewMetrics, normalizeOverviewModules, normalizePluginUpdateMode, + normalizeStandalonePort, normalizeStepTableColumns, normalizeThemeAccent, normalizeTopbarCapsuleSlots, @@ -77,6 +78,7 @@ export { normalizeOverviewMetrics, normalizeOverviewModules, normalizePluginUpdateMode, + normalizeStandalonePort, normalizeStepTableColumns, normalizeThemeAccent, normalizeTopbarCapsuleSlots, @@ -95,23 +97,70 @@ export const PLUGIN_ROOT = dirname(dirname(HERE)); export const PLUGIN_MANIFEST_FILE = join(PLUGIN_ROOT, 'plugin.json'); export const LOCAL_CATALOG_FILE = join(PLUGIN_ROOT, 'pricing-catalog.json'); +function resolveGeminiBaseDir() { + const envGemini = String(process.env.ANTIGRAVITY_GEMINI_DIR || '').trim(); + return envGemini || join(homedir(), '.gemini'); +} + +function dedupeDirCandidates(list) { + const seen = new Set(); + const out = []; + for (const item of list) { + const clean = String(item || '').trim(); + if (!clean) continue; + const key = process.platform === 'win32' ? clean.toLowerCase() : clean; + if (seen.has(key)) continue; + seen.add(key); + out.push(clean); + } + return out; +} + +function resolveProductDataRoots() { + const geminiBase = resolveGeminiBaseDir(); + const explicitAppDir = String( + process.env.USAGE_MONITOR_APP_DATA_DIR || process.env.ANTIGRAVITY_APP_DATA_DIR || '' + ).trim(); + const customRoot = explicitAppDir + ? /[\\/]|^[a-zA-Z]:/.test(explicitAppDir) + ? explicitAppDir + : join(geminiBase, explicitAppDir) + : ''; + return dedupeDirCandidates([ + customRoot, + join(geminiBase, 'antigravity'), + join(geminiBase, 'antigravity-cli'), + join(geminiBase, 'antigravity-ide'), + join(geminiBase, 'antigravity-idea'), + ]); +} + /** * 插件持久化数据目录(默认由 Antigravity 宿主注入 `~/.gemini/antigravity/sidecar_data/usage-monitor/panel/data`)。 - * 当通过插件 `mcp_config.json` 在 Antigravity IDE 中后台启动且未注入 `ANTIGRAVITY_EXECUTABLE_DATA_DIR` 时, - * 自动对齐至同一 `sidecar_data` 目录,确保双端共享同一份设置、历史轨迹缓存与窗口桥接租约。 + * 兼容桌面端、Antigravity IDE 与无头 `agy` CLI(`~/.gemini/antigravity-cli`): + * 优先使用已存在的持久化目录,纯 CLI 服务器自动落入 `~/.gemini/antigravity-cli/sidecar_data/usage-monitor/panel/data`, + * 避免落入插件源码目录而在自更新时丢失缓存与设置。 */ function resolveDefaultDataDir() { + const explicitDataDir = String(process.env.USAGE_MONITOR_DATA_DIR || '').trim(); + if (explicitDataDir) { + return explicitDataDir; + } if (process.env.ANTIGRAVITY_EXECUTABLE_DATA_DIR) { return process.env.ANTIGRAVITY_EXECUTABLE_DATA_DIR; } if (String(process.env.ANTIGRAVITY_LS_ADDRESS || '').trim() === 'test.invalid') { return join(HERE, '.data'); } - const antigravityRoot = join(homedir(), '.gemini', 'antigravity'); + const geminiBase = resolveGeminiBaseDir(); + const antigravityRoot = join(geminiBase, 'antigravity'); + const cliRoot = join(geminiBase, 'antigravity-cli'); const panelDataDir = join(antigravityRoot, 'sidecar_data', 'usage-monitor', 'panel', 'data'); const legacyDataDir = join(antigravityRoot, 'sidecar_data', 'usage-monitor', 'data'); + const cliPanelDataDir = join(cliRoot, 'sidecar_data', 'usage-monitor', 'panel', 'data'); if (existsSync(panelDataDir)) return panelDataDir; if (existsSync(legacyDataDir)) return legacyDataDir; + if (existsSync(cliPanelDataDir)) return cliPanelDataDir; if (existsSync(antigravityRoot)) return panelDataDir; if ( process.env.USAGE_MONITOR_PLUGIN_DATA && @@ -119,6 +168,7 @@ function resolveDefaultDataDir() { ) { return process.env.USAGE_MONITOR_PLUGIN_DATA; } + if (existsSync(cliRoot)) return cliPanelDataDir; return join(HERE, '.data'); } @@ -128,29 +178,41 @@ export const CACHE_FILE = join(DATA_DIR, 'trajectory_usage_cache.json'); export const REMOTE_CATALOG_CACHE_FILE = join(DATA_DIR, 'remote_pricing_cache.json'); /** - * 本地对话记录目录与跨端深层统计缓存路径候选列表。 + * 本地对话记录目录、脑图日志目录、守护发现目录与跨端深层统计缓存路径候选列表(联合覆盖 Desktop / CLI / IDE)。 */ -export const CONVERSATIONS_DIR = join(homedir(), '.gemini', 'antigravity', 'conversations'); -export const BRAIN_DIR = join(homedir(), '.gemini', 'antigravity', 'brain'); -export const DEEP_STATS_CACHE_CANDIDATES = [ - join(homedir(), '.gemini', 'antigravity-ide', 'brain', '.deep_stats_cache.json'), - join(homedir(), '.gemini', 'antigravity', 'brain', '.deep_stats_cache.json'), - join(homedir(), '.gemini', 'antigravity-idea', 'brain', '.deep_stats_cache.json'), -]; +export const PRODUCT_DATA_ROOTS = resolveProductDataRoots(); +export const CONVERSATION_DIRS = PRODUCT_DATA_ROOTS.map((root) => join(root, 'conversations')); +export const BRAIN_DIRS = PRODUCT_DATA_ROOTS.map((root) => join(root, 'brain')); +export const ANNOTATION_DIRS = PRODUCT_DATA_ROOTS.map((root) => join(root, 'annotations')); +export const DAEMON_DIRS = dedupeDirCandidates([ + join(resolveGeminiBaseDir(), 'antigravity-cli', 'daemon'), + ...PRODUCT_DATA_ROOTS.map((root) => join(root, 'daemon')), +]); +export const CONVERSATIONS_DIR = CONVERSATION_DIRS[0]; +export const BRAIN_DIR = BRAIN_DIRS[0]; +export const DEEP_STATS_CACHE_CANDIDATES = dedupeDirCandidates([ + join(resolveGeminiBaseDir(), 'antigravity-ide', 'brain', '.deep_stats_cache.json'), + join(resolveGeminiBaseDir(), 'antigravity-cli', 'brain', '.deep_stats_cache.json'), + join(resolveGeminiBaseDir(), 'antigravity', 'brain', '.deep_stats_cache.json'), + join(resolveGeminiBaseDir(), 'antigravity-idea', 'brain', '.deep_stats_cache.json'), + ...BRAIN_DIRS.map((dir) => join(dir, '.deep_stats_cache.json')), +]); /** - * Antigravity 本地 Language Server Connect RPC 端点与鉴权 Token(支持环境变量静态注入与进程动态发现)。 + * Antigravity 本地 Language Server Connect RPC 端点与鉴权 Token(支持环境变量静态注入与进程/守护文件动态发现)。 */ const rawLsAddr = String(process.env.ANTIGRAVITY_LS_ADDRESS || '').trim(); const LS_PROTOCOL = /^https:\/\//i.test(rawLsAddr) ? 'https' : 'http'; export const LS_ADDR = rawLsAddr.replace(/^https?:\/\//i, '').replace(/\/+$/, ''); export const LS_BASE_URL = LS_ADDR ? `${LS_PROTOCOL}://${LS_ADDR}` : ''; -export const CSRF_TOKEN = process.env.ANTIGRAVITY_CSRF_TOKEN; +export const CSRF_TOKEN = + process.env.ANTIGRAVITY_CSRF_TOKEN || process.env.ANTIGRAVITY_SERVER_CSRF_TOKEN; export const lsRuntimeEndpoint = { addr: LS_ADDR, baseUrl: LS_BASE_URL, csrfToken: CSRF_TOKEN || '', + isDynamic: false, }; /** @@ -158,14 +220,16 @@ export const lsRuntimeEndpoint = { * * @param {string} nextAddr * @param {string} nextCsrfToken + * @param {{ isDynamic?: boolean }} [opts] */ -export function setLsRuntimeEndpoint(nextAddr, nextCsrfToken) { +export function setLsRuntimeEndpoint(nextAddr, nextCsrfToken, { isDynamic = true } = {}) { const raw = String(nextAddr || '').trim(); const proto = /^https:\/\//i.test(raw) ? 'https' : 'http'; const cleanAddr = raw.replace(/^https?:\/\//i, '').replace(/\/+$/, ''); lsRuntimeEndpoint.addr = cleanAddr; lsRuntimeEndpoint.baseUrl = cleanAddr ? `${proto}://${cleanAddr}` : ''; lsRuntimeEndpoint.csrfToken = String(nextCsrfToken || '').trim(); + lsRuntimeEndpoint.isDynamic = Boolean(cleanAddr && isDynamic); } /** @@ -268,6 +332,7 @@ export function computeRuntimeCodeVersion() { join(HERE, 'app.js'), join(HERE, 'styles.css'), join(HERE, 'main.mjs'), + join(HERE, 'standalone.mjs'), join(HERE, 'bridge-daemon.mjs'), join(HERE, 'mcp-entry.mjs'), join(HERE, 'speed-metrics.mjs'), @@ -362,6 +427,11 @@ export const externalDeepStatsMemo = { convos: new Map(), }; +export const localSummaryMemo = { + sig: '', + byId: new Map(), +}; + /** 并发请求去重表(防止同一参数并发重复拉取)。 */ export const inFlightRequests = new Map(); @@ -414,6 +484,8 @@ export function clearRuntimeCaches() { cacheState.needsSave = false; externalDeepStatsMemo.sig = ''; externalDeepStatsMemo.convos.clear(); + localSummaryMemo.sig = ''; + localSummaryMemo.byId.clear(); quotaSummaryCache.ts = 0; quotaSummaryCache.lastAttemptTs = 0; quotaSummaryCache.accountName = ''; diff --git a/sidecars/panel/backend/local-scanner.mjs b/sidecars/panel/backend/local-scanner.mjs index de5a0a5..9e179c0 100644 --- a/sidecars/panel/backend/local-scanner.mjs +++ b/sidecars/panel/backend/local-scanner.mjs @@ -18,10 +18,13 @@ import { parseIsoMs, } from '../speed-metrics.mjs'; import { + ANNOTATION_DIRS, BRAIN_DIR, + BRAIN_DIRS, CACHE_FILE, CACHE_SCHEMA_VERSION, CONVERSATIONS_DIR, + CONVERSATION_DIRS, DEEP_STATS_CACHE_CANDIDATES, cacheState, externalDeepStatsMemo, @@ -29,39 +32,89 @@ import { saveJson, trajectoryCache, } from './config.mjs'; +import { + hasBuiltinNodeSqlite, + readAnnotationTitleForCascade, + readLocalSqliteTrajectory, + readLocalSummaryIndex, +} from './cli-sqlite-reader.mjs'; import { callLsRpc } from './ls-rpc.mjs'; import { formatGenericModelSlug, getBaseModelLabel } from './model-pricing.mjs'; import { PLACEHOLDER_MAP } from './pricing-catalog.mjs'; +const CONV_FILE_RE = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.(db|pb|db-wal)$/i; +const TRANSCRIPT_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + /** - * 扫描本地 `conversations` 目录,按会话归并轨迹文件。 + * 联合扫描本地多端(Desktop / CLI / IDE)的 `conversations` 与 `brain//.system_generated/logs/transcript.jsonl`, + * 按小写 `cascadeId` 归并关联磁盘文件路径。 * * @returns {Map} */ function discoverLocalConversationFiles() { const map = new Map(); - if (!existsSync(CONVERSATIONS_DIR)) return map; - try { - for (const name of readdirSync(CONVERSATIONS_DIR)) { - const m = name.match( - /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.(db|pb|db-wal)$/i - ); - if (!m) continue; - const cascadeId = m[1].toLowerCase(); - if (!map.has(cascadeId)) map.set(cascadeId, []); - map.get(cascadeId).push(name); + const convDirs = + Array.isArray(CONVERSATION_DIRS) && CONVERSATION_DIRS.length > 0 + ? CONVERSATION_DIRS + : [CONVERSATIONS_DIR]; + for (const dir of convDirs) { + if (!dir || !existsSync(dir)) continue; + try { + for (const rawName of readdirSync(dir)) { + const name = String(rawName || ''); + const m = name.match(CONV_FILE_RE); + if (!m) continue; + const cascadeId = m[1].toLowerCase(); + if (!map.has(cascadeId)) map.set(cascadeId, []); + map.get(cascadeId).push(join(dir, name)); + } + } catch { + // 忽略目录读取异常 + } + } + + const brainDirs = + Array.isArray(BRAIN_DIRS) && BRAIN_DIRS.length > 0 ? BRAIN_DIRS : [BRAIN_DIR]; + for (const dir of brainDirs) { + if (!dir || !existsSync(dir)) continue; + try { + for (const rawName of readdirSync(dir)) { + const name = String(rawName || '').trim(); + const cascadeId = name.toLowerCase(); + if (!TRANSCRIPT_UUID_RE.test(cascadeId)) continue; + const transcriptPath = join(dir, name, '.system_generated', 'logs', 'transcript.jsonl'); + if (!existsSync(transcriptPath)) continue; + if (!map.has(cascadeId)) map.set(cascadeId, []); + map.get(cascadeId).push(transcriptPath); + } + } catch { + // 忽略目录读取异常 + } + } + + const annotationDirs = Array.isArray(ANNOTATION_DIRS) ? ANNOTATION_DIRS : []; + if (annotationDirs.length > 0 && map.size > 0) { + for (const [cascadeId, fileList] of map.entries()) { + for (const annDir of annotationDirs) { + if (!annDir) continue; + const pbtxtPath = join(annDir, `${cascadeId}.pbtxt`); + if (existsSync(pbtxtPath)) { + fileList.push(pbtxtPath); + } + } } - } catch { - // 忽略目录读取异常 } return map; } function readConversationMtime(files = []) { let mtimeMs = 0; - for (const name of files) { + for (const nameOrPath of files) { try { - mtimeMs = Math.max(mtimeMs, statSync(join(CONVERSATIONS_DIR, name)).mtimeMs); + const fullPath = /[\\/]|^[a-zA-Z]:/.test(nameOrPath) + ? nameOrPath + : join(CONVERSATIONS_DIR, nameOrPath); + mtimeMs = Math.max(mtimeMs, Number(statSync(fullPath)?.mtimeMs || 0)); } catch { // 轨迹文件可能在目录枚举后被宿主删除。 } @@ -236,6 +289,420 @@ const failedFetchCooldownMap = new Map(); const liveActivityMemo = new Map(); const transcriptTailMemo = new Map(); +function findTranscriptPath(cascadeId) { + if (!cascadeId) return ''; + const normId = String(cascadeId).trim().toLowerCase(); + if (!UUID_RE.test(normId)) return ''; + const dirs = Array.isArray(BRAIN_DIRS) && BRAIN_DIRS.length > 0 ? BRAIN_DIRS : [BRAIN_DIR]; + let bestPath = ''; + let bestMtime = -1; + for (const dir of dirs) { + if (!dir) continue; + const candidate = join(dir, normId, '.system_generated', 'logs', 'transcript.jsonl'); + if (!existsSync(candidate)) continue; + if (dirs.length === 1) return candidate; + try { + const mtime = Number(statSync(candidate)?.mtimeMs || 0); + if (mtime > bestMtime) { + bestMtime = mtime; + bestPath = candidate; + } + } catch { + if (!bestPath) bestPath = candidate; + } + } + return bestPath; +} + +function inferConversationAppSource(diskFiles = [], extMatch = null) { + if (extMatch?.appSource && extMatch.appSource !== 'standalone') { + return extMatch.appSource; + } + for (const filePath of Array.isArray(diskFiles) ? diskFiles : []) { + const s = String(filePath || ''); + if (/[\\/]antigravity-cli(?:[\\/]|$)/i.test(s)) return 'cli'; + if (/[\\/]antigravity-ide(?:[\\/]|$)/i.test(s)) return 'ide'; + } + return ''; +} + +function extractOfflineUserTitle(rawContent) { + if (typeof rawContent !== 'string' || !rawContent.trim()) return ''; + const withoutSummary = rawContent + .replace(/[\s\S]*?<\/CONTEXT_SUMMARY>/gi, '') + .replace(/[\s\S]*$/i, ''); + const reqMatches = [...withoutSummary.matchAll(/([\s\S]*?)<\/USER_REQUEST>/gi)]; + const body = + reqMatches.length > 0 + ? reqMatches[reqMatches.length - 1][1] + : withoutSummary.replace(/[\s\S]*$/i, ''); + const firstLine = String(body || '') + .split(/\r?\n/) + .map((l) => l.replace(/\s+/g, ' ').trim()) + .find(Boolean); + if (!firstLine) return ''; + return firstLine.length > 48 ? `${firstLine.slice(0, 47)}…` : firstLine; +} + +function hasLocalSqliteDb(diskFiles = []) { + return Array.isArray(diskFiles) && diskFiles.some((f) => /\.db$/i.test(String(f || ''))); +} + +function findBestSqliteDbPath(diskFiles = []) { + if (!Array.isArray(diskFiles) || diskFiles.length === 0) return ''; + let bestPath = ''; + let bestMtime = -1; + for (const rawPath of diskFiles) { + const p = String(rawPath || '').trim(); + if (!/\.db$/i.test(p)) continue; + const fullPath = /[\\/]|^[a-zA-Z]:/.test(p) ? p : join(CONVERSATIONS_DIR, p); + if (!existsSync(fullPath)) continue; + try { + const mtime = Number(statSync(fullPath)?.mtimeMs || 0); + if (mtime > bestMtime) { + bestMtime = mtime; + bestPath = fullPath; + } + } catch { + if (!bestPath) bestPath = fullPath; + } + } + return bestPath; +} + +/** + * 当 Language Server RPC 离线或跨端不可达(如 `agy` CLI 独立会话目录)时,优先融合本地 SQLite + * (`conversations/.db` + `conversation_summaries.db` + `annotations/.pbtxt`) 与 `transcript.jsonl` + * (及可选 `.deep_stats_cache.json`)恢复完整步骤耗时、TTFT、思考/正文拆分、10 通道上下文构成与真实标题。 + */ +function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, localSummary = null) { + const cidLower = String(conv?.cascadeId || '').trim().toLowerCase(); + if (!cidLower) return null; + const extMatch = externalByLower?.get(cidLower) || null; + const sqliteDbPath = findBestSqliteDbPath(diskFiles); + const sqliteTraj = sqliteDbPath ? readLocalSqliteTrajectory(sqliteDbPath) : null; + const transcriptPath = findTranscriptPath(cidLower); + + const transcriptLines = []; + if (transcriptPath && existsSync(transcriptPath)) { + try { + const raw = readFileSync(transcriptPath, 'utf8'); + if (typeof raw === 'string' && raw.trim()) { + for (const line of raw.split(/\r?\n/)) { + const trimmed = line.trim(); + if (!trimmed) continue; + try { + const parsed = JSON.parse(trimmed); + if (parsed && typeof parsed === 'object') { + transcriptLines.push(parsed); + } + } catch { + // 忽略尾部半行或损坏 JSON 行 + } + } + } + } catch { + // 忽略文件读取失败 + } + } + + if (!sqliteTraj && transcriptLines.length === 0 && !extMatch) { + return null; + } + + let firstUserTitle = ''; + const transcriptByStepIdx = new Map(); + for (let rawIdx = 0; rawIdx < transcriptLines.length; rawIdx++) { + const line = transcriptLines[rawIdx]; + const sIdx = Number.isFinite(Number(line.step_index)) ? Number(line.step_index) : rawIdx; + transcriptByStepIdx.set(sIdx, line); + const upperType = String(line.type || '').trim().toUpperCase(); + if ( + !firstUserTitle && + (upperType === 'USER_INPUT' || + upperType === 'CORTEX_STEP_TYPE_USER_INPUT' || + (line.userInput && typeof line.userInput === 'object')) + ) { + firstUserTitle = extractOfflineUserTitle( + typeof line.content === 'string' ? line.content : line.userInput?.userResponse || '' + ); + } + } + + let steps = []; + let fromSqlite = false; + + if (sqliteTraj && sqliteTraj.steps.length > 0) { + fromSqlite = true; + const sqliteRawSteps = []; + let maxSqliteStepIdx = -1; + let modelOrdinal = 0; + + for (const sq of sqliteTraj.steps) { + const sIdx = Number(sq.metadata?.sourceTrajectoryStepInfo?.stepIndex ?? sq.idx); + if (Number.isFinite(sIdx) && sIdx > maxSqliteStepIdx) { + maxSqliteStepIdx = sIdx; + } + const tLine = transcriptByStepIdx.get(sIdx) || null; + if (sq.type === 'CORTEX_STEP_TYPE_USER_INPUT') { + sqliteRawSteps.push({ + type: sq.type, + status: sq.status, + ...(typeof tLine?.content === 'string' ? { content: tLine.content } : {}), + ...(tLine?.userInput ? { userInput: tLine.userInput } : {}), + ...(Array.isArray(tLine?.media) ? { media: tLine.media } : {}), + metadata: sq.metadata, + }); + continue; + } + + if (sq.metadata?.modelUsage) { + const deepStep = extMatch?.steps?.[modelOrdinal] || null; + modelOrdinal += 1; + const mu = { ...sq.metadata.modelUsage }; + if (!mu.model) { + const fallbackModel = String( + tLine?.model || tLine?.generator_model || deepStep?.modelKey || '' + ).trim(); + if (fallbackModel) mu.model = fallbackModel; + } + if (!mu.responseModel && (tLine?.response_model || deepStep?.responseModel)) { + mu.responseModel = String(tLine?.response_model || deepStep?.responseModel).trim(); + } + sqliteRawSteps.push({ + type: sq.type, + status: sq.status, + plannerResponse: { + response: typeof tLine?.content === 'string' ? tLine.content : '', + thinking: typeof tLine?.thinking === 'string' ? tLine.thinking : '', + toolCalls: Array.isArray(tLine?.tool_calls) ? tLine.tool_calls : [], + }, + metadata: { + ...sq.metadata, + modelUsage: mu, + }, + }); + } + } + + // 补充可能已刷入 transcript.jsonl 但尚未刷入 SQLite 的尾部步骤 + for (const [sIdx, line] of transcriptByStepIdx.entries()) { + if (sIdx <= maxSqliteStepIdx) continue; + const upperType = String(line.type || '').trim().toUpperCase(); + if ( + upperType === 'USER_INPUT' || + upperType === 'CORTEX_STEP_TYPE_USER_INPUT' || + (line.userInput && typeof line.userInput === 'object') + ) { + sqliteRawSteps.push(line); + } else if ( + line.input_tokens !== undefined || + line.cache_read_tokens !== undefined || + line.output_tokens !== undefined + ) { + sqliteRawSteps.push({ + type: + upperType === 'CHECKPOINT' || upperType === 'CORTEX_STEP_TYPE_CHECKPOINT' + ? 'CORTEX_STEP_TYPE_CHECKPOINT' + : String(line.type || 'PLANNER_RESPONSE'), + status: /CANCEL/i.test(String(line.status || '')) + ? 'CORTEX_STEP_STATUS_CANCELED' + : 'CORTEX_STEP_STATUS_DONE', + plannerResponse: { + response: typeof line.content === 'string' ? line.content : '', + thinking: typeof line.thinking === 'string' ? line.thinking : '', + toolCalls: Array.isArray(line.tool_calls) ? line.tool_calls : [], + }, + metadata: { + createdAt: String(line.created_at || line.createdAt || ''), + sourceTrajectoryStepInfo: { stepIndex: sIdx }, + modelUsage: { + model: String(line.model || line.generator_model || 'unknown').trim() || 'unknown', + inputTokens: line.input_tokens ?? 0, + cacheReadTokens: line.cache_read_tokens ?? 0, + outputTokens: line.output_tokens ?? 0, + }, + }, + }); + } + } + + steps = extractModelSteps(sqliteRawSteps, sqliteTraj.generatorMetadata || []); + } + + if (steps.length === 0 && transcriptLines.length > 0) { + const syntheticSteps = []; + let modelOrdinal = 0; + + for (let rawIdx = 0; rawIdx < transcriptLines.length; rawIdx++) { + const line = transcriptLines[rawIdx]; + const rawType = String(line.type || '').trim(); + const upperType = rawType.toUpperCase(); + if ( + upperType === 'USER_INPUT' || + upperType === 'CORTEX_STEP_TYPE_USER_INPUT' || + (line.userInput && typeof line.userInput === 'object') + ) { + syntheticSteps.push(line); + continue; + } + + if (line.metadata?.modelUsage) { + syntheticSteps.push(line); + modelOrdinal += 1; + continue; + } + + const hasTokenCounts = + line.input_tokens !== undefined || + line.cache_read_tokens !== undefined || + line.output_tokens !== undefined; + if (!hasTokenCounts) continue; + + const deepStep = extMatch?.steps?.[modelOrdinal] || null; + modelOrdinal += 1; + const isCheckpoint = + upperType === 'CHECKPOINT' || upperType === 'CORTEX_STEP_TYPE_CHECKPOINT'; + const rawStatus = String(line.status || '').trim().toUpperCase(); + const mappedStatus = /CANCEL/.test(rawStatus) + ? 'CORTEX_STEP_STATUS_CANCELED' + : 'CORTEX_STEP_STATUS_DONE'; + const finishedAt = String( + line.finished_generating_at || + line.finishedGeneratingAt || + line.completed_at || + line.completedAt || + '' + ).trim(); + const modelKey = + String(line.model || line.generator_model || deepStep?.modelKey || 'unknown').trim() || + 'unknown'; + const responseModel = String(line.response_model || deepStep?.responseModel || '').trim(); + const apiProvider = String(line.api_provider || deepStep?.apiProvider || '').trim(); + const modelDisplayName = String( + line.model_display_name || deepStep?.modelDisplayName || '' + ).trim(); + const thinkingTokens = Number(line.thinking_tokens ?? deepStep?.thinkingTokens ?? 0) || 0; + const responseTokens = line.response_tokens ?? deepStep?.responseTokens; + + syntheticSteps.push({ + type: isCheckpoint ? 'CORTEX_STEP_TYPE_CHECKPOINT' : rawType || 'PLANNER_RESPONSE', + status: mappedStatus, + plannerResponse: { + response: typeof line.content === 'string' ? line.content : '', + thinking: typeof line.thinking === 'string' ? line.thinking : '', + toolCalls: Array.isArray(line.tool_calls) ? line.tool_calls : [], + ...(thinkingTokens > 0 ? { thinkingTokens } : {}), + ...(responseTokens !== undefined ? { responseTokens } : {}), + }, + metadata: { + createdAt: String(line.created_at || line.createdAt || deepStep?.createdAt || ''), + ...(finishedAt ? { finishedGeneratingAt: finishedAt } : {}), + sourceTrajectoryStepInfo: { + stepIndex: Number.isFinite(Number(line.step_index)) ? Number(line.step_index) : rawIdx, + }, + modelUsage: { + model: modelKey, + ...(responseModel ? { responseModel } : {}), + ...(apiProvider ? { apiProvider } : {}), + inputTokens: line.input_tokens ?? deepStep?.inputTokens ?? 0, + cacheReadTokens: line.cache_read_tokens ?? deepStep?.cacheReadTokens ?? 0, + outputTokens: line.output_tokens ?? deepStep?.outputTokens ?? 0, + ...(thinkingTokens > 0 ? { thinkingOutputTokens: thinkingTokens } : {}), + ...(responseTokens !== undefined ? { responseOutputTokens: responseTokens } : {}), + }, + ...(modelDisplayName + ? { generatorMetadata: [{ chatModel: { modelDisplayName } }] } + : {}), + }, + }); + } + + steps = syntheticSteps.length > 0 ? extractModelSteps(syntheticSteps, []) : []; + } + + if (steps.length === 0 && Array.isArray(extMatch?.steps) && extMatch.steps.length > 0) { + const extSynthetic = extMatch.steps.map((ds, idx) => ({ + type: 'PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + plannerResponse: { + ...(ds.thinkingTokens > 0 ? { thinkingTokens: ds.thinkingTokens } : {}), + ...(ds.responseTokens !== undefined ? { responseTokens: ds.responseTokens } : {}), + }, + metadata: { + createdAt: ds.createdAt || '', + sourceTrajectoryStepInfo: { stepIndex: ds.stepIndex ?? idx + 1 }, + modelUsage: { + model: ds.modelKey || 'unknown', + ...(ds.responseModel ? { responseModel: ds.responseModel } : {}), + ...(ds.apiProvider ? { apiProvider: ds.apiProvider } : {}), + inputTokens: ds.inputTokens || 0, + cacheReadTokens: ds.cacheReadTokens || 0, + outputTokens: ds.outputTokens || 0, + ...(ds.thinkingTokens > 0 ? { thinkingOutputTokens: ds.thinkingTokens } : {}), + ...(ds.responseTokens !== undefined + ? { responseOutputTokens: ds.responseTokens } + : {}), + }, + ...(ds.modelDisplayName + ? { generatorMetadata: [{ chatModel: { modelDisplayName: ds.modelDisplayName } }] } + : {}), + }, + })); + steps = extractModelSteps(extSynthetic, []); + } + + const defaultShortId = cidLower.slice(0, 8); + const nonShortTitle = (t) => { + const clean = String(t || '').trim(); + return clean && clean.toLowerCase() !== defaultShortId ? clean : ''; + }; + const annotationTitle = nonShortTitle(readAnnotationTitleForCascade(cidLower)); + const summaryTitle = nonShortTitle(localSummary?.title); + const currentTitle = nonShortTitle(conv.title); + const extTitle = nonShortTitle(extMatch?.title); + const resolvedTitle = + annotationTitle || + summaryTitle || + currentTitle || + extTitle || + firstUserTitle || + String(conv.title || '').trim() || + conv.cascadeId.slice(0, 8); + + const parentConversationId = String( + localSummary?.parentConversationId || + sqliteTraj?.parentConversationId || + conv.parentConversationId || + '' + ) + .trim() + .toLowerCase(); + const rawRootCid = String(sqliteTraj?.rootConversationId || conv.rootConversationId || '') + .trim() + .toLowerCase(); + const rootConversationId = + rawRootCid && rawRootCid !== cidLower ? rawRootCid : parentConversationId; + + const lastStepMs = steps[steps.length - 1]?.createdAtMs || 0; + return { + steps, + fromSqlite, + title: resolvedTitle, + accountName: extMatch?.accountName || '', + appSource: inferConversationAppSource(diskFiles, extMatch), + parentConversationId, + rootConversationId, + lastModifiedMs: Math.max( + conv.lastModifiedMs || 0, + localSummary?.lastModifiedMs || 0, + extMatch?.lastModifiedMs || 0, + lastStepMs + ), + subagentRefs: [], + }; +} + /** * 读取指定会话在本地 `brain//.system_generated/logs/transcript.jsonl` 的尾部步骤。 * 采用 `mtimeMs + size` 签名缓存与尾部 96KB 定长切片读取,避免长会话大文件全量读取阻塞事件循环。 @@ -248,20 +715,20 @@ function readTranscriptTailSteps(cascadeId, maxLines = 24) { if (!cascadeId) return []; const normId = String(cascadeId).trim().toLowerCase(); if (!UUID_RE.test(normId)) return []; - const transcriptPath = join( - BRAIN_DIR, - normId, - '.system_generated', - 'logs', - 'transcript.jsonl' - ); - if (!existsSync(transcriptPath)) return []; + const transcriptPath = findTranscriptPath(normId); + if (!transcriptPath) return []; try { const st = statSync(transcriptPath); const mtimeMs = Number(st?.mtimeMs || 0); const size = Number(st?.size || 0); const cached = transcriptTailMemo.get(normId); - if (cached && cached.mtimeMs === mtimeMs && cached.size === size && size > 0) { + if ( + cached && + cached.path === transcriptPath && + cached.mtimeMs === mtimeMs && + cached.size === size && + size > 0 + ) { return cached.steps; } @@ -302,7 +769,7 @@ function readTranscriptTailSteps(cascadeId, maxLines = 24) { } if (typeof raw !== 'string' || !raw.trim()) { - transcriptTailMemo.set(normId, { mtimeMs, size, steps: [] }); + transcriptTailMemo.set(normId, { path: transcriptPath, mtimeMs, size, steps: [] }); return []; } const lines = raw.trim().split(/\r?\n/); @@ -324,7 +791,7 @@ function readTranscriptTailSteps(cascadeId, maxLines = 24) { const oldestKey = transcriptTailMemo.keys().next().value; if (oldestKey !== undefined) transcriptTailMemo.delete(oldestKey); } - transcriptTailMemo.set(normId, { mtimeMs, size, steps }); + transcriptTailMemo.set(normId, { path: transcriptPath, mtimeMs, size, steps }); return steps; } catch { return []; @@ -627,10 +1094,13 @@ export async function enumerateAndSyncConversations({ } } + const localSummaryByLower = readLocalSummaryIndex(); + const STALE_LOCAL_RUNNING_MAX_AGE_MS = 10 * 60_000; const reqLower = String(requestedConvId || '').trim().toLowerCase(); const rawConversations = []; for (const [cidLower, cascadeId] of canonicalIdByLower.entries()) { const item = summariesByLower.get(cidLower); + const localSum = item ? null : localSummaryByLower.get(cidLower) || null; const cached = trajectoryCache[cascadeId]; if ( cached?.accountName && @@ -644,12 +1114,20 @@ export async function enumerateAndSyncConversations({ const diskMtimeMs = summaryMtimeMs ? null : readConversationMtime(diskConvMap.get(cidLower)); const rawMeta = item?.trajectoryMetadata || item?.metadata || {}; const parentConversationId = String( - rawMeta.parentConversationId || cached?.parentConversationId || '' + rawMeta.parentConversationId || + localSum?.parentConversationId || + cached?.parentConversationId || + '' ).toLowerCase(); const rootConversationId = String( rawMeta.rootConversationId || cached?.rootConversationId || parentConversationId || '' ).toLowerCase(); - const subagentSpec = mergeSubagentSpecs(rawMeta.subagentSpec, cached?.subagentSpec); + const localAgentSpec = + parentConversationId && localSum?.agentName ? { role: localSum.agentName } : null; + const subagentSpec = mergeSubagentSpecs( + rawMeta.subagentSpec, + mergeSubagentSpecs(localAgentSpec, cached?.subagentSpec) + ); const agentScriptName = rawMeta.agentScript?.name || cached?.agentScriptName || ''; const createdTimeMs = parseIsoMs(item?.createdTime || rawMeta?.createdAt) || cached?.createdTimeMs || 0; @@ -658,6 +1136,13 @@ export async function enumerateAndSyncConversations({ const isSubagent = Boolean(parentConversationId) || Boolean(rootConversationId && rootConversationId !== cidLower); + const latestLocalTouchMs = Math.max(diskMtimeMs || 0, localSum?.lastModifiedMs || 0); + const localStatus = + localSum?.status === 'CASCADE_RUN_STATUS_RUNNING' && + latestLocalTouchMs > 0 && + nowSweepMs - latestLocalTouchMs <= STALE_LOCAL_RUNNING_MAX_AGE_MS + ? 'CASCADE_RUN_STATUS_RUNNING' + : 'IDLE'; if (item) { const lastModifiedMs = @@ -691,12 +1176,17 @@ export async function enumerateAndSyncConversations({ const cachedStepCount = Number(cached.steps?.length || 0); rawConversations.push({ cascadeId, - title: cached.title || cascadeId.slice(0, 8), + title: localSum?.title || cached.title || cascadeId.slice(0, 8), stepCount: cachedStepCount, - rawStepCount: cachedStepCount, - status: 'IDLE', - lastModifiedTime: '', - lastModifiedMs: Math.max(cached.lastModifiedMs || 0, lastStepMs, diskMtimeMs), + rawStepCount: localSum?.stepCount || cachedStepCount, + status: localStatus, + lastModifiedTime: localSum?.lastModifiedTime || '', + lastModifiedMs: Math.max( + cached.lastModifiedMs || 0, + lastStepMs, + diskMtimeMs || 0, + localSum?.lastModifiedMs || 0 + ), diskMtimeMs, inSummaries: false, isSubagent, @@ -711,21 +1201,21 @@ export async function enumerateAndSyncConversations({ } else { rawConversations.push({ cascadeId, - title: cascadeId.slice(0, 8), + title: localSum?.title || cascadeId.slice(0, 8), stepCount: 0, - rawStepCount: 0, - status: 'IDLE', - lastModifiedTime: '', - lastModifiedMs: diskMtimeMs, + rawStepCount: localSum?.stepCount || 0, + status: localStatus, + lastModifiedTime: localSum?.lastModifiedTime || '', + lastModifiedMs: Math.max(diskMtimeMs || 0, localSum?.lastModifiedMs || 0), diskMtimeMs, inSummaries: false, needsInitialLoad: true, - isSubagent: false, - parentConversationId: '', - rootConversationId: '', - subagentSpec: null, - agentScriptName: '', - createdTimeMs: 0, + isSubagent, + parentConversationId, + rootConversationId, + subagentSpec, + agentScriptName, + createdTimeMs, spawnOrder: null, subagentRefs: null, }); @@ -793,6 +1283,8 @@ export async function enumerateAndSyncConversations({ return checks; } + let lazyExternalByLower = null; + /** * 批量拉取会话轨迹并提取步骤、子代理元数据 (`trajectory.metadata`) 与子代理调用引用 (`invokeSubagent`)。 * @@ -899,6 +1391,7 @@ export async function enumerateAndSyncConversations({ (prev?.rootConversationId || '') !== (cacheEntry.rootConversationId || ''); const stepsChanged = !prev || + Boolean(prev.offlineTranscriptFallback) || prev.signature !== sig || Boolean(prev.wasRunning) !== isRunning || !prev.contextLimitTelemetry || @@ -914,8 +1407,102 @@ export async function enumerateAndSyncConversations({ cacheDirty = true; } } catch (err) { - console.error(`Failed loading trajectory ${conv.cascadeId}: ${err.message}`); - if (!(isRunning && hasTailStepInfo)) { + let offlineRecovered = false; + if (!conv.inSummaries && (!prev || prev.offlineTranscriptFallback)) { + if (!lazyExternalByLower) { + lazyExternalByLower = new Map(); + for (const ext of loadExternalDeepStatsCache().values()) { + const extCid = String(ext?.cascadeId || '').toLowerCase(); + if (!extCid) continue; + if ( + ext.accountName && + currentAccountName !== '' && + ext.accountName !== currentAccountName + ) { + continue; + } + const existingExt = lazyExternalByLower.get(extCid); + if (!existingExt || (ext.steps?.length || 0) > (existingExt.steps?.length || 0)) { + lazyExternalByLower.set(extCid, ext); + } + } + } + const cidLower = conv.cascadeId.toLowerCase(); + const diskFiles = diskConvMap.get(cidLower) || []; + const offlineFallback = loadOfflineTranscriptConversation( + conv, + diskFiles, + lazyExternalByLower, + localSummaryByLower.get(cidLower) || null + ); + if (offlineFallback) { + offlineRecovered = true; + conv.title = offlineFallback.title; + conv.lastModifiedMs = offlineFallback.lastModifiedMs; + conv.stepCount = offlineFallback.steps.length; + conv.subagentRefs = offlineFallback.subagentRefs; + if (offlineFallback.parentConversationId) { + conv.parentConversationId = offlineFallback.parentConversationId; + } + if (offlineFallback.rootConversationId) { + conv.rootConversationId = offlineFallback.rootConversationId; + } + conv.isSubagent = + Boolean(conv.parentConversationId) || + Boolean(conv.rootConversationId && conv.rootConversationId !== cidLower); + const resolvedDiskMtime = conv.diskMtimeMs ?? readConversationMtime(diskFiles); + const offlineEntry = { + signature: sig, + accountName: + prev?.accountName || offlineFallback.accountName || currentAccountName || '', + title: offlineFallback.title, + ...(offlineFallback.appSource ? { appSource: offlineFallback.appSource } : {}), + lastModifiedMs: offlineFallback.lastModifiedMs, + diskMtimeMs: resolvedDiskMtime, + wasRunning: isRunning, + offlineTranscriptFallback: true, + ...(offlineFallback.fromSqlite ? { offlineSqliteTelemetry: true } : {}), + contextLimitTelemetry: true, + speedClearedTelemetry: true, + turnRailTelemetry: true, + contextGroupsTelemetry: true, + steps: offlineFallback.steps, + subagentRefs: offlineFallback.subagentRefs, + }; + if (conv.isSubagent) { + offlineEntry.parentConversationId = conv.parentConversationId; + offlineEntry.rootConversationId = conv.rootConversationId; + if (conv.subagentSpec) offlineEntry.subagentSpec = conv.subagentSpec; + if (conv.agentScriptName) offlineEntry.agentScriptName = conv.agentScriptName; + if (conv.createdTimeMs) offlineEntry.createdTimeMs = conv.createdTimeMs; + if (Number.isFinite(conv.spawnOrder)) offlineEntry.spawnOrder = conv.spawnOrder; + } + const changed = + !prev || + prev.signature !== sig || + prev.title !== offlineEntry.title || + Boolean(prev.wasRunning) !== isRunning || + Boolean(prev.offlineSqliteTelemetry) !== Boolean(offlineEntry.offlineSqliteTelemetry) || + !isDeepStrictEqual(prev.steps, offlineEntry.steps); + if (!changed) offlineEntry.steps = prev.steps; + trajectoryCache[conv.cascadeId] = offlineEntry; + if (changed) { + cacheDirty = true; + } + } + } + if ( + !offlineRecovered && + !( + !conv.inSummaries && + /(?:\(404\)|\bnot_found\b|Language Server address unavailable)/i.test( + String(err?.message || '') + ) + ) + ) { + console.error(`Failed loading trajectory ${conv.cascadeId}: ${err.message}`); + } + if (!(isRunning && (hasTailStepInfo || offlineRecovered))) { const cooldownMs = isRunning || isReq ? ACTIVE_FAILED_RPC_COOLDOWN_MS : FAILED_RPC_COOLDOWN_MS; failedFetchCooldownMap.set(cooldownKey, { failedAt: nowPollMs, cooldownMs }); @@ -935,6 +1522,7 @@ export async function enumerateAndSyncConversations({ } } if ( + !offlineRecovered && prev && String(prev.signature || '').startsWith(`${CACHE_SCHEMA_VERSION}:`) && !Array.isArray(prev.subagentRefs) @@ -986,6 +1574,7 @@ export async function enumerateAndSyncConversations({ const toFetch = rawConversations.filter((conv) => { const sig = buildConvSig(conv); if (isFetchInCooldown(conv, sig)) return false; + const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING'; const cached = trajectoryCache[conv.cascadeId]; if (!cached || conv.needsInitialLoad) return true; const lowerCid = conv.cascadeId.toLowerCase(); @@ -1009,7 +1598,20 @@ export async function enumerateAndSyncConversations({ if (hasMissingStepFields(cached)) return true; const missingSubagentRefs = !Array.isArray(cached.subagentRefs); if (!conv.inSummaries) { - if (missingSubagentRefs && conv.cascadeId.toLowerCase() === reqLower) { + if (isRunning || cached.wasRunning) return true; + if ( + cached.offlineTranscriptFallback && + !cached.offlineSqliteTelemetry && + hasBuiltinNodeSqlite() && + hasLocalSqliteDb(diskConvMap.get(lowerCid)) + ) { + return true; + } + const localSum = localSummaryByLower.get(lowerCid); + if (cached.offlineTranscriptFallback && localSum?.title && cached.title !== localSum.title) { + return true; + } + if (missingSubagentRefs && lowerCid === reqLower) { return true; } if ( @@ -1017,8 +1619,15 @@ export async function enumerateAndSyncConversations({ conv.diskMtimeMs > (cached.diskMtimeMs || cached.lastModifiedMs || 0) ) return true; } else { - const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING'; - if (missingSubagentRefs || cached.signature !== sig || isRunning || cached.wasRunning) return true; + if ( + cached.offlineTranscriptFallback || + missingSubagentRefs || + cached.signature !== sig || + isRunning || + cached.wasRunning + ) { + return true; + } } // 保留已有效的历史测速,按批补读需要确认原始状态与生成结束时间的旧步骤。 if (!cached.speedClearedTelemetry && readStepFieldChecks(cached.steps).hasIncompleteTiming) { @@ -1114,6 +1723,7 @@ export async function enumerateAndSyncConversations({ const isSelectedSubFamily = rootId === selectedRootId; const hasValidSubCache = existingSubCache && + !(existingSubCache.offlineTranscriptFallback && subConv.inSummaries) && String(existingSubCache.signature || '').startsWith(`${CACHE_SCHEMA_VERSION}:`) && !hasMissingStepFields(existingSubCache) && (!isSelectedSubFamily || diff --git a/sidecars/panel/backend/ls-discovery.mjs b/sidecars/panel/backend/ls-discovery.mjs index e032810..b73617e 100644 --- a/sidecars/panel/backend/ls-discovery.mjs +++ b/sidecars/panel/backend/ls-discovery.mjs @@ -1,14 +1,16 @@ /** - * @fileoverview Antigravity Hub / Language Server 本地进程自动发现器。 + * @fileoverview Antigravity Hub / Language Server 本地守护文件与进程自动发现器。 * - * 当插件通过 `mcp_config.json` 在 Antigravity IDE 中以后台守护方式启动时, - * 宿主可能未在环境变量中直接注入 `ANTIGRAVITY_LS_ADDRESS` 与 `ANTIGRAVITY_CSRF_TOKEN`。 - * 本模块跨平台(Windows / macOS / Linux)枚举当前用户的 `agy --hub` 或 `language_server` 进程, - * 优先匹配父进程 `process.ppid`,并经 `GetUserStatus` 实测握手验证后写入 `lsRuntimeEndpoint`。 + * 兼容 Antigravity 2.0、Antigravity IDE、无头 `agy` CLI 与 `agy remote-control serve`: + * 1. 优先读取 `~/.gemini//daemon/hub_*.json`(跨平台零外部命令依赖,毫秒级命中 `httpPort` + `csrfToken`); + * 2. 回退枚举当前用户的 `agy` / `antigravity-cli` / `language_server` 进程; + * 3. 在精简版无头 Linux 环境优先通过 `/proc//fd` + `/proc/net/tcp{,6}` 与 `ss -H -lntp` 解析监听端口,不强依赖 `lsof`; + * 4. 经 `GetUserStatus` 实测握手验证后写入 `lsRuntimeEndpoint`。 */ -import { existsSync, readdirSync, readFileSync } from 'node:fs'; -import { lsRuntimeEndpoint, setLsRuntimeEndpoint } from './config.mjs'; +import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; +import { join } from 'node:path'; +import { DAEMON_DIRS, lsRuntimeEndpoint, setLsRuntimeEndpoint } from './config.mjs'; const LS_DISC_COOLDOWN_MS = 4000; @@ -17,8 +19,20 @@ const lsDiscoveryState = { lastAttemptMs: 0, }; +function defaultIsLsPidAlive(pid) { + if (!Number.isInteger(pid) || pid <= 0) return true; + if (typeof process?.kill !== 'function') return true; + if (pid === process.pid) return true; + try { + process.kill(pid, 0); + return true; + } catch (err) { + return err?.code === 'EPERM'; + } +} + /** - * 从 `agy --hub` 或 `language_server` 命令行字符串中提取端口号与 CSRF 令牌。 + * 从 `agy`(`--hub` / `remote-control` / CLI)或 `language_server` 命令行字符串中提取端口号与 CSRF 令牌。 * * @param {string} commandLine * @returns {{ hubPort: number|null, csrfToken: string, isHub: boolean, isLanguageServer: boolean }} @@ -28,11 +42,14 @@ export function parseLsArgsFromCommandLine(commandLine) { if (!cmd) { return { hubPort: null, csrfToken: '', isHub: false, isLanguageServer: false }; } - const isHub = /(?:^|[\s/\\"'])agy(?:\.exe)?(?:["'\s]|$)/i.test(cmd) && /--hub\b/i.test(cmd); + const isAgyBinary = /(?:^|[\s/\\"'])(?:agy|antigravity-cli)(?:\.exe)?(?:["'\s]|$)/i.test(cmd); + const isHub = isAgyBinary && /(?:--hub\b|\bremote-control\b|--csrf[-_]token\b)/i.test(cmd); const isLanguageServer = /language_server/i.test(cmd); let hubPort = null; - const portMatch = cmd.match(/--hub[-_]port(?:=|\s+)["']?(\d{1,5})["']?(?=\s|$)/i); + const portMatch = cmd.match( + /--(?:hub[-_]port|http[-_]port|https[-_]server[-_]port|server[-_]port)(?:=|\s+)["']?(\d{1,5})["']?(?=\s|$)/i + ); if (portMatch) { const num = Number(portMatch[1]); if (Number.isInteger(num) && num > 0 && num <= 65535) { @@ -54,6 +71,159 @@ export function parseLsArgsFromCommandLine(commandLine) { }; } +/** + * 解析 Linux `/proc/net/tcp` 或 `/proc/net/tcp6` 内容,提取指定 socket inode 集合中处于 `0A` (LISTEN) 状态的本地端口。 + * + * @param {string} tcpTableText + * @param {Set} socketInodes + * @returns {number[]} + */ +export function parseLinuxProcNetTcpPorts(tcpTableText, socketInodes) { + if (!tcpTableText || !(socketInodes instanceof Set) || socketInodes.size === 0) { + return []; + } + const ports = new Set(); + for (const rawLine of String(tcpTableText).split(/\r?\n/)) { + const line = rawLine.trim(); + if (!line || /^sl\b/i.test(line)) continue; + const cols = line.split(/\s+/); + if (cols.length < 10) continue; + const localAddr = cols[1] || ''; + const stateHex = (cols[3] || '').toUpperCase(); + const inode = cols[9] || ''; + if (stateHex !== '0A' || !socketInodes.has(inode)) continue; + const colonIdx = localAddr.lastIndexOf(':'); + if (colonIdx < 0) continue; + const port = Number.parseInt(localAddr.slice(colonIdx + 1), 16); + if (Number.isInteger(port) && port > 0 && port <= 65535) { + ports.add(port); + } + } + return Array.from(ports); +} + +/** + * 解析 Linux `ss -H -lntp` 输出,提取归属于目标 `pid` 的监听端口。 + * + * @param {string} ssOutput + * @param {number} pid + * @returns {number[]} + */ +export function parseSsListeningPorts(ssOutput, pid) { + if (!ssOutput || !Number.isInteger(pid) || pid <= 0) return []; + const pidTokenRe = new RegExp(`\\bpid=${pid}\\b`); + const ports = new Set(); + for (const rawLine of String(ssOutput).split(/\r?\n/)) { + const line = rawLine.trim(); + if (!line || !pidTokenRe.test(line)) continue; + const cols = line.split(/\s+/); + const localCol = cols[3] || ''; + const m = localCol.match(/:(\d{1,5})$/); + if (m) { + const p = Number(m[1]); + if (Number.isInteger(p) && p > 0 && p <= 65535) ports.add(p); + } + } + return Array.from(ports); +} + +async function readLinuxProcListeningPorts(pid, customProcFs = null) { + try { + const fsMod = customProcFs || (await import('node:fs')); + const readlinkFn = fsMod.readlinkSync || fsMod.default?.readlinkSync; + const readdirFn = fsMod.readdirSync || fsMod.default?.readdirSync || readdirSync; + const readFileFn = fsMod.readFileSync || fsMod.default?.readFileSync || readFileSync; + const existsFn = fsMod.existsSync || fsMod.default?.existsSync || existsSync; + if (typeof readlinkFn !== 'function') return []; + + const fdDir = `/proc/${pid}/fd`; + if (!existsFn(fdDir)) return []; + const socketInodes = new Set(); + for (const fdName of readdirFn(fdDir)) { + try { + const target = String(readlinkFn(`${fdDir}/${fdName}`) || ''); + const m = target.match(/^socket:\[(\d+)\]$/); + if (m) socketInodes.add(m[1]); + } catch { + // 忽略瞬态关闭的 fd + } + } + if (socketInodes.size === 0) return []; + + const ports = new Set(); + for (const netFile of [`/proc/${pid}/net/tcp`, `/proc/${pid}/net/tcp6`, '/proc/net/tcp', '/proc/net/tcp6']) { + if (!existsFn(netFile)) continue; + try { + const raw = String(readFileFn(netFile, 'utf8') || ''); + for (const p of parseLinuxProcNetTcpPorts(raw, socketInodes)) { + ports.add(p); + } + } catch { + // 忽略不可读的 proc 网络表 + } + } + return Array.from(ports); + } catch { + return []; + } +} + +function readHubDaemonCandidates(daemonDirs, preferredPids, isPidAliveFn) { + const candidates = []; + const seenKeys = new Set(); + for (const dir of Array.isArray(daemonDirs) ? daemonDirs : []) { + if (!dir || !existsSync(dir)) continue; + let names = []; + try { + names = readdirSync(dir); + } catch { + continue; + } + for (const name of names) { + if (!/^hub_.*\.json$/i.test(name)) continue; + const fullPath = join(dir, name); + try { + const st = statSync(fullPath); + const parsed = JSON.parse(readFileSync(fullPath, 'utf8')); + const csrfToken = String(parsed?.csrfToken || parsed?.csrf_token || '').trim(); + if (!csrfToken) continue; + const pid = Number(parsed?.pid) || 0; + if (pid > 0 && !isPidAliveFn(pid)) continue; + const httpPort = Number(parsed?.httpPort || parsed?.port) || 0; + const httpsPort = Number(parsed?.httpsPort) || 0; + const targets = []; + if (Number.isInteger(httpPort) && httpPort > 0 && httpPort <= 65535) { + targets.push({ port: httpPort, protos: ['http', 'https'] }); + } + if ( + Number.isInteger(httpsPort) && + httpsPort > 0 && + httpsPort <= 65535 && + httpsPort !== httpPort + ) { + targets.push({ port: httpsPort, protos: ['https', 'http'] }); + } + if (targets.length === 0) continue; + const dedupKey = `${pid}:${httpPort}:${httpsPort}:${csrfToken}`; + if (seenKeys.has(dedupKey)) continue; + seenKeys.add(dedupKey); + const priority = preferredPids.has(pid) ? 115 : 95; + candidates.push({ + pid, + priority, + mtimeMs: Number(st?.mtimeMs || 0), + csrfToken, + targets, + }); + } catch { + // 忽略损坏或正在替换的 daemon 文件 + } + } + } + candidates.sort((a, b) => b.priority - a.priority || b.mtimeMs - a.mtimeMs || b.pid - a.pid); + return candidates; +} + async function execLsDiscoveryCmd(file, args, timeoutMs = 5000) { const cpMod = await import('node:child_process'); const execFileFn = cpMod.execFile || cpMod.default?.execFile; @@ -87,7 +257,7 @@ function readLinuxProcCandidates() { const rawCmd = readFileSync(`/proc/${pid}/cmdline`, 'utf8'); if (!rawCmd) continue; const commandLine = rawCmd.replace(/\0+/g, ' ').trim(); - if (!/agy|language_server/i.test(commandLine)) continue; + if (!/agy|antigravity-cli|language_server/i.test(commandLine)) continue; let ppid = 0; try { const statRaw = readFileSync(`/proc/${pid}/stat`, 'utf8'); @@ -111,7 +281,7 @@ function readLinuxProcCandidates() { async function listCandidateOsProcesses(platform, execCmdFn) { if (platform === 'win32') { const psScript = - "Get-CimInstance Win32_Process -Filter \"Name LIKE 'agy%' OR Name LIKE 'language_server%'\" | Select-Object ProcessId,ParentProcessId,CommandLine | ConvertTo-Json -Compress"; + "Get-CimInstance Win32_Process -Filter \"Name LIKE 'agy%' OR Name LIKE 'antigravity-cli%' OR Name LIKE 'language_server%'\" | Select-Object ProcessId,ParentProcessId,CommandLine | ConvertTo-Json -Compress"; const out = await execCmdFn('powershell.exe', [ '-NoProfile', '-NonInteractive', @@ -144,7 +314,7 @@ async function listCandidateOsProcesses(platform, execCmdFn) { const m = line.trim().match(/^(\d+)\s+(\d+)\s+(.+)$/); if (!m) continue; const cmdLine = m[3]; - if (!/agy|language_server/i.test(cmdLine)) continue; + if (!/agy|antigravity-cli|language_server/i.test(cmdLine)) continue; results.push({ pid: Number(m[1]) || 0, ppid: Number(m[2]) || 0, @@ -154,10 +324,10 @@ async function listCandidateOsProcesses(platform, execCmdFn) { return results; } -async function findListeningPortsForPid(pid, platform, execCmdFn) { +async function findListeningPortsForPid(pid, platform, execCmdFn, procFs = null) { if (!Number.isInteger(pid) || pid <= 0) return []; - try { - if (platform === 'win32') { + if (platform === 'win32') { + try { const out = await execCmdFn('powershell.exe', [ '-NoProfile', '-NonInteractive', @@ -175,7 +345,24 @@ async function findListeningPortsForPid(pid, platform, execCmdFn) { .filter((p) => Number.isInteger(p) && p > 0 && p <= 65535) ) ); + } catch { + return []; } + } + + if (platform === 'linux') { + const procPorts = await readLinuxProcListeningPorts(pid, procFs); + if (procPorts.length > 0) return procPorts; + try { + const ssOut = await execCmdFn('ss', ['-H', '-lntp']); + const ssPorts = parseSsListeningPorts(ssOut, pid); + if (ssPorts.length > 0) return ssPorts; + } catch { + // 无 ss 或权限受限时继续回退至 lsof + } + } + + try { const out = await execCmdFn('lsof', ['-Pan', '-p', String(pid), '-iTCP', '-sTCP:LISTEN']); const ports = new Set(); for (const line of out.split(/\r?\n/)) { @@ -191,8 +378,8 @@ async function findListeningPortsForPid(pid, platform, execCmdFn) { } } -async function probeLsCandidate(port, csrfToken, fetchFn) { - for (const proto of ['http', 'https']) { +async function probeLsCandidate(port, csrfToken, fetchFn, protos = ['http', 'https']) { + for (const proto of protos) { try { const addr = `127.0.0.1:${port}`; const baseUrl = `${proto}://${addr}`; @@ -225,6 +412,9 @@ async function probeLsCandidate(port, csrfToken, fetchFn) { * ppid?: number, * ancestorPids?: number[], * platform?: string, + * daemonDirs?: string[], + * isPidAliveFn?: (pid: number) => boolean, + * procFs?: object|null, * execCmdFn?: (file: string, args: string[]) => Promise, * fetchFn?: typeof fetch * }} [options] @@ -235,6 +425,9 @@ export async function discoverAntigravityLsEndpoint(options = {}) { ppid = Number(process?.ppid || 0), ancestorPids = [], platform = process?.platform || 'win32', + daemonDirs = options.execCmdFn ? [] : DAEMON_DIRS, + isPidAliveFn = defaultIsLsPidAlive, + procFs = null, execCmdFn = execLsDiscoveryCmd, fetchFn = typeof fetch === 'function' ? fetch : null, } = options; @@ -247,6 +440,20 @@ export async function discoverAntigravityLsEndpoint(options = {}) { .filter((n) => Number.isInteger(n) && n > 0) ); + // 1. 优先探测 ~/.gemini//daemon/hub_*.json 守护端点描述文件(零外部进程开销) + const daemonCandidates = readHubDaemonCandidates(daemonDirs, preferredPids, isPidAliveFn); + const probedDaemonKeys = new Set(); + for (const cand of daemonCandidates) { + for (const target of cand.targets) { + probedDaemonKeys.add(`${target.port}:${cand.csrfToken}`); + const verified = await probeLsCandidate(target.port, cand.csrfToken, fetchFn, target.protos); + if (verified) { + return { ...verified, pid: cand.pid }; + } + } + } + + // 2. 回退枚举操作系统进程并解析监听端口 let rawProcs = []; try { rawProcs = await listCandidateOsProcesses(platform, execCmdFn); @@ -280,8 +487,9 @@ export async function discoverAntigravityLsEndpoint(options = {}) { for (const cand of parsedCandidates) { const ports = cand.hubPort ? [cand.hubPort] - : await findListeningPortsForPid(cand.pid, platform, execCmdFn); + : await findListeningPortsForPid(cand.pid, platform, execCmdFn, procFs); for (const port of ports) { + if (probedDaemonKeys.has(`${port}:${cand.csrfToken}`)) continue; const verified = await probeLsCandidate(port, cand.csrfToken, fetchFn); if (verified) { return { ...verified, pid: cand.pid }; @@ -292,12 +500,16 @@ export async function discoverAntigravityLsEndpoint(options = {}) { } /** - * 确保 `lsRuntimeEndpoint` 已就绪(具备并发去重与失败冷却保护)。 + * 确保 `lsRuntimeEndpoint` 已就绪(具备并发去重、失败冷却与动态端点重连能力)。 * - * @param {{ force?: boolean, ancestorPids?: number[] }} [options] + * @param {{ force?: boolean, respectCooldown?: boolean, ancestorPids?: number[] }} [options] * @returns {Promise} */ -export async function ensureLsEndpointDiscovered({ force = false, ancestorPids = [] } = {}) { +export async function ensureLsEndpointDiscovered({ + force = false, + respectCooldown = false, + ancestorPids = [], +} = {}) { if (lsRuntimeEndpoint.addr === 'test.invalid') { return false; } @@ -309,7 +521,7 @@ export async function ensureLsEndpointDiscovered({ force = false, ancestorPids = } const now = Date.now(); if ( - !force && + (!force || respectCooldown) && lsDiscoveryState.lastAttemptMs > 0 && now - lsDiscoveryState.lastAttemptMs < LS_DISC_COOLDOWN_MS ) { @@ -328,7 +540,7 @@ export async function ensureLsEndpointDiscovered({ force = false, ancestorPids = ancestorPids: [...envHintPids, ...ancestorPids], }); if (found && found.addr && found.csrfToken) { - setLsRuntimeEndpoint(found.addr, found.csrfToken); + setLsRuntimeEndpoint(found.addr, found.csrfToken, { isDynamic: true }); return true; } return Boolean(lsRuntimeEndpoint.baseUrl); diff --git a/sidecars/panel/backend/settings-schema.mjs b/sidecars/panel/backend/settings-schema.mjs index 759ee97..de979d9 100644 --- a/sidecars/panel/backend/settings-schema.mjs +++ b/sidecars/panel/backend/settings-schema.mjs @@ -342,6 +342,19 @@ export function normalizeModelContextWindows(value) { ); } +/** + * 归一化独立 Web 服务自动托管端口(`0` 表示关闭自动拉起,合法监听端口范围 `1024..65535`)。 + * + * @param {unknown} port + * @returns {number} + */ +export function normalizeStandalonePort(port) { + const num = Number(port); + if (!Number.isInteger(num) || num <= 0) return 0; + if (num >= 1024 && num <= 65535) return num; + return 0; +} + export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({ language: 'zh-CN', themeAccent: 'host', @@ -355,6 +368,7 @@ export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({ autoUpdatePlugin: false, windowMountMode: 'dual', enableWindowOverlay: true, + standalonePort: 0, showTopbarMultiSession: true, topbarCapsuleSlots: DEFAULT_TOPBAR_SLOTS, hoverModules: DEFAULT_HOVER_MODULES, @@ -383,6 +397,7 @@ export function createDefaultSettingsObject() { autoUpdatePlugin: DEFAULT_SETTINGS_SCHEMA.autoUpdatePlugin, windowMountMode: DEFAULT_SETTINGS_SCHEMA.windowMountMode, enableWindowOverlay: DEFAULT_SETTINGS_SCHEMA.enableWindowOverlay, + standalonePort: DEFAULT_SETTINGS_SCHEMA.standalonePort, showTopbarMultiSession: DEFAULT_SETTINGS_SCHEMA.showTopbarMultiSession, topbarCapsuleSlots: [...DEFAULT_TOPBAR_SLOTS], hoverModules: [...DEFAULT_HOVER_MODULES], @@ -429,6 +444,7 @@ export function normalizeFullSettings(rawInput) { autoUpdatePlugin: pluginUpdateMode === 'auto', windowMountMode, enableWindowOverlay: windowMountMode !== 'sidebar', + standalonePort: normalizeStandalonePort(safeRaw.standalonePort), showTopbarMultiSession: safeRaw.showTopbarMultiSession !== false, topbarCapsuleSlots: normalizeTopbarCapsuleSlots(safeRaw.topbarCapsuleSlots), hoverModules: normalizeHoverModules(safeRaw.hoverModules), diff --git a/sidecars/panel/backend/standalone-server.mjs b/sidecars/panel/backend/standalone-server.mjs new file mode 100644 index 0000000..8739606 --- /dev/null +++ b/sidecars/panel/backend/standalone-server.mjs @@ -0,0 +1,639 @@ +/** + * @fileoverview 无 `sidecar_sdk` 依赖的独立 Web 监控 HTTP 服务端 (`standalone-server.mjs`)。 + * + * 面向无头 Linux CLI (`agy` / `agy remote-control serve`)、SSH 端口转发 (`ssh -L`) 与受保护远程访问场景: + * 1. 默认严格绑定 `127.0.0.1`(本机浏览器或 `ssh -L` 零配置直连,校检回环地址与同端口 Host/Origin); + * 2. 若显式绑定非回环地址(如 `0.0.0.0`、`::` 或局域网 IP),强制要求配置 `--token ` 或 + * `USAGE_MONITOR_STANDALONE_TOKEN`,拒绝无鉴权公网/局域网裸奔启动; + * 3. 完整托管四分页 Web 面板(`/`、`/app.js`、`/styles.css`、`/preload.js` 兼容桩)与 `/api/*` 路由。 + */ + +import { createHash, createHmac, timingSafeEqual } from 'node:crypto'; +import http from 'node:http'; +import { + dispatchBridgeApiRequest, + isLocalHostRequest, + readLocalAsync, +} from './api-actions.mjs'; +import { lsRuntimeEndpoint, setLsRuntimeEndpoint } from './config.mjs'; +import { ensureLsEndpointDiscovered } from './ls-discovery.mjs'; +import { syncCloudCatalog } from './plugin-updater.mjs'; + +const MAX_JSON_BODY_BYTES = 1024 * 1024; +const AUTH_COOKIE_NAME = 'ag_um_token'; +const NO_STORE_HEADERS = { + 'Cache-Control': 'no-store, no-cache, must-revalidate', + 'X-Content-Type-Options': 'nosniff', +}; + +/** + * 判断绑定监听地址是否属于纯本机回环地址。 + * + * @param {string} host + * @returns {boolean} + */ +export function isLoopbackBindHost(host) { + const clean = String(host || '127.0.0.1') + .trim() + .toLowerCase() + .replace(/^\[|\]$/g, ''); + if (!clean) return true; + if (clean === 'localhost' || clean === '::1' || clean === '0:0:0:0:0:0:0:1') { + return true; + } + return /^127\.(?:25[0-5]|2[0-4]\d|1?\d?\d)\.(?:25[0-5]|2[0-4]\d|1?\d?\d)\.(?:25[0-5]|2[0-4]\d|1?\d?\d)$/.test( + clean + ); +} + +function isLoopbackRemoteAddress(remoteAddress) { + const addr = String(remoteAddress || '').trim().toLowerCase(); + if (!addr) return true; + if (addr === '::1' || addr === '127.0.0.1') return true; + if (addr.startsWith('::ffff:')) { + return isLoopbackBindHost(addr.slice(7)); + } + return isLoopbackBindHost(addr); +} + +function sha256Buffer(value) { + return createHash('sha256').update(String(value ?? ''), 'utf8').digest(); +} + +function safeEqualSecret(candidate, expected) { + if (typeof candidate !== 'string' || typeof expected !== 'string' || !expected) { + return false; + } + return timingSafeEqual(sha256Buffer(candidate), sha256Buffer(expected)); +} + +function deriveCookieValue(secret) { + return createHmac('sha256', 'ag-usage-monitor-standalone-cookie-v1') + .update(secret, 'utf8') + .digest('hex'); +} + +function parseCookies(cookieHeader) { + const out = {}; + for (const part of String(cookieHeader || '').split(';')) { + const idx = part.indexOf('='); + if (idx <= 0) continue; + const k = part.slice(0, idx).trim(); + const v = part.slice(idx + 1).trim(); + if (!k) continue; + try { + out[k] = decodeURIComponent(v); + } catch { + out[k] = v; + } + } + return out; +} + +function extractBearerToken(authHeader) { + const raw = String(authHeader || '').trim(); + const m = raw.match(/^Bearer\s+(.+)$/i); + return m ? m[1].trim() : ''; +} + +function renderTokenLoginHtml(hasError = false) { + const errHtml = hasError + ? '

访问令牌无效,请核对后重新输入。

' + : ''; + return ` + + + + + 用量监控 · 访问验证 + + + +
+

Antigravity Usage Monitor

+

当前独立监控服务已启用访问令牌保护,请输入 Token 继续。

+ ${errHtml} + + +
+ +`; +} + +/** + * 解析独立 Web 模式的命令行参数与环境变量。 + * + * @param {string[]} [argv=[]] + * @param {Record} [env=process.env] + * @param {{ defaultPort?: number }} [options] + */ +export function parseStandaloneCliArgs(argv = [], env = process.env, { defaultPort = 8787 } = {}) { + const out = { + help: false, + standaloneFlag: false, + host: String(env.USAGE_MONITOR_STANDALONE_HOST || '127.0.0.1').trim() || '127.0.0.1', + port: null, + portExplicit: false, + token: String(env.USAGE_MONITOR_STANDALONE_TOKEN || '').trim(), + lsAddr: String(env.ANTIGRAVITY_LS_ADDRESS || '').trim(), + csrfToken: String(env.ANTIGRAVITY_CSRF_TOKEN || env.ANTIGRAVITY_SERVER_CSRF_TOKEN || '').trim(), + dataDir: String(env.USAGE_MONITOR_DATA_DIR || '').trim(), + appDataDir: String(env.USAGE_MONITOR_APP_DATA_DIR || env.ANTIGRAVITY_APP_DATA_DIR || '').trim(), + geminiDir: String(env.ANTIGRAVITY_GEMINI_DIR || '').trim(), + }; + + if (env.USAGE_MONITOR_STANDALONE_PORT !== undefined && String(env.USAGE_MONITOR_STANDALONE_PORT).trim() !== '') { + const envPort = Number(env.USAGE_MONITOR_STANDALONE_PORT); + if (Number.isInteger(envPort) && envPort >= 0 && envPort <= 65535) { + out.port = envPort; + out.portExplicit = true; + } + } + + const args = Array.isArray(argv) ? argv : []; + for (let i = 0; i < args.length; i++) { + const raw = String(args[i] || ''); + if (!raw) continue; + if (raw === '--help' || raw === '-h') { + out.help = true; + continue; + } + if (raw === '--standalone') { + out.standaloneFlag = true; + continue; + } + + const eqIdx = raw.indexOf('='); + const flag = eqIdx > 0 ? raw.slice(0, eqIdx) : raw; + const readVal = () => { + if (eqIdx > 0) return raw.slice(eqIdx + 1); + if (i + 1 < args.length) { + i += 1; + return String(args[i] || ''); + } + return ''; + }; + + if (flag === '--port' || flag === '-p') { + const num = Number(readVal().trim()); + if (!Number.isInteger(num) || num < 0 || num > 65535) { + throw new Error(`Invalid --port value (expected 0..65535)`); + } + out.port = num; + out.portExplicit = true; + } else if (flag === '--host' || flag === '-H') { + const val = readVal().trim(); + if (!val) throw new Error('Missing value for --host'); + out.host = val; + } else if (flag === '--token') { + out.token = readVal().trim(); + } else if (flag === '--ls-addr') { + out.lsAddr = readVal().trim(); + } else if (flag === '--csrf-token') { + out.csrfToken = readVal().trim(); + } else if (flag === '--data-dir') { + out.dataDir = readVal().trim(); + } else if (flag === '--app-data-dir') { + out.appDataDir = readVal().trim(); + } else if (flag === '--gemini-dir') { + out.geminiDir = readVal().trim(); + } + } + + if (out.port === null) { + out.port = defaultPort; + } + return out; +} + +export function formatStandaloneHelpText() { + return [ + 'Antigravity Usage Monitor — Standalone Web Server (CLI / Remote Mode)', + '', + 'Usage:', + ' node sidecars/panel/standalone.mjs [options]', + '', + 'Options:', + ' -p, --port HTTP listen port (default: 8787; 0 picks a random port)', + ' -H, --host Bind address (default: 127.0.0.1)', + ' --token Access token (required when --host is non-loopback)', + ' --ls-addr Explicit Language Server / Hub address override', + ' --csrf-token Explicit Language Server CSRF token override', + ' --app-data-dir Additional product data dir (e.g. ~/.gemini/antigravity-cli)', + ' --data-dir Persistent cache & settings storage directory', + ' -h, --help Show this help message', + '', + 'Examples:', + ' # 1) Recommended for headless Linux servers (use with ssh -L 8787:127.0.0.1:8787 user@host):', + ' node sidecars/panel/standalone.mjs --port 8787', + '', + ' # 2) Direct LAN / reverse-proxy bind (requires --token):', + ' node sidecars/panel/standalone.mjs --host 0.0.0.0 --port 8787 --token ', + ].join('\n'); +} + +function readRawBody(req, maxBytes = MAX_JSON_BODY_BYTES) { + return new Promise((resolve, reject) => { + const chunks = []; + let total = 0; + let settled = false; + req.on('data', (chunk) => { + if (settled) return; + const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf8'); + total += buf.length; + if (total > maxBytes) { + settled = true; + const err = new Error('Payload too large'); + err.statusCode = 413; + reject(err); + req.resume(); + return; + } + chunks.push(buf); + }); + req.on('end', () => { + if (settled) return; + settled = true; + resolve(Buffer.concat(chunks).toString('utf8')); + }); + req.on('error', (err) => { + if (settled) return; + settled = true; + reject(err); + }); + }); +} + +function isSameOriginPostRequest(req) { + const secFetchSite = String(req.headers?.['sec-fetch-site'] || '').trim().toLowerCase(); + if (secFetchSite === 'cross-site') return false; + const origin = String(req.headers?.origin || '').trim(); + if (!origin) return true; + const host = String(req.headers?.host || '').trim().toLowerCase(); + if (!host) return false; + try { + const parsedOrigin = new URL(origin); + return parsedOrigin.host.toLowerCase() === host; + } catch { + return false; + } +} + +/** + * 创建独立 Web 监控服务器控制器。 + * + * @param {{ + * host?: string, + * port?: number, + * token?: string, + * lsAddr?: string, + * csrfToken?: string, + * handleApiRequest?: typeof dispatchBridgeApiRequest, + * readAssetFn?: typeof readLocalAsync, + * onRestart?: (() => void) | null, + * skipStartupDiscovery?: boolean + * }} [options] + */ +export function createStandaloneWebServer(options = {}) { + const host = String(options.host || '127.0.0.1').trim() || '127.0.0.1'; + const requestedPort = Number.isInteger(options.port) ? options.port : 8787; + const token = String(options.token || '').trim(); + const loopbackHost = isLoopbackBindHost(host); + + if (!loopbackHost && !token) { + throw new Error( + `Refusing to bind standalone server to non-loopback host "${host}" without --token (or USAGE_MONITOR_STANDALONE_TOKEN). Bind to 127.0.0.1 with SSH port forwarding (ssh -L), or configure an access token.` + ); + } + + if (options.lsAddr && options.csrfToken) { + setLsRuntimeEndpoint(options.lsAddr, options.csrfToken, { isDynamic: false }); + } + + const expectedCookieVal = token ? deriveCookieValue(token) : ''; + const onRestart = typeof options.onRestart === 'function' ? options.onRestart : () => {}; + const handleApi = + options.handleApiRequest || + ((pathname, method, data) => + dispatchBridgeApiRequest(pathname, method, data, { onRestart })); + const readAsset = options.readAssetFn || readLocalAsync; + + let server = null; + let boundPort = 0; + + function sendResponse(res, status, contentType, body, extraHeaders = {}) { + const payload = Buffer.isBuffer(body) ? body : Buffer.from(String(body ?? ''), 'utf8'); + res.writeHead(status, { + 'Content-Type': contentType, + 'Content-Length': payload.length, + ...NO_STORE_HEADERS, + ...extraHeaders, + }); + res.end(payload); + } + + function checkRequestAuthorized(req, urlObj) { + if (!token) { + if (!isLoopbackRemoteAddress(req.socket?.remoteAddress)) { + return { ok: false, status: 403, reason: 'Forbidden non-loopback client' }; + } + if (!isLocalHostRequest(req)) { + return { ok: false, status: 403, reason: 'Forbidden host or origin' }; + } + return { ok: true, viaQueryToken: false }; + } + + const headerToken = String(req.headers?.['x-usage-monitor-token'] || '').trim(); + const bearerToken = extractBearerToken(req.headers?.authorization); + const hasExplicitHeaderAuth = + (headerToken && safeEqualSecret(headerToken, token)) || + (bearerToken && safeEqualSecret(bearerToken, token)); + + if (hasExplicitHeaderAuth) { + return { ok: true, viaQueryToken: false }; + } + + if (req.method === 'POST' && !isSameOriginPostRequest(req)) { + return { ok: false, status: 403, reason: 'Forbidden cross-origin request' }; + } + + const cookies = parseCookies(req.headers?.cookie); + if (cookies[AUTH_COOKIE_NAME] && safeEqualSecret(cookies[AUTH_COOKIE_NAME], expectedCookieVal)) { + return { ok: true, viaQueryToken: false }; + } + + if (req.method === 'GET' || req.method === 'HEAD') { + const queryToken = urlObj.searchParams.get('token') || ''; + if (queryToken && safeEqualSecret(queryToken, token)) { + return { ok: true, viaQueryToken: true }; + } + } + + return { ok: false, status: 401, reason: 'Unauthorized: valid access token required' }; + } + + async function handleHttpRequest(req, res) { + try { + const method = String(req.method || 'GET').toUpperCase(); + const rawUrl = String(req.url || '/'); + const urlObj = new URL(rawUrl, 'http://127.0.0.1'); + const pathname = urlObj.pathname || '/'; + + if (token && pathname === '/api/standalone-auth' && method === 'POST') { + if (!isSameOriginPostRequest(req)) { + sendResponse(res, 403, 'text/plain; charset=utf-8', 'Forbidden cross-origin request'); + return; + } + const formRaw = await readRawBody(req, 16 * 1024); + const formParams = new URLSearchParams(formRaw); + const submitted = String(formParams.get('token') || '').trim(); + if (!safeEqualSecret(submitted, token)) { + sendResponse(res, 401, 'text/html; charset=utf-8', renderTokenLoginHtml(true)); + return; + } + res.writeHead(303, { + Location: '/', + 'Set-Cookie': `${AUTH_COOKIE_NAME}=${expectedCookieVal}; HttpOnly; SameSite=Strict; Path=/`, + ...NO_STORE_HEADERS, + }); + res.end(); + return; + } + + const auth = checkRequestAuthorized(req, urlObj); + if (!auth.ok) { + if (auth.status === 401 && (pathname === '/' || pathname === '/index.html') && method === 'GET') { + sendResponse(res, 401, 'text/html; charset=utf-8', renderTokenLoginHtml(false)); + return; + } + sendResponse( + res, + auth.status, + 'application/json; charset=utf-8', + JSON.stringify({ error: auth.reason }) + ); + return; + } + + if (auth.viaQueryToken && (pathname === '/' || pathname === '/index.html') && method === 'GET') { + urlObj.searchParams.delete('token'); + const cleanSearch = urlObj.searchParams.toString(); + const redirectTarget = cleanSearch ? `/?${cleanSearch}` : '/'; + res.writeHead(302, { + Location: redirectTarget, + 'Set-Cookie': `${AUTH_COOKIE_NAME}=${expectedCookieVal}; HttpOnly; SameSite=Strict; Path=/`, + ...NO_STORE_HEADERS, + }); + res.end(); + return; + } + + if (method === 'GET' || method === 'HEAD') { + if (pathname === '/' || pathname === '/index.html') { + const html = await readAsset('index.html'); + sendResponse(res, 200, 'text/html; charset=utf-8', method === 'HEAD' ? '' : html); + return; + } + if (pathname === '/preload.js') { + sendResponse( + res, + 200, + 'application/javascript; charset=utf-8', + method === 'HEAD' ? '' : '/* standalone web mode */\n' + ); + return; + } + if (pathname === '/app.js') { + const js = await readAsset('app.js'); + sendResponse(res, 200, 'application/javascript; charset=utf-8', method === 'HEAD' ? '' : js); + return; + } + if (pathname === '/styles.css') { + const css = await readAsset('styles.css'); + sendResponse(res, 200, 'text/css; charset=utf-8', method === 'HEAD' ? '' : css); + return; + } + if (pathname === '/favicon.ico') { + res.writeHead(204, NO_STORE_HEADERS); + res.end(); + return; + } + } + + if (pathname.startsWith('/api/')) { + let data = undefined; + if (method === 'GET') { + data = Object.fromEntries(urlObj.searchParams.entries()); + delete data.token; + } else if (method === 'POST') { + const rawBody = await readRawBody(req, MAX_JSON_BODY_BYTES); + if (rawBody.trim()) { + try { + data = JSON.parse(rawBody); + } catch { + sendResponse( + res, + 400, + 'application/json; charset=utf-8', + JSON.stringify({ error: 'Invalid JSON request body' }) + ); + return; + } + } else { + data = {}; + } + } else { + sendResponse( + res, + 405, + 'application/json; charset=utf-8', + JSON.stringify({ error: 'Method not allowed' }) + ); + return; + } + + const out = await handleApi(pathname, method, data); + sendResponse( + res, + out?.status || 200, + out?.contentType || 'application/json; charset=utf-8', + out?.body ?? '{}', + out?.headers || {} + ); + return; + } + + sendResponse( + res, + 404, + 'application/json; charset=utf-8', + JSON.stringify({ error: 'Not found' }) + ); + } catch (err) { + const status = Number(err?.statusCode) || 500; + sendResponse( + res, + status, + 'application/json; charset=utf-8', + JSON.stringify({ error: err?.message || 'Internal server error' }) + ); + } + } + + async function start() { + if (server && boundPort > 0) { + return getStatus(); + } + if (!options.skipStartupDiscovery && lsRuntimeEndpoint.addr !== 'test.invalid') { + if (lsRuntimeEndpoint.baseUrl) { + syncCloudCatalog({ force: false }).catch(() => {}); + } else { + ensureLsEndpointDiscovered({ force: false }) + .then((ok) => { + if (ok) syncCloudCatalog({ force: false }).catch(() => {}); + }) + .catch(() => {}); + } + } + + const srv = http.createServer((req, res) => { + void handleHttpRequest(req, res); + }); + + await new Promise((resolve, reject) => { + const onError = (err) => { + srv.removeListener('listening', onListening); + reject(err); + }; + const onListening = () => { + srv.removeListener('error', onError); + resolve(); + }; + srv.once('error', onError); + srv.once('listening', onListening); + srv.listen(requestedPort, host); + }); + + server = srv; + const addrInfo = srv.address(); + boundPort = typeof addrInfo === 'object' && addrInfo ? Number(addrInfo.port || 0) : requestedPort; + return getStatus(); + } + + async function stop() { + const srv = server; + server = null; + boundPort = 0; + if (!srv) return; + await new Promise((resolve) => { + srv.close(() => resolve()); + }); + } + + function getStatus() { + const displayHost = host.includes(':') && !host.startsWith('[') ? `[${host}]` : host; + return { + running: Boolean(server && boundPort > 0), + host, + port: boundPort, + loopbackOnly: loopbackHost, + tokenProtected: Boolean(token), + url: boundPort > 0 ? `http://${displayHost}:${boundPort}` : '', + }; + } + + return { + start, + stop, + getStatus, + }; +} diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index 78cb846..203c969 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -21,11 +21,13 @@ import { computeRuntimeCodeVersion, inFlightRequests, loadSettings, + lsRuntimeEndpoint, roundMetric, trajectoryCache, } from './config.mjs'; import { getContextWindowGroups, getContextWindowModels } from './context-windows.mjs'; import { enumerateAndSyncConversations } from './local-scanner.mjs'; +import { ensureLsEndpointDiscovered } from './ls-discovery.mjs'; import { callLsRpc, getContextModelCatalog, getOfficialQuotaSummary } from './ls-rpc.mjs'; import { computeStepCost, @@ -647,7 +649,29 @@ export async function buildTelemetryPayloadInternal( filterOpts = {} ) { const settings = loadSettings(); - const userStatus = await callLsRpc('GetUserStatus', {}).then((data) => data?.userStatus).catch(() => null); + let userStatus = await callLsRpc('GetUserStatus', {}) + .then((data) => data?.userStatus) + .catch(() => null); + if ( + !userStatus && + lsRuntimeEndpoint.addr !== 'test.invalid' && + (!lsRuntimeEndpoint.baseUrl || lsRuntimeEndpoint.isDynamic) + ) { + const prevBaseUrl = lsRuntimeEndpoint.baseUrl; + const prevCsrf = lsRuntimeEndpoint.csrfToken; + await ensureLsEndpointDiscovered({ + force: true, + respectCooldown: !forceQuotaRefresh, + }); + if ( + lsRuntimeEndpoint.baseUrl && + (lsRuntimeEndpoint.baseUrl !== prevBaseUrl || lsRuntimeEndpoint.csrfToken !== prevCsrf) + ) { + userStatus = await callLsRpc('GetUserStatus', {}) + .then((data) => data?.userStatus) + .catch(() => null); + } + } const currentAccountName = userStatus?.email || userStatus?.name || ''; const accountStatus = currentAccountName ? 'signedIn' : userStatus && !userStatus.userTier && !userStatus.planStatus ? 'signedOut' : 'unknown'; diff --git a/sidecars/panel/bridge-daemon.mjs b/sidecars/panel/bridge-daemon.mjs index 9eaf578..01f68e1 100644 --- a/sidecars/panel/bridge-daemon.mjs +++ b/sidecars/panel/bridge-daemon.mjs @@ -1,37 +1,117 @@ /** - * @fileoverview Antigravity IDE / 2.0 独立后台双栖窗口桥接守护进程 (`bridge-daemon.mjs`)。 + * @fileoverview Antigravity IDE / 2.0 / CLI 独立后台守护进程 (`bridge-daemon.mjs`)。 * - * 由 `mcp-entry.mjs` 托管拉起,负责: - * 1. 动态探测本机运行中的 `agy --hub` / `language_server` 端点与 `DevToolsActivePort`; - * 2. 启动本地回环桥接服务并通过 CDP 将顶栏/输入框监控胶囊热挂载至 Antigravity IDE 与 2.0 窗口; - * 3. 收到父进程 `SHUTDOWN_DISPOSE` 指令或终止信号时,主动清理窗口浮层并平滑退出。 + * 由 `mcp-entry.mjs` 托管拉起(亦支持命令行 `--standalone` 直接启动),负责: + * 1. 动态探测本机运行中的 `agy` (`daemon/hub_*.json` / `--hub` / `remote-control`) 或 `language_server` 端点; + * 2. 在桌面端 / IDE 环境启动本地回环桥接服务并通过 CDP 挂载监控胶囊; + * 3. 当配置了 `USAGE_MONITOR_STANDALONE_PORT` 或 `settings.json` 中的 `standalonePort`(`1024..65535`)时, + * 自动在后台托管独立 Web 监控端口,无需手工另开进程; + * 4. 收到父进程 `SHUTDOWN_DISPOSE` 指令或终止信号时,主动清理窗口浮层与独立端口并平滑退出。 */ import { resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { bootWindowBridgeRuntime } from './backend/api-actions.mjs'; +import { + bootWindowBridgeRuntime, + setStandalonePortListener, +} from './backend/api-actions.mjs'; +import { loadSettings, normalizeStandalonePort } from './backend/config.mjs'; +import { + createStandaloneWebServer, + parseStandaloneCliArgs, +} from './backend/standalone-server.mjs'; +import { runStandaloneCli } from './standalone.mjs'; export function startBridgeDaemon() { let shuttingDown = false; let sawShutdownDispose = false; let stdinBuf = ''; + let standaloneController = null; + let activeStandalonePort = 0; + let reconcileChain = Promise.resolve(); + + const envArgs = parseStandaloneCliArgs([], process.env, { defaultPort: 0 }); + const envPinnedPort = envArgs.portExplicit ? normalizeStandalonePort(envArgs.port) : null; + + const triggerRestart = () => { + void shutdown({ disposeWindows: false, exitCode: 0 }); + }; const controller = bootWindowBridgeRuntime({ allowDynamicLs: true, - onRestart: () => { - void shutdown({ disposeWindows: false, exitCode: 0 }); - }, + onRestart: triggerRestart, }); + function resolveDesiredStandalonePort(settingsOverride = null) { + if (envPinnedPort !== null) { + return envPinnedPort; + } + const settings = settingsOverride || loadSettings(); + return normalizeStandalonePort(settings?.standalonePort); + } + + function scheduleStandaloneReconcile(targetPort) { + reconcileChain = reconcileChain + .then(async () => { + if (shuttingDown) return; + const nextPort = normalizeStandalonePort(targetPort); + if (nextPort === activeStandalonePort && standaloneController) { + return; + } + if (standaloneController) { + const prev = standaloneController; + standaloneController = null; + activeStandalonePort = 0; + await prev.stop().catch(() => {}); + } + if (nextPort <= 0 || shuttingDown) { + return; + } + try { + const srv = createStandaloneWebServer({ + host: envArgs.host, + port: nextPort, + token: envArgs.token, + onRestart: triggerRestart, + skipStartupDiscovery: true, + }); + const status = await srv.start(); + standaloneController = srv; + activeStandalonePort = nextPort; + console.error(`[usage-monitor] Auto-hosted standalone Web UI at ${status.url}`); + } catch (err) { + if (err?.code === 'EADDRINUSE') { + console.error( + `[usage-monitor] Standalone port ${nextPort} already in use; keeping existing listener.` + ); + } else { + console.error(`[usage-monitor] Auto-hosted standalone server skipped: ${err.message}`); + } + } + }) + .catch(() => {}); + } + + setStandalonePortListener((updatedPort) => { + if (envPinnedPort === null) { + scheduleStandaloneReconcile(updatedPort); + } + }); + scheduleStandaloneReconcile(resolveDesiredStandalonePort()); + async function shutdown({ disposeWindows = false, exitCode = 0 } = {}) { if (shuttingDown) return; shuttingDown = true; + setStandalonePortListener(null); const forceTimer = setTimeout(() => { process.exit(exitCode); }, 1500); forceTimer.unref?.(); try { - await controller?.stop?.({ disposeWindows }); + await Promise.allSettled([ + controller?.stop?.({ disposeWindows }), + standaloneController?.stop?.(), + ]); } catch { // 忽略退出清理异常 } finally { @@ -70,5 +150,10 @@ export function startBridgeDaemon() { const invokedPath = process.argv[1] ? resolve(process.argv[1]) : ''; if (invokedPath && invokedPath === fileURLToPath(import.meta.url)) { - startBridgeDaemon(); + const cliArgs = process.argv.slice(2); + if (cliArgs.includes('--standalone') || cliArgs.includes('--help') || cliArgs.includes('-h')) { + void runStandaloneCli(cliArgs); + } else { + startBridgeDaemon(); + } } diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index ffa494d..f9d05bb 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/package.json b/sidecars/panel/package.json index cda6499..29fb062 100644 --- a/sidecars/panel/package.json +++ b/sidecars/panel/package.json @@ -6,6 +6,7 @@ "description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor.", "scripts": { "build": "node scripts/build-bundle.mjs", + "standalone": "node standalone.mjs", "test": "node --test test/*.test.mjs" } } diff --git a/sidecars/panel/src/main.js b/sidecars/panel/src/main.js index fc1ee04..63c924f 100644 --- a/sidecars/panel/src/main.js +++ b/sidecars/panel/src/main.js @@ -41,6 +41,14 @@ function startEntry() { mountWindowOverlay(); return; } + if ( + typeof window !== 'undefined' && + !window.sidecar?.fetch && + typeof document !== 'undefined' && + document.documentElement + ) { + document.documentElement.setAttribute('data-standalone', 'true'); + } bootstrapApp(); } diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index 6392979..a541a49 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -1029,6 +1029,11 @@ export async function saveSettingsPatch(patch) { if (Object.prototype.hasOwnProperty.call(safePatch, 'orchestratorIdMode')) { safePatch.orchestratorIdMode = normalizeClientOrchestratorIdMode(safePatch.orchestratorIdMode); } + if (Object.prototype.hasOwnProperty.call(safePatch, 'standalonePort')) { + const numPort = Number(safePatch.standalonePort); + safePatch.standalonePort = + Number.isInteger(numPort) && numPort >= 1024 && numPort <= 65535 ? numPort : 0; + } if (Object.prototype.hasOwnProperty.call(safePatch, 'windowMountMode')) { const normMount = normalizeClientWindowMountMode( safePatch.windowMountMode, diff --git a/sidecars/panel/src/styles/base.css b/sidecars/panel/src/styles/base.css index e0a7bdb..565115f 100644 --- a/sidecars/panel/src/styles/base.css +++ b/sidecars/panel/src/styles/base.css @@ -62,6 +62,19 @@ input { position: relative; } +html[data-standalone="true"] .app-shell { + max-width: 960px; + margin: 0 auto; +} + +@media (min-width: 980px) { + html[data-standalone="true"] .app-shell { + padding: var(--space-4) var(--space-5); + border-left: 1px solid var(--border-hairline); + border-right: 1px solid var(--border-hairline); + } +} + .top-deck { display: flex; flex-direction: column; diff --git a/sidecars/panel/src/styles/tokens.css b/sidecars/panel/src/styles/tokens.css index 22383c8..c8ab516 100644 --- a/sidecars/panel/src/styles/tokens.css +++ b/sidecars/panel/src/styles/tokens.css @@ -119,3 +119,15 @@ --space-4: 10px; --space-5: 12px; } + +@media (prefers-color-scheme: dark) { + html[data-standalone="true"] { + color-scheme: dark; + --background: hsl(222 18% 10%); + --card: hsl(222 16% 13%); + --border: hsl(220 14% 21%); + --foreground: hsl(214 24% 92%); + --muted-foreground: hsl(215 14% 63%); + --primary: hsl(217 86% 61%); + } +} diff --git a/sidecars/panel/standalone.mjs b/sidecars/panel/standalone.mjs new file mode 100644 index 0000000..f5cb23a --- /dev/null +++ b/sidecars/panel/standalone.mjs @@ -0,0 +1,123 @@ +#!/usr/bin/env node +/** + * @fileoverview Antigravity Usage Monitor 独立 Web 监控 CLI 入口 (`standalone.mjs`)。 + * + * 在无头服务器 (`agy` / `agy remote-control serve`) 或纯终端环境下,脱离 `sidecar_sdk` + * 直接拉起完整的四分页监控面板与 API 服务: + * - `node sidecars/panel/standalone.mjs --port 8787`(配合 `ssh -L 8787:127.0.0.1:8787` 零鉴权安全访问) + * - `node sidecars/panel/standalone.mjs --host 0.0.0.0 --port 8787 --token `(带访问令牌保护) + */ + +import { resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +function applyPreImportEnvOverrides(argv) { + for (let i = 0; i < argv.length; i++) { + const raw = String(argv[i] || ''); + if (!raw) continue; + const eqIdx = raw.indexOf('='); + const flag = eqIdx > 0 ? raw.slice(0, eqIdx) : raw; + const readVal = () => { + if (eqIdx > 0) return raw.slice(eqIdx + 1).trim(); + if (i + 1 < argv.length) { + i += 1; + return String(argv[i] || '').trim(); + } + return ''; + }; + if (flag === '--data-dir') { + const v = readVal(); + if (v) process.env.USAGE_MONITOR_DATA_DIR = v; + } else if (flag === '--app-data-dir') { + const v = readVal(); + if (v) process.env.USAGE_MONITOR_APP_DATA_DIR = v; + } else if (flag === '--gemini-dir') { + const v = readVal(); + if (v) process.env.ANTIGRAVITY_GEMINI_DIR = v; + } else if (flag === '--ls-addr') { + const v = readVal(); + if (v) process.env.ANTIGRAVITY_LS_ADDRESS = v; + } else if (flag === '--csrf-token') { + const v = readVal(); + if (v) process.env.ANTIGRAVITY_CSRF_TOKEN = v; + } + } +} + +export async function runStandaloneCli(argv = process.argv.slice(2)) { + applyPreImportEnvOverrides(argv); + + const { + createStandaloneWebServer, + formatStandaloneHelpText, + parseStandaloneCliArgs, + } = await import('./backend/standalone-server.mjs'); + const { DATA_DIR, lsRuntimeEndpoint } = await import('./backend/config.mjs'); + const { ensureLsEndpointDiscovered } = await import('./backend/ls-discovery.mjs'); + + let parsed; + try { + parsed = parseStandaloneCliArgs(argv, process.env, { defaultPort: 8787 }); + } catch (err) { + console.error(`[usage-monitor] ${err.message}`); + process.exitCode = 1; + return null; + } + + if (parsed.help) { + console.log(formatStandaloneHelpText()); + return null; + } + + let controller; + try { + controller = createStandaloneWebServer({ + host: parsed.host, + port: parsed.port, + token: parsed.token, + lsAddr: parsed.lsAddr, + csrfToken: parsed.csrfToken, + }); + const status = await controller.start(); + await ensureLsEndpointDiscovered({ force: false }).catch(() => false); + const lsDesc = lsRuntimeEndpoint.baseUrl + ? `connected (${lsRuntimeEndpoint.baseUrl})` + : 'offline fallback (reading local transcripts/cache; will auto-connect when agy starts)'; + const authDesc = status.tokenProtected + ? 'token required (--token)' + : 'loopback-only (use ssh -L for remote access)'; + console.log(`[usage-monitor] Standalone Web UI listening at ${status.url}`); + console.log(`[usage-monitor] Security mode: ${authDesc}`); + console.log(`[usage-monitor] Language Server: ${lsDesc}`); + console.log(`[usage-monitor] Data directory: ${DATA_DIR}`); + } catch (err) { + console.error(`[usage-monitor] Failed to start standalone server: ${err.message}`); + process.exitCode = 1; + return null; + } + + let closing = false; + const gracefulShutdown = async () => { + if (closing) return; + closing = true; + try { + await controller.stop(); + } finally { + process.exit(0); + } + }; + + process.on('SIGINT', () => { + void gracefulShutdown(); + }); + process.on('SIGTERM', () => { + void gracefulShutdown(); + }); + + return controller; +} + +const invokedPath = process.argv[1] ? resolve(process.argv[1]) : ''; +if (invokedPath && invokedPath === fileURLToPath(import.meta.url)) { + void runStandaloneCli(); +} diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index 11cbf6c..5891a4a 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -121,6 +121,18 @@ --space-5: 12px; } +@media (prefers-color-scheme: dark) { + html[data-standalone="true"] { + color-scheme: dark; + --background: hsl(222 18% 10%); + --card: hsl(222 16% 13%); + --border: hsl(220 14% 21%); + --foreground: hsl(214 24% 92%); + --muted-foreground: hsl(215 14% 63%); + --primary: hsl(217 86% 61%); + } +} + /* --- src/styles/base.css --- */ /* * Base reset, viewport-locked shell (preventing ultra-long px scroll pages), @@ -186,6 +198,19 @@ input { position: relative; } +html[data-standalone="true"] .app-shell { + max-width: 960px; + margin: 0 auto; +} + +@media (min-width: 980px) { + html[data-standalone="true"] .app-shell { + padding: var(--space-4) var(--space-5); + border-left: 1px solid var(--border-hairline); + border-right: 1px solid var(--border-hairline); + } +} + .top-deck { display: flex; flex-direction: column; diff --git a/sidecars/panel/test/backend-harness.mjs b/sidecars/panel/test/backend-harness.mjs index 9139b36..e88fff5 100644 --- a/sidecars/panel/test/backend-harness.mjs +++ b/sidecars/panel/test/backend-harness.mjs @@ -21,6 +21,7 @@ const BACKEND_MODULE_FILES = [ '../backend/account-switch.mjs', '../backend/settings-schema.mjs', '../backend/config.mjs', + '../backend/cli-sqlite-reader.mjs', '../backend/ls-discovery.mjs', '../backend/pricing-catalog.mjs', '../backend/plugin-updater.mjs', @@ -49,6 +50,7 @@ export function backendHarness({ cache={}, deepStats=null, transcripts={}, + diskDirs={}, settings={}, trajectories={}, summaries={}, @@ -69,7 +71,7 @@ export function backendHarness({ const mainUrl = pluginRootPath ? `file://${pluginRootPath}/sidecars/panel/main.mjs` : 'file:///test/sidecars/panel/main.mjs'; const mainPath = pluginRootPath ? `${pluginRootPath}/sidecars/panel/main.mjs` : '/test/sidecars/panel/main.mjs'; const source = stripEsmSyntax(sourceText ?? loadCombinedBackendSource(), mainUrl); - const state={calls:[],errors:[],saves:[],settings,trajectories,transcripts,transcriptMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,deepStats,deepStatsMtimeMs:1}; + const state={calls:[],errors:[],saves:[],settings,trajectories,summaries,transcripts,transcriptMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,deepStats,deepStatsMtimeMs:1}; const ctx={ ...metricsImplementation, URL, AbortSignal, Buffer, isDeepStrictEqual, randomUUID, ...(clock ? { Date: class extends Date { @@ -96,9 +98,15 @@ export function backendHarness({ return Boolean(m && state.transcripts?.[m[1]]); } if (norm.endsWith('/.git')) return Boolean(state.hasGitDir); + if (diskDirs && Object.prototype.hasOwnProperty.call(diskDirs, norm)) return true; return false; }, - mkdirSync:()=>{},readdirSync:()=>[], + mkdirSync:()=>{}, + readdirSync:p=>{ + const norm = String(p).replace(/\\/g, '/'); + if (diskDirs && Array.isArray(diskDirs[norm])) return diskDirs[norm]; + return []; + }, statSync:p=>{ const norm = String(p).replace(/\\/g, '/'); if (norm.endsWith('/.system_generated/logs/transcript.jsonl')) { @@ -160,10 +168,10 @@ export function backendHarness({ if(qs instanceof Error) throw qs; return {ok:true,json:async()=>({response:qs})}; } - const data={GetUserStatus:{userStatus:state.userStatus},GetAvailableModels:{response:{models:availableModels}},GetAllCascadeTrajectories:{trajectorySummaries:summaries}}[method]; + const data={GetUserStatus:{userStatus:state.userStatus},GetAvailableModels:{response:{models:availableModels}},GetAllCascadeTrajectories:{trajectorySummaries:state.summaries}}[method]; return {ok:true,json:async()=>data}; }, }; - vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,computeStepCost,resolveModelInfo,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns};',ctx); + vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,computeStepCost,resolveModelInfo,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle};',ctx); return {...ctx.api,state}; } diff --git a/sidecars/panel/test/backend.test.mjs b/sidecars/panel/test/backend.test.mjs index 1413d34..f8bfbd4 100644 --- a/sidecars/panel/test/backend.test.mjs +++ b/sidecars/panel/test/backend.test.mjs @@ -1,9 +1,17 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { existsSync, mkdtempSync, readFileSync, readdirSync, rmdirSync, unlinkSync, writeFileSync } from 'node:fs'; +import { execFileSync } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, rmdirSync, unlinkSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import {backendHarness} from './backend-harness.mjs'; +import { + getNodeSqliteDatabaseSync, + parseAnnotationPbtxtTitle, + readAnnotationTitleForCascade, + readLocalSqliteTrajectory, + readLocalSummaryIndex, +} from '../backend/cli-sqlite-reader.mjs'; import { writeTrajectoryCacheFile } from '../backend/trajectory-cache-file.mjs'; const raw={trajectory:{steps:[{status:'CORTEX_STEP_STATUS_DONE',metadata:{ @@ -1316,3 +1324,439 @@ test('reconciles 8-group context breakdown with real API prompt+output tokens an const fetchCountAfterSecond = h.state.calls.filter((c) => c.method === 'GetCascadeTrajectory').length; assert.equal(fetchCountAfterSecond, 1); }); + +test('antigravity-cli multi-dir transcript fallback recovers offline sessions and upgrades once LS comes online', async () => { + const cliId = '88888888-4444-4444-8888-111111111111'; + const h = backendHarness({ + summaries: {}, + trajectories: { + [cliId]: new Error('Language Server offline'), + }, + diskDirs: { + '/test-home/.gemini/antigravity-cli/brain': [cliId], + }, + deepStats: { + titleMap: {}, + perConvo: { + [`cli:${cliId}`]: { + appSource: 'cli', + entries: [ + { + ts: '2026-11-15T12:00:02Z', + model: 'claude-sonnet-4-6', + modelCanonicalId: 'claude-sonnet-4-6', + modelDisplayName: 'Claude Sonnet 4.6', + provider: 'API_PROVIDER_ANTHROPIC_VERTEX', + inp: 4000, + cache: 16000, + out: 300, + reasoning: 100, + }, + ], + }, + }, + }, + transcripts: { + [cliId]: [ + { + step_index: 1, + source: 'USER_EXPLICIT', + type: 'USER_INPUT', + status: 'DONE', + created_at: '2026-11-15T12:00:00Z', + content: '\n排查无头 Linux CLI 远程监控配置\n', + }, + { + step_index: 2, + source: 'MODEL', + type: 'PLANNER_RESPONSE', + status: 'DONE', + created_at: '2026-11-15T12:00:02Z', + input_tokens: 4000, + cache_read_tokens: 16000, + output_tokens: 400, + content: '已完成排查。', + }, + ], + }, + }); + + // 1. Offline mode: recovers CLI conversation list, prompt-derived title, turn rail, and token accounting + const offlinePayload = await h.buildTelemetryPayloadInternal(cliId); + assert.equal(offlinePayload.conversations.length, 1); + assert.equal(offlinePayload.conversations[0].cascadeId, cliId); + assert.equal(offlinePayload.conversations[0].title, '排查无头 Linux CLI 远程监控配置'); + assert.equal(offlinePayload.activeConversation.inputTokens, 4000); + assert.equal(offlinePayload.activeConversation.cacheReadTokens, 16000); + assert.equal(offlinePayload.activeConversation.outputTokens, 400); + const offlineStep = offlinePayload.activeConversation.recentSteps[0]; + assert.equal(offlineStep.turnIndex, 1); + assert.equal(offlineStep.turnPrompt, '排查无头 Linux CLI 远程监控配置'); + assert.equal(offlineStep.tokPerSec, null); + assert.equal(offlineStep.selectedSpeedReason, 'incomplete_or_invalid_timing'); + assert.equal( + offlinePayload.consumption.sourcesBreakdown.some( + (s) => s.name === 'Antigravity CLI' && s.totalTokens === 20400 + ), + true + ); + + // Steady offline poll does not hammer GetCascadeTrajectory + const callsAfterFirst = h.state.calls.filter((c) => c.method === 'GetCascadeTrajectory').length; + assert.equal(callsAfterFirst, 1); + await h.buildTelemetryPayloadInternal(cliId); + const callsAfterSecond = h.state.calls.filter((c) => c.method === 'GetCascadeTrajectory').length; + assert.equal(callsAfterSecond, 1); + + // 2. Language Server comes online: immediately upgrades offline fallback entry to full RPC telemetry + h.state.summaries = { + [cliId]: { + stepCount: 2, + lastModifiedTime: '2026-11-15T12:00:06Z', + status: 'IDLE', + annotations: { title: 'CLI 在线完整轨迹' }, + }, + }; + h.state.trajectories[cliId] = { + numTotalSteps: 2, + trajectory: { + steps: [ + { + type: 'CORTEX_STEP_TYPE_USER_INPUT', + userInput: { userResponse: '排查无头 Linux CLI 远程监控配置' }, + }, + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + plannerResponse: { response: '已完成排查。', thinkingTokens: 100, responseTokens: 300 }, + metadata: { + createdAt: '2026-11-15T12:00:02Z', + finishedGeneratingAt: '2026-11-15T12:00:06Z', + sourceTrajectoryStepInfo: { stepIndex: 1 }, + modelUsage: { + model: 'MODEL_CLAUDE_4_SONNET', + responseModel: 'claude-sonnet-4-6', + apiProvider: 'API_PROVIDER_ANTHROPIC_VERTEX', + inputTokens: 4000, + cacheReadTokens: 16000, + outputTokens: 400, + }, + }, + }, + ], + generatorMetadata: [ + { + stepIndices: [1], + chatModel: { + timeToFirstToken: '0.8s', + modelDisplayName: 'Claude Sonnet 4.6', + }, + }, + ], + }, + }; + + const onlinePayload = await h.buildTelemetryPayloadInternal(cliId); + const onlineStep = onlinePayload.activeConversation.recentSteps[0]; + assert.equal(onlinePayload.activeConversation.title, 'CLI 在线完整轨迹'); + assert.equal(onlineStep.tokPerSec, 100); + assert.equal(onlineStep.ttftSec, 0.8); +}); + +test('standalonePort setting normalizes valid ports and notifies auto-host listener on change and reset', () => { + const h = backendHarness(); + const observedPorts = []; + h.setStandalonePortListener((p) => observedPorts.push(p)); + + assert.equal(h.normalizeStandalonePort(0), 0); + assert.equal(h.normalizeStandalonePort(80), 0); + assert.equal(h.normalizeStandalonePort(70000), 0); + assert.equal(h.normalizeStandalonePort('8787'), 8787); + + const saved = h.executeSettingsAction({ standalonePort: 8787 }); + assert.equal(saved.ok, true); + assert.equal(saved.updated.standalonePort, 8787); + assert.deepEqual(observedPorts, [8787]); + + // Same port does not re-trigger listener + h.executeSettingsAction({ standalonePort: 8787 }); + assert.deepEqual(observedPorts, [8787]); + + // Reset returns standalonePort to 0 and notifies listener + const reset = h.executeResetSettingsAction(); + assert.equal(reset.ok, true); + assert.equal(reset.updated.standalonePort, 0); + assert.deepEqual(observedPorts, [8787, 0]); +}); + +function encodeProtoVarint(value) { + let v = BigInt(value); + const out = []; + while (v >= 0x80n) { + out.push(Number((v & 0x7fn) | 0x80n)); + v >>= 7n; + } + out.push(Number(v)); + return Buffer.from(out); +} + +function encodeProtoFieldVarint(fieldNo, value) { + return Buffer.concat([encodeProtoVarint((fieldNo << 3) | 0), encodeProtoVarint(value)]); +} + +function encodeProtoFieldBytes(fieldNo, payload) { + const buf = typeof payload === 'string' ? Buffer.from(payload, 'utf8') : payload; + return Buffer.concat([ + encodeProtoVarint((fieldNo << 3) | 2), + encodeProtoVarint(buf.length), + buf, + ]); +} + +test('Antigravity CLI annotations.pbtxt + SQLite trajectory reader recovers title, TPS, TTFT, thinking split, and 10-channel context', () => { + assert.equal( + parseAnnotationPbtxtTitle('last_user_view_time:{seconds:1794759792}\ntitle:"Greeting and Hello"\n'), + 'Greeting and Hello' + ); + assert.equal( + parseAnnotationPbtxtTitle('title: "用量图表与调用记录优化建议"'), + '用量图表与调用记录优化建议' + ); + // Octal UTF-8 byte escape for "你好" (\344\275\240\345\245\275) + escaped quote + assert.equal( + parseAnnotationPbtxtTitle('title:"\\344\\275\\240\\345\\245\\275 \\"CLI\\""'), + '你好 "CLI"' + ); + + const DatabaseSync = getNodeSqliteDatabaseSync(); + if (!DatabaseSync) return; + + const tempRoot = mkdtempSync(fileURLToPath(new URL('./.cli-sqlite-', import.meta.url))); + try { + const cliRoot = join(tempRoot, 'antigravity-cli'); + const convDir = join(cliRoot, 'conversations'); + const annDir = join(cliRoot, 'annotations'); + const cid = '278a0174-296c-45a9-bc6c-62ce7bdd82c4'; + const logDir = join(cliRoot, 'brain', cid, '.system_generated', 'logs'); + mkdirSync(convDir, { recursive: true }); + mkdirSync(annDir, { recursive: true }); + mkdirSync(logDir, { recursive: true }); + + writeFileSync( + join(annDir, `${cid}.pbtxt`), + 'last_user_view_time:{seconds:1794759792 nanos:730218300}\ntitle:"Greeting and Hello"\n', + 'utf8' + ); + assert.equal(readAnnotationTitleForCascade(cid, [annDir]), 'Greeting and Hello'); + + // Create conversation_summaries.db matching Antigravity CLI 1.5.9 schema + const sumDb = new DatabaseSync(join(cliRoot, 'conversation_summaries.db')); + sumDb.exec(` + CREATE TABLE conversation_summaries ( + conversation_id TEXT NOT NULL, + title TEXT, + status TEXT, + parent_conversation_id TEXT, + agent_name TEXT, + not_fully_idle INTEGER, + killed INTEGER, + step_count INTEGER, + last_modified_time TEXT, + app_data_dir TEXT + ); + `); + sumDb + .prepare( + `INSERT INTO conversation_summaries + (conversation_id, title, status, parent_conversation_id, agent_name, not_fully_idle, killed, step_count, last_modified_time, app_data_dir) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` + ) + .run( + cid, + 'Greeting and Hello', + 'CASCADE_RUN_STATUS_IDLE', + '', + '', + 0, + 0, + 2, + '2026-11-15 16:23:12.7302183+00:00', + 'antigravity-cli' + ); + sumDb.close(); + + const summaryMap = readLocalSummaryIndex([cliRoot]); + assert.equal(summaryMap.get(cid)?.title, 'Greeting and Hello'); + assert.equal(summaryMap.get(cid)?.status, 'CASCADE_RUN_STATUS_IDLE'); + + // Create conversations/.db with protobuf metadata matching Antigravity CLI 1.5.9 + const modelUsageBuf = Buffer.concat([ + encodeProtoFieldVarint(1, 1526), // MODEL_PLACEHOLDER_M526 + encodeProtoFieldVarint(2, 14569), // inputTokens + encodeProtoFieldVarint(3, 89), // outputTokens + encodeProtoFieldVarint(6, 24), // API_PROVIDER_GOOGLE_GEMINI + encodeProtoFieldVarint(9, 57), // thinkingOutputTokens + encodeProtoFieldVarint(10, 32), // responseOutputTokens + ]); + const stepMetaBuf = Buffer.concat([ + encodeProtoFieldBytes( + 1, + Buffer.concat([encodeProtoFieldVarint(1, 1794759788), encodeProtoFieldVarint(2, 899044700)]) + ), + encodeProtoFieldBytes( + 6, + Buffer.concat([encodeProtoFieldVarint(1, 1794759792), encodeProtoFieldVarint(2, 175393200)]) + ), + encodeProtoFieldBytes( + 7, + Buffer.concat([encodeProtoFieldVarint(1, 1794759792), encodeProtoFieldVarint(2, 730218300)]) + ), + encodeProtoFieldBytes(9, modelUsageBuf), + encodeProtoFieldBytes(20, encodeProtoFieldVarint(2, 1)), + ]); + + const encodeGroup = (name, typeInt, numTokens, children = []) => + Buffer.concat([ + encodeProtoFieldBytes(1, name), + encodeProtoFieldVarint(2, typeInt), + encodeProtoFieldVarint(4, numTokens), + ...children.map((c) => encodeProtoFieldBytes(5, c)), + ]); + const tokenBreakdownBuf = Buffer.concat([ + encodeProtoFieldBytes(1, encodeGroup('System Prompt', 1, 6244)), + encodeProtoFieldBytes(1, encodeGroup('Mcp Tools', 4, 234)), + encodeProtoFieldBytes(1, encodeGroup('Subagents', 6, 689)), + encodeProtoFieldBytes(1, encodeGroup('Skills', 5, 4102)), + encodeProtoFieldBytes(1, encodeGroup('Rules', 3, 2282)), + encodeProtoFieldBytes(1, encodeGroup('Tools', 2, 6972)), + encodeProtoFieldBytes( + 1, + encodeGroup('Chat Messages', 7, 149, [encodeGroup('0: USER_INPUT', 0, 149)]) + ), + ]); + const contextWindowBuf = Buffer.concat([ + encodeProtoFieldVarint(1, 20672), + encodeProtoFieldBytes(3, tokenBreakdownBuf), + encodeProtoFieldVarint(4, 256000), + ]); + const chatModelBuf = Buffer.concat([ + encodeProtoFieldBytes(1, 'x'.repeat(8192)), // large prompt skipped in O(1) + encodeProtoFieldVarint(3, 1526), + encodeProtoFieldBytes(4, modelUsageBuf), + encodeProtoFieldBytes(9, encodeProtoFieldBytes(10, contextWindowBuf)), + encodeProtoFieldBytes( + 11, + Buffer.concat([encodeProtoFieldVarint(1, 3), encodeProtoFieldVarint(2, 276645700)]) + ), + encodeProtoFieldBytes(12, encodeProtoFieldVarint(2, 555832700)), + encodeProtoFieldBytes(19, 'gemini-4-hydrogen'), + encodeProtoFieldBytes( + 20, + Buffer.concat([ + encodeProtoFieldBytes(1, 'model_enum'), + encodeProtoFieldBytes(2, 'MODEL_PLACEHOLDER_M526'), + ]) + ), + encodeProtoFieldBytes(21, 'Gemini 4 Hydrogen (Medium)'), + ]); + const genMetaBuf = Buffer.concat([ + encodeProtoFieldBytes(2, Buffer.from([1])), + encodeProtoFieldBytes(1, chatModelBuf), + ]); + + const convDbPath = join(convDir, `${cid}.db`); + const convDb = new DatabaseSync(convDbPath); + convDb.exec(` + CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, metadata BLOB, step_payload BLOB); + CREATE TABLE gen_metadata (idx INTEGER PRIMARY KEY, data BLOB); + `); + convDb.prepare('INSERT INTO steps (idx, step_type, status, metadata) VALUES (?, ?, ?, ?)').run(0, 14, 3, null); + convDb.prepare('INSERT INTO steps (idx, step_type, status, metadata) VALUES (?, ?, ?, ?)').run(1, 15, 3, stepMetaBuf); + convDb.prepare('INSERT INTO gen_metadata (idx, data) VALUES (?, ?)').run(0, genMetaBuf); + convDb.close(); + + writeFileSync( + join(logDir, 'transcript.jsonl'), + [ + JSON.stringify({ + step_index: 0, + type: 'USER_INPUT', + status: 'DONE', + created_at: '2026-11-15T16:23:08Z', + content: '\n你好\n', + }), + JSON.stringify({ + step_index: 1, + type: 'PLANNER_RESPONSE', + status: 'DONE', + created_at: '2026-11-15T16:23:08Z', + model: 'gemini-4-hydrogen-medium', + input_tokens: 14569, + cache_read_tokens: 0, + output_tokens: 89, + content: '你好呀!今天有什么我可以帮你的吗?', + }), + ].join('\n'), + 'utf8' + ); + + const decoded = readLocalSqliteTrajectory(convDbPath); + assert.ok(decoded); + assert.equal(decoded.steps.length, 2); + assert.equal(decoded.generatorMetadata.length, 1); + assert.equal(decoded.generatorMetadata[0].chatModel.modelDisplayName, 'Gemini 4 Hydrogen (Medium)'); + + // End-to-end verification in isolated child process with ANTIGRAVITY_GEMINI_DIR + const builderUrl = new URL('../backend/telemetry-builder.mjs', import.meta.url).href; + const rawOut = execFileSync( + process.execPath, + [ + '--input-type=module', + '-e', + `const { buildTelemetryPayload } = await import(${JSON.stringify(builderUrl)}); + const p = await buildTelemetryPayload(${JSON.stringify(cid)}, false, { range: 'all' }); + process.stdout.write(JSON.stringify({ + title: p.activeConversation?.title, + modelLabel: p.activeConversation?.activeModelLabel, + tokPerSec: p.activeConversation?.latestTokPerSec, + ttftSec: p.activeConversation?.latestTtftSec, + step: p.activeConversation?.recentSteps?.[0], + ctx: p.activeConversation?.context, + sources: p.consumption?.sourcesBreakdown, + }));`, + ], + { + env: { + ...process.env, + ANTIGRAVITY_GEMINI_DIR: tempRoot, + USAGE_MONITOR_DATA_DIR: join(tempRoot, 'data'), + ANTIGRAVITY_LS_ADDRESS: 'test.invalid', + ANTIGRAVITY_CSRF_TOKEN: 'test', + }, + encoding: 'utf8', + } + ); + const parsed = JSON.parse(rawOut); + assert.equal(parsed.title, 'Greeting and Hello'); + assert.equal(parsed.modelLabel, 'Gemini 4 Hydrogen (Medium)'); + assert.equal(parsed.tokPerSec, 23.2); + assert.ok(Math.abs(parsed.ttftSec - 3.2766) < 0.01); + assert.equal(parsed.step.thinkingTokens, 57); + assert.equal(parsed.step.responseTokens, 32); + assert.equal(parsed.step.turnPrompt, '你好'); + assert.equal(parsed.step.estimatedContextTokens, 20672); + assert.equal(parsed.step.contextBreakdown.mcpToolsTokens, 234); + assert.equal(parsed.step.contextBreakdown.skillsTokens, 4102); + assert.equal(parsed.step.contextBreakdown.userRulesTokens, 2282); + assert.equal(parsed.step.contextBreakdown.systemToolsTokens, 6972); + assert.equal(parsed.step.contextBreakdown.userInputTokens, 149); + assert.equal(parsed.ctx.totalTokens, 14658); + assert.equal(parsed.ctx.limitTokens, 256000); + const cliSource = parsed.sources?.find((s) => s.name === 'Antigravity CLI'); + assert.ok(cliSource); + assert.equal(cliSource.calls, 1); + assert.equal(cliSource.totalTokens, 14658); + } finally { + rmSync(tempRoot, { recursive: true, force: true }); + } +}); diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index 3a6ceb1..ffb6bc7 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -21,8 +21,15 @@ import { } from '../backend/window-bridge.mjs'; import { discoverAntigravityLsEndpoint, + parseLinuxProcNetTcpPorts, parseLsArgsFromCommandLine, + parseSsListeningPorts, } from '../backend/ls-discovery.mjs'; +import { + createStandaloneWebServer, + isLoopbackBindHost, + parseStandaloneCliArgs, +} from '../backend/standalone-server.mjs'; import { handleMcpJsonRpcMessage } from '../mcp-entry.mjs'; import { computeCapsuleLayoutMode } from '../src/components/layout/WindowOverlayShell.js'; import { @@ -4808,3 +4815,274 @@ test('Step table semantic tone classes (speed/cache/ttft/cost) and domain-aligne 'Capsule step cost $0.198 matches tone-warn' ); }); + +test('Headless CLI LS discovery reads daemon/hub_*.json without subprocesses and falls back to Linux /proc + ss without lsof', async () => { + // 1. CLI command line parsing covers agy remote-control serve & antigravity-cli + const rcParsed = parseLsArgsFromCommandLine( + '/home/ubuntu/.local/bin/agy remote-control serve --http-port=43120 --csrf-token rc-token-99' + ); + assert.equal(rcParsed.isHub, true); + assert.equal(rcParsed.hubPort, 43120); + assert.equal(rcParsed.csrfToken, 'rc-token-99'); + + const cliBinParsed = parseLsArgsFromCommandLine( + '/usr/local/bin/antigravity-cli --hub --hub-port 51200 --csrf_token=cli-tok' + ); + assert.equal(cliBinParsed.isHub, true); + assert.equal(cliBinParsed.hubPort, 51200); + assert.equal(cliBinParsed.csrfToken, 'cli-tok'); + + // 2. Stage 1: daemon/hub_*.json zero-subprocess discovery skips dead PIDs and prefers plain HTTP port + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ag-um-daemon-test-')); + try { + fs.writeFileSync( + path.join(tmpDir, 'hub_dead.json'), + JSON.stringify({ + pid: 99991, + httpPort: 19001, + httpsPort: 19000, + csrfToken: 'dead-token', + }), + 'utf8' + ); + fs.writeFileSync( + path.join(tmpDir, 'hub_13019.json'), + JSON.stringify({ + pid: 42424, + httpPort: 13019, + httpsPort: 13018, + lsVersion: '2.32.1', + csrfToken: 'live-hub-token', + }), + 'utf8' + ); + + let subprocessCalled = false; + const probedUrls = []; + const foundViaDaemon = await discoverAntigravityLsEndpoint({ + platform: 'linux', + daemonDirs: [tmpDir], + isPidAliveFn: (pid) => pid === 42424, + execCmdFn: async () => { + subprocessCalled = true; + return ''; + }, + fetchFn: async (url, init) => { + probedUrls.push({ url, token: init?.headers?.['x-codeium-csrf-token'] }); + return { ok: url.startsWith('http://127.0.0.1:13019/') }; + }, + }); + + assert.equal(subprocessCalled, false, 'daemon/hub_*.json hits without spawning ps/ss/lsof'); + assert.equal(probedUrls.length, 1, 'Dead PID hub_dead.json skipped; httpPort probed first'); + assert.equal(foundViaDaemon?.addr, '127.0.0.1:13019'); + assert.equal(foundViaDaemon?.baseUrl, 'http://127.0.0.1:13019'); + assert.equal(foundViaDaemon?.csrfToken, 'live-hub-token'); + assert.equal(foundViaDaemon?.pid, 42424); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + + // 3. Linux /proc//fd + /proc/net/tcp parser (0xA4D3 = 42195, state 0A = LISTEN) + const tcpSample = [ + ' sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode', + ' 0: 0100007F:A4D3 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 554433 1 0 100 0', + ' 1: 0100007F:1F90 0100007F:C350 01 00000000:00000000 00:00000000 00000000 1000 0 554434 1 0 100 0', + ].join('\n'); + assert.deepEqual(parseLinuxProcNetTcpPorts(tcpSample, new Set(['554433', '554434'])), [42195]); + + const foundViaProcFs = await discoverAntigravityLsEndpoint({ + platform: 'linux', + daemonDirs: [], + procFs: { + existsSync: (p) => p === '/proc/7788/fd' || p === '/proc/7788/net/tcp', + readdirSync: (p) => (p === '/proc/7788/fd' ? ['3', '4'] : []), + readlinkSync: (p) => (p === '/proc/7788/fd/4' ? 'socket:[554433]' : '/dev/null'), + readFileSync: () => tcpSample, + }, + execCmdFn: async (cmd) => { + if (cmd === 'ps') { + return '7788 1 /opt/agy/language_server_linux_x64 --csrf_token proc-tok-1\n'; + } + throw new Error(`Unexpected command ${cmd}`); + }, + fetchFn: async (url, init) => ({ + ok: + url.startsWith('http://127.0.0.1:42195/') && + init?.headers?.['x-codeium-csrf-token'] === 'proc-tok-1', + }), + }); + assert.equal(foundViaProcFs?.addr, '127.0.0.1:42195'); + assert.equal(foundViaProcFs?.csrfToken, 'proc-tok-1'); + + // 4. Linux ss -H -lntp fallback when /proc net is restricted and lsof is not installed + const ssSample = + 'LISTEN 0 4096 127.0.0.1:38899 0.0.0.0:* users:(("language_server",pid=8899,fd=7))\n'; + assert.deepEqual(parseSsListeningPorts(ssSample, 8899), [38899]); +}); + +test('Standalone Web server enforces loopback/non-loopback security boundaries, serves full assets, and supports token cookie/Bearer auth', async () => { + // 1. CLI arg & host boundary validation + assert.equal(isLoopbackBindHost('127.0.0.1'), true); + assert.equal(isLoopbackBindHost('localhost'), true); + assert.equal(isLoopbackBindHost('::1'), true); + assert.equal(isLoopbackBindHost('[::1]'), true); + assert.equal(isLoopbackBindHost('0.0.0.0'), false); + assert.equal(isLoopbackBindHost('192.168.1.25'), false); + + const parsedArgs = parseStandaloneCliArgs( + ['--port', '9090', '--host=0.0.0.0', '--token', 's3cr3t'], + {} + ); + assert.equal(parsedArgs.port, 9090); + assert.equal(parsedArgs.host, '0.0.0.0'); + assert.equal(parsedArgs.token, 's3cr3t'); + + // Refuse non-loopback bind without --token + assert.throws( + () => createStandaloneWebServer({ host: '0.0.0.0', port: 0, skipStartupDiscovery: true }), + /Refusing to bind standalone server to non-loopback host "0\.0\.0\.0" without --token/ + ); + + // 2. Default 127.0.0.1 loopback server (ssh -L friendly, blocks cross-site & DNS rebinding) + const loopSrv = createStandaloneWebServer({ + host: '127.0.0.1', + port: 0, + skipStartupDiscovery: true, + readAssetFn: async (rel) => `ASSET:${rel}`, + handleApiRequest: async (pathname, method, data) => ({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ ok: true, pathname, method, data }), + }), + }); + + try { + const st = await loopSrv.start(); + assert.equal(st.running, true); + assert.ok(st.port > 0); + assert.equal(st.loopbackOnly, true); + assert.equal(st.tokenProtected, false); + + const indexRes = await fetch(`${st.url}/`); + assert.equal(indexRes.status, 200); + assert.equal(await indexRes.text(), 'ASSET:index.html'); + + const preloadRes = await fetch(`${st.url}/preload.js`); + assert.equal(preloadRes.status, 200); + assert.match(await preloadRes.text(), /standalone web mode/); + + const apiRes = await fetch(`${st.url}/api/telemetry?range=today`); + assert.equal(apiRes.status, 200); + const apiJson = await apiRes.json(); + assert.deepEqual(apiJson, { + ok: true, + pathname: '/api/telemetry', + method: 'GET', + data: { range: 'today' }, + }); + + // Cross-site Origin blocked with 403 + const crossSiteRes = await fetch(`${st.url}/api/telemetry`, { + headers: { Origin: 'https://evil.example' }, + }); + assert.equal(crossSiteRes.status, 403); + + // DNS rebinding Host header blocked with 403 + const rebindStatus = await new Promise((resolve, reject) => { + const req = http.request( + { + hostname: '127.0.0.1', + port: st.port, + path: '/api/telemetry', + method: 'GET', + headers: { Host: `attacker.rebind.test:${st.port}` }, + }, + (res) => { + res.resume(); + resolve(res.statusCode); + } + ); + req.on('error', reject); + req.end(); + }); + assert.equal(rebindStatus, 403); + } finally { + await loopSrv.stop(); + } + + // 3. Token-protected mode (--token): 401 prompt, ?token= 302 -> HttpOnly cookie, Bearer header, and cross-origin POST block + const tokenSrv = createStandaloneWebServer({ + host: '127.0.0.1', + port: 0, + token: 'cli-remote-secret', + skipStartupDiscovery: true, + readAssetFn: async (rel) => `PROTECTED:${rel}`, + handleApiRequest: async (pathname, method, data) => ({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ ok: true, pathname, method, data }), + }), + }); + + try { + const st = await tokenSrv.start(); + assert.equal(st.tokenProtected, true); + + // Unauthenticated browser GET / -> 401 HTML login form + const unauthPage = await fetch(`${st.url}/`); + assert.equal(unauthPage.status, 401); + assert.match(await unauthPage.text(), /standalone-auth/); + + // Unauthenticated API -> 401 JSON + const unauthApi = await fetch(`${st.url}/api/telemetry`); + assert.equal(unauthApi.status, 401); + + // Bearer header works directly + const bearerApi = await fetch(`${st.url}/api/telemetry?range=week`, { + headers: { Authorization: 'Bearer cli-remote-secret' }, + }); + assert.equal(bearerApi.status, 200); + + // Browser GET /?token=cli-remote-secret sets HttpOnly cookie and 302 redirects to clean / + const loginRedirect = await fetch(`${st.url}/?token=cli-remote-secret`, { + redirect: 'manual', + }); + assert.equal(loginRedirect.status, 302); + assert.equal(loginRedirect.headers.get('location'), '/'); + const setCookie = loginRedirect.headers.get('set-cookie') || ''; + assert.match(setCookie, /ag_um_token=[0-9a-f]{64}; HttpOnly; SameSite=Strict; Path=\//); + const cookiePair = setCookie.split(';')[0]; + + // Cookie authenticates same-origin GET and POST, but blocks cross-origin POST CSRF + const authedPage = await fetch(`${st.url}/`, { + headers: { Cookie: cookiePair }, + }); + assert.equal(authedPage.status, 200); + assert.equal(await authedPage.text(), 'PROTECTED:index.html'); + + const csrfPost = await fetch(`${st.url}/api/settings`, { + method: 'POST', + headers: { + Cookie: cookiePair, + Origin: 'https://evil.example', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ language: 'en-US' }), + }); + assert.equal(csrfPost.status, 403); + + const validPost = await fetch(`${st.url}/api/settings`, { + method: 'POST', + headers: { + Cookie: cookiePair, + Origin: st.url, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ language: 'en-US' }), + }); + assert.equal(validPost.status, 200); + } finally { + await tokenSrv.stop(); + } +});