@jakedowns/progress-tool-opencode-plugin 0.0.0-stage → 2.14.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/src/gui.tsx ADDED
@@ -0,0 +1,613 @@
1
+ /**
2
+ * OpenCode Progress Plugin — desktop / web GUI part.
3
+ *
4
+ * Runs in every app window (Electron and browser) and contributes a composer
5
+ * pill next to the native status row. The pill's menu lists the dependency
6
+ * tree, including nested children.
7
+ */
8
+
9
+ import { ComposerPill, Plugin } from "@opencode/plugin/gui";
10
+ import { For, Index, Show, createEffect, createSignal } from "solid-js";
11
+ import pkg from "../package.json";
12
+ import { ProgressRpc } from "./rpc.js";
13
+ import {
14
+ buildTree,
15
+ barParts,
16
+ countActive,
17
+ flattenTreeWithDepth,
18
+ visibleRows,
19
+ countDescendants,
20
+ collapsedRootMap,
21
+ summarizeEntries,
22
+ isDismissed,
23
+ normalizeBarOptions,
24
+ normalizeProgressText,
25
+ normalizeRefreshMs,
26
+ normalizeVisibilityOptions,
27
+ oneLineText,
28
+ progressLabel,
29
+ scopeEntries,
30
+ visibleEntries,
31
+ type BarOptions,
32
+ } from "./tree.js";
33
+ import type { ProgressEntry, TreeNode } from "./types.js";
34
+
35
+ type GuiState = {
36
+ entries: Record<string, ProgressEntry>;
37
+ loaded: boolean;
38
+ error?: string;
39
+ };
40
+
41
+ function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
42
+ return Promise.race([
43
+ promise,
44
+ new Promise<T>((_, reject) => setTimeout(() => reject(new Error(`timeout after ${ms}ms`)), ms)),
45
+ ]);
46
+ }
47
+
48
+ function toneFor(status: TreeNode["status"]): "success" | "warning" | "danger" | undefined {
49
+ if (status === "error") return "danger";
50
+ if (status === "done") return "success";
51
+ if (status === "waiting") return "warning";
52
+ return undefined;
53
+ }
54
+
55
+ function dotColor(status: TreeNode["status"]): string {
56
+ if (status === "error") return "#ef4444";
57
+ if (status === "done") return "#10b981";
58
+ if (status === "waiting") return "#f59e0b";
59
+ return "#3b82f6";
60
+ }
61
+
62
+ /** "Nov 18, 2:03 PM" in the viewer's locale and timezone. */
63
+ function formatDateTime(ms: number | undefined): string {
64
+ if (!ms) return "";
65
+ try {
66
+ return new Date(ms).toLocaleString(undefined, {
67
+ month: "short",
68
+ day: "numeric",
69
+ hour: "numeric",
70
+ minute: "2-digit",
71
+ });
72
+ } catch {
73
+ return new Date(ms).toISOString();
74
+ }
75
+ }
76
+
77
+ /** Human-readable age: "just now", "42 seconds ago", "3 minutes ago", ... */
78
+ function formatRelative(ms: number | undefined): string {
79
+ if (!ms) return "";
80
+ const delta = Math.max(0, Date.now() - ms);
81
+ if (delta < 10_000) return "just now";
82
+ const seconds = Math.floor(delta / 1000);
83
+ if (seconds < 60) return `${seconds} second${seconds === 1 ? "" : "s"} ago`;
84
+ const minutes = Math.floor(seconds / 60);
85
+ if (minutes < 60) return `${minutes} minute${minutes === 1 ? "" : "s"} ago`;
86
+ const hours = Math.floor(minutes / 60);
87
+ if (hours < 24) return `${hours} hour${hours === 1 ? "" : "s"} ago`;
88
+ const days = Math.floor(hours / 24);
89
+ return `${days} day${days === 1 ? "" : "s"} ago`;
90
+ }
91
+
92
+ /** Render normalized text with real <br> elements, never innerHTML. */
93
+ function Multiline(props: { text: string }) {
94
+ return (
95
+ <Index each={normalizeProgressText(props.text).split("\n")}>
96
+ {(line, index) => (
97
+ <>
98
+ {index > 0 ? <br /> : null}
99
+ {line()}
100
+ </>
101
+ )}
102
+ </Index>
103
+ );
104
+ }
105
+
106
+ function MenuRow(props: {
107
+ node: TreeNode;
108
+ depth: number;
109
+ options: BarOptions;
110
+ onDismiss?: () => void;
111
+ hasChildren?: boolean;
112
+ collapsed?: boolean;
113
+ onToggle?: () => void;
114
+ }) {
115
+ const pct = () => progressLabel(props.node.progress);
116
+ const parts = () => barParts(props.node.progress, props.options);
117
+
118
+ return (
119
+ <div
120
+ onClick={(event: MouseEvent) => {
121
+ if (!props.hasChildren) return;
122
+ // Do not hijack text selection drags.
123
+ const selected = window.getSelection?.()?.toString();
124
+ if (selected) return;
125
+ event.preventDefault();
126
+ props.onToggle?.();
127
+ }}
128
+ style={{
129
+ display: "flex",
130
+ "align-items": "flex-start",
131
+ gap: "8px",
132
+ "padding-left": `${props.depth * 14}px`,
133
+ "padding-top": "5px",
134
+ "padding-bottom": "5px",
135
+ cursor: props.hasChildren ? "pointer" : "default",
136
+ }}
137
+ >
138
+ <Show when={props.hasChildren}>
139
+ <span
140
+ aria-hidden="true"
141
+ style={{
142
+ flex: "0 0 auto",
143
+ opacity: "0.6",
144
+ "font-size": "11px",
145
+ width: "14px",
146
+ "margin-top": "4px",
147
+ "user-select": "none",
148
+ "line-height": "1",
149
+ display: "inline-block",
150
+ transform: props.collapsed ? "rotate(0deg)" : "rotate(90deg)",
151
+ transition: "transform 0.35s ease-in-out",
152
+ }}
153
+ >
154
+ {props.collapsed ? "▸" : "▾"}
155
+ </span>
156
+ </Show>
157
+ <div
158
+ style={{
159
+ width: "8px",
160
+ height: "8px",
161
+ "border-radius": "50%",
162
+ "margin-top": "6px",
163
+ flex: "0 0 auto",
164
+ background: dotColor(props.node.status),
165
+ }}
166
+ />
167
+ <div style={{ flex: "1 1 auto", "min-width": "0" }}>
168
+ <div
169
+ style={{
170
+ "font-weight": props.depth === 0 ? "650" : "500",
171
+ "white-space": "normal",
172
+ "overflow-wrap": "anywhere",
173
+ "word-break": "break-word",
174
+ }}
175
+ title={`${props.node.status}: ${oneLineText(props.node.title)}`}
176
+ >
177
+ <Multiline text={props.node.title} />
178
+ </div>
179
+ <Show when={props.node.detail}>
180
+ <div
181
+ style={{
182
+ "margin-top": "2px",
183
+ "font-size": "12px",
184
+ opacity: "0.72",
185
+ "white-space": "normal",
186
+ "overflow-wrap": "anywhere",
187
+ "word-break": "break-word",
188
+ }}
189
+ title={props.node.detail ? `${props.node.status}: ${oneLineText(props.node.detail)}` : ""}
190
+ >
191
+ <Multiline text={props.node.detail ?? ""} />
192
+ </div>
193
+ </Show>
194
+ <div
195
+ style={{
196
+ "margin-top": "4px",
197
+ display: "flex",
198
+ gap: "8px",
199
+ "align-items": "center",
200
+ "font-size": "11px",
201
+ opacity: "0.58",
202
+ }}
203
+ >
204
+ <span style={{ "font-family": "ui-monospace, SFMono-Regular, Menlo, monospace" }}>
205
+ {parts().bar}
206
+ </span>
207
+ <Show when={pct()}>
208
+ <span>{pct()}</span>
209
+ </Show>
210
+ <Show when={props.collapsed && props.node.children.length > 0}>
211
+ <span>
212
+ {countDescendants(props.node)} descendant
213
+ {countDescendants(props.node) === 1 ? "" : "s"}
214
+ </span>
215
+ </Show>
216
+ <Show when={props.node.startedAt}>
217
+ <span
218
+ title={`Last updated ${formatRelative(props.node.updatedAt)} (${formatDateTime(props.node.updatedAt)})`}
219
+ style={{ "white-space": "nowrap", cursor: "default" }}
220
+ >
221
+ started {formatDateTime(props.node.startedAt)}
222
+ </span>
223
+ </Show>
224
+ </div>
225
+ </div>
226
+ <Show when={props.onDismiss}>
227
+ <button
228
+ type="button"
229
+ title="Dismiss"
230
+ aria-label="Dismiss"
231
+ onClick={(event: MouseEvent) => {
232
+ event.stopPropagation();
233
+ props.onDismiss?.();
234
+ }}
235
+ style={{
236
+ flex: "0 0 auto",
237
+ border: "1px solid rgba(127,127,127,0.35)",
238
+ background: "transparent",
239
+ color: "inherit",
240
+ opacity: "0.65",
241
+ "border-radius": "50%",
242
+ width: "22px",
243
+ height: "22px",
244
+ cursor: "pointer",
245
+ "line-height": "1",
246
+ }}
247
+ >
248
+ ×
249
+ </button>
250
+ </Show>
251
+ </div>
252
+ );
253
+ }
254
+
255
+ function rowFor(node: TreeNode, depth: number, options: BarOptions) {
256
+ const parts = barParts(node.progress, options);
257
+ const pct = progressLabel(node.progress);
258
+ const indent = depth > 0 ? "\u00A0\u00A0".repeat(depth) + "└─ " : "";
259
+ const suffix =
260
+ parts.style === "emoji"
261
+ ? `: ${parts.bar}${parts.fraction}`
262
+ : pct
263
+ ? ` · ${pct}`
264
+ : "";
265
+ return {
266
+ id: node.key,
267
+ label: `${indent}${oneLineText(node.title)}${suffix}`,
268
+ detail: node.detail ? oneLineText(node.detail) : undefined,
269
+ tone: toneFor(node.status),
270
+ };
271
+ }
272
+
273
+ export default Plugin.define({
274
+ setup(ctx) {
275
+ const [state, setState] = createSignal<GuiState>({ entries: {}, loaded: false });
276
+ // Dismissal is per root task and scoped to that task itself; the revival
277
+ // semantics (re-report always revives, non-terminal status changes revive,
278
+ // terminal dismissals only revive on failure or re-report) live in
279
+ // tree.ts's isDismissed, shared and unit-tested.
280
+ //
281
+ // The dismissed state is PERSISTED in the shared state doc as
282
+ // entry.dismissed = { status, at } (view-plane metadata written through
283
+ // the plugin server's locked atomic writer), so it survives window
284
+ // reloads and is shared by every view. This signal holds only optimistic
285
+ // writes between the click and the next observed state.
286
+ const [pendingDismissed, setPendingDismissed] = createSignal<Record<string, { status: string; at: number }>>({});
287
+ const options = normalizeBarOptions(ctx.options);
288
+ const visibility = normalizeVisibilityOptions(ctx.options);
289
+ const refreshMs = normalizeRefreshMs(ctx.options);
290
+ let alive = true;
291
+
292
+ const refresh = async () => {
293
+ try {
294
+ const session = ctx.sessions.current();
295
+ if (!session) {
296
+ setState((prev) => ({ ...prev, loaded: true }));
297
+ return;
298
+ }
299
+ const result = await withTimeout(session.server.client.rpc(ProgressRpc).list({}), 4000);
300
+ if (!alive) return;
301
+ setState({
302
+ entries: (result?.entries ?? {}) as Record<string, ProgressEntry>,
303
+ loaded: true,
304
+ });
305
+ // Drop optimistic dismissals once the persisted state reflects them.
306
+ setPendingDismissed((prev) => {
307
+ const next = { ...prev };
308
+ for (const [key, value] of Object.entries(prev)) {
309
+ const d = (result?.entries ?? {})[key]?.dismissed;
310
+ if (d && typeof d === "object" && (d as { at: number }).at >= value.at - 500) {
311
+ delete next[key];
312
+ }
313
+ }
314
+ return next;
315
+ });
316
+ } catch (error) {
317
+ if (!alive) return;
318
+ setState((prev) => ({ ...prev, loaded: true, error: String(error) }));
319
+ console.error("[opencode-progress] rpc list failed", String(error));
320
+ }
321
+ };
322
+
323
+ console.log(`[opencode-progress] gui setup v${pkg.version} (opencode ${ctx.app.version}, ${ctx.app.platform})`);
324
+ if (ctx.options?.notifyOnLoad === true) {
325
+ ctx.toast.show({
326
+ title: "Progress plugin loaded",
327
+ description: `${ctx.app.platform} · opencode-progress v${pkg.version}`,
328
+ variant: "success",
329
+ duration: 2500,
330
+ });
331
+ }
332
+ void refresh();
333
+ const timer = setInterval(() => void refresh(), refreshMs);
334
+
335
+ /** Persisted dismissals, read straight from the state doc entries. */
336
+ const dismissedFromEntries = () => {
337
+ const map: Record<string, { status: string; at: number }> = {};
338
+ for (const [key, entry] of Object.entries(state().entries)) {
339
+ const d = entry.dismissed;
340
+ if (d && typeof d === "object" && typeof d.at === "number") {
341
+ map[key] = { status: String(d.status ?? ""), at: d.at };
342
+ }
343
+ }
344
+ return map;
345
+ };
346
+
347
+ /** Persisted + optimistic: pending wins while newer than persisted. */
348
+ const dismissedMap = () => {
349
+ const merged = dismissedFromEntries();
350
+ for (const [key, pending] of Object.entries(pendingDismissed())) {
351
+ const persisted = merged[key];
352
+ if (!persisted || pending.at > persisted.at) merged[key] = pending;
353
+ }
354
+ return merged;
355
+ };
356
+
357
+ type DismissSession = {
358
+ server: {
359
+ client: {
360
+ rpc: (contract: unknown) => {
361
+ dismiss(input: { key: string; status: string }): Promise<{ ok: boolean }>;
362
+ };
363
+ };
364
+ };
365
+ };
366
+
367
+ /** Persist the dismissal via the plugin server, optimistically in-memory. */
368
+ const dismissKey = (
369
+ session: DismissSession,
370
+ key: string,
371
+ status: string
372
+ ) => {
373
+ setPendingDismissed((prev) => ({ ...prev, [key]: { status, at: Date.now() } }));
374
+ void session.server.client
375
+ .rpc(ProgressRpc)
376
+ .dismiss({ key, status })
377
+ .catch((error: unknown) =>
378
+ console.error("[opencode-progress] dismiss rpc failed", String(error))
379
+ );
380
+ };
381
+
382
+ const ProgressMenu = (props: { session: DismissSession; sessionID: string }) => {
383
+ const scoped = () => scopeEntries(state().entries, props.sessionID, visibility);
384
+ const visibleRoots = () => {
385
+ const roots = buildTree(visibleEntries(scoped(), Date.now(), visibility));
386
+ return roots.filter((root) => !isDismissed(root, dismissedMap()));
387
+ };
388
+ const [expandedOverrides, setExpandedOverrides] = createSignal<Record<string, boolean>>({});
389
+ const expandByDefault = ctx.options?.expandRootsByDefault === true;
390
+ const collapsedMap = () =>
391
+ collapsedRootMap(visibleRoots(), expandByDefault, expandedOverrides());
392
+ const rows = () => visibleRows(visibleRoots(), collapsedMap());
393
+
394
+ // Our own scroll container: <For> rebuilds row DOM when the tree
395
+ // changes (e.g. after a dismiss), which resets scrollTop. Track the
396
+ // user's position and restore it after each re-render.
397
+ let listEl: HTMLDivElement | undefined;
398
+ let scrollTop = 0;
399
+ createEffect(() => {
400
+ rows();
401
+ const target = scrollTop;
402
+ queueMicrotask(() => {
403
+ if (listEl && listEl.scrollTop !== target) listEl.scrollTop = target;
404
+ });
405
+ });
406
+
407
+ return (
408
+ <div
409
+ ref={(el) => (listEl = el)}
410
+ onScroll={(event) => {
411
+ scrollTop = event.currentTarget.scrollTop;
412
+ }}
413
+ style={{
414
+ display: "flex",
415
+ "flex-direction": "column",
416
+ gap: "2px",
417
+ "max-height": "min(60vh, 520px)",
418
+ "overflow-y": "auto",
419
+ "overflow-x": "hidden",
420
+ "min-width": "320px",
421
+ "max-width": "520px",
422
+ "padding-right": "4px",
423
+ }}
424
+ >
425
+ <Show
426
+ when={rows().length > 0}
427
+ fallback={
428
+ <div style={{ opacity: "0.6", "font-size": "13px", padding: "8px" }}>
429
+ No active progress
430
+ </div>
431
+ }
432
+ >
433
+ <For each={visibleRoots()}>
434
+ {(root) => {
435
+ const isCollapsed = () => collapsedMap()[root.key] ?? false;
436
+ return (
437
+ <>
438
+ <MenuRow
439
+ node={root}
440
+ depth={0}
441
+ options={options}
442
+ hasChildren={root.children.length > 0}
443
+ collapsed={isCollapsed()}
444
+ onToggle={() =>
445
+ setExpandedOverrides((prev) => ({
446
+ ...prev,
447
+ [root.key]: !(prev[root.key] ?? expandByDefault),
448
+ }))
449
+ }
450
+ onDismiss={() => dismissKey(props.session, root.key, root.status ?? "")}
451
+ />
452
+ <div
453
+ style={{
454
+ display: "grid",
455
+ "grid-template-rows": isCollapsed() ? "0fr" : "1fr",
456
+ transition: "grid-template-rows 0.5s ease-in-out",
457
+ }}
458
+ >
459
+ <div style={{ overflow: "hidden", "min-height": "0" }}>
460
+ <For each={flattenTreeWithDepth(root.children, 1)}>
461
+ {({ node, depth }) => (
462
+ <MenuRow node={node} depth={depth} options={options} />
463
+ )}
464
+ </For>
465
+ </div>
466
+ </div>
467
+ </>
468
+ );
469
+ }}
470
+ </For>
471
+ <button
472
+ type="button"
473
+ onClick={() => {
474
+ for (const root of visibleRoots()) {
475
+ dismissKey(props.session, root.key, root.status ?? "");
476
+ }
477
+ }}
478
+ style={{
479
+ "margin-top": "6px",
480
+ border: "none",
481
+ background: "transparent",
482
+ color: "inherit",
483
+ opacity: "0.65",
484
+ cursor: "pointer",
485
+ "text-align": "left",
486
+ padding: "6px 8px",
487
+ "font-size": "12px",
488
+ }}
489
+ >
490
+ ✕ Dismiss all
491
+ </button>
492
+ </Show>
493
+ <div
494
+ style={{
495
+ "margin-top": "4px",
496
+ padding: "4px 8px 6px",
497
+ "font-size": "10px",
498
+ opacity: "0.45",
499
+ "user-select": "none",
500
+ }}
501
+ >
502
+ progress plugin desktop v{pkg.version}
503
+ </div>
504
+ </div>
505
+ );
506
+ };
507
+
508
+ ctx.add(ComposerPill, () => ({
509
+ id: "progress",
510
+ show: (input) => {
511
+ const current = state();
512
+ const scoped = scopeEntries(current.entries, input.session.id, visibility);
513
+ const empty = Object.keys(scoped).length === 0;
514
+
515
+ if (current.error && empty) {
516
+ return {
517
+ label: "progress: error",
518
+ title: "Progress plugin error",
519
+ rows: [
520
+ {
521
+ id: "error",
522
+ label: current.error.slice(0, 160),
523
+ tone: "danger" as const,
524
+ },
525
+ ],
526
+ };
527
+ }
528
+
529
+ if (!current.loaded && empty) {
530
+ return { label: "progress: loading", title: "Progress plugin" };
531
+ }
532
+
533
+ const roots = buildTree(visibleEntries(scoped, Date.now(), visibility));
534
+ const visibleRoots = roots.filter((root) => !isDismissed(root, dismissedMap()));
535
+ if (visibleRoots.length === 0) return undefined;
536
+
537
+ const active = countActive(visibleRoots);
538
+ const top = visibleRoots[0];
539
+ const topPct = progressLabel(top.progress);
540
+ const parts = barParts(top.progress, options);
541
+ const topTitle = oneLineText(top.title);
542
+
543
+ // Collapsed pill prefix: the aggregate % shows even with a single
544
+ // root; the root count is included only when there is more than one
545
+ // ("(2 · 60%)", "(40%)"). Prefix placement survives truncation.
546
+ const rootProgresses = visibleRoots
547
+ .map((root) => root.progress)
548
+ .filter((value): value is number => typeof value === "number" && Number.isFinite(value));
549
+ const aggregatePct =
550
+ rootProgresses.length > 0
551
+ ? progressLabel(rootProgresses.reduce((a, b) => a + b, 0) / rootProgresses.length)
552
+ : null;
553
+ const pillPrefix = aggregatePct
554
+ ? `(${visibleRoots.length > 1 ? `${visibleRoots.length} · ` : ""}${aggregatePct}) `
555
+ : visibleRoots.length > 1
556
+ ? `(${visibleRoots.length}) `
557
+ : "";
558
+
559
+ const label =
560
+ parts.style === "emoji"
561
+ ? `${pillPrefix}${topTitle}: ${parts.bar}${parts.fraction}`
562
+ : active > 0
563
+ ? `${pillPrefix}${topTitle}${topPct ? ` ${topPct}` : ""}`
564
+ : `${pillPrefix}${topTitle}`;
565
+
566
+ return {
567
+ label,
568
+ // Headline counts include descendants (the store, not just roots):
569
+ // "4 active · 3 done · 2 dismissed".
570
+ title: (() => {
571
+ const summary = summarizeEntries(scoped);
572
+ const parts: string[] = [];
573
+ if (summary.active > 0) parts.push(`${summary.active} active`);
574
+ if (summary.done > 0) parts.push(`${summary.done} done`);
575
+ if (summary.dismissed > 0) parts.push(`${summary.dismissed} dismissed`);
576
+ return parts.length > 0 ? parts.join(" · ") : "Agent progress";
577
+ })(),
578
+ rows: [
579
+ ...flattenTreeWithDepth(visibleRoots)
580
+ .slice(0, 7)
581
+ .map(({ node, depth }) => {
582
+ const row = rowFor(node, depth, options);
583
+ if (depth !== 0) return row;
584
+ return {
585
+ ...row,
586
+ icon: "circle-x" as const,
587
+ detail: row.detail ?? "dismiss",
588
+ run: () => dismissKey(input.session, node.key, node.status ?? ""),
589
+ };
590
+ }),
591
+ {
592
+ id: "dismiss",
593
+ label: "✕ Dismiss all",
594
+ run: () => {
595
+ for (const root of visibleRoots) {
596
+ dismissKey(input.session, root.key, root.status ?? "");
597
+ }
598
+ },
599
+ },
600
+ ],
601
+ };
602
+ },
603
+ menu: (input) => (
604
+ <ProgressMenu session={input.session} sessionID={input.session.id} />
605
+ ),
606
+ }));
607
+
608
+ return () => {
609
+ alive = false;
610
+ clearInterval(timer);
611
+ };
612
+ },
613
+ });