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): a preferences registry, and settings that survive a restart (#231)

Abdurrahman Fakhrulc7071d5296c7
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 27531eb9..3c5e994b 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,7 +8,8 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Added**
-- `tui` a vertical tab rail, from the same layout the horizontal row uses
+- `tui` a preferences registry, and settings that survive a restart
+- `tui` a vertical tab rail, from the same layout the horizontal row uses (#230)
## 2026-11-01
diff --git a/scripts/mso-agent-cmd-settings.mjs b/scripts/mso-agent-cmd-settings.mjs
new file mode 100644
index 00000000..1f904e73
--- /dev/null
+++ b/scripts/mso-agent-cmd-settings.mjs
@@ -0,0 +1,87 @@
+import process from "node:process";
+import { createPrinter } from "./mso-agent-print.mjs";
+import {
+ SETTINGS,
+ defaultSettingsPath,
+ formatSettingsTable,
+ getSettingWarnings,
+ getSettings,
+ resetSettings,
+ resolveSetting,
+ saveSettings,
+} from "./mso-agent-settings.mjs";
+
+export async function handleSettingsCommand(ctx, args = []) {
+ const { session, C: colors = {} } = ctx;
+ const { print, printBlock } = createPrinter(ctx);
+ const sub = String(args[0] || "").toLowerCase().trim();
+ const filePath = defaultSettingsPath();
+ const width = Number(ctx.width || process.stdout?.columns) || 80;
+
+ if (sub === "reset") {
+ const settings = resetSettings({ path: filePath });
+ if (session) {
+ if (settings.pane) session.paneKind = settings.pane;
+ if (settings.statusbar) session.statusBar = settings.statusbar === "on";
+ }
+ print(`reset settings to defaults from ${filePath}`);
+ printBlock(formatSettingsTable(SETTINGS, settings, { colors, width }));
+ return "handled";
+ }
+
+ if (!args.length) {
+ const warnings = getSettingWarnings();
+ for (const w of warnings) print(`${colors.warn || ""}warning:${colors.reset || ""} ${w}`);
+ print(`config: ${filePath}`);
+ printBlock(formatSettingsTable(SETTINGS, getSettings(), { colors, width }));
+ return "handled";
+ }
+
+ const resolved = resolveSetting(SETTINGS, sub);
+ if (resolved?.status === "ambiguous") {
+ const candidates = resolved.ambiguous.map((e) => e.key).join(", ");
+ print(`${colors.warn || ""}ambiguous setting "${args[0]}": matches [${candidates}]${colors.reset || ""}`);
+ return "handled";
+ }
+
+ if (!resolved || !resolved.entry) {
+ print(`${colors.warn || ""}unknown setting "${args[0]}"${colors.reset || ""}`);
+ return "handled";
+ }
+
+ const entry = resolved.entry;
+ if (args.length === 1) {
+ const current = getSettings()[entry.key] ?? entry.default;
+ const allowed = entry.values ? ` (options: ${entry.values.join(", ")})` : "";
+ print(`${entry.key} = ${current}${allowed}: ${entry.description}`);
+ return "handled";
+ }
+
+ const requestedValue = String(args[1]).toLowerCase().trim();
+ if (entry.values && !entry.values.includes(requestedValue)) {
+ print(
+ `${colors.warn || ""}invalid value "${args[1]}" for ${entry.key}; valid options: ${entry.values.join(", ")}${colors.reset || ""}`
+ );
+ return "handled";
+ }
+
+ saveSettings({ [entry.key]: requestedValue }, { path: filePath });
+
+ // Apply to running session if present
+ if (session) {
+ if (entry.key === "pane") session.paneKind = requestedValue;
+ if (entry.key === "statusbar") session.statusBar = requestedValue === "on";
+ }
+
+ print(`${colors.cyan || ""}setting ${entry.key} = ${requestedValue}${colors.reset || ""}`);
+ return "handled";
+}
+
+// Applied once at session start, before the first frame. Without this the registry only stores
+// preferences: a value saved in one run would never take effect in the next, which makes every entry
+// look like a switch that does nothing.
+export function applySettings(session, settings = getSettings()) {
+ if (!session || !settings) return;
+ if (settings.pane) session.paneKind = settings.pane;
+ if (settings.statusbar) session.statusBar = settings.statusbar === "on";
+}
diff --git a/scripts/mso-agent-commands.mjs b/scripts/mso-agent-commands.mjs
index eccf06c1..f096582f 100644
--- a/scripts/mso-agent-commands.mjs
+++ b/scripts/mso-agent-commands.mjs
@@ -19,6 +19,7 @@ import { handleInspectCommand } from "./mso-agent-cmd-inspect.mjs";
import { handleSessionCommand } from "./mso-agent-cmd-session.mjs";
import { handleJobsCommand } from "./mso-agent-jobs.mjs";
import { handleTerminalCommand } from "./mso-agent-cmd-terminal.mjs";
+import { handleSettingsCommand } from "./mso-agent-cmd-settings.mjs";
import { createPrinter } from "./mso-agent-print.mjs";
export { SHARE_UNAVAILABLE_MESSAGE, buildExportArgv };
@@ -105,6 +106,7 @@ export async function handleSlash(rl, line, session, { runTurn, runSubagent }) {
if (cmd === "/jobs") return handleJobsCommand(ctx, args);
if (cmd === "/terminal" || cmd === "/term") return handleTerminalCommand(ctx, args);
+ if (cmd === "/settings" || cmd === "/setting") return handleSettingsCommand(ctx, args);
switch (cmd) {
case "/help":
diff --git a/scripts/mso-agent-help.mjs b/scripts/mso-agent-help.mjs
index 472591d6..7e2ff52e 100644
--- a/scripts/mso-agent-help.mjs
+++ b/scripts/mso-agent-help.mjs
@@ -18,6 +18,7 @@ export const HELP_LINES = [
" /todos [--all] show session checklist from todo_write",
" /pane [kind] cycle or set side pane (todos, diff, files, off)",
" /keybind [sub] view keybindings (sub: reset, conflicts)",
+ " /settings [key] [val] view or set TUI preferences (sub: reset)",
" /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-settings.mjs b/scripts/mso-agent-settings.mjs
new file mode 100644
index 00000000..48adf624
--- /dev/null
+++ b/scripts/mso-agent-settings.mjs
@@ -0,0 +1,204 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import {
+ defaultKeybindsPath,
+ defaultKeybinds,
+ resolveKeybind,
+ detectConflicts,
+ loadKeybinds,
+} from "./mso-agent-keybinds.mjs";
+
+// Preferences registry: non-keybind TUI preferences with live behavior today.
+// Evaluated candidates without active consumers are omitted to avoid phantom settings.
+export const SETTINGS = [
+ {
+ category: "Session", key: "pane", path: "session.pane",
+ description: "Side pane content to display", default: "off",
+ values: ["todos", "diff", "files", "mcp", "context", "off"],
+ keywords: ["sidebar", "panel", "paneKind"],
+ },
+ {
+ category: "Session", key: "statusbar", path: "session.status_bar",
+ description: "Dynamic status bar at bottom of prompt", default: "on",
+ values: ["on", "off"], keywords: ["status", "bar", "statusbar"],
+ },
+];
+
+let cachedState = null;
+const readTextFile = /** @type {(p: string, enc?: string) => string} */ ((p, enc = "utf8") => fs.readFileSync(p, enc));
+const writeTextFile = (p, data) => {
+ fs.mkdirSync(path.dirname(p), { recursive: true });
+ fs.writeFileSync(p, data, "utf8");
+};
+
+export function defaultSettingsPath() {
+ return path.join(os.homedir(), ".mso", "settings.json");
+}
+
+export function defaultSettings() {
+ const result = {};
+ for (const entry of SETTINGS) result[entry.key] = entry.default;
+ return result;
+}
+
+function settleSettings(resolved, warnings, filePath, raw) {
+ cachedState = { settings: { ...resolved }, warnings, path: filePath, raw };
+ const out = { ...resolved };
+ Object.defineProperty(out, "settings", { value: { ...resolved }, enumerable: false, writable: true });
+ Object.defineProperty(out, "warnings", { value: warnings, enumerable: false, writable: true });
+ Object.defineProperty(out, "raw", { value: raw, enumerable: false, writable: true });
+ return out;
+}
+
+export function loadSettings({ path: filePath = defaultSettingsPath(), readFile = readTextFile } = {}) {
+ const defaults = defaultSettings(), warnings = [];
+ let raw = "";
+ try {
+ raw = readFile(filePath, "utf8");
+ } catch {
+ return settleSettings(defaults, warnings, filePath, {});
+ }
+ if (!raw || !raw.trim()) return settleSettings(defaults, warnings, filePath, {});
+
+ let parsed = null;
+ try {
+ parsed = JSON.parse(raw);
+ } catch {
+ warnings.push(`malformed JSON in ${filePath}`);
+ return settleSettings(defaults, warnings, filePath, {});
+ }
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
+ warnings.push(`settings config must be an object in ${filePath}`);
+ return settleSettings(defaults, warnings, filePath, {});
+ }
+
+ // Preserve unknown keys from newer versions while applying known settings
+ const resolved = { ...parsed, ...defaults };
+ for (const entry of SETTINGS) {
+ const val = parsed[entry.key] ?? parsed[entry.path];
+ if (val !== undefined) {
+ if (entry.values && !entry.values.includes(val)) {
+ warnings.push(`invalid value "${val}" for ${entry.key}, falling back to default "${entry.default}"`);
+ resolved[entry.key] = entry.default;
+ } else {
+ resolved[entry.key] = val;
+ }
+ }
+ }
+ return settleSettings(resolved, warnings, filePath, parsed);
+}
+
+export function getSettings() {
+ if (!cachedState) loadSettings();
+ return cachedState.settings;
+}
+
+export function getSettingWarnings() {
+ if (!cachedState) loadSettings();
+ return cachedState.warnings;
+}
+
+export function saveSettings(updates = {}, {
+ path: filePath = defaultSettingsPath(),
+ readFile = readTextFile,
+ writeFile = writeTextFile,
+} = {}) {
+ let existing = {};
+ try {
+ const raw = readFile(filePath, "utf8");
+ if (raw && raw.trim()) {
+ const parsed = JSON.parse(raw);
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) existing = parsed;
+ }
+ } catch {
+ existing = {};
+ }
+ // Unknown keys from existing are preserved in merged
+ const merged = { ...existing, ...updates };
+ writeFile(filePath, JSON.stringify(merged, null, 2) + "\n");
+ if (cachedState && cachedState.path === filePath) {
+ cachedState.settings = { ...cachedState.settings, ...updates };
+ }
+ return merged;
+}
+
+export function resetSettings({ path: filePath = defaultSettingsPath(), unlinkSync = fs.unlinkSync } = {}) {
+ try { unlinkSync(filePath); } catch { /* ignore if absent */ }
+ return loadSettings({ path: filePath });
+}
+
+export function resolveSetting(entries, query) {
+ const q = String(query || "").trim().toLowerCase();
+ if (!q) return null;
+ const list = Array.isArray(entries) ? entries : [];
+
+ // Exact match on key, path, or alias keyword
+ const exact = list.find((e) =>
+ e.key.toLowerCase() === q || e.path.toLowerCase() === q ||
+ (Array.isArray(e.keywords) && e.keywords.map((k) => k.toLowerCase()).includes(q))
+ );
+ if (exact) return { ...exact, entry: exact, status: "exact", ambiguous: [] };
+
+ // Prefix match on key or path; refuse ambiguous match rather than guessing
+ const prefixMatches = list.filter((e) =>
+ e.key.toLowerCase().startsWith(q) || e.path.toLowerCase().startsWith(q)
+ );
+ if (prefixMatches.length === 1) {
+ const single = prefixMatches[0];
+ return { ...single, entry: single, status: "prefix", ambiguous: [] };
+ }
+ if (prefixMatches.length > 1) {
+ return { entry: null, status: "ambiguous", ambiguous: prefixMatches };
+ }
+ return null;
+}
+
+function stripAnsiText(str) {
+ return String(str || "").replace(/\x1b\[[0-9;]*m/g, "");
+}
+
+function fitLineWidth(raw, maxW) {
+ if (!maxW || maxW <= 0) return raw;
+ const visible = stripAnsiText(raw);
+ if (visible.length <= maxW) return raw;
+ if (visible === raw) return maxW > 1 ? `${raw.slice(0, maxW - 1)}…` : raw.slice(0, maxW);
+ return maxW > 1 ? `${visible.slice(0, maxW - 1)}…` : visible.slice(0, maxW);
+}
+
+export function formatSettingsTable(entries, current = {}, { colors = {}, width = 80 } = {}) {
+ const b = colors.bold || "", r = colors.reset || "", dim = colors.dim || "", c = colors.cyan || "";
+ const lines = [`${b}Settings${r}`];
+ const list = Array.isArray(entries) ? entries : [];
+ if (!list.length) return lines.join("\n");
+
+ const maxKey = Math.max(7, ...list.map((e) => e.key.length));
+ const maxVal = Math.max(5, ...list.map((e) => String(current[e.key] ?? e.default ?? "").length));
+ const padKey = Math.min(maxKey, Math.max(7, Math.floor((width - 10) * 0.3)));
+ const padVal = Math.min(maxVal, Math.max(5, Math.floor((width - 10) * 0.2)));
+
+ lines.push(fitLineWidth(`${dim}${"Setting".padEnd(padKey)} ${"Value".padEnd(padVal)} Description${r}`, width));
+ for (const entry of list) {
+ const val = String(current[entry.key] ?? entry.default ?? "");
+ const desc = entry.description || "";
+ const prefixNoColor = `${entry.key.padEnd(padKey)} ${val.padEnd(padVal)} `;
+ const avail = width - prefixNoColor.length;
+ let fittedDesc = desc;
+ if (avail > 0 && desc.length > avail) {
+ fittedDesc = avail > 1 ? `${desc.slice(0, avail - 1)}…` : desc.slice(0, avail);
+ } else if (avail <= 0) {
+ fittedDesc = "";
+ }
+ const row = `${c}${entry.key.padEnd(padKey)}${r} ${val.padEnd(padVal)} ${fittedDesc}`;
+ lines.push(fitLineWidth(row, width));
+ }
+ return lines.join("\n");
+}
+
+export {
+ defaultKeybindsPath,
+ defaultKeybinds,
+ resolveKeybind,
+ detectConflicts,
+ loadKeybinds,
+};
diff --git a/scripts/mso-agent-settings.test.ts b/scripts/mso-agent-settings.test.ts
new file mode 100644
index 00000000..abff383a
--- /dev/null
+++ b/scripts/mso-agent-settings.test.ts
@@ -0,0 +1,173 @@
+import { describe, expect, it } from "vitest";
+import {
+ SETTINGS,
+ defaultSettings,
+ detectConflicts,
+ formatSettingsTable,
+ loadKeybinds,
+ loadSettings,
+ resolveKeybind,
+ resolveSetting,
+ saveSettings,
+} from "./mso-agent-settings.mjs";
+import { handleSettingsCommand } from "./mso-agent-cmd-settings.mjs";
+
+describe("MSO Agent Settings Registry", () => {
+ it("1. a missing settings file returns defaults", () => {
+ const missing = loadSettings({
+ path: "/nonexistent/settings.json",
+ readFile: () => {
+ const err = new Error("ENOENT");
+ // @ts-expect-error test code property
+ err.code = "ENOENT";
+ throw err;
+ },
+ });
+ expect(missing).toEqual(defaultSettings());
+ expect(missing.pane).toBe("off");
+ expect(missing.statusbar).toBe("on");
+ });
+
+ it("2. a malformed file returns defaults and does not throw", () => {
+ let result: any = null;
+ expect(() => {
+ result = loadSettings({
+ path: "/corrupt/settings.json",
+ readFile: () => "{ invalid: json",
+ });
+ }).not.toThrow();
+ expect(result).toEqual(defaultSettings());
+ expect(result.warnings.length).toBeGreaterThan(0);
+ expect(result.warnings[0]).toContain("malformed JSON");
+ });
+
+ it("3. unknown keys written by a newer version survive a save", () => {
+ let written = "";
+ const seed = JSON.stringify({
+ future_feature_flag: true,
+ newer_schema_version: 42,
+ pane: "off",
+ });
+
+ const saved: Record<string, any> = saveSettings(
+ { pane: "todos" },
+ {
+ path: "/mock/settings.json",
+ readFile: () => seed,
+ writeFile: (_p, data) => { written = data; },
+ },
+ );
+
+ expect(saved.pane).toBe("todos");
+ expect(saved.future_feature_flag).toBe(true);
+ expect(saved.newer_schema_version).toBe(42);
+
+ const parsed = JSON.parse(written);
+ expect(parsed.future_feature_flag).toBe(true);
+ expect(parsed.newer_schema_version).toBe(42);
+ expect(parsed.pane).toBe("todos");
+ });
+
+ it("4. resolveSetting resolves exact and unique-prefix, and refuses ambiguous with a distinct result", () => {
+ const entries = [
+ { category: "Session", key: "pane", path: "session.pane", description: "Pane", default: "off", values: ["off", "todos"] },
+ { category: "Session", key: "statusbar", path: "session.status_bar", description: "Status", default: "on", values: ["on", "off"] },
+ { category: "Session", key: "statusmode", path: "session.status_mode", description: "Mode", default: "full", values: ["full", "compact"] },
+ ];
+
+ // Exact key match
+ const exact = resolveSetting(entries, "pane");
+ expect(exact?.status).toBe("exact");
+ expect(exact?.entry?.key).toBe("pane");
+
+ // Unique prefix match
+ const unique = resolveSetting(entries, "p");
+ expect(unique?.status).toBe("prefix");
+ expect(unique?.entry?.key).toBe("pane");
+
+ // Ambiguous prefix match refused with distinct result
+ const amb = resolveSetting(entries, "status");
+ expect(amb?.status).toBe("ambiguous");
+ expect(amb?.entry).toBeNull();
+ expect(amb?.ambiguous?.map((e: any) => e.key)).toEqual(["statusbar", "statusmode"]);
+
+ // Unknown setting returns null
+ expect(resolveSetting(entries, "nonexistent")).toBeNull();
+ });
+
+ it("5. the table renders within width and has no ANSI when colours are empty", () => {
+ const formatted = formatSettingsTable(SETTINGS, defaultSettings(), { width: 50 });
+ expect(formatted).not.toContain("\x1b");
+ const lines = formatted.split("\n");
+ for (const line of lines) {
+ expect(line.length).toBeLessThanOrEqual(50);
+ }
+ expect(formatted).toContain("Settings");
+ expect(formatted).toContain("pane");
+ expect(formatted).toContain("statusbar");
+ });
+
+ it("6. every declared entry has a non-empty description and a default that is within its own values when values is present", () => {
+ expect(SETTINGS.length).toBeGreaterThan(0);
+ for (const entry of SETTINGS) {
+ expect(entry.category).toBeTruthy();
+ expect(entry.key).toBeTruthy();
+ expect(entry.path).toBeTruthy();
+ expect(typeof entry.description).toBe("string");
+ expect(entry.description.trim().length).toBeGreaterThan(0);
+ if (entry.values) {
+ expect(Array.isArray(entry.values)).toBe(true);
+ expect(entry.values).toContain(entry.default);
+ }
+ }
+ });
+
+ it("existing keybind behaviour unchanged: loads hand-written file, resolves binds and detects conflicts", () => {
+ const rawKeymap = JSON.stringify({
+ interrupt: "ctrl+c",
+ clear_screen: "ctrl+k",
+ dismiss: "escape",
+ submit: "ctrl+c",
+ });
+
+ const loaded = loadKeybinds({
+ path: "/user/keybinds.json",
+ readFile: () => rawKeymap,
+ });
+
+ // Custom binding resolves correctly
+ expect(resolveKeybind({ ctrl: true, name: "k" }, loaded.bindings)).toBe("clear_screen");
+ // Standard binding resolves correctly
+ expect(resolveKeybind({ name: "escape" }, loaded.bindings)).toBe("dismiss");
+
+ // detectConflicts still detects the conflict between interrupt and submit on ctrl+c
+ const conflicts = detectConflicts(loaded.bindings);
+ expect(conflicts.length).toBe(1);
+ expect(conflicts[0].key).toBe("ctrl+c");
+ expect(conflicts[0].actions).toContain("interrupt");
+ expect(conflicts[0].actions).toContain("submit");
+ });
+
+ it("handleSettingsCommand updates session state and rejects invalid values", async () => {
+ const printed: string[] = [];
+ const session: any = { paneKind: "off", statusBar: true };
+ const ctx = {
+ session,
+ C: {},
+ write: (line: string) => printed.push(line),
+ };
+
+ // Valid update updates session
+ await handleSettingsCommand(ctx, ["pane", "todos"]);
+ expect(session.paneKind).toBe("todos");
+
+ // Invalid value rejected
+ await handleSettingsCommand(ctx, ["pane", "invalid_choice"]);
+ expect(session.paneKind).toBe("todos");
+ expect(printed.some((p) => p.includes("invalid value"))).toBe(true);
+
+ // Reset restores defaults
+ await handleSettingsCommand(ctx, ["reset"]);
+ expect(session.paneKind).toBe("off");
+ });
+});
diff --git a/scripts/mso-agent.mjs b/scripts/mso-agent.mjs
index b177b6b0..6b208c64 100644
--- a/scripts/mso-agent.mjs
+++ b/scripts/mso-agent.mjs
@@ -20,6 +20,7 @@ import { createQueue, dequeue } from "./mso-agent-queue.mjs";
import { pendingImageBlock } from "./mso-agent-image.mjs";
import { altScreenRequested, startAltScreen } from "./mso-agent-altscreen.mjs";
import { captureBanner } from "./mso-agent-banner-lines.mjs";
+import { applySettings } from "./mso-agent-cmd-settings.mjs";
import { visibleSessionRows } from "./mso-agent-sessions.mjs";
import { chromeLines } from "./mso-agent-chrome.mjs";
import { switchToSession } from "./mso-agent-cmd-session.mjs";
@@ -64,6 +65,7 @@ async function main() {
// Ephemeral queue: held only in memory for this TUI process and not persisted to server state.
queue: createQueue(),
};
+ applySettings(session); // Saved preferences, applied before the first frame.
let recentSessions = session.agentSession ? [session.agentSession] : [];
// Refreshed after a switch, not per keystroke: a tab row must not cost a network call per render.
const refreshSessions = () => { listCliSessions(20).then((rows) => { recentSessions = visibleSessionRows(rows); }).catch(() => {}); };