diff --git a/frontend/packages/swarm-ui/src/agent/terminal/AgentInputForm.css b/frontend/packages/swarm-ui/src/agent/terminal/AgentInputForm.css index 74efb86eb..8ed05e658 100644 --- a/frontend/packages/swarm-ui/src/agent/terminal/AgentInputForm.css +++ b/frontend/packages/swarm-ui/src/agent/terminal/AgentInputForm.css @@ -1,5 +1,5 @@ /* — one row: the text field takes the width, the send - button sits at its baseline. */ + button sits at its baseline. The field is the anchor of the command menu. */ .ui-agent-input { margin-block-start: 0.5rem; } @@ -8,6 +8,7 @@ align-items: flex-end; gap: 0.5em; } -.ui-agent-input-form > :first-child { +.ui-agent-input-field { + position: relative; flex: 1; } diff --git a/frontend/packages/swarm-ui/src/agent/terminal/AgentInputForm.tsx b/frontend/packages/swarm-ui/src/agent/terminal/AgentInputForm.tsx index 020ba1ce1..91be52a60 100644 --- a/frontend/packages/swarm-ui/src/agent/terminal/AgentInputForm.tsx +++ b/frontend/packages/swarm-ui/src/agent/terminal/AgentInputForm.tsx @@ -3,16 +3,47 @@ // message, 503 when it is not listening, problem+json otherwise. The agent // sees it as an inbox turn from the logged-in user (the controller takes the // sender from the gateway, not from this request). -import { useState } from "preact/hooks"; +// +// While the text is one `/word`, a menu of the agent's commands and skills +// opens above the box (`CommandMenu`): the arrow keys move, Tab or Enter take +// the selected one into the box, Esc closes it. The list is the agent's own +// (`useAgentCommands`); an agent without one gets a plain box. +import { useEffect, useState } from "preact/hooks"; import { ApiErrorPanel } from "@hive/shared/api-error-panel.js"; import { TextField } from "../../ui/text-field/TextField.js"; import { Button } from "../../ui/button/Button.js"; import { useSubmit } from "../../ui/submit/useSubmit.js"; +import { CommandMenu } from "./CommandMenu.js"; +import { + completion, + enterSends, + matchCommands, + menuQuery, + moveSelection, + type AgentCommand, +} from "./command-menu.js"; +import { useAgentCommands } from "./useAgentCommands.js"; import "./AgentInputForm.css"; export function AgentInputForm({ agentName }: { agentName: string }) { const [body, setBody] = useState(""); + const [selected, setSelected] = useState(0); + const [closed, setClosed] = useState(false); const { state, submitting, run } = useSubmit(); + const commands = useAgentCommands(agentName); + + const query = menuQuery(body); + const matches = + query === null || closed ? [] : matchCommands(commands, query); + const open = matches.length > 0; + const menuId = `agent-input-${agentName}-commands`; + + // A new query starts at the top again, and Esc only lasts until the text + // changes. + useEffect(() => { + setSelected(0); + setClosed(false); + }, [body]); function submit(e: Event) { e.preventDefault(); @@ -27,18 +58,60 @@ export function AgentInputForm({ agentName }: { agentName: string }) { ); } + function take(command: AgentCommand) { + setBody(completion(command)); + } + + function onKeyDown(e: KeyboardEvent) { + if (!open) return; + const current = matches[Math.min(selected, matches.length - 1)]; + if (e.key === "ArrowDown" || e.key === "ArrowUp") { + e.preventDefault(); + setSelected(moveSelection(selected, matches.length, e.key)); + } else if ( + e.key === "Tab" || + (e.key === "Enter" && !enterSends(body, current)) + ) { + e.preventDefault(); + take(current); + } else if (e.key === "Escape") { + e.preventDefault(); + setClosed(true); + } + } + return (
- +
+ {open && ( + + )} + +
diff --git a/frontend/packages/swarm-ui/src/agent/terminal/CommandMenu.css b/frontend/packages/swarm-ui/src/agent/terminal/CommandMenu.css new file mode 100644 index 000000000..cfffa742f --- /dev/null +++ b/frontend/packages/swarm-ui/src/agent/terminal/CommandMenu.css @@ -0,0 +1,91 @@ +/* — a card floating above the message box, in the panel's own + border and elevation, with the selected row lit in the accent. */ +.ui-command-menu { + position: absolute; + inset-inline: 0; + bottom: calc(100% + 0.4em); + z-index: 20; + overflow: hidden; + border: 1px solid var(--border); + border-radius: 0.5em; + background: var(--bg-elev); + box-shadow: + 0 0.4em 1.2em rgba(0, 0, 0, 0.45), + 0 0 0 1px color-mix(in srgb, var(--purple) 18%, transparent); +} + +.ui-command-menu-list { + max-height: 16em; + margin: 0; + padding: 0.25em; + overflow-y: auto; + list-style: none; +} + +.ui-command-menu-item { + display: grid; + grid-template-columns: auto auto minmax(0, 1fr); + align-items: baseline; + gap: 0.75em; + padding: 0.4em 0.6em; + border-radius: 0.35em; + cursor: pointer; +} + +.ui-command-menu-item-selected { + background: color-mix(in srgb, var(--purple) 22%, transparent); + box-shadow: inset 2px 0 0 var(--purple); +} + +.ui-command-menu-name { + font-family: var(--mono, monospace); + color: var(--fg); + white-space: nowrap; +} + +.ui-command-menu-name mark { + background: none; + color: var(--purple); + text-shadow: 0 0 8px color-mix(in srgb, var(--purple) 55%, transparent); +} + +.ui-command-menu-kind { + padding: 0 0.5em; + border: 1px solid var(--border); + border-radius: 1em; + color: var(--muted); + font-size: 0.75em; + white-space: nowrap; +} + +.ui-command-menu-kind-command { + border-color: color-mix(in srgb, var(--green) 45%, transparent); + color: var(--green); +} + +.ui-command-menu-kind-skill { + border-color: color-mix(in srgb, var(--blue) 45%, transparent); + color: var(--blue); +} + +.ui-command-menu-desc { + overflow: hidden; + color: var(--muted); + font-size: 0.9em; + text-overflow: ellipsis; + white-space: nowrap; +} + +.ui-command-menu-hint { + padding: 0.35em 0.85em; + border-top: 1px solid var(--border); + color: var(--muted); + font-size: 0.75em; +} + +.ui-command-menu-hint kbd { + padding: 0 0.35em; + border: 1px solid var(--border); + border-radius: 0.3em; + font-family: var(--mono, monospace); +} diff --git a/frontend/packages/swarm-ui/src/agent/terminal/CommandMenu.tsx b/frontend/packages/swarm-ui/src/agent/terminal/CommandMenu.tsx new file mode 100644 index 000000000..2f1d56103 --- /dev/null +++ b/frontend/packages/swarm-ui/src/agent/terminal/CommandMenu.tsx @@ -0,0 +1,69 @@ +// — the list that opens above an agent's message box while its +// text is one `/word`: the matching commands and skills, the selected one +// marked, the typed part of each name emphasised. A pick comes from the mouse +// here; the keys belong to the box (`AgentInputForm`), which owns the focus. +// Rows take a mouse press before the box loses focus, so the box never blurs. +import { splitName, type AgentCommand } from "./command-menu.js"; +import "./CommandMenu.css"; + +export function CommandMenu({ + id, + commands, + query, + selected, + onPick, + onHover, +}: { + /** The list's id, for the box's `aria-controls`. */ + id: string; + commands: AgentCommand[]; + query: string; + selected: number; + onPick: (command: AgentCommand) => void; + onHover: (index: number) => void; +}) { + return ( +
+
    + {commands.map((c, i) => { + const { before, hit, after } = splitName(c.name, query); + return ( +
  • { + e.preventDefault(); + onPick(c); + }} + onMouseEnter={() => onHover(i)} + > + + /{before} + {hit && {hit}} + {after} + + + {c.kind} + + {c.description} +
  • + ); + })} +
