Skip to content

Commit b75d04d

Browse files
authored
fix(macos): finish ChatGPT login after Gateway reconnect
Closes #134182 ## What Problem This Solves Fixes an issue where users who started ChatGPT Login during macOS onboarding could receive a generic Gateway transport error after the socket reconnected. The callback was rejected before dispatch, but the app cancelled the live wizard session and left the visible Submit control unable to send another request. ## Why This Change Was Made The native onboarding owner now retries only the typed `notDispatched` failure, which proves the callback did not reach the Gateway. It reacquires the same route, preserves the existing wizard session and answer, and sends one replacement request. Post-dispatch failures, provider errors, cancellation, route changes, and a failed replacement request keep their existing cancellation and reconciliation behavior. The retry never starts a second provider login. ## User Impact ChatGPT Login can finish after a same-route Gateway socket reconnect during the browser flow. Users still see the provider's real error when the provider rejects the callback. ## Evidence | Proof | Result | | --- | --- | | [Exact-main macOS run](https://github.com/openclaw/openclaw/actions/runs/33404854399) at `2278fbc9df879d52efbb6a0b81f7798a9f7c16c1` plus the regression test | The replacement socket received no `wizard.next`; onboarding sent `wizard.cancel`, showed `OpenClawChatTransportSendError error 0`, and stayed disconnected. | | [Exact-head pull request CI](https://github.com/openclaw/openclaw/actions/runs/33414196718) at `a603799a69a9d230d34de146769174ffe3e169b5` | Swift lint, native release build, existing onboarding tests, and the focused stale-lease regression passed. All required checks are green. | The regression rotates the physical socket after provider auth starts. It verifies that one replacement `wizard.next` carries the same session ID, step ID, and callback value, and that no wizard cancellation occurs. Production LOC: +52/-33, net +19. Of these additions, 25 are a pure move of existing non-localized helpers into the existing support file so the owner stays under its enforced file-length limit without changing the string inventory. The remaining growth implements the typed, same-route, exactly-once recovery boundary. Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 3c150ea commit b75d04d

3 files changed

Lines changed: 129 additions & 33 deletions

File tree

‎apps/macos/Sources/OpenClaw/OnboardingAISetup.swift‎

Lines changed: 27 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -753,20 +753,6 @@ extension OnboardingAISetupModel {
753753
"No Gateway is selected. Select a Gateway, then try again.")
754754
}
755755

756-
/// Candidates the automatic ladder may try: skip definitively logged-out
757-
/// installs and anything already attempted.
758-
private func autoCandidateAfter(kind: String?) -> Candidate? {
759-
let startIndex: Int = if let kind, let index = candidates.firstIndex(where: { $0.kind == kind }) {
760-
index + 1
761-
} else {
762-
0
763-
}
764-
guard startIndex <= self.candidates.count else { return nil }
765-
return self.candidates[startIndex...].first { candidate in
766-
candidate.credentials != false && self.statuses[candidate.kind] == .untried
767-
}
768-
}
769-
770756
func userSelect(kind: String) {
771757
guard self.canSelectCandidate(kind: kind) else { return }
772758
var supersededKind: String?
@@ -1241,17 +1227,6 @@ extension OnboardingAISetupModel {
12411227
}
12421228
}
12431229

1244-
func continueProviderAuth() {
1245-
guard let step = authStep else { return }
1246-
let value: AnyCodable? = switch wizardStepType(step) {
1247-
case "text": AnyCodable(self.authText)
1248-
case "select": self.selectedAuthWizardOption?.value
1249-
case "confirm": AnyCodable(self.authConfirmation)
1250-
default: nil
1251-
}
1252-
self.advanceProviderAuth(stepID: step.id, value: value)
1253-
}
1254-
12551230
func cancelProviderAuth() {
12561231
let sessionID = self.authSessionID
12571232
let authServerLease = self.serverLease
@@ -1291,7 +1266,7 @@ extension OnboardingAISetupModel {
12911266
}
12921267
}
12931268

1294-
private func advanceProviderAuth(stepID: String?, value: AnyCodable?) {
1269+
func advanceProviderAuth(stepID: String?, value: AnyCodable?) {
12951270
guard let sessionID = authSessionID, let serverLease else { return }
12961271
self.authBusy = true
12971272
self.authError = nil
@@ -1306,12 +1281,31 @@ extension OnboardingAISetupModel {
13061281
let token = self.attemptToken
13071282
let authAttemptID = self.authAttemptID
13081283
Task {
1284+
var requestLease = serverLease
13091285
do {
1310-
let data = try await self.gateway.request(
1311-
method: "wizard.next",
1312-
params: params,
1313-
timeoutMs: Self.providerAuthRequestTimeoutMs,
1314-
ifCurrentServerLease: serverLease)
1286+
let data: Data
1287+
do {
1288+
data = try await self.gateway.request(
1289+
method: "wizard.next",
1290+
params: params,
1291+
timeoutMs: Self.providerAuthRequestTimeoutMs,
1292+
ifCurrentServerLease: requestLease)
1293+
} catch OpenClawChatTransportSendError.notDispatched {
1294+
guard token == self.attemptToken, authAttemptID == self.authAttemptID else { return }
1295+
// Only this error proves the callback never reached the Gateway.
1296+
// Keep the wizard identity and retry once on the same route.
1297+
let replacementLease = try await self.gateway.acquireServerLease(
1298+
ifSameRouteAs: requestLease,
1299+
timeoutMs: 5000)
1300+
guard token == self.attemptToken, authAttemptID == self.authAttemptID else { return }
1301+
requestLease = replacementLease
1302+
self.serverLease = requestLease
1303+
data = try await self.gateway.request(
1304+
method: "wizard.next",
1305+
params: params,
1306+
timeoutMs: Self.providerAuthRequestTimeoutMs,
1307+
ifCurrentServerLease: requestLease)
1308+
}
13151309
guard token == self.attemptToken, authAttemptID == self.authAttemptID else { return }
13161310
let result = try JSONDecoder().decode(WizardNextResult.self, from: data)
13171311
self.applyAuthWizardResult(
@@ -1321,13 +1315,13 @@ extension OnboardingAISetupModel {
13211315
error: result.error,
13221316
preparedModelRef: result.preparedmodelref)
13231317
} catch {
1324-
let cancellation = await self.gateway.cancelWizardSession(sessionID, on: serverLease)
1318+
let cancellation = await self.gateway.cancelWizardSession(sessionID, on: requestLease)
13251319
guard token == self.attemptToken, authAttemptID == self.authAttemptID else { return }
13261320
if cancellation != .cancelled,
13271321
await self.reconcileProviderAuthAfterUnknownOutcome(
13281322
token: token,
13291323
before: self.lastDetectedActivationState,
1330-
originalServerLease: serverLease)
1324+
originalServerLease: requestLease)
13311325
{
13321326
return
13331327
}

‎apps/macos/Sources/OpenClaw/OnboardingAISetupSupport.swift‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,31 @@ extension OnboardingAISetupModel {
236236
self.startProviderWizard(option, kind: .auth)
237237
}
238238

239+
func continueProviderAuth() {
240+
guard let step = authStep else { return }
241+
let value: AnyCodable? = switch wizardStepType(step) {
242+
case "text": AnyCodable(self.authText)
243+
case "select": self.selectedAuthWizardOption?.value
244+
case "confirm": AnyCodable(self.authConfirmation)
245+
default: nil
246+
}
247+
self.advanceProviderAuth(stepID: step.id, value: value)
248+
}
249+
250+
/// Candidates the automatic ladder may try: skip definitively logged-out
251+
/// installs and anything already attempted.
252+
func autoCandidateAfter(kind: String?) -> Candidate? {
253+
let startIndex: Int = if let kind, let index = candidates.firstIndex(where: { $0.kind == kind }) {
254+
index + 1
255+
} else {
256+
0
257+
}
258+
guard startIndex <= self.candidates.count else { return nil }
259+
return self.candidates[startIndex...].first { candidate in
260+
candidate.credentials != false && self.statuses[candidate.kind] == .untried
261+
}
262+
}
263+
239264
func startProviderPrepare(_ option: PrepareOption) {
240265
self.startProviderWizard(
241266
AuthOption(

‎apps/macos/Tests/OpenClawIPCTests/OnboardingAISetupTests.swift‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1137,6 +1137,83 @@ struct OnboardingAISetupTests {
11371137
#expect(model.authError == nil)
11381138
}
11391139

1140+
@Test func `provider auth callback reacquires its route after a pre-dispatch disconnect`() async throws {
1141+
let defaults = try #require(isolatedAISetupDefaults(prefix: "OnboardingProviderAuthReconnectTests"))
1142+
let detections = AISetupSocketGeneration()
1143+
let answeredSessions = LockIsolated<[String]>([])
1144+
let cancelledSessions = LockIsolated<[String]>([])
1145+
let url = try #require(URL(string: "ws://example.invalid"))
1146+
let harness = AISetupHarness(url: url) { _, request, _ in
1147+
switch request.method {
1148+
case "openclaw.setup.detect":
1149+
return detections.claim() == 0
1150+
? detectedSetupResponse(id: request.id)
1151+
: persistedDetectedSetupResponse(id: request.id)
1152+
case "openclaw.setup.auth.start":
1153+
let sessionID = try #require(request.params["sessionId"] as? String)
1154+
return Data(
1155+
"""
1156+
{"type":"res","id":"\(request.id)","ok":true,"payload":{
1157+
"sessionId":"\(sessionID)","done":false,"status":"running",
1158+
"step":{"id":"login","type":"text","executor":"client",
1159+
"message":"Enter the sign-in response"}}}
1160+
""".utf8)
1161+
case "wizard.next":
1162+
let sessionID = try #require(request.params["sessionId"] as? String)
1163+
let answer = try #require(request.params["answer"] as? [String: Any])
1164+
#expect(answer["stepId"] as? String == "login")
1165+
#expect(answer["value"] as? String == "callback-value")
1166+
answeredSessions.withValue { $0.append(sessionID) }
1167+
return wizardDoneResponse(id: request.id, sessionID: sessionID)
1168+
case "wizard.cancel":
1169+
let sessionID = try #require(request.params["sessionId"] as? String)
1170+
cancelledSessions.withValue { $0.append(sessionID) }
1171+
return Data(
1172+
#"{"type":"res","id":"\#(request.id)","ok":true,"payload":{"status":"cancelled"}}"#.utf8)
1173+
default:
1174+
Issue.record("Unexpected setup request: \(request.method)")
1175+
return successfulEmptyResponse(id: request.id)
1176+
}
1177+
}
1178+
let model = harness.model(defaults: defaults)
1179+
let option = OnboardingAISetupModel.AuthOption(
1180+
id: "test-provider-login", brandId: nil, label: "Test provider", hint: nil,
1181+
groupLabel: nil, icon: nil, website: nil, kind: "oauth", featured: false)
1182+
1183+
await model.detectAndAutoConnect()
1184+
model.startProviderAuth(option)
1185+
for _ in 0..<200 where model.authStep == nil {
1186+
try await Task.sleep(for: .milliseconds(5))
1187+
}
1188+
let sessionID = try #require(model._test_authSessionID)
1189+
let staleLease = try #require(await harness.gateway.captureServerLease())
1190+
let firstSocket = try #require(harness.session.latestTask())
1191+
1192+
firstSocket.emitReceiveFailure()
1193+
for _ in 0..<200 {
1194+
guard await harness.gateway.isCurrentServerLease(staleLease) else { break }
1195+
try await Task.sleep(for: .milliseconds(5))
1196+
}
1197+
#expect(await !harness.gateway.isCurrentServerLease(staleLease))
1198+
model.authText = "callback-value"
1199+
model.continueProviderAuth()
1200+
for _ in 0..<400 where !model.connected && model.authError == nil {
1201+
try await Task.sleep(for: .milliseconds(5))
1202+
}
1203+
1204+
#expect(answeredSessions.value == [sessionID])
1205+
#expect(cancelledSessions.value.isEmpty)
1206+
#expect(harness.session.snapshotMakeCount() == 2)
1207+
#expect(model.authError == nil)
1208+
#expect(model.connected)
1209+
1210+
let requestCount = (await harness.recorder.snapshot()).methods.count
1211+
model.continueProviderAuth()
1212+
await settleQueuedAISetupTasks()
1213+
#expect((await harness.recorder.snapshot()).methods.count == requestCount)
1214+
await harness.gateway.shutdown()
1215+
}
1216+
11401217
@Test(arguments: ["timeout", "replacement-unavailable", "commit-locked", "commit-locked-after-completion"])
11411218
func `unresolved provider auth cancellation reports recovery without discarding the session`(
11421219
failure: String) async throws

0 commit comments

Comments
 (0)