xonecas.io
64875
Mc

mini-coder / commit db5652f

feat: support repo-local settings overlays

xonecas2026-04-19 db5652fcfae7f882501258d49702c01d8dd4854d parent bd0263e

9 files changed

spec.md+45−33
@@ -147,7 +147,7 @@ Implementation details:
147147
148148 ### Configured MCP tools
149149
150-When `settings.json` includes `mcp.servers`, mini-coder keeps those Streamable HTTP MCP endpoints in runtime state, connects enabled ones when needed, and imports their advertised tools.
150+When the effective startup settings include `mcp.servers`, mini-coder keeps those Streamable HTTP MCP endpoints in runtime state, connects enabled ones when needed, and imports their advertised tools.
151151
152152 Implementation details:
153153
@@ -781,21 +781,21 @@ add tests for undo_
781781
782782 ### Commands
783783
784-| Command | Description …
785-| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- …
786-| `/model` | Interactive model selector. The list includes built-in models plus any custom OpenAI-compatible models discovered from `settings.json`. 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 …
787-| `/session` | Interactive session manager (list, resume). Sessions scoped to CWD. …
788-| `/new` | Start a new session. Clears conversation, resets cost/token counters. …
789-| `/fork` | Fork the current conversation into a new session. Copies the full message history, continues from here independently, and appends a UI-only `Forked session.` notice in the new session. The original session is preserved. …
790-| `/undo` | Remove the last conversational turn from history: the most recent user message and all assistant/tool messages that followed in that turn. Persisted UI messages are not part of turns and are not removed by `/undo`. Context-only — does not revert filesystem changes. …
791-| `/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. …
792-| `/verbose` | Toggle [verbose tool rendering](#verbose-tool-rendering) for shell previews/results, read previews/results, grep previews/results, edit previews, and edit errors. Successful edit results stay compact regardless of this setting. Todo tool results always render in full. …
793-| `/mcp` | Interactive MCP server selector. Lists configured MCP servers with their current on/off state. Selecting a server toggles it for future turns, persists the new on/off state immediately, and appends a UI-only notice with the exact tool delta, for example `Disabled MCP server "docs" (-3 tools).` Turning a server on reconnects it on demand; turning it off disconnects it. `/mcp` still does not add, remove, or reload server definitions. …
794-| `/todo` | Append the current session todo list to the conversation pane as a UI-only checklist block. The message is persisted with the session, excluded from model context, and does not create a session by itself when no session exists yet. …
795-| `/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. …
796-| `/logout` | Interactive OAuth logout. Shows a selector with logged-in OAuth providers. Selecting one clears its saved credentials. …
797-| `/effort` | Interactive effort selector. Shows the four reasoning levels (`low`, `medium`, `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`). …
798-| `/help` | List available commands, including the current on/off state of `/reasoning`, `/verbose`, and configured MCP servers, plus loaded AGENTS.md files and discovered skills. …
784+| Command | Description …
785+| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- …
786+| `/model` | Interactive model selector. The list includes built-in models plus any custom OpenAI-compatible models discovered from the loaded settings. 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 refl …
787+| `/session` | Interactive session manager (list, resume). Sessions scoped to CWD. …
788+| `/new` | Start a new session. Clears conversation, resets cost/token counters. …
789+| `/fork` | Fork the current conversation into a new session. Copies the full message history, continues from here independently, and appends a UI-only `Forked session.` notice in the new session. The original session is preserved. …
790+| `/undo` | Remove the last conversational turn from history: the most recent user message and all assistant/tool messages that followed in that turn. Persisted UI messages are not part of turns and are not removed by `/undo`. Context-only — does not revert filesystem changes. …
791+| `/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. …
792+| `/verbose` | Toggle [verbose tool rendering](#verbose-tool-rendering) for shell previews/results, read previews/results, grep previews/results, edit previews, and edit errors. Successful edit results stay compact regardless of this setting. Todo tool results always render in full. …
793+| `/mcp` | Interactive MCP server selector. Lists configured MCP servers with their current on/off state. Selecting a server toggles it for future turns and appends a UI-only notice with the exact tool delta, for example `Disabled MCP server "docs" (-3 tools).` Turning a server on reconnects it on demand; turning it off disconnects it. For globally configured servers, the new on/off state is persisted immediately. Repo-local server definitions loaded from `<git-root>/.mini-coder/settings.j …
794+| `/todo` | Append the current session todo list to the conversation pane as a UI-only checklist block. The message is persisted with the session, excluded from model context, and does not create a session by itself when no session exists yet. …
795+| `/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. …
796+| `/logout` | Interactive OAuth logout. Shows a selector with logged-in OAuth providers. Selecting one clears its saved credentials. …
797+| `/effort` | Interactive effort selector. Shows the four reasoning levels (`low`, `medium`, `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`). …
798+| `/help` | List available commands, including the current on/off state of `/reasoning`, `/verbose`, and configured MCP servers, plus loaded AGENTS.md files and discovered skills. …
799799
800800 Commands are discoverable when the input starts with `/`: pressing `Tab` in that state switches from file-path autocomplete to interactive command select/filter.
801801
@@ -857,38 +857,46 @@ This means headless one-shot runs appear in normal `/session` history for that w
857857 On launch, mini-coder:
858858
859859 1. Discovers built-in providers (env vars, OAuth tokens).
860-2. Loads user settings from `~/.config/mini-coder/settings.json`.
861-3. Discovers user-configured custom OpenAI-compatible providers from `settings.json`.
860+2. Loads global user settings from `~/.config/mini-coder/settings.json`.
861+3. If the current working directory is inside a git repo, loads `<git-root>/.mini-coder/settings.json` as a repo-local read-only overlay.
862+ - Missing or invalid content in either settings file is treated as "no settings from that file" rather than a fatal startup error.
863+ - Repo-local values win on collisions.
864+ - `customProviders` is merged by provider `name` instead of replacing the whole array. Same-name repo-local entries override global ones.
865+ - `mcp.servers` is merged by server `name` instead of replacing the whole array. Same-name repo-local entries override global ones.
866+4. Discovers user-configured custom OpenAI-compatible providers from the effective settings.
862867 - Each entry is queried at `${baseUrl}/models`.
863868 - Each returned model is added to the launch's available model list as `provider/model`, where `provider` is the configured custom provider name.
864- - Invalid entries are dropped while loading settings. Duplicate custom provider names keep the first entry.
869+ - Invalid entries are dropped while loading settings. Duplicate custom provider names within the same settings source keep the first entry.
865870 - If an endpoint is unreachable, returns a non-2xx response, or the custom provider name conflicts with an already-available built-in provider, startup continues and a warning is added to the UI log.
866-4. Loads user-configured MCP servers from `settings.json`.
871+5. Loads user-configured MCP servers from the effective settings.
867872 - Each entry must provide a `name` and Streamable HTTP endpoint `url`. It also stores an `enabled` flag; older entries that omit it default to enabled.
868- - Invalid entries are dropped while loading settings. Duplicate MCP server names keep the first entry.
873+ - Invalid entries are dropped while loading settings. Duplicate MCP server names within the same settings source keep the first entry.
869874 - Startup connects only servers whose `enabled` flag is on. Imported MCP tool names are exposed to the model as `<serverName>__<toolName>`.
870875 - Disabled servers stay listed in runtime state so `/mcp` can reconnect them on demand later in the same app run.
876+ - Servers whose effective definition comes from the repo-local overlay stay read-only. `/mcp` can toggle them during the current app run, but only globally configured servers persist new enabled states back to `~/.config/mini-coder/settings.json`.
871877 - If an enabled server URL is invalid, the endpoint is unreachable, or the server exposes no tools, startup continues and a warning is added to the UI log.
872-5. Selects the startup model, effort, reasoning visibility, and verbose mode from those settings when available.
878+6. Selects the startup model, effort, reasoning visibility, and verbose mode from those effective settings when available.
873879 - `defaultModel`: if the saved provider/model is currently available, use it; otherwise fall back to the first available model for this launch.
874880 - `defaultEffort`: if valid, use it; otherwise fall back to `medium`.
875881 - `showReasoning`: if present, use it; otherwise fall back to `true`.
876882 - `verbose`: if present, use it; otherwise fall back to `false`.
877-6. Loads AGENTS.md files and skills.
878-7. Selects the launch mode:
883+7. Loads AGENTS.md files and skills.
884+8. Selects the launch mode:
879885 - Interactive TUI when `stdin` and `stdout` are both TTYs and `-p` was not provided.
880886 - Headless one-shot mode otherwise.
881-8. In interactive mode, renders the UI with an empty conversation log, a minimal `mini-coder` empty-state banner (showing the packaged version when available, otherwise a simple dev label), and the status bar populated.
882-9. Starts a new session only when a prompt is actually submitted (no 0-message sessions in the DB).
887+9. In interactive mode, renders the UI with an empty conversation log, a minimal `mini-coder` empty-state banner (showing the packaged version when available, otherwise a simple dev label), and the status bar populated.
888+10. Starts a new session only when a prompt is actually submitted (no 0-message sessions in the DB).
883889
884890 The empty-state banner is only shown while the conversation log has no messages. In headless mode, stdout is reserved for the final assistant text response by default, with any lightweight non-JSON activity snippets going to stderr, or NDJSON event output when `--json` is used.
885891
886892 ## User settings persistence
887893
888-mini-coder persists global user defaults in `~/.config/mini-coder/settings.json`.
894+mini-coder persists global user defaults in `~/.config/mini-coder/settings.json`. When launched inside a git repo, it also reads `<git-root>/.mini-coder/settings.json` as a repo-local read-only overlay for that app run.
889895
890896 ### Stored settings
891897
898+The global settings file and the optional repo-local overlay use the same JSON shape.
899+
892900 ```json
893901 {
894902 "defaultModel": "anthropic/claude-sonnet-4",
@@ -914,20 +922,24 @@ mini-coder persists global user defaults in `~/.config/mini-coder/settings.json`
914922
915923 ### Semantics
916924
917-- Settings are **global to the user**, not scoped per project, repository, or session.
918-- `/model`, `/effort`, `/reasoning`, and `/verbose` persist their new values immediately when changed.
925+- Global defaults are persisted in `~/.config/mini-coder/settings.json`.
926+- When launched inside a git repo, mini-coder also loads `<git-root>/.mini-coder/settings.json` as a repo-local read-only overlay for that app run.
927+- The effective settings are built by loading the global file first and then overlaying the repo-local file. Repo-local values win on collisions.
928+- `customProviders` is merged by provider `name` instead of replacing the whole array. Same-name repo-local entries override global ones.
929+- `mcp.servers` is merged by server `name` instead of replacing the whole array. Same-name repo-local entries override global ones.
930+- `/model`, `/effort`, `/reasoning`, and `/verbose` persist their new values immediately to the global settings file only.
919931 - 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.
920-- Invalid or missing settings file content is treated as "no saved settings" rather than a fatal startup error.
932+- Invalid or missing content in either settings file is treated as "no settings from that file" rather than a fatal startup error.
921933 - `/new`, `/fork`, and `/session` do not modify global settings.
922934 - Session records remain historical: their `model` and `effort` fields reflect the values active when that session was created, not the current global defaults.
923-- `customProviders` is an optional array of user-configured OpenAI-compatible endpoints, typically local model servers.
935+- The effective `customProviders` list is an optional array of user-configured OpenAI-compatible endpoints, typically local model servers.
924936 - Each `customProviders` entry has a `name`, `baseUrl`, and optional `apiKey`. The `name` becomes the provider prefix shown in model ids such as `lm-studio/qwen3-coder`.
925937 - Unreachable or invalid custom providers do not block startup; mini-coder skips them and shows a warning in the interactive log.
926938 - Custom providers are discovered only at startup. There is currently no interactive slash command to add or remove them.
927-- `mcp.servers` is an optional array of user-configured Streamable HTTP MCP endpoints.
939+- The effective `mcp.servers` list is an optional array of user-configured Streamable HTTP MCP endpoints.
928940 - Each `mcp.servers` entry has a `name`, `url`, and `enabled` flag. `name` must be a simple identifier (`A-Z`, `a-z`, `0-9`, `_`, `-`) because it becomes the imported tool prefix, for example `docs__search`. Older entries that omit `enabled` default to `true` when loaded.
929941 - Invalid MCP entries are dropped while loading settings. Invalid MCP URLs are skipped immediately. Enabled MCP servers that are unreachable or tool-less do not block startup; mini-coder skips them and shows a warning in the interactive log.
930-- MCP server definitions are loaded at startup. `/mcp` can toggle configured servers on or off for future turns during the current app run, and that on/off state is persisted back to `settings.json`. Turning a server on reconnects it on demand; turning it off disconnects it. There is still no interactive slash command to add, remove, or reload server definitions.
942+- MCP server definitions are loaded at startup. `/mcp` can toggle configured servers on or off for future turns during the current app run. For servers defined only in global settings, that on/off state is persisted back to `~/.config/mini-coder/settings.json`. Servers whose effective definition comes from the repo-local overlay are read-only and their toggles last only until the app exits. Turning a server on reconnects it on demand; turning it off disconnects it. There is still no interactive …
931943 - Only MCP tools are imported today; MCP prompts and resources are not surfaced yet.
932944
933945 ## Session persistence
src/headless.test.ts+1−0
@@ -48,6 +48,7 @@ function createTestState(): AppState {
4848 providers: new Map(),
4949 oauthCredentials: {},
5050 settings: {},
51+ repoSettings: {},
5152 settingsPath: join(tmp, "settings.json"),
5253 cwd: tmp,
5354 canonicalCwd: tmp,
src/index.test.ts+99−0
@@ -12,6 +12,7 @@ import {
1212 getAvailableModels,
1313 loadOAuthCredentials,
1414 loadPromptContext,
15+ loadUserSettingsForLaunch,
1516 reloadPromptContext,
1617 runHeadlessCli,
1718 } from "./index.ts";
@@ -45,6 +46,7 @@ function createTestState(): AppState {
4546 providers: new Map(),
4647 oauthCredentials: {},
4748 settings: {},
49+ repoSettings: {},
4850 settingsPath: join(cwd, "settings.json"),
4951 cwd,
5052 canonicalCwd: cwd,
@@ -191,6 +193,103 @@ test("init treats invalid settings.json as no saved settings", async () => {
191193 });
192194 });
193195
196+test("loadUserSettingsForLaunch keeps global settings separate from the repo overlay", () => {
197+ const dir = createTempDir();
198+ const settingsPath = join(dir, "settings.json");
199+ const repoRoot = join(dir, "project");
200+ mkdirSync(join(repoRoot, ".mini-coder"), { recursive: true });
201+
202+ writeFileSync(
203+ settingsPath,
204+ JSON.stringify({
205+ defaultModel: "openai/gpt-5",
206+ verbose: false,
207+ customProviders: [
208+ { name: "ollama", baseUrl: "http://global-ollama/v1" },
209+ { name: "lm-studio", baseUrl: "http://global-lm/v1" },
210+ ],
211+ mcp: {
212+ servers: [
213+ { name: "docs", url: "http://global-docs/mcp", enabled: false },
214+ { name: "down", url: "http://down.test/mcp", enabled: false },
215+ ],
216+ },
217+ }),
218+ "utf-8",
219+ );
220+ writeFileSync(
221+ join(repoRoot, ".mini-coder", "settings.json"),
222+ JSON.stringify({
223+ defaultModel: "anthropic/claude-sonnet-4",
224+ showReasoning: false,
225+ customProviders: [
226+ { name: "ollama", baseUrl: "http://repo-ollama/v1" },
227+ { name: "vllm", baseUrl: "http://repo-vllm/v1" },
228+ ],
229+ mcp: {
230+ servers: [
231+ { name: "docs", url: "http://repo-docs/mcp", enabled: true },
232+ { name: "repo", url: "http://repo.test/mcp", enabled: true },
233+ ],
234+ },
235+ }),
236+ "utf-8",
237+ );
238+
239+ expect(
240+ loadUserSettingsForLaunch({
241+ settingsPath,
242+ gitRoot: repoRoot,
243+ }),
244+ ).toEqual({
245+ settings: {
246+ defaultModel: "openai/gpt-5",
247+ verbose: false,
248+ customProviders: [
249+ { name: "ollama", baseUrl: "http://global-ollama/v1" },
250+ { name: "lm-studio", baseUrl: "http://global-lm/v1" },
251+ ],
252+ mcp: {
253+ servers: [
254+ { name: "docs", url: "http://global-docs/mcp", enabled: false },
255+ { name: "down", url: "http://down.test/mcp", enabled: false },
256+ ],
257+ },
258+ },
259+ repoSettings: {
260+ defaultModel: "anthropic/claude-sonnet-4",
261+ showReasoning: false,
262+ customProviders: [
263+ { name: "ollama", baseUrl: "http://repo-ollama/v1" },
264+ { name: "vllm", baseUrl: "http://repo-vllm/v1" },
265+ ],
266+ mcp: {
267+ servers: [
268+ { name: "docs", url: "http://repo-docs/mcp", enabled: true },
269+ { name: "repo", url: "http://repo.test/mcp", enabled: true },
270+ ],
271+ },
272+ },
273+ effectiveSettings: {
274+ defaultModel: "anthropic/claude-sonnet-4",
275+ showReasoning: false,
276+ verbose: false,
277+ customProviders: [
278+ { name: "ollama", baseUrl: "http://repo-ollama/v1" },
279+ { name: "lm-studio", baseUrl: "http://global-lm/v1" },
280+ { name: "vllm", baseUrl: "http://repo-vllm/v1" },
281+ ],
282+ mcp: {
283+ servers: [
284+ { name: "docs", url: "http://repo-docs/mcp", enabled: true },
285+ { name: "down", url: "http://down.test/mcp", enabled: false },
286+ { name: "repo", url: "http://repo.test/mcp", enabled: true },
287+ ],
288+ },
289+ },
290+ });
291+});
292+
194293 test("runHeadlessCli uses final-text mode by default in non-TTY environments", async () => {
195294 const state = createTestState();
196295 const calls: string[] = [];
src/index.ts+45−7
@@ -53,6 +53,7 @@ import {
5353 import {
5454 type CustomProvider,
5555 loadStartupSettings,
56+ mergeUserSettings,
5657 resolveStartupSettings,
5758 type UserSettings,
5859 } from "./settings.ts";
@@ -447,6 +448,37 @@ export async function loadPromptContext(opts?: { cwd?: string }): Promise<{
447448 };
448449 }
449450
451+/**
452+ * Load global and repo-local settings for the current launch.
453+ *
454+ * The repo-local overlay is read only and is loaded only when a git root is
455+ * known. Invalid startup content in either file is treated as empty settings.
456+ *
457+ * @param opts - Optional settings path and git-root override for tests.
458+ * @returns Global settings, repo-local overlay settings, and the merged result.
459+ */
460+export function loadUserSettingsForLaunch(opts?: {
461+ settingsPath?: string;
462+ gitRoot?: string | null;
463+}): {
464+ settings: UserSettings;
465+ repoSettings: UserSettings;
466+ effectiveSettings: UserSettings;
467+} {
468+ const settingsPath = opts?.settingsPath ?? SETTINGS_PATH;
469+ const gitRoot = opts?.gitRoot ?? null;
470+ const settings = loadStartupSettings(settingsPath);
471+ const repoSettings = gitRoot
472+ ? loadStartupSettings(join(gitRoot, ".mini-coder", "settings.json"))
473+ : {};
474+
475+ return {
476+ settings,
477+ repoSettings,
478+ effectiveSettings: mergeUserSettings(settings, repoSettings),
479+ };
480+}
481+
450482 /** Refresh the current prompt/session context at a reload boundary like `/new`. */
451483 export async function reloadPromptContext(
452484 state: AppState,
@@ -501,6 +533,8 @@ export interface AppState {
501533 oauthCredentials: Record<string, OAuthCredentials>;
502534 /** Loaded global user settings. */
503535 settings: UserSettings;
536+ /** Loaded repo-local settings overlay for the current app run. */
537+ repoSettings: UserSettings;
504538 /** Absolute path to the global settings file. */
505539 settingsPath: string;
506540 /** Working directory as entered by the user/shell (for display and tool execution). */
@@ -541,13 +575,17 @@ export async function init(): Promise<AppState> {
541575 // Discover providers (env + OAuth)
542576 const { providers, oauthCredentials } = await discoverProviders();
543577
544- // Load user settings and resolve startup defaults
545- const settings = loadStartupSettings(SETTINGS_PATH);
578+ const promptContext = await loadPromptContext({ cwd });
579+ const { settings, repoSettings, effectiveSettings } =
580+ loadUserSettingsForLaunch({
581+ settingsPath: SETTINGS_PATH,
582+ gitRoot: promptContext.git?.root ?? null,
583+ });
546584
547- // Discover custom providers from settings
585+ // Discover custom providers from effective settings
548586 const builtInProviderNames = new Set(providers.keys());
549587 const customResult = await discoverCustomProviders(
550- settings.customProviders ?? [],
588+ effectiveSettings.customProviders ?? [],
551589 builtInProviderNames,
552590 );
553591
@@ -556,12 +594,12 @@ export async function init(): Promise<AppState> {
556594 providers.set(name, key);
557595 }
558596
559- const mcpResult = await discoverMcpServers(settings.mcp);
597+ const mcpResult = await discoverMcpServers(effectiveSettings.mcp);
560598
561599 const builtInModels = listAvailableModels(providers);
562600 const availableModels = [...builtInModels, ...customResult.models];
563601 const startup = resolveStartupSettings(
564- settings,
602+ effectiveSettings,
565603 availableModels.map((model) => `${model.provider}/${model.id}`),
566604 );
567605 const model = selectModel(availableModels, startup.modelId);
@@ -570,7 +608,6 @@ export async function init(): Promise<AppState> {
570608 const db = openDatabase(DB_PATH);
571609 const effort = startup.effort;
572610 const conversation = createConversationSnapshot();
573- const promptContext = await loadPromptContext({ cwd });
574611
575612 return {
576613 db,
@@ -588,6 +625,7 @@ export async function init(): Promise<AppState> {
588625 providers,
589626 oauthCredentials,
590627 settings,
628+ repoSettings,
591629 settingsPath: SETTINGS_PATH,
592630 cwd: promptContext.cwd,
593631 canonicalCwd: promptContext.canonicalCwd,
src/settings.test.ts+98−0
@@ -11,6 +11,7 @@ import { join } from "node:path";
1111 import {
1212 loadSettings,
1313 loadStartupSettings,
14+ mergeUserSettings,
1415 resolveStartupSettings,
1516 saveSettings,
1617 type UserSettings,
@@ -138,6 +139,103 @@ describe("settings", () => {
138139 expect(loadSettings(path)).toEqual(updated);
139140 });
140141
142+ test("mergeUserSettings overlays scalars and merges named arrays", () => {
143+ const merged = mergeUserSettings(
144+ {
145+ defaultModel: "openai/gpt-5",
146+ verbose: false,
147+ customProviders: [
148+ { name: "ollama", baseUrl: "http://global-ollama/v1" },
149+ { name: "lm-studio", baseUrl: "http://global-lm/v1" },
150+ ],
151+ mcp: {
152+ servers: [
153+ { name: "docs", url: "http://global-docs/mcp", enabled: false },
154+ { name: "down", url: "http://down.test/mcp", enabled: false },
155+ ],
156+ },
157+ },
158+ {
159+ defaultModel: "anthropic/claude-sonnet-4",
160+ showReasoning: false,
161+ customProviders: [
162+ { name: "ollama", baseUrl: "http://repo-ollama/v1" },
163+ { name: "vllm", baseUrl: "http://repo-vllm/v1" },
164+ ],
165+ mcp: {
166+ servers: [
167+ { name: "docs", url: "http://repo-docs/mcp", enabled: true },
168+ { name: "repo", url: "http://repo.test/mcp", enabled: true },
169+ ],
170+ },
171+ },
172+ );
173+
174+ expect(merged).toEqual({
175+ defaultModel: "anthropic/claude-sonnet-4",
176+ showReasoning: false,
177+ verbose: false,
178+ customProviders: [
179+ { name: "ollama", baseUrl: "http://repo-ollama/v1" },
180+ { name: "lm-studio", baseUrl: "http://global-lm/v1" },
181+ { name: "vllm", baseUrl: "http://repo-vllm/v1" },
182+ ],
183+ mcp: {
184+ servers: [
185+ { name: "docs", url: "http://repo-docs/mcp", enabled: true },
186+ { name: "down", url: "http://down.test/mcp", enabled: false },
187+ { name: "repo", url: "http://repo.test/mcp", enabled: true },
188+ ],
189+ },
190+ });
191+ });
192+
193+ test("updateSettings merges customProviders and MCP servers by name", () => {
194+ const dir = createTempDir();
195+ const path = join(dir, "settings.json");
196+ saveSettings(path, {
197+ customProviders: [
198+ { name: "ollama", baseUrl: "http://global-ollama/v1" },
199+ { name: "lm-studio", baseUrl: "http://global-lm/v1" },
200+ ],
201+ mcp: {
202+ servers: [
203+ { name: "docs", url: "http://global-docs/mcp", enabled: false },
204+ { name: "down", url: "http://down.test/mcp", enabled: false },
205+ ],
206+ },
207+ });
208+
209+ const updated = updateSettings(path, {
210+ customProviders: [
211+ { name: "ollama", baseUrl: "http://updated-ollama/v1" },
212+ { name: "vllm", baseUrl: "http://updated-vllm/v1" },
213+ ],
214+ mcp: {
215+ servers: [
216+ { name: "docs", url: "http://updated-docs/mcp", enabled: true },
217+ { name: "repo", url: "http://repo.test/mcp", enabled: true },
218+ ],
219+ },
220+ });
221+
222+ expect(updated).toEqual({
223+ customProviders: [
224+ { name: "ollama", baseUrl: "http://updated-ollama/v1" },
225+ { name: "lm-studio", baseUrl: "http://global-lm/v1" },
226+ { name: "vllm", baseUrl: "http://updated-vllm/v1" },
227+ ],
228+ mcp: {
229+ servers: [
230+ { name: "docs", url: "http://updated-docs/mcp", enabled: true },
231+ { name: "down", url: "http://down.test/mcp", enabled: false },
232+ { name: "repo", url: "http://repo.test/mcp", enabled: true },
233+ ],
234+ },
235+ });
236+ expect(loadSettings(path)).toEqual(updated);
237+ });
238+
141239 test("resolveStartupSettings uses saved defaults when available", () => {
142240 const resolved = resolveStartupSettings(
143241 {
src/settings.ts+76−1
@@ -132,6 +132,52 @@ export function loadStartupSettings(path: string): UserSettings {
132132 }
133133 }
134134
135+/**
136+ * Merge two settings objects using startup overlay semantics.
137+ *
138+ * Scalar fields use override-wins. `customProviders` merges by provider name,
139+ * and `mcp.servers` merges by server name. Same-name override entries replace
140+ * base entries while keeping the base ordering stable; new override entries are
141+ * appended in override order.
142+ *
143+ * @param base - Base settings, usually the global settings file.
144+ * @param override - Higher-priority settings, usually a repo-local overlay.
145+ * @returns The merged effective settings.
146+ */
147+export function mergeUserSettings(
148+ base: UserSettings,
149+ override: UserSettings,
150+): UserSettings {
151+ const sanitizedBase = sanitizeSettings(base);
152+ const sanitizedOverride = sanitizeSettings(override);
153+ const merged: UserSettings = {
154+ ...sanitizedBase,
155+ ...sanitizedOverride,
156+ };
157+
158+ const customProviders = mergeNamedEntries(
159+ sanitizedBase.customProviders,
160+ sanitizedOverride.customProviders,
161+ );
162+ if (customProviders) {
163+ merged.customProviders = customProviders;
164+ } else {
165+ delete merged.customProviders;
166+ }
167+
168+ const servers = mergeNamedEntries(
169+ sanitizedBase.mcp?.servers,
170+ sanitizedOverride.mcp?.servers,
171+ );
172+ if (servers) {
173+ merged.mcp = { servers };
174+ } else {
175+ delete merged.mcp;
176+ }
177+
178+ return merged;
179+}
180+
135181 /**
136182 * Save user settings to disk.
137183 *
@@ -166,7 +212,7 @@ export function updateSettings(
166212 update: Partial<UserSettings>,
167213 ): UserSettings {
168214 const current = loadSettings(path);
169- const merged = { ...current, ...sanitizeSettings(update) };
215+ const merged = mergeUserSettings(current, sanitizeSettings(update));
170216 return saveSettings(path, merged);
171217 }
172218
@@ -199,6 +245,35 @@ export function resolveStartupSettings(
199245 };
200246 }
201247
248+function mergeNamedEntries<T extends { name: string }>(
249+ base: readonly T[] | undefined,
250+ override: readonly T[] | undefined,
251+): T[] | undefined {
252+ if (!base?.length && !override?.length) {
253+ return undefined;
254+ }
255+
256+ const merged = [...(base ?? [])];
257+ const indexes = new Map<string, number>();
258+
259+ for (const [index, entry] of merged.entries()) {
260+ indexes.set(entry.name, index);
261+ }
262+
263+ for (const entry of override ?? []) {
264+ const existingIndex = indexes.get(entry.name);
265+ if (existingIndex === undefined) {
266+ indexes.set(entry.name, merged.length);
267+ merged.push(entry);
268+ continue;
269+ }
270+
271+ merged[existingIndex] = entry;
272+ }
273+
274+ return merged.length > 0 ? merged : undefined;
275+}
276+
202277 function parseSettingsFile(path: string): UserSettings {
203278 const raw = JSON.parse(readFileSync(path, "utf-8")) as unknown;
204279 return sanitizeSettings(raw);
src/ui.test.ts+1−0
@@ -130,6 +130,7 @@ function createTestState(): AppState {
130130 providers: new Map(),
131131 oauthCredentials: {},
132132 settings: {},
133+ repoSettings: {},
133134 settingsPath,
134135 cwd,
135136 canonicalCwd: cwd,
src/ui/commands.test.ts+182−0
@@ -64,6 +64,7 @@ function createTestState(): AppState {
6464 providers: new Map(),
6565 oauthCredentials: {},
6666 settings: {},
67+ repoSettings: {},
6768 settingsPath,
6869 cwd,
6970 canonicalCwd: cwd,
@@ -558,6 +559,187 @@ describe("ui/commands", () => {
558559 }
559560 });
560561
562+ test("/mcp toggles repo-local servers for the current run without persisting a global shadow copy", async () => {
563+ const state = createTestState();
564+ state.model = {
565+ id: "test-model",
566+ name: "test-model",
567+ api: "openai-completions",
568+ provider: "test-provider",
569+ baseUrl: "http://localhost:1234/v1",
570+ reasoning: false,
571+ input: ["text"],
572+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
573+ contextWindow: 8192,
574+ maxTokens: 4096,
575+ };
576+
577+ const docsTools = [
578+ {
579+ name: "docs__search",
580+ description: "[MCP docs] Search the docs",
581+ parameters: Type.Object({}),
582+ },
583+ ];
584+ const docsHandlers = new Map();
585+ let disconnectCalls = 0;
586+ let connectCalls = 0;
587+
588+ state.mcpServers = [
589+ {
590+ name: "docs",
591+ url: "http://repo-docs.test/mcp",
592+ enabled: true,
593+ connected: true,
594+ tools: docsTools,
595+ toolHandlers: docsHandlers,
596+ close: async () => {
597+ disconnectCalls += 1;
598+ },
599+ },
600+ ];
601+ state.settings = saveSettings(state.settingsPath, {
602+ mcp: {
603+ servers: [
604+ {
605+ name: "docs",
606+ url: "http://global-docs.test/mcp",
607+ enabled: false,
608+ },
609+ {
610+ name: "down",
611+ url: "http://down.test/mcp",
612+ enabled: false,
613+ },
614+ ],
615+ },
616+ });
617+ state.repoSettings = {
618+ mcp: {
619+ servers: [
620+ {
621+ name: "docs",
622+ url: "http://repo-docs.test/mcp",
623+ enabled: true,
624+ },
625+ ],
626+ },
627+ };
628+ const runtimeState = { overlay: null as ActiveOverlay | null };
629+ const appended: Array<{
630+ text: string;
631+ sessionId: string | null;
632+ }> = [];
633+ const controller = createCommandController(
634+ {
635+ openOverlay: (nextOverlay) => {
636+ runtimeState.overlay = nextOverlay;
637+ },
638+ dismissOverlay: () => {
639+ runtimeState.overlay = null;
640+ },
641+ setInputValue: () => {},
642+ appendInfoMessage: (text, nextState) => {
643+ appended.push({ text, sessionId: nextState.session?.id ?? null });
644+ },
645+ appendTodoMessage: () => {},
646+ scrollConversationToBottom: () => {},
647+ requestRender: () => {},
648+ reloadPromptContext: async () => {},
649+ openInBrowser: () => {},
650+ },
651+ {
652+ connectMcpServer: async (server) => {
653+ connectCalls += 1;
654+ server.connected = true;
655+ server.tools = docsTools;
656+ server.toolHandlers = docsHandlers;
657+ server.close = async () => {
658+ disconnectCalls += 1;
659+ };
660+ return [];
661+ },
662+ disconnectMcpServer: async (server) => {
663+ await server.close();
664+ server.connected = false;
665+ server.tools = [];
666+ server.toolHandlers = new Map();
667+ server.close = async () => {};
668+ },
669+ },
670+ );
671+
672+ try {
673+ expect(controller.handleCommand("mcp", state)).toBe(true);
674+ renderSelect(expectOverlay(runtimeState.overlay)).props.onKeyPress?.(
675+ "enter",
676+ );
677+ await Promise.resolve();
678+ await Promise.resolve();
679+
680+ expect(state.mcpServers[0]?.enabled).toBe(false);
681+ expect(state.mcpServers[0]?.connected).toBe(false);
682+ expect(state.settings).toEqual({
683+ mcp: {
684+ servers: [
685+ {
686+ name: "docs",
687+ url: "http://global-docs.test/mcp",
688+ enabled: false,
689+ },
690+ {
691+ name: "down",
692+ url: "http://down.test/mcp",
693+ enabled: false,
694+ },
695+ ],
696+ },
697+ });
698+ expect(loadSettings(state.settingsPath)).toEqual(state.settings);
699+ expect(disconnectCalls).toBe(1);
700+
701+ expect(controller.handleCommand("mcp", state)).toBe(true);
702+ renderSelect(expectOverlay(runtimeState.overlay)).props.onKeyPress?.(
703+ "enter",
704+ );
705+ await Promise.resolve();
706+ await Promise.resolve();
707+
708+ expect(state.mcpServers[0]?.enabled).toBe(true);
709+ expect(state.mcpServers[0]?.connected).toBe(true);
710+ expect(connectCalls).toBe(1);
711+ expect(state.settings).toEqual({
712+ mcp: {
713+ servers: [
714+ {
715+ name: "docs",
716+ url: "http://global-docs.test/mcp",
717+ enabled: false,
718+ },
719+ {
720+ name: "down",
721+ url: "http://down.test/mcp",
722+ enabled: false,
723+ },
724+ ],
725+ },
726+ });
727+ expect(loadSettings(state.settingsPath)).toEqual(state.settings);
728+ expect(appended).toEqual([
729+ {
730+ text: 'Disabled MCP server "docs" (-1 tool).',
731+ sessionId: null,
732+ },
733+ {
734+ text: 'Enabled MCP server "docs" (+1 tool).',
735+ sessionId: null,
736+ },
737+ ]);
738+ } finally {
739+ state.db.close();
740+ }
741+ });
742+
561743 test("/help appends a markdown info message without creating a session", () => {
562744 const state = createTestState();
563745 state.mcpServers = [
src/ui/commands.ts+19−17
@@ -248,30 +248,32 @@ function formatMcpToggleMessage(
248248 return `${action} MCP server "${server.name}" (${delta} ${toolSuffix}).`;
249249 }
250250
251+function isRepoLocalMcpServer(state: AppState, serverName: string): boolean {
252+ return (
253+ state.repoSettings.mcp?.servers?.some(
254+ (entry) => entry.name === serverName,
255+ ) ?? false
256+ );
257+}
258+
251259 function persistMcpServerSettings(
252260 state: AppState,
253261 server: AppState["mcpServers"][number],
254262 ): void {
255- const currentServers = state.settings.mcp?.servers ?? [];
256- let found = false;
257- const servers = currentServers.map((entry) => {
258- if (entry.name !== server.name) {
259- return entry;
260- }
261- found = true;
262- return { ...entry, enabled: server.enabled };
263- });
264-
265- if (!found) {
266- servers.push({
267- name: server.name,
268- url: server.url,
269- enabled: server.enabled,
270- });
263+ if (isRepoLocalMcpServer(state, server.name)) {
264+ return;
271265 }
272266
273267 state.settings = updateSettings(state.settingsPath, {
274- mcp: { servers },
268+ mcp: {
269+ servers: [
270+ {
271+ name: server.name,
272+ url: server.url,
273+ enabled: server.enabled,
274+ },
275+ ],
276+ },
275277 });
276278 }