-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathOpenCodeClientTests.swift
More file actions
2478 lines (2116 loc) · 101 KB
/
OpenCodeClientTests.swift
File metadata and controls
2478 lines (2116 loc) · 101 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
//
// OpenCodeClientTests.swift
// OpenCodeClientTests
//
// Created by Yan Wang on 2/12/26.
//
import Foundation
import SwiftUI
import Testing
@testable import OpenCodeClient
// MARK: - Existing Tests
struct OpenCodeClientTests {
@Test func defaultServerAddress() {
#expect(APIClient.defaultServer == "127.0.0.1:4096")
}
@Test func correctMalformedServerURL() {
// Malformed "host://host:port" from iOS .textContentType(.URL) autocorrect
#expect(AppState.correctMalformedServerURL("quantum.tail63c3c5.ts.net://quantum.tail63c3c5.ts.net:4096") == "quantum.tail63c3c5.ts.net:4096")
#expect(AppState.correctMalformedServerURL("host.example.com://host.example.com:8080") == "host.example.com:8080")
// Legitimate URLs unchanged
#expect(AppState.correctMalformedServerURL("http://quantum.tail63c3c5.ts.net:4096") == nil)
#expect(AppState.correctMalformedServerURL("quantum.tail63c3c5.ts.net:4096") == nil)
#expect(AppState.correctMalformedServerURL("127.0.0.1:4096") == nil)
}
@Test func ensureServerURLHasScheme() {
#expect(AppState.ensureServerURLHasScheme("quantum.tail63c3c5.ts.net:4096") == "http://quantum.tail63c3c5.ts.net:4096")
#expect(AppState.ensureServerURLHasScheme("127.0.0.1:4096") == "http://127.0.0.1:4096")
#expect(AppState.ensureServerURLHasScheme("http://quantum.tail63c3c5.ts.net:4096") == nil)
#expect(AppState.ensureServerURLHasScheme("https://example.com:443") == nil)
}
@Test @MainActor func migrateLegacyDefaultServerAddress() {
let key = "serverURL"
let previous = UserDefaults.standard.string(forKey: key)
defer {
if let previous {
UserDefaults.standard.set(previous, forKey: key)
} else {
UserDefaults.standard.removeObject(forKey: key)
}
}
UserDefaults.standard.set("localhost:4096", forKey: key)
let state = AppState()
#expect(state.serverURL == "127.0.0.1:4096")
}
@Test func sessionDecoding() throws {
let json = """
{"id":"s1","slug":"s1","projectID":"p1","directory":"/tmp","parentID":null,"title":"Test","version":"1","time":{"created":0,"updated":0},"share":null,"summary":null}
"""
let data = json.data(using: .utf8)!
let session = try JSONDecoder().decode(Session.self, from: data)
#expect(session.id == "s1")
#expect(session.title == "Test")
}
@Test func messageDecoding() throws {
let json = """
{"id":"m1","sessionID":"s1","role":"user","parentID":null,"model":{"providerID":"anthropic","modelID":"claude-3"},"time":{"created":0,"completed":null},"finish":null}
"""
let data = json.data(using: .utf8)!
let message = try JSONDecoder().decode(Message.self, from: data)
#expect(message.id == "m1")
#expect(message.isUser == true)
}
@Test func messageDecodingWithoutTokenTotal() throws {
let json = """
{"id":"m2","sessionID":"s1","role":"assistant","parentID":"m1","providerID":"openai","modelID":"gpt-5.2","time":{"created":0,"completed":1},"finish":"stop","tokens":{"input":10,"output":2,"reasoning":3,"cache":{"read":0,"write":0}}}
"""
let data = json.data(using: .utf8)!
let message = try JSONDecoder().decode(Message.self, from: data)
#expect(message.isAssistant == true)
#expect(message.tokens?.input == 10)
#expect(message.tokens?.output == 2)
#expect(message.tokens?.reasoning == 3)
#expect(message.tokens?.total == 15)
}
// Regression: server.connected event has no directory; SSEEvent.directory must be optional
@Test func sseEventDecodingWithoutDirectory() throws {
let json = """
{"payload":{"type":"server.connected","properties":{}}}
"""
let data = json.data(using: .utf8)!
let event = try JSONDecoder().decode(SSEEvent.self, from: data)
#expect(event.directory == nil)
#expect(event.payload.type == "server.connected")
}
@Test func sseEventDecodingWithDirectory() throws {
let json = """
{"directory":"/path/to/workspace","payload":{"type":"message.updated","properties":{}}}
"""
let data = json.data(using: .utf8)!
let event = try JSONDecoder().decode(SSEEvent.self, from: data)
#expect(event.directory == "/path/to/workspace")
#expect(event.payload.type == "message.updated")
}
// handleSSEEvent depends on these event structures - document expected format
@Test func sseEventSessionStatus() throws {
let json = """
{"payload":{"type":"session.status","properties":{"sessionID":"s1","status":{"type":"busy","attempt":1,"message":"Processing","next":null}}}}
"""
let data = json.data(using: .utf8)!
let event = try JSONDecoder().decode(SSEEvent.self, from: data)
#expect(event.payload.type == "session.status")
let props = event.payload.properties ?? [:]
#expect((props["sessionID"]?.value as? String) == "s1")
let statusObj = props["status"]?.value as? [String: Any]
#expect(statusObj != nil)
#expect((statusObj?["type"] as? String) == "busy")
}
@Test func sseEventPermissionAsked() throws {
let json = """
{"payload":{"type":"permission.asked","properties":{"sessionID":"s1","permissionID":"perm1","description":"Run command","tool":"run_terminal_cmd"}}}
"""
let data = json.data(using: .utf8)!
let event = try JSONDecoder().decode(SSEEvent.self, from: data)
#expect(event.payload.type == "permission.asked")
let props = event.payload.properties ?? [:]
#expect((props["sessionID"]?.value as? String) == "s1")
#expect((props["permissionID"]?.value as? String) == "perm1")
#expect((props["description"]?.value as? String) == "Run command")
#expect((props["tool"]?.value as? String) == "run_terminal_cmd")
}
@Test func sseEventTodoUpdated() throws {
let json = """
{"payload":{"type":"todo.updated","properties":{"sessionID":"s1","todos":[{"id":"t1","content":"Task 1","completed":false},{"id":"t2","content":"Task 2","completed":true}]}}}
"""
let data = json.data(using: .utf8)!
let event = try JSONDecoder().decode(SSEEvent.self, from: data)
#expect(event.payload.type == "todo.updated")
let props = event.payload.properties ?? [:]
#expect((props["sessionID"]?.value as? String) == "s1")
let todosObj = props["todos"]?.value
#expect(JSONSerialization.isValidJSONObject(todosObj ?? []))
}
@Test func sseEventMessageUpdated() throws {
let json = """
{"payload":{"type":"message.updated","properties":{"sessionID":"s1","messageID":"m1"}}}
"""
let data = json.data(using: .utf8)!
let event = try JSONDecoder().decode(SSEEvent.self, from: data)
#expect(event.payload.type == "message.updated")
let props = event.payload.properties ?? [:]
#expect((props["sessionID"]?.value as? String) == "s1")
}
// Think Streaming: message.part.updated with delta for typing effect
@Test func sseEventMessagePartUpdatedWithDelta() throws {
let json = """
{"payload":{"type":"message.part.updated","properties":{"sessionID":"s1","messageID":"m1","delta":"Hello ","part":{"id":"p1","messageID":"m1","sessionID":"s1","type":"reasoning"}}}}
"""
let data = json.data(using: .utf8)!
let event = try JSONDecoder().decode(SSEEvent.self, from: data)
#expect(event.payload.type == "message.part.updated")
let props = event.payload.properties ?? [:]
#expect((props["sessionID"]?.value as? String) == "s1")
#expect((props["delta"]?.value as? String) == "Hello ")
let partObj = props["part"]?.value as? [String: Any]
#expect(partObj != nil)
#expect((partObj?["messageID"] as? String) == "m1")
#expect((partObj?["id"] as? String) == "p1")
}
// Regression: Part.state can be String or object (ToolState); was causing loadMessages decode failure during thinking
@Test func partDecodingWithStateAsString() throws {
let partJson = """
{"id":"p1","messageID":"m1","sessionID":"s1","type":"tool","text":null,"tool":"read_file","callID":"c1","state":"pending","metadata":null,"files":null}
"""
let data = partJson.data(using: .utf8)!
let part = try JSONDecoder().decode(Part.self, from: data)
#expect(part.stateDisplay == "pending")
#expect(part.isTool == true)
}
@Test func partDecodingWithStateAsObject() throws {
let partJson = """
{"id":"p1","messageID":"m1","sessionID":"s1","type":"tool","text":null,"tool":"read_file","callID":"c1","state":{"status":"running","input":{},"time":{"start":1700000000}},"metadata":null,"files":null}
"""
let data = partJson.data(using: .utf8)!
let part = try JSONDecoder().decode(Part.self, from: data)
#expect(part.stateDisplay == "running")
}
@Test func partDecodingWithStateObjectWithTitle() throws {
let partJson = """
{"id":"p1","messageID":"m1","sessionID":"s1","type":"tool","text":null,"tool":"run_terminal_cmd","callID":"c1","state":{"status":"completed","input":{},"output":"done","title":"Running command","metadata":{},"time":{"start":0,"end":1}},"metadata":null,"files":null}
"""
let data = partJson.data(using: .utf8)!
let part = try JSONDecoder().decode(Part.self, from: data)
#expect(part.stateDisplay == "completed")
}
@Test func partDecodingTodoFromMetadataWithObjectInput() throws {
let partJson = """
{"id":"p1","messageID":"m1","sessionID":"s1","type":"tool","text":null,"tool":"todowrite","callID":"c1","state":{"status":"completed","input":{},"output":"[{\\"content\\":\\"Write tests\\",\\"status\\":\\"pending\\",\\"priority\\":\\"high\\"}]","title":"1 todo","metadata":{"todos":[{"content":"Write tests","status":"pending","priority":"high"}],"input":{"todos":[{"content":"Write tests","status":"pending","priority":"high"}]},"description":"todo update"},"time":{"start":0,"end":1}},"metadata":{"input":{"todos":[{"content":"Write tests","status":"pending","priority":"high"}]},"todos":[{"content":"Write tests","status":"pending","priority":"high"}]},"files":null}
"""
let data = partJson.data(using: .utf8)!
let part = try JSONDecoder().decode(Part.self, from: data)
#expect(part.toolTodos.count == 1)
#expect(part.toolTodos.first?.content == "Write tests")
#expect(part.toolTodos.first?.id.isEmpty == false)
}
@Test func todoItemDecodingLegacyCompletedShape() throws {
let json = """
{"content":"Task 1","completed":true}
"""
let data = json.data(using: .utf8)!
let item = try JSONDecoder().decode(TodoItem.self, from: data)
#expect(item.content == "Task 1")
#expect(item.status == "completed")
#expect(item.priority == "medium")
#expect(item.id.isEmpty == false)
}
@Test func messageWithPartsDecodingWithToolStateObject() throws {
let json = """
{"info":{"id":"m1","sessionID":"s1","role":"assistant","parentID":null,"model":{"providerID":"anthropic","modelID":"claude-3"},"time":{"created":0,"completed":null},"finish":null},"parts":[{"id":"p1","messageID":"m1","sessionID":"s1","type":"text","text":"Hello","tool":null,"callID":null,"state":null,"metadata":null,"files":null},{"id":"p2","messageID":"m1","sessionID":"s1","type":"tool","text":null,"tool":"read_file","callID":"c1","state":{"status":"running","input":{},"time":{"start":0}},"metadata":null,"files":null}]}
"""
let data = json.data(using: .utf8)!
let msg = try JSONDecoder().decode(MessageWithParts.self, from: data)
#expect(msg.parts.count == 2)
#expect(msg.parts[0].stateDisplay == nil)
#expect(msg.parts[1].stateDisplay == "running")
}
@Test func partFilePathsFromApplyPatch() throws {
// patchText with "*** Add File: path" - path should be extracted
let partJson = """
{"id":"p1","messageID":"m1","sessionID":"s1","type":"tool","text":null,"tool":"apply_patch","callID":"c1","state":{"status":"completed","input":{"patchText":"*** Begin Patch\\n*** Add File: research/deepseek-news-2026-02.md\\n+# content"},"metadata":{}},"metadata":null,"files":null}
"""
let data = partJson.data(using: .utf8)!
let part = try JSONDecoder().decode(Part.self, from: data)
#expect(part.filePathsForNavigation.contains("research/deepseek-news-2026-02.md"))
}
@Test func testImageExtensionDetection() {
#expect(ImageFileUtils.isImage("image.png") == true)
#expect(ImageFileUtils.isImage("photo.jpg") == true)
#expect(ImageFileUtils.isImage("photo.jpeg") == true)
#expect(ImageFileUtils.isImage("animation.gif") == true)
#expect(ImageFileUtils.isImage("asset.webp") == true)
#expect(ImageFileUtils.isImage("capture.heic") == true)
#expect(ImageFileUtils.isImage("file.swift") == false)
#expect(ImageFileUtils.isImage("README.md") == false)
#expect(ImageFileUtils.isImage("notes.txt") == false)
#expect(ImageFileUtils.isImage("payload.json") == false)
#expect(ImageFileUtils.isImage("ICON.PNG") == true)
#expect(ImageFileUtils.isImage("photo.Jpg") == true)
#expect(ImageFileUtils.isImage("archive.tar.gz") == false)
#expect(ImageFileUtils.isImage("photo.edit.png") == true)
}
@Test func testBase64ImageDecoding() {
let base64PNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO5WZfQAAAAASUVORK5CYII="
let data = Data(base64Encoded: base64PNG)
#expect(data != nil)
if let data {
#expect(UIImage(data: data) != nil)
}
}
}
// MARK: - Session Filtering (Code Review 1.3)
struct SessionFilteringTests {
@Test func shouldProcessWhenSessionMatches() {
#expect(AppState.shouldProcessMessageEvent(eventSessionID: "s1", currentSessionID: "s1") == true)
}
@Test func shouldNotProcessWhenSessionMismatch() {
#expect(AppState.shouldProcessMessageEvent(eventSessionID: "s2", currentSessionID: "s1") == false)
}
@Test func shouldNotProcessWhenNoCurrentSession() {
#expect(AppState.shouldProcessMessageEvent(eventSessionID: "s1", currentSessionID: nil) == false)
}
@Test func shouldProcessWhenNoEventSessionIDForBackwardCompat() {
#expect(AppState.shouldProcessMessageEvent(eventSessionID: nil, currentSessionID: "s1") == true)
}
@Test func shouldApplySessionScopedResultWhenRequestedStillCurrent() {
#expect(AppState.shouldApplySessionScopedResult(requestedSessionID: "s1", currentSessionID: "s1") == true)
}
@Test func shouldDropSessionScopedResultWhenSessionChanged() {
#expect(AppState.shouldApplySessionScopedResult(requestedSessionID: "s2", currentSessionID: "s1") == false)
}
}
// MARK: - Message Pagination
struct MessagePaginationTests {
@Test func normalizedMessageFetchLimitDefaultsToPageSize() {
#expect(AppState.normalizedMessageFetchLimit(current: nil) == 20)
}
@Test func normalizedMessageFetchLimitUsesAtLeastPageSize() {
#expect(AppState.normalizedMessageFetchLimit(current: 2) == 20)
#expect(AppState.normalizedMessageFetchLimit(current: 24) == 24)
}
@Test func nextMessageFetchLimitAddsOnePage() {
#expect(AppState.nextMessageFetchLimit(current: nil) == 40)
#expect(AppState.nextMessageFetchLimit(current: 20) == 40)
#expect(AppState.nextMessageFetchLimit(current: 40) == 60)
}
}
// MARK: - Session Deletion Selection
struct SessionDeletionSelectionTests {
@Test func keepCurrentWhenDeletingDifferentSession() {
let sessions = [
makeSession(id: "s1", updated: 3),
makeSession(id: "s2", updated: 2),
makeSession(id: "s3", updated: 1),
]
let next = AppState.nextSessionIDAfterDeleting(
deletedSessionID: "s2",
currentSessionID: "s1",
remainingSessions: sessions.filter { $0.id != "s2" }
)
#expect(next == "s1")
}
@Test func pickMostRecentlyUpdatedWhenDeletingCurrentSession() {
let sessions = [
makeSession(id: "older", updated: 10),
makeSession(id: "newer", updated: 30),
makeSession(id: "middle", updated: 20),
]
let next = AppState.nextSessionIDAfterDeleting(
deletedSessionID: "older",
currentSessionID: "older",
remainingSessions: sessions.filter { $0.id != "older" }
)
#expect(next == "newer")
}
@Test func clearCurrentWhenDeletingLastSession() {
let next = AppState.nextSessionIDAfterDeleting(
deletedSessionID: "only",
currentSessionID: "only",
remainingSessions: []
)
#expect(next == nil)
}
private func makeSession(id: String, updated: Int) -> Session {
Session(
id: id,
slug: id,
projectID: "p1",
directory: "/tmp",
parentID: nil,
title: id,
version: "1",
time: .init(created: 0, updated: updated, archived: nil),
share: nil,
summary: nil
)
}
}
// MARK: - Message & Role Tests
struct MessageRoleTests {
@Test func messageIsAssistant() throws {
let json = """
{"id":"m2","sessionID":"s1","role":"assistant","parentID":null,"model":{"providerID":"openai","modelID":"gpt-4"},"time":{"created":100,"completed":200},"finish":"stop"}
"""
let data = json.data(using: .utf8)!
let message = try JSONDecoder().decode(Message.self, from: data)
#expect(message.isAssistant == true)
#expect(message.isUser == false)
#expect(message.finish == "stop")
}
@Test func messageWithNilModel() throws {
let json = """
{"id":"m3","sessionID":"s1","role":"user","parentID":"m2","model":null,"time":{"created":50,"completed":null},"finish":null}
"""
let data = json.data(using: .utf8)!
let message = try JSONDecoder().decode(Message.self, from: data)
#expect(message.model == nil)
#expect(message.parentID == "m2")
}
}
// MARK: - ModelPreset Tests
struct ModelPresetTests {
@Test func modelPresetId() {
let preset = ModelPreset(displayName: "Claude", providerID: "anthropic", modelID: "claude-3")
#expect(preset.id == "anthropic/claude-3")
#expect(preset.displayName == "Claude")
}
@Test func modelPresetDecoding() throws {
let json = """
{"displayName":"GPT-4","providerID":"openai","modelID":"gpt-4-turbo"}
"""
let data = json.data(using: .utf8)!
let preset = try JSONDecoder().decode(ModelPreset.self, from: data)
#expect(preset.id == "openai/gpt-4-turbo")
}
}
// MARK: - Session Tests
struct SessionDecodingTests {
@Test func sessionWithShareAndSummary() throws {
let json = """
{"id":"s2","slug":"s2","projectID":"p1","directory":"/workspace","parentID":"s1","title":"Feature Branch","version":"2","time":{"created":1000,"updated":2000},"share":{"url":"https://example.com/share/s2"},"summary":{"additions":42,"deletions":10,"files":3}}
"""
let data = json.data(using: .utf8)!
let session = try JSONDecoder().decode(Session.self, from: data)
#expect(session.parentID == "s1")
#expect(session.share?.url == "https://example.com/share/s2")
#expect(session.summary?.additions == 42)
#expect(session.summary?.deletions == 10)
#expect(session.summary?.files == 3)
}
@Test func sessionStatusDecoding() throws {
let json = """
{"type":"busy","attempt":2,"message":"Processing...","next":null}
"""
let data = json.data(using: .utf8)!
let status = try JSONDecoder().decode(SessionStatus.self, from: data)
#expect(status.type == "busy")
#expect(status.attempt == 2)
#expect(status.message == "Processing...")
}
@Test func sessionStatusIdleDecoding() throws {
let json = """
{"type":"idle","attempt":null,"message":null,"next":null}
"""
let data = json.data(using: .utf8)!
let status = try JSONDecoder().decode(SessionStatus.self, from: data)
#expect(status.type == "idle")
#expect(status.attempt == nil)
}
}
// MARK: - Part Type Check Tests
struct PartTypeTests {
private func makePart(type: String, tool: String? = nil, text: String? = nil) throws -> Part {
let toolStr = tool.map { "\"\($0)\"" } ?? "null"
let textStr = text.map { "\"\($0)\"" } ?? "null"
let json = """
{"id":"p1","messageID":"m1","sessionID":"s1","type":"\(type)","text":\(textStr),"tool":\(toolStr),"callID":null,"state":null,"metadata":null,"files":null}
"""
return try JSONDecoder().decode(Part.self, from: json.data(using: .utf8)!)
}
@Test func partIsText() throws {
let part = try makePart(type: "text", text: "Hello world")
#expect(part.isText == true)
#expect(part.isReasoning == false)
#expect(part.isTool == false)
#expect(part.isPatch == false)
#expect(part.isStepStart == false)
#expect(part.isStepFinish == false)
}
@Test func partIsReasoning() throws {
let part = try makePart(type: "reasoning", text: "Let me think...")
#expect(part.isReasoning == true)
#expect(part.isText == false)
}
@Test func partIsTool() throws {
let part = try makePart(type: "tool", tool: "bash")
#expect(part.isTool == true)
#expect(part.isText == false)
}
@Test func partIsPatch() throws {
let part = try makePart(type: "patch")
#expect(part.isPatch == true)
}
@Test func partIsStepStart() throws {
let part = try makePart(type: "step-start")
#expect(part.isStepStart == true)
#expect(part.isStepFinish == false)
}
@Test func partIsStepFinish() throws {
let part = try makePart(type: "step-finish")
#expect(part.isStepFinish == true)
#expect(part.isStepStart == false)
}
}
// MARK: - File Path Navigation Tests
struct FilePathNavigationTests {
@Test func filePathsFromFilesArray() throws {
let json = """
{"id":"p1","messageID":"m1","sessionID":"s1","type":"patch","text":null,"tool":null,"callID":null,"state":null,"metadata":null,"files":[{"path":"src/main.swift","additions":5,"deletions":2,"status":"modified"},{"path":"src/utils.swift","additions":10,"deletions":0,"status":"added"}]}
"""
let data = json.data(using: .utf8)!
let part = try JSONDecoder().decode(Part.self, from: data)
#expect(part.filePathsForNavigation.count == 2)
#expect(part.filePathsForNavigation.contains("src/main.swift"))
#expect(part.filePathsForNavigation.contains("src/utils.swift"))
}
@Test func filePathsFromMetadata() throws {
let json = """
{"id":"p1","messageID":"m1","sessionID":"s1","type":"tool","text":null,"tool":"read_file","callID":"c1","state":null,"metadata":{"path":"docs/README.md","title":null,"input":null},"files":null}
"""
let data = json.data(using: .utf8)!
let part = try JSONDecoder().decode(Part.self, from: data)
#expect(part.filePathsForNavigation == ["docs/README.md"])
}
@Test func filePathsFromStateInputPath() throws {
let json = """
{"id":"p1","messageID":"m1","sessionID":"s1","type":"tool","text":null,"tool":"write_file","callID":"c1","state":{"status":"completed","input":{"path":"src/new_file.swift","content":"// new"},"metadata":{}},"metadata":null,"files":null}
"""
let data = json.data(using: .utf8)!
let part = try JSONDecoder().decode(Part.self, from: data)
#expect(part.filePathsForNavigation.contains("src/new_file.swift"))
}
@Test func filePathsDeduplicated() throws {
// state.input.path same as metadata.path — should not duplicate
let json = """
{"id":"p1","messageID":"m1","sessionID":"s1","type":"tool","text":null,"tool":"edit_file","callID":"c1","state":{"status":"completed","input":{"path":"src/app.swift"},"metadata":{}},"metadata":{"path":"src/app.swift","title":null,"input":null},"files":null}
"""
let data = json.data(using: .utf8)!
let part = try JSONDecoder().decode(Part.self, from: data)
#expect(part.filePathsForNavigation.count == 1)
#expect(part.filePathsForNavigation[0] == "src/app.swift")
}
@Test func filePathsFromUpdateFilePatch() throws {
let json = """
{"id":"p1","messageID":"m1","sessionID":"s1","type":"tool","text":null,"tool":"apply_patch","callID":"c1","state":{"status":"completed","input":{"patchText":"*** Begin Patch\\n*** Update File: lib/parser.py\\n@@ -10,3 +10,5 @@\\n+import os"},"metadata":{}},"metadata":null,"files":null}
"""
let data = json.data(using: .utf8)!
let part = try JSONDecoder().decode(Part.self, from: data)
#expect(part.filePathsForNavigation.contains("lib/parser.py"))
}
@Test func filePathsEmptyWhenNone() throws {
let json = """
{"id":"p1","messageID":"m1","sessionID":"s1","type":"text","text":"Hello","tool":null,"callID":null,"state":null,"metadata":null,"files":null}
"""
let data = json.data(using: .utf8)!
let part = try JSONDecoder().decode(Part.self, from: data)
#expect(part.filePathsForNavigation.isEmpty)
}
// Path normalization: a/, b/ prefix, #L, :line:col suffixes stripped (via filePathsForNavigation)
@Test func filePathsNormalizedFromMetadata() throws {
let json = """
{"id":"p1","messageID":"m1","sessionID":"s1","type":"tool","text":null,"tool":"read_file","callID":"c1","state":null,"metadata":{"path":"a/src/app.swift","title":null,"input":null},"files":null}
"""
let data = json.data(using: .utf8)!
let part = try JSONDecoder().decode(Part.self, from: data)
#expect(part.filePathsForNavigation == ["src/app.swift"])
}
@Test func filePathsNormalizedStripHashAndLine() throws {
// # and everything after -> stripped first; :line:col at end -> stripped
let json = """
{"id":"p1","messageID":"m1","sessionID":"s1","type":"tool","text":null,"tool":"read_file","callID":"c1","state":null,"metadata":{"path":"docs/readme.md#L42","title":null,"input":null},"files":null}
"""
let data = json.data(using: .utf8)!
let part = try JSONDecoder().decode(Part.self, from: data)
#expect(part.filePathsForNavigation == ["docs/readme.md"])
}
@Test func filePathsNormalizedStripLineColSuffix() throws {
let json = """
{"id":"p1","messageID":"m1","sessionID":"s1","type":"tool","text":null,"tool":"read_file","callID":"c1","state":null,"metadata":{"path":"src/app.swift:42:10","title":null,"input":null},"files":null}
"""
let data = json.data(using: .utf8)!
let part = try JSONDecoder().decode(Part.self, from: data)
#expect(part.filePathsForNavigation == ["src/app.swift"])
}
}
// MARK: - PathNormalizer (Code Review 1.4)
struct PathNormalizerTests {
@Test func stripsABPrefix() {
#expect(PathNormalizer.normalize("a/src/app.swift") == "src/app.swift")
#expect(PathNormalizer.normalize("b/docs/readme.md") == "docs/readme.md")
}
@Test func stripsHashAndSuffix() {
#expect(PathNormalizer.normalize("docs/readme.md#L42") == "docs/readme.md")
}
@Test func stripsLineColSuffix() {
#expect(PathNormalizer.normalize("src/app.swift:42:10") == "src/app.swift")
#expect(PathNormalizer.normalize("lib/parser.py:10") == "lib/parser.py")
}
@Test func trimsWhitespace() {
#expect(PathNormalizer.normalize(" src/app.swift ") == "src/app.swift")
}
@Test func leavesPlainPathUnchanged() {
#expect(PathNormalizer.normalize("src/main.swift") == "src/main.swift")
}
@Test func stripsDotDotSegments() {
#expect(PathNormalizer.normalize("../secrets.txt") == "secrets.txt")
#expect(PathNormalizer.normalize("src/../app.swift") == "src/app.swift")
#expect(PathNormalizer.normalize("a/../b/./c.txt") == "b/c.txt")
}
@Test func resolvesWorkspaceRelativeFromAbsolutePath() {
let dir = "/Users/test/workspace"
let abs = "/Users/test/workspace/docs/readme.md#L42"
#expect(PathNormalizer.resolveWorkspaceRelativePath(abs, workspaceDirectory: dir) == "docs/readme.md")
}
@Test func resolvesWorkspaceRelativeKeepsRelativePath() {
let dir = "/Users/test/workspace"
let rel = "docs/readme.md"
#expect(PathNormalizer.resolveWorkspaceRelativePath(rel, workspaceDirectory: dir) == "docs/readme.md")
}
@Test func resolvesWorkspaceRelativeDecodesPercentEncoding() {
let dir = "/Users/test/workspace"
let abs = "/Users/test/workspace/src%2Fapp.swift"
#expect(PathNormalizer.resolveWorkspaceRelativePath(abs, workspaceDirectory: dir) == "src/app.swift")
}
}
// MARK: - PartStateBridge Tests
struct PartStateBridgeTests {
@Test func stateWithOutputAndTitle() throws {
let json = """
{"id":"p1","messageID":"m1","sessionID":"s1","type":"tool","text":null,"tool":"bash","callID":"c1","state":{"status":"completed","input":{"command":"ls -la"},"output":"file1 file2","title":"Listing files","metadata":{}},"metadata":null,"files":null}
"""
let data = json.data(using: .utf8)!
let part = try JSONDecoder().decode(Part.self, from: data)
#expect(part.toolReason == "Listing files")
#expect(part.toolInputSummary == "ls -la")
#expect(part.toolOutput == "file1 file2")
}
@Test func stateWithOutputDirectly() throws {
// When state has output directly at top level
let json = """
{"id":"p1","messageID":"m1","sessionID":"s1","type":"tool","text":null,"tool":"custom","callID":"c1","state":{"status":"running","input":{},"output":"partial result","title":"Fetching data"},"metadata":null,"files":null}
"""
let data = json.data(using: .utf8)!
let part = try JSONDecoder().decode(Part.self, from: data)
#expect(part.toolReason == "Fetching data")
#expect(part.toolOutput == "partial result")
}
@Test func stateWithStringInput() throws {
let json = """
{"id":"p1","messageID":"m1","sessionID":"s1","type":"tool","text":null,"tool":"eval","callID":"c1","state":{"status":"completed","input":"print('hello')"},"metadata":null,"files":null}
"""
let data = json.data(using: .utf8)!
let part = try JSONDecoder().decode(Part.self, from: data)
#expect(part.toolInputSummary == "print('hello')")
// No path extraction from string input
#expect(part.filePathsForNavigation.isEmpty)
}
}
// MARK: - API Response Model Tests
struct APIResponseModelTests {
@Test func fileContentTextDecoding() throws {
let json = """
{"type":"text","content":"# Hello World"}
"""
let data = json.data(using: .utf8)!
let fc = try JSONDecoder().decode(FileContent.self, from: data)
#expect(fc.text == "# Hello World")
#expect(fc.type == "text")
}
@Test func fileContentBinaryDecoding() throws {
let json = """
{"type":"binary","content":null}
"""
let data = json.data(using: .utf8)!
let fc = try JSONDecoder().decode(FileContent.self, from: data)
#expect(fc.text == nil)
#expect(fc.type == "binary")
}
@Test func fileNodeDecoding() throws {
let json = """
{"name":"src","path":"src","absolute":"/workspace/src","type":"directory","ignored":false}
"""
let data = json.data(using: .utf8)!
let node = try JSONDecoder().decode(FileNode.self, from: data)
#expect(node.id == "src")
#expect(node.type == "directory")
#expect(node.absolute == "/workspace/src")
#expect(node.ignored == false)
}
@Test func fileDiffDecoding() throws {
let json = """
{"file":"main.swift","before":"old","after":"new","additions":5,"deletions":3,"status":"modified"}
"""
let data = json.data(using: .utf8)!
let diff = try JSONDecoder().decode(FileDiff.self, from: data)
#expect(diff.id == "main.swift")
#expect(diff.additions == 5)
#expect(diff.deletions == 3)
#expect(diff.status == "modified")
}
@Test func fileDiffEquality() {
let d1 = FileDiff(file: "a.swift", before: "", after: "x", additions: 1, deletions: 0, status: nil)
let d2 = FileDiff(file: "a.swift", before: "", after: "y", additions: 2, deletions: 0, status: nil)
#expect(d1 == d2) // equality is by file name only
}
@Test func healthResponseDecoding() throws {
let json = """
{"healthy":true,"version":"1.2.3"}
"""
let data = json.data(using: .utf8)!
let health = try JSONDecoder().decode(HealthResponse.self, from: data)
#expect(health.healthy == true)
#expect(health.version == "1.2.3")
}
@Test func projectDecoding() throws {
let json = """
{"id":"abc123","worktree":"/Users/me/co/knowledge_working","vcs":"git","icon":{"color":"pink"},"time":{"created":1770951645865,"updated":1771000000360},"sandboxes":[]}
"""
let data = json.data(using: .utf8)!
let project = try JSONDecoder().decode(Project.self, from: data)
#expect(project.id == "abc123")
#expect(project.worktree == "/Users/me/co/knowledge_working")
#expect(project.displayName == "knowledge_working")
}
@Test func fileStatusEntryDecoding() throws {
let json = """
{"path":"src/app.swift","status":"modified"}
"""
let data = json.data(using: .utf8)!
let entry = try JSONDecoder().decode(FileStatusEntry.self, from: data)
#expect(entry.path == "src/app.swift")
#expect(entry.status == "modified")
}
}
// MARK: - AppError Tests
struct AppErrorTests {
@Test func appErrorConnectionFailed() {
let error = AppError.connectionFailed("Network unreachable")
#expect(error.localizedDescription == L10n.errorMessage(.errorConnectionFailed, "Network unreachable"))
#expect(error.isConnectionError == true)
#expect(error.isRecoverable == true)
}
@Test func appErrorUnauthorized() {
let error = AppError.unauthorized
#expect(error.localizedDescription == L10n.t(.errorUnauthorized))
#expect(error.isRecoverable == true)
}
@Test func appErrorFromFileNotFound() {
let error = AppError.fileNotFound("/path/to/file.swift")
#expect(error.localizedDescription == L10n.errorMessage(.errorFileNotFound, "/path/to/file.swift"))
#expect(error.isRecoverable == false)
}
@Test func appErrorFromNSError() {
let nsError = NSError(domain: NSURLErrorDomain, code: -1001, userInfo: [NSLocalizedDescriptionKey: "Request timed out"])
let appError = AppError.from(nsError)
if case .connectionFailed = appError {
#expect(Bool(true))
} else {
Issue.record("Expected connectionFailed error")
}
}
@Test func appErrorEquality() {
let e1 = AppError.connectionFailed("test")
let e2 = AppError.connectionFailed("test")
let e3 = AppError.connectionFailed("other")
#expect(e1 == e2)
#expect(e1 != e3)
}
}
struct LocalizationTests {
@Test func localizationKeyCoverage() {
#expect(L10n.missingEnglishKeys.isEmpty)
#expect(L10n.missingChineseKeys.isEmpty)
}
}
// MARK: - LayoutConstants Tests
struct LayoutConstantsTests {
@Test func splitViewFractions() {
#expect(LayoutConstants.SplitView.sidebarWidthFraction == 1.0 / 6.0)
#expect(LayoutConstants.SplitView.previewWidthFraction == 5.0 / 12.0)
#expect(LayoutConstants.SplitView.chatWidthFraction == 5.0 / 12.0)
}
@Test func splitViewFractionsSum() {
let total = LayoutConstants.SplitView.sidebarWidthFraction
+ LayoutConstants.SplitView.previewWidthFraction
+ LayoutConstants.SplitView.chatWidthFraction
#expect(total == 1.0)
}
@Test func splitViewBoundFractions() {
#expect(LayoutConstants.SplitView.sidebarMinFraction < LayoutConstants.SplitView.sidebarWidthFraction)
#expect(LayoutConstants.SplitView.sidebarMaxFraction > LayoutConstants.SplitView.sidebarWidthFraction)
#expect(LayoutConstants.SplitView.paneMinFraction < LayoutConstants.SplitView.previewWidthFraction)
#expect(LayoutConstants.SplitView.paneMaxFraction > LayoutConstants.SplitView.previewWidthFraction)
}
@Test func animationDurations() {
#expect(LayoutConstants.Animation.shortDuration < LayoutConstants.Animation.defaultDuration)
#expect(LayoutConstants.Animation.defaultDuration < LayoutConstants.Animation.longDuration)
}
@Test func spacingValues() {
#expect(LayoutConstants.Spacing.compact < LayoutConstants.Spacing.standard)
#expect(LayoutConstants.Spacing.standard < LayoutConstants.Spacing.comfortable)
#expect(LayoutConstants.Spacing.comfortable < LayoutConstants.Spacing.spacious)
}
}
// MARK: - Speech Recognition Defaults
struct SpeechRecognitionDefaultsTests {
@Test @MainActor func speechRecognitionDefaultPromptAndTerminology() async {
// Clear stored values so AppState falls back to defaults
UserDefaults.standard.removeObject(forKey: "aiBuilderCustomPrompt")
UserDefaults.standard.removeObject(forKey: "aiBuilderTerminology")
let state = AppState()
#expect(state.aiBuilderCustomPrompt.contains("snake_case"))
#expect(state.aiBuilderCustomPrompt.contains("lowercase"))
#expect(state.aiBuilderTerminology == "adhoc_jobs, life_consulting, survey_sessions, thought_review")
}
@Test @MainActor func speechRecognitionPersistence() async {
let state = AppState()
state.aiBuilderCustomPrompt = "test prompt"
state.aiBuilderTerminology = "foo, bar"
#expect(state.aiBuilderCustomPrompt == "test prompt")
#expect(state.aiBuilderTerminology == "foo, bar")
// Restore defaults for other tests
UserDefaults.standard.removeObject(forKey: "aiBuilderCustomPrompt")
UserDefaults.standard.removeObject(forKey: "aiBuilderTerminology")
}
}
struct AIBuildersAudioClientTests {
@Test func normalizedBaseURLAddsHTTPSWhenMissing() {
let url = AIBuildersAudioClient.normalizedBaseURL(from: "space.ai-builders.com/backend")
#expect(url.absoluteString == "https://space.ai-builders.com/backend")
}
@Test func realtimeWebSocketURLPreservesHostAndSwitchesScheme() throws {
let baseURL = URL(string: "https://space.ai-builders.com/backend")!
let websocketURL = try AIBuildersAudioClient.realtimeWebSocketURL(
baseURL: baseURL,
relativePath: "/v1/audio/realtime/ws?ticket=abc123"
)
#expect(websocketURL.absoluteString == "wss://space.ai-builders.com/v1/audio/realtime/ws?ticket=abc123")
}
@Test func realtimeWebSocketURLWithMountPath() throws {
let baseURL = URL(string: "https://space.ai-builders.com/backend")!
let websocketURL = try AIBuildersAudioClient.realtimeWebSocketURL(
baseURL: baseURL,
relativePath: "/backend/v1/audio/realtime/ws?ticket=abc123"
)
#expect(websocketURL.absoluteString == "wss://space.ai-builders.com/backend/v1/audio/realtime/ws?ticket=abc123")
}
@Test func buildAPIURLPreservesMountPath() throws {
let baseWithMount = URL(string: "https://space.ai-builders.com/backend")!
let url = AIBuildersAudioClient.buildAPIURL(base: baseWithMount, path: "/v1/audio/realtime/sessions")
#expect(url?.absoluteString == "https://space.ai-builders.com/backend/v1/audio/realtime/sessions")
}
@Test func buildAPIURLWithoutMountPath() throws {
let baseNoMount = URL(string: "https://space.ai-builders.com")!
let url = AIBuildersAudioClient.buildAPIURL(base: baseNoMount, path: "/v1/audio/realtime/sessions")
#expect(url?.absoluteString == "https://space.ai-builders.com/v1/audio/realtime/sessions")
}
@Test func mergedSpeechInputOmitsLeadingSpaceForEmptyPrefix() {
#expect(ChatTabView.mergedSpeechInput(prefix: "", transcript: " hello world ") == "hello world")
}
@Test func mergedSpeechInputKeepsSeparatorForExistingInput() {
#expect(ChatTabView.mergedSpeechInput(prefix: "Existing draft", transcript: "partial") == "Existing draft partial")
}
}
// MARK: - APIConstants Tests
struct APIConstantsTests {
@Test func defaultServer() {
#expect(APIConstants.defaultServer == "127.0.0.1:4096")
}
@Test func legacyDefaultServer() {
#expect(APIConstants.legacyDefaultServer == "localhost:4096")
}
@Test func sseEndpoint() {
#expect(APIConstants.sseEndpoint == "/global/event")
}
@Test func healthEndpoint() {
#expect(APIConstants.healthEndpoint == "/global/health")
}
@Test func timeoutValues() {
#expect(APIConstants.Timeout.connection > 0)
#expect(APIConstants.Timeout.request > APIConstants.Timeout.connection)
}
}
struct MessageRenderingHeuristicTests {
@Test func markdownHeuristicDetectsPlainText() {
#expect(MessageRowView.hasMarkdownSyntax("this is a plain sentence") == false)
}
@Test func markdownHeuristicDetectsHeader() {
#expect(MessageRowView.hasMarkdownSyntax("# Title") == true)
}
@Test func markdownHeuristicDetectsCodeFence() {
#expect(MessageRowView.hasMarkdownSyntax("```swift\nprint(1)\n```") == true)
}
}
struct ChatScrollBehaviorTests {
@Test func shouldAutoScrollWhenBottomMarkerIsVisible() {
#expect(
ChatScrollBehavior.shouldAutoScroll(
bottomMarkerMinY: 640,