Skip to content

Commit c14ead3

Browse files
shanselmanCopilot
andauthored
fix(setup): complete wizard on terminal hosted TUI SIGTERM (#1132)
The gateway tears down its in-process hosted wizard TUI when the configuration applied by the final wizard step restarts the gateway. Setup answered every step through the final `done` acknowledgement, then received a terminal payload whose error was exactly `Error: TUI exited from signal SIGTERM`, failed the run-wizard step, and issued a best-effort wizard.cancel against a gateway that was already restarting. Two independent Windows-node release-check lanes reproduced this after successful pairing, verify-e2e, reload-mode restoration, managed restart, health, and provenance checks. Accept that one terminal result as completion, and only that one. The payload must be terminal, the request just sent must have answered the authoritative final step (a plain acknowledgement note with no options whose id or title normalizes to `done`, last in order when the gateway supplies position metadata), and the error must equal the exact message apart from surrounding whitespace. Every other terminal error, an earlier SIGTERM, a progress poll, a replayed session, an answerable step, and a non-terminal payload keep the wizard failure and keep cancellation. Terminal-payload classification now goes through a pure decision seam, and the final-step flag is owned by a tracker, so the accepted path and each rejected path are directly testable. #1129 reload-mode restoration, its exact startup-migration-lease retry inside the 15 second deadline, cancellation and restoration ordering, and the one-shot managed restart are unchanged. Co-authored-by: Copilot App <[email protected]>
1 parent 77141d2 commit c14ead3

9 files changed

Lines changed: 563 additions & 16 deletions

‎docs/ARCHITECTURE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ leading and trailing pipe. Columns, in order:
122122
| setup-shellescape-closed | closed | src/OpenClaw.SetupEngine/SetupSteps.cs | private ShellEscape helpers with divergent wrap semantics | WslShellQuoting | - | SetupSteps builds WSL command lines only via WslShellQuoting; no local ShellEscape helper | SetupStepsShellEscapeClosureTests.SetupSteps_DoesNotReintroduce_PrivateShellEscape | source-shape | when SetupSteps.cs no longer builds any WSL command strings |
123123
| wsl-distro-install-path | authoritative | OpenClaw.SetupEngine/SetupSteps.cs | inline Path.Combine wsl distro install-path derivation | DistroInstallPathPolicy | - | new installs use the strict supported name grammar; teardown accepts only unambiguous single-segment names whose canonical path is an immediate child of LocalDataDir\wsl with no aliases, case or Unicode collisions, or reparse points at the root or child | SetupStepsTests.DistroInstallPathPolicy_ResolvesImmediateChild | behavioral | - |
124124
| managed-local-provenance | authoritative | scattered connection, setup, browser, and reconnect call sites | implicit loopback trust and duplicated strong-credential listener checks | ManagedLocalGatewayPortProvenanceService | callers request inspection, authorization, or conflict repair only | unknown, incomplete, conflicting, or changed Windows listener ownership never receives strong credentials or destructive remediation; relayless ownership requires a complete empty Windows snapshot, expected-distro systemd MainPID proof, and immediate complete empty revalidation | ManagedLocalGatewayPortProvenanceServiceTests.InteractiveCredentialGate_ExpectedCacheThenOwnerChanges_FailsClosed | behavioral | - |
125-
| gateway-wizard-restart-recovery | authoritative | WizardPage + SetupWizardRunner reconnect call sites | duplicated exact-version terminal-restart classification and bounded provenance retry orchestration | GatewayWizardRestartRecoveryPolicy | WizardPage and SetupWizardRunner apply hosted and headless lifecycle and consume provenance inspection results | only managed-local restart-like disconnects may retry NoListener or the typed snapshot-changed race; other unknown or conflicting ownership fails immediately, retryable startup close 1013 stays inside the existing reconnect bound, and exact Gateway 2026.7.1 final model-check close 1012 completes only after a fresh hello-ok | GatewayWizardRestartRecoveryPolicyTests.Exact2026_7_1TerminalModelCheckServiceRestart_IsExpected | behavioral | when the 2026.7.1 terminal-restart compatibility path is removed |
125+
| gateway-wizard-restart-recovery | authoritative | WizardPage + SetupWizardRunner reconnect call sites | duplicated exact-version terminal-restart classification and bounded provenance retry orchestration | GatewayWizardRestartRecoveryPolicy | WizardPage and SetupWizardRunner apply hosted and headless lifecycle and consume provenance inspection results | only managed-local restart-like disconnects may retry NoListener or the typed snapshot-changed race; other unknown or conflicting ownership fails immediately, retryable startup close 1013 stays inside the existing reconnect bound, and exact Gateway 2026.7.1 final model-check close 1012 completes only after a fresh hello-ok, and a terminal hosted-wizard payload completes on the exact TUI SIGTERM termination only when the request just sent answered the authoritative final done acknowledgement step | GatewayWizardRestartRecoveryPolicyTests.Exact2026_7_1TerminalModelCheckServiceRestart_IsExpected | behavioral | when the 2026.7.1 terminal-restart compatibility path is removed |
126126
| managed-local-repair | authoritative | src/OpenClaw.Tray.WinUI/App.xaml.cs and direct reconnect callbacks | repair eligibility, restart budgets, port remediation, and reconnect verification | ManagedLocalGatewayAutoRepairMonitor + ManagedLocalGatewayRepairCoordinator | App composition and dependency callbacks only | explicit disconnect and gateway switches abort repair before restart or reconnect | ManagedLocalGatewayRepairCoordinatorTests.UserDisconnectedIntent_AbortsBeforeProbeOrRestart | behavioral | - |
127127
| app-managed-local-repair-closed | closed | src/OpenClaw.Tray.WinUI/App.xaml.cs | managed-local repair loops, probing, restart budgeting, and verification implementation | ManagedLocalGatewayAutoRepairMonitor + ManagedLocalGatewayRepairCoordinator | service construction, callback adapters, and lifetime wiring only | App remains the composition root and does not regain repair implementation | AppRefactorContractTests.ManagedLocalGatewayRepair_StaysDelegatedToDedicatedOwners | source-shape | when App no longer constructs the managed-local repair services directly |
128128
| connection-page-direct-connect-closed | closed | src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs | direct-connect registry, identity-token, settings, rollback, terminal-wait, and runtime-tunnel transaction | GatewayDirectConnectService | add-form control reads, input validation, result text, and post-success visual refresh only | the page delegates one request; rollback restores the durable registry before identity and settings, reconnects a previously live gateway, and a later credential writer wins | GatewayDirectConnectServiceTests.Connect_Failure_RestoresPreviousLiveConnection | behavioral | when the Connection page no longer contains any direct-connect persistence or rollback logic |

‎docs/ONBOARDING_WIZARD.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ The wizard keeps recovery choices visible while setup steps are running so users
4949

5050
Exact Gateway 2026.7.1 has a terminal compatibility path for an app-managed local WSL gateway. When the final `model-check` answer produces WebSocket close 1012 before the gateway can return `done`, setup retries the temporary `NoListener` state and the typed snapshot-changed race that can occur while the listener is restarting. Other unknown or conflicting endpoint ownership fails immediately, and no credential is sent until the managed endpoint is verified again. A retryable startup close 1013 remains inside the existing reconnect timeout. Setup completes only after a fresh authenticated `hello-ok` handshake. Other versions and steps keep the normal managed-local wizard replay behavior with the same bounded ownership wait; remote gateways and other disconnects do not enter this recovery path.
5151

52+
The headless setup engine also treats one terminal wizard payload as completion instead of failure. When the answers applied by the wizard restart the gateway, the gateway can tear down its own hosted wizard TUI and return a terminal payload whose error is exactly `Error: TUI exited from signal SIGTERM`. Setup accepts that result only when the payload is terminal and the request it just sent answered the authoritative final step, so the wizard is not cancelled after it already finished. The final step must be a plain acknowledgement note with no options whose id or title normalizes to `done`, and when the gateway supplies step position metadata it must also be the last step. An earlier `SIGTERM`, a progress poll, a replayed wizard session, any answerable step, any other step id or title, a non-terminal payload, and any other message (different signal, extra text, or different casing) all keep the wizard failure. Only surrounding whitespace is tolerated in the message. Reload-mode restoration, the one-shot managed restart, health verification, and provenance checks are unchanged and still fail closed.
53+
5254
When the gateway config wizard surfaces an error and the active gateway is an app-managed WSL distro, the error state also offers **Open terminal** and **Restart gateway**. The wizard does not parse or classify the gateway's error text; it leaves the message visible and selectable so the user can copy any command the gateway reports. The buttons reuse the shared `GatewayTerminalLauncher` and `WslGatewayController` (in `OpenClaw.Connection`, also used by the Connections tab). Restart re-enters the gateway config wizard (the provider/model onboarding step - not the whole V2 onboarding, and without re-installing the WSL distro) so fixes such as newly-installed tools are picked up on `PATH`. Because the gateway restart clears its wizard session, this resumes at the first config question rather than the exact step that failed. Detection is gated on `GatewayRecord.SetupManagedDistroName`, so it never appears for remote/SSH gateways.
5355

5456
### All set

‎src/OpenClaw.SetupEngine/GatewayWizardRestartRecoveryPolicy.cs‎

Lines changed: 53 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,14 @@ internal static class GatewayWizardRestartRecoveryPolicy
77
{
88
private const string TerminalRestartVersion = "2026.7.1";
99
private const string TerminalStepKey = "model-check";
10+
private const string FinalWizardStepKey = "done";
11+
12+
/// <summary>
13+
/// Exact terminal error the gateway reports when a config-driven gateway restart
14+
/// terminates the hosted wizard TUI process.
15+
/// </summary>
16+
public const string HostedWizardTerminationError =
17+
"Error: TUI exited from signal SIGTERM";
1018

1119
public static bool IsTerminalRestartCandidate(
1220
string? gatewayVersion,
@@ -17,7 +25,44 @@ public static bool IsTerminalRestartCandidate(
1725
gatewayVersion?.Trim(),
1826
TerminalRestartVersion,
1927
StringComparison.Ordinal) &&
20-
IsTerminalStep(stepId, title, message);
28+
MatchesStepKey(TerminalStepKey, stepId, title, message);
29+
30+
/// <summary>
31+
/// True when a wizard step is the authoritative final <c>done</c> step. The gateway
32+
/// assigns opaque step ids, so the step is identified by its normalized id or title.
33+
/// It must be a plain acknowledgement note with no options, and when the gateway
34+
/// supplies position metadata the step must also be the last one.
35+
/// </summary>
36+
public static bool IsAuthoritativeFinalWizardStep(
37+
string? stepType,
38+
string? stepId,
39+
string? title,
40+
bool hasOptions,
41+
int stepIndex,
42+
int totalSteps) =>
43+
!hasOptions &&
44+
WizardStepClassifier.Categorize(stepType, hasOptions) ==
45+
WizardStepCategory.Acknowledge &&
46+
(MatchesStepKey(FinalWizardStepKey, stepId) ||
47+
MatchesStepKey(FinalWizardStepKey, title)) &&
48+
(totalSteps <= 0 || stepIndex == totalSteps - 1 || stepIndex == totalSteps);
49+
50+
/// <summary>
51+
/// True only when a terminal wizard payload reports the exact hosted-TUI termination
52+
/// error after the authoritative final <c>done</c> step was already answered. Only
53+
/// surrounding whitespace is tolerated: every other terminal error, an earlier step,
54+
/// a non-terminal payload, and any other message keeps the wizard failure.
55+
/// </summary>
56+
public static bool IsHostedWizardTerminationAfterFinalStep(
57+
bool payloadIsTerminal,
58+
string? error,
59+
bool answeredAuthoritativeFinalStep) =>
60+
payloadIsTerminal &&
61+
answeredAuthoritativeFinalStep &&
62+
string.Equals(
63+
error?.Trim(),
64+
HostedWizardTerminationError,
65+
StringComparison.Ordinal);
2166

2267
public static bool IsExpectedTerminalRestart(
2368
string? gatewayVersion,
@@ -90,15 +135,16 @@ private static bool IsServiceRestartDisconnect(Exception exception)
90135
return false;
91136
}
92137

93-
private static bool IsTerminalStep(
138+
private static bool MatchesStepKey(
139+
string expectedKey,
94140
string? stepId,
95141
string? title,
96142
string? message) =>
97-
IsTerminalStepKey(stepId) ||
98-
IsTerminalStepKey(title) ||
99-
IsTerminalStepKey(message);
143+
MatchesStepKey(expectedKey, stepId) ||
144+
MatchesStepKey(expectedKey, title) ||
145+
MatchesStepKey(expectedKey, message);
100146

101-
private static bool IsTerminalStepKey(string? value)
147+
private static bool MatchesStepKey(string expectedKey, string? value)
102148
{
103149
if (string.IsNullOrWhiteSpace(value))
104150
return false;
@@ -110,6 +156,6 @@ private static bool IsTerminalStepKey(string? value)
110156
.Split(
111157
[' ', '\t', '\r', '\n', '_', '-'],
112158
StringSplitOptions.RemoveEmptyEntries));
113-
return string.Equals(normalized, TerminalStepKey, StringComparison.Ordinal);
159+
return string.Equals(normalized, expectedKey, StringComparison.Ordinal);
114160
}
115161
}

‎src/OpenClaw.SetupEngine/SetupWizardRunner.cs‎

Lines changed: 64 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,7 @@ private async Task<StepResult> RunCoreAsync(CancellationToken ct)
259259
var totalProgressPolls = 0;
260260
var lastProgressStepId = "";
261261
var interactiveSteps = 0;
262+
var finalStepTracker = new WizardFinalStepTracker();
262263

263264
// A reconnect restarts the wizard session, so reset replay-scoped
264265
// counters before processing the replacement start payload.
@@ -362,6 +363,7 @@ await PairOperatorStep.EnsurePairingEndpointTrustedAsync(
362363
progressPolls = 0;
363364
totalProgressPolls = 0;
364365
lastProgressStepId = "";
366+
finalStepTracker.ResetForNewSession();
365367
return await SendWizardStartAsync(client);
366368
}
367369
}
@@ -375,14 +377,15 @@ await PairOperatorStep.EnsurePairingEndpointTrustedAsync(
375377
{
376378
if (!string.IsNullOrWhiteSpace(parsed.Error))
377379
{
378-
if (IsKnownGatewayFinalizationPromptBug(parsed.Error))
379-
{
380-
wizardCompleted = true;
381-
_ctx.Logger.Warn($"Gateway wizard ended after applying setup but hit known finalization prompt bug: {parsed.Error}");
382-
return StepResult.Ok("Gateway wizard completed with non-fatal finalization prompt warning");
383-
}
384-
385-
return StepResult.Fail($"Gateway wizard failed: {parsed.Error}");
380+
var decision = DecideTerminalWizardError(
381+
parsed.IsDone,
382+
parsed.Error,
383+
finalStepTracker.AnsweredFinalStep);
384+
if (decision.LogWarning is not null)
385+
_ctx.Logger.Warn(decision.LogWarning);
386+
387+
wizardCompleted = decision.MarksWizardCompleted;
388+
return decision.Result;
386389
}
387390

388391
if (discoveredSteps.Count > 0)
@@ -430,6 +433,7 @@ await PairOperatorStep.EnsurePairingEndpointTrustedAsync(
430433
: $"Wizard progress: {progressText}");
431434

432435
await Task.Delay(WizardTimeouts.ProgressPollDelay, ct);
436+
finalStepTracker.RecordProgressAcknowledgement();
433437
payload = await SendWizardNextAsync(
434438
WizardNextPayload.Acknowledge(sessionId, parsed.StepId),
435439
TimeoutFor(parsed),
@@ -476,6 +480,13 @@ await PairOperatorStep.EnsurePairingEndpointTrustedAsync(
476480
}
477481
: WizardNextPayload.Acknowledge(sessionId, parsed.StepId);
478482

483+
finalStepTracker.RecordAnsweredStep(
484+
parsed.StepType,
485+
parsed.StepId,
486+
parsed.Title,
487+
parsed.Options.Count > 0,
488+
parsed.StepIndex,
489+
parsed.TotalSteps);
479490
payload = await SendWizardNextAsync(
480491
parameters,
481492
TimeoutFor(parsed, answerResult.Answer),
@@ -881,6 +892,51 @@ private static bool IsKnownGatewayFinalizationPromptBug(string error)
881892
return error.Contains("this.prompt is not a function", StringComparison.OrdinalIgnoreCase);
882893
}
883894

895+
/// <summary>
896+
/// Classifies a terminal wizard payload that carries an error. Only a known
897+
/// non-fatal finalization prompt bug, or the exact hosted-TUI termination reported
898+
/// immediately after the authoritative final step, count as completion; everything
899+
/// else stays a wizard failure and never marks the wizard completed.
900+
/// </summary>
901+
internal static WizardTerminalDecision DecideTerminalWizardError(
902+
bool payloadIsTerminal,
903+
string error,
904+
bool answeredFinalWizardStep)
905+
{
906+
if (payloadIsTerminal && IsKnownGatewayFinalizationPromptBug(error))
907+
{
908+
return new WizardTerminalDecision(
909+
MarksWizardCompleted: true,
910+
StepResult.Ok("Gateway wizard completed with non-fatal finalization prompt warning"),
911+
$"Gateway wizard ended after applying setup but hit known finalization prompt bug: {error}");
912+
}
913+
914+
// The gateway terminates its hosted wizard TUI when the configuration applied by
915+
// the final step restarts the gateway. That is completion, not failure, but only
916+
// for the exact terminal message right after the authoritative final step.
917+
if (GatewayWizardRestartRecoveryPolicy.IsHostedWizardTerminationAfterFinalStep(
918+
payloadIsTerminal,
919+
error,
920+
answeredFinalWizardStep))
921+
{
922+
return new WizardTerminalDecision(
923+
MarksWizardCompleted: true,
924+
StepResult.Ok(
925+
"Gateway wizard completed; the gateway terminated its hosted wizard TUI after the final step"),
926+
$"Gateway wizard applied every step through the final step and then terminated its hosted TUI: {error}");
927+
}
928+
929+
return new WizardTerminalDecision(
930+
MarksWizardCompleted: false,
931+
StepResult.Fail($"Gateway wizard failed: {error}"),
932+
LogWarning: null);
933+
}
934+
935+
internal sealed record WizardTerminalDecision(
936+
bool MarksWizardCompleted,
937+
StepResult Result,
938+
string? LogWarning);
939+
884940
private static string AnswerPlaceholderFor(WizardTemplateStep step)
885941
{
886942
return step.Type switch
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
namespace OpenClaw.SetupEngine;
2+
3+
/// <summary>
4+
/// Tracks whether the wizard request that is about to be sent answers the authoritative
5+
/// final step. Only that request may be followed by a terminal hosted-TUI termination
6+
/// that counts as completion, so every other transition clears the flag.
7+
/// </summary>
8+
internal sealed class WizardFinalStepTracker
9+
{
10+
/// <summary>True when the most recent request answered the authoritative final step.</summary>
11+
public bool AnsweredFinalStep { get; private set; }
12+
13+
/// <summary>Clears the flag for a fresh or replayed wizard session.</summary>
14+
public void ResetForNewSession() => AnsweredFinalStep = false;
15+
16+
/// <summary>A progress poll carries no answer, so it is never the final step.</summary>
17+
public void RecordProgressAcknowledgement() => AnsweredFinalStep = false;
18+
19+
/// <summary>Records the step whose answer is about to be sent.</summary>
20+
public void RecordAnsweredStep(
21+
string? stepType,
22+
string? stepId,
23+
string? title,
24+
bool hasOptions,
25+
int stepIndex,
26+
int totalSteps) =>
27+
AnsweredFinalStep =
28+
GatewayWizardRestartRecoveryPolicy.IsAuthoritativeFinalWizardStep(
29+
stepType,
30+
stepId,
31+
title,
32+
hasOptions,
33+
stepIndex,
34+
totalSteps);
35+
}

0 commit comments

Comments
 (0)