Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(asktool): bound question prompt length (#1616)
Lan38d71cc5eacd
diff --git a/docs/spec/03-runtime/17-asktool-questions.md b/docs/spec/03-runtime/17-asktool-questions.mdindex 56b0d24e9..cedc0a4a5 100644--- a/docs/spec/03-runtime/17-asktool-questions.md+++ b/docs/spec/03-runtime/17-asktool-questions.md@@ -17,6 +17,11 @@ The tool accepts a non-empty `questions` array. Each question contains:`description`;- `multiSelect`: optional; when true, more than one selectable answer is allowed.+Each question prompt is limited to 300 Unicode characters, including Markdown+source. Longer prompts are rejected by the runtime before a pending card is+created, so the model can retry with a shorter question. The character count+uses Unicode code points, so a supplementary-plane character counts once.+Plain string options remain supported. The card renders CommonMark/GFM textformatting such as emphasis, inline code, paragraphs, and lists. Links render asnon-interactive text, images as alt text, and raw HTML is ignored. Questiondiff --git a/docs/spec/04-ux/11-asktool-question-card.md b/docs/spec/04-ux/11-asktool-question-card.mdindex d0bc97812..434db0499 100644--- a/docs/spec/04-ux/11-asktool-question-card.md+++ b/docs/spec/04-ux/11-asktool-question-card.md@@ -29,6 +29,9 @@ The card has no countdown or expiration copy. On narrow screens options remainfull-width and actions may share the row; question text and custom input maywrap naturally without clipping.+Question text is limited to 300 Unicode characters before a card is opened.+Overlong questions return a tool validation error and do not create a card.+## Rich-text contentQuestion text and selectable option text may use CommonMark/GFM formatting,diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 767150438..295fec914 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -366,14 +366,18 @@(decline, skip, next) with no legacy bottom action row, then walk select →next → submit, skip → submit, decline-all, and a custom answer, remountingwith a fresh request id between flows. Finally mount a question whose body- holds two markdown blocks and measure their boxes.+ holds two markdown blocks and measure their boxes, then answer a question at+ the 300-character limit.- **Expected:** Every flow resolves through the store's `resolveAsk` with theexact answers (skips recorded as `null`), and no render errors are reported.The two question blocks stack vertically on a shared left edge that spans- the card's text column, so a sentence never wraps inside a flex column.+ the card's text column, so a sentence never wraps inside a flex column. The+ full 300-character question remains visible and answerable; runtime validation+ rejects a 301-character question before opening the card.- **Status:** Automated in `pnpm test:e2e:asktool-card`, which mounts theproduction `AskToolCard` in a real Chromium page, clicks through the header- actions, and measures the multi-block question layout.+ actions, and measures the multi-block question layout. Runtime boundary+ validation is covered by `packages/agent-runtime/src/runtime.test.ts`.### E2E-POWER-keep-awake-settingdiff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex 4764d1347..df0304e48 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -2379,6 +2379,71 @@ describe("DesktopAgentRuntime deferred tool catalog", () => {await runtime.dispose();});+ it("rejects asktool questions over 300 Unicode characters before opening a card", async () => {+ const onEvent = vi.fn();+ const runtime = createRuntime({ onEvent });+ type AskToolTestTool = {+ name: string;+ parameters: {+ properties: {+ questions: {+ items: { properties: { question: { maxLength?: number } } };+ };+ };+ };+ execute: (toolCallId: string, params: unknown) => Promise<unknown>;+ };+ const tools = (runtime as unknown as {+ agent: { state: { tools: AskToolTestTool[] } };+ }).agent.state.tools;+ const askTool = tools.find((tool) => tool.name === "asktool");+ if (!askTool) throw new Error("asktool is missing from the runtime");+ const questionSchema = askTool.parameters.properties.questions.items.properties.question;+ expect(questionSchema.maxLength).toBe(300);++ const result = await askTool.execute("ask-call-too-long", {+ questions: [{ question: "q".repeat(301), options: ["Continue"] }],+ });++ expect(result).toMatchObject({+ isError: true,+ details: { errorCode: "ASKTOOL_INVALID_ARGUMENT" },+ });+ const askRequests = () =>+ onEvent.mock.calls+ .map(([envelope]) =>+ (envelope as {+ event: {+ type: string;+ request?: { requestId: string; questions: Array<{ question: string }> };+ };+ }).event,+ )+ .filter((event) => event.type === "asktool_request");+ expect(askRequests()).toHaveLength(0);++ const validQuestion = "🧭".repeat(300);+ const pendingAtLimit = askTool.execute("ask-call-at-limit", {+ questions: [{ question: validQuestion, options: ["Continue"] }],+ });+ await new Promise<void>((resolve) => setImmediate(resolve));+ const request = askRequests()[0]?.request;+ if (!request) throw new Error("valid asktool question did not open a card");+ expect(request.questions[0].question).toBe(validQuestion);+ expect(+ runtime.resolveAskTool({+ requestId: request.requestId,+ sessionId: "session-1",+ answers: [["Continue"]],+ }),+ ).toEqual({ ok: true });+ await expect(pendingAtLimit).resolves.toMatchObject({+ content: [{ text: `${validQuestion}:Continue` }],+ details: { answers: [["Continue"]] },+ });+ await runtime.dispose();+ });+it("normalizes legacy chat onto the Plan core", async () => {const runtime = createRuntime({mode: "chat",diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex 8d5311fa5..838403b60 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -110,7 +110,9 @@ import {formatSessionMessage,hostedSearchFromMessage,isCommandShellOption,+ isAskToolQuestionWithinLimit,isToolsOutputParams,+ MAX_ASK_TOOL_QUESTION_CHARS,MAX_SUBAGENT_CONCURRENCY,normalizeAskToolOption,normalizeSubagentName,@@ -3193,7 +3195,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when thecase "TodoWrite":return todoWriteDescription;case ASK_TOOL_NAME:- return "Ask the user one or more questions. Use Markdown in question text and option labels when formatting helps (for example, emphasis, inline code, or lists); the desktop card renders it safely. Plain strings and existing `{ label, description? }` options are accepted; descriptions remain plain text and answers return the selected source label. The card always provides a custom user-input option.";+ return `Ask the user one or more questions. Keep each question to ${MAX_ASK_TOOL_QUESTION_CHARS} characters or fewer. Use Markdown in question text and option labels when formatting helps (for example, emphasis, inline code, or lists); the desktop card renders it safely. Plain strings and existing { label, description? } options are accepted; descriptions remain plain text and answers return the selected source label. The card always provides a custom user-input option.`;case "PluginScaffold":return "Create a PI-Desktop plugin from a template and load it for development. `directory` is workspace-relative and must be empty or new; `template` is one of panel-basic, agent-tool-basic, skill-pack, full-demo. Use this instead of hand-writing plugin files.";case "PluginCheck":@@ -3701,7 +3703,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when theparameters: Type.Object({questions: Type.Array(Type.Object({- question: Type.String(),+ question: Type.String({ maxLength: MAX_ASK_TOOL_QUESTION_CHARS }),options: Type.Array(Type.Union([Type.String(),@@ -3723,7 +3725,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when thecontent: [{type: "text",- text: `${ASK_TOOL_NAME} requires one or more questions, each with a question and at least one option.`,+ text: `${ASK_TOOL_NAME} requires 1–20 questions. Each question must contain 1–${MAX_ASK_TOOL_QUESTION_CHARS} characters and at least one option.`,},],details: { errorCode: "ASKTOOL_INVALID_ARGUMENT" },@@ -5819,6 +5821,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when thefor (const raw of params.questions) {if (!isRecord(raw)) return undefined;const question = typeof raw.question === "string" ? raw.question.trim() : "";+ if (!question || !isAskToolQuestionWithinLimit(question)) return undefined;const options: AskToolQuestion["options"] = [];const seenLabels = new Set<string>();if (Array.isArray(raw.options)) {@@ -5831,7 +5834,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when theoptions.push(option);}}- if (!question || options.length === 0) return undefined;+ if (options.length === 0) return undefined;questions.push({question,options,diff --git a/packages/shared/src/asktool.test.ts b/packages/shared/src/asktool.test.tsindex ea673946a..450de1837 100644--- a/packages/shared/src/asktool.test.ts+++ b/packages/shared/src/asktool.test.ts@@ -1,5 +1,10 @@import { describe, expect, it } from "vitest";-import { formatAskToolOutput, type AskToolQuestion } from "./types.js";+import {+ formatAskToolOutput,+ isAskToolQuestionWithinLimit,+ MAX_ASK_TOOL_QUESTION_CHARS,+ type AskToolQuestion,+} from "./types.js";describe("asktool output", () => {const questions: AskToolQuestion[] = [@@ -25,4 +30,11 @@ describe("asktool output", () => {"Preferred color?:\n---\nWhich platforms?:Desktop",);});++ it("limits questions to 300 Unicode characters", () => {+ expect(isAskToolQuestionWithinLimit("q".repeat(MAX_ASK_TOOL_QUESTION_CHARS))).toBe(true);+ expect(isAskToolQuestionWithinLimit("q".repeat(MAX_ASK_TOOL_QUESTION_CHARS + 1))).toBe(false);+ expect(isAskToolQuestionWithinLimit("🧭".repeat(MAX_ASK_TOOL_QUESTION_CHARS))).toBe(true);+ expect(isAskToolQuestionWithinLimit("🧭".repeat(MAX_ASK_TOOL_QUESTION_CHARS + 1))).toBe(false);+ });});diff --git a/packages/shared/src/types/agent.ts b/packages/shared/src/types/agent.tsindex 7d594b325..6d3e1bf90 100644--- a/packages/shared/src/types/agent.ts+++ b/packages/shared/src/types/agent.ts@@ -180,6 +180,18 @@ export type AskToolOption =description?: string;};+/** Maximum length of one asktool prompt, counted in Unicode code points. */+export const MAX_ASK_TOOL_QUESTION_CHARS = 300;++export function isAskToolQuestionWithinLimit(question: string): boolean {+ let characterCount = 0;+ for (const _character of question) {+ if (characterCount >= MAX_ASK_TOOL_QUESTION_CHARS) return false;+ characterCount += 1;+ }+ return true;+}+/** Normalize a model-provided asktool option and discard malformed/empty values. */export function normalizeAskToolOption(value: unknown): AskToolOption | undefined {if (typeof value === "string") {diff --git a/scripts/e2e/asktool-card.tsx b/scripts/e2e/asktool-card.tsxindex 6d641e0f4..26fdbeec2 100644--- a/scripts/e2e/asktool-card.tsx+++ b/scripts/e2e/asktool-card.tsx@@ -17,6 +17,7 @@ import { flushSync } from "react-dom";import i18n from "i18next";import { I18nextProvider } from "react-i18next";import { en } from "@pi-desktop/i18n";+import { MAX_ASK_TOOL_QUESTION_CHARS } from "../../packages/shared/src/types/agent";import { AskToolCard } from "../../apps/desktop/src/components/AskToolCard";import { api } from "../../apps/desktop/src/lib/api";import { useAppStore } from "../../apps/desktop/src/stores/app-store";@@ -95,6 +96,11 @@ const LONG_QUESTIONS: FixtureQuestion[] = [},];+const MAX_LENGTH_QUESTION: FixtureQuestion = {+ question: "q".repeat(MAX_ASK_TOOL_QUESTION_CHARS),+ options: [{ label: "continue", description: "Proceed with the selected choice." }],+};+export async function asktoolCardProbe() {await i18n.init({ lng: "en", resources: { en: { translation: en } } });const initial = useAppStore.getState();@@ -369,6 +375,22 @@ export async function asktoolCardProbe() {"the next long question starts at the top",);+ // Flow G: the maximum permitted prompt remains visible and answerable.+ mount("ask-max-length", [MAX_LENGTH_QUESTION]);+ await until(() => options().length === 1, "maximum-length question mounts");+ const maxLengthQuestion = "q".repeat(MAX_ASK_TOOL_QUESTION_CHARS);+ assert(+ questionText().endsWith(maxLengthQuestion),+ "the card displays the complete 300-character question",+ );+ flushSync(() => options()[0]!.click());+ flushSync(() => headerButtons().primary.click());+ await until(() => resolutions.length === 5, "maximum-length question resolves");+ assert(+ JSON.stringify(resolutions[4]!.answers) === JSON.stringify([["continue"]]),+ "the maximum-length question remains answerable",+ );+assert(errors.length === 0, `render errors: ${errors.map(String)}`);return { ok: true, resolutions: resolutions.length };} catch (error) {