opencode-progress-panel 0.0.0-stage → 0.1.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.
package/README.md CHANGED
@@ -1,3 +1,107 @@
1
- # Temporary Holding Version
1
+ # opencode-progress-panel
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Полоса прогресса в боковой панели OpenCode TUI. Агент создаёт задачи через инструменты `pw_*`, плагин опрашивает их shell-команды и показывает проценты в секции Sidebar -> content.
4
+
5
+ ## Требования
6
+
7
+ - OpenCode V2 (2.4+).
8
+ - Node или Bun, которые поставляет сам OpenCode. Отдельная установка не нужна.
9
+
10
+ ## Установка
11
+
12
+ Плагин живёт в этом репозитории. Есть два способа.
13
+
14
+ 1. Скопировать или слинковать каталог в проект:
15
+
16
+ ```sh
17
+ mkdir -p .opencode/plugins
18
+ ln -s /absolute/path/to/23-opencode-progress-plugin .opencode/plugins/progress-panel
19
+ ```
20
+
21
+ Содержимое `.opencode/plugins/` загружается автоматически.
22
+
23
+ 2. Указать пакет в `opencode.jsonc`:
24
+
25
+ ```jsonc
26
+ {
27
+ "plugins": [
28
+ { "package": "/absolute/path/to/23-opencode-progress-plugin" }
29
+ ]
30
+ }
31
+ ```
32
+
33
+ `exports` в `package.json` отдают три части: серверную (`.`), TUI (`./tui`) и RPC-контракт (`./rpc`).
34
+
35
+ ## Инструменты
36
+
37
+ | Инструмент | Параметры | Результат |
38
+ | --- | --- | --- |
39
+ | `pw_create` | `name`, `shell`, `color?` | `{ id }` |
40
+ | `pw_edit` | `id`, `name?`, `shell?`, `color?` | обновлённое поле |
41
+ | `pw_remove` | `id` | `{ ok: true }` |
42
+ | `pw_list` | - | `[{ id, name, shell, percent, color }]` |
43
+ | `pw_clean` | - | `{ ok: true, removed }` |
44
+
45
+ `pw_clean` удаляет все поля и останавливает их опрос одним вызовом.
46
+
47
+ `name` - от 1 до 12 символов.
48
+
49
+ `color` - необязательный индекс палитры `0..4`. Одно и то же число даёт один и тот же цвет, поэтому агент может группировать задачи по цвету. Без `color` используется акцентный цвет темы. Завершённые задачи всё равно показывают свой текст цветом success.
50
+
51
+ ## Контракт shell-команды
52
+
53
+ Команда должна напечатать число 0-100. Имя необязательно: если его нет, поле сохраняет своё текущее название.
54
+
55
+ ```sh
56
+ printf '42'
57
+ ```
58
+
59
+ Если команда должна сама переименовать поле, добавь имя после числа (1-12 символов) - оно заменит текущее:
60
+
61
+ ```sh
62
+ printf '42 Build'
63
+ ```
64
+
65
+ Берётся первая строка, которая начинается с числа; строки без числа (например, отладочный `echo "step=$s"`) пропускаются. Дробные значения округляются (`22.0` -> 22). Если команда завершилась ошибкой или числа нет ни в одной строке, показывается 0%.
66
+
67
+ ## Опрос
68
+
69
+ Следующий опрос планируется через `max(1000 мс, 1.5 * время предыдущего выполнения)` после завершения предыдущего. Опросы одного поля не пересекаются. У каждого поля свой таймер, он сбрасывается при редактировании и удалении поля.
70
+
71
+ ## TUI
72
+
73
+ Секция появляется в Sidebar -> content. Заголовок виден всегда (и при пустом списке). Если полей нет, под развёрнутым заголовком выводится `no tasks running`.
74
+
75
+ Иначе сверху жирный заголовок. В развёрнутом виде: `▼ Tasks in progress:`, ниже одна строка на поле. Полоса теперь сплошная и без скобок: имя слева, процент справа, между ними цветная полоса во всю оставшуюся ширину сайдбара. Заполненная часть окрашена в цвет задачи (акцентный цвет темы, если `color` не задан), незаполненная - в мягкий приподнятый фон темы (`background.raised.high`).
76
+
77
+ Заголовок складывается по клику. В свёрнутом виде остаётся только строка `▶ Tasks in progress: 2/3`, где первое число - задачи всё ещё в работе (процент < 100), второе - общее число задач. Завершённые задачи (100%) показываются цветом success.
78
+
79
+ ## Сон системы
80
+
81
+ На macOS плагин держит один процесс `caffeinate -i`, пока хотя бы у одной задачи процент < 100. Процесс один на все задачи: он стартует, когда появляется первая незавершённая задача, и завершается, когда все задачи достигли 100%, удалены или очищены (`pw_clean`) либо плагин выгружается. На других платформах это no-op.
82
+
83
+ Жёсткое убийство сервера OpenCode не даёт выполнить очистку, поэтому `caffeinate` может остаться висеть. Убрать его можно командой `pkill caffeinate`.
84
+
85
+ ## Уведомление о завершении
86
+
87
+ Когда задача впервые достигает 100%, сессия, создавшая её, получает системное сообщение `Progress task "<name>" completed (100%).` (доставка: steer, сообщение попадает к агенту перед следующим вызовом модели, даже посреди работы), поэтому агент видит его в чате. Уведомление приходит один раз на завершение: если процент опускается ниже 100 и задача снова достигает 100%, уведомление срабатывает заново.
88
+
89
+ ## Сохранение состояния
90
+
91
+ Поля сохраняются в plugin storage OpenCode отдельно для каждого проекта (ключ `fields:<каталог проекта>`). Перезагрузка плагина (OpenCode следит за его файлами) и перезапуск сервера не теряют задачи: при загрузке поля возвращаются, опрос стартует заново, а проценты берутся из последнего опроса перед сохранением. После восстановления TUI сразу получает актуальный список, поэтому старые полосы не зависают.
92
+
93
+ Уведомление о завершении для восстановленного поля продолжает работать, если сессия, создавшая его, ещё существует; иначе сообщение просто отбрасывается.
94
+
95
+ ## Архитектура
96
+
97
+ ```
98
+ agent
99
+ -> инструменты pw_*
100
+ -> store + поллер (процесс сервера, состояние в plugin storage)
101
+ -> RPC list / changed
102
+ -> слот sidebar.content (процесс TUI)
103
+ ```
104
+
105
+ ## Ограничения
106
+
107
+ - Поля привязаны к проекту (локации): `pw_*` в проекте видят только поля этого проекта, а сайдбар показывает поля текущего проекта сессии.
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "opencode-progress-panel",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Progress bars in the OpenCode TUI sidebar, driven by the agent through pw_* tools.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "exports": {
8
+ ".": "./src/server.ts",
9
+ "./tui": "./src/tui.tsx",
10
+ "./rpc": "./src/rpc.ts"
11
+ },
12
+ "files": [
13
+ "src",
14
+ "README.md"
15
+ ],
16
+ "scripts": {
17
+ "test": "bun test",
18
+ "typecheck": "tsc --noEmit"
19
+ },
20
+ "dependencies": {
21
+ "@opencode/plugin": "^2.4.1"
22
+ },
23
+ "devDependencies": {
24
+ "@opencode/theme": "^2.4.1",
25
+ "@opentui/core": ">=0.8.0",
26
+ "@opentui/solid": ">=0.8.0",
27
+ "@types/bun": "^1.4.5",
28
+ "@types/node": "^24.0.0",
29
+ "solid-js": "^1.9.0",
30
+ "typescript": "^5.9.0"
31
+ }
32
+ }
@@ -0,0 +1,56 @@
1
+ import { spawn } from "node:child_process"
2
+ import type { ChildProcess } from "node:child_process"
3
+
4
+ export type Spawner = (command: string, args: string[]) => ChildProcess
5
+
6
+ /** Keeps a single `caffeinate -i` alive while work is in progress (macOS only). */
7
+ export class Caffeinate {
8
+ private child: ChildProcess | undefined
9
+ private readonly spawner: Spawner
10
+ private readonly platform: NodeJS.Platform
11
+
12
+ constructor(
13
+ spawner: Spawner = (command, args) => spawn(command, args, { stdio: "ignore" }),
14
+ platform: NodeJS.Platform = process.platform,
15
+ ) {
16
+ this.spawner = spawner
17
+ this.platform = platform
18
+ }
19
+
20
+ update(active: boolean): void {
21
+ if (active) this.start()
22
+ else this.stop()
23
+ }
24
+
25
+ dispose(): void {
26
+ this.stop()
27
+ }
28
+
29
+ private start(): void {
30
+ if (this.platform !== "darwin" || this.child) return
31
+ try {
32
+ const child = this.spawner("caffeinate", ["-i"])
33
+ this.child = child
34
+ child.on("exit", () => {
35
+ if (this.child === child) this.child = undefined
36
+ })
37
+ // Spawn failures arrive as an async error event; without a listener Node throws.
38
+ child.on("error", () => {
39
+ if (this.child === child) this.child = undefined
40
+ })
41
+ } catch {
42
+ this.child = undefined
43
+ }
44
+ }
45
+
46
+ private stop(): void {
47
+ const child = this.child
48
+ this.child = undefined
49
+ if (!child) return
50
+ try {
51
+ child.kill()
52
+ } catch {
53
+ // already gone
54
+ }
55
+ }
56
+ }
@@ -0,0 +1,33 @@
1
+ /** Longest allowed progress field name. */
2
+ export const NAME_MAX = 12
3
+
4
+ /** A name must be 1-12 characters after trimming. */
5
+ export function validName(name: string): boolean {
6
+ const length = name.trim().length
7
+ return length >= 1 && length <= NAME_MAX
8
+ }
9
+
10
+ /**
11
+ * Reads `<percent> [name]` from the first line that starts with a number.
12
+ * Lines without a leading number are ignored, so debug output before the
13
+ * value is harmless. Decimals are rounded. Anything unparseable yields 0.
14
+ */
15
+ export function parseOutput(text: string): { percent: number; name?: string } {
16
+ for (const raw of text.split(/\r?\n/)) {
17
+ const match = /^(\d{1,3}(?:\.\d+)?)(?:\s+(.+))?$/.exec(raw.trim())
18
+ if (!match) continue
19
+
20
+ const value = Number(match[1])
21
+ if (!Number.isFinite(value)) continue
22
+
23
+ const percent = Math.min(100, Math.max(0, Math.round(value)))
24
+ const name = match[2]?.trim().slice(0, NAME_MAX)
25
+ return name ? { percent, name } : { percent }
26
+ }
27
+ return { percent: 0 }
28
+ }
29
+
30
+ /** Waits at least a second, otherwise 1.5x the last run so slow commands poll less. */
31
+ export function nextDelay(durationMs: number): number {
32
+ return Math.max(1000, Math.round(durationMs * 1.5))
33
+ }
package/src/rpc.ts ADDED
@@ -0,0 +1,51 @@
1
+ import { Rpc } from "@opencode/plugin"
2
+
3
+ /** Highest palette index the agent may pass as `color` (0..COLOR_MAX). */
4
+ export const COLOR_MAX = 4
5
+
6
+ /** One progress field as shown in the TUI and reported by `pw_list`. */
7
+ export interface ProgressField {
8
+ id: string
9
+ name: string
10
+ shell: string
11
+ percent: number
12
+ /** Palette index chosen by the agent, or null for the theme's accent color. */
13
+ color: number | null
14
+ }
15
+
16
+ const Field = {
17
+ type: "object",
18
+ properties: {
19
+ id: { type: "string" },
20
+ name: { type: "string" },
21
+ shell: { type: "string" },
22
+ percent: { type: "number" },
23
+ color: { anyOf: [{ type: "integer" }, { type: "null" }] },
24
+ },
25
+ required: ["id", "name", "shell", "percent", "color"],
26
+ additionalProperties: false,
27
+ } as const
28
+
29
+ const Snapshot = {
30
+ type: "object",
31
+ properties: { fields: { type: "array", items: Field } },
32
+ required: ["fields"],
33
+ additionalProperties: false,
34
+ } as const
35
+
36
+ /**
37
+ * Channel between the server part (owns the fields) and the TUI part.
38
+ * The TUI calls `list` once, then follows the `changed` event snapshots.
39
+ */
40
+ export const Progress = Rpc.define({
41
+ id: "progress-panel",
42
+ methods: {
43
+ list: {
44
+ input: { type: "object", properties: {}, additionalProperties: false },
45
+ output: Snapshot,
46
+ },
47
+ },
48
+ events: {
49
+ changed: { schema: Snapshot },
50
+ },
51
+ })
package/src/server.ts ADDED
@@ -0,0 +1,243 @@
1
+ import { execFile } from "node:child_process"
2
+ import { Plugin } from "@opencode/plugin"
3
+ import { ProgressStore } from "./store.js"
4
+ import type { CompletedField } from "./store.js"
5
+ import { Caffeinate } from "./caffeinate.js"
6
+ import { validName } from "./progress.js"
7
+ import { Progress, COLOR_MAX } from "./rpc.js"
8
+ import type { ProgressField } from "./rpc.js"
9
+
10
+ function execShell(shell: string): Promise<string> {
11
+ return new Promise((resolve, reject) => {
12
+ execFile("/bin/sh", ["-c", shell], { timeout: 10_000, maxBuffer: 64 * 1024 }, (error, stdout) => {
13
+ if (error) reject(error)
14
+ else resolve(stdout)
15
+ })
16
+ })
17
+ }
18
+
19
+ function stringField(input: unknown, key: string): string | undefined {
20
+ if (typeof input !== "object" || input === null) return undefined
21
+ const value = (input as Record<string, unknown>)[key]
22
+ return typeof value === "string" ? value : undefined
23
+ }
24
+
25
+ function requireString(input: unknown, key: string): string {
26
+ const value = stringField(input, key)
27
+ if (value === undefined) throw new Error(`${key} is required`)
28
+ return value
29
+ }
30
+
31
+ function requireId(input: unknown): string {
32
+ return requireString(input, "id")
33
+ }
34
+
35
+ function validateName(name: string): void {
36
+ if (!validName(name)) throw new Error("name must be 1-12 characters")
37
+ }
38
+
39
+ function validateShell(shell: string): void {
40
+ if (shell.trim().length === 0) throw new Error("shell must not be empty")
41
+ }
42
+
43
+ function colorField(input: unknown): number | null | undefined {
44
+ if (typeof input !== "object" || input === null) return undefined
45
+ const value = (input as Record<string, unknown>).color
46
+ if (value === undefined) return undefined
47
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > COLOR_MAX) {
48
+ throw new Error(`color must be an integer 0-${COLOR_MAX}`)
49
+ }
50
+ return value
51
+ }
52
+
53
+ const COLOR_HINT =
54
+ `color is an optional palette index 0-${COLOR_MAX} used to group tasks by color in the sidebar ` +
55
+ "(same number = same color)."
56
+
57
+ const SHELL_HINT =
58
+ "The shell command runs through /bin/sh and must print a percent 0-100 on a line. " +
59
+ "Decimals are rounded and lines without a leading number are ignored, so debug output is harmless. " +
60
+ "An optional name (1-12 characters) after the percent replaces the field name, " +
61
+ "for example: printf '42' or printf '42 Build'. No matching line is shown as 0%."
62
+
63
+ function parseSaved(value: unknown): CompletedField[] {
64
+ if (!Array.isArray(value)) return []
65
+ const entries: CompletedField[] = []
66
+ for (const raw of value) {
67
+ if (typeof raw !== "object" || raw === null) continue
68
+ const entry = raw as Record<string, unknown>
69
+ const { id, name, shell, sessionID, percent, color } = entry
70
+ if (typeof id !== "string" || id.length === 0) continue
71
+ if (typeof name !== "string" || !validName(name)) continue
72
+ if (typeof shell !== "string" || shell.trim().length === 0) continue
73
+ if (typeof sessionID !== "string" || sessionID.length === 0) continue
74
+ if (typeof percent !== "number" || !Number.isFinite(percent)) continue
75
+ const palette =
76
+ color === undefined || color === null
77
+ ? null
78
+ : typeof color === "number" && Number.isInteger(color) && color >= 0 && color <= COLOR_MAX
79
+ ? color
80
+ : undefined
81
+ if (palette === undefined) continue
82
+ entries.push({ id, name, shell, percent, color: palette, sessionID })
83
+ }
84
+ return entries
85
+ }
86
+
87
+ export default Plugin.define({
88
+ id: "progress-panel",
89
+ async setup(ctx) {
90
+ let store: ProgressStore | undefined
91
+ const caffeinate = new Caffeinate()
92
+ const storageKey = `fields:${ctx.location.directory}`
93
+ const saved = await ctx.storage.get(storageKey)
94
+
95
+ const registration = await ctx.rpc.register(Progress, {
96
+ list: async () => ({ fields: store?.list() ?? [] }),
97
+ })
98
+
99
+ const publish = (fields: ProgressField[]) => {
100
+ void registration.events.emit("changed", { fields }).catch(() => {})
101
+ caffeinate.update(fields.some((field) => field.percent < 100))
102
+ if (store !== undefined) {
103
+ // Spread into plain objects so the snapshot satisfies the JSON storage type.
104
+ const snapshot = store.dump().map((field) => ({ ...field }))
105
+ void ctx.storage.set(storageKey, snapshot).catch(() => {})
106
+ }
107
+ }
108
+
109
+ store = new ProgressStore(
110
+ execShell,
111
+ publish,
112
+ (field) => {
113
+ void ctx.session
114
+ .synthetic({
115
+ sessionID: field.sessionID as Parameters<typeof ctx.session.synthetic>[0]["sessionID"],
116
+ text: `Progress task "${field.name}" completed (100%).`,
117
+ description: `Progress task completed: ${field.name}`,
118
+ delivery: "steer",
119
+ })
120
+ .catch(() => {})
121
+ },
122
+ )
123
+ const progress = store
124
+
125
+ progress.restore(parseSaved(saved))
126
+ // Always publish once so a TUI left over from a previous instance re-syncs.
127
+ publish(progress.list())
128
+
129
+ await ctx.tool.transform((editor) => {
130
+ editor.add({
131
+ name: "pw_create",
132
+ description:
133
+ "Create a progress field shown as a bar in the user's OpenCode sidebar. " +
134
+ `${SHELL_HINT} ${COLOR_HINT} ` +
135
+ "The field starts at 0% and the command is polled automatically.",
136
+ input: {
137
+ type: "object",
138
+ properties: {
139
+ name: { type: "string", minLength: 1, maxLength: 12 },
140
+ shell: { type: "string", minLength: 1 },
141
+ color: { type: "integer", minimum: 0, maximum: COLOR_MAX },
142
+ },
143
+ required: ["name", "shell"],
144
+ additionalProperties: false,
145
+ },
146
+ execute: async (input, context) => {
147
+ const name = requireString(input, "name")
148
+ const shell = requireString(input, "shell")
149
+ const color = colorField(input)
150
+ validateName(name)
151
+ validateShell(shell)
152
+ const field = progress.create(name.trim(), shell, context.sessionID, color ?? null)
153
+ return { content: JSON.stringify({ id: field.id }) }
154
+ },
155
+ })
156
+
157
+ editor.add({
158
+ name: "pw_edit",
159
+ description:
160
+ "Update the name, the shell command or the color of an existing progress field. " +
161
+ "Changing the command restarts polling immediately. " +
162
+ `${COLOR_HINT} ` +
163
+ "Omit a property to leave it unchanged.",
164
+ input: {
165
+ type: "object",
166
+ properties: {
167
+ id: { type: "string" },
168
+ name: { type: "string", minLength: 1, maxLength: 12 },
169
+ shell: { type: "string", minLength: 1 },
170
+ color: { type: "integer", minimum: 0, maximum: COLOR_MAX },
171
+ },
172
+ required: ["id"],
173
+ additionalProperties: false,
174
+ },
175
+ execute: async (input) => {
176
+ const id = requireId(input)
177
+ const name = stringField(input, "name")
178
+ const shell = stringField(input, "shell")
179
+ const color = colorField(input)
180
+ if (name !== undefined) validateName(name)
181
+ if (shell !== undefined) validateShell(shell)
182
+ const field = progress.edit(id, {
183
+ name: name?.trim(),
184
+ shell,
185
+ color,
186
+ })
187
+ if (!field) throw new Error(`progress field ${id} not found`)
188
+ return { content: JSON.stringify(field) }
189
+ },
190
+ })
191
+
192
+ editor.add({
193
+ name: "pw_remove",
194
+ description: "Delete a progress field and stop its polling. Returns { ok: true }.",
195
+ input: {
196
+ type: "object",
197
+ properties: { id: { type: "string" } },
198
+ required: ["id"],
199
+ additionalProperties: false,
200
+ },
201
+ execute: async (input) => {
202
+ const id = requireId(input)
203
+ if (!progress.remove(id)) throw new Error(`progress field ${id} not found`)
204
+ return { content: JSON.stringify({ ok: true }) }
205
+ },
206
+ })
207
+
208
+ editor.add({
209
+ name: "pw_list",
210
+ description:
211
+ "List every progress field with its id, name, shell command, current percent 0-100 and color.",
212
+ input: {
213
+ type: "object",
214
+ properties: {},
215
+ required: [],
216
+ additionalProperties: false,
217
+ },
218
+ execute: async () => ({ content: JSON.stringify(progress.list()) }),
219
+ })
220
+
221
+ editor.add({
222
+ name: "pw_clean",
223
+ description:
224
+ "Remove every progress field and stop polling all of them. Returns { ok: true, removed }.",
225
+ input: {
226
+ type: "object",
227
+ properties: {},
228
+ required: [],
229
+ additionalProperties: false,
230
+ },
231
+ execute: async () => {
232
+ const removed = progress.clear()
233
+ return { content: JSON.stringify({ ok: true, removed }) }
234
+ },
235
+ })
236
+ })
237
+
238
+ return () => {
239
+ progress.dispose()
240
+ caffeinate.dispose()
241
+ }
242
+ },
243
+ })
package/src/store.ts ADDED
@@ -0,0 +1,180 @@
1
+ import { randomBytes } from "node:crypto"
2
+ import type { ProgressField } from "./rpc.js"
3
+ import { nextDelay, parseOutput } from "./progress.js"
4
+
5
+ export type Exec = (shell: string) => Promise<string>
6
+
7
+ /** A field at 100% plus the session that created it, for the success notice. */
8
+ export type CompletedField = ProgressField & { sessionID: string }
9
+
10
+ interface Field extends CompletedField {
11
+ timer?: ReturnType<typeof setTimeout>
12
+ generation: number
13
+ notified: boolean
14
+ }
15
+
16
+ /**
17
+ * Owns the progress fields and their polling loops. `onChange` receives a full
18
+ * snapshot whenever an observable value changes.
19
+ */
20
+ export class ProgressStore {
21
+ private readonly fields = new Map<string, Field>()
22
+ private disposed = false
23
+
24
+ constructor(
25
+ private readonly exec: Exec,
26
+ private readonly onChange: (fields: ProgressField[]) => void,
27
+ private readonly onSuccess?: (field: CompletedField) => void,
28
+ ) {}
29
+
30
+ create(name: string, shell: string, sessionID: string, color: number | null = null): ProgressField {
31
+ const field: Field = {
32
+ id: randomBytes(9).toString("hex"),
33
+ name,
34
+ shell,
35
+ percent: 0,
36
+ color,
37
+ sessionID,
38
+ generation: 0,
39
+ notified: false,
40
+ }
41
+ this.fields.set(field.id, field)
42
+ this.onChange(this.list())
43
+ this.poll(field.id)
44
+ return toPublic(field)
45
+ }
46
+
47
+ edit(id: string, patch: { name?: string; shell?: string; color?: number | null }): ProgressField | undefined {
48
+ const field = this.fields.get(id)
49
+ if (!field) return undefined
50
+
51
+ let changed = false
52
+ if (patch.name !== undefined && patch.name !== field.name) {
53
+ field.name = patch.name
54
+ changed = true
55
+ }
56
+ if (patch.color !== undefined && patch.color !== field.color) {
57
+ field.color = patch.color
58
+ changed = true
59
+ }
60
+ if (patch.shell !== undefined && patch.shell !== field.shell) {
61
+ field.shell = patch.shell
62
+ field.generation++
63
+ if (field.timer !== undefined) clearTimeout(field.timer)
64
+ field.timer = undefined
65
+ changed = true
66
+ this.poll(id)
67
+ }
68
+ if (changed) this.onChange(this.list())
69
+ return toPublic(field)
70
+ }
71
+
72
+ remove(id: string): boolean {
73
+ const field = this.fields.get(id)
74
+ if (!field) return false
75
+ if (field.timer !== undefined) clearTimeout(field.timer)
76
+ this.fields.delete(id)
77
+ this.onChange(this.list())
78
+ return true
79
+ }
80
+
81
+ clear(): number {
82
+ for (const field of this.fields.values()) {
83
+ if (field.timer !== undefined) clearTimeout(field.timer)
84
+ }
85
+ const removed = this.fields.size
86
+ this.fields.clear()
87
+ this.onChange([])
88
+ return removed
89
+ }
90
+
91
+ list(): ProgressField[] {
92
+ return [...this.fields.values()].map(toPublic)
93
+ }
94
+
95
+ /** Every field including the session that owns it, for persistence. */
96
+ dump(): CompletedField[] {
97
+ return [...this.fields.values()].map(toCompleted)
98
+ }
99
+
100
+ /** Re-add saved fields and resume their polling. Does not notify onChange. */
101
+ restore(entries: readonly CompletedField[]): void {
102
+ for (const entry of entries) {
103
+ if (typeof entry.id !== "string" || this.fields.has(entry.id)) continue
104
+ const percent = typeof entry.percent === "number" && Number.isFinite(entry.percent)
105
+ ? Math.min(100, Math.max(0, Math.round(entry.percent)))
106
+ : 0
107
+ this.fields.set(entry.id, {
108
+ id: entry.id,
109
+ name: entry.name,
110
+ shell: entry.shell,
111
+ percent,
112
+ color: entry.color,
113
+ sessionID: entry.sessionID,
114
+ generation: 0,
115
+ notified: percent >= 100,
116
+ })
117
+ this.poll(entry.id)
118
+ }
119
+ }
120
+
121
+ dispose(): void {
122
+ this.disposed = true
123
+ for (const field of this.fields.values()) {
124
+ if (field.timer !== undefined) clearTimeout(field.timer)
125
+ field.timer = undefined
126
+ // Bumping the generation makes any in-flight poll bail out after its await.
127
+ field.generation++
128
+ }
129
+ }
130
+
131
+ private poll(id: string): void {
132
+ const field = this.fields.get(id)
133
+ if (!field) return
134
+ const generation = field.generation
135
+ const shell = field.shell
136
+ const started = Date.now()
137
+
138
+ this.exec(shell).then(
139
+ (output) => output,
140
+ () => "",
141
+ ).then((output) => {
142
+ const current = this.fields.get(id)
143
+ if (!current || current.generation !== generation || this.disposed) return
144
+
145
+ const parsed = parseOutput(output)
146
+ let changed = false
147
+ if (parsed.percent !== current.percent) {
148
+ current.percent = parsed.percent
149
+ changed = true
150
+ }
151
+ if (parsed.name !== undefined && parsed.name !== current.name) {
152
+ current.name = parsed.name
153
+ changed = true
154
+ }
155
+
156
+ let completed = false
157
+ if (current.percent >= 100) {
158
+ if (!current.notified) {
159
+ current.notified = true
160
+ completed = true
161
+ }
162
+ } else {
163
+ current.notified = false
164
+ }
165
+
166
+ if (changed) this.onChange(this.list())
167
+ if (completed) this.onSuccess?.({ ...toPublic(current), sessionID: current.sessionID })
168
+
169
+ current.timer = setTimeout(() => this.poll(id), nextDelay(Date.now() - started))
170
+ })
171
+ }
172
+ }
173
+
174
+ function toPublic(field: Field): ProgressField {
175
+ return { id: field.id, name: field.name, shell: field.shell, percent: field.percent, color: field.color }
176
+ }
177
+
178
+ function toCompleted(field: Field): CompletedField {
179
+ return { ...toPublic(field), sessionID: field.sessionID }
180
+ }
package/src/tui.tsx ADDED
@@ -0,0 +1,126 @@
1
+ import { Plugin, usePlugin } from "@opencode/plugin/tui"
2
+ import { TextAttributes } from "@opentui/core"
3
+ import { For, Show, createEffect, createSignal } from "solid-js"
4
+ import { Progress, type ProgressField } from "./rpc.js"
5
+
6
+ type Snapshot = { fields: ProgressField[] }
7
+
8
+ const PERCENT_WIDTH = 4 // "100%"
9
+
10
+ function clampPercent(value: number): number {
11
+ if (!Number.isFinite(value)) return 0
12
+ return Math.min(100, Math.max(0, Math.round(value)))
13
+ }
14
+
15
+ function isDone(field: ProgressField): boolean {
16
+ return clampPercent(field.percent) >= 100
17
+ }
18
+
19
+ function Row(props: { field: ProgressField }) {
20
+ const theme = usePlugin().theme
21
+ const percent = () => clampPercent(props.field.percent)
22
+ const percentText = () => `${percent()}%`.padStart(PERCENT_WIDTH)
23
+ const done = () => percent() >= 100
24
+ const fill = () => {
25
+ if (props.field.color === null || props.field.color === undefined) return theme.hue.accent[500]
26
+ if (theme.categorical.length === 0) return theme.hue.accent[500]
27
+ return theme.categorical[props.field.color % theme.categorical.length][500]
28
+ }
29
+
30
+ return (
31
+ <box width="100%" flexDirection="row" height={1}>
32
+ <text wrapMode="none" fg={done() ? theme.text.feedback.success.base : undefined}>
33
+ {props.field.name}
34
+ </text>
35
+ <box flexGrow={1} flexBasis={0} height={1} flexDirection="row" marginLeft={1} marginRight={1}>
36
+ <box flexGrow={percent()} flexBasis={0} height={1} backgroundColor={fill()} />
37
+ <box flexGrow={100 - percent()} flexBasis={0} height={1} backgroundColor={theme.background.raised.high} />
38
+ </box>
39
+ <text wrapMode="none" fg={done() ? theme.text.feedback.success.base : undefined}>
40
+ {percentText()}
41
+ </text>
42
+ </box>
43
+ )
44
+ }
45
+
46
+ function Panel(props: {
47
+ sessionID: string
48
+ byDir: () => Record<string, ProgressField[]>
49
+ ensureLoaded: (directory?: string) => void
50
+ fallbackDirectory?: string
51
+ }) {
52
+ const context = usePlugin()
53
+ const theme = context.theme
54
+ const [collapsed, setCollapsed] = createSignal(false)
55
+ const directory = () =>
56
+ context.data.session.get(props.sessionID)?.location?.directory ?? props.fallbackDirectory
57
+ createEffect(() => props.ensureLoaded(directory()))
58
+ const fields = () => props.byDir()[directory() ?? ""] ?? []
59
+ const unfinished = () => fields().filter((field) => !isDone(field)).length
60
+ const title = () =>
61
+ collapsed()
62
+ ? `▶ Tasks in progress: ${unfinished()}/${fields().length}`
63
+ : "▼ Tasks in progress:"
64
+
65
+ return (
66
+ <box width="100%" flexDirection="column">
67
+ <box width="100%" onMouseDown={() => setCollapsed((value) => !value)}>
68
+ <text attributes={TextAttributes.BOLD} wrapMode="none">
69
+ {title()}
70
+ </text>
71
+ </box>
72
+ <Show when={!collapsed()}>
73
+ <Show when={fields().length > 0} fallback={<text fg={theme.text.muted}>no tasks running</text>}>
74
+ <For each={fields()}>{(field) => <Row field={field} />}</For>
75
+ </Show>
76
+ </Show>
77
+ </box>
78
+ )
79
+ }
80
+
81
+ export default Plugin.define({
82
+ id: "progress-panel.tui",
83
+ async setup(context) {
84
+ const [byDir, setByDir] = createSignal<Record<string, ProgressField[]>>({})
85
+ const loaded = new Set<string>()
86
+ const rpc = context.client.rpc(Progress)
87
+
88
+ const ensureLoaded = (directory?: string) => {
89
+ if (!directory || loaded.has(directory)) return
90
+ loaded.add(directory)
91
+ // A rejected load must not crash the panel: the directory just stays empty.
92
+ void rpc.list({}, { location: { directory } }).then(
93
+ (snapshot) =>
94
+ setByDir((prev) =>
95
+ prev[directory] ? prev : { ...prev, [directory]: (snapshot as Snapshot).fields },
96
+ ),
97
+ () => loaded.delete(directory),
98
+ )
99
+ }
100
+
101
+ // Keep every directory: the panel filters by the session's directory.
102
+ const off = rpc.events.on("changed", (event) => {
103
+ setByDir((prev) => ({
104
+ ...prev,
105
+ [event.location.directory]: (event.data as unknown as Snapshot).fields,
106
+ }))
107
+ })
108
+
109
+ const release = context.ui.slot({
110
+ append: "sidebar.content",
111
+ render: (input) => (
112
+ <Panel
113
+ sessionID={input.sessionID}
114
+ byDir={byDir}
115
+ ensureLoaded={ensureLoaded}
116
+ fallbackDirectory={context.location?.directory}
117
+ />
118
+ ),
119
+ })
120
+
121
+ return () => {
122
+ off()
123
+ release()
124
+ }
125
+ },
126
+ })