Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(tui): configurable keybinds, with the defaults kept byte-identical (#182)

Abdurrahman Fakhrul8a4791f63ed4
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 98944697..4c8559c8 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Added**
+- `tui` configurable keybinds, with the defaults kept byte-identical
- `agent` show the todo checklist in the TUI and in the status row (#179)
**Changed**
diff --git a/scripts/mso-agent-cmd-session.mjs b/scripts/mso-agent-cmd-session.mjs
index dc712592..c2fca9c9 100644
--- a/scripts/mso-agent-cmd-session.mjs
+++ b/scripts/mso-agent-cmd-session.mjs
@@ -9,6 +9,7 @@ import {
import { api, state } from "./mso-agent-api.mjs";
import { C } from "./mso-agent-runtime.mjs";
import { clearTodos, formatTodoBlock, latestTodos } from "./mso-agent-todos.mjs";
+import { handleKeybindCommand } from "./mso-agent-keybinds.mjs";
export async function handleTodos(ctx, args = []) {
const { C: colors = C } = ctx;
@@ -29,6 +30,9 @@ export async function handleSessionCommand(ctx, cmd, args) {
if (cmd === "/todos") {
return handleTodos(ctx, args);
}
+ if (cmd === "/keybind" || cmd === "/keybinds") {
+ return handleKeybindCommand(ctx, args);
+ }
const { rl, session, C: colors = C } = ctx;
switch (cmd) {
case "/new":
diff --git a/scripts/mso-agent-composer.mjs b/scripts/mso-agent-composer.mjs
index 8e293aed..29d8fbf0 100644
--- a/scripts/mso-agent-composer.mjs
+++ b/scripts/mso-agent-composer.mjs
@@ -2,6 +2,7 @@ import readline from "node:readline";
import { wordLeftIndex, wordRightIndex } from "./mso-agent-editing.mjs";
import process from "node:process";
import { resumeActiveActivity, suspendActiveActivity } from "./mso-agent-activity.mjs";
+import { getKeybinds, resolveKeybind } from "./mso-agent-keybinds.mjs";
import {
chars, clamp, CLEAR_LINE, CLEAR_SCREEN, completionWindow, CURSOR_DOWN, CURSOR_RIGHT, CURSOR_UP, eraseComposerRows, inputLayout, inputViewport, menuLines, reserveComposerRows, verticalCursor, width,
@@ -9,18 +10,14 @@ import {
export { completionWindow, inputLayout, inputViewport, verticalCursor } from "./mso-agent-composer-ui.mjs";
export class AgentComposer {
- constructor({ input = process.stdin, output = process.stdout, colors }) {
- this.input = input;
- this.output = output;
- this.C = colors;
- this.history = [];
- this.closed = false;
- this._cancelCurrent = null;
- this._notifyCurrent = null;
+ constructor({ input = process.stdin, output = process.stdout, colors, keybinds = null, onToggleStatusBar = null }) {
+ this.input = input; this.output = output; this.C = colors;
+ this.keybinds = keybinds; this.onToggleStatusBar = onToggleStatusBar;
+ this.history = []; this.closed = false; this._cancelCurrent = null; this._notifyCurrent = null;
readline.emitKeypressEvents(this.input);
}
- async question(prompt, { complete = null, history = true, onCancel = null, onTab = null, panelLabel = "commands & skills", selectOnEnter = false, escapeCancels = false, footer = null, separator = null } = {}) {
+ async question(prompt, { complete = null, history = true, onCancel = null, onTab = null, panelLabel = "commands & skills", selectOnEnter = false, escapeCancels = false, footer = null, separator = null, onToggleStatusBar = null } = {}) {
if (this.closed) return null;
const input = this.input, output = this.output, C = this.C;
return new Promise((resolve) => {
@@ -33,7 +30,7 @@ export class AgentComposer {
const matches = () => dismissed || !complete ? [] : complete(value) || [];
// Reserve physical rows only when the dropdown first grows. Selection changes then
- // redraw with cursor movement only — no LF/CRLF — so ↑/↓ never create scrollback rows.
+ // redraw with cursor movement only -- no LF/CRLF -- so ↑/↓ never create scrollback rows.
const reserve = (rows) => { reservedRows = reserveComposerRows(output, reservedRows, rows); };
const erase = () => eraseComposerRows(output, reservedRows);
const render = () => {
@@ -127,41 +124,30 @@ export class AgentComposer {
const onResize = () => { if (!settled) render(); };
const onKey = (str, key = {}) => {
const items = matches();
- if (key.ctrl && key.name === "c") {
- if (value) return edit("", 0);
- return cancel(true);
- }
- if (key.ctrl && key.name === "l") {
- output.write(CLEAR_SCREEN); reservedRows = 0; return render();
- }
- if (key.name === "escape") {
+ const action = resolveKeybind(key, this.keybinds || getKeybinds());
+ if (action === "interrupt") return value ? edit("", 0) : cancel(true);
+ if (action === "clear_screen") { output.write(CLEAR_SCREEN); reservedRows = 0; return render(); }
+ if (action === "dismiss") {
if (escapeCancels) return cancel(false);
dismissed = true; selected = 0; return render();
}
+ if (action === "toggle_status_bar") {
+ const toggle = onToggleStatusBar || this.onToggleStatusBar;
+ if (typeof toggle === "function") toggle();
+ return render();
+ }
if (items.length && (key.name === "up" || key.name === "down")) {
selected = (selected + (key.name === "up" ? -1 : 1) + items.length) % items.length;
return render();
}
- if (key.name === "tab" && items.length) {
- if (selectOnEnter) {
- const item = items[selected];
- return finish(item.value ?? item.text, true, item.label || item.text);
- }
- return apply(items[selected]);
- }
- if (key.name === "tab" && !value && typeof onTab === "function") {
- onTab();
- dismissed = false; selected = 0;
- return render();
+ // Tab is claimed only when there is something to complete, otherwise it falls through to
+ // the editing path exactly as it did before keybinds existed.
+ if (action === "complete" && (items.length || (!value && typeof onTab === "function"))) {
+ if (items.length) return selectOnEnter ? finish(items[selected].value ?? items[selected].text, true, items[selected].label || items[selected].text) : apply(items[selected]);
+ onTab(); dismissed = false; selected = 0; return render();
}
- if (key.name === "return" || key.name === "enter") {
- if (selectOnEnter && items[selected]) {
- const item = items[selected];
- return finish(item.value ?? item.text, true, item.label || item.text);
- }
- // Exact input wins even when another prefix match is highlighted first
- // (`/model` vs `/models`). Enter submits what the user actually typed;
- // Tab is the explicit "apply highlighted completion" key.
+ if (action === "submit") {
+ if (selectOnEnter && items[selected]) return finish(items[selected].value ?? items[selected].text, true, items[selected].label || items[selected].text);
if (items.some((item) => item?.text === value)) return finish(value);
if (items.length && items[selected]?.text) return apply(items[selected]);
return finish(value);
@@ -172,8 +158,8 @@ export class AgentComposer {
const moved = verticalCursor(value, cursor, layout.lineWidth, key.name === "up" ? -1 : 1, verticalColumn);
if (moved.moved) { cursor = moved.cursor; verticalColumn = moved.column; return render(); }
}
- if ((key.name === "up" && !items.length) || (key.ctrl && key.name === "p")) return historyMove(-1);
- if ((key.name === "down" && !items.length) || (key.ctrl && key.name === "n")) return historyMove(1);
+ if (action === "history_prev" || (key.name === "up" && !items.length)) return historyMove(-1);
+ if (action === "history_next" || (key.name === "down" && !items.length)) return historyMove(1);
const row = chars(value);
if (key.ctrl && key.name === "d") {
if (!value) return finish(null, false);
diff --git a/scripts/mso-agent-help.mjs b/scripts/mso-agent-help.mjs
index 6057cb55..37cdb5de 100644
--- a/scripts/mso-agent-help.mjs
+++ b/scripts/mso-agent-help.mjs
@@ -13,6 +13,7 @@ export const HELP_LINES = [
" /context alias for /status",
" /diff [ref] [--full] show diff viewer panel for artifact write action",
" /todos [--all] show session checklist from todo_write",
+ " /keybind [sub] view keybindings (sub: reset, conflicts)",
" /compact force context compaction and archive history",
" /statusbar [on|off] toggle compact dynamic status line",
" /reasoning [on|off] toggle per-turn reasoning token metrics (/reasoning on|off)",
diff --git a/scripts/mso-agent-keybinds.mjs b/scripts/mso-agent-keybinds.mjs
new file mode 100644
index 00000000..9dcb349b
--- /dev/null
+++ b/scripts/mso-agent-keybinds.mjs
@@ -0,0 +1,219 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+// Supported actions and human descriptions. Actions without reachable handlers are excluded.
+export const ACTIONS = {
+ interrupt: "Cancel input line or prompt",
+ clear_screen: "Clear terminal screen and repaint",
+ dismiss: "Dismiss completion menu or cancel",
+ complete: "Apply completion or cycle permissions",
+ history_prev: "Previous prompt in history",
+ history_next: "Next prompt in history",
+ submit: "Submit prompt line or selected item",
+ toggle_status_bar: "Toggle compact status bar",
+};
+
+export const READLINE_EDITING_KEYS = new Set([
+ "left", "right", "up", "down", "home", "end", "backspace", "delete",
+ "ctrl+a", "ctrl+b", "ctrl+d", "ctrl+e", "ctrl+f", "ctrl+k", "ctrl+u", "ctrl+w",
+ "alt+b", "alt+f", "ctrl+left", "ctrl+right",
+]);
+
+let cachedState = null;
+
+const readTextFile = /** @type {(p: string, enc?: string) => string} */ ((p, enc = "utf8") => fs.readFileSync(p, enc));
+
+// One fixed location, no env override: an extra knob needs a documented .env.example entry.
+export function defaultKeybindsPath() {
+ return path.join(os.homedir(), ".mso", "keybinds.json");
+}
+
+export function defaultKeybinds() {
+ return {
+ interrupt: "ctrl+c",
+ clear_screen: "ctrl+l",
+ dismiss: "escape",
+ complete: "tab",
+ history_prev: "ctrl+p",
+ history_next: "ctrl+n",
+ submit: "return",
+ };
+}
+
+export function normalizeKey(spec) {
+ if (!spec) return "";
+ if (typeof spec === "object") {
+ const parts = [];
+ if (spec.ctrl) parts.push("ctrl");
+ if (spec.meta) parts.push("alt");
+ if (spec.shift) parts.push("shift");
+ const name = String(spec.name || "").toLowerCase().trim();
+ if (!name) return "";
+ parts.push(name === "enter" ? "return" : name);
+ return parts.join("+");
+ }
+ const tokens = String(spec).toLowerCase().trim().replace(/\s+/g, "").split("+").filter(Boolean);
+ if (!tokens.length) return "";
+ const mods = [];
+ let key = "";
+ for (const token of tokens) {
+ if (token === "ctrl" || token === "control") mods.push("ctrl");
+ else if (token === "alt" || token === "meta") mods.push("alt");
+ else if (token === "shift") mods.push("shift");
+ else key = token === "enter" ? "return" : token;
+ }
+ return key ? [...mods, key].join("+") : "";
+}
+
+/**
+ * @param {any} key
+ * @param {Record<string, string>|null} [bindings]
+ * @returns {string|null}
+ */
+export function resolveKeybind(key, bindings = null) {
+ const norm = normalizeKey(key);
+ if (!norm) return null;
+ const active = bindings || getKeybinds();
+ for (const [action, boundKey] of Object.entries(active)) {
+ if (normalizeKey(boundKey) === norm) return action;
+ }
+ return null;
+}
+
+export function detectConflicts(bindings = {}) {
+ const byKey = new Map();
+ for (const [action, rawKey] of Object.entries(bindings)) {
+ const key = normalizeKey(rawKey);
+ if (!key) continue;
+ if (!byKey.has(key)) byKey.set(key, []);
+ byKey.get(key).push(action);
+ }
+ const conflicts = [];
+ for (const [key, actions] of byKey.entries()) {
+ if (actions.length > 1) {
+ conflicts.push({ key, actions, action1: actions[0], action2: actions[1] });
+ }
+ }
+ return conflicts;
+}
+
+function settle(bindings, warnings, filePath) {
+ cachedState = { bindings: { ...bindings }, warnings, path: filePath };
+ return { bindings: { ...bindings }, warnings };
+}
+
+/**
+ * The encoding is always utf8, so callers and tests never have to satisfy fs.readFileSync's
+ * Buffer overload.
+ * @param {{ path?: string, readFile?: (p: string, enc?: string) => string }} [options]
+ * @returns {{ bindings: Record<string, string>, warnings: string[] }}
+ */
+export function loadKeybinds({ path: filePath = defaultKeybindsPath(), readFile = readTextFile } = {}) {
+ const defaults = defaultKeybinds();
+ const warnings = [];
+ let raw = "";
+ try {
+ raw = readFile(filePath, "utf8");
+ } catch {
+ return settle(defaults, [], filePath);
+ }
+ let parsed = null;
+ if (!raw.trim()) return settle(defaults, [], filePath);
+ try {
+ parsed = JSON.parse(raw);
+ } catch {
+ warnings.push(`malformed JSON in ${filePath}`);
+ return settle(defaults, warnings, filePath);
+ }
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
+ warnings.push(`keybinds config must be an object in ${filePath}`);
+ return settle(defaults, warnings, filePath);
+ }
+
+ const entries = parsed.bindings && typeof parsed.bindings === "object" && !Array.isArray(parsed.bindings)
+ ? parsed.bindings : parsed;
+
+ const resolved = { ...defaults };
+ for (const [actionKey, keyValue] of Object.entries(entries)) {
+ const action = actionKey.replace(/-/g, "_");
+ if (!(action in ACTIONS)) {
+ warnings.push(`unknown action "${actionKey}" dropped`);
+ continue;
+ }
+ if (typeof keyValue !== "string") {
+ warnings.push(`invalid key format for action "${actionKey}"`);
+ continue;
+ }
+ const norm = normalizeKey(keyValue);
+ if (!norm) {
+ warnings.push(`invalid key "${keyValue}" for action "${actionKey}"`);
+ continue;
+ }
+ if (READLINE_EDITING_KEYS.has(norm)) {
+ warnings.push(`binding "${norm}" overrides line editing`);
+ }
+ resolved[action] = norm;
+ }
+
+ return settle(resolved, warnings, filePath);
+}
+
+export function getKeybinds() {
+ if (!cachedState) loadKeybinds();
+ return cachedState.bindings;
+}
+
+export function getKeybindWarnings() {
+ if (!cachedState) loadKeybinds();
+ return cachedState.warnings;
+}
+
+export function resetKeybinds({ path: filePath = defaultKeybindsPath(), unlinkSync = fs.unlinkSync } = {}) {
+ try { unlinkSync(filePath); } catch { /* ignore if absent */ }
+ return loadKeybinds({ path: filePath });
+}
+
+export function formatKeybindTable(bindings, { colors = {} } = {}) {
+ const b = colors.bold || "", r = colors.reset || "", dim = colors.dim || "", c = colors.cyan || "";
+ const lines = [`${b}Keybinds${r}`];
+ const entries = Object.entries(bindings);
+ const maxAction = Math.max(8, ...entries.map(([act]) => act.length));
+ const maxKey = Math.max(8, ...entries.map(([, key]) => String(key || "").length));
+ lines.push(`${dim}${"Action".padEnd(maxAction)} ${"Key".padEnd(maxKey)} Description${r}`);
+ for (const [action, key] of entries) {
+ const desc = ACTIONS[action] || "";
+ lines.push(`${c}${action.padEnd(maxAction)}${r} ${String(key || "").padEnd(maxKey)} ${desc}`);
+ }
+ return lines.join("\n");
+}
+
+export async function handleKeybindCommand(ctx, args = []) {
+ const { C: colors = {} } = ctx;
+ const sub = String(args[0] || "").toLowerCase().trim();
+ const filePath = defaultKeybindsPath();
+
+ if (sub === "reset") {
+ const { bindings } = resetKeybinds({ path: filePath });
+ console.log(`reset keybinds to defaults from ${filePath}`);
+ console.log(formatKeybindTable(bindings, { colors }));
+ return "handled";
+ }
+
+ if (sub === "conflicts") {
+ const conflicts = detectConflicts(getKeybinds());
+ if (!conflicts.length) {
+ console.log("no keybind conflicts detected");
+ } else {
+ console.log(`${colors.warn || ""}keybind conflicts detected:${colors.reset || ""}`);
+ for (const item of conflicts) console.log(` "${item.key}" bound to: ${item.actions.join(", ")}`);
+ }
+ return "handled";
+ }
+
+ const warnings = getKeybindWarnings();
+ for (const w of warnings) console.log(`${colors.warn || ""}warning:${colors.reset || ""} ${w}`);
+ console.log(`config: ${filePath}`);
+ console.log(formatKeybindTable(getKeybinds(), { colors }));
+ return "handled";
+}
diff --git a/scripts/mso-agent-keybinds.test.ts b/scripts/mso-agent-keybinds.test.ts
new file mode 100644
index 00000000..985948f0
--- /dev/null
+++ b/scripts/mso-agent-keybinds.test.ts
@@ -0,0 +1,130 @@
+import { describe, expect, it } from "vitest";
+import {
+ ACTIONS,
+ defaultKeybinds,
+ detectConflicts,
+ formatKeybindTable,
+ loadKeybinds,
+ normalizeKey,
+ resolveKeybind,
+} from "./mso-agent-keybinds.mjs";
+
+describe("MSO Agent Keybinds", () => {
+ it("defaults reproduce today's behaviour: resolving ctrl+c, ctrl+l, escape and tab yields the same actions", () => {
+ const defaults = defaultKeybinds();
+ expect(resolveKeybind({ ctrl: true, name: "c" }, defaults)).toBe("interrupt");
+ expect(resolveKeybind({ ctrl: true, name: "l" }, defaults)).toBe("clear_screen");
+ expect(resolveKeybind({ name: "escape" }, defaults)).toBe("dismiss");
+ expect(resolveKeybind({ name: "tab" }, defaults)).toBe("complete");
+ expect(resolveKeybind({ ctrl: true, name: "p" }, defaults)).toBe("history_prev");
+ expect(resolveKeybind({ ctrl: true, name: "n" }, defaults)).toBe("history_next");
+ expect(resolveKeybind({ name: "return" }, defaults)).toBe("submit");
+ expect(resolveKeybind({ name: "enter" }, defaults)).toBe("submit");
+ });
+
+ it("an empty or missing config file yields defaults and no warnings", () => {
+ const missing = loadKeybinds({
+ path: "/nonexistent/keybinds.json",
+ readFile: () => {
+ const err = new Error("ENOENT");
+ // @ts-expect-error test code property
+ err.code = "ENOENT";
+ throw err;
+ },
+ });
+ expect(missing.bindings).toEqual(defaultKeybinds());
+ expect(missing.warnings).toEqual([]);
+
+ const empty = loadKeybinds({
+ path: "/empty/keybinds.json",
+ readFile: () => "",
+ });
+ expect(empty.bindings).toEqual(defaultKeybinds());
+ expect(empty.warnings).toEqual([]);
+
+ const emptyObj = loadKeybinds({
+ path: "/empty-obj/keybinds.json",
+ readFile: () => "{}",
+ });
+ expect(emptyObj.bindings).toEqual(defaultKeybinds());
+ expect(emptyObj.warnings).toEqual([]);
+ });
+
+ it("a malformed JSON file yields defaults and a warning, and does not throw", () => {
+ const malformed = loadKeybinds({
+ path: "/bad/keybinds.json",
+ readFile: () => "{ not valid json",
+ });
+ expect(malformed.bindings).toEqual(defaultKeybinds());
+ expect(malformed.warnings.length).toBeGreaterThan(0);
+ expect(malformed.warnings[0]).toContain("malformed JSON");
+ });
+
+ it("an unknown action name is dropped with a warning that names it", () => {
+ const result = loadKeybinds({
+ path: "/custom/keybinds.json",
+ readFile: () => JSON.stringify({
+ unknown_foo: "ctrl+t",
+ clear_screen: "ctrl+k",
+ }),
+ });
+ expect(result.bindings.clear_screen).toBe("ctrl+k");
+ expect(result.bindings.unknown_foo).toBeUndefined();
+ expect(result.warnings.some((w) => w.includes("unknown_foo"))).toBe(true);
+ });
+
+ it("two actions bound to the same key produce a conflict, and detectConflicts reports it", () => {
+ const conflicting = {
+ ...defaultKeybinds(),
+ clear_screen: "ctrl+c",
+ };
+ const conflicts = detectConflicts(conflicting);
+ expect(conflicts.length).toBe(1);
+ expect(conflicts[0].key).toBe("ctrl+c");
+ expect(conflicts[0].actions).toContain("interrupt");
+ expect(conflicts[0].actions).toContain("clear_screen");
+ });
+
+ it("a user binding overrides a default for that key only, leaving other defaults intact", () => {
+ const defaults = defaultKeybinds();
+ const result = loadKeybinds({
+ path: "/user/keybinds.json",
+ readFile: () => JSON.stringify({
+ clear_screen: "ctrl+k",
+ }),
+ });
+ expect(result.bindings.clear_screen).toBe("ctrl+k");
+ expect(result.bindings.interrupt).toBe(defaults.interrupt);
+ expect(result.bindings.dismiss).toBe(defaults.dismiss);
+ expect(result.bindings.complete).toBe(defaults.complete);
+ expect(result.bindings.history_prev).toBe(defaults.history_prev);
+ expect(result.bindings.history_next).toBe(defaults.history_next);
+ expect(result.bindings.submit).toBe(defaults.submit);
+ });
+
+ it("formatKeybindTable shows every resolved binding and no ANSI codes when no palette is passed", () => {
+ const defaults = defaultKeybinds();
+ const formatted = formatKeybindTable(defaults);
+ expect(formatted).not.toContain("\x1b");
+ for (const [action, key] of Object.entries(defaults)) {
+ expect(formatted).toContain(action);
+ expect(formatted).toContain(key);
+ expect(formatted).toContain(ACTIONS[action as keyof typeof ACTIONS]);
+ }
+ });
+
+ it("normalizes keys and warns when overriding readline editing keys", () => {
+ expect(normalizeKey("Ctrl + C")).toBe("ctrl+c");
+ expect(normalizeKey("ALT+B")).toBe("alt+b");
+ expect(normalizeKey({ ctrl: true, name: "c" })).toBe("ctrl+c");
+
+ const result = loadKeybinds({
+ path: "/override/keybinds.json",
+ readFile: () => JSON.stringify({
+ toggle_status_bar: "ctrl+a",
+ }),
+ });
+ expect((result.bindings as Record<string, string>).toggle_status_bar).toBe("ctrl+a");
+ expect(result.warnings.some((w) => w.includes("overrides line editing"))).toBe(true);
+ });
+});
diff --git a/scripts/mso-agent.mjs b/scripts/mso-agent.mjs
index 81e2ada0..1974702c 100644
--- a/scripts/mso-agent.mjs
+++ b/scripts/mso-agent.mjs
@@ -81,7 +81,7 @@ async function main() {
// Ephemeral queue: held only in memory for this TUI process and not persisted to server state.
queue: createQueue(),
};
- const rl = new AgentComposer({ input: process.stdin, output: process.stdout, colors: C }); syncPromptHistory(rl, session);
+ const rl = new AgentComposer({ input: process.stdin, output: process.stdout, colors: C, onToggleStatusBar: () => { session.statusBar = !session.statusBar; } }); syncPromptHistory(rl, session);
let inboundRequestQueued = false;
const localBridge = new LocalAgentBridge({
session,