import { afterEach, describe, expect, it, vi } from "vitest"; import { visibleWidth } from "@earendil-works/pi-tui"; import { askQuestion, askUser, isCancel } from "./ui.js"; import { ANSWER_TYPE, PendingQuestions, registerQuestionHooks } from "./deferred.js"; import { attachHost } from "../notices.js"; import { EXPLAINED, questionTools } from "../test-helpers.js"; const UP = "\x1b[A"; const DOWN = "\x1b[B"; const LEFT = "\x1b[D"; const RIGHT = "\x1b[C"; const ENTER = "\r"; const ESC = "\x1b"; const CTRL_C = "\x03"; const SPACE = " "; const CTRL_E = "\x05"; const ALT_LEFT = "\x1b[1;3D"; const ALT_RIGHT = "\x1b[1;3C"; const BINDINGS: Record = { "tui.input.submit": [ENTER], "tui.input.newLine": ["shift+enter"], "tui.select.confirm": [ENTER], "tui.select.cancel": [ESC, CTRL_C], "tui.select.up": [UP], "tui.select.down": [DOWN], }; const keybindings = { matches: (data: string, id: string) => (BINDINGS[id] ?? []).includes(data), getKeys: (id: string) => (BINDINGS[id] ?? []).map((key) => ({ [ENTER]: "enter", [ESC]: "escape", [CTRL_C]: "ctrl+c", [UP]: "up", [DOWN]: "down" })[key] ?? key), }; const theme = { fg: (_color: string, text: string) => text, bg: (_color: string, text: string) => text, bold: (text: string) => text }; type Script = (component: any, step: number) => void; // Each custom() call mounts the real component and plays `script` against it; `step` counts mounts. function fakeUI(script: Script, extra: Record = {}) { const frames: string[][] = []; let step = 0; const ui = { working: [] as Array, setWorkingMessage(message?: string) { ui.working.push(message); }, custom: (factory: any) => new Promise((settle) => { const tui = { requestRender() {}, terminal: { rows: 40, columns: 100 } }; const component = factory(tui, theme, keybindings, settle); component.press = (...keys: string[]) => { for (const key of keys) component.handleInput(key); frames.push(component.render(100)); }; frames.push(component.render(100)); script(component, step++); }), ...extra, }; return { ui, frames }; } function harness(script: Script, extra: Record = {}, ctxExtra: Record = {}) { const tools = questionTools(); const { ui, frames } = fakeUI(script, extra); const ctx = { hasUI: true, ui, ...ctxExtra }; const run = (params: any, signal?: AbortSignal) => tools.run("ask_user", params, ctx, { signal }); return { tool: tools.registered.get("ask_user"), ui, frames, ctx, run }; } const text = (result: any) => result.content[0].text as string; const screen = (frames: string[][]) => frames[frames.length - 1]!.join("\n"); describe("ask_user in the terminal", () => { it("returns a single selection and shows the question as the main line", async () => { const { run, ui, frames } = harness((c) => c.press(DOWN, ENTER)); const result = await run({ question: "Pick a database", header: "DB", options: ["A", { title: "B", description: "bee" }] }); expect(text(result)).toBe("User answered: B"); expect(result.details).toMatchObject({ question: "Pick a database", header: "DB", options: [{ title: "A" }, { title: "B", description: "bee" }], response: { kind: "selection", selections: ["B"] }, cancelled: false, status: "answered" }); const first = frames[0]!.join("\n"); expect(first).toMatch(/╭─ ask_user · DB ─/); expect(first).toContain("Pick a database"); expect(first).not.toContain("Question"); expect(first).toContain("Other… type your own answer"); }); it("drops a context field a model still sends instead of failing", async () => { const { run, frames } = harness((c) => c.press(ENTER)); const result = await run({ question: "Pick", context: "old field", options: ["A", "B"] }); expect(text(result)).toBe("User answered: A"); expect(screen(frames)).not.toContain("old field"); expect(result.details.context).toBeUndefined(); }); it("focuses and marks the recommended option", async () => { const { run, frames } = harness((c) => c.press(ENTER)); const result = await run({ question: "Pick", options: ["A", "B", "C"], recommended: "C" }); expect(text(result)).toBe("User answered: C"); expect(frames[0]!.join("\n")).toMatch(/❯ 3 C {2}★ recommended/); }); it("answers at once with a digit and opens Other… with its own digit", async () => { expect(text(await harness((c) => c.press("2")).run({ question: "Pick", options: ["A", "B"] }))).toBe("User answered: B"); const other = harness((c) => c.press("3", ..."mine", ENTER)); expect(text(await other.run({ question: "Pick", options: ["A", "B"] }))).toBe("User answered: mine"); }); it("ignores ctrl+c in the list and in the editors", async () => { const { run, frames } = harness((c) => c.press(CTRL_C, DOWN, DOWN, ENTER, CTRL_C, ..."x", ENTER)); expect(text(await run({ question: "Pick", options: ["A", "B"] }))).toBe("User answered: x"); for (const frame of frames) expect(frame.join("\n")).not.toContain("ctrl+c"); }); it("cancels on esc after an optional reason, and with the reason when one is typed", async () => { const plain = harness((c) => c.press(ESC, ESC)); const result = await plain.run({ question: "Pick", options: ["A", "B"] }); expect(result.details).toMatchObject({ cancelled: true, cancelReason: "user", status: "cancelled" }); expect(text(result)).toMatch(/^User cancelled the question\. Do not ask it again/); const why = harness((c) => c.press(ESC, ..."need more info", ENTER)); const reasoned = await why.run({ question: "Pick", options: ["A", "B"] }); expect(reasoned.details.cancelNote).toBe("need more info"); expect(text(reasoned)).toContain('Their reason: "need more info"'); expect(screen(why.frames)).toContain("Why cancel? (optional)"); }); it("takes a free answer from Other…, keeping the draft when going back", async () => { const { run, frames } = harness((c) => c.press(DOWN, DOWN, ENTER, ..."dra", ESC, ENTER, ..."ft", ENTER)); expect(text(await run({ question: "Pick", options: ["A", "B"] }))).toBe("User answered: draft"); expect(frames.some((frame) => frame.join("\n").includes("Your answer"))).toBe(true); }); it("asks for free text directly when there are no options", async () => { const { run } = harness((c) => c.press(..."hello", ENTER)); const result = await run({ question: "Name?" }); expect(text(result)).toBe("User answered: hello"); expect(result.details.response).toEqual({ kind: "freeform", text: "hello" }); }); it("adds a comment with ctrl+e and keeps the pick when the comment is abandoned", async () => { const commented = harness((c) => c.press(DOWN, CTRL_E, ..."why not", ENTER)); expect(text(await commented.run({ question: "Pick", options: ["A", "B"] }))).toBe("User answered: B — why not"); expect(screen(commented.frames)).toContain("Comment on B"); const abandoned = harness((c) => c.press(CTRL_E, ESC, ENTER)); expect(text(await abandoned.run({ question: "Pick", options: ["A", "B"] }))).toBe("User answered: A"); const off = harness((c) => c.press(CTRL_E, ENTER)); expect(text(await off.run({ question: "Pick", options: ["A", "B"], allowComment: false }))).toBe("User answered: A"); }); it("toggles several options, never submits an empty selection, and adds a custom item", async () => { const { run, frames } = harness((c) => c.press(ENTER, DOWN, DOWN, SPACE, DOWN, SPACE, ..."E2E", ENTER, ENTER)); const result = await run({ question: "Checks?", options: ["Unit", "Lint", "Scan"], allowMultiple: true }); expect(result.details.response).toEqual({ kind: "selection", selections: ["Unit", "Scan"], other: "E2E" }); expect(text(result)).toBe("User answered: Unit, Scan, Other: E2E"); expect(frames[1]!.join("\n")).toContain("☑ Unit"); expect(screen(frames)).toContain("Other… E2E"); }); it("moves between questions with the arrow keys and keeps earlier answers", async () => { let mounts = 0; const { run } = harness((c, step) => { mounts++; if (step === 0) c.press(DOWN, ENTER); else if (step === 1) c.press(LEFT); else if (step === 2) c.press(RIGHT); else c.press(ALT_RIGHT, ENTER); }); const result = await run({ questions: [{ question: "One", options: ["A", "B"] }, { question: "Two", options: ["C", "D"] }] }); expect(text(result)).toBe("User answered:\n1. One: B\n2. Two: C"); expect(mounts).toBe(4); }); it("shows the counter and header in the frame and keeps the help line on one row", async () => { const { run, frames } = harness((c) => c.press(ENTER)); await run({ questions: [{ question: "One", header: "Region", options: ["A", "B"] }] }); expect(frames[0]![0]).toMatch(/ask_user · 1\/1 · Region/); const help = frames[0]!.filter((line) => line.includes("esc cancel")); expect(help).toHaveLength(1); for (const line of frames[0]!) expect(visibleWidth(line)).toBeLessThanOrEqual(100); }); it("delivers nothing when the run is aborted while the question is open, or before it opens", async () => { const controller = new AbortController(); const open = harness(() => controller.abort()); expect(await open.run({ question: "Pick", options: ["A", "B"] }, controller.signal)).toBeNull(); const before = harness(() => {}); expect(await before.run({ question: "Pick", options: ["A", "B"] }, controller.signal)).toBeNull(); }); it("wakes the agent with an answer or a reason, and leaves a bare dismissal for the user's next message", async () => { const answered = await harness((c) => c.press(ENTER)).run({ question: "Pick", options: ["A", "B"] }); expect(answered.delivery).toEqual({ deliverAs: "followUp", triggerTurn: true }); const dismissed = await harness((c) => c.press(ESC, ESC)).run({ question: "Pick", options: ["A", "B"] }); // Into the conversation at once without starting anything, so whatever runs next sees it. expect(dismissed.delivery).toEqual({ triggerTurn: false }); const reasoned = await harness((c) => c.press(ESC, ..."why", ENTER)).run({ question: "Pick", options: ["A", "B"] }); expect(reasoned.delivery).toEqual({ deliverAs: "followUp", triggerTurn: true }); }); }); describe("ask_user validation", () => { const run = (params: any) => harness(() => {}).run(params); it("rejects one option, duplicates and decline-only options before showing anything", async () => { expect(text(await run({ question: "Pick", options: ["Only"] }))).toMatch(/one option is not a choice/); expect(text(await run({ question: "Pick", options: ["A", "a"] }))).toMatch(/twice/); expect(text(await run({ question: "Go?", options: ["Yes", "Cancel"] }))).toMatch(/only declines.*use confirm/); expect(text(await run({ question: "Pick", options: ["A", "B"], recommended: "C" }))).toMatch(/not one of its options/); expect((await run({ questions: [{ question: "One", options: ["A", "B"] }, { question: "Two", options: ["X"] }] })).isError).toBe(true); }); it("rejects a decline option even next to real ones", async () => { expect(text(await run({ question: "Pick", options: ["A", "B", "Skip"] }))).toMatch(/"Skip", which only declines/); }); }); describe("ask_user without a UI", () => { it("returns every question with full options and asks the model to proceed on stated assumptions", async () => { const tool = questionTools().registered.get("ask_user"); const result = await tool.execute("id", tool.prepareArguments({ questions: [ { question: "Strategy?", options: [{ title: "Rolling", description: "default" }, "Canary"], recommended: "Canary" }, { question: "Checks?", options: ["Unit", "Lint"], allowMultiple: true, recommended: "Unit" }, ] }), undefined, undefined, { hasUI: false }); expect(result.isError).toBeUndefined(); expect(result.details.status).toBe("unattended"); expect(text(result)).toContain("1) Strategy?\n1. Rolling — default\n2. Canary (recommended)"); expect(text(result)).toContain("2) Checks? (several answers allowed)"); expect(text(result)).toContain("Take the recommended option for each"); }); }); describe("ask_user over host dialogs", () => { afterEach(() => { delete process.env.PASEO_AGENT_ID; attachHost({ mode: "tui" }); }); function dialogHost(answers: Array string | undefined)>) { const calls: Array<{ method: string; title: string; options?: string[]; placeholder?: string }> = []; const next = (title: string, options?: string[]) => { const answer = answers.shift(); return typeof answer === "function" ? answer(title, options) : answer; }; const ui = { select: vi.fn(async (title: string, options: string[]) => (calls.push({ method: "select", title, options }), next(title, options))), input: vi.fn(async (title: string, placeholder: string) => (calls.push({ method: "input", title, placeholder }), next(title))), notify: vi.fn(), }; const tools = questionTools(); const ctx = { hasUI: true, mode: "rpc", ui, isIdle: () => false }; attachHost(ctx); return { calls, ui, run: (params: any) => tools.run("ask_user", params, ctx) }; } it("sends one-line titles and Title — description options without numbers, and answers by label", async () => { const { calls, run } = dialogHost(["Blue/green (recommended) — instant rollback"]); const result = await run({ question: "Strategy?\nfor payments", options: ["Rolling", { title: "Blue/green", description: "instant rollback" }], recommended: "Blue/green" }); expect(text(result)).toBe("User answered: Blue/green"); expect(calls).toEqual([{ method: "select", title: "Strategy? for payments", options: ["Rolling", "Blue/green (recommended) — instant rollback", "Other…"] }]); }); it("accepts a host answering with the bare option title instead of the label it was shown", async () => { const { run } = dialogHost(["Blue/green"]); expect(text(await run({ question: "Pick", options: ["Rolling", { title: "Blue/green", description: "instant rollback" }] }))).toBe("User answered: Blue/green"); }); it("keeps titles and options within the strictest host's limits", async () => { const long = "q".repeat(400); const { calls, run } = dialogHost(["A"]); await run({ question: long, options: ["A", "o".repeat(900)] }); expect(calls[0]!.title.length).toBeLessThanOrEqual(160); expect(Math.max(...calls[0]!.options!.map((o) => o.length))).toBeLessThanOrEqual(200); }); it("pages a long option list", async () => { const options = Array.from({ length: 70 }, (_, i) => `opt${i}`); const { calls, run } = dialogHost([(_t, o) => o!.at(-1), "opt55"]); expect(text(await run({ question: "Pick", options, allowFreeform: false }))).toBe("User answered: opt55"); expect(calls[0]!.options!.length).toBeLessThanOrEqual(64); expect(calls[0]!.options!.at(-1)).toMatch(/^More… \(22 more\)$/); }); it("takes Other… through an input, and a typed answer the host made up as the answer", async () => { const { calls, run } = dialogHost(["Other…", "use argo"]); expect(text(await run({ question: "Strategy?", options: ["A", "B"] }))).toBe("User answered: use argo"); expect(calls[1]).toMatchObject({ method: "input", title: "Your answer — Strategy?", placeholder: "Type your answer" }); const sentinel = dialogHost(["✏️ Type custom response...", "my own"]); expect(text(await sentinel.run({ question: "Strategy?", options: ["A", "B"] }))).toBe("User answered: my own"); }); it("offers a comment only when asked for, and a dismissed comment keeps the answer", async () => { const { calls, run } = dialogHost(["Add a comment…", undefined, (_t, o) => o![1]]); const result = await run({ question: "Pick", options: ["A", "B"], allowComment: true }); expect(text(result)).toBe("User answered: B"); expect(calls[0]!.options).toEqual(["A", "B", "Other…", "Add a comment…"]); const plain = dialogHost(["A"]); await plain.run({ question: "Pick", options: ["A", "B"] }); expect(plain.calls[0]!.options).toEqual(["A", "B", "Other…"]); }); it("attaches a comment typed before picking", async () => { const { calls, run } = dialogHost(["Add a comment…", "keep surge at 1", "B"]); expect(text(await run({ question: "Pick", options: ["A", "B"], allowComment: true }))).toBe("User answered: B — keep surge at 1"); expect(calls[2]!.title).toBe("(comment added) Pick"); }); it("answers a multi-select with the one option picked, as bb's form submits it", async () => { // bb shows every select as a form with its own Submit: picking an option and submitting is the answer. const { calls, run } = dialogHost(["Lint (recommended) — style"]); const result = await run({ question: "Checks?", options: ["Unit", { title: "Lint", description: "style" }, "Scan"], allowMultiple: true, recommended: "Lint" }); expect(result.details.status).toBe("answered"); expect(result.details.response).toEqual({ kind: "selection", selections: ["Lint"] }); expect(calls).toHaveLength(1); expect(calls[0]!.options).toEqual(["Unit", "Lint (recommended) — style", "Scan", "Choose several…", "Other…"]); }); it("selects several options after Choose several…, with Done first", async () => { const { calls, run } = dialogHost(["Choose several…", "☐ Unit", "☐ Lint", "☑ Unit", "☐ Scan — slow", (_t, o) => o![0]]); const result = await run({ question: "Checks?", options: ["Unit", "Lint", { title: "Scan", description: "slow" }], allowMultiple: true }); expect(result.details.response).toEqual({ kind: "selection", selections: ["Lint", "Scan"] }); expect(calls[1]!.options).toEqual(["☐ Unit", "☐ Lint", "☐ Scan — slow", "Add your own…"]); expect(calls[5]!.title).toBe("(2 selected: Lint, Scan; pick to add or remove) Checks?"); expect(calls[5]!.options![0]).toBe("Done — use 2 selected"); }); it("finishes on a host that always answers with the first entry", async () => { const { run } = dialogHost(Array.from({ length: 20 }, () => (_t: string, o?: string[]) => o![0])); const result = await run({ question: "Checks?", options: ["Unit", "Lint"], allowMultiple: true }); expect(result.details.response).toEqual({ kind: "selection", selections: ["Unit"] }); }); it("gives up on a host that keeps returning the same toggle instead of looping", async () => { const { run } = dialogHost(["Choose several…", ...Array.from({ length: 20 }, () => (_t: string, o?: string[]) => o!.find((x) => x.endsWith(" Lint")))]); const result = await run({ question: "Checks?", options: ["Unit", "Lint"], allowMultiple: true }); expect(result.details.status).toBe("incomplete"); expect(text(result)).toMatch(/Ask the question in plain prose/); // The unconfirmed selection is not the user's reason for anything. expect(text(result)).not.toMatch(/Their reason/); }); it("learns that the host cannot take typed text, hides Other…, and tells the model to ask in prose", async () => { const { calls, run } = dialogHost(["Other…", undefined, undefined]); const result = await run({ question: "Pick", options: ["A", "B"] }); expect(calls.map((c) => c.method)).toEqual(["select", "input", "select"]); expect(calls[2]!.title).toBe("(typing is unavailable here) Pick"); expect(calls[2]!.options).toEqual(["A", "B"]); expect(result.details.status).toBe("cancelled"); const freeText = dialogHost([undefined]); const typed = await freeText.run({ question: "Name?" }); expect(typed.details.status).toBe("typing_unavailable"); expect(text(typed)).toMatch(/cannot collect typed answers/); }); it("walks a sequence with Back and a final review, and changing one answer returns straight to the review", async () => { const { calls, run } = dialogHost(["A", "← Back", "B", "D", "E", "Change 1: One: B", "A", "Submit"]); const result = await run({ questions: [{ question: "One", options: ["A", "B"] }, { question: "Two", options: ["C", "D"] }, { question: "Three", options: ["E", "F"] }] }); expect(text(result)).toBe("User answered:\n1. One: A\n2. Two: D\n3. Three: E"); expect(calls[0]!.title).toBe("(1/3) One"); expect(calls[1]!.options).toContain("← Back"); expect(calls[5]!.title).toBe("Submit these answers?"); expect(calls[5]!.options![0]).toBe("Submit"); expect(calls[6]!.title).toBe("(1/3) One"); expect(calls[7]!.title).toBe("Submit these answers?"); }); it("reports every answer as unsubmitted when the review is dismissed", async () => { const { run } = dialogHost(["A", "C", undefined]); const result = await run({ questions: [{ question: "One", options: ["A", "B"] }, { question: "Two", options: ["C", "D"] }] }); expect(text(result)).toMatch(/^User dismissed the final review; the answers were not submitted\..*\n1\. One: A\n2\. Two: C$/s); }); it("reports earlier answers as not submitted when a sequence is cancelled", async () => { const { run } = dialogHost(["A", undefined]); const result = await run({ questions: [{ question: "One", options: ["A", "B"] }, { question: "Two", options: ["C", "D"] }] }); expect(text(result)).toMatch(/^Stopped at question 2\/2: \(cancelled\)\..*Answered before stopping \(not submitted as a batch\):\n1\. One: A/s); }); it("keeps the comment Paseo's form took with a custom answer", async () => { process.env.PASEO_AGENT_ID = "a"; const { calls, run } = dialogHost(["✏️ Type custom response...", "use argo", "only on staging"]); expect(text(await run({ question: "Pick", options: ["A", "B"], allowComment: true }))).toBe("User answered: use argo\n\nComment: only on staging"); expect(calls[2]).toMatchObject({ method: "input", placeholder: "Optional comment — leave empty to skip" }); }); it("leaves Other… to Paseo's form for every question when the call asks for comments at the top level", async () => { process.env.PASEO_AGENT_ID = "a"; const { calls, run } = dialogHost(["A", "", "C", "", "Submit"]); await run({ allowComment: true, questions: [{ question: "One", options: ["A", "B"] }, { question: "Two", options: ["C", "D"] }] }); expect(calls[0]!.options).toEqual(["A", "B"]); expect(calls[2]!.options).toEqual(["C", "D", "← Back"]); }); it("lets Paseo's own form collect the comment, and leaves Other… to it", async () => { process.env.PASEO_AGENT_ID = "a"; const { calls, run } = dialogHost(["B", "looks fine"]); const result = await run({ question: "Pick", options: ["A", "B"], allowComment: true }); expect(text(result)).toBe("User answered: B — looks fine"); expect(calls[0]!.options).toEqual(["A", "B"]); expect(calls[1]).toMatchObject({ method: "input", placeholder: "Optional comment — leave empty to skip" }); }); }); describe("ask_user rendering", () => { const tools = questionTools(); const tool = tools.registered.get("ask_user"); it("shows the header or the question count on the call line", () => { expect(tool.renderCall({ question: "Which db?", header: "DB" }, theme).render(80).join("\n")).toContain("ask_user DB"); expect(tool.renderCall({ questions: [{}, {}] }, theme).render(80).join("\n")).toContain("ask_user 2 questions"); }); it("summarises every answer on one line each", () => { const answer = (question: string, response: any) => ({ question, options: [], response, cancelled: !response, status: response ? "answered" : "cancelled" }); const details = { ...answer("Two", { kind: "freeform", text: "hi" }), answers: [answer("One", { kind: "selection", selections: ["A"], comment: "ok" }), answer("Two", { kind: "freeform", text: "hi" }), answer("Three", null)] }; const out = tool.renderResult({ content: [], details }, { expanded: false, isPartial: false }, theme).render(120).join("\n"); expect(out).toContain("✓ One → A “ok”"); expect(out).toContain("✓ Two → “hi”"); expect(out).toContain("✗ Three cancelled"); }); it("lists the options with the chosen one marked when expanded", () => { const details = { question: "Pick", options: [{ title: "A" }, { title: "B", description: "bee" }], response: { kind: "selection", selections: ["B"] }, cancelled: false }; const out = tool.renderResult({ content: [], details }, { expanded: true, isPartial: false }, theme).render(120).join("\n"); expect(out).toContain("○ A"); expect(out).toContain("● B — bee"); }); }); describe("confirm", () => { function confirmTool() { const tools = questionTools(); return { execute: (_id: string, params: any, _signal: unknown, _onUpdate: unknown, ctx: any) => tools.run("confirm", params, ctx) }; } it("answers yes and no from the terminal, with y and n", async () => { const tool = confirmTool(); const yes = fakeUI((c) => c.press("y")); const resultYes = await tool.execute("id", { question: "Delete?" }, undefined, undefined, { hasUI: true, ui: yes.ui }); expect(resultYes.details.decision).toBe("yes"); expect(yes.frames[0]!.join("\n")).toMatch(/╭─ confirm ─/); const no = fakeUI((c) => c.press("n")); expect((await tool.execute("id", { question: "Delete?" }, undefined, undefined, { hasUI: true, ui: no.ui })).content[0].text).toMatch(/^User declined: no\. Do not do it/); }); it("puts No first for a dangerous action and reports a dismissal as not approved", async () => { const tool = confirmTool(); const enter = fakeUI((c) => c.press(ENTER)); expect((await tool.execute("id", { question: "Drop db?", danger: true }, undefined, undefined, { hasUI: true, ui: enter.ui })).details.decision).toBe("no"); const esc = fakeUI((c) => c.press(ESC, ESC)); const dismissed = await tool.execute("id", { question: "Drop db?" }, undefined, undefined, { hasUI: true, ui: esc.ui }); expect(dismissed.details.decision).toBe("dismissed"); expect(dismissed.content[0].text).toMatch(/not approved/); }); it("uses the host's native confirm with the question in the title", async () => { const tool = confirmTool(); const confirm = vi.fn(async () => true); const result = await tool.execute("id", { question: "Delete\n3 namespaces?", detail: "recreated on next PR" }, undefined, undefined, { hasUI: true, mode: "rpc", ui: { confirm } }); expect(confirm).toHaveBeenCalledWith("Delete 3 namespaces?", "recreated on next PR", expect.anything()); expect(result.details.decision).toBe("yes"); }); it("without a user, proceeds only on reversible actions and never on dangerous ones", async () => { const tool = confirmTool(); expect((await tool.execute("id", { question: "Restart?" }, undefined, undefined, { hasUI: false })).content[0].text).toMatch(/Proceed only if the action is reversible/); expect((await tool.execute("id", { question: "Drop?", danger: true }, undefined, undefined, { hasUI: false })).content[0].text).toMatch(/Do not do it/); }); }); describe("askUser for pi-pi's own menus", () => { it("returns a selection, a cancel, or null without a UI", async () => { const { ui } = fakeUI((c) => c.press(DOWN, ENTER)); expect(await askUser({ hasUI: true, ui }, { question: "Menu", options: ["One", "Two"], allowFreeform: false, allowComment: false })).toEqual({ kind: "selection", selections: ["Two"] }); const esc = fakeUI((c) => c.press(ESC)); expect(isCancel(await askUser({ hasUI: true, ui: esc.ui }, { question: "Menu", options: ["One", "Two"], allowFreeform: false }))).toBe(true); expect(await askQuestion({ hasUI: false, ui: null }, { question: "x" })).toBeNull(); }); it("makes every dangerous confirm distinct, so no host answers it from an earlier approval", async () => { const tools = questionTools(); const tool = { execute: (_id: string, params: any, _signal: unknown, _onUpdate: unknown, ctx: any) => tools.run("confirm", params, ctx) }; const confirm = vi.fn(async (_title: string, _message: string) => false); await tool.execute("id", { question: "Drop db?", danger: true }, undefined, undefined, { hasUI: true, mode: "rpc", ui: { confirm } }); await tool.execute("id", { question: "Drop db?", danger: true }, undefined, undefined, { hasUI: true, mode: "rpc", ui: { confirm } }); expect(confirm.mock.calls[0]![1]).toMatch(/^⚠ Destructive · request [0-9a-f]{8}$/); expect(confirm.mock.calls[1]![1]).not.toBe(confirm.mock.calls[0]![1]); }); }); describe("questions at the end of the turn", () => { function hooks(questions: PendingQuestions) { const handlers = new Map any>(); registerQuestionHooks({ on: (event: string, handler: any) => handlers.set(event, handler) } as any, questions); return (event: string, payload: any = {}, ctx: any = {}) => handlers.get(event)!(payload, ctx); } it("registers the question and returns at once, telling the model to explain and end the turn", async () => { const tools = questionTools(); const { ui } = fakeUI(() => {}); const ask = tools.registered.get("ask_user"); const result = await ask.execute("id", ask.prepareArguments({ question: "Pick", options: ["A", "B"] }), undefined, undefined, { hasUI: true, ui }); expect(result.details.status).toBe("registered"); expect(text(result)).toMatch(/^Registered: the question opens for the user when this turn ends, under your final message\./); expect(text(result)).toContain("Call no tool"); expect(tools.questions.waiting).toBe(true); const confirm = tools.registered.get("confirm"); const second = await confirm.execute("id", { question: "Go?" }, undefined, undefined, { hasUI: true, ui }); expect(second.isError).toBe(true); expect(text(second)).toMatch(/^Not asked: another question is already waiting for the user/); }); it("blocks every tool while a question waits, and none once it is answered", async () => { const tools = questionTools(); const fire = hooks(tools.questions); expect(await fire("tool_call", { toolName: "bash" })).toBeUndefined(); const { ui } = fakeUI((c) => c.press(ENTER)); const ask = tools.registered.get("ask_user"); await ask.execute("id", ask.prepareArguments({ question: "Pick", options: ["A", "B"] }), undefined, undefined, { hasUI: true, ui }); expect(await fire("tool_call", { toolName: "bash" })).toEqual({ block: true, reason: expect.stringMatching(/^A question for the user \("Pick"\) is registered for the end of this turn, so no tool runs until they answer\./) }); expect(await fire("tool_call", { toolName: "ask_user" })).toEqual({ block: true, reason: expect.stringMatching(/^Not asked: a question \("Pick"\) is already registered.*`questions` array/) }); await tools.questions.turnEnded({ hasUI: true, ui }, EXPLAINED); expect(tools.sent[0]!.message).toMatchObject({ customType: ANSWER_TYPE, content: "User answered: A", display: true, details: { tool: "ask_user" } }); expect(await fire("tool_call", { toolName: "bash" })).toBeUndefined(); }); it("keeps a question through a failed or empty turn, drops it when the turn is stopped, and keeps it for a message that joins the run", async () => { const sent: any[] = []; const register = (questions: PendingQuestions) => questions.register({ tool: "confirm", title: "Go?", form: "confirm", present: async () => ({ text: "x", details: {}, wake: true }) }); const questions = new PendingQuestions({ send: (message, options) => sent.push({ message, options }), warn: () => {} }); const fire = hooks(questions); register(questions); expect(await questions.turnEnded({}, { stopReason: "error" })).toBe(false); // No explanation to open under: recovery nudges the model for one first. expect(await questions.turnEnded({}, { stopReason: "stop", content: [] })).toBe(false); expect(questions.waiting).toBe(true); expect(await questions.turnEnded({}, { stopReason: "aborted" })).toBe(false); expect(questions.waiting).toBe(false); register(questions); await fire("input", { source: "extension", text: "[PI-PI] continue" }); await fire("input", { source: "rpc", text: "also fix the tests", streamingBehavior: "steer" }); expect(questions.waiting).toBe(true); expect(sent).toEqual([]); }); it("is not held back by a worker's update queued while the turn ended, only by the user's message", async () => { const sent: any[] = []; const questions = new PendingQuestions({ send: (message, options) => sent.push({ message, options }), warn: () => {} }); questions.register({ tool: "confirm", title: "Go?", form: "confirm", present: async () => ({ text: "User confirmed: yes.", details: {}, wake: true }) }); expect(await questions.turnEnded({ hasPendingMessages: () => true }, EXPLAINED)).toBe(true); expect(sent).toHaveLength(1); }); it("does not ask a question the user wrote past once the run ended, and tells the model so", async () => { const sent: any[] = []; const questions = new PendingQuestions({ send: (message, options) => sent.push({ message, options }), warn: () => {} }); const fire = hooks(questions); questions.register({ tool: "confirm", title: "Go?", form: "confirm", present: async () => ({ text: "x", details: {}, wake: true }) }); expect(await fire("input", { source: "rpc", text: "never mind" })).toEqual({ action: "continue" }); expect(questions.waiting).toBe(false); expect(sent).toEqual([{ message: expect.objectContaining({ customType: ANSWER_TYPE, content: expect.stringMatching(/^Your question \("Go\?"\) was not shown: the user wrote before it opened/) }), options: { triggerTurn: false } }]); }); it("tells the model when the question could not be shown at all", async () => { const sent: any[] = []; const questions = new PendingQuestions({ send: (message, options) => sent.push({ message, options }), warn: () => {} }); questions.register({ tool: "ask_user", title: "Pick", form: "ask", present: async () => { throw new Error("boom"); } }); expect(await questions.turnEnded({}, EXPLAINED)).toBe(true); expect(sent[0]!.message.content).toMatch(/could not be shown to the user \(boom\)\. Ask it in plain prose/); expect(sent[0]!.options).toEqual({ deliverAs: "followUp", triggerTurn: true }); }); it("renders the registered call and the answer message in the terminal", async () => { const tools = questionTools(); const ask = tools.registered.get("ask_user"); expect(ask.renderResult({ content: [], details: { status: "registered", question: "Pick", options: [] } }, { expanded: false, isPartial: false }, theme).render(80).join("\n")).toContain("asked when the turn ends"); const answer = await harness((c) => c.press(DOWN, ENTER)).run({ question: "Pick a database", header: "DB", options: ["A", "B"] }); const render = tools.renderers.get(ANSWER_TYPE)!; expect(render({ details: answer.details }, { expanded: false }, theme).render(80).join("\n")).toContain("✓ DB → B"); const confirmed = await tools.run("confirm", { question: "Go?" }, { hasUI: true, ui: fakeUI((c) => c.press("y")).ui }); expect(render({ details: confirmed.details }, { expanded: false }, theme).render(80).join("\n")).toContain("✓ yes"); }); }); describe("questions racing the user", () => { it("closes a reset question's dialog once, and a late end of it does not close the next one's", async () => { const events: boolean[] = []; const questions = new PendingQuestions({ send: () => {}, warn: () => {} }); questions.subscribe((open) => events.push(open)); let finishFirst!: () => void; questions.register({ tool: "ask_user", title: "Pick", form: "ask", present: () => new Promise((resolve) => { finishFirst = () => resolve({ text: "late", details: {}, wake: true }); }) }); const first = questions.turnEnded({}, EXPLAINED); await vi.waitFor(() => expect(events).toEqual([true])); questions.reset(); expect(events).toEqual([true, false]); questions.register({ tool: "confirm", title: "Go?", form: "confirm", present: () => new Promise(() => {}) }); void questions.turnEnded({}, EXPLAINED); await vi.waitFor(() => expect(events).toEqual([true, false, true])); finishFirst(); await first; expect(events).toEqual([true, false, true]); expect(questions.open).toBe(true); }); });