opencode-copilot-delegate 0.9.0 → 0.10.0

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