-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathopencode-process.test.ts
More file actions
1663 lines (1411 loc) · 57.2 KB
/
Copy pathopencode-process.test.ts
File metadata and controls
1663 lines (1411 loc) · 57.2 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
/** Tests for OpenCodeProcess — verifies SSE event mapping, lifecycle, and provider interface compliance. */
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest'
import { summarizeToolInput } from './tool-labels.js'
// Mock fetch globally for HTTP calls
const mockFetch = vi.fn()
vi.stubGlobal('fetch', mockFetch)
// Mock child_process.spawn for the server process
vi.mock('child_process', async (importOriginal) => {
const actual = await importOriginal<typeof import('child_process')>()
return {
...actual,
spawn: vi.fn(() => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const EventEmitter = require('events').EventEmitter
const proc = Object.assign(new EventEmitter(), {
stdin: { write: vi.fn(), end: vi.fn() },
stdout: Object.assign(new EventEmitter(), { on: vi.fn() }),
stderr: Object.assign(new EventEmitter(), { on: vi.fn() }),
kill: vi.fn(),
killed: false,
})
return proc
}),
}
})
import { OpenCodeProcess, stopOpenCodeServer, permissionRulesetFor, OPENCODE_SYSTEM_CONTEXT, isVersionOlder, MIN_TESTED_OPENCODE_VERSION } from './opencode-process.js'
import { writeFileSync, mkdtempSync, rmSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { OPENCODE_CAPABILITIES } from './coding-process.js'
describe('OpenCodeProcess', () => {
let ocp: OpenCodeProcess
beforeEach(() => {
vi.clearAllMocks()
ocp = new OpenCodeProcess('/tmp/test-repo', {
sessionId: 'test-session-id',
model: 'anthropic/claude-sonnet-4',
})
})
afterEach(() => {
ocp.stop()
stopOpenCodeServer()
})
// ---------------------------------------------------------------------------
// Interface compliance
// ---------------------------------------------------------------------------
describe('provider interface', () => {
it('reports provider as opencode', () => {
expect(ocp.provider).toBe('opencode')
})
it('has opencode capabilities', () => {
expect(ocp.capabilities).toBe(OPENCODE_CAPABILITIES)
expect(ocp.capabilities.multiProvider).toBe(true)
})
it('starts as not alive', () => {
expect(ocp.isAlive()).toBe(false)
})
it('returns codekin session ID when no opencode session exists', () => {
expect(ocp.getSessionId()).toBe('test-session-id')
})
it('returns opencode session ID when available (for resume)', () => {
const ocp2 = new OpenCodeProcess('/tmp/test-repo', {
sessionId: 'codekin-id',
opencodeSessionId: 'opencode-abc-123',
})
expect(ocp2.getSessionId()).toBe('opencode-abc-123')
ocp2.stop()
})
it('generates a session ID if not provided', () => {
const ocp2 = new OpenCodeProcess('/tmp/test-repo')
expect(ocp2.getSessionId()).toBeTruthy()
expect(ocp2.getSessionId()).toHaveLength(36) // UUID format
ocp2.stop()
})
it('accepts opencodeSessionId for resume via constructor', () => {
const ocp2 = new OpenCodeProcess('/tmp/test-repo', {
opencodeSessionId: 'oc-resume-id',
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((ocp2 as any).opencodeSessionId).toBe('oc-resume-id')
ocp2.stop()
})
it('sendRaw is a no-op', () => {
// Should not throw
ocp.sendRaw('anything')
})
it('waitForExit resolves immediately when not alive', async () => {
await expect(ocp.waitForExit()).resolves.toBeUndefined()
})
})
// ---------------------------------------------------------------------------
// SSE event mapping
// ---------------------------------------------------------------------------
// Access the private handleSSEEvent method for testing event mapping
const callHandleSSE = (ocp: OpenCodeProcess, event: Record<string, unknown>) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(ocp as any).handleSSEEvent(event)
}
// Set the opencodeSessionId so session filtering works
const setSessionId = (ocp: OpenCodeProcess, id: string) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(ocp as any).opencodeSessionId = id
}
describe('SSE event mapping', () => {
it('maps text delta events to text events', () => {
const textHandler = vi.fn()
ocp.on('text', textHandler)
setSessionId(ocp, 'oc-session-1')
callHandleSSE(ocp, {
type: 'message.part.delta',
properties: {
sessionID: 'oc-session-1',
field: 'text',
delta: 'Hello',
},
})
expect(textHandler).toHaveBeenCalledWith('Hello')
callHandleSSE(ocp, {
type: 'message.part.delta',
properties: {
sessionID: 'oc-session-1',
field: 'text',
delta: ' world',
},
})
expect(textHandler).toHaveBeenCalledWith(' world')
expect(textHandler).toHaveBeenCalledTimes(2)
})
it('ignores non-text delta events', () => {
const textHandler = vi.fn()
ocp.on('text', textHandler)
setSessionId(ocp, 'oc-session-1')
callHandleSSE(ocp, {
type: 'message.part.delta',
properties: {
sessionID: 'oc-session-1',
field: 'reasoning',
delta: 'some reasoning',
},
})
expect(textHandler).not.toHaveBeenCalled()
})
it('ignores delta events from other sessions', () => {
const textHandler = vi.fn()
ocp.on('text', textHandler)
setSessionId(ocp, 'oc-session-1')
callHandleSSE(ocp, {
type: 'message.part.delta',
properties: {
sessionID: 'other-session',
field: 'text',
delta: 'Hello',
},
})
expect(textHandler).not.toHaveBeenCalled()
})
it('strips user echo prefix from text deltas', () => {
const textHandler = vi.fn()
ocp.on('text', textHandler)
setSessionId(ocp, 'oc-session-1')
// Simulate sendMessage storing lastUserInput
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(ocp as any).lastUserInput = 'hello'
// First delta — matches user input, should be buffered
callHandleSSE(ocp, {
type: 'message.part.delta',
properties: { sessionID: 'oc-session-1', field: 'text', delta: 'hello' },
})
expect(textHandler).not.toHaveBeenCalled()
// Second delta — flushes buffer, strips user echo, emits remainder
callHandleSSE(ocp, {
type: 'message.part.delta',
properties: { sessionID: 'oc-session-1', field: 'text', delta: 'Hello there!' },
})
// Buffer was "helloHello there!" which starts with "hello", so emits "Hello there!"
expect(textHandler).toHaveBeenCalledWith('Hello there!')
})
it('emits full buffer when no user echo match', () => {
const textHandler = vi.fn()
ocp.on('text', textHandler)
setSessionId(ocp, 'oc-session-1')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(ocp as any).lastUserInput = 'hello'
// Delta that doesn't match user input once it reaches the threshold
callHandleSSE(ocp, {
type: 'message.part.delta',
properties: { sessionID: 'oc-session-1', field: 'text', delta: 'Sure, I can help!' },
})
expect(textHandler).toHaveBeenCalledWith('Sure, I can help!')
})
it('emits reasoning deltas as thinking events', () => {
const thinkingHandler = vi.fn()
ocp.on('thinking', thinkingHandler)
setSessionId(ocp, 'oc-session-1')
// Short reasoning — not enough for summary
callHandleSSE(ocp, {
type: 'message.part.delta',
properties: { sessionID: 'oc-session-1', field: 'reasoning', delta: 'Let me ' },
})
expect(thinkingHandler).not.toHaveBeenCalled()
// More reasoning — exceeds threshold, emits thinking summary
callHandleSSE(ocp, {
type: 'message.part.delta',
properties: { sessionID: 'oc-session-1', field: 'reasoning', delta: 'think about this carefully.' },
})
expect(thinkingHandler).toHaveBeenCalledTimes(1)
expect(thinkingHandler.mock.calls[0][0]).toContain('Let me think about this carefully.')
})
it('strips user echo from full text in message.part.updated', () => {
const textHandler = vi.fn()
ocp.on('text', textHandler)
setSessionId(ocp, 'oc-session-1')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(ocp as any).lastUserInput = 'hello'
callHandleSSE(ocp, {
type: 'message.part.updated',
properties: {
sessionID: 'oc-session-1',
part: { type: 'text', text: 'helloHere is my response.' },
},
})
expect(textHandler).toHaveBeenCalledWith('Here is my response.')
})
it('ignores text part updates (content arrives via deltas)', () => {
const textHandler = vi.fn()
ocp.on('text', textHandler)
setSessionId(ocp, 'oc-session-1')
callHandleSSE(ocp, {
type: 'message.part.updated',
properties: {
sessionID: 'oc-session-1',
part: { type: 'text', content: 'Hello' },
},
})
expect(textHandler).not.toHaveBeenCalled()
})
it('maps reasoning parts to thinking events', () => {
const thinkingHandler = vi.fn()
ocp.on('thinking', thinkingHandler)
setSessionId(ocp, 'oc-session-1')
callHandleSSE(ocp, {
type: 'message.part.updated',
properties: {
sessionID: 'oc-session-1',
part: { type: 'reasoning', text: 'Let me think about this carefully and consider all the options.' },
},
})
expect(thinkingHandler).toHaveBeenCalledTimes(1)
expect(thinkingHandler.mock.calls[0][0]).toBeTruthy()
})
it('ignores short reasoning content', () => {
const thinkingHandler = vi.fn()
ocp.on('thinking', thinkingHandler)
setSessionId(ocp, 'oc-session-1')
callHandleSSE(ocp, {
type: 'message.part.updated',
properties: {
sessionID: 'oc-session-1',
part: { type: 'reasoning', text: 'Short' },
},
})
expect(thinkingHandler).not.toHaveBeenCalled()
})
it('routes Kimi-style field=text deltas by partID (reasoning hidden, answer shown)', async () => {
// Kimi via OpenCode streams BOTH reasoning and the answer as field=text
// deltas, distinguished only by partID, and never sends
// message.part.updated — so the part kind is resolved via a REST lookup.
const textHandler = vi.fn()
const thinkingHandler = vi.fn()
ocp.on('text', textHandler)
ocp.on('thinking', thinkingHandler)
setSessionId(ocp, 'oc-session-1')
// Classify 'prt_reason' as reasoning, everything else as text.
mockFetch.mockImplementation((url: string) => {
const type = url.includes('prt_reason') ? 'reasoning' : 'text'
return Promise.resolve({ ok: true, json: () => Promise.resolve({ type }) })
})
for (const d of ['The user ', 'is greeting me. ', 'I should respond.']) {
callHandleSSE(ocp, {
type: 'message.part.delta',
properties: { sessionID: 'oc-session-1', messageID: 'msg_1', partID: 'prt_reason', field: 'text', delta: d },
})
}
// Deltas are buffered pending classification — nothing emitted yet.
expect(textHandler).not.toHaveBeenCalled()
expect(thinkingHandler).not.toHaveBeenCalled()
// Once the lookup resolves, reasoning becomes a thinking summary, never text.
await vi.waitFor(() => expect(thinkingHandler).toHaveBeenCalledTimes(1))
expect(textHandler).not.toHaveBeenCalled()
for (const d of ['Hello', '! How can I help?']) {
callHandleSSE(ocp, {
type: 'message.part.delta',
properties: { sessionID: 'oc-session-1', messageID: 'msg_1', partID: 'prt_answer', field: 'text', delta: d },
})
}
await vi.waitFor(() => expect(textHandler).toHaveBeenCalled())
const shown = textHandler.mock.calls.map(c => c[0] as string).join('')
expect(shown).toBe('Hello! How can I help?')
expect(shown).not.toContain('greeting')
})
it('maps running tool parts to tool_active events', () => {
const toolActiveHandler = vi.fn()
ocp.on('tool_active', toolActiveHandler)
setSessionId(ocp, 'oc-session-1')
callHandleSSE(ocp, {
type: 'message.part.updated',
properties: {
sessionID: 'oc-session-1',
part: {
type: 'tool',
tool: 'bash',
state: { status: 'running', input: { command: 'ls -la' } },
},
},
})
expect(toolActiveHandler).toHaveBeenCalledWith('bash', '$ ls -la')
})
it('maps completed tool parts to tool_done and tool_output events', () => {
const toolDoneHandler = vi.fn()
const toolOutputHandler = vi.fn()
ocp.on('tool_done', toolDoneHandler)
ocp.on('tool_output', toolOutputHandler)
setSessionId(ocp, 'oc-session-1')
callHandleSSE(ocp, {
type: 'message.part.updated',
properties: {
sessionID: 'oc-session-1',
part: {
type: 'tool',
tool: 'read',
state: { status: 'completed', output: 'file contents here' },
},
},
})
expect(toolDoneHandler).toHaveBeenCalledWith('read', 'file contents here')
expect(toolOutputHandler).toHaveBeenCalledWith('file contents here', false)
})
it('maps error tool parts to tool_done and error tool_output', () => {
const toolDoneHandler = vi.fn()
const toolOutputHandler = vi.fn()
ocp.on('tool_done', toolDoneHandler)
ocp.on('tool_output', toolOutputHandler)
setSessionId(ocp, 'oc-session-1')
callHandleSSE(ocp, {
type: 'message.part.updated',
properties: {
sessionID: 'oc-session-1',
part: {
type: 'tool',
tool: 'bash',
state: { status: 'error', error: 'command not found' },
},
},
})
expect(toolDoneHandler).toHaveBeenCalledWith('bash', 'Error: command not found')
expect(toolOutputHandler).toHaveBeenCalledWith('command not found', true)
})
it('maps session.status idle to result event', () => {
const resultHandler = vi.fn()
ocp.on('result', resultHandler)
setSessionId(ocp, 'oc-session-1')
callHandleSSE(ocp, {
type: 'session.status',
properties: {
sessionID: 'oc-session-1',
status: { type: 'idle' },
},
})
expect(resultHandler).toHaveBeenCalledWith('', false)
})
it('maps session.error to error event', () => {
const errorHandler = vi.fn()
ocp.on('error', errorHandler)
setSessionId(ocp, 'oc-session-1')
callHandleSSE(ocp, {
type: 'session.error',
properties: { sessionID: 'oc-session-1', error: { message: 'Rate limit exceeded' } },
})
expect(errorHandler).toHaveBeenCalledWith('Rate limit exceeded')
})
it('filters session.error from other sessions', () => {
const errorHandler = vi.fn()
ocp.on('error', errorHandler)
setSessionId(ocp, 'my-session')
callHandleSSE(ocp, {
type: 'session.error',
properties: { sessionID: 'other-session', error: { message: 'Should be ignored' } },
})
expect(errorHandler).not.toHaveBeenCalled()
})
it('maps permission.asked to control_request event', () => {
const controlHandler = vi.fn()
ocp.on('control_request', controlHandler)
setSessionId(ocp, 'oc-session-1')
callHandleSSE(ocp, {
type: 'permission.asked',
properties: {
sessionID: 'oc-session-1',
id: 'perm-123',
permission: 'external_directory',
patterns: ['/tmp/*'],
metadata: { filepath: '/tmp', parentDir: '/tmp' },
tool: { messageID: 'msg-1', callID: 'call-1' },
},
})
expect(controlHandler).toHaveBeenCalledWith('perm-123', 'external_directory', {
permission: 'external_directory',
filepath: '/tmp',
parentDir: '/tmp',
patterns: ['/tmp/*'],
})
})
it('filters permission.asked from other sessions', () => {
const controlHandler = vi.fn()
ocp.on('control_request', controlHandler)
setSessionId(ocp, 'my-session')
callHandleSSE(ocp, {
type: 'permission.asked',
properties: {
sessionID: 'other-session',
id: 'perm-456',
permission: 'external_directory',
patterns: ['/tmp/*'],
},
})
expect(controlHandler).not.toHaveBeenCalled()
})
it('filters events from other sessions', () => {
const textHandler = vi.fn()
ocp.on('text', textHandler)
setSessionId(ocp, 'my-session')
callHandleSSE(ocp, {
type: 'message.part.updated',
properties: {
sessionID: 'other-session',
part: { type: 'text', content: 'Should be ignored' },
},
})
expect(textHandler).not.toHaveBeenCalled()
})
it('truncates long tool output', () => {
const toolOutputHandler = vi.fn()
ocp.on('tool_output', toolOutputHandler)
setSessionId(ocp, 'oc-session-1')
const longOutput = 'x'.repeat(3000)
callHandleSSE(ocp, {
type: 'message.part.updated',
properties: {
sessionID: 'oc-session-1',
part: {
type: 'tool',
tool: 'read',
state: { status: 'completed', output: longOutput },
},
},
})
const emitted = toolOutputHandler.mock.calls[0][0] as string
expect(emitted.length).toBeLessThan(longOutput.length)
expect(emitted).toContain('truncated')
})
})
// ---------------------------------------------------------------------------
// Lifecycle
// ---------------------------------------------------------------------------
describe('lifecycle', () => {
it('stop() sets alive to false and emits exit', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(ocp as any).alive = true
expect(ocp.isAlive()).toBe(true)
const exitHandler = vi.fn()
ocp.on('exit', exitHandler)
ocp.stop()
expect(ocp.isAlive()).toBe(false)
expect(exitHandler).toHaveBeenCalledWith(0, null)
})
it('waitForExit resolves after stop', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(ocp as any).alive = true
const exitPromise = ocp.waitForExit(5000)
ocp.stop()
await expect(exitPromise).resolves.toBeUndefined()
})
it('sendMessage emits error when not connected', () => {
const errorHandler = vi.fn()
ocp.on('error', errorHandler)
ocp.sendMessage('hello')
expect(errorHandler).toHaveBeenCalledWith('OpenCode process is not connected')
})
it('sendControlResponse calls replyToPermission', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const replyFn = vi.spyOn(ocp as any, 'replyToPermission').mockResolvedValue(undefined)
ocp.sendControlResponse('req-1', 'allow')
expect(replyFn).toHaveBeenCalledWith('req-1', 'once')
})
it('sendControlResponse maps deny to reject', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const replyFn = vi.spyOn(ocp as any, 'replyToPermission').mockResolvedValue(undefined)
ocp.sendControlResponse('req-2', 'deny')
expect(replyFn).toHaveBeenCalledWith('req-2', 'reject')
})
it('sendControlResponse maps allow_always to always', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const replyFn = vi.spyOn(ocp as any, 'replyToPermission').mockResolvedValue(undefined)
ocp.sendControlResponse('req-3', 'allow_always')
expect(replyFn).toHaveBeenCalledWith('req-3', 'always')
})
})
// ---------------------------------------------------------------------------
// Turn lifecycle hardening
// ---------------------------------------------------------------------------
describe('turn lifecycle', () => {
it('emits result only once even when multiple idle events arrive', () => {
const resultHandler = vi.fn()
ocp.on('result', resultHandler)
setSessionId(ocp, 'oc-session-1')
callHandleSSE(ocp, {
type: 'session.idle',
properties: { sessionID: 'oc-session-1' },
})
callHandleSSE(ocp, {
type: 'message.completed',
properties: { sessionID: 'oc-session-1' },
})
callHandleSSE(ocp, {
type: 'session.status',
properties: { sessionID: 'oc-session-1', status: { type: 'idle' } },
})
expect(resultHandler).toHaveBeenCalledTimes(1)
})
it('clears the turn watchdog when the turn completes', () => {
setSessionId(ocp, 'oc-session-1')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(ocp as any).startTurnWatchdog()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((ocp as any).turnWatchdog).not.toBeNull()
callHandleSSE(ocp, {
type: 'session.idle',
properties: { sessionID: 'oc-session-1' },
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((ocp as any).turnWatchdog).toBeNull()
})
it('recovers a missed completion event via message poll', async () => {
const resultHandler = vi.fn()
ocp.on('result', resultHandler)
setSessionId(ocp, 'oc-session-1')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(ocp as any).alive = true
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(ocp as any).turnComplete = false
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => [
{ info: { role: 'user', time: { created: 1 } } },
{ info: { role: 'assistant', time: { created: 2, completed: 3 } } },
],
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await (ocp as any).checkTurnLiveness(true)
expect(resultHandler).toHaveBeenCalledWith('', false)
})
it('does not force-complete when the assistant message is still running', async () => {
const resultHandler = vi.fn()
ocp.on('result', resultHandler)
setSessionId(ocp, 'oc-session-1')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(ocp as any).alive = true
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => [
{ info: { role: 'assistant', time: { created: 2 } } },
],
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await (ocp as any).checkTurnLiveness(true)
expect(resultHandler).not.toHaveBeenCalled()
})
it('handles flat message objects (no info wrapper) in poll response', async () => {
const resultHandler = vi.fn()
ocp.on('result', resultHandler)
setSessionId(ocp, 'oc-session-1')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(ocp as any).alive = true
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => [
{ role: 'assistant', time: { created: 2, completed: 3 } },
],
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await (ocp as any).checkTurnLiveness(true)
expect(resultHandler).toHaveBeenCalledWith('', false)
})
})
// ---------------------------------------------------------------------------
// Permission mode → OpenCode permission ruleset
// ---------------------------------------------------------------------------
describe('permissionRulesetFor', () => {
it('maps bypassPermissions to an all-allow ruleset', () => {
expect(permissionRulesetFor('bypassPermissions')).toEqual([
{ permission: '*', pattern: '*', action: 'allow' },
])
})
it('maps dangerouslySkipPermissions to an all-allow ruleset', () => {
expect(permissionRulesetFor('dangerouslySkipPermissions')).toEqual([
{ permission: '*', pattern: '*', action: 'allow' },
])
})
it('maps acceptEdits to an edit-allow ruleset', () => {
expect(permissionRulesetFor('acceptEdits')).toEqual([
{ permission: 'edit', pattern: '*', action: 'allow' },
])
})
it('returns undefined for default, plan, and unset modes', () => {
expect(permissionRulesetFor('default')).toBeUndefined()
expect(permissionRulesetFor('plan')).toBeUndefined()
expect(permissionRulesetFor(undefined)).toBeUndefined()
})
})
// ---------------------------------------------------------------------------
// sendMessage request body (agent, system, model, command routing)
// ---------------------------------------------------------------------------
describe('sendMessage request body', () => {
/** Prepare a connected process and capture the next outgoing request. */
const connect = (proc: OpenCodeProcess) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(proc as any).alive = true
setSessionId(proc, 'oc-session-1')
mockFetch.mockResolvedValue({ ok: true, json: async () => ({}) })
}
const lastRequest = () => {
const [url, init] = mockFetch.mock.calls[mockFetch.mock.calls.length - 1] as [string, { body: string }]
return { url, body: JSON.parse(init.body) as Record<string, unknown> }
}
it('selects the build agent and appends Codekin system context by default', () => {
connect(ocp)
ocp.sendMessage('hello')
const { url, body } = lastRequest()
expect(url).toContain('/session/oc-session-1/prompt_async')
expect(body.agent).toBe('build')
expect(body.system).toBe(OPENCODE_SYSTEM_CONTEXT)
expect(body.model).toEqual({ providerID: 'anthropic', modelID: 'claude-sonnet-4' })
})
it('selects the plan agent in plan mode', () => {
const planProc = new OpenCodeProcess('/tmp/test-repo', {
sessionId: 'plan-session',
model: 'anthropic/claude-sonnet-4',
permissionMode: 'plan',
})
connect(planProc)
planProc.sendMessage('propose a refactor')
const { body } = lastRequest()
expect(body.agent).toBe('plan')
planProc.stop()
})
it('splits OpenRouter-style model IDs at the first slash only', () => {
const orProc = new OpenCodeProcess('/tmp/test-repo', {
sessionId: 'or-session',
model: 'openrouter/meta-llama/llama-3.1-8b',
})
connect(orProc)
orProc.sendMessage('hi')
const { body } = lastRequest()
expect(body.model).toEqual({ providerID: 'openrouter', modelID: 'meta-llama/llama-3.1-8b' })
orProc.stop()
})
it('routes known slash commands to the command endpoint', () => {
connect(ocp)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(ocp as any).commands = new Map([['review', { name: 'review', source: 'command' }]])
ocp.sendMessage('/review src/index.ts')
const { url, body } = lastRequest()
expect(url).toContain('/session/oc-session-1/command')
expect(body.command).toBe('review')
expect(body.arguments).toBe('src/index.ts')
expect(body.agent).toBe('build')
expect(body.model).toBe('anthropic/claude-sonnet-4')
})
it('routes a known slash command without arguments', () => {
connect(ocp)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(ocp as any).commands = new Map([['init', { name: 'init' }]])
ocp.sendMessage('/init')
const { url, body } = lastRequest()
expect(url).toContain('/command')
expect(body.command).toBe('init')
expect(body.arguments).toBeUndefined()
})
it('sends unknown slash commands as a regular prompt', () => {
connect(ocp)
ocp.sendMessage('/not-a-command do things')
const { url, body } = lastRequest()
expect(url).toContain('/prompt_async')
expect((body.parts as Array<{ text: string }>)[0].text).toBe('/not-a-command do things')
})
it('does not route commands when attachments are present', () => {
connect(ocp)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(ocp as any).commands = new Map([['review', { name: 'review' }]])
// Attached file does not exist — attachment is skipped, but the message
// had an attachment prefix, so it must go through the prompt path.
ocp.sendMessage('[Attached files: /nonexistent/file.png]\n/review this')
const { url } = lastRequest()
expect(url).toContain('/prompt_async')
})
})
// ---------------------------------------------------------------------------
// step-finish flushing
// ---------------------------------------------------------------------------
describe('step-finish', () => {
it('flushes buffered text deltas on step-finish', () => {
const textHandler = vi.fn()
ocp.on('text', textHandler)
setSessionId(ocp, 'oc-session-1')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(ocp as any).lastUserInput = 'a long user message that exceeds the delta'
// Short delta — buffered awaiting the echo check
callHandleSSE(ocp, {
type: 'message.part.delta',
properties: { sessionID: 'oc-session-1', field: 'text', delta: 'Done.' },
})
expect(textHandler).not.toHaveBeenCalled()
// Step boundary — buffer must flush
callHandleSSE(ocp, {
type: 'message.part.updated',
properties: { sessionID: 'oc-session-1', part: { type: 'step-finish' } },
})
expect(textHandler).toHaveBeenCalledWith('Done.')
})
})
// ---------------------------------------------------------------------------
// Permission reply retries
// ---------------------------------------------------------------------------
describe('permission reply retries', () => {
it('emits error when all permission reply attempts fail', async () => {
const errorHandler = vi.fn()
ocp.on('error', errorHandler)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(ocp as any).permissionRetryDelayMs = 0
mockFetch.mockRejectedValue(new Error('connection refused'))
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await (ocp as any).replyToPermission('perm-1', 'once')
expect(mockFetch).toHaveBeenCalledTimes(3)
expect(errorHandler).toHaveBeenCalledTimes(1)
expect(errorHandler.mock.calls[0][0]).toContain('permission response')
})
it('does not emit error when a retry succeeds', async () => {
const errorHandler = vi.fn()
ocp.on('error', errorHandler)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(ocp as any).permissionRetryDelayMs = 0
mockFetch
.mockRejectedValueOnce(new Error('connection refused'))
.mockResolvedValueOnce({ ok: true })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await (ocp as any).replyToPermission('perm-2', 'once')
expect(mockFetch).toHaveBeenCalledTimes(2)
expect(errorHandler).not.toHaveBeenCalled()
})
})
// ---------------------------------------------------------------------------
// Tool input summarization
// ---------------------------------------------------------------------------
describe('summarizeToolInput', () => {
it('summarizes bash commands', () => {
expect(summarizeToolInput('bash', { command: 'npm install' })).toBe('$ npm install')
})
it('summarizes read/view with file path', () => {
expect(summarizeToolInput('read', { file_path: '/src/index.ts' })).toBe('/src/index.ts')
expect(summarizeToolInput('view', { filePath: '/src/main.ts' })).toBe('/src/main.ts')
})
it('summarizes edit/write with file path', () => {
expect(summarizeToolInput('edit', { file_path: '/README.md' })).toBe('/README.md')
})
it('summarizes glob/grep with pattern', () => {
expect(summarizeToolInput('glob', { pattern: '**/*.ts' })).toBe('**/*.ts')
expect(summarizeToolInput('grep', { pattern: 'TODO' })).toBe('TODO')
})
it('returns empty string for unknown tools', () => {
expect(summarizeToolInput('unknown_tool', {})).toBe('')
})
})
// ---------------------------------------------------------------------------
// Task/Todo support
// ---------------------------------------------------------------------------
describe('task tracking', () => {
it('emits todo_update for TodoWrite tool calls', () => {
const todoHandler = vi.fn()
ocp.on('todo_update', todoHandler)
setSessionId(ocp, 'oc-session-1')
callHandleSSE(ocp, {
type: 'message.part.updated',
properties: {
sessionID: 'oc-session-1',
part: {
type: 'tool',
tool: 'TodoWrite',
state: {
status: 'running',
input: {
todos: [
{ content: 'Fix bug', status: 'in_progress', activeForm: 'Fixing bug' },
{ content: 'Write tests', status: 'pending', activeForm: 'Writing tests' },
],
},
},
},
},
})
expect(todoHandler).toHaveBeenCalledTimes(1)
const tasks = todoHandler.mock.calls[0][0]
expect(tasks).toHaveLength(2)
expect(tasks[0].subject).toBe('Fix bug')
expect(tasks[0].status).toBe('in_progress')
expect(tasks[1].subject).toBe('Write tests')
expect(tasks[1].status).toBe('pending')
})
it('does not emit todo_update for non-task tools', () => {
const todoHandler = vi.fn()
ocp.on('todo_update', todoHandler)
setSessionId(ocp, 'oc-session-1')
callHandleSSE(ocp, {
type: 'message.part.updated',
properties: {
sessionID: 'oc-session-1',
part: {
type: 'tool',
tool: 'bash',
state: { status: 'running', input: { command: 'ls' } },
},
},
})
expect(todoHandler).not.toHaveBeenCalled()
})
})
// ---------------------------------------------------------------------------
// Abort on stop (in-flight turn interrupt)
// ---------------------------------------------------------------------------
describe('abort on stop', () => {
const connect = (proc: OpenCodeProcess) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(proc as any).alive = true
setSessionId(proc, 'oc-session-1')
mockFetch.mockResolvedValue({ ok: true, json: async () => ({}) })
}
it('aborts an in-flight turn when stopped', () => {
connect(ocp)
ocp.sendMessage('do something long')
mockFetch.mockClear()
ocp.stop()
const abortCall = mockFetch.mock.calls.find(
([url]) => typeof url === 'string' && url.includes('/session/oc-session-1/abort'),
)
expect(abortCall).toBeDefined()
expect((abortCall![1] as { method: string }).method).toBe('POST')
})
it('does not abort when no turn is in flight', () => {
connect(ocp)
mockFetch.mockClear()
ocp.stop()