-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathCLINotifyProcessIntegrationRegressionTests.swift
More file actions
9453 lines (8629 loc) · 430 KB
/
Copy pathCLINotifyProcessIntegrationRegressionTests.swift
File metadata and controls
9453 lines (8629 loc) · 430 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
import Darwin
#if canImport(cmux_DEV)
@testable import cmux_DEV
#elseif canImport(cmux)
@testable import cmux
#endif
final class CLINotifyProcessIntegrationRegressionTests: XCTestCase {
func testClaudeClearSessionStartMarksWorkspaceRunning() throws {
let context = try makeClaudeHookContext(name: "claude-clear-running")
defer { context.cleanup() }
let result = runClaudeHook(
context: context,
arguments: ["hooks", "claude", "session-start"],
standardInput: #"{"session_id":"clear-session","source":"clear","cwd":"\#(context.root.path)","hook_event_name":"SessionStart"}"#
)
XCTAssertFalse(result.timedOut, result.stderr)
XCTAssertEqual(result.status, 0, result.stderr)
XCTAssertEqual(result.stdout, "OK\n")
XCTAssertTrue(
context.state.commands.contains { $0 == "clear_notifications --tab=\(context.workspaceId)" },
"Expected clear SessionStart to clear stale notifications, saw \(context.state.commands)"
)
XCTAssertTrue(
context.state.commands.contains {
$0.hasPrefix("set_status claude_code Running --icon=bolt.fill --color=#4C8DFF --tab=\(context.workspaceId)")
&& $0.contains("--panel=\(context.surfaceId)")
},
"Expected clear SessionStart to mark Claude running, saw \(context.state.commands)"
)
}
func testClaudeSessionStartRecordIsNotRestorableUntilPrompt() throws {
let context = try makeClaudeHookContext(name: "claude-session-restorable")
defer { context.cleanup() }
let sessionId = "startup-only-session"
let start = runClaudeHook(
context: context,
arguments: ["hooks", "claude", "session-start"],
standardInput: #"{"session_id":"\#(sessionId)","source":"startup","cwd":"\#(context.root.path)","transcript_path":"\#(context.root.path)/projects/startup-only-session.jsonl","hook_event_name":"SessionStart"}"#
)
XCTAssertFalse(start.timedOut, start.stderr)
XCTAssertEqual(start.status, 0, start.stderr)
var record = try readClaudeHookSession(sessionId, context: context)
XCTAssertEqual(
record["isRestorable"] as? Bool,
false,
"Startup SessionStart records are only routing state until Claude creates a conversation."
)
XCTAssertEqual(
record["transcriptPath"] as? String,
"\(context.root.path)/projects/startup-only-session.jsonl"
)
let prompt = runClaudeHook(
context: context,
arguments: ["hooks", "claude", "prompt-submit"],
standardInput: #"{"session_id":"\#(sessionId)","turn_id":"turn-1","cwd":"\#(context.root.path)","transcript_path":"\#(context.root.path)/projects/startup-only-session.jsonl","hook_event_name":"UserPromptSubmit"}"#
)
XCTAssertFalse(prompt.timedOut, prompt.stderr)
XCTAssertEqual(prompt.status, 0, prompt.stderr)
record = try readClaudeHookSession(sessionId, context: context)
XCTAssertEqual(
record["isRestorable"] as? Bool,
true,
"UserPromptSubmit marks the session eligible for resume."
)
}
func testClaudePreToolUseFeedContextReadsOnlyRecentTranscriptTail() throws {
let context = try makeClaudeHookContext(name: "claude-pretool-tail")
defer { context.cleanup() }
let transcriptURL = context.root.appendingPathComponent("large-claude-session.jsonl")
_ = FileManager.default.createFile(atPath: transcriptURL.path, contents: nil)
let handle = try FileHandle(forWritingTo: transcriptURL)
func writeLine(_ line: String) throws {
try handle.write(contentsOf: Data((line + "\n").utf8))
}
try writeLine(#"{"type":"user","message":{"role":"user","content":"ancient user message"}}"#)
try writeLine(#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"ancient assistant response"},{"type":"tool_use","name":"Bash","input":{"command":"echo old"}}]}}"#)
let fillerPayload = String(repeating: "x", count: 1_200)
for _ in 0..<1_200 {
try writeLine(#"{"type":"user","message":{"role":"user","content":"\#(fillerPayload)"}}"#)
}
try writeLine(#"{"type":"user","message":{"role":"user","content":"recent user message"}}"#)
try writeLine(#"{"type":"assistant","message":{"role":"assistant","content":"recent assistant response"}}"#)
try handle.close()
let result = runClaudeHook(
context: context,
arguments: ["hooks", "claude", "pre-tool-use"],
standardInput: #"{"session_id":"tail-session","turn_id":"turn-1","cwd":"\#(context.root.path)","transcript_path":"\#(transcriptURL.path)","hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"echo recent"}}"#
)
XCTAssertFalse(result.timedOut, result.stderr)
XCTAssertEqual(result.status, 0, result.stderr)
let preToolEvent = try XCTUnwrap(
feedPushEvents(in: context).last { $0["hook_event_name"] as? String == "PreToolUse" }
)
let feedContext = try XCTUnwrap(preToolEvent["context"] as? [String: Any])
XCTAssertEqual(feedContext["lastUserMessage"] as? String, "recent user message")
XCTAssertEqual(feedContext["assistantPreamble"] as? String, "recent assistant response")
XCTAssertFalse(String(describing: feedContext).contains("ancient"), "\(feedContext)")
}
func testClaudePreToolUseFeedContextKeepsOversizedFinalTranscriptLine() throws {
let context = try makeClaudeHookContext(name: "claude-pretool-oversized-final")
defer { context.cleanup() }
let transcriptURL = context.root.appendingPathComponent("oversized-final-claude-session.jsonl")
_ = FileManager.default.createFile(atPath: transcriptURL.path, contents: nil)
let handle = try FileHandle(forWritingTo: transcriptURL)
defer { try? handle.close() }
try handle.write(contentsOf: Data(#"{"type":"user","message":{"role":"user","content":"ancient user message"}}"#.utf8))
try handle.write(contentsOf: Data("\n".utf8))
let longAssistantText = "recent assistant response " + String(repeating: "r", count: 1_100_000)
let finalLine = #"{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"\#(longAssistantText)"},{"type":"tool_use","name":"Bash","input":{"command":"echo huge"}}]}}"#
try handle.write(contentsOf: Data(finalLine.utf8))
try handle.close()
let result = runClaudeHook(
context: context,
arguments: ["hooks", "claude", "pre-tool-use"],
standardInput: #"{"session_id":"oversized-final-session","turn_id":"turn-1","cwd":"\#(context.root.path)","transcript_path":"\#(transcriptURL.path)","hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"echo huge"}}"#
)
XCTAssertFalse(result.timedOut, result.stderr)
XCTAssertEqual(result.status, 0, result.stderr)
let preToolEvent = try XCTUnwrap(
feedPushEvents(in: context).last { $0["hook_event_name"] as? String == "PreToolUse" }
)
let feedContext = try XCTUnwrap(preToolEvent["context"] as? [String: Any])
let assistantPreamble = try XCTUnwrap(feedContext["assistantPreamble"] as? String)
XCTAssertTrue(assistantPreamble.hasPrefix("recent assistant response"), "\(feedContext)")
}
func testCodexStopReadsOversizedFinalTranscriptLine() throws {
let context = try makeClaudeHookContext(name: "codex-oversized-final-transcript")
defer { context.cleanup() }
startAgentHookMockServerAccepting(context: context, connectionLimit: 32)
let turnId = "oversized-final-turn"
let transcriptURL = context.root.appendingPathComponent("oversized-final-codex-session.jsonl")
_ = FileManager.default.createFile(atPath: transcriptURL.path, contents: nil)
let handle = try FileHandle(forWritingTo: transcriptURL)
defer { try? handle.close() }
try handle.write(contentsOf: Data(#"{"type":"session_meta","payload":{"id":"codex-oversized-final-session"}}"#.utf8))
try handle.write(contentsOf: Data("\n".utf8))
let padding = String(repeating: "p", count: 600_000)
let finalLine = #"{"type":"event_msg","payload":{"type":"turn_complete","turn_id":"\#(turnId)","padding":"\#(padding)"}}"#
try handle.write(contentsOf: Data(finalLine.utf8))
try handle.close()
let stop = runCodexHook(
context: context,
subcommand: "stop",
standardInput: #"{"session_id":"codex-oversized-final-session","turn_id":"\#(turnId)","cwd":"\#(context.root.path)","transcript_path":"\#(transcriptURL.path)","hook_event_name":"Stop","last_assistant_message":null}"#
)
XCTAssertFalse(stop.timedOut, stop.stderr)
XCTAssertEqual(stop.status, 0, stop.stderr)
XCTAssertTrue(
context.state.commands.contains { command in
command.contains("notify_target_async \(context.workspaceId) \(context.surfaceId) Codex|Error|Codex ended before sending a final response")
},
"Expected Codex to parse the oversized final transcript line, saw \(context.state.commands)"
)
}
func testCodexPromptSubmitRefreshesLastTurnDiffBaseline() throws {
let context = try makeClaudeHookContext(name: "codex-prompt-baseline")
defer { context.cleanup() }
let storyURL = context.root.appendingPathComponent("story.txt")
func runGit(_ arguments: [String]) throws -> String {
let result = runProcess(
executablePath: "/usr/bin/env",
arguments: ["git", "-C", context.root.path] + arguments,
environment: ["PATH": "/usr/bin:/bin:/usr/sbin:/sbin"],
timeout: 10
)
XCTAssertFalse(result.timedOut, result.stderr)
XCTAssertEqual(result.status, 0, result.stderr)
guard result.status == 0 else {
throw NSError(domain: "CLINotifyProcessIntegrationRegressionTests.git", code: Int(result.status))
}
return result.stdout.trimmingCharacters(in: .whitespacesAndNewlines)
}
func baselineRecords() throws -> [[String: Any]] {
let storeURL = context.root.appendingPathComponent("agent-turn-diff-baselines.json")
let store = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(contentsOf: storeURL)) as? [String: Any])
return try XCTUnwrap(store["records"] as? [[String: Any]])
}
_ = try runGit(["init"])
_ = try runGit(["checkout", "-b", "main"])
_ = try runGit(["config", "user.name", "cmux tests"])
_ = try runGit(["config", "user.email", "cmux@example.invalid"])
try "one\n".write(to: storyURL, atomically: true, encoding: .utf8)
_ = try runGit(["add", "story.txt"])
_ = try runGit(["commit", "-m", "initial"])
let initialCommit = try runGit(["rev-parse", "HEAD"])
startAgentHookMockServerAccepting(context: context, connectionLimit: 32)
let sessionId = "codex-last-turn-session"
let sessionStart = runCodexHook(
context: context,
subcommand: "session-start",
standardInput: #"{"session_id":"\#(sessionId)","turn_id":"turn-0","cwd":"\#(context.root.path)","hook_event_name":"SessionStart"}"#,
extraEnvironment: codexLaunchEnvironment(context: context, sessionId: sessionId)
)
XCTAssertFalse(sessionStart.timedOut, sessionStart.stderr)
XCTAssertEqual(sessionStart.status, 0, sessionStart.stderr)
try "one\ntwo\n".write(to: storyURL, atomically: true, encoding: .utf8)
_ = try runGit(["add", "story.txt"])
_ = try runGit(["commit", "-m", "add two"])
let promptCommit = try runGit(["rev-parse", "HEAD"])
let promptSubmit = runCodexHook(
context: context,
subcommand: "prompt-submit",
standardInput: #"{"session_id":"\#(sessionId)","turn_id":"turn-1","cwd":"\#(context.root.path)","hook_event_name":"UserPromptSubmit"}"#,
extraEnvironment: codexLaunchEnvironment(context: context, sessionId: sessionId)
)
XCTAssertFalse(promptSubmit.timedOut, promptSubmit.stderr)
XCTAssertEqual(promptSubmit.status, 0, promptSubmit.stderr)
let records = try baselineRecords()
let startRecord = try XCTUnwrap(records.first { $0["turnId"] as? String == "turn-0" })
let promptRecord = try XCTUnwrap(records.first { $0["turnId"] as? String == "turn-1" })
XCTAssertEqual(startRecord["baseCommit"] as? String, initialCommit)
XCTAssertEqual(promptRecord["baseCommit"] as? String, promptCommit)
XCTAssertEqual(promptRecord["workspaceId"] as? String, context.workspaceId)
XCTAssertEqual(promptRecord["surfaceId"] as? String, context.surfaceId)
try "one\ntwo\nnested\n".write(to: storyURL, atomically: true, encoding: .utf8)
_ = try runGit(["add", "story.txt"])
_ = try runGit(["commit", "-m", "nested child change"])
let childPrompt = runCodexHook(
context: context,
subcommand: "prompt-submit",
standardInput: #"{"session_id":"\#(sessionId)","turn_id":"child-turn","cwd":"\#(context.root.path)","hook_event_name":"UserPromptSubmit"}"#,
extraEnvironment: codexLaunchEnvironment(context: context, sessionId: sessionId)
)
XCTAssertFalse(childPrompt.timedOut, childPrompt.stderr)
XCTAssertEqual(childPrompt.status, 0, childPrompt.stderr)
let childRecords = try baselineRecords()
XCTAssertNil(
childRecords.first { $0["turnId"] as? String == "child-turn" },
"Nested Codex prompts should not create a last-turn diff baseline."
)
let parentRecordAfterChild = try XCTUnwrap(childRecords.first { $0["turnId"] as? String == "turn-1" })
XCTAssertEqual(parentRecordAfterChild["baseCommit"] as? String, promptCommit)
let childStop = runCodexHook(
context: context,
subcommand: "stop",
standardInput: #"{"session_id":"\#(sessionId)","turn_id":"child-turn","cwd":"\#(context.root.path)","hook_event_name":"Stop","last_assistant_message":"child done"}"#,
extraEnvironment: codexLaunchEnvironment(context: context, sessionId: sessionId)
)
XCTAssertFalse(childStop.timedOut, childStop.stderr)
XCTAssertEqual(childStop.status, 0, childStop.stderr)
let parentStop = runCodexHook(
context: context,
subcommand: "stop",
standardInput: #"{"session_id":"\#(sessionId)","turn_id":"turn-1","cwd":"\#(context.root.path)","hook_event_name":"Stop","last_assistant_message":"parent done"}"#,
extraEnvironment: codexLaunchEnvironment(context: context, sessionId: sessionId)
)
XCTAssertFalse(parentStop.timedOut, parentStop.stderr)
XCTAssertEqual(parentStop.status, 0, parentStop.stderr)
try "one\ntwo\nthree\n".write(to: storyURL, atomically: true, encoding: .utf8)
let dirtyPromptSubmit = runCodexHook(
context: context,
subcommand: "prompt-submit",
standardInput: #"{"session_id":"\#(sessionId)","turn_id":"turn-1","cwd":"\#(context.root.path)","hook_event_name":"UserPromptSubmit"}"#,
extraEnvironment: codexLaunchEnvironment(context: context, sessionId: sessionId)
)
XCTAssertFalse(dirtyPromptSubmit.timedOut, dirtyPromptSubmit.stderr)
XCTAssertEqual(dirtyPromptSubmit.status, 0, dirtyPromptSubmit.stderr)
let dirtyRecords = try baselineRecords()
let dirtyRecord = try XCTUnwrap(dirtyRecords.first { $0["turnId"] as? String == "turn-1" })
let dirtyBaseCommit = try XCTUnwrap(dirtyRecord["baseCommit"] as? String)
XCTAssertEqual(
try runGit(["show-ref", "--verify", "--hash", "refs/cmux/last-turn/\(dirtyBaseCommit)"]),
dirtyBaseCommit
)
let dirtyStop = runCodexHook(
context: context,
subcommand: "stop",
standardInput: #"{"session_id":"\#(sessionId)","turn_id":"turn-1","cwd":"\#(context.root.path)","hook_event_name":"Stop","last_assistant_message":"dirty done"}"#,
extraEnvironment: codexLaunchEnvironment(context: context, sessionId: sessionId)
)
XCTAssertFalse(dirtyStop.timedOut, dirtyStop.stderr)
XCTAssertEqual(dirtyStop.status, 0, dirtyStop.stderr)
try "one\ntwo\nthree\nfour\n".write(to: storyURL, atomically: true, encoding: .utf8)
let refreshedDirtyPromptSubmit = runCodexHook(
context: context,
subcommand: "prompt-submit",
standardInput: #"{"session_id":"\#(sessionId)","turn_id":"turn-1","cwd":"\#(context.root.path)","hook_event_name":"UserPromptSubmit"}"#,
extraEnvironment: codexLaunchEnvironment(context: context, sessionId: sessionId)
)
XCTAssertFalse(refreshedDirtyPromptSubmit.timedOut, refreshedDirtyPromptSubmit.stderr)
XCTAssertEqual(refreshedDirtyPromptSubmit.status, 0, refreshedDirtyPromptSubmit.stderr)
let refreshedRecords = try baselineRecords()
let refreshedRecord = try XCTUnwrap(refreshedRecords.first { $0["turnId"] as? String == "turn-1" })
let refreshedBaseCommit = try XCTUnwrap(refreshedRecord["baseCommit"] as? String)
XCTAssertNotEqual(refreshedBaseCommit, dirtyBaseCommit)
let oldRef = runProcess(
executablePath: "/usr/bin/env",
arguments: ["git", "-C", context.root.path, "show-ref", "--verify", "--hash", "refs/cmux/last-turn/\(dirtyBaseCommit)"],
environment: ["PATH": "/usr/bin:/bin:/usr/sbin:/sbin"],
timeout: 10
)
XCTAssertFalse(oldRef.timedOut, oldRef.stderr)
XCTAssertNotEqual(oldRef.status, 0, oldRef.stdout)
XCTAssertEqual(
try runGit(["show-ref", "--verify", "--hash", "refs/cmux/last-turn/\(refreshedBaseCommit)"]),
refreshedBaseCommit
)
}
func testClaudeStopFromPreviousSessionDoesNotClobberClearRunningStatus() throws {
let context = try makeClaudeHookContext(name: "claude-clear-stale-stop")
defer { context.cleanup() }
let oldStart = runClaudeHook(
context: context,
arguments: ["hooks", "claude", "session-start"],
standardInput: #"{"session_id":"old-session","cwd":"\#(context.root.path)","hook_event_name":"SessionStart"}"#
)
XCTAssertFalse(oldStart.timedOut, oldStart.stderr)
XCTAssertEqual(oldStart.status, 0, oldStart.stderr)
let clearStart = runClaudeHook(
context: context,
arguments: ["hooks", "claude", "session-start"],
standardInput: #"{"session_id":"clear-session","source":"clear","cwd":"\#(context.root.path)","hook_event_name":"SessionStart"}"#
)
XCTAssertFalse(clearStart.timedOut, clearStart.stderr)
XCTAssertEqual(clearStart.status, 0, clearStart.stderr)
let lateOldStart = runClaudeHook(
context: context,
arguments: ["hooks", "claude", "session-start"],
standardInput: #"{"session_id":"old-session","source":"startup","cwd":"\#(context.root.path)","hook_event_name":"SessionStart"}"#
)
XCTAssertFalse(lateOldStart.timedOut, lateOldStart.stderr)
XCTAssertEqual(lateOldStart.status, 0, lateOldStart.stderr)
let staleStop = runClaudeHook(
context: context,
arguments: ["hooks", "claude", "stop"],
standardInput: #"{"session_id":"old-session","cwd":"\#(context.root.path)","hook_event_name":"Stop","last_assistant_message":"old turn finished late"}"#
)
XCTAssertFalse(staleStop.timedOut, staleStop.stderr)
XCTAssertEqual(staleStop.status, 0, staleStop.stderr)
XCTAssertTrue(
context.state.commands.contains {
$0.hasPrefix("set_status claude_code Running --icon=bolt.fill --color=#4C8DFF --tab=\(context.workspaceId)")
&& $0.contains("--panel=\(context.surfaceId)")
},
"Expected clear SessionStart to mark Claude running, saw \(context.state.commands)"
)
XCTAssertFalse(
context.state.commands.contains {
$0.hasPrefix("set_status claude_code Idle ") && $0.contains("--tab=\(context.workspaceId)")
},
"Expected stale Stop from old session not to clobber the clear session, saw \(context.state.commands)"
)
let resumeBindingRequests = context.state.commands.compactMap { command -> [String: Any]? in
guard let payload = jsonObject(command),
payload["method"] as? String == "surface.resume.set" else {
return nil
}
return payload["params"] as? [String: Any]
}
XCTAssertEqual(resumeBindingRequests.count, 1, context.state.commands.joined(separator: "\n"))
XCTAssertEqual(resumeBindingRequests.first?["checkpoint_id"] as? String, "clear-session")
XCTAssertEqual(resumeBindingRequests.first?["auto_resume"] as? Bool, true)
}
func testClaudePromptSubmitFromNewSessionCanReplaceStoppedSession() throws {
let context = try makeClaudeHookContext(name: "claude-new-session-after-stop")
defer { context.cleanup() }
let oldStart = runClaudeHook(
context: context,
arguments: ["hooks", "claude", "session-start"],
standardInput: #"{"session_id":"old-session","cwd":"\#(context.root.path)","hook_event_name":"SessionStart"}"#
)
XCTAssertFalse(oldStart.timedOut, oldStart.stderr)
XCTAssertEqual(oldStart.status, 0, oldStart.stderr)
let oldPrompt = runClaudeHook(
context: context,
arguments: ["hooks", "claude", "prompt-submit"],
standardInput: #"{"session_id":"old-session","turn_id":"turn-1","cwd":"\#(context.root.path)","hook_event_name":"PromptSubmit"}"#
)
XCTAssertFalse(oldPrompt.timedOut, oldPrompt.stderr)
XCTAssertEqual(oldPrompt.status, 0, oldPrompt.stderr)
let oldStop = runClaudeHook(
context: context,
arguments: ["hooks", "claude", "stop"],
standardInput: #"{"session_id":"old-session","turn_id":"turn-1","cwd":"\#(context.root.path)","hook_event_name":"Stop","last_assistant_message":"old turn finished"}"#
)
XCTAssertFalse(oldStop.timedOut, oldStop.stderr)
XCTAssertEqual(oldStop.status, 0, oldStop.stderr)
let newStart = runClaudeHook(
context: context,
arguments: ["hooks", "claude", "session-start"],
standardInput: #"{"session_id":"new-session","source":"startup","cwd":"\#(context.root.path)","hook_event_name":"SessionStart"}"#
)
XCTAssertFalse(newStart.timedOut, newStart.stderr)
XCTAssertEqual(newStart.status, 0, newStart.stderr)
let newPromptStart = context.state.commands.count
let newPrompt = runClaudeHook(
context: context,
arguments: ["hooks", "claude", "prompt-submit"],
standardInput: #"{"session_id":"new-session","turn_id":"turn-1","cwd":"\#(context.root.path)","hook_event_name":"PromptSubmit"}"#
)
XCTAssertFalse(newPrompt.timedOut, newPrompt.stderr)
XCTAssertEqual(newPrompt.status, 0, newPrompt.stderr)
let newPromptCommands = Array(context.state.commands.dropFirst(newPromptStart))
XCTAssertTrue(
newPromptCommands.contains {
$0.hasPrefix("set_status claude_code Running --icon=bolt.fill --color=#4C8DFF --tab=\(context.workspaceId)")
},
"Expected a new Claude session to replace a stopped idle owner on prompt-submit, saw \(newPromptCommands)"
)
}
// MARK: - Forked conversation restore (https://github.com/manaflow-ai/cmux/issues/5908)
//
// `claude --resume <parent> --fork-session` fires SessionStart with the PARENT
// session id; the forked session id is only minted at the first UserPromptSubmit.
// Without special handling the fork pane's SessionStart steals the parent record's
// surface binding, and the forked session's own hooks are dropped as stale by the
// per-workspace active-session gate, so a restart restores the parent conversation
// in the fork pane and the forked conversation is lost.
private func claudeForkLaunchEnvironment(
context: ClaudeHookContext,
parentSessionId: String
) -> [String: String] {
agentLaunchEnvironment(
context: context,
kind: "claude",
executable: "/usr/local/bin/claude",
arguments: ["/usr/local/bin/claude", "--resume", parentSessionId, "--fork-session"]
)
}
private func seedClaudeForkHookStore(
context: ClaudeHookContext,
parentSessionId: String,
parentSurfaceId: String,
forkedSessionId: String? = nil,
forkedSurfaceId: String? = nil,
activeSessionId: String,
activeTurnId: String?
) throws {
let now = Date().timeIntervalSince1970
var sessions: [String: Any] = [
parentSessionId: [
"sessionId": parentSessionId,
"workspaceId": context.workspaceId,
"surfaceId": parentSurfaceId,
"cwd": context.root.path,
"agentLifecycle": "running",
"startedAt": now,
"updatedAt": now,
],
]
if let forkedSessionId, let forkedSurfaceId {
sessions[forkedSessionId] = [
"sessionId": forkedSessionId,
"workspaceId": context.workspaceId,
"surfaceId": forkedSurfaceId,
"cwd": context.root.path,
"agentLifecycle": "running",
"startedAt": now,
"updatedAt": now,
]
}
var active: [String: Any] = [
"sessionId": activeSessionId,
"updatedAt": now,
]
if let activeTurnId {
active["turnId"] = activeTurnId
}
let store: [String: Any] = [
"version": 1,
"sessions": sessions,
"activeSessionsByWorkspace": [context.workspaceId: active],
]
try JSONSerialization.data(withJSONObject: store, options: [.prettyPrinted])
.write(
to: context.root.appendingPathComponent("claude-hook-sessions.json"),
options: .atomic
)
}
/// Multi-connection mock server for tests that invoke several hooks in one
/// scenario; pair with `runClaudeHookWithoutServer`. The per-call
/// `runClaudeHookListingSurfaces` server accepts a single connection, which
/// deadlocks sequences once any CLI invocation opens more than one.
private func startClaudeHookMockServerAccepting(
context: ClaudeHookContext,
surfaceIds: [String],
connectionLimit: Int
) {
DispatchQueue.global(qos: .userInitiated).async {
var accepted = 0
while accepted < connectionLimit {
var clientAddr = sockaddr_un()
var clientAddrLen = socklen_t(MemoryLayout<sockaddr_un>.size)
let clientFD = withUnsafeMutablePointer(to: &clientAddr) { ptr in
ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockaddrPtr in
Darwin.accept(context.listenerFD, sockaddrPtr, &clientAddrLen)
}
}
if clientFD < 0 {
if errno == EINTR { continue }
return
}
accepted += 1
DispatchQueue.global(qos: .userInitiated).async {
defer { Darwin.close(clientFD) }
var pending = Data()
var buffer = [UInt8](repeating: 0, count: 4096)
while true {
let count = Darwin.read(clientFD, &buffer, buffer.count)
if count < 0 {
if errno == EINTR { continue }
return
}
if count == 0 { return }
pending.append(buffer, count: count)
while let newlineRange = pending.firstRange(of: Data([0x0A])) {
let lineData = pending.subdata(in: 0..<newlineRange.lowerBound)
pending.removeSubrange(0...newlineRange.lowerBound)
guard let line = String(data: lineData, encoding: .utf8) else { continue }
context.state.append(line)
let response = self.claudeHookMockResponse(line: line, surfaceIds: surfaceIds) + "\n"
_ = response.withCString { ptr in
Darwin.write(clientFD, ptr, strlen(ptr))
}
}
}
}
}
}
}
private func claudeHookMockResponse(line: String, surfaceIds: [String]) -> String {
guard let payload = jsonObject(line) else {
return "OK"
}
guard let id = payload["id"] as? String, let method = payload["method"] as? String else {
return malformedRequestResponse(id: payload["id"] as? String, raw: line)
}
switch method {
case "surface.list":
return v2Response(
id: id,
ok: true,
result: [
"surfaces": surfaceIds.enumerated().map { index, surfaceId in
["id": surfaceId, "ref": "surface:\(index + 1)", "focused": index == 0] as [String: Any]
}
]
)
case "feed.push":
return v2Response(id: id, ok: true, result: [:])
case "surface.resume.set":
return v2Response(id: id, ok: true, result: ["resume_binding": [:]])
case "surface.resume.clear":
return v2Response(id: id, ok: true, result: ["cleared": true])
default:
return v2Response(id: id, ok: false, error: ["code": "unrecognized_method", "message": "unexpected method: \(method)"])
}
}
private func runClaudeHookWithoutServer(
context: ClaudeHookContext,
arguments: [String],
standardInput: String,
extraEnvironment: [String: String] = [:]
) -> ProcessRunResult {
var environment = [
"HOME": context.root.path,
"PATH": "/usr/bin:/bin:/usr/sbin:/sbin",
"CMUX_SOCKET_PATH": context.socketPath,
"CMUX_WORKSPACE_ID": context.workspaceId,
"CMUX_SURFACE_ID": context.surfaceId,
"CMUX_CLAUDE_HOOK_STATE_PATH": context.root.appendingPathComponent("claude-hook-sessions.json").path,
"CMUX_CLI_SENTRY_DISABLED": "1",
"CMUX_CLAUDE_HOOK_SENTRY_DISABLED": "1",
]
for (key, value) in extraEnvironment {
environment[key] = value
}
return runProcess(
executablePath: context.cliPath,
arguments: arguments,
environment: environment,
standardInput: standardInput,
timeout: 5
)
}
private func runClaudeHookListingSurfaces(
context: ClaudeHookContext,
surfaceIds: [String],
arguments: [String],
standardInput: String,
extraEnvironment: [String: String] = [:]
) -> ProcessRunResult {
let serverHandled = startMockServer(listenerFD: context.listenerFD, state: context.state) { line in
guard let payload = self.jsonObject(line) else {
return "OK"
}
guard let id = payload["id"] as? String, let method = payload["method"] as? String else {
return self.malformedRequestResponse(id: payload["id"] as? String, raw: line)
}
switch method {
case "surface.list":
return self.v2Response(
id: id,
ok: true,
result: [
"surfaces": surfaceIds.enumerated().map { index, surfaceId in
["id": surfaceId, "ref": "surface:\(index + 1)", "focused": index == 0] as [String: Any]
}
]
)
case "feed.push":
return self.v2Response(id: id, ok: true, result: [:])
case "surface.resume.set":
return self.v2Response(id: id, ok: true, result: ["resume_binding": [:]])
case "surface.resume.clear":
return self.v2Response(id: id, ok: true, result: ["cleared": true])
default:
return self.v2Response(id: id, ok: false, error: ["code": "unrecognized_method", "message": "unexpected method: \(method)"])
}
}
var environment = [
"HOME": context.root.path,
"PATH": "/usr/bin:/bin:/usr/sbin:/sbin",
"CMUX_SOCKET_PATH": context.socketPath,
"CMUX_WORKSPACE_ID": context.workspaceId,
"CMUX_SURFACE_ID": context.surfaceId,
"CMUX_CLAUDE_HOOK_STATE_PATH": context.root.appendingPathComponent("claude-hook-sessions.json").path,
"CMUX_CLI_SENTRY_DISABLED": "1",
"CMUX_CLAUDE_HOOK_SENTRY_DISABLED": "1",
]
for (key, value) in extraEnvironment {
environment[key] = value
}
let result = runProcess(
executablePath: context.cliPath,
arguments: arguments,
environment: environment,
standardInput: standardInput,
timeout: 5
)
wait(for: [serverHandled], timeout: 5)
return result
}
func testClaudeForkSessionStartKeepsParentSessionBoundToOriginalSurface() throws {
let context = try makeClaudeHookContext(name: "claude-fork-session-start")
defer { context.cleanup() }
let parentSessionId = "parent-session"
let parentSurfaceId = "99999999-9999-9999-9999-999999999999"
try seedClaudeForkHookStore(
context: context,
parentSessionId: parentSessionId,
parentSurfaceId: parentSurfaceId,
activeSessionId: parentSessionId,
activeTurnId: "parent-turn-1"
)
let result = runClaudeHookListingSurfaces(
context: context,
surfaceIds: [parentSurfaceId, context.surfaceId],
arguments: ["hooks", "claude", "session-start"],
standardInput: #"{"session_id":"\#(parentSessionId)","source":"resume","cwd":"\#(context.root.path)","hook_event_name":"SessionStart"}"#,
extraEnvironment: claudeForkLaunchEnvironment(context: context, parentSessionId: parentSessionId)
)
XCTAssertFalse(result.timedOut, result.stderr)
XCTAssertEqual(result.status, 0, result.stderr)
let parentRecord = try readClaudeHookSession(parentSessionId, context: context)
XCTAssertEqual(
parentRecord["surfaceId"] as? String,
parentSurfaceId,
"Fork-session SessionStart reports the parent session id and must not steal the parent record's surface binding for the fork pane"
)
}
func testClaudeForkSessionStartWithoutSurfaceIdentityDoesNotRegisterPIDOnFallbackPane() throws {
let context = try makeClaudeHookContext(name: "claude-fork-no-surface")
defer { context.cleanup() }
let parentSessionId = "parent-session"
let parentSurfaceId = "99999999-9999-9999-9999-999999999999"
try seedClaudeForkHookStore(
context: context,
parentSessionId: parentSessionId,
parentSurfaceId: parentSurfaceId,
activeSessionId: parentSessionId,
activeTurnId: nil
)
// No surface identity: resolution falls back to the focused surface,
// which is some other pane. The fork's PID must not be registered
// there — the matching SessionEnd cleanup only clears authoritative
// surfaces, so a fallback registration would never be cleared.
var environment = claudeForkLaunchEnvironment(context: context, parentSessionId: parentSessionId)
environment["CMUX_SURFACE_ID"] = ""
environment["CMUX_CLAUDE_PID"] = "12345"
let result = runClaudeHookListingSurfaces(
context: context,
surfaceIds: [parentSurfaceId, context.surfaceId],
arguments: ["hooks", "claude", "session-start"],
standardInput: #"{"session_id":"\#(parentSessionId)","source":"resume","cwd":"\#(context.root.path)","hook_event_name":"SessionStart"}"#,
extraEnvironment: environment
)
XCTAssertFalse(result.timedOut, result.stderr)
XCTAssertEqual(result.status, 0, result.stderr)
XCTAssertFalse(
context.state.commands.contains { $0.hasPrefix("set_agent_pid claude_code ") },
"A fork SessionStart without an authoritative surface must not register its PID on a borrowed fallback pane, saw \(context.state.commands)"
)
}
func testClaudeForkSessionStartRecognizesEqualsFlagForm() throws {
let context = try makeClaudeHookContext(name: "claude-fork-equals-form")
defer { context.cleanup() }
let parentSessionId = "parent-session"
let parentSurfaceId = "99999999-9999-9999-9999-999999999999"
try seedClaudeForkHookStore(
context: context,
parentSessionId: parentSessionId,
parentSurfaceId: parentSurfaceId,
activeSessionId: parentSessionId,
activeTurnId: "parent-turn-1"
)
let result = runClaudeHookListingSurfaces(
context: context,
surfaceIds: [parentSurfaceId, context.surfaceId],
arguments: ["hooks", "claude", "session-start"],
standardInput: #"{"session_id":"\#(parentSessionId)","source":"resume","cwd":"\#(context.root.path)","hook_event_name":"SessionStart"}"#,
extraEnvironment: agentLaunchEnvironment(
context: context,
kind: "claude",
executable: "/usr/local/bin/claude",
arguments: ["/usr/local/bin/claude", "--resume", parentSessionId, "--fork-session=true"]
)
)
XCTAssertFalse(result.timedOut, result.stderr)
XCTAssertEqual(result.status, 0, result.stderr)
let parentRecord = try readClaudeHookSession(parentSessionId, context: context)
XCTAssertEqual(
parentRecord["surfaceId"] as? String,
parentSurfaceId,
"Fork detection must recognize the --fork-session=true flag form the launch sanitizer already accepts"
)
}
func testClaudeLegacyStoreBackfillsPaneBoundaryFromWorkspaceActiveSlot() throws {
let context = try makeClaudeHookContext(name: "claude-legacy-backfill")
defer { context.cleanup() }
let paneA = "99999999-9999-9999-9999-999999999999"
let paneB = context.surfaceId
let now = Date().timeIntervalSince1970
// A store written before per-surface tracking: pane A's current
// session-2 holds the workspace slot; stale session-1 also lives in
// pane A; no activeSessionsBySurface key at all.
let store: [String: Any] = [
"version": 1,
"sessions": [
"session-1": [
"sessionId": "session-1",
"workspaceId": context.workspaceId,
"surfaceId": paneA,
"cwd": context.root.path,
"agentLifecycle": "running",
"startedAt": now,
"updatedAt": now,
],
"session-2": [
"sessionId": "session-2",
"workspaceId": context.workspaceId,
"surfaceId": paneA,
"cwd": context.root.path,
"agentLifecycle": "running",
"startedAt": now,
"updatedAt": now,
],
],
"activeSessionsByWorkspace": [
context.workspaceId: [
"sessionId": "session-2",
"updatedAt": now,
],
],
]
try JSONSerialization.data(withJSONObject: store, options: [.prettyPrinted])
.write(
to: context.root.appendingPathComponent("claude-hook-sessions.json"),
options: .atomic
)
startClaudeHookMockServerAccepting(
context: context,
surfaceIds: [paneA, paneB],
connectionLimit: 32
)
// Pane B takes the workspace-active slot under the new code…
let paneBPrompt = runClaudeHookWithoutServer(
context: context,
arguments: ["hooks", "claude", "prompt-submit"],
standardInput: #"{"session_id":"session-3","turn_id":"turn-3","cwd":"\#(context.root.path)","hook_event_name":"UserPromptSubmit","prompt":"three"}"#,
extraEnvironment: ["CMUX_SURFACE_ID": paneB]
)
XCTAssertFalse(paneBPrompt.timedOut, paneBPrompt.stderr)
XCTAssertEqual(paneBPrompt.status, 0, paneBPrompt.stderr)
// …then a late Stop from stale session-1 in pane A must stay stale:
// the pane boundary (session-2 owns pane A) has to survive the upgrade
// via backfill from the legacy workspace slot.
let lateStop = runClaudeHookWithoutServer(
context: context,
arguments: ["hooks", "claude", "stop"],
standardInput: #"{"session_id":"session-1","cwd":"\#(context.root.path)","hook_event_name":"Stop","last_assistant_message":"late"}"#,
extraEnvironment: ["CMUX_SURFACE_ID": paneA]
)
XCTAssertFalse(lateStop.timedOut, lateStop.stderr)
XCTAssertEqual(lateStop.status, 0, lateStop.stderr)
let staleRecord = try readClaudeHookSession("session-1", context: context)
XCTAssertEqual(
staleRecord["agentLifecycle"] as? String,
"running",
"A legacy store must backfill the pane boundary so pre-upgrade stale sessions stay stale after another pane promotes"
)
}
func testClaudeForkedSessionPromptSubmitRecordsWhileParentTurnActive() throws {
let context = try makeClaudeHookContext(name: "claude-fork-prompt-submit")
defer { context.cleanup() }
let parentSessionId = "parent-session"
let parentSurfaceId = "99999999-9999-9999-9999-999999999999"
let forkedSessionId = "forked-session"
try seedClaudeForkHookStore(
context: context,
parentSessionId: parentSessionId,
parentSurfaceId: parentSurfaceId,
activeSessionId: parentSessionId,
activeTurnId: "parent-turn-1"
)
let commandStart = context.state.commands.count
let result = runClaudeHookListingSurfaces(
context: context,
surfaceIds: [parentSurfaceId, context.surfaceId],
arguments: ["hooks", "claude", "prompt-submit"],
standardInput: #"{"session_id":"\#(forkedSessionId)","turn_id":"fork-turn-1","cwd":"\#(context.root.path)","hook_event_name":"UserPromptSubmit","prompt":"diverge here"}"#,
extraEnvironment: claudeForkLaunchEnvironment(context: context, parentSessionId: parentSessionId)
)
XCTAssertFalse(result.timedOut, result.stderr)
XCTAssertEqual(result.status, 0, result.stderr)
let forkedRecord = try readClaudeHookSession(forkedSessionId, context: context)
XCTAssertEqual(
forkedRecord["surfaceId"] as? String,
context.surfaceId,
"The forked session's first prompt-submit must bind the forked session to the fork pane even while the parent session owns the workspace's active turn"
)
XCTAssertEqual(
forkedRecord["isRestorable"] as? Bool,
true,
"The forked session must become restorable so a cmux restart resumes the fork, not the parent"
)
let promptCommands = Array(context.state.commands.dropFirst(commandStart))
let resumeBindingRequests = promptCommands.compactMap { command -> [String: Any]? in
guard let payload = jsonObject(command),
payload["method"] as? String == "surface.resume.set" else {
return nil
}
return payload["params"] as? [String: Any]
}
XCTAssertEqual(resumeBindingRequests.count, 1, promptCommands.joined(separator: "\n"))
let request = try XCTUnwrap(resumeBindingRequests.first)
XCTAssertEqual(request["checkpoint_id"] as? String, forkedSessionId)
XCTAssertEqual(request["surface_id"] as? String, context.surfaceId)
}
func testClaudeForkSessionEndBeforeFirstPromptDoesNotConsumeParentSession() throws {
let context = try makeClaudeHookContext(name: "claude-fork-session-end")
defer { context.cleanup() }
let parentSessionId = "parent-session"
let parentSurfaceId = "99999999-9999-9999-9999-999999999999"
try seedClaudeForkHookStore(
context: context,
parentSessionId: parentSessionId,
parentSurfaceId: parentSurfaceId,
activeSessionId: parentSessionId,
activeTurnId: nil
)
// Exiting a fork pane before its first prompt fires SessionEnd with the
// PARENT session id (the forked id is only minted at the first prompt).
let result = runClaudeHookListingSurfaces(
context: context,
surfaceIds: [parentSurfaceId, context.surfaceId],
arguments: ["hooks", "claude", "session-end"],
standardInput: #"{"session_id":"\#(parentSessionId)","cwd":"\#(context.root.path)","hook_event_name":"SessionEnd"}"#,
extraEnvironment: claudeForkLaunchEnvironment(context: context, parentSessionId: parentSessionId)
)
XCTAssertFalse(result.timedOut, result.stderr)
XCTAssertEqual(result.status, 0, result.stderr)
let parentRecord = try readClaudeHookSession(parentSessionId, context: context)
XCTAssertEqual(
parentRecord["surfaceId"] as? String,
parentSurfaceId,
"A pre-prompt fork exit must not consume the parent session record the original pane still owns"
)
let resumeClearRequests = context.state.commands.compactMap { command -> [String: Any]? in
guard let payload = jsonObject(command),
payload["method"] as? String == "surface.resume.clear" else {
return nil
}
return payload["params"] as? [String: Any]
}
XCTAssertTrue(
resumeClearRequests.isEmpty,
"A pre-prompt fork exit must not clear the parent pane's resume binding, saw \(resumeClearRequests)"
)
XCTAssertTrue(
context.state.commands.contains {
$0.hasPrefix("clear_agent_pid claude_code ") && $0.contains("--panel=\(context.surfaceId)")
},
"A pre-prompt fork exit must still clear the agent PID/status registered for the fork pane, saw \(context.state.commands)"
)
}
func testClaudeForkedSessionPromptSubmitRecordsWithSurfaceRefForm() throws {
let context = try makeClaudeHookContext(name: "claude-fork-surface-ref")
defer { context.cleanup() }
let parentSessionId = "parent-session"
let parentSurfaceId = "99999999-9999-9999-9999-999999999999"
let forkedSessionId = "forked-session"
try seedClaudeForkHookStore(
context: context,
parentSessionId: parentSessionId,
parentSurfaceId: parentSurfaceId,
activeSessionId: parentSessionId,