xonecas.io
64875
Mc

mini-coder / commit 2e78982

feat: persist global user settings

xonecas2026-04-06 2e789826cffe5d796eda63fefea9a839641835e1 parent 1bd4ec0

7 files changed

TODO.md+2−3
@@ -1,8 +1,8 @@
11 # TODO
22
3-Keep this always update so work can continue accross sessions.
3+Keep this always updated so work can continue across sessions.
44 Don't keep completed items bloating the file.
5-Keep the file strucured and minimal.
5+Keep the file structured and minimal.
66 The spec.md and code are the sources of truth, not this file, don't assume anything because it's documented here.
77
88 ## Bugs — from code review
@@ -46,7 +46,6 @@ The spec.md and code are the sources of truth, not this file, don't assume anyth
4646
4747 ## Future ideas
4848
49-- [ ] User preferences persistence (model, effort) — not in spec, currently resets to defaults on launch
5049 - [ ] Session list preview — show first user message snippet in `/session` selector
5150 - [ ] Divider theme plugin — customizable divider animations (scanning pulse, breathing, flowing dots, wave)
5251 - [ ] Backward-compatibility and migration policy for 1.0 (session/app data versioning, explicit migration strategy)
spec.md+48−18
@@ -494,7 +494,7 @@ Scrollable area that shows the full conversation history. Stick-to-bottom by def
494494 Message types and their rendering:
495495
496496 - **User messages**: displayed as plain text with a subtle background color to distinguish them from agent responses. No prefix or role indicator.
497-- **Assistant messages**: streamed markdown rendered via cel-tui's `Markdown` component on the default background. Thinking/reasoning content is collapsible (shown by default, toggled with `/reasoning`).
497+- **Assistant messages**: streamed markdown rendered via cel-tui's `Markdown` component on the default background. Thinking/reasoning content is collapsible (shown or hidden according to the user's persisted `/reasoning` preference; defaults to shown when no setting exists).
498498 - **Tool calls — shell**: rendered with a left border (`│`) and dimmed foreground. Shows the command (`$ command`) and the tool output. When `/verbose` is off, shell output is previewed as the first 20 lines followed by `And X lines more` when additional lines exist. When `/verbose` is on, the shell block expands to the full stored tool result. Exit code display is intended but not implemented yet.
499499 - **Tool calls — edit**: rendered with a left border (`│`) and dimmed foreground. Shows the file path and a unified diff of the change (added lines in green, removed in red). When `/verbose` is off, the diff preview shows the first 20 diff lines followed by `And X lines more` when additional lines exist. When `/verbose` is on, the diff expands to the full stored tool result. Uses the `diff` package (`structuredPatch`) for line-level diffing.
500500 - **Tool calls — plugin tools**: rendered with a left border, prefixed with plugin/tool name.
@@ -529,19 +529,19 @@ Supports:
529529
530530 ### Commands
531531
532-| Command | Description |
533-| ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
534-| `/model` | Interactive model selector (provider + model + effort). Switching models mid-session is allowed — pi-ai's context is model-agnostic. The `readImage` tool is re-evaluated (added/removed based on the new model's capabilities). The status bar updates immediately. The session record's `model` field is not updated (it reflects the initial choice). |
535-| `/session` | Interactive session manager (list, resume). Sessions scoped to CWD. |
536-| `/new` | Start a new session. Clears conversation, resets cost/token counters. |
537-| `/fork` | Fork the current conversation into a new session. Copies the full message history, continues from here independently. The original session is preserved. |
538-| `/undo` | Remove the last turn from conversation history (the user message and all assistant/tool messages that followed). Context-only — does not revert filesystem changes. |
539-| `/reasoning` | Toggle display of model thinking/reasoning content in the log. Reasoning is shown by default. |
540-| `/verbose` | Toggle full shell-output and edit-diff display in the UI. When off, those tool blocks show a concise preview (first 20 lines plus `And X lines more` when applicable). When on, they expand to the full stored tool result. Verbose mode is off by default. |
541-| `/login` | Interactive OAuth login. Shows a selector with available OAuth providers and their login status (logged in / not logged in). Selecting a provider starts the browser-based OAuth flow. Uses pi-ai's OAuth registry. Credentials are persisted to the app data directory and used for provider discovery on subsequent launches. |
542-| `/logout` | Interactive OAuth logout. Shows a selector with logged-in OAuth providers. Selecting one clears its saved credentials. |
543-| `/effort` | Interactive effort selector. Shows the four reasoning levels (`low`, `med`, `high`, `xhigh`) with the current level highlighted. Updates the status bar immediately. Does not update the session record's `effort` field (it reflects the initial choice, like `/model`). |
544-| `/help` | List available commands, including the current on/off state of `/reasoning` and `/verbose`, plus loaded AGENTS.md files, discovered skills, and active plugins. |
532+| Command | Description |
533+| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
534+| `/model` | Interactive model selector. Switching models mid-session is allowed — pi-ai's context is model-agnostic. The `readImage` tool is re-evaluated (added/removed based on the new model's capabilities). The status bar updates immediately, and the selected model is persisted immediately as the user's global default. The session record's `model` field is not updated (it reflects the initial choice). |
535+| `/session` | Interactive session manager (list, resume). Sessions scoped to CWD. |
536+| `/new` | Start a new session. Clears conversation, resets cost/token counters. |
537+| `/fork` | Fork the current conversation into a new session. Copies the full message history, continues from here independently. The original session is preserved. |
538+| `/undo` | Remove the last turn from conversation history (the user message and all assistant/tool messages that followed). Context-only — does not revert filesystem changes. |
539+| `/reasoning` | Toggle display of model thinking/reasoning content in the log. The new on/off state is persisted immediately and restored on launch. When no setting exists yet, reasoning defaults to shown. |
540+| `/verbose` | Toggle full shell-output and edit-diff display in the UI. When off, those tool blocks show a concise preview (first 20 lines plus `And X lines more` when applicable). When on, they expand to the full stored tool result. The new on/off state is persisted immediately and restored on launch. When no setting exists yet, verbose mode defaults to off. |
541+| `/login` | Interactive OAuth login. Shows a selector with available OAuth providers and their login status (logged in / not logged in). Selecting a provider starts the browser-based OAuth flow. Uses pi-ai's OAuth registry. Credentials are persisted to the app data directory and used for provider discovery on subsequent launches. |
542+| `/logout` | Interactive OAuth logout. Shows a selector with logged-in OAuth providers. Selecting one clears its saved credentials. |
543+| `/effort` | Interactive effort selector. Shows the four reasoning levels (`low`, `med`, `high`, `xhigh`) with the current level highlighted. Updates the status bar immediately, and the selected effort is persisted immediately as the user's global default. The session record's `effort` field is not updated (it reflects the initial choice, like `/model`). |
544+| `/help` | List available commands, including the current on/off state of `/reasoning` and `/verbose`, plus loaded AGENTS.md files, discovered skills, and active plugins. |
545545
546546 Commands are discoverable via `/` + Tab to interactively select/filter in the input area.
547547
@@ -550,12 +550,42 @@ Commands are discoverable via `/` + Tab to interactively select/filter in the in
550550 On launch, mini-coder:
551551
552552 1. Discovers providers (env vars, OAuth tokens).
553-2. Loads AGENTS.md files, skills, plugins.
554-3. Renders the UI with an empty conversation log and the status bar populated.
555-4. Starts a new session when the user sends a message (no 0-message sessions in the DB).
553+2. Loads user settings from `~/.config/mini-coder/settings.json`.
554+3. Selects the startup model, effort, reasoning visibility, and verbose mode from those settings when available.
555+ - `defaultModel`: if the saved provider/model is currently available, use it; otherwise fall back to the first available model for this launch.
556+ - `defaultEffort`: if valid, use it; otherwise fall back to `medium`.
557+ - `showReasoning`: if present, use it; otherwise fall back to `true`.
558+ - `verbose`: if present, use it; otherwise fall back to `false`.
559+4. Loads AGENTS.md files, skills, plugins.
560+5. Renders the UI with an empty conversation log and the status bar populated.
561+6. Starts a new session when the user sends a message (no 0-message sessions in the DB).
556562
557563 No banner or splash screen. The status bar already shows all the context the user needs.
558564
565+## User settings persistence
566+
567+mini-coder persists global user defaults in `~/.config/mini-coder/settings.json`.
568+
569+### Stored settings
570+
571+```json
572+{
573+ "defaultModel": "anthropic/claude-sonnet-4",
574+ "defaultEffort": "medium",
575+ "showReasoning": true,
576+ "verbose": false
577+}
578+```
579+
580+### Semantics
581+
582+- Settings are **global to the user**, not scoped per project, repository, or session.
583+- `/model`, `/effort`, `/reasoning`, and `/verbose` persist their new values immediately when changed.
584+- If `defaultModel` is saved but unavailable at startup (for example, missing credentials), mini-coder keeps the saved preference unchanged and uses a runtime fallback model for that launch.
585+- Invalid or missing settings file content is treated as "no saved settings" rather than a fatal startup error.
586+- `/new`, `/fork`, and `/session` do not modify global settings.
587+- Session records remain historical: their `model` and `effort` fields reflect the values active when that session was created, not the current global defaults.
588+
559589 ## Session persistence
560590
561591 Single SQLite file at `~/.config/mini-coder/mini-coder.db` via `bun:sqlite`.
@@ -596,7 +626,7 @@ CREATE INDEX idx_messages_session ON messages(session_id, turn);
596626
597627 **Turn number assignment**: when a user message is appended, its turn number is `MAX(turn) + 1` for the session (or 1 for the first message). All subsequent messages in the same agent loop (assistant responses, tool results) share that turn number. This is what makes `/undo` atomic — it deletes all messages with the highest turn.
598628
599-**Model/effort on the session**: stored at creation for display in `/session` list. The user can change models mid-session via `/model`; the session record reflects the initial choice, individual messages record their actual model via pi-ai's `AssistantMessage.model`.
629+**Model/effort on the session**: stored at creation for display in `/session` list. The user can change models and effort mid-session via `/model` and `/effort`; those commands update the current in-memory state and global user settings, but the session record still reflects the initial values for that session. Individual assistant messages record their actual model via pi-ai's `AssistantMessage.model`.
600630
601631 **Session truncation**: sessions are truncated per cwd to keep only the 20 most recently updated sessions (`updated_at DESC`), deleting older sessions and their messages via cascade.
602632
src/index.ts+62−28
@@ -45,6 +45,11 @@ import {
4545 type SessionStats,
4646 truncateSessions,
4747 } from "./session.ts";
48+import {
49+ loadSettings,
50+ resolveStartupSettings,
51+ type UserSettings,
52+} from "./settings.ts";
4853 import { discoverSkills, type Skill } from "./skills.ts";
4954 import { DEFAULT_THEME, mergeThemes, type Theme } from "./theme.ts";
5055 import {
@@ -72,14 +77,10 @@ const PLUGIN_CONFIG_PATH = join(DATA_DIR, "plugins.json");
7277 /** OAuth credentials file path. */
7378 const AUTH_PATH = join(DATA_DIR, "auth.json");
7479
75-/** Default effort level. */
76-const DEFAULT_EFFORT: ThinkingLevel = "medium";
77-
78-/** Whether reasoning blocks are shown by default. */
79-export const DEFAULT_SHOW_REASONING = true;
80+/** User settings file path. */
81+const SETTINGS_PATH = join(DATA_DIR, "settings.json");
8082
81-/** Whether full tool output is shown by default. */
82-export const DEFAULT_VERBOSE = false;
83+export { DEFAULT_SHOW_REASONING, DEFAULT_VERBOSE } from "./settings.ts";
8384
8485 /** Maximum sessions to keep per CWD. */
8586 const MAX_SESSIONS_PER_CWD = 20;
@@ -168,19 +169,41 @@ async function discoverProviders(): Promise<DiscoveryResult> {
168169 // ---------------------------------------------------------------------------
169170
170171 /**
171- * Select the first available model from discovered providers.
172+ * List all models from authenticated providers.
172173 *
173- * Returns the first model from the first provider that has models
174- * in the registry, or `null` if none are available.
174+ * @param availableProviders - Providers with usable credentials.
175+ * @returns Flat list of available models.
175176 */
176-function selectModel(
177+function listAvailableModels(
177178 availableProviders: Map<string, string>,
178-): Model<string> | null {
179+): Model<string>[] {
180+ const result: Model<string>[] = [];
179181 for (const provider of availableProviders.keys()) {
180182 const models = getModels(provider as KnownProvider);
181- if (models.length > 0) return models[0]!;
183+ for (const model of models) {
184+ result.push(model);
185+ }
182186 }
183- return null;
187+ return result;
188+}
189+
190+/**
191+ * Select a model by id from the available model list.
192+ *
193+ * @param models - Available models.
194+ * @param modelId - Preferred provider/model identifier.
195+ * @returns Matching model, or `null` when none is selected.
196+ */
197+function selectModel(
198+ models: readonly Model<string>[],
199+ modelId: string | null,
200+): Model<string> | null {
201+ if (modelId == null) {
202+ return null;
203+ }
204+ return (
205+ models.find((model) => `${model.provider}/${model.id}` === modelId) ?? null
206+ );
184207 }
185208
186209 // ---------------------------------------------------------------------------
@@ -294,6 +317,10 @@ export interface AppState {
294317 providers: Map<string, string>;
295318 /** OAuth credentials on disk. */
296319 oauthCredentials: Record<string, OAuthCredentials>;
320+ /** Loaded global user settings. */
321+ settings: UserSettings;
322+ /** Absolute path to the global settings file. */
323+ settingsPath: string;
297324 /** Working directory as entered by the user/shell (for display and tool execution). */
298325 cwd: string;
299326 /** Canonical working directory (for path identity and session scoping). */
@@ -323,8 +350,14 @@ export async function init(): Promise<AppState> {
323350 // Discover providers (env + OAuth)
324351 const { providers, oauthCredentials } = await discoverProviders();
325352
326- // Select first available model (null if no providers found)
327- const model = selectModel(providers);
353+ // Load user settings and resolve startup defaults
354+ const settings = loadSettings(SETTINGS_PATH);
355+ const availableModels = listAvailableModels(providers);
356+ const startup = resolveStartupSettings(
357+ settings,
358+ availableModels.map((model) => `${model.provider}/${model.id}`),
359+ );
360+ const model = selectModel(availableModels, startup.modelId);
328361
329362 // Gather git state
330363 const git = await getGitState(cwd);
@@ -341,7 +374,7 @@ export async function init(): Promise<AppState> {
341374
342375 // Open database and create session
343376 const db = openDatabase(DB_PATH);
344- const effort = DEFAULT_EFFORT;
377+ const effort = startup.effort;
345378 const modelLabel = model ? `${model.provider}/${model.id}` : undefined;
346379 const session = createSession(db, {
347380 cwd: canonicalCwd,
@@ -382,12 +415,14 @@ export async function init(): Promise<AppState> {
382415 git,
383416 providers,
384417 oauthCredentials,
418+ settings,
419+ settingsPath: SETTINGS_PATH,
385420 cwd,
386421 canonicalCwd,
387422 running: false,
388423 abortController: null,
389- showReasoning: DEFAULT_SHOW_REASONING,
390- verbose: DEFAULT_VERBOSE,
424+ showReasoning: startup.showReasoning,
425+ verbose: startup.verbose,
391426 };
392427 }
393428
@@ -426,14 +461,7 @@ export function buildToolList(state: AppState): {
426461 * for, suitable for the `/model` selector.
427462 */
428463 export function getAvailableModels(state: AppState): Model<string>[] {
429- const result: Model<string>[] = [];
430- for (const provider of state.providers.keys()) {
431- const models = getModels(provider as KnownProvider);
432- for (const model of models) {
433- result.push(model);
434- }
435- }
436- return result;
464+ return listAvailableModels(state.providers);
437465 }
438466
439467 /** Clean up resources on shutdown. */
@@ -448,7 +476,13 @@ export async function shutdown(state: AppState): Promise<void> {
448476 // OAuth helpers (re-exported for /login and /logout commands)
449477 // ---------------------------------------------------------------------------
450478
451-export { AUTH_PATH, DATA_DIR, loadOAuthCredentials, saveOAuthCredentials };
479+export {
480+ AUTH_PATH,
481+ DATA_DIR,
482+ loadOAuthCredentials,
483+ SETTINGS_PATH,
484+ saveOAuthCredentials,
485+};
452486
453487 // ---------------------------------------------------------------------------
454488 // Main
src/settings.test.ts+191−0
@@ -0,0 +1,191 @@
1+import { afterEach, describe, expect, test } from "bun:test";
2+import {
3+ existsSync,
4+ mkdtempSync,
5+ readFileSync,
6+ rmSync,
7+ writeFileSync,
8+} from "node:fs";
9+import { tmpdir } from "node:os";
10+import { join } from "node:path";
11+import {
12+ loadSettings,
13+ resolveStartupSettings,
14+ saveSettings,
15+ type UserSettings,
16+ updateSettings,
17+} from "./settings.ts";
18+
19+const tempDirs: string[] = [];
20+
21+function createTempDir(): string {
22+ const dir = mkdtempSync(join(tmpdir(), "mini-coder-settings-"));
23+ tempDirs.push(dir);
24+ return dir;
25+}
26+
27+afterEach(() => {
28+ for (const dir of tempDirs.splice(0)) {
29+ rmSync(dir, { recursive: true, force: true });
30+ }
31+});
32+
33+describe("settings", () => {
34+ test("loadSettings returns empty object when the file does not exist", () => {
35+ const dir = createTempDir();
36+ const path = join(dir, "settings.json");
37+
38+ expect(loadSettings(path)).toEqual({});
39+ });
40+
41+ test("loadSettings parses valid settings", () => {
42+ const dir = createTempDir();
43+ const path = join(dir, "settings.json");
44+ const settings: UserSettings = {
45+ defaultModel: "anthropic/claude-sonnet-4",
46+ defaultEffort: "high",
47+ showReasoning: false,
48+ verbose: true,
49+ };
50+ writeFileSync(path, JSON.stringify(settings), "utf-8");
51+
52+ expect(loadSettings(path)).toEqual(settings);
53+ });
54+
55+ test("loadSettings ignores invalid JSON", () => {
56+ const dir = createTempDir();
57+ const path = join(dir, "settings.json");
58+ writeFileSync(path, "{not json", "utf-8");
59+
60+ expect(loadSettings(path)).toEqual({});
61+ });
62+
63+ test("loadSettings keeps valid fields and drops invalid ones", () => {
64+ const dir = createTempDir();
65+ const path = join(dir, "settings.json");
66+ writeFileSync(
67+ path,
68+ JSON.stringify({
69+ defaultModel: "openai/gpt-5",
70+ defaultEffort: "turbo",
71+ showReasoning: "yes",
72+ verbose: false,
73+ }),
74+ "utf-8",
75+ );
76+
77+ expect(loadSettings(path)).toEqual({
78+ defaultModel: "openai/gpt-5",
79+ verbose: false,
80+ });
81+ });
82+
83+ test("saveSettings creates parent directories and writes the file", () => {
84+ const dir = createTempDir();
85+ const path = join(dir, "nested", "settings.json");
86+ const settings: UserSettings = {
87+ defaultModel: "anthropic/claude-sonnet-4",
88+ defaultEffort: "medium",
89+ showReasoning: true,
90+ verbose: false,
91+ };
92+
93+ saveSettings(path, settings);
94+
95+ expect(existsSync(path)).toBe(true);
96+ expect(JSON.parse(readFileSync(path, "utf-8"))).toEqual(settings);
97+ });
98+
99+ test("updateSettings merges a partial update with existing settings", () => {
100+ const dir = createTempDir();
101+ const path = join(dir, "settings.json");
102+ writeFileSync(
103+ path,
104+ JSON.stringify({
105+ defaultModel: "anthropic/claude-sonnet-4",
106+ defaultEffort: "medium",
107+ showReasoning: true,
108+ verbose: false,
109+ }),
110+ "utf-8",
111+ );
112+
113+ const updated = updateSettings(path, {
114+ defaultEffort: "xhigh",
115+ verbose: true,
116+ });
117+
118+ expect(updated).toEqual({
119+ defaultModel: "anthropic/claude-sonnet-4",
120+ defaultEffort: "xhigh",
121+ showReasoning: true,
122+ verbose: true,
123+ });
124+ expect(loadSettings(path)).toEqual(updated);
125+ });
126+
127+ test("resolveStartupSettings uses saved defaults when available", () => {
128+ const resolved = resolveStartupSettings(
129+ {
130+ defaultModel: "anthropic/claude-sonnet-4",
131+ defaultEffort: "high",
132+ showReasoning: false,
133+ verbose: true,
134+ },
135+ ["anthropic/claude-sonnet-4", "openai/gpt-5"],
136+ );
137+
138+ expect(resolved).toEqual({
139+ modelId: "anthropic/claude-sonnet-4",
140+ effort: "high",
141+ showReasoning: false,
142+ verbose: true,
143+ });
144+ });
145+
146+ test("resolveStartupSettings falls back to the first available model when the saved model is unavailable", () => {
147+ const resolved = resolveStartupSettings(
148+ {
149+ defaultModel: "openai/gpt-5",
150+ },
151+ ["anthropic/claude-sonnet-4", "google/gemini-2.5-pro"],
152+ );
153+
154+ expect(resolved).toEqual({
155+ modelId: "anthropic/claude-sonnet-4",
156+ effort: "medium",
157+ showReasoning: true,
158+ verbose: false,
159+ });
160+ });
161+
162+ test("resolveStartupSettings falls back to defaults when saved values are missing", () => {
163+ const resolved = resolveStartupSettings({}, ["anthropic/claude-sonnet-4"]);
164+
165+ expect(resolved).toEqual({
166+ modelId: "anthropic/claude-sonnet-4",
167+ effort: "medium",
168+ showReasoning: true,
169+ verbose: false,
170+ });
171+ });
172+
173+ test("resolveStartupSettings returns a null model when no models are available", () => {
174+ const resolved = resolveStartupSettings(
175+ {
176+ defaultModel: "anthropic/claude-sonnet-4",
177+ defaultEffort: "low",
178+ showReasoning: true,
179+ verbose: false,
180+ },
181+ [],
182+ );
183+
184+ expect(resolved).toEqual({
185+ modelId: null,
186+ effort: "low",
187+ showReasoning: true,
188+ verbose: false,
189+ });
190+ });
191+});
src/settings.ts+184−0
@@ -0,0 +1,184 @@
1+/**
2+ * User settings persistence and startup resolution.
3+ *
4+ * Stores global defaults such as model, effort, reasoning visibility,
5+ * and verbose tool output in a JSON file under the app data directory.
6+ *
7+ * @module
8+ */
9+
10+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
11+import { dirname } from "node:path";
12+import type { ThinkingLevel } from "@mariozechner/pi-ai";
13+
14+/** Default reasoning effort when no saved setting exists. */
15+export const DEFAULT_EFFORT: ThinkingLevel = "medium";
16+
17+/** Default reasoning visibility when no saved setting exists. */
18+export const DEFAULT_SHOW_REASONING = true;
19+
20+/** Default verbose tool rendering flag when no saved setting exists. */
21+export const DEFAULT_VERBOSE = false;
22+
23+/** Persisted global user settings. */
24+export interface UserSettings {
25+ /** Preferred provider/model identifier. */
26+ defaultModel?: string;
27+ /** Preferred reasoning effort. */
28+ defaultEffort?: ThinkingLevel;
29+ /** Whether reasoning blocks are shown in the UI. */
30+ showReasoning?: boolean;
31+ /** Whether full tool output is shown in the UI. */
32+ verbose?: boolean;
33+}
34+
35+/** Resolved startup settings after applying defaults and availability checks. */
36+export interface StartupSettings {
37+ /** Model to use for this launch, or `null` if none are available. */
38+ modelId: string | null;
39+ /** Effective reasoning effort. */
40+ effort: ThinkingLevel;
41+ /** Effective reasoning visibility. */
42+ showReasoning: boolean;
43+ /** Effective verbose flag. */
44+ verbose: boolean;
45+}
46+
47+const THINKING_LEVELS = new Set<ThinkingLevel>([
48+ "low",
49+ "medium",
50+ "high",
51+ "xhigh",
52+]);
53+
54+/**
55+ * Load and validate user settings from disk.
56+ *
57+ * Invalid or missing files are treated as empty settings.
58+ *
59+ * @param path - Absolute path to `settings.json`.
60+ * @returns The validated settings object.
61+ */
62+export function loadSettings(path: string): UserSettings {
63+ if (!existsSync(path)) {
64+ return {};
65+ }
66+
67+ try {
68+ const raw = JSON.parse(readFileSync(path, "utf-8")) as unknown;
69+ return sanitizeSettings(raw);
70+ } catch {
71+ return {};
72+ }
73+}
74+
75+/**
76+ * Save user settings to disk.
77+ *
78+ * Parent directories are created automatically. Only validated fields are
79+ * written to disk.
80+ *
81+ * @param path - Absolute path to `settings.json`.
82+ * @param settings - Settings to persist.
83+ * @returns The validated settings that were written.
84+ */
85+export function saveSettings(
86+ path: string,
87+ settings: UserSettings,
88+): UserSettings {
89+ const sanitized = sanitizeSettings(settings);
90+ mkdirSync(dirname(path), { recursive: true });
91+ writeFileSync(path, JSON.stringify(sanitized, null, 2), "utf-8");
92+ return sanitized;
93+}
94+
95+/**
96+ * Merge a partial settings update with the current file contents and persist it.
97+ *
98+ * Invalid fields in the update are ignored.
99+ *
100+ * @param path - Absolute path to `settings.json`.
101+ * @param update - Partial settings update to merge.
102+ * @returns The merged settings after persistence.
103+ */
104+export function updateSettings(
105+ path: string,
106+ update: Partial<UserSettings>,
107+): UserSettings {
108+ const current = loadSettings(path);
109+ const merged = { ...current, ...sanitizeSettings(update) };
110+ return saveSettings(path, merged);
111+}
112+
113+/**
114+ * Resolve the effective startup settings for the current launch.
115+ *
116+ * The saved preferred model is only used when it is currently available.
117+ * Otherwise the first available model is used for this launch, while the saved
118+ * preference remains unchanged on disk.
119+ *
120+ * @param settings - Saved user settings.
121+ * @param availableModelIds - Provider/model identifiers available this launch.
122+ * @returns Effective startup settings with fallbacks applied.
123+ */
124+export function resolveStartupSettings(
125+ settings: UserSettings,
126+ availableModelIds: readonly string[],
127+): StartupSettings {
128+ const preferredModel = settings.defaultModel;
129+ const modelId =
130+ preferredModel && availableModelIds.includes(preferredModel)
131+ ? preferredModel
132+ : (availableModelIds[0] ?? null);
133+
134+ return {
135+ modelId,
136+ effort: settings.defaultEffort ?? DEFAULT_EFFORT,
137+ showReasoning: settings.showReasoning ?? DEFAULT_SHOW_REASONING,
138+ verbose: settings.verbose ?? DEFAULT_VERBOSE,
139+ };
140+}
141+
142+/**
143+ * Validate and normalize a parsed settings object.
144+ *
145+ * Unknown or invalid fields are dropped.
146+ *
147+ * @param value - Parsed JSON value.
148+ * @returns Sanitized settings.
149+ */
150+function sanitizeSettings(value: unknown): UserSettings {
151+ if (value == null || typeof value !== "object" || Array.isArray(value)) {
152+ return {};
153+ }
154+
155+ const candidate = value as Record<string, unknown>;
156+ const settings: UserSettings = {};
157+
158+ if (typeof candidate.defaultModel === "string") {
159+ settings.defaultModel = candidate.defaultModel;
160+ }
161+ if (isThinkingLevel(candidate.defaultEffort)) {
162+ settings.defaultEffort = candidate.defaultEffort;
163+ }
164+ if (typeof candidate.showReasoning === "boolean") {
165+ settings.showReasoning = candidate.showReasoning;
166+ }
167+ if (typeof candidate.verbose === "boolean") {
168+ settings.verbose = candidate.verbose;
169+ }
170+
171+ return settings;
172+}
173+
174+/**
175+ * Check whether a value is a valid thinking level.
176+ *
177+ * @param value - Value to validate.
178+ * @returns `true` when the value is a supported thinking level.
179+ */
180+function isThinkingLevel(value: unknown): value is ThinkingLevel {
181+ return (
182+ typeof value === "string" && THINKING_LEVELS.has(value as ThinkingLevel)
183+ );
184+}
src/ui.test.ts+93−1
@@ -1,4 +1,7 @@
1-import { describe, expect, test } from "bun:test";
1+import { afterEach, describe, expect, test } from "bun:test";
2+import { mkdtempSync, rmSync } from "node:fs";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
25 import type { Node } from "@cel-tui/types";
36 import {
47 fauxAssistantMessage,
@@ -12,8 +15,11 @@ import {
1215 DEFAULT_VERBOSE,
1316 } from "./index.ts";
1417 import { createSession, loadMessages, openDatabase } from "./session.ts";
18+import { loadSettings } from "./settings.ts";
1519 import { DEFAULT_THEME, type Theme } from "./theme.ts";
1620 import {
21+ applyEffortSelection,
22+ applyModelSelection,
1723 buildConversationLog,
1824 buildHelpText,
1925 createInputController,
@@ -67,10 +73,19 @@ function findTextNode(node: Node | null, content: string): Node | null {
6773 return null;
6874 }
6975
76+const tempDirs: string[] = [];
77+
78+function createTempDir(): string {
79+ const dir = mkdtempSync(join(tmpdir(), "mini-coder-ui-test-"));
80+ tempDirs.push(dir);
81+ return dir;
82+}
83+
7084 function createTestState(): AppState {
7185 const db = openDatabase(":memory:");
7286 const cwd = "/tmp/mini-coder-ui-test";
7387 const session = createSession(db, { cwd });
88+ const settingsPath = join(createTempDir(), "settings.json");
7489 return {
7590 db,
7691 session,
@@ -85,6 +100,8 @@ function createTestState(): AppState {
85100 git: null,
86101 providers: new Map(),
87102 oauthCredentials: {},
103+ settings: {},
104+ settingsPath,
88105 cwd,
89106 canonicalCwd: cwd,
90107 running: false,
@@ -94,6 +111,12 @@ function createTestState(): AppState {
94111 };
95112 }
96113
114+afterEach(() => {
115+ for (const dir of tempDirs.splice(0)) {
116+ rmSync(dir, { recursive: true, force: true });
117+ }
118+});
119+
97120 async function waitFor(
98121 predicate: () => boolean,
99122 timeoutMs = 1_000,
@@ -114,6 +137,75 @@ describe("ui rendering", () => {
114137 expect(DEFAULT_VERBOSE).toBe(false);
115138 });
116139
140+ test("/reasoning toggles the UI state and persists it", () => {
141+ const state = createTestState();
142+
143+ try {
144+ expect(state.showReasoning).toBe(true);
145+
146+ handleInput("/reasoning", state);
147+
148+ expect(state.showReasoning).toBe(false);
149+ expect(state.settings.showReasoning).toBe(false);
150+ expect(loadSettings(state.settingsPath)).toEqual({
151+ showReasoning: false,
152+ });
153+ } finally {
154+ state.db.close();
155+ }
156+ });
157+
158+ test("/verbose toggles the UI state and persists it", () => {
159+ const state = createTestState();
160+
161+ try {
162+ expect(state.verbose).toBe(false);
163+
164+ handleInput("/verbose", state);
165+
166+ expect(state.verbose).toBe(true);
167+ expect(state.settings.verbose).toBe(true);
168+ expect(loadSettings(state.settingsPath)).toEqual({ verbose: true });
169+ } finally {
170+ state.db.close();
171+ }
172+ });
173+
174+ test("applyModelSelection updates the active model and persists it", () => {
175+ const faux = registerFauxProvider();
176+ const state = createTestState();
177+ const model = faux.getModel();
178+
179+ try {
180+ applyModelSelection(state, model);
181+
182+ expect(state.model).toBe(model);
183+ expect(state.settings.defaultModel).toBe(`${model.provider}/${model.id}`);
184+ expect(loadSettings(state.settingsPath)).toEqual({
185+ defaultModel: `${model.provider}/${model.id}`,
186+ });
187+ } finally {
188+ faux.unregister();
189+ state.db.close();
190+ }
191+ });
192+
193+ test("applyEffortSelection updates the active effort and persists it", () => {
194+ const state = createTestState();
195+
196+ try {
197+ applyEffortSelection(state, "xhigh");
198+
199+ expect(state.effort).toBe("xhigh");
200+ expect(state.settings.defaultEffort).toBe("xhigh");
201+ expect(loadSettings(state.settingsPath)).toEqual({
202+ defaultEffort: "xhigh",
203+ });
204+ } finally {
205+ state.db.close();
206+ }
207+ });
208+
117209 test("renderAssistantMessage keeps streamed markdown inside one top-level container", () => {
118210 const message = fauxAssistantMessage("First paragraph\n\nSecond paragraph");
119211
src/ui.ts+41−2
@@ -56,6 +56,7 @@ import {
5656 type UiMessage,
5757 undoLastTurn,
5858 } from "./session.ts";
59+import { updateSettings } from "./settings.ts";
5960 import type { Theme } from "./theme.ts";
6061
6162 // ---------------------------------------------------------------------------
@@ -1020,6 +1021,38 @@ export function renderInputArea(
10201021 // Command handlers
10211022 // ---------------------------------------------------------------------------
10221023
1024+/**
1025+ * Apply a model selection to the active state and persisted settings.
1026+ *
1027+ * @param state - Application state.
1028+ * @param model - Selected model.
1029+ */
1030+export function applyModelSelection(
1031+ state: AppState,
1032+ model: AppState["model"] & NonNullable<AppState["model"]>,
1033+): void {
1034+ state.model = model;
1035+ state.settings = updateSettings(state.settingsPath, {
1036+ defaultModel: `${model.provider}/${model.id}`,
1037+ });
1038+}
1039+
1040+/**
1041+ * Apply an effort selection to the active state and persisted settings.
1042+ *
1043+ * @param state - Application state.
1044+ * @param effort - Selected reasoning effort.
1045+ */
1046+export function applyEffortSelection(
1047+ state: AppState,
1048+ effort: ThinkingLevel,
1049+): void {
1050+ state.effort = effort;
1051+ state.settings = updateSettings(state.settingsPath, {
1052+ defaultEffort: effort,
1053+ });
1054+}
1055+
10231056 /** Handle the /model command: show interactive model selector. */
10241057 function handleModelCommand(state: AppState): void {
10251058 const models = getAvailableModels(state);
@@ -1051,7 +1084,7 @@ function handleModelCommand(state: AppState): void {
10511084 onSelect: (value) => {
10521085 const picked = models.find((m) => `${m.provider}/${m.id}` === value);
10531086 if (picked) {
1054- state.model = picked;
1087+ applyModelSelection(state, picked);
10551088 }
10561089 dismissOverlay();
10571090 },
@@ -1086,7 +1119,7 @@ function handleEffortCommand(state: AppState): void {
10861119 focused: true,
10871120 highlightColor: state.theme.accentText,
10881121 onSelect: (value) => {
1089- state.effort = value as ThinkingLevel;
1122+ applyEffortSelection(state, value as ThinkingLevel);
10901123 dismissOverlay();
10911124 },
10921125 onBlur: dismissOverlay,
@@ -1229,12 +1262,18 @@ function handleUndoCommand(state: AppState): void {
12291262 /** Handle the /reasoning command: toggle thinking display. */
12301263 function handleReasoningCommand(state: AppState): void {
12311264 state.showReasoning = !state.showReasoning;
1265+ state.settings = updateSettings(state.settingsPath, {
1266+ showReasoning: state.showReasoning,
1267+ });
12321268 cel.render();
12331269 }
12341270
12351271 /** Handle the /verbose command: toggle full output display. */
12361272 function handleVerboseCommand(state: AppState): void {
12371273 state.verbose = !state.verbose;
1274+ state.settings = updateSettings(state.settingsPath, {
1275+ verbose: state.verbose,
1276+ });
12381277 cel.render();
12391278 }