Skip to content

Commit 599faff

Browse files
committed
fix(setup): own gateway lifecycle during wizard
Co-authored-by: Copilot App <[email protected]> Copilot-Session: 84bc73e4-939a-4e25-ba88-26af9f4fc8b5
1 parent 6cfb586 commit 599faff

3 files changed

Lines changed: 564 additions & 31 deletions

File tree

‎src/OpenClaw.SetupEngine/SetupSteps.cs‎

Lines changed: 48 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1829,6 +1829,11 @@ private static int CountConfigSetCommands(string configCommands)
18291829
internal static string? GetDefaultDevicePairPublicUrl(GatewayConfig gw, int port, bool tailscaleEnabled = false) =>
18301830
gw.Bind == "loopback" && !tailscaleEnabled ? $"http://127.0.0.1:{port}" : null;
18311831

1832+
internal static string GetEffectiveReloadMode(GatewayConfig gw) =>
1833+
gw.ExtraConfig?.TryGetValue("gateway.reload.mode", out var overrideMode) == true
1834+
? overrideMode
1835+
: gw.ReloadMode;
1836+
18321837
internal static bool IsSafeExtraConfigKey(string value)
18331838
=> System.Text.RegularExpressions.Regex.IsMatch(value, "^[A-Za-z0-9._-]+$");
18341839
}
@@ -1863,31 +1868,44 @@ public sealed class StartGatewayStep : SetupStep
18631868
public override string DisplayName => "Start gateway";
18641869
public override RetryPolicy Retry => new(MaxAttempts: 3, InitialDelay: TimeSpan.FromSeconds(3));
18651870

1866-
public override async Task<StepResult> ExecuteAsync(SetupContext ctx, CancellationToken ct)
1871+
public override Task<StepResult> ExecuteAsync(SetupContext ctx, CancellationToken ct) =>
1872+
StartOrRestartAndWaitForHealthAsync(ctx, restart: false, ct);
1873+
1874+
internal static Task<StepResult> RestartAndWaitForHealthAsync(
1875+
SetupContext ctx,
1876+
CancellationToken ct) =>
1877+
StartOrRestartAndWaitForHealthAsync(ctx, restart: true, ct);
1878+
1879+
private static async Task<StepResult> StartOrRestartAndWaitForHealthAsync(
1880+
SetupContext ctx,
1881+
bool restart,
1882+
CancellationToken ct)
18671883
{
18681884
var distro = ctx.DistroName!;
18691885
var pathCmd = ctx.WslPathPrefix;
1886+
var action = restart ? "restart" : "start";
18701887

1871-
// Check for port conflicts before starting
1872-
var portCheck = await ctx.Commands.RunInWslAsync(
1873-
distro, $"ss -tlnp 2>/dev/null | grep ':{ctx.Config.GatewayPort}\\b' || true",
1874-
TimeSpan.FromSeconds(10), ct: ct);
1875-
1876-
if (!string.IsNullOrWhiteSpace(portCheck.Stdout) && portCheck.Stdout.Contains($":{ctx.Config.GatewayPort}"))
1888+
if (!restart)
18771889
{
1878-
if (!portCheck.Stdout.Contains("openclaw", StringComparison.OrdinalIgnoreCase))
1890+
var portCheck = await ctx.Commands.RunInWslAsync(
1891+
distro, $"ss -tlnp 2>/dev/null | grep ':{ctx.Config.GatewayPort}\\b' || true",
1892+
TimeSpan.FromSeconds(10), ct: ct);
1893+
1894+
if (!string.IsNullOrWhiteSpace(portCheck.Stdout) && portCheck.Stdout.Contains($":{ctx.Config.GatewayPort}"))
18791895
{
1880-
ctx.Logger.Warn($"Port {ctx.Config.GatewayPort} is in use by another process:\n{portCheck.Stdout.Trim()}");
1881-
return StepResult.Fail(
1882-
$"Port {ctx.Config.GatewayPort} is already in use by another process. Either stop the conflicting process or change GatewayPort in the setup config.");
1883-
}
1896+
if (!portCheck.Stdout.Contains("openclaw", StringComparison.OrdinalIgnoreCase))
1897+
{
1898+
ctx.Logger.Warn($"Port {ctx.Config.GatewayPort} is in use by another process:\n{portCheck.Stdout.Trim()}");
1899+
return StepResult.Fail(
1900+
$"Port {ctx.Config.GatewayPort} is already in use by another process. Either stop the conflicting process or change GatewayPort in the setup config.");
1901+
}
18841902

1885-
ctx.Logger.Info($"Port {ctx.Config.GatewayPort} appears to be in use by openclaw — proceeding");
1903+
ctx.Logger.Info($"Port {ctx.Config.GatewayPort} appears to be in use by openclaw — proceeding");
1904+
}
18861905
}
18871906

1888-
// Start the service
18891907
var start = await ctx.Commands.RunInWslAsync(
1890-
distro, $"{pathCmd} && openclaw gateway start", TimeSpan.FromSeconds(30), ct: ct);
1908+
distro, $"{pathCmd} && openclaw gateway {action}", TimeSpan.FromSeconds(30), ct: ct);
18911909

18921910
if (start.ExitCode != 0)
18931911
{
@@ -1901,17 +1919,28 @@ await ctx.Commands.RunInWslAsync(
19011919
TimeSpan.FromSeconds(10),
19021920
ct: ct);
19031921
await Task.Delay(2000, ct);
1904-
start = await ctx.Commands.RunInWslAsync(distro, $"{pathCmd} && openclaw gateway start", TimeSpan.FromSeconds(30), ct: ct);
1922+
start = await ctx.Commands.RunInWslAsync(
1923+
distro,
1924+
$"{pathCmd} && openclaw gateway {action}",
1925+
TimeSpan.FromSeconds(30),
1926+
ct: ct);
19051927
if (start.ExitCode != 0)
1906-
return StepResult.Fail($"Gateway start failed after reset: {start.Stderr}");
1928+
return StepResult.Fail($"Gateway {action} failed after reset: {start.Stderr}");
19071929
}
19081930
else
19091931
{
1910-
return StepResult.Fail($"Gateway start failed (exit {start.ExitCode}): {start.Stderr}");
1932+
return StepResult.Fail($"Gateway {action} failed (exit {start.ExitCode}): {start.Stderr}");
19111933
}
19121934
}
19131935

