opencode-copilot-delegate 0.9.0 → 0.10.1

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.
@@ -0,0 +1,438 @@
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 TestApiControls = {
36
+ api: TuiPluginApi
37
+ commandFactories: Array<() => TuiCommand[]>
38
+ dialogReplacements: DialogReplacement[]
39
+ dialogSizes: Array<'medium' | 'large' | 'xlarge'>
40
+ clearCalls: number
41
+ disposeHandlers: Array<() => void | Promise<void>>
42
+ toastCalls: ToastCall[]
43
+ unregisterCalls: number
44
+ }
45
+
46
+ const originalFetch = globalThis.fetch
47
+ const originalXdgCacheHome = process.env.XDG_CACHE_HOME
48
+ const originalSessionId = process.env.OPENCODE_SESSION_ID
49
+ const tempPaths: string[] = []
50
+
51
+ afterEach(() => {
52
+ globalThis.fetch = originalFetch
53
+ process.env.XDG_CACHE_HOME = originalXdgCacheHome
54
+ process.env.OPENCODE_SESSION_ID = originalSessionId
55
+
56
+ for (const tempPath of tempPaths.splice(0)) {
57
+ rmSync(tempPath, { force: true, recursive: true })
58
+ }
59
+ })
60
+
61
+ async function loadTuiPlugin(): Promise<TuiPlugin> {
62
+ await import('@opentui/solid/runtime-plugin-support')
63
+
64
+ const module = await import('../index')
65
+ const pluginModule = Reflect.get(module, 'default') as TuiPluginModule
66
+ const plugin = pluginModule.tui
67
+
68
+ expect(pluginModule).toEqual({
69
+ id: 'opencode-copilot-delegate',
70
+ tui: expect.any(Function),
71
+ })
72
+
73
+ expect(typeof plugin).toBe('function')
74
+
75
+ return plugin as TuiPlugin
76
+ }
77
+
78
+ function createTestApi(): TestApiControls {
79
+ const commandFactories: Array<() => TuiCommand[]> = []
80
+ const dialogReplacements: DialogReplacement[] = []
81
+ const dialogSizes: Array<'medium' | 'large' | 'xlarge'> = []
82
+ const disposeHandlers: Array<() => void | Promise<void>> = []
83
+ const toastCalls: ToastCall[] = []
84
+ let clearCalls = 0
85
+ let unregisterCalls = 0
86
+
87
+ const api = {
88
+ command: {
89
+ register: (cb: () => TuiCommand[]) => {
90
+ commandFactories.push(cb)
91
+ return () => {
92
+ unregisterCalls += 1
93
+ }
94
+ },
95
+ trigger: () => {},
96
+ show: () => {},
97
+ },
98
+ ui: {
99
+ Dialog: ((props: { children?: JSX.Element }) =>
100
+ props.children ?? null) as TuiPluginApi['ui']['Dialog'],
101
+ DialogAlert: (() => null) as TuiPluginApi['ui']['DialogAlert'],
102
+ DialogConfirm: (() => null) as TuiPluginApi['ui']['DialogConfirm'],
103
+ DialogPrompt: (() => null) as TuiPluginApi['ui']['DialogPrompt'],
104
+ DialogSelect: (() => null) as TuiPluginApi['ui']['DialogSelect'],
105
+ Slot: (() => null) as TuiPluginApi['ui']['Slot'],
106
+ Prompt: (() => null) as TuiPluginApi['ui']['Prompt'],
107
+ toast: (input: TuiToast) => {
108
+ toastCalls.push({
109
+ message: input.message,
110
+ variant: input.variant,
111
+ duration: input.duration,
112
+ })
113
+ },
114
+ dialog: {
115
+ replace: (render: () => JSX.Element, onClose?: () => void) => {
116
+ dialogReplacements.push({ render, onClose })
117
+ },
118
+ clear: () => {
119
+ clearCalls += 1
120
+ },
121
+ setSize: (size: 'medium' | 'large' | 'xlarge') => {
122
+ dialogSizes.push(size)
123
+ },
124
+ size: 'medium',
125
+ depth: 0,
126
+ open: false,
127
+ },
128
+ },
129
+ lifecycle: {
130
+ signal: new AbortController().signal,
131
+ onDispose: (fn: () => void | Promise<void>) => {
132
+ disposeHandlers.push(fn)
133
+ return () => {}
134
+ },
135
+ },
136
+ } as unknown as TuiPluginApi
137
+
138
+ return {
139
+ api,
140
+ commandFactories,
141
+ dialogReplacements,
142
+ dialogSizes,
143
+ get clearCalls() {
144
+ return clearCalls
145
+ },
146
+ disposeHandlers,
147
+ toastCalls,
148
+ get unregisterCalls() {
149
+ return unregisterCalls
150
+ },
151
+ }
152
+ }
153
+
154
+ function makeCacheHome(): string {
155
+ const path = mkdtempSync(join(tmpdir(), 'copilot-status-index-'))
156
+ tempPaths.push(path)
157
+ return path
158
+ }
159
+
160
+ function writePortFile(
161
+ cacheHome: string,
162
+ sessionDiscriminator: string,
163
+ contents: unknown,
164
+ ) {
165
+ const sessionDir = join(
166
+ cacheHome,
167
+ 'opencode',
168
+ 'copilot-delegate',
169
+ sessionDiscriminator,
170
+ )
171
+
172
+ mkdirSync(sessionDir, { recursive: true })
173
+ writeFileSync(join(sessionDir, 'server-port.json'), JSON.stringify(contents))
174
+ }
175
+
176
+ async function waitForFrame(options: {
177
+ renderOnce: () => Promise<void>
178
+ idle: () => Promise<void>
179
+ captureCharFrame: () => string
180
+ includes: string
181
+ attempts?: number
182
+ }): Promise<string> {
183
+ const attempts = options.attempts ?? 10
184
+
185
+ for (let index = 0; index < attempts; index += 1) {
186
+ await Promise.resolve()
187
+ await new Promise((resolve) => setTimeout(resolve, 0))
188
+ await options.renderOnce()
189
+ await options.idle()
190
+ await options.renderOnce()
191
+
192
+ const frame = options.captureCharFrame()
193
+ if (frame.includes(options.includes)) {
194
+ return frame
195
+ }
196
+ }
197
+
198
+ return options.captureCharFrame()
199
+ }
200
+
201
+ function makePluginMeta(): TuiPluginMeta {
202
+ return {
203
+ id: 'copilot-status-test',
204
+ source: 'npm',
205
+ spec: 'opencode-copilot-delegate',
206
+ target: '/tmp/opencode-copilot-delegate',
207
+ requested: 'opencode-copilot-delegate',
208
+ version: '0.9.0',
209
+ modified: Date.now(),
210
+ first_time: Date.now(),
211
+ last_time: Date.now(),
212
+ time_changed: Date.now(),
213
+ load_count: 1,
214
+ fingerprint: 'test-fingerprint',
215
+ state: 'same',
216
+ }
217
+ }
218
+
219
+ describe('tui entrypoint', () => {
220
+ it('registers /copilot-status using the value field', async () => {
221
+ const plugin = await loadTuiPlugin()
222
+ const controls = createTestApi()
223
+
224
+ await plugin(controls.api, undefined, makePluginMeta())
225
+
226
+ expect(controls.commandFactories).toHaveLength(1)
227
+ expect(controls.disposeHandlers).toHaveLength(1)
228
+
229
+ const commands = controls.commandFactories[0]()
230
+
231
+ expect(commands).toHaveLength(1)
232
+ expect(commands[0]).toMatchObject({
233
+ title: 'Copilot Status',
234
+ value: '/copilot-status',
235
+ slash: { name: 'copilot-status' },
236
+ })
237
+
238
+ await controls.disposeHandlers[0]()
239
+ expect(controls.unregisterCalls).toBe(1)
240
+ })
241
+
242
+ it('opens the modal list and loads tasks when /copilot-status is selected', async () => {
243
+ const plugin = await loadTuiPlugin()
244
+ const controls = createTestApi()
245
+ const cacheHome = makeCacheHome()
246
+ const sessionDiscriminator = 'tui-index-open'
247
+ const fetchCalls: Array<{
248
+ url: string
249
+ authorization?: string
250
+ body?: string
251
+ }> = []
252
+
253
+ process.env.XDG_CACHE_HOME = cacheHome
254
+ process.env.OPENCODE_SESSION_ID = sessionDiscriminator
255
+
256
+ writePortFile(cacheHome, sessionDiscriminator, {
257
+ port: 43123,
258
+ pid: process.pid,
259
+ token: 'token-index-open',
260
+ })
261
+
262
+ const stubFetch = Object.assign(
263
+ async (input: string | URL | Request, init?: RequestInit) => {
264
+ const headers = new Headers(init?.headers)
265
+ fetchCalls.push({
266
+ url: String(input),
267
+ authorization: headers.get('Authorization') ?? undefined,
268
+ body: typeof init?.body === 'string' ? init.body : undefined,
269
+ })
270
+
271
+ return new Response(JSON.stringify({ tasks: [] }), {
272
+ status: 200,
273
+ headers: { 'content-type': 'application/json' },
274
+ })
275
+ },
276
+ { preconnect: originalFetch.preconnect },
277
+ )
278
+
279
+ globalThis.fetch = stubFetch as unknown as typeof fetch
280
+
281
+ await plugin(controls.api, undefined, makePluginMeta())
282
+
283
+ const [command] = controls.commandFactories[0]()
284
+ command.onSelect?.()
285
+
286
+ expect(controls.dialogReplacements).toHaveLength(1)
287
+ expect(controls.dialogSizes).toEqual(['large'])
288
+
289
+ const { renderOnce, captureCharFrame, renderer } = await testRender(
290
+ () => controls.dialogReplacements[0].render(),
291
+ { useThread: false },
292
+ )
293
+ await renderOnce()
294
+
295
+ const frame = await waitForFrame({
296
+ renderOnce,
297
+ idle: () => renderer.idle(),
298
+ captureCharFrame,
299
+ includes: '0 running · 0 recent',
300
+ })
301
+ expect(fetchCalls).toEqual([
302
+ {
303
+ url: 'http://127.0.0.1:43123/tasks/list',
304
+ authorization: 'Bearer token-index-open',
305
+ body: '{}',
306
+ },
307
+ ])
308
+ expect(frame).toContain('0 running · 0 recent')
309
+ expect(frame).toContain('No Copilot delegations are running.')
310
+ expect(frame).not.toContain('Unit 6')
311
+ })
312
+
313
+ it('does not pass a re-entrant host onClose callback to the custom status dialog', async () => {
314
+ const plugin = await loadTuiPlugin()
315
+ const controls = createTestApi()
316
+
317
+ await plugin(controls.api, undefined, makePluginMeta())
318
+
319
+ const [command] = controls.commandFactories[0]()
320
+ command.onSelect?.()
321
+
322
+ expect(controls.dialogReplacements).toHaveLength(1)
323
+ expect(controls.dialogReplacements[0].onClose).toBeUndefined()
324
+ expect(controls.clearCalls).toBe(0)
325
+ })
326
+
327
+ it('does not toast when rpc is unavailable', async () => {
328
+ const plugin = await loadTuiPlugin()
329
+ const controls = createTestApi()
330
+ const cacheHome = makeCacheHome()
331
+ process.env.XDG_CACHE_HOME = cacheHome
332
+ process.env.OPENCODE_SESSION_ID = 'tui-index-error'
333
+
334
+ await plugin(controls.api, undefined, makePluginMeta())
335
+
336
+ const [command] = controls.commandFactories[0]()
337
+ command.onSelect?.()
338
+
339
+ expect(controls.dialogReplacements).toHaveLength(1)
340
+ expect(controls.dialogSizes).toEqual(['large'])
341
+
342
+ const { renderOnce, renderer } = await testRender(
343
+ () => controls.dialogReplacements[0].render(),
344
+ { useThread: false },
345
+ )
346
+
347
+ await renderOnce()
348
+ await renderer.idle()
349
+ await renderOnce()
350
+
351
+ expect(controls.dialogReplacements).toHaveLength(1)
352
+ expect(controls.dialogSizes).toEqual(['large'])
353
+ expect(controls.toastCalls).toEqual([])
354
+ })
355
+
356
+ it('keeps /copilot-status on a single read-only dialog replacement', async () => {
357
+ const plugin = await loadTuiPlugin()
358
+ const controls = createTestApi()
359
+ const cacheHome = makeCacheHome()
360
+ const sessionDiscriminator = 'tui-index-read-only'
361
+
362
+ process.env.XDG_CACHE_HOME = cacheHome
363
+ process.env.OPENCODE_SESSION_ID = sessionDiscriminator
364
+
365
+ writePortFile(cacheHome, sessionDiscriminator, {
366
+ port: 43124,
367
+ pid: process.pid,
368
+ token: 'token-index-read-only',
369
+ })
370
+
371
+ const stubFetch = Object.assign(
372
+ async (_input: string | URL | Request) => {
373
+ return new Response(
374
+ JSON.stringify({
375
+ tasks: [
376
+ {
377
+ taskId: 'cpl_alpha',
378
+ status: 'running',
379
+ agent: 'default',
380
+ model: 'gpt-5',
381
+ elapsedMs: 0,
382
+ toolCallCount: 1,
383
+ startedAt: 0,
384
+ },
385
+ {
386
+ taskId: 'cpl_beta',
387
+ status: 'running',
388
+ agent: 'reviewer',
389
+ model: 'claude-sonnet-4.7',
390
+ elapsedMs: 0,
391
+ toolCallCount: 2,
392
+ startedAt: 0,
393
+ },
394
+ ],
395
+ }),
396
+ {
397
+ status: 200,
398
+ headers: { 'content-type': 'application/json' },
399
+ },
400
+ )
401
+ },
402
+ { preconnect: originalFetch.preconnect },
403
+ )
404
+
405
+ globalThis.fetch = stubFetch as unknown as typeof fetch
406
+
407
+ await plugin(controls.api, undefined, makePluginMeta())
408
+
409
+ const [command] = controls.commandFactories[0]()
410
+ command.onSelect?.()
411
+
412
+ expect(controls.dialogReplacements).toHaveLength(1)
413
+
414
+ const listRender = await testRender(
415
+ () => controls.dialogReplacements[0].render(),
416
+ {
417
+ width: 120,
418
+ height: 20,
419
+ useThread: false,
420
+ },
421
+ )
422
+
423
+ await listRender.renderOnce()
424
+
425
+ const listFrame = await waitForFrame({
426
+ renderOnce: listRender.renderOnce,
427
+ idle: () => listRender.renderer.idle(),
428
+ captureCharFrame: listRender.captureCharFrame,
429
+ includes: '2 running · 0 recent',
430
+ })
431
+ expect(listFrame).toContain('cpl_beta')
432
+ expect(listFrame).toContain('Esc close')
433
+ expect(listFrame).not.toContain('navigate')
434
+ expect(listFrame).not.toContain('c cancel')
435
+ expect(controls.dialogReplacements).toHaveLength(1)
436
+ expect(controls.dialogSizes).toEqual(['large'])
437
+ })
438
+ })