-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathpermissions_e2e_test.go
More file actions
837 lines (730 loc) · 26.1 KB
/
Copy pathpermissions_e2e_test.go
File metadata and controls
837 lines (730 loc) · 26.1 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
package e2e
import (
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
copilot "github.com/github/copilot-sdk/go"
"github.com/github/copilot-sdk/go/internal/e2e/testharness"
"github.com/github/copilot-sdk/go/rpc"
)
func TestPermissionsE2E(t *testing.T) {
ctx := testharness.NewTestContext(t)
client := ctx.NewClient()
t.Cleanup(func() { client.ForceStop() })
t.Run("permission handler for write operations", func(t *testing.T) {
ctx.ConfigureForTest(t)
var permissionRequests []copilot.PermissionRequest
var mu sync.Mutex
onPermissionRequest := func(request copilot.PermissionRequest, invocation copilot.PermissionInvocation) (copilot.PermissionRequestResult, error) {
mu.Lock()
permissionRequests = append(permissionRequests, request)
mu.Unlock()
if invocation.SessionID == "" {
t.Error("Expected non-empty session ID in invocation")
}
return copilot.PermissionRequestResult{Kind: copilot.PermissionRequestResultKindApproved}, nil
}
session, err := client.CreateSession(t.Context(), &copilot.SessionConfig{
OnPermissionRequest: onPermissionRequest,
})
if err != nil {
t.Fatalf("Failed to create session: %v", err)
}
testFile := filepath.Join(ctx.WorkDir, "test.txt")
err = os.WriteFile(testFile, []byte("original content"), 0644)
if err != nil {
t.Fatalf("Failed to write test file: %v", err)
}
_, err = session.SendAndWait(t.Context(), copilot.MessageOptions{
Prompt: "Edit test.txt and replace 'original' with 'modified'",
})
if err != nil {
t.Fatalf("Failed to send message: %v", err)
}
mu.Lock()
if len(permissionRequests) == 0 {
t.Error("Expected at least one permission request")
}
writeCount := 0
for _, req := range permissionRequests {
if _, ok := req.(*copilot.PermissionRequestWrite); ok {
writeCount++
}
}
mu.Unlock()
if writeCount == 0 {
t.Error("Expected at least one write permission request")
}
})
t.Run("permission handler for shell commands", func(t *testing.T) {
ctx.ConfigureForTest(t)
var permissionRequests []copilot.PermissionRequest
var mu sync.Mutex
onPermissionRequest := func(request copilot.PermissionRequest, invocation copilot.PermissionInvocation) (copilot.PermissionRequestResult, error) {
mu.Lock()
permissionRequests = append(permissionRequests, request)
mu.Unlock()
return copilot.PermissionRequestResult{Kind: copilot.PermissionRequestResultKindApproved}, nil
}
session, err := client.CreateSession(t.Context(), &copilot.SessionConfig{
OnPermissionRequest: onPermissionRequest,
})
if err != nil {
t.Fatalf("Failed to create session: %v", err)
}
_, err = session.SendAndWait(t.Context(), copilot.MessageOptions{
Prompt: "Run 'echo hello' and tell me the output",
})
if err != nil {
t.Fatalf("Failed to send message: %v", err)
}
mu.Lock()
shellCount := 0
for _, req := range permissionRequests {
if _, ok := req.(*copilot.PermissionRequestShell); ok {
shellCount++
}
}
mu.Unlock()
if shellCount == 0 {
t.Error("Expected at least one shell permission request")
}
})
t.Run("deny permission", func(t *testing.T) {
ctx.ConfigureForTest(t)
onPermissionRequest := func(request copilot.PermissionRequest, invocation copilot.PermissionInvocation) (copilot.PermissionRequestResult, error) {
return copilot.PermissionRequestResult{Kind: copilot.PermissionRequestResultKindRejected}, nil
}
session, err := client.CreateSession(t.Context(), &copilot.SessionConfig{
OnPermissionRequest: onPermissionRequest,
})
if err != nil {
t.Fatalf("Failed to create session: %v", err)
}
// Regression check for https://github.com/github/copilot-sdk/issues/1194:
// the reject decision must round-trip through the CLI with its discriminator
// intact so the agent surfaces the user-rejected error to the model. The
// CLI emits a kind-specific error message ("The user rejected this tool call.")
// for the reject decision, which lets us assert the decision was honored
// — not merely that the operation didn't happen.
var mu sync.Mutex
userRejectedToolCall := false
session.On(func(event copilot.SessionEvent) {
if d, ok := event.Data.(*copilot.ToolExecutionCompleteData); ok &&
!d.Success &&
d.Error != nil &&
strings.Contains(strings.ToLower(d.Error.Message), "user rejected") {
mu.Lock()
userRejectedToolCall = true
mu.Unlock()
}
})
testFile := filepath.Join(ctx.WorkDir, "protected.txt")
originalContent := []byte("protected content")
err = os.WriteFile(testFile, originalContent, 0644)
if err != nil {
t.Fatalf("Failed to write test file: %v", err)
}
_, err = session.Send(t.Context(), copilot.MessageOptions{
Prompt: "Edit protected.txt and replace 'protected' with 'hacked'.",
})
if err != nil {
t.Fatalf("Failed to send message: %v", err)
}
_, err = testharness.GetFinalAssistantMessage(t.Context(), session)
if err != nil {
t.Fatalf("Failed to get final message: %v", err)
}
mu.Lock()
if !userRejectedToolCall {
t.Error("Expected a tool.execution_complete event whose error indicates the user rejected the call.")
}
mu.Unlock()
// Verify the file was NOT modified
content, err := os.ReadFile(testFile)
if err != nil {
t.Fatalf("Failed to read test file: %v", err)
}
if string(content) != string(originalContent) {
t.Errorf("Expected file to remain unchanged after denied permission, got: %s", string(content))
}
})
t.Run("should deny tool operations when handler explicitly denies", func(t *testing.T) {
ctx.ConfigureForTest(t)
session, err := client.CreateSession(t.Context(), &copilot.SessionConfig{
OnPermissionRequest: func(request copilot.PermissionRequest, invocation copilot.PermissionInvocation) (copilot.PermissionRequestResult, error) {
return copilot.PermissionRequestResult{Kind: copilot.PermissionRequestResultKindUserNotAvailable}, nil
},
})
if err != nil {
t.Fatalf("Failed to create session: %v", err)
}
var mu sync.Mutex
permissionDenied := false
session.On(func(event copilot.SessionEvent) {
if d, ok := event.Data.(*copilot.ToolExecutionCompleteData); ok &&
!d.Success &&
d.Error != nil &&
strings.Contains(d.Error.Message, "Permission denied") {
mu.Lock()
permissionDenied = true
mu.Unlock()
}
})
if _, err = session.SendAndWait(t.Context(), copilot.MessageOptions{
Prompt: "Run 'node --version'",
}); err != nil {
t.Fatalf("Failed to send message: %v", err)
}
mu.Lock()
defer mu.Unlock()
if !permissionDenied {
t.Error("Expected a tool.execution_complete event with Permission denied result")
}
})
t.Run("should deny tool operations when handler explicitly denies after resume", func(t *testing.T) {
ctx.ConfigureForTest(t)
session1, err := client.CreateSession(t.Context(), &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
})
if err != nil {
t.Fatalf("Failed to create session: %v", err)
}
sessionID := session1.SessionID
if _, err = session1.SendAndWait(t.Context(), copilot.MessageOptions{Prompt: "What is 1+1?"}); err != nil {
t.Fatalf("Failed to send message: %v", err)
}
session2, err := client.ResumeSession(t.Context(), sessionID, &copilot.ResumeSessionConfig{
OnPermissionRequest: func(request copilot.PermissionRequest, invocation copilot.PermissionInvocation) (copilot.PermissionRequestResult, error) {
return copilot.PermissionRequestResult{Kind: copilot.PermissionRequestResultKindUserNotAvailable}, nil
},
})
if err != nil {
t.Fatalf("Failed to resume session: %v", err)
}
var mu sync.Mutex
permissionDenied := false
session2.On(func(event copilot.SessionEvent) {
if d, ok := event.Data.(*copilot.ToolExecutionCompleteData); ok &&
!d.Success &&
d.Error != nil &&
strings.Contains(d.Error.Message, "Permission denied") {
mu.Lock()
permissionDenied = true
mu.Unlock()
}
})
if _, err = session2.SendAndWait(t.Context(), copilot.MessageOptions{
Prompt: "Run 'node --version'",
}); err != nil {
t.Fatalf("Failed to send message: %v", err)
}
mu.Lock()
defer mu.Unlock()
if !permissionDenied {
t.Error("Expected a tool.execution_complete event with Permission denied result")
}
})
t.Run("should work with approve-all permission handler", func(t *testing.T) {
ctx.ConfigureForTest(t)
session, err := client.CreateSession(t.Context(), &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
})
if err != nil {
t.Fatalf("Failed to create session: %v", err)
}
_, err = session.Send(t.Context(), copilot.MessageOptions{Prompt: "What is 2+2?"})
if err != nil {
t.Fatalf("Failed to send message: %v", err)
}
message, err := testharness.GetFinalAssistantMessage(t.Context(), session)
if err != nil {
t.Fatalf("Failed to get final message: %v", err)
}
if md, ok := message.Data.(*copilot.AssistantMessageData); !ok || !strings.Contains(md.Content, "4") {
var content string
if ok {
content = md.Content
}
t.Errorf("Expected message to contain '4', got: %v", content)
}
})
t.Run("should handle async permission handler", func(t *testing.T) {
ctx.ConfigureForTest(t)
var permissionRequestReceived atomicBool
session, err := client.CreateSession(t.Context(), &copilot.SessionConfig{
OnPermissionRequest: func(req copilot.PermissionRequest, inv copilot.PermissionInvocation) (copilot.PermissionRequestResult, error) {
permissionRequestReceived.Set(true)
return copilot.PermissionRequestResult{Kind: copilot.PermissionRequestResultKindApproved}, nil
},
})
if err != nil {
t.Fatalf("CreateSession failed: %v", err)
}
_, err = session.SendAndWait(t.Context(), copilot.MessageOptions{
Prompt: "Run 'echo test' and tell me what happens",
})
if err != nil {
t.Fatalf("SendAndWait failed: %v", err)
}
if !permissionRequestReceived.Get() {
t.Error("Expected permission handler to have been invoked")
}
})
t.Run("should resume session with permission handler", func(t *testing.T) {
ctx.ConfigureForTest(t)
session1, err := client.CreateSession(t.Context(), &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
})
if err != nil {
t.Fatalf("CreateSession failed: %v", err)
}
sessionID := session1.SessionID
if _, err := session1.SendAndWait(t.Context(), copilot.MessageOptions{Prompt: "What is 1+1?"}); err != nil {
t.Fatalf("Initial SendAndWait failed: %v", err)
}
if err := session1.Disconnect(); err != nil {
t.Fatalf("Disconnect failed: %v", err)
}
var permissionRequestReceived atomicBool
session2, err := client.ResumeSession(t.Context(), sessionID, &copilot.ResumeSessionConfig{
OnPermissionRequest: func(req copilot.PermissionRequest, inv copilot.PermissionInvocation) (copilot.PermissionRequestResult, error) {
permissionRequestReceived.Set(true)
return copilot.PermissionRequestResult{Kind: copilot.PermissionRequestResultKindApproved}, nil
},
})
if err != nil {
t.Fatalf("ResumeSession failed: %v", err)
}
_, err = session2.SendAndWait(t.Context(), copilot.MessageOptions{
Prompt: "Run 'echo resumed' for me",
})
if err != nil {
t.Fatalf("SendAndWait (after resume) failed: %v", err)
}
if !permissionRequestReceived.Get() {
t.Error("Expected permission handler from ResumeSessionConfig to have been invoked")
}
})
t.Run("should handle permission handler errors gracefully", func(t *testing.T) {
ctx.ConfigureForTest(t)
session, err := client.CreateSession(t.Context(), &copilot.SessionConfig{
OnPermissionRequest: func(req copilot.PermissionRequest, inv copilot.PermissionInvocation) (copilot.PermissionRequestResult, error) {
return copilot.PermissionRequestResult{}, fmt.Errorf("handler error")
},
})
if err != nil {
t.Fatalf("CreateSession failed: %v", err)
}
message, err := session.SendAndWait(t.Context(), copilot.MessageOptions{
Prompt: "Run 'echo test'. If you can't, say 'failed'.",
})
if err != nil {
t.Fatalf("SendAndWait failed: %v", err)
}
ad, ok := message.Data.(*copilot.AssistantMessageData)
if !ok {
t.Fatalf("Expected *AssistantMessageData, got %T", message.Data)
}
content := strings.ToLower(ad.Content)
matched := false
for _, keyword := range []string{"fail", "cannot", "unable", "permission"} {
if strings.Contains(content, keyword) {
matched = true
break
}
}
if !matched {
t.Errorf("Expected response to indicate failure (fail/cannot/unable/permission), got %q", ad.Content)
}
})
t.Run("should receive toolCallId in permission requests", func(t *testing.T) {
ctx.ConfigureForTest(t)
var receivedToolCallID atomicBool
session, err := client.CreateSession(t.Context(), &copilot.SessionConfig{
OnPermissionRequest: func(req copilot.PermissionRequest, inv copilot.PermissionInvocation) (copilot.PermissionRequestResult, error) {
if shellReq, ok := req.(*copilot.PermissionRequestShell); ok && shellReq.ToolCallID != nil && *shellReq.ToolCallID != "" {
receivedToolCallID.Set(true)
}
return copilot.PermissionRequestResult{Kind: copilot.PermissionRequestResultKindApproved}, nil
},
})
if err != nil {
t.Fatalf("CreateSession failed: %v", err)
}
_, err = session.SendAndWait(t.Context(), copilot.MessageOptions{Prompt: "Run 'echo test'"})
if err != nil {
t.Fatalf("SendAndWait failed: %v", err)
}
if !receivedToolCallID.Get() {
t.Error("Expected ToolCallID to be populated on shell permission request")
}
})
t.Run("should wait for slow permission handler", func(t *testing.T) {
ctx.ConfigureForTest(t)
type lifecycleEvent struct {
Phase string
ToolCallID string
}
handlerEntered := make(chan struct{}, 1)
releaseHandler := make(chan struct{})
targetToolCallID := make(chan string, 1)
var lifecycleMu sync.Mutex
var lifecycle []lifecycleEvent
addLifecycle := func(phase, toolCallID string) {
lifecycleMu.Lock()
lifecycle = append(lifecycle, lifecycleEvent{phase, toolCallID})
lifecycleMu.Unlock()
}
session, err := client.CreateSession(t.Context(), &copilot.SessionConfig{
OnPermissionRequest: func(req copilot.PermissionRequest, inv copilot.PermissionInvocation) (copilot.PermissionRequestResult, error) {
shellReq, ok := req.(*copilot.PermissionRequestShell)
if !ok {
return copilot.PermissionRequestResult{Kind: copilot.PermissionRequestResultKindApproved}, nil
}
toolCallID := ""
if shellReq.ToolCallID != nil {
toolCallID = *shellReq.ToolCallID
}
addLifecycle("permission-start", toolCallID)
select {
case targetToolCallID <- toolCallID:
default:
}
select {
case handlerEntered <- struct{}{}:
default:
}
<-releaseHandler
addLifecycle("permission-complete", toolCallID)
return copilot.PermissionRequestResult{Kind: copilot.PermissionRequestResultKindApproved}, nil
},
})
if err != nil {
t.Fatalf("CreateSession failed: %v", err)
}
t.Cleanup(func() { _ = session.Disconnect() })
session.On(func(event copilot.SessionEvent) {
switch d := event.Data.(type) {
case *copilot.ToolExecutionStartData:
addLifecycle("tool-start", d.ToolCallID)
case *copilot.ToolExecutionCompleteData:
addLifecycle("tool-complete", d.ToolCallID)
}
})
go func() {
_, _ = session.Send(t.Context(), copilot.MessageOptions{
Prompt: "Run 'echo slow_handler_test'",
})
}()
select {
case <-handlerEntered:
case <-time.After(30 * time.Second):
t.Fatal("Timed out waiting for permission handler to be entered")
}
var targetID string
select {
case targetID = <-targetToolCallID:
default:
}
// Verify tool-complete has not yet happened while handler is still running
lifecycleMu.Lock()
for _, evt := range lifecycle {
if evt.Phase == "tool-complete" && evt.ToolCallID == targetID {
t.Error("tool-complete should not have occurred before permission handler completed")
}
}
lifecycleMu.Unlock()
close(releaseHandler)
message, err := testharness.GetFinalAssistantMessage(t.Context(), session)
if err != nil {
t.Fatalf("GetFinalAssistantMessage failed: %v", err)
}
lifecycleMu.Lock()
orderedLifecycle := make([]lifecycleEvent, len(lifecycle))
copy(orderedLifecycle, lifecycle)
lifecycleMu.Unlock()
permStartIdx, permCompleteIdx, toolStartIdx, toolCompleteIdx := -1, -1, -1, -1
for i, evt := range orderedLifecycle {
if evt.ToolCallID != targetID && targetID != "" {
continue
}
switch evt.Phase {
case "permission-start":
if permStartIdx < 0 {
permStartIdx = i
}
case "permission-complete":
if permCompleteIdx < 0 {
permCompleteIdx = i
}
case "tool-start":
if toolStartIdx < 0 {
toolStartIdx = i
}
case "tool-complete":
if toolCompleteIdx < 0 {
toolCompleteIdx = i
}
}
}
if permStartIdx < 0 || permCompleteIdx < 0 || toolCompleteIdx < 0 {
t.Errorf("Expected permission-start, permission-complete, and tool-complete in lifecycle; got %v", orderedLifecycle)
}
if permCompleteIdx >= 0 && toolCompleteIdx >= 0 && permCompleteIdx >= toolCompleteIdx {
t.Errorf("Expected permission completion before tool completion; lifecycle=%v", orderedLifecycle)
}
if toolStartIdx >= 0 && toolCompleteIdx >= 0 && toolStartIdx >= toolCompleteIdx {
t.Errorf("Expected tool start before tool completion; lifecycle=%v", orderedLifecycle)
}
if md, ok := message.Data.(*copilot.AssistantMessageData); !ok || !strings.Contains(md.Content, "slow_handler_test") {
t.Errorf("Expected assistant message to reference 'slow_handler_test', got %v", message.Data)
}
})
t.Run("should handle concurrent permission requests from parallel tools", func(t *testing.T) {
ctx.ConfigureForTest(t)
type EmptyParams struct{}
var permissionRequestCount int
var permissionRequestsMu sync.Mutex
var permissionRequests []copilot.PermissionRequest
bothStarted := make(chan struct{})
var bothStartedOnce sync.Once
firstToolCalled := make(chan struct{}, 1)
secondToolCalled := make(chan struct{}, 1)
firstToolCompleted := make(chan *copilot.ToolExecutionCompleteData, 1)
secondToolCompleted := make(chan *copilot.ToolExecutionCompleteData, 1)
session, err := client.CreateSession(t.Context(), &copilot.SessionConfig{
Tools: []copilot.Tool{
copilot.DefineTool("first_permission_tool", "First concurrent permission test tool",
func(_ EmptyParams, inv copilot.ToolInvocation) (copilot.ToolResult, error) {
select {
case firstToolCalled <- struct{}{}:
default:
}
return copilot.ToolResult{
TextResultForLLM: "first_permission_tool completed after permission approval",
ResultType: "rejected",
}, nil
}),
copilot.DefineTool("second_permission_tool", "Second concurrent permission test tool",
func(_ EmptyParams, inv copilot.ToolInvocation) (copilot.ToolResult, error) {
select {
case secondToolCalled <- struct{}{}:
default:
}
return copilot.ToolResult{
TextResultForLLM: "second_permission_tool completed after permission approval",
ResultType: "rejected",
}, nil
}),
},
AvailableTools: []string{"first_permission_tool", "second_permission_tool"},
OnPermissionRequest: func(req copilot.PermissionRequest, inv copilot.PermissionInvocation) (copilot.PermissionRequestResult, error) {
permissionRequestsMu.Lock()
permissionRequestCount++
permissionRequests = append(permissionRequests, req)
count := permissionRequestCount
permissionRequestsMu.Unlock()
if count >= 2 {
bothStartedOnce.Do(func() { close(bothStarted) })
}
select {
case <-bothStarted:
case <-time.After(30 * time.Second):
}
return copilot.PermissionRequestResult{Kind: copilot.PermissionRequestResultKindApproved}, nil
},
})
if err != nil {
t.Fatalf("CreateSession failed: %v", err)
}
t.Cleanup(func() { _ = session.Disconnect() })
session.On(func(event copilot.SessionEvent) {
if d, ok := event.Data.(*copilot.ToolExecutionCompleteData); ok {
var errMsg string
if d.Error != nil {
errMsg = d.Error.Message
}
switch {
case strings.Contains(errMsg, "first_permission_tool"):
select {
case firstToolCompleted <- d:
default:
}
case strings.Contains(errMsg, "second_permission_tool"):
select {
case secondToolCompleted <- d:
default:
}
}
}
})
if _, err := session.Send(t.Context(), copilot.MessageOptions{
Prompt: "Call both first_permission_tool and second_permission_tool in the same turn. Do not call any other tools.",
}); err != nil {
t.Fatalf("Send failed: %v", err)
}
select {
case <-firstToolCalled:
case <-time.After(60 * time.Second):
t.Fatal("Timed out waiting for first_permission_tool to be called")
}
select {
case <-secondToolCalled:
case <-time.After(60 * time.Second):
t.Fatal("Timed out waiting for second_permission_tool to be called")
}
permissionRequestsMu.Lock()
reqCount := permissionRequestCount
reqs := make([]copilot.PermissionRequest, len(permissionRequests))
copy(reqs, permissionRequests)
permissionRequestsMu.Unlock()
if reqCount < 2 {
t.Errorf("Expected at least 2 permission requests, got %d", reqCount)
}
hasFirst := false
hasSecond := false
for _, req := range reqs {
if customReq, ok := req.(*copilot.PermissionRequestCustomTool); ok {
if customReq.ToolName == "first_permission_tool" {
hasFirst = true
}
if customReq.ToolName == "second_permission_tool" {
hasSecond = true
}
}
}
if !hasFirst {
t.Error("Expected permission request for first_permission_tool")
}
if !hasSecond {
t.Error("Expected permission request for second_permission_tool")
}
assertRejectedToolComplete := func(name string, ch <-chan *copilot.ToolExecutionCompleteData, expectedMessage string) {
t.Helper()
select {
case d := <-ch:
if d.Success {
t.Errorf("Expected %s tool execution to complete with Success=false", name)
}
if d.Error == nil {
t.Errorf("Expected %s tool execution to include an error", name)
return
}
if d.Error.Code == nil || *d.Error.Code != "rejected" {
t.Errorf("Expected %s tool execution error code 'rejected', got %v", name, d.Error.Code)
}
if !strings.Contains(d.Error.Message, expectedMessage) {
t.Errorf("Expected %s tool execution error message to contain %q, got %q", name, expectedMessage, d.Error.Message)
}
case <-time.After(60 * time.Second):
t.Fatalf("Timed out waiting for %s tool.execution_complete", name)
}
}
assertRejectedToolComplete("first_permission_tool", firstToolCompleted, "first_permission_tool completed after permission approval")
assertRejectedToolComplete("second_permission_tool", secondToolCompleted, "second_permission_tool completed after permission approval")
})
t.Run("should deny permission with noresult kind", func(t *testing.T) {
ctx.ConfigureForTest(t)
permissionCalled := make(chan struct{}, 1)
session, err := client.CreateSession(t.Context(), &copilot.SessionConfig{
OnPermissionRequest: func(req copilot.PermissionRequest, inv copilot.PermissionInvocation) (copilot.PermissionRequestResult, error) {
select {
case permissionCalled <- struct{}{}:
default:
}
return copilot.PermissionRequestResult{Kind: copilot.PermissionRequestResultKindNoResult}, nil
},
})
if err != nil {
t.Fatalf("CreateSession failed: %v", err)
}
t.Cleanup(func() { _ = session.Disconnect() })
if _, err := session.Send(t.Context(), copilot.MessageOptions{
Prompt: "Run 'node --version'",
}); err != nil {
t.Fatalf("Send failed: %v", err)
}
select {
case <-permissionCalled:
// Expected: legacy no-result does not send a permission decision.
case <-time.After(30 * time.Second):
t.Fatal("Timed out waiting for permission handler to be called")
}
_ = session.Abort(t.Context())
})
t.Run("should short circuit permission handler when set approve all enabled", func(t *testing.T) {
ctx.ConfigureForTest(t)
var handlerCallCount int
var handlerCallCountMu sync.Mutex
session, err := client.CreateSession(t.Context(), &copilot.SessionConfig{
OnPermissionRequest: func(req copilot.PermissionRequest, inv copilot.PermissionInvocation) (copilot.PermissionRequestResult, error) {
handlerCallCountMu.Lock()
handlerCallCount++
handlerCallCountMu.Unlock()
return copilot.PermissionRequestResult{Kind: copilot.PermissionRequestResultKindApproved}, nil
},
})
if err != nil {
t.Fatalf("CreateSession failed: %v", err)
}
t.Cleanup(func() { _ = session.Disconnect() })
// Runtime contract: when approveAllToolPermissionRequests is true the runtime
// short-circuits the permission flow before invoking the SDK-supplied handler.
setResult, err := session.RPC.Permissions.SetApproveAll(t.Context(), &rpc.PermissionsSetApproveAllRequest{Enabled: true})
if err != nil {
t.Fatalf("SetApproveAll failed: %v", err)
}
if !setResult.Success {
t.Fatalf("SetApproveAll returned success=false")
}
defer func() {
_, _ = session.RPC.Permissions.SetApproveAll(t.Context(), &rpc.PermissionsSetApproveAllRequest{Enabled: false})
}()
toolCompleted := make(chan struct{}, 1)
session.On(func(event copilot.SessionEvent) {
if d, ok := event.Data.(*copilot.ToolExecutionCompleteData); ok && d.Success {
select {
case toolCompleted <- struct{}{}:
default:
}
}
})
if _, err := session.SendAndWait(t.Context(), copilot.MessageOptions{
Prompt: "Run 'echo test' and tell me what happens",
}); err != nil {
t.Fatalf("SendAndWait failed: %v", err)
}
select {
case <-toolCompleted:
// A real shell tool completed successfully under runtime-level approval.
case <-time.After(30 * time.Second):
t.Fatal("Timed out waiting for successful tool.execution_complete")
}
handlerCallCountMu.Lock()
count := handlerCallCount
handlerCallCountMu.Unlock()
if count != 0 {
t.Errorf("Expected permission handler to NOT be called when SetApproveAll is enabled, got %d calls", count)
}
})
}
// atomicBool is a tiny helper for concurrent flag updates in handler callbacks.
type atomicBool struct {
mu sync.Mutex
v bool
}
func (a *atomicBool) Set(v bool) {
a.mu.Lock()
a.v = v
a.mu.Unlock()
}
func (a *atomicBool) Get() bool {
a.mu.Lock()
defer a.mu.Unlock()
return a.v
}