1914-
// Wait for health endpoint
1936+
return await WaitForHealthAsync(ctx, ct);
1937+
}
1938+
1939+
internal static async Task<StepResult> WaitForHealthAsync(
1940+
SetupContext ctx,
1941+
CancellationToken ct)
1942+
{
1943+
var distro = ctx.DistroName!;
19151944
ctx.Logger.Info("Waiting for gateway health endpoint...");
19161945
var healthDeadline = DateTimeOffset.UtcNow.Add(TimeSpan.FromSeconds(ctx.Config.Gateway.HealthTimeoutSeconds));
19171946

‎src/OpenClaw.SetupEngine/SetupWizardRunner.cs‎

Lines changed: 210 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
using System.Runtime.ExceptionServices;
12
using System.Text.Json;
23
using System.Text.RegularExpressions;
34
using OpenClaw.Connection;
@@ -15,13 +16,101 @@ public sealed class SetupWizardRunner
1516
// so setup fails with a diagnostic instead of hanging.
1617

1718
private readonly SetupContext _ctx;
19+
private bool _reloadSuspended;
1820

1921
public SetupWizardRunner(SetupContext ctx)
2022
{
2123
_ctx = ctx;
2224
}
2325

2426
public async Task<StepResult> RunAsync(CancellationToken ct)
27+
{
28+
return await RunWithReloadRestorationAsync(() => RunCoreAsync(ct));
29+
}
30+
31+
internal async Task<StepResult> RunWithReloadRestorationAsync(
32+
Func<Task<StepResult>> runWizard)
33+
{
34+
ArgumentNullException.ThrowIfNull(runWizard);
35+
36+
StepResult? wizardResult = null;
37+
Exception? wizardException = null;
38+
try
39+
{
40+
wizardResult = await runWizard();
41+
}
42+
catch (Exception ex)
43+
{
44+
wizardException = ex;
45+
}
46+
47+
StepResult? restoreResult = null;
48+
if (_reloadSuspended)
49+
{
50+
restoreResult = await RestoreReloadModeAsync();
51+
_reloadSuspended = false;
52+
}
53+
54+
if (restoreResult?.IsSuccess == false)
55+
{
56+
if (wizardException is null && wizardResult?.IsSuccess == false)
57+
{
58+
return StepResult.Fail(
59+
$"{restoreResult.Message} The wizard also failed: {wizardResult.Message}",
60+
CombineErrors(restoreResult.Error, wizardResult.Error));
61+
}
62+
63+
if (wizardException is null)
64+
return restoreResult;
65+
66+
var restorationException =
67+
new InvalidOperationException(restoreResult.Message, restoreResult.Error);
68+
return StepResult.Fail(
69+
$"{restoreResult.Message} The wizard also exited with {wizardException.GetType().Name}.",
70+
new AggregateException(restorationException, wizardException));
71+
}
72+
73+
if (wizardException is not null)
74+
ExceptionDispatchInfo.Capture(wizardException).Throw();
75+
76+
return wizardResult!;
77+
}
78+
79+
internal void MarkReloadSuspended() => _reloadSuspended = true;
80+
81+
internal async Task<StepResult> SuspendReloadModeAsync()
82+
{
83+
try
84+
{
85+
var result = await _ctx.Commands.RunInWslAsync(
86+
_ctx.DistroName!,
87+
$"{_ctx.WslPathPrefix} && openclaw config set gateway.reload.mode off",
88+
TimeSpan.FromSeconds(15),
89+
// This bounded handoff must finish so we know whether restoration is required.
90+
ct: CancellationToken.None);
91+
if (result.ExitCode != 0)
92+
{
93+
return StepResult.Fail(
94+
$"Failed to suspend gateway reload for wizard (exit {result.ExitCode}): {result.Stderr.Trim()}");
95+
}
96+
97+
_reloadSuspended = true;
98+
_ctx.Logger.Info("Suspended gateway reload immediately before wizard");
99+
var healthResult =
100+
await StartGatewayStep.WaitForHealthAsync(_ctx, CancellationToken.None);
101+
if (!healthResult.IsSuccess)
102+
return healthResult;
103+
104+
return await VerifyExpectedManagedGatewayAsync(
105+
"after suspending gateway reload");
106+
}
107+
catch (Exception ex)
108+
{
109+
return StepResult.Fail($"Failed to suspend gateway reload for wizard: {ex.Message}", ex);
110+
}
111+
}
112+
113+
private async Task<StepResult> RunCoreAsync(CancellationToken ct)
25114
{
26115
var registry = new GatewayRegistry(_ctx.DataDir, logger: new SetupOpenClawLogger(_ctx.Logger));
27116
registry.Load();
@@ -101,8 +190,43 @@ public async Task<StepResult> RunAsync(CancellationToken ct)
101190
if (connection != PairOperatorStep.ConnectionOutcome.Connected)
102191
return StepResult.Fail($"Cannot run gateway wizard because operator connection failed: {connection}");
103192

193+
var suspendResult = await SuspendReloadModeAsync();
194+
if (!suspendResult.IsSuccess)
195+
return suspendResult;
196+
197+
try
198+
{
199+
await client.DisconnectAsync();
200+
}
201+
catch (Exception ex)
202+
{
203+
_ctx.Logger.Debug(
204+
$"Wizard client disconnect before reload-suspension reconnect failed: {ex.Message}");
205+
}
206+
finally
207+
{
208+
client.Dispose();
209+
}
210+
211+
client = CreateWizardClient(
212+
credential,
213+
identityPath,
214+
wsLogger,
215+
restartRecovery: true);
216+
connection = await PairOperatorStep.WaitForConnectionOrPairing(
217+
client,
218+
_ctx,
219+
TimeSpan.FromSeconds(30),
220+
ct,
221+
retryGatewayStartupDisconnects: true);
222+
if (connection != PairOperatorStep.ConnectionOutcome.Connected)
223+
{
224+
return StepResult.Fail(
225+
$"Cannot run gateway wizard because operator reconnect after reload suspension failed: {connection}");
226+
}
227+
104228
_ctx.Logger.Info("Starting gateway wizard");
105-
var payload = await client.SendWizardRequestAsync("wizard.start", timeoutMs: 30_000);
229+
var payload = await SendWizardStartAsync(client);
106230
wizardStarted = true;
107231

108232
var visits = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
@@ -214,7 +338,7 @@ await PairOperatorStep.EnsurePairingEndpointTrustedAsync(
214338
progressPolls = 0;
215339
totalProgressPolls = 0;
216340
lastProgressStepId = "";
217-
return await client.SendWizardRequestAsync("wizard.start", timeoutMs: 30_000);
341+
return await SendWizardStartAsync(client);
218342
}
219343
}
220344

@@ -355,9 +479,6 @@ await PairOperatorStep.EnsurePairingEndpointTrustedAsync(
355479
if (client is not null && wizardStarted && !wizardCompleted && !string.IsNullOrWhiteSpace(sessionId))
356480
await TryCancelWizardAsync(client, sessionId);
357481

358-
if (wizardStarted)
359-
await TryResetReloadModeAsync();
360-
361482
if (client != null)
362483
{
363484
await client.DisconnectAsync();
@@ -366,6 +487,34 @@ await PairOperatorStep.EnsurePairingEndpointTrustedAsync(
366487
}
367488
}
368489

490+
internal static object BuildWizardStartParameters() => new { installDaemon = false };
491+
492+
internal static bool IsInstallDaemonParameterUnsupported(Exception ex) =>
493+
ex is InvalidOperationException &&
494+
ex.Message.Contains(
495+
"unexpected property 'installDaemon'",
496+
StringComparison.OrdinalIgnoreCase);
497+
498+
private async Task<JsonElement> SendWizardStartAsync(
499+
OpenClawGatewayClient client)
500+
{
501+
try
502+
{
503+
return await client.SendWizardRequestAsync(
504+
"wizard.start",
505+
BuildWizardStartParameters(),
506+
timeoutMs: 30_000);
507+
}
508+
catch (Exception ex) when (IsInstallDaemonParameterUnsupported(ex))
509+
{
510+
_ctx.Logger.Info(
511+
"Gateway wizard predates installDaemon ownership control; retrying compatible wizard.start");
512+
return await client.SendWizardRequestAsync(
513+
"wizard.start",
514+
timeoutMs: 30_000);
515+
}
516+
}
517+
369518
private OpenClawGatewayClient CreateWizardClient(
370519
string credential,
371520
string identityPath,
@@ -398,27 +547,76 @@ private async Task TryCancelWizardAsync(OpenClawGatewayClient client, string ses
398547
}
399548
}
400549

401-
private async Task TryResetReloadModeAsync()
550+
internal async Task<StepResult> RestoreReloadModeAsync()
402551
{
552+
var reloadMode = ConfigureGatewayStep.GetEffectiveReloadMode(_ctx.Config.Gateway);
403553
try
404554
{
405555
var result = await _ctx.Commands.RunInWslAsync(
406556
_ctx.DistroName!,
407-
$"{_ctx.WslPathPrefix} && openclaw config set gateway.reload.mode hybrid",
557+
$"{_ctx.WslPathPrefix} && openclaw config set gateway.reload.mode {WslShellQuoting.QuotePosixSingleQuote(reloadMode)}",
408558
TimeSpan.FromSeconds(15),
409559
ct: CancellationToken.None);
410560

411-
if (result.ExitCode == 0)
412-
_ctx.Logger.Info("Reset gateway.reload.mode to hybrid after wizard");
413-
else
414-
_ctx.Logger.Warn($"Failed to reset gateway.reload.mode after wizard (exit {result.ExitCode}): {result.Stderr.Trim()}");
561+
if (result.ExitCode != 0)
562+
{
563+
return StepResult.Fail(
564+
$"Failed to restore gateway.reload.mode after wizard (exit {result.ExitCode}): {result.Stderr.Trim()}");
565+
}
566+
567+
_ctx.Logger.Info(
568+
$"Restored gateway.reload.mode to {reloadMode} after wizard; restarting gateway to apply wizard configuration");
569+
var restartResult =
570+
await StartGatewayStep.RestartAndWaitForHealthAsync(
571+
_ctx,
572+
CancellationToken.None);
573+
if (!restartResult.IsSuccess)
574+
{
575+
return StepResult.Fail(
576+
$"Gateway restart after wizard failed: {restartResult.Message}",
577+
restartResult.Error);
578+
}
579+
580+
var ownershipResult = await VerifyExpectedManagedGatewayAsync(
581+
"after restoring gateway reload");
582+
if (!ownershipResult.IsSuccess)
583+
return ownershipResult;
584+
585+
return StepResult.Ok(
586+
$"Restored gateway.reload.mode to {reloadMode} and restarted gateway");
415587
}
416588
catch (Exception ex)
417589
{
418-
_ctx.Logger.Warn($"Failed to reset gateway.reload.mode after wizard: {ex.Message}");
590+
return StepResult.Fail(
591+
$"Failed to restore gateway.reload.mode after wizard: {ex.Message}",
592+
ex);
419593
}
420594
}
421595

596+
private async Task<StepResult> VerifyExpectedManagedGatewayAsync(string phase)
597+
{
598+
var provenanceResult =
599+
await PairOperatorStep.EnsurePairingEndpointTrustedAsync(
600+
_ctx,
601+
CancellationToken.None,
602+
noListenerRetryCount: 30,
603+
noListenerRetryDelay: TimeSpan.FromSeconds(1));
604+
return provenanceResult is null
605+
? StepResult.Ok($"Verified managed gateway ownership {phase}")
606+
: StepResult.Fail(
607+
$"Gateway ownership verification failed {phase}: {provenanceResult.Message}",
608+
provenanceResult.Error);
609+
}
610+
611+
private static Exception? CombineErrors(Exception? first, Exception? second) =>
612+
(first, second) switch
613+
{
614+
(null, null) => null,
615+
(not null, null) => first,
616+
(null, not null) => second,
617+
_ => new AggregateException(first!, second!),
618+
};
619+
422620
private string WriteAnswerTemplate(IReadOnlyList<WizardTemplateStep> discoveredSteps, WizardPayload? missingStep)
423621
{
424622
var logPath = _ctx.Config.LogPath;

0 commit comments

Comments
 (0)