1+ using System . Runtime . ExceptionServices ;
12using System . Text . Json ;
23using System . Text . RegularExpressions ;
34using 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