Skip to content

Commit 84d2e6a

Browse files
bkudiessCopilotCopilotshanselman
authored
Make setup wizard resilient to richer gateway protocol steps (#824)
* Wizard protocol resilience: progress/non-interactive steps, auth prompts, restart hardening Co-authored-by: Copilot <[email protected]> * Harden wizard progress polling budget Allow a single long-running gateway progress step to use the full bounded progress budget instead of failing after the previous shorter per-step cap. Share the progress constants between the setup runner and UI and cover the intended budget in tests. Co-authored-by: Copilot <[email protected]> --------- Co-authored-by: Copilot <[email protected]> Co-authored-by: Copilot <[email protected]> Co-authored-by: Scott Hanselman <[email protected]>
1 parent 9447c0f commit 84d2e6a

10 files changed

Lines changed: 775 additions & 151 deletions

File tree

‎src/OpenClaw.SetupEngine.UI/Pages/WizardPage.xaml.cs‎

Lines changed: 184 additions & 96 deletions
Large diffs are not rendered by default.

‎src/OpenClaw.SetupEngine/SetupWizardRunner.cs‎

Lines changed: 131 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -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
}
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
using System.Text.RegularExpressions;
2+
3+
namespace OpenClaw.SetupEngine;
4+
5+
/// <summary>The kind of content a single wizard message line carries.</summary>
6+
public enum WizardLineKind
7+
{
8+
/// <summary>Plain text.</summary>
9+
Text,
10+
11+
/// <summary>Contains an http(s) URL (e.g. an OAuth/device-authorization link).</summary>
12+
Url,
13+
14+
/// <summary>A "Code: XXXX" style device/pairing code the user must enter elsewhere.</summary>
15+
Code,
16+
}
17+
18+
/// <summary>A classified wizard message line with an optional highlighted URL or code.</summary>
19+
public sealed record WizardLineSegment(
20+
WizardLineKind Kind,
21+
string Text,
22+
string Prefix,
23+
string Highlight,
24+
string Suffix);
25+
26+
/// <summary>Detects actionable URLs and manual entry codes in wizard messages.</summary>
27+
public static class WizardMessageFormatting
28+
{
29+
// "Code: ABCD-EFGH" / "user_code = ABC123" style manual entry codes.
30+
private static readonly Regex s_codeRegex = new(
31+
@"^((?:Code|code|user_code|USER_CODE|User Code)\s*[:=]\s*)([A-Z0-9]{2,8}(?:-[A-Z0-9]{2,8})+|[A-Z0-9]{4,12})\b",
32+
RegexOptions.Compiled);
33+
34+
private static readonly Regex s_urlRegex = new(
35+
@"https?://[^\s\)\""]+",
36+
RegexOptions.Compiled | RegexOptions.IgnoreCase);
37+
38+
/// <summary>Classifies a line as plain text, URL, or device-code text.</summary>
39+
public static WizardLineSegment ClassifyLine(string? line)
40+
{
41+
var trimmed = (line ?? string.Empty).TrimEnd('\r');
42+
43+
var codeMatch = s_codeRegex.Match(trimmed);
44+
if (codeMatch.Success)
45+
{
46+
return new WizardLineSegment(
47+
WizardLineKind.Code,
48+
trimmed,
49+
Prefix: codeMatch.Groups[1].Value,
50+
Highlight: codeMatch.Groups[2].Value,
51+
Suffix: string.Empty);
52+
}
53+
54+
var urlMatch = s_urlRegex.Match(trimmed);
55+
if (urlMatch.Success)
56+
{
57+
var url = urlMatch.Value.TrimEnd('.', ',');
58+
if (Uri.TryCreate(url, UriKind.Absolute, out _))
59+
{
60+
var index = trimmed.IndexOf(urlMatch.Value, StringComparison.Ordinal);
61+
var prefix = index > 0 ? trimmed[..index] : string.Empty;
62+
var suffix = trimmed[(index + urlMatch.Value.Length)..];
63+
return new WizardLineSegment(WizardLineKind.Url, trimmed, prefix, url, suffix);
64+
}
65+
}
66+
67+
return new WizardLineSegment(WizardLineKind.Text, trimmed, trimmed, string.Empty, string.Empty);
68+
}
69+
70+
/// <summary>Returns all distinct absolute http(s) URLs found in a message.</summary>
71+
public static IReadOnlyList<string> ExtractUrls(string? message)
72+
{
73+
if (string.IsNullOrWhiteSpace(message))
74+
return Array.Empty<string>();
75+
76+
var urls = new List<string>();
77+
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
78+
foreach (Match match in s_urlRegex.Matches(message))
79+
{
80+
var url = match.Value.TrimEnd('.', ',');
81+
if (Uri.TryCreate(url, UriKind.Absolute, out _) && seen.Add(url))
82+
urls.Add(url);
83+
}
84+
85+
return urls;
86+
}
87+
88+
/// <summary>True when the message contains at least one actionable auth URL.</summary>
89+
public static bool ContainsAuthUrl(string? message) => ExtractUrls(message).Count > 0;
90+
}

0 commit comments

Comments
 (0)