Skip to content

Commit 9cadb6b

Browse files
ranjeshjCopilot
andcommitted
Address remaining setup feedback
Co-authored-by: Copilot <[email protected]>
1 parent 4f8f62e commit 9cadb6b

8 files changed

Lines changed: 371 additions & 25 deletions

File tree

‎src/OpenClaw.SetupEngine/SetupContext.cs‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -188,10 +188,14 @@ public void MergeIntoSettingsFile(string settingsPath)
188188
}
189189
}
190190

191-
var defaults = new Dictionary<string, object>
191+
var setupOwnedSettings = new Dictionary<string, object>
192192
{
193193
["EnableNodeMode"] = EnableNodeMode,
194194
["AutoStart"] = AutoStart,
195+
};
196+
197+
var initialDefaults = new Dictionary<string, object>
198+
{
195199
["NodeSystemRunEnabled"] = NodeSystemRunEnabled,
196200
["NodeCanvasEnabled"] = NodeCanvasEnabled,
197201
["NodeScreenEnabled"] = NodeScreenEnabled,
@@ -209,7 +213,10 @@ public void MergeIntoSettingsFile(string settingsPath)
209213
settings[kvp.Key] = kvp.Value;
210214
}
211215

212-
foreach (var kvp in defaults)
216+
foreach (var kvp in setupOwnedSettings)
217+
settings[kvp.Key] = kvp.Value;
218+
219+
foreach (var kvp in initialDefaults)
213220
settings.TryAdd(kvp.Key, kvp.Value);
214221

215222
Directory.CreateDirectory(Path.GetDirectoryName(settingsPath)!);

‎src/OpenClaw.SetupEngine/SetupSteps.cs‎

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2313,10 +2313,7 @@ internal static bool TryGetExistingKeepalive(string markerPath, string distro, o
23132313
if (process.HasExited)
23142314
return false;
23152315

2316-
var commandLine = GetProcessCommandLine(pid);
2317-
return commandLine != null
2318-
&& commandLine.Contains(distro, StringComparison.OrdinalIgnoreCase)
2319-
&& commandLine.Contains("sleep", StringComparison.OrdinalIgnoreCase);
2316+
return IsKeepaliveCommandLine(GetProcessCommandLine(pid), distro);
23202317
}
23212318
}
23222319
catch
@@ -2335,8 +2332,8 @@ public override async Task RollbackAsync(SetupContext ctx, CancellationToken ct)
23352332
return;
23362333
}
23372334

2338-
// Kill keepalive wsl.exe processes for this distro
2339-
// Pattern: wsl.exe -d <distro> -- sleep <N>
2335+
// Kill keepalive wsl.exe processes for this distro.
2336+
// Pattern: wsl.exe -d <distro> -- sleep infinity
23402337
try
23412338
{
23422339
var procs = System.Diagnostics.Process.GetProcessesByName("wsl")
@@ -2348,12 +2345,11 @@ public override async Task RollbackAsync(SetupContext ctx, CancellationToken ct)
23482345
{
23492346
// Read command line via WMI/CIM
23502347
var cmdLine = GetProcessCommandLine(proc.Id);
2351-
if (cmdLine != null
2352-
&& cmdLine.Contains(distro, StringComparison.OrdinalIgnoreCase)
2353-
&& cmdLine.Contains("sleep", StringComparison.OrdinalIgnoreCase))
2348+
if (IsKeepaliveCommandLine(cmdLine, distro))
23542349
{
2355-
proc.Kill();
2356-
ctx.Logger.Info($"[Uninstall] Killed keepalive process PID {proc.Id}");
2350+
proc.Kill(entireProcessTree: true);
2351+
proc.WaitForExit(5000);
2352+
ctx.Logger.Info($"[Uninstall] Killed keepalive process tree PID {proc.Id}");
23572353
}
23582354
}
23592355
catch { /* process may have exited */ }
@@ -2385,6 +2381,16 @@ public override async Task RollbackAsync(SetupContext ctx, CancellationToken ct)
23852381
await Task.CompletedTask;
23862382
}
23872383

