forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAgentRuntimeProcessTests.swift
More file actions
1988 lines (1766 loc) · 79.6 KB
/
Copy pathAgentRuntimeProcessTests.swift
File metadata and controls
1988 lines (1766 loc) · 79.6 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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import XCTest
@testable import Omi_Computer
private struct TokenRefreshAuthorization: Equatable, Sendable {
let ownerID: String
let generation: UInt64
}
private actor DelayedOwnerBoundTokenRefreshHarness {
private var ownerId: String? = "owner-a"
private var generation: UInt64 = 0
private var fetchStarted = false
private var fetchStartedWaiter: CheckedContinuation<Void, Never>?
private var pendingFetch: CheckedContinuation<String, Error>?
private(set) var fetchedOwnerIds: [String] = []
private(set) var sentToken: String?
private(set) var sentOwnerId: String?
func captureAuthorization() -> TokenRefreshAuthorization? {
guard let ownerId else { return nil }
return TokenRefreshAuthorization(ownerID: ownerId, generation: generation)
}
func isAuthorizationCurrent(_ authorization: TokenRefreshAuthorization) -> Bool {
ownerId == authorization.ownerID && generation == authorization.generation
}
func fetchAuthHeader(expectedOwnerId: String) async throws -> String {
fetchedOwnerIds.append(expectedOwnerId)
return try await withCheckedThrowingContinuation { continuation in
pendingFetch = continuation
fetchStarted = true
fetchStartedWaiter?.resume()
fetchStartedWaiter = nil
}
}
func waitUntilFetchStarted() async {
if fetchStarted { return }
await withCheckedContinuation { continuation in
fetchStartedWaiter = continuation
}
}
func replaceOwnerASessionAndCompleteFetch(header: String) -> Bool {
ownerId = nil
generation &+= 1
ownerId = "owner-a"
generation &+= 1
guard let pendingFetch else { return false }
self.pendingFetch = nil
pendingFetch.resume(returning: header)
return true
}
func recordSend(token: String, ownerId: String) -> Bool {
sentToken = token
sentOwnerId = ownerId
return true
}
func snapshot() -> (fetchedOwnerIds: [String], sentToken: String?, sentOwnerId: String?) {
(fetchedOwnerIds, sentToken, sentOwnerId)
}
}
private actor GatedRuntimeStartupHarness {
private var launchCount = 0
private var launchStarted = false
private var launchStartedWaiter: CheckedContinuation<Void, Never>?
private var releaseContinuation: CheckedContinuation<Void, Never>?
func launch(receipt: UInt64) async -> UInt64 {
launchCount += 1
launchStarted = true
launchStartedWaiter?.resume()
launchStartedWaiter = nil
await withCheckedContinuation { continuation in
releaseContinuation = continuation
}
return receipt
}
func waitUntilLaunchStarted() async {
if launchStarted { return }
await withCheckedContinuation { continuation in
launchStartedWaiter = continuation
}
}
func release() -> Bool {
guard let releaseContinuation else { return false }
self.releaseContinuation = nil
releaseContinuation.resume()
return true
}
func launches() -> Int { launchCount }
}
private actor ContextProjectionRaceHarness {
private var generation = 1
private var events: [String] = []
private var admissionAttempts = 0
func record(_ event: String) {
events.append(event)
}
func advance(_ event: String) {
generation += 1
events.append(event)
}
func freshness() -> AgentContextFreshness {
AgentContextFreshness(
version: "snapshot-v\(generation)",
generation: generation,
rendererFingerprint: "renderer-v\(generation)",
capabilityVersion: "capabilities-v\(generation)"
)
}
func recordAdmissionAttempt() -> Int {
admissionAttempts += 1
events.append("admission_attempt_\(admissionAttempts)")
return admissionAttempts
}
func snapshot() -> [String] { events }
}
private actor GateAdmissionOrderProbe {
private(set) var order: [String] = []
func append(_ value: String) {
order.append(value)
}
func snapshot() -> [String] {
order
}
}
/// Signals are latched, not edge-triggered. The signaller and its waiter run on
/// separate tasks, so nothing orders `signalEntered()` before `waitUntilEntered()`
/// (or `release()` before `waitUntilReleased()`); an unlatched signal that lands
/// first is dropped and its waiter suspends forever, which hangs the whole suite
/// until the per-suite budget kills it. The other probes in this file latch the
/// same way.
private actor GateHoldProbe {
private var hasEntered = false
private var hasReleased = false
private var enteredWaiter: CheckedContinuation<Void, Never>?
private var releaseContinuation: CheckedContinuation<Void, Never>?
func waitUntilEntered() async {
if hasEntered { return }
await withCheckedContinuation { enteredWaiter = $0 }
}
func signalEntered() {
hasEntered = true
enteredWaiter?.resume()
enteredWaiter = nil
}
func waitUntilReleased() async {
if hasReleased { return }
await withCheckedContinuation { releaseContinuation = $0 }
}
func release() {
hasReleased = true
releaseContinuation?.resume()
releaseContinuation = nil
}
}
private final class GateGrantCancellationRaceProbe: @unchecked Sendable {
private let lock = NSLock()
private let resumeGrantedWaiter = DispatchSemaphore(value: 0)
private var waiterRegistered = false
private var grantPaused = false
private var registrationWaiter: CheckedContinuation<Void, Never>?
private var grantWaiter: CheckedContinuation<Void, Never>?
func signalWaiterRegistered() {
lock.lock()
waiterRegistered = true
let waiter = registrationWaiter
registrationWaiter = nil
lock.unlock()
waiter?.resume()
}
func waitUntilWaiterRegistered() async {
await withCheckedContinuation { continuation in
lock.lock()
if waiterRegistered {
lock.unlock()
continuation.resume()
return
}
registrationWaiter = continuation
lock.unlock()
}
}
func pauseGrantedHandoff() {
lock.lock()
grantPaused = true
let waiter = grantWaiter
grantWaiter = nil
lock.unlock()
waiter?.resume()
resumeGrantedWaiter.wait()
}
func waitUntilGrantPaused() async {
await withCheckedContinuation { continuation in
lock.lock()
if grantPaused {
lock.unlock()
continuation.resume()
return
}
grantWaiter = continuation
lock.unlock()
}
}
func resumeGrantedHandoff() {
resumeGrantedWaiter.signal()
}
}
private actor ContextProjectionTaskBox {
private var task: Task<Void, Never>?
func store(_ task: Task<Void, Never>) {
self.task = task
}
func wait() async {
await task?.value
}
}
private enum CredentialRefreshShouldNotRun: Error {
case invoked
}
private actor CredentialFreeControlStartProbe {
private var startupCredentialFetches = 0
private var runtimeCredentialRefreshes = 0
private var ownerSynchronizations = 0
func attemptStartupCredentialFetch() throws -> String? {
startupCredentialFetches += 1
throw CredentialRefreshShouldNotRun.invoked
}
func attemptRuntimeCredentialRefresh() throws -> Bool {
runtimeCredentialRefreshes += 1
throw CredentialRefreshShouldNotRun.invoked
}
func synchronizeOwner() {
ownerSynchronizations += 1
}
func snapshot() -> (startupCredentialFetches: Int, runtimeCredentialRefreshes: Int, ownerSynchronizations: Int) {
(startupCredentialFetches, runtimeCredentialRefreshes, ownerSynchronizations)
}
}
private actor ContextAdmissionRetryTestState {
private(set) var attempts: [AgentContextFreshness?] = []
private(set) var refreshCount = 0
func recordRefresh() {
refreshCount += 1
}
func recordAttempt(_ context: AgentContextFreshness?) -> Int {
attempts.append(context)
return attempts.count
}
func snapshot() -> (attempts: [AgentContextFreshness?], refreshCount: Int) {
(attempts, refreshCount)
}
}
final class AgentRuntimeProcessTests: XCTestCase {
func testHermeticFaultModelTokenIsNonProductionOnlyAndAvoidsFirebaseRefresh() {
let environment = [
AgentRuntimeCredentialPolicy.hermeticFaultModelTokenEnvironmentKey: "fault-suite-model-token"
]
let token = AgentRuntimeCredentialPolicy.hermeticFaultModelToken(
isNonProduction: true,
bundleIdentifier: AgentRuntimeCredentialPolicy.hermeticFaultBundleIdentifier,
environment: environment)
XCTAssertEqual(token, "fault-suite-model-token")
XCTAssertFalse(
AgentRuntimeCredentialPolicy.requiresManagedCredentials(
requestedCredentials: true,
isNonProduction: true,
hermeticFaultModelToken: token),
"the isolated fault backend must exercise its injected response without Firebase")
XCTAssertNil(
AgentRuntimeCredentialPolicy.hermeticFaultModelToken(
isNonProduction: false,
bundleIdentifier: AgentRuntimeCredentialPolicy.hermeticFaultBundleIdentifier,
environment: environment),
"production must never accept a harness-supplied model token")
XCTAssertNil(
AgentRuntimeCredentialPolicy.hermeticFaultModelToken(
isNonProduction: true,
bundleIdentifier: "com.omi.some-other-dev-bundle",
environment: environment),
"only the named fault bundle may opt into the inert model token")
XCTAssertNil(
AgentRuntimeCredentialPolicy.hermeticFaultModelToken(
isNonProduction: true,
bundleIdentifier: AgentRuntimeCredentialPolicy.hermeticFaultBundleIdentifier,
environment: [
AgentRuntimeCredentialPolicy.hermeticFaultModelTokenEnvironmentKey: " "
]))
}
func testNonProductionJournalControlStartDoesNotRefreshCredentials() async throws {
let probe = CredentialFreeControlStartProbe()
XCTAssertFalse(
AgentRuntimeCredentialPolicy.requiresManagedCredentials(
requestedCredentials: false,
isNonProduction: true))
XCTAssertTrue(
AgentRuntimeCredentialPolicy.requiresManagedCredentials(
requestedCredentials: false,
isNonProduction: false),
"production must never permit a credential-free runtime start")
XCTAssertTrue(
AgentRuntimeCredentialPolicy.requiresManagedCredentials(
requestedCredentials: true,
isNonProduction: true),
"normal model starts must remain credential-required")
let authHeader = try await AgentRuntimeProcess.startupAuthHeader(
requiresCredentials: false,
fetchAuthHeader: {
try await probe.attemptStartupCredentialFetch()
})
XCTAssertNil(authHeader)
await AgentBridge.synchronizeAuthorityForStart(
requiresCredentials: false,
refreshCredentials: {
try await probe.attemptRuntimeCredentialRefresh()
},
refreshOwner: {
await probe.synchronizeOwner()
})
let snapshot = await probe.snapshot()
XCTAssertEqual(snapshot.startupCredentialFetches, 0)
XCTAssertEqual(snapshot.runtimeCredentialRefreshes, 0)
XCTAssertEqual(snapshot.ownerSynchronizations, 1)
}
func testPinnedPiMonoSessionsFetchTokenAfterHarnessSwitch() async throws {
XCTAssertFalse(
AgentRuntimeCredentialPolicy.shouldRequirePiMonoCredentials(
preferredAdapterIsPiMono: false,
requestedCredentials: true,
isNonProduction: false),
"ACP/Hermes/OpenClaw must still start without a managed token")
XCTAssertTrue(
AgentRuntimeCredentialPolicy.requiresManagedCredentials(
requestedCredentials: true,
isNonProduction: false),
"production alternate-harness starts must still fetch the managed token")
XCTAssertTrue(
AgentRuntimeCredentialPolicy.shouldRequirePiMonoCredentials(
preferredAdapterIsPiMono: true,
requestedCredentials: true,
isNonProduction: false))
var fetches = 0
let header = try await AgentRuntimeProcess.startupAuthHeader(
requiresCredentials: AgentRuntimeCredentialPolicy.requiresManagedCredentials(
requestedCredentials: true,
isNonProduction: false),
fetchAuthHeader: {
fetches += 1
return "Bearer pinned-session-token"
})
XCTAssertEqual(fetches, 1)
XCTAssertEqual(header, "Bearer pinned-session-token")
var skippedFetches = 0
let skipped = try await AgentRuntimeProcess.startupAuthHeader(
requiresCredentials: AgentRuntimeCredentialPolicy.requiresManagedCredentials(
requestedCredentials: false,
isNonProduction: true),
fetchAuthHeader: {
skippedFetches += 1
return "Bearer should-not-fetch"
})
XCTAssertEqual(skippedFetches, 0)
XCTAssertNil(skipped)
}
func testNamedBundleStartupUsesValidSeededCredentialWithoutForcedRefresh() {
XCTAssertFalse(
AgentRuntimeCredentialPolicy.shouldForceRefreshAtStartup(
isNonProduction: true,
isDesktopLocalProfile: false),
"a named bundle has no Firebase SDK session to satisfy a forced refresh")
XCTAssertFalse(
AgentRuntimeCredentialPolicy.shouldForceRefreshAtStartup(
isNonProduction: true,
isDesktopLocalProfile: true),
"the local harness owns its credential lifecycle")
XCTAssertTrue(
AgentRuntimeCredentialPolicy.shouldForceRefreshAtStartup(
isNonProduction: false,
isDesktopLocalProfile: false),
"production and Beta starts must continue forcing a fresh credential")
}
func testKernelJournalMutationClosesTheRuntimeReplayBoundary() async throws {
let runtime = AgentRuntimeProcess()
let turn = try XCTUnwrap(
KernelJournalTurn(dictionary: [
"conversationId": "conversation",
"turnId": "turn-terminal",
"turnSeq": 1,
"conversationGeneration": 1,
"generationBaseTurnSeq": 0,
"producerId": "producer",
"payloadHash": "hash",
"role": "assistant",
"surfaceKind": "main_chat",
"content": "Done",
"status": "completed",
"origin": "chat",
"contentBlocks": [],
"resources": [],
"metadataJson": "{}",
"createdAtMs": 1,
"updatedAtMs": 1,
]))
await runtime.dispatchJournalTurnChangedForTesting(turn)
var lifecycle = await runtime.bridgeLifecycleSnapshotForTesting()
XCTAssertTrue(lifecycle.settledTurnIDs.contains("turn-terminal"))
XCTAssertEqual(
lifecycle.reduce(.walFrame(turnID: "turn-terminal")),
[.rejectWALFrame(turnID: "turn-terminal")])
}
func testRuntimeHandshakeRejectsStaleV2RuntimeWithoutRequiredCapability() throws {
let valid = try XCTUnwrap(
AgentRuntimeProcess.RuntimeMessage.parse(
#"{"type":"init","protocolVersion":2,"sessionId":"","agentControlTools":[],"runtimeVersion":"1.0.0","runtimeCapabilities":["journal_import_remote_turn","runtime_adapter_availability","chat_first_capability_projection"]}"#
))
let handshake = try AgentRuntimeProcess.validateRuntimeHandshake(valid)
XCTAssertEqual(handshake.protocolVersion, AgentRuntimeProcess.expectedProtocolVersion)
XCTAssertTrue(handshake.capabilities.contains("journal_import_remote_turn"))
let stale = try XCTUnwrap(
AgentRuntimeProcess.RuntimeMessage.parse(
#"{"type":"init","protocolVersion":2,"sessionId":"","agentControlTools":[],"runtimeVersion":"1.0.0","runtimeCapabilities":[]}"#
))
XCTAssertThrowsError(try AgentRuntimeProcess.validateRuntimeHandshake(stale))
let wrongProtocol = try XCTUnwrap(
AgentRuntimeProcess.RuntimeMessage.parse(
#"{"type":"init","protocolVersion":1,"sessionId":"","agentControlTools":[],"runtimeVersion":"1.0.0","runtimeCapabilities":["journal_import_remote_turn","runtime_adapter_availability","chat_first_capability_projection"]}"#
))
XCTAssertThrowsError(try AgentRuntimeProcess.validateRuntimeHandshake(wrongProtocol))
}
func testJournalDeadlineAcceptsResultAfterSQLiteBusyWindowWithoutWallClockDelay() {
let simulatedArrivalNanoseconds: UInt64 = 6_170_000_000
XCTAssertEqual(
AgentRuntimeJournalTimeoutPolicy.sqliteBusyWindowNanoseconds,
5_000_000_000
)
XCTAssertEqual(AgentRuntimeJournalTimeoutPolicy.ipcSlackNanoseconds, 5_000_000_000)
XCTAssertGreaterThan(
AgentRuntimeJournalTimeoutPolicy.deadlineNanoseconds,
AgentRuntimeJournalTimeoutPolicy.sqliteBusyWindowNanoseconds
)
XCTAssertLessThan(
simulatedArrivalNanoseconds,
AgentRuntimeJournalTimeoutPolicy.deadlineNanoseconds
)
XCTAssertTrue(
AgentRuntimeJournalTimeoutPolicy.allowsCorrelatedResult(
elapsedNanoseconds: simulatedArrivalNanoseconds
)
)
}
func testJournalDeadlineClassifiesExactAndLaterArrivalsAsTimedOut() {
let deadline = AgentRuntimeJournalTimeoutPolicy.deadlineNanoseconds
XCTAssertEqual(deadline, 10_000_000_000)
XCTAssertFalse(
AgentRuntimeJournalTimeoutPolicy.allowsCorrelatedResult(
elapsedNanoseconds: deadline
),
"the actor removes the request at the exact deadline before late results can route"
)
XCTAssertFalse(
AgentRuntimeJournalTimeoutPolicy.allowsCorrelatedResult(
elapsedNanoseconds: deadline + 1_170_000_000
),
"post-deadline results remain unroutable"
)
}
// MARK: - CHAT-02 agent stall hook
func testSuspendStreamNoOpsWithoutRunningProcess() async {
// External contract: the debug suspend never reports success without a real
// suspend — it returns an error (prod-gated in the test host, or no running
// process on a dev bundle), never suspended:true, and never SIGSTOPs a bogus pid.
let result = await AgentRuntimeProcess.shared.debugSuspendStream(durationMs: 190_000)
XCTAssertNotEqual(result["suspended"], "true")
XCTAssertNotNil(result["error"])
}
func testResumeStreamNoOpsWithoutProcess() {
// debugResumeStream is nonisolated now (off-actor SIGCONT) — no await needed.
let result = AgentRuntimeProcess.shared.debugResumeStream()
XCTAssertNotEqual(result["resumed"], "true")
XCTAssertNotNil(result["error"])
}
func testAgentStallHookIsNonProdGatedAndSafe() throws {
let processSource = try String(
contentsOf: URL(fileURLWithPath: #filePath)
.deletingLastPathComponent().deletingLastPathComponent()
.appendingPathComponent("Sources/Chat/AgentRuntimeProcess.swift"),
encoding: .utf8)
// Production gate, live-process guard, real signals, bounded window, and a
// generation-guarded auto-resume so a forgotten resume can't wedge the agent.
for needle in [
"func debugSuspendStream(durationMs: Int)",
"guard AppBuild.isNonProduction else",
"process.isRunning, process.processIdentifier > 0",
"kill(pid, SIGSTOP)",
"kill($0, SIGCONT)",
"min(durationMs, 300_000)",
"generation == self.generation",
] {
XCTAssertTrue(processSource.contains(needle), "AgentRuntimeProcess missing stall-hook invariant: \(needle)")
}
let bridgeSource = try String(
contentsOf: URL(fileURLWithPath: #filePath)
.deletingLastPathComponent().deletingLastPathComponent()
.appendingPathComponent("Sources/DesktopAutomationBridge.swift"),
encoding: .utf8)
for needle in ["name: \"suspend_agent_stream\"", "name: \"resume_agent_stream\""] {
XCTAssertTrue(bridgeSource.contains(needle), "bridge missing action: \(needle)")
}
// Both actions must be behind the non-prod guard.
let suspendIdx = bridgeSource.range(of: "name: \"suspend_agent_stream\"")!.lowerBound
let afterSuspend = String(bridgeSource[suspendIdx...].prefix(600))
XCTAssertTrue(
afterSuspend.contains("AppBuild.isNonProduction"),
"suspend_agent_stream must be gated to non-production bundles")
}
func testV2ResultParsingPreservesCanonicalAndAdapterIds() {
let line = """
{"type":"result","protocolVersion":2,"requestId":"req-1","clientId":"client-1","sessionId":"omi-1","runId":"run-1","attemptId":"attempt-1","adapterSessionId":"acp-1","terminalStatus":"succeeded","text":"done","costUsd":1.25,"inputTokens":3,"outputTokens":4,"cacheReadTokens":5,"cacheWriteTokens":6}
"""
let message = AgentRuntimeProcess.RuntimeMessage.parse(line)
XCTAssertEqual(message?.kind, .result)
XCTAssertEqual(message?.requestId, "req-1")
XCTAssertEqual(message?.clientId, "client-1")
XCTAssertEqual(
message?.requestKey, AgentRuntimeProcess.RuntimeMessage.RequestKey(clientId: "client-1", requestId: "req-1"))
XCTAssertEqual(message?.payload["sessionId"] as? String, "omi-1")
XCTAssertEqual(message?.payload["adapterSessionId"] as? String, "acp-1")
XCTAssertEqual(message?.payload["terminalStatus"] as? String, "succeeded")
}
func testTurnActivityParsingPreservesRequestCorrelationWithoutContent() throws {
let message = try XCTUnwrap(
AgentRuntimeProcess.RuntimeMessage.parse(
#"{"type":"turn_activity","phase":"running","protocolVersion":2,"requestId":"quiet-1","clientId":"client-1","sessionId":"omi-1","runId":"run-1","attemptId":"attempt-1"}"#
))
XCTAssertEqual(message.kind, .turnActivity)
XCTAssertEqual(
message.requestKey,
AgentRuntimeProcess.RuntimeMessage.RequestKey(clientId: "client-1", requestId: "quiet-1")
)
XCTAssertEqual(message.payload["phase"] as? String, "running")
XCTAssertNil(message.payload["text"])
}
func testCancelAckRoutesByRequestId() {
let message = AgentRuntimeProcess.RuntimeMessage.parse(
#"{"type":"cancel_ack","protocolVersion":2,"requestId":"cancel-me","clientId":"client-1","accepted":true,"dispatchAttempted":true,"adapterAcknowledged":false}"#
)
XCTAssertEqual(message?.kind, .cancelAck)
XCTAssertEqual(
message?.requestKey, AgentRuntimeProcess.RuntimeMessage.RequestKey(clientId: "client-1", requestId: "cancel-me"))
XCTAssertEqual(message?.payload["accepted"] as? Bool, true)
XCTAssertEqual(message?.payload["adapterAcknowledged"] as? Bool, false)
}
func testInitMessageCarriesAdvertisedAgentControlTools() {
let message = AgentRuntimeProcess.RuntimeMessage.parse(
#"{"type":"init","sessionId":"","agentControlTools":["list_agent_sessions","spawn_background_agent"]}"#
)
XCTAssertEqual(message?.kind, .initMessage)
XCTAssertEqual(
message?.payload["agentControlTools"] as? [String], ["list_agent_sessions", "spawn_background_agent"])
}
func testControlToolResultRoutesByRequestId() {
let message = AgentRuntimeProcess.RuntimeMessage.parse(
#"{"type":"control_tool_result","protocolVersion":2,"requestId":"control-1","clientId":"client-1","ownerId":"owner-1","name":"inspect_agent_artifacts","result":"{\"ok\":true,\"artifacts\":[]}"}"#
)
XCTAssertEqual(message?.kind, .controlToolResult)
XCTAssertEqual(
message?.requestKey, AgentRuntimeProcess.RuntimeMessage.RequestKey(clientId: "client-1", requestId: "control-1"))
XCTAssertEqual(message?.payload["ownerId"] as? String, "owner-1")
XCTAssertEqual(message?.payload["name"] as? String, "inspect_agent_artifacts")
XCTAssertEqual(message?.payload["result"] as? String, #"{"ok":true,"artifacts":[]}"#)
}
func testDirectControlWireAndResultValidationAreOwnerBound() {
let request = AgentRuntimeProcess.directControlToolWireMessage(
clientId: "client-1",
requestId: "control-1",
ownerId: "owner-a",
name: "spawn_agent",
input: ["objective": "Inspect memories"])
XCTAssertEqual(request["type"] as? String, "direct_control_tool")
XCTAssertEqual(request["ownerId"] as? String, "owner-a")
XCTAssertTrue(
AgentRuntimeProcess.isDirectControlResultOwnerCurrent(
expectedOwnerId: "owner-a",
expectedOwnerEpoch: 1,
resultOwnerId: "owner-a",
currentOwnerId: "owner-a",
currentOwnerEpoch: 1))
XCTAssertFalse(
AgentRuntimeProcess.isDirectControlResultOwnerCurrent(
expectedOwnerId: "owner-a",
expectedOwnerEpoch: 1,
resultOwnerId: nil,
currentOwnerId: "owner-a",
currentOwnerEpoch: 1))
XCTAssertFalse(
AgentRuntimeProcess.isDirectControlResultOwnerCurrent(
expectedOwnerId: "owner-a",
expectedOwnerEpoch: 1,
resultOwnerId: "owner-b",
currentOwnerId: "owner-a",
currentOwnerEpoch: 1))
XCTAssertFalse(
AgentRuntimeProcess.isDirectControlResultOwnerCurrent(
expectedOwnerId: "owner-a",
expectedOwnerEpoch: 1,
resultOwnerId: "owner-a",
currentOwnerId: "owner-b",
currentOwnerEpoch: 2))
XCTAssertFalse(
AgentRuntimeProcess.isDirectControlResultOwnerCurrent(
expectedOwnerId: "owner-a",
expectedOwnerEpoch: 1,
resultOwnerId: "owner-a",
currentOwnerId: "owner-a",
currentOwnerEpoch: 3))
}
func testLocalProviderRuntimeOwnerHandshakePrecedesOwnerScopedStartupWork() throws {
let handshake = AgentRuntimeProcess.runtimeOwnerHandshakeWireMessage(ownerId: "signed-in-owner")
XCTAssertEqual(handshake["type"] as? String, "refresh_owner")
XCTAssertEqual(handshake["ownerId"] as? String, "signed-in-owner")
XCTAssertNil(handshake["token"])
// omi-test-quality: source-inspection -- static contract: every harness must synchronize daemon owner authority before owner-scoped legacy migration; wire and resource-layout behavior are tested directly beside this ordering guard
let bridgeSource = try sourceFile("Chat/AgentBridge.swift")
let startRange = try XCTUnwrap(
bridgeSource.range(
of: "func start(\n authorizationSnapshot:"))
let restartRange = try XCTUnwrap(
bridgeSource.range(
of: "\n func restart() async throws",
range: startRange.upperBound..<bridgeSource.endIndex))
let startBody = String(bridgeSource[startRange.lowerBound..<restartRange.lowerBound])
let handshakeRange = try XCTUnwrap(
startBody.range(
of: "await synchronizeRuntimeAuthority(\n authorizationSnapshot: authorizationSnapshot,"))
let migrationRange = try XCTUnwrap(
startBody.range(
of: "await migrateLegacyMainChatSessionsIfNeeded("))
XCTAssertLessThan(handshakeRange.lowerBound, migrationRange.lowerBound)
XCTAssertTrue(bridgeSource.contains("synchronizeAuthorityForStart("))
XCTAssertTrue(bridgeSource.contains("runtime.refreshRuntimeOwner("))
}
func testRuntimeStartupSingleFlightLaunchesExactlyOnceForConcurrentSameKey() async throws {
let singleFlight = AgentRuntimeStartupSingleFlight<String, UInt64>()
let harness = GatedRuntimeStartupHarness()
let first = Task {
try await singleFlight.run(key: "owner-a:generation-1") {
await harness.launch(receipt: 41)
}
}
await harness.waitUntilLaunchStarted()
let second = Task {
try await singleFlight.run(key: "owner-a:generation-1") {
await harness.launch(receipt: 99)
}
}
var observedTwoParticipants = false
for _ in 0..<10_000 {
if await singleFlight.participantCountForTesting() == 2 {
observedTwoParticipants = true
break
}
await Task.yield()
}
XCTAssertTrue(observedTwoParticipants)
let launchesBeforeRelease = await harness.launches()
let released = await harness.release()
XCTAssertEqual(launchesBeforeRelease, 1)
XCTAssertTrue(released)
let firstReceipt = try await first.value
let secondReceipt = try await second.value
XCTAssertEqual(firstReceipt, 41)
XCTAssertEqual(secondReceipt, 41)
let finalLaunches = await harness.launches()
XCTAssertEqual(finalLaunches, 1)
}
func testRuntimeStartupSingleFlightRejectsDifferentOwnerGenerationWhileSuspended() async throws {
let singleFlight = AgentRuntimeStartupSingleFlight<String, UInt64>()
let harness = GatedRuntimeStartupHarness()
let first = Task {
try await singleFlight.run(key: "owner-a:generation-1") {
await harness.launch(receipt: 7)
}
}
await harness.waitUntilLaunchStarted()
do {
_ = try await singleFlight.run(key: "owner-a:generation-2") { 8 }
XCTFail("new owner generation must not join an older credential-bearing launch")
} catch BridgeError.restarting {
// Expected: caller retries only after the exact older flight terminates.
} catch {
XCTFail("unexpected mismatch error: \(error)")
}
let launchesBeforeRelease = await harness.launches()
let released = await harness.release()
XCTAssertEqual(launchesBeforeRelease, 1)
XCTAssertTrue(released)
let receipt = try await first.value
XCTAssertEqual(receipt, 7)
}
func testOwnerBoundTokenRefreshDropsDelayedTokenAcrossSameOwnerSessionReplacement() async throws {
let harness = DelayedOwnerBoundTokenRefreshHarness()
let refreshTask = Task {
try await AgentBridge.refreshOwnerBoundToken(
captureAuthorization: {
await harness.captureAuthorization()
},
authorizationOwnerId: { authorization in
authorization.ownerID
},
isAuthorizationCurrent: { authorization in
await harness.isAuthorizationCurrent(authorization)
},
fetchAuthHeader: { expectedOwnerId in
try await harness.fetchAuthHeader(expectedOwnerId: expectedOwnerId)
},
sendToken: { token, expectedOwnerId, _ in
await harness.recordSend(token: token, ownerId: expectedOwnerId)
}
)
}
await harness.waitUntilFetchStarted()
let resumed = await harness.replaceOwnerASessionAndCompleteFetch(
header: "Bearer owner-a-token")
XCTAssertTrue(resumed)
let refreshed = try await refreshTask.value
XCTAssertFalse(refreshed)
let snapshot = await harness.snapshot()
XCTAssertEqual(snapshot.fetchedOwnerIds, ["owner-a"])
XCTAssertNil(snapshot.sentToken, "stale owner-A token must never reach the runtime sender")
XCTAssertNil(snapshot.sentOwnerId, "stale refresh must not mutate runtime owner credentials")
}
func testRuntimeRefreshTokenWireRequiresCapturedOwnerToRemainCurrent() {
let authorized = AgentRuntimeProcess.refreshTokenWireMessage(
token: "owner-a-token",
expectedOwnerId: "owner-a",
currentOwnerId: "owner-a"
)
XCTAssertEqual(authorized?["type"] as? String, "refresh_token")
XCTAssertEqual(authorized?["token"] as? String, "owner-a-token")
XCTAssertEqual(authorized?["ownerId"] as? String, "owner-a")
XCTAssertNil(
AgentRuntimeProcess.refreshTokenWireMessage(
token: "owner-a-token",
expectedOwnerId: "owner-a",
currentOwnerId: "owner-b"
))
XCTAssertNil(
AgentRuntimeProcess.refreshTokenWireMessage(
token: "owner-a-token",
expectedOwnerId: "owner-a",
currentOwnerId: nil
))
}
func testOwnerRuntimeRevocationWireAndCorrelatedReceiptShape() {
let wire = AgentRuntimeProcess.revokeOwnerRuntimeWireMessage(
clientId: "runtime-owner-transition",
requestId: "revoke-1",
ownerId: "owner-a")
XCTAssertEqual(wire["type"] as? String, "revoke_owner_runtime")
XCTAssertEqual(wire["protocolVersion"] as? Int, 2)
XCTAssertEqual(wire["requestId"] as? String, "revoke-1")
XCTAssertEqual(wire["clientId"] as? String, "runtime-owner-transition")
XCTAssertEqual(wire["ownerId"] as? String, "owner-a")
let receipt = AgentRuntimeProcess.RuntimeMessage.parse(
#"{"type":"owner_runtime_revoked","protocolVersion":2,"requestId":"revoke-1","clientId":"runtime-owner-transition","ownerId":"owner-a","ok":true,"duplicate":false,"revokedRunIds":["run-1"],"invalidatedBindingIds":["binding-1"]}"#
)
XCTAssertEqual(receipt?.kind, .ownerRuntimeRevoked)
XCTAssertEqual(
receipt?.requestKey,
AgentRuntimeProcess.RuntimeMessage.RequestKey(
clientId: "runtime-owner-transition",
requestId: "revoke-1"))
XCTAssertEqual(receipt?.payload["ownerId"] as? String, "owner-a")
XCTAssertEqual(receipt?.payload["revokedRunIds"] as? [String], ["run-1"])
XCTAssertEqual(receipt?.payload["invalidatedBindingIds"] as? [String], ["binding-1"])
}
func testRuntimeNodeResourceLookupSupportsAppAndSwiftPMTestLayoutsWithoutFatalAccessor() {
let appBundle = URL(fileURLWithPath: "/Applications/omi-test.app")
let testBundle = URL(fileURLWithPath: "/tmp/debug/Omi ComputerPackageTests.xctest")
let executable =
testBundle
.appendingPathComponent("Contents/MacOS/Omi ComputerPackageTests")
let candidates = AgentRuntimeProcess.runtimeResourceExecutableCandidates(
named: "node",
bundleURLs: [appBundle, testBundle],
executableURL: executable)
XCTAssertTrue(
candidates.contains(
"/Applications/omi-test.app/Contents/Resources/Omi Computer_Omi Computer.bundle/Contents/Resources/node"))
XCTAssertTrue(
candidates.contains(
"/tmp/debug/Omi Computer_Omi Computer.bundle/node"))
XCTAssertFalse(candidates.isEmpty)
}
func testLegacyMainChatAliasReceiptRoutesByRequestAndOwner() {
let message = AgentRuntimeProcess.RuntimeMessage.parse(
#"{"type":"legacy_main_chat_sessions_imported","protocolVersion":2,"requestId":"legacy-1","clientId":"client-1","ownerId":"owner-1","acceptedEntries":[{"chatId":"default","agentSessionId":"ses-1"}],"acceptedCount":1,"importedCount":1}"#
)
XCTAssertEqual(message?.kind, .legacyMainChatSessionsImported)
XCTAssertEqual(
message?.requestKey,
AgentRuntimeProcess.RuntimeMessage.RequestKey(clientId: "client-1", requestId: "legacy-1")
)
XCTAssertEqual(message?.payload["ownerId"] as? String, "owner-1")
}
func testLegacyMainChatAliasImportWireMessageCarriesOwnerAndEntries() {
let entry = LegacyMainChatSessionAliasEntry(chatId: "default", agentSessionId: "ses-1")
let message = AgentRuntimeProcess.importLegacyMainChatSessionsWireMessage(
clientId: "client-1",
requestId: "legacy-1",
ownerId: "owner-1",
entries: [entry]
)
XCTAssertEqual(message["type"] as? String, "import_legacy_main_chat_sessions")
XCTAssertEqual(message["protocolVersion"] as? Int, 2)
XCTAssertEqual(message["ownerId"] as? String, "owner-1")
XCTAssertEqual(
message["entries"] as? [[String: String]],
[["chatId": "default", "agentSessionId": "ses-1"]]
)
}
func testAuthorizedToolExecutionCarriesLedgerIdentityWithoutRequestScope() {
let message = AgentRuntimeProcess.RuntimeMessage.parse(
#"{"type":"authorized_tool_execution","protocolVersion":2,"invocationId":"invoke-1","ownerId":"owner-1","sessionId":"session-1","runId":"run-1","attemptId":"attempt-1","profileGeneration":2,"manifestVersion":1,"manifestDigest":"sha256:test","daemonBootEpoch":"boot-1","executionGeneration":3,"toolName":"get_memories","input":{},"inputHash":"sha256:e3b0","effectClass":"read_only","retryPolicy":"safe_retry","surfaceKind":"background_agent","externalRefKind":null,"externalRefId":null,"originatingUserText":"find memories","precedingAssistantText":null,"runMode":"act","chatMode":null}"#
)
XCTAssertEqual(message?.kind, .authorizedToolExecution)
XCTAssertNil(message?.requestKey)
XCTAssertEqual(message?.payload["invocationId"] as? String, "invoke-1")
XCTAssertEqual(message?.payload["attemptId"] as? String, "attempt-1")
}
func testSwiftHasNoCapabilityAuthorityOrRequestScopedExecution() throws {
let processSourceURL = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent()
.deletingLastPathComponent()
.appendingPathComponent("Sources/Chat/AgentRuntimeProcess.swift")
let processSource = try String(contentsOf: processSourceURL, encoding: .utf8)
XCTAssertTrue(processSource.contains("AuthorizedToolExecution.parse("))
XCTAssertTrue(processSource.contains(#"case .authorizedToolExecution:"#))
XCTAssertFalse(processSource.contains("RunToolCapabilityRegistry"))
XCTAssertFalse(processSource.contains("toolCapabilities"))
XCTAssertFalse(processSource.contains("tool_capability_register"))
XCTAssertFalse(processSource.contains("guard let request = routedRequest(for: message) else"))
}
func testV2MessagesWithoutClientIdDoNotHaveRequestKey() {
let message = AgentRuntimeProcess.RuntimeMessage.parse(
#"{"type":"result","protocolVersion":2,"requestId":"req-1","sessionId":"omi-1","runId":"run-1","attemptId":"attempt-1","terminalStatus":"succeeded","text":"done"}"#
)
XCTAssertEqual(message?.kind, .result)
XCTAssertNil(message?.requestKey)
}
func testHarnessModeMapsNamedAdapters() {
XCTAssertEqual(AgentRuntimeProcess.adapterId(forHarnessMode: "piMono"), "pi-mono")
XCTAssertEqual(AgentRuntimeProcess.adapterId(forHarnessMode: "pi-mono"), "pi-mono")
XCTAssertEqual(AgentRuntimeProcess.adapterId(forHarnessMode: "hermes"), "hermes")
XCTAssertEqual(AgentRuntimeProcess.adapterId(forHarnessMode: "openclaw"), "openclaw")
XCTAssertEqual(AgentRuntimeProcess.adapterId(forHarnessMode: "openClaw"), "openclaw")
XCTAssertNil(AgentRuntimeProcess.adapterId(forHarnessMode: "unknown"))
}
func testPiMonoAliasUsesCanonicalAdapterForAuthGuards() throws {
let processSourceURL = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent()
.deletingLastPathComponent()
.appendingPathComponent("Sources/Chat/AgentRuntimeProcess.swift")
let processSource = try String(contentsOf: processSourceURL, encoding: .utf8)
XCTAssertTrue(
processSource.contains("let preferredAdapterId = AgentRuntimeRouting.adapterId(for: preferredHarness)"))
XCTAssertTrue(processSource.contains("preferredAdapterId == .piMono"))
XCTAssertFalse(processSource.contains(#"preferredHarnessMode == "piMono""#))
let bridgeSourceURL = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent()
.deletingLastPathComponent()
.appendingPathComponent("Sources/Chat/AgentBridge.swift")
let bridgeSource = try String(contentsOf: bridgeSourceURL, encoding: .utf8)
XCTAssertTrue(
bridgeSource.contains(
"AgentRuntimeProcess.adapterId(forHarnessMode: harnessMode) == AgentAdapterId.piMono.rawValue"))
XCTAssertTrue(bridgeSource.contains("shouldRequirePiMonoCredentials("))
XCTAssertTrue(bridgeSource.contains("shouldFetchManagedToken"))
XCTAssertFalse(bridgeSource.contains("if adapterId == AgentAdapterId.piMono.rawValue"))
XCTAssertTrue(
bridgeSource.contains(
"if requiresCredentials {\n ensureTokenRefreshTask(authorizationSnapshot: authorizationSnapshot)"))
XCTAssertFalse(bridgeSource.contains("guard isPiMonoHarness else { return false }"))
XCTAssertFalse(bridgeSource.contains(#"harnessMode == "piMono""#))
}
func testPiMonoInvalidTokenRetriesAfterForcedAuthRefresh() throws {
let bridgeSourceURL = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent()