@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.
@@ -0,0 +1,293 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
2
+ import { refreshUiModules, subscribeUiInvalidate, handleUiManagement, type UiModulesBridgeCtx } from "../ui-modules.js";
3
+ import type { ExtensionUiModule } from "@blackbelt-technology/pi-dashboard-shared/types.js";
4
+
5
+ /**
6
+ * Minimal bus + ctx harness. The real bridge wires this up via `pi.events`
7
+ * (a real `EventEmitter`); the contract this module relies on is `on` /
8
+ * `emit`, so a hand-rolled bus is sufficient for tests.
9
+ */
10
+ function createTestCtx(sessionId = "s1") {
11
+ const listeners = new Map<string, Array<(...args: any[]) => any>>();
12
+ const sent: any[] = [];
13
+
14
+ const ctx: UiModulesBridgeCtx & { _sent: any[]; _listeners: typeof listeners } = {
15
+ pi: {
16
+ events: {
17
+ on: vi.fn((event: string, fn: (...args: any[]) => any) => {
18
+ if (!listeners.has(event)) listeners.set(event, []);
19
+ listeners.get(event)!.push(fn);
20
+ }) as any,
21
+ emit: vi.fn((event: string, ...args: any[]) => {
22
+ const handlers = listeners.get(event) ?? [];
23
+ for (const h of handlers) h(...args);
24
+ }) as any,
25
+ },
26
+ },
27
+ connection: {
28
+ send: vi.fn((msg: unknown) => {
29
+ sent.push(msg);
30
+ }) as any,
31
+ },
32
+ getSessionId: () => sessionId,
33
+ _sent: sent,
34
+ _listeners: listeners,
35
+ };
36
+ return ctx;
37
+ }
38
+
39
+ const sampleModule = (id: string, command: string): ExtensionUiModule => ({
40
+ kind: "management-modal",
41
+ id,
42
+ command,
43
+ title: id,
44
+ view: { kind: "table", dataEvent: `${id}:rows`, fields: [{ key: "id", label: "ID", kind: "text" }] },
45
+ });
46
+
47
+ describe("refreshUiModules", () => {
48
+ it("emits ui:list-modules and forwards collected modules as ui_modules_list", () => {
49
+ const ctx = createTestCtx("session-A");
50
+ ctx._listeners.set("ui:list-modules", [
51
+ (probe: { modules: ExtensionUiModule[] }) => {
52
+ probe.modules.push(sampleModule("judo-status", "/judo:status"));
53
+ probe.modules.push(sampleModule("ragger-workspaces", "/ragger:workspaces"));
54
+ },
55
+ ]);
56
+
57
+ refreshUiModules(ctx);
58
+
59
+ expect(ctx.pi.events!.emit).toHaveBeenCalledWith("ui:list-modules", expect.any(Object));
60
+ expect(ctx._sent).toHaveLength(1);
61
+ expect(ctx._sent[0]).toMatchObject({
62
+ type: "ui_modules_list",
63
+ sessionId: "session-A",
64
+ modules: [
65
+ expect.objectContaining({ id: "judo-status", command: "/judo:status" }),
66
+ expect.objectContaining({ id: "ragger-workspaces", command: "/ragger:workspaces" }),
67
+ ],
68
+ });
69
+ });
70
+
71
+ it("forwards an empty modules list when no listeners push", () => {
72
+ const ctx = createTestCtx();
73
+ refreshUiModules(ctx);
74
+ expect(ctx._sent).toEqual([{ type: "ui_modules_list", sessionId: "s1", modules: [] }]);
75
+ });
76
+
77
+ it("last-write-wins on duplicate id and warns once per collision", () => {
78
+ const ctx = createTestCtx();
79
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
80
+ try {
81
+ ctx._listeners.set("ui:list-modules", [
82
+ (probe: { modules: ExtensionUiModule[] }) => {
83
+ // First push wins on insertion order; second push for same id replaces it.
84
+ const a: ExtensionUiModule = { ...sampleModule("dup", "/a"), title: "First" };
85
+ const b: ExtensionUiModule = { ...sampleModule("dup", "/b"), title: "Second" };
86
+ const c: ExtensionUiModule = { ...sampleModule("dup", "/c"), title: "Third" };
87
+ probe.modules.push(a, b, c);
88
+ },
89
+ ]);
90
+
91
+ refreshUiModules(ctx);
92
+
93
+ const sent = ctx._sent[0] as { modules: ExtensionUiModule[] };
94
+ expect(sent.modules).toHaveLength(1);
95
+ expect(sent.modules[0]).toMatchObject({ id: "dup", title: "Third", command: "/c" });
96
+ // Two collisions reported, but only one warning per id.
97
+ expect(warn).toHaveBeenCalledTimes(1);
98
+ expect(warn.mock.calls[0]?.[0]).toMatch(/duplicate module id "dup"/);
99
+ } finally {
100
+ warn.mockRestore();
101
+ }
102
+ });
103
+
104
+ it("ignores modules with missing/empty id", () => {
105
+ const ctx = createTestCtx();
106
+ ctx._listeners.set("ui:list-modules", [
107
+ (probe: { modules: any[] }) => {
108
+ probe.modules.push({ kind: "management-modal", id: "", command: "/x", title: "x", view: { kind: "table" } });
109
+ probe.modules.push({ kind: "management-modal", command: "/y", title: "y", view: { kind: "table" } });
110
+ probe.modules.push(sampleModule("ok", "/ok"));
111
+ },
112
+ ]);
113
+
114
+ refreshUiModules(ctx);
115
+ const sent = ctx._sent[0] as { modules: ExtensionUiModule[] };
116
+ expect(sent.modules.map((m) => m.id)).toEqual(["ok"]);
117
+ });
118
+
119
+ it("does not throw or send when pi.events is missing", () => {
120
+ const ctx = createTestCtx();
121
+ ctx.pi = { events: undefined as any };
122
+ expect(() => refreshUiModules(ctx)).not.toThrow();
123
+ expect(ctx._sent).toHaveLength(0);
124
+ });
125
+
126
+ it("absorbs handler errors without breaking the bridge", () => {
127
+ const ctx = createTestCtx();
128
+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
129
+ try {
130
+ ctx._listeners.set("ui:list-modules", [
131
+ () => {
132
+ throw new Error("listener exploded");
133
+ },
134
+ ]);
135
+ expect(() => refreshUiModules(ctx)).not.toThrow();
136
+ expect(errSpy).toHaveBeenCalled();
137
+ expect(ctx._sent).toHaveLength(0);
138
+ } finally {
139
+ errSpy.mockRestore();
140
+ }
141
+ });
142
+ });
143
+
144
+ describe("subscribeUiInvalidate", () => {
145
+ it("re-runs the probe whenever ui:invalidate fires (leading + trailing throttle, see Phase 2)", () => {
146
+ vi.useFakeTimers();
147
+ try {
148
+ const ctx = createTestCtx();
149
+ ctx._listeners.set("ui:list-modules", [
150
+ (probe: { modules: ExtensionUiModule[] }) => {
151
+ probe.modules.push(sampleModule("a", "/a"));
152
+ },
153
+ ]);
154
+
155
+ subscribeUiInvalidate(ctx);
156
+ // First emit triggers a leading-edge probe immediately.
157
+ ctx.pi.events!.emit("ui:invalidate", { id: "a" });
158
+ expect(ctx._sent).toHaveLength(1);
159
+ expect((ctx._sent[0] as any).type).toBe("ui_modules_list");
160
+
161
+ // Second emit within the throttle window coalesces into a trailing-edge
162
+ // probe; advance timers past the 50ms window to flush it.
163
+ ctx.pi.events!.emit("ui:invalidate", {});
164
+ vi.advanceTimersByTime(100);
165
+ expect(ctx._sent).toHaveLength(2);
166
+ } finally {
167
+ vi.useRealTimers();
168
+ }
169
+ });
170
+
171
+ it("is a no-op when pi.events.on is missing", () => {
172
+ const ctx = createTestCtx();
173
+ ctx.pi = { events: { emit: vi.fn() as any } as any };
174
+ expect(() => subscribeUiInvalidate(ctx)).not.toThrow();
175
+ });
176
+ });
177
+
178
+ describe("handleUiManagement", () => {
179
+ it("re-emits the event on pi.events with action and _reply injected, and forwards synchronous data.items", () => {
180
+ const ctx = createTestCtx("S");
181
+ ctx._listeners.set("judo:status-rows", [
182
+ (data: { action: string; items?: unknown[] }) => {
183
+ expect(data.action).toBe("list");
184
+ data.items = [{ id: 1 }, { id: 2 }];
185
+ },
186
+ ]);
187
+
188
+ handleUiManagement(ctx, {
189
+ type: "ui_management",
190
+ sessionId: "S",
191
+ action: "list",
192
+ event: "judo:status-rows",
193
+ });
194
+
195
+ expect(ctx.pi.events!.emit).toHaveBeenCalledWith("judo:status-rows", expect.any(Object));
196
+ expect(ctx._sent).toEqual([
197
+ { type: "ui_data_list", sessionId: "S", event: "judo:status-rows", items: [{ id: 1 }, { id: 2 }] },
198
+ ]);
199
+ });
200
+
201
+ it("supports async _reply path (extension calls _reply asynchronously)", () => {
202
+ const ctx = createTestCtx();
203
+ ctx._listeners.set("judo:rows", [
204
+ (data: { _reply: (items: unknown[]) => void }) => {
205
+ // Simulate async: call _reply later in this tick.
206
+ setTimeout(() => data._reply([{ id: 7 }]), 0);
207
+ },
208
+ ]);
209
+
210
+ handleUiManagement(ctx, { type: "ui_management", sessionId: "s1", action: "list", event: "judo:rows" });
211
+ // Synchronous fast-path didn't fire because data.items wasn't set.
212
+ expect(ctx._sent).toHaveLength(0);
213
+ return new Promise<void>((resolve) => {
214
+ setTimeout(() => {
215
+ expect(ctx._sent).toEqual([
216
+ { type: "ui_data_list", sessionId: "s1", event: "judo:rows", items: [{ id: 7 }] },
217
+ ]);
218
+ resolve();
219
+ }, 5);
220
+ });
221
+ });
222
+
223
+ it("does not double-send if both data.items is set and _reply is called", () => {
224
+ const ctx = createTestCtx();
225
+ ctx._listeners.set("e", [
226
+ (data: { _reply: (items: unknown[]) => void; items?: unknown[] }) => {
227
+ data._reply([1, 2]);
228
+ data.items = [3, 4];
229
+ },
230
+ ]);
231
+ handleUiManagement(ctx, { type: "ui_management", sessionId: "s1", action: "list", event: "e" });
232
+ // _reply ran synchronously inside the emit; data.items fast-path is gated by `replied`.
233
+ expect(ctx._sent).toHaveLength(1);
234
+ expect((ctx._sent[0] as any).items).toEqual([1, 2]);
235
+ });
236
+
237
+ it("does NOT send a ui_data_list for fire-and-forget actions (no items, no _reply)", () => {
238
+ const ctx = createTestCtx();
239
+ ctx._listeners.set("judo:delete-row", [() => { /* side-effect only */ }]);
240
+ handleUiManagement(ctx, {
241
+ type: "ui_management",
242
+ sessionId: "s1",
243
+ action: "delete",
244
+ event: "judo:delete-row",
245
+ params: { id: 42 },
246
+ });
247
+ expect(ctx._sent).toHaveLength(0);
248
+ });
249
+
250
+ it("forwards the action and params verbatim to listeners", () => {
251
+ const ctx = createTestCtx();
252
+ let captured: any = null;
253
+ ctx._listeners.set("e", [(data: any) => { captured = { ...data }; }]);
254
+ handleUiManagement(ctx, {
255
+ type: "ui_management",
256
+ sessionId: "s1",
257
+ action: "delete",
258
+ event: "e",
259
+ params: { id: 42, force: true },
260
+ });
261
+ expect(captured).toMatchObject({ action: "delete", id: 42, force: true });
262
+ expect(typeof captured._reply).toBe("function");
263
+ });
264
+
265
+ it("absorbs handler errors without sending data", () => {
266
+ const ctx = createTestCtx();
267
+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
268
+ try {
269
+ ctx._listeners.set("explode", [() => { throw new Error("boom"); }]);
270
+ expect(() => handleUiManagement(ctx, { type: "ui_management", sessionId: "s1", action: "list", event: "explode" })).not.toThrow();
271
+ expect(errSpy).toHaveBeenCalled();
272
+ expect(ctx._sent).toHaveLength(0);
273
+ } finally {
274
+ errSpy.mockRestore();
275
+ }
276
+ });
277
+ });
278
+
279
+ describe("Bridge invariants", () => {
280
+ it("ui-modules.ts does not import pi.newSession / ctx.fork / ctx.switchSession", async () => {
281
+ // Mirrors the contract checked by `no-session-replacement-calls.test.ts`,
282
+ // but localized to the new module so a regression is caught at unit-test
283
+ // granularity in addition to the global lint test.
284
+ const fs = await import("node:fs/promises");
285
+ const url = await import("node:url");
286
+ const path = await import("node:path");
287
+ const here = path.dirname(url.fileURLToPath(import.meta.url));
288
+ const src = await fs.readFile(path.join(here, "..", "ui-modules.ts"), "utf8");
289
+ expect(src).not.toMatch(/pi\.newSession\s*\(/);
290
+ expect(src).not.toMatch(/ctx\.fork\s*\(/);
291
+ expect(src).not.toMatch(/ctx\.switchSession\s*\(/);
292
+ });
293
+ });
@@ -6,61 +6,76 @@
6
6
  * register ask_user. Runtime registration bypasses detectExtensionConflicts.
7
7
  */
8
8
  import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
9
- import { Type } from "@sinclair/typebox";
9
+ import { Type } from "typebox";
10
+ import { polyfillMultiselect } from "./multiselect-polyfill.js";
10
11
 
11
12
  // ──────────────────────────────────────────────────────────────────────────
12
- // Single-question schema arms (reused inside the batch arm's questions array)
13
+ // Schema definition
14
+ //
15
+ // IMPORTANT: We use a single flat `Type.Object` at the root (rather than a
16
+ // `Type.Union` of per-method object arms) so the generated JSON Schema has
17
+ // `"type": "object"` at the root.
18
+ //
19
+ // Rationale: OpenAI's function-calling validator (and especially the strict
20
+ // mode used by GPT-4.1+/GPT-5.x/Codex/Responses API) REQUIRES the parameters
21
+ // schema to be an object at the root. A `Type.Union` produces `anyOf` at the
22
+ // root with no `type` field, which Anthropic accepts but OpenAI rejects with:
23
+ // "Invalid schema for function 'ask_user': schema must be a JSON Schema
24
+ // of 'type: \"object\"', got 'type: \"None\"'."
25
+ //
26
+ // Per-method validation (which fields are required for which `method`) is
27
+ // enforced at runtime by `prepareArguments` (rescue/normalization) and the
28
+ // `execute` switch below — the JSON Schema only needs to describe the union
29
+ // of allowed fields.
13
30
  // ──────────────────────────────────────────────────────────────────────────
14
31
 
15
- const ConfirmSchema = Type.Object({
16
- method: Type.Literal("confirm", { description: "Yes/no question" }),
17
- title: Type.String({ description: "The question to confirm" }),
18
- message: Type.Optional(Type.String({ description: "Additional context or detailed question body" })),
19
- });
20
-
21
- const SelectSchema = Type.Object({
22
- method: Type.Literal("select", { description: "Pick one option from a list" }),
23
- title: Type.String({ description: "Short title for the question" }),
24
- options: Type.Array(Type.String(), {
25
- minItems: 2,
26
- description: "Options the user chooses between (at least 2; use 'confirm' for yes/no)",
27
- }),
28
- message: Type.Optional(Type.String({ description: "Additional context" })),
29
- });
30
-
31
- const MultiselectSchema = Type.Object({
32
- method: Type.Literal("multiselect", { description: "Pick multiple options from a list" }),
33
- title: Type.String({ description: "Short title for the question" }),
34
- options: Type.Array(Type.String(), {
35
- minItems: 1,
36
- description: "Options the user can multi-select",
37
- }),
38
- message: Type.Optional(Type.String({ description: "Additional context" })),
39
- });
40
-
41
- const InputSchema = Type.Object({
42
- method: Type.Literal("input", { description: "Free-text input" }),
43
- title: Type.String({ description: "Short title for the question" }),
44
- placeholder: Type.Optional(Type.String({ description: "Placeholder text for the input field" })),
45
- message: Type.Optional(Type.String({ description: "Additional context" })),
46
- });
47
-
48
- // Sub-question union deliberately omits the batch arm (no nesting).
49
- const SubQuestionSchema = Type.Union([ConfirmSchema, SelectSchema, MultiselectSchema, InputSchema], {
50
- description: "A single question inside a batch. Must not itself be a batch.",
51
- });
52
-
53
- const BatchSchema = Type.Object({
54
- method: Type.Literal("batch", {
55
- description: "Ask multiple related questions in one call; answers are returned as an ordered array.",
56
- }),
57
- title: Type.String({ description: "Header shown above the sequence of dialogs" }),
58
- questions: Type.Array(SubQuestionSchema, {
59
- minItems: 1,
60
- description: "One or more sub-questions (confirm/select/multiselect/input). Cannot nest batch.",
61
- }),
62
- message: Type.Optional(Type.String({ description: "Additional context for the whole batch" })),
63
- });
32
+ const MethodEnum = Type.Union(
33
+ [
34
+ Type.Literal("confirm"),
35
+ Type.Literal("select"),
36
+ Type.Literal("multiselect"),
37
+ Type.Literal("input"),
38
+ Type.Literal("batch"),
39
+ ],
40
+ {
41
+ description:
42
+ "Question kind. 'confirm' = yes/no, 'select' = pick one of options[], 'multiselect' = pick many of options[], 'input' = free text, 'batch' = ask several questions in one call (provide questions[]).",
43
+ },
44
+ );
45
+
46
+ // Sub-question schema for batch.method — flat object (no nested union) so the
47
+ // emitted JSON Schema stays OpenAI-compatible at every level. Sub-questions
48
+ // cannot themselves be a batch (no nesting); enforced at runtime.
49
+ const SubQuestionSchema = Type.Object(
50
+ {
51
+ method: Type.Union(
52
+ [
53
+ Type.Literal("confirm"),
54
+ Type.Literal("select"),
55
+ Type.Literal("multiselect"),
56
+ Type.Literal("input"),
57
+ ],
58
+ { description: "Sub-question kind. Cannot be 'batch' (no nesting)." },
59
+ ),
60
+ title: Type.String({ description: "Short title / question text for this sub-question" }),
61
+ options: Type.Optional(
62
+ Type.Array(Type.String(), {
63
+ description:
64
+ "Required for 'select' (>=2) and 'multiselect' (>=1). Plain string[] — not [{label,value}].",
65
+ }),
66
+ ),
67
+ placeholder: Type.Optional(
68
+ Type.String({ description: "Placeholder for 'input' method" }),
69
+ ),
70
+ message: Type.Optional(
71
+ Type.String({ description: "Additional context for this sub-question" }),
72
+ ),
73
+ },
74
+ {
75
+ description:
76
+ "A single question inside a batch. Must not itself be a batch.",
77
+ },
78
+ );
64
79
 
65
80
  // ──────────────────────────────────────────────────────────────────────────
66
81
  // Argument rescue helpers
@@ -121,7 +136,7 @@ export function registerAskUserTool(pi: ExtensionAPI): void {
121
136
  name: "ask_user",
122
137
  label: "Ask User",
123
138
  description:
124
- "Ask the user a question interactively. Use this when you need clarification, confirmation, or a choice from the user before proceeding.",
139
+ "Ask the user a question interactively. Use this when you need clarification, confirmation, or a choice from the user before proceeding. UI provides a Select all toggle; do not add one.",
125
140
  promptSnippet:
126
141
  "Ask the user interactive questions (confirm, select, multiselect, input, or batch — multiple related questions at once)",
127
142
  promptGuidelines: [
@@ -131,9 +146,42 @@ export function registerAskUserTool(pi: ExtensionAPI): void {
131
146
  "Do not nest batches. Send `options` as a plain string[] — not [{label, value}].",
132
147
  "This applies to all workflows including OpenSpec, planning, and any situation where you need user input before proceeding.",
133
148
  ],
134
- parameters: Type.Union(
135
- [ConfirmSchema, SelectSchema, MultiselectSchema, InputSchema, BatchSchema],
136
- { description: "Parameters for ask_user, discriminated by method." },
149
+ // Flat object schema (root: type=object) for OpenAI/Anthropic compatibility.
150
+ // Field requirements per method are enforced at runtime, not via JSON Schema.
151
+ parameters: Type.Object(
152
+ {
153
+ method: MethodEnum,
154
+ title: Type.Optional(
155
+ Type.String({
156
+ description:
157
+ "Short title / question text. Required for all methods except when 'questions' carry it (batch may omit and inherit from first sub-question).",
158
+ }),
159
+ ),
160
+ message: Type.Optional(
161
+ Type.String({ description: "Additional context shown alongside the question(s)." }),
162
+ ),
163
+ options: Type.Optional(
164
+ Type.Array(Type.String(), {
165
+ description:
166
+ "Required for method 'select' (>=2 items) and 'multiselect' (>=1 item). Plain string[] — not [{label,value}]. Ignored for other methods.",
167
+ }),
168
+ ),
169
+ placeholder: Type.Optional(
170
+ Type.String({
171
+ description: "Placeholder for method 'input'. Ignored for other methods.",
172
+ }),
173
+ ),
174
+ questions: Type.Optional(
175
+ Type.Array(SubQuestionSchema, {
176
+ description:
177
+ "Required for method 'batch' (>=1 sub-question). Each sub-question is its own confirm/select/multiselect/input — cannot nest 'batch'.",
178
+ }),
179
+ ),
180
+ },
181
+ {
182
+ description:
183
+ "Parameters for ask_user. The required fields depend on `method`: confirm→title; select→title+options(>=2); multiselect→title+options(>=1); input→title (placeholder optional); batch→questions[] (title auto-derived from first question if omitted). Validation is enforced at runtime.",
184
+ },
137
185
  ),
138
186
  prepareArguments(args: unknown) {
139
187
  let obj = (args && typeof args === "object" ? { ...(args as Record<string, unknown>) } : {}) as Record<string, unknown>;
@@ -254,7 +302,7 @@ export function registerAskUserTool(pi: ExtensionAPI): void {
254
302
  `ask_user batch: sub-question method "multiselect" requires a non-empty "options" array.`,
255
303
  );
256
304
  }
257
- answer = await (ctx.ui as any).multiselect(subTitle, opts, subMsg);
305
+ answer = await polyfillMultiselect(ctx, subTitle, opts, subMsg);
258
306
  break;
259
307
  }
260
308
  case "input":
@@ -336,7 +384,7 @@ export function registerAskUserTool(pi: ExtensionAPI): void {
336
384
  result = await ctx.ui.select(title, options, msgOpts);
337
385
  break;
338
386
  case "multiselect":
339
- result = await (ctx.ui as any).multiselect(title, options, msgOpts);
387
+ result = await polyfillMultiselect(ctx, title, options, msgOpts);
340
388
  break;
341
389
  case "input":
342
390
  result = await ctx.ui.input(title, params.placeholder, msgOpts);