diff --git a/src/model/hints.ts b/src/model/hints.ts deleted file mode 100644 index b42e473..0000000 --- a/src/model/hints.ts +++ /dev/null @@ -1,31 +0,0 @@ -/** A key a hint names, as the keyboard handler receives it. */ -export interface HintKey { - readonly name: string; - readonly sequence: string; - readonly shift: boolean; - readonly ctrl: boolean; -} - -const NAMED: Record = { esc: "escape", enter: "return", tab: "tab" }; - -/** - * The key at the start of a hint like "y approve" or "ctrl+k commands", so a click on the hint - * can press it. Hints that name a choice of keys ("j/k move", "1-9 pick") or a chord that - * sends a message ("alt+enter steer") aren't clickable. - */ -export function hintKey(hint: string, mode: string): HintKey | null { - const token = hint.trim().split(/\s+/)[0] ?? ""; - if (hint.includes(" or ") || /^\d-\d$/.test(token)) return null; - if (token.length > 1 && token.includes("/")) return null; - const ctrl = token.startsWith("ctrl+"); - const key = ctrl ? token.slice(5) : token; - if (key.includes("+") || key.includes("↑") || key.includes("↓")) return null; - // In the composer, enter is the composer's own: it sends, and a click shouldn't. - if (key === "enter" && (mode === "input" || ctrl)) return null; - const named = NAMED[key]; - if (named) return { name: named, sequence: named === "return" ? "\r" : named === "tab" ? "\t" : "\x1b", shift: false, ctrl }; - if ([...key].length !== 1) return null; - const lower = key.toLowerCase(); - const shift = lower !== key; - return { name: lower, sequence: ctrl ? String.fromCharCode(lower.charCodeAt(0) & 0x1f) : key, shift, ctrl }; -} diff --git a/src/model/keymap.ts b/src/model/keymap.ts new file mode 100644 index 0000000..a4c43cc --- /dev/null +++ b/src/model/keymap.ts @@ -0,0 +1,122 @@ +import type { PaletteCommand } from "./palette.ts"; + +/** + * One thing a key does, written once: the keys that do it, how the hint bar names it, and + * how the palette lists it. Key handling, the hints, clicks on hints and the palette's + * shortcuts all read the same binding, so they can't drift apart. + * + * Keys are written as people read them: "y", "Y" (shift+y), "ctrl+k", "alt+enter", "esc", + * "enter", "↑", "[", "pagedown". The first key is the one shown. + */ +export interface Binding { + readonly keys: readonly string[]; + /** Absent for a hint that only explains ("1-9 pick"): it isn't clickable and takes no key. */ + readonly run?: () => void; + /** The hint bar shows ` `. */ + readonly hint?: string; + /** The key as the hint and palette show it, when that isn't the first key ("j/k"). */ + readonly label?: string; + /** + * The key belongs to the focused input (enter in the composer sends), so the keymap leaves + * it alone; the hint still shows, and a click on it still runs. + */ + readonly passive?: boolean; + /** Listed in the palette. */ + readonly command?: { readonly id: string; readonly title: string; readonly keywords?: readonly string[] }; +} + +/** The key event fields the keymap reads, as OpenTUI's KeyEvent has them. */ +export interface KeyLike { + readonly name: string; + readonly ctrl: boolean; + readonly meta: boolean; + readonly shift: boolean; + readonly sequence?: string; +} + +/** A hint in the bar: the key, what it does, and the action a click runs. */ +export interface Hint { + readonly key: string; + readonly label: string; + readonly run?: () => void; +} + +const NAMES: Record = { esc: "escape", enter: "return", "↑": "up", "↓": "down", "←": "left", "→": "right" }; + +interface Spec { + readonly name: string; + readonly ctrl: boolean; + readonly meta: boolean; + /** null: either. Shift only counts for letters and named keys; "?" and ":" come shifted anyway. */ + readonly shift: boolean | null; +} + +const specs = new Map(); + +function parse(key: string): Spec { + const cached = specs.get(key); + if (cached) return cached; + const parts = key.length > 1 ? key.split("+") : [key]; + // "ctrl++" would split into empty parts; a lone "+" is the key itself. + const last = parts.pop() || "+"; + const modifiers = new Set(parts); + const letter = /^[a-z]$/i.test(last); + const name = NAMES[last] ?? (letter ? last.toLowerCase() : last); + const shifted = modifiers.has("shift") || (letter && last !== last.toLowerCase()); + const spec = { name, ctrl: modifiers.has("ctrl"), meta: modifiers.has("alt") || modifiers.has("meta"), shift: letter || name.length > 1 ? shifted : null }; + specs.set(key, spec); + return spec; +} + +/** Whether a key event is the key a binding names. */ +export function keyMatches(key: string, event: KeyLike): boolean { + const spec = parse(key); + // Terminals send ctrl+j as a bare line feed. + if (spec.name === "j" && spec.ctrl && !spec.meta && event.name === "linefeed") return true; + if (event.ctrl !== spec.ctrl || event.meta !== spec.meta) return false; + if (spec.shift !== null && event.shift !== spec.shift) return false; + return event.name === spec.name || (spec.name.length === 1 && event.sequence === spec.name); +} + +/** The first binding that takes this key. Order is precedence: put the more specific first. */ +export function bindingFor(bindings: readonly Binding[], event: KeyLike): Binding | undefined { + return bindings.find((binding) => binding.run && !binding.passive && binding.keys.some((key) => keyMatches(key, event))); +} + +/** The key a binding shows. */ +export function shownKey(binding: Binding): string | undefined { + return binding.label ?? binding.keys[0]; +} + +/** The hint bar for these bindings, in their order. */ +export function hintsFor(bindings: readonly Binding[]): Hint[] { + return bindings.flatMap((binding) => (binding.hint === undefined ? [] : [{ key: shownKey(binding) ?? "", label: binding.hint, ...(binding.run ? { run: binding.run } : {}) }])); +} + +/** The palette's commands among these bindings, with their keys as shortcuts. */ +export function commandsFor(bindings: readonly Binding[]): (PaletteCommand & { readonly run: () => void })[] { + const seen = new Set(); + return bindings.flatMap((binding) => { + const command = binding.command; + if (!command || !binding.run || seen.has(command.id)) return []; + seen.add(command.id); + const shortcut = shownKey(binding); + return [{ id: command.id, title: command.title, run: binding.run, ...(shortcut ? { shortcut } : {}), ...(command.keywords ? { keywords: command.keywords } : {}) }]; + }); +} + +/** A palette command with a key, as a binding: the key runs it too. */ +export function fromCommand(command: PaletteCommand & { readonly run: () => void }, hint?: string): Binding { + const { id, title, keywords, shortcut, run } = command; + return { keys: shortcut ? [shortcut] : [], run, command: { id, title, ...(keywords ? { keywords } : {}) }, ...(hint ? { hint } : {}) }; +} + +/** A list of bindings, leaving out the ones whose condition is false: `keys(open && close, ...more)`. */ +export function keys(...items: readonly (Binding | readonly Binding[] | false | null | undefined | "" | 0)[]): Binding[] { + return items.flatMap((item) => (!item ? [] : Array.isArray(item) ? item : [item as Binding])); +} + +/** The same binding with a hint, for a list that names it. */ +export function hinted(binding: Binding, hint: string): Binding { + return { ...binding, hint }; +} diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 482681c..6fedbb9 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -50,7 +50,7 @@ import { useTurns } from "./useTurns.ts"; import { ThreadView, type ConversationMouse, type ConversationTarget } from "./ThreadView.tsx"; import { Button, ResizeHandle } from "./Button.tsx"; import { HintBar } from "./HintBar.tsx"; -import type { HintKey } from "../model/hints.ts"; +import { bindingFor, commandsFor, fromCommand, hinted, hintsFor, keys, type Binding } from "../model/keymap.ts"; import { useEvent } from "./useEvent.ts"; import { useQueue } from "./useQueue.ts"; import { useSecretRequest } from "./useSecretRequest.ts"; @@ -385,7 +385,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C say, toInput: () => setMode("input"), }); - const secret = useSecretRequest({ session, projection: draft ? null : projection }); + const secret = useSecretRequest({ session, projection: draft ? null : projection, questionPending: pendingInput !== undefined }); onAlert.current = (alert) => { const mode = config.notificationMode; if (mode === "sound" || mode === "notifications-and-sound") ring(); @@ -1033,65 +1033,6 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C }); // The command palette: everything the keys do, plus what the details panel offers. - const commands: (PaletteCommand & { readonly run: () => void })[] = [...turns.commands]; - const command = (id: string, label: string, action: () => void, extra: Omit = {}) => commands.push({ id, title: label, run: action, ...extra }); - if (pendingApproval) { - command("approve", "Approve request", () => respond("accept"), { shortcut: "y" }); - command("approve-session", "Always allow this session", () => respond("acceptForSession"), { shortcut: "Y" }); - command("decline", "Decline request", () => respond("decline"), { shortcut: "n" }); - } - if (threadId && pendingInput?.dismissible) command("dismiss", "Dismiss question", () => run("Dismissed", () => session.dismissQuestion(threadId, pendingInput.requestId)), { shortcut: "x" }); - if (threadId) command("type", "Write a message", () => setMode("input"), { shortcut: "i", keywords: ["compose", "send", "steer"] }); - commands.push(...secret.commands, ...queue.commands); - for (const agent of projection?.subagents ?? []) { - if (threadId && canStopSubagent(agent)) command(`stop-subagent:${agent.id}`, `Stop subagent: ${agent.title ?? "subagent"}`, () => run("Stop requested", () => session.stopSubagent(agent)), { keywords: ["interrupt", "cancel", "kill"] }); - } - if (threadId && working) command("stop", "Stop thread", () => run("Stop requested", () => session.stopThread(threadId)), { shortcut: "S", keywords: ["interrupt", "cancel"] }); - if (details?.changes && details.changes.files.length > 0) command("diff", "View uncommitted changes", () => openDiff(null), { keywords: ["diff", "changes"] }); - for (const action of actions) { - if (action.kind === "git") command(action.id, `Git: ${action.git.label}`, () => runGit(action.git), { keywords: ["commit", "push", "pull request", "pr"] }); - if (action.kind === "server") command(action.id, `Stop server ${action.server.url}`, () => stopServer(action.server), { keywords: ["port", "kill"] }); - if (action.kind === "automation") { - command(action.id, `Run automation: ${action.task.title}`, () => runAutomation(action.task), { keywords: ["scheduled", "task"] }); - command(`${action.id}:toggle`, `${action.task.enabled ? "Turn off" : "Turn on"} automation: ${action.task.title}`, () => toggleAutomation(action.task), { keywords: ["scheduled", "task", "enable", "disable"] }); - command(`${action.id}:edit`, `Edit automation: ${action.task.title}`, () => automationEditing.editAutomation(action.task), { keywords: ["scheduled", "task", "editor"] }); - command(`${action.id}:delete`, `Delete automation: ${action.task.title}`, () => automationEditing.deleteAutomation(action.task), { keywords: ["scheduled", "task", "remove"] }); - } - } - if (parent) command("parent", `Go to parent: ${parent.title}`, () => openThread(parent.threadId), { shortcut: "u" }); - command("details", showDetails ? "Hide thread details" : "Show thread details", () => setDetailsPref(!showDetails), { shortcut: "d", keywords: ["panel", "info"] }); - if (threadShell) command("focus-details", "Focus thread details", focusDetails, { shortcut: "l" }); - command("expand", expandAll ? "Collapse work" : "Expand all work", () => setExpandAll(!expandAll), { shortcut: "e", keywords: ["fold", "tool calls"] }); - if (thread?.history.hasMore) command("earlier", "Load earlier turns", loadEarlier, { shortcut: "o", keywords: ["history", "older"] }); - if (!attached) { - command("filter", "Filter threads", () => setMode("filter"), { shortcut: "/", keywords: ["search"] }); - command("settled", showFolded ? "Hide settled threads" : "Show settled threads", () => setShowFolded(!showFolded), { shortcut: "z", keywords: ["snoozed", "archive"] }); - } - if (threadShell) command("thread-menu", "Thread actions…", openSelectedThreadMenu, { shortcut: ".", keywords: ["settle", "pin", "snooze", "rename", "archive", "delete", "copy", "unread", "menu"] }); - command("new-thread", "New thread", startDraft, { shortcut: "c", keywords: ["create", "start", "chat"] }); - if (draft) { - command("draft-project", "New thread: choose project", openProjectPicker, { shortcut: "p" }); - command("draft-workspace", draft.envMode === "local" && !draft.existingWorktree ? "New thread: use a new worktree" : "New thread: run in the project folder", toggleWorkspace, { shortcut: "w", keywords: ["worktree", "local", "branch"] }); - command("draft-cancel", "Cancel new thread", () => setDraft(null), { keywords: ["discard"] }); - } - if (currentModel) command("model", "Change model, options or mode", openModelPicker, { shortcut: "m", keywords: ["provider", "thinking", "reasoning", "effort", "speed", "fast", "access", "approval"] }); - commands.push(...workspace.commands); - if (threadId || draft) command("editor", "Write the message in $EDITOR", openEditor, { shortcut: "ctrl+g", keywords: ["vim", "editor", "compose"] }); - if (threadId || draft) commands.push(...attach.commands); - command("new-automation", "New automation", automationEditing.newAutomation, { keywords: ["scheduled", "task", "create", "editor"] }); - usageInfo.credits.forEach((credit, index) => command(`reset-credit:${index}`, `Use reset credit: ${credit.label}`, () => useResetCredit(credit), { keywords: ["usage", "limit", "reset", "credit"] })); - for (const prCommand of pullRequests.commands) commands.push(prCommand); - command("settings", "Settings", openSettings, { keywords: ["preferences", "config", "options", "notifications", "alerts"] }); - command("quit", "Quit tui3", quit, { shortcut: "q", keywords: ["exit"] }); - - commands.push(...library.commands(threadId)); - if (threadId && !draft) command("find", "Find in thread", openFind, { shortcut: "f", keywords: ["search", "messages", "plans"] }); - const paletteSearch = usePaletteSearch(session, library.merged, paletteQuery, mode === "palette"); - const paletteSnapshot = useMemo(() => mergeThreadShells(library.merged, paletteSearch.result?.threads ?? []), [library.merged, paletteSearch.result]); - const commandKey = commands.map((candidate) => `${candidate.id}:${candidate.title}`).join("|"); - // eslint-disable-next-line react-hooks/exhaustive-deps -- commands are rebuilt each render; commandKey tracks what changed. - const groups = useMemo(() => (mode === "palette" ? messageMatchGroups(paletteGroups({ query: paletteQuery, commands, snapshot: paletteSnapshot, now }), paletteSearch.result, paletteSnapshot, paletteQuery, now) : []), [mode, paletteQuery, commandKey, paletteSnapshot, paletteSearch.result]); - const entries = paletteEntries(groups); const openPalette = () => { if (mode !== "palette" && mode !== "confirm") returnMode.current = mode === "filter" ? "nav" : mode; setPaletteQuery(""); @@ -1106,22 +1047,6 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C commands.find((candidate) => candidate.id === entry.command.id)?.run(); }; - /** Keys that work in every mode. Returns true when handled. */ - const globalKey = (key: KeyEvent): boolean => { - if (key.ctrl && key.name === "c") return quit(), true; - if (key.ctrl && key.name === "k") return openPalette(), true; - if ((key.ctrl && key.name === "j") || key.name === "linefeed") return workspace.openTerminal(), true; - if (key.ctrl && key.name === "g" && (threadId || draft)) return openEditor(), true; - // One-line inputs keep ctrl+u and ctrl+d for editing. - const lineInput = mode === "filter" || mode === "palette" || mode === "confirm"; - if (key.name === "pagedown" || (!lineInput && key.ctrl && key.name === "d")) return scrollPage(1), true; - if (key.name === "pageup" || (!lineInput && key.ctrl && key.name === "u")) return scrollPage(-1), true; - if (!attached && ((key.ctrl && key.name === "n") || (key.meta && key.name === "down"))) return move(1), true; - if (!attached && ((key.ctrl && key.name === "p") || (key.meta && key.name === "up"))) return move(-1), true; - if (mode === "input" && key.meta && key.name === "return") return submit(true), true; - return false; - }; - // The / $ @ # menu: the web composer's suggestions for the trigger under the cursor. const composerCwd = draft ? (draftProject?.workspaceRoot ?? null) : (threadShell?.worktreePath ?? project?.workspaceRoot ?? null); const composerProvider = currentModel ? providerConfig?.providers.find((candidate) => candidate.instanceId === currentModel.instanceId) : undefined; @@ -1167,7 +1092,6 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C return null; } })(); - const menuOpen = menu !== null; const menuSelected = menu ? Math.min(menuIndex, Math.max(0, menu.items.length - 1)) : 0; useEffect(() => setMenuIndex(0), [triggerKey]); // A different composer (another thread, or the draft) mounts with its own text. @@ -1199,213 +1123,297 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C setComposerLines(composerLineCount(composer)); if (item.action === "model") openModelPicker(); }; - /** Keys the menu takes while it's open; the rest go to the message box. */ - const menuKey = (key: KeyEvent): boolean => { - if (!menu) return false; - if (key.name === "escape") return setMenuDismissed(triggerKey), true; - // Enter waits for a search in flight rather than sending the half-typed mention. - if (menu.loading && key.name === "return") return true; - if (menu.items.length === 0) return false; - if (key.name === "down" || (key.ctrl && key.name === "n")) return setMenuIndex(Math.min(menu.items.length - 1, menuSelected + 1)), true; - if (key.name === "up" || (key.ctrl && key.name === "p")) return setMenuIndex(Math.max(0, menuSelected - 1)), true; - if (key.name === "tab" || (key.name === "return" && !key.shift && !key.meta)) return chooseMenuItem(menu.items[menuSelected]), true; - return false; + // Keys. Each state has its bindings in hint order; the first one that takes a key runs it. + // The same bindings name the hints, make them clickable, and give the palette its shortcuts. + const hasComposer = threadId !== undefined || draft !== null; + const scrollBy = (lines: number) => scrollRef.current?.scrollBy(lines); + const toInput = () => { + if (hasComposer) setMode("input"); }; + const dismissQuestion = threadId && pendingInput?.dismissible ? () => run("Dismissed", () => session.dismissQuestion(threadId, pendingInput.requestId)) : null; + const leaveDetails = () => { + setDetailsSelected(null); + setMode("nav"); + }; + const selectedAction = () => actions.find((candidate) => candidate.id === detailsSelected); + + // Keys that work wherever there's no line input to type into. + const quitKey: Binding = { keys: ["ctrl+c"], run: quit }; + const paletteKey: Binding = { keys: ["ctrl+k"], run: openPalette }; + const terminalKey: Binding = { keys: ["ctrl+j"], run: workspace.openTerminal }; + const editorKey: Binding | null = hasComposer ? { keys: ["ctrl+g"], run: openEditor, command: { id: "editor", title: "Write the message in $EDITOR", keywords: ["vim", "editor", "compose"] } } : null; + const nextThreadKey: Binding = { keys: ["ctrl+n", "alt+↓"], label: "ctrl+n/p", run: () => move(1) }; + const previousThreadKey: Binding = { keys: ["ctrl+p", "alt+↑"], run: () => move(-1) }; + // One-line inputs keep ctrl+u and ctrl+d for editing. + const lineInput = mode === "filter"; + const globalKeys = keys( + quitKey, + paletteKey, + terminalKey, + editorKey, + { keys: lineInput ? ["pagedown"] : ["pagedown", "ctrl+d"], run: () => scrollPage(1) }, + { keys: lineInput ? ["pageup"] : ["pageup", "ctrl+u"], run: () => scrollPage(-1) }, + !attached && nextThreadKey, + !attached && previousThreadKey, + ); + + const digitKeys = pendingInput ? [1, 2, 3, 4, 5, 6, 7, 8, 9].map((digit): Binding => ({ keys: [String(digit)], run: () => pickOption(digit - 1) })) : []; + const pickHint: Binding = { keys: [], label: "1-9", hint: "pick" }; + + // Navigation: single keys move, open and act on the thread. + const scrollDiffDown: Binding = { keys: ["j", "↓"], label: "j/k", run: () => scrollBy(1), hint: "scroll" }; + const closeDiff: Binding = { keys: ["esc", "q"], run: () => setDiff(null), hint: "close diff" }; + const typeKey: Binding = { keys: ["i", "enter", "tab"], run: toInput, hint: "type", ...(threadId ? { command: { id: "type", title: "Write a message", keywords: ["compose", "send", "steer"] } } : {}) }; + const projectKey: Binding | null = draft ? { keys: ["p"], run: openProjectPicker, hint: "project", command: { id: "draft-project", title: "New thread: choose project" } } : null; + const modelKey: Binding | null = currentModel ? { keys: ["m"], run: openModelPicker, hint: "model", command: { id: "model", title: "Change model, options or mode", keywords: ["provider", "thinking", "reasoning", "effort", "speed", "fast", "access", "approval"] } } : null; + const worktreeKey: Binding | null = draft + ? { keys: ["w"], run: toggleWorkspace, hint: "worktree", command: { id: "draft-workspace", title: draft.envMode === "local" && !draft.existingWorktree ? "New thread: use a new worktree" : "New thread: run in the project folder", keywords: ["worktree", "local", "branch"] } } + : null; + const detailsKey: Binding = { keys: ["l", "→"], run: focusDetails, hint: "details", ...(threadShell ? { command: { id: "focus-details", title: "Focus thread details" } } : {}) }; + const cancelDraftKey: Binding | null = draft ? { keys: ["esc"], run: () => setDraft(null), hint: "cancel", command: { id: "draft-cancel", title: "Cancel new thread", keywords: ["discard"] } } : null; + const navKeys = keys( + diff && [scrollDiffDown, { keys: ["k", "↑"], run: () => scrollBy(-1) }, closeDiff], + turns.bindings, + pendingApproval && [ + { keys: ["y"], run: () => respond("accept"), hint: "approve", command: { id: "approve", title: "Approve request" } }, + { keys: ["Y"], run: () => respond("acceptForSession"), hint: "always", command: { id: "approve-session", title: "Always allow this session" } }, + { keys: ["n"], run: () => respond("decline"), hint: "decline", command: { id: "decline", title: "Decline request" } }, + ], + !diff && secret.bindings, + pendingInput && pickHint, + digitKeys, + dismissQuestion && { keys: ["x"], run: dismissQuestion, hint: "dismiss", command: { id: "dismiss", title: "Dismiss question" } }, + queue.keys.nav, + library.commands(threadId).map((command) => fromCommand(command)), + workspace.commands.map((command) => fromCommand(command)), + threadId && !draft && { keys: ["f"], run: openFind, command: { id: "find", title: "Find in thread", keywords: ["search", "messages", "plans"] } }, + // Only P is a navigation key; the rest are the PR view's own (below). + pullRequests.commands.filter((command) => command.id === "pull-requests").map((command) => fromCommand(command)), + { keys: ["j", "↓"], label: "j/k", run: () => (attached ? scrollBy(1) : move(1)), hint: attached ? "scroll" : "threads" }, + { keys: ["k", "↑"], run: () => (attached ? scrollBy(-1) : move(-1)) }, + !attached && { keys: ["/"], run: () => setMode("filter"), hint: "filter", command: { id: "filter", title: "Filter threads", keywords: ["search"] } }, + typeKey, + projectKey, + { keys: ["c"], run: startDraft, hint: "new", command: { id: "new-thread", title: "New thread", keywords: ["create", "start", "chat"] } }, + hasComposer && attach.commands.map((command) => fromCommand(command, command.id === "attach-file" ? "attach" : undefined)), + threadShell && { keys: ["."], run: openSelectedThreadMenu, hint: "actions", command: { id: "thread-menu", title: "Thread actions…", keywords: ["settle", "pin", "snooze", "rename", "archive", "delete", "copy", "unread", "menu"] } }, + modelKey, + worktreeKey, + hinted(terminalKey, "terminal"), + detailsKey, + parent && { keys: ["u"], run: () => openThread(parent.threadId), hint: "parent", command: { id: "parent", title: `Go to parent: ${parent.title}` } }, + hinted(paletteKey, "commands"), + { keys: ["q"], run: quit, hint: "quit", command: { id: "quit", title: "Quit tui3", keywords: ["exit"] } }, + { keys: ["d"], run: () => setDetailsPref(!showDetails), command: { id: "details", title: showDetails ? "Hide thread details" : "Show thread details", keywords: ["panel", "info"] } }, + { keys: ["e"], run: () => setExpandAll((value) => !value), command: { id: "expand", title: expandAll ? "Collapse work" : "Expand all work", keywords: ["fold", "tool calls"] } }, + thread?.history.hasMore && { keys: ["o"], run: loadEarlier, command: { id: "earlier", title: "Load earlier turns", keywords: ["history", "older"] } }, + !attached && { keys: ["z"], run: () => setShowFolded((value) => !value), command: { id: "settled", title: showFolded ? "Hide settled threads" : "Show settled threads", keywords: ["snoozed", "archive"] } }, + threadId && working && { keys: ["S"], run: () => run("Stop requested", () => session.stopThread(threadId)), command: { id: "stop", title: "Stop thread", keywords: ["interrupt", "cancel"] } }, + { keys: ["g"], run: () => scrollRef.current?.scrollTo(0) }, + { keys: ["G"], run: () => scrollRef.current?.scrollTo(scrollRef.current.scrollHeight) }, + { keys: [":"], run: openPalette }, + cancelDraftKey, + ); + // A diff and a draft name their own few keys; everything else names the lot. + const navHints = diff + ? [scrollDiffDown, closeDiff, detailsKey] + : draft + ? keys(hinted(typeKey, "write the first message"), projectKey, modelKey && hinted(modelKey, "model & mode"), worktreeKey, cancelDraftKey) + : navKeys; + + // Commands only the palette runs. + const paletteOnly = keys( + editorKey, + queue.keys.input, + queue.keys.palette, + (projection?.subagents ?? []).filter((agent) => threadId && canStopSubagent(agent)).map((agent): Binding => ({ keys: [], run: () => run("Stop requested", () => session.stopSubagent(agent)), command: { id: `stop-subagent:${agent.id}`, title: `Stop subagent: ${agent.title ?? "subagent"}`, keywords: ["interrupt", "cancel", "kill"] } })), + details?.changes && details.changes.files.length > 0 && { keys: [], run: () => openDiff(null), command: { id: "diff", title: "View uncommitted changes", keywords: ["diff", "changes"] } }, + actions.flatMap((action): Binding[] => { + if (action.kind === "git") return [{ keys: [], run: () => runGit(action.git), command: { id: action.id, title: `Git: ${action.git.label}`, keywords: ["commit", "push", "pull request", "pr"] } }]; + if (action.kind === "server") return [{ keys: [], run: () => stopServer(action.server), command: { id: action.id, title: `Stop server ${action.server.url}`, keywords: ["port", "kill"] } }]; + if (action.kind !== "automation") return []; + const task = action.task; + return [ + { keys: [], run: () => runAutomation(task), command: { id: action.id, title: `Run automation: ${task.title}`, keywords: ["scheduled", "task"] } }, + { keys: [], run: () => toggleAutomation(task), command: { id: `${action.id}:toggle`, title: `${task.enabled ? "Turn off" : "Turn on"} automation: ${task.title}`, keywords: ["scheduled", "task", "enable", "disable"] } }, + { keys: [], run: () => automationEditing.editAutomation(task), command: { id: `${action.id}:edit`, title: `Edit automation: ${task.title}`, keywords: ["scheduled", "task", "editor"] } }, + { keys: [], run: () => automationEditing.deleteAutomation(task), command: { id: `${action.id}:delete`, title: `Delete automation: ${task.title}`, keywords: ["scheduled", "task", "remove"] } }, + ]; + }), + { keys: [], run: automationEditing.newAutomation, command: { id: "new-automation", title: "New automation", keywords: ["scheduled", "task", "create", "editor"] } }, + usageInfo.credits.map((credit, index): Binding => ({ keys: [], run: () => useResetCredit(credit), command: { id: `reset-credit:${index}`, title: `Use reset credit: ${credit.label}`, keywords: ["usage", "limit", "reset", "credit"] } })), + // The PR view's keys are its own; the palette shows them without taking them here. + pullRequests.commands.map((command): Binding => ({ ...fromCommand(command), keys: [], ...(command.shortcut ? { label: command.shortcut } : {}) })), + { keys: [], run: openSettings, command: { id: "settings", title: "Settings", keywords: ["preferences", "config", "options", "notifications", "alerts"] } }, + ); + const commands = commandsFor([...navKeys, ...paletteOnly]); + + // The composer. Enter and newlines are the textarea's own; their hints only explain. + const sendKey = config.sendShortcut === "enter" ? "enter" : "ctrl+enter"; + const inputKeys = keys( + pendingApproval && { keys: [], label: "approval waiting:", hint: "esc, then y/n" }, + pendingInput && pickHint, + pendingInput && composerEmpty && digitKeys, + { keys: [], label: sendKey, hint: working ? config.followUpBehavior : "send" }, + working && { keys: [], label: "alt+enter", hint: config.followUpBehavior === "steer" ? "queue" : "steer" }, + { keys: ["alt+enter"], run: () => submit(true) }, + queue.keys.input, + { keys: [], label: config.sendShortcut === "enter" ? "shift+enter or \\" : "enter", hint: "newline" }, + editorKey && hinted(editorKey, "editor"), + { keys: ["esc"], run: () => setMode("nav"), hint: "navigate" }, + !attached && hinted(nextThreadKey, "thread"), + ); + const menuKeys = menu + ? keys( + { keys: [], label: "↑/↓", hint: "move" }, + menu.items.length > 0 && [ + { keys: ["↓", "ctrl+n"], run: () => setMenuIndex(Math.min(menu.items.length - 1, menuSelected + 1)) }, + { keys: ["↑", "ctrl+p"], run: () => setMenuIndex(Math.max(0, menuSelected - 1)) }, + ], + // Enter waits for a search in flight rather than sending the half-typed mention. + menu.loading && { keys: ["enter"], run: () => {} }, + menu.items.length > 0 ? { keys: ["tab", "enter"], label: "tab or enter", hint: "choose", run: () => chooseMenuItem(menu.items[menuSelected]) } : { keys: [], label: "tab or enter", hint: "choose" }, + { keys: ["esc"], run: () => setMenuDismissed(triggerKey), hint: "close" }, + ) + : []; + + // Lists and overlays. + const listMove = (step: (delta: number) => void): Binding[] => [ + { keys: [], label: "↑/↓", hint: "move" }, + { keys: ["↓", "ctrl+n"], run: () => step(1) }, + { keys: ["↑", "ctrl+p"], run: () => step(-1) }, + ]; + const detailsKeys = keys( + { keys: ["j", "↓"], label: "j/k", run: () => moveDetails(1), hint: "move" }, + { keys: ["k", "↑"], run: () => moveDetails(-1) }, + { + keys: ["enter", "space"], + run: () => { + const action = selectedAction(); + if (action) activate(action); + }, + hint: "open", + }, + { + keys: ["t"], + run: () => { + const action = selectedAction(); + if (action?.kind === "automation") toggleAutomation(action.task); + }, + hint: "toggle automation", + }, + { keys: ["esc"], run: () => (diff ? setDiff(null) : leaveDetails()), hint: "back" }, + { keys: ["h", "←"], run: leaveDetails }, + ); + const settingsKeys = keys( + { keys: ["j", "↓"], label: "j/k", run: () => setSettingsIndex(Math.min(settingsRows.length - 1, (settingsIndex ?? 0) + 1)), hint: "move" }, + { keys: ["k", "↑"], run: () => setSettingsIndex(Math.max(0, (settingsIndex ?? 0) - 1)) }, + { keys: ["enter", "space"], run: () => cycleSetting(settingsIndex ?? 0), hint: "change" }, + { keys: ["esc", "q", "h", "←"], run: closeSettings, hint: "close" }, + ); + const prCommand = (prefix: string) => pullRequests.commands.find((command) => command.id.startsWith(prefix)); + const prKey = (key: string, prefix: string, hint: string): Binding | null => { + const command = prCommand(prefix); + return command ? { keys: [key], run: command.run, hint } : null; + }; + const pullRequestKeys = keys( + { keys: ["j", "↓"], label: "j/k", run: () => scrollBy(1), hint: "scroll" }, + { keys: ["k", "↑"], run: () => scrollBy(-1) }, + { keys: ["g"], run: () => scrollRef.current?.scrollTo(0) }, + { keys: ["G"], run: () => scrollRef.current?.scrollTo(scrollRef.current.scrollHeight) }, + prKey("o", "pr-open", "open"), + prKey("r", "pr-refresh", "refresh"), + prKey("c", "pr-comment", "comment"), + prKey("R", "pr-review", "review"), + prKey("a", "pr-actions", "actions"), + prKey("w", "watch-pull-request", "watch"), + prKey("u", "unlink-pull-request", "unlink"), + { keys: ["esc", "q"], run: pullRequests.close, hint: "close" }, + ); + const findKeys = keys( + { keys: ["enter"], run: () => find.step(1), hint: "next match" }, + { keys: ["shift+enter"], run: () => find.step(-1), hint: "previous" }, + { keys: ["ctrl+n"], label: "ctrl+n/p", run: () => find.step(1), hint: "match" }, + { keys: ["ctrl+p"], run: () => find.step(-1) }, + { keys: ["esc"], run: () => setMode("nav"), hint: "close find" }, + quitKey, + paletteKey, + ); + const closePicker = () => { + setPicker(null); + setMode(returnMode.current); + }; + const confirmNow = () => { + const pending = confirmation; + closeOverlay(); + pending?.run(""); + }; + + /** The bindings for the current state, most specific first, and the ones the hint bar names. */ + const keymap = ((): { readonly layers: readonly (readonly Binding[])[]; readonly hints: readonly Binding[] } => { + switch (mode) { + case "find": + return { layers: [findKeys], hints: findKeys }; + case "picker": { + const pickerKeys = [...listMove((delta) => setPickerIndex((index) => Math.max(0, Math.min(pickerEntries.length - 1, index + delta)))), { keys: [], label: "enter", hint: "choose" }, { keys: ["esc"], run: closePicker, hint: "close" }, quitKey]; + return { layers: [pickerKeys], hints: pickerKeys }; + } + case "palette": { + const paletteKeys = [...listMove((delta) => setPaletteIndex((index) => Math.max(0, Math.min(entries.length - 1, index + delta)))), { keys: [], label: "enter", hint: "run" }, { keys: ["esc", "ctrl+k"], run: () => setMode(returnMode.current), hint: "close" }, quitKey]; + return { layers: [paletteKeys], hints: paletteKeys }; + } + case "confirm": { + // Without a message box, enter confirms here; with one, the box's submit does. + const confirmKeys = [confirmation?.message ? { keys: [], label: "enter", hint: "confirm" } : { keys: ["enter"], run: confirmNow, hint: "confirm" }, { keys: ["esc"], run: closeOverlay, hint: "cancel" }, quitKey]; + return { layers: [confirmKeys], hints: confirmKeys }; + } + } + // The secret field takes every key while it's focused. + if (secret.focused) return { layers: [secret.bindings, [quitKey]], hints: secret.bindings }; + switch (mode) { + case "input": + if (menu) return { layers: [menuKeys, inputKeys, globalKeys], hints: menuKeys }; + if (queue.editing) return { layers: [queue.keys.editing, inputKeys, globalKeys], hints: queue.keys.editing }; + return { layers: [inputKeys, globalKeys], hints: inputKeys }; + case "filter": { + const filterKeys = [{ keys: [], label: "enter", hint: "done" }, { keys: ["esc"], run: () => setMode("nav"), hint: "close" }]; + return { layers: [filterKeys, globalKeys], hints: filterKeys }; + } + case "settings": + return { layers: [settingsKeys, globalKeys], hints: settingsKeys }; + case "pull-request": + return { layers: [pullRequestKeys, globalKeys], hints: pullRequestKeys }; + case "details": + return { layers: [detailsKeys, globalKeys, navKeys], hints: detailsKeys }; + default: + if (queue.focused) return { layers: [queue.keys.focused, globalKeys, navKeys], hints: queue.keys.focused }; + return { layers: [globalKeys, navKeys], hints: navHints }; + } + })(); const handleKey = (key: KeyEvent) => { // A key ends a mouse selection; it was copied when the drag ended. if (renderer.hasSelection) renderer.clearSelection(); - if (mode === "find") { - if (key.ctrl && key.name === "c") return quit(); - if (key.ctrl && key.name === "k") return openPalette(), key.preventDefault(); - if (find.handleKey(key)) { - if (key.name === "escape") setMode("nav"); + for (const layer of keymap.layers) { + const binding = bindingFor(layer, key); + if (binding?.run) { + binding.run(); return key.preventDefault(); } - return; } - if (mode === "input" && menuKey(key)) return key.preventDefault(); - if (mode === "picker") { - if (key.ctrl && key.name === "c") return quit(); - if (key.name === "escape") { - setPicker(null); - setMode(returnMode.current); - } else if (key.name === "down" || (key.ctrl && key.name === "n")) setPickerIndex((index) => Math.min(pickerEntries.length - 1, index + 1)); - else if (key.name === "up" || (key.ctrl && key.name === "p")) setPickerIndex((index) => Math.max(0, index - 1)); - else return; - return key.preventDefault(); - } - if (mode === "palette") { - if (key.ctrl && key.name === "c") return quit(); - if (key.name === "escape" || (key.ctrl && key.name === "k")) setMode(returnMode.current); - else if (key.name === "down" || (key.ctrl && key.name === "n")) setPaletteIndex((index) => Math.min(entries.length - 1, index + 1)); - else if (key.name === "up" || (key.ctrl && key.name === "p")) setPaletteIndex((index) => Math.max(0, index - 1)); - else return; - return key.preventDefault(); - } - if (mode === "confirm") { - if (key.ctrl && key.name === "c") return quit(); - if (key.name === "escape") { - closeOverlay(); - return key.preventDefault(); - } - // Without a message box, enter confirms here; with one, the box's submit does. - if (key.name === "return" && !confirmation?.message) { - const pending = confirmation; - closeOverlay(); - pending?.run(""); - return key.preventDefault(); - } - return; - } - if (secret.key(key, mode === "nav" && !diff, Boolean(pendingInput))) return key.preventDefault(); - if (queue.key(key, mode === "nav" ? "nav" : mode === "input" ? "input" : "other")) return key.preventDefault(); - if (globalKey(key)) return key.preventDefault(); - const digit = /^[1-9]$/.test(key.name) && !key.ctrl && !key.meta ? Number(key.name) - 1 : -1; - if (digit >= 0 && pendingInput && (mode === "nav" || (mode === "input" && composerEmpty))) { - pickOption(digit); - return key.preventDefault(); - } - if (mode === "input" || mode === "filter") { - if (key.name === "escape") { - setMode("nav"); - key.preventDefault(); - } - return; - } - const scroll = scrollRef.current; - if (mode === "pull-request") { - if (pullRequests.handleKey(key, scroll)) return key.preventDefault(); - return; - } - if (mode === "settings") { - const index = settingsIndex ?? 0; - switch (key.name) { - case "j": - case "down": - return setSettingsIndex(Math.min(settingsRows.length - 1, index + 1)); - case "k": - case "up": - return setSettingsIndex(Math.max(0, index - 1)); - case "return": - case "space": - cycleSetting(index); - return key.preventDefault(); - case "escape": - case "q": - case "h": - case "left": - return closeSettings(); - } - return; - } - if (mode === "details") { - switch (key.name) { - case "j": - case "down": - return moveDetails(1); - case "k": - case "up": - return moveDetails(-1); - case "return": - case "space": { - const action = actions.find((candidate) => candidate.id === detailsSelected); - if (action) activate(action); - return key.preventDefault(); - } - case "t": { - const action = actions.find((candidate) => candidate.id === detailsSelected); - if (action?.kind === "automation") toggleAutomation(action.task); - return; - } - case "escape": - if (diff) return setDiff(null); - setDetailsSelected(null); - return setMode("nav"); - case "h": - case "left": - setDetailsSelected(null); - return setMode("nav"); - } - } - if (workspace.key(key)) return; - if (mode === "nav" && library.key(key, threadId)) return key.preventDefault(); - if (mode === "nav" && key.name === "f" && threadId && !draft) return openFind(), key.preventDefault(); - if (mode === "nav" && turns.onKey(key)) return key.preventDefault(); - switch (key.name) { - case "q": - if (diff) return setDiff(null); - return quit(); - case "escape": - if (diff) setDiff(null); - else if (draft) setDraft(null); - return; - case "c": - return startDraft(); - case "a": - if (threadId || draft) attach.attachFile(); - return; - case "m": - return openModelPicker(); - case ".": - return openSelectedThreadMenu(); - case "p": - if (key.shift) return pullRequests.open(); - if (draft) openProjectPicker(); - return; - case "w": - if (draft) toggleWorkspace(); - return; - case "j": - case "down": - return attached || diff ? scroll?.scrollBy(1) : move(1); - case "k": - case "up": - return attached || diff ? scroll?.scrollBy(-1) : move(-1); - case "g": - return key.shift ? scroll?.scrollTo(scroll.scrollHeight) : scroll?.scrollTo(0); - case "d": - return setDetailsPref(!showDetails); - case "l": - case "right": - return focusDetails(); - case "u": - if (parent) openThread(parent.threadId); - return; - case "e": - return setExpandAll((value) => !value); - case "o": - return loadEarlier(); - case "z": - return setShowFolded((value) => !value); - case "y": - return respond(key.shift ? "acceptForSession" : "accept"); - case "n": - return respond("decline"); - case "x": - if (threadId && pendingInput?.dismissible) run("Dismissed", () => session.dismissQuestion(threadId, pendingInput.requestId)); - return; - case "s": - if (threadId && key.shift) run("Stop requested", () => session.stopThread(threadId)); - return; - case ":": - openPalette(); - return key.preventDefault(); - case "/": - if (!attached) setMode("filter"); - return key.preventDefault(); - case "i": - case "return": - case "tab": - if (threadId || draft) setMode("input"); - return key.preventDefault(); + if (secret.focused && mode !== "find" && mode !== "picker" && mode !== "palette" && mode !== "confirm") { + secret.type(key); + key.preventDefault(); } }; useKeyboard(handleKey); - /** A click on a key hint presses that key, through the same handler as the keyboard. */ - const pressKey = (hint: HintKey) => - handleKey({ ...hint, meta: false, option: false, number: false, raw: hint.sequence, eventType: "press", source: "raw", preventDefault() {}, stopPropagation() {} } as unknown as KeyEvent); + const paletteSearch = usePaletteSearch(session, library.merged, paletteQuery, mode === "palette"); + const paletteSnapshot = useMemo(() => mergeThreadShells(library.merged, paletteSearch.result?.threads ?? []), [library.merged, paletteSearch.result]); + const commandKey = commands.map((candidate) => `${candidate.id}:${candidate.title}:${candidate.shortcut ?? ""}`).join("|"); + // eslint-disable-next-line react-hooks/exhaustive-deps -- commands are rebuilt each render; commandKey tracks what changed. + const groups = useMemo(() => (mode === "palette" ? messageMatchGroups(paletteGroups({ query: paletteQuery, commands, snapshot: paletteSnapshot, now }), paletteSearch.result, paletteSnapshot, paletteQuery, now) : []), [mode, paletteQuery, commandKey, paletteSnapshot, paletteSearch.result]); + const entries = paletteEntries(groups); // The mouse in the conversation: stable callbacks, since its rows are memoized. const conversationMouse: ConversationMouse = { @@ -1702,13 +1710,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C {detailsColumn ? detailsPanel(false) : null} - {flash ? ( - {flash.text} - ) : menuOpen ? ( - ↑/↓ move · tab or enter choose · esc close - ) : ( - 0 ? "queued" : null })} /> - )} + {flash ? {flash.text} : } {mode === "palette" ? ( (error instanceof Error ? error.message : String(error)); /** diff --git a/src/ui/HintBar.tsx b/src/ui/HintBar.tsx index ede52db..e29a2c6 100644 --- a/src/ui/HintBar.tsx +++ b/src/ui/HintBar.tsx @@ -1,33 +1,32 @@ import type { MouseEvent } from "@opentui/core"; -import { hintKey, type HintKey } from "../model/hints.ts"; +import type { Hint } from "../model/keymap.ts"; import { isLeftClick, useHover } from "./Button.tsx"; import { colors } from "./theme.ts"; -/** The key hints along the bottom; each one that names a single key presses it when clicked. */ -export function HintBar(props: { readonly text: string; readonly mode: string; readonly onPress: (key: HintKey) => void }) { - const parts = props.text.split(" · "); +/** The key hints along the bottom; a click on one does what its key does. */ +export function HintBar(props: { readonly hints: readonly Hint[] }) { return ( - {parts.map((part, index) => ( - 0} hintKey={hintKey(part, props.mode)} onPress={props.onPress} /> + {props.hints.map((hint, index) => ( + 0} /> ))} ); } -function Hint(props: { readonly text: string; readonly separator: boolean; readonly hintKey: HintKey | null; readonly onPress: (key: HintKey) => void }) { +function HintItem(props: { readonly hint: Hint; readonly separator: boolean }) { const [hover, hoverProps] = useHover(); - const key = props.hintKey; + const { key, label, run } = props.hint; return ( {props.separator ? {" · "} : null} isLeftClick(event) && props.onPress(key) } : {})} + {...(run ? { ...hoverProps, onMouseDown: (event: MouseEvent) => isLeftClick(event) && run() } : {})} > - {props.text} + {key ? `${key} ${label}` : label} ); diff --git a/src/ui/useDiffContext.ts b/src/ui/useDiffContext.ts index ccc448b..c7862ae 100644 --- a/src/ui/useDiffContext.ts +++ b/src/ui/useDiffContext.ts @@ -1,4 +1,4 @@ -import type { KeyEvent, ScrollBoxRenderable } from "@opentui/core"; +import type { ScrollBoxRenderable } from "@opentui/core"; import { useEffect, useMemo, useRef, useState, type RefObject } from "react"; import type { T3Session } from "../client/session.ts"; import { splitPatch, wholeFilePatch } from "../model/diffs.ts"; @@ -32,19 +32,10 @@ export function useDiffContext(session: T3Session, diff: DiffState | null, scrol setSelected(next); scrollRef.current?.scrollChildIntoView(`diff-file-${next}`); }; - const onKey = (key: KeyEvent): boolean => { - if (!diff) return false; - if (key.name === "[" || key.name === "]") { - move(key.name === "[" ? -1 : 1); - return true; - } - if (key.name === "x" || key.name === "return") { expand(); return true; } - return false; - }; /** A click on a file's header: select it, and a second click opens its whole file. */ const click = (index: number) => { if (index === selected) return expand(index); setSelected(index); }; - return { selected, expanded, onKey, move, expand, click }; + return { selected, expanded, move, expand, click }; } diff --git a/src/ui/useQueue.ts b/src/ui/useQueue.ts index be46f75..2fc0373 100644 --- a/src/ui/useQueue.ts +++ b/src/ui/useQueue.ts @@ -1,9 +1,10 @@ import type { ModelSelection, OrchestrationV2ThreadProjection, RunId, ThreadId } from "@t3tools/contracts"; import { queuedRunEditBlockedReason, resolveQueuedEditExit } from "@t3tools/client-runtime/queued-run-edit"; -import type { KeyEvent, TextareaRenderable } from "@opentui/core"; +import type { TextareaRenderable } from "@opentui/core"; import { useEffect, useState } from "react"; import type { T3Session } from "../client/session.ts"; +import type { Binding } from "../model/keymap.ts"; import { queueState, type QueuedMessage } from "../model/queue.ts"; interface QueuedEdit { @@ -108,47 +109,36 @@ export function useQueue(input: { return false; }; - const key = (event: KeyEvent, mode: "nav" | "input" | "other"): boolean => { - if (mode === "nav" && focus !== null) { - const message = queued[focus]!; - switch (event.name) { - case "j": - case "down": - return setFocus(Math.min(queued.length - 1, focus + 1)), true; - case "k": - case "up": - return setFocus(Math.max(0, focus - 1)), true; - case "return": - case "s": - return sendNow(message), true; - case "e": - return beginEdit(message), true; - case "x": - case "d": - case "backspace": - return remove(message), true; - case "escape": - case "q": - return setFocus(null), true; - } - return false; - } - if (mode === "nav" && event.name === "q" && event.shift && queued.length > 0) return setFocus(0), true; - // The web's alt+↑: edit the last queued message. - if (mode === "input" && event.meta && event.name === "up" && !editing && queued.length > 0) return beginEdit(queued[queued.length - 1]!), true; - if (mode === "input" && event.name === "escape" && editing) return cancelEdit(), true; - return false; - }; - const first = queued[0]; const last = queued[queued.length - 1]; - const commands = [ - ...(first && queue && (queue.canSendNow || queue.canPromoteToSteer) ? [{ id: "queue-send", title: "Queue: send first queued message", run: () => sendNow(first), keywords: ["steer", "now"] }] : []), - ...(last ? [{ id: "queue-edit", title: "Queue: edit last queued message", run: () => beginEdit(last), shortcut: "alt+↑", keywords: ["change"] }] : []), - ...(queued.length > 0 ? [{ id: "queue-focus", title: "Queue: go through queued messages", run: () => setFocus(0), shortcut: "Q", keywords: ["remove", "cancel", "delete"] }] : []), - ...queued.map((message, index) => ({ id: `queue-remove:${message.runId}`, title: `Queue: remove ${index + 1}. ${message.text.replace(/\s+/g, " ").slice(0, 60)}`, run: () => remove(message), keywords: ["cancel", "delete"] })), - ...(canResume ? [{ id: "queue-resume", title: queue?.resumableRunId ? "Continue where it left off" : "Send held queued messages", run: resume, keywords: ["resume", "interrupted"] }] : []), - ]; + const focused = focus === null ? undefined : queued[focus]; + const onFocused = (action: (message: QueuedMessage) => void) => () => focused && action(focused); + const keys = { + /** In navigation: Q goes through the queue. */ + nav: queued.length > 0 ? [{ keys: ["Q"], run: () => setFocus(0), hint: "queue", command: { id: "queue-focus", title: "Queue: go through queued messages", keywords: ["remove", "cancel", "delete"] } }] : [], + /** While going through the queue: the focused message's keys. */ + focused: focus === null ? [] : [ + { keys: ["j", "↓"], label: "j/k", run: () => setFocus(Math.min(queued.length - 1, focus + 1)), hint: "move" }, + { keys: ["k", "↑"], run: () => setFocus(Math.max(0, focus - 1)) }, + { keys: ["enter", "s"], run: onFocused(sendNow), hint: "send now" }, + { keys: ["e"], run: onFocused(beginEdit), hint: "edit" }, + { keys: ["x", "d", "backspace"], run: onFocused(remove), hint: "remove" }, + { keys: ["esc", "q"], run: () => setFocus(null), hint: "back" }, + ], + /** In the composer: the web's alt+↑ edits the last queued message. */ + input: last && !editing ? [{ keys: ["alt+↑"], run: () => beginEdit(last), hint: "edit queued", command: { id: "queue-edit", title: "Queue: edit last queued message", keywords: ["change"] } }] : [], + /** In the composer while it holds a queued message. */ + editing: editing ? [ + { keys: ["enter"], label: "enter", hint: "save the queued message" }, + { keys: ["esc"], run: cancelEdit, hint: "cancel the edit" }, + ] : [], + /** Palette-only commands. */ + palette: [ + ...(first && queue && (queue.canSendNow || queue.canPromoteToSteer) ? [{ keys: [], run: () => sendNow(first), command: { id: "queue-send", title: "Queue: send first queued message", keywords: ["steer", "now"] } }] : []), + ...queued.map((message, index) => ({ keys: [], run: () => remove(message), command: { id: `queue-remove:${message.runId}`, title: `Queue: remove ${index + 1}. ${message.text.replace(/\s+/g, " ").slice(0, 60)}`, keywords: ["cancel", "delete"] } })), + ...(canResume ? [{ keys: [], run: resume, command: { id: "queue-resume", title: queue?.resumableRunId ? "Continue where it left off" : "Send held queued messages", keywords: ["resume", "interrupted"] } }] : []), + ], + } satisfies Record; const placeholder = editing ? "Edit the queued message (enter saves, esc cancels)" : canResume ? (queue?.resumableRunId ? "Ask anything, or press enter to continue where it left off" : "Ask anything, or press enter to send the held messages") : null; @@ -164,5 +154,5 @@ export function useQueue(input: { resume: canResume ? resume : null, }; - return { queue, queued, focus, focused: focus !== null, editingRunId: editing?.runId ?? null, editing: editing !== null, key, submit, commands, placeholder, actions }; + return { queue, queued, focus, focused: focus !== null, editingRunId: editing?.runId ?? null, editing: editing !== null, keys, submit, placeholder, actions }; } diff --git a/src/ui/useSecretRequest.ts b/src/ui/useSecretRequest.ts index 18e7d98..67dc737 100644 --- a/src/ui/useSecretRequest.ts +++ b/src/ui/useSecretRequest.ts @@ -5,6 +5,7 @@ import { usePaste } from "@opentui/react"; import { useEffect, useState } from "react"; import type { T3Session } from "../client/session.ts"; +import type { Binding } from "../model/keymap.ts"; import { pendingSecretRequest } from "../model/queue.ts"; const decoder = new TextDecoder(); @@ -13,7 +14,12 @@ const decoder = new TextDecoder(); * The open thread's pending secret request and its masked field. The field takes keys itself * (the composer never sees the value, so it can't be sent as a message by mistake). */ -export function useSecretRequest(input: { readonly session: T3Session; readonly projection: OrchestrationV2ThreadProjection | null | undefined }) { +export function useSecretRequest(input: { + readonly session: T3Session; + readonly projection: OrchestrationV2ThreadProjection | null | undefined; + /** x dismisses a question first, so it only declines the secret when no question is open. */ + readonly questionPending: boolean; +}) { const request = input.projection ? pendingSecretRequest(input.projection) : null; const [value, setValue] = useState(null); const [error, setError] = useState(null); @@ -42,36 +48,35 @@ export function useSecretRequest(input: { readonly session: T3Session; readonly .finally(() => setBusy(false)); }; - /** Keys for the field while it's focused, and enter / x on the card in navigation. */ - const key = (event: KeyEvent, nav: boolean, questionPending: boolean): boolean => { - if (!request) return false; - if (value === null) { - if (!nav) return false; - if (event.name === "return") return setValue(""), true; - if (event.name === "x" && !questionPending) return answer({ type: "decline" }), true; - return false; - } - if (event.ctrl && event.name === "c") return false; - if (event.name === "escape") setValue(null); - else if (event.name === "return") answer({ type: "save", secret: value }); - else if (event.name === "backspace") setValue(value.slice(0, -1)); + /** Typing in the focused field: characters, backspace and ctrl+u. Every key stays here. */ + const type = (event: KeyEvent) => { + if (value === null) return; + if (event.name === "backspace") setValue(value.slice(0, -1)); else if (event.ctrl && event.name === "u") setValue(""); else if (!event.ctrl && !event.meta && event.sequence.length === 1 && event.sequence >= " ") setValue(value + event.sequence); - return true; }; - const commands = request - ? [ - { id: "secret-answer", title: `Answer secret request: ${request.label}`, run: () => setValue(""), shortcut: "enter", keywords: ["password", "token", "key", "credential"] }, - { id: "secret-decline", title: `Decline secret request: ${request.label}`, run: () => answer({ type: "decline" }), keywords: ["password", "token", "key", "credential"] }, - ] - : []; - const actions = { focus: () => setValue(""), cancel: () => setValue(null), save: () => value !== null && answer({ type: "save", secret: value }), decline: () => answer({ type: "decline" }), }; - return { request, value, error, busy, focused: value !== null, key, commands, actions }; + + const keywords = ["password", "token", "key", "credential"]; + /** On the card in navigation: enter opens the field, x declines. While the field is focused: its own keys. */ + const bindings: Binding[] = !request + ? [] + : value === null + ? [ + { keys: ["enter"], run: actions.focus, hint: "answer the secret request", command: { id: "secret-answer", title: `Answer secret request: ${request.label}`, keywords } }, + { keys: input.questionPending ? [] : ["x"], run: actions.decline, ...(input.questionPending ? {} : { hint: "decline" }), command: { id: "secret-decline", title: `Decline secret request: ${request.label}`, keywords } }, + ] + : [ + { keys: [], label: "", hint: "type or paste the secret" }, + { keys: ["enter"], run: actions.save, hint: "save securely" }, + { keys: ["esc"], run: actions.cancel, hint: "cancel" }, + ]; + + return { request, value, error, busy, focused: value !== null, bindings, type, actions }; } diff --git a/src/ui/useTurns.ts b/src/ui/useTurns.ts index ff3ddab..1137010 100644 --- a/src/ui/useTurns.ts +++ b/src/ui/useTurns.ts @@ -1,8 +1,8 @@ -import type { KeyEvent, ScrollBoxRenderable } from "@opentui/core"; +import type { ScrollBoxRenderable } from "@opentui/core"; import type { OrchestrationV2ThreadProjection, ServerConfig, ThreadId } from "@t3tools/contracts"; import { useEffect, useRef, useState, type Dispatch, type RefObject, type SetStateAction } from "react"; import type { T3Session } from "../client/session.ts"; -import type { PaletteCommand } from "../model/palette.ts"; +import type { Binding } from "../model/keymap.ts"; import type { Timeline } from "../model/timeline.ts"; import { recallableComposerPrompt } from "../../vendor/t3code/apps/web/src/components/chat/composerPromptHistory.ts"; import { adjacentTurn, diffTurn, findRevertCheckpoint, type TurnCheckpoint } from "../model/turns.ts"; @@ -90,33 +90,36 @@ export function useTurns(input: { }, }); }; - const commands: (PaletteCommand & { readonly run: () => void })[] = input.enabled && turns.length ? [ - { id: "previous-turn", title: "Select previous turn", shortcut: "[", keywords: ["turn", "cursor"], run: () => move(-1) }, - { id: "next-turn", title: "Select next turn", shortcut: "]", keywords: ["turn", "cursor"], run: () => move(1) }, - { id: "turn-diff", title: "View changes from this turn", shortcut: "D", keywords: ["diff", "checkpoint"], run: () => openDiff(false) }, - { id: "thread-diff", title: "View all changes in this thread", keywords: ["diff", "checkpoint"], run: () => openDiff(true) }, - ...(selected ? [ - { id: "turn-revert", title: "Revert to this turn", shortcut: "R", keywords: ["rollback", "rewind", "keep changes"], run: () => revert() }, - { id: "turn-revert-files", title: "Revert files too", keywords: ["rollback", "rewind", "turn"], run: () => revert(true) }, - { id: "turn-clear", title: "Clear turn selection", shortcut: "esc", run: () => setCursor(null) }, - ] : []), - ] : []; - if (input.diff) { - commands.push( - { id: "diff-previous-file", title: "Previous changed file", shortcut: "[", keywords: ["diff"], run: () => diffContext.move(-1) }, - { id: "diff-next-file", title: "Next changed file", shortcut: "]", keywords: ["diff"], run: () => diffContext.move(1) }, - ); - if (input.diff.source) commands.push({ id: "diff-context", title: "Show whole file / collapse context", shortcut: "x", keywords: ["diff", "expand", "unchanged"], run: diffContext.expand }); - } - const onKey = (key: KeyEvent): boolean => { - if (key.ctrl || key.meta || !input.enabled) return false; - if (diffContext.onKey(key)) return true; - if (key.name === "[" || key.name === "]") { move(key.name === "[" ? -1 : 1); return true; } - if (key.name.toLowerCase() === "d" && key.shift) { openDiff(false); return true; } - if (key.name.toLowerCase() === "r" && key.shift) { revert(); return true; } - if (key.name === "escape" && !input.diff && selectedMessageId) { setCursor(null); return true; } - return false; - }; + const turnKeys = input.enabled && turns.length > 0; + /** + * Turn keys in navigation. A diff's own keys come first: there, [ and ] step through its + * files rather than the turns. + */ + const bindings: Binding[] = [ + ...(input.enabled && input.diff + ? [ + { keys: ["["], run: () => diffContext.move(-1), command: { id: "diff-previous-file", title: "Previous changed file", keywords: ["diff"] } }, + { keys: ["]"], run: () => diffContext.move(1), command: { id: "diff-next-file", title: "Next changed file", keywords: ["diff"] } }, + ...(input.diff.source ? [{ keys: ["x", "enter"], run: () => diffContext.expand(), command: { id: "diff-context", title: "Show whole file / collapse context", keywords: ["diff", "expand", "unchanged"] } }] : []), + ] + : []), + ...(turnKeys + ? [ + { keys: ["["], run: () => move(-1), command: { id: "previous-turn", title: "Select previous turn", keywords: ["turn", "cursor"] } }, + { keys: ["]"], run: () => move(1), command: { id: "next-turn", title: "Select next turn", keywords: ["turn", "cursor"] } }, + { keys: ["D"], run: () => openDiff(false), command: { id: "turn-diff", title: "View changes from this turn", keywords: ["diff", "checkpoint"] } }, + { keys: [], run: () => openDiff(true), command: { id: "thread-diff", title: "View all changes in this thread", keywords: ["diff", "checkpoint"] } }, + // R says how to select a turn when none is. + { keys: ["R"], run: () => revert(), ...(selected ? { command: { id: "turn-revert", title: "Revert to this turn", keywords: ["rollback", "rewind", "keep changes"] } } : {}) }, + ] + : []), + ...(turnKeys && selected + ? [ + { keys: [], run: () => revert(true), command: { id: "turn-revert-files", title: "Revert files too", keywords: ["rollback", "rewind", "turn"] } }, + ...(input.diff ? [] : [{ keys: ["esc"], run: () => setCursor(null), command: { id: "turn-clear", title: "Clear turn selection" } }]), + ] + : []), + ]; /** The prompt's right-click menu. */ const menuFor = (messageId: string) => { const turn = turns.find((candidate) => candidate.messageId === messageId); @@ -131,7 +134,7 @@ export function useTurns(input: { ] : []), ]; }; - return { selectedMessageId, commands, onKey, diffContext, select, menuFor }; + return { selectedMessageId, bindings, diffContext, select, menuFor }; } function messageOf(error: unknown): string { return error instanceof Error ? error.message : String(error); } diff --git a/test/app/app.test.tsx b/test/app/app.test.tsx index a35a6b4..023f157 100644 --- a/test/app/app.test.tsx +++ b/test/app/app.test.tsx @@ -60,6 +60,26 @@ describe("modes and hints", () => { }); }); +describe("keys falling through", () => { + test("in the details panel, navigation keys still work", async () => { + const app = await open(); + await app.press("l"); + await app.press("c"); + expect(app.frame()).toContain("What should the new thread do?"); + }); + + test("the composer's / menu takes the arrows and esc; esc again leaves the composer", async () => { + const app = await open(); + await app.press("i"); + await app.type("/"); + expect(app.hints()).toBe("↑/↓ move · tab or enter choose · esc close"); + await app.press("escape"); + expect(app.hints()).toStartWith("enter send"); + await app.press("escape"); + expect(app.hints()).toStartWith("j/k threads"); + }); +}); + describe("palette and pickers", () => { test("ctrl+k opens the palette, typing filters it, esc closes it", async () => { const app = await open(); @@ -79,6 +99,13 @@ describe("palette and pickers", () => { expect(app.frame()).toMatch(/New thread\s+c/); }); + test("palette entries for pending requests carry their keys", async () => { + const app = await open({ session: fakeSession({ projection: withApproval() }) }); + await app.press("k", { ctrl: true }); + await app.type("always allow"); + expect(app.frame()).toMatch(/Always allow this session\s+Y/); + }); + test("running a command from the palette", async () => { const app = await open(); await app.press("k", { ctrl: true }); diff --git a/test/hints.test.ts b/test/hints.test.ts deleted file mode 100644 index a1c25d8..0000000 --- a/test/hints.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { describe, expect, test } from "bun:test"; - -import { hintKey } from "../src/model/hints.ts"; - -describe("clickable key hints", () => { - test("single keys, shifted keys and ctrl chords", () => { - expect(hintKey("y approve", "nav")).toEqual({ name: "y", sequence: "y", shift: false, ctrl: false }); - expect(hintKey("Y always", "nav")).toEqual({ name: "y", sequence: "Y", shift: true, ctrl: false }); - expect(hintKey("ctrl+k commands", "nav")).toEqual({ name: "k", sequence: "\x0b", shift: false, ctrl: true }); - expect(hintKey("esc close", "palette")?.name).toBe("escape"); - expect(hintKey(". actions", "nav")?.name).toBe("."); - expect(hintKey("/ filter", "nav")?.name).toBe("/"); - }); - - test("choices of keys, ranges and sending chords stay text", () => { - expect(hintKey("j/k threads", "nav")).toBeNull(); - expect(hintKey("ctrl+n/p thread", "input")).toBeNull(); - expect(hintKey("1-9 pick", "nav")).toBeNull(); - expect(hintKey("alt+enter steer", "input")).toBeNull(); - expect(hintKey("alt+↑ edit queued", "input")).toBeNull(); - expect(hintKey("shift+enter or \\ newline", "input")).toBeNull(); - expect(hintKey("enter send", "input")).toBeNull(); - expect(hintKey("enter confirm", "confirm")?.name).toBe("return"); - }); -}); diff --git a/test/keymap.test.ts b/test/keymap.test.ts new file mode 100644 index 0000000..b882437 --- /dev/null +++ b/test/keymap.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, test } from "bun:test"; + +import { bindingFor, commandsFor, fromCommand, hintsFor, keyMatches, type Binding, type KeyLike } from "../src/model/keymap.ts"; + +const key = (name: string, extra: Partial = {}): KeyLike => ({ name, ctrl: false, meta: false, shift: false, sequence: name.length === 1 ? name : "", ...extra }); + +describe("keys as people write them", () => { + test("letters, shifted letters and chords", () => { + expect(keyMatches("y", key("y"))).toBe(true); + expect(keyMatches("y", key("y", { shift: true }))).toBe(false); + expect(keyMatches("Y", key("y", { shift: true }))).toBe(true); + expect(keyMatches("Y", key("y"))).toBe(false); + expect(keyMatches("ctrl+k", key("k", { ctrl: true }))).toBe(true); + expect(keyMatches("k", key("k", { ctrl: true }))).toBe(false); + expect(keyMatches("alt+enter", key("return", { meta: true }))).toBe(true); + expect(keyMatches("alt+↑", key("up", { meta: true }))).toBe(true); + expect(keyMatches("shift+enter", key("return", { shift: true }))).toBe(true); + expect(keyMatches("enter", key("return", { shift: true }))).toBe(false); + }); + + test("named keys and punctuation", () => { + expect(keyMatches("esc", key("escape"))).toBe(true); + expect(keyMatches("enter", key("return"))).toBe(true); + expect(keyMatches("[", key("["))).toBe(true); + // ":" and "?" arrive shifted; that's how they're typed. + expect(keyMatches(":", key(":", { shift: true }))).toBe(true); + expect(keyMatches(".", key("."))).toBe(true); + expect(keyMatches("pagedown", key("pagedown"))).toBe(true); + }); + + test("ctrl+j also comes as a line feed", () => { + expect(keyMatches("ctrl+j", key("linefeed"))).toBe(true); + expect(keyMatches("j", key("linefeed"))).toBe(false); + }); +}); + +describe("bindings", () => { + const ran: string[] = []; + const bindings: Binding[] = [ + { keys: ["y"], run: () => ran.push("approve"), hint: "approve", command: { id: "approve", title: "Approve request" } }, + { keys: ["j", "↓"], label: "j/k", run: () => ran.push("down"), hint: "threads" }, + { keys: ["k", "↑"], run: () => ran.push("up") }, + { keys: [], label: "1-9", hint: "pick" }, + { keys: ["enter"], run: () => ran.push("send"), hint: "send", passive: true }, + { keys: ["y"], run: () => ran.push("shadowed") }, + ]; + + test("the first binding with the key runs; passive ones leave it to the input", () => { + bindingFor(bindings, key("y"))?.run?.(); + bindingFor(bindings, key("down"))?.run?.(); + expect(ran).toEqual(["approve", "down"]); + expect(bindingFor(bindings, key("return"))).toBeUndefined(); + expect(bindingFor(bindings, key("1"))).toBeUndefined(); + }); + + test("hints in order, clickable when they run something", () => { + const hints = hintsFor(bindings); + expect(hints.map((hint) => `${hint.key} ${hint.label}`)).toEqual(["y approve", "j/k threads", "1-9 pick", "enter send"]); + expect(hints.map((hint) => hint.run !== undefined)).toEqual([true, true, false, true]); + }); + + test("palette commands carry their key", () => { + expect(commandsFor(bindings).map(({ id, title, shortcut }) => ({ id, title, shortcut }))).toEqual([{ id: "approve", title: "Approve request", shortcut: "y" }]); + }); + + test("a palette command's shortcut becomes its key", () => { + const binding = fromCommand({ id: "archived", title: "Show archived threads", shortcut: "A", run: () => ran.push("archived") }); + bindingFor([binding], key("a", { shift: true }))?.run?.(); + expect(ran.at(-1)).toBe("archived"); + expect(commandsFor([binding])[0]?.shortcut).toBe("A"); + }); +});