@blackbelt-technology/pi-dashboard-extension 0.4.1 → 0.4.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blackbelt-technology/pi-dashboard-extension",
3
- "version": "0.4.1",
3
+ "version": "0.4.3",
4
4
  "description": "Pi bridge extension for pi-dashboard",
5
5
  "type": "module",
6
6
  "repository": {
@@ -24,7 +24,7 @@
24
24
  ".pi/skills/pi-dashboard/"
25
25
  ],
26
26
  "dependencies": {
27
- "@blackbelt-technology/pi-dashboard-shared": "^0.4.1",
27
+ "@blackbelt-technology/pi-dashboard-shared": "^0.4.3",
28
28
  "ws": "^8.18.0"
29
29
  },
30
30
  "peerDependencies": {
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Regression guard for the `ask_user` tool's parameters JSON Schema shape.
3
+ *
4
+ * History:
5
+ * 1. Pre-a53933f — schema was `Type.Union` of per-method `Type.Object`
6
+ * arms (root-level `anyOf`). Anthropic loved it; OpenAI rejected it
7
+ * ("schema must be a JSON Schema of 'type: \"object\"', got
8
+ * 'type: \"None\"'").
9
+ *
10
+ * 2. a53933f — collapsed to a single flat `Type.Object` (root
11
+ * `type: "object"`, all fields optional). OpenAI happy. Anthropic
12
+ * lost its per-method strictness; Claude started emitting
13
+ * multiselect calls without `options` and the dashboard auto-
14
+ * cancelled them — the user-visible bug behind
15
+ * fix-multiselect-auto-cancel-on-dashboard.
16
+ *
17
+ * 3. Layer-2 attempt of fix-multiselect-auto-cancel-on-dashboard —
18
+ * tried to keep root `type: "object"` AND attach a body-level
19
+ * `oneOf` discriminator over `method`. Anthropic worked. Real
20
+ * OpenAI gpt-5 rejected it (verified 2026-04-30) with: "schema
21
+ * must have type 'object' and not have 'oneOf' / 'anyOf' / 'allOf'
22
+ * / 'enum' / 'not' at the top level." The fallback documented in
23
+ * tasks.md §9.7 was taken: Layer 2 dropped, Layer 1 (multiselect
24
+ * dashboard routing) ships alone — that's what actually fixes the
25
+ * user bug.
26
+ *
27
+ * This test pins the post-fallback shape so it cannot regress in
28
+ * either direction:
29
+ * • Root MUST be `type: "object"` (OpenAI rule).
30
+ * • Root MUST NOT have `oneOf`, `anyOf`, `allOf`, `enum`, `not`.
31
+ * • The same five forbidden keys MUST NOT appear on `SubQuestionSchema`
32
+ * either — OpenAI applies the rule recursively per the error message.
33
+ *
34
+ * Per-method strictness is enforced by `prepareArguments` rescue + the
35
+ * `execute` runtime switch (covered by `ask-user-tool.test.ts`).
36
+ *
37
+ * See change: fix-multiselect-auto-cancel-on-dashboard.
38
+ */
39
+ import { describe, it, expect, vi } from "vitest";
40
+ import { registerAskUserTool } from "../ask-user-tool.js";
41
+
42
+ const FORBIDDEN_TOP_LEVEL_KEYS = ["oneOf", "anyOf", "allOf", "enum", "not"] as const;
43
+
44
+ interface PiSchema {
45
+ type?: string;
46
+ properties?: Record<string, any>;
47
+ required?: string[];
48
+ description?: string;
49
+ oneOf?: unknown;
50
+ anyOf?: unknown;
51
+ allOf?: unknown;
52
+ enum?: unknown;
53
+ not?: unknown;
54
+ }
55
+
56
+ function captureRegisteredTool() {
57
+ const calls: any[] = [];
58
+ const pi = {
59
+ registerTool: vi.fn((def: any) => calls.push(def)),
60
+ };
61
+ registerAskUserTool(pi as any);
62
+ expect(calls.length).toBe(1);
63
+ return calls[0];
64
+ }
65
+
66
+ function getSubQuestionSchema(parameters: PiSchema): PiSchema {
67
+ const items = parameters.properties?.questions?.items;
68
+ expect(items).toBeDefined();
69
+ return items as PiSchema;
70
+ }
71
+
72
+ // Walk a Union<Literal> schema (typebox emits it as `anyOf` of `{const: ...}`)
73
+ // into a flat list of literal values.
74
+ function flattenUnionLiterals(s: any): string[] {
75
+ if (!s) return [];
76
+ if (Array.isArray(s.anyOf)) return s.anyOf.flatMap(flattenUnionLiterals);
77
+ if (s.const !== undefined) return [String(s.const)];
78
+ return [];
79
+ }
80
+
81
+ describe("ask_user parameters schema — OpenAI strict-mode shape", () => {
82
+ it("root is type:object", () => {
83
+ const tool = captureRegisteredTool();
84
+ const params = tool.parameters as PiSchema;
85
+ expect(params.type).toBe("object");
86
+ });
87
+
88
+ it.each(FORBIDDEN_TOP_LEVEL_KEYS)(
89
+ "root has NO `%s` (OpenAI strict mode forbids it at the top level)",
90
+ (key) => {
91
+ const tool = captureRegisteredTool();
92
+ const params = tool.parameters as Record<string, unknown>;
93
+ expect(
94
+ params[key],
95
+ `parameters.${key} would break OpenAI gpt-5: "schema must have type 'object' and not have 'oneOf' / 'anyOf' / 'allOf' / 'enum' / 'not' at the top level."`,
96
+ ).toBeUndefined();
97
+ },
98
+ );
99
+
100
+ it("declares the five method literals (regression guard for MethodEnum)", () => {
101
+ const tool = captureRegisteredTool();
102
+ const methodSchema = (tool.parameters as PiSchema).properties?.method;
103
+ expect(methodSchema).toBeDefined();
104
+ // typebox emits a Union<Literal> as `anyOf` UNDER `properties.method`
105
+ // (NOT at the schema root). That is OpenAI-legal because it isn't at
106
+ // the top level. We only assert the literal set is preserved.
107
+ const methods = flattenUnionLiterals(methodSchema);
108
+ expect(methods).toEqual(
109
+ expect.arrayContaining(["confirm", "select", "multiselect", "input", "batch"]),
110
+ );
111
+ });
112
+ });
113
+
114
+ describe("ask_user SubQuestionSchema — OpenAI strict-mode shape", () => {
115
+ it("sub-question schema is type:object", () => {
116
+ const tool = captureRegisteredTool();
117
+ const sq = getSubQuestionSchema(tool.parameters);
118
+ expect(sq.type).toBe("object");
119
+ });
120
+
121
+ it.each(FORBIDDEN_TOP_LEVEL_KEYS)(
122
+ "sub-question schema has NO `%s` at top level (OpenAI rule applies recursively)",
123
+ (key) => {
124
+ const tool = captureRegisteredTool();
125
+ const sq = getSubQuestionSchema(tool.parameters) as Record<string, unknown>;
126
+ expect(sq[key]).toBeUndefined();
127
+ },
128
+ );
129
+
130
+ it("sub-question excludes 'batch' from method literals (no nesting)", () => {
131
+ const tool = captureRegisteredTool();
132
+ const sq = getSubQuestionSchema(tool.parameters);
133
+ const methodSchema = sq.properties?.method;
134
+ expect(methodSchema).toBeDefined();
135
+ const methods = flattenUnionLiterals(methodSchema);
136
+ expect(methods).toEqual(
137
+ expect.arrayContaining(["confirm", "select", "multiselect", "input"]),
138
+ );
139
+ expect(methods).not.toContain("batch");
140
+ });
141
+ });
@@ -80,13 +80,24 @@ describe("registerAskUserTool", () => {
80
80
  it("passes message through opts for input", async () => {
81
81
  const { tool, ctx } = getToolAndMockCtx();
82
82
  await tool.execute("id", { method: "input", title: "Q", message: "Details here" }, undefined, undefined, ctx);
83
- expect(ctx.ui.input).toHaveBeenCalledWith("Q", undefined, { message: "Details here" });
83
+ // toolCallId is also threaded through opts since change
84
+ // `fix-interactive-ui-reorder`. Asserts both fields without
85
+ // pinning property order.
86
+ expect(ctx.ui.input).toHaveBeenCalledWith(
87
+ "Q",
88
+ undefined,
89
+ expect.objectContaining({ message: "Details here", toolCallId: "id" }),
90
+ );
84
91
  });
85
92
 
86
93
  it("passes message through opts for select", async () => {
87
94
  const { tool, ctx } = getToolAndMockCtx();
88
95
  await tool.execute("id", { method: "select", title: "Pick", message: "Context", options: ["A", "B"] }, undefined, undefined, ctx);
89
- expect(ctx.ui.select).toHaveBeenCalledWith("Pick", ["A", "B"], { message: "Context" });
96
+ expect(ctx.ui.select).toHaveBeenCalledWith(
97
+ "Pick",
98
+ ["A", "B"],
99
+ expect.objectContaining({ message: "Context", toolCallId: "id" }),
100
+ );
90
101
  });
91
102
 
92
103
  it("dispatches multiselect through the polyfill via ctx.ui.custom", async () => {
@@ -104,28 +115,48 @@ describe("registerAskUserTool", () => {
104
115
  expect(result.details.result).toEqual(["A"]);
105
116
  });
106
117
 
107
- it("does not pass opts when message is undefined", async () => {
118
+ it("passes only toolCallId through opts when message is undefined", async () => {
108
119
  const { tool, ctx } = getToolAndMockCtx();
109
120
  await tool.execute("id", { method: "input", title: "Q" }, undefined, undefined, ctx);
110
- expect(ctx.ui.input).toHaveBeenCalledWith("Q", undefined, undefined);
121
+ // Even with no `message`, the wrapper still attaches toolCallId so
122
+ // the resulting prompt_request can be paired by the client reducer.
123
+ expect(ctx.ui.input).toHaveBeenCalledWith(
124
+ "Q",
125
+ undefined,
126
+ expect.objectContaining({ toolCallId: "id" }),
127
+ );
111
128
  });
112
129
 
113
130
  it("falls back to message when title is missing", async () => {
114
131
  const { tool, ctx } = getToolAndMockCtx();
115
132
  await tool.execute("id", { method: "input", message: "Detailed question" }, undefined, undefined, ctx);
116
- expect(ctx.ui.input).toHaveBeenCalledWith("Detailed question", undefined, { message: "Detailed question" });
133
+ expect(ctx.ui.input).toHaveBeenCalledWith(
134
+ "Detailed question",
135
+ undefined,
136
+ expect.objectContaining({ message: "Detailed question", toolCallId: "id" }),
137
+ );
117
138
  });
118
139
 
119
140
  it("falls back to 'Question' when both title and message are missing", async () => {
120
141
  const { tool, ctx } = getToolAndMockCtx();
121
142
  await tool.execute("id", { method: "confirm" }, undefined, undefined, ctx);
122
- expect(ctx.ui.confirm).toHaveBeenCalledWith("Question", "");
143
+ // confirm now also threads toolCallId via 3rd arg.
144
+ expect(ctx.ui.confirm).toHaveBeenCalledWith(
145
+ "Question",
146
+ "",
147
+ expect.objectContaining({ toolCallId: "id" }),
148
+ );
123
149
  });
124
150
 
125
151
  it("parses options from JSON string", async () => {
126
152
  const { tool, ctx } = getToolAndMockCtx();
127
153
  await tool.execute("id", { method: "select", title: "Pick", options: '["A", "B"]' }, undefined, undefined, ctx);
128
- expect(ctx.ui.select).toHaveBeenCalledWith("Pick", ["A", "B"], undefined);
154
+ // No message, no other opts — only toolCallId.
155
+ expect(ctx.ui.select).toHaveBeenCalledWith(
156
+ "Pick",
157
+ ["A", "B"],
158
+ expect.objectContaining({ toolCallId: "id" }),
159
+ );
129
160
  });
130
161
 
131
162
  it("throws when select reaches execute with unparseable options string", async () => {
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Tests for the bridge's `ctx.ui.multiselect` PromptBus patch and the TUI
3
+ * adapter's multiselect handling. The patch lives in `bridge.ts` but is
4
+ * exercised here through a small reproduction harness so we don't pull in
5
+ * the full session lifecycle.
6
+ *
7
+ * See change: fix-multiselect-auto-cancel-on-dashboard.
8
+ */
9
+ import { describe, it, expect, vi, beforeEach } from "vitest";
10
+ import { decodeMultiselectAnswer } from "../multiselect-decode.js";
11
+
12
+ // ──────────────────────────────────────────────────────────────────────
13
+ // `decodeMultiselectAnswer` — pure helper used by both the runtime patch
14
+ // and the TUI adapter's response encoding round-trip.
15
+ // ──────────────────────────────────────────────────────────────────────
16
+
17
+ describe("decodeMultiselectAnswer", () => {
18
+ it("resolves cancellation as undefined", () => {
19
+ expect(decodeMultiselectAnswer({ cancelled: true })).toBeUndefined();
20
+ expect(decodeMultiselectAnswer({ cancelled: true, answer: '["x"]' })).toBeUndefined();
21
+ });
22
+
23
+ it("resolves successful selection from JSON-encoded array", () => {
24
+ expect(decodeMultiselectAnswer({ cancelled: false, answer: '["a","c"]' })).toEqual(["a", "c"]);
25
+ });
26
+
27
+ it("resolves empty selection as []", () => {
28
+ expect(decodeMultiselectAnswer({ cancelled: false, answer: "[]" })).toEqual([]);
29
+ });
30
+
31
+ it("resolves null / undefined / empty answer as [] (not undefined)", () => {
32
+ expect(decodeMultiselectAnswer({ cancelled: false, answer: undefined })).toEqual([]);
33
+ expect(decodeMultiselectAnswer({ cancelled: false, answer: "" })).toEqual([]);
34
+ });
35
+
36
+ it("resolves unparseable JSON as [] without throwing", () => {
37
+ expect(decodeMultiselectAnswer({ cancelled: false, answer: "not-json" })).toEqual([]);
38
+ expect(decodeMultiselectAnswer({ cancelled: false, answer: "{not:array}" })).toEqual([]);
39
+ });
40
+
41
+ it("resolves valid JSON that is not an array as []", () => {
42
+ expect(decodeMultiselectAnswer({ cancelled: false, answer: '"just-a-string"' })).toEqual([]);
43
+ expect(decodeMultiselectAnswer({ cancelled: false, answer: '{"k":"v"}' })).toEqual([]);
44
+ });
45
+ });
46
+
47
+ // ──────────────────────────────────────────────────────────────────────
48
+ // Bridge patch reproduction — emulate the assignment block in
49
+ // `bridge.ts:935-948` plus the new multiselect arm and assert behavior.
50
+ // We cannot import `bridge.ts` directly (it has heavy session-lifecycle
51
+ // imports), so we reproduce the assignment closure here. The closure
52
+ // shape MUST match `bridge.ts` exactly; if `bridge.ts` drifts, the
53
+ // regression guard test (see "ctx.ui.multiselect is assigned by the
54
+ // bridge patch block" below) re-loads the bridge source and asserts
55
+ // the assignment exists.
56
+ // ──────────────────────────────────────────────────────────────────────
57
+
58
+ interface BusRequestArgs {
59
+ pipeline: string;
60
+ type: string;
61
+ question: string;
62
+ options?: string[];
63
+ metadata?: Record<string, unknown>;
64
+ }
65
+
66
+ interface FakeBus {
67
+ request: (args: BusRequestArgs) => Promise<{ cancelled?: boolean; answer?: string }>;
68
+ }
69
+
70
+ function applyMultiselectPatch(
71
+ ctx: { ui: Record<string, any> },
72
+ bus: FakeBus,
73
+ ): void {
74
+ const existing = (ctx.ui as any).multiselect;
75
+ if (typeof existing === "function") {
76
+ // eslint-disable-next-line no-console
77
+ console.warn("[bridge] ctx.ui.multiselect already exists — overriding for PromptBus routing");
78
+ }
79
+ (ctx.ui as any).multiselect = (title: string, options: string[], opts?: { message?: string }) =>
80
+ bus.request({
81
+ pipeline: "command",
82
+ type: "multiselect",
83
+ question: title,
84
+ options,
85
+ metadata: opts?.message ? { message: opts.message } : undefined,
86
+ }).then((r) => decodeMultiselectAnswer(r));
87
+ }
88
+
89
+ describe("bridge ctx.ui.multiselect patch", () => {
90
+ let ctx: { ui: Record<string, any> };
91
+ let bus: FakeBus;
92
+ let requestSpy: ReturnType<typeof vi.fn>;
93
+
94
+ beforeEach(() => {
95
+ requestSpy = vi.fn();
96
+ bus = { request: requestSpy as any };
97
+ ctx = { ui: {} };
98
+ });
99
+
100
+ it("assigns ctx.ui.multiselect as a function after the patch runs", () => {
101
+ expect(typeof ctx.ui.multiselect).toBe("undefined");
102
+ applyMultiselectPatch(ctx, bus);
103
+ expect(typeof ctx.ui.multiselect).toBe("function");
104
+ });
105
+
106
+ it("dispatches bus.request with the right shape on call", async () => {
107
+ applyMultiselectPatch(ctx, bus);
108
+ requestSpy.mockResolvedValue({ cancelled: false, answer: '["a","c"]' });
109
+
110
+ const result = await ctx.ui.multiselect("Pick", ["a", "b", "c"], { message: "ctx" });
111
+
112
+ expect(requestSpy).toHaveBeenCalledTimes(1);
113
+ expect(requestSpy).toHaveBeenCalledWith({
114
+ pipeline: "command",
115
+ type: "multiselect",
116
+ question: "Pick",
117
+ options: ["a", "b", "c"],
118
+ metadata: { message: "ctx" },
119
+ });
120
+ expect(result).toEqual(["a", "c"]);
121
+ });
122
+
123
+ it("omits metadata when no message is provided", async () => {
124
+ applyMultiselectPatch(ctx, bus);
125
+ requestSpy.mockResolvedValue({ cancelled: false, answer: "[]" });
126
+
127
+ await ctx.ui.multiselect("Pick", ["a", "b"]);
128
+
129
+ expect(requestSpy).toHaveBeenCalledWith(
130
+ expect.objectContaining({ metadata: undefined }),
131
+ );
132
+ });
133
+
134
+ it("resolves successful selection through the decoder", async () => {
135
+ applyMultiselectPatch(ctx, bus);
136
+ requestSpy.mockResolvedValue({ cancelled: false, answer: '["a","c"]' });
137
+ await expect(ctx.ui.multiselect("t", ["a", "b", "c"])).resolves.toEqual(["a", "c"]);
138
+ });
139
+
140
+ it("resolves empty selection as []", async () => {
141
+ applyMultiselectPatch(ctx, bus);
142
+ requestSpy.mockResolvedValue({ cancelled: false, answer: "[]" });
143
+ await expect(ctx.ui.multiselect("t", ["a"])).resolves.toEqual([]);
144
+ });
145
+
146
+ it("resolves cancellation as undefined", async () => {
147
+ applyMultiselectPatch(ctx, bus);
148
+ requestSpy.mockResolvedValue({ cancelled: true });
149
+ await expect(ctx.ui.multiselect("t", ["a"])).resolves.toBeUndefined();
150
+ });
151
+
152
+ it("resolves unparseable answer as [] without throwing", async () => {
153
+ applyMultiselectPatch(ctx, bus);
154
+ requestSpy.mockResolvedValue({ cancelled: false, answer: "not-json" });
155
+ await expect(ctx.ui.multiselect("t", ["a"])).resolves.toEqual([]);
156
+ });
157
+
158
+ it("warns when ctx.ui.multiselect was already a function before the patch", () => {
159
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
160
+ ctx.ui.multiselect = () => Promise.resolve(["pre-existing"]);
161
+
162
+ applyMultiselectPatch(ctx, bus);
163
+
164
+ expect(warnSpy).toHaveBeenCalledWith(
165
+ expect.stringContaining("already exists"),
166
+ );
167
+ // The patch still wins — subsequent calls go through bus.request.
168
+ requestSpy.mockResolvedValue({ cancelled: false, answer: '["winner"]' });
169
+ return ctx.ui.multiselect("t", ["a"]).then((r: any) => {
170
+ expect(r).toEqual(["winner"]);
171
+ expect(requestSpy).toHaveBeenCalled();
172
+ warnSpy.mockRestore();
173
+ });
174
+ });
175
+ });
176
+
177
+ // ──────────────────────────────────────────────────────────────────────
178
+ // Source regression guard — re-load bridge.ts as text and assert the
179
+ // multiselect patch line exists. Mirrors `no-direct-process-kill.test.ts`
180
+ // pattern: textual scan over a single file, fail with file:line if the
181
+ // expected snippet is missing or moved.
182
+ // ──────────────────────────────────────────────────────────────────────
183
+
184
+ describe("bridge.ts source regression guard", () => {
185
+ it("contains the ctx.ui.multiselect PromptBus assignment", async () => {
186
+ const fs = await import("node:fs");
187
+ const path = await import("node:path");
188
+ const url = await import("node:url");
189
+ const here = path.dirname(url.fileURLToPath(import.meta.url));
190
+ const bridgePath = path.resolve(here, "../bridge.ts");
191
+ const src = fs.readFileSync(bridgePath, "utf8");
192
+
193
+ // The assignment must mention `multiselect` as a key on ctx.ui AND
194
+ // dispatch through bus.request with type:"multiselect".
195
+ expect(src).toMatch(/\(ctx\.ui as any\)\.multiselect\s*=/);
196
+ expect(src).toMatch(/type:\s*"multiselect"/);
197
+ });
198
+
199
+ // Note: the previous-change assertions about `custom: ctx.ui.custom?.bind(...)`
200
+ // capture and the TUI `prompt.type === "multiselect"` arm were removed by
201
+ // change `fix-multiselect-tui-arm-self-cancel`. The inverse-guard for that
202
+ // removal lives in `no-tui-multiselect-arm-regression.test.ts`.
203
+ });
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Tests for `polyfillMultiselect`'s fallback chain. After the
3
+ * fix-multiselect-auto-cancel-on-dashboard change, the polyfill prefers a
4
+ * bridge-patched `ctx.ui.multiselect` (the PromptBus path that surfaces in
5
+ * the dashboard browser) and falls back to the legacy `ctx.ui.custom` +
6
+ * `MultiSelectList` overlay only when the patch is absent (older pi
7
+ * versions or non-bridge embeddings).
8
+ *
9
+ * See change: fix-multiselect-auto-cancel-on-dashboard.
10
+ */
11
+ import { describe, it, expect, vi } from "vitest";
12
+ import { polyfillMultiselect } from "../multiselect-polyfill.js";
13
+
14
+ describe("polyfillMultiselect — fallback chain", () => {
15
+ it("delegates to ctx.ui.multiselect when present (primary, bus-routed path)", async () => {
16
+ const multiselectFn = vi.fn().mockResolvedValue(["a"]);
17
+ const customFn = vi.fn();
18
+ const ctx = {
19
+ ui: {
20
+ multiselect: multiselectFn,
21
+ custom: customFn,
22
+ },
23
+ };
24
+
25
+ const result = await polyfillMultiselect(ctx as any, "Pick", ["a", "b"]);
26
+
27
+ expect(result).toEqual(["a"]);
28
+ expect(multiselectFn).toHaveBeenCalledTimes(1);
29
+ expect(multiselectFn).toHaveBeenCalledWith("Pick", ["a", "b"], undefined);
30
+ expect(customFn).not.toHaveBeenCalled();
31
+ });
32
+
33
+ it("forwards opts.message to ctx.ui.multiselect when present", async () => {
34
+ const multiselectFn = vi.fn().mockResolvedValue([]);
35
+ const ctx = { ui: { multiselect: multiselectFn, custom: vi.fn() } };
36
+
37
+ await polyfillMultiselect(ctx as any, "Pick", ["a"], { message: "ctx" });
38
+
39
+ expect(multiselectFn).toHaveBeenCalledWith("Pick", ["a"], { message: "ctx" });
40
+ });
41
+
42
+ it("propagates undefined (cancellation) through the primary path", async () => {
43
+ const multiselectFn = vi.fn().mockResolvedValue(undefined);
44
+ const ctx = { ui: { multiselect: multiselectFn, custom: vi.fn() } };
45
+
46
+ await expect(polyfillMultiselect(ctx as any, "t", ["a"])).resolves.toBeUndefined();
47
+ });
48
+
49
+ it("falls back to ctx.ui.custom when ctx.ui.multiselect is absent (TUI path)", async () => {
50
+ let capturedDone: ((r: string[] | undefined) => void) | undefined;
51
+ const customFn = vi.fn().mockImplementation((factory: any) => {
52
+ return new Promise<string[] | undefined>((resolve) => {
53
+ const done = (r: string[] | undefined) => resolve(r);
54
+ capturedDone = done;
55
+ const component = factory({}, {}, {}, done);
56
+ // Simulate user confirming after the factory wires the component.
57
+ component?.onConfirm?.(["b"]);
58
+ });
59
+ });
60
+ const ctx = { ui: { custom: customFn } };
61
+
62
+ const result = await polyfillMultiselect(ctx as any, "Pick", ["a", "b"]);
63
+
64
+ expect(result).toEqual(["b"]);
65
+ expect(customFn).toHaveBeenCalledTimes(1);
66
+ expect(capturedDone).toBeTypeOf("function");
67
+ });
68
+
69
+ it("falls back to ctx.ui.custom and resolves undefined on cancel", async () => {
70
+ const customFn = vi.fn().mockImplementation((factory: any) => {
71
+ return new Promise<string[] | undefined>((resolve) => {
72
+ const component = factory({}, {}, {}, (r: any) => resolve(r));
73
+ component?.onCancel?.();
74
+ });
75
+ });
76
+ const ctx = { ui: { custom: customFn } };
77
+
78
+ await expect(polyfillMultiselect(ctx as any, "Pick", ["a"])).resolves.toBeUndefined();
79
+ });
80
+
81
+ it("does NOT fall back to ctx.ui.custom when ctx.ui.multiselect resolves to []", async () => {
82
+ // Empty selection is a valid answer — must NOT trigger the legacy fallback.
83
+ const multiselectFn = vi.fn().mockResolvedValue([]);
84
+ const customFn = vi.fn();
85
+ const ctx = { ui: { multiselect: multiselectFn, custom: customFn } };
86
+
87
+ const result = await polyfillMultiselect(ctx as any, "t", ["a"]);
88
+
89
+ expect(result).toEqual([]);
90
+ expect(customFn).not.toHaveBeenCalled();
91
+ });
92
+ });
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Repo-level invariant: `packages/extension/src/bridge.ts` MUST NOT
3
+ * contain the co-occurrence of two substrings:
4
+ *
5
+ * 1. `originals.custom`
6
+ * 2. `prompt.type === "multiselect"`
7
+ *
8
+ * If both appear in the same file, a contributor has (re)introduced the
9
+ * TUI PromptBus-adapter multiselect arm that was removed by change
10
+ * `fix-multiselect-tui-arm-self-cancel`. The arm is forbidden because
11
+ * pi 0.70's RPC mode (the only mode dashboard headless sessions run
12
+ * under) defines `ExtensionUIContext.custom` as an unconditional no-op
13
+ * (`async custom() { return undefined; }`, see
14
+ * `~/.nvm/.../@mariozechner/pi-coding-agent/dist/modes/rpc/rpc-mode.js`
15
+ * lines 150-153). Awaiting that primitive resolves to `undefined`
16
+ * synchronously, and the TUI arm's `bus.respond({ cancelled: true,
17
+ * source: "tui" })` triggers the PromptBus's first-response-wins
18
+ * dismissal — which auto-cancels the dashboard's already-rendered
19
+ * `MultiselectRenderer` within ~1 event-loop tick.
20
+ *
21
+ * The bus-routed `(ctx.ui as any).multiselect = (...) => bus.request(...)`
22
+ * patch site uses the substring `type: "multiselect"` (object-literal
23
+ * shape), not `prompt.type === "multiselect"` (equality-check shape),
24
+ * so it is unaffected by this lint.
25
+ *
26
+ * To remove a legitimate `originals.custom` reference (e.g. for a
27
+ * future use that does not include multiselect prompt routing), keep
28
+ * one substring and ensure the other does not co-occur.
29
+ *
30
+ * See change: fix-multiselect-tui-arm-self-cancel.
31
+ */
32
+ import { describe, it, expect } from "vitest";
33
+ import fs from "node:fs/promises";
34
+ import path from "node:path";
35
+ import url from "node:url";
36
+
37
+ const FORBIDDEN_A = "originals.custom";
38
+ const FORBIDDEN_B = 'prompt.type === "multiselect"';
39
+
40
+ function findLineNumbers(src: string, needle: string): number[] {
41
+ const lines = src.split(/\r?\n/);
42
+ const hits: number[] = [];
43
+ lines.forEach((line, idx) => {
44
+ if (line.includes(needle)) hits.push(idx + 1);
45
+ });
46
+ return hits;
47
+ }
48
+
49
+ describe("no TUI multiselect arm regression in bridge.ts", () => {
50
+ it("bridge.ts MUST NOT contain both `originals.custom` and `prompt.type === \"multiselect\"`", async () => {
51
+ const here = path.dirname(url.fileURLToPath(import.meta.url));
52
+ const bridgePath = path.resolve(here, "..", "bridge.ts");
53
+ const src = await fs.readFile(bridgePath, "utf-8");
54
+
55
+ const hasA = src.includes(FORBIDDEN_A);
56
+ const hasB = src.includes(FORBIDDEN_B);
57
+
58
+ if (hasA && hasB) {
59
+ const linesA = findLineNumbers(src, FORBIDDEN_A);
60
+ const linesB = findLineNumbers(src, FORBIDDEN_B);
61
+ const msg =
62
+ `Forbidden co-occurrence in ${path.relative(process.cwd(), bridgePath)}:\n` +
63
+ ` - "${FORBIDDEN_A}" found on line(s): ${linesA.join(", ")}\n` +
64
+ ` - "${FORBIDDEN_B}" found on line(s): ${linesB.join(", ")}\n` +
65
+ `\n` +
66
+ `This pattern was removed by change "fix-multiselect-tui-arm-self-cancel".\n` +
67
+ `pi 0.70 RPC mode's ctx.ui.custom is a no-op, so a TUI multiselect\n` +
68
+ `arm that awaits originals.custom auto-cancels the dashboard-rendered\n` +
69
+ `dialog within ~1 event-loop tick. The bus-routed ctx.ui.multiselect\n` +
70
+ `patch + DashboardDefaultAdapter handle multiselect end-to-end without\n` +
71
+ `any TUI arm participation. See:\n` +
72
+ ` openspec/changes/archive/<date>-fix-multiselect-tui-arm-self-cancel/\n` +
73
+ `(or openspec/changes/fix-multiselect-tui-arm-self-cancel/ if not yet archived).`;
74
+ expect.fail(msg);
75
+ }
76
+
77
+ // Guardrail: at least one of the two substrings absent (we already
78
+ // assert above that both-present is illegal). Either-alone is fine.
79
+ expect(hasA && hasB).toBe(false);
80
+ });
81
+ });
@@ -43,9 +43,26 @@ const MethodEnum = Type.Union(
43
43
  },
44
44
  );
45
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.
46
+ // Sub-question schema for batch.method — flat object (root: type=object) so
47
+ // the emitted JSON Schema stays OpenAI-compatible at every level.
48
+ //
49
+ // IMPORTANT: this object MUST NOT carry a root-level `oneOf` / `anyOf` /
50
+ // `allOf` / `enum` / `not`. OpenAI strict mode (GPT-4.1+, GPT-5.x, Codex,
51
+ // Responses API) explicitly rejects those at *any* schema's top level
52
+ // with: "schema must have type 'object' and not have 'oneOf' / 'anyOf' /
53
+ // 'allOf' / 'enum' / 'not' at the top level." An earlier draft of
54
+ // fix-multiselect-auto-cancel-on-dashboard tried to add a body-level
55
+ // `oneOf` discriminator to restore Anthropic's per-arm strictness, but
56
+ // real-world OpenAI gpt-5 rejected it; the fallback path documented in
57
+ // tasks.md §9.7 was taken — Layer 2 dropped, Layer 1 ships alone.
58
+ //
59
+ // Per-method requirements (select/multiselect need `options`, batch
60
+ // needs `questions[]`, etc.) are enforced exclusively by
61
+ // `prepareArguments` rescue + the `execute` switch's runtime guards.
62
+ // Sub-questions cannot themselves be a batch (no nesting); enforced at
63
+ // runtime in `execute`.
64
+ //
65
+ // See change: fix-multiselect-auto-cancel-on-dashboard.
49
66
  const SubQuestionSchema = Type.Object(
50
67
  {
51
68
  method: Type.Union(
@@ -146,8 +163,33 @@ export function registerAskUserTool(pi: ExtensionAPI): void {
146
163
  "Do not nest batches. Send `options` as a plain string[] — not [{label, value}].",
147
164
  "This applies to all workflows including OpenSpec, planning, and any situation where you need user input before proceeding.",
148
165
  ],
149
- // Flat object schema (root: type=object) for OpenAI/Anthropic compatibility.
150
- // Field requirements per method are enforced at runtime, not via JSON Schema.
166
+ // Flat object schema (root: type=object) for OpenAI strict-mode
167
+ // compatibility.
168
+ //
169
+ // IMPORTANT: this object MUST NOT carry a root-level `oneOf` / `anyOf`
170
+ // / `allOf` / `enum` / `not`. OpenAI strict mode (GPT-4.1+, GPT-5.x,
171
+ // Codex, Responses API) explicitly rejects those at the top level with:
172
+ // "schema must have type 'object' and not have 'oneOf' / 'anyOf' /
173
+ // 'allOf' / 'enum' / 'not' at the top level."
174
+ //
175
+ // An earlier iteration of fix-multiselect-auto-cancel-on-dashboard
176
+ // ("Layer 2: defense in depth") tried adding a body-level `oneOf`
177
+ // discriminator over `method` so Anthropic would regain per-arm
178
+ // `required` + `minItems` enforcement. That worked for Anthropic
179
+ // models but real-world OpenAI gpt-5 rejected the schema (verified by
180
+ // the user 2026-04-30). The fallback documented in tasks.md §9.7 was
181
+ // taken: Layer 2 was dropped; Layer 1 (multiselect dashboard routing)
182
+ // ships alone, which is what actually fixes the user-reported bug.
183
+ //
184
+ // Per-method shape requirements (select/multiselect need `options`,
185
+ // batch needs `questions[]`, etc.) are enforced exclusively at runtime
186
+ // by `prepareArguments` (rescue/normalization) and the `execute` switch.
187
+ //
188
+ // The `no-root-oneof-in-ask-user-schema` guard test at
189
+ // packages/extension/src/__tests__/ask-user-schema-discriminator.test.ts
190
+ // pins this constraint so a future refactor cannot reintroduce it.
191
+ //
192
+ // See change: fix-multiselect-auto-cancel-on-dashboard.
151
193
  parameters: Type.Object(
152
194
  {
153
195
  method: MethodEnum,
@@ -180,7 +222,7 @@ export function registerAskUserTool(pi: ExtensionAPI): void {
180
222
  },
181
223
  {
182
224
  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.",
225
+ "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 by prepareArguments + execute (no schema-level discriminator — OpenAI strict mode forbids root-level oneOf).",
184
226
  },
185
227
  ),
186
228
  prepareArguments(args: unknown) {
@@ -270,6 +312,21 @@ export function registerAskUserTool(pi: ExtensionAPI): void {
270
312
  return obj as any;
271
313
  },
272
314
  async execute(_toolCallId: any, params: any, _signal: any, _onUpdate: any, ctx: any) {
315
+ // Capture the originating toolCallId so the resulting prompt_request
316
+ // metadata carries it; the client reducer pairs the interactiveUi
317
+ // row with its parent toolResult row using this id.
318
+ // See change: fix-interactive-ui-reorder.
319
+ const toolCallId: string | undefined =
320
+ typeof _toolCallId === "string" && _toolCallId.length > 0
321
+ ? _toolCallId
322
+ : undefined;
323
+ const withTcid = (
324
+ opts: Record<string, unknown> | undefined,
325
+ ): Record<string, unknown> | undefined => {
326
+ if (!toolCallId) return opts;
327
+ return { ...(opts ?? {}), toolCallId };
328
+ };
329
+
273
330
  // ── Batch branch ─────────────────────────────────────────────────
274
331
  if (params.method === "batch" && Array.isArray(params.questions)) {
275
332
  const results: Array<unknown> = [];
@@ -277,13 +334,17 @@ export function registerAskUserTool(pi: ExtensionAPI): void {
277
334
 
278
335
  for (const sq of params.questions) {
279
336
  const subTitle = `${params.title} — ${sq.title ?? "Question"}`;
280
- const subMsg = params.message ? { message: params.message } : undefined;
337
+ const subMsg = withTcid(params.message ? { message: params.message } : undefined);
281
338
 
282
339
  let answer: unknown;
283
340
  try {
284
341
  switch (sq.method) {
285
342
  case "confirm":
286
- answer = await ctx.ui.confirm(subTitle, sq.message ?? params.message ?? "");
343
+ answer = await ctx.ui.confirm(
344
+ subTitle,
345
+ sq.message ?? params.message ?? "",
346
+ withTcid(undefined),
347
+ );
287
348
  break;
288
349
  case "select": {
289
350
  const opts = Array.isArray(sq.options) ? sq.options : [];
@@ -359,7 +420,7 @@ export function registerAskUserTool(pi: ExtensionAPI): void {
359
420
 
360
421
  // ── Single-question branches (unchanged behavior) ────────────────
361
422
  let result: unknown;
362
- const msgOpts = params.message ? { message: params.message } : undefined;
423
+ const msgOpts = withTcid(params.message ? { message: params.message } : undefined);
363
424
  const title = params.title || params.message || "Question";
364
425
 
365
426
  const options: string[] = Array.isArray(params.options)
@@ -378,7 +439,7 @@ export function registerAskUserTool(pi: ExtensionAPI): void {
378
439
 
379
440
  switch (params.method) {
380
441
  case "confirm":
381
- result = await ctx.ui.confirm(title, params.message ?? "");
442
+ result = await ctx.ui.confirm(title, params.message ?? "", withTcid(undefined));
382
443
  break;
383
444
  case "select":
384
445
  result = await ctx.ui.select(title, options, msgOpts);
package/src/bridge.ts CHANGED
@@ -26,6 +26,7 @@ import { expandPromptTemplateFromDisk } from "./prompt-expander.js";
26
26
  import { PromptBus } from "./prompt-bus.js";
27
27
  import { DashboardDefaultAdapter } from "./dashboard-default-adapter.js";
28
28
  import { registerAskUserTool } from "./ask-user-tool.js";
29
+ import { decodeMultiselectAnswer } from "./multiselect-decode.js";
29
30
  import { activate as activateProviderRegister, onProviderChanged, reloadProviders } from "./provider-register.js";
30
31
  import type { FlowInfo } from "@blackbelt-technology/pi-dashboard-shared/types.js";
31
32
  import { startMetricsMonitor, stopMetricsMonitor, collectMetrics } from "./process-metrics.js";
@@ -854,6 +855,16 @@ function initBridge(pi: ExtensionAPI) {
854
855
  input: ctx.ui.input?.bind(ctx.ui) as ((q: string, placeholder?: string, extra?: any) => Promise<string | undefined>) | undefined,
855
856
  confirm: ctx.ui.confirm?.bind(ctx.ui) as ((q: string, msg: string, extra?: any) => Promise<boolean>) | undefined,
856
857
  editor: ctx.ui.editor?.bind(ctx.ui) as ((q: string, prefill?: string, extra?: any) => Promise<string | undefined>) | undefined,
858
+ // NOTE: the `custom` field is intentionally NOT captured here. A
859
+ // previous change (fix-multiselect-auto-cancel-on-dashboard) added a
860
+ // TUI multiselect arm that awaited the original ctx.ui.custom binding,
861
+ // but pi 0.70's RPC mode defines that primitive as a no-op (returns
862
+ // undefined synchronously), causing the TUI adapter to auto-cancel the
863
+ // dashboard-rendered dialog within one event-loop tick. The arm has
864
+ // been removed; see change fix-multiselect-tui-arm-self-cancel for full
865
+ // rationale. A repo lint (no-tui-multiselect-arm-regression.test.ts)
866
+ // prevents reintroduction by banning the co-occurrence of two
867
+ // substrings (the captured original binding and the TUI arm match).
857
868
  };
858
869
 
859
870
  // Register TUI adapter — presents prompts in the terminal using original
@@ -882,6 +893,13 @@ function initBridge(pi: ExtensionAPI) {
882
893
  } else if (prompt.type === "editor" && originals.editor) {
883
894
  answer = await originals.editor(prompt.question, prompt.defaultValue || "", { signal: ac.signal });
884
895
  } else {
896
+ // NOTE: there is intentionally no `else if` arm for the
897
+ // multiselect prompt type here. See change
898
+ // fix-multiselect-tui-arm-self-cancel — pi 0.70 RPC mode's
899
+ // ctx.ui.custom primitive is a no-op, so any TUI arm that
900
+ // awaits it auto-cancels the dashboard-rendered dialog. The
901
+ // bus-routed ctx.ui.multiselect patch below + the
902
+ // DashboardDefaultAdapter handle multiselect end-to-end.
885
903
  return;
886
904
  }
887
905
 
@@ -932,22 +950,66 @@ function initBridge(pi: ExtensionAPI) {
932
950
  // now route through the bus, which distributes to all registered adapters.
933
951
  {
934
952
  const bus = promptBus;
953
+ // Build a `metadata` envelope for bus.request that includes both
954
+ // `message` (existing) and `toolCallId` (new — added by change
955
+ // `fix-interactive-ui-reorder` so the client reducer can pair the
956
+ // resulting interactiveUi row with its parent toolResult row).
957
+ // Free-floating callers (slash commands, architect prompts) omit
958
+ // `opts.toolCallId` and the metadata field stays undefined.
959
+ const buildMeta = (
960
+ opts: any,
961
+ explicitMessage?: string,
962
+ ): Record<string, unknown> | undefined => {
963
+ const message = explicitMessage ?? opts?.message;
964
+ const toolCallId = opts?.toolCallId;
965
+ if (!message && !toolCallId) return undefined;
966
+ const meta: Record<string, unknown> = {};
967
+ if (message) meta.message = message;
968
+ if (toolCallId) meta.toolCallId = toolCallId;
969
+ return meta;
970
+ };
971
+
935
972
  (ctx.ui as any).select = (title: string, options: string[], opts?: any) =>
936
- bus.request({ pipeline: "command", type: "select", question: title, options, metadata: opts?.message ? { message: opts.message } : undefined })
973
+ bus.request({ pipeline: "command", type: "select", question: title, options, metadata: buildMeta(opts) })
937
974
  .then(r => r.cancelled ? undefined : r.answer);
938
975
 
939
976
  (ctx.ui as any).input = (title: string, placeholder?: string, opts?: any) =>
940
- bus.request({ pipeline: "command", type: "input", question: title, defaultValue: placeholder, metadata: opts?.message ? { message: opts.message } : undefined })
977
+ bus.request({ pipeline: "command", type: "input", question: title, defaultValue: placeholder, metadata: buildMeta(opts) })
941
978
  .then(r => r.cancelled ? undefined : r.answer);
942
979
 
943
980
  (ctx.ui as any).confirm = (title: string, message?: string, opts?: any) =>
944
- bus.request({ pipeline: "command", type: "confirm", question: title, metadata: (message || opts?.message) ? { message: message || opts?.message } : undefined })
981
+ bus.request({ pipeline: "command", type: "confirm", question: title, metadata: buildMeta(opts, message) })
945
982
  .then(r => !r.cancelled && r.answer === "true");
946
983
 
947
984
  (ctx.ui as any).editor = (title: string, prefill?: string, opts?: any) =>
948
- bus.request({ pipeline: "command", type: "editor", question: title, defaultValue: prefill, metadata: opts?.message ? { message: opts.message } : undefined })
985
+ bus.request({ pipeline: "command", type: "editor", question: title, defaultValue: prefill, metadata: buildMeta(opts) })
949
986
  .then(r => r.cancelled ? undefined : r.answer);
950
987
 
988
+ // ── Multiselect ──────────────────────────────────────────────
989
+ // ctx.ui.multiselect is NOT a built-in pi method — we attach it here
990
+ // so that polyfillMultiselect (and any other consumer) routes through
991
+ // PromptBus. The dashboard adapter renders a real browser dialog via
992
+ // MultiselectRenderer; there is intentionally no TUI adapter arm for
993
+ // multiselect (pi 0.70 RPC mode's ctx.ui.custom is a no-op, so any TUI
994
+ // arm would auto-cancel the dashboard render in <1s). See changes
995
+ // fix-multiselect-auto-cancel-on-dashboard (initial bus routing) and
996
+ // fix-multiselect-tui-arm-self-cancel (TUI arm removal).
997
+ if (typeof (ctx.ui as any).multiselect === "function") {
998
+ // Defensive: future upstream pi may add a built-in multiselect.
999
+ // Override is intentional — the bus-routed version is what
1000
+ // participates in PromptBus first-response-wins semantics.
1001
+ // eslint-disable-next-line no-console
1002
+ console.warn("[bridge] ctx.ui.multiselect already exists — overriding for PromptBus routing");
1003
+ }
1004
+ (ctx.ui as any).multiselect = (title: string, options: string[], opts?: any) =>
1005
+ bus.request({
1006
+ pipeline: "command",
1007
+ type: "multiselect",
1008
+ question: title,
1009
+ options,
1010
+ metadata: opts?.message ? { message: opts.message } : undefined,
1011
+ }).then(decodeMultiselectAnswer);
1012
+
951
1013
  // Notify is fire-and-forget: call original + forward to dashboard
952
1014
  (ctx.ui as any).notify = (message: string, level?: string) => {
953
1015
  originalNotify?.(message, level);
@@ -0,0 +1,40 @@
1
+ /**
2
+ * decodeMultiselectAnswer — pure helper that turns a `PromptResponse`
3
+ * (from PromptBus) into the `string[] | undefined` shape expected by
4
+ * `polyfillMultiselect` and other multiselect callers.
5
+ *
6
+ * Contract:
7
+ * • cancelled: true → undefined
8
+ * • cancelled: false, answer: undefined / null / "" → [] (empty selection
9
+ * is a real answer,
10
+ * distinct from
11
+ * cancellation)
12
+ * • cancelled: false, answer: '["a","b"]' → ["a","b"]
13
+ * • cancelled: false, answer: <unparseable> → [] (graceful
14
+ * degradation,
15
+ * never throw)
16
+ *
17
+ * Kept separate from `bridge.ts` so unit tests can exercise it without
18
+ * instantiating a live PromptBus or session context.
19
+ *
20
+ * See change: fix-multiselect-auto-cancel-on-dashboard.
21
+ */
22
+
23
+ export interface DecodableResponse {
24
+ cancelled?: boolean;
25
+ answer?: string | undefined;
26
+ }
27
+
28
+ export function decodeMultiselectAnswer(
29
+ response: DecodableResponse,
30
+ ): string[] | undefined {
31
+ if (response.cancelled) return undefined;
32
+ const answer = response.answer;
33
+ if (answer == null || answer === "") return [];
34
+ try {
35
+ const parsed = JSON.parse(answer);
36
+ return Array.isArray(parsed) ? (parsed as string[]) : [];
37
+ } catch {
38
+ return [];
39
+ }
40
+ }
@@ -4,23 +4,38 @@
4
4
  * `ExtensionUIContext` does not expose. Without this, any TUI dispatch of
5
5
  * `method: "multiselect"` crashes with `"ctx.ui.multiselect is not a function"`.
6
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.
7
+ * Fallback chain (introduced by change fix-multiselect-auto-cancel-on-dashboard):
12
8
  *
13
- * The result contract matches what the current (broken) call expects:
9
+ * 1. PRIMARY — bridge-patched `ctx.ui.multiselect` (PromptBus path).
10
+ * The bridge attaches this method on session_start so the dashboard
11
+ * browser renders a real `MultiselectRenderer` dialog and the TUI
12
+ * adapter renders a `MultiSelectList` overlay in the terminal.
13
+ *
14
+ * 2. FALLBACK — legacy `ctx.ui.custom` + `MultiSelectList` overlay.
15
+ * Reached when (a) running against an older pi without the bridge
16
+ * patch, (b) running outside the bridge entirely, or (c) the bridge
17
+ * patch was removed for some reason. TUI-only — does NOT render a
18
+ * browser dialog in dashboard / RPC mode (which is exactly the bug
19
+ * that motivated the primary path).
20
+ *
21
+ * The result contract is unchanged in either branch:
14
22
  * - resolves to `string[]` when the user confirms a selection
15
23
  * (possibly empty if nothing is checked)
16
- * - resolves to `undefined` when the user cancels (Escape)
24
+ * - resolves to `undefined` when the user cancels (Escape / Cancel)
25
+ *
26
+ * See change: fix-multiselect-auto-cancel-on-dashboard.
17
27
  */
18
28
  import { MultiSelectList } from "./multiselect-list.js";
19
29
 
20
30
  // Intentionally loose: `ctx` shape varies slightly across pi versions; the
21
- // polyfill only needs `ctx.ui.custom`.
31
+ // polyfill only needs `ctx.ui.multiselect` (primary) or `ctx.ui.custom` (fallback).
22
32
  export interface PolyfillCtx {
23
33
  ui: {
34
+ multiselect?: (
35
+ title: string,
36
+ options: string[],
37
+ opts?: { message?: string },
38
+ ) => Promise<string[] | undefined>;
24
39
  custom<T>(
25
40
  factory: (tui: unknown, theme: unknown, keybindings: unknown, done: (result: T) => void) => unknown,
26
41
  options?: unknown,
@@ -34,6 +49,21 @@ export function polyfillMultiselect(
34
49
  options: string[],
35
50
  opts?: { message?: string },
36
51
  ): Promise<string[] | undefined> {
52
+ // Primary path: delegate to the bridge-patched ctx.ui.multiselect (which
53
+ // routes through PromptBus → DashboardDefaultAdapter → client
54
+ // MultiselectRenderer). This is the only working path on pi 0.70 RPC mode
55
+ // (dashboard headless sessions).
56
+ const ui = ctx.ui as PolyfillCtx["ui"] & { multiselect?: Function };
57
+ if (typeof ui.multiselect === "function") {
58
+ return Promise.resolve(ui.multiselect(title, options, opts));
59
+ }
60
+
61
+ // Legacy fallback: TUI overlay via ctx.ui.custom. Used when the bridge
62
+ // patch is absent (older pi / non-bridge embedding) OR a future pi version
63
+ // restores ctx.ui.custom in RPC mode. NOTE: in pi 0.70 RPC mode
64
+ // ctx.ui.custom is a no-op that resolves to undefined synchronously, so
65
+ // this branch returns undefined immediately on dashboard headless
66
+ // sessions — the primary path above is the only effective route there.
37
67
  return ctx.ui.custom<string[] | undefined>((_tui, _theme, _keybindings, done) => {
38
68
  const list = new MultiSelectList(title, options, opts?.message);
39
69
  list.onConfirm = (selected) => done(selected);