opencode-copilot-delegate 0.12.1 → 0.12.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,561 +0,0 @@
1
- import { afterEach, describe, expect, it } from 'bun:test'
2
- import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
3
- import { tmpdir } from 'node:os'
4
- import { join } from 'node:path'
5
- import type {
6
- TuiCommand,
7
- TuiPluginApi,
8
- TuiPluginMeta,
9
- TuiToast,
10
- } from '@opencode-ai/plugin/tui'
11
- import { type JSX, testRender } from '@opentui/solid'
12
-
13
- type TuiPlugin = (
14
- api: TuiPluginApi,
15
- options: unknown,
16
- meta: TuiPluginMeta,
17
- ) => Promise<void>
18
-
19
- type TuiPluginModule = {
20
- id: string
21
- tui: TuiPlugin
22
- }
23
-
24
- type DialogReplacement = {
25
- render: () => JSX.Element
26
- onClose?: () => void
27
- }
28
-
29
- type ToastCall = {
30
- message: string
31
- variant?: string
32
- duration?: number
33
- }
34
-
35
- type KeymapLayerCall = {
36
- commands: ReadonlyArray<Record<string, unknown>>
37
- bindings: ReadonlyArray<unknown>
38
- }
39
-
40
- type TestApiControls = {
41
- api: TuiPluginApi
42
- commandFactories: Array<() => TuiCommand[]>
43
- dialogReplacements: DialogReplacement[]
44
- dialogSizes: Array<'medium' | 'large' | 'xlarge'>
45
- clearCalls: number
46
- disposeHandlers: Array<() => void | Promise<void>>
47
- toastCalls: ToastCall[]
48
- unregisterCalls: number
49
- keymapLayerCalls: KeymapLayerCall[]
50
- keymapUnregisterCalls: number
51
- }
52
-
53
- type CreateTestApiOptions = {
54
- /**
55
- * Which TUI registration surfaces the api stub exposes:
56
- * - `'command'` (default): only `api.command.register` — OpenCode 1.14.41 baseline
57
- * - `'keymap'`: only `api.keymap.registerLayer` — OpenCode 1.14.44+ canonical (and the 1.14.42–43 gap)
58
- * - `'both'`: both surfaces — the 1.14.44+ shim era where `command.register` is restored as a deprecated shim
59
- *
60
- * Default `'command'` preserves the existing test suite's assertions about the
61
- * legacy `command.register` registration path without modification.
62
- */
63
- surfaces?: 'command' | 'keymap' | 'both'
64
- }
65
-
66
- const originalFetch = globalThis.fetch
67
- const originalXdgCacheHome = process.env.XDG_CACHE_HOME
68
- const originalSessionId = process.env.OPENCODE_SESSION_ID
69
- const tempPaths: string[] = []
70
-
71
- afterEach(() => {
72
- globalThis.fetch = originalFetch
73
- process.env.XDG_CACHE_HOME = originalXdgCacheHome
74
- process.env.OPENCODE_SESSION_ID = originalSessionId
75
-
76
- for (const tempPath of tempPaths.splice(0)) {
77
- rmSync(tempPath, { force: true, recursive: true })
78
- }
79
- })
80
-
81
- async function loadTuiPlugin(): Promise<TuiPlugin> {
82
- await import('@opentui/solid/runtime-plugin-support')
83
-
84
- const module = await import('../index')
85
- const pluginModule = Reflect.get(module, 'default') as TuiPluginModule
86
- const plugin = pluginModule.tui
87
-
88
- expect(pluginModule).toEqual({
89
- id: 'opencode-copilot-delegate',
90
- tui: expect.any(Function),
91
- })
92
-
93
- expect(typeof plugin).toBe('function')
94
-
95
- return plugin as TuiPlugin
96
- }
97
-
98
- function createTestApi(options: CreateTestApiOptions = {}): TestApiControls {
99
- const surfaces = options.surfaces ?? 'command'
100
- const exposeKeymap = surfaces === 'keymap' || surfaces === 'both'
101
- const exposeCommand = surfaces === 'command' || surfaces === 'both'
102
-
103
- const commandFactories: Array<() => TuiCommand[]> = []
104
- const dialogReplacements: DialogReplacement[] = []
105
- const dialogSizes: Array<'medium' | 'large' | 'xlarge'> = []
106
- const disposeHandlers: Array<() => void | Promise<void>> = []
107
- const toastCalls: ToastCall[] = []
108
- const keymapLayerCalls: KeymapLayerCall[] = []
109
- let clearCalls = 0
110
- let unregisterCalls = 0
111
- let keymapUnregisterCalls = 0
112
-
113
- const commandSurface = exposeCommand
114
- ? {
115
- register: (cb: () => TuiCommand[]) => {
116
- commandFactories.push(cb)
117
- return () => {
118
- unregisterCalls += 1
119
- }
120
- },
121
- trigger: () => {},
122
- show: () => {},
123
- }
124
- : undefined
125
-
126
- const keymapSurface = exposeKeymap
127
- ? {
128
- registerLayer: (layer: {
129
- commands: ReadonlyArray<Record<string, unknown>>
130
- bindings: ReadonlyArray<unknown>
131
- }) => {
132
- keymapLayerCalls.push({
133
- commands: layer.commands,
134
- bindings: layer.bindings,
135
- })
136
- return () => {
137
- keymapUnregisterCalls += 1
138
- }
139
- },
140
- }
141
- : undefined
142
-
143
- const api = {
144
- ...(commandSurface ? { command: commandSurface } : {}),
145
- ...(keymapSurface ? { keymap: keymapSurface } : {}),
146
- ui: {
147
- Dialog: ((props: { children?: JSX.Element }) =>
148
- props.children ?? null) as TuiPluginApi['ui']['Dialog'],
149
- DialogAlert: (() => null) as TuiPluginApi['ui']['DialogAlert'],
150
- DialogConfirm: (() => null) as TuiPluginApi['ui']['DialogConfirm'],
151
- DialogPrompt: (() => null) as TuiPluginApi['ui']['DialogPrompt'],
152
- DialogSelect: (() => null) as TuiPluginApi['ui']['DialogSelect'],
153
- Slot: (() => null) as TuiPluginApi['ui']['Slot'],
154
- Prompt: (() => null) as TuiPluginApi['ui']['Prompt'],
155
- toast: (input: TuiToast) => {
156
- toastCalls.push({
157
- message: input.message,
158
- variant: input.variant,
159
- duration: input.duration,
160
- })
161
- },
162
- dialog: {
163
- replace: (render: () => JSX.Element, onClose?: () => void) => {
164
- dialogReplacements.push({ render, onClose })
165
- },
166
- clear: () => {
167
- clearCalls += 1
168
- },
169
- setSize: (size: 'medium' | 'large' | 'xlarge') => {
170
- dialogSizes.push(size)
171
- },
172
- size: 'medium',
173
- depth: 0,
174
- open: false,
175
- },
176
- },
177
- lifecycle: {
178
- signal: new AbortController().signal,
179
- onDispose: (fn: () => void | Promise<void>) => {
180
- disposeHandlers.push(fn)
181
- return () => {}
182
- },
183
- },
184
- } as unknown as TuiPluginApi
185
-
186
- return {
187
- api,
188
- commandFactories,
189
- dialogReplacements,
190
- dialogSizes,
191
- get clearCalls() {
192
- return clearCalls
193
- },
194
- disposeHandlers,
195
- toastCalls,
196
- get unregisterCalls() {
197
- return unregisterCalls
198
- },
199
- keymapLayerCalls,
200
- get keymapUnregisterCalls() {
201
- return keymapUnregisterCalls
202
- },
203
- }
204
- }
205
-
206
- function makeCacheHome(): string {
207
- const path = mkdtempSync(join(tmpdir(), 'copilot-status-index-'))
208
- tempPaths.push(path)
209
- return path
210
- }
211
-
212
- function writePortFile(
213
- cacheHome: string,
214
- sessionDiscriminator: string,
215
- contents: unknown,
216
- ) {
217
- const sessionDir = join(
218
- cacheHome,
219
- 'opencode',
220
- 'copilot-delegate',
221
- sessionDiscriminator,
222
- )
223
-
224
- mkdirSync(sessionDir, { recursive: true })
225
- writeFileSync(join(sessionDir, 'server-port.json'), JSON.stringify(contents))
226
- }
227
-
228
- async function waitForFrame(options: {
229
- renderOnce: () => Promise<void>
230
- idle: () => Promise<void>
231
- captureCharFrame: () => string
232
- includes: string
233
- attempts?: number
234
- }): Promise<string> {
235
- const attempts = options.attempts ?? 10
236
-
237
- for (let index = 0; index < attempts; index += 1) {
238
- await Promise.resolve()
239
- await new Promise((resolve) => setTimeout(resolve, 0))
240
- await options.renderOnce()
241
- await options.idle()
242
- await options.renderOnce()
243
-
244
- const frame = options.captureCharFrame()
245
- if (frame.includes(options.includes)) {
246
- return frame
247
- }
248
- }
249
-
250
- return options.captureCharFrame()
251
- }
252
-
253
- function makePluginMeta(): TuiPluginMeta {
254
- return {
255
- id: 'copilot-status-test',
256
- source: 'npm',
257
- spec: 'opencode-copilot-delegate',
258
- target: '/tmp/opencode-copilot-delegate',
259
- requested: 'opencode-copilot-delegate',
260
- version: '0.9.0',
261
- modified: Date.now(),
262
- first_time: Date.now(),
263
- last_time: Date.now(),
264
- time_changed: Date.now(),
265
- load_count: 1,
266
- fingerprint: 'test-fingerprint',
267
- state: 'same',
268
- }
269
- }
270
-
271
- describe('tui entrypoint', () => {
272
- it('registers /copilot-status using the value field', async () => {
273
- const plugin = await loadTuiPlugin()
274
- const controls = createTestApi()
275
-
276
- await plugin(controls.api, undefined, makePluginMeta())
277
-
278
- expect(controls.commandFactories).toHaveLength(1)
279
- expect(controls.disposeHandlers).toHaveLength(1)
280
-
281
- const commands = controls.commandFactories[0]()
282
-
283
- expect(commands).toHaveLength(1)
284
- expect(commands[0]).toMatchObject({
285
- title: 'Copilot Status',
286
- value: '/copilot-status',
287
- slash: { name: 'copilot-status' },
288
- })
289
-
290
- await controls.disposeHandlers[0]()
291
- expect(controls.unregisterCalls).toBe(1)
292
- })
293
-
294
- it('opens the modal list and loads tasks when /copilot-status is selected', async () => {
295
- const plugin = await loadTuiPlugin()
296
- const controls = createTestApi()
297
- const cacheHome = makeCacheHome()
298
- const sessionDiscriminator = 'tui-index-open'
299
- const fetchCalls: Array<{
300
- url: string
301
- authorization?: string
302
- body?: string
303
- }> = []
304
-
305
- process.env.XDG_CACHE_HOME = cacheHome
306
- process.env.OPENCODE_SESSION_ID = sessionDiscriminator
307
-
308
- writePortFile(cacheHome, sessionDiscriminator, {
309
- port: 43123,
310
- pid: process.pid,
311
- token: 'token-index-open',
312
- })
313
-
314
- const stubFetch = Object.assign(
315
- async (input: string | URL | Request, init?: RequestInit) => {
316
- const headers = new Headers(init?.headers)
317
- fetchCalls.push({
318
- url: String(input),
319
- authorization: headers.get('Authorization') ?? undefined,
320
- body: typeof init?.body === 'string' ? init.body : undefined,
321
- })
322
-
323
- return new Response(JSON.stringify({ tasks: [] }), {
324
- status: 200,
325
- headers: { 'content-type': 'application/json' },
326
- })
327
- },
328
- { preconnect: originalFetch.preconnect },
329
- )
330
-
331
- globalThis.fetch = stubFetch as unknown as typeof fetch
332
-
333
- await plugin(controls.api, undefined, makePluginMeta())
334
-
335
- const [command] = controls.commandFactories[0]()
336
- command.onSelect?.()
337
-
338
- expect(controls.dialogReplacements).toHaveLength(1)
339
- expect(controls.dialogSizes).toEqual(['large'])
340
-
341
- const { renderOnce, captureCharFrame, renderer } = await testRender(
342
- () => controls.dialogReplacements[0].render(),
343
- { useThread: false },
344
- )
345
- await renderOnce()
346
-
347
- const frame = await waitForFrame({
348
- renderOnce,
349
- idle: () => renderer.idle(),
350
- captureCharFrame,
351
- includes: '0 running · 0 recent',
352
- })
353
- expect(fetchCalls).toEqual([
354
- {
355
- url: 'http://127.0.0.1:43123/tasks/list',
356
- authorization: 'Bearer token-index-open',
357
- body: '{}',
358
- },
359
- ])
360
- expect(frame).toContain('0 running · 0 recent')
361
- expect(frame).toContain('No Copilot delegations are running.')
362
- expect(frame).not.toContain('Unit 6')
363
- })
364
-
365
- it('does not pass a re-entrant host onClose callback to the custom status dialog', async () => {
366
- const plugin = await loadTuiPlugin()
367
- const controls = createTestApi()
368
-
369
- await plugin(controls.api, undefined, makePluginMeta())
370
-
371
- const [command] = controls.commandFactories[0]()
372
- command.onSelect?.()
373
-
374
- expect(controls.dialogReplacements).toHaveLength(1)
375
- expect(controls.dialogReplacements[0].onClose).toBeUndefined()
376
- expect(controls.clearCalls).toBe(0)
377
- })
378
-
379
- it('does not toast when rpc is unavailable', async () => {
380
- const plugin = await loadTuiPlugin()
381
- const controls = createTestApi()
382
- const cacheHome = makeCacheHome()
383
- process.env.XDG_CACHE_HOME = cacheHome
384
- process.env.OPENCODE_SESSION_ID = 'tui-index-error'
385
-
386
- await plugin(controls.api, undefined, makePluginMeta())
387
-
388
- const [command] = controls.commandFactories[0]()
389
- command.onSelect?.()
390
-
391
- expect(controls.dialogReplacements).toHaveLength(1)
392
- expect(controls.dialogSizes).toEqual(['large'])
393
-
394
- const { renderOnce, renderer } = await testRender(
395
- () => controls.dialogReplacements[0].render(),
396
- { useThread: false },
397
- )
398
-
399
- await renderOnce()
400
- await renderer.idle()
401
- await renderOnce()
402
-
403
- expect(controls.dialogReplacements).toHaveLength(1)
404
- expect(controls.dialogSizes).toEqual(['large'])
405
- expect(controls.toastCalls).toEqual([])
406
- })
407
-
408
- it('prefers api.keymap.registerLayer when available (OpenCode 1.14.44+)', async () => {
409
- const plugin = await loadTuiPlugin()
410
- const controls = createTestApi({ surfaces: 'keymap' })
411
-
412
- await plugin(controls.api, undefined, makePluginMeta())
413
-
414
- expect(controls.keymapLayerCalls).toHaveLength(1)
415
- expect(controls.commandFactories).toHaveLength(0)
416
-
417
- const layer = controls.keymapLayerCalls[0]
418
- expect(layer.bindings).toEqual([])
419
- expect(layer.commands).toHaveLength(1)
420
-
421
- const command = layer.commands[0]
422
- expect(command).toMatchObject({
423
- namespace: 'palette',
424
- name: 'copilot-status',
425
- title: 'Copilot Status',
426
- category: 'Copilot',
427
- })
428
- expect(typeof command.run).toBe('function')
429
-
430
- expect(controls.disposeHandlers).toHaveLength(1)
431
- await controls.disposeHandlers[0]()
432
- expect(controls.keymapUnregisterCalls).toBe(1)
433
- expect(controls.unregisterCalls).toBe(0)
434
- })
435
-
436
- it('prefers api.keymap.registerLayer when both APIs exist (1.14.44+ shim era)', async () => {
437
- const plugin = await loadTuiPlugin()
438
- const controls = createTestApi({ surfaces: 'both' })
439
-
440
- await plugin(controls.api, undefined, makePluginMeta())
441
-
442
- expect(controls.keymapLayerCalls).toHaveLength(1)
443
- expect(controls.commandFactories).toHaveLength(0)
444
- })
445
-
446
- it('falls back to api.command.register when keymap.registerLayer is absent (OpenCode 1.14.41)', async () => {
447
- const plugin = await loadTuiPlugin()
448
- const controls = createTestApi({ surfaces: 'command' })
449
-
450
- await plugin(controls.api, undefined, makePluginMeta())
451
-
452
- expect(controls.commandFactories).toHaveLength(1)
453
- expect(controls.keymapLayerCalls).toHaveLength(0)
454
- expect(controls.disposeHandlers).toHaveLength(1)
455
-
456
- // Dispose unregisters via the command-register path, mirroring the
457
- // keymap-path test's assertion that the correct teardown route runs.
458
- await controls.disposeHandlers[0]()
459
- expect(controls.unregisterCalls).toBe(1)
460
- expect(controls.keymapUnregisterCalls).toBe(0)
461
- })
462
-
463
- it('opens the modal list when the keymap-path command is run', async () => {
464
- const plugin = await loadTuiPlugin()
465
- const controls = createTestApi({ surfaces: 'keymap' })
466
-
467
- await plugin(controls.api, undefined, makePluginMeta())
468
-
469
- const command = controls.keymapLayerCalls[0]?.commands[0] as
470
- | (Record<string, unknown> & { run?: () => void })
471
- | undefined
472
- expect(command).toBeDefined()
473
- command?.run?.()
474
-
475
- expect(controls.dialogReplacements).toHaveLength(1)
476
- expect(controls.dialogSizes).toEqual(['large'])
477
- })
478
-
479
- it('keeps /copilot-status on a single read-only dialog replacement', async () => {
480
- const plugin = await loadTuiPlugin()
481
- const controls = createTestApi()
482
- const cacheHome = makeCacheHome()
483
- const sessionDiscriminator = 'tui-index-read-only'
484
-
485
- process.env.XDG_CACHE_HOME = cacheHome
486
- process.env.OPENCODE_SESSION_ID = sessionDiscriminator
487
-
488
- writePortFile(cacheHome, sessionDiscriminator, {
489
- port: 43124,
490
- pid: process.pid,
491
- token: 'token-index-read-only',
492
- })
493
-
494
- const stubFetch = Object.assign(
495
- async (_input: string | URL | Request) => {
496
- return new Response(
497
- JSON.stringify({
498
- tasks: [
499
- {
500
- taskId: 'cpl_alpha',
501
- status: 'running',
502
- agent: 'default',
503
- model: 'gpt-5',
504
- elapsedMs: 0,
505
- toolCallCount: 1,
506
- startedAt: 0,
507
- },
508
- {
509
- taskId: 'cpl_beta',
510
- status: 'running',
511
- agent: 'reviewer',
512
- model: 'claude-sonnet-4.7',
513
- elapsedMs: 0,
514
- toolCallCount: 2,
515
- startedAt: 0,
516
- },
517
- ],
518
- }),
519
- {
520
- status: 200,
521
- headers: { 'content-type': 'application/json' },
522
- },
523
- )
524
- },
525
- { preconnect: originalFetch.preconnect },
526
- )
527
-
528
- globalThis.fetch = stubFetch as unknown as typeof fetch
529
-
530
- await plugin(controls.api, undefined, makePluginMeta())
531
-
532
- const [command] = controls.commandFactories[0]()
533
- command.onSelect?.()
534
-
535
- expect(controls.dialogReplacements).toHaveLength(1)
536
-
537
- const listRender = await testRender(
538
- () => controls.dialogReplacements[0].render(),
539
- {
540
- width: 120,
541
- height: 20,
542
- useThread: false,
543
- },
544
- )
545
-
546
- await listRender.renderOnce()
547
-
548
- const listFrame = await waitForFrame({
549
- renderOnce: listRender.renderOnce,
550
- idle: () => listRender.renderer.idle(),
551
- captureCharFrame: listRender.captureCharFrame,
552
- includes: '2 running · 0 recent',
553
- })
554
- expect(listFrame).toContain('cpl_beta')
555
- expect(listFrame).toContain('Esc close')
556
- expect(listFrame).not.toContain('navigate')
557
- expect(listFrame).not.toContain('c cancel')
558
- expect(controls.dialogReplacements).toHaveLength(1)
559
- expect(controls.dialogSizes).toEqual(['large'])
560
- })
561
- })