+ +
+ ); +} diff --git a/frontend/packages/swarm-ui/src/agent/terminal/command-menu.ts b/frontend/packages/swarm-ui/src/agent/terminal/command-menu.ts new file mode 100644 index 000000000..866f05915 --- /dev/null +++ b/frontend/packages/swarm-ui/src/agent/terminal/command-menu.ts @@ -0,0 +1,94 @@ +// The command menu under an agent's message box, without a DOM: what one +// command is, when the typed text asks for the menu, which commands match, and +// how the arrow keys move through them. The list itself comes from the backend +// (`GET /api/agents/{name}/commands`); nothing about which commands exist is +// decided here. + +/** One entry the menu offers. */ +export interface AgentCommand { + /** The name without the slash: `compact`, `base:pr-review`. */ + name: string; + /** One line saying what it does. */ + description: string; + /** A command of the harness, or a skill the agent has. */ + kind: "command" | "skill"; +} + +/** + * What follows the slash when the whole text is one `/word` (so the menu is + * wanted), lower-cased, else `null`. Text with a space in it, or one that does + * not start with a slash, is a message and not a command being typed. + */ +export function menuQuery(text: string): string | null { + const m = /^\/([^\s/]*)$/.exec(text); + return m ? m[1].toLowerCase() : null; +} + +/** + * The commands to show for `query`: names that start with it first, then names + * that contain it, then descriptions that do. Commands come before skills + * within each, and names sort alphabetically after that. + */ +export function matchCommands( + all: AgentCommand[], + query: string, +): AgentCommand[] { + const q = query.toLowerCase(); + const rank = (c: AgentCommand): number | null => { + const name = c.name.toLowerCase(); + if (name.startsWith(q)) return 0; + if (name.includes(q)) return 1; + if (c.description.toLowerCase().includes(q)) return 2; + return null; + }; + return all + .map((c) => ({ c, r: rank(c) })) + .filter((x): x is { c: AgentCommand; r: number } => x.r !== null) + .sort( + (a, b) => + a.r - b.r || + Number(a.c.kind === "skill") - Number(b.c.kind === "skill") || + a.c.name.localeCompare(b.c.name), + ) + .map((x) => x.c); +} + +/** What the box holds once `command` is taken: the command and a space. */ +export function completion(command: AgentCommand): string { + return `/${command.name} `; +} + +/** A name split around the part the query matched, for emphasis. */ +export function splitName( + name: string, + query: string, +): { before: string; hit: string; after: string } { + const at = + query === "" ? -1 : name.toLowerCase().indexOf(query.toLowerCase()); + if (at < 0) return { before: name, hit: "", after: "" }; + return { + before: name.slice(0, at), + hit: name.slice(at, at + query.length), + after: name.slice(at + query.length), + }; +} + +/** The selected row after an arrow key, wrapping at both ends. */ +export function moveSelection( + index: number, + count: number, + key: "ArrowDown" | "ArrowUp", +): number { + if (count <= 0) return 0; + return key === "ArrowDown" + ? (index + 1) % count + : (index - 1 + count) % count; +} + +/** + * Whether Enter should send the text as it stands: the box already holds the + * selected command in full, so there is nothing left to complete. + */ +export function enterSends(text: string, selected: AgentCommand): boolean { + return text.trim() === `/${selected.name}`; +} diff --git a/frontend/packages/swarm-ui/src/agent/terminal/useAgentCommands.ts b/frontend/packages/swarm-ui/src/agent/terminal/useAgentCommands.ts new file mode 100644 index 000000000..f88a38764 --- /dev/null +++ b/frontend/packages/swarm-ui/src/agent/terminal/useAgentCommands.ts @@ -0,0 +1,19 @@ +// The commands and skills an agent's message box offers, from +// `GET /api/agents/{name}/commands`, refetched now and then since an agent's +// skills change when its config does. An agent whose list cannot be read has an +// empty one: the box then works as a plain box, without the menu. Mount per +// agent name. +import { fetchJson, usePolled } from "../../ui/polled/usePolled.js"; +import type { AgentCommand } from "./command-menu.js"; + +const REFRESH_MS = 60_000; + +export function useAgentCommands(agentName: string): AgentCommand[] { + const { data } = usePolled(REFRESH_MS, async (signal) => + fetchJson( + `/api/agents/${encodeURIComponent(agentName)}/commands`, + signal, + ), + ); + return data ?? []; +} diff --git a/frontend/packages/swarm-ui/src/ui/text-field/TextField.tsx b/frontend/packages/swarm-ui/src/ui/text-field/TextField.tsx index 8da717631..4570b3523 100644 --- a/frontend/packages/swarm-ui/src/ui/text-field/TextField.tsx +++ b/frontend/packages/swarm-ui/src/ui/text-field/TextField.tsx @@ -24,6 +24,8 @@ export function TextField({ placeholder, hideLabel, suggestions, + onKeyDown, + combobox, }: { id: string; label: string; @@ -39,6 +41,16 @@ export function TextField({ /** Values to pick from. The field stays free text: a value that is not in * the list can still be typed. */ suggestions?: TextFieldSuggestion[]; + /** Key presses in the field, for a caller that draws its own menu. */ + onKeyDown?: (e: KeyboardEvent) => void; + /** Marks the field as the text box of a menu the caller draws itself. */ + combobox?: { + expanded: boolean; + /** The id of the menu's list. */ + controls: string; + /** The id of the selected row, when there is one. */ + activeDescendant?: string; + }; }) { const listId = `${id}-suggestions`; return ( @@ -56,6 +68,13 @@ export function TextField({ required={required} placeholder={placeholder} list={suggestions ? listId : undefined} + autoComplete={combobox ? "off" : undefined} + role={combobox ? "combobox" : undefined} + aria-expanded={combobox ? combobox.expanded : undefined} + aria-controls={combobox ? combobox.controls : undefined} + aria-activedescendant={combobox?.activeDescendant} + aria-autocomplete={combobox ? "list" : undefined} + onKeyDown={onKeyDown} onInput={(e) => onInput((e.target as HTMLInputElement).value)} /> {suggestions ? ( diff --git a/frontend/packages/swarm-ui/test/command-menu.test.mjs b/frontend/packages/swarm-ui/test/command-menu.test.mjs new file mode 100644 index 000000000..577779a2b --- /dev/null +++ b/frontend/packages/swarm-ui/test/command-menu.test.mjs @@ -0,0 +1,100 @@ +// The command menu's matching, completion and keys. Run by `npm test`, which +// imports the `.ts` module as it is. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + completion, + enterSends, + matchCommands, + menuQuery, + moveSelection, + splitName, +} from "../src/agent/terminal/command-menu.ts"; + +const cmd = (name, kind = "command", description = "") => ({ + name, + kind, + description, +}); + +test("the menu is wanted only while the text is one slash word", () => { + assert.equal(menuQuery("/"), ""); + assert.equal(menuQuery("/comp"), "comp"); + assert.equal(menuQuery("/Base:PR"), "base:pr"); + assert.equal(menuQuery("hello /comp"), null); + assert.equal(menuQuery("/compact now"), null); + assert.equal(menuQuery("/compact "), null); + assert.equal(menuQuery("//x"), null); + assert.equal(menuQuery(""), null); +}); + +test("prefix matches come first, then contains, then description", () => { + const all = [ + cmd("recompact"), + cmd("compact"), + cmd("other", "command", "will compact the thing"), + cmd("combine"), + ]; + assert.deepEqual( + matchCommands(all, "com").map((c) => c.name), + ["combine", "compact", "recompact", "other"], + ); +}); + +test("commands sort before skills within a rank, then by name", () => { + const all = [ + cmd("zeta", "command"), + cmd("alpha", "skill"), + cmd("beta", "command"), + ]; + assert.deepEqual( + matchCommands(all, "").map((c) => c.name), + ["beta", "zeta", "alpha"], + ); +}); + +test("nothing matches a query nothing contains", () => { + assert.deepEqual(matchCommands([cmd("compact")], "zzz"), []); +}); + +test("taking a command leaves the command and a space", () => { + assert.equal(completion(cmd("compact")), "/compact "); + assert.equal(completion(cmd("base:pr-review", "skill")), "/base:pr-review "); +}); + +test("the name splits around the matched part, case-insensitively", () => { + assert.deepEqual(splitName("compact", "mpa"), { + before: "co", + hit: "mpa", + after: "ct", + }); + assert.deepEqual(splitName("Compact", "COM"), { + before: "", + hit: "Com", + after: "pact", + }); + assert.deepEqual(splitName("compact", ""), { + before: "compact", + hit: "", + after: "", + }); + assert.deepEqual(splitName("compact", "x"), { + before: "compact", + hit: "", + after: "", + }); +}); + +test("the arrow keys wrap around the list", () => { + assert.equal(moveSelection(0, 3, "ArrowDown"), 1); + assert.equal(moveSelection(2, 3, "ArrowDown"), 0); + assert.equal(moveSelection(0, 3, "ArrowUp"), 2); + assert.equal(moveSelection(1, 3, "ArrowUp"), 0); + assert.equal(moveSelection(0, 0, "ArrowDown"), 0); +}); + +test("Enter sends once the selected command is already typed in full", () => { + assert.equal(enterSends("/compact", cmd("compact")), true); + assert.equal(enterSends("/comp", cmd("compact")), false); + assert.equal(enterSends("/", cmd("compact")), false); +});