2384+
internal static bool IsKeepaliveCommandLine(string? commandLine, string distro)
2385+
{
2386+
if (string.IsNullOrWhiteSpace(commandLine) || string.IsNullOrWhiteSpace(distro))
2387+
return false;
2388+
2389+
return commandLine.Contains(distro, StringComparison.OrdinalIgnoreCase)
2390+
&& commandLine.Contains("sleep", StringComparison.OrdinalIgnoreCase)
2391+
&& commandLine.Contains("infinity", StringComparison.OrdinalIgnoreCase);
2392+
}
2393+
23882394
private static string? GetProcessCommandLine(int pid)
23892395
{
23902396
try

‎src/OpenClaw.SetupEngine/TrayArtifactCleanup.cs‎

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System.Runtime.Versioning;
22
using Microsoft.Win32;
3+
using OpenClaw.Connection;
34

45
namespace OpenClaw.SetupEngine;
56

@@ -45,7 +46,7 @@ public static void Run(SetupContext ctx, bool preserveLogs = false)
4546
DeleteFileIfExists(Path.Combine(appDataDir, "exec-policy.json"), "exec-policy.json", logger);
4647

4748
// 4. Reset onboarding settings in settings.json
48-
ResetOnboardingSettings(appDataDir, logger);
49+
ResetOnboardingSettings(appDataDir, logger, preserveNodeSettings: HasRemainingGatewayRecords(appDataDir, logger));
4950

5051
// 5. Optionally delete gateway logs
5152
if (!preserveLogs)
@@ -95,7 +96,22 @@ private static void DeleteLogsDir(string dir, string label, SetupLogger logger)
9596
}
9697
}
9798

98-
private static void ResetOnboardingSettings(string appDataDir, SetupLogger logger)
99+
private static bool HasRemainingGatewayRecords(string appDataDir, SetupLogger logger)
100+
{
101+
try
102+
{
103+
var registry = new GatewayRegistry(appDataDir);
104+
registry.Load();
105+
return registry.GetAll().Count > 0;
106+
}
107+
catch (Exception ex)
108+
{
109+
logger.Warn($"[Uninstall] Failed to inspect gateway registry: {ex.Message}");
110+
return false;
111+
}
112+
}
113+
114+
internal static void ResetOnboardingSettings(string appDataDir, SetupLogger logger, bool preserveNodeSettings)
99115
{
100116
var settingsPath = Path.Combine(appDataDir, "settings.json");
101117
if (!File.Exists(settingsPath))
@@ -123,15 +139,13 @@ private static void ResetOnboardingSettings(string appDataDir, SetupLogger logge
123139
changed = true;
124140
}
125141

126-
// Set EnableNodeMode to false
127-
if (dict.ContainsKey("EnableNodeMode"))
142+
if (!preserveNodeSettings && dict.ContainsKey("EnableNodeMode"))
128143
{
129144
dict["EnableNodeMode"] = System.Text.Json.JsonSerializer.SerializeToElement(false);
130145
changed = true;
131146
}
132147

133-
// Set AutoStart to false
134-
if (dict.ContainsKey("AutoStart"))
148+
if (!preserveNodeSettings && dict.ContainsKey("AutoStart"))
135149
{
136150
dict["AutoStart"] = System.Text.Json.JsonSerializer.SerializeToElement(false);
137151
changed = true;
@@ -142,7 +156,9 @@ private static void ResetOnboardingSettings(string appDataDir, SetupLogger logge
142156
var updatedJson = System.Text.Json.JsonSerializer.Serialize(dict,
143157
new System.Text.Json.JsonSerializerOptions { WriteIndented = true });
144158
AtomicFile.WriteAllText(settingsPath, updatedJson);
145-
logger.Info("[Uninstall] Reset onboarding settings (GatewayUrl, EnableNodeMode, AutoStart)");
159+
logger.Info(preserveNodeSettings
160+
? "[Uninstall] Reset onboarding settings (GatewayUrl)"
161+
: "[Uninstall] Reset onboarding settings (GatewayUrl, EnableNodeMode, AutoStart)");
146162
}
147163
else
148164
{

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

Lines changed: 136 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1778,7 +1778,10 @@ private async Task TryEnsureLocalGatewayKeepAliveAsync()
17781778

17791779
var activeRecord = _gatewayRegistry?.GetActive();
17801780
if (!WslKeepAlivePolicy.ShouldStart(activeRecord, _settings.GetEffectiveGatewayUrl()))
1781+
{
1782+
await StopStaleLocalGatewayKeepAliveAsync();
17811783
return;
1784+
}
17821785

17831786
var distroName = await ResolveLocalGatewayDistroNameAsync(activeRecord);
17841787
if (string.IsNullOrWhiteSpace(distroName)) return;
@@ -1795,7 +1798,7 @@ private async Task TryEnsureLocalGatewayKeepAliveAsync()
17951798
// Spawn a detached wsl sleep process to keep the VM alive
17961799
var psi = new System.Diagnostics.ProcessStartInfo
17971800
{
1798-
FileName = "wsl.exe",
1801+
FileName = ResolveWslExePath(),
17991802
UseShellExecute = false,
18001803
CreateNoWindow = true,
18011804
};
@@ -1817,6 +1820,138 @@ private async Task TryEnsureLocalGatewayKeepAliveAsync()
18171820
}
18181821
}
18191822

1823+
private async Task StopStaleLocalGatewayKeepAliveAsync()
1824+
{
1825+
try
1826+
{
1827+
var localDataDir = SetupExistingGatewayClassifier.ResolveLocalDataPath();
1828+
var markerDir = Path.Combine(localDataDir, "wsl-keepalive");
1829+
var markerDistroNames = ReadKeepAliveMarkerDistroNames(markerDir);
1830+
var setupStateDistroName = await ReadSetupStateDistroNameAsync(localDataDir);
1831+
var records = _gatewayRegistry?.GetAll() ?? [];
1832+
1833+
foreach (var distroName in WslKeepAlivePolicy.FindStaleSetupManagedDistroNames(
1834+
records,
1835+
markerDistroNames,
1836+
setupStateDistroName))
1837+
{
1838+
StopKeepAliveProcessesForDistro(distroName);
1839+
DeleteKeepAliveMarker(markerDir, distroName);
1840+
}
1841+
}
1842+
catch (Exception ex)
1843+
{
1844+
Logger.Warn($"[WslKeepAlive] Stale keepalive cleanup failed (non-fatal): {ex.Message}");
1845+
}
1846+
}
1847+
1848+
private static IReadOnlyList<string> ReadKeepAliveMarkerDistroNames(string markerDir)
1849+
{
1850+
if (!Directory.Exists(markerDir))
1851+
return [];
1852+
1853+
var distroNames = new List<string>();
1854+
foreach (var markerPath in Directory.EnumerateFiles(markerDir, "*.json"))
1855+
{
1856+
if (WslKeepAlivePolicy.TryGetMarkerDistroName(File.ReadAllText(markerPath), out var distroName))
1857+
distroNames.Add(distroName);
1858+
}
1859+
1860+
return distroNames;
1861+
}
1862+
1863+
private static async Task<string?> ReadSetupStateDistroNameAsync(string localDataDir)
1864+
{
1865+
var stateFile = Path.Combine(localDataDir, "setup-state.json");
1866+
if (!File.Exists(stateFile))
1867+
return null;
1868+
1869+
var json = await File.ReadAllTextAsync(stateFile);
1870+
using var doc = System.Text.Json.JsonDocument.Parse(json);
1871+
return doc.RootElement.TryGetProperty("DistroName", out var distroElement)
1872+
? distroElement.GetString()
1873+
: null;
1874+
}
1875+
1876+
private static void StopKeepAliveProcessesForDistro(string distroName)
1877+
{
1878+
var procs = System.Diagnostics.Process.GetProcessesByName("wsl")
1879+
.Concat(System.Diagnostics.Process.GetProcessesByName("wsl.exe"));
1880+
1881+
foreach (var proc in procs)
1882+
{
1883+
try
1884+
{
1885+
if (WslKeepAlivePolicy.IsKeepaliveCommandLine(GetProcessCommandLine(proc.Id), distroName))
1886+
{
1887+
proc.Kill(entireProcessTree: true);
1888+
proc.WaitForExit(5000);
1889+
Logger.Info($"[WslKeepAlive] Stopped stale keepalive for {distroName} (PID {proc.Id}).");
1890+
}
1891+
}
1892+
catch
1893+
{
1894+
// Process may have exited while being inspected.
1895+
}
1896+
finally
1897+
{
1898+
proc.Dispose();
1899+
}
1900+
}
1901+
}
1902+
1903+
private static void DeleteKeepAliveMarker(string markerDir, string distroName)
1904+
{
1905+
if (!Directory.Exists(markerDir))
1906+
return;
1907+
1908+
foreach (var markerPath in Directory.EnumerateFiles(markerDir, "*.json"))
1909+
{
1910+
try
1911+
{
1912+
if (WslKeepAlivePolicy.TryGetMarkerDistroName(File.ReadAllText(markerPath), out var markerDistro)
1913+
&& string.Equals(markerDistro, distroName, StringComparison.OrdinalIgnoreCase))
1914+
{
1915+
File.Delete(markerPath);
1916+
Logger.Info($"[WslKeepAlive] Deleted stale keepalive marker for {distroName}.");
1917+
}
1918+
}
1919+
catch
1920+
{
1921+
// Best-effort cleanup; stale/corrupt markers are not fatal.
1922+
}
1923+
}
1924+
}
1925+
1926+
private static string? GetProcessCommandLine(int pid)
1927+
{
1928+
try
1929+
{
1930+
var psi = new System.Diagnostics.ProcessStartInfo("powershell.exe",
1931+
$"-NoProfile -Command \"(Get-CimInstance Win32_Process -Filter 'ProcessId={pid}').CommandLine\"")
1932+
{
1933+
RedirectStandardOutput = true,
1934+
UseShellExecute = false,
1935+
CreateNoWindow = true
1936+
};
1937+
using var p = System.Diagnostics.Process.Start(psi);
1938+
if (p == null) return null;
1939+
var output = p.StandardOutput.ReadToEnd();
1940+
p.WaitForExit(5000);
1941+
return output.Trim();
1942+
}
1943+
catch { return null; }
1944+
}
1945+
1946+
private static string ResolveWslExePath()
1947+
{
1948+
var windowsDir = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
1949+
if (string.IsNullOrWhiteSpace(windowsDir))
1950+
windowsDir = Environment.GetEnvironmentVariable("SystemRoot") ?? @"C:\Windows";
1951+
1952+
return Path.Combine(windowsDir, "System32", "wsl.exe");
1953+
}
1954+
18201955
/// <summary>
18211956
/// Resolves the WSL distro name to keep alive. Prefers the value persisted by
18221957
/// onboarding in <c>setup-state.json</c> so the keepalive always targets the distro

‎src/OpenClaw.Tray.WinUI/Services/WslKeepAlivePolicy.cs‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,66 @@ public static bool ShouldStart(GatewayRecord? activeRecord, string? legacyGatewa
3838

3939
return "OpenClawGateway";
4040
}
41+
42+
public static IReadOnlyList<string> FindStaleSetupManagedDistroNames(
43+
IEnumerable<GatewayRecord> records,
44+
IEnumerable<string> markerDistroNames,
45+
string? setupStateDistroName)
46+
{
47+
var managedLocalDistros = records
48+
.Where(IsSetupManagedLocalRecord)
49+
.Select(r => r.SetupManagedDistroName)
50+
.Where(name => !string.IsNullOrWhiteSpace(name))
51+
.ToHashSet(StringComparer.OrdinalIgnoreCase);
52+
53+
var candidates = markerDistroNames
54+
.Append(setupStateDistroName)
55+
.Where(name => !string.IsNullOrWhiteSpace(name))
56+
.Distinct(StringComparer.OrdinalIgnoreCase);
57+
58+
return candidates
59+
.Where(distro => !managedLocalDistros.Contains(distro!))
60+
.Select(distro => distro!)
61+
.ToArray();
62+
}
63+
64+
public static bool IsKeepaliveCommandLine(string? commandLine, string distroName)
65+
{
66+
if (string.IsNullOrWhiteSpace(commandLine) || string.IsNullOrWhiteSpace(distroName))
67+
return false;
68+
69+
return commandLine.Contains(distroName, StringComparison.OrdinalIgnoreCase)
70+
&& commandLine.Contains("sleep", StringComparison.OrdinalIgnoreCase)
71+
&& commandLine.Contains("infinity", StringComparison.OrdinalIgnoreCase);
72+
}
73+
74+
public static bool TryGetMarkerDistroName(string markerJson, out string distroName)
75+
{
76+
distroName = string.Empty;
77+
78+
try
79+
{
80+
using var doc = System.Text.Json.JsonDocument.Parse(markerJson);
81+
if (!doc.RootElement.TryGetProperty("DistroName", out var distroElement))
82+
return false;
83+
84+
distroName = distroElement.GetString() ?? string.Empty;
85+
return !string.IsNullOrWhiteSpace(distroName);
86+
}
87+
catch (System.Text.Json.JsonException)
88+
{
89+
return false;
90+
}
91+
}
92+
93+
private static bool IsSetupManagedLocalRecord(GatewayRecord record)
94+
{
95+
if (record.SshTunnel is not null)
96+
return false;
97+
98+
if (string.IsNullOrWhiteSpace(record.SetupManagedDistroName))
99+
return false;
100+
101+
return record.IsLocal || LocalGatewayUrlClassifier.IsLocalGatewayUrl(record.Url);
102+
}
41103
}

0 commit comments

Comments
 (0)