diff --git a/sidecars/panel/backend/desktop-launcher-config.mjs b/sidecars/panel/backend/desktop-launcher-config.mjs index 9041b10..8ad0004 100644 --- a/sidecars/panel/backend/desktop-launcher-config.mjs +++ b/sidecars/panel/backend/desktop-launcher-config.mjs @@ -199,7 +199,13 @@ export function patchWindowsShellOpenCommand(rawValue, { enabled = true } = {}) function isLinuxAntigravityDesktopLeaf(leaf) { const lower = String(leaf || '').trim().toLowerCase(); if (!lower || lower.includes('ide')) return false; - return /^antigravity(?:$|[-_.\d]|(?:\.appimage$))/i.test(lower); + return /^(?:google[-_])?antigravity(?:$|[-_.\d]|(?:\.appimage$))/i.test(lower); +} + +function isWindowsVendorSubdirName(dirName) { + const lower = String(dirName || '').trim().toLowerCase(); + if (!lower) return false; + return lower.includes('antigravity') || /^google(?:\b|[\s_-]|$)/i.test(lower); } function splitLinuxExecTokens(cmdBody) { @@ -254,7 +260,17 @@ export function patchLinuxDesktopEntryText(rawText, { enabled = true } = {}) { binIdx = 1; while (binIdx < tokens.length) { const unquoted = stripOuterQuotes(tokens[binIdx].raw); - if (unquoted === '-S' || /^[A-Za-z_][A-Za-z0-9_]*=/.test(unquoted)) { + if (unquoted === '-u' || unquoted === '--unset') { + binIdx += 2; + continue; + } + if ( + unquoted === '-S' || + unquoted === '-i' || + unquoted === '--ignore-environment' || + unquoted.startsWith('--unset=') || + /^[A-Za-z_][A-Za-z0-9_]*=/.test(unquoted) + ) { binIdx += 1; continue; } @@ -280,6 +296,15 @@ export function patchLinuxDesktopEntryText(rawText, { enabled = true } = {}) { } configured = true; changed = true; + const doubleDashMatch = rest.match(/^(.*?)(?:^|\s)(--(?:\s+.*)?)$/); + if (doubleDashMatch) { + const beforeDash = doubleDashMatch[1].trim(); + const fromDash = doubleDashMatch[2].trim(); + const mid = beforeDash + ? `${beforeDash} ${REMOTE_DEBUG_LAUNCH_FLAG}` + : REMOTE_DEBUG_LAUNCH_FLAG; + return `${prefix}${headThroughExe} ${mid} ${fromDash}`; + } const fieldCodeMatch = rest.match(/^(.*?)\s*(%[fFuUdDnNickvm](?:\s+%[fFuUdDnNickvm])*)\s*$/); if (fieldCodeMatch) { const beforeCodes = fieldCodeMatch[1].trim(); @@ -309,8 +334,24 @@ export function patchLinuxDesktopEntryText(rawText, { enabled = true } = {}) { }; } +function stripAppImageMountPathEntries(rawVal, { omitIfEmpty = false } = {}) { + const str = String(rawVal ?? ''); + if (!str || !str.includes('/.mount_')) { + return str; + } + const parts = str.split(':').filter((entry) => { + const trimmed = entry.trim(); + return trimmed && !trimmed.startsWith('/tmp/.mount_') && !trimmed.includes('/.mount_'); + }); + if (parts.length === 0 && omitIfEmpty) { + return null; + } + return parts.join(':'); +} + /** * 清理 Sidecar / MCP 子进程继承的宿主会话私有环境变量,确保重拉后的客户端运行于纯净桌面上下文。 + * 同时剔除 Linux AppImage 挂载期注入的临时变量与 `/tmp/.mount_*` 路径,防止旧挂载卸载后新进程加载失败。 * * @param {Record} [baseEnv=process.env] * @returns {Record} @@ -320,12 +361,26 @@ export function buildSanitizedDesktopRelaunchEnv(baseEnv = process.env) { for (const [key, val] of Object.entries(baseEnv || {})) { if (val === undefined || val === null) continue; if ( - /^(?:ANTIGRAVITY_|CHROME_DEVTOOLS_MCP_|USAGE_MONITOR_|ELECTRON_RUN_AS_NODE$|NODE_OPTIONS$)/i.test( + /^(?:ANTIGRAVITY_|CHROME_DEVTOOLS_MCP_|USAGE_MONITOR_|ELECTRON_RUN_AS_NODE$|NODE_OPTIONS$|APPIMAGE$|APPDIR$|OWD$|ARGV0$|APPIMAGE_EXTRACT_AND_RUN$)/i.test( key ) ) { continue; } + if (key === 'LD_LIBRARY_PATH') { + const cleanedLib = stripAppImageMountPathEntries(val, { omitIfEmpty: true }); + if (cleanedLib !== null) { + clean[key] = cleanedLib; + } + continue; + } + if (key === 'PATH' && String(val).includes('/.mount_')) { + const cleanedPath = stripAppImageMountPathEntries(val, { omitIfEmpty: false }); + if (cleanedPath) { + clean[key] = cleanedPath; + } + continue; + } clean[key] = String(val); } return clean; @@ -440,9 +495,11 @@ export function resolveDesktopHostExecutable({ if (platform === 'win32') { const localAppData = env?.LOCALAPPDATA || join(homeDir, 'AppData', 'Local'); const programFiles = env?.ProgramFiles || 'C:\\Program Files'; + const programFilesX86 = String(env?.['ProgramFiles(x86)'] || '').trim(); const winCandidates = [ join(localAppData, 'Programs', 'Antigravity', 'Antigravity.exe'), join(programFiles, 'Antigravity', 'Antigravity.exe'), + ...(programFilesX86 ? [join(programFilesX86, 'Antigravity', 'Antigravity.exe')] : []), join(localAppData, 'Antigravity', 'Antigravity.exe'), ]; for (const cand of winCandidates) { @@ -469,9 +526,12 @@ export function resolveDesktopHostExecutable({ } else { const linuxCandidates = [ '/opt/Antigravity/antigravity', + '/opt/Antigravity/Antigravity', '/opt/antigravity/antigravity', '/usr/share/antigravity/antigravity', '/usr/bin/antigravity', + '/usr/bin/google-antigravity', + '/usr/local/bin/antigravity', join(homeDir, '.local', 'bin', 'antigravity'), ]; for (const cand of linuxCandidates) { @@ -577,11 +637,12 @@ export function inspectWindowsLnkBuffer(buf) { /** * 纯 Node.js 零子进程快速扫描当前机器上的 `Antigravity.exe` 快捷方式配置状态(耗时通常 `< 2ms`)。 - * 桌面与任务栏严格仅扫描顶层 `.lnk`(绝不进入用户项目文件夹或 `node_modules`),开始菜单仅检查顶层及 `Antigravity*` 一级子目录。 + * 桌面与任务栏严格仅扫描顶层 `.lnk`(绝不进入用户项目文件夹或 `node_modules`),开始菜单仅检查顶层及 Antigravity/Google 一级厂商子目录。 * * @param {{ * env?: Record, * homeDir?: string, + * extraDirs?: string[], * fsOps?: { * readdirFn?: typeof readdirSync, * statFn?: typeof statSync, @@ -592,6 +653,7 @@ export function inspectWindowsLnkBuffer(buf) { export function probeWindowsShortcutsFast({ env = process.env, homeDir = homedir(), + extraDirs = [], fsOps = null, } = {}) { const readdirFn = fsOps?.readdirFn || readdirSync; @@ -605,6 +667,12 @@ export function probeWindowsShortcutsFast({ const programData = String(env?.ProgramData || 'C:\\ProgramData').trim(); const flatDirs = []; + if (Array.isArray(extraDirs)) { + for (const d of extraDirs) { + const clean = String(d || '').trim(); + if (clean) flatDirs.push(clean); + } + } if (userProfile) { flatDirs.push(pathWin32.join(userProfile, 'Desktop'), pathWin32.join(userProfile, zhDesktop)); } @@ -637,7 +705,7 @@ export function probeWindowsShortcutsFast({ const candidateLnks = []; const seenLnks = new Set(); - const collectTopLevelLnks = (dirPath, expandAntigravitySubdirs = false) => { + const collectTopLevelLnks = (dirPath, expandVendorSubdirs = false) => { if (!dirPath) return; const normDir = dirPath.toLowerCase(); if (seenDirs.has(normDir)) return; @@ -659,9 +727,9 @@ export function probeWindowsShortcutsFast({ candidateLnks.push(full); } } else if ( - expandAntigravitySubdirs && + expandVendorSubdirs && ent.isDirectory?.() && - name.toLowerCase().startsWith('antigravity') + isWindowsVendorSubdirName(name) ) { collectTopLevelLnks(pathWin32.join(dirPath, name), false); } @@ -708,52 +776,59 @@ $enableFlag = $env:AGY_LAUNCH_ENABLED -eq '1' $updated = New-Object System.Collections.Generic.List[string] $configured = New-Object System.Collections.Generic.List[string] $readOnly = New-Object System.Collections.Generic.List[string] +$discoveredDirs = New-Object System.Collections.Generic.List[string] $ws = $null +$userDesktopDir = [Environment]::GetFolderPath('Desktop') +$commonDesktopDir = [Environment]::GetFolderPath('CommonDesktopDirectory') $userProgramsDir = [Environment]::GetFolderPath('Programs') +$commonProgramsDir = [Environment]::GetFolderPath('CommonPrograms') +$userStartupDir = [Environment]::GetFolderPath('Startup') $zhDesktop = ([string][char]0x684C + [string][char]0x9762) $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) { +function Add-ScanDir([string]$dirPath, [bool]$isCommon, [string]$kind, [bool]$expandVendorSubdir, [bool]$recordDiscovered) { 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 ($recordDiscovered) { $discoveredDirs.Add($dirPath) } 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)) { + foreach ($sub in @(Get-ChildItem -LiteralPath $dirPath -Directory -ErrorAction SilentlyContinue)) { + if ($sub -and $sub.Name -and ($sub.Name -match '(?i)antigravity|^google(?:\\b|[\\s_-]|$)') -and $sub.FullName -and $seenScanDir.Add([string]$sub.FullName)) { $flatSpecs.Add(@{ Dir = [string]$sub.FullName; IsCommon = $isCommon; Kind = $kind }) + if ($recordDiscovered) { $discoveredDirs.Add([string]$sub.FullName) } } } } catch {} } } +Add-ScanDir $userDesktopDir $false 'desktop' $false $true 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 + Add-ScanDir $d $false 'desktop' $false $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 (Join-Path $od 'Desktop') $false 'desktop' $false $false + Add-ScanDir (Join-Path $od $zhDesktop) $false 'desktop' $false $false } } -Add-ScanDir $userProgramsDir $false 'programs' $true -Add-ScanDir ([Environment]::GetFolderPath('StartMenu')) $false 'startmenu' $false -Add-ScanDir ([Environment]::GetFolderPath('Startup')) $false 'startup' $false +Add-ScanDir $userProgramsDir $false 'programs' $true $true +Add-ScanDir ([Environment]::GetFolderPath('StartMenu')) $false 'startmenu' $false $false +Add-ScanDir $userStartupDir $false 'startup' $false $true if ($env:APPDATA) { - Add-ScanDir (Join-Path $env:APPDATA 'Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar') $false 'taskbar' $false + Add-ScanDir (Join-Path $env:APPDATA 'Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar') $false 'taskbar' $false $false } -Add-ScanDir ([Environment]::GetFolderPath('CommonDesktopDirectory')) $true 'desktop' $false -Add-ScanDir ([Environment]::GetFolderPath('CommonPrograms')) $true 'programs' $true +Add-ScanDir $commonDesktopDir $true 'desktop' $false $true +Add-ScanDir $commonProgramsDir $true 'programs' $true $true $seen = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase) foreach ($spec in $flatSpecs) { @@ -829,14 +904,19 @@ foreach ($spec in $flatSpecs) { } } -$runSubPath = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run' -try { - $runReadKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($runSubPath, $false) - if ($runReadKey) { +$runTargets = @( + @{ Root = [Microsoft.Win32.Registry]::CurrentUser; Label = 'HKCU'; SubPath = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run' }, + @{ Root = [Microsoft.Win32.Registry]::LocalMachine; Label = 'HKLM'; SubPath = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run' }, + @{ Root = [Microsoft.Win32.Registry]::LocalMachine; Label = 'HKLM'; SubPath = 'Software\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Run' } +) +foreach ($rt in $runTargets) { + try { + $runReadKey = $rt.Root.OpenSubKey($rt.SubPath, $false) + if (-not $runReadKey) { continue } $runNames = @($runReadKey.GetValueNames()) $runReadKey.Close() foreach ($valName in $runNames) { - $rk = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($runSubPath, $false) + $rk = $rt.Root.OpenSubKey($rt.SubPath, $false) if (-not $rk) { continue } $rawCmd = [string]$rk.GetValue($valName, '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) $rk.Close() @@ -846,94 +926,125 @@ try { $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 } + $entryId = if ($rt.Label -eq 'HKLM') { "HKLM:Run:$($rt.SubPath)|$valName" } else { "HKCU:Run:$valName" } if ($enableFlag) { if ($restPart -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { - $configured.Add("HKCU:Run:$valName") + $configured.Add($entryId) continue } $nextRest = ($restPart.Trim() + ' --remote-debugging-port=0').Trim() $nextVal = "$quotedExe $nextRest" + $saved = $false try { - $wk = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($runSubPath, $true) + $wk = $rt.Root.OpenSubKey($rt.SubPath, $true) if ($wk) { $wk.SetValue($valName, $nextVal, [Microsoft.Win32.RegistryValueKind]::String) $wk.Close() - $updated.Add("HKCU:Run:$valName") - $configured.Add("HKCU:Run:$valName") + $saved = $true } } catch {} + if ($saved) { + $updated.Add($entryId) + $configured.Add($entryId) + } elseif ($rt.Label -eq 'HKLM') { + $readOnly.Add($entryId) + } } 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()) { + $saved = $false try { - $wk = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($runSubPath, $true) + $wk = $rt.Root.OpenSubKey($rt.SubPath, $true) if ($wk) { $wk.SetValue($valName, $nextVal, [Microsoft.Win32.RegistryValueKind]::String) $wk.Close() - $updated.Add("HKCU:Run:$valName") + $saved = $true } } catch {} + if ($saved) { + $updated.Add($entryId) + } elseif ($rt.Label -eq 'HKLM') { + $readOnly.Add($entryId) + } } if ($strippedRest -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { - $configured.Add("HKCU:Run:$valName") + $configured.Add($entryId) } } } - } -} catch {} + } 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) +$classRoots = @( + @{ Root = [Microsoft.Win32.Registry]::CurrentUser; Label = 'HKCU'; FullPrefix = 'HKEY_CURRENT_USER' }, + @{ Root = [Microsoft.Win32.Registry]::LocalMachine; Label = 'HKLM'; FullPrefix = 'HKEY_LOCAL_MACHINE' } +) +foreach ($cr in $classRoots) { + foreach ($relSubKey in $exactClassSubKeys) { + try { + $rOpen = $cr.Root.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 = if ($cr.Label -eq 'HKLM') { "HKLM:Class:$relSubKey" } else { "$($cr.FullPrefix)\\$relSubKey" } + if ($enableFlag) { + if ($restOpen -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { $configured.Add($fullKeyName) + continue } - } 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()) { + $nextOpen = if ($restOpen) { "$quotedOpenExe --remote-debugging-port=0 $restOpen" } else { "$quotedOpenExe --remote-debugging-port=0" } + $saved = $false try { - $wOpen = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($relSubKey, $true) + $wOpen = $cr.Root.OpenSubKey($relSubKey, $true) if ($wOpen) { $wOpen.SetValue('', $nextOpen, [Microsoft.Win32.RegistryValueKind]::String) $wOpen.Close() - $updated.Add($fullKeyName) + $saved = $true } } catch {} + if ($saved) { + $updated.Add($fullKeyName) + $configured.Add($fullKeyName) + } elseif ($cr.Label -eq 'HKLM') { + $readOnly.Add($fullKeyName) + } + } 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()) { + $saved = $false + try { + $wOpen = $cr.Root.OpenSubKey($relSubKey, $true) + if ($wOpen) { + $wOpen.SetValue('', $nextOpen, [Microsoft.Win32.RegistryValueKind]::String) + $wOpen.Close() + $saved = $true + } + } catch {} + if ($saved) { + $updated.Add($fullKeyName) + } elseif ($cr.Label -eq 'HKLM') { + $readOnly.Add($fullKeyName) + } + } + if ($strippedOpen -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { + $configured.Add($fullKeyName) + } } - if ($strippedOpen -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { - $configured.Add($fullKeyName) - } - } - } catch {} + } catch {} + } } [pscustomobject]@{ @@ -941,9 +1052,80 @@ foreach ($relSubKey in $exactClassSubKeys) { updatedPaths = @($updated) configuredPaths = @($configured) readOnlyPaths = @($readOnly) + discoveredDirs = @($discoveredDirs) } | ConvertTo-Json -Compress `.trim(); +const cachedDiscoveredWinDirsByHome = new Map(); + +function getCachedWinDiscoveredDirs(homeDir) { + const key = String(homeDir || '').trim().toLowerCase(); + return cachedDiscoveredWinDirsByHome.get(key) || []; +} + +function rememberWinDiscoveredDirs(homeDir, dirs) { + if (!Array.isArray(dirs) || dirs.length === 0) return; + const key = String(homeDir || '').trim().toLowerCase(); + const seen = new Set(); + const list = []; + for (const d of dirs) { + const clean = String(d || '').trim(); + if (!clean) continue; + const norm = clean.toLowerCase(); + if (!seen.has(norm)) { + seen.add(norm); + list.push(clean); + } + } + if (list.length > 0) { + cachedDiscoveredWinDirsByHome.set(key, list); + } +} + +function collectLinuxDesktopCandidates(dirPath, ops, { filterByName = false, fallbackNames = [] } = {}) { + const files = []; + const seen = new Set(); + const joinDir = (name) => + dirPath.startsWith('/') + ? `${dirPath.replace(/\/+$/, '')}/${name}` + : join(dirPath, name); + const addName = (name) => { + const clean = String(name || '').trim(); + if (!clean || !clean.toLowerCase().endsWith('.desktop')) return; + if (filterByName && !clean.toLowerCase().includes('antigravity')) return; + const full = joinDir(clean); + if (!seen.has(full)) { + seen.add(full); + files.push({ name: clean, full }); + } + }; + + try { + const rawEntries = ops.readdirFn(dirPath); + if (Array.isArray(rawEntries)) { + let count = 0; + for (const entry of rawEntries) { + const name = typeof entry === 'string' ? entry : String(entry?.name || ''); + if (!name || !name.toLowerCase().endsWith('.desktop')) continue; + count += 1; + if (count > 256) break; + addName(name); + } + } + } catch { + // 目录不存在或无读取权限时退回显式候选探测 + } + + for (const fallback of fallbackNames) { + const full = joinDir(fallback); + if (!seen.has(full) && ops.existsFn(full)) { + seen.add(full); + files.push({ name: fallback, full }); + } + } + return files; +} + /** * 自动同步当前系统下用户空间启动入口(Windows `.lnk` / `HKCU:Run` / `HKCU:Classes`、Linux `.desktop`)中的 `--remote-debugging-port=0`。 * @@ -1005,7 +1187,12 @@ export async function ensureDesktopLaunchEntriesConfigured({ if (platform === 'win32') { // 稳态零子进程快检:当调试端口已活跃或处于周期复检且所有 `.lnk` 字节内均已含参数时,直接返回(<2ms,不拉起 PowerShell) if (!execFileFn && fastCheckIfActive) { - const fast = probeWindowsShortcutsFast({ env, homeDir, fsOps: ops }); + const fast = probeWindowsShortcutsFast({ + env, + homeDir, + extraDirs: getCachedWinDiscoveredDirs(homeDir), + fsOps: ops, + }); if (enabled && fast.allConfigured) { return { checked: true, @@ -1060,6 +1247,9 @@ export async function ensureDesktopLaunchEntriesConfigured({ const readOnlyPaths = Array.isArray(parsed?.readOnlyPaths) ? parsed.readOnlyPaths.map(String).filter(Boolean) : []; + if (Array.isArray(parsed?.discoveredDirs) && parsed.discoveredDirs.length > 0) { + rememberWinDiscoveredDirs(homeDir, parsed.discoveredDirs); + } const hasReadOnlyShortcuts = enabled && readOnlyPaths.length > 0; return { checked: true, @@ -1090,46 +1280,116 @@ export async function ensureDesktopLaunchEntriesConfigured({ if (platform === 'linux') { const dataHome = env?.XDG_DATA_HOME || join(homeDir, '.local', 'share'); const configHome = env?.XDG_CONFIG_HOME || join(homeDir, '.config'); - const userDesktopFile = join(dataHome, 'applications', 'antigravity.desktop'); - const systemDesktopFiles = [ - '/usr/share/applications/antigravity.desktop', - '/usr/local/share/applications/antigravity.desktop', - ]; - const autostartDesktopFile = join(configHome, 'autostart', 'antigravity.desktop'); + const userAppsDir = join(dataHome, 'applications'); + const userAutostartDir = join(configHome, 'autostart'); + const systemAppsDirs = []; + const seenSysDirs = new Set([userAppsDir]); + const addSysAppsDir = (d) => { + const clean = String(d || '').trim(); + if (!clean || seenSysDirs.has(clean)) return; + seenSysDirs.add(clean); + systemAppsDirs.push(clean); + }; + addSysAppsDir('/usr/share/applications'); + addSysAppsDir('/usr/local/share/applications'); + const rawDataDirs = String(env?.XDG_DATA_DIRS || '').trim(); + if (rawDataDirs) { + const dataDirParts = /^[A-Za-z]:[\\/]/.test(rawDataDirs) + ? rawDataDirs.split(';') + : rawDataDirs.split(':'); + for (const base of dataDirParts) { + const cleanBase = base.trim(); + if (cleanBase) { + addSysAppsDir( + cleanBase.startsWith('/') + ? `${cleanBase.replace(/\/+$/, '')}/applications` + : join(cleanBase, 'applications') + ); + } + } + } const updatedPaths = []; const configuredPaths = []; + const handledUserFileNames = new Set(); + + const readDesktopTextSafe = (filePath) => { + try { + const st = ops.statFn(filePath); + if (st && Number(st.size) > 65536) return ''; + } catch { + // 允许单测 mock 仅实现 existsFn/readFn 而不提供 statFn + } + try { + return String(ops.readFn(filePath, 'utf8') || ''); + } catch { + return ''; + } + }; try { - let baseUserText = ''; - if (ops.existsFn(userDesktopFile)) { - baseUserText = String(ops.readFn(userDesktopFile, 'utf8') || ''); - } else if (enabled) { - const sysSource = systemDesktopFiles.find((p) => ops.existsFn(p)); - if (sysSource) { - baseUserText = String(ops.readFn(sysSource, 'utf8') || ''); - } - } - if (baseUserText) { - const patched = patchLinuxDesktopEntryText(baseUserText, { enabled }); + const userCandidates = collectLinuxDesktopCandidates(userAppsDir, ops, { + filterByName: false, + fallbackNames: ['antigravity.desktop'], + }); + for (const cand of userCandidates) { + const rawText = readDesktopTextSafe(cand.full); + if (!rawText) continue; + const patched = patchLinuxDesktopEntryText(rawText, { enabled }); + if (!patched.matched) continue; + handledUserFileNames.add(cand.name.toLowerCase()); if (patched.changed) { - writeTextFileAtomically(userDesktopFile, patched.text, ops); - updatedPaths.push(userDesktopFile); + writeTextFileAtomically(cand.full, patched.text, ops); + updatedPaths.push(cand.full); } if (patched.configured) { - configuredPaths.push(userDesktopFile); + configuredPaths.push(cand.full); } } - if (ops.existsFn(autostartDesktopFile)) { - const autoRaw = String(ops.readFn(autostartDesktopFile, 'utf8') || ''); + if (enabled) { + for (const sysDir of systemAppsDirs) { + const sysCandidates = collectLinuxDesktopCandidates(sysDir, ops, { + filterByName: true, + fallbackNames: ['antigravity.desktop'], + }); + for (const cand of sysCandidates) { + const nameKey = cand.name.toLowerCase(); + if (handledUserFileNames.has(nameKey)) continue; + const rawText = readDesktopTextSafe(cand.full); + if (!rawText) continue; + const patched = patchLinuxDesktopEntryText(rawText, { enabled: true }); + if (!patched.matched) continue; + handledUserFileNames.add(nameKey); + if (patched.changed) { + const targetUserFile = join(userAppsDir, cand.name); + writeTextFileAtomically(targetUserFile, patched.text, ops); + updatedPaths.push(targetUserFile); + if (patched.configured) { + configuredPaths.push(targetUserFile); + } + } else if (patched.configured) { + configuredPaths.push(cand.full); + } + } + } + } + + const autostartCandidates = collectLinuxDesktopCandidates(userAutostartDir, ops, { + filterByName: false, + fallbackNames: ['antigravity.desktop'], + }); + for (const cand of autostartCandidates) { + const autoRaw = readDesktopTextSafe(cand.full); + if (!autoRaw) continue; const patchedAuto = patchLinuxDesktopEntryText(autoRaw, { enabled }); + if (!patchedAuto.matched) continue; if (patchedAuto.changed) { - writeTextFileAtomically(autostartDesktopFile, patchedAuto.text, ops); - updatedPaths.push(autostartDesktopFile); + writeTextFileAtomically(cand.full, patchedAuto.text, ops); + updatedPaths.push(cand.full); } if (patchedAuto.configured) { - configuredPaths.push(autostartDesktopFile); + configuredPaths.push(cand.full); } } @@ -1221,13 +1481,33 @@ async function discoverRunningHostExecutable({ if (bundlePath && /\.app$/i.test(bundlePath)) { return { found: true, - kind: 'desktop', + kind: /antigravity\s*ide\.app$/i.test(bundlePath) ? 'ide' : 'desktop', executablePath: bundlePath, appBundlePath: bundlePath, }; } } catch { - // 忽略 AppleScript 探测异常 + // 忽略 AppleScript 探测异常(例如 TCC 限制),回退无权限依赖的 ps 扫描 + } + try { + const psOut = await runner('ps', ['-axo', 'comm='], { timeoutMs: 3000 }); + for (const rawLine of String(psOut || '').split(/\r?\n/)) { + const line = rawLine.trim(); + const m = line.match(/^(\/.+?\.app)\/Contents\/MacOS\/([^/]+)$/i); + if (!m) continue; + const bundlePath = m[1]; + const binLeaf = m[2]; + if (!/antigravity/i.test(bundlePath) && !/antigravity/i.test(binLeaf)) continue; + if (/helper/i.test(binLeaf)) continue; + return { + found: true, + kind: /antigravity\s*ide\.app$/i.test(bundlePath) ? 'ide' : 'desktop', + executablePath: line, + appBundlePath: bundlePath, + }; + } + } catch { + // 忽略 ps 探测异常 } } else if (platform === 'linux') { if (!execFileFn && typeof process.getuid === 'function') { @@ -1239,7 +1519,9 @@ async function discoverRunningHostExecutable({ try { const st = statSync(procDir); if (st.uid !== myUid) continue; - const exeTarget = String(readlinkSync(`${procDir}/exe`) || '').trim(); + const exeTarget = String(readlinkSync(`${procDir}/exe`) || '') + .trim() + .replace(/\s+\(deleted\)$/, ''); if (!exeTarget) continue; const leaf = basename(exeTarget); if (!isLinuxAntigravityDesktopLeaf(leaf)) continue; @@ -1328,13 +1610,14 @@ export function buildWindowsRelaunchInnerScript( .join(', '); return ` +param([string]$HostElevated = '0') 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' +$wasHostElevated = ($HostElevated -eq '1') -or ($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 @@ -1345,20 +1628,67 @@ if (-not $exe -or -not (Test-Path -LiteralPath $exe)) { 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 } + $ws = $null + foreach ($item in $paths) { + if (-not $item) { continue } + if ($item.StartsWith('HKLM:Run:')) { 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() + $restKey = $item.Substring(9) + $sepIdx = $restKey.IndexOf('|') + if ($sepIdx -gt 0) { + $subPath = $restKey.Substring(0, $sepIdx) + $valName = $restKey.Substring($sepIdx + 1) + $rk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($subPath, $false) + if ($rk) { + $rawCmd = [string]$rk.GetValue($valName, '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) + $rk.Close() + if ($rawCmd -match '^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$') { + $exeCand = if ($Matches[1]) { $Matches[1] } else { $Matches[2] } + $restPart = [string]$Matches[3] + if ([System.IO.Path]::GetFileName($exeCand) -ieq 'Antigravity.exe' -and $restPart -notmatch '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { + $qExe = if ($Matches[1] -or $exeCand -match '\\s') { '"' + $exeCand + '"' } else { $exeCand } + $nextVal = ($qExe + ' ' + ($restPart.Trim() + ' --remote-debugging-port=0').Trim()).Trim() + $wk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($subPath, $true) + if ($wk) { $wk.SetValue($valName, $nextVal, [Microsoft.Win32.RegistryValueKind]::String); $wk.Close() } + } + } + } } } catch {} + continue } - } catch {} + if ($item.StartsWith('HKLM:Class:')) { + try { + $relKey = $item.Substring(11) + $rk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($relKey, $false) + if ($rk) { + $rawOpen = [string]$rk.GetValue('', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) + $rk.Close() + if ($rawOpen -match '^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$') { + $exeCand = if ($Matches[1]) { $Matches[1] } else { $Matches[2] } + $restOpen = ([string]$Matches[3]).Trim() + if ([System.IO.Path]::GetFileName($exeCand) -ieq 'Antigravity.exe' -and $restOpen -notmatch '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { + $qExe = if ($Matches[1] -or $exeCand -match '\\s') { '"' + $exeCand + '"' } else { $exeCand } + $nextOpen = if ($restOpen) { "$qExe --remote-debugging-port=0 $restOpen" } else { "$qExe --remote-debugging-port=0" } + $wk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($relKey, $true) + if ($wk) { $wk.SetValue('', $nextOpen, [Microsoft.Win32.RegistryValueKind]::String); $wk.Close() } + } + } + } + } catch {} + continue + } + if (-not (Test-Path -LiteralPath $item)) { continue } + try { + if (-not $ws) { $ws = New-Object -ComObject WScript.Shell } + $sc = $ws.CreateShortcut($item) + $cur = [string]$sc.Arguments + if ($cur -notmatch '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { + $sc.Arguments = ($cur.Trim() + ' --remote-debugging-port=0').Trim() + $sc.Save() + } + } catch {} + } } if ($readOnlyShortcuts.Count -gt 0) { @@ -1368,20 +1698,70 @@ if ($readOnlyShortcuts.Count -gt 0) { $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" + ('$targets = @(' + $roJoined + ')'), + '$ws = $null', + 'foreach ($item in $targets) {', + ' if (-not $item) { continue }', + ' if ($item.StartsWith(''HKLM:Run:'')) {', + ' try {', + ' $restKey = $item.Substring(9)', + ' $sepIdx = $restKey.IndexOf(''|'')', + ' if ($sepIdx -gt 0) {', + ' $subPath = $restKey.Substring(0, $sepIdx)', + ' $valName = $restKey.Substring($sepIdx + 1)', + ' $rk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($subPath, $false)', + ' if ($rk) {', + ' $rawCmd = [string]$rk.GetValue($valName, '''', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)', + ' $rk.Close()', + ' if ($rawCmd -match ''^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$'') {', + ' $exeCand = if ($Matches[1]) { $Matches[1] } else { $Matches[2] }', + ' $restPart = [string]$Matches[3]', + ' if ([System.IO.Path]::GetFileName($exeCand) -ieq ''Antigravity.exe'' -and $restPart -notmatch ''(?:^|\\s)--remote-debugging-port(?:=|\\s|$)'') {', + ' $qExe = if ($Matches[1] -or $exeCand -match ''\\s'') { ''"'' + $exeCand + ''"'' } else { $exeCand }', + ' $nextVal = ($qExe + '' '' + ($restPart.Trim() + '' --remote-debugging-port=0'').Trim()).Trim()', + ' $wk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($subPath, $true)', + ' if ($wk) { $wk.SetValue($valName, $nextVal, [Microsoft.Win32.RegistryValueKind]::String); $wk.Close() }', + ' }', + ' }', + ' }', + ' }', + ' } catch {}', + ' continue', + ' }', + ' if ($item.StartsWith(''HKLM:Class:'')) {', + ' try {', + ' $relKey = $item.Substring(11)', + ' $rk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($relKey, $false)', + ' if ($rk) {', + ' $rawOpen = [string]$rk.GetValue('''', '''', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)', + ' $rk.Close()', + ' if ($rawOpen -match ''^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$'') {', + ' $exeCand = if ($Matches[1]) { $Matches[1] } else { $Matches[2] }', + ' $restOpen = ([string]$Matches[3]).Trim()', + ' if ([System.IO.Path]::GetFileName($exeCand) -ieq ''Antigravity.exe'' -and $restOpen -notmatch ''(?:^|\\s)--remote-debugging-port(?:=|\\s|$)'') {', + ' $qExe = if ($Matches[1] -or $exeCand -match ''\\s'') { ''"'' + $exeCand + ''"'' } else { $exeCand }', + ' $nextOpen = if ($restOpen) { $qExe + '' --remote-debugging-port=0 '' + $restOpen } else { $qExe + '' --remote-debugging-port=0'' }', + ' $wk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($relKey, $true)', + ' if ($wk) { $wk.SetValue('''', $nextOpen, [Microsoft.Win32.RegistryValueKind]::String); $wk.Close() }', + ' }', + ' }', + ' }', + ' } catch {}', + ' continue', + ' }', + ' if (Test-Path -LiteralPath $item) {', + ' try {', + ' if (-not $ws) { $ws = New-Object -ComObject WScript.Shell }', + ' $sc = $ws.CreateShortcut($item)', + ' $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))) @@ -1422,13 +1802,17 @@ if ((& $findTargets).Count -gt 0 -and -not $isSelfElevated -and $exe -and (Test- $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" + ('$exe = ' + $exeLit), + ('$procName = ' + $procLit), + ('$staleList = @(' + $staleJoined + ')'), + '$mySid = (Get-Process -Id $PID).SessionId', + '$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)) }) }', + '& $findTargets | Stop-Process -Force -ErrorAction SilentlyContinue', + 'for ($i = 0; $i -lt 25; $i++) { if ((& $findTargets).Count -eq 0) { break }; Start-Sleep -Milliseconds 200 }', + 'foreach ($fp in $staleList) { if ($fp -and (Test-Path -LiteralPath $fp)) { Remove-Item -LiteralPath $fp -Force -ErrorAction SilentlyContinue } }', + '$wd = Split-Path -Parent $exe', + 'Start-Process -FilePath $exe -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))) @@ -1473,8 +1857,9 @@ const WIN_OUT_OF_JOB_DISPATCH_PS = ` $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 + '"' +$elevFlag = if ($isElev) { '1' } else { '0' } +$env:AGY_HOST_WAS_ELEVATED = $elevFlag +$innerArgs = '-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File "' + $env:AGY_RELAUNCH_PS1 + '" -HostElevated ' + $elevFlag $fullCmd = '"' + $psBin + '" ' + $innerArgs if ($isElev) { @@ -1613,18 +1998,23 @@ export async function triggerDesktopHostRelaunch({ if (platform === 'darwin') { const appTarget = hostInfo.appBundlePath || hostInfo.executablePath; - const appName = hostInfo.kind === 'ide' ? 'Antigravity IDE' : 'Antigravity'; + const bundleDerivedName = hostInfo.appBundlePath + ? basename(hostInfo.appBundlePath).replace(/\.app$/i, '').trim() + : ''; + const appName = + bundleDerivedName || (hostInfo.kind === 'ide' ? 'Antigravity IDE' : 'Antigravity'); const shScript = [ 'sleep 0.45', - `osascript -e 'tell application "${appName}" to quit' >/dev/null 2>&1 || true`, - `i=0; while [ $i -lt 25 ] && pgrep -x "${appName}" >/dev/null 2>&1; do sleep 0.2; i=$((i+1)); done`, - `if pgrep -x "${appName}" >/dev/null 2>&1; then killall "${appName}" >/dev/null 2>&1 || true; sleep 0.4; fi`, - 'IFS=":"; for f in $AGY_STALE_PORT_FILES; do [ -n "$f" ] && rm -f "$f"; done', + 'if osascript -e \'on run argv\' -e \'tell application (item 1 of argv) to quit\' -e \'end run\' -- "$AGY_APP_NAME" >/dev/null 2>&1; then i=0; while [ $i -lt 25 ] && pgrep -x "$AGY_APP_NAME" >/dev/null 2>&1; do sleep 0.2; i=$((i+1)); done; fi', + 'if pgrep -x "$AGY_APP_NAME" >/dev/null 2>&1; then pkill -TERM -x "$AGY_APP_NAME" >/dev/null 2>&1 || killall -TERM "$AGY_APP_NAME" >/dev/null 2>&1 || true; j=0; while [ $j -lt 20 ] && pgrep -x "$AGY_APP_NAME" >/dev/null 2>&1; do sleep 0.2; j=$((j+1)); done; fi', + 'if pgrep -x "$AGY_APP_NAME" >/dev/null 2>&1; then pkill -KILL -x "$AGY_APP_NAME" >/dev/null 2>&1 || killall -KILL "$AGY_APP_NAME" >/dev/null 2>&1 || true; k=0; while [ $k -lt 15 ] && pgrep -x "$AGY_APP_NAME" >/dev/null 2>&1; do sleep 0.2; k=$((k+1)); done; fi', + 'old_ifs="$IFS"; set -f; IFS=":"; for f in $AGY_STALE_PORT_FILES; do [ -n "$f" ] && rm -f "$f"; done; set +f; IFS="$old_ifs"', 'open -a "$AGY_RELAUNCH_APP" --args --remote-debugging-port=0 >/dev/null 2>&1', ].join('; '); await spawner('/bin/sh', ['-c', shScript], { env: { ...cleanEnv, + AGY_APP_NAME: appName, AGY_RELAUNCH_APP: appTarget, AGY_STALE_PORT_FILES: cleanStaleFiles.join(':'), }, @@ -1638,12 +2028,15 @@ export async function triggerDesktopHostRelaunch({ } const procLeaf = basename(hostInfo.executablePath) || 'antigravity'; + const procComm = procLeaf.slice(0, 15); const linuxScript = [ 'sleep 0.45', 'uid="$(id -u)"', - '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', + 'is_alive() { for pn in "$AGY_PROC_NAME" antigravity Antigravity "$AGY_PROC_COMM" google-antigravity; do [ -n "$pn" ] && pgrep -u "$uid" -x "$pn" >/dev/null 2>&1 && return 0; done; return 1; }', + 'for pn in "$AGY_PROC_NAME" antigravity Antigravity "$AGY_PROC_COMM" google-antigravity; do [ -n "$pn" ] && pkill -TERM -u "$uid" -x "$pn" >/dev/null 2>&1 || true; done', + 'i=0; while [ $i -lt 25 ] && is_alive; do sleep 0.2; i=$((i+1)); done', + 'if is_alive; then for pn in "$AGY_PROC_NAME" antigravity Antigravity "$AGY_PROC_COMM" google-antigravity; do [ -n "$pn" ] && pkill -KILL -u "$uid" -x "$pn" >/dev/null 2>&1 || true; done; j=0; while [ $j -lt 15 ] && is_alive; do sleep 0.2; j=$((j+1)); done; fi', + 'old_ifs="$IFS"; set -f; IFS=":"; for f in $AGY_STALE_PORT_FILES; do [ -n "$f" ] && rm -f "$f"; done; set +f; IFS="$old_ifs"', 'nohup "$AGY_RELAUNCH_EXE" --remote-debugging-port=0 >/dev/null 2>&1 &', ].join('; '); await spawner('/bin/sh', ['-c', linuxScript], { @@ -1651,6 +2044,7 @@ export async function triggerDesktopHostRelaunch({ ...cleanEnv, AGY_RELAUNCH_EXE: hostInfo.executablePath, AGY_PROC_NAME: procLeaf, + AGY_PROC_COMM: procComm, AGY_STALE_PORT_FILES: cleanStaleFiles.join(':'), }, }); diff --git a/sidecars/panel/backend/window-bridge.mjs b/sidecars/panel/backend/window-bridge.mjs index ae53f5f..eddc4b5 100644 --- a/sidecars/panel/backend/window-bridge.mjs +++ b/sidecars/panel/backend/window-bridge.mjs @@ -10,7 +10,15 @@ * 3. 完全不触碰宿主 `app.asar` 文件,客户端升级或无调试端口时静默回退至右侧辅助栏。 */ -import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'; +import { + existsSync, + mkdirSync, + readdirSync, + readFileSync, + renameSync, + unlinkSync, + writeFileSync, +} from 'node:fs'; import { homedir } from 'node:os'; import { dirname, join } from 'node:path'; import { @@ -54,46 +62,110 @@ const ALLOWED_BRIDGE_PATHS = new Set(BRIDGE_API_PATHS); /** * 解析各操作系统下 Antigravity 2.0 与 Antigravity IDE 写入 `DevToolsActivePort` 的候选路径列表。 + * Linux 额外兼容全小写目录名、自定义 `XDG_CONFIG_HOME` 回退以及 Flatpak / Snap 一级容器配置目录。 * * @param {Record} [env=process.env] * @param {string} [platform=process.platform] * @param {string} [homeDir=homedir()] + * @param {{ readdirFn?: typeof readdirSync }|null} [fsOps=null] * @returns {string[]} */ export function resolveDevToolsPortCandidates( env = process.env, platform = process.platform, - homeDir = homedir() + homeDir = homedir(), + fsOps = null ) { const explicitFile = String(env?.ANTIGRAVITY_DEVTOOLS_PORT_FILE || '').trim(); if (explicitFile) { return [explicitFile]; } + const out = []; + const seen = new Set(); + const pushUnique = (p) => { + const clean = String(p || '').trim(); + if (clean && !seen.has(clean)) { + seen.add(clean); + out.push(clean); + } + }; + const portableRoot = String(env?.VSCODE_PORTABLE || '').trim(); + if (platform === 'win32') { const appData = env?.APPDATA || join(homeDir, 'AppData', 'Roaming'); const localAppData = env?.LOCALAPPDATA || join(homeDir, 'AppData', 'Local'); - return [ - join(appData, 'Antigravity', 'DevToolsActivePort'), - join(localAppData, 'Antigravity', 'DevToolsActivePort'), - join(appData, 'Antigravity IDE', 'DevToolsActivePort'), - join(localAppData, 'Antigravity IDE', 'DevToolsActivePort'), - ]; + pushUnique(join(appData, 'Antigravity', 'DevToolsActivePort')); + pushUnique(join(localAppData, 'Antigravity', 'DevToolsActivePort')); + pushUnique(join(appData, 'Antigravity IDE', 'DevToolsActivePort')); + pushUnique(join(localAppData, 'Antigravity IDE', 'DevToolsActivePort')); + if (portableRoot) { + pushUnique(join(portableRoot, 'user-data', 'DevToolsActivePort')); + } + return out; } if (platform === 'darwin') { - return [ - join(homeDir, 'Library', 'Application Support', 'Antigravity', 'DevToolsActivePort'), - join(homeDir, 'Library', 'Application Support', 'Antigravity IDE', 'DevToolsActivePort'), - join(homeDir, 'Library', 'Application Support', 'antigravity', 'DevToolsActivePort'), - join(homeDir, 'Library', 'Application Support', 'antigravity-ide', 'DevToolsActivePort'), - join(homeDir, '.config', 'Antigravity', 'DevToolsActivePort'), - join(homeDir, '.config', 'Antigravity IDE', 'DevToolsActivePort'), - ]; + pushUnique(join(homeDir, 'Library', 'Application Support', 'Antigravity', 'DevToolsActivePort')); + pushUnique( + join(homeDir, 'Library', 'Application Support', 'Antigravity IDE', 'DevToolsActivePort') + ); + pushUnique(join(homeDir, 'Library', 'Application Support', 'antigravity', 'DevToolsActivePort')); + pushUnique( + join(homeDir, 'Library', 'Application Support', 'antigravity-ide', 'DevToolsActivePort') + ); + pushUnique(join(homeDir, '.config', 'Antigravity', 'DevToolsActivePort')); + pushUnique(join(homeDir, '.config', 'Antigravity IDE', 'DevToolsActivePort')); + if (portableRoot) { + pushUnique(join(portableRoot, 'user-data', 'DevToolsActivePort')); + } + return out; } - const configHome = env?.XDG_CONFIG_HOME || join(homeDir, '.config'); - return [ - join(configHome, 'Antigravity', 'DevToolsActivePort'), - join(configHome, 'Antigravity IDE', 'DevToolsActivePort'), - ]; + + const defaultConfigHome = join(homeDir, '.config'); + const configHome = env?.XDG_CONFIG_HOME || defaultConfigHome; + pushUnique(join(configHome, 'Antigravity', 'DevToolsActivePort')); + pushUnique(join(configHome, 'Antigravity IDE', 'DevToolsActivePort')); + pushUnique(join(configHome, 'antigravity', 'DevToolsActivePort')); + pushUnique(join(configHome, 'antigravity-ide', 'DevToolsActivePort')); + if (configHome !== defaultConfigHome) { + pushUnique(join(defaultConfigHome, 'Antigravity', 'DevToolsActivePort')); + pushUnique(join(defaultConfigHome, 'Antigravity IDE', 'DevToolsActivePort')); + pushUnique(join(defaultConfigHome, 'antigravity', 'DevToolsActivePort')); + pushUnique(join(defaultConfigHome, 'antigravity-ide', 'DevToolsActivePort')); + } + if (portableRoot) { + pushUnique(join(portableRoot, 'user-data', 'DevToolsActivePort')); + } + + const readdirFn = fsOps?.readdirFn || readdirSync; + const flatpakRoot = join(homeDir, '.var', 'app'); + try { + for (const rawEntry of readdirFn(flatpakRoot) || []) { + const appId = typeof rawEntry === 'string' ? rawEntry : String(rawEntry?.name || ''); + if (!appId || !/antigravity/i.test(appId)) continue; + pushUnique(join(flatpakRoot, appId, 'config', 'Antigravity', 'DevToolsActivePort')); + pushUnique(join(flatpakRoot, appId, 'config', 'antigravity', 'DevToolsActivePort')); + pushUnique(join(flatpakRoot, appId, 'config', 'Antigravity IDE', 'DevToolsActivePort')); + } + } catch { + // 宿主机未安装 Flatpak 或目录不可读时静默忽略 + } + + const snapRoot = join(homeDir, 'snap'); + try { + for (const rawEntry of readdirFn(snapRoot) || []) { + const snapName = typeof rawEntry === 'string' ? rawEntry : String(rawEntry?.name || ''); + if (!snapName || !/antigravity/i.test(snapName)) continue; + pushUnique(join(snapRoot, snapName, 'current', '.config', 'Antigravity', 'DevToolsActivePort')); + pushUnique(join(snapRoot, snapName, 'current', '.config', 'antigravity', 'DevToolsActivePort')); + pushUnique( + join(snapRoot, snapName, 'current', '.config', 'Antigravity IDE', 'DevToolsActivePort') + ); + } + } catch { + // 宿主机未安装 Snap 或目录不可读时静默忽略 + } + + return out; } /** diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index b4fe942..4dd279d 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -113,9 +113,40 @@ test('DevToolsActivePort parsing, cross-platform discovery (2.0 + IDE), and stri ); const linuxPaths = resolveDevToolsPortCandidates({ XDG_CONFIG_HOME: '/home/dev/.config' }, 'linux', '/home/dev'); - assert.equal(linuxPaths.length, 2); + assert.equal(linuxPaths.length, 4); assert.equal(linuxPaths[0], path.join('/home/dev/.config', 'Antigravity', 'DevToolsActivePort')); assert.equal(linuxPaths[1], path.join('/home/dev/.config', 'Antigravity IDE', 'DevToolsActivePort')); + assert.equal(linuxPaths[2], path.join('/home/dev/.config', 'antigravity', 'DevToolsActivePort')); + assert.equal(linuxPaths[3], path.join('/home/dev/.config', 'antigravity-ide', 'DevToolsActivePort')); + + const linuxContainerPaths = resolveDevToolsPortCandidates( + { XDG_CONFIG_HOME: '/home/dev/.custom-cfg', VSCODE_PORTABLE: '/opt/ag-portable' }, + 'linux', + '/home/dev', + { + readdirFn: (dir) => { + if (dir === path.join('/home/dev', '.var', 'app')) { + return ['org.mozilla.firefox', 'com.google.Antigravity']; + } + if (dir === path.join('/home/dev', 'snap')) { + return ['firefox', 'antigravity']; + } + return []; + }, + } + ); + assert.ok(linuxContainerPaths.includes(path.join('/home/dev/.config', 'Antigravity', 'DevToolsActivePort'))); + assert.ok(linuxContainerPaths.includes(path.join('/opt/ag-portable', 'user-data', 'DevToolsActivePort'))); + assert.ok( + linuxContainerPaths.includes( + path.join('/home/dev', '.var', 'app', 'com.google.Antigravity', 'config', 'Antigravity', 'DevToolsActivePort') + ) + ); + assert.ok( + linuxContainerPaths.includes( + path.join('/home/dev', 'snap', 'antigravity', 'current', '.config', 'antigravity', 'DevToolsActivePort') + ) + ); assert.equal( isAntigravityMainPageTarget({ @@ -4991,8 +5022,10 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi const visitedDirs = []; const fakeDesktopDir = 'C:\\Users\\Dev\\Desktop'; + const fakeRedirectedDesktopDir = 'D:\\LocalizedDesktop'; const fakeProgramsDir = 'C:\\Users\\Dev\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs'; const fakeAgySubDir = `${fakeProgramsDir}\\Antigravity`; + const fakeGoogleSubDir = `${fakeProgramsDir}\\Google`; const fastProbeRes = probeWindowsShortcutsFast({ env: { USERPROFILE: 'C:\\Users\\Dev', @@ -5001,6 +5034,7 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi ProgramData: 'C:\\ProgramData', }, homeDir: 'C:\\Users\\Dev', + extraDirs: [fakeRedirectedDesktopDir], fsOps: { readdirFn: (dir) => { visitedDirs.push(dir); @@ -5010,15 +5044,22 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi { name: 'huge-repo-with-node_modules', isFile: () => false, isDirectory: () => true }, ]; } + if (dir === fakeRedirectedDesktopDir) { + return [{ name: 'Antigravity-Redir.lnk', isFile: () => true, isDirectory: () => false }]; + } if (dir === fakeProgramsDir) { return [ { name: 'Visual Studio 2022', isFile: () => false, isDirectory: () => true }, { name: 'Antigravity', isFile: () => false, isDirectory: () => true }, + { name: 'Google', isFile: () => false, isDirectory: () => true }, ]; } if (dir === fakeAgySubDir) { return [{ name: 'Antigravity IDE.lnk', isFile: () => true, isDirectory: () => false }]; } + if (dir === fakeGoogleSubDir) { + return [{ name: 'Antigravity-Google.lnk', isFile: () => true, isDirectory: () => false }]; + } return []; }, statFn: () => ({ size: 512 }), @@ -5029,6 +5070,9 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi }, }); assert.equal(fastProbeRes.allConfigured, true); + assert.equal(fastProbeRes.configuredPaths.length, 3); + assert.ok(fastProbeRes.configuredPaths.some((p) => p.includes('Antigravity-Redir.lnk'))); + assert.ok(fastProbeRes.configuredPaths.some((p) => p.includes('Antigravity-Google.lnk'))); assert.equal( visitedDirs.some((d) => d.includes('huge-repo') || d.includes('Visual Studio')), false, @@ -5074,6 +5118,13 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi }).matched, false ); + const linuxGoogleDashRaw = 'Exec=env -u BAD_VAR /usr/bin/google-antigravity -- %U'; + const linuxGoogleDashPatched = patchLinuxDesktopEntryText(linuxGoogleDashRaw, { enabled: true }); + assert.equal(linuxGoogleDashPatched.matched, true); + assert.equal( + linuxGoogleDashPatched.text, + 'Exec=env -u BAD_VAR /usr/bin/google-antigravity --remote-debugging-port=0 -- %U' + ); const resolvedLinuxAppImage = resolveDesktopHostExecutable({ env: { @@ -5121,7 +5172,8 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi assert.equal(resolvedMacHost.appBundlePath, '/Applications/Antigravity.app'); const sanitizedEnv = buildSanitizedDesktopRelaunchEnv({ - PATH: 'C:\\Windows\\System32', + PATH: '/tmp/.mount_Antigr123/usr/bin:/usr/local/bin:/usr/bin', + LD_LIBRARY_PATH: '/tmp/.mount_Antigr123/usr/lib:/usr/lib/x86_64-linux-gnu', USERPROFILE: 'C:\\Users\\Administrator', ANTIGRAVITY_LS_ADDRESS: 'localhost:13088', ANTIGRAVITY_CSRF_TOKEN: 'secret', @@ -5129,11 +5181,22 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi USAGE_MONITOR_HOST_PPID: '123', ELECTRON_RUN_AS_NODE: '1', NODE_OPTIONS: '--inspect', + APPIMAGE: '/home/alice/Antigravity.AppImage', + APPDIR: '/tmp/.mount_Antigr123', + OWD: '/home/alice', + ARGV0: '/home/alice/Antigravity.AppImage', + APPIMAGE_EXTRACT_AND_RUN: '1', }); assert.deepEqual(sanitizedEnv, { - PATH: 'C:\\Windows\\System32', + PATH: '/usr/local/bin:/usr/bin', + LD_LIBRARY_PATH: '/usr/lib/x86_64-linux-gnu', USERPROFILE: 'C:\\Users\\Administrator', }); + assert.equal( + buildSanitizedDesktopRelaunchEnv({ LD_LIBRARY_PATH: '/tmp/.mount_Only/lib' }).LD_LIBRARY_PATH, + undefined, + 'Omits LD_LIBRARY_PATH completely when only AppImage mount entries were present' + ); // 4. Linux .desktop provisioning on real temp dir + Windows shortcut provisioning + stale DevToolsActivePort (cdp_unreachable) + relaunch dispatch const simTmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ag-233-auto-')); @@ -5201,6 +5264,105 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi /--remote-debugging-port=0 %U/ ); + // Dynamic Linux .desktop discovery: vendor/AppImageLauncher/capitalized filenames across user, system, XDG_DATA_DIRS, and autostart + const linuxDynData = path.join(simTmp, 'xdg-data-dyn'); + const linuxDynCfg = path.join(simTmp, 'xdg-cfg-dyn'); + const linuxSysVendor = path.join(simTmp, 'sys-vendor-share'); + const appImageDesktop = path.join( + linuxDynData, + 'applications', + 'appimagekit_1a2b3c-Antigravity.desktop' + ); + const vendorSysDesktop = path.join(linuxSysVendor, 'applications', 'google-antigravity.desktop'); + const unrelatedSysDesktop = path.join(linuxSysVendor, 'applications', 'firefox.desktop'); + const capAutostart = path.join(linuxDynCfg, 'autostart', 'Antigravity.desktop'); + fs.mkdirSync(path.dirname(appImageDesktop), { recursive: true }); + fs.mkdirSync(path.dirname(vendorSysDesktop), { recursive: true }); + fs.mkdirSync(path.dirname(capAutostart), { recursive: true }); + fs.writeFileSync(appImageDesktop, linuxAppImageRaw, 'utf8'); + fs.writeFileSync( + vendorSysDesktop, + '[Desktop Entry]\nName=Antigravity\nExec=/usr/bin/google-antigravity %U\nType=Application\n', + 'utf8' + ); + fs.writeFileSync(unrelatedSysDesktop, '[Desktop Entry]\nName=Firefox\nExec=firefox %u\n', 'utf8'); + fs.writeFileSync(capAutostart, linuxDesktopRaw, 'utf8'); + const linuxDynProv = await ensureDesktopLaunchEntriesConfigured({ + enabled: true, + env: { + XDG_DATA_HOME: linuxDynData, + XDG_CONFIG_HOME: linuxDynCfg, + XDG_DATA_DIRS: linuxSysVendor, + }, + platform: 'linux', + homeDir, + allowInTest: true, + fsOps: { + existsFn: fs.existsSync, + readFn: fs.readFileSync, + writeFn: fs.writeFileSync, + mkdirFn: fs.mkdirSync, + renameFn: fs.renameSync, + unlinkFn: fs.unlinkSync, + readdirFn: fs.readdirSync, + statFn: fs.statSync, + }, + }); + assert.equal(linuxDynProv.updated, true); + assert.equal(linuxDynProv.updatedPaths.length, 3); + assert.match(fs.readFileSync(appImageDesktop, 'utf8'), /--remote-debugging-port=0 %U/); + assert.match( + fs.readFileSync(path.join(linuxDynData, 'applications', 'google-antigravity.desktop'), 'utf8'), + /google-antigravity --remote-debugging-port=0 %U/ + ); + assert.match(fs.readFileSync(capAutostart, 'utf8'), /--remote-debugging-port=0 %U/); + assert.equal(fs.existsSync(path.join(linuxDynData, 'applications', 'firefox.desktop')), false); + + // Verify Windows PowerShell provisioning covers HKLM Run/WOW6432Node/Classes + caches discoveredDirs for subsequent fastCheckIfActive + let capturedWinProvPs = ''; + const redirHome = 'C:\\Users\\RedirUser'; + const redirDesktop = 'D:\\RedirectedDesktop'; + await ensureDesktopLaunchEntriesConfigured({ + enabled: true, + env: { USERPROFILE: redirHome }, + platform: 'win32', + homeDir: redirHome, + allowInTest: true, + execFileFn: async (_f, args) => { + capturedWinProvPs = args[args.length - 1]; + return JSON.stringify({ + ok: true, + updatedPaths: [`${redirDesktop}\\Antigravity.lnk`], + configuredPaths: [`${redirDesktop}\\Antigravity.lnk`], + readOnlyPaths: [], + discoveredDirs: [redirDesktop], + }); + }, + }); + assert.match(capturedWinProvPs, /LocalMachine/); + assert.match(capturedWinProvPs, /WOW6432Node/); + assert.match(capturedWinProvPs, /HKLM:Run:/); + assert.match(capturedWinProvPs, /HKLM:Class:/); + const fastCachedRes = await ensureDesktopLaunchEntriesConfigured({ + enabled: true, + fastCheckIfActive: true, + env: { USERPROFILE: redirHome, APPDATA: '', PUBLIC: '', ProgramData: '' }, + platform: 'win32', + homeDir: redirHome, + allowInTest: true, + fsOps: { + readdirFn: (dir) => + dir === redirDesktop + ? [{ name: 'Antigravity.lnk', isFile: () => true, isDirectory: () => false }] + : [], + statFn: () => ({ size: 512 }), + readFn: () => makeFakeLnkBuf('C:\\App\\Antigravity.exe', '--remote-debugging-port=0'), + }, + }); + assert.equal(fastCachedRes.fastPath, true); + assert.equal(fastCachedRes.allConfigured ?? fastCachedRes.configured, true); + assert.ok(fastCachedRes.configuredPaths.some((p) => p.includes('RedirectedDesktop'))); + // Verify Windows shortcut auto-provisioning + read-only public shortcut tracking + periodic recheck + clean rollback const winPsCalls = []; let simulateReadOnlyPublicDesktop = false; @@ -5291,10 +5453,16 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi assert.equal(relaunchWinRes.ok, true); assert.equal(relaunchWinRes.relaunching, true); assert.equal(capturedRelaunchArgs.includes('-Sta'), true, 'Forces STA for Shell.Application COM'); + assert.match( + capturedRelaunchArgs[capturedRelaunchArgs.length - 1], + /-HostElevated /, + 'Passes -HostElevated via CLI arg so WMI/Shell.Application preserve elevation state' + ); assert.equal(capturedRelaunchEnv.ANTIGRAVITY_LS_ADDRESS, undefined, 'Strips host LS env'); assert.equal(fs.existsSync(capturedRelaunchEnv.AGY_RELAUNCH_PS1), true); const writtenPs1 = fs.readFileSync(capturedRelaunchEnv.AGY_RELAUNCH_PS1, 'utf8'); assert.equal(writtenPs1.startsWith('\uFEFF'), true, 'Writes UTF-8 BOM for Windows PowerShell 5.1'); + assert.match(writtenPs1, /^[\uFEFF]?param\(\[string\]\$HostElevated = '0'\)/); assert.match(writtenPs1, /--remote-debugging-port=0/); assert.ok(writtenPs1.includes(stalePortFile)); @@ -5335,12 +5503,44 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi }); assert.equal(relaunchMacRes.ok, true); assert.equal(macSpawnArgs.env.AGY_RELAUNCH_APP, '/Applications/Antigravity.app'); + assert.equal(macSpawnArgs.env.AGY_APP_NAME, 'Antigravity'); + assert.match(macSpawnArgs.args[1], /if osascript .* then .* fi/); + assert.match(macSpawnArgs.args[1], /pkill -TERM -x "\$AGY_APP_NAME"/); + assert.match(macSpawnArgs.args[1], /pkill -KILL -x "\$AGY_APP_NAME"/); assert.match(macSpawnArgs.args[1], /open -a "\$AGY_RELAUNCH_APP" --args --remote-debugging-port=0/); - // Verify Linux /proc dynamic AppImage discovery & multi-comm pkill handling + // macOS TCC-blocked osascript falls back to ps -axo comm= and derives custom .app name + let macPsFallbackSpawn = null; + const relaunchMacPsRes = await triggerDesktopHostRelaunch({ + env: { PATH: '/usr/bin:/bin' }, + platform: 'darwin', + homeDir: '/Users/dev', + allowInTest: true, + existsFn: () => false, + execFileFn: async (file) => { + if (file === 'osascript') throw new Error('Not authorized to send Apple events (-1743)'); + if (file === 'ps') { + return '/Users/dev/Apps/Antigravity Beta.app/Contents/MacOS/Antigravity Beta\n'; + } + return ''; + }, + spawnFn: async (file, args, opts) => { + macPsFallbackSpawn = { file, args, env: opts?.env }; + return { pid: 4322 }; + }, + }); + assert.equal(relaunchMacPsRes.ok, true); + assert.equal(macPsFallbackSpawn.env.AGY_RELAUNCH_APP, '/Users/dev/Apps/Antigravity Beta.app'); + assert.equal(macPsFallbackSpawn.env.AGY_APP_NAME, 'Antigravity Beta'); + + // Verify Linux /proc dynamic AppImage discovery, 15-char comm truncation, and SIGKILL fallback let linuxSpawnArgs = null; const relaunchLinuxRes = await triggerDesktopHostRelaunch({ - env: { PATH: '/usr/bin:/bin' }, + env: { + PATH: '/tmp/.mount_Ag/bin:/usr/bin:/bin', + APPIMAGE: '/home/alice/Apps/Antigravity-2.33.0.AppImage', + LD_LIBRARY_PATH: '/tmp/.mount_Ag/lib', + }, platform: 'linux', homeDir: '/home/alice', stalePortFiles: ['/home/alice/.config/Antigravity/DevToolsActivePort'], @@ -5354,17 +5554,30 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi }); 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/); + assert.equal(linuxSpawnArgs.env.AGY_PROC_COMM, 'Antigravity-2.3'); + assert.equal(linuxSpawnArgs.env.APPIMAGE, undefined, 'Strips APPIMAGE from relaunch env'); + assert.equal(linuxSpawnArgs.env.LD_LIBRARY_PATH, undefined, 'Strips mount LD_LIBRARY_PATH'); + assert.match(linuxSpawnArgs.args[1], /for pn in "\$AGY_PROC_NAME" antigravity Antigravity "\$AGY_PROC_COMM"/); + assert.match(linuxSpawnArgs.args[1], /pkill -KILL -u "\$uid" -x "\$pn"/); - // Explicit ANTIGRAVITY_DEVTOOLS_PORT fallback & UAC read-only shortcut + de-elevation script generation + // Explicit ANTIGRAVITY_DEVTOOLS_PORT fallback, HKLM UAC patching, single-quoted UAC script safety & de-elevation const innerScriptCheck = buildWindowsRelaunchInnerScript(fakeExe, [stalePortFile], 'desktop', { - readOnlyShortcutPaths: ['C:\\Users\\Public\\Desktop\\Antigravity.lnk'], + readOnlyShortcutPaths: [ + 'C:\\Users\\Public\\Desktop\\Antigravity.lnk', + 'HKLM:Run:Software\\Microsoft\\Windows\\CurrentVersion\\Run|Antigravity', + 'HKLM:Class:Software\\Classes\\antigravity\\shell\\open\\command', + ], 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, /HKLM:Run:/); + assert.match(innerScriptCheck, /HKLM:Class:/); + assert.match(innerScriptCheck, /'\$ws = \$null'/); + assert.match(innerScriptCheck, /'\$mySid = \(Get-Process -Id \$PID\)\.SessionId'/); + assert.match(innerScriptCheck, /'Remove-Item -LiteralPath \$PSCommandPath -Force -ErrorAction SilentlyContinue'/); assert.match(innerScriptCheck, /\$isSelfElevated -and -not \$wasHostElevated/); } finally { fs.rmSync(simTmp, { recursive: true, force: true });