-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathindex.test.js
More file actions
1263 lines (1149 loc) · 54.5 KB
/
Copy pathindex.test.js
File metadata and controls
1263 lines (1149 loc) · 54.5 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 assert from "node:assert/strict"
import { createHash } from "node:crypto"
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"
import { tmpdir } from "node:os"
import { join } from "node:path"
import test from "node:test"
import { QueuePlugin } from "./index.ts"
const model = { providerID: "test", modelID: "model" }
const deferred = () => {
let resolve, reject
const promise = new Promise((yes, no) => { resolve = yes; reject = no })
return { promise, resolve, reject }
}
const output = (id, text) => ({
message: { id, agent: "build", model },
parts: [{ id: `${id}-part`, type: "text", text }],
})
const plugin = async (session = {}, project = "project", request = async () => ({ response: new Response() }), known = ["review"]) => {
const toasts = []
const selected = []
const client = {
_client: {
post: async (input) => {
assert.equal(input.url, "/tui/select-session")
selected.push(input.body.sessionID)
return request(input)
},
},
tui: {
showToast: async ({ body }) => void toasts.push(body.message),
executeCommand: async () => undefined,
},
command: {
list: async () => {
if (!known) return { data: undefined, error: { message: "command list unavailable" } }
return { data: known.map((name) => ({ name, template: "" })) }
},
},
session: {
messages: async () => ({ data: [] }),
status: async () => ({ data: {} }),
prompt: async () => undefined,
shell: async () => undefined,
command: async () => undefined,
summarize: async () => undefined,
...session,
},
}
const hooks = await QueuePlugin({ client, directory: `/${project}`, project: { id: project } })
hooks.toasts = toasts
hooks.selected = selected
return hooks
}
const chat = (hooks, id, text, sessionID = "session") => hooks["chat.message"]({ sessionID, agent: "build", model }, output(id, text))
const busy = (hooks, sessionID = "session") => hooks.event({ event: { type: "session.status", properties: { sessionID, status: { type: "busy" } } } })
const idle = (hooks, sessionID = "session") => hooks.event({ event: { type: "session.idle", properties: { sessionID } } })
const list = async (hooks, sessionID = "session") => {
await chat(hooks, `list-${sessionID}`, "/queue:list", sessionID)
return hooks.toasts.at(-1)
}
const control = async (hooks, command, sessionID = "session") => {
await assert.rejects(
hooks["command.execute.before"]({ sessionID, command, arguments: "" }, { parts: [] }),
(response) => response.status === 204,
)
return hooks.toasts.at(-1)
}
const isolated = (name, run) =>
test(name, { concurrency: false }, async () => {
const previous = process.env.XDG_DATA_HOME
const previousAlways = process.env.OPENCODE_QUEUE_ALWAYS
const data = await mkdtemp(join(tmpdir(), "opencode-queue-"))
process.env.XDG_DATA_HOME = data
delete process.env.OPENCODE_QUEUE_ALWAYS
try {
await run(data)
} finally {
if (previous === undefined) delete process.env.XDG_DATA_HOME
else process.env.XDG_DATA_HOME = previous
if (previousAlways === undefined) delete process.env.OPENCODE_QUEUE_ALWAYS
else process.env.OPENCODE_QUEUE_ALWAYS = previousAlways
await rm(data, { recursive: true, force: true })
}
})
isolated("restores queued items and stopped state after restart", async () => {
const first = await plugin()
await chat(first, "stop", "/queue:stop")
await chat(first, "queued", "/queue survive restart")
const second = await plugin()
assert.equal(await list(second), "1. survive restart\nQueue is stopped")
const transformed = { messages: [{ info: { id: "queued" } }, { info: { id: "other" } }] }
await second["experimental.chat.messages.transform"]({}, transformed)
assert.deepEqual(transformed.messages.map((message) => message.info.id), ["other"])
await chat(second, "clear", "/queue:clear")
const third = await plugin()
assert.equal(await list(third), "Queue is empty\nQueue is stopped")
})
isolated("persists global always mode and bypasses it with now", async () => {
const first = await plugin()
await chat(first, "always-on", "/queue:always-on")
const hooks = await plugin({}, "other-project")
await chat(hooks, "always-status", "/queue:always")
assert.equal(hooks.toasts.at(-1), "Always queue is on globally")
await busy(hooks)
await chat(hooks, "plain", "queue without the command")
const immediate = output("now", "")
await hooks["command.execute.before"]({ sessionID: "session", command: "queue:now", arguments: "send immediately" }, immediate)
await hooks["chat.message"]({ sessionID: "session", agent: "build", model }, immediate)
assert.equal(immediate.parts[0].text, "send immediately")
assert.equal(await list(hooks), "1. queue without the command")
await chat(hooks, "now-shell", "/queue:now !pwd")
assert.equal(await list(hooks), "1. queue without the command\n2. !pwd")
const queuedCommand = { parts: [{ type: "text", text: "changes" }] }
await hooks["command.execute.before"]({ sessionID: "session", command: "review", arguments: "changes" }, queuedCommand)
assert.equal(queuedCommand.parts[0].text, "/queue /review changes")
await chat(hooks, "clear", "/queue:clear")
await chat(hooks, "always-off", "/queue:always-off")
await busy(first)
const direct = output("direct", "send immediately")
await first["chat.message"]({ sessionID: "session", agent: "build", model }, direct)
assert.equal(direct.parts[0].text, "send immediately")
})
isolated("environment always mode works without creating global settings", async (data) => {
const other = await plugin({}, "other-project")
process.env.OPENCODE_QUEUE_ALWAYS = "1"
const local = await plugin()
delete process.env.OPENCODE_QUEUE_ALWAYS
const direct = output("idle", "send while idle")
await local["chat.message"]({ sessionID: "session", agent: "build", model }, direct)
assert.equal(direct.parts[0].text, "send while idle")
await busy(local)
await busy(other)
await chat(local, "queued", "queue locally")
await chat(other, "direct", "send normally")
assert.equal(await list(local), "1. queue locally")
assert.equal(await list(other), "Queue is empty")
const immediate = output("now", "")
await local["command.execute.before"]({ sessionID: "session", command: "queue:now", arguments: "send immediately" }, immediate)
await local["chat.message"]({ sessionID: "session", agent: "build", model }, immediate)
assert.equal(immediate.parts[0].text, "send immediately")
assert.equal(await list(local), "1. queue locally")
await control(local, "queue:always-off")
await control(local, "queue:always-on")
await assert.rejects(readFile(join(data, "opencode", "opencode-queue", "settings.json")), { code: "ENOENT" })
})
for (const [value, enabled] of [["1", true], ["0", false]]) {
isolated(`environment always mode ${enabled} stays local through runtime toggles`, async (data) => {
const global = await plugin({}, "global-project")
const initialCommand = enabled ? "queue:always-on" : "queue:always-off"
const toggledCommand = enabled ? "queue:always-off" : "queue:always-on"
await control(global, toggledCommand)
const settingsPath = join(data, "opencode", "opencode-queue", "settings.json")
const stored = await readFile(settingsPath, "utf8")
process.env.OPENCODE_QUEUE_ALWAYS = value
const local = await plugin()
const peer = await plugin()
delete process.env.OPENCODE_QUEUE_ALWAYS
const ordinary = await plugin({}, "ordinary-project")
const status = `Always queue is ${enabled ? "on" : "off"} for this instance (OPENCODE_QUEUE_ALWAYS)`
assert.equal(await control(local, "queue:always"), status)
await busy(local)
await chat(local, "initial", "initial input")
assert.equal(await list(local), enabled ? "1. initial input" : "Queue is empty")
const command = output("command", "changes")
await local["command.execute.before"]({ sessionID: "session", command: "review", arguments: "changes" }, command)
assert.equal(command.parts[0].text, enabled ? "/queue /review changes" : "changes")
assert.equal(await control(local, toggledCommand), `Always queue is ${enabled ? "off" : "on"} for this instance (OPENCODE_QUEUE_ALWAYS)`)
assert.equal(await control(peer, "queue:always"), status)
assert.equal(await readFile(settingsPath, "utf8"), stored)
await chat(local, "toggled", "input after toggle")
assert.equal(await list(local), enabled ? "1. initial input" : "1. input after toggle")
await chat(local, "restore", `/${initialCommand}`)
assert.equal(local.toasts.at(-1), status)
assert.equal(await readFile(settingsPath, "utf8"), stored)
assert.equal(await control(local, "queue:always", "another-session"), status)
for (const setting of [enabled, !enabled]) {
await control(global, setting ? "queue:always-on" : "queue:always-off")
assert.equal(await control(ordinary, "queue:always"), `Always queue is ${setting ? "on" : "off"} globally`)
assert.equal(await control(local, "queue:always"), status)
}
await control(local, toggledCommand)
process.env.OPENCODE_QUEUE_ALWAYS = value
const restarted = await plugin()
assert.equal(await control(restarted, "queue:always"), status)
})
}
isolated("environment always mode accepts boolean words regardless of case or whitespace", async () => {
for (const [value, enabled] of [["true", true], [" ON ", true], ["false", false], [" OFF ", false]]) {
process.env.OPENCODE_QUEUE_ALWAYS = value
assert.equal(await control(await plugin(), "queue:always"), `Always queue is ${enabled ? "on" : "off"} for this instance (OPENCODE_QUEUE_ALWAYS)`)
}
})
isolated("empty environment values keep global runtime settings", async () => {
for (const value of ["", " "]) {
process.env.OPENCODE_QUEUE_ALWAYS = value
const hooks = await plugin()
assert.equal(await control(hooks, "queue:always-on"), "Always queue is on globally")
assert.equal(await control(await plugin(), "queue:always"), "Always queue is on globally")
await control(hooks, "queue:always-off")
}
})
isolated("invalid environment values fail initialization without changing global settings", async (data) => {
const hooks = await plugin()
await control(hooks, "queue:always-on")
const settingsPath = join(data, "opencode", "opencode-queue", "settings.json")
const stored = await readFile(settingsPath, "utf8")
for (const value of ["tru", "2"]) {
process.env.OPENCODE_QUEUE_ALWAYS = value
await assert.rejects(plugin(), /OPENCODE_QUEUE_ALWAYS must be/)
}
assert.equal(await readFile(settingsPath, "utf8"), stored)
})
isolated("registers dedicated commands and retains q for ordinary input", async () => {
const hooks = await plugin()
const config = {}
await hooks.config(config)
assert.deepEqual(Object.keys(config.command).sort(), [
"q", "queue", "queue:always", "queue:always-off", "queue:always-on", "queue:apply_model", "queue:carry", "queue:carry-front",
"queue:clear", "queue:flush", "queue:front", "queue:list", "queue:now", "queue:start", "queue:stop",
])
await busy(hooks)
await chat(hooks, "last", "/q last")
await chat(hooks, "first", "/queue:front first")
assert.equal(await list(hooks), "1. first\n2. last")
await chat(hooks, "literal", "/queue front page is unreachable")
assert.equal(await list(hooks), "1. first\n2. last\n3. front page is unreachable")
await chat(hooks, "trailing", "trailing /q")
assert.equal(await list(hooks), "1. first\n2. last\n3. front page is unreachable\n4. trailing")
})
isolated("bare queue and q show the queue through both input paths", async () => {
const hooks = await plugin()
const empty = output("empty", "/queue")
await hooks["chat.message"]({ sessionID: "session", agent: "build", model }, empty)
assert.equal(hooks.toasts.at(-1), "Queue is empty")
assert.equal(empty.parts[0].ignored, true)
await busy(hooks)
await chat(hooks, "item", "/queue first")
const command = output("command", "")
await assert.rejects(
hooks["command.execute.before"]({ sessionID: "session", command: "queue", arguments: "" }, command),
(response) => response.status === 204,
)
assert.equal(hooks.toasts.at(-1), "1. first")
await chat(hooks, "alias", "/q")
assert.equal(hooks.toasts.at(-1), "1. first")
const attachment = output("attachment", "/queue")
attachment.parts.push({ type: "file", mime: "text/plain", url: "file:///notes.txt" })
await hooks["chat.message"]({ sessionID: "session", agent: "build", model }, attachment)
assert.equal(await list(hooks), "1. first\n2. 1 attachment")
})
isolated("old control words are literal input and dedicated controls reject extra input", async () => {
const hooks = await plugin()
await busy(hooks)
await chat(hooks, "old-stop", "/queue stop")
await chat(hooks, "old-carry", "/q carry")
assert.equal(await list(hooks), "1. stop\n2. carry")
await chat(hooks, "bad-stop", "/queue:stop later")
assert.equal(hooks.toasts.at(-1), "Queue stop does not accept input")
await chat(hooks, "bad-clear", "/queue:clear 0")
assert.equal(hooks.toasts.at(-1), "Queue clear expects one or more positive item numbers")
assert.equal(await list(hooks), "1. stop\n2. carry")
const oldTrailing = output("old-trailing", "do this /queue front")
await hooks["chat.message"]({ sessionID: "session", agent: "build", model }, oldTrailing)
assert.equal(oldTrailing.parts[0].text, "do this /queue front")
const now = output("now", "/queue:now carry")
await hooks["chat.message"]({ sessionID: "session", agent: "build", model }, now)
assert.equal(now.parts[0].text, "carry")
assert.equal(await list(hooks), "1. stop\n2. carry")
})
isolated("routes dedicated commands through the command hook", async () => {
const hooks = await plugin()
await busy(hooks)
const first = output("first", "")
await hooks["command.execute.before"]({ sessionID: "session", command: "queue:front", arguments: "first" }, first)
assert.equal(first.parts[0].text, "/queue:front first")
await hooks["chat.message"]({ sessionID: "session", agent: "build", model }, first)
await chat(hooks, "second", "/queue second")
assert.equal(await list(hooks), "1. first\n2. second")
await assert.rejects(
hooks["command.execute.before"]({ sessionID: "session", command: "queue:clear", arguments: "1" }, { parts: [] }),
(response) => response.status === 204,
)
assert.equal(await list(hooks), "1. second")
})
isolated("applies the selected model across carry boundaries and restores it for every replay kind", async () => {
const hooks = await plugin()
await control(hooks, "queue:stop")
const attachment = { type: "file", mime: "text/plain", url: "file:///notes.txt" }
const queued = output("prompt", "/queue first")
queued.parts.push(attachment)
await hooks["chat.message"]({ sessionID: "session", agent: "plan", model, variant: "old" }, queued)
await control(hooks, "queue:carry")
await chat(hooks, "command", "/queue /review changes")
await chat(hooks, "shell", "/queue !pwd")
await chat(hooks, "compact", "/queue /compact")
await control(hooks, "queue:stop", "other")
await chat(hooks, "other", "/queue other session", "other")
const selected = { providerID: "other", modelID: "reasoner" }
const message = output("apply", "")
await hooks["command.execute.before"]({ sessionID: "session", command: "queue:apply_model", arguments: "" }, message)
assert.equal(message.parts[0].text, "/queue:apply_model")
await assert.rejects(
hooks["chat.message"]({ sessionID: "session", agent: "build", model: selected, variant: "high" }, message),
(response) => response.status === 204,
)
assert.equal(hooks.toasts.at(-1), "Applied other/reasoner (high) to 4 queued items")
const replayed = {}
const restored = await plugin({
prompt: async ({ path, body }) => { replayed[path.id] = body },
command: async ({ body }) => { replayed.command = body },
shell: async ({ body }) => { replayed.shell = body },
summarize: async ({ body }) => { replayed.compact = body },
create: async () => ({ data: { id: "next" } }),
})
await control(restored, "queue:flush")
assert.deepEqual(replayed.session.model, selected)
assert.equal(replayed.session.variant, "high")
assert.equal(replayed.session.agent, "plan")
assert.deepEqual(replayed.session.parts[1], { ...attachment, id: undefined })
await control(restored, "queue:flush")
await control(restored, "queue:flush", "next")
assert.equal(replayed.command.model, "other/reasoner")
assert.equal(replayed.command.variant, "high")
assert.deepEqual(replayed.shell.model, selected)
assert.deepEqual(replayed.compact, selected)
await control(restored, "queue:flush", "other")
assert.deepEqual(replayed.other.model, model)
})
isolated("apply_model clears the previous variant and excludes in-flight entries", async () => {
const started = deferred()
const finished = deferred()
const replayed = []
const hooks = await plugin({ prompt: async ({ body }) => {
replayed.push(body)
if (replayed.length === 1) {
started.resolve()
await finished.promise
}
} })
await control(hooks, "queue:stop")
await chat(hooks, "first", "/queue running")
const flushing = control(hooks, "queue:flush")
await started.promise
await hooks["chat.message"]({ sessionID: "session", agent: "plan", model, variant: "old" }, output("second", "/queue waiting"))
const selected = { providerID: "other", modelID: "plain" }
await assert.rejects(
hooks["chat.message"]({ sessionID: "session", agent: "build", model: selected }, output("apply", "/queue:apply_model")),
(response) => response.status === 204,
)
assert.equal(hooks.toasts.at(-1), "Applied other/plain to 1 queued item")
finished.resolve()
await flushing
await control(hooks, "queue:flush")
assert.deepEqual(replayed[0].model, model)
assert.deepEqual(replayed[1].model, selected)
assert.equal(replayed[1].variant, undefined)
assert.equal(replayed[1].agent, "plan")
await assert.rejects(chat(hooks, "empty", "/queue:apply_model"), (response) => response.status === 204)
assert.equal(hooks.toasts.at(-1), "Queue is empty")
})
isolated("apply_model waits for pending input and cancels without recording a placeholder", async (data) => {
const inspecting = deferred()
const inspected = deferred()
const prior = { agent: "build", model, variant: "low" }
let inspections = 0
const replayed = []
const hooks = await plugin({
messages: async () => {
inspections++
inspecting.resolve()
await inspected.promise
return { data: [{ info: { role: "user", ...prior } }] }
},
prompt: async ({ body }) => replayed.push(body),
})
await control(hooks, "queue:stop")
const queuing = chat(hooks, "queued", "/queue waiting")
await inspecting.promise
const selected = { providerID: "other", modelID: "reasoner" }
const message = output("apply", "/queue:apply_model")
Object.assign(message.message, { agent: "plan", model: selected, variant: "high" })
const update = assert.rejects(
hooks["chat.message"]({ sessionID: "session", variant: "high" }, message),
(response) => response.status === 204,
)
const flushing = control(hooks, "queue:flush")
inspected.resolve()
await Promise.all([queuing, update, flushing])
assert.equal(inspections, 1)
assert.equal(replayed.length, 1)
assert.deepEqual(replayed[0].model, selected)
assert.equal(replayed[0].variant, "high")
assert.equal(replayed[0].agent, "build")
const stored = JSON.parse(await readFile(join(data, "opencode", "opencode-queue", `${createHash("sha256").update("project").digest("hex")}.json`), "utf8"))
assert.deepEqual(stored.sessions.session.hidden, ["queued"])
assert.equal(stored.sessions.session.stopped, true)
})
isolated("apply_model leaves live entries and its placeholder intact when persistence fails", async (data) => {
const replayed = []
const hooks = await plugin({ prompt: async ({ body }) => replayed.push(body) })
await control(hooks, "queue:stop")
await hooks["chat.message"]({ sessionID: "session", agent: "plan", model, variant: "old" }, output("queued", "/queue waiting"))
const storage = join(data, "opencode", "opencode-queue")
await rm(storage, { recursive: true })
await writeFile(storage, "not a directory")
const message = output("failed", "/queue:apply_model")
const selected = { providerID: "other", modelID: "reasoner" }
await assert.rejects(hooks["chat.message"]({ sessionID: "session", model: selected, variant: "high" }, message))
assert.equal(message.parts[0].text, "/queue:apply_model")
assert.equal(message.parts[0].ignored, undefined)
await rm(storage)
await mkdir(storage)
await control(hooks, "queue:flush")
assert.deepEqual(replayed[0].model, model)
assert.equal(replayed[0].variant, "old")
assert.equal(replayed[0].agent, "plan")
})
isolated("apply_model rejects arguments and attachments", async () => {
const hooks = await plugin()
await assert.rejects(
hooks["command.execute.before"]({ sessionID: "session", command: "queue:apply_model", arguments: "other/model" }, { parts: [] }),
(response) => response.status === 204,
)
assert.equal(hooks.toasts.at(-1), "Queue apply_model does not accept input")
const message = output("attachment", "/queue:apply_model")
message.parts.push({ type: "file", mime: "text/plain", url: "file:///notes.txt" })
await assert.rejects(
hooks["chat.message"]({ sessionID: "session", agent: "build", model }, message),
(response) => response.status === 204,
)
assert.equal(hooks.toasts.at(-1), "Queue apply_model does not accept input")
})
isolated("runs trailing slash commands directly when idle and queues them when busy", async () => {
const hooks = await plugin()
const direct = output("direct", "changes /queue")
await hooks["command.execute.before"]({ sessionID: "session", command: "review", arguments: "changes /queue" }, direct)
assert.equal(direct.parts[0].text, "changes")
await busy(hooks)
const queued = output("queued", "changes /queue")
await hooks["command.execute.before"]({ sessionID: "session", command: "review", arguments: "changes /queue" }, queued)
assert.equal(queued.parts[0].text, "/queue /review changes")
await hooks["chat.message"]({ sessionID: "session", agent: "build", model }, queued)
assert.equal(await list(hooks), "1. /review changes")
})
isolated("queued commands retain their attachment when the submitted message changes", async () => {
const replayed = []
const hooks = await plugin({ command: async ({ body }) => replayed.push(body.parts) })
await busy(hooks)
const attachment = { type: "file", mime: "text/plain", url: "file:///original.txt" }
const queued = output("review", "/queue:front /review changes")
queued.parts.push(attachment)
await hooks["chat.message"]({ sessionID: "session", agent: "build", model }, queued)
attachment.url = "file:///changed.txt"
await chat(hooks, "flush", "/queue:flush")
assert.deepEqual(replayed, [[{ ...attachment, url: "file:///original.txt" }]])
})
isolated("sends a queued command as a prompt when the command no longer exists", async () => {
const replayed = []
const executed = []
let hooks
hooks = await plugin({
prompt: async ({ body }) => {
await hooks["chat.message"]({ sessionID: "session", agent: "build", model }, { message: { id: "fallback", agent: "build", model }, parts: body.parts })
replayed.push(body.parts[0].text)
},
command: async ({ body }) => executed.push(body.command),
})
await chat(hooks, "always-on", "/queue:always-on")
await busy(hooks)
await chat(hooks, "missing", "/queue /notacommand keep this text")
await chat(hooks, "flush", "/queue:flush")
assert.deepEqual(replayed, ["/notacommand keep this text"])
assert.deepEqual(executed, [])
assert.ok(hooks.toasts.includes("Command /notacommand not found; sending it as a prompt"))
assert.equal(await list(hooks), "Queue is empty")
})
isolated("replays a queued command normally when the command list is unavailable", async () => {
const executed = []
const hooks = await plugin({ command: async ({ body }) => executed.push(body.command) }, "project", undefined, null)
await busy(hooks)
await chat(hooks, "review", "/queue /review changes")
await chat(hooks, "flush", "/queue:flush")
assert.deepEqual(executed, ["review"])
assert.equal(await list(hooks), "Queue is empty")
})
isolated("does not requeue internal replays in always mode", async () => {
const replayed = []
let done
const completed = new Promise((resolve) => (done = resolve))
let hooks
const receive = async (message) => {
await hooks["chat.message"]({ sessionID: "session", agent: "build", model }, message)
replayed.push(message.parts[0].text)
await hooks.event({ event: { type: "session.idle", properties: { sessionID: "session" } } })
if (replayed.length === 2) done()
}
hooks = await plugin({
prompt: async ({ body }) => receive({ ...output("prompt-replay", ""), parts: body.parts }),
command: async ({ body }) => {
const message = output("command-replay", `ran /${body.command} ${body.arguments}`)
await hooks["command.execute.before"]({ sessionID: "session", command: body.command, arguments: body.arguments }, message)
return receive(message)
},
})
await chat(hooks, "always-on", "/queue:always-on")
await busy(hooks)
await chat(hooks, "prompt", "first")
await chat(hooks, "command", "/queue /review changes")
await hooks.event({ event: { type: "session.idle", properties: { sessionID: "session" } } })
await completed
assert.deepEqual(replayed, ["first", "ran /review changes"])
})
isolated("restores a running queue without replaying until the session finishes", async () => {
const first = await plugin()
await busy(first)
await chat(first, "queued", "/queue resume after restart")
let replay
const replayed = new Promise((resolve) => (replay = resolve))
const second = await plugin({ prompt: async ({ body }) => replay(body.parts[0].text) })
await second.event({ event: { type: "session.status", properties: { sessionID: "session", status: { type: "idle" } } } })
await second.event({ event: { type: "session.idle", properties: { sessionID: "session" } } })
await chat(second, "later", "/queue later")
assert.equal(await list(second), "1. resume after restart\n2. later")
await busy(second)
await second.event({ event: { type: "session.status", properties: { sessionID: "session", status: { type: "idle" } } } })
assert.equal(await replayed, "resume after restart")
assert.equal(await list(second), "1. later")
})
isolated("replays input queued while the session becomes idle", async () => {
let finishInspection
const inspection = new Promise((resolve) => (finishInspection = resolve))
let finishReplay
const replayed = new Promise((resolve) => (finishReplay = resolve))
const current = await plugin({ prompt: async ({ body }) => finishReplay(body.parts[0].text), messages: () => inspection })
await busy(current)
const queued = chat(current, "queued", "/queue idle race")
await current.event({ event: { type: "session.idle", properties: { sessionID: "session" } } })
finishInspection({ data: [] })
await queued
assert.equal(await replayed, "idle race")
})
isolated("keeps delayed input queued after a session error", async () => {
let finishInspection
const inspection = new Promise((resolve) => (finishInspection = resolve))
let finishReplay
const replayed = new Promise((resolve) => (finishReplay = resolve))
let replays = 0
const current = await plugin({
messages: () => inspection,
prompt: async ({ body }) => {
replays++
finishReplay(body.parts[0].text)
},
})
await busy(current)
const queued = chat(current, "queued", "/queue retry after error")
await current.event({ event: { type: "session.error", properties: { sessionID: "session" } } })
await current.event({ event: { type: "session.idle", properties: { sessionID: "session" } } })
finishInspection({ data: [] })
await queued
assert.equal(await list(current), "1. retry after error")
assert.equal(replays, 0)
await chat(current, "start", "/queue:start")
assert.equal(await replayed, "retry after error")
})
isolated("does not recreate a deleted session from pending input", async () => {
let finishInspection
const inspection = new Promise((resolve) => (finishInspection = resolve))
const current = await plugin({ messages: () => inspection })
await busy(current)
const queued = chat(current, "queued", "/queue stale input")
await current.event({ event: { type: "session.deleted", properties: { info: { id: "session" } } } })
finishInspection({ data: [] })
await queued
const restarted = await plugin()
assert.equal(await list(restarted), "Queue is empty")
})
isolated("rolls back queue state when persistence fails", async (data) => {
const current = await plugin()
await busy(current)
await chat(current, "first", "/queue first")
const storage = join(data, "opencode", "opencode-queue")
await rm(storage, { recursive: true })
await writeFile(storage, "not a directory")
await assert.rejects(chat(current, "failed", "/queue rolled back"))
await assert.rejects(
current["command.execute.before"]({ sessionID: "session", command: "queue:list", arguments: "" }, { parts: [] }),
(response) => response.status === 204,
)
assert.equal(current.toasts.at(-1), "1. first")
await rm(storage)
await mkdir(storage, { recursive: true })
await chat(current, "second", "/queue after failure")
assert.equal(await list(current), "1. first\n2. after failure")
})
isolated("preserves arrival order while inspecting concurrent input", async () => {
let calls = 0
let inspected
let release
const inspectionStarted = new Promise((resolve) => (inspected = resolve))
const firstInspection = new Promise((resolve) => (release = resolve))
const current = await plugin({ messages: async () => {
if (calls++) return { data: [] }
inspected()
return firstInspection
} })
await busy(current)
const first = chat(current, "first", "/queue first")
await inspectionStarted
const second = chat(current, "second", "/queue second")
release({ data: [] })
await Promise.all([first, second])
assert.equal(await list(current), "1. first\n2. second")
})
isolated("orders queue controls after pending input", async () => {
let inspected
let release
const inspectionStarted = new Promise((resolve) => (inspected = resolve))
const inspection = new Promise((resolve) => (release = resolve))
const current = await plugin({ messages: () => {
inspected()
return inspection
} })
await busy(current)
const queued = chat(current, "queued", "/queue pending item")
await inspectionStarted
const cleared = chat(current, "clear", "/queue:clear")
release({ data: [] })
await Promise.all([queued, cleared])
assert.equal(await list(current), "Queue is empty")
})
isolated("restores in-flight items when completion persistence fails", async (data) => {
let replays = 0
let replaying
let release
const replayStarted = new Promise((resolve) => (replaying = resolve))
const replay = new Promise((resolve) => (release = resolve))
const current = await plugin({ prompt: async () => {
replays++
replaying()
await replay
} })
await chat(current, "stop", "/queue:stop")
await chat(current, "queued", "/queue retry completion")
const flushing = chat(current, "flush", "/queue:flush")
await replayStarted
const storage = join(data, "opencode", "opencode-queue")
await rm(storage, { recursive: true })
await writeFile(storage, "not a directory")
release()
await assert.rejects(flushing)
await rm(storage)
await mkdir(storage, { recursive: true })
assert.equal(await list(current), "1. retry completion\nQueue is stopped")
await chat(current, "flush-again", "/queue:flush")
assert.equal(replays, 2)
})
isolated("keeps an in-flight item durable until replay succeeds", async () => {
let release
const pending = new Promise((resolve) => (release = resolve))
let replaying
const replayStarted = new Promise((resolve) => (replaying = resolve))
const first = await plugin({ prompt: () => {
replaying()
return pending
} })
await chat(first, "stop", "/queue:stop")
await chat(first, "queued", "/queue retry after crash")
const flushing = chat(first, "flush", "/queue:flush")
await replayStarted
await chat(first, "concurrent-flush", "/queue:flush")
assert.equal(first.toasts.at(-1), "Queue is empty")
const recovered = await plugin()
assert.equal(await list(recovered), "1. retry after crash\nQueue is stopped")
const transformed = { messages: [{ info: { id: "concurrent-flush" } }] }
await recovered["experimental.chat.messages.transform"]({}, transformed)
assert.deepEqual(transformed.messages, [])
release()
await flushing
const finished = await plugin()
assert.equal(await list(finished), "Queue is empty\nQueue is stopped")
})
isolated("keeps a queued item after an SDK replay error", async () => {
const current = await plugin({ prompt: async (options) => {
assert.equal(options.throwOnError, true)
throw new Error("request failed")
} })
await chat(current, "stop", "/queue:stop")
await chat(current, "queued", "/queue do not lose this")
await chat(current, "flush", "/queue:flush")
const recovered = await plugin()
assert.equal(await list(recovered), "1. do not lose this\nQueue is stopped")
})
isolated("flush steers all remaining messages while an automatic replay is still running", async () => {
const replayed = []
const requests = Array.from({ length: 3 }, () => ({ started: deferred(), finished: deferred() }))
const current = await plugin({
prompt: async ({ body }) => {
const index = replayed.length
const message = { ...output(`replay-${index}`, ""), parts: body.parts }
replayed.push(message)
await current["chat.message"]({ sessionID: "session", agent: "build", model }, message)
requests[index].started.resolve()
await requests[index].finished.promise
},
abort: () => assert.fail("flush must not interrupt the agent"),
})
await chat(current, "always", "/queue:always-on")
await busy(current)
await chat(current, "first", "/queue first")
await chat(current, "second", "/queue second")
await chat(current, "third", "/queue third")
await current.event({ event: { type: "session.idle", properties: { sessionID: "session" } } })
await requests[0].started.promise
await busy(current)
const flushing = assert.rejects(
current["command.execute.before"]({ sessionID: "session", command: "queue:flush", arguments: "" }, { parts: [] }),
(response) => response.status === 204,
)
await Promise.all(requests.map((request) => request.started.promise))
assert.deepEqual(replayed.map((message) => message.parts[0].text), ["first", "second", "third"])
const transformed = { messages: replayed.map((message) => ({ info: message.message })) }
await current["experimental.chat.messages.transform"]({}, transformed)
assert.equal(transformed.messages.length, 3)
assert.equal(await list(current), "Queue is empty")
// Finishing the manual batch must not remove the still-running automatic replay.
requests[1].finished.resolve()
requests[2].finished.resolve()
await flushing
const recovered = await plugin()
assert.equal(await list(recovered), "1. first")
requests[0].finished.resolve()
await list(current)
})
for (const [order, busyAgain] of [[[0, 1], false], [[1, 0], false], [[0, 1], true], [[1, 0], true]]) {
isolated(`concurrent flushes settle in order ${order}, busy again: ${busyAgain}`, async () => {
const requests = Array.from({ length: 3 }, () => ({ started: deferred(), finished: deferred() }))
const replayed = []
const current = await plugin({ prompt: async ({ body }) => {
const index = replayed.length
replayed.push(body.parts[0].text)
requests[index].started.resolve()
await requests[index].finished.promise
} })
await busy(current)
await chat(current, "first", "/queue first")
const first = chat(current, "flush-first", "/queue:flush")
await requests[0].started.promise
await chat(current, "second", "/queue second")
const second = chat(current, "flush-second", "/queue:flush")
await requests[1].started.promise
await current.event({ event: { type: "session.idle", properties: { sessionID: "session" } } })
if (busyAgain) await busy(current)
await chat(current, "third", "/queue third")
assert.equal(await list(current), "1. third")
const flushing = [first, second]
for (const index of order) {
requests[index].finished.resolve()
await flushing[index]
if (busyAgain || index === order[0]) assert.deepEqual(replayed, ["first", "second"])
if (index === order[0]) {
const remaining = index === 0 ? "second" : "first"
assert.equal(await list(await plugin()), `1. ${remaining}\n2. third`)
}
}
if (busyAgain) {
assert.equal(await list(current), "1. third")
await current.event({ event: { type: "session.idle", properties: { sessionID: "session" } } })
}
await requests[2].started.promise
assert.deepEqual(replayed, ["first", "second", "third"])
requests[2].finished.resolve()
await list(current)
})
}
isolated("concurrent flushes preserve failed order and stop after later busy events", async () => {
const requests = Array.from({ length: 2 }, () => ({ started: deferred(), finished: deferred() }))
const replayed = []
const current = await plugin({ prompt: async ({ body }) => {
const text = body.parts[0].text
const index = replayed.length
replayed.push(text)
requests[index].started.resolve()
await requests[index].finished.promise
if (text === "retry") throw new Error("request failed")
} })
await busy(current)
await chat(current, "retry", "/queue retry")
const first = chat(current, "flush-first", "/queue:flush")
await requests[0].started.promise
await chat(current, "second", "/queue second")
const second = chat(current, "flush-second", "/queue:flush")
await requests[1].started.promise
await chat(current, "third", "/queue third")
requests[0].finished.resolve()
await first
await busy(current)
assert.equal(await list(await plugin()), "1. retry\n2. second\n3. third")
requests[1].finished.resolve()
await second
await current.event({ event: { type: "session.idle", properties: { sessionID: "session" } } })
assert.deepEqual(replayed, ["retry", "second"])
assert.equal(await list(current), "1. retry\n2. third")
})
isolated("lists, restores, and removes individual carry boundaries", async () => {
const prior = { agent: "build", model, variant: "low" }
const current = await plugin({ messages: async () => ({ data: [{ info: { role: "user", ...prior } }] }) })
await chat(current, "stop", "/queue:stop")
await chat(current, "first", "/queue first")
await assert.rejects(
current["command.execute.before"]({ sessionID: "session", command: "queue:carry", arguments: "" }, { parts: [] }),
(response) => response.status === 204,
)
await chat(current, "second", "/queue /review changes")
const boundary = output("boundary", "/queue:carry")
await current["chat.message"]({ sessionID: "session", agent: "plan", model: { providerID: "other", modelID: "other" }, variant: "high" }, boundary)
assert.deepEqual(boundary.message, { id: "boundary", ...prior })
assert.equal(boundary.parts[0].ignored, true)
await chat(current, "third", "/queue !pwd")
await chat(current, "front", "/queue:carry-front")
const restored = await plugin()
assert.equal(await list(restored), [
"1. --- carry: new session 1 ---",
"2. first",
"3. --- carry: new session 2 ---",
"4. /review changes",
"5. --- carry: new session 3 ---",
"6. !pwd",
"Queue is stopped",
].join("\n"))
await chat(restored, "clear-boundaries", "/queue:clear 1 3")
assert.equal(await list(restored), "1. first\n2. /review changes\n3. --- carry: new session 1 ---\n4. !pwd\nQueue is stopped")
})
isolated("carry placeholders retain the latest usable assistant context", async () => {
const current = await plugin({ messages: async () => ({ data: [
{ info: { role: "user", agent: "build", model } },
{ info: { role: "assistant", mode: "plan", providerID: "other", modelID: "reasoner", variant: "high" } },
{ info: { role: "assistant" } },
] }) })
await busy(current)
const message = output("carry", "/queue:carry")
await current["chat.message"]({ sessionID: "session", agent: "build", model }, message)
assert.deepEqual(message.message, { id: "carry", agent: "plan", model: { providerID: "other", modelID: "reasoner" }, variant: "high" })
assert.equal(message.parts[0].ignored, true)
assert.equal(await list(current), "1. --- carry: new session 1 ---")
})
isolated("carries a chain into fresh sessions only after each prompt finishes", async (data) => {
const replayed = []
const requests = Array.from({ length: 3 }, () => ({ started: deferred(), finished: deferred() }))
let created = 0
const current = await plugin({
create: async (options) => {
assert.deepEqual(options, { query: { directory: "/project" }, throwOnError: true })
return { data: { id: `next-${++created}` } }
},
prompt: async ({ path, body }) => {
const index = replayed.length
const message = { ...output(`replay-${index}`, ""), parts: body.parts }
await current["chat.message"]({ sessionID: path.id, ...body }, message)
replayed.push({ sid: path.id, body })
await busy(current, path.id)
requests[index].started.resolve()
await requests[index].finished.promise
await idle(current, path.id)
},
})
await chat(current, "always", "/queue:always-on")
await busy(current)
await chat(current, "first", "/queue first")
await chat(current, "carry-1", "/queue:carry")
const attachment = { type: "file", mime: "text/plain", url: "file:///project/notes.txt", filename: "notes.txt" }
const queued = output("second", "/queue second")
queued.parts.push(attachment)
const selected = { agent: "plan", model: { providerID: "other", modelID: "reasoner" }, variant: "high" }
await current["chat.message"]({ sessionID: "session", ...selected }, queued)
await chat(current, "carry-2", "/queue:carry")
await chat(current, "third", "/queue third")
assert.equal(created, 0)
await idle(current)
await requests[0].started.promise
assert.equal(created, 0)
requests[0].finished.resolve()
await requests[1].started.promise
assert.equal(created, 1)
assert.equal(await list(current), "Queue is empty")
assert.equal(await list(current, "next-1"), "1. --- carry: new session 1 ---\n2. third")
assert.deepEqual(replayed[1].body.model, selected.model)
assert.equal(replayed[1].body.agent, selected.agent)
assert.equal(replayed[1].body.variant, selected.variant)
assert.deepEqual(replayed[1].body.parts[1], { ...attachment, id: undefined })
const path = join(data, "opencode", "opencode-queue", `${createHash("sha256").update("project").digest("hex")}.json`)
const stored = JSON.parse(await readFile(path, "utf8"))
assert.deepEqual(stored.sessions.session.items, [])
assert.deepEqual(stored.sessions["next-1"].items.map((item) => item.kind), ["prompt", "carry", "prompt"])
assert.ok(stored.sessions.session.hidden.includes("carry-1"))
assert.ok(!stored.sessions["next-1"].hidden.includes("carry-1"))
requests[1].finished.resolve()
await requests[2].started.promise
assert.equal(created, 2)
assert.equal(await list(current, "next-1"), "Queue is empty")