From ff39b9dcbce3a7d70bab2b5fc8ce558700ac3e98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaroslav=20Bene=C5=A1?= Date: Thu, 12 Nov 2026 19:02:08 +0000 Subject: [PATCH] What is a command where there is no menu; /command and /skill; hidden custom commands A command that takes no words is the command only alone, and /mcp only for a server's name: anything else is a prompt. lembas run --json gets the text as an event and the end; a command that could not do what was asked exits 1. /command runs a custom command by name (TUI and link), /skill works over the link, and a custom command hidden by a built-in's name is said once at start. The start-up line for a failed MCP server is cleaned, redacted, and promises only what every front end has. The status bar's MCP subscription is dropped with the screen. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 19 +++- src/app.ts | 13 ++- src/cli.ts | 11 ++- src/session/commands.ts | 48 +++++++--- src/tui/app.tsx | 9 +- src/tui/commands.ts | 12 +++ tests/e2e.test.ts | 35 ++++++++ tests/tui/mcp.test.tsx | 192 +++++++++++++++++++++++++++++++++++++--- 8 files changed, 305 insertions(+), 34 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 660b707..c79ce5b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,8 +39,23 @@ All notable changes to LLeMbas CLI. The format follows - **`/agents` is a menu** of the subagents; Enter puts one's name in the box to hand it a task. - **`lembas run "/mcp"`** (and `/status`, `/permissions`, `/agents`, `/team`) prints the command's text instead of sending the words to the model; the same text answers these commands over the - link. `permissions` and `status` are now command names of the program: a custom command or a - skill of either name is reached as `/skill `. + link. Only the command alone is the command: `/status of the build?` is a question for the + model, and `/mcp ` is the command only when the word is a server's name. With `--json` + the text is an event of the stream; a command that could not do what was asked exits 1. +- **`/command [words]`** runs a custom command by its name, and **`/skill `** now + works over the link too. `permissions`, `status` and `command` are command names of the + program: a custom command of such a name is said once at start, with `/command ` as the + way to it; a skill is reached as `/skill `. +- **What `/mcp` prints does not carry what your config resolved to**: an address is shown + without user, password or query, a local server by its program's name alone, an error by its + first line with what looks like a secret taken out — and never a local server's stderr. The + menu shows an error in full, on your own screen. +- **A server's own words cannot draw on your terminal or put markup into a reply**: control + characters and escape sequences are taken out of every name, description, error and stderr + line an MCP server supplies; where `/mcp`'s text becomes a markdown reply, descriptions are + escaped. +- **Two MCP tools whose names come out the same both get a distinguishing suffix**, so a server + that lists its tools in another order cannot move an "always allow" onto the other tool. ### Changed diff --git a/src/app.ts b/src/app.ts index b37e421..4b72d78 100644 --- a/src/app.ts +++ b/src/app.ts @@ -43,6 +43,9 @@ import { instances as lembasInstances, keyFile as lembasKeyFile } from "./lembas import { PERSONAL_KEYS, personalConfig, pushPersonalization } from "./lembas/personal.ts" import type { Plan } from "./plan/plan.ts" import { LIBRARY_SERVER, mcpInstructions } from "./mcp/index.ts" +import { clean as cleanText, errorLine } from "./mcp/clean.ts" +import { customCommands } from "./project/commands.ts" +import { TUI_COMMAND_NAMES } from "./session/commands.ts" import type { McpServer } from "./config/schema.ts" import { embedderFor } from "./library/embed.ts" import { isLevel, levelsFor, readLevel, type Level } from "./provider/effort.ts" @@ -798,8 +801,10 @@ export function createApp(o: AppOptions): App { seen.set(s.name, s.status) // A server that connected says nothing: that is what was meant to happen, and the status // bar counts it. One that did not gets one line that says which, why, and where to go. - if (s.status === "failed") bus.emit({ type: "notice", level: "warn", message: `MCP ${s.name} did not connect: ${(s.error ?? "failed").split("\n")[0]} — /mcp ${s.name} shows more and reconnects` }) - else if (s.status === "needs_auth") bus.emit({ type: "notice", level: "warn", message: `MCP ${s.name} needs you to sign in — /mcp ${s.name}` }) + // One line, cleaned and with nothing secret in it (it goes to every front end, the link's + // included), and promising only what every front end has: /mcp shows the server. + if (s.status === "failed") bus.emit({ type: "notice", level: "warn", message: `MCP ${cleanText(s.name)} did not connect: ${errorLine(s.error) || "no reason given"} — /mcp ${cleanText(s.name)} shows more` }) + else if (s.status === "needs_auth") bus.emit({ type: "notice", level: "warn", message: `MCP ${cleanText(s.name)} needs you to sign in — /mcp ${cleanText(s.name)}` }) } }) const mcpReady = mcp.start() @@ -954,6 +959,10 @@ export function createApp(o: AppOptions): App { } if (session) bus.emit({ type: "session", id: session.id, model: model.ref, mode }) + // A custom command named like a command of the program is hidden by it: said once at start, + // with the way to it. + for (const cc of customCommands(trusted ? project.dir : undefined)) + if ((TUI_COMMAND_NAMES as readonly string[]).includes(cc.name)) loaded.warnings.push(`the custom command /${cc.name} (${cc.file}) has the name of a built-in command, which wins — run it as /command ${cc.name}, or rename the file`) for (const w of loaded.warnings) bus.emit({ type: "notice", message: w }) return { bus, diff --git a/src/cli.ts b/src/cli.ts index 495d9da..49b9f4f 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -347,11 +347,16 @@ async function main() { await app.mcpReady // A command that only says something (/mcp, /agents, /team — what the TUI shows as a menu): // its text, and no model is asked. - const said = expandSlash(app, prompt) + const said = expandSlash(app, prompt, { plain: true }) if (said?.kind === "message") { - console.log(said.text) + // With --json the text is an event of the stream like any other, then the end; plainly, it + // is the output. A command that could not do what was asked exits 1. + if (values.json) { + app.bus.emit({ type: "notice", level: said.error ? "error" : "info", message: said.text }) + app.bus.emit({ type: "done", reason: said.error ? "error" : "stop" }) + } else (said.error ? console.error : console.log)(said.text) app.discardIfEmpty() - process.exit(0) + process.exit(said.error ? 1 : 0) } const atts = attachmentsFor(prompt, app.engine.o.toolCtx, app.engine.model.spec.vision === true) // Through the turns, like every front end: a job's note wakes the session the same way. diff --git a/src/session/commands.ts b/src/session/commands.ts index ac0bb72..ada5fc0 100644 --- a/src/session/commands.ts +++ b/src/session/commands.ts @@ -40,7 +40,7 @@ export const TUI_COMMAND_NAMES = [ "agents", "continue", "help", "model", "effort", "mode", "plan", "plans", "prototype", "review", "changelog", "init", "release", "tasks", "decisions", "decide", "jobs", "sessions", "resume", "remote", "delete", "new", "clear", "copy", "undo", "redo", "diff", "checkpoint", "checkpoints", "branch", "commit", "context", "compact", "memory", "skills", "skill", "personality", "voice", "speak", "mcp", "login", "logout", "settings", "usage", "kb", "theme", "skin", "terminal", - "icons", "trust", "reload", "restart", "quit", "exit", "q", "team", "rename", "schedule", "schedules", "search", "permissions", "status", + "icons", "trust", "reload", "restart", "quit", "exit", "q", "team", "rename", "schedule", "schedules", "search", "permissions", "status", "command", ] as const /** The built-ins that work without a screen of their own. Descriptions as the TUI's (a test). */ @@ -55,6 +55,8 @@ export const SHARED_BUILTINS: { name: string; description: string; hint?: string { name: "mcp", description: "MCP servers: a menu of them — state, tools and what each may do, sign in, switch one on or off", hint: "server" }, { name: "permissions", description: "the permission rules in force — this session's, the project's, yours, the built-in ones; change or add one" }, { name: "status", description: "everything in one place: the server and login, the session, the project, the MCP servers, this terminal" }, + { name: "skill", description: "use a skill (for one whose name a command already has)", hint: "name [instruction]" }, + { name: "command", description: "run a custom command by its name (for one whose name a built-in command has)", hint: "name [words]" }, { name: "agents", description: "subagents: list them, make one, or hand one a task", hint: "name" }, { name: "team", description: "subagents: the tree and the room; how many; stop one; their findings", hint: "size | stop | findings " }, ] @@ -193,7 +195,8 @@ export type Expanded = /** A built-in that is not a prompt (compact, undo; plan without a task). */ | { kind: "action"; name: "compact" | "undo" | "plan"; arg: string } /** Nothing to send, and why (a review with no changes). */ - | { kind: "message"; name: string; text: string } + /** `error`: the text says the command could not do what was asked (an unknown name). */ + | { kind: "message"; name: string; text: string; error?: boolean } /** `/review [head | ]`: the change, as a prompt for a read-only review — or why there is none. */ export function reviewPrompt(app: App, arg: string): { prompt: string } | { message: string } { @@ -249,7 +252,9 @@ export function initPrompt(app: App, arg: string): string { /** A prompt's text as a command of the shared set, or undefined when it is not one — then it goes * to the model as it is, `/` and all (a path, a regex, a command this machine does not have). */ -export function expandSlash(app: App, text: string): Expanded | undefined { +/** `plain`: the text is printed as it is (`lembas run`), not drawn as markdown (a reply in the + * web UI, which is what a prompt over the link becomes). */ +export function expandSlash(app: App, text: string, o: { plain?: boolean } = {}): Expanded | undefined { const t = text.trim() const m = /^\/([a-z0-9_:-]+)(?:\s+([\s\S]*))?$/i.exec(t) if (!m) return undefined @@ -266,18 +271,20 @@ export function expandSlash(app: App, text: string): Expanded | undefined { case "agents": // List and describe anywhere; `new` and ` ` are the TUI's own. if (/^(new)\b/.test(arg) || arg.trim().split(/\s+/).length > 1) return { kind: "message", name, text: "/agents here lists and describes the subagents; making one or handing one a task is done at the terminal." } - return { kind: "message", name, text: agentsText(app, arg) } + return ((text) => ({ kind: "message" as const, name, text, ...(text.startsWith("no agent ") ? { error: true } : {}) }))(agentsText(app, arg)) case "team": return { kind: "message", name, text: teamText(app, arg) } + // A command that takes no words is the command only when it stands alone: "/status of the + // build?" is a question for the model. case "permissions": - return { kind: "message", name, text: permissionsText(app) } + return arg ? undefined : { kind: "message", name, text: permissionsText(app) } case "status": - return { kind: "message", name, text: statusText(app) } + return arg ? undefined : { kind: "message", name, text: statusText(app) } case "mcp": - // No menu here: the servers as a table, or one server's tools. What changes a server (sign - // in, switch off) is the terminal's to do. - if (/^(reconnect|on|off|auth|code|logout)\b/.test(arg.trim())) return { kind: "message", name, text: "/mcp here shows the servers and their tools; connecting, switching one off and signing in are done at the terminal." } - return { kind: "message", name, text: mcpText(app.mcp, arg.trim().split(/\s+/)[0] ?? "", (tool) => app.engine.ruleFor(tool)) } + // No menu here: the servers as a list, or — when the one word after it is exactly a + // server's name — that server's tools. Anything else is a prompt. + if (arg && !app.mcp.servers.has(arg)) return undefined + return { kind: "message", name, text: mcpText(app.mcp, arg, (tool) => app.engine.ruleFor(tool), { markdown: !o.plain }) } case "init": // The prompt is ours; only what was typed after the name may attach files. return { kind: "prompt", name, prompt: initPrompt(app, arg), shown: t, attachFrom: arg } @@ -291,17 +298,30 @@ export function expandSlash(app: App, text: string): Expanded | undefined { return "message" in r ? { kind: "message", name, text: r.message } : { kind: "prompt", name, prompt: r.prompt, shown: t, attachFrom: "" } } } - if (reserved.has(name)) return undefined const src = sourcesOf(app) - const cc = customCommands(src.projectDir).find((c) => c.name === name) + // The way to a skill or a custom command whose own name a built-in command has. + let wanted = name + let words = arg + let only: "skill" | "custom" | undefined + if (name === "skill" || name === "command") { + const [first = "", ...rest] = arg.split(/\s+/) + if (!first) return undefined + wanted = name === "skill" ? slug(first) : first.toLowerCase() + words = rest.join(" ") + only = name === "skill" ? "skill" : "custom" + } else if (reserved.has(name)) return undefined + const cc = only === "skill" ? undefined : customCommands(src.projectDir).find((c) => c.name === wanted) + if (only === "custom" && !cc) return { kind: "message", name, text: `no custom command "${wanted}"`, error: true } if (cc) { + const arg = words // A project's command may make the mode stricter for its prompt, never looser; your own may. const own = cc.mode && (MODES as readonly string[]).includes(cc.mode) ? (cc.mode as Mode) : undefined const mode = own && cc.source === "project" ? stricter(own, app.engine.mode) : own return { kind: "prompt", name, prompt: expandCommand(cc, arg, app.project.root, app.engine.o.perm.hardline), shown: t, attachFrom: arg, model: cc.model, ...(mode ? { mode } : {}) } } - const sk = src.skills().find((s) => slug(s.name) === name) - if (sk) return { kind: "prompt", name, prompt: skillMessage(sk, arg), shown: t, attachFrom: arg } + const sk = src.skills().find((s) => slug(s.name) === wanted) + if (sk) return { kind: "prompt", name, prompt: skillMessage(sk, words), shown: t, attachFrom: words } + if (only === "skill") return { kind: "message", name, text: `no skill "${wanted}"`, error: true } return undefined } diff --git a/src/tui/app.tsx b/src/tui/app.tsx index 6f90ddb..998b910 100644 --- a/src/tui/app.tsx +++ b/src/tui/app.tsx @@ -65,7 +65,7 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () => // "team 3/4 · 2 working" while the lead has members (team.md, the TUI's status). const teamWord = () => (rev(), teamLabel(app.team.team)) // The status bar follows the MCP servers as they connect (and nothing is said in the transcript). - app.mcp.onChange(() => refresh()) + onCleanup(app.mcp.onChange(() => refresh())) const busy = () => view.state.phase !== "idle" const branch = () => (rev(), app.project.gitRoot ? currentBranch(app.project.gitRoot) : undefined) // A word in the status bar that goes by itself (a copy): it says something happened without @@ -302,6 +302,11 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () => continueTask: () => continueTask(), sendAs: (prompt: string, shown: string, opts?: { model?: string; mode?: string }) => void sendAs(prompt, shown, opts), runLine: (line: string) => submit(line), + runCustom: (name: string, arg: string, typed: string) => { + const cc = custom().find((x) => x.name === name) + if (cc) void runCustom(cc, arg, typed) + return Boolean(cc) + }, setInput(text: string) { input?.setText(text) input?.gotoBufferEnd() @@ -465,7 +470,7 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () => if (c) { // Not mid-task: what changes the session under it, and what sends a prompt of its own // (that would start a second turn on top of the running one). - const midTask = ["new", "delete", "compact", "sessions", "model", "undo", "redo", "commit", "diff", "release", "changelog", "init", "checkpoint", "checkpoints", "branch", "reload", "review", "skill"] + const midTask = ["command", "new", "delete", "compact", "sessions", "model", "undo", "redo", "commit", "diff", "release", "changelog", "init", "checkpoint", "checkpoints", "branch", "reload", "review", "skill"] if ((busy() || app.turns.current) && (midTask.includes(c.name) || (c.name === "plan" && arg && arg !== "show"))) return (view.info("wait for the reply to finish (esc stops it)", "warn"), false) return void c.run(cmd, arg) } diff --git a/src/tui/commands.ts b/src/tui/commands.ts index 7094a48..9dc984c 100644 --- a/src/tui/commands.ts +++ b/src/tui/commands.ts @@ -53,6 +53,8 @@ export interface CommandCtx extends Ctx { /** Run a line as if it had been typed and sent — a command chosen in a menu goes through the * same checks as one typed (not mid-reply, and so on). false: refused. */ runLine(line: string): boolean | void + /** Run a custom command (a file under commands/) by its name; false when there is none. */ + runCustom(name: string, arg: string, typed: string): boolean setMode(m: Mode): void setEffort(e: Level): void setTheme(name: string): void @@ -934,6 +936,16 @@ export const COMMANDS: Command[] = [ c.sendAs?.(skillMessage(s, rest.join(" ")), `/skill ${arg.trim()}`, { attachFrom: rest.join(" ") }) }, }, + { + name: "command", + args: " [words]", + description: "run a custom command by its name (for one whose name a built-in command has)", + run(c, arg) { + const [name = "", ...rest] = arg.trim().split(/\s+/) + if (!name) return c.view.info("usage: /command [words] — a custom command from .agent/commands or ~/.config/lembas/commands", "warn") + if (!c.runCustom(name, rest.join(" "), `/command ${arg.trim()}`)) c.view.info(`no custom command "${name}"`, "warn") + }, + }, { name: "personality", args: "[preset|custom|none]", diff --git a/tests/e2e.test.ts b/tests/e2e.test.ts index 18d5e89..8ca2d99 100644 --- a/tests/e2e.test.ts +++ b/tests/e2e.test.ts @@ -139,6 +139,41 @@ describe("end to end", () => { expect(out).toBe("Hi from the fake.\n") expect(code).toBe(0) }) + + test("the CLI: a command that only says something is printed; the same word in a sentence is a prompt; --json gets events; an unknown name exits 1", async () => { + const dir = setup([{ chunks: [delta({ content: "The build is fine." })] }, { chunks: [delta({ content: "No such server." })] }]) + const run = async (...args: string[]) => { + const p = Bun.spawn(["bun", join(import.meta.dir, "../src/cli.ts"), "run", "--no-store", ...args], { cwd: dir, env: { ...process.env }, stdout: "pipe", stderr: "pipe" }) + const [out, err, code] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text(), p.exited]) + return { out, err, code } + } + // Alone, it is the command: its text, no model asked. + const status = await run("/status") + expect(status.code).toBe(0) + expect(status.out).toContain("This program:\n- version: ") + expect(fake!.requests).toHaveLength(0) + // In a sentence it is a question for the model. + const asked = await run("/status of the build?") + expect(asked.out).toBe("The build is fine.\n") + expect(fake!.requests).toHaveLength(1) + expect(JSON.stringify(fake!.requests[0].messages.at(-1))).toContain("/status of the build?") + // /mcp with a word that is no server's name: a prompt too. + const mcp = await run("/mcp servers are what, exactly?") + expect(mcp.out).toBe("No such server.\n") + expect(fake!.requests).toHaveLength(2) + // --json: every line of stdout is an event; the text is one of them, then the end. + const json = await run("--json", "/permissions") + const events = json.out.trim().split("\n").map((l) => JSON.parse(l) as { type: string; message?: string; reason?: string; level?: string }) + expect(events.find((e) => e.type === "notice" && e.level === "info")!.message).toStartWith("Mode: ") + expect(events.at(-1)).toMatchObject({ type: "done", reason: "stop" }) + expect(json.code).toBe(0) + // A command that could not do what was asked: on stderr, exit 1. + const none = await run("/agents nosuchagent") + expect(none.code).toBe(1) + expect(none.out).toBe("") + expect(none.err).toContain('no agent "nosuchagent"') + expect(fake!.requests).toHaveLength(2) + }, 60_000) }) describe("nobody to approve", () => { diff --git a/tests/tui/mcp.test.tsx b/tests/tui/mcp.test.tsx index 3d539c4..c028c84 100644 --- a/tests/tui/mcp.test.tsx +++ b/tests/tui/mcp.test.tsx @@ -17,11 +17,10 @@ test("a server that connects says nothing at start: no warning sign, no block await t.app.mcpReady await t.settle(200) const f = t.frame() - // (Other notices may be there — the whole suite shares one config directory — but none of MCP.) - const said = t.view.state.items.filter((i) => i.kind === "notice").map((i) => (i as { text: string }).text) - expect(said.filter((x) => /MCP|mcp__|connected/.test(x))).toEqual([]) - expect(f).not.toContain(`${NOTICES.warn.glyph} MCP`) - expect(f).not.toContain("connected —") + // No notice of any kind, and no warning sign anywhere on the screen. + expect(t.view.state.items.filter((i) => i.kind === "notice")).toEqual([]) + expect(f).not.toContain(NOTICES.warn.glyph) + expect(f).not.toContain("connected") expect(f).not.toContain("mcp__") expect(f.split("\n").at(-2)).toContain("MCP 1 · ") }) @@ -30,11 +29,11 @@ test("a server that fails gets one plain line naming it and /mcp; the status bar t = await tui([], { width: 140, height: 30 }, `mcp:\n${local("fix")}${broken("gone")}`) await t.app.mcpReady await t.settle(300) - const notices = (t.view.state.items.filter((i) => i.kind === "notice") as { text: string; level: string }[]).filter((n) => n.text.startsWith("MCP ")) + const notices = t.view.state.items.filter((i) => i.kind === "notice") as { text: string; level: string }[] expect(notices.length).toBe(1) expect(notices[0]!.level).toBe("warn") expect(notices[0]!.text).toStartWith("MCP gone did not connect: ") - expect(notices[0]!.text).toEndWith("— /mcp gone shows more and reconnects") + expect(notices[0]!.text).toEndWith("— /mcp gone shows more") expect(notices[0]!.text).not.toContain("\n") expect(t.frame().split("\n").at(-2)).toContain("MCP 1/2 · ") }) @@ -241,12 +240,183 @@ test("without a menu — over the link, in lembas run — /mcp is a plain table, ]) const one = (expandSlash(t.app, "/mcp alpha") as { text: string }).text expect(one).toContain("alpha — connected — 2 tools") - expect(one).toContain("\n- mcp__alpha__tool_0 — asks — Does thing 0.") - expect(one).toContain("\n- mcp__alpha__tool_1 — always allowed — Does thing 1.") + // Over the link the text is drawn as markdown: a tool's name is code. + expect(one).toContain("\n- `mcp__alpha__tool_0` — asks — Does thing 0.") + expect(one).toContain("\n- `mcp__alpha__tool_1` — always allowed — Does thing 1.") + // In lembas run it is printed as it is. + const plain = (expandSlash(t.app, "/mcp alpha", { plain: true }) as { text: string }).text + expect(plain).toContain("\n- mcp__alpha__tool_0 — asks — Does thing 0.") // One to a line in a terminal and where a reply is drawn as markdown: list lines, none indented. expect(text.split("\n").some((l) => /^ {1,3}\S/.test(l))).toBe(false) - expect((expandSlash(t.app, "/mcp beta") as { text: string }).text).toContain("at the second line") - expect((expandSlash(t.app, "/mcp off alpha") as { text: string }).text).toContain("done at the terminal") + // An error is its first line only where the text may leave this machine. + expect((expandSlash(t.app, "/mcp beta") as { text: string }).text).not.toContain("at the second line") + // Only alone, or with exactly a server's name, is it the command; anything else is a prompt. + expect(expandSlash(t.app, "/mcp off alpha")).toBeUndefined() + expect(expandSlash(t.app, "/mcp nosuch")).toBeUndefined() + expect(expandSlash(t.app, "/status of the build?")).toBeUndefined() + expect(expandSlash(t.app, "/permissions please")).toBeUndefined() expect(mcpText(t.app.mcp, "nosuch")).toContain('No MCP server "nosuch"') expect(readFileSync(join(import.meta.dir, "..", "..", "src", "mcp", "text.ts"), "utf8")).not.toMatch(/\.lan\b/) }) + +// ---- found in review ---- + +import { mkdirSync, writeFileSync } from "node:fs" +import { TextareaRenderable } from "@opentui/core" +import { paths } from "../../src/config/paths.ts" +const box = (n: any): TextareaRenderable => (n instanceof TextareaRenderable ? n : n.getChildren?.().map(box).find(Boolean)) +const noticesOf = () => (t!.view.state.items.filter((i) => i.kind === "notice") as { text: string; level: string }[]).map((n) => n.text) + +test("a server's strings cannot draw on the screen; a prompt goes into the box under its registered name", async () => { + t = await tui([], { width: 110, height: 34 }) + const a = box(t.setup.renderer.root) + put( + fake("evil", { + tools: [{ name: "wipe", description: "Clears \x1b[2J\x1b[Hthe \x1b]0;pwned\x07screen.\nAnd more.", inputSchema: {} }], + prompts: [{ name: "do it.now", description: "Says \x1b[31mhello" }], + error: undefined, + }), + ) + t.app.mcp.tools() + await t.input.typeText("/mcp evil") + t.input.pressEnter() + expect(await t.until("MCP · evil")).toBe(true) + const f = t.frame() + expect(f).not.toContain("\x1b") + expect(f).not.toContain("pwned") + expect(f).toContain("Clears the screen.") + expect(f).toContain("/evil:do_it_now") + expect(f).not.toContain("/evil:do it.now") + t.input.pressKey("END") + await t.settle() + t.input.pressEnter() + await t.settle() + expect(a.plainText).toBe("/evil:do_it_now ") +}) + +test("a reconnect that fails says so once; reading the error does not close the menu on Enter; signing out asks first", async () => { + t = await tui([], { width: 120, height: 36 }, `mcp:\n${broken("gone")}`) + await t.app.mcpReady + await t.settle(300) + expect(noticesOf().filter((x) => x.startsWith("MCP gone")).length).toBe(1) + await t.input.typeText("/mcp gone") + t.input.pressEnter() + expect(await t.until("Connect again")).toBe(true) + t.input.pressEnter() // Connect again + const end = Date.now() + 6000 + while (Date.now() < end && noticesOf().filter((x) => x.startsWith("MCP gone")).length < 2) await t.settle(60) + await t.settle(400) + // One more line for the one more failure — not two. + expect(noticesOf().filter((x) => x.startsWith("MCP gone")).length).toBe(2) + expect(await t.until("MCP · gone")).toBe(true) + // The error in full: Enter on a line of it does nothing, and the view stays. + for (let i = 0; i < 2; i++) t.input.pressArrow("down") + t.input.pressEnter() + expect(await t.until("MCP · gone · the last error")).toBe(true) + t.input.pressEnter() + await t.settle(120) + expect(t.frame()).toContain("MCP · gone · the last error") + t.input.pressEscape() + await t.settle() + t.input.pressEscape() + await t.settle() + t.input.pressEscape() + await t.settle() + // Sign out: asked once, and "keep" is where the cursor starts. + put(fake("web", { status: "connected" })) + let out = 0 + t.app.mcp.logout = () => void out++ + await t.input.typeText("/mcp web") + t.input.pressEnter() + expect(await t.until("MCP · web")).toBe(true) + for (let i = 0; i < 3; i++) t.input.pressArrow("down") + t.input.pressEnter() + expect(await t.until("Sign out of web?")).toBe(true) + t.input.pressEnter() // keep the sign-in + expect(await t.until("MCP · web")).toBe(true) + expect(out).toBe(0) + t.input.pressEnter() + expect(await t.until("Sign out of web?")).toBe(true) + t.input.pressArrow("up") + t.input.pressEnter() + await t.settle(150) + expect(out).toBe(1) +}) + +test("a server the person's own config switches off is switched on for the session only, and the menu says why", async () => { + t = await tui([], { width: 130, height: 34 }) + // As if the project were trusted: the question is only what "on" may be kept for. + ;(t.app as { trusted: boolean }).trusted = true + put(fake("quiet", { status: "disabled", cfg: { url: "https://example.org/quiet/mcp", source: "global", enabled: false } as never, tools: [] })) + await t.input.typeText("/mcp quiet") + t.input.pressEnter() + expect(await t.until("MCP · quiet")).toBe(true) + const row = t.frame().split("\n").find((l) => l.includes("Switch on"))! + expect(row).toContain("connect it — for this session") + expect(row).not.toContain("for this project") + // Why, under the list while the row is highlighted. + expect(t.frame()).toContain("Your own config switches this server off") + expect(t.frame()).toContain("project cannot switch it") +}) + +test("a menu fits the rows there are, and its list does not move when the highlighted row has more to say", async () => { + for (const height of [9, 12, 16]) { + t?.stop() + t = await tui([], { width: 80, height }) + put(fake("srv", { toolCount: 40 })) + t.app.mcp.tools() + await t.input.typeText("/mcp srv") + t.input.pressEnter() + expect(await t.until("MCP · srv")).toBe(true) + const lines = t.frame().split("\n") + // The whole box is on the screen: its title row and its bottom border, and the key hints. + expect(lines.some((l) => l.includes("╭─ MCP · srv"))).toBe(true) + expect(lines.some((l) => l.includes("╰"))).toBe(true) + expect(t.frame()).toContain("esc back") + expect(lines.filter((l, i) => i < lines.length - 1 || l.trim()).length).toBeLessThanOrEqual(height) + // Nothing of the box is cut off: its top and bottom borders are both there, in that order. + expect(lines.findIndex((l) => l.includes("╭─ MCP · srv"))).toBeLessThan(lines.findLastIndex((l) => l.includes("╰"))) + } + t?.stop() + t = await tui([], { width: 100, height: 36 }) + put(fake("srv", { toolCount: 5 })) + t.app.mcp.tools() + await t.input.typeText("/mcp srv") + t.input.pressEnter() + expect(await t.until("MCP · srv")).toBe(true) + // On an action (nothing more to say) and then on a tool (a description under the list): the + // rows of the list stay where they are. + const rowOf = (text: string) => t!.frame().split("\n").findIndex((l) => l.includes(text)) + const before = [rowOf("Reconnect"), rowOf("tool_0"), rowOf("esc back")] + for (let i = 0; i < 2; i++) t.input.pressArrow("down") + await t.settle() + expect(t.frame()).toContain("Does thing 0.") + expect([rowOf("Reconnect"), rowOf("tool_0"), rowOf("esc back")]).toEqual(before) +}) + +test("a custom command named like a built-in is said at start, and reached with /command", async () => { + mkdirSync(join(paths.config, "commands"), { recursive: true }) + const file = join(paths.config, "commands", "status.md") + writeFileSync(file, "---\ndescription: my own status\n---\nSay how the build is doing. $ARGUMENTS\n") + try { + const { delta, usage } = await import("../fake-provider.ts") + t = await tui([{ chunks: [delta({ content: "Green." }), usage(10, 2)] }], { width: 130, height: 30 }) + await t.settle(150) + const said = noticesOf().filter((x) => x.includes("/status")) + expect(said.length).toBe(1) + expect(said[0]).toContain("has the name of a built-in command") + expect(said[0]).toContain("/command status") + await t.input.typeText("/command status today") + t.input.pressEnter() + expect(await t.until("Green.")).toBe(true) + expect(JSON.stringify(t.fake.requests[0].messages.at(-1))).toContain("Say how the build is doing. today") + // Over the link the same way; and /skill has a way too. + expect(expandSlash(t.app, "/command status now")).toMatchObject({ kind: "prompt", name: "command" }) + expect(expandSlash(t.app, "/command nosuch")).toMatchObject({ kind: "message", error: true }) + expect(expandSlash(t.app, "/skill nosuchskill do it")).toMatchObject({ kind: "message", error: true, text: 'no skill "nosuchskill"' }) + expect(expandSlash(t.app, "/status")).toMatchObject({ kind: "message", name: "status" }) // the built-in still wins + } finally { + const { rmSync } = await import("node:fs") + rmSync(file, { force: true }) + } +})