@@ -10,6 +10,10 @@ public sealed class SetupWizardRunner
1010 private const int MaxWizardSteps = 50 ;
1111 private const int MaxSameStepVisits = 3 ;
1212 private static readonly Regex s_normalizeKeyRegex = new ( "[^a-z0-9]+" , RegexOptions . Compiled ) ;
13+
14+ // Progress steps can repeat while background work runs; keep bounded caps
15+ // so setup fails with a diagnostic instead of hanging.
16+
1317 private readonly SetupContext _ctx ;
1418
1519 public SetupWizardRunner ( SetupContext ctx )
@@ -84,7 +88,45 @@ public async Task<StepResult> RunAsync(CancellationToken ct)
8488
8589 var visits = new Dictionary < string , int > ( StringComparer . OrdinalIgnoreCase ) ;
8690 var restartAttempts = 0 ;
87- for ( var i = 0 ; i < MaxWizardSteps ; i ++ )
91+ var progressPolls = 0 ;
92+ var totalProgressPolls = 0 ;
93+ var lastProgressStepId = "" ;
94+ var interactiveSteps = 0 ;
95+
96+ // A reconnect restarts the wizard session, so reset replay-scoped
97+ // counters before processing the replacement start payload.
98+ async Task < JsonElement > SendWizardNextAsync ( object parameters , int timeoutMs )
99+ {
100+ try
101+ {
102+ return await client ! . SendWizardRequestAsync ( "wizard.next" , parameters , timeoutMs ) ;
103+ }
104+ catch ( Exception ex ) when ( ! ct . IsCancellationRequested && IsRestartLikeWizardDisconnect ( ex ) && restartAttempts < 2 )
105+ {
106+ restartAttempts ++ ;
107+ _ctx . Logger . Warn ( $ "Gateway restarted during wizard; reconnecting and replaying answers (attempt { restartAttempts } /2): { ex . Message } ") ;
108+
109+ try { await client ! . DisconnectAsync ( ) ; } catch { }
110+ client ! . Dispose ( ) ;
111+
112+ await Task . Delay ( TimeSpan . FromSeconds ( 3 ) , ct ) ;
113+ client = CreateWizardClient ( credential , identityPath , wsLogger ) ;
114+ var reconnect = await PairOperatorStep . WaitForConnectionOrPairing ( client , _ctx , TimeSpan . FromSeconds ( 30 ) , ct ) ;
115+ if ( reconnect != PairOperatorStep . ConnectionOutcome . Connected )
116+ throw new WizardFatalException ( $ "Gateway wizard reconnect failed after restart: { reconnect } ") ;
117+
118+ sessionId = "" ;
119+ visits . Clear ( ) ;
120+ discoveredSteps . Clear ( ) ;
121+ interactiveSteps = 0 ;
122+ progressPolls = 0 ;
123+ totalProgressPolls = 0 ;
124+ lastProgressStepId = "" ;
125+ return await client . SendWizardRequestAsync ( "wizard.start" , timeoutMs : 30_000 ) ;
126+ }
127+ }
128+
129+ while ( true )
88130 {
89131 ct . ThrowIfCancellationRequested ( ) ;
90132
@@ -123,6 +165,39 @@ public async Task<StepResult> RunAsync(CancellationToken ct)
123165 if ( string . IsNullOrWhiteSpace ( parsed . StepId ) )
124166 return StepResult . Fail ( "Gateway wizard step is missing an id." ) ;
125167
168+ var category = WizardStepClassifier . Categorize ( parsed . StepType , parsed . Options . Count > 0 ) ;
169+
170+ // Progress carries no answer; poll until the gateway emits the
171+ // next interactive step or reaches a bounded failure.
172+ if ( category == WizardStepCategory . Progress )
173+ {
174+ if ( ! string . Equals ( parsed . StepId , lastProgressStepId , StringComparison . Ordinal ) )
175+ {
176+ lastProgressStepId = parsed . StepId ;
177+ progressPolls = 0 ;
178+ }
179+
180+ progressPolls ++ ;
181+ totalProgressPolls ++ ;
182+ if ( progressPolls > WizardTimeouts . MaxProgressPollsPerStep )
183+ return StepResult . Fail ( $ "Gateway wizard progress step '{ parsed . StepId } ' did not complete after { WizardTimeouts . MaxProgressPollsPerStep } polls.") ;
184+ if ( totalProgressPolls > WizardTimeouts . MaxTotalProgressPolls )
185+ return StepResult . Fail ( $ "Gateway wizard did not finish after { WizardTimeouts . MaxTotalProgressPolls } progress updates.") ;
186+
187+ var progressText = $ "{ parsed . Title } { parsed . Message } ". Trim ( ) ;
188+ _ctx . Logger . Info ( string . IsNullOrWhiteSpace ( progressText )
189+ ? $ "Wizard progress step '{ parsed . StepId } ' — polling for next step"
190+ : $ "Wizard progress: { progressText } ") ;
191+
192+ await Task . Delay ( WizardTimeouts . ProgressPollDelay , ct ) ;
193+ payload = await SendWizardNextAsync ( WizardNextPayload . Acknowledge ( sessionId , parsed . StepId ) , TimeoutFor ( parsed ) ) ;
194+ continue ;
195+ }
196+
197+ interactiveSteps ++ ;
198+ if ( interactiveSteps > MaxWizardSteps )
199+ return StepResult . Fail ( $ "Gateway wizard exceeded { MaxWizardSteps } steps.") ;
200+
126201 var visitKey = $ "{ parsed . StepId } :{ parsed . StepIndex } ";
127202 visits . TryGetValue ( visitKey , out var visitCount ) ;
128203 visits [ visitKey ] = visitCount + 1 ;
@@ -142,9 +217,9 @@ public async Task<StepResult> RunAsync(CancellationToken ct)
142217
143218 _ctx . Logger . Info ( answerResult . HasAnswer
144219 ? $ "Wizard step '{ parsed . StepId } ' ({ parsed . StepType } , key={ StableAnswerKey ( parsed . Title , parsed . Message , parsed . StepId ) } ) answered with { ( parsed . Sensitive ? "[sensitive]" : $ "'{ answerResult . Answer } '") } "
145- : $ "Wizard step '{ parsed . StepId } ' ({ parsed . StepType } ) continuing without explicit answer") ;
220+ : $ "Wizard step '{ parsed . StepId } ' ({ parsed . StepType } , { category } ) continuing without explicit answer") ;
146221
147- var parameters = answerResult . HasAnswer
222+ object parameters = answerResult . HasAnswer
148223 ? new
149224 {
150225 sessionId ,
@@ -154,42 +229,21 @@ public async Task<StepResult> RunAsync(CancellationToken ct)
154229 value = AnswerValueForWire ( parsed , answerResult . Answer )
155230 }
156231 }
157- : ( object ) new { sessionId } ;
232+ : WizardNextPayload . Acknowledge ( sessionId , parsed . StepId ) ;
158233
159- try
160- {
161- payload = await client . SendWizardRequestAsync ( "wizard.next" , parameters , timeoutMs : TimeoutFor ( parsed ) ) ;
162- }
163- catch ( Exception ex ) when ( ! ct . IsCancellationRequested && IsRestartLikeWizardDisconnect ( ex ) && restartAttempts < 2 )
164- {
165- restartAttempts ++ ;
166- _ctx . Logger . Warn ( $ "Gateway restarted during wizard; reconnecting and replaying answers (attempt { restartAttempts } /2): { ex . Message } ") ;
167-
168- // slopwatch-ignore: SW003 Cleanup is best-effort; failure cannot improve caller state and the original outcome is preserved.
169- try { await client . DisconnectAsync ( ) ; } catch { }
170- client . Dispose ( ) ;
171-
172- await Task . Delay ( TimeSpan . FromSeconds ( 3 ) , ct ) ;
173- client = CreateWizardClient ( credential , identityPath , wsLogger ) ;
174- var reconnect = await PairOperatorStep . WaitForConnectionOrPairing ( client , _ctx , TimeSpan . FromSeconds ( 30 ) , ct ) ;
175- if ( reconnect != PairOperatorStep . ConnectionOutcome . Connected )
176- return StepResult . Fail ( $ "Gateway wizard reconnect failed after restart: { reconnect } ") ;
177-
178- sessionId = "" ;
179- visits . Clear ( ) ;
180- discoveredSteps . Clear ( ) ;
181- payload = await client . SendWizardRequestAsync ( "wizard.start" , timeoutMs : 30_000 ) ;
182- }
234+ payload = await SendWizardNextAsync ( parameters , TimeoutFor ( parsed ) ) ;
183235 }
184-
185- return StepResult . Fail ( $ "Gateway wizard exceeded { MaxWizardSteps } steps.") ;
186236 }
187237 catch ( OperationCanceledException )
188238 {
189239 if ( client is not null && wizardStarted && ! string . IsNullOrWhiteSpace ( sessionId ) )
190240 await TryCancelWizardAsync ( client , sessionId ) ;
191241 throw ;
192242 }
243+ catch ( WizardFatalException ex )
244+ {
245+ return StepResult . Fail ( ex . Message , ex ) ;
246+ }
193247 catch ( Exception ex )
194248 {
195249 return StepResult . Fail ( $ "Gateway wizard failed: { ex . Message } ", ex ) ;
@@ -225,6 +279,7 @@ private async Task TryCancelWizardAsync(OpenClawGatewayClient client, string ses
225279 _ctx . Logger . Warn ( "Cancelling gateway wizard session" ) ;
226280 await client . SendWizardRequestAsync ( "wizard.cancel" , new { sessionId } , timeoutMs : 10_000 ) ;
227281 }
282+
228283 catch ( Exception ex )
229284 {
230285 _ctx . Logger . Warn ( $ "Failed to cancel gateway wizard session: { ex . Message } ") ;
@@ -291,19 +346,34 @@ private static AnswerResolution ResolveAnswer(WizardPayload step, Dictionary<str
291346 if ( TryGetConfiguredAnswer ( step , configuredAnswers , out var configured ) )
292347 return ValidateAnswer ( step , configured , configuredAnswer : true ) ;
293348
294- var inferred = step . StepType switch
349+ var category = WizardStepClassifier . Categorize ( step . StepType , step . Options . Count > 0 ) ;
350+ if ( WizardStepClassifier . ContinuesWithoutAnswer ( category ) )
295351 {
296- "note" => "true" ,
297- "confirm" => InferConfirmAnswer ( step ) ,
298- "select" => InferOptionAnswer ( step ) ,
299- "multiselect" => InferOptionAnswer ( step ) ,
300- "text" => InferTextAnswer ( step ) ,
301- _ => ! string . IsNullOrWhiteSpace ( step . InitialValue ) ? step . InitialValue : null
302- } ;
352+ return AnswerResolution . Continue ( ) ;
353+ }
354+
355+ switch ( category )
356+ {
357+ case WizardStepCategory . Acknowledge :
358+ return AnswerResolution . Ok ( "true" ) ;
359+
360+ case WizardStepCategory . Confirm :
361+ return ValidateAnswer ( step , InferConfirmAnswer ( step ) , configuredAnswer : false ) ;
362+ }
363+
364+ // Unknown types with options are choice prompts for wire-shaping purposes.
365+ var inferred = step . Options . Count > 0 && step . StepType != "text"
366+ ? InferOptionAnswer ( step )
367+ : step . StepType switch
368+ {
369+ "select" or "multiselect" => InferOptionAnswer ( step ) ,
370+ "text" => InferTextAnswer ( step ) ,
371+ _ => ! string . IsNullOrWhiteSpace ( step . InitialValue ) ? step . InitialValue : null
372+ } ;
303373
304374 if ( inferred == null )
305375 {
306- return AnswerResolution . Fail ( $ "Gateway wizard step '{ step . StepId } ' ({ step . StepType } ) requires a text answer .") ;
376+ return AnswerResolution . Fail ( $ "Gateway wizard step '{ step . StepId } ' ({ step . StepType } ) requires a value that was not provided .") ;
307377 }
308378
309379 return ValidateAnswer ( step , inferred , configuredAnswer : false ) ;
@@ -337,7 +407,11 @@ private static string InferConfirmAnswer(WizardPayload step)
337407
338408 private static object AnswerValueForWire ( WizardPayload step , string answer )
339409 {
340- return WizardAnswerBuilder . BuildWireValue ( step . StepType , answer , step . Options ) ;
410+ // Preserve the selected option's raw JSON value for unknown choice-style steps.
411+ var effectiveType = step . Options . Count > 0 && step . StepType is not ( "select" or "multiselect" or "text" )
412+ ? "select"
413+ : step . StepType ;
414+ return WizardAnswerBuilder . BuildWireValue ( effectiveType , answer , step . Options ) ;
341415 }
342416
343417 private static string ? InferTextAnswer ( WizardPayload step )
@@ -404,17 +478,7 @@ private static bool TryGetConfiguredAnswer(WizardPayload step, Dictionary<string
404478 return false ;
405479 }
406480
407- private static int TimeoutFor ( WizardPayload step )
408- {
409- var text = $ "{ step . Title } { step . Message } ";
410- return text . Contains ( "device" , StringComparison . OrdinalIgnoreCase )
411- || text . Contains ( "authorize" , StringComparison . OrdinalIgnoreCase )
412- || text . Contains ( "login" , StringComparison . OrdinalIgnoreCase )
413- || text . Contains ( "sign in" , StringComparison . OrdinalIgnoreCase )
414- || text . Contains ( "oauth" , StringComparison . OrdinalIgnoreCase )
415- ? 300_000
416- : 30_000 ;
417- }
481+ private static int TimeoutFor ( WizardPayload step ) => WizardTimeouts . ForStep ( step . Title , step . Message ) ;
418482
419483 private static bool IsRestartLikeWizardDisconnect ( Exception ex )
420484 {
@@ -434,7 +498,11 @@ private static string AnswerPlaceholderFor(WizardTemplateStep step)
434498 {
435499 "select" => step . Options . FirstOrDefault ( ) ? . Value ?? "<select one option value>" ,
436500 "multiselect" => "<comma-separated option values>" ,
437- "text" => step . Sensitive ? "<sensitive value>" : "<text value>" ,
501+ "text" => step . Sensitive
502+ ? "<sensitive value>"
503+ : step . AuthUrls . Count > 0
504+ ? $ "<value obtained from: { step . AuthUrls [ 0 ] } >"
505+ : "<text value>" ,
438506 _ => step . SuggestedAnswer ?? "true"
439507 } ;
440508 }
@@ -461,8 +529,12 @@ private sealed record AnswerResolution(bool Success, bool HasAnswer, string Answ
461529 {
462530 public static AnswerResolution Ok ( string answer ) => new ( true , true , answer , null ) ;
463531 public static AnswerResolution Fail ( string error ) => new ( false , false , "" , error ) ;
532+
533+ public static AnswerResolution Continue ( ) => new ( true , false , "" , null ) ;
464534 }
465535
536+ private sealed class WizardFatalException ( string message ) : Exception ( message ) ;
537+
466538 private sealed record WizardPayload (
467539 bool IsDone ,
468540 string ? SessionId ,
@@ -499,7 +571,8 @@ public static WizardPayload Parse(JsonElement payload)
499571 if ( ! payload . TryGetProperty ( "step" , out var step ) || step . ValueKind != JsonValueKind . Object )
500572 return ErrorPayload ( "Gateway wizard response is missing a step object." ) ;
501573
502- var type = step . TryGetProperty ( "type" , out var typeProperty ) ? typeProperty . ToString ( ) : "note" ;
574+ var rawType = step . TryGetProperty ( "type" , out var typeProperty ) ? typeProperty . ToString ( ) : "note" ;
575+ var type = string . IsNullOrWhiteSpace ( rawType ) ? "note" : rawType . Trim ( ) . ToLowerInvariant ( ) ;
503576 var title = step . TryGetProperty ( "title" , out var titleProperty ) ? titleProperty . ToString ( ) : "" ;
504577 var message = step . TryGetProperty ( "message" , out var messageProperty ) ? messageProperty . ToString ( ) : "" ;
505578 var stepId = step . TryGetProperty ( "id" , out var idProperty ) ? idProperty . ToString ( ) : "" ;
@@ -530,7 +603,8 @@ private sealed record WizardTemplateStep(
530603 string Message ,
531604 bool Sensitive ,
532605 string ? SuggestedAnswer ,
533- IReadOnlyList < WizardOptionValue > Options )
606+ IReadOnlyList < WizardOptionValue > Options ,
607+ IReadOnlyList < string > AuthUrls )
534608 {
535609 public static WizardTemplateStep From ( WizardPayload payload )
536610 {
@@ -549,7 +623,9 @@ public static WizardTemplateStep From(WizardPayload payload)
549623 if ( payload . Sensitive && ! string . IsNullOrWhiteSpace ( suggested ) )
550624 suggested = "<sensitive value>" ;
551625
552- return new ( payload . StepId , payload . StepType , payload . Title , payload . Message , payload . Sensitive , suggested , payload . Options ) ;
626+ var authUrls = WizardMessageFormatting . ExtractUrls ( $ "{ payload . Title } \n { payload . Message } ") ;
627+
628+ return new ( payload . StepId , payload . StepType , payload . Title , payload . Message , payload . Sensitive , suggested , payload . Options , authUrls ) ;
553629 }
554630 }
555631}
0 commit comments