forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatErrorStateTests.swift
More file actions
431 lines (380 loc) · 18.5 KB
/
Copy pathChatErrorStateTests.swift
File metadata and controls
431 lines (380 loc) · 18.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
import XCTest
@testable import Omi_Computer
/// Coverage for the catch-block-to-card pipeline (lightweight — full
/// ChatProvider integration tests are out of scope here since the
/// provider is heavy to construct in isolation).
final class ChatErrorStateMappingTests: XCTestCase {
/// Every `ChatErrorRecoveryAction` must be *reachable* — produced by
/// some `ChatErrorState.primaryRecovery`. Guards against dead recovery
/// actions: an enum case with a handler in ChatProvider/ChatErrorCard
/// but no state that ever yields it. (Relies on `CaseIterable`.)
func testEveryRecoveryActionIsReachableFromSomeState() {
let allStates: [ChatErrorState] = [
.authRequired,
.timeout(toolName: nil),
.bridgeUnavailable(reason: .nodeMissing),
.bridgeUnavailable(reason: .runtimeMissing),
.bridgeUnavailable(reason: .crashed),
.bridgeUnavailable(reason: .unknown),
.interrupted,
.noDataFound,
]
let reachable = Set(allStates.map { $0.primaryRecovery })
XCTAssertEqual(
reachable, Set(ChatErrorRecoveryAction.allCases),
"Every ChatErrorRecoveryAction must be produced by some state's primaryRecovery — unreachable actions are dead code."
)
}
/// The catch-block prefers ChatErrorState over the legacy
/// errorMessage banner ONLY when the BridgeError maps. Unmappable
/// errors still surface via errorMessage so no error path becomes
/// invisible during the migration. This test locks which cases
/// map and which don't — changing the factory's mapping requires
/// updating this test, which surfaces the user-visible impact.
func testFactoryMappabilityIsStableUnderRefactor() {
XCTAssertNil(ChatErrorState.from(BridgeError.stopped))
XCTAssertNotNil(ChatErrorState.from(BridgeError.timeout))
XCTAssertNotNil(ChatErrorState.from(BridgeError.notRunning))
XCTAssertNotNil(ChatErrorState.from(BridgeError.restarting))
XCTAssertNotNil(ChatErrorState.from(BridgeError.authMissing))
// These must NOT map — they fall through to the legacy banner.
XCTAssertNil(ChatErrorState.from(BridgeError.encodingError))
XCTAssertNil(ChatErrorState.from(BridgeError.agentError("foo")))
XCTAssertNil(ChatErrorState.from(BridgeError.requestAlreadyActive))
XCTAssertNil(
ChatErrorState.from(
BridgeError.quotaExceeded(plan: "free", unit: "msg", used: 100, limit: 100, resetAtUnix: nil)
))
}
}
final class ChatErrorStateTests: XCTestCase {
// MARK: - Exhaustive recovery coverage
/// Every `ChatErrorState` case must have a `primaryRecovery`. Implemented
/// as an exhaustive switch so adding a new case here forces the
/// implementation to provide a recovery action (compiler enforced).
func testEveryCaseHasARecoveryAction() {
let cases: [ChatErrorState] = [
.authRequired,
.timeout(toolName: nil),
.timeout(toolName: "search"),
.bridgeUnavailable(reason: .nodeMissing),
.bridgeUnavailable(reason: .runtimeMissing),
.bridgeUnavailable(reason: .crashed),
.bridgeUnavailable(reason: .unknown),
.interrupted,
.noDataFound,
]
for state in cases {
// Exhaustive switch — any new case added to ChatErrorRecoveryAction
// without being assigned here will fail to compile.
switch state.primaryRecovery {
case .retry, .signIn, .installRuntime, .dismiss:
break
}
}
// Spot-check the canonical mappings so a refactor that swaps recoveries
// around fails loudly.
XCTAssertEqual(ChatErrorState.authRequired.primaryRecovery, .signIn)
XCTAssertEqual(ChatErrorState.timeout(toolName: nil).primaryRecovery, .retry)
XCTAssertEqual(ChatErrorState.interrupted.primaryRecovery, .dismiss)
XCTAssertEqual(ChatErrorState.noDataFound.primaryRecovery, .dismiss)
XCTAssertEqual(
ChatErrorState.bridgeUnavailable(reason: .nodeMissing).primaryRecovery,
.installRuntime
)
XCTAssertEqual(
ChatErrorState.bridgeUnavailable(reason: .runtimeMissing).primaryRecovery,
.installRuntime
)
XCTAssertEqual(
ChatErrorState.bridgeUnavailable(reason: .crashed).primaryRecovery,
.retry
)
XCTAssertEqual(
ChatErrorState.bridgeUnavailable(reason: .unknown).primaryRecovery,
.retry
)
}
// MARK: - BridgeError → ChatErrorState
func testFromBridgeErrorMapsTimeoutToTimeout() {
let mapped = ChatErrorState.from(.timeout)
XCTAssertEqual(mapped, .timeout(toolName: nil))
}
func testFromBridgeErrorDoesNotMapStoppedToResumeCard() {
let mapped = ChatErrorState.from(.stopped)
XCTAssertNil(mapped)
}
func testFromBridgeErrorReturnsNilForUnmappableCases() {
// These should fall through to the existing generic errorMessage banner
// / paywall sheets rather than the new card.
XCTAssertNil(ChatErrorState.from(.encodingError))
XCTAssertNil(
ChatErrorState.from(
.quotaExceeded(
plan: "Free", unit: "cost_usd", used: 5.0, limit: 5.0, resetAtUnix: nil)
)
)
XCTAssertNil(ChatErrorState.from(.agentError("something opaque went wrong")))
XCTAssertNil(
ChatErrorState.from(
.agentRuntimeFailure(
AgentRuntimeFailure(
code: "adapter_config_invalid",
userMessage: "OpenClaw needs a config migration.",
technicalMessage: nil,
source: "adapter_process",
adapterId: "openclaw",
provider: nil,
retryable: false
)
)
)
)
}
func testStructuredAgentRuntimeFailureKeepsUserMessage() {
let error = BridgeError.agentRuntimeFailure(
AgentRuntimeFailure(
code: "adapter_config_invalid",
userMessage: "OpenClaw needs a config migration. Run `openclaw doctor --fix`, then retry.",
technicalMessage: "OpenClaw config is invalid",
source: "adapter_process",
adapterId: "openclaw",
provider: nil,
retryable: false
)
)
XCTAssertEqual(
error.localizedDescription,
"OpenClaw needs a config migration. Run `openclaw doctor --fix`, then retry."
)
}
// MARK: - Bridge-unavailable reason coverage
func testBridgeUnavailableReasonsCoverNodeMissing() {
let mapped = ChatErrorState.from(.nodeNotFound)
XCTAssertEqual(mapped, .bridgeUnavailable(reason: .nodeMissing))
}
func testBridgeUnavailableReasonsCoverRuntimeMissing() {
let mapped = ChatErrorState.from(.bridgeScriptNotFound)
XCTAssertEqual(mapped, .bridgeUnavailable(reason: .runtimeMissing))
}
func testBridgeUnavailableReasonsCoverCrashed() {
XCTAssertEqual(
ChatErrorState.from(.processExited),
.bridgeUnavailable(reason: .crashed)
)
XCTAssertEqual(
ChatErrorState.from(.outOfMemory),
.bridgeUnavailable(reason: .crashed)
)
}
func testTypedBridgeStartFailureSurfacesARecoverableRetryCard() {
let error = BridgeError.failedToStart(.handshakeTimedOut)
XCTAssertEqual(
ChatErrorState.from(error),
.bridgeUnavailable(reason: .failedToStart(.handshakeTimedOut)))
XCTAssertEqual(ChatErrorState.from(error)?.primaryRecovery, .retry)
XCTAssertEqual(ChatErrorState.from(error)?.userFacingSummary, "AI took too long to start. Try again.")
}
func testBridgeUnavailableReasonsCoverUnknown() {
XCTAssertEqual(
ChatErrorState.from(.notRunning),
.bridgeUnavailable(reason: .unknown)
)
XCTAssertEqual(
ChatErrorState.from(.restarting),
.bridgeUnavailable(reason: .unknown)
)
}
// MARK: - Auth mapping
func testFromBridgeErrorMapsAuthMissingToAuthRequired() {
let mapped = ChatErrorState.from(.authMissing)
XCTAssertEqual(mapped, .authRequired)
}
func testFromBridgeErrorMapsInvalidTokenAgentErrorToAuthRequired() {
let mapped = ChatErrorState.from(.agentError("401 \"invalid_token\""))
XCTAssertEqual(mapped, .authRequired)
XCTAssertTrue(BridgeError.agentError("401 \"invalid_token\"").isSessionAuthenticationFailure)
}
func testFromBridgeErrorMapsUnauthorizedAgentErrorToAuthRequired() {
let mapped = ChatErrorState.from(.agentError("Unauthorized - please sign in again"))
XCTAssertEqual(mapped, .authRequired)
}
func testFromBridgeErrorMapsTokenAgentErrorToAuthRequired() {
let mapped = ChatErrorState.from(.agentError("401 auth token rejected"))
XCTAssertEqual(mapped, .authRequired)
}
func testFromBridgeErrorDoesNotMapProviderAuthFailuresToAuthRequired() {
XCTAssertNil(ChatErrorState.from(.agentError("AI service authentication failed")))
XCTAssertNil(ChatErrorState.from(.agentError("Anthropic provider unauthorized")))
XCTAssertNil(ChatErrorState.from(.agentError("invalid key")))
XCTAssertFalse(BridgeError.agentError("Anthropic provider unauthorized").isSessionAuthenticationFailure)
}
// T4: provider auth_required must not present the Pro upgrade sheet.
func testAuthRequiredHandlerDoesNotWireProSheet() throws {
let source = try sourceFile("Providers/ChatProvider.swift")
guard let range = source.range(of: "func handleClaudeAuthRequired") else {
return XCTFail("missing handleClaudeAuthRequired")
}
let snippet = String(source[range.lowerBound...]).prefix(900)
XCTAssertFalse(snippet.contains("isClaudeAuthRequired = true"))
XCTAssertFalse(snippet.contains("startClaudeAuth()"))
}
func testStartClaudeAuthKeepsUserClaudeGuard() throws {
let source = try sourceFile("Providers/ChatProvider.swift")
guard let range = source.range(of: "func startClaudeAuth()") else {
return XCTFail("missing startClaudeAuth")
}
let snippet = String(source[range.lowerBound...]).prefix(300)
XCTAssertTrue(snippet.contains("guard isUserClaudeMode else { return }"))
}
func testEnsureBridgeStartedMapsAuthMissingToAuthRequired() throws {
let source = try sourceFile("Providers/ChatProvider.swift")
XCTAssertTrue(source.contains("ChatErrorState.from(bridgeError)"))
let range = source.range(of: "Failed to start agent bridge")
XCTAssertNotNil(range)
let snippet = String(source[range!.lowerBound...]).prefix(500)
XCTAssertTrue(snippet.contains("currentError = card"))
XCTAssertFalse(snippet.contains("\"AI not available: Please sign in"))
}
func testSendPreservesDraftUntilTurnIsAccepted() throws {
let source = try sourceFile("Providers/ChatProvider.swift")
XCTAssertTrue(source.contains("onAccepted: (@MainActor () -> Void)? = nil"))
XCTAssertTrue(source.contains("onAccepted?()"))
XCTAssertTrue(source.contains("self.draftRevision == submittedRevision"))
XCTAssertTrue(source.contains("self.draftText == text\n else { return }"))
XCTAssertFalse(source.contains("draftText = trimmedText"))
}
func testTerminationFlushesDraftsBeforeAsyncAgentShutdown() throws {
let source = try sourceFile("Providers/ChatProvider.swift")
let observerStart = try XCTUnwrap(source.range(of: "terminationObserver = NotificationCenter.default.addObserver"))
let observerTail = String(source[observerStart.lowerBound...])
let observerEnd = try XCTUnwrap(observerTail.range(of: "private var terminationObserver"))
let observer = String(observerTail[..<observerEnd.lowerBound])
let flush = try XCTUnwrap(observer.range(of: "ChatDraftStore.shared.flush()"))
let asyncShutdown = try XCTUnwrap(observer.range(of: "Task { @MainActor in"))
XCTAssertTrue(observer.contains("MainActor.assumeIsolated"))
XCTAssertLessThan(flush.lowerBound, asyncShutdown.lowerBound)
}
func testSignInRecoveryRetriesAfterOAuth() throws {
let source = try sourceFile("Providers/ChatProvider.swift")
let range = source.range(of: "ChatErrorCard: .signIn recovery")
XCTAssertNotNil(range)
// Scope to the .signIn case block — stop at the next case to avoid
// incidental matches from unrelated methods elsewhere in the file.
let fromSignIn = String(source[range!.lowerBound...])
let endOfCase = fromSignIn.range(of: "case .installRuntime:")
XCTAssertNotNil(endOfCase, "expected .installRuntime case after .signIn recovery")
let snippet = endOfCase.map { String(fromSignIn[..<$0.lowerBound]) } ?? fromSignIn
XCTAssertTrue(snippet.contains("signInWithGoogle()"))
XCTAssertTrue(snippet.contains("signInWithApple()"))
XCTAssertTrue(snippet.contains("ensureBridgeStarted()"))
XCTAssertTrue(snippet.contains("await sendMessage(prompt)"))
}
func testDashboardShowsChatErrorCard() throws {
let source = try sourceFile("MainWindow/Pages/DashboardPage.swift")
XCTAssertTrue(source.contains("dashboardChatErrorCard"))
XCTAssertTrue(source.contains("ChatErrorCard("))
}
/// Static tripwire for the Home chat layout. The shared ChatErrorCard belongs to
/// homePanelStage, below the composer; placing it inside homeChatPanel as well
/// visibly duplicates the sign-in recovery CTA for the same ChatProvider state.
func testDashboardHomeChatHasOneSharedErrorCardRenderSite() throws {
let source = try sourceFile("MainWindow/Pages/DashboardPage.swift")
let panelStart = try XCTUnwrap(source.range(of: "private func homePanelStage"))
let chatStart = try XCTUnwrap(source.range(of: "private func homeChatPanel"))
let connectStart = try XCTUnwrap(source.range(of: "private func homeConnectPanel"))
let panelSource = String(source[panelStart.lowerBound..<chatStart.lowerBound])
let chatSource = String(source[chatStart.lowerBound..<connectStart.lowerBound])
XCTAssertEqual(
panelSource.components(separatedBy: "dashboardChatErrorCard").count - 1,
1,
"Home must have one canonical error-card owner outside the chat panel."
)
XCTAssertFalse(
chatSource.contains("dashboardChatErrorCard"),
"The embedded chat panel must not render a second copy of the shared auth gate."
)
}
func testFloatingBarReadsCurrentError() throws {
let source = try sourceFile("Providers/ChatProvider.swift")
XCTAssertTrue(source.contains("var displayErrorMessage"))
XCTAssertTrue(source.contains("currentError.userFacingSummary"))
let floating = try sourceFile("FloatingControlBar/FloatingControlBarWindow.swift")
XCTAssertTrue(floating.contains("displayErrorMessage"))
}
func testChatSignInRecoveryUsesDesktopOAuthInsteadOfHomepage() throws {
let source = try sourceFile("Providers/ChatProvider.swift")
XCTAssertTrue(source.contains("try await AuthService.shared.signInWithGoogle()"))
XCTAssertTrue(source.contains("ChatErrorCard: .signIn recovery — starting desktop OAuth"))
XCTAssertFalse(source.contains("ChatErrorCard: .signIn recovery — opening omi.me sign-in URL"))
XCTAssertFalse(source.contains(#"URL(string: "https://omi.me/")"#))
}
func testSavedUserDefaultsSessionIsValidatedBeforeUse() throws {
let source = try sourceFile("AuthService.swift")
XCTAssertTrue(source.contains("validateRestoredSession(attempt: attempt)"))
XCTAssertTrue(source.contains("refreshSingleFlight(auth: self)"))
XCTAssertTrue(source.contains("Restored session validated via forced refresh"))
XCTAssertTrue(source.contains("Restored session validation deferred - preserving credentials for retry"))
XCTAssertFalse(source.contains("cached ID token expired"))
}
func testRestoredSessionValidationDoesNotClearPersistedTokensOnTransientFailure() throws {
let source = try sourceFile("AuthService.swift")
let validationBlockRange = source.range(
of: "Restored session validation deferred - preserving credentials for retry")
XCTAssertNotNil(validationBlockRange)
let snippet = String(source[validationBlockRange!.lowerBound...])
let catchBlock = String(snippet[..<(snippet.range(of: "} catch {")?.lowerBound ?? snippet.endIndex)])
XCTAssertFalse(catchBlock.contains("clearTokens()"))
XCTAssertTrue(source.contains("invalidateSession(reason: .definitiveRefreshFailure)"))
}
func testRestoredSessionInvalidatesWhenValidationClearedTokens() throws {
let source = try sourceFile("AuthService.swift")
let range = source.range(of: "Restored session validation proved credentials absent")
XCTAssertNotNil(range)
let snippet = String(source[range!.lowerBound...]).prefix(200)
XCTAssertTrue(snippet.contains("invalidateSession(reason: .restoredSessionInvalid)"))
let methodStart = source.range(of: "private func validateRestoredSessionNow(attempt:")
XCTAssertNotNil(methodStart)
let methodEnd = source.range(
of: "// MARK: - Auth State Listener",
range: methodStart!.upperBound..<source.endIndex)
XCTAssertNotNil(methodEnd)
let method = String(source[methodStart!.lowerBound..<methodEnd!.lowerBound])
XCTAssertTrue(method.contains("sessionCoordinator.phase == .needsReauth"))
XCTAssertTrue(method.contains("storedIdToken == nil && storedRefreshToken == nil"))
}
func testRestoredSessionValidationForceRefreshesOnLaunch() throws {
let source = try sourceFile("AuthService.swift")
let validationRange = source.range(of: "private func validateRestoredSessionNow(attempt:")
XCTAssertNotNil(validationRange)
let snippet = String(source[validationRange!.lowerBound...])
XCTAssertTrue(snippet.contains("storedRefreshToken != nil") || snippet.contains("storedIdToken != nil"))
XCTAssertTrue(snippet.contains("refreshSingleFlight(auth: self)"))
XCTAssertFalse(snippet.contains("!self.isTokenExpired"))
}
func testAuthListenerValidatesSavedSessionInsteadOfBlindPreserve() throws {
let source = try sourceFile("AuthService.swift")
XCTAssertTrue(source.contains("validateSavedSessionAfterFirebaseNil()"))
XCTAssertFalse(source.contains("Keeping saved session (not overriding isSignedIn)"))
XCTAssertTrue(source.contains("skipping REST validation while launch restore is in flight"))
}
func testChatSignInRecoveryDoesNotDuplicatePlanRefresh() throws {
// signInWithGoogle() already schedules fetchPlan() on success (twice, in
// the OAuth completion path); the recovery path must not duplicate it.
let source = try sourceFile("Providers/ChatProvider.swift")
let recoveryRange = source.range(of: "ChatErrorCard: .signIn recovery — starting desktop OAuth")
XCTAssertNotNil(recoveryRange)
let snippet = String(source[recoveryRange!.lowerBound...])
.prefix(400)
XCTAssertTrue(snippet.contains("try await AuthService.shared.signInWithGoogle()"))
XCTAssertFalse(snippet.contains("FloatingBarUsageLimiter.shared.fetchPlan()"))
}
private func sourceFile(_ relativePath: String) throws -> String {
let sourceURL = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent()
.deletingLastPathComponent()
.appendingPathComponent("Sources")
.appendingPathComponent(relativePath)
return try String(contentsOf: sourceURL, encoding: .utf8)
}
}