Skip to content

Commit b175439

Browse files
authored
refactor: extract WslGatewayKeepAliveService from App.xaml.cs
Merged during first-pass triage after dual-model adversarial review and green reported checks.
1 parent d5543b9 commit b175439

2 files changed

Lines changed: 252 additions & 227 deletions

File tree

‎src/OpenClaw.Tray.WinUI/App.xaml.cs‎

Lines changed: 2 additions & 227 deletions
Original file line numberDiff line numberDiff line change
@@ -608,7 +608,8 @@ _dispatcherQueue is null
608608
// hosts. Fire-and-forget on a background task so a slow LxssManager at
609609
// cold logon never delays InitializeGatewayClient. The keepalive itself
610610
// runs detached from the tray — see WslDistroKeepAlive in LocalGatewaySetup.cs.
611-
_ = Task.Run(TryEnsureLocalGatewayKeepAliveAsync);
611+
var wslKeepAlive = new WslGatewayKeepAliveService(() => _settings, () => _gatewayRegistry);
612+
_ = Task.Run(wslKeepAlive.TryEnsureAsync);
612613
InitializeGatewayClient();
613614

614615
// Pre-warm chat window (WebView2 init takes 1-3s, do it now so left-click is instant)
@@ -1928,232 +1929,6 @@ private bool ShouldInitializeNodeService()
19281929
return _settings?.EnableNodeMode == true || _settings?.EnableMcpServer == true;
19291930
}
19301931

1931-
/// <summary>
1932-
/// Ensures a WSL keepalive process is running for the local gateway distro
1933-
/// so the WSL2 VM stays up even after the tray exits.
1934-
/// Best-effort, fire-and-forget.
1935-
/// </summary>
1936-
private async Task TryEnsureLocalGatewayKeepAliveAsync()
1937-
{
1938-
try
1939-
{
1940-
if (_settings is null) return;
1941-
1942-
var activeRecord = _gatewayRegistry?.GetActive();
1943-
if (!WslKeepAlivePolicy.ShouldStart(activeRecord, _settings.GetEffectiveGatewayUrl()))
1944-
{
1945-
await StopStaleLocalGatewayKeepAliveAsync();
1946-
return;
1947-
}
1948-
1949-
var distroName = await ResolveLocalGatewayDistroNameAsync(activeRecord);
1950-
if (string.IsNullOrWhiteSpace(distroName)) return;
1951-
1952-
// Verify distro exists before spawning keepalive
1953-
var runner = new WslExeCommandRunner(new AppLogger(), defaultTimeout: TimeSpan.FromSeconds(4));
1954-
var distros = await runner.ListDistrosAsync();
1955-
if (!distros.Any(d => string.Equals(d.Name, distroName, StringComparison.OrdinalIgnoreCase)))
1956-
{
1957-
Logger.Warn($"[WslKeepAlive] Distro '{distroName}' not found; skipping keepalive.");
1958-
return;
1959-
}
1960-
1961-
// Spawn a detached wsl sleep process to keep the VM alive
1962-
var psi = new System.Diagnostics.ProcessStartInfo
1963-
{
1964-
FileName = ResolveWslExePath(),
1965-
UseShellExecute = false,
1966-
CreateNoWindow = true,
1967-
};
1968-
psi.ArgumentList.Add("-d");
1969-
psi.ArgumentList.Add(distroName);
1970-
psi.ArgumentList.Add("--");
1971-
psi.ArgumentList.Add("sleep");
1972-
psi.ArgumentList.Add("infinity");
1973-
1974-
var proc = System.Diagnostics.Process.Start(psi);
1975-
if (proc is not null)
1976-
{
1977-
Logger.Info($"[WslKeepAlive] Started keepalive for {distroName} (PID {proc.Id}).");
1978-
}
1979-
}
1980-
catch (Exception ex)
1981-
{
1982-
Logger.Warn($"[WslKeepAlive] Startup keepalive failed (non-fatal): {ex.Message}");
1983-
}
1984-
}
1985-
1986-
private async Task StopStaleLocalGatewayKeepAliveAsync()
1987-
{
1988-
try
1989-
{
1990-
var localDataDir = SetupExistingGatewayClassifier.ResolveLocalDataPath();
1991-
var markerDir = Path.Combine(localDataDir, "wsl-keepalive");
1992-
var markerDistroNames = ReadKeepAliveMarkerDistroNames(markerDir);
1993-
var setupStateDistroName = await ReadSetupStateDistroNameAsync(localDataDir);
1994-
var records = _gatewayRegistry?.GetAll() ?? [];
1995-
1996-
foreach (var distroName in WslKeepAlivePolicy.FindStaleSetupManagedDistroNames(
1997-
records,
1998-
markerDistroNames,
1999-
setupStateDistroName))
2000-
{
2001-
StopKeepAliveProcessesForDistro(distroName);
2002-
DeleteKeepAliveMarker(markerDir, distroName);
2003-
}
2004-
}
2005-
catch (Exception ex)
2006-
{
2007-
Logger.Warn($"[WslKeepAlive] Stale keepalive cleanup failed (non-fatal): {ex.Message}");
2008-
}
2009-
}
2010-
2011-
private static IReadOnlyList<string> ReadKeepAliveMarkerDistroNames(string markerDir)
2012-
{
2013-
if (!Directory.Exists(markerDir))
2014-
return [];
2015-
2016-
var distroNames = new List<string>();
2017-
foreach (var markerPath in Directory.EnumerateFiles(markerDir, "*.json"))
2018-
{
2019-
if (WslKeepAlivePolicy.TryGetMarkerDistroName(File.ReadAllText(markerPath), out var distroName))
2020-
distroNames.Add(distroName);
2021-
}
2022-
2023-
return distroNames;
2024-
}
2025-
2026-
private static async Task<string?> ReadSetupStateDistroNameAsync(string localDataDir)
2027-
{
2028-
var stateFile = Path.Combine(localDataDir, "setup-state.json");
2029-
if (!File.Exists(stateFile))
2030-
return null;
2031-
2032-
var json = await File.ReadAllTextAsync(stateFile);
2033-
using var doc = System.Text.Json.JsonDocument.Parse(json);
2034-
return doc.RootElement.TryGetProperty("DistroName", out var distroElement)
2035-
? distroElement.GetString()
2036-
: null;
2037-
}
2038-
2039-
private static void StopKeepAliveProcessesForDistro(string distroName)
2040-
{
2041-
var procs = System.Diagnostics.Process.GetProcessesByName("wsl")
2042-
.Concat(System.Diagnostics.Process.GetProcessesByName("wsl.exe"));
2043-
2044-
foreach (var proc in procs)
2045-
{
2046-
try
2047-
{
2048-
if (WslKeepAlivePolicy.IsKeepaliveCommandLine(GetProcessCommandLine(proc.Id), distroName))
2049-
{
2050-
proc.Kill(entireProcessTree: true);
2051-
proc.WaitForExit(5000);
2052-
Logger.Info($"[WslKeepAlive] Stopped stale keepalive for {distroName} (PID {proc.Id}).");
2053-
}
2054-
}
2055-
catch
2056-
{
2057-
// Process may have exited while being inspected.
2058-
}
2059-
finally
2060-
{
2061-
proc.Dispose();
2062-
}
2063-
}
2064-
}
2065-
2066-
private static void DeleteKeepAliveMarker(string markerDir, string distroName)
2067-
{
2068-
if (!Directory.Exists(markerDir))
2069-
return;
2070-
2071-
foreach (var markerPath in Directory.EnumerateFiles(markerDir, "*.json"))
2072-
{
2073-
try
2074-
{
2075-
if (WslKeepAlivePolicy.TryGetMarkerDistroName(File.ReadAllText(markerPath), out var markerDistro)
2076-
&& string.Equals(markerDistro, distroName, StringComparison.OrdinalIgnoreCase))
2077-
{
2078-
File.Delete(markerPath);
2079-
Logger.Info($"[WslKeepAlive] Deleted stale keepalive marker for {distroName}.");
2080-
}
2081-
}
2082-
catch
2083-
{
2084-
// Best-effort cleanup; stale/corrupt markers are not fatal.
2085-
}
2086-
}
2087-
}
2088-
2089-
private static string? GetProcessCommandLine(int pid)
2090-
{
2091-
try
2092-
{
2093-
var psi = new System.Diagnostics.ProcessStartInfo("powershell.exe",
2094-
$"-NoProfile -Command \"(Get-CimInstance Win32_Process -Filter 'ProcessId={pid}').CommandLine\"")
2095-
{
2096-
RedirectStandardOutput = true,
2097-
UseShellExecute = false,
2098-
CreateNoWindow = true
2099-
};
2100-
using var p = System.Diagnostics.Process.Start(psi);
2101-
if (p == null) return null;
2102-
var output = p.StandardOutput.ReadToEnd();
2103-
p.WaitForExit(5000);
2104-
return output.Trim();
2105-
}
2106-
catch { return null; }
2107-
}
2108-
2109-
private static string ResolveWslExePath()
2110-
{
2111-
var windowsDir = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
2112-
if (string.IsNullOrWhiteSpace(windowsDir))
2113-
windowsDir = Environment.GetEnvironmentVariable("SystemRoot") ?? @"C:\Windows";
2114-
2115-
return Path.Combine(windowsDir, "System32", "wsl.exe");
2116-
}
2117-
2118-
/// <summary>
2119-
/// Resolves the WSL distro name to keep alive. Prefers the value persisted by
2120-
/// onboarding in <c>setup-state.json</c> so the keepalive always targets the distro
2121-
/// the user actually installed. In DEBUG / test builds, an
2122-
/// <c>OPENCLAW_WSL_DISTRO_NAME</c> environment override is honored to match
2123-
/// Resolves the local gateway distro name by reading setup-state.json.
2124-
/// Falls back to "OpenClawGateway" if not found.
2125-
/// </summary>
2126-
private async Task<string?> ResolveLocalGatewayDistroNameAsync(GatewayRecord? activeRecord)
2127-
{
2128-
string? setupStateDistroName = null;
2129-
try
2130-
{
2131-
var stateFile = Path.Combine(
2132-
SetupExistingGatewayClassifier.ResolveLocalDataPath(),
2133-
"setup-state.json");
2134-
2135-
if (File.Exists(stateFile))
2136-
{
2137-
var json = await File.ReadAllTextAsync(stateFile);
2138-
using var doc = System.Text.Json.JsonDocument.Parse(json);
2139-
if (doc.RootElement.TryGetProperty("DistroName", out var dn) &&
2140-
dn.GetString() is { Length: > 0 } distroName)
2141-
{
2142-
setupStateDistroName = distroName;
2143-
}
2144-
}
2145-
}
2146-
catch (Exception ex)
2147-
{
2148-
Logger.Warn($"[WslKeepAlive] Failed to read setup-state.json: {ex.Message}");
2149-
}
2150-
2151-
return WslKeepAlivePolicy.ResolveDistroName(
2152-
activeRecord,
2153-
setupStateDistroName,
2154-
Environment.GetEnvironmentVariable("OPENCLAW_WSL_DISTRO_NAME"));
2155-
}
2156-
21571932
// The pre-unification ShouldInitializeNodeService(GatewayRecord, string) overload
21581933
// and LocalNodeServiceOwnsIdentityFor have been removed: GatewayConnectionManager
21591934
// is now the single owner of the WindowsNodeClient lifecycle for ALL gateways

0 commit comments

Comments
 (0)