Commit d32375ceb378

Vincent Demeester <vincent@sbr.pm>
2026-10-22 12:14:29
fix(pi): support RPC multi-select questions
Preserved user decisions outside the terminal UI by using an RPC-safe input fallback. Signed-off-by: Vincent Demeester <vincent@sbr.pm>
1 parent 49d2578
dots/pi/agent/extensions/ask-user-utils.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, test } from "bun:test";
+
+import { multiSelectInputPrompt, parseMultiSelectAnswer } from "./ask-user-utils";
+
+describe("multiSelectInputPrompt", () => {
+	test("presents the question, options, and comma-separated input instruction for RPC", () => {
+		expect(multiSelectInputPrompt("Which features?", ["auth", "logging", "caching"])).toBe(
+			"Which features?\n\nOptions: auth, logging, caching\nEnter one or more choices, separated by commas:",
+		);
+	});
+});
+
+describe("parseMultiSelectAnswer", () => {
+	test("returns trimmed comma-separated selections", () => {
+		expect(parseMultiSelectAnswer(" auth, logging ,caching ")).toEqual(["auth", "logging", "caching"]);
+	});
+
+	test("returns no selection for cancellation or blank input", () => {
+		expect(parseMultiSelectAnswer(undefined)).toEqual([]);
+		expect(parseMultiSelectAnswer("  ,  ")).toEqual([]);
+	});
+});
dots/pi/agent/extensions/ask-user-utils.ts
@@ -0,0 +1,10 @@
+export function multiSelectInputPrompt(question: string, suggestions: string[]): string {
+	return `${question}\n\nOptions: ${suggestions.join(", ")}\nEnter one or more choices, separated by commas:`;
+}
+
+export function parseMultiSelectAnswer(answer: string | undefined): string[] {
+	return (answer ?? "")
+		.split(",")
+		.map((selection) => selection.trim())
+		.filter(Boolean);
+}
dots/pi/agent/extensions/ask-user.test.ts
@@ -0,0 +1,77 @@
+import { expect, mock, test } from "bun:test";
+
+mock.module("@earendil-works/pi-coding-agent", () => ({
+	DynamicBorder: class {},
+	getSettingsListTheme: () => ({}),
+}));
+mock.module("@earendil-works/pi-tui", () => ({
+	Container: class {},
+	SettingsList: class {},
+	Text: class {},
+}));
+mock.module("@sinclair/typebox", () => ({
+	Type: {
+		String: (options: unknown) => options,
+		Boolean: (options: unknown) => options,
+		Array: (items: unknown, options: unknown) => ({ items, ...options }),
+		Optional: (schema: unknown) => schema,
+		Object: (schema: unknown) => schema,
+	},
+}));
+
+const { default: registerAskUser } = await import("./ask-user");
+
+function registeredTool() {
+	let tool: any;
+	registerAskUser({ registerTool: (registered: unknown) => (tool = registered) } as any);
+	return tool;
+}
+
+test("advertises the registered AskUserQuestion tool in its prompt metadata", () => {
+	const tool = registeredTool();
+
+	expect(tool.promptSnippet).toContain("Ask the user");
+	expect(tool.promptGuidelines).toContain(
+		"Use AskUserQuestion when you need user input, clarification, or a decision before proceeding.",
+	);
+});
+
+test("uses an RPC input fallback for multi-select instead of terminal custom UI", async () => {
+	const tool = registeredTool();
+	const input = mock(async () => " auth, logging ");
+	const custom = mock(() => {
+		throw new Error("RPC must not use custom UI");
+	});
+
+	const result = await tool.execute(
+		"tool-call",
+		{ question: "Which features?", suggestions: ["auth", "logging"], multiSelect: true },
+		new AbortController().signal,
+		() => {},
+		{ mode: "rpc", hasUI: true, ui: { input, custom } },
+	);
+
+	expect(result.content[0].text).toBe("User selected: auth, logging");
+	expect(result.details).toEqual({
+		question: "Which features?",
+		suggestions: ["auth", "logging"],
+		multiSelect: true,
+		answer: "auth, logging",
+		selected: ["auth", "logging"],
+	});
+});
+
+test("reports cancellation when the RPC multi-select input is blank", async () => {
+	const tool = registeredTool();
+
+	const result = await tool.execute(
+		"tool-call",
+		{ question: "Which features?", suggestions: ["auth"], multiSelect: true },
+		new AbortController().signal,
+		() => {},
+		{ mode: "rpc", hasUI: true, ui: { input: async () => "  , " } },
+	);
+
+	expect(result.content[0].text).toBe("User cancelled — did not select any options.");
+	expect(result.details.selected).toEqual([]);
+});
dots/pi/agent/extensions/ask-user.ts
@@ -6,9 +6,9 @@
  * multi-select checkboxes.
  *
  * Usage by the AI:
- *   ask_user({ question: "Which database should I use?" })
- *   ask_user({ question: "How should I handle errors?", suggestions: ["retry", "fail fast", "log and continue"] })
- *   ask_user({ question: "Which features?", suggestions: ["auth", "logging", "caching"], multiSelect: true })
+ *   AskUserQuestion({ question: "Which database should I use?" })
+ *   AskUserQuestion({ question: "How should I handle errors?", suggestions: ["retry", "fail fast", "log and continue"] })
+ *   AskUserQuestion({ question: "Which features?", suggestions: ["auth", "logging", "caching"], multiSelect: true })
  */
 
 import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
@@ -16,6 +16,8 @@ import { DynamicBorder, getSettingsListTheme } from "@earendil-works/pi-coding-a
 import { Container, type SettingItem, SettingsList, Text } from "@earendil-works/pi-tui";
 import { Type } from "@sinclair/typebox";
 
+import { multiSelectInputPrompt, parseMultiSelectAnswer } from "./ask-user-utils";
+
 /**
  * Serializes TUI access across concurrent tool calls.
  *
@@ -46,9 +48,10 @@ export default function (pi: ExtensionAPI) {
 		label: "Ask User",
 		description:
 			"Ask the user a question and wait for their response. Use when you need clarification, a decision, or user input to proceed. Supports optional suggestions the user can pick from or ignore.",
+		promptSnippet: "Ask the user a concise question when a decision or missing information blocks progress.",
 		promptGuidelines: [
-			"Use ask_user when you need user input, clarification, or a decision before proceeding.",
-			"Prefer ask_user over guessing when the choice significantly affects the outcome.",
+			"Use AskUserQuestion when you need user input, clarification, or a decision before proceeding.",
+			"Prefer AskUserQuestion over guessing when the choice significantly affects the outcome.",
 			"Keep questions concise and specific. Provide suggestions when there are obvious options.",
 			"Use multiSelect: true when the user may want to pick more than one option from the suggestions.",
 		],
@@ -91,6 +94,22 @@ export default function (pi: ExtensionAPI) {
 			let answer: string | undefined;
 
 			if (multiSelect && hasSuggestions) {
+				if (ctx.mode !== "tui") {
+					const selected = parseMultiSelectAnswer(await ctx.ui.input(multiSelectInputPrompt(question, suggestions)));
+					if (selected.length === 0) {
+						return {
+							content: [{ type: "text", text: "User cancelled — did not select any options." }],
+							details: { question, suggestions, multiSelect: true, answer: null, selected: [] },
+						};
+					}
+
+					answer = selected.join(", ");
+					return {
+						content: [{ type: "text", text: `User selected: ${answer}` }],
+						details: { question, suggestions, multiSelect: true, answer, selected },
+					};
+				}
+
 				// Multi-select: checkbox-style toggles using SettingsList
 				const selected = new Set<string>();