@devries-cameron20 / t3code-1 / commits / a6f7981abb
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(pi): ask_user_question single-select questions render as a structured card (#32125)

Julius Marminge committed Nov 16, 2026 at 13:41 UTC a6f7981abba71a51b299bd0ecbf7577d20660541
2 files changed +434 -2
packages/provider-pi/src/server/adapter.test.ts
+289
@@ -4895,6 +4895,295 @@ describe("PiAdapterV2", () => {
4895 }).pipe(Effect.scoped, Effect.provide(layerTest)),
4896 );
4897
4898 + it.effect("renders an ask_user_question select from the tool call's structured question", () =>
4899 + Effect.gen(function* () {
4900 + const fake = yield* makeFakePi;
4901 + const { runtime, takeEvent } = yield* openRuntime(fake);
4902 + const providerThread = yield* runtime.ensureThread({
4903 + threadId: THREAD_ID,
4904 + modelSelection: modelSelection("default"),
4905 + runtimePolicy,
4906 + });
4907 + yield* startTurn(runtime, providerThread);
4908 + yield* fake.takeRequest("prompt");
4909 + yield* fake.emit({
4910 + type: "tool_execution_start",
4911 + toolCallId: "ask-call",
4912 + toolName: "ask_user_question",
4913 + args: {
4914 + questions: [
4915 + {
4916 + header: "Area",
4917 + question: "Which area should we work on?",
4918 + options: [
4919 + {
4920 + label: "Docker/Compose",
4921 + description: "Review or edit Compose projects",
4922 + preview: "services:\n web: {}",
4923 + },
4924 + { label: "Home Assistant", description: "Automations, dashboards or YAML" },
4925 + ],
4926 + },
4927 + ],
4928 + },
4929 + });
4930 + const dockerLine = "1. Docker/Compose — Review or edit Compose projects";
4931 + yield* fake.emit({
4932 + type: "extension_ui_request",
4933 + id: "ui-ask",
4934 + method: "select",
4935 + title:
4936 + "[Area] Which area should we work on?\n\n--- 1. Docker/Compose preview ---\nservices:\n web: {}",
4937 + options: [
4938 + dockerLine,
4939 + "2. Home Assistant — Automations, dashboards or YAML",
4940 + "3. Type something.",
4941 + ],
4942 + });
4943 + const event = yield* takeEvent(
4944 + (event) =>
4945 + event.type === "turn_item.updated" && event.turnItem.type === "user_input_request",
4946 + );
4947 + if (event.type !== "turn_item.updated" || event.turnItem.type !== "user_input_request") {
4948 + return assert.fail("expected a user input request");
4949 + }
4950 + const question = decodeUserInputQuestions(event.turnItem.questions)[0];
4951 + assert.deepEqual(
4952 + {
4953 + header: question?.header,
4954 + question: question?.question,
4955 + options: question?.options.map(({ label, description }) => ({ label, description })),
4956 + },
4957 + {
4958 + header: "Area",
4959 + question:
4960 + "Which area should we work on?\n\n--- 1. Docker/Compose preview ---\nservices:\n web: {}",
4961 + options: [
4962 + { label: "Docker/Compose", description: "Review or edit Compose projects" },
4963 + { label: "Home Assistant", description: "Automations, dashboards or YAML" },
4964 + ],
4965 + },
4966 + );
4967 + yield* runtime.respondToRuntimeRequest({
4968 + requestId: event.turnItem.requestId,
4969 + answers: { [question!.id]: question!.options[0]!.value },
4970 + });
4971 + const response = yield* fake.takeRequest("extension_ui_response");
4972 + assert.equal(response["id"], "ui-ask");
4973 + assert.equal(response["value"], dockerLine);
4974 + }).pipe(Effect.scoped, Effect.provide(layerTest)),
4975 + );
4976 +
4977 + it.effect("matches an ask_user_question select to the question with the same full title", () =>
4978 + Effect.gen(function* () {
4979 + const fake = yield* makeFakePi;
4980 + const { runtime, takeEvent } = yield* openRuntime(fake);
4981 + const providerThread = yield* runtime.ensureThread({
4982 + threadId: THREAD_ID,
4983 + modelSelection: modelSelection("default"),
4984 + runtimePolicy,
4985 + });
4986 + yield* startTurn(runtime, providerThread);
4987 + yield* fake.takeRequest("prompt");
4988 + const options = [
4989 + { label: "Yes", description: "Go ahead" },
4990 + { label: "No", description: "Stop here" },
4991 + ];
4992 + yield* fake.emit({
4993 + type: "tool_execution_start",
4994 + toolCallId: "ask-call",
4995 + toolName: "ask_user_question",
4996 + // Some models JSON-encode `questions`; the extension decodes it before asking.
4997 + args: {
4998 + questions: JSON.stringify([
4999 + { header: "Deploy", question: "Proceed?", options },
5000 + { header: "Deploy", question: "Proceed? Only for staging?", options },
5001 + ]),
5002 + },
5003 + });
5004 + yield* fake.emit({
5005 + type: "extension_ui_request",
5006 + id: "ui-ask",
5007 + method: "select",
5008 + title: "[Deploy] Proceed? Only for staging?",
5009 + options: ["1. Yes — Go ahead", "2. No — Stop here", "3. Type something."],
5010 + });
5011 + const event = yield* takeEvent(
5012 + (event) =>
5013 + event.type === "turn_item.updated" && event.turnItem.type === "user_input_request",
5014 + );
5015 + if (event.type !== "turn_item.updated" || event.turnItem.type !== "user_input_request") {
5016 + return assert.fail("expected a user input request");
5017 + }
5018 + const question = decodeUserInputQuestions(event.turnItem.questions)[0];
5019 + assert.equal(question?.question, "Proceed? Only for staging?");
5020 + // Option lines that differ from the recorded call keep the raw select.
5021 + const unmatchedLines = ["1. Yes — Go", "2. No — Stop here", "3. Type something."];
5022 + yield* fake.emit({
5023 + type: "extension_ui_request",
5024 + id: "ui-unmatched",
5025 + method: "select",
5026 + title: "[Deploy] Proceed?",
5027 + options: unmatchedLines,
5028 + });
5029 + const unmatched = yield* takeEvent(
5030 + (event) =>
5031 + event.type === "turn_item.updated" && event.turnItem.type === "user_input_request",
5032 + );
5033 + if (
5034 + unmatched.type !== "turn_item.updated" ||
5035 + unmatched.turnItem.type !== "user_input_request"
5036 + ) {
5037 + return assert.fail("expected a user input request");
5038 + }
5039 + const unmatchedQuestion = decodeUserInputQuestions(unmatched.turnItem.questions)[0];
5040 + assert.deepEqual(
5041 + {
5042 + header: unmatchedQuestion?.header,
5043 + question: unmatchedQuestion?.question,
5044 + options: unmatchedQuestion?.options.map(({ label, value }) => [label, value]),
5045 + },
5046 + {
5047 + header: "Question",
5048 + question: "[Deploy] Proceed?",
5049 + options: unmatchedLines.map((line) => [line, line]),
5050 + },
5051 + );
5052 + }).pipe(Effect.scoped, Effect.provide(layerTest)),
5053 + );
5054 +
5055 + it.effect("answers each ask_user_question custom text through its follow-up input", () =>
5056 + Effect.gen(function* () {
5057 + const fake = yield* makeFakePi;
5058 + const { runtime, takeEvent } = yield* openRuntime(fake);
5059 + const providerThread = yield* runtime.ensureThread({
5060 + threadId: THREAD_ID,
5061 + modelSelection: modelSelection("default"),
5062 + runtimePolicy,
5063 + });
5064 + yield* startTurn(runtime, providerThread);
5065 + yield* fake.takeRequest("prompt");
5066 + const args = {
5067 + questions: [
5068 + {
5069 + question: "How many replicas?",
5070 + options: [
5071 + { label: "One", description: "Single instance" },
5072 + { label: "Three", description: "High availability" },
5073 + ],
5074 + },
5075 + ],
5076 + };
5077 + // Parallel questionnaires can ask the same question.
5078 + yield* fake.emit({
5079 + type: "tool_execution_start",
5080 + toolCallId: "ask-call",
5081 + toolName: "ask_user_question",
5082 + args,
5083 + });
5084 + yield* fake.emit({
5085 + type: "tool_execution_start",
5086 + toolCallId: "ask-call-parallel",
5087 + toolName: "ask_user_question",
5088 + args,
5089 + });
5090 + const lines = ["1. One — Single instance", "2. Three — High availability"];
5091 + const followUpTitle = `How many replicas?\n\n${lines.join("\n")}\n\nType your answer:`;
5092 + const takeWaitingRequest = Effect.fnUntraced(function* () {
5093 + const event = yield* takeEvent(
5094 + (event) =>
5095 + event.type === "turn_item.updated" &&
5096 + event.turnItem.type === "user_input_request" &&
5097 + event.turnItem.status === "waiting",
5098 + );
5099 + if (event.type !== "turn_item.updated" || event.turnItem.type !== "user_input_request") {
5100 + return assert.fail("expected a user input request");
5101 + }
5102 + return event.turnItem;
5103 + });
5104 + const answerWithCustomText = Effect.fnUntraced(function* (id: string, text: string) {
5105 + yield* fake.emit({
5106 + type: "extension_ui_request",
5107 + id,
5108 + method: "select",
5109 + title: "How many replicas?",
5110 + options: [...lines, "3. Type something."],
5111 + });
5112 + const request = yield* takeWaitingRequest();
5113 + yield* runtime.respondToRuntimeRequest({
5114 + requestId: request.requestId,
5115 + answers: { [request.questions[0]!.id]: text },
5116 + });
5117 + const selectResponse = yield* fake.takeRequest("extension_ui_response");
5118 + assert.equal(selectResponse["value"], "3. Type something.");
5119 + });
5120 + // The extension reads a bare number sent as the select's value as that option.
5121 + yield* answerWithCustomText("ui-ask", "2");
5122 + yield* answerWithCustomText("ui-ask-parallel", "5");
5123 + // Parallel dialogs can arrive before the follow-up input, including a multi-select of the
5124 + // same question, which the extension asks as an input with a non-empty placeholder.
5125 + const multiSelectTitle = `How many replicas?\n\n${lines.join("\n")}\n\nEnter the numbers of all that apply.`;
5126 + yield* fake.emit({
5127 + type: "extension_ui_request",
5128 + id: "ui-multi",
5129 + method: "input",
5130 + title: multiSelectTitle,
5131 + placeholder: "1,3; custom answer",
5132 + });
5133 + // Another extension's blank-placeholder input that only shares the question is asked.
5134 + const unrelatedTitle = "How many replicas?\n\nEnter the release note:";
5135 + yield* fake.emit({
5136 + type: "extension_ui_request",
5137 + id: "ui-unrelated",
5138 + method: "input",
5139 + title: unrelatedTitle,
5140 + placeholder: "",
5141 + });
5142 + yield* fake.emit({
5143 + type: "extension_ui_request",
5144 + id: "ui-other",
5145 + method: "input",
5146 + title: "Anything else?",
5147 + });
5148 + assert.equal((yield* takeWaitingRequest()).title, multiSelectTitle);
5149 + assert.equal((yield* takeWaitingRequest()).title, unrelatedTitle);
5150 + assert.equal((yield* takeWaitingRequest()).title, "Anything else?");
5151 + for (const [id, value] of [
5152 + ["ui-custom", "2"],
5153 + ["ui-custom-parallel", "5"],
5154 + ]) {
5155 + yield* fake.emit({
5156 + type: "extension_ui_request",
5157 + id,
5158 + method: "input",
5159 + title: followUpTitle,
5160 + placeholder: "",
5161 + });
5162 + const inputResponse = yield* fake.takeRequest("extension_ui_response");
5163 + assert.deepEqual({ id: inputResponse["id"], value: inputResponse["value"] }, { id, value });
5164 + }
5165 + // An answer staged when the turn ends is dropped, so a later matching input is asked.
5166 + yield* answerWithCustomText("ui-ask-late", "7");
5167 + yield* fake.emit({ type: "agent_end", messages: [], willRetry: false });
5168 + yield* fake.emit({ type: "agent_settled" });
5169 + yield* takeEvent((event) => event.type === "turn.terminal");
5170 + yield* fake.emit({
5171 + type: "extension_ui_request",
5172 + id: "ui-custom-late",
5173 + method: "input",
5174 + title: followUpTitle,
5175 + placeholder: "",
5176 + });
5177 + yield* fake.emit({
5178 + type: "extension_ui_request",
5179 + id: "ui-after",
5180 + method: "input",
5181 + title: "Anything else?",
5182 + });
5183 + assert.equal((yield* takeWaitingRequest()).title, followUpTitle);
5184 + }).pipe(Effect.scoped, Effect.provide(layerTest)),
5185 + );
5186 +
5187 it.effect.each(["Which database?\n1. Postgres\n2. Type something.\nType your answer:", " "])(
5188 "asks an input dialog's title when its placeholder is blank, with title '%s'",
5189 (title) =>
packages/provider-pi/src/server/adapter.ts
+145 -2
@@ -409,6 +409,17 @@ interface PendingPiPrompt {
409 runtimeRequest: OrchestrationV2RuntimeRequest;
410 readonly node: OrchestrationV2ExecutionNode;
411 readonly turnItem: OrchestrationV2TurnItem;
412 + readonly customAnswerRoute: PiCustomAnswerRoute | undefined;
413 +}
414 +
415 +/**
416 + * The ask_user_question extension misreads typed text sent as a select value, so a custom answer
417 + * picks the select's last "Type something." line and answers the input dialog that follows.
418 + */
419 +interface PiCustomAnswerRoute {
420 + readonly lines: ReadonlyArray<unknown>;
421 + readonly sentinel: string;
422 + readonly followUpTitlePrefix: string;
423 }
424
425 function piApprovalRequestKind(title: string): "command" | "file-change" {
@@ -601,6 +612,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
612 ProviderAdapter.ProviderAdapterV2Error | Cause.Done
613 >();
614 const pendingPrompts = new Map<string, PendingPiPrompt>();
615 + // Custom answers waiting for their ask_user_question follow-up input, keyed by title prefix.
616 + // FIFO per prefix: the extension asks each follow-up right after its own select is answered.
617 + const customAnswerFollowUps = new Map<string, string[]>();
618 const sessionApprovals = new Set<string>();
619 // Async pi-subagents runs launched in this session, by async id, until they settle.
620 const piAsyncRuns = new Map<
@@ -1685,6 +1699,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
1699 ) {
1700 const pending = Array.from(pendingPrompts.values());
1701 pendingPrompts.clear();
1702 + customAnswerFollowUps.clear();
1703 yield* Effect.forEach(pending, (prompt) => cancelPrompt(prompt, resolvedAt), {
1704 discard: true,
1705 });
@@ -1777,6 +1792,24 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
1792 return;
1793 }
1794 if (nativeRequestId === undefined) return;
1795 + // The extension's follow-up input has an empty placeholder; its multi-select input does not.
1796 + const inputTitle =
1797 + method === "input" && event["placeholder"] === ""
1798 + ? (recordString(event, "title") ?? "")
1799 + : "";
1800 + const followUpPrefix = Array.from(customAnswerFollowUps.keys())
1801 + .filter((prefix) => inputTitle.startsWith(prefix))
1802 + .reduce<string | undefined>(
1803 + (longest, prefix) => (prefix.length > (longest?.length ?? -1) ? prefix : longest),
1804 + undefined,
1805 + );
1806 + if (followUpPrefix !== undefined) {
1807 + const queued = customAnswerFollowUps.get(followUpPrefix) ?? [];
1808 + const value = queued.shift() ?? "";
1809 + if (queued.length === 0) customAnswerFollowUps.delete(followUpPrefix);
1810 + yield* connection.send({ type: "extension_ui_response", id: nativeRequestId, value });
1811 + return;
1812 + }
1813 const approvalTitle = recordString(event, "title") ?? "";
1814 const approvalKey = `${approvalTitle.length}:${approvalTitle}${recordString(event, "message") ?? ""}`;
1815 if (method === "confirm" && sessionApprovals.has(approvalKey)) {
@@ -1851,6 +1884,10 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
1884 completedAt: null,
1885 updatedAt: createdAt,
1886 };
1887 + const askUser =
1888 + method === "select" && turn !== null
1889 + ? piAskUserSingleSelectQuestion(nativeRequestId, title, event, turn.toolArgs)
1890 + : undefined;
1891 const turnItem: OrchestrationV2TurnItem =
1892 method === "confirm"
1893 ? {
@@ -1864,7 +1901,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
1901 ...itemBase,
1902 type: "user_input_request",
1903 requestId,
1867 - questions: [piQuestion(nativeRequestId, method, title, event)],
1904 + questions: [askUser?.question ?? piQuestion(nativeRequestId, method, title, event)],
1905 };
1906 const pending: PendingPiPrompt = {
1907 nativeRequestId,
@@ -1876,6 +1913,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
1913 runtimeRequest,
1914 node,
1915 turnItem,
1916 + customAnswerRoute: askUser?.customAnswerRoute,
1917 };
1918 pendingPrompts.set(String(requestId), pending);
1919 yield* emit({
@@ -3575,7 +3613,20 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
3613 `Pi extension request ${requestInput.requestId} has expired`,
3614 );
3615 }
3578 - const response = piUiResponse(pending, requestInput.decision, requestInput.answers);
3616 + let response = piUiResponse(pending, requestInput.decision, requestInput.answers);
3617 + const route = pending.customAnswerRoute;
3618 + if (
3619 + route !== undefined &&
3620 + typeof response["value"] === "string" &&
3621 + response["value"].trim().length > 0 &&
3622 + !route.lines.includes(response["value"])
3623 + ) {
3624 + customAnswerFollowUps.set(route.followUpTitlePrefix, [
3625 + ...(customAnswerFollowUps.get(route.followUpTitlePrefix) ?? []),
3626 + response["value"],
3627 + ]);
3628 + response = { value: route.sentinel };
3629 + }
3630 yield* connection.send({
3631 type: "extension_ui_response",
3632 id: pending.nativeRequestId,
@@ -4170,6 +4221,98 @@ function piQuestion(
4221 };
4222 }
4223
4224 +/** The extension normalizes line terminators in each question field before building the dialog. */
4225 +const rpivField = (input: unknown, key: string) =>
4226 + recordString(input, key)?.replace(/\r\n/g, "\n").replace(/\r/g, "");
4227 +
4228 +const rpivOptionLine = (option: unknown, index: number) =>
4229 + // oxlint-disable-next-line t3code/no-em-dash-copy -- Matches the extension's option line format.
4230 + `${index + 1}. ${rpivField(option, "label")} — ${rpivField(option, "description")}`;
4231 +
4232 +/** The extension folds option previews into the select title, the only place clients show them. */
4233 +const rpivPreviewBlock = (options: ReadonlyArray<unknown>) => {
4234 + const blocks = options.flatMap((option, index) => {
4235 + const preview = rpivField(option, "preview");
4236 + return preview
4237 + ? [`--- ${index + 1}. ${rpivField(option, "label")} preview ---\n${preview.slice(0, 600)}`]
4238 + : [];
4239 + });
4240 + return blocks.length > 0 ? `\n\n${blocks.join("\n\n")}` : "";
4241 +};
4242 +
4243 +/** Mirrors the extension's `prepareQuestionArguments`: some models JSON-encode nested args. */
4244 +const rpivDecoded = (value: unknown, isShape: (parsed: unknown) => boolean) => {
4245 + if (typeof value !== "string") return value;
4246 + try {
4247 + const parsed: unknown = JSON.parse(value);
4248 + return isShape(parsed) ? parsed : value;
4249 + } catch {
4250 + return value;
4251 + }
4252 +};
4253 +
4254 +/**
4255 + * @juicesharp/rpiv-ask-user-question asks a single-select question over RPC as a select of
4256 + * "N. label — description" lines plus a trailing "Type something." entry. Rebuild the question
4257 + * from the tool call's arguments; each option answers with its original line, which the extension
4258 + * maps back to that option.
4259 + */
4260 +function piAskUserSingleSelectQuestion(
4261 + questionId: string,
4262 + title: string,
4263 + event: PiRpcRecord,
4264 + toolArgs: ReadonlyMap<string, unknown>,
4265 +):
4266 + | { question: OrchestrationV2UserInputQuestion; customAnswerRoute: PiCustomAnswerRoute }
4267 + | undefined {
4268 + const lines = event["options"];
4269 + if (!Array.isArray(lines) || lines.length < 2) return undefined;
4270 + const sentinel = lines.at(-1);
4271 + if (typeof sentinel !== "string") return undefined;
4272 + for (const args of toolArgs.values()) {
4273 + const questions = rpivDecoded(recordField(args, "questions"), Array.isArray);
4274 + if (!Array.isArray(questions)) continue;
4275 + for (const entry of questions) {
4276 + const question = rpivDecoded(entry, Predicate.isObject);
4277 + const text = rpivField(question, "question");
4278 + const header = rpivField(question, "header");
4279 + if (recordField(question, "multiSelect") === true || !text?.trim()) continue;
4280 + const prefix = header ? `[${header}] ` : "";
4281 + if (!title.startsWith(`${prefix}${text}`)) continue;
4282 + const encodedOptions = rpivDecoded(recordField(question, "options"), Array.isArray);
4283 + if (!Array.isArray(encodedOptions) || encodedOptions.length !== lines.length - 1) continue;
4284 + const options = encodedOptions.map((option) => rpivDecoded(option, Predicate.isObject));
4285 + const body = `${text}${rpivPreviewBlock(options)}`;
4286 + if (title !== `${prefix}${body}`) continue;
4287 + if (!options.every((option, index) => lines[index] === rpivOptionLine(option, index))) {
4288 + continue;
4289 + }
4290 + return {
4291 + question: {
4292 + id: questionId,
4293 + header: header?.trim() || "Question",
4294 + question: body.trim(),
4295 + options: options.map((option, index) => {
4296 + const label = rpivField(option, "label")?.trim() || `Option ${index + 1}`;
4297 + return {
4298 + label,
4299 + description: rpivField(option, "description")?.trim() || label,
4300 + value: rpivOptionLine(option, index),
4301 + };
4302 + }),
4303 + },
4304 + // The follow-up repeats the option lines; only its trailing instruction is localized.
4305 + customAnswerRoute: {
4306 + lines,
4307 + sentinel,
4308 + followUpTitlePrefix: `${prefix}${text}\n\n${lines.slice(0, -1).join("\n")}\n\n`,
4309 + },
4310 + };
4311 + }
4312 + }
4313 + return undefined;
4314 +}
4315 +
4316 function piUiResponse(
4317 pending: PendingPiPrompt,
4318 decision: ProviderApprovalDecision | undefined,