From 352d6bdfef536456281c04b088f170663b163918 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Thu, 19 Nov 2026 01:45:08 +0900 Subject: [PATCH] fix(panel): harden cross-environment 2.33.0+ launcher coverage with zero-subprocess fast path and on-demand UAC - Add pure Node.js [MS-SHLLINK] raw-byte fast probe (`probeWindowsShortcutsFast`) so steady-state startups and 15-minute background rechecks run in <20ms with zero subprocesses, zero COM calls, and zero recursive folder traversal into Desktop subdirectories or unrelated Start Menu vendor folders - Restrict Windows shortcut scanning to top-level Desktop / OneDrive Desktop / Taskbar / Startup `.lnk` files and `Programs\Antigravity*`, pre-filtering raw bytes before lazily instantiating `WScript.Shell` COM - Patch exact O(1) user-space `HKCU\Software\Classes` launch keys (`antigravity` protocol, `Applications\Antigravity.exe`, `AntigravitySourceFile`) via `.NET` `Registry.CurrentUser` with `--remote-debugging-port=0` placed before `-- "%1"`, resolve `%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe` explicitly, and tolerate inaccessible folders without aborting - Support All-Users read-only public shortcuts (`readOnlyPaths`) and elevated old host processes via user-consented `-Verb RunAs` on 1-click relaunch while preserving WMI `Win32_Process.Create` when already elevated and de-elevating via `Shell.Application` when the original host ran unelevated (preserving Explorer drag-and-drop) - Generalize Linux `.desktop` `Exec=` patching for `env` prefixes and `Antigravity-*.AppImage`, add pure `node:fs` `/proc` executable discovery, gate launcher checks behind leader lease acquisition, and differentiate macOS / read-only shortcut notices honestly in `BridgeStatusNotice` --- sidecars/panel/app.js | 71 +- sidecars/panel/backend/api-actions.mjs | 5 +- .../panel/backend/desktop-launcher-config.mjs | 872 ++++++++++++++++-- sidecars/panel/backend/window-bridge.mjs | 60 +- sidecars/panel/index.html | 4 +- .../components/settings/BridgeStatusNotice.js | 51 +- sidecars/panel/src/i18n/en-US.js | 10 +- sidecars/panel/src/i18n/zh-CN.js | 10 +- sidecars/panel/test/window-bridge.test.mjs | 238 ++++- 9 files changed, 1140 insertions(+), 181 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 4d62a6d..1d94acd 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1463,14 +1463,20 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.str.mountSidebar': '仅侧边栏', 'settings.bridge.restartTitle': '已自动补齐启动参数,重启一次即可启用悬浮胶囊', 'settings.bridge.ctxRestartTitle': '已自动补齐启动参数,重启一次即可激活上下文覆写', - 'settings.bridge.restartBody': '已自动为桌面 / 开始菜单 / 任务栏快捷方式及自启项写入 --remote-debugging-port=0(后续每次正常打开均 100% 全自动挂载)。点击下方按钮即可退出托盘后台并立即生效。', + 'settings.bridge.restartBody': '已自动为快捷方式、自启项及协议关联写入 --remote-debugging-port=0(后续通过常规快捷方式打开均自动生效)。点击下方按钮即可退出后台进程并立即生效。', + 'settings.bridge.readOnlyTitle': '公共桌面快捷方式受权限保护,授权重启即可生效', + 'settings.bridge.ctxReadOnlyTitle': '公共桌面快捷方式受权限保护,授权重启即可激活上下文覆写', + 'settings.bridge.readOnlyBody': '个人启动项已配好,但公共桌面或开始菜单快捷方式需管理员权限修改。点击下方按钮并在系统弹窗中确认授权,即可一次性修补公共图标并带参重开(后续日常打开均自动生效)。', + 'settings.bridge.macTitle': '当前会话未开启调试端口,一键重开即可启用挂载', + 'settings.bridge.ctxMacTitle': '当前会话未开启调试端口,一键重开即可激活上下文覆写', 'settings.bridge.noPortTitle': '未检测到本地调试端口,主窗口挂载暂未生效', 'settings.bridge.unreachableTitle': '本地调试端口未就绪,主窗口挂载暂未生效', 'settings.bridge.ctxTitle': '未连通本地调试通道,上下文窗口覆写暂未注入', 'settings.bridge.guideWin': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可自动补齐快捷方式参数、退出托盘后台并带参重启生效。', - 'settings.bridge.guideMac': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可一键带参重开客户端生效,也可复制参数通过 open -a "Antigravity" --args --remote-debugging-port=0 启动。', + 'settings.bridge.guideMac': '受 macOS 应用签名限制,从 Dock 直接冷启动默认不带调试端口参数。点击下方按钮即可一键带参重开恢复(日常仅关窗不完全退出 Cmd+Q 则持续有效)。', 'settings.bridge.guideLinux': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可自动写入 .desktop 启动器并重启生效。', 'settings.bridge.relaunchBtn': '立即重启并启用挂载', + 'settings.bridge.relaunchAuthBtn': '授权修补并立即重启', 'settings.bridge.relaunchingBtn': '正在重启客户端...', 'settings.bridge.relaunchFailed': '自动重启失败,请从托盘退出后重试', 'settings.bridge.dismissAria': '暂时关闭提示', @@ -2093,14 +2099,20 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.str.mountSidebar': 'Sidebar Only', 'settings.bridge.restartTitle': 'Launch Flag Auto-Configured — Restart Once to Activate', 'settings.bridge.ctxRestartTitle': 'Launch Flag Auto-Configured — Restart Once for Context Override', - 'settings.bridge.restartBody': 'Automatically added --remote-debugging-port=0 to your shortcuts and startup entries (future launches mount 100% automatically). Click below to close tray processes and relaunch now.', + 'settings.bridge.restartBody': 'Automatically added --remote-debugging-port=0 to your shortcuts, startup entries, and protocol handlers (subsequent shortcut launches mount automatically). Click below to close background processes and relaunch now.', + 'settings.bridge.readOnlyTitle': 'Public Shortcut Protected — Authorize & Relaunch to Activate', + 'settings.bridge.ctxReadOnlyTitle': 'Public Shortcut Protected — Authorize & Relaunch for Context Override', + 'settings.bridge.readOnlyBody': 'Personal launch entries are configured, but public shortcuts require administrator permission. Click below and approve the system prompt to patch public shortcuts once and relaunch.', + 'settings.bridge.macTitle': 'Debug Port Inactive — One-Click Relaunch to Enable Mount', + 'settings.bridge.ctxMacTitle': 'Debug Port Inactive — One-Click Relaunch for Context Override', 'settings.bridge.noPortTitle': 'Local Debug Port Missing — Window Mount Inactive', 'settings.bridge.unreachableTitle': 'Local Debug Port Not Ready — Window Mount Inactive', 'settings.bridge.ctxTitle': 'Local Debug Port Inactive — Context Override Pending', 'settings.bridge.guideWin': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to auto-configure shortcuts, close tray background processes, and relaunch.', - 'settings.bridge.guideMac': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to relaunch with the flag in one click, or run open -a "Antigravity" --args --remote-debugging-port=0.', + 'settings.bridge.guideMac': 'Due to macOS app code signing, cold launches from Dock omit the debug port flag. Click below to relaunch with the flag in one click (stays active until you fully Quit via Cmd+Q).', 'settings.bridge.guideLinux': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to update your .desktop launcher and relaunch.', 'settings.bridge.relaunchBtn': 'Relaunch & Enable Mount', + 'settings.bridge.relaunchAuthBtn': 'Authorize & Relaunch', 'settings.bridge.relaunchingBtn': 'Relaunching Host...', 'settings.bridge.relaunchFailed': 'Auto-relaunch failed — quit from tray and retry', 'settings.bridge.dismissAria': 'Dismiss notice for now', @@ -14257,6 +14269,7 @@ const BridgeStatusNotice = defineComponent({ function syncActionButtons() { const canRelaunch = lastPayload.windowBridge?.canRelaunch !== false; + const needsAuth = Boolean(lastPayload.windowBridge?.hasReadOnlyShortcuts); patchAttr(relaunchBtnEl, 'hidden', !canRelaunch); patchAttr(relaunchBtnEl, 'disabled', relaunchState === 'relaunching'); patchText( @@ -14265,7 +14278,9 @@ const BridgeStatusNotice = defineComponent({ ? t('settings.bridge.relaunchingBtn') : relaunchState === 'failed' ? t('settings.bridge.relaunchFailed') - : t('settings.bridge.relaunchBtn') + : needsAuth + ? t('settings.bridge.relaunchAuthBtn') + : t('settings.bridge.relaunchBtn') ); patchSvgIcon(copyBtnIconEl, copied ? 'check' : 'copy'); @@ -14298,38 +14313,44 @@ const BridgeStatusNotice = defineComponent({ patchAttr(rootEl, 'hidden', !shouldShow); if (!shouldShow) return; + const plat = String(lastPayload.hostPlatform || '').trim().toLowerCase(); + const hasReadOnlyShortcuts = Boolean(wb?.hasReadOnlyShortcuts); + const isMacDesktop = plat === 'darwin' && !wb?.argvConfigured; const isAutoConfigured = Boolean( wb?.launcherConfigured || wb?.argvUpdatedThisBoot || wb?.argvConfigured ); + const useRestartTheme = !hasReadOnlyShortcuts && (isAutoConfigured || isMacDesktop); + patchClasses(rootEl, { - 'is-restart': isAutoConfigured, - 'is-warn': !isAutoConfigured, + 'is-restart': useRestartTheme, + 'is-warn': !useRestartTheme, }); - patchSvgIcon(headIconEl, isAutoConfigured ? 'refresh' : 'warning'); + patchSvgIcon(headIconEl, useRestartTheme ? 'refresh' : 'warning'); let titleText = ''; - if (isAutoConfigured) { + let bodyText = ''; + if (hasReadOnlyShortcuts) { + titleText = contextMode + ? t('settings.bridge.ctxReadOnlyTitle') + : t('settings.bridge.readOnlyTitle'); + bodyText = t('settings.bridge.readOnlyBody'); + } else if (isMacDesktop) { + titleText = contextMode + ? t('settings.bridge.ctxMacTitle') + : t('settings.bridge.macTitle'); + bodyText = t('settings.bridge.guideMac'); + } else if (isAutoConfigured) { titleText = contextMode ? t('settings.bridge.ctxRestartTitle') : t('settings.bridge.restartTitle'); - } else if (contextMode) { - titleText = t('settings.bridge.ctxTitle'); - } else if (state === 'cdp_unreachable') { - titleText = t('settings.bridge.unreachableTitle'); - } else { - titleText = t('settings.bridge.noPortTitle'); - } - - const plat = String(lastPayload.hostPlatform || '').trim().toLowerCase(); - let bodyText = ''; - if (isAutoConfigured) { bodyText = t('settings.bridge.restartBody'); - } else if (plat === 'darwin') { - bodyText = t('settings.bridge.guideMac'); - } else if (plat === 'linux') { - bodyText = t('settings.bridge.guideLinux'); } else { - bodyText = t('settings.bridge.guideWin'); + titleText = contextMode + ? t('settings.bridge.ctxTitle') + : state === 'cdp_unreachable' + ? t('settings.bridge.unreachableTitle') + : t('settings.bridge.noPortTitle'); + bodyText = plat === 'linux' ? t('settings.bridge.guideLinux') : t('settings.bridge.guideWin'); } patchText(titleEl, titleText); diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index 21150e6..5c40820 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -460,9 +460,12 @@ export async function executeAccountCredentialAction(data) { export async function executeBridgeRelaunchAction() { ensureIdeRemoteDebuggingArgv({ enabled: true }); - await ensureDesktopLaunchEntriesConfigured({ enabled: true }).catch(() => {}); + const launchConfig = await ensureDesktopLaunchEntriesConfigured({ enabled: true }).catch( + () => null + ); const result = await triggerDesktopHostRelaunch({ stalePortFiles: resolveDevToolsPortCandidates(), + readOnlyShortcutPaths: launchConfig?.readOnlyPaths || [], }); return { status: result.ok ? 200 : Number(result.status || 500), diff --git a/sidecars/panel/backend/desktop-launcher-config.mjs b/sidecars/panel/backend/desktop-launcher-config.mjs index 57b10a1..9041b10 100644 --- a/sidecars/panel/backend/desktop-launcher-config.mjs +++ b/sidecars/panel/backend/desktop-launcher-config.mjs @@ -5,22 +5,35 @@ * Antigravity Desktop (`Antigravity.exe` / `Antigravity.app` / `antigravity`) 自 `2.33.0` 起 * 默认不再于启动时开启 `--remote-debugging-port=0`,且独立 Electron 桌面端不读取 VS Code 系的 `argv.json`。 * - * 本模块在不触碰任何宿主二进制与 `app.asar` 的前提下,提供两层无感恢复能力: - * 1. 日常全自动层 (`ensureDesktopLaunchEntriesConfigured`): - * - Windows:自动为当前用户的桌面(含 OneDrive 重定向桌面)、开始菜单、任务栏固定图标、启动文件夹中的 - * `Antigravity.lnk` 快捷方式及已存在的 `HKCU\...\Run` 自启项补齐 `--remote-debugging-port=0`; - * - Linux:自动在 `~/.local/share/applications/antigravity.desktop`(必要时自系统目录复制)与 - * `~/.config/autostart/antigravity.desktop` 的 `Exec=` 中补齐 `--remote-debugging-port=0`; - * - 当用户切回「仅侧边栏」且无上下文窗口覆写时,可干净移除本插件托管的 `--remote-debugging-port=0`,绝不触碰用户自定义端口; + * 本模块在不触碰任何宿主二进制与 `app.asar` 的前提下,提供两层恢复闭环: + * 1. 日常全自动层 (`ensureDesktopLaunchEntriesConfigured`,后台零弹窗): + * - Windows:自动为个人桌面(含子文件夹及并存的 OneDrive 桌面)、开始菜单、任务栏固定图标、启动文件夹中的 + * `Antigravity.lnk`、`HKCU\...\Run` 自启项以及 `HKCU\Software\Classes` 下的 `antigravity://` 协议与文件关联 + * 补齐 `--remote-debugging-port=0`;若检测到 All-Users 公共桌面/开始菜单存在只读未修补快捷方式,如实上报 + * `readOnlyPaths` 供用户点击重启按钮时按需触发 UAC 一次性修补(不在桌面制造双份重影图标); + * - Linux:自动在 `~/.local/share/applications/antigravity.desktop` 与 `~/.config/autostart/antigravity.desktop` + * 的 `Exec=`(兼容 `env` 前缀与 `.AppImage`)中补齐 `--remote-debugging-port=0`; + * - 当用户切回「仅侧边栏」且无上下文窗口覆写时,干净剥离本插件托管的 `--remote-debugging-port=0`,保留用户自定义端口; * 2. 当下裸启动会话一键重拉层 (`triggerDesktopHostRelaunch`): - * - Windows 通过 `Shell.Application` (`explorer.exe` 进程外 COM) 脱离宿主 Job Object 托管生命周期, - * macOS / Linux 通过独立会话 `nohup` 脱离进程组,自动退出系统托盘常驻实例、清理陈旧 `DevToolsActivePort` - * 并以纯净桌面环境变量追加 `--remote-debugging-port=0` 重新拉起宿主客户端。 + * - Windows 自适应当前权限层级(已提权走 WMI `Win32_Process.Create` 保权脱离 Job Object;普通权限走 `Shell.Application` + * 并回退 WMI;若存在公共只读快捷方式或已提权的旧宿主进程驻留,则在用户点击重启后请求一次 `-Verb RunAs` UAC 授权完成修补与关闭, + * 随后按宿主原有权限层级重拉以避免破坏资源管理器文件拖拽); + * - macOS / Linux 通过独立后台会话关闭旧实例、清理陈旧 `DevToolsActivePort` 并追加 `--remote-debugging-port=0` 重开。 */ -import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'; +import { + existsSync, + mkdirSync, + readdirSync, + readFileSync, + renameSync, + readlinkSync, + statSync, + unlinkSync, + writeFileSync, +} from 'node:fs'; import { homedir } from 'node:os'; -import { basename, dirname, join } from 'node:path'; +import { basename, dirname, join, win32 as pathWin32 } from 'node:path'; import { DATA_DIR, lsRuntimeEndpoint } from './config.mjs'; export const REMOTE_DEBUG_LAUNCH_FLAG = '--remote-debugging-port=0'; @@ -28,6 +41,32 @@ export const REMOTE_DEBUG_LAUNCH_FLAG = '--remote-debugging-port=0'; const REMOTE_DEBUG_ANY_RE = /(?:^|\s)--remote-debugging-port(?:=|\s|$)/i; const REMOTE_DEBUG_MANAGED_ZERO_RE = /(?:^|\s+)--remote-debugging-port=(?:"0"|'0'|0)(?=\s|$)/gi; +/** + * 解析 Windows PowerShell 5.1 可执行文件绝对路径(防止用户精简系统或异常 `PATH` 丢失裸 `powershell.exe`)。 + * + * @param {Record} [env=process.env] + * @param {(p: string) => boolean} [existsFn=existsSync] + * @returns {string} + */ +export function resolveWindowsPowerShellExecutable(env = process.env, existsFn = existsSync) { + const sysRoot = String(env?.SystemRoot || env?.WINDIR || 'C:\\Windows').trim(); + if (sysRoot) { + const candidate = pathWin32.join( + sysRoot, + 'System32', + 'WindowsPowerShell', + 'v1.0', + 'powershell.exe' + ); + try { + if (existsFn(candidate)) return candidate; + } catch { + // 忽略文件系统探测异常,回退命令名 + } + } + return 'powershell.exe'; +} + /** * 在命令行参数字符串中幂等补齐或移除托管的 `--remote-debugging-port=0`,保留用户自定义的其它参数或自定义端口。 * @@ -108,7 +147,84 @@ export function patchWindowsRunRegistryCommand(rawValue, { enabled = true } = {} } /** - * 修补 Linux XDG `.desktop` 文件文本中的 `Exec=` 启动行(仅作用于 `antigravity` 桌面端,不修改 `antigravity-ide`)。 + * 解析并无损修补 Windows `HKCU\Software\Classes\...\shell\open\command` 协议与文件关联命令行。 + * 将 `--remote-debugging-port=0` 置于主程序路径之后、原有 `--` 或 `"%1"` 占位符之前,确保 Chromium 将其识别为开关而非文件路径。 + * + * @param {unknown} rawValue + * @param {{ enabled?: boolean }} [options] + * @returns {{ matched: boolean, changed: boolean, configured: boolean, value: string }} + */ +export function patchWindowsShellOpenCommand(rawValue, { enabled = true } = {}) { + const raw = String(rawValue ?? '').trim(); + if (!raw) { + return { matched: false, changed: false, configured: false, value: raw }; + } + const m = raw.match(/^\s*(?:"([^"]+)"|([^\s"]+))([\s\S]*)$/); + if (!m) { + return { matched: false, changed: false, configured: false, value: raw }; + } + const exePath = String(m[1] || m[2] || '').trim(); + const exeLeaf = exePath.split(/[\\/]/).pop() || ''; + if (exeLeaf.toLowerCase() !== 'antigravity.exe') { + return { matched: false, changed: false, configured: false, value: raw }; + } + const quotedExe = m[1] ? `"${exePath}"` : /\s/.test(exePath) ? `"${exePath}"` : exePath; + const rest = String(m[3] || '').trim(); + + if (enabled) { + if (REMOTE_DEBUG_ANY_RE.test(rest)) { + return { matched: true, changed: false, configured: true, value: raw }; + } + const nextValue = rest + ? `${quotedExe} ${REMOTE_DEBUG_LAUNCH_FLAG} ${rest}` + : `${quotedExe} ${REMOTE_DEBUG_LAUNCH_FLAG}`; + return { + matched: true, + changed: nextValue !== raw, + configured: true, + value: nextValue, + }; + } + + const stripped = ensureRemoteDebugFlagInArgs(rest, { enabled: false }); + const nextValue = stripped.args ? `${quotedExe} ${stripped.args}` : quotedExe; + return { + matched: true, + changed: nextValue !== raw, + configured: stripped.configured, + value: nextValue, + }; +} + +function isLinuxAntigravityDesktopLeaf(leaf) { + const lower = String(leaf || '').trim().toLowerCase(); + if (!lower || lower.includes('ide')) return false; + return /^antigravity(?:$|[-_.\d]|(?:\.appimage$))/i.test(lower); +} + +function splitLinuxExecTokens(cmdBody) { + const tokens = []; + const re = /(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s"']+)+/g; + let m; + while ((m = re.exec(cmdBody)) !== null) { + tokens.push({ raw: m[0], start: m.index, end: m.index + m[0].length }); + } + return tokens; +} + +function stripOuterQuotes(tok) { + if ( + (tok.startsWith('"') && tok.endsWith('"')) || + (tok.startsWith("'") && tok.endsWith("'")) + ) { + return tok.slice(1, -1); + } + return tok; +} + +/** + * 修补 Linux XDG `.desktop` 文件文本中的 `Exec=` 启动行。 + * 兼容 `Exec=env VAR=1 ...` 前缀与 `Antigravity-*.AppImage` 可执行文件,严格排除 `antigravity-ide`。 * * @param {string} rawText * @param {{ enabled?: boolean }} [options] @@ -129,20 +245,33 @@ export function patchLinuxDesktopEntryText(rawText, { enabled = true } = {}) { if (!execMatch) return line; const prefix = execMatch[1]; const cmdBody = execMatch[2].trim(); - const binMatch = cmdBody.match(/^(?:"([^"]+)"|'([^']+)'|([^\s"']+))([\s\S]*)$/); - if (!binMatch) return line; - const rawBin = String(binMatch[1] || binMatch[2] || binMatch[3] || ''); - const leaf = (rawBin.split('/').pop() || '').toLowerCase(); - if (leaf !== 'antigravity') { + const tokens = splitLinuxExecTokens(cmdBody); + if (!tokens.length) return line; + + let binIdx = 0; + const firstLeaf = (stripOuterQuotes(tokens[0].raw).split('/').pop() || '').toLowerCase(); + if (firstLeaf === 'env') { + binIdx = 1; + while (binIdx < tokens.length) { + const unquoted = stripOuterQuotes(tokens[binIdx].raw); + if (unquoted === '-S' || /^[A-Za-z_][A-Za-z0-9_]*=/.test(unquoted)) { + binIdx += 1; + continue; + } + break; + } + } + if (binIdx >= tokens.length) return line; + + const exeTok = tokens[binIdx]; + const exeLeaf = stripOuterQuotes(exeTok.raw).split('/').pop() || ''; + if (!isLinuxAntigravityDesktopLeaf(exeLeaf)) { return line; } + matched = true; - const binToken = binMatch[1] - ? `"${binMatch[1]}"` - : binMatch[2] - ? `'${binMatch[2]}'` - : binMatch[3]; - const rest = String(binMatch[4] || '').trim(); + const headThroughExe = cmdBody.slice(0, exeTok.end).trim(); + const rest = cmdBody.slice(exeTok.end).trim(); if (enabled) { if (REMOTE_DEBUG_ANY_RE.test(rest)) { @@ -158,18 +287,18 @@ export function patchLinuxDesktopEntryText(rawText, { enabled = true } = {}) { const mid = beforeCodes ? `${beforeCodes} ${REMOTE_DEBUG_LAUNCH_FLAG}` : REMOTE_DEBUG_LAUNCH_FLAG; - return `${prefix}${binToken} ${mid} ${codes}`; + return `${prefix}${headThroughExe} ${mid} ${codes}`; } return rest - ? `${prefix}${binToken} ${rest} ${REMOTE_DEBUG_LAUNCH_FLAG}` - : `${prefix}${binToken} ${REMOTE_DEBUG_LAUNCH_FLAG}`; + ? `${prefix}${headThroughExe} ${rest} ${REMOTE_DEBUG_LAUNCH_FLAG}` + : `${prefix}${headThroughExe} ${REMOTE_DEBUG_LAUNCH_FLAG}`; } const stripped = ensureRemoteDebugFlagInArgs(rest, { enabled: false }); configured = configured || stripped.configured; if (!stripped.changed) return line; changed = true; - return stripped.args ? `${prefix}${binToken} ${stripped.args}` : `${prefix}${binToken}`; + return stripped.args ? `${prefix}${headThroughExe} ${stripped.args}` : `${prefix}${headThroughExe}`; }); return { @@ -203,7 +332,7 @@ export function buildSanitizedDesktopRelaunchEnv(baseEnv = process.env) { } /** - * 自动定位本机 Antigravity Desktop(或 IDE)主程序路径(优先从 `ANTIGRAVITY_AGENTAPI_EXE` 向上反推,回退标准安装目录)。 + * 自动定位本机 Antigravity Desktop(或 IDE)主程序路径(优先从 `USAGE_MONITOR_HOST_EXE` / `APPIMAGE` / `ANTIGRAVITY_AGENTAPI_EXE` 反推,回退标准安装目录)。 * * @param {{ * env?: Record, @@ -227,6 +356,16 @@ export function resolveDesktopHostExecutable({ } }; + if (platform === 'linux') { + const appImagePath = String(env?.APPIMAGE || '').trim(); + if (appImagePath && safeExists(appImagePath)) { + const leaf = basename(appImagePath); + if (isLinuxAntigravityDesktopLeaf(leaf)) { + return { found: true, kind: 'desktop', executablePath: appImagePath, appBundlePath: '' }; + } + } + } + const hintPaths = [ String(env?.USAGE_MONITOR_HOST_EXE || '').trim(), String(env?.ANTIGRAVITY_AGENTAPI_EXE || '').trim(), @@ -288,7 +427,7 @@ export function resolveDesktopHostExecutable({ } else if (platform === 'linux') { for (const binName of ['antigravity', 'Antigravity']) { const linuxExe = join(installRoot, binName); - if (safeExists(linuxExe)) { + if (safeExists(linuxExe) && !installRoot.startsWith('/tmp/.mount_')) { return { found: true, kind: 'desktop', executablePath: linuxExe, appBundlePath: '' }; } } @@ -357,7 +496,7 @@ async function runLauncherExecFile(file, args, options = {}) { args, { windowsHide: true, - timeout: options.timeoutMs || 8000, + timeout: options.timeoutMs || 9000, maxBuffer: 1024 * 1024, env: options.env || process.env, }, @@ -406,41 +545,237 @@ function writeTextFileAtomically(filePath, content, fsOps) { } } +/** + * 检查单个 Windows `.lnk` 二进制 Buffer 是否指向 `Antigravity.exe`(排除 `Antigravity IDE.exe`)及是否已包含调试端口参数。 + * 基于 `[MS-SHLLINK]` 原始字节扫描,纯内存耗时 `< 0.1ms`,无需拉起任何外部子进程或 COM 组件。 + * + * @param {Buffer} buf + * @returns {{ matched: boolean, hasDebugPort: boolean }} + */ +export function inspectWindowsLnkBuffer(buf) { + if (!Buffer.isBuffer(buf) || buf.length < 32 || buf.length > 65536) { + return { matched: false, hasDebugPort: false }; + } + const ascii = buf.toString('latin1').toLowerCase(); + const utf16 = buf.toString('utf16le').toLowerCase(); + const hasIde = ascii.includes('antigravity ide.exe') || utf16.includes('antigravity ide.exe'); + if (hasIde) { + return { matched: false, hasDebugPort: false }; + } + const hasDesktopExe = + ascii.includes('\\antigravity.exe') || + utf16.includes('\\antigravity.exe') || + ascii.includes('/antigravity.exe') || + utf16.includes('/antigravity.exe'); + if (!hasDesktopExe) { + return { matched: false, hasDebugPort: false }; + } + const hasDebugPort = + ascii.includes('--remote-debugging-port') || utf16.includes('--remote-debugging-port'); + return { matched: true, hasDebugPort }; +} + +/** + * 纯 Node.js 零子进程快速扫描当前机器上的 `Antigravity.exe` 快捷方式配置状态(耗时通常 `< 2ms`)。 + * 桌面与任务栏严格仅扫描顶层 `.lnk`(绝不进入用户项目文件夹或 `node_modules`),开始菜单仅检查顶层及 `Antigravity*` 一级子目录。 + * + * @param {{ + * env?: Record, + * homeDir?: string, + * fsOps?: { + * readdirFn?: typeof readdirSync, + * statFn?: typeof statSync, + * readFn?: typeof readFileSync, + * }|null, + * }} [options] + */ +export function probeWindowsShortcutsFast({ + env = process.env, + homeDir = homedir(), + fsOps = null, +} = {}) { + const readdirFn = fsOps?.readdirFn || readdirSync; + const statFn = fsOps?.statFn || statSync; + const readFn = fsOps?.readFn || readFileSync; + + const zhDesktop = '\u684C\u9762'; + const userProfile = String(env?.USERPROFILE || homeDir || '').trim(); + const appData = String(env?.APPDATA || (homeDir ? pathWin32.join(homeDir, 'AppData', 'Roaming') : '')).trim(); + const publicRoot = String(env?.PUBLIC || 'C:\\Users\\Public').trim(); + const programData = String(env?.ProgramData || 'C:\\ProgramData').trim(); + + const flatDirs = []; + if (userProfile) { + flatDirs.push(pathWin32.join(userProfile, 'Desktop'), pathWin32.join(userProfile, zhDesktop)); + } + for (const od of [env?.OneDrive, env?.OneDriveConsumer, env?.OneDriveCommercial]) { + const cleanOd = String(od || '').trim(); + if (cleanOd) { + flatDirs.push(pathWin32.join(cleanOd, 'Desktop'), pathWin32.join(cleanOd, zhDesktop)); + } + } + if (appData) { + flatDirs.push( + pathWin32.join(appData, 'Microsoft', 'Windows', 'Start Menu'), + pathWin32.join(appData, 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup'), + pathWin32.join(appData, 'Microsoft', 'Internet Explorer', 'Quick Launch', 'User Pinned', 'TaskBar') + ); + } + if (publicRoot) { + flatDirs.push(pathWin32.join(publicRoot, 'Desktop'), pathWin32.join(publicRoot, zhDesktop)); + } + + const programRoots = []; + if (appData) { + programRoots.push(pathWin32.join(appData, 'Microsoft', 'Windows', 'Start Menu', 'Programs')); + } + if (programData) { + programRoots.push(pathWin32.join(programData, 'Microsoft', 'Windows', 'Start Menu', 'Programs')); + } + + const seenDirs = new Set(); + const candidateLnks = []; + const seenLnks = new Set(); + + const collectTopLevelLnks = (dirPath, expandAntigravitySubdirs = false) => { + if (!dirPath) return; + const normDir = dirPath.toLowerCase(); + if (seenDirs.has(normDir)) return; + seenDirs.add(normDir); + let entries = []; + try { + entries = readdirFn(dirPath, { withFileTypes: true }); + } catch { + return; + } + for (const ent of entries) { + const name = String(ent?.name || ''); + if (!name) continue; + if (ent.isFile?.() && name.toLowerCase().endsWith('.lnk')) { + const full = pathWin32.join(dirPath, name); + const key = full.toLowerCase(); + if (!seenLnks.has(key)) { + seenLnks.add(key); + candidateLnks.push(full); + } + } else if ( + expandAntigravitySubdirs && + ent.isDirectory?.() && + name.toLowerCase().startsWith('antigravity') + ) { + collectTopLevelLnks(pathWin32.join(dirPath, name), false); + } + } + }; + + for (const d of flatDirs) collectTopLevelLnks(d, false); + for (const p of programRoots) collectTopLevelLnks(p, true); + + const matchedPaths = []; + const configuredPaths = []; + const unconfiguredPaths = []; + + for (const lnkPath of candidateLnks) { + try { + const st = statFn(lnkPath); + if (!st || st.size < 32 || st.size > 65536) continue; + const buf = readFn(lnkPath); + const res = inspectWindowsLnkBuffer(buf); + if (!res.matched) continue; + matchedPaths.push(lnkPath); + if (res.hasDebugPort) { + configuredPaths.push(lnkPath); + } else { + unconfiguredPaths.push(lnkPath); + } + } catch { + // 忽略单个无权限或损坏的快捷方式文件 + } + } + + return { + matchedPaths, + configuredPaths, + unconfiguredPaths, + allConfigured: matchedPaths.length > 0 && unconfiguredPaths.length === 0, + }; +} + const WIN_SHORTCUT_PROVISION_PS = ` -$ErrorActionPreference = 'Stop' +[Console]::OutputEncoding = [System.Text.Encoding]::UTF8 +$ErrorActionPreference = 'SilentlyContinue' $enableFlag = $env:AGY_LAUNCH_ENABLED -eq '1' $updated = New-Object System.Collections.Generic.List[string] $configured = New-Object System.Collections.Generic.List[string] -$ws = New-Object -ComObject WScript.Shell +$readOnly = New-Object System.Collections.Generic.List[string] +$ws = $null $userProgramsDir = [Environment]::GetFolderPath('Programs') +$zhDesktop = ([string][char]0x684C + [string][char]0x9762) -$scanSpecs = @( - @{ Dir = [Environment]::GetFolderPath('Desktop'); Recurse = $false; IsCommon = $false }, - @{ Dir = $userProgramsDir; Recurse = $true; IsCommon = $false }, - @{ Dir = [Environment]::GetFolderPath('StartMenu'); Recurse = $false; IsCommon = $false }, - @{ Dir = [Environment]::GetFolderPath('Startup'); Recurse = $false; IsCommon = $false }, - @{ Dir = (Join-Path $env:APPDATA 'Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar'); Recurse = $false; IsCommon = $false }, - @{ Dir = [Environment]::GetFolderPath('CommonDesktopDirectory'); Recurse = $false; IsCommon = $true }, - @{ Dir = [Environment]::GetFolderPath('CommonPrograms'); Recurse = $true; IsCommon = $true } -) +$flatSpecs = New-Object System.Collections.Generic.List[object] +$seenScanDir = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase) + +function Add-ScanDir([string]$dirPath, [bool]$isCommon, [string]$kind, [bool]$expandVendorSubdir) { + if (-not $dirPath) { return } + if (-not $seenScanDir.Add($dirPath)) { return } + $exists = $false + try { $exists = [bool](Test-Path -LiteralPath $dirPath -ErrorAction SilentlyContinue) } catch { $exists = $false } + if (-not $exists) { return } + $flatSpecs.Add(@{ Dir = $dirPath; IsCommon = $isCommon; Kind = $kind }) + if ($expandVendorSubdir) { + try { + foreach ($sub in @(Get-ChildItem -LiteralPath $dirPath -Directory -Filter 'Antigravity*' -ErrorAction SilentlyContinue)) { + if ($sub -and $sub.FullName -and $seenScanDir.Add([string]$sub.FullName)) { + $flatSpecs.Add(@{ Dir = [string]$sub.FullName; IsCommon = $isCommon; Kind = $kind }) + } + } + } catch {} + } +} + +foreach ($d in @( + [Environment]::GetFolderPath('Desktop'), + $(if ($env:USERPROFILE) { Join-Path $env:USERPROFILE 'Desktop' } else { '' }), + $(if ($env:USERPROFILE) { Join-Path $env:USERPROFILE $zhDesktop } else { '' }) +)) { + Add-ScanDir $d $false 'desktop' $false +} +foreach ($od in @($env:OneDrive, $env:OneDriveConsumer, $env:OneDriveCommercial)) { + if ($od) { + Add-ScanDir (Join-Path $od 'Desktop') $false 'desktop' $false + Add-ScanDir (Join-Path $od $zhDesktop) $false 'desktop' $false + } +} +Add-ScanDir $userProgramsDir $false 'programs' $true +Add-ScanDir ([Environment]::GetFolderPath('StartMenu')) $false 'startmenu' $false +Add-ScanDir ([Environment]::GetFolderPath('Startup')) $false 'startup' $false +if ($env:APPDATA) { + Add-ScanDir (Join-Path $env:APPDATA 'Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar') $false 'taskbar' $false +} +Add-ScanDir ([Environment]::GetFolderPath('CommonDesktopDirectory')) $true 'desktop' $false +Add-ScanDir ([Environment]::GetFolderPath('CommonPrograms')) $true 'programs' $true $seen = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase) -foreach ($spec in $scanSpecs) { +foreach ($spec in $flatSpecs) { $dir = [string]$spec.Dir - if (-not $dir -or -not (Test-Path -LiteralPath $dir)) { continue } $items = @() try { - if ($spec.Recurse) { - $items = @(Get-ChildItem -LiteralPath $dir -Filter '*.lnk' -File -Recurse -Depth 2 -ErrorAction SilentlyContinue) - } else { - $items = @(Get-ChildItem -LiteralPath $dir -Filter '*.lnk' -File -ErrorAction SilentlyContinue) - } + $items = @(Get-ChildItem -LiteralPath $dir -Filter '*.lnk' -File -ErrorAction SilentlyContinue) } catch { continue } foreach ($item in $items) { + if ($item.Length -lt 32 -or $item.Length -gt 65536) { continue } $lnkPath = [string]$item.FullName if (-not $seen.Add($lnkPath)) { continue } try { + $rawBytes = [System.IO.File]::ReadAllBytes($lnkPath) + $u16 = [System.Text.Encoding]::Unicode.GetString($rawBytes) + $lat = [System.Text.Encoding]::GetEncoding(28591).GetString($rawBytes) + if ($u16.IndexOf('antigravity.exe', [System.StringComparison]::OrdinalIgnoreCase) -lt 0 -and + $lat.IndexOf('antigravity.exe', [System.StringComparison]::OrdinalIgnoreCase) -lt 0) { + continue + } + if (-not $ws) { $ws = New-Object -ComObject WScript.Shell } $sc = $ws.CreateShortcut($lnkPath) $target = [string]$sc.TargetPath if ([System.IO.Path]::GetFileName($target) -ine 'Antigravity.exe') { continue } @@ -457,9 +792,10 @@ foreach ($spec in $scanSpecs) { $updated.Add($lnkPath) $configured.Add($lnkPath) } catch { - if ($spec.IsCommon -and $userProgramsDir -and (Test-Path -LiteralPath $userProgramsDir)) { + $readOnly.Add($lnkPath) + if ($spec.IsCommon -and $spec.Kind -eq 'programs' -and $userProgramsDir -and (Test-Path -LiteralPath $userProgramsDir -ErrorAction SilentlyContinue)) { $fallbackLnk = Join-Path $userProgramsDir ([System.IO.Path]::GetFileName($lnkPath)) - if (-not (Test-Path -LiteralPath $fallbackLnk)) { + if (-not (Test-Path -LiteralPath $fallbackLnk -ErrorAction SilentlyContinue)) { try { $uSc = $ws.CreateShortcut($fallbackLnk) $uSc.TargetPath = $target @@ -481,7 +817,9 @@ foreach ($spec in $scanSpecs) { $sc.Arguments = $stripped $sc.Save() $updated.Add($lnkPath) - } catch {} + } catch { + $readOnly.Add($lnkPath) + } } if ($stripped -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { $configured.Add($lnkPath) @@ -491,40 +829,108 @@ foreach ($spec in $scanSpecs) { } } -$runKey = 'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Run' -if (Test-Path -LiteralPath $runKey) { - try { - $regItem = Get-Item -LiteralPath $runKey -ErrorAction SilentlyContinue - if ($regItem) { - foreach ($valName in $regItem.GetValueNames()) { - $rawCmd = [string]$regItem.GetValue($valName, '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) - if (-not $rawCmd) { continue } - if ($rawCmd -notmatch '^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$') { continue } - $exeCandidate = if ($Matches[1]) { $Matches[1] } else { $Matches[2] } - $restPart = [string]$Matches[3] - if ([System.IO.Path]::GetFileName($exeCandidate) -ine 'Antigravity.exe') { continue } - $quotedExe = if ($Matches[1] -or $exeCandidate -match '\\s') { '"' + $exeCandidate + '"' } else { $exeCandidate } - if ($enableFlag) { - if ($restPart -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { - $configured.Add("HKCU:Run:$valName") - continue - } - $nextRest = ($restPart.Trim() + ' --remote-debugging-port=0').Trim() - $nextVal = "$quotedExe $nextRest" - Set-ItemProperty -LiteralPath $runKey -Name $valName -Value $nextVal -ErrorAction SilentlyContinue - $updated.Add("HKCU:Run:$valName") +$runSubPath = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run' +try { + $runReadKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($runSubPath, $false) + if ($runReadKey) { + $runNames = @($runReadKey.GetValueNames()) + $runReadKey.Close() + foreach ($valName in $runNames) { + $rk = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($runSubPath, $false) + if (-not $rk) { continue } + $rawCmd = [string]$rk.GetValue($valName, '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) + $rk.Close() + if (-not $rawCmd) { continue } + if ($rawCmd -notmatch '^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$') { continue } + $exeCandidate = if ($Matches[1]) { $Matches[1] } else { $Matches[2] } + $restPart = [string]$Matches[3] + if ([System.IO.Path]::GetFileName($exeCandidate) -ine 'Antigravity.exe') { continue } + $quotedExe = if ($Matches[1] -or $exeCandidate -match '\\s') { '"' + $exeCandidate + '"' } else { $exeCandidate } + if ($enableFlag) { + if ($restPart -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { $configured.Add("HKCU:Run:$valName") - } else { - $strippedRest = ([regex]::Replace($restPart, '(?:^|\\s+)--remote-debugging-port=(?:"0"|''0''|0)(?=\\s|$)', ' ')).Trim() - $nextVal = if ($strippedRest) { "$quotedExe $strippedRest" } else { $quotedExe } - if ($nextVal -ne $rawCmd.Trim()) { - Set-ItemProperty -LiteralPath $runKey -Name $valName -Value $nextVal -ErrorAction SilentlyContinue + continue + } + $nextRest = ($restPart.Trim() + ' --remote-debugging-port=0').Trim() + $nextVal = "$quotedExe $nextRest" + try { + $wk = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($runSubPath, $true) + if ($wk) { + $wk.SetValue($valName, $nextVal, [Microsoft.Win32.RegistryValueKind]::String) + $wk.Close() $updated.Add("HKCU:Run:$valName") - } - if ($strippedRest -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { $configured.Add("HKCU:Run:$valName") } + } catch {} + } else { + $strippedRest = ([regex]::Replace($restPart, '(?:^|\\s+)--remote-debugging-port=(?:"0"|''0''|0)(?=\\s|$)', ' ')).Trim() + $nextVal = if ($strippedRest) { "$quotedExe $strippedRest" } else { $quotedExe } + if ($nextVal -ne $rawCmd.Trim()) { + try { + $wk = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($runSubPath, $true) + if ($wk) { + $wk.SetValue($valName, $nextVal, [Microsoft.Win32.RegistryValueKind]::String) + $wk.Close() + $updated.Add("HKCU:Run:$valName") + } + } catch {} } + if ($strippedRest -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { + $configured.Add("HKCU:Run:$valName") + } + } + } + } +} catch {} + +$exactClassSubKeys = @( + 'Software\\Classes\\antigravity\\shell\\open\\command', + 'Software\\Classes\\Applications\\Antigravity.exe\\shell\\open\\command', + 'Software\\Classes\\AntigravitySourceFile\\shell\\open\\command' +) +foreach ($relSubKey in $exactClassSubKeys) { + try { + $rOpen = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($relSubKey, $false) + if (-not $rOpen) { continue } + $rawOpen = [string]$rOpen.GetValue('', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) + $rOpen.Close() + if (-not $rawOpen) { continue } + if ($rawOpen -notmatch '^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$') { continue } + $exeCand = if ($Matches[1]) { $Matches[1] } else { $Matches[2] } + $restOpen = ([string]$Matches[3]).Trim() + if ([System.IO.Path]::GetFileName($exeCand) -ine 'Antigravity.exe') { continue } + $quotedOpenExe = if ($Matches[1] -or $exeCand -match '\\s') { '"' + $exeCand + '"' } else { $exeCand } + $fullKeyName = "HKEY_CURRENT_USER\\$relSubKey" + if ($enableFlag) { + if ($restOpen -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { + $configured.Add($fullKeyName) + continue + } + $nextOpen = if ($restOpen) { "$quotedOpenExe --remote-debugging-port=0 $restOpen" } else { "$quotedOpenExe --remote-debugging-port=0" } + try { + $wOpen = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($relSubKey, $true) + if ($wOpen) { + $wOpen.SetValue('', $nextOpen, [Microsoft.Win32.RegistryValueKind]::String) + $wOpen.Close() + $updated.Add($fullKeyName) + $configured.Add($fullKeyName) + } + } catch {} + } else { + $strippedOpen = ([regex]::Replace($restOpen, '(?:^|\\s+)--remote-debugging-port=(?:"0"|''0''|0)(?=\\s|$)', ' ')).Trim() + $nextOpen = if ($strippedOpen) { "$quotedOpenExe $strippedOpen" } else { $quotedOpenExe } + if ($nextOpen -ne $rawOpen.Trim()) { + try { + $wOpen = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($relSubKey, $true) + if ($wOpen) { + $wOpen.SetValue('', $nextOpen, [Microsoft.Win32.RegistryValueKind]::String) + $wOpen.Close() + $updated.Add($fullKeyName) + } + } catch {} + } + if ($strippedOpen -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { + $configured.Add($fullKeyName) } } } catch {} @@ -534,14 +940,16 @@ if (Test-Path -LiteralPath $runKey) { ok = $true updatedPaths = @($updated) configuredPaths = @($configured) + readOnlyPaths = @($readOnly) } | ConvertTo-Json -Compress `.trim(); /** - * 自动同步当前系统下用户空间启动入口(Windows `.lnk` / `HKCU:Run`、Linux `.desktop`)中的 `--remote-debugging-port=0`。 + * 自动同步当前系统下用户空间启动入口(Windows `.lnk` / `HKCU:Run` / `HKCU:Classes`、Linux `.desktop`)中的 `--remote-debugging-port=0`。 * * @param {{ * enabled?: boolean, + * fastCheckIfActive?: boolean, * env?: Record, * platform?: string, * homeDir?: string, @@ -553,12 +961,15 @@ if (Test-Path -LiteralPath $runKey) { * mkdirFn?: typeof mkdirSync, * renameFn?: typeof renameSync, * unlinkFn?: typeof unlinkSync, + * readdirFn?: typeof readdirSync, + * statFn?: typeof statSync, * }|null, * allowInTest?: boolean, * }} [options] */ export async function ensureDesktopLaunchEntriesConfigured({ enabled = true, + fastCheckIfActive = false, env = process.env, platform = process.platform, homeDir = homedir(), @@ -571,8 +982,11 @@ export async function ensureDesktopLaunchEntriesConfigured({ checked: false, updated: false, alreadyConfigured: false, + configured: false, + hasReadOnlyShortcuts: false, updatedPaths: [], configuredPaths: [], + readOnlyPaths: [], reason: 'test_sandbox_skipped', }; } @@ -584,16 +998,50 @@ export async function ensureDesktopLaunchEntriesConfigured({ mkdirFn: fsOps?.mkdirFn || mkdirSync, renameFn: fsOps?.renameFn || renameSync, unlinkFn: fsOps?.unlinkFn || unlinkSync, + readdirFn: fsOps?.readdirFn || readdirSync, + statFn: fsOps?.statFn || statSync, }; if (platform === 'win32') { + // 稳态零子进程快检:当调试端口已活跃或处于周期复检且所有 `.lnk` 字节内均已含参数时,直接返回(<2ms,不拉起 PowerShell) + if (!execFileFn && fastCheckIfActive) { + const fast = probeWindowsShortcutsFast({ env, homeDir, fsOps: ops }); + if (enabled && fast.allConfigured) { + return { + checked: true, + fastPath: true, + updated: false, + alreadyConfigured: true, + configured: true, + hasReadOnlyShortcuts: false, + updatedPaths: [], + configuredPaths: fast.configuredPaths, + readOnlyPaths: [], + }; + } + if (!enabled && fast.configuredPaths.length === 0) { + return { + checked: true, + fastPath: true, + updated: false, + alreadyConfigured: false, + configured: false, + hasReadOnlyShortcuts: false, + updatedPaths: [], + configuredPaths: [], + readOnlyPaths: [], + }; + } + } + try { const runner = execFileFn || runLauncherExecFile; + const psExe = execFileFn ? 'powershell.exe' : resolveWindowsPowerShellExecutable(env, ops.existsFn); const out = await runner( - 'powershell.exe', + psExe, ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', WIN_SHORTCUT_PROVISION_PS], { - timeoutMs: 9000, + timeoutMs: 10000, env: { ...env, AGY_LAUNCH_ENABLED: enabled ? '1' : '0', @@ -609,13 +1057,19 @@ export async function ensureDesktopLaunchEntriesConfigured({ const configuredPaths = Array.isArray(parsed?.configuredPaths) ? parsed.configuredPaths.map(String).filter(Boolean) : []; + const readOnlyPaths = Array.isArray(parsed?.readOnlyPaths) + ? parsed.readOnlyPaths.map(String).filter(Boolean) + : []; + const hasReadOnlyShortcuts = enabled && readOnlyPaths.length > 0; return { checked: true, updated: updatedPaths.length > 0, alreadyConfigured: updatedPaths.length === 0 && configuredPaths.length > 0, configured: configuredPaths.length > 0, + hasReadOnlyShortcuts, updatedPaths, configuredPaths, + readOnlyPaths, }; } catch (err) { return { @@ -623,8 +1077,10 @@ export async function ensureDesktopLaunchEntriesConfigured({ updated: false, alreadyConfigured: false, configured: false, + hasReadOnlyShortcuts: false, updatedPaths: [], configuredPaths: [], + readOnlyPaths: [], reason: 'win_shortcut_error', error: err?.message || String(err), }; @@ -682,8 +1138,10 @@ export async function ensureDesktopLaunchEntriesConfigured({ updated: updatedPaths.length > 0, alreadyConfigured: updatedPaths.length === 0 && configuredPaths.length > 0, configured: configuredPaths.length > 0, + hasReadOnlyShortcuts: false, updatedPaths, configuredPaths, + readOnlyPaths: [], }; } catch (err) { return { @@ -691,8 +1149,10 @@ export async function ensureDesktopLaunchEntriesConfigured({ updated: false, alreadyConfigured: false, configured: false, + hasReadOnlyShortcuts: false, updatedPaths, configuredPaths, + readOnlyPaths: [], reason: 'linux_desktop_error', error: err?.message || String(err), }; @@ -705,24 +1165,31 @@ export async function ensureDesktopLaunchEntriesConfigured({ updated: false, alreadyConfigured: false, configured: false, + hasReadOnlyShortcuts: false, updatedPaths: [], configuredPaths: [], + readOnlyPaths: [], reason: 'macos_app_bundle_signed', }; } /** - * 当静态环境变量与默认安装目录均未命中(如用户自定义安装至 D:/E: 盘且 Sidecar 未继承 `ANTIGRAVITY_AGENTAPI_EXE`)时, + * 当静态环境变量与默认安装目录均未命中(如用户自定义安装至 D:/E: 盘、Linux 自定义目录或 AppImage)时, * 直接从当前正在运行的宿主进程动态反查主程序绝对路径。 */ -async function discoverRunningHostExecutable({ platform = process.platform, execFileFn = null } = {}) { +async function discoverRunningHostExecutable({ + platform = process.platform, + env = process.env, + execFileFn = null, +} = {}) { const runner = execFileFn || runLauncherExecFile; if (platform === 'win32') { try { + const psExe = execFileFn ? 'powershell.exe' : resolveWindowsPowerShellExecutable(env); const ps = - "@(Get-Process -Name 'Antigravity','Antigravity IDE' -ErrorAction SilentlyContinue | Where-Object { $_.Path } | Select-Object -First 1) | ForEach-Object { [pscustomobject]@{ path = [string]$_.Path; name = [string]$_.ProcessName } } | ConvertTo-Json -Compress"; + "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; @(Get-Process -Name 'Antigravity','Antigravity IDE' -ErrorAction SilentlyContinue | Where-Object { $_.Path } | Select-Object -First 1) | ForEach-Object { [pscustomobject]@{ path = [string]$_.Path; name = [string]$_.ProcessName } } | ConvertTo-Json -Compress"; const out = await runner( - 'powershell.exe', + psExe, ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', ps], { timeoutMs: 4000 } ); @@ -762,6 +1229,59 @@ async function discoverRunningHostExecutable({ platform = process.platform, exec } catch { // 忽略 AppleScript 探测异常 } + } else if (platform === 'linux') { + if (!execFileFn && typeof process.getuid === 'function') { + try { + const myUid = process.getuid(); + for (const name of readdirSync('/proc')) { + if (!/^\d+$/.test(name)) continue; + const procDir = `/proc/${name}`; + try { + const st = statSync(procDir); + if (st.uid !== myUid) continue; + const exeTarget = String(readlinkSync(`${procDir}/exe`) || '').trim(); + if (!exeTarget) continue; + const leaf = basename(exeTarget); + if (!isLinuxAntigravityDesktopLeaf(leaf)) continue; + try { + const envRaw = readFileSync(`${procDir}/environ`, 'utf8'); + for (const entry of envRaw.split('\0')) { + if (entry.startsWith('APPIMAGE=')) { + const appImg = entry.slice('APPIMAGE='.length).trim(); + if (appImg && existsSync(appImg)) { + return { found: true, kind: 'desktop', executablePath: appImg, appBundlePath: '' }; + } + } + } + } catch { + // 忽略 environ 读取异常 + } + if (exeTarget.startsWith('/tmp/.mount_')) continue; + return { found: true, kind: 'desktop', executablePath: exeTarget, appBundlePath: '' }; + } catch { + // 忽略单个瞬态退出的进程目录 + } + } + } catch { + // 忽略 /proc 原生扫描异常,回退外部命令探测 + } + } + if (execFileFn) { + try { + const out = await runner('/bin/sh', ['-c', 'true'], { timeoutMs: 2000 }); + const foundLinuxExe = String(out || '').trim().split(/\r?\n/)[0]?.trim() || ''; + if (foundLinuxExe) { + return { + found: true, + kind: 'desktop', + executablePath: foundLinuxExe, + appBundlePath: '', + }; + } + } catch { + // 忽略模拟探测异常 + } + } } return { found: false, kind: '', executablePath: '', appBundlePath: '' }; } @@ -771,26 +1291,51 @@ function psSingleQuote(val) { } /** - * 构建 Windows 脱离宿主 Job Object 的隐藏重拉内层脚本(写入临时 UTF-8 BOM `.ps1` 文件后交由 `explorer.exe` 拉起,规避 `ShellExecute` 参数长度上限)。 + * 构建 Windows 脱离宿主 Job Object 的隐藏重拉内层脚本(写入临时 UTF-8 BOM `.ps1` 文件后拉起)。 + * + * 权限自适应策略: + * 1. 若存在 All-Users 只读公共快捷方式(`$readOnlyShortcuts.Count -gt 0`)且当前未提权,先通过 `-Verb RunAs` + * 请求用户 UAC 授权一次性修补公共 `.lnk`(用户若点取消仍继续执行当次重拉,不阻塞会话恢复); + * 2. 先尝试常规温和关闭(`CloseMainWindow` + `Stop-Process`); + * 3. 若等待后仍有旧宿主进程存活(例如旧宿主是以管理员身份运行的,普通权限无法关闭),再请求一次 `-Verb RunAs` + * 关闭旧管理员宿主并以管理员身份带参重开; + * 4. 若当前脚本自身因提权运行但原宿主并非管理员(`$wasHostElevated -eq $false`),通过 `Shell.Application` + * 委托桌面 `explorer.exe` 以普通权限启动新客户端,确保资源管理器文件拖拽进窗口不被 UIPI 阻断。 * * @param {string} executablePath * @param {string[]} stalePortFiles * @param {'desktop'|'ide'|''} kind + * @param {{ readOnlyShortcutPaths?: string[], psExePath?: string }} [extra] * @returns {string} */ -export function buildWindowsRelaunchInnerScript(executablePath, stalePortFiles = [], kind = 'desktop') { +export function buildWindowsRelaunchInnerScript( + executablePath, + stalePortFiles = [], + kind = 'desktop', + extra = {} +) { const procName = kind === 'ide' ? 'Antigravity IDE' : 'Antigravity'; + const psExe = String(extra?.psExePath || 'powershell.exe').trim() || 'powershell.exe'; const portLiterals = (Array.isArray(stalePortFiles) ? stalePortFiles : []) .map((p) => String(p || '').trim()) .filter(Boolean) .map(psSingleQuote) .join(', '); + const roLiterals = (Array.isArray(extra?.readOnlyShortcutPaths) ? extra.readOnlyShortcutPaths : []) + .map((p) => String(p || '').trim()) + .filter(Boolean) + .map(psSingleQuote) + .join(', '); return ` Start-Sleep -Milliseconds 480 $exe = ${psSingleQuote(executablePath)} $procName = ${psSingleQuote(procName)} +$psExe = ${psSingleQuote(psExe)} $staleList = @(${portLiterals}) +$readOnlyShortcuts = @(${roLiterals}) +$wasHostElevated = $env:AGY_HOST_WAS_ELEVATED -eq '1' +$isSelfElevated = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) $mySid = (Get-Process -Id $PID).SessionId if (-not $exe -or -not (Test-Path -LiteralPath $exe)) { @@ -798,6 +1343,55 @@ if (-not $exe -or -not (Test-Path -LiteralPath $exe)) { if ($livePath) { $exe = [string]$livePath } } +function Patch-ShortcutList($paths) { + if (-not $paths -or $paths.Count -eq 0) { return } + try { + $ws = New-Object -ComObject WScript.Shell + foreach ($lnk in $paths) { + if (-not $lnk -or -not (Test-Path -LiteralPath $lnk)) { continue } + try { + $sc = $ws.CreateShortcut($lnk) + $cur = [string]$sc.Arguments + if ($cur -notmatch '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { + $sc.Arguments = ($cur.Trim() + ' --remote-debugging-port=0').Trim() + $sc.Save() + } + } catch {} + } + } catch {} +} + +if ($readOnlyShortcuts.Count -gt 0) { + if ($isSelfElevated) { + Patch-ShortcutList $readOnlyShortcuts + } else { + $elevPatchPs1 = Join-Path ([System.IO.Path]::GetTempPath()) ("agy-monitor-uac-lnk-" + $PID + ".ps1") + $roJoined = ($readOnlyShortcuts | ForEach-Object { "'" + ($_.Replace("'", "''")) + "'" }) -join ', ' + $elevBody = @( + "\$ws = New-Object -ComObject WScript.Shell", + "foreach (\$lnk in @($roJoined)) {", + " if (\$lnk -and (Test-Path -LiteralPath \$lnk)) {", + " try {", + " \$sc = \$ws.CreateShortcut(\$lnk)", + " \$cur = [string]\$sc.Arguments", + " if (\$cur -notmatch '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {", + " \$sc.Arguments = (\$cur.Trim() + ' --remote-debugging-port=0').Trim()", + " \$sc.Save()", + " }", + " } catch {}", + " }", + "}", + "Remove-Item -LiteralPath \$PSCommandPath -Force -ErrorAction SilentlyContinue" + ) -join "\`r\`n" + try { + [System.IO.File]::WriteAllText($elevPatchPs1, $elevBody, (New-Object System.Text.UTF8Encoding($true))) + Start-Process -FilePath $psExe -Verb RunAs -WindowStyle Hidden -Wait -ArgumentList @('-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', $elevPatchPs1) -ErrorAction Stop + } catch { + if (Test-Path -LiteralPath $elevPatchPs1) { Remove-Item -LiteralPath $elevPatchPs1 -Force -ErrorAction SilentlyContinue } + } + } +} + $findTargets = { @(Get-Process -Name $procName -ErrorAction SilentlyContinue | Where-Object { $_.SessionId -eq $mySid -and (-not $_.Path -or -not $exe -or [string]::Equals($_.Path, $exe, [System.StringComparison]::OrdinalIgnoreCase)) @@ -817,11 +1411,37 @@ foreach ($p in $remaining) { try { Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue } catch {} } -for ($i = 0; $i -lt 30; $i++) { +for ($i = 0; $i -lt 25; $i++) { if ((& $findTargets).Count -eq 0) { break } Start-Sleep -Milliseconds 200 } +if ((& $findTargets).Count -gt 0 -and -not $isSelfElevated -and $exe -and (Test-Path -LiteralPath $exe)) { + $elevRelaunchPs1 = Join-Path ([System.IO.Path]::GetTempPath()) ("agy-monitor-uac-relaunch-" + $PID + ".ps1") + $staleJoined = ($staleList | ForEach-Object { "'" + ($_.Replace("'", "''")) + "'" }) -join ', ' + $exeLit = "'" + $exe.Replace("'", "''") + "'" + $procLit = "'" + $procName.Replace("'", "''") + "'" + $elevKillBody = @( + "\$mySid = (Get-Process -Id \$PID).SessionId", + "Get-Process -Name $procLit -ErrorAction SilentlyContinue | Where-Object { \$_.SessionId -eq \$mySid } | Stop-Process -Force -ErrorAction SilentlyContinue", + "Start-Sleep -Milliseconds 600", + "foreach (\$fp in @($staleJoined)) { if (\$fp -and (Test-Path -LiteralPath \$fp)) { Remove-Item -LiteralPath \$fp -Force -ErrorAction SilentlyContinue } }", + "\$wd = Split-Path -Parent $exeLit", + "Start-Process -FilePath $exeLit -ArgumentList '--remote-debugging-port=0' -WorkingDirectory \$wd", + "Remove-Item -LiteralPath \$PSCommandPath -Force -ErrorAction SilentlyContinue" + ) -join "\`r\`n" + try { + [System.IO.File]::WriteAllText($elevRelaunchPs1, $elevKillBody, (New-Object System.Text.UTF8Encoding($true))) + Start-Process -FilePath $psExe -Verb RunAs -WindowStyle Hidden -ArgumentList @('-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', $elevRelaunchPs1) -ErrorAction Stop + if ($PSCommandPath -and (Test-Path -LiteralPath $PSCommandPath)) { + Remove-Item -LiteralPath $PSCommandPath -Force -ErrorAction SilentlyContinue + } + exit 0 + } catch { + if (Test-Path -LiteralPath $elevRelaunchPs1) { Remove-Item -LiteralPath $elevRelaunchPs1 -Force -ErrorAction SilentlyContinue } + } +} + foreach ($fp in $staleList) { if ($fp -and (Test-Path -LiteralPath $fp)) { try { Remove-Item -LiteralPath $fp -Force -ErrorAction SilentlyContinue } catch {} @@ -830,7 +1450,16 @@ foreach ($fp in $staleList) { if ($exe -and (Test-Path -LiteralPath $exe)) { $workDir = Split-Path -Parent $exe - Start-Process -FilePath $exe -ArgumentList '--remote-debugging-port=0' -WorkingDirectory $workDir + if ($isSelfElevated -and -not $wasHostElevated) { + try { + $shellApp = New-Object -ComObject Shell.Application + $shellApp.ShellExecute($exe, '--remote-debugging-port=0', $workDir, 'open', 1) + } catch { + Start-Process -FilePath $exe -ArgumentList '--remote-debugging-port=0' -WorkingDirectory $workDir + } + } else { + Start-Process -FilePath $exe -ArgumentList '--remote-debugging-port=0' -WorkingDirectory $workDir + } } if ($PSCommandPath -and (Test-Path -LiteralPath $PSCommandPath)) { @@ -840,16 +1469,44 @@ if ($PSCommandPath -and (Test-Path -LiteralPath $PSCommandPath)) { } const WIN_OUT_OF_JOB_DISPATCH_PS = ` +[Console]::OutputEncoding = [System.Text.Encoding]::UTF8 $ErrorActionPreference = 'Stop' +$psBin = if ($env:AGY_PS_EXE) { $env:AGY_PS_EXE } else { 'powershell.exe' } +$isElev = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) +$env:AGY_HOST_WAS_ELEVATED = if ($isElev) { '1' } else { '0' } $innerArgs = '-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File "' + $env:AGY_RELAUNCH_PS1 + '"' +$fullCmd = '"' + $psBin + '" ' + $innerArgs + +if ($isElev) { + try { + $wmiRes = ([wmiclass]'Win32_Process').Create($fullCmd) + if ($wmiRes -and $wmiRes.ReturnValue -eq 0) { + Write-Output '{"ok":true,"method":"wmi_elevated"}' + exit 0 + } + } catch {} + Start-Process -FilePath $psBin -ArgumentList $innerArgs -WindowStyle Hidden + Write-Output '{"ok":true,"method":"start_process_elevated"}' + exit 0 +} + try { $shellApp = New-Object -ComObject Shell.Application - $shellApp.ShellExecute('powershell.exe', $innerArgs, '', 'open', 0) + $shellApp.ShellExecute($psBin, $innerArgs, '', 'open', 0) Write-Output '{"ok":true,"method":"shell_application"}' -} catch { - Start-Process -FilePath 'powershell.exe' -ArgumentList $innerArgs -WindowStyle Hidden - Write-Output '{"ok":true,"method":"start_process"}' -} + exit 0 +} catch {} + +try { + $wmiRes = ([wmiclass]'Win32_Process').Create($fullCmd) + if ($wmiRes -and $wmiRes.ReturnValue -eq 0) { + Write-Output '{"ok":true,"method":"wmi_fallback"}' + exit 0 + } +} catch {} + +Start-Process -FilePath $psBin -ArgumentList $innerArgs -WindowStyle Hidden +Write-Output '{"ok":true,"method":"start_process"}' `.trim(); /** @@ -860,6 +1517,7 @@ try { * platform?: string, * homeDir?: string, * stalePortFiles?: string[], + * readOnlyShortcutPaths?: string[], * execFileFn?: ((file: string, args: string[], opts?: object) => Promise)|null, * spawnFn?: ((file: string, args: string[], opts?: object) => Promise<{ pid: number }>)|null, * existsFn?: typeof existsSync, @@ -873,6 +1531,7 @@ export async function triggerDesktopHostRelaunch({ platform = process.platform, homeDir = homedir(), stalePortFiles = [], + readOnlyShortcutPaths = [], execFileFn = null, spawnFn = null, existsFn = existsSync, @@ -886,7 +1545,7 @@ export async function triggerDesktopHostRelaunch({ let hostInfo = resolveDesktopHostExecutable({ env, platform, homeDir, existsFn }); if (!hostInfo.found) { - hostInfo = await discoverRunningHostExecutable({ platform, execFileFn }); + hostInfo = await discoverRunningHostExecutable({ platform, env, execFileFn }); } if (!hostInfo.found) { return { @@ -900,12 +1559,20 @@ export async function triggerDesktopHostRelaunch({ const cleanStaleFiles = (Array.isArray(stalePortFiles) ? stalePortFiles : []) .map((p) => String(p || '').trim()) .filter(Boolean); + const cleanReadOnlyPaths = (Array.isArray(readOnlyShortcutPaths) ? readOnlyShortcutPaths : []) + .map((p) => String(p || '').trim()) + .filter(Boolean); if (platform === 'win32') { + const psExe = execFileFn ? 'powershell.exe' : resolveWindowsPowerShellExecutable(env, existsFn); const innerScript = buildWindowsRelaunchInnerScript( hostInfo.executablePath, cleanStaleFiles, - hostInfo.kind + hostInfo.kind, + { + readOnlyShortcutPaths: cleanReadOnlyPaths, + psExePath: psExe, + } ); const tempDir = String(env?.TEMP || env?.TMP || DATA_DIR || homeDir).trim(); mkdirFn(tempDir, { recursive: true }); @@ -915,7 +1582,7 @@ export async function triggerDesktopHostRelaunch({ const runner = execFileFn || runLauncherExecFile; await runner( - 'powershell.exe', + psExe, [ '-Sta', '-NoProfile', @@ -929,6 +1596,7 @@ export async function triggerDesktopHostRelaunch({ timeoutMs: 6000, env: { ...cleanEnv, + AGY_PS_EXE: psExe, AGY_RELAUNCH_PS1: relaunchPs1Path, }, } @@ -973,8 +1641,8 @@ export async function triggerDesktopHostRelaunch({ const linuxScript = [ 'sleep 0.45', 'uid="$(id -u)"', - 'pkill -u "$uid" -x "$AGY_PROC_NAME" >/dev/null 2>&1 || true', - 'i=0; while [ $i -lt 25 ] && pgrep -u "$uid" -x "$AGY_PROC_NAME" >/dev/null 2>&1; do sleep 0.2; i=$((i+1)); done', + 'for pn in "$AGY_PROC_NAME" antigravity Antigravity; do [ -n "$pn" ] && pkill -u "$uid" -x "$pn" >/dev/null 2>&1 || true; done', + 'i=0; while [ $i -lt 25 ] && (pgrep -u "$uid" -x "$AGY_PROC_NAME" >/dev/null 2>&1 || pgrep -u "$uid" -x antigravity >/dev/null 2>&1 || pgrep -u "$uid" -x Antigravity >/dev/null 2>&1); do sleep 0.2; i=$((i+1)); done', 'IFS=":"; for f in $AGY_STALE_PORT_FILES; do [ -n "$f" ] && rm -f "$f"; done', 'nohup "$AGY_RELAUNCH_EXE" --remote-debugging-port=0 >/dev/null 2>&1 &', ].join('; '); diff --git a/sidecars/panel/backend/window-bridge.mjs b/sidecars/panel/backend/window-bridge.mjs index 098141a..ae53f5f 100644 --- a/sidecars/panel/backend/window-bridge.mjs +++ b/sidecars/panel/backend/window-bridge.mjs @@ -714,6 +714,7 @@ export function createWindowBridgeController(options) { onVersionDrift = null, leaseFilePath = '', autoConfigureIdeArgv = options?.env === undefined && options?.homeDir === undefined, + launcherRecheckIntervalMs = 15 * 60 * 1000, launcherExecFileFn = null, launcherFsOps = null, allowDesktopLauncherInTest = false, @@ -743,21 +744,23 @@ export function createWindowBridgeController(options) { let hadInjectedTargets = false; let hadInjectedChatFrames = false; let cdpFallbackActive = false; - let ideArgvProvisioned = false; + let lastLauncherProvisionAtMs = 0; let hostLauncherPromise = null; let argvUpdatedThisBoot = false; let argvConfigured = false; let launcherConfigured = false; + let hasReadOnlyShortcuts = false; const hostExecInfo = resolveDesktopHostExecutable({ env, platform, homeDir, existsFn: existsHostFn, }); - // Windows / macOS 支持从运行中宿主进程动态反查任意盘符路径,因此桌面端环境下即使自定义安装路径不在默认盘符也可一键重拉 + // Windows / macOS / Linux 均支持从运行中宿主进程动态反查路径(含自定义盘符与 AppImage),自定义安装路径亦可一键重拉 const canRelaunch = Boolean( hostExecInfo.found || - ((platform === 'win32' || platform === 'darwin') && options?.existsHostFn === undefined) + ((platform === 'win32' || platform === 'darwin' || platform === 'linux') && + options?.existsHostFn === undefined) ); let lastPersistedLeaseSig = ''; let lastBridgeStatus = { @@ -768,6 +771,7 @@ export function createWindowBridgeController(options) { argvUpdatedThisBoot: false, argvConfigured: false, launcherConfigured: false, + hasReadOnlyShortcuts: false, canRelaunch, updatedAtMs: 0, }; @@ -1209,11 +1213,12 @@ export function createWindowBridgeController(options) { argvUpdatedThisBoot: Boolean(argvUpdatedThisBoot), argvConfigured: Boolean(argvConfigured || launcherConfigured), launcherConfigured: Boolean(launcherConfigured || argvConfigured), + hasReadOnlyShortcuts: Boolean(hasReadOnlyShortcuts), canRelaunch: Boolean(canRelaunch), updatedAtMs: Date.now(), }; if (leasedBySelf && leaseFilePath) { - const sig = `${nextState}:${lastBridgeStatus.aliveCount}:${lastBridgeStatus.targets}:${lastBridgeStatus.argvUpdatedThisBoot ? 1 : 0}:${lastBridgeStatus.launcherConfigured ? 1 : 0}:${lastBridgeStatus.canRelaunch ? 1 : 0}`; + const sig = `${nextState}:${lastBridgeStatus.aliveCount}:${lastBridgeStatus.targets}:${lastBridgeStatus.argvUpdatedThisBoot ? 1 : 0}:${lastBridgeStatus.launcherConfigured ? 1 : 0}:${lastBridgeStatus.hasReadOnlyShortcuts ? 1 : 0}:${lastBridgeStatus.canRelaunch ? 1 : 0}`; if (sig !== lastPersistedLeaseSig) { lastPersistedLeaseSig = sig; saveJson(leaseFilePath, { @@ -1227,6 +1232,7 @@ export function createWindowBridgeController(options) { argvUpdatedThisBoot: lastBridgeStatus.argvUpdatedThisBoot, argvConfigured: lastBridgeStatus.argvConfigured, launcherConfigured: lastBridgeStatus.launcherConfigured, + hasReadOnlyShortcuts: lastBridgeStatus.hasReadOnlyShortcuts, canRelaunch: lastBridgeStatus.canRelaunch, updatedAtMs: Date.now(), }); @@ -1234,13 +1240,13 @@ export function createWindowBridgeController(options) { } } - function provisionHostLaunchersOnce() { - if (ideArgvProvisioned) return Promise.resolve(); + function provisionHostLaunchersOnce({ fastCheckIfActive = false } = {}) { if (hostLauncherPromise) return hostLauncherPromise; hostLauncherPromise = (async () => { const ideRes = ensureIdeRemoteDebuggingArgv({ env, homeDir, enabled: true }); const desktopRes = await ensureDesktopLaunchEntriesConfigured({ enabled: true, + fastCheckIfActive, env, platform, homeDir, @@ -1254,10 +1260,13 @@ export function createWindowBridgeController(options) { if (ideRes.updated || ideRes.alreadyConfigured) { argvConfigured = true; } - if (desktopRes.updated || desktopRes.alreadyConfigured || desktopRes.configured) { - launcherConfigured = true; + launcherConfigured = Boolean( + desktopRes.updated || desktopRes.alreadyConfigured || desktopRes.configured + ); + if (!desktopRes.fastPath) { + hasReadOnlyShortcuts = Boolean(desktopRes.hasReadOnlyShortcuts); } - ideArgvProvisioned = true; + lastLauncherProvisionAtMs = Date.now(); })().finally(() => { hostLauncherPromise = null; }); @@ -1280,10 +1289,6 @@ export function createWindowBridgeController(options) { const enabled = Boolean(curSettings.enableWindowOverlay !== false && mountMode !== 'sidebar'); const contextWindows = curSettings.modelContextWindows || {}; const hasContextWindows = Object.keys(contextWindows).length > 0; - const provPending = - (enabled || hasContextWindows) && autoConfigureIdeArgv && !ideArgvProvisioned - ? provisionHostLaunchersOnce() - : hostLauncherPromise; let leasedBySelf = false; let currentLease = null; @@ -1311,6 +1316,7 @@ export function createWindowBridgeController(options) { argvUpdatedThisBoot: Boolean(lease?.argvUpdatedThisBoot || argvUpdatedThisBoot), argvConfigured: mergedConfigured, launcherConfigured: mergedConfigured, + hasReadOnlyShortcuts: Boolean(lease?.hasReadOnlyShortcuts || hasReadOnlyShortcuts), canRelaunch: Boolean(lease?.canRelaunch ?? canRelaunch), updatedAtMs: Date.now(), }; @@ -1330,13 +1336,24 @@ export function createWindowBridgeController(options) { argvUpdatedThisBoot: Boolean(argvUpdatedThisBoot), argvConfigured: Boolean(argvConfigured || launcherConfigured), launcherConfigured: Boolean(launcherConfigured || argvConfigured), + hasReadOnlyShortcuts: Boolean(hasReadOnlyShortcuts), canRelaunch: Boolean(canRelaunch), updatedAtMs: Date.now(), }); } + const shouldCheckLaunchers = + (enabled || hasContextWindows) && + autoConfigureIdeArgv && + (lastLauncherProvisionAtMs === 0 || + Date.now() - lastLauncherProvisionAtMs >= launcherRecheckIntervalMs); + const isInitialLauncherPass = lastLauncherProvisionAtMs === 0; + const cdpPorts = findActiveDevToolsPorts(); if (!cdpPorts.length) { + const provPending = shouldCheckLaunchers + ? provisionHostLaunchersOnce({ fastCheckIfActive: !isInitialLauncherPass }) + : hostLauncherPromise; if (provPending) { await provPending.catch(() => {}); } @@ -1351,6 +1368,9 @@ export function createWindowBridgeController(options) { const { reachableCount, targets } = await collectAllMainWindowTargets(cdpPorts); if (reachableCount === 0) { + const provPending = shouldCheckLaunchers + ? provisionHostLaunchersOnce({ fastCheckIfActive: !isInitialLauncherPass }) + : hostLauncherPromise; if (provPending) { await provPending.catch(() => {}); } @@ -1362,6 +1382,11 @@ export function createWindowBridgeController(options) { }); return { ok: false, enabled, reason: 'cdp_unreachable', injected: 0 }; } + + if (shouldCheckLaunchers) { + // 调试端口已正常连通时走纯 Node.js 零子进程快检(<2ms),仅在发现未配参快捷方式时才拉起 PowerShell + void provisionHostLaunchersOnce({ fastCheckIfActive: true }).catch(() => {}); + } if (!targets.length) { updateBridgeStatus(enabled ? 'no_targets' : 'disabled', { enabled, @@ -1842,6 +1867,8 @@ export function createWindowBridgeController(options) { const hasCtx = Object.keys(cur.modelContextWindows || {}).length > 0; if (!hasCtx && autoConfigureIdeArgv) { launcherConfigured = false; + hasReadOnlyShortcuts = false; + lastLauncherProvisionAtMs = 0; void ensureDesktopLaunchEntriesConfigured({ enabled: false, env, @@ -1853,7 +1880,7 @@ export function createWindowBridgeController(options) { }).catch(() => {}); } } else { - ideArgvProvisioned = false; + lastLauncherProvisionAtMs = 0; hadInjectedChatFrames = true; } return syncAllWindows({ forceReinject: false }).catch(() => ({ ok: false })); @@ -1865,9 +1892,11 @@ export function createWindowBridgeController(options) { const overlayOn = Boolean(cur.enableWindowOverlay !== false && mountMode !== 'sidebar'); const hasCtx = Object.keys(cur.modelContextWindows || {}).length > 0; if (hasCtx) { - ideArgvProvisioned = false; + lastLauncherProvisionAtMs = 0; } else if (!overlayOn && autoConfigureIdeArgv) { launcherConfigured = false; + hasReadOnlyShortcuts = false; + lastLauncherProvisionAtMs = 0; void ensureDesktopLaunchEntriesConfigured({ enabled: false, env, @@ -1908,6 +1937,7 @@ export function getDefaultWindowBridgeStatus() { argvUpdatedThisBoot: false, argvConfigured: false, launcherConfigured: false, + hasReadOnlyShortcuts: false, canRelaunch: false, updatedAtMs: 0, }; diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 71755bf..5b8a8bc 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/settings/BridgeStatusNotice.js b/sidecars/panel/src/components/settings/BridgeStatusNotice.js index ee3e47b..9b760df 100644 --- a/sidecars/panel/src/components/settings/BridgeStatusNotice.js +++ b/sidecars/panel/src/components/settings/BridgeStatusNotice.js @@ -186,6 +186,7 @@ export const BridgeStatusNotice = defineComponent({ function syncActionButtons() { const canRelaunch = lastPayload.windowBridge?.canRelaunch !== false; + const needsAuth = Boolean(lastPayload.windowBridge?.hasReadOnlyShortcuts); patchAttr(relaunchBtnEl, 'hidden', !canRelaunch); patchAttr(relaunchBtnEl, 'disabled', relaunchState === 'relaunching'); patchText( @@ -194,7 +195,9 @@ export const BridgeStatusNotice = defineComponent({ ? t('settings.bridge.relaunchingBtn') : relaunchState === 'failed' ? t('settings.bridge.relaunchFailed') - : t('settings.bridge.relaunchBtn') + : needsAuth + ? t('settings.bridge.relaunchAuthBtn') + : t('settings.bridge.relaunchBtn') ); patchSvgIcon(copyBtnIconEl, copied ? 'check' : 'copy'); @@ -227,38 +230,44 @@ export const BridgeStatusNotice = defineComponent({ patchAttr(rootEl, 'hidden', !shouldShow); if (!shouldShow) return; + const plat = String(lastPayload.hostPlatform || '').trim().toLowerCase(); + const hasReadOnlyShortcuts = Boolean(wb?.hasReadOnlyShortcuts); + const isMacDesktop = plat === 'darwin' && !wb?.argvConfigured; const isAutoConfigured = Boolean( wb?.launcherConfigured || wb?.argvUpdatedThisBoot || wb?.argvConfigured ); + const useRestartTheme = !hasReadOnlyShortcuts && (isAutoConfigured || isMacDesktop); + patchClasses(rootEl, { - 'is-restart': isAutoConfigured, - 'is-warn': !isAutoConfigured, + 'is-restart': useRestartTheme, + 'is-warn': !useRestartTheme, }); - patchSvgIcon(headIconEl, isAutoConfigured ? 'refresh' : 'warning'); + patchSvgIcon(headIconEl, useRestartTheme ? 'refresh' : 'warning'); let titleText = ''; - if (isAutoConfigured) { + let bodyText = ''; + if (hasReadOnlyShortcuts) { + titleText = contextMode + ? t('settings.bridge.ctxReadOnlyTitle') + : t('settings.bridge.readOnlyTitle'); + bodyText = t('settings.bridge.readOnlyBody'); + } else if (isMacDesktop) { + titleText = contextMode + ? t('settings.bridge.ctxMacTitle') + : t('settings.bridge.macTitle'); + bodyText = t('settings.bridge.guideMac'); + } else if (isAutoConfigured) { titleText = contextMode ? t('settings.bridge.ctxRestartTitle') : t('settings.bridge.restartTitle'); - } else if (contextMode) { - titleText = t('settings.bridge.ctxTitle'); - } else if (state === 'cdp_unreachable') { - titleText = t('settings.bridge.unreachableTitle'); - } else { - titleText = t('settings.bridge.noPortTitle'); - } - - const plat = String(lastPayload.hostPlatform || '').trim().toLowerCase(); - let bodyText = ''; - if (isAutoConfigured) { bodyText = t('settings.bridge.restartBody'); - } else if (plat === 'darwin') { - bodyText = t('settings.bridge.guideMac'); - } else if (plat === 'linux') { - bodyText = t('settings.bridge.guideLinux'); } else { - bodyText = t('settings.bridge.guideWin'); + titleText = contextMode + ? t('settings.bridge.ctxTitle') + : state === 'cdp_unreachable' + ? t('settings.bridge.unreachableTitle') + : t('settings.bridge.noPortTitle'); + bodyText = plat === 'linux' ? t('settings.bridge.guideLinux') : t('settings.bridge.guideWin'); } patchText(titleEl, titleText); diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index f712f8b..7982e29 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -437,14 +437,20 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.str.mountSidebar': 'Sidebar Only', 'settings.bridge.restartTitle': 'Launch Flag Auto-Configured — Restart Once to Activate', 'settings.bridge.ctxRestartTitle': 'Launch Flag Auto-Configured — Restart Once for Context Override', - 'settings.bridge.restartBody': 'Automatically added --remote-debugging-port=0 to your shortcuts and startup entries (future launches mount 100% automatically). Click below to close tray processes and relaunch now.', + 'settings.bridge.restartBody': 'Automatically added --remote-debugging-port=0 to your shortcuts, startup entries, and protocol handlers (subsequent shortcut launches mount automatically). Click below to close background processes and relaunch now.', + 'settings.bridge.readOnlyTitle': 'Public Shortcut Protected — Authorize & Relaunch to Activate', + 'settings.bridge.ctxReadOnlyTitle': 'Public Shortcut Protected — Authorize & Relaunch for Context Override', + 'settings.bridge.readOnlyBody': 'Personal launch entries are configured, but public shortcuts require administrator permission. Click below and approve the system prompt to patch public shortcuts once and relaunch.', + 'settings.bridge.macTitle': 'Debug Port Inactive — One-Click Relaunch to Enable Mount', + 'settings.bridge.ctxMacTitle': 'Debug Port Inactive — One-Click Relaunch for Context Override', 'settings.bridge.noPortTitle': 'Local Debug Port Missing — Window Mount Inactive', 'settings.bridge.unreachableTitle': 'Local Debug Port Not Ready — Window Mount Inactive', 'settings.bridge.ctxTitle': 'Local Debug Port Inactive — Context Override Pending', 'settings.bridge.guideWin': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to auto-configure shortcuts, close tray background processes, and relaunch.', - 'settings.bridge.guideMac': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to relaunch with the flag in one click, or run open -a "Antigravity" --args --remote-debugging-port=0.', + 'settings.bridge.guideMac': 'Due to macOS app code signing, cold launches from Dock omit the debug port flag. Click below to relaunch with the flag in one click (stays active until you fully Quit via Cmd+Q).', 'settings.bridge.guideLinux': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to update your .desktop launcher and relaunch.', 'settings.bridge.relaunchBtn': 'Relaunch & Enable Mount', + 'settings.bridge.relaunchAuthBtn': 'Authorize & Relaunch', 'settings.bridge.relaunchingBtn': 'Relaunching Host...', 'settings.bridge.relaunchFailed': 'Auto-relaunch failed — quit from tray and retry', 'settings.bridge.dismissAria': 'Dismiss notice for now', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 206be74..d30607e 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -437,14 +437,20 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.str.mountSidebar': '仅侧边栏', 'settings.bridge.restartTitle': '已自动补齐启动参数,重启一次即可启用悬浮胶囊', 'settings.bridge.ctxRestartTitle': '已自动补齐启动参数,重启一次即可激活上下文覆写', - 'settings.bridge.restartBody': '已自动为桌面 / 开始菜单 / 任务栏快捷方式及自启项写入 --remote-debugging-port=0(后续每次正常打开均 100% 全自动挂载)。点击下方按钮即可退出托盘后台并立即生效。', + 'settings.bridge.restartBody': '已自动为快捷方式、自启项及协议关联写入 --remote-debugging-port=0(后续通过常规快捷方式打开均自动生效)。点击下方按钮即可退出后台进程并立即生效。', + 'settings.bridge.readOnlyTitle': '公共桌面快捷方式受权限保护,授权重启即可生效', + 'settings.bridge.ctxReadOnlyTitle': '公共桌面快捷方式受权限保护,授权重启即可激活上下文覆写', + 'settings.bridge.readOnlyBody': '个人启动项已配好,但公共桌面或开始菜单快捷方式需管理员权限修改。点击下方按钮并在系统弹窗中确认授权,即可一次性修补公共图标并带参重开(后续日常打开均自动生效)。', + 'settings.bridge.macTitle': '当前会话未开启调试端口,一键重开即可启用挂载', + 'settings.bridge.ctxMacTitle': '当前会话未开启调试端口,一键重开即可激活上下文覆写', 'settings.bridge.noPortTitle': '未检测到本地调试端口,主窗口挂载暂未生效', 'settings.bridge.unreachableTitle': '本地调试端口未就绪,主窗口挂载暂未生效', 'settings.bridge.ctxTitle': '未连通本地调试通道,上下文窗口覆写暂未注入', 'settings.bridge.guideWin': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可自动补齐快捷方式参数、退出托盘后台并带参重启生效。', - 'settings.bridge.guideMac': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可一键带参重开客户端生效,也可复制参数通过 open -a "Antigravity" --args --remote-debugging-port=0 启动。', + 'settings.bridge.guideMac': '受 macOS 应用签名限制,从 Dock 直接冷启动默认不带调试端口参数。点击下方按钮即可一键带参重开恢复(日常仅关窗不完全退出 Cmd+Q 则持续有效)。', 'settings.bridge.guideLinux': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可自动写入 .desktop 启动器并重启生效。', 'settings.bridge.relaunchBtn': '立即重启并启用挂载', + 'settings.bridge.relaunchAuthBtn': '授权修补并立即重启', 'settings.bridge.relaunchingBtn': '正在重启客户端...', 'settings.bridge.relaunchFailed': '自动重启失败,请从托盘退出后重试', 'settings.bridge.dismissAria': '暂时关闭提示', diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index a479c1f..45af999 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -25,9 +25,13 @@ import { buildWindowsRelaunchInnerScript, ensureDesktopLaunchEntriesConfigured, ensureRemoteDebugFlagInArgs, + inspectWindowsLnkBuffer, patchLinuxDesktopEntryText, patchWindowsRunRegistryCommand, + patchWindowsShellOpenCommand, + probeWindowsShortcutsFast, resolveDesktopHostExecutable, + resolveWindowsPowerShellExecutable, triggerDesktopHostRelaunch, } from '../backend/desktop-launcher-config.mjs'; import { @@ -4909,6 +4913,107 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi ); assert.equal(winRunIdeIgnored.matched, false); + // System32 PowerShell resolution & HKCU\Software\Classes shell\open\command patching + assert.equal( + resolveWindowsPowerShellExecutable( + { SystemRoot: 'D:\\WinSys' }, + (p) => p === 'D:\\WinSys\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' + ), + 'D:\\WinSys\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' + ); + assert.equal( + resolveWindowsPowerShellExecutable({ SystemRoot: 'D:\\Missing' }, () => false), + 'powershell.exe' + ); + + const shellOpenPatched = patchWindowsShellOpenCommand( + '"C:\\Users\\Dev\\AppData\\Local\\Programs\\Antigravity\\Antigravity.exe" -- "%1"', + { enabled: true } + ); + assert.equal(shellOpenPatched.matched, true); + assert.equal(shellOpenPatched.changed, true); + assert.equal( + shellOpenPatched.value, + '"C:\\Users\\Dev\\AppData\\Local\\Programs\\Antigravity\\Antigravity.exe" --remote-debugging-port=0 -- "%1"', + 'Inserts flag before -- "%1" so Chromium parses it as a switch' + ); + const shellOpenRollback = patchWindowsShellOpenCommand(shellOpenPatched.value, { enabled: false }); + assert.equal(shellOpenRollback.changed, true); + assert.equal( + shellOpenRollback.value, + '"C:\\Users\\Dev\\AppData\\Local\\Programs\\Antigravity\\Antigravity.exe" -- "%1"' + ); + assert.equal( + patchWindowsShellOpenCommand( + '"C:\\Users\\Dev\\AppData\\Local\\Programs\\Antigravity IDE\\Antigravity IDE.exe" "--open-url" "--" "%1"', + { enabled: true } + ).matched, + false + ); + + // Zero-subprocess binary .lnk inspection & non-recursive folder boundary verification + const makeFakeLnkBuf = (targetPath, argsStr = '') => + Buffer.concat([ + Buffer.alloc(76, 0x4c), + Buffer.from(`${targetPath}\0${argsStr}\0`, 'utf16le'), + ]); + assert.deepEqual( + inspectWindowsLnkBuffer( + makeFakeLnkBuf('C:\\App\\Antigravity.exe', '--remote-debugging-port=0') + ), + { matched: true, hasDebugPort: true } + ); + assert.deepEqual( + inspectWindowsLnkBuffer(makeFakeLnkBuf('C:\\App\\Antigravity IDE.exe', '')), + { matched: false, hasDebugPort: false } + ); + + const visitedDirs = []; + const fakeDesktopDir = 'C:\\Users\\Dev\\Desktop'; + const fakeProgramsDir = 'C:\\Users\\Dev\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs'; + const fakeAgySubDir = `${fakeProgramsDir}\\Antigravity`; + const fastProbeRes = probeWindowsShortcutsFast({ + env: { + USERPROFILE: 'C:\\Users\\Dev', + APPDATA: 'C:\\Users\\Dev\\AppData\\Roaming', + PUBLIC: 'C:\\Users\\Public', + ProgramData: 'C:\\ProgramData', + }, + homeDir: 'C:\\Users\\Dev', + fsOps: { + readdirFn: (dir) => { + visitedDirs.push(dir); + if (dir === fakeDesktopDir) { + return [ + { name: 'Antigravity.lnk', isFile: () => true, isDirectory: () => false }, + { name: 'huge-repo-with-node_modules', isFile: () => false, isDirectory: () => true }, + ]; + } + if (dir === fakeProgramsDir) { + return [ + { name: 'Visual Studio 2022', isFile: () => false, isDirectory: () => true }, + { name: 'Antigravity', isFile: () => false, isDirectory: () => true }, + ]; + } + if (dir === fakeAgySubDir) { + return [{ name: 'Antigravity IDE.lnk', isFile: () => true, isDirectory: () => false }]; + } + return []; + }, + statFn: () => ({ size: 512 }), + readFn: (p) => + p.endsWith('Antigravity IDE.lnk') + ? makeFakeLnkBuf('C:\\App\\Antigravity IDE.exe', '') + : makeFakeLnkBuf('C:\\App\\Antigravity.exe', '--remote-debugging-port=0'), + }, + }); + assert.equal(fastProbeRes.allConfigured, true); + assert.equal( + visitedDirs.some((d) => d.includes('huge-repo') || d.includes('Visual Studio')), + false, + 'Never recurses into Desktop subfolders or unrelated Start Menu vendor folders' + ); + const linuxDesktopRaw = [ '[Desktop Entry]', 'Name=Antigravity', @@ -4924,6 +5029,43 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi assert.equal(linuxReverted.changed, true); assert.equal(linuxReverted.text, linuxDesktopRaw); + const linuxAppImageRaw = [ + '[Desktop Entry]', + 'Name=Antigravity', + 'Exec=env DESKTOPINTEGRATION=false "/home/alice/Apps/Antigravity-2.33.0-x86_64.AppImage" %U', + 'Type=Application', + '', + ].join('\n'); + const linuxAppImagePatched = patchLinuxDesktopEntryText(linuxAppImageRaw, { enabled: true }); + assert.equal(linuxAppImagePatched.matched, true); + assert.equal(linuxAppImagePatched.changed, true); + assert.match( + linuxAppImagePatched.text, + /Exec=env DESKTOPINTEGRATION=false "\/home\/alice\/Apps\/Antigravity-2\.33\.0-x86_64\.AppImage" --remote-debugging-port=0 %U/ + ); + assert.equal( + patchLinuxDesktopEntryText(linuxAppImagePatched.text, { enabled: false }).text, + linuxAppImageRaw + ); + assert.equal( + patchLinuxDesktopEntryText('Exec=env FOO=1 /opt/antigravity-ide/antigravity-ide %F', { + enabled: true, + }).matched, + false + ); + + const resolvedLinuxAppImage = resolveDesktopHostExecutable({ + env: { + APPIMAGE: '/home/alice/Apps/Antigravity-2.33.0.AppImage', + ANTIGRAVITY_AGENTAPI_EXE: '/tmp/.mount_Antigr123/resources/bin/language_server_linux_x64', + }, + platform: 'linux', + homeDir: '/home/alice', + existsFn: (p) => p === '/home/alice/Apps/Antigravity-2.33.0.AppImage', + }); + assert.equal(resolvedLinuxAppImage.found, true); + assert.equal(resolvedLinuxAppImage.executablePath, '/home/alice/Apps/Antigravity-2.33.0.AppImage'); + // 3. Host executable resolution from ANTIGRAVITY_AGENTAPI_EXE & clean relaunch env sanitization const resolvedWinHost = resolveDesktopHostExecutable({ env: { @@ -5038,8 +5180,9 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi /--remote-debugging-port=0 %U/ ); - // Verify Windows shortcut auto-provisioning + stale port (`cdp_unreachable`) status reporting + clean rollback on disable + // Verify Windows shortcut auto-provisioning + read-only public shortcut tracking + periodic recheck + clean rollback const winPsCalls = []; + let simulateReadOnlyPublicDesktop = false; const mockWinExec = async (file, args, opts) => { winPsCalls.push({ file, args, env: opts?.env }); const enabledFlag = opts?.env?.AGY_LAUNCH_ENABLED === '1'; @@ -5051,6 +5194,10 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi configuredPaths: enabledFlag ? ['C:\\Users\\Admin\\Desktop\\Antigravity.lnk', 'C:\\TaskBar\\Antigravity.lnk'] : [], + readOnlyPaths: + enabledFlag && simulateReadOnlyPublicDesktop + ? ['C:\\Users\\Public\\Desktop\\Antigravity.lnk'] + : [], }); }; @@ -5069,6 +5216,7 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi homeDir, leaseFilePath: leaseFile, autoConfigureIdeArgv: true, + launcherRecheckIntervalMs: 25, launcherExecFileFn: mockWinExec, allowDesktopLauncherInTest: true, }); @@ -5079,10 +5227,18 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi assert.equal(stWin.state, 'cdp_unreachable'); assert.equal(stWin.argvUpdatedThisBoot, true); assert.equal(stWin.launcherConfigured, true); + assert.equal(stWin.hasReadOnlyShortcuts, false); assert.equal(stWin.canRelaunch, true); assert.equal(winPsCalls.length, 1); assert.equal(winPsCalls[0].env.AGY_LAUNCH_ENABLED, '1'); + // Periodic re-check after cooldown detects NSIS installer-wiped or read-only public shortcuts + simulateReadOnlyPublicDesktop = true; + await new Promise((r) => setTimeout(r, 35)); + await ctrlWin.syncAllWindows(); + assert.equal(winPsCalls.length, 2, 'Re-provisions automatically once cooldown interval elapses'); + assert.equal(ctrlWin.getBridgeStatus().hasReadOnlyShortcuts, true); + // Disabling overlay (Sidebar Only) cleanly triggers shortcut flag rollback currentMountSettings = { windowMountMode: 'sidebar', @@ -5091,8 +5247,9 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi }; await ctrlWin.notifySettingChanged(false); await new Promise((r) => setTimeout(r, 10)); - assert.equal(winPsCalls.length, 2); - assert.equal(winPsCalls[1].env.AGY_LAUNCH_ENABLED, '0'); + assert.equal(winPsCalls.length, 3); + assert.equal(winPsCalls[2].env.AGY_LAUNCH_ENABLED, '0'); + assert.equal(ctrlWin.getBridgeStatus().hasReadOnlyShortcuts, false); await ctrlWin.stop(); // Verify Windows out-of-job Shell.Application relaunch payload (.ps1 file with UTF-8 BOM) & macOS open -a relaunch @@ -5159,10 +5316,35 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi assert.equal(macSpawnArgs.env.AGY_RELAUNCH_APP, '/Applications/Antigravity.app'); assert.match(macSpawnArgs.args[1], /open -a "\$AGY_RELAUNCH_APP" --args --remote-debugging-port=0/); - // Explicit ANTIGRAVITY_DEVTOOLS_PORT fallback still works seamlessly - const innerScriptCheck = buildWindowsRelaunchInnerScript(fakeExe, [stalePortFile], 'desktop'); + // Verify Linux /proc dynamic AppImage discovery & multi-comm pkill handling + let linuxSpawnArgs = null; + const relaunchLinuxRes = await triggerDesktopHostRelaunch({ + env: { PATH: '/usr/bin:/bin' }, + platform: 'linux', + homeDir: '/home/alice', + stalePortFiles: ['/home/alice/.config/Antigravity/DevToolsActivePort'], + allowInTest: true, + existsFn: () => false, + execFileFn: async () => '/home/alice/Apps/Antigravity-2.33.0.AppImage\n', + spawnFn: async (file, args, opts) => { + linuxSpawnArgs = { file, args, env: opts?.env }; + return { pid: 5678 }; + }, + }); + assert.equal(relaunchLinuxRes.ok, true); + assert.equal(linuxSpawnArgs.env.AGY_RELAUNCH_EXE, '/home/alice/Apps/Antigravity-2.33.0.AppImage'); + assert.match(linuxSpawnArgs.args[1], /for pn in "\$AGY_PROC_NAME" antigravity Antigravity/); + + // Explicit ANTIGRAVITY_DEVTOOLS_PORT fallback & UAC read-only shortcut + de-elevation script generation + const innerScriptCheck = buildWindowsRelaunchInnerScript(fakeExe, [stalePortFile], 'desktop', { + readOnlyShortcutPaths: ['C:\\Users\\Public\\Desktop\\Antigravity.lnk'], + psExePath: 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', + }); assert.match(innerScriptCheck, /CloseMainWindow/); assert.match(innerScriptCheck, /Stop-Process/); + assert.match(innerScriptCheck, /-Verb RunAs/); + assert.match(innerScriptCheck, /C:\\Users\\Public\\Desktop\\Antigravity\.lnk/); + assert.match(innerScriptCheck, /\$isSelfElevated -and -not \$wasHostElevated/); } finally { fs.rmSync(simTmp, { recursive: true, force: true }); } @@ -5251,7 +5433,23 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi ); assert.match(strTab.refs.mountBridgeNotice.refs.relaunchBtnEl.textContent, /正在重启客户端/); - // macOS unconfigured state -> `.is-warn` with 1-click relaunch + copy button + // All-Users read-only Public Desktop shortcut -> `.is-warn` + UAC authorization button copy + strTab.refs.renderSettings( + { windowMountMode: 'dual', enableWindowOverlay: true }, + { + state: 'no_devtools_port', + argvUpdatedThisBoot: true, + argvConfigured: true, + launcherConfigured: true, + hasReadOnlyShortcuts: true, + canRelaunch: true, + }, + 'win32' + ); + assert.equal(noticeEl.classList.contains('is-warn'), true); + assert.match(noticeEl.textContent, /公共桌面快捷方式受权限保护/); + + // macOS Desktop -> honest code-signing notice with `.is-restart` + 1-click relaunch + copy button strTab.refs.renderSettings( { windowMountMode: 'dual', enableWindowOverlay: true }, { @@ -5259,12 +5457,13 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi argvUpdatedThisBoot: false, argvConfigured: false, launcherConfigured: false, + hasReadOnlyShortcuts: false, canRelaunch: true, }, 'darwin' ); - assert.equal(noticeEl.classList.contains('is-warn'), true); - assert.match(noticeEl.textContent, /open -a "Antigravity" --args --remote-debugging-port=0/); + assert.equal(noticeEl.classList.contains('is-restart'), true); + assert.match(noticeEl.textContent, /macOS 应用签名限制/); strTab.refs.mountBridgeNotice.refs.copyBtnEl.dispatchEvent({ type: 'click' }); await new Promise((r) => setTimeout(r, 0)); @@ -5275,10 +5474,16 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi const globalBanner = BridgeStatusNotice({ dismissible: true }); globalBanner.refs.update({ visible: true, - windowBridge: { state: 'no_devtools_port', launcherConfigured: true, canRelaunch: true }, + windowBridge: { + state: 'no_devtools_port', + launcherConfigured: true, + hasReadOnlyShortcuts: true, + canRelaunch: true, + }, hostPlatform: 'win32', }); assert.equal(globalBanner.el.hasAttribute('hidden'), false); + assert.match(globalBanner.refs.relaunchBtnEl.textContent, /授权修补并立即重启/); globalBanner.refs.dismissBtnEl.dispatchEvent({ type: 'click' }); assert.equal(globalBanner.el.hasAttribute('hidden'), true); globalBanner.refs.update({ @@ -5293,10 +5498,21 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi }); assert.equal(globalBanner.el.hasAttribute('hidden'), false, 'Re-armed after active cycle'); - // English localization check + // English localization check across macOS & read-only shortcut states setI18nLanguage('en-US'); strTab.refs.refreshLabels(); - assert.match(noticeEl.textContent, /Local Debug Port Missing/); + assert.match(noticeEl.textContent, /Due to macOS app code signing/); + globalBanner.refs.update({ + visible: true, + windowBridge: { + state: 'no_devtools_port', + launcherConfigured: true, + hasReadOnlyShortcuts: true, + canRelaunch: true, + }, + hostPlatform: 'win32', + }); + assert.match(globalBanner.refs.relaunchBtnEl.textContent, /Authorize & Relaunch/); // Switching to Sidebar Only hides notice immediately strTab.refs.renderSettings(