opencode-copilot-delegate 0.12.2 → 0.13.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.
@@ -1,5 +1,4 @@
1
1
  import { readFile } from 'node:fs/promises'
2
- import { homedir } from 'node:os'
3
2
  import { join } from 'node:path'
4
3
  import type { ZodIssue, ZodType } from 'zod'
5
4
  import {
@@ -13,6 +12,10 @@ import {
13
12
  type TasksListResponse,
14
13
  TasksListResponseSchema,
15
14
  } from '../runtime/rpc-contract'
15
+ import {
16
+ defaultPortFileBaseDir,
17
+ defaultSessionDiscriminator,
18
+ } from '../runtime/rpc-paths'
16
19
 
17
20
  type CreateRpcClientOptions = {
18
21
  baseDir?: string
@@ -83,20 +86,9 @@ export class RpcAuthError extends RpcServerError {
83
86
  }
84
87
  }
85
88
 
86
- function defaultBaseDir(): string {
87
- const cacheHome =
88
- process.env.XDG_CACHE_HOME ?? join(process.env.HOME ?? homedir(), '.cache')
89
-
90
- return join(cacheHome, 'opencode', 'copilot-delegate')
91
- }
92
-
93
- function defaultSessionDiscriminator(): string {
94
- return process.env.OPENCODE_SESSION_ID ?? String(process.pid)
95
- }
96
-
97
89
  function resolvePortFilePath(options: CreateRpcClientOptions): string {
98
90
  return join(
99
- options.baseDir ?? defaultBaseDir(),
91
+ options.baseDir ?? defaultPortFileBaseDir(),
100
92
  options.sessionDiscriminator ?? defaultSessionDiscriminator(),
101
93
  'server-port.json',
102
94
  )
@@ -0,0 +1,243 @@
1
+ /** @jsxImportSource @opentui/solid */
2
+
3
+ import type { TuiPluginApi } from '@opencode-ai/plugin/tui'
4
+ import type { RpcClient } from './rpc-client'
5
+ import {
6
+ formatTaskDescription,
7
+ formatTaskFooter,
8
+ type StatusTask,
9
+ } from './status-format'
10
+
11
+ /**
12
+ * `/copilot-status` UI built from the host's own dialog components
13
+ * (`DialogSelect`, `DialogConfirm`, `DialogAlert`).
14
+ *
15
+ * The host owns theming, keyboard handling, and dialog teardown (including
16
+ * Esc). This module must therefore never call `api.ui.dialog.clear()` and
17
+ * must never pass an `onClose` to `api.ui.dialog.replace(...)`: feeding
18
+ * host-owned close handling back into `clear()` re-entered dialog teardown
19
+ * and froze the TUI on Esc (see
20
+ * docs/solutions/ui-bugs/re-entrant-dialog-close-froze-copilot-status-on-escape-2026-05-02.md).
21
+ *
22
+ * Host `DialogConfirm` / `DialogAlert` call `dialog.clear()` themselves right
23
+ * after `onConfirm` / `onCancel` returns, so any follow-up dialog is opened on
24
+ * a deferred tick instead of synchronously from those callbacks.
25
+ */
26
+
27
+ /** Delay before reopening a dialog after a host confirm/alert closes itself. */
28
+ const REOPEN_DELAY_MS = 50
29
+
30
+ export type StatusDialogsRpc = Pick<RpcClient, 'tasksList' | 'tasksCancel'>
31
+
32
+ export type StatusDialogsOptions = {
33
+ rpc: StatusDialogsRpc
34
+ /** Schedules `fn` after the host's own close has finished. Returns a canceller. */
35
+ defer?: (fn: () => void) => () => void
36
+ now?: () => number
37
+ }
38
+
39
+ export type StatusDialogs = {
40
+ openList: (currentTaskId?: string) => void
41
+ dispose: () => void
42
+ }
43
+
44
+ type DialogApi = Pick<TuiPluginApi, 'ui'>
45
+
46
+ function errorMessage(error: unknown): string {
47
+ if (error instanceof Error && error.message.trim().length > 0) {
48
+ return error.message.trim()
49
+ }
50
+
51
+ return 'Unknown RPC error.'
52
+ }
53
+
54
+ function warnNonFatal(error: unknown) {
55
+ // The TUI half has no structured log channel; a failure here must never
56
+ // take the host down, so it is reported and swallowed.
57
+ console.warn(
58
+ `[opencode-copilot-delegate] /copilot-status dialog failed: ${errorMessage(error)}`,
59
+ )
60
+ }
61
+
62
+ function defaultDefer(fn: () => void): () => void {
63
+ const handle = setTimeout(fn, REOPEN_DELAY_MS)
64
+
65
+ return () => {
66
+ clearTimeout(handle)
67
+ }
68
+ }
69
+
70
+ export function createStatusDialogs(
71
+ api: DialogApi,
72
+ options: StatusDialogsOptions,
73
+ ): StatusDialogs {
74
+ const { rpc } = options
75
+ const defer = options.defer ?? defaultDefer
76
+ const now = options.now ?? (() => Date.now())
77
+ const pending = new Set<() => void>()
78
+ let disposed = false
79
+ let generation = 0
80
+
81
+ const deferred = (fn: () => void) => {
82
+ const cancel = defer(() => {
83
+ pending.delete(cancel)
84
+ if (disposed) {
85
+ return
86
+ }
87
+
88
+ try {
89
+ fn()
90
+ } catch (error) {
91
+ warnNonFatal(error)
92
+ }
93
+ })
94
+ pending.add(cancel)
95
+ }
96
+
97
+ const showAlert = (
98
+ title: string,
99
+ message: string,
100
+ onConfirm?: () => void,
101
+ ) => {
102
+ api.ui.dialog.setSize('medium')
103
+ api.ui.dialog.replace(() => (
104
+ <api.ui.DialogAlert
105
+ title={title}
106
+ message={message}
107
+ onConfirm={onConfirm}
108
+ />
109
+ ))
110
+ }
111
+
112
+ const showCancelFailure = (task: StatusTask, message: string) => {
113
+ showAlert(
114
+ `Could not cancel ${task.taskId}`,
115
+ message,
116
+ // The host closes the alert itself; come back to the list afterwards.
117
+ () => {
118
+ deferred(() => {
119
+ openList(task.taskId)
120
+ })
121
+ },
122
+ )
123
+ }
124
+
125
+ const cancelTask = async (task: StatusTask) => {
126
+ let failure: string | undefined
127
+
128
+ try {
129
+ const response = await rpc.tasksCancel(task.taskId)
130
+
131
+ // "no such task" means it already finished; the refreshed list shows that.
132
+ if (!response.cancelled && response.error !== 'no such task') {
133
+ failure = response.error ?? 'Unknown RPC error.'
134
+ }
135
+ } catch (error) {
136
+ failure = errorMessage(error)
137
+ }
138
+
139
+ if (disposed) {
140
+ return
141
+ }
142
+
143
+ // The host's DialogConfirm clears itself after `onConfirm`; defer so the
144
+ // next dialog lands after that close rather than inside it.
145
+ deferred(() => {
146
+ if (failure === undefined) {
147
+ openList()
148
+ } else {
149
+ showCancelFailure(task, failure)
150
+ }
151
+ })
152
+ }
153
+
154
+ const openConfirm = (task: StatusTask) => {
155
+ api.ui.dialog.setSize('medium')
156
+ api.ui.dialog.replace(() => (
157
+ <api.ui.DialogConfirm
158
+ title={`Cancel Copilot delegation ${task.taskId}?`}
159
+ message="Confirm stops the running Copilot process. Cancel keeps it running."
160
+ onConfirm={() => {
161
+ void cancelTask(task)
162
+ }}
163
+ onCancel={() => {
164
+ deferred(() => {
165
+ openList(task.taskId)
166
+ })
167
+ }}
168
+ />
169
+ ))
170
+ }
171
+
172
+ const renderList = (tasks: StatusTask[], currentTaskId?: string) => {
173
+ if (tasks.length === 0) {
174
+ showAlert(
175
+ 'No Copilot delegations are running.',
176
+ 'Start one with the copilot_delegate tool, then reopen /copilot-status.',
177
+ )
178
+ return
179
+ }
180
+
181
+ const nowMs = now()
182
+ const byId = new Map(tasks.map((task) => [task.taskId, task]))
183
+ const running = tasks.filter((task) => task.status === 'running').length
184
+
185
+ api.ui.dialog.setSize('large')
186
+ api.ui.dialog.replace(() => (
187
+ <api.ui.DialogSelect<string>
188
+ title={`Copilot delegations (${running} running)`}
189
+ current={currentTaskId}
190
+ options={tasks.map((task) => ({
191
+ title: task.taskId,
192
+ value: task.taskId,
193
+ description: formatTaskDescription(task),
194
+ footer: formatTaskFooter(task, nowMs),
195
+ // Only a running task can be cancelled.
196
+ disabled: task.status !== 'running',
197
+ }))}
198
+ onSelect={(option) => {
199
+ const task = byId.get(option.value)
200
+
201
+ if (task?.status === 'running') {
202
+ openConfirm(task)
203
+ }
204
+ }}
205
+ />
206
+ ))
207
+ }
208
+
209
+ const openList = (currentTaskId?: string) => {
210
+ const mine = ++generation
211
+
212
+ void (async () => {
213
+ let tasks: StatusTask[]
214
+
215
+ try {
216
+ tasks = (await rpc.tasksList()).tasks
217
+ } catch (error) {
218
+ if (!disposed && mine === generation) {
219
+ showAlert('Status unavailable.', errorMessage(error))
220
+ }
221
+ return
222
+ }
223
+
224
+ // A newer open, or disposal, supersedes this load.
225
+ if (disposed || mine !== generation) {
226
+ return
227
+ }
228
+
229
+ renderList(tasks, currentTaskId)
230
+ })().catch(warnNonFatal)
231
+ }
232
+
233
+ return {
234
+ openList,
235
+ dispose() {
236
+ disposed = true
237
+ for (const cancel of pending) {
238
+ cancel()
239
+ }
240
+ pending.clear()
241
+ },
242
+ }
243
+ }
@@ -1,6 +1,6 @@
1
- import type { TasksListResponse } from '../../runtime/rpc-contract'
1
+ import type { TasksListResponse } from '../runtime/rpc-contract'
2
2
 
3
- export type ModalListTask = TasksListResponse['tasks'][number]
3
+ export type StatusTask = TasksListResponse['tasks'][number]
4
4
 
5
5
  export function displayValue(value: string): string {
6
6
  const trimmed = value.trim()
@@ -26,7 +26,7 @@ export function formatElapsed(elapsedMs: number): string {
26
26
  return `${totalSeconds}s`
27
27
  }
28
28
 
29
- function formatStatus(status: ModalListTask['status']): string {
29
+ export function formatStatus(status: StatusTask['status']): string {
30
30
  return status === 'running' ? `● ${status}` : status
31
31
  }
32
32
 
@@ -34,8 +34,12 @@ export function formatToolCalls(toolCallCount: number): string {
34
34
  return `${toolCallCount} ${toolCallCount === 1 ? 'call' : 'calls'}`
35
35
  }
36
36
 
37
- export function formatRowText(task: ModalListTask, nowMs: number): string {
38
- const elapsed = Math.max(0, nowMs - task.startedAt)
37
+ /** Secondary line of a list option: who is running it and how busy it is. */
38
+ export function formatTaskDescription(task: StatusTask): string {
39
+ return `${displayValue(task.agent)} · ${displayValue(task.model)} · ${formatToolCalls(task.toolCallCount)}`
40
+ }
39
41
 
40
- return `${formatStatus(task.status)} ${task.taskId} ${displayValue(task.agent)} ${displayValue(task.model)} ${formatElapsed(elapsed)} ${formatToolCalls(task.toolCallCount)}`
42
+ /** Right-hand footer of a list option: status and elapsed time. */
43
+ export function formatTaskFooter(task: StatusTask, nowMs: number): string {
44
+ return `${formatStatus(task.status)} · ${formatElapsed(Math.max(0, nowMs - task.startedAt))}`
41
45
  }
@@ -1,12 +0,0 @@
1
- /** @jsxImportSource @opentui/solid */
2
- import type { RpcClient } from '../rpc-client';
3
- import type { ModalListTask } from './row';
4
- type ConfirmCardProps = {
5
- task: ModalListTask;
6
- rpc: Pick<RpcClient, 'tasksCancel'>;
7
- onConfirm: () => void;
8
- onCancel: () => void;
9
- onDismissAfterError: () => void;
10
- };
11
- export declare function ConfirmCard(props: ConfirmCardProps): any;
12
- export default ConfirmCard;
@@ -1,16 +0,0 @@
1
- /** @jsxImportSource @opentui/solid */
2
- import type { RpcClient } from '../rpc-client';
3
- export type ModalListClock = {
4
- now(): number;
5
- setInterval(fn: () => void, delayMs: number): unknown;
6
- clearInterval(handle: unknown): void;
7
- };
8
- type ModalListProps = {
9
- rpc: Pick<RpcClient, 'tasksList'>;
10
- onClose: () => void;
11
- onLoadError?: (error: unknown) => void;
12
- initialTaskId?: string;
13
- clock?: ModalListClock;
14
- };
15
- export declare function ModalList(props: ModalListProps): any;
16
- export default ModalList;
@@ -1,6 +0,0 @@
1
- import type { TasksListResponse } from '../../runtime/rpc-contract';
2
- export type ModalListTask = TasksListResponse['tasks'][number];
3
- export declare function displayValue(value: string): string;
4
- export declare function formatElapsed(elapsedMs: number): string;
5
- export declare function formatToolCalls(toolCallCount: number): string;
6
- export declare function formatRowText(task: ModalListTask, nowMs: number): string;
@@ -1,252 +0,0 @@
1
- /** @jsxImportSource @opentui/solid */
2
-
3
- import {
4
- type KeyEvent,
5
- TextAttributes,
6
- type TextRenderable,
7
- } from '@opentui/core'
8
- import { useRenderer } from '@opentui/solid'
9
- import { onCleanup } from 'solid-js'
10
- import type { RpcClient } from '../rpc-client'
11
- import type { ModalListTask } from './row'
12
-
13
- type ConfirmCardProps = {
14
- task: ModalListTask
15
- rpc: Pick<RpcClient, 'tasksCancel'>
16
- onConfirm: () => void
17
- onCancel: () => void
18
- onDismissAfterError: () => void
19
- }
20
-
21
- type ConfirmState =
22
- | {
23
- kind: 'confirm'
24
- focusedAction: 'confirm' | 'cancel'
25
- busy: boolean
26
- }
27
- | {
28
- kind: 'error'
29
- message: string
30
- }
31
-
32
- function errorMessage(error: unknown): string {
33
- if (error instanceof Error && error.message.trim().length > 0) {
34
- return error.message.trim()
35
- }
36
-
37
- return 'Unknown RPC error.'
38
- }
39
-
40
- function matchesKey(key: KeyEvent, expected: string): boolean {
41
- return (
42
- key.name === expected || key.sequence === expected || key.raw === expected
43
- )
44
- }
45
-
46
- function isActivateKey(key: KeyEvent): boolean {
47
- return (
48
- matchesKey(key, 'return') ||
49
- matchesKey(key, 'enter') ||
50
- matchesKey(key, 'space') ||
51
- key.sequence === ' ' ||
52
- key.raw === ' '
53
- )
54
- }
55
-
56
- function isLeftKey(key: KeyEvent): boolean {
57
- return matchesKey(key, 'left')
58
- }
59
-
60
- function isRightKey(key: KeyEvent): boolean {
61
- return matchesKey(key, 'right')
62
- }
63
-
64
- function updateText(
65
- node: TextRenderable | undefined,
66
- content: string,
67
- attributes = TextAttributes.NONE,
68
- ) {
69
- if (!node) {
70
- return
71
- }
72
-
73
- node.content = content
74
- node.attributes = attributes
75
- node.visible = content.length > 0
76
- }
77
-
78
- export function ConfirmCard(props: ConfirmCardProps) {
79
- const renderer = useRenderer()
80
- const title = `Cancel Copilot delegation ${props.task.taskId}?`
81
- const state: { value: ConfirmState } = {
82
- value: {
83
- kind: 'confirm',
84
- focusedAction: 'confirm',
85
- busy: false,
86
- },
87
- }
88
-
89
- let confirmText: TextRenderable | undefined
90
- let cancelText: TextRenderable | undefined
91
- let errorText: TextRenderable | undefined
92
- let dismissText: TextRenderable | undefined
93
-
94
- const renderView = () => {
95
- const currentState = state.value
96
-
97
- if (currentState.kind === 'error') {
98
- updateText(confirmText, '')
99
- updateText(cancelText, '')
100
- updateText(errorText, `Cancel failed: ${currentState.message}`)
101
- updateText(dismissText, 'Dismiss', TextAttributes.INVERSE)
102
- renderer.requestRender()
103
- return
104
- }
105
-
106
- updateText(
107
- confirmText,
108
- 'Cancel Task',
109
- currentState.focusedAction === 'confirm'
110
- ? TextAttributes.INVERSE
111
- : TextAttributes.NONE,
112
- )
113
- updateText(
114
- cancelText,
115
- 'Keep Running',
116
- currentState.focusedAction === 'cancel'
117
- ? TextAttributes.INVERSE
118
- : TextAttributes.NONE,
119
- )
120
- updateText(errorText, '')
121
- updateText(dismissText, '')
122
- renderer.requestRender()
123
- }
124
-
125
- const confirmCancel = async () => {
126
- if (state.value.kind !== 'confirm' || state.value.busy) {
127
- return
128
- }
129
-
130
- state.value = { ...state.value, busy: true }
131
-
132
- try {
133
- const response = await props.rpc.tasksCancel(props.task.taskId)
134
-
135
- if (response.cancelled) {
136
- props.onConfirm()
137
- return
138
- }
139
-
140
- if (response.error === 'no such task') {
141
- props.onConfirm()
142
- return
143
- }
144
-
145
- state.value = {
146
- kind: 'error',
147
- message: response.error ?? 'Unknown RPC error.',
148
- }
149
- } catch (error) {
150
- state.value = { kind: 'error', message: errorMessage(error) }
151
- }
152
-
153
- renderView()
154
- }
155
-
156
- const activateFocusedAction = () => {
157
- if (state.value.kind === 'error') {
158
- props.onDismissAfterError()
159
- return
160
- }
161
-
162
- if (state.value.focusedAction === 'confirm') {
163
- void confirmCancel()
164
- return
165
- }
166
-
167
- props.onCancel()
168
- }
169
-
170
- const focusConfirm = () => {
171
- if (state.value.kind !== 'confirm' || state.value.busy) {
172
- return
173
- }
174
-
175
- state.value = { ...state.value, focusedAction: 'confirm' }
176
- renderView()
177
- }
178
-
179
- const focusCancel = () => {
180
- if (state.value.kind !== 'confirm' || state.value.busy) {
181
- return
182
- }
183
-
184
- state.value = { ...state.value, focusedAction: 'cancel' }
185
- renderView()
186
- }
187
-
188
- const handleKeyPress = (key: KeyEvent) => {
189
- if (state.value.kind === 'confirm' && !state.value.busy) {
190
- if (isLeftKey(key)) {
191
- key.preventDefault()
192
- focusConfirm()
193
- return
194
- }
195
-
196
- if (isRightKey(key)) {
197
- key.preventDefault()
198
- focusCancel()
199
- return
200
- }
201
- }
202
-
203
- if (isActivateKey(key)) {
204
- key.preventDefault()
205
- activateFocusedAction()
206
- }
207
- }
208
-
209
- renderer.keyInput.on('keypress', handleKeyPress)
210
-
211
- onCleanup(() => {
212
- renderer.keyInput.off('keypress', handleKeyPress)
213
- })
214
-
215
- return (
216
- <box flexDirection="column" gap={1} padding={1} width="100%">
217
- <text>{title}</text>
218
- {/* biome-ignore lint/a11y/noStaticElementInteractions: OpenTUI text nodes handle terminal mouse events directly. */}
219
- <text
220
- ref={confirmText}
221
- attributes={TextAttributes.INVERSE}
222
- onMouseUp={() => {
223
- focusConfirm()
224
- void confirmCancel()
225
- }}
226
- >
227
- Cancel Task
228
- </text>
229
- {/* biome-ignore lint/a11y/noStaticElementInteractions: OpenTUI text nodes handle terminal mouse events directly. */}
230
- <text
231
- ref={cancelText}
232
- onMouseUp={() => {
233
- focusCancel()
234
- props.onCancel()
235
- }}
236
- >
237
- Keep Running
238
- </text>
239
- <text ref={errorText} visible={false} />
240
- {/* biome-ignore lint/a11y/noStaticElementInteractions: OpenTUI text nodes handle terminal mouse events directly. */}
241
- <text
242
- ref={dismissText}
243
- visible={false}
244
- onMouseUp={() => {
245
- props.onDismissAfterError()
246
- }}
247
- />
248
- </box>
249
- )
250
- }
251
-
252
- export default ConfirmCard