@blackbelt-technology/pi-dashboard-extension 0.3.0 → 0.4.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.
package/src/bridge.ts CHANGED
@@ -35,6 +35,7 @@ import { filterHiddenCommands, extractFirstMessage, getCurrentModelString } from
35
35
  import { sendStateSync as _sendStateSync, replaySessionEntries as _replaySessionEntries, handleSessionChange as _handleSessionChange } from "./session-sync.js";
36
36
  import { sendModelUpdateIfChanged as _sendModelUpdateIfChanged, sendSessionNameIfChanged as _sendSessionNameIfChanged, sendGitInfoIfChanged as _sendGitInfoIfChanged } from "./model-tracker.js";
37
37
  import { registerFlowEventListeners, FLOW_EVENT_MAP, SUBAGENT_EVENT_MAP } from "./flow-event-wiring.js";
38
+ import { refreshUiModules, subscribeUiInvalidate, handleUiManagement, type UiModulesBridgeCtx } from "./ui-modules.js";
38
39
 
39
40
  const HEARTBEAT_INTERVAL = 15_000;
40
41
  const GIT_POLL_INTERVAL = 30_000;
@@ -186,6 +187,61 @@ function initBridge(pi: ExtensionAPI) {
186
187
  let lastThinkingLevel: string | undefined;
187
188
  let promptBus: PromptBus | undefined;
188
189
 
190
+ // ── Per-message entry id tracking (for fix-per-message-fork) ──
191
+ // Pi 0.69+ awaits extension handlers BEFORE sessionManager.appendMessage runs,
192
+ // which means getLeafId() at emit time returns the previous leaf, not the
193
+ // entry id of the message currently being emitted. We solve this by:
194
+ // 1. Wrapping ctx.sessionManager.appendMessage at session_start to stamp
195
+ // the just-generated entry id onto the message object reference.
196
+ // 2. Deferring the message_end enrichment-and-send via setTimeout(0) so
197
+ // the awaited dispatcher unwinds and appendMessage runs in between.
198
+ // 3. Stamping a nonce on message_start/message_end events; emitting an
199
+ // entry_persisted event after appendMessage so the client reducer can
200
+ // back-fill user-message ChatMessage.entryId.
201
+ // See change: fix-per-message-fork.
202
+ const idByMessage = new WeakMap<object, string>();
203
+ const pendingNonces = new WeakMap<object, string>();
204
+ let nonceCounter = 0;
205
+ const nextNonce = (): string => `n-${++nonceCounter}-${Date.now()}`;
206
+ let appendMessageWrapped = false;
207
+ let lastWrappedSm: any = null;
208
+
209
+ /**
210
+ * Wrap ctx.sessionManager.appendMessage once per session so that when pi
211
+ * generates an entry id we capture it in the WeakMap and emit
212
+ * entry_persisted to the server.
213
+ */
214
+ function wrapAppendMessageForCtx(ctx: any): void {
215
+ const sm = ctx?.sessionManager;
216
+ if (!sm || typeof sm.appendMessage !== "function") return;
217
+ // Re-wrap when sessionManager identity changes (session replacement).
218
+ if (sm === lastWrappedSm && appendMessageWrapped) return;
219
+ const original = sm.appendMessage.bind(sm);
220
+ sm.appendMessage = (msg: any, ...rest: any[]) => {
221
+ const result = original(msg, ...rest);
222
+ try {
223
+ if (msg && typeof msg === "object" && typeof msg.id === "string") {
224
+ idByMessage.set(msg as object, msg.id);
225
+ const nonce = pendingNonces.get(msg as object);
226
+ if (nonce && sessionReady && isActive()) {
227
+ const ev = {
228
+ type: "entry_persisted",
229
+ entryId: msg.id,
230
+ nonce,
231
+ };
232
+ connection.send(mapEventToProtocol(sessionId, ev));
233
+ pendingNonces.delete(msg as object);
234
+ }
235
+ }
236
+ } catch (err) {
237
+ console.error("[dashboard] entry_persisted emit failed:", err);
238
+ }
239
+ return result;
240
+ };
241
+ lastWrappedSm = sm;
242
+ appendMessageWrapped = true;
243
+ }
244
+
189
245
  /** Wrap a callback so errors log instead of crashing the host pi agent. */
190
246
  function safe<T extends (...args: any[]) => any>(fn: T): T {
191
247
  return ((...args: any[]) => {
@@ -208,11 +264,29 @@ function initBridge(pi: ExtensionAPI) {
208
264
  const config = loadConfig();
209
265
  const dashboardUrl = process.env.PI_DASHBOARD_URL ?? `ws://localhost:${config.piPort}`;
210
266
 
267
+ // Long-lived ctx wrapper for the Extension UI System (Phase 1) — see
268
+ // change: add-extension-ui-modal. `getSessionId` reads the closed-over
269
+ // `sessionId` so the helper always uses the current value (which is
270
+ // mutated when `event.reason ∈ {"new","fork","resume"}` fires).
271
+ const uiModulesBridgeCtx: UiModulesBridgeCtx = {
272
+ pi: pi as any,
273
+ connection: { send: (msg: unknown) => connection.send(msg) },
274
+ getSessionId: () => sessionId,
275
+ };
276
+
211
277
  const connection = new ConnectionManager({
212
278
  url: dashboardUrl,
213
279
  onMessage: safe(async (data: unknown) => {
214
280
  if (!isActive()) return; // Stale listener guard
215
281
  const msg = data as ServerToExtensionMessage;
282
+ // Extension UI System (Phase 1): browser-originated action / data
283
+ // request. Re-emit on pi.events; the listener either populates
284
+ // data.items synchronously or calls _reply asynchronously.
285
+ // See change: add-extension-ui-modal.
286
+ if ((msg as any).type === "ui_management") {
287
+ handleUiManagement(uiModulesBridgeCtx, msg as any);
288
+ return;
289
+ }
216
290
  // Legacy extension_ui_response removed — now handled by prompt_response → promptBus.respond()
217
291
  // Reload auth credentials when dashboard notifies of changes
218
292
  if (msg.type === "credentials_updated") {
@@ -408,6 +482,11 @@ function initBridge(pi: ExtensionAPI) {
408
482
  if (getBridgeState().isAgentStreaming) {
409
483
  connection.send(mapEventToProtocol(sessionId, { type: "agent_start" }));
410
484
  }
485
+ // Extension UI System (Phase 1): re-probe modules after every
486
+ // reconnect so the server-side cache stays accurate. The probe is
487
+ // synchronous and re-runs the listener stack each call.
488
+ // See change: add-extension-ui-modal.
489
+ refreshUiModules(uiModulesBridgeCtx);
411
490
  }),
412
491
  });
413
492
 
@@ -612,30 +691,53 @@ function initBridge(pi: ExtensionAPI) {
612
691
  }
613
692
  }
614
693
 
615
- // For message_start, enrich with entryId immediately (current leaf)
694
+ // For message_start: stamp a nonce on the event so the client reducer
695
+ // can correlate a later entry_persisted back-fill with this bubble.
696
+ // We do NOT attach entryId here — the message has no id yet on pi
697
+ // 0.69+ (persistence is deferred to message_end). See change:
698
+ // fix-per-message-fork.
616
699
  if (eventType === "message_start") {
617
- const entryId = ctx.sessionManager?.getLeafId?.();
618
- if (entryId) {
619
- const enriched = { ...event, entryId };
700
+ wrapAppendMessageForCtx(ctx);
701
+ const messageRef = (event as any).message;
702
+ if (messageRef && typeof messageRef === "object") {
703
+ const nonce = nextNonce();
704
+ pendingNonces.set(messageRef as object, nonce);
705
+ const enriched = { ...event, nonce };
620
706
  const msg = mapEventToProtocol(sessionId, enriched);
621
707
  connection.send(msg);
622
708
  return;
623
709
  }
624
710
  }
625
711
 
626
- // For message_end, defer getLeafId() so it runs after pi core persists the entry.
627
- // Pi core calls _emit (which invokes this handler) BEFORE appendMessage (which updates leafId).
628
- // Since _emit doesn't await async handlers, yielding via queueMicrotask lets appendMessage
629
- // run first, so getLeafId() returns the correct entry ID for the just-persisted message.
712
+ // For message_end: defer the SEND via setTimeout(0). Pi 0.69+ runs
713
+ // sessionManager.appendMessage AFTER the awaited extension dispatcher
714
+ // returns, so a queueMicrotask deferral is no longer enough. By the
715
+ // time the macrotask fires, appendMessage has run, pi has mutated
716
+ // event.message.id in place, and the wrapped appendMessage above has
717
+ // populated idByMessage. We also stamp a nonce so a downstream
718
+ // entry_persisted can correlate (covers user message_end where the
719
+ // earlier message_start nonce is what the reducer is waiting on).
720
+ // See change: fix-per-message-fork.
630
721
  if (eventType === "message_end") {
631
- await new Promise<void>(resolve => queueMicrotask(resolve));
632
- const entryId = ctx.sessionManager?.getLeafId?.();
633
- if (entryId) {
634
- const enriched = { ...event, entryId };
635
- const msg = mapEventToProtocol(sessionId, enriched);
636
- connection.send(msg);
637
- return;
722
+ wrapAppendMessageForCtx(ctx);
723
+ const messageRef = (event as any).message;
724
+ const nonce = messageRef && typeof messageRef === "object"
725
+ ? (pendingNonces.get(messageRef as object) ?? nextNonce())
726
+ : nextNonce();
727
+ if (messageRef && typeof messageRef === "object" && !pendingNonces.has(messageRef as object)) {
728
+ pendingNonces.set(messageRef as object, nonce);
638
729
  }
730
+ setTimeout(() => {
731
+ if (!isActive() || !sessionReady) return;
732
+ const entryId =
733
+ (messageRef && typeof messageRef === "object" && typeof messageRef.id === "string" ? messageRef.id : undefined)
734
+ ?? (messageRef ? idByMessage.get(messageRef as object) : undefined)
735
+ ?? ctx.sessionManager?.getLeafId?.();
736
+ const enriched = { ...event, entryId, nonce };
737
+ const protoMsg = mapEventToProtocol(sessionId, enriched);
738
+ connection.send(protoMsg);
739
+ }, 0);
740
+ return;
639
741
  }
640
742
 
641
743
  const msg = mapEventToProtocol(sessionId, event);
@@ -694,6 +796,15 @@ function initBridge(pi: ExtensionAPI) {
694
796
  cachedCtx = ctx;
695
797
  sessionId = newSessionId;
696
798
 
799
+ // Wrap sessionManager.appendMessage so that future message_end events can
800
+ // recover the just-generated entry id, even when their setTimeout(0)
801
+ // fires before pi has finished mutating event.message in place. The
802
+ // helper is idempotent and re-wraps on session replacement.
803
+ // See change: fix-per-message-fork.
804
+ appendMessageWrapped = false;
805
+ lastWrappedSm = null;
806
+ wrapAppendMessageForCtx(ctx);
807
+
697
808
  // Register ask_user at runtime (not at load time) to avoid static
698
809
  // tool-name conflicts with other extensions like pi-flows.
699
810
  registerAskUserTool(pi);
@@ -1073,6 +1184,13 @@ function initBridge(pi: ExtensionAPI) {
1073
1184
 
1074
1185
  // Register flow event listeners (pi-flows emits these via pi.events)
1075
1186
  registerFlowEventListeners(syncBc(), () => sessionReady, getFlowsList);
1187
+
1188
+ // Extension UI System (Phase 1): subscribe to invalidate once per
1189
+ // session, then run the discovery probe. The probe is synchronous
1190
+ // and re-runs on every reconnect (see `onReconnect` callback above).
1191
+ // See change: add-extension-ui-modal.
1192
+ subscribeUiInvalidate(uiModulesBridgeCtx);
1193
+ refreshUiModules(uiModulesBridgeCtx);
1076
1194
  }));
1077
1195
 
1078
1196
  // Shared handler for session changes (new/fork/resume)
@@ -0,0 +1,146 @@
1
+ /**
2
+ * MultiSelectList — a TUI multi-select component implementing pi-tui's
3
+ * `Component` interface. Used by `polyfillMultiselect` to emulate the
4
+ * `ctx.ui.multiselect(...)` call that `pi-coding-agent`'s `ExtensionUIContext`
5
+ * does not expose natively.
6
+ *
7
+ * Keyboard contract (intentional — no "select all" binding in TUI):
8
+ * ↑ / k move cursor up
9
+ * ↓ / j move cursor down
10
+ * space toggle the checked state of the current item
11
+ * enter confirm → onConfirm(selected[])
12
+ * esc cancel → onCancel()
13
+ *
14
+ * The selected array preserves the original option order, not toggle order.
15
+ */
16
+
17
+ interface Item {
18
+ value: string;
19
+ label: string;
20
+ description?: string;
21
+ checked: boolean;
22
+ }
23
+
24
+ /**
25
+ * Minimal shape of pi-tui's `Component` interface — we avoid importing from
26
+ * `@mariozechner/pi-tui` directly so this module stays compile-friendly when
27
+ * that peer dep isn't present (e.g. in unit tests running via vitest without
28
+ * the full pi runtime).
29
+ */
30
+ export interface ComponentLike {
31
+ render(width: number): string[];
32
+ handleInput?(data: string): void;
33
+ }
34
+
35
+ const CURSOR = "▸ ";
36
+ const NO_CURSOR = " ";
37
+ const CHECKED = "[x]";
38
+ const UNCHECKED = "[ ]";
39
+ const FOOTER_HINT = "space toggle · enter confirm · esc cancel";
40
+
41
+ const MAX_VISIBLE = 10;
42
+
43
+ function truncate(text: string, maxWidth: number): string {
44
+ if (maxWidth <= 1) return "";
45
+ if (text.length <= maxWidth) return text;
46
+ if (maxWidth <= 1) return "…";
47
+ return text.slice(0, Math.max(0, maxWidth - 1)) + "…";
48
+ }
49
+
50
+ export class MultiSelectList implements ComponentLike {
51
+ private items: Item[];
52
+ private cursor = 0;
53
+ private scrollOffset = 0;
54
+
55
+ onConfirm?: (selectedValues: string[]) => void;
56
+ onCancel?: () => void;
57
+
58
+ constructor(
59
+ private title: string,
60
+ options: string[],
61
+ private message?: string,
62
+ ) {
63
+ this.items = options.map((opt) => ({
64
+ value: opt,
65
+ label: opt,
66
+ checked: false,
67
+ }));
68
+ }
69
+
70
+ /** Expose current state for testing / adapters. */
71
+ getItems(): readonly Item[] {
72
+ return this.items;
73
+ }
74
+ getCursor(): number {
75
+ return this.cursor;
76
+ }
77
+
78
+ /** Return values of currently checked items in original option order. */
79
+ private selectedValues(): string[] {
80
+ return this.items.filter((it) => it.checked).map((it) => it.value);
81
+ }
82
+
83
+ render(width: number): string[] {
84
+ const lines: string[] = [];
85
+ if (this.title) lines.push(truncate(this.title, width));
86
+ if (this.message) lines.push(truncate(this.message, width));
87
+ if (lines.length > 0) lines.push("");
88
+
89
+ // Scroll window around cursor.
90
+ const visible = Math.min(MAX_VISIBLE, this.items.length);
91
+ if (this.cursor < this.scrollOffset) {
92
+ this.scrollOffset = this.cursor;
93
+ } else if (this.cursor >= this.scrollOffset + visible) {
94
+ this.scrollOffset = this.cursor - visible + 1;
95
+ }
96
+
97
+ for (let i = 0; i < visible; i++) {
98
+ const idx = this.scrollOffset + i;
99
+ const item = this.items[idx];
100
+ if (!item) break;
101
+ const marker = idx === this.cursor ? CURSOR : NO_CURSOR;
102
+ const box = item.checked ? CHECKED : UNCHECKED;
103
+ let line = `${marker}${box} ${item.label}`;
104
+ if (item.description) line += ` — ${item.description}`;
105
+ lines.push(truncate(line, width));
106
+ }
107
+
108
+ if (this.items.length > visible) {
109
+ lines.push(` (${this.cursor + 1}/${this.items.length})`);
110
+ }
111
+
112
+ lines.push("");
113
+ lines.push(truncate(FOOTER_HINT, width));
114
+ return lines;
115
+ }
116
+
117
+ handleInput(data: string): void {
118
+ // Escape
119
+ if (data === "\u001b" || data === "\x1b") {
120
+ this.onCancel?.();
121
+ return;
122
+ }
123
+ // Enter (CR or LF)
124
+ if (data === "\r" || data === "\n") {
125
+ this.onConfirm?.(this.selectedValues());
126
+ return;
127
+ }
128
+ // Space — toggle current
129
+ if (data === " ") {
130
+ const item = this.items[this.cursor];
131
+ if (item) item.checked = !item.checked;
132
+ return;
133
+ }
134
+ // Arrow up / k
135
+ if (data === "\u001b[A" || data === "k") {
136
+ if (this.cursor > 0) this.cursor--;
137
+ return;
138
+ }
139
+ // Arrow down / j
140
+ if (data === "\u001b[B" || data === "j") {
141
+ if (this.cursor < this.items.length - 1) this.cursor++;
142
+ return;
143
+ }
144
+ // Everything else (including "a", "A", bulk-toggle attempts) is a no-op.
145
+ }
146
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Polyfill for `ctx.ui.multiselect(...)` — a method the dashboard bridge's
3
+ * `ask_user` tool advertises but which `pi-coding-agent`'s
4
+ * `ExtensionUIContext` does not expose. Without this, any TUI dispatch of
5
+ * `method: "multiselect"` crashes with `"ctx.ui.multiselect is not a function"`.
6
+ *
7
+ * Implementation strategy: always delegate to the already-exposed
8
+ * `ctx.ui.custom<T>()` primitive, which takes a factory that returns a
9
+ * focused pi-tui `Component`. We instantiate a `MultiSelectList`, wire
10
+ * `onConfirm` → `done(selected)` and `onCancel` → `done(undefined)`, and
11
+ * return the component.
12
+ *
13
+ * The result contract matches what the current (broken) call expects:
14
+ * - resolves to `string[]` when the user confirms a selection
15
+ * (possibly empty if nothing is checked)
16
+ * - resolves to `undefined` when the user cancels (Escape)
17
+ */
18
+ import { MultiSelectList } from "./multiselect-list.js";
19
+
20
+ // Intentionally loose: `ctx` shape varies slightly across pi versions; the
21
+ // polyfill only needs `ctx.ui.custom`.
22
+ export interface PolyfillCtx {
23
+ ui: {
24
+ custom<T>(
25
+ factory: (tui: unknown, theme: unknown, keybindings: unknown, done: (result: T) => void) => unknown,
26
+ options?: unknown,
27
+ ): Promise<T>;
28
+ };
29
+ }
30
+
31
+ export function polyfillMultiselect(
32
+ ctx: PolyfillCtx,
33
+ title: string,
34
+ options: string[],
35
+ opts?: { message?: string },
36
+ ): Promise<string[] | undefined> {
37
+ return ctx.ui.custom<string[] | undefined>((_tui, _theme, _keybindings, done) => {
38
+ const list = new MultiSelectList(title, options, opts?.message);
39
+ list.onConfirm = (selected) => done(selected);
40
+ list.onCancel = () => done(undefined);
41
+ return list as unknown;
42
+ });
43
+ }
@@ -11,6 +11,7 @@ import { createRequire } from "node:module";
11
11
  import { fileURLToPath } from "node:url";
12
12
  import type { DashboardConfig } from "@blackbelt-technology/pi-dashboard-shared/config.js";
13
13
  import { resolveJitiImport } from "@blackbelt-technology/pi-dashboard-shared/resolve-jiti.js";
14
+ import { toFileUrl, shouldUrlWrapEntry } from "@blackbelt-technology/pi-dashboard-shared/platform/node-spawn.js";
14
15
  import { isDashboardRunning } from "@blackbelt-technology/pi-dashboard-shared/server-identity.js";
15
16
 
16
17
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -77,11 +78,22 @@ export async function launchServer(config: DashboardConfig): Promise<LaunchResul
77
78
  );
78
79
  } catch { /* if we can't open the log, spawn still works */ }
79
80
 
80
- // Spawn server via the detached-spawn primitive. resolveJitiImport()
81
- // returns a file:// URL (required on Windows for node --import).
81
+ // Spawn server via the detached-spawn primitive. The loader is always
82
+ // URL-wrapped (Node needs file:// for --import on Windows drive letters).
83
+ // The entry is URL-wrapped only on Windows + non-tsx loader (Node parses
84
+ // drive letters as URL schemes in argv); on POSIX the entry MUST be raw
85
+ // because jiti's resolver misbehaves on file:// URL entries. See
86
+ // openspec/changes/archive/2026-04-24-fix-windows-entry-script-url.
87
+ const loader = resolveJitiImport();
88
+ const wrapEntry = shouldUrlWrapEntry(loader);
89
+ // entry is gated by shouldUrlWrapEntry(loader): returns true only on
90
+ // Windows + non-tsx (where URL wrap is required); false on POSIX
91
+ // where jiti needs the raw path (file:// URL entries trigger jiti's
92
+ // `<cwd>/file:/...` misresolution bug).
93
+ const entry = wrapEntry ? toFileUrl(cliPath) : cliPath;
82
94
  const r = await spawnDetached({
83
95
  cmd: process.execPath,
84
- args: ["--import", resolveJitiImport(), cliPath, ...args],
96
+ args: ["--import", loader, entry, ...args], // ban:raw-node-import-ok: entry gated by shouldUrlWrapEntry
85
97
  env: { ...process.env },
86
98
  logFd,
87
99
  });