/help, /permissions, /status and /agents as menus on the shared one
ci / check (push) Canceled after 0s

/help: every command under a heading, found by typing, run or put in the
box. /permissions (new): the rules in force by where they were made;
change, add, remove. /status (new): server, model, session, project, MCP
and terminal on one screen, what needs attention marked, enter opens what
changes it. /agents: a menu. Each has its text for where there is no menu
(session/report.ts): over the link, and lembas run now prints a
message-kind command instead of sending it to the model.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-11-12 17:31:40 +00:00
1 parent 6887f9e414
commit dd9cb9135f
8 files changed
+532 -5

No files matched your search

+16
View File
@@ -20,6 +20,22 @@ All notable changes to LLeMbas CLI. The format follows
- **Menus have sections, state marks, a line about the highlighted row, Esc-goes-back, PgUp/PgDn
and Home/End, and say where the cursor is in a long list** — every picker is the one component.
- **`/help` is a menu**: every command under a heading (this session, the model, the project,
what it knows and can use, account and settings, look), found by typing a word of its name or
of what it does; Enter runs it, or puts it in the box when it needs words. The keys are in it
too.
- **`/permissions`** (new): the permission rules in force, by where each was made — this session,
the project, your config, built in. Enter changes one (asks / always allowed / denied), the
first row adds one (`bash git status* allow`), and a rule of this session can be removed.
- **`/status`** (new): the server and login, the model, the session, the project and whether it
is trusted, the MCP servers, and this terminal — how copying and pasting images work here —
on one screen. What needs attention is marked; Enter on a row opens what changes it.
- **`/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 <name>`.
### Changed
- **An MCP server that connects no longer says so with a warning sign at every start.** Nothing is
+8 -1
View File
@@ -21,6 +21,7 @@ import { SUBAGENTS } from "../team/subagents.ts"
import { progressLine } from "./progress.ts"
import { fillPrompt } from "../prompt/fill.ts"
import { mcpText } from "../mcp/text.ts"
import { permissionsText, statusText } from "./report.ts"
export type CommandKind = "custom" | "skill" | "builtin"
@@ -39,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",
"icons", "trust", "reload", "restart", "quit", "exit", "q", "team", "rename", "schedule", "schedules", "search", "permissions", "status",
] as const
/** The built-ins that work without a screen of their own. Descriptions as the TUI's (a test). */
@@ -52,6 +53,8 @@ export const SHARED_BUILTINS: { name: string; description: string; hint?: string
{ name: "init", description: "make or update the project's AGENTS.md from what the repository says", hint: "what to focus on" },
{ name: "continue", description: "carry on — after esc stopped it, or when it should keep going (ctrl+g)" },
{ 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: "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 <min> <max> | stop <name> | findings <name>" },
]
@@ -266,6 +269,10 @@ export function expandSlash(app: App, text: string): Expanded | undefined {
return { kind: "message", name, text: agentsText(app, arg) }
case "team":
return { kind: "message", name, text: teamText(app, arg) }
case "permissions":
return { kind: "message", name, text: permissionsText(app) }
case "status":
return { 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.
+101
View File
@@ -0,0 +1,101 @@
// What two of the menus say as plain text, where there is no menu (`lembas run`, a prompt over
// the link): the permission rules in force, and the state of this installation in one place.
import type { App } from "../app.ts"
import type { Rule } from "../permission/evaluate.ts"
import { VERSION } from "../version.ts"
import { sourceOf, stateLine } from "../mcp/text.ts"
export type RuleFrom = "session" | "project" | "user" | "builtin"
export const RULE_FROM: Record<RuleFrom, string> = { session: "This session", project: "This project (.agent/config.yaml)", user: "Your config", builtin: "Built in" }
/** Where a rule was made. */
export function ruleFrom(rule: Rule, own: readonly Rule[]): RuleFrom {
if (own.includes(rule)) return "session"
return rule.source === "project" ? "project" : rule.source === "global" ? "user" : "builtin"
}
/** Every rule in force, the most specific place first: this session's, the project's, the
* person's own, the built-in ones. A later rule of the same permission and pattern wins, so only
* the one that speaks is listed. */
export function rulesInForce(app: App): { rule: Rule; from: RuleFrom }[] {
const own = app.engine.ownRules
const seen = new Set<string>()
const out: { rule: Rule; from: RuleFrom }[] = []
for (const rule of [...app.engine.rules].reverse()) {
const key = `${rule.permission}\u0000${rule.pattern}`
if (seen.has(key)) continue
seen.add(key)
out.push({ rule, from: ruleFrom(rule, own) })
}
const order: RuleFrom[] = ["session", "project", "user", "builtin"]
return out.sort((a, b) => order.indexOf(a.from) - order.indexOf(b.from) || a.rule.permission.localeCompare(b.rule.permission) || a.rule.pattern.localeCompare(b.rule.pattern))
}
export const ruleLine = (r: Rule) => `${r.permission}${r.pattern === "*" ? "" : ` ${r.pattern}`}`
export function permissionsText(app: App): string {
const rules = rulesInForce(app)
const lines = [`Mode: ${app.engine.mode}. A call no rule speaks of is asked about or allowed by its kind and the mode.`]
let from: RuleFrom | undefined
for (const { rule, from: f } of rules) {
if (f !== from) lines.push("", `${RULE_FROM[f]}:`)
from = f
lines.push(` ${rule.action.padEnd(5)} ${ruleLine(rule)}`)
}
return lines.join("\n")
}
/** One fact of the status screen: what it is, what it says, whether it needs attention, and the
* command that changes it. */
export interface StatusRow {
label: string
value: string
attention?: boolean
command?: string
section: string
}
export function statusRows(app: App): StatusRow[] {
const e = app.engine
const conns = Object.entries(app.loaded.connections)
const servers = [...app.mcp.servers.values()]
const troubled = servers.filter((s) => s.status === "failed" || s.status === "needs_auth")
const rows: StatusRow[] = [
{ section: "This program", label: "version", value: VERSION },
{
section: "The LLeMbas server",
label: "signed in to",
value: conns.length ? conns.map(([name, c]) => `${name}${c.webui?.url ? ` (${c.webui.url})` : ""}`).join(", ") : "nothing — /login <address>",
attention: !conns.length,
command: "login",
},
{ section: "The LLeMbas server", label: "model", value: `${e.model.ref}${e.model.spec.context ? ` · context ${e.model.spec.context}` : ""}`, command: "model" },
{ section: "This session", label: "mode", value: e.mode, command: "mode" },
{ section: "This session", label: "session", value: e.sessionId ? `${e.sessionId}${app.store?.session(e.sessionId)?.title ? ` — ${app.store.session(e.sessionId)!.title}` : ""}` : "not kept", command: "sessions" },
{ section: "This project", label: "folder", value: app.project.root },
{ section: "This project", label: "trusted", value: app.trusted ? "yes: its .agent config, commands and servers are used" : "no: its .agent config is ignored — /trust", attention: !app.trusted, command: app.trusted ? undefined : "trust" },
{
section: "MCP servers",
label: "servers",
value: servers.length ? `${servers.filter((s) => s.status === "connected").length} of ${servers.length} connected${troubled.length ? ` — ${troubled.map((s) => s.name).join(", ")} not` : ""}` : "none configured",
attention: troubled.length > 0,
command: "mcp",
},
...troubled.map((s) => ({ section: "MCP servers", label: s.name, value: `${stateLine(s)} (${sourceOf(s) === "library" ? "the server's library" : sourceOf(s)})`, attention: true, command: `mcp ${s.name}` })),
]
return rows
}
export function statusText(app: App): string {
const rows = statusRows(app)
const width = Math.max(...rows.map((r) => r.label.length))
const out: string[] = []
let section = ""
for (const r of rows) {
if (r.section !== section) out.push(...(out.length ? [""] : []), `${r.section}:`)
section = r.section
out.push(` ${r.label.padEnd(width)} ${r.value}${r.attention ? " (needs attention)" : ""}`)
}
return out.join("\n")
}
+18 -2
View File
@@ -31,6 +31,7 @@ import { keyMatcher } from "../voice/index.ts"
import { PLAYER_NAMES, playerFor, recorderFor } from "../voice/audio.ts"
import { duration } from "../duration.ts"
import { openMcpMenu, openMcpServer, runAction } from "./mcpmenu.ts"
import { openAgents, openHelp, openPermissions, openStatus } from "./menus.ts"
import type { Job, JobInfo } from "../jobs/registry.ts"
export interface CommandCtx extends Ctx {
@@ -170,6 +171,7 @@ export const COMMANDS: Command[] = [
` model the session's, or one you name${a.model ? ` (its own model: ${a.model} is not used)` : ""} · mode ${a.mode ?? "the session's"} · tools ${a.tools?.join(", ") ?? "all a subagent may have"}${a.isolation ? " · own worktree" : ""}`,
].join("\n")
if (named) return c.view.info(describe(named))
if (!first) return openAgents(c)
c.view.info(
[
...list.map(describe),
@@ -189,8 +191,22 @@ export const COMMANDS: Command[] = [
name: "help",
description: "commands and keys",
run(c) {
const lines = COMMANDS.map((cmd) => `/${cmd.name}${cmd.args ? " " + cmd.args : ""} — ${cmd.description}`)
c.view.info([...lines, "", ...HELP_KEYS].join("\n"))
openHelp(c, COMMANDS, HELP_KEYS, (cmd) => void cmd.run(c, ""))
},
},
{
name: "permissions",
description: "the permission rules in force — this session's, the project's, yours, the built-in ones; change or add one",
run: (c) => openPermissions(c),
},
{
name: "status",
description: "everything in one place: the server and login, the session, the project, the MCP servers, this terminal",
run(c) {
openStatus(c, (line) => {
const [name = "", ...rest] = line.split(" ")
void findCommand(name)?.run(c, rest.join(" "))
})
},
},
{
+1 -1
View File
@@ -149,7 +149,7 @@ export function Dialog(p: { spec: DialogSpec; close: () => void }) {
return out
})
// What the screen leaves for the list: less the body above it and the detail below.
const visible = () => Math.max(3, Math.min(16, dims().height - 10 - Math.min(body().length, BODY_ROWS) - (detail().length ? DETAIL_ROWS + 1 : 0)))
const visible = () => Math.max(3, Math.min(22, dims().height - 10 - Math.min(body().length, BODY_ROWS) - (detail().length ? DETAIL_ROWS + 1 : 0)))
const offset = () => {
const at = rows().findIndex((r) => "option" in r && r.index === sel())
const first = Math.max(0, Math.min(at - Math.floor(visible() / 2), rows().length - visible()))
+208
View File
@@ -0,0 +1,208 @@
// Menus that used to be dumps of text, or did not exist: /help, /permissions, /status, /agents.
// All on the shared menu (components/dialog.tsx). What each says without a menu is in
// session/report.ts and session/commands.ts.
import { join } from "node:path"
import { paths } from "../config/paths.ts"
import type { Rule } from "../permission/evaluate.ts"
import { RULE_FROM, ruleFrom, ruleLine, rulesInForce, statusRows, type StatusRow } from "../session/report.ts"
import type { Command, CommandCtx } from "./commands.ts"
import type { Option } from "./components/dialog.tsx"
import { hostCopier, isRemote } from "./clipboard.ts"
import { kittyClipboardLikely } from "./kitty-clipboard.ts"
import type { Mark } from "./notices.ts"
// ---- /help ----
/** Where each command stands in /help. A command not named here is under "More". */
const GROUPS: [string, string[]][] = [
["This session", ["new", "sessions", "search", "rename", "delete", "continue", "undo", "redo", "compact", "context", "copy", "remote"]],
["Model and how it works", ["model", "effort", "mode", "permissions", "plan", "plans", "personality", "team", "agents", "jobs"]],
["The project", ["diff", "commit", "branch", "checkpoint", "checkpoints", "review", "init", "changelog", "release", "tasks", "decisions", "decide", "prototype", "trust"]],
["What it knows and can use", ["memory", "skills", "skill", "kb", "mcp", "schedule"]],
["Account and settings", ["status", "login", "logout", "usage", "settings", "voice", "speak"]],
["Look", ["theme", "icons", "terminal"]],
]
const KEY = "\u0000key:"
/** /help: every command under a heading, found by typing; enter runs one, or puts it in the box
* when it takes words. The keys are its last section. */
export function openHelp(c: CommandCtx, commands: Command[], keys: string[], run: (cmd: Command) => void) {
const placed = new Set(GROUPS.flatMap(([, names]) => names))
const groups: [string, string[]][] = [...GROUPS, ["More", commands.filter((cmd) => !placed.has(cmd.name)).map((cmd) => cmd.name)]]
const options: Option[] = groups.flatMap(([section, names]) =>
names.flatMap((name) => {
const cmd = commands.find((x) => x.name === name)
if (!cmd) return []
const also = cmd.aliases?.length ? ` (also /${cmd.aliases.join(", /")})` : ""
return [{ label: `/${cmd.name}`, value: cmd.name, description: cmd.description, section, detail: `/${cmd.name}${cmd.args ? ` ${cmd.args}` : ""}${also}\n${cmd.description}` }]
}),
)
// A key line is "keys what they do · keys what they do": one row each, so they can be found too.
const keyRows: Option[] = keys.flatMap((line) => line.split(" · ")).map((k, i) => ({ label: k, value: `${KEY}${i}`, section: "Keys" }))
c.openDialog({
title: "Help — commands and keys",
options: [...options, ...keyRows],
filter: true,
width: 84,
hint: "type to find · ↑↓ move · enter run (or put in the box) · esc close",
onSelect: (v) => {
if (v.startsWith(KEY)) return
const cmd = commands.find((x) => x.name === v)!
// A command that takes words goes into the box to be finished; one that takes none runs.
if (cmd.args && !cmd.args.startsWith("[")) return c.setInput(`/${cmd.name} `)
run(cmd)
},
})
}
// ---- /permissions ----
const ACTION_MARK: Record<Rule["action"], Mark> = { allow: "on", ask: "off", deny: "failed" }
const ACTION_WORDS: Record<Rule["action"], string> = { allow: "always allowed", ask: "asks", deny: "denied" }
const ADD = "\u0000add"
/** A rule as typed: `<permission> [pattern] <allow|ask|deny>` — `bash git status* allow`,
* `mcp__files__read allow`. The pattern is everything between; none is `*`. */
export function parseRule(text: string): Pick<Rule, "permission" | "pattern" | "action"> | string {
const words = text.trim().split(/\s+/).filter(Boolean)
const action = words.at(-1)
if (words.length < 2 || (action !== "allow" && action !== "ask" && action !== "deny")) return "a rule is: <permission> [pattern] <allow|ask|deny> — for example: bash git status* allow"
return { permission: words[0]!, pattern: words.slice(1, -1).join(" ") || "*", action }
}
function applyRule(c: CommandCtx, rule: Pick<Rule, "permission" | "pattern" | "action">) {
const r = c.app.engine.setRule(rule)
if ("refused" in r) return c.view.info(`${ruleLine(rule as Rule)}: your own config says ${r.refused.action} — change it there (~/.config/lembas/config.yaml, permission:); a rule made here cannot loosen it`, "warn")
c.flash(`${ruleLine(rule as Rule)}: ${ACTION_WORDS[rule.action]}${r.saved === "project" ? " — saved to the project" : " for this session"}`)
}
/** /permissions: the rules in force by where they were made; enter changes one, the first row adds one. */
export function openPermissions(c: CommandCtx, select?: string) {
const rules = rulesInForce(c.app)
const key = (r: Rule) => `${r.permission}\u0000${r.pattern}`
const where = c.app.trusted ? "this session, and saved to this project's .agent/config.yaml" : "this session only (the project is not trusted)"
c.openDialog({
title: `Permissions — mode ${c.app.engine.mode}`,
body: [`A call no rule speaks of is asked about or allowed by its kind and the mode (/mode). A change made here holds for ${where}.`],
options: [
{ label: "Add a rule…", value: ADD, description: "<permission> [pattern] <allow|ask|deny>" },
...rules.map(({ rule, from }) => ({ label: ruleLine(rule), value: key(rule), mark: ACTION_MARK[rule.action], description: ACTION_WORDS[rule.action], section: RULE_FROM[from], detail: `${rule.permission} · pattern ${rule.pattern} · ${rule.action}${rule.learned ? " · from an \"always\" answer" : ""}` })),
],
filter: true,
width: 84,
...(select ? { select } : {}),
hint: "type to find · ↑↓ move · enter change · esc close",
onSelect: (v) => {
if (v === ADD)
return c.openDialog({
title: "Add a permission rule",
options: [],
empty: "Type the rule and press enter: <permission> [pattern] <allow|ask|deny> — bash git status* allow · edit src/** ask · mcp__files__write deny",
custom: {
label: "add",
onSubmit: (text) => {
const rule = parseRule(text)
if (typeof rule === "string") c.view.info(rule, "warn")
else applyRule(c, rule)
openPermissions(c, typeof rule === "string" ? undefined : key(rule as Rule))
},
},
onBack: () => openPermissions(c),
onSelect: () => {},
})
const hit = rules.find((r) => key(r.rule) === v)
if (!hit) return
const own = ruleFrom(hit.rule, c.app.engine.ownRules) === "session"
c.openDialog({
title: ruleLine(hit.rule),
body: [`${RULE_FROM[hit.from]} says: ${ACTION_WORDS[hit.rule.action]}. A change holds for ${where}.`],
options: [
{ label: "Ask each time", value: "ask", current: hit.rule.action === "ask" },
{ label: "Always allow", value: "allow", current: hit.rule.action === "allow" },
{ label: "Deny", value: "deny", current: hit.rule.action === "deny" },
...(own ? [{ label: "Remove this session's rule", value: "remove", description: "what stood before it holds again" }] : []),
],
filter: false,
onBack: () => openPermissions(c, v),
onSelect: (action) => {
if (action === "remove") {
c.app.engine.dropSessionRule(hit.rule.permission, hit.rule.pattern)
c.flash(`${ruleLine(hit.rule)}: this session's rule is removed`)
} else applyRule(c, { permission: hit.rule.permission, pattern: hit.rule.pattern, action: action as Rule["action"] })
openPermissions(c, v)
},
})
},
})
}
// ---- /status ----
/** What only the terminal knows: the terminal itself, and how copying and pasting images go. */
export function terminalRows(c: CommandCtx): StatusRow[] {
const caps = c.renderer.capabilities as { terminal?: { name?: string; version?: string }; remote?: boolean; osc52_support?: string } | null
const remote = isRemote(c.renderer as never)
const name = caps?.terminal?.name ? `${caps.terminal.name}${caps.terminal.version ? ` ${caps.terminal.version}` : ""}` : "did not say"
const copy = caps?.osc52_support === "supported" ? "through the terminal (OSC 52)" : !remote && hostCopier() ? "this machine's clipboard" : caps?.osc52_support === "unsupported" ? "not possible here — hold Shift and select with the terminal" : "through the terminal, if it takes OSC 52 (it did not say)"
const images = !remote
? "ctrl+v reads this machine's clipboard"
: process.env.DISPLAY
? "ctrl+v reads the forwarded X clipboard (ssh -X)"
: c.app.loaded.config.kitty_clipboard === true && kittyClipboardLikely()
? "ctrl+v asks the terminal for its clipboard (kitty)"
: "over SSH: paste a data URL, or use @path"
return [
{ section: "This terminal", label: "terminal", value: `${name}${remote ? " · over SSH" : ""}`, command: "terminal" },
{ section: "This terminal", label: "copying", value: copy, attention: caps?.osc52_support === "unsupported" && (remote || !hostCopier()) },
{ section: "This terminal", label: "pasting images", value: images, command: "settings" },
]
}
/** /status: the server, the session, the project, the MCP servers and the terminal on one screen.
* A row that needs attention is marked; enter on a row opens what changes it. */
export function openStatus(c: CommandCtx, run: (line: string) => void) {
const share = c.share?.status()
const rows: StatusRow[] = [...statusRows(c.app), ...(share ? [{ section: "This session", label: "web UI", value: share, command: "remote" } satisfies StatusRow] : []), ...terminalRows(c)]
// Sections in the order they first appear, each one's rows together.
const sections = [...new Set(rows.map((r) => r.section))]
const ordered = sections.flatMap((s) => rows.filter((r) => r.section === s))
const width = Math.max(...ordered.map((r) => r.label.length))
c.openDialog({
title: "Status",
options: ordered.map((r, i) => ({ label: `${r.label.padEnd(width)} ${r.value}`, value: String(i), section: r.section, mark: r.attention ? "attention" : "on", detail: `${r.value}${r.command ? `\nenter: /${r.command}` : ""}` })),
filter: false,
width: 96,
hint: "↑↓ move · enter open what changes it · esc close",
onSelect: (v) => {
const r = ordered[Number(v)]
if (r?.command) run(r.command)
},
})
}
// ---- /agents ----
const NEW_AGENT = "\u0000new"
/** /agents: the subagents the model may hand work to; enter puts `/agents <name> ` in the box, to
* be finished with the task. */
export function openAgents(c: CommandCtx) {
const list = c.app.agents
c.openDialog({
title: `Subagents — ${list.length} the model may hand work to`,
body: ["The model hands work to one through its task tool when that helps; enter a name to hand one a task yourself."],
options: [
...list.map((a) => ({
label: a.name,
value: a.name,
description: a.description,
section: a.source === "builtin" ? "Built in" : a.source === "project" ? "This project (.agent/agents)" : "Your own",
detail: `mode ${a.mode ?? "the session's"} · tools ${a.tools?.join(", ") ?? "all a subagent may have"}\n${a.description}`,
})),
{ label: "New subagent…", value: NEW_AGENT, description: `writes a starter file under ${join(paths.config, "agents")} to edit`, section: "Make one" },
],
empty: "No subagents.",
hint: "↑↓ move · enter hand it a task · esc close",
onSelect: (v) => c.setInput(v === NEW_AGENT ? "/agents new " : `/agents ${v} `),
})
}
+8 -1
View File
@@ -912,8 +912,15 @@ test("/agents lists the subagents; /agents new writes a starter; /agents <name>
t = await tui([{ chunks: [delta({ content: "Handing it over." }, "stop")] }])
await t.input.typeText("/agents")
t.input.pressEnter()
// A menu (tests/tui/menus.test.tsx); the description of one is still text.
expect(await t.until("Subagents — ")).toBe(true)
expect(t.frame()).toContain("explore")
expect(t.frame()).toContain("general")
t.input.pressEscape()
await t.settle()
await t.input.typeText("/agents explore")
t.input.pressEnter()
expect(await t.until("explore (builtin)")).toBe(true)
expect(t.frame()).toContain("general (builtin)")
const name = `scout${Date.now() % 100000}`
await t.input.typeText(`/agents new ${name}`)
t.input.pressEnter()
+172
View File
@@ -0,0 +1,172 @@
// The menus built on the shared one: /help, /permissions, /status, /agents — and what the same
// commands say where there is no menu.
import { afterEach, expect, test } from "bun:test"
import { TextareaRenderable } from "@opentui/core"
import { expandSlash } from "../../src/session/commands.ts"
import { COMMANDS } from "../../src/tui/commands.ts"
import { parseRule } from "../../src/tui/menus.ts"
import { tui } from "./harness.tsx"
let t: Awaited<ReturnType<typeof tui>> | undefined
afterEach(() => t?.stop())
const box = (n: any): TextareaRenderable => (n instanceof TextareaRenderable ? n : n.getChildren?.().map(box).find(Boolean))
const widest = () => Math.max(...t!.frame().split("\n").map((l) => l.trimEnd().length))
const text = (cmd: string) => (expandSlash(t!.app, cmd) as { text: string }).text
test("/help is a menu: commands under headings, found by typing; enter runs one, or puts one that needs words in the box", async () => {
t = await tui([], { width: 110, height: 36 })
const a = box(t.setup.renderer.root)
await t.input.typeText("/help")
t.input.pressEnter()
expect(await t.until("Help — commands and keys")).toBe(true)
let f = t.frame()
expect(f).toContain("This session")
expect(f).toContain("/new")
expect(f).toContain("type to find")
expect(f).not.toContain("⚠")
// Typing finds a command by what it does, not only by its name.
for (const ch of "permission rules") t.input.pressKey(ch)
await t.settle()
f = t.frame()
expect(f).toContain("/permissions")
expect(f).not.toContain("/theme")
t.input.pressEnter()
expect(await t.until("Permissions — mode")).toBe(true)
t.input.pressEscape()
await t.settle()
// One that needs words goes into the box to be finished.
await t.input.typeText("/help")
t.input.pressEnter()
expect(await t.until("Help — commands and keys")).toBe(true)
for (const ch of "/rename") t.input.pressKey(ch)
await t.settle()
t.input.pressEnter()
await t.settle()
expect(a.plainText).toBe("/rename ")
// The keys are rows too.
a.setText("")
await t.input.typeText("/help")
t.input.pressEnter()
expect(await t.until("Help — commands and keys")).toBe(true)
for (const ch of "ctrl+g") t.input.pressKey(ch)
await t.settle()
expect(t.frame()).toContain("Keys")
expect(t.frame()).toContain("ctrl+g continue")
})
test("every command has a place in /help", async () => {
t = await tui([], { width: 110, height: 60 })
await t.input.typeText("/help")
t.input.pressEnter()
expect(await t.until("Help — commands and keys")).toBe(true)
const missing: string[] = []
for (const cmd of COMMANDS) {
for (const ch of `/${cmd.name}`) t.input.pressKey(ch)
await t.settle(12)
if (!new RegExp(`/${cmd.name}(\\s|$)`, "m").test(t.frame())) missing.push(cmd.name)
for (let i = 0; i <= cmd.name.length; i++) t.input.pressBackspace()
await t.settle(8)
}
expect(missing).toEqual([])
}, 40_000)
test("/permissions: the rules by where they were made; enter changes one; a rule can be added and this session's removed", async () => {
t = await tui([], { width: 110, height: 36 }, "permission:\n bash:\n 'git push *': deny\n")
await t.input.typeText("/permissions")
t.input.pressEnter()
expect(await t.until("Permissions — mode manual")).toBe(true)
let f = t.frame()
expect(f).toContain("Add a rule…")
expect(f).toContain("Your config")
expect(f).toMatch(/✗ bash git push \* {2}denied/)
expect(f).toContain("this session only")
expect(f).toContain("not trusted")
// Add one.
t.input.pressEnter()
expect(await t.until("Add a permission rule")).toBe(true)
expect(t.frame()).toContain("Type the rule and press enter")
for (const ch of "bash git status* allow") t.input.pressKey(ch)
await t.settle()
t.input.pressEnter()
expect(await t.until("Permissions — mode manual")).toBe(true)
expect(t.app.engine.ruleFor("bash", "git status*")).toBe("allow")
f = t.frame()
expect(f).toContain("This session")
expect(f).toMatch(/● bash git status\* {2}always allowed/)
// The menu comes back on the rule just made: enter opens it, and it can be removed.
t.input.pressEnter()
expect(await t.until("Remove this session's rule")).toBe(true)
for (let i = 0; i < 3; i++) t.input.pressArrow("down")
t.input.pressEnter()
expect(await t.until("Permissions — mode manual")).toBe(true)
expect(t.app.engine.ruleFor("bash", "git status*")).not.toBe("allow")
t.input.pressEscape()
await t.settle()
// The person's own deny is not loosened from here: said, and nothing changes.
expect(t.app.engine.setRule({ permission: "bash", pattern: "git push *", action: "allow" })).toMatchObject({ refused: { action: "deny" } })
expect(parseRule("bash git status* allow")).toEqual({ permission: "bash", pattern: "git status*", action: "allow" })
expect(parseRule("mcp__files__read deny")).toEqual({ permission: "mcp__files__read", pattern: "*", action: "deny" })
expect(parseRule("edit src/my file.ts ask")).toEqual({ permission: "edit", pattern: "src/my file.ts", action: "ask" })
expect(typeof parseRule("bash")).toBe("string")
expect(typeof parseRule("bash git status* maybe")).toBe("string")
})
test("/status: one screen; what needs attention is marked; enter opens what changes it", async () => {
t = await tui([], { width: 110, height: 40 })
await t.input.typeText("/status")
t.input.pressEnter()
expect(await t.until("Status")).toBe(true)
const f = t.frame()
for (const s of ["This program", "The LLeMbas server", "This session", "This project", "MCP servers", "This terminal"]) expect(f).toContain(s)
expect(f).toMatch(/● version +2\./)
expect(f).toMatch(/● model +fake\/coder/)
// The test project is not trusted: that is the one row marked.
expect(f).toMatch(/⚠ trusted +no: its \.agent config is ignored/)
expect(f).toContain("pasting images")
// Enter on the model row opens the model picker.
for (let i = 0; i < 2; i++) t.input.pressArrow("down")
t.input.pressEnter()
expect(await t.until("fake/other")).toBe(true)
})
test("/agents is a menu; enter puts the subagent's name in the box to hand it a task", async () => {
t = await tui([], { width: 110, height: 36 })
const a = box(t.setup.renderer.root)
await t.input.typeText("/agents")
t.input.pressEnter()
expect(await t.until("Subagents — ")).toBe(true)
expect(t.frame()).toContain("Built in")
expect(t.frame()).toContain("New subagent…")
const first = t.app.agents[0]!.name
t.input.pressEnter()
await t.settle()
expect(a.plainText).toBe(`/agents ${first} `)
})
test("the menus fit a 60-column terminal", async () => {
t = await tui([], { width: 60, height: 24 }, "permission:\n bash:\n 'git push --force-with-lease origin some-very-long-branch-name-indeed *': deny\n")
for (const cmd of ["/help", "/permissions", "/status", "/agents", "/mcp", "/settings"]) {
await t.input.typeText(cmd)
t.input.pressEnter()
await t.settle(120)
expect(t.frame()).toContain("esc close")
expect(widest()).toBeLessThanOrEqual(60)
t.input.pressEscape()
await t.settle(60)
}
})
test("without a menu the same commands are plain text: /permissions and /status over the link and in lembas run", async () => {
t = await tui([], undefined, "permission:\n bash:\n 'git push *': deny\n")
t.app.engine.setRule({ permission: "edit", pattern: "docs/*", action: "allow" })
const p = text("/permissions")
expect(p).toStartWith("Mode: manual.")
expect(p).toContain("This session:\n allow edit docs/*")
expect(p).toContain("Your config:\n deny bash git push *")
expect(p).toContain("Built in:")
const s = text("/status")
expect(s).toContain("This program:\n version")
expect(s).toMatch(/model +fake\/coder/)
expect(s).toMatch(/trusted +no: .*\(needs attention\)/)
expect(s).toMatch(/servers +none configured/)
})