@@ -601,7 +601,8 @@ _dispatcherQueue is null
601601 // hosts. Fire-and-forget on a background task so a slow LxssManager at
602602 // cold logon never delays InitializeGatewayClient. The keepalive itself
603603 // runs detached from the tray — see WslDistroKeepAlive in LocalGatewaySetup.cs.
604- _ = Task . Run ( TryEnsureLocalGatewayKeepAliveAsync ) ;
604+ var wslKeepAlive = new WslGatewayKeepAliveService ( ( ) => _settings , ( ) => _gatewayRegistry ) ;
605+ _ = Task . Run ( wslKeepAlive . TryEnsureAsync ) ;
605606 InitializeGatewayClient ( ) ;
606607
607608 // Pre-warm chat window (WebView2 init takes 1-3s, do it now so left-click is instant)
@@ -1857,232 +1858,6 @@ private bool ShouldInitializeNodeService()
18571858 return _settings ? . EnableNodeMode == true || _settings ? . EnableMcpServer == true ;
18581859 }
18591860
1860- /// <summary>
1861- /// Ensures a WSL keepalive process is running for the local gateway distro
1862- /// so the WSL2 VM stays up even after the tray exits.
1863- /// Best-effort, fire-and-forget.
1864- /// </summary>
1865- private async Task TryEnsureLocalGatewayKeepAliveAsync ( )
1866- {
1867- try
1868- {
1869- if ( _settings is null ) return ;
1870-
1871- var activeRecord = _gatewayRegistry ? . GetActive ( ) ;
1872- if ( ! WslKeepAlivePolicy . ShouldStart ( activeRecord , _settings . GetEffectiveGatewayUrl ( ) ) )
1873- {
1874- await StopStaleLocalGatewayKeepAliveAsync ( ) ;
1875- return ;
1876- }
1877-
1878- var distroName = await ResolveLocalGatewayDistroNameAsync ( activeRecord ) ;
1879- if ( string . IsNullOrWhiteSpace ( distroName ) ) return ;
1880-
1881- // Verify distro exists before spawning keepalive
1882- var runner = new WslExeCommandRunner ( new AppLogger ( ) , defaultTimeout : TimeSpan . FromSeconds ( 4 ) ) ;
1883- var distros = await runner . ListDistrosAsync ( ) ;
1884- if ( ! distros . Any ( d => string . Equals ( d . Name , distroName , StringComparison . OrdinalIgnoreCase ) ) )
1885- {
1886- Logger . Warn ( $ "[WslKeepAlive] Distro '{ distroName } ' not found; skipping keepalive.") ;
1887- return ;
1888- }
1889-
1890- // Spawn a detached wsl sleep process to keep the VM alive
1891- var psi = new System . Diagnostics . ProcessStartInfo
1892- {
1893- FileName = ResolveWslExePath ( ) ,
1894- UseShellExecute = false ,
1895- CreateNoWindow = true ,
1896- } ;
1897- psi . ArgumentList . Add ( "-d" ) ;
1898- psi . ArgumentList . Add ( distroName ) ;
1899- psi . ArgumentList . Add ( "--" ) ;
1900- psi . ArgumentList . Add ( "sleep" ) ;
1901- psi . ArgumentList . Add ( "infinity" ) ;
1902-
1903- var proc = System . Diagnostics . Process . Start ( psi ) ;
1904- if ( proc is not null )
1905- {
1906- Logger . Info ( $ "[WslKeepAlive] Started keepalive for { distroName } (PID { proc . Id } ).") ;
1907- }
1908- }
1909- catch ( Exception ex )
1910- {
1911- Logger . Warn ( $ "[WslKeepAlive] Startup keepalive failed (non-fatal): { ex . Message } ") ;
1912- }
1913- }
1914-
1915- private async Task StopStaleLocalGatewayKeepAliveAsync ( )
1916- {
1917- try
1918- {
1919- var localDataDir = SetupExistingGatewayClassifier . ResolveLocalDataPath ( ) ;
1920- var markerDir = Path . Combine ( localDataDir , "wsl-keepalive" ) ;
1921- var markerDistroNames = ReadKeepAliveMarkerDistroNames ( markerDir ) ;
1922- var setupStateDistroName = await ReadSetupStateDistroNameAsync ( localDataDir ) ;
1923- var records = _gatewayRegistry ? . GetAll ( ) ?? [ ] ;
1924-
1925- foreach ( var distroName in WslKeepAlivePolicy . FindStaleSetupManagedDistroNames (
1926- records ,
1927- markerDistroNames ,
1928- setupStateDistroName ) )
1929- {
1930- StopKeepAliveProcessesForDistro ( distroName ) ;
1931- DeleteKeepAliveMarker ( markerDir , distroName ) ;
1932- }
1933- }
1934- catch ( Exception ex )
1935- {
1936- Logger . Warn ( $ "[WslKeepAlive] Stale keepalive cleanup failed (non-fatal): { ex . Message } ") ;
1937- }
1938- }
1939-
1940- private static IReadOnlyList < string > ReadKeepAliveMarkerDistroNames ( string markerDir )
1941- {
1942- if ( ! Directory . Exists ( markerDir ) )
1943- return [ ] ;
1944-
1945- var distroNames = new List < string > ( ) ;
1946- foreach ( var markerPath in Directory . EnumerateFiles ( markerDir , "*.json" ) )
1947- {
1948- if ( WslKeepAlivePolicy . TryGetMarkerDistroName ( File . ReadAllText ( markerPath ) , out var distroName ) )
1949- distroNames . Add ( distroName ) ;
1950- }
1951-
1952- return distroNames ;
1953- }
1954-
1955- private static async Task < string ? > ReadSetupStateDistroNameAsync ( string localDataDir )
1956- {
1957- var stateFile = Path . Combine ( localDataDir , "setup-state.json" ) ;
1958- if ( ! File . Exists ( stateFile ) )
1959- return null ;
1960-
1961- var json = await File . ReadAllTextAsync ( stateFile ) ;
1962- using var doc = System . Text . Json . JsonDocument . Parse ( json ) ;
1963- return doc . RootElement . TryGetProperty ( "DistroName" , out var distroElement )
1964- ? distroElement . GetString ( )
1965- : null ;
1966- }
1967-
1968- private static void StopKeepAliveProcessesForDistro ( string distroName )
1969- {
1970- var procs = System . Diagnostics . Process . GetProcessesByName ( "wsl" )
1971- . Concat ( System . Diagnostics . Process . GetProcessesByName ( "wsl.exe" ) ) ;
1972-
1973- foreach ( var proc in procs )
1974- {
1975- try
1976- {
1977- if ( WslKeepAlivePolicy . IsKeepaliveCommandLine ( GetProcessCommandLine ( proc . Id ) , distroName ) )
1978- {
1979- proc . Kill ( entireProcessTree : true ) ;
1980- proc . WaitForExit ( 5000 ) ;
1981- Logger . Info ( $ "[WslKeepAlive] Stopped stale keepalive for { distroName } (PID { proc . Id } ).") ;
1982- }
1983- }
1984- catch
1985- {
1986- // Process may have exited while being inspected.
1987- }
1988- finally
1989- {
1990- proc . Dispose ( ) ;
1991- }
1992- }
1993- }
1994-
1995- private static void DeleteKeepAliveMarker ( string markerDir , string distroName )
1996- {
1997- if ( ! Directory . Exists ( markerDir ) )
1998- return ;
1999-
2000- foreach ( var markerPath in Directory . EnumerateFiles ( markerDir , "*.json" ) )
2001- {
2002- try
2003- {
2004- if ( WslKeepAlivePolicy . TryGetMarkerDistroName ( File . ReadAllText ( markerPath ) , out var markerDistro )
2005- && string . Equals ( markerDistro , distroName , StringComparison . OrdinalIgnoreCase ) )
2006- {
2007- File . Delete ( markerPath ) ;
2008- Logger . Info ( $ "[WslKeepAlive] Deleted stale keepalive marker for { distroName } .") ;
2009- }
2010- }
2011- catch
2012- {
2013- // Best-effort cleanup; stale/corrupt markers are not fatal.
2014- }
2015- }
2016- }
2017-
2018- private static string ? GetProcessCommandLine ( int pid )
2019- {
2020- try
2021- {
2022- var psi = new System . Diagnostics . ProcessStartInfo ( "powershell.exe" ,
2023- $ "-NoProfile -Command \" (Get-CimInstance Win32_Process -Filter 'ProcessId={ pid } ').CommandLine\" ")
2024- {
2025- RedirectStandardOutput = true ,
2026- UseShellExecute = false ,
2027- CreateNoWindow = true
2028- } ;
2029- using var p = System . Diagnostics . Process . Start ( psi ) ;
2030- if ( p == null ) return null ;
2031- var output = p . StandardOutput . ReadToEnd ( ) ;
2032- p . WaitForExit ( 5000 ) ;
2033- return output . Trim ( ) ;
2034- }
2035- catch { return null ; }
2036- }
2037-
2038- private static string ResolveWslExePath ( )
2039- {
2040- var windowsDir = Environment . GetFolderPath ( Environment . SpecialFolder . Windows ) ;
2041- if ( string . IsNullOrWhiteSpace ( windowsDir ) )
2042- windowsDir = Environment . GetEnvironmentVariable ( "SystemRoot" ) ?? @"C:\Windows" ;
2043-
2044- return Path . Combine ( windowsDir , "System32" , "wsl.exe" ) ;
2045- }
2046-
2047- /// <summary>
2048- /// Resolves the WSL distro name to keep alive. Prefers the value persisted by
2049- /// onboarding in <c>setup-state.json</c> so the keepalive always targets the distro
2050- /// the user actually installed. In DEBUG / test builds, an
2051- /// <c>OPENCLAW_WSL_DISTRO_NAME</c> environment override is honored to match
2052- /// Resolves the local gateway distro name by reading setup-state.json.
2053- /// Falls back to "OpenClawGateway" if not found.
2054- /// </summary>
2055- private async Task < string ? > ResolveLocalGatewayDistroNameAsync ( GatewayRecord ? activeRecord )
2056- {
2057- string ? setupStateDistroName = null ;
2058- try
2059- {
2060- var stateFile = Path . Combine (
2061- SetupExistingGatewayClassifier . ResolveLocalDataPath ( ) ,
2062- "setup-state.json" ) ;
2063-
2064- if ( File . Exists ( stateFile ) )
2065- {
2066- var json = await File . ReadAllTextAsync ( stateFile ) ;
2067- using var doc = System . Text . Json . JsonDocument . Parse ( json ) ;
2068- if ( doc . RootElement . TryGetProperty ( "DistroName" , out var dn ) &&
2069- dn . GetString ( ) is { Length : > 0 } distroName )
2070- {
2071- setupStateDistroName = distroName ;
2072- }
2073- }
2074- }
2075- catch ( Exception ex )
2076- {
2077- Logger . Warn ( $ "[WslKeepAlive] Failed to read setup-state.json: { ex . Message } ") ;
2078- }
2079-
2080- return WslKeepAlivePolicy . ResolveDistroName (
2081- activeRecord ,
2082- setupStateDistroName ,
2083- Environment . GetEnvironmentVariable ( "OPENCLAW_WSL_DISTRO_NAME" ) ) ;
2084- }
2085-
20861861 // The pre-unification ShouldInitializeNodeService(GatewayRecord, string) overload
20871862 // and LocalNodeServiceOwnsIdentityFor have been removed: GatewayConnectionManager
20881863 // is now the single owner of the WindowsNodeClient lifecycle for ALL gateways
0 commit comments