Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(config): migrate all remaining writers to patch transactions (#1513)
Call White0c6c8aaf0740
diff --git a/config/v2_config.py b/config/v2_config.pyindex d4e17f742..743033c38 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -115,7 +115,7 @@ def config_write_transaction(config_path: Optional[Path] = None) -> Iterator["V2from config import paths as _pathspath = config_path or _paths.get_config_path()- with _memory_config_transaction(path):+ with config_file_lock(path):try:config = V2Config.load(path)except FileNotFoundError:@@ -4125,7 +4125,7 @@ class V2Config:)paths.ensure_data_dirs()path = config_path or paths.get_config_path()- with _memory_config_transaction(path):+ with config_file_lock(path):try:memory = type(self).load(path).memoryexcept FileNotFoundError:@@ -4241,7 +4241,7 @@ def atomic_update_memory(paths.ensure_data_dirs()path = config_path or paths.get_config_path()- with _memory_config_transaction(path):+ with config_file_lock(path):config = V2Config.load(path)memory = mutator(deepcopy(config.memory))if not isinstance(memory, MemoryConfig):diff --git a/core/agent_auth_service.py b/core/agent_auth_service.pyindex ca1cfd3e6..99cbe2f5b 100644--- a/core/agent_auth_service.py+++ b/core/agent_auth_service.py@@ -3880,97 +3880,118 @@ class AgentAuthService:await self._clear_codex_api_key_for_oauth()try:config = getattr(self.controller, "config", None)- target = getattr(getattr(config, "agents", None), backend, None)- saver = getattr(config, "save", None) if config is not None else None- loaded_config = None- if target is None or not callable(saver):- from config.v2_config import V2Config- loaded_config = V2Config.load()- target = getattr(getattr(loaded_config, "agents", None), backend, None)- saver = getattr(loaded_config, "save", None)- if target is None or not callable(saver):- return- # An explicit OAuth save must also flip ``auth_mode_set``- # for Claude — otherwise a successful OAuth flow on a- # legacy install never trips the marker (auth_mode was- # already "oauth" from the schema default), so- # ``build_claude_subprocess_env`` keeps preserving env-var- # auth and the OAuth credentials are ignored at launch.- needs_mode_write = getattr(target, "auth_mode", None) != auth_mode- needs_marker_write = (- backend == "claude"- and not bool(getattr(target, "auth_mode_set", False))- )- needs_codex_oauth_cleanup = (- backend == "codex"- and auth_mode == "oauth"- and (- bool(getattr(target, "api_key", None))- or bool(getattr(target, "base_url", None))- or getattr(target, "oauth_relay_marker", None) is not None- or captured_codex_relay is not None- or observed_codex_api_key_auth+ # Persisted write: cross-process patch transaction (#1458+ # stage ③) — load fresh inside the file lock, compute the+ # needs/marker decisions FROM that lock-fresh snapshot, apply+ # only the auth fields, save. Decisions computed outside the+ # lock could race an auth save from the other process (e.g.+ # a stale target reading "already explicit OAuth" while the+ # UI API just persisted API-key mode — the early no-op path+ # would leave the API-key mode selected after a successful+ # OAuth flow, or restore an older relay marker over a fresh+ # one). The relay-marker pre-persist above stays a SEPARATE+ # durable boundary: it must land before the external ~/.codex+ # cleanup, which no config transaction can span.+ from config.v2_config import update_config_fields++ applied: dict[str, Any] = {}++ def _apply_auth_fields(cfg) -> None:+ # An explicit OAuth save must also flip ``auth_mode_set``+ # for Claude — otherwise a successful OAuth flow on a+ # legacy install never trips the marker (auth_mode was+ # already "oauth" from the schema default), so+ # ``build_claude_subprocess_env`` keeps preserving+ # env-var auth and the OAuth credentials are ignored at+ # launch.+ cfg_target = getattr(getattr(cfg, "agents", None), backend, None)+ if cfg_target is None:+ applied["skip"] = True+ return+ needs_mode_write = getattr(cfg_target, "auth_mode", None) != auth_mode+ needs_marker_write = (+ backend == "claude"+ and not bool(getattr(cfg_target, "auth_mode_set", False)))- )- # Relay-marker retention semantics for the OAuth transition:- # fresh capture → overwrite (latest relay wins)- # official-key transition → clear (the user deliberately- # left relay auth; a stale marker- # would resurface and reroute a- # future key to the old relay)- # repeated pure-OAuth → retain (nothing new observed;- # the earlier capture stays valid)- if captured_codex_relay is not None:- resolved_codex_relay_marker: dict | None = captured_codex_relay- elif observed_codex_api_key_auth:- resolved_codex_relay_marker = None- else:- resolved_codex_relay_marker = getattr(target, "oauth_relay_marker", None)- if not needs_mode_write and not needs_marker_write and not needs_codex_oauth_cleanup:- return- try:- from config.v2_config import CONFIG_LOCK-- with CONFIG_LOCK:- if needs_mode_write:- target.auth_mode = auth_mode- if needs_marker_write:- target.auth_mode_set = True- if needs_codex_oauth_cleanup:- target.api_key = None- # ``base_url`` returns to plain "last saved- # preference" semantics (the live relay is gone- # for OAuth); the explicit ``oauth_relay_marker``- # carries the recovery record instead. A repeated- # OAuth transition captures nothing (the pointer- # is already gone), so retain any existing marker- # — only an explicit API-key save or sign-out- # clears it.- target.base_url = None- target.oauth_relay_marker = resolved_codex_relay_marker- saver()- except ImportError:+ needs_codex_oauth_cleanup = (+ backend == "codex"+ and auth_mode == "oauth"+ and (+ bool(getattr(cfg_target, "api_key", None))+ or bool(getattr(cfg_target, "base_url", None))+ or getattr(cfg_target, "oauth_relay_marker", None) is not None+ or captured_codex_relay is not None+ or observed_codex_api_key_auth+ )+ )+ # Relay-marker retention semantics for the OAuth+ # transition, computed from the lock-fresh snapshot:+ # fresh capture → overwrite (latest relay wins)+ # official-key transition → clear (the user deliberately+ # left relay auth; a stale marker+ # would resurface and reroute a+ # future key to the old relay)+ # repeated pure-OAuth → retain (nothing new observed;+ # the earlier capture stays valid)+ if captured_codex_relay is not None:+ resolved_codex_relay_marker: dict | None = captured_codex_relay+ elif observed_codex_api_key_auth:+ resolved_codex_relay_marker = None+ else:+ resolved_codex_relay_marker = getattr(cfg_target, "oauth_relay_marker", None)++ applied["needs_mode_write"] = needs_mode_write+ applied["needs_marker_write"] = needs_marker_write+ applied["needs_codex_oauth_cleanup"] = needs_codex_oauth_cleanup+ applied["resolved_marker"] = resolved_codex_relay_marker+ applied["skip"] = not (+ needs_mode_write or needs_marker_write or needs_codex_oauth_cleanup+ )+ if applied["skip"]:+ returnif needs_mode_write:- target.auth_mode = auth_mode+ cfg_target.auth_mode = auth_modeif needs_marker_write:- target.auth_mode_set = True+ cfg_target.auth_mode_set = Trueif needs_codex_oauth_cleanup:- target.api_key = None- target.base_url = None- target.oauth_relay_marker = resolved_codex_relay_marker- saver()- if loaded_config is not None and config is not None:- compat_target = getattr(config, backend, None)- if compat_target is not None:- if needs_mode_write:- setattr(compat_target, "auth_mode", auth_mode)- if needs_marker_write:- setattr(compat_target, "auth_mode_set", True)- if needs_codex_oauth_cleanup:- setattr(compat_target, "api_key", None)- setattr(compat_target, "base_url", None)- setattr(compat_target, "oauth_relay_marker", resolved_codex_relay_marker)+ cfg_target.api_key = None+ # ``base_url`` returns to plain "last saved+ # preference" semantics (the live relay is gone+ # for OAuth); the explicit ``oauth_relay_marker``+ # carries the recovery record instead.+ cfg_target.base_url = None+ cfg_target.oauth_relay_marker = resolved_codex_relay_marker++ # The transaction may wait on another process' config lock and do+ # synchronous file I/O. Keep both the fresh-snapshot decision and+ # the mutation inside the worker, but do not block the ASGI loop+ # that services OAuth polling and unrelated UI requests.+ await asyncio.to_thread(update_config_fields, _apply_auth_fields)++ if applied.get("skip"):+ return++ def _mirroronto(obj) -> None:+ if obj is None:+ return+ if applied["needs_mode_write"]:+ setattr(obj, "auth_mode", auth_mode)+ if applied["needs_marker_write"]:+ setattr(obj, "auth_mode_set", True)+ if applied["needs_codex_oauth_cleanup"]:+ setattr(obj, "api_key", None)+ setattr(obj, "base_url", None)+ setattr(obj, "oauth_relay_marker", applied["resolved_marker"])++ # Mirror onto the controller's LIVE config objects so the+ # running process observes the transition without a reload.+ # The controller's own agents object is mirrored when present;+ # the legacy compat projection (top-level ``config.<backend>``)+ # is mirrored too when present.+ if config is not None:+ _mirroronto(getattr(getattr(config, "agents", None), backend, None))+ _mirroronto(getattr(config, backend, None))except Exception as err: # noqa: BLE001logger.warning("Failed to persist auth_mode=%s after web flow for %s: %s",diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 11558f877..5e780327e 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -189,13 +189,10 @@ class V2ModelHubConfigStore:def save(self, model_hub: ModelHubConfig) -> None:model_hub = ModelHubConfig.from_payload(model_hub.to_payload())- with CONFIG_LOCK:- try:- config = V2Config.load()- except FileNotFoundError:- config = default_config()- config.model_hub = model_hub- config.save()+ self.ensure_writable()+ from config.v2_config import update_config_fields++ update_config_fields(lambda cfg: setattr(cfg, "model_hub", model_hub))class UnavailableEngineAdapter:"""Explicit fail-closed adapter for isolated callers and tests."""diff --git a/core/services/settings.py b/core/services/settings.pyindex 9538deffe..ba181da9c 100644--- a/core/services/settings.py+++ b/core/services/settings.py@@ -80,11 +80,27 @@ def load_config("""target = config_path or paths.get_config_path()- if not target.exists():- if default_factory is None:++ if default_factory is None:+ # Pure read: no lock and NO side effects — ``V2Config.load``+ # unconditionally ``ensure_data_dirs()`` (creating the whole+ # home tree), and taking the config file lock would mkdir the+ # config directory too. A caller asking for a must-exist config+ # must not mutate its environment; check existence first and+ # raise without loading. A bare read cannot lose updates.+ if not target.exists():raise FileNotFoundError(f"V2 config not found at {target}")- default = default_factory()- default.save(target)+ return V2Config.load(target)++ from config.v2_config import config_file_lock++ # Create-if-absent under the cross-process file lock (#1458 stage+ # ③): the existence check and the seeding save are one atomic step+ # (see the matching note in vibe.runtime.ensure_config).+ with config_file_lock(target):+ if not target.exists():+ default = default_factory()+ default.save(target)return V2Config.load(target)diff --git a/docs/plans/config-cross-process-write-serialization.md b/docs/plans/config-cross-process-write-serialization.mdindex 92069d43b..e0cd560ed 100644--- a/docs/plans/config-cross-process-write-serialization.md+++ b/docs/plans/config-cross-process-write-serialization.md@@ -53,9 +53,42 @@ read-merge-write cycle); a snapshot overwrite silently reverts them.default_provider, rotate_session_secret; real two-process lock-contracttest).-## Remaining — stage ③ (the close-out)--Migrate every remaining direct writer to `update_config_fields`:+## PR #1513 implementation update (2026-08-22)++The remaining UI writers are now expressed through one client-side mutation+protocol. `ApiContext.mutateConfig()` accepts explicit leaf assignments and+the whitelisted `platforms.enabled` add/remove operation; it is the only UI+owner that serializes those mutations to the existing `/api/config` merge-patch+HTTP body. Wizard steps derive mutations from the fields they own, so a later+step cannot replay mount-time `agents`, platform sections, or runtime paths. The wizard also+records only list operations it actually submitted; the load-time enabled list is an observation,+not permission to re-enable a platform at Finish. Channel and guild settings are committed by+the Channels/credential steps, while Summary owns completion flags and final wizard list intent+only, so it does not replay the accumulated channel snapshot. After Finish,+Summary routes startup and bind-code handling from the lock-fresh config+response, not the wizard's local platform selection; a skipped or otherwise+unpersisted selection therefore resolves to the platforms actually enabled by+the transaction (including a valid Workbench-only setup).++On the server, `config_file_lock` is the single cross-process lock owner. The+generic `save_config` read/merge/validate/write cycle, `config_write_transaction`,+first-run creators, ordinary `V2Config.save`, Memory updates, and the WeChat QR+writer all use that lock (nested acquisition is re-entrant). The lock prevents+overlapping read-modify-write cycles; it does not make an explicitly submitted+stale snapshot safe, which is why the UI mutation boundary remains required.++The branch adds lock-boundary tests that prove both the transaction's load and+mutator wait behind the migration lock, plus focused UI tests for field ownership+and Wizard step isolation. This is the intended close-out shape for stage ③;+the remaining work is remote review/CI verification on the rebased branch.++## Remaining — stage ③ (the close-out checklist)++The original checklist below names the writer surfaces that needed ownership+and transaction coverage. A surface may use `save_config` with an explicit+patch (when it must retain API validation/runtime reconciliation) or+`update_config_fields` (for a typed in-memory mutator); the contract is the+same: the decision and write must observe one lock-fresh snapshot.1. `vibe/api.py` `save_config` — serialize the WHOLE read-merge-writecycle (base load currently happens outside the file lock, so a@@ -94,4 +127,6 @@ Non-goals: no schema change, no file split, no new IPC, no guards.Stage ③ merged → every cross-process `config.json` writer ispatch-shaped under the transaction → issue closed with a pointer to the-parked single-writer option.+parked single-writer option. A green local run is not sufficient: close only+after the PR head has a clean merge state, zero unresolved review findings,+and passing CI on the final pushed commit.diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex cb113d2b3..e37dbd93f 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -2390,7 +2390,13 @@ class CodexRelayRoundTripScenarioTests(unittest.IsolatedAsyncioTestCase):self.home = Path(state_dir.name)codex_home = self.home / ".codex"codex_home.mkdir(parents=True)- self._codex_home_env = patch.dict(os.environ, {"CODEX_HOME": str(codex_home)})+ # AVIBE_HOME isolation: the V2Config writes in this scenario go+ # through the cross-process config transaction, which resolves+ # config.json from AVIBE_HOME — keep them on the test's temp dir.+ self._codex_home_env = patch.dict(+ os.environ,+ {"CODEX_HOME": str(codex_home), "AVIBE_HOME": str(self.home)},+ )self._codex_home_env.start()self.addCleanup(self._codex_home_env.stop)@@ -2418,6 +2424,15 @@ class CodexRelayRoundTripScenarioTests(unittest.IsolatedAsyncioTestCase):)self.harness.controller.config.agents.codex = self.codex_cfgself.harness.controller.config.save = lambda: None+ # Seed the real (isolated) config with the api_key pre-state: the+ # transaction computes its needs/marker decisions from the+ # lock-fresh file, so the transition must be warranted on disk.+ from config.v2_config import V2Config++ real_cfg = V2Config.default()+ real_cfg.agents.codex.auth_mode = "api_key"+ real_cfg.agents.codex.api_key = "sk-relay"+ real_cfg.save()def _api_module(self):from vibe import api as vibe_api@@ -2507,7 +2522,9 @@ class CodexRelayRoundTripScenarioTests(unittest.IsolatedAsyncioTestCase):# The user's provider settings survive the round trip.self.assertIn('wire_api = "responses"', toml)self.assertNotIn("[model_providers.openai-managed]", toml)- self.assertIsNone(self.codex_cfg.oauth_relay_marker)+ from config.v2_config import V2Config++ self.assertIsNone(V2Config.load().agents.codex.oauth_relay_marker)ScenarioExpect.step_history(runner, ["oauth_transition", "settings_reload", "api_key_save"]diff --git a/tests/test_agent_auth_service.py b/tests/test_agent_auth_service.pyindex 4ee7cf57c..93bb69428 100644--- a/tests/test_agent_auth_service.py+++ b/tests/test_agent_auth_service.py@@ -2,6 +2,7 @@ import asyncioimport osimport sysimport tempfile+import threadingimport unittestfrom contextlib import contextmanagerfrom pathlib import Path@@ -28,6 +29,12 @@ class _IsolatedClaudeConfigDirMixin:self._claude_config_dir_tmp = tempfile.TemporaryDirectory()self._previous_claude_config_dir = os.environ.get("CLAUDE_CONFIG_DIR")os.environ["CLAUDE_CONFIG_DIR"] = str(Path(self._claude_config_dir_tmp.name) / ".claude")+ # V2Config writes go through the cross-process transaction, which+ # resolves config.json from AVIBE_HOME — isolate it per test so+ # no test touches the developer's real ~/.avibe.+ self._avibe_home_tmp = tempfile.TemporaryDirectory()+ self._previous_avibe_home = os.environ.get("AVIBE_HOME")+ os.environ["AVIBE_HOME"] = self._avibe_home_tmp.namedef tearDown(self):if self._previous_claude_config_dir is None:@@ -35,6 +42,11 @@ class _IsolatedClaudeConfigDirMixin:else:os.environ["CLAUDE_CONFIG_DIR"] = self._previous_claude_config_dirself._claude_config_dir_tmp.cleanup()+ if self._previous_avibe_home is None:+ os.environ.pop("AVIBE_HOME", None)+ else:+ os.environ["AVIBE_HOME"] = self._previous_avibe_home+ self._avibe_home_tmp.cleanup()super().tearDown()@@ -1338,9 +1350,17 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyntimeout=service.setup_timeout_seconds,)cleanup.assert_called()- self.assertEqual(controller.config.agents.claude.auth_mode, "oauth")+ # The persisted write goes through the cross-process config+ # transaction; the live mirror fires only for fields the+ # transaction decided to change, computed from the lock-fresh+ # snapshot. The stub claude starts without auth_mode_set, so the+ # marker mirror applies; auth_mode itself is asserted on the+ # persisted file (the fresh snapshot already said "oauth").self.assertTrue(controller.config.agents.claude.auth_mode_set)- self.assertEqual(controller.config.save_calls, 1)+ from config.v2_config import V2Config as _V2++ self.assertEqual(_V2.load().agents.claude.auth_mode, "oauth")+ self.assertTrue(_V2.load().agents.claude.auth_mode_set)service._refresh_backend_runtime.assert_awaited_once_with("claude")service._disconnect_claude_client.assert_awaited_once_with(flow.claude_client)self.assertIn("login is active again", controller.im_client.sent_messages[0][1].lower())@@ -1399,6 +1419,42 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsynself.assertTrue(saved.agents.claude.auth_mode_set)self.assertTrue(controller.config.claude.auth_mode_set)+ async def test_persist_backend_auth_mode_runs_config_transaction_off_event_loop(self):+ controller = _StubController()+ controller.config.agents.claude = SimpleNamespace(+ auth_mode="api_key",+ auth_mode_set=False,+ )+ service = AgentAuthService(controller)+ service._clear_claude_settings_env_for_oauth = AsyncMock()++ fresh_config = SimpleNamespace(+ agents=SimpleNamespace(+ claude=SimpleNamespace(auth_mode="api_key", auth_mode_set=False),+ ),+ )+ transaction_thread = None++ def fake_update_config_fields(mutator):+ nonlocal transaction_thread+ transaction_thread = threading.current_thread()+ mutator(fresh_config)+ return fresh_config++ with patch(+ "config.v2_config.update_config_fields",+ side_effect=fake_update_config_fields,+ ):+ caller_thread = threading.current_thread()+ await service._persist_backend_auth_mode("claude", "oauth")++ self.assertIsNotNone(transaction_thread)+ self.assertIsNot(transaction_thread, caller_thread)+ self.assertEqual(fresh_config.agents.claude.auth_mode, "oauth")+ self.assertTrue(fresh_config.agents.claude.auth_mode_set)+ self.assertEqual(controller.config.agents.claude.auth_mode, "oauth")+ self.assertTrue(controller.config.agents.claude.auth_mode_set)+async def test_wait_for_claude_completion_reports_settings_cleanup_failure(self):controller = _StubController()service = AgentAuthService(controller)diff --git a/tests/test_api_save_config_merge.py b/tests/test_api_save_config_merge.pyindex 946da579f..df2409d93 100644--- a/tests/test_api_save_config_merge.py+++ b/tests/test_api_save_config_merge.py@@ -987,14 +987,38 @@ def test_platform_runnable_config_keeps_wechat_token_optional():assert "return Boolean(data?.wechat);" in source-def test_wizard_platform_selection_preserves_credential_drafts_on_continue():+def test_wizard_platform_selection_submits_only_edited_credential_drafts():source = Path("ui/src/components/steps/PlatformSelection.tsx").read_text(encoding="utf-8")assert "const nextData = {" in source- assert "...credentialDraft," in source+ assert "const dirtySections" in source+ assert "dirtyPayload[key] = credentialDraft[key]" in source+ assert "...dirtyPayload," in sourceassert "await onSave(nextData);" in sourceassert "onNext(nextData);" in sourceassert "onNext(selectionData);" not in source+ assert "...credentialDraft," not in source+++def test_ui_config_writes_have_one_mutation_boundary():+ """Every browser config write must pass through ApiContext's mutation serializer."""++ ui_root = Path("ui/src")+ raw_save_callers = []+ direct_config_posts = []+ for path in (*ui_root.rglob("*.ts"), *ui_root.rglob("*.tsx")):+ if ".test." in path.name:+ continue+ text = path.read_text(encoding="utf-8")+ if "saveConfig" in text:+ raw_save_callers.append(str(path))+ if path.name != "ApiContext.tsx" and re.search(+ r"\b(?:postJson|apiFetch)\(\s*['\"]\/api\/config", text+ ):+ direct_config_posts.append(str(path))++ assert raw_save_callers == []+ assert direct_config_posts == []# ---------------------------------------------------------------------------@@ -1710,3 +1734,79 @@ def test_editor_config_write_error_code_keeps_every_failure_localizable():ValueError(""),):assert api.editor_config_write_error_code(exc) == "editor_config_write_invalid"+++def test_save_config_list_ops_merge_against_lock_fresh_base(monkeypatch, tmp_path):+ """The ``__avibe_list_ops`` verb mutates the CURRENT persisted list+ instead of replacing it with a stale browser snapshot: a toggle that+ was computed before another process added a platform must not drop+ that platform (#1458 stage ③ list semantics)."""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ original = api.save_config(_full_config_payload())+ # Another process seeds lark credentials and enables lark AFTER the+ # browser rendered its snapshot.+ api.save_config(+ {+ "lark": {"app_id": "cli_lark_id", "app_secret": "lark-secret"},+ "platforms": {"enabled": ["discord", "lark"]},+ }+ )++ # The browser's stale snapshot only knows slack; the toggle wants to+ # remove slack — expressed as an operation, not a list replacement.+ updated = api.save_config(+ {+ "__avibe_list_ops": {"platforms.enabled": {"remove": ["discord"]}},+ }+ )++ assert "discord" not in updated.platforms.enabled+ assert "lark" in updated.platforms.enabled+++def test_list_ops_enable_requires_credentials(monkeypatch, tmp_path):+ """List-op additions are validated like explicit list saves: enabling+ a platform without credentials through the verb is rejected (#1458+ stage ③ list semantics)."""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ api.save_config(_full_config_payload())++ import pytest++ with pytest.raises(ValueError, match="lark"):+ api.save_config({"__avibe_list_ops": {"platforms.enabled": {"add": ["lark"]}}})+++def test_list_ops_reject_unwhitelisted_paths(monkeypatch, tmp_path):+ """Only whitelisted list paths accept operations — arbitrary dotted+ paths (e.g. model_hub.sources, which must go through ModelHubService)+ are rejected instead of silently mutating the persisted base."""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ api.save_config(_full_config_payload())++ import pytest++ with pytest.raises(ValueError, match="not supported"):+ api.save_config(+ {"__avibe_list_ops": {"model_hub.sources": {"add": ["rogue"]}}}+ )+++ "operations",+ [+ {"add": 1},+ {"remove": 1},+ {"add": ["discord", 1]},+ {"remove": [""]},+ {"add": ["discord"], "replace": ["slack"]},+ ],+)+def test_list_ops_reject_malformed_operands(monkeypatch, tmp_path, operations):+ """Malformed list operations are client errors, never a server 500."""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ api.save_config(_full_config_payload())++ with pytest.raises(ValueError, match="Config list operation"):+ api.save_config({"__avibe_list_ops": {"platforms.enabled": operations}})diff --git a/tests/test_codex_api_auth.py b/tests/test_codex_api_auth.pyindex b32dc37f2..31509f5c4 100644--- a/tests/test_codex_api_auth.py+++ b/tests/test_codex_api_auth.py@@ -35,6 +35,24 @@ def _seed_disk(home: Path, *, api_key: str | None, store: str | None) -> None:(codex_home / "config.toml").write_text(toml, encoding="utf-8")+def _seed_v2_codex(monkeypatch, tmp_path: Path, **codex_fields) -> None:+ """Seed an isolated real V2Config so cross-process transaction writes+ (update_config_fields) have a hermetic file to land on."""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "avibe-home"))+ from config.v2_config import V2Config++ cfg = V2Config.default()+ for key, value in codex_fields.items():+ setattr(cfg.agents.codex, key, value)+ cfg.save()+++def _load_v2_codex():+ from config.v2_config import V2Config++ return V2Config.load().agents.codex++def test_get_codex_auth_forwards_credentials_store_fields(monkeypatch, tmp_path: Path) -> None:"""The keyring-warning gate in SettingsCodexProviderPage reads bothfields; dropping them silently caused incorrect warnings even when@@ -69,14 +87,9 @@ def test_save_codex_auth_prefers_disk_over_v2config_cache(monkeypatch, tmp_path:monkeypatch.setenv("CODEX_HOME", str(tmp_path / ".codex"))_seed_disk(tmp_path, api_key="sk-fresh-on-disk", store="file")- # Cached V2Config carries a stale key.- fake_codex = types.SimpleNamespace(- auth_mode="api_key", api_key="sk-stale-from-cache", base_url=None- )- fake_agents = types.SimpleNamespace(codex=fake_codex)- fake_config = types.SimpleNamespace(agents=fake_agents, save=lambda: None)- monkeypatch.setattr(api, "load_config", lambda: fake_config)- # Don't actually restart the backend in unit tests.+ # Cached V2Config carries a stale key (seeded in the isolated real+ # config — the transactional write lands there, not on a fake).+ _seed_v2_codex(monkeypatch, tmp_path, api_key="sk-stale-from-cache")monkeypatch.setattr(api, "restart_backend", lambda name, **kwargs: {"ok": True})payload = {"auth_mode": "api_key", "api_key": None, "base_url": "https://example/v1"}@@ -87,8 +100,8 @@ def test_save_codex_auth_prefers_disk_over_v2config_cache(monkeypatch, tmp_path:# the freshly-rotated one, not the stale cache value.auth = json.loads((tmp_path / ".codex" / "auth.json").read_text(encoding="utf-8"))assert auth["OPENAI_API_KEY"] == "sk-fresh-on-disk"- # And the V2Config write should reflect the same (disk-sourced) key.- assert fake_codex.api_key == "sk-fresh-on-disk"+ # And the persisted V2Config write reflects the same (disk-sourced) key.+ assert _load_v2_codex().api_key == "sk-fresh-on-disk"def test_save_codex_auth_falls_back_to_v2config_when_disk_empty(@@ -142,12 +155,7 @@ def test_save_codex_auth_rescues_disk_base_url_when_cache_empty(encoding="utf-8",)- fake_codex = types.SimpleNamespace(- auth_mode="api_key", api_key="sk-any", base_url=None- )- fake_agents = types.SimpleNamespace(codex=fake_codex)- fake_config = types.SimpleNamespace(agents=fake_agents, save=lambda: None)- monkeypatch.setattr(api, "load_config", lambda: fake_config)+ _seed_v2_codex(monkeypatch, tmp_path, auth_mode="api_key", api_key="sk-any")monkeypatch.setattr(api, "restart_backend", lambda name, **kwargs: {"ok": True})# No base_url in the payload: the disk relay URL must survive.@@ -157,9 +165,9 @@ def test_save_codex_auth_rescues_disk_base_url_when_cache_empty(toml = (codex_home / "config.toml").read_text(encoding="utf-8")assert 'base_url = "https://relay.example/v1"' in toml- # The rescued value is also mirrored into the V2Config cache so the- # next save (and the Settings form) starts from it.- assert fake_codex.base_url == "https://relay.example/v1"+ # The rescued value is also persisted into the V2Config mirror so+ # the next save (and the Settings form) starts from it.+ assert _load_v2_codex().base_url == "https://relay.example/v1"def test_save_codex_auth_prefers_disk_base_url_over_stale_cache(@@ -179,12 +187,9 @@ def test_save_codex_auth_prefers_disk_base_url_over_stale_cache(encoding="utf-8",)- fake_codex = types.SimpleNamespace(- auth_mode="api_key", api_key="sk-any", base_url="https://stale.example/v1"+ _seed_v2_codex(+ monkeypatch, tmp_path, auth_mode="api_key", api_key="sk-any", base_url="https://stale.example/v1")- fake_agents = types.SimpleNamespace(codex=fake_codex)- fake_config = types.SimpleNamespace(agents=fake_agents, save=lambda: None)- monkeypatch.setattr(api, "load_config", lambda: fake_config)monkeypatch.setattr(api, "restart_backend", lambda name, **kwargs: {"ok": True})result = api.save_codex_auth({"auth_mode": "api_key", "api_key": "sk-relay"})@@ -192,7 +197,7 @@ def test_save_codex_auth_prefers_disk_base_url_over_stale_cache(toml = (codex_home / "config.toml").read_text(encoding="utf-8")assert 'base_url = "https://fresh.example/v1"' in toml- assert fake_codex.base_url == "https://fresh.example/v1"+ assert _load_v2_codex().base_url == "https://fresh.example/v1"def test_save_codex_auth_restores_relay_from_oauth_marker(@@ -226,15 +231,12 @@ def test_save_codex_auth_restores_relay_from_oauth_marker(encoding="utf-8",)- fake_codex = types.SimpleNamespace(+ _seed_v2_codex(+ monkeypatch,+ tmp_path,auth_mode="oauth",- api_key=None,- base_url=None,oauth_relay_marker={"provider_id": "OpenAI", "base_url": "https://relay.example/v1"},)- fake_agents = types.SimpleNamespace(codex=fake_codex)- fake_config = types.SimpleNamespace(agents=fake_agents, save=lambda: None)- monkeypatch.setattr(api, "load_config", lambda: fake_config)monkeypatch.setattr(api, "restart_backend", lambda name, **kwargs: {"ok": True})result = api.save_codex_auth({"auth_mode": "api_key", "api_key": "sk-relay"})@@ -246,8 +248,9 @@ def test_save_codex_auth_restores_relay_from_oauth_marker(pointer = [line for line in toml.splitlines() if line.startswith("model_provider")]assert pointer == ['model_provider = "OpenAI"']assert 'base_url = "https://relay.example/v1"' in toml- assert fake_codex.oauth_relay_marker is None- assert fake_codex.base_url == "https://relay.example/v1"+ persisted = _load_v2_codex()+ assert persisted.oauth_relay_marker is None+ assert persisted.base_url == "https://relay.example/v1"def test_save_codex_auth_ignores_marker_after_external_api_key_switch(@@ -407,21 +410,20 @@ def test_remove_backend_api_key_clears_codex_relay_marker()(codex_home / "config.toml").write_text('model = "gpt-5.4"\n', encoding="utf-8")- fake_codex = types.SimpleNamespace(+ _seed_v2_codex(+ monkeypatch,+ tmp_path,auth_mode="api_key",api_key="sk-official",- base_url=None,oauth_relay_marker={"provider_id": "OpenAI", "base_url": "https://stale.example/v1"},)- fake_agents = types.SimpleNamespace(codex=fake_codex)- fake_config = types.SimpleNamespace(agents=fake_agents, save=lambda: None)- monkeypatch.setattr(api, "load_config", lambda: fake_config)monkeypatch.setattr(api, "restart_backend", lambda name, **kwargs: {"ok": True})result = api.remove_backend_api_key("codex")assert result.get("ok") is True- assert fake_codex.api_key is None- assert fake_codex.oauth_relay_marker is None+ persisted = _load_v2_codex()+ assert persisted.api_key is None+ assert persisted.oauth_relay_marker is Nonedef test_marker_ignored_when_credentials_may_live_in_keyring(@@ -527,13 +529,7 @@ def test_save_codex_auth_oauth_captures_relay_marker(encoding="utf-8",)- fake_codex = types.SimpleNamespace(- auth_mode="api_key", api_key="sk-relay", base_url=None, oauth_relay_marker=None- )- fake_config = types.SimpleNamespace(- agents=types.SimpleNamespace(codex=fake_codex), save=lambda: None- )- monkeypatch.setattr(api, "load_config", lambda: fake_config)+ _seed_v2_codex(monkeypatch, tmp_path, auth_mode="api_key", api_key="sk-relay")monkeypatch.setattr(api, "restart_backend", lambda name, **kwargs: {"ok": True})persisted: list[dict | None] = []import vibe.codex_config as codex_config_module@@ -549,8 +545,8 @@ def test_save_codex_auth_oauth_captures_relay_marker(# Durable pre-persist fired before the cleanup…assert persisted == [{"provider_id": "OpenAI", "base_url": "https://relay.example/v1"}]- # …and the owning V2Config write mirrors it.- assert fake_codex.oauth_relay_marker == {+ # …and the owning V2Config write persists it.+ assert _load_v2_codex().oauth_relay_marker == {"provider_id": "OpenAI","base_url": "https://relay.example/v1",}@@ -576,21 +572,17 @@ def test_save_codex_auth_oauth_official_key_transition_clears_marker('cli_auth_credentials_store = "file"\nmodel = "gpt-5.4"\n', encoding="utf-8")- fake_codex = types.SimpleNamespace(+ _seed_v2_codex(+ monkeypatch,+ tmp_path,auth_mode="api_key",- api_key=None,- base_url=None,oauth_relay_marker={"provider_id": "OpenAI", "base_url": "https://stale.example/v1"},)- fake_config = types.SimpleNamespace(- agents=types.SimpleNamespace(codex=fake_codex), save=lambda: None- )- monkeypatch.setattr(api, "load_config", lambda: fake_config)monkeypatch.setattr(api, "restart_backend", lambda name, **kwargs: {"ok": True})result = api.save_codex_auth({"auth_mode": "oauth"})assert result.get("ok") is True- assert fake_codex.oauth_relay_marker is None+ assert _load_v2_codex().oauth_relay_marker is Nonedef test_save_codex_auth_keeps_live_provider_when_urls_match_marker(@@ -656,17 +648,15 @@ def test_remove_backend_api_key_reports_v2_clear_failure()(codex_home / "config.toml").write_text('model = "gpt-5.4"\n', encoding="utf-8")- def boom():+ _seed_v2_codex(monkeypatch, tmp_path, auth_mode="api_key", api_key="sk-official")+ monkeypatch.setattr(api, "restart_backend", lambda name, **kwargs: {"ok": True})++ from config.v2_config import V2Config as _V2++ def _boom_save(self, config_path=None):raise OSError("disk full")- fake_codex = types.SimpleNamespace(- auth_mode="api_key", api_key="sk-official", base_url=None, oauth_relay_marker=None- )- fake_config = types.SimpleNamespace(- agents=types.SimpleNamespace(codex=fake_codex), save=boom- )- monkeypatch.setattr(api, "load_config", lambda: fake_config)- monkeypatch.setattr(api, "restart_backend", lambda name, **kwargs: {"ok": True})+ monkeypatch.setattr(_V2, "save", _boom_save)result = api.remove_backend_api_key("codex")assert result.get("ok") is True@@ -802,17 +792,16 @@ def test_save_codex_auth_reports_v2_mirror_failure('cli_auth_credentials_store = "file"\nmodel = "gpt-5.4"\n', encoding="utf-8")- def failing_save():+ _seed_v2_codex(monkeypatch, tmp_path, auth_mode="oauth")+ monkeypatch.setattr(api, "restart_backend", lambda name, **kwargs: {"ok": True})++ # Fail the transactional save itself (the mirror write path).+ from config.v2_config import V2Config as _V2++ def _failing_save(self, config_path=None):raise OSError("config.json unwritable")- fake_codex = types.SimpleNamespace(- auth_mode="oauth", api_key=None, base_url=None, oauth_relay_marker=None- )- fake_config = types.SimpleNamespace(- agents=types.SimpleNamespace(codex=fake_codex), save=failing_save- )- monkeypatch.setattr(api, "load_config", lambda: fake_config)- monkeypatch.setattr(api, "restart_backend", lambda name, **kwargs: {"ok": True})+ monkeypatch.setattr(_V2, "save", _failing_save)result = api.save_codex_auth({"auth_mode": "api_key", "api_key": "sk-new"})assert result.get("ok") is True@@ -839,17 +828,15 @@ def test_remove_backend_api_key_appends_v2_clear_failure_notice(encoding="utf-8",)- def failing_save():+ _seed_v2_codex(monkeypatch, tmp_path, auth_mode="api_key", api_key="sk-relay")+ monkeypatch.setattr(api, "restart_backend", lambda name, **kwargs: {"ok": True})++ from config.v2_config import V2Config as _V2++ def _failing_save(self, config_path=None):raise OSError("disk full")- fake_codex = types.SimpleNamespace(- auth_mode="api_key", api_key="sk-relay", base_url=None, oauth_relay_marker=None- )- fake_config = types.SimpleNamespace(- agents=types.SimpleNamespace(codex=fake_codex), save=failing_save- )- monkeypatch.setattr(api, "load_config", lambda: fake_config)- monkeypatch.setattr(api, "restart_backend", lambda name, **kwargs: {"ok": True})+ monkeypatch.setattr(_V2, "save", _failing_save)result = api.remove_backend_api_key("codex")assert result.get("ok") is Truediff --git a/tests/test_config_write_transaction.py b/tests/test_config_write_transaction.pyindex 3f50c28a8..72c43a56a 100644--- a/tests/test_config_write_transaction.py+++ b/tests/test_config_write_transaction.py@@ -99,6 +99,26 @@ def _ordinary_save_worker(home: str, attempted: threading.Event, done: threadingdone.set()+def _transaction_worker(+ home: str,+ attempted: threading.Event,+ entered: threading.Event,+ done: threading.Event,+) -> None:+ import os as _os++ _os.environ["AVIBE_HOME"] = home+ from config.v2_config import update_config_fields++ def mutator(config: V2Config) -> None:+ entered.set()+ config.language = "zh"++ attempted.set()+ update_config_fields(mutator)+ done.set()++def test_transaction_blocks_second_process_until_first_releases(isolated_config_home: Path,) -> None:@@ -182,6 +202,45 @@ def test_ordinary_save_waits_for_migration_file_lock(assert V2Config.load().language == "zh"+def test_transaction_load_and_mutator_wait_for_migration_file_lock(+ isolated_config_home: Path,+) -> None:+ """The transaction owns the migration lock before it reads or mutates."""++ import multiprocessing as mp++ ctx = mp.get_context("spawn")+ migration_entered = ctx.Event()+ release = ctx.Event()+ attempted = ctx.Event()+ mutator_entered = ctx.Event()+ done = ctx.Event()+ home = str(isolated_config_home.parent.parent)+ migration = ctx.Process(+ target=_migration_lock_worker,+ args=(home, migration_entered, release),+ )+ writer = ctx.Process(+ target=_transaction_worker,+ args=(home, attempted, mutator_entered, done),+ )++ migration.start()+ assert migration_entered.wait(timeout=15), "migration worker never acquired its lock"+ writer.start()+ assert attempted.wait(timeout=15), "transaction writer never reached the transaction"+ assert not mutator_entered.wait(timeout=1.0), "transaction mutated before taking the migration lock"++ release.set()+ migration.join(timeout=15)+ writer.join(timeout=15)+ assert migration.exitcode == 0, f"migration worker failed: {migration.exitcode}"+ assert writer.exitcode == 0, f"transaction writer failed: {writer.exitcode}"+ assert mutator_entered.is_set()+ assert done.is_set()+ assert V2Config.load().language == "zh"++def test_mutator_exception_aborts_without_write(isolated_config_home: Path) -> None:def boom(cfg: V2Config) -> None:cfg.language = "zh"diff --git a/tests/test_memory_config.py b/tests/test_memory_config.pyindex f2635e69f..e63b4448a 100644--- a/tests/test_memory_config.py+++ b/tests/test_memory_config.py@@ -10,7 +10,6 @@ import pytestfrom config.v2_config import (AgentsConfig,- CONFIG_LOCK,MemoryCloudConfig,MemoryConfig,MemoryEndpointConfig,@@ -144,20 +143,6 @@ def _memory_writer(done.set()-class _ObservedConfigLock:- def __init__(self, contender_entered: threading.Event) -> None:- self._contender_entered = contender_entered-- def __enter__(self):- if threading.current_thread().name == "second-config-save":- self._contender_entered.set()- CONFIG_LOCK.acquire()- return self-- def __exit__(self, *_args) -> None:- CONFIG_LOCK.release()--def test_memory_config_round_trips_and_hides_keys(tmp_path) -> None:config = V2Config.from_payload(_payload(@@ -1140,13 +1125,20 @@ def test_concurrent_generic_config_saves_preserve_both_updates(monkeypatch,tmp_path,) -> None:- """Generic read/merge/write stays one process-local linearized operation."""+ """Generic read/merge/write stays one linearized operation.++ With the cross-process config transaction (#1458 stage ③) the whole+ cycle — base load, merge, write — runs under the config file lock,+ so a second save that starts mid-cycle blocks at the lock (not the+ process-local CONFIG_LOCK), and both updates persist.+ """monkeypatch.setenv("AVIBE_HOME", str(tmp_path))V2Config.from_payload(_payload({})).save()first_merged = threading.Event()release_first = threading.Event()- second_entered = threading.Event()+ second_started = threading.Event()+ second_done = threading.Event()failures: list[BaseException] = []merge = api._deep_merge_dicts@@ -1164,16 +1156,20 @@ def test_concurrent_generic_config_saves_preserve_both_updates(except BaseException as exc:failures.append(exc)- monkeypatch.setattr(api, "CONFIG_LOCK", _ObservedConfigLock(second_entered))monkeypatch.setattr(api, "_deep_merge_dicts", hold_first_merge)first = _config_writer(save,args=({"language": "zh"},),name="first-config-save",)++ def observed_second_save() -> None:+ second_started.set()+ save({"runtime": {"log_level": "DEBUG"}})+ second_done.set()+second = _config_writer(- save,- args=({"runtime": {"log_level": "DEBUG"}},),+ observed_second_save,name="second-config-save",)@@ -1181,7 +1177,8 @@ def test_concurrent_generic_config_saves_preserve_both_updates(first.start()assert first_merged.wait(_WRITER_TIMEOUT_SECONDS)second.start()- assert second_entered.wait(_WRITER_TIMEOUT_SECONDS)+ assert second_started.wait(_WRITER_TIMEOUT_SECONDS)+ assert not second_done.wait(1.0), "second save entered while first held the lock"finally:release_first.set()_join_config_writers(first, second)diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.pyindex 1e44eebc7..575611f17 100644--- a/tests/test_ui_server_fastapi.py+++ b/tests/test_ui_server_fastapi.py@@ -2019,6 +2019,39 @@ def test_platform_runtime_fields_changed_detects_primary_only_change():)+def test_platform_runtime_fields_changed_ignores_idempotent_list_operation():+ from config.v2_config import V2Config++ payload = _full_config_payload()+ payload["platforms"] = {"enabled": ["discord"], "primary": "discord"}+ previous = V2Config.from_payload(payload)+ current = V2Config.from_payload(payload)++ assert (+ ui_server._platform_runtime_fields_changed(+ previous,+ current,+ {"__avibe_list_ops": {"platforms.enabled": {"add": ["discord"]}}},+ )+ is False+ )++ current = V2Config.from_payload(+ {+ **payload,+ "platforms": {"enabled": ["discord", "slack"], "primary": "discord"},+ }+ )+ assert (+ ui_server._platform_runtime_fields_changed(+ previous,+ current,+ {"__avibe_list_ops": {"platforms.enabled": {"add": ["slack"]}}},+ )+ is True+ )++def test_changed_agent_backend_runtimes_uses_backend_runtime_projection():from config.v2_config import V2Configdiff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.pyindex 749f20c62..ea8762410 100644--- a/tests/test_web_oauth_flow.py+++ b/tests/test_web_oauth_flow.py@@ -70,6 +70,10 @@ def isolated_claude_config_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch)claude_home = tmp_path / "default-claude"claude_home.mkdir()monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(claude_home))+ # V2Config writes go through the cross-process transaction, which+ # resolves config.json from AVIBE_HOME — isolate it so no test+ # touches the developer's real ~/.avibe.+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "avibe-home"))@pytest.fixture@@ -333,7 +337,6 @@ def test_codex_oauth_success_clears_api_key_state('base_url = "https://relay.example/v1"\n',encoding="utf-8",)- saves: list[str] = []codex_cfg = SimpleNamespace(auth_mode="api_key",api_key="sk-old",@@ -343,8 +346,18 @@ def test_codex_oauth_success_clears_api_key_state(service.controller.config = SimpleNamespace(language="en",agents=SimpleNamespace(codex=codex_cfg),- save=lambda: saves.append("saved"),+ save=lambda: None,)+ # Seed the real (isolated) config with the api_key pre-state: the+ # transaction computes its decisions from the lock-fresh file, not+ # the live fake, so the transition must be warranted on disk too.+ from config.v2_config import V2Config++ real_cfg = V2Config.default()+ real_cfg.agents.codex.auth_mode = "api_key"+ real_cfg.agents.codex.api_key = "sk-old"+ real_cfg.agents.codex.base_url = "https://relay.example/v1"+ real_cfg.save()_run(service._invoke_post_web_success_hook("codex"))@@ -366,7 +379,16 @@ def test_codex_oauth_success_clears_api_key_state("provider_id": "OpenAI","base_url": "https://relay.example/v1",}- assert saves == ["saved"]+ # Persistence lands through the cross-process config transaction+ # (the stub save is no longer invoked); the marker is durable in the+ # isolated real config file.+ from config.v2_config import V2Config++ persisted_codex = V2Config.load().agents.codex+ assert persisted_codex.oauth_relay_marker == {+ "provider_id": "OpenAI",+ "base_url": "https://relay.example/v1",+ }# A repeated OAuth transition captures nothing (the pointer is# already gone) and must RETAIN the marker rather than erase it —diff --git a/ui/eslint-baseline.json b/ui/eslint-baseline.jsonindex fa6281acd..20e15b491 100644--- a/ui/eslint-baseline.json+++ b/ui/eslint-baseline.json@@ -20,17 +20,17 @@"react-hooks/set-state-in-effect": 1},"src/components/Wizard.tsx": {- "@typescript-eslint/no-explicit-any": 9+ "@typescript-eslint/no-explicit-any": 8},"src/components/settings/SettingsBackendsPage.tsx": {"@typescript-eslint/no-explicit-any": 1},"src/components/settings/SettingsMessagingPage.tsx": {- "@typescript-eslint/no-explicit-any": 3,+ "@typescript-eslint/no-explicit-any": 2,"react-hooks/set-state-in-effect": 1},"src/components/settings/SettingsPlatformsPage.tsx": {- "@typescript-eslint/no-explicit-any": 10+ "@typescript-eslint/no-explicit-any": 9},"src/components/settings/SettingsServicePage.tsx": {"@typescript-eslint/no-explicit-any": 4@@ -42,7 +42,7 @@"@typescript-eslint/no-explicit-any": 1},"src/components/settings/shared/useBackendRuntime.ts": {- "@typescript-eslint/no-explicit-any": 2+ "@typescript-eslint/no-explicit-any": 1},"src/components/settings/shared/useOAuthFlowLock.ts": {"react-hooks/preserve-manual-memoization": 1@@ -70,13 +70,13 @@"@typescript-eslint/no-explicit-any": 2},"src/components/steps/PlatformSelection.tsx": {- "@typescript-eslint/no-explicit-any": 7+ "@typescript-eslint/no-explicit-any": 10},"src/components/steps/SlackConfig.tsx": {"@typescript-eslint/no-explicit-any": 4},"src/components/steps/Summary.tsx": {- "@typescript-eslint/no-explicit-any": 9+ "@typescript-eslint/no-explicit-any": 5},"src/components/steps/TelegramConfig.tsx": {"@typescript-eslint/no-explicit-any": 4@@ -119,7 +119,7 @@"@typescript-eslint/no-explicit-any": 5},"src/context/ApiContext.tsx": {- "@typescript-eslint/no-explicit-any": 50,+ "@typescript-eslint/no-explicit-any": 49,"react-refresh/only-export-components": 1},"src/context/DockProvider.tsx": {diff --git a/ui/src/components/LanguageSwitcher.tsx b/ui/src/components/LanguageSwitcher.tsxindex b668b3d42..8a4dc0de3 100644--- a/ui/src/components/LanguageSwitcher.tsx+++ b/ui/src/components/LanguageSwitcher.tsx@@ -3,10 +3,11 @@ import { useTranslation } from 'react-i18next';import { Check } from 'lucide-react';import clsx from 'clsx';import { useApi } from '../context/ApiContext';+import { setConfigField } from '../lib/configMutations';export const LanguageSwitcher: React.FC<{ openUpward?: boolean }> = ({ openUpward = false }) => {const { i18n, t } = useTranslation();- const { getConfig, saveConfig } = useApi();+ const { getConfig, mutateConfig } = useApi();const [isOpen, setIsOpen] = useState(false);const wrapRef = useRef<HTMLDivElement>(null);@@ -54,7 +55,7 @@ export const LanguageSwitcher: React.FC<{ openUpward?: boolean }> = ({ openUpwarif (code === i18n.language) return;i18n.changeLanguage(code);try {- await saveConfig({ language: code });+ await mutateConfig([setConfigField(['language'], code)]);} catch {// Ignore save errors - language change already applied locally}diff --git a/ui/src/components/VersionBadge.tsx b/ui/src/components/VersionBadge.tsxindex 72b92c00b..ac06aa980 100644--- a/ui/src/components/VersionBadge.tsx+++ b/ui/src/components/VersionBadge.tsx@@ -7,6 +7,7 @@ import { ToggleSwitch } from './settings/SettingsPrimitives';import { Button } from './ui/button';import { badgeVariants } from './ui/badge-variants';import { cn } from '@/lib/utils';+import { setConfigField } from '@/lib/configMutations';import { scheduleUpgradeReload } from '../lib/upgradeReload';// Dev / regression builds carry long versions like@@ -62,7 +63,7 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =const handleAutoUpdateToggle = async (enabled: boolean) => {setSavingAutoUpdate(true);try {- await api.saveConfig({ update: { auto_update: enabled } });+ await api.mutateConfig([setConfigField(['update', 'auto_update'], enabled)]);setAutoUpdate(enabled);} catch (e) {console.error('Failed to save auto-update setting:', e);diff --git a/ui/src/components/Wizard.tsx b/ui/src/components/Wizard.tsxindex 0a5b78cbd..689b9f5ba 100644--- a/ui/src/components/Wizard.tsx+++ b/ui/src/components/Wizard.tsx@@ -15,113 +15,24 @@ import { useApi } from '../context/ApiContext';import clsx from 'clsx';import {getEnabledPlatforms,- platformHasRunnableConfig,platformSupportsChannels,} from '../lib/platforms';-import { withoutConfiguredSecretMarker, withSecretDraft, withSecretDrafts } from '../lib/secretFields';+import {+ buildWizardStepMutations,+ collectWizardEnabledPlatformDelta,+ type WizardEnabledPlatformDelta,+} from '../lib/wizardConfigMutations';import { WizardChrome } from './visual';-const getPersistableWizardPlatforms = (data: any) =>- getEnabledPlatforms(data).filter((platform) => platformHasRunnableConfig(data, platform));--const buildConfigPayload = (data: any, enabledPlatformOverride?: string[]) => {- const enabledPlatforms = enabledPlatformOverride ?? getEnabledPlatforms(data);-- return {- // No user-facing primary platform: the backend derives an internal default- // from ``platforms.enabled``, so the wizard sends only the enabled set.- platforms: {- enabled: enabledPlatforms,- },- mode: data.mode || 'self_host',- version: 'v2',- slack: {- // Preserve all existing slack fields- ...withSecretDrafts(data.slack, {- bot_token: data.slack?.bot_token,- app_token: data.slack?.app_token,- }),- // Override only the fields that setup modifies- require_mention: data.slack?.require_mention || false,- },- discord: {- ...withSecretDraft(data.discord, 'bot_token', data.discord?.bot_token),- require_mention: data.discord?.require_mention || false,- },- telegram: {- ...withSecretDraft(data.telegram, 'bot_token', data.telegram?.bot_token),- require_mention: data.telegram?.require_mention ?? true,- forum_auto_topic: data.telegram?.forum_auto_topic ?? true,- use_webhook: data.telegram?.use_webhook ?? false,- },- lark: (() => {- const lark = data.lark || {};- const appId = lark.app_id || '';- const appIdChanged = Boolean(lark.original_app_id && appId && appId !== lark.original_app_id);- const base = appIdChanged ? withoutConfiguredSecretMarker(lark, 'app_secret') : lark;- return {- ...withSecretDraft(base, 'app_secret', lark.app_secret),- app_id: appId,- domain: lark.domain || 'feishu',- require_mention: lark.require_mention || false,- };- })(),- wechat: {- ...withSecretDraft(data.wechat, 'bot_token', data.wechat?.bot_token),- base_url: data.wechat?.base_url || 'https://ilinkai.weixin.qq.com',- cdn_base_url: data.wechat?.cdn_base_url || 'https://novac2c.cdn.weixin.qq.com/c2c',- require_mention: data.wechat?.require_mention || false,- },- runtime: {- // Preserve existing runtime config- ...data.runtime,- default_cwd: data.default_cwd || data.runtime?.default_cwd || '.',- },- agents: {- opencode: {- // Preserve existing opencode config- ...data.agents?.opencode,- enabled: data.agents?.opencode?.enabled ?? true,- cli_path: data.agents?.opencode?.cli_path || 'opencode',- default_agent: data.opencode_default_agent ?? data.agents?.opencode?.default_agent ?? null,- default_reasoning_effort: data.opencode_default_reasoning_effort ?? data.agents?.opencode?.default_reasoning_effort ?? null,- },- claude: {- // Preserve existing claude config- ...data.agents?.claude,- enabled: data.agents?.claude?.enabled ?? true,- cli_path: data.agents?.claude?.cli_path || 'claude',- },- codex: {- // Preserve existing codex config- ...data.agents?.codex,- enabled: data.agents?.codex?.enabled ?? false,- cli_path: data.agents?.codex?.cli_path || 'codex',- },- },- // Preserve gateway config entirely- gateway: data.gateway,- ui: {- // Preserve existing ui config- ...data.ui,- setup_host: data.ui?.setup_host || '127.0.0.1',- setup_port: data.ui?.setup_port || 5123,- },- // Preserve existing update config entirely- update: data.update,- // Preserve ack_mode- ack_mode: data.ack_mode,- show_duration: data.show_duration ?? false,- // Preserve language- language: data.language,- };-};-export const Wizard: React.FC = () => {const { t } = useTranslation();const api = useApi();const [currentStep, setCurrentStep] = useState(0);- const [data, setData] = useState<any>({ show_duration: false });+ const [data, setData] = useState<any>({+ show_duration: false,+ __wizardEnabledAdds: [],+ __wizardEnabledRemoves: [],+ });const [loaded, setLoaded] = useState(false);const steps = React.useMemo(() => {@@ -192,6 +103,17 @@ export const Wizard: React.FC = () => {...configWithCatalog,discordGuildAllowlist: discordSettings?.guild_allowlist || [],channelConfigsByPlatform,+ // Baseline for deselection encoding: platforms enabled when+ // the wizard loaded. A user deselecting one of these must+ // produce a REMOVE operation on save — an add-only verb+ // would silently leave the adapter enabled and receiving+ // messages. Concurrent additions by other processes are NOT+ // in this baseline and are preserved.+ __wizardEnabledBaseline: enabledPlatforms,+ // Finish may reassert only list operations that this wizard has+ // actually submitted. These are intent records, not config fields.+ __wizardEnabledAdds: [],+ __wizardEnabledRemoves: [],agents: {opencode: config.agents?.opencode,claude: config.agents?.claude,@@ -219,11 +141,39 @@ export const Wizard: React.FC = () => {const nextData = {...data,...(platformsChanged ? { channelConfigsByPlatform: {} } : {}),- ...(nextPlatforms.includes('wechat') ? { show_duration: false } : {}),+ // Keep a loaded WeChat value intact until the wizard-owned platform or+ // Finish mutation persists the required override. Normalizing it on+ // unrelated steps would erase the baseline and make Finish believe the+ // persisted value is already false.+ ...(nextPlatforms.includes('wechat') && !previousPlatforms.includes('wechat')+ ? { show_duration: false }+ : {}),...stepData,};+ const submittedDelta = await persistStep(steps[currentStep].id, stepData, data, nextData);+ const previousAdds = Array.isArray(data.__wizardEnabledAdds)+ ? data.__wizardEnabledAdds.filter(+ (platform: unknown): platform is string => typeof platform === 'string',+ )+ : [];+ const previousRemoves = Array.isArray(data.__wizardEnabledRemoves)+ ? data.__wizardEnabledRemoves.filter(+ (platform: unknown): platform is string => typeof platform === 'string',+ )+ : [];+ const wizardAdds = new Set(previousAdds);+ const wizardRemoves = new Set(previousRemoves);+ for (const platform of submittedDelta.remove) {+ wizardAdds.delete(platform);+ wizardRemoves.add(platform);+ }+ for (const platform of submittedDelta.add) {+ wizardRemoves.delete(platform);+ wizardAdds.add(platform);+ }+ nextData.__wizardEnabledAdds = [...wizardAdds];+ nextData.__wizardEnabledRemoves = [...wizardRemoves];setData(nextData);- await persistStep(stepData, nextData);if (currentStep < steps.length - 1) {setCurrentStep(currentStep + 1);}@@ -235,35 +185,15 @@ export const Wizard: React.FC = () => {}};- const persistStep = async (stepData: any, mergedData: any) => {- if (!mergedData) return;- const platformSelectionOnly =- Boolean(stepData.platforms || stepData.platform) &&- !stepData.agents &&- !stepData.slack &&- !stepData.discord &&- !stepData.telegram &&- !stepData.lark &&- !stepData.wechat &&- !stepData.mode &&- !stepData.channelConfigsByPlatform;- const shouldPersistConfig =- !platformSelectionOnly &&- Boolean(- mergedData.agents ||- mergedData.slack ||- mergedData.discord ||- mergedData.telegram ||- mergedData.lark ||- mergedData.wechat ||- mergedData.mode ||- mergedData.platforms ||- mergedData.platform ||- mergedData.channelConfigsByPlatform- );- if (shouldPersistConfig) {- await api.saveConfig(buildConfigPayload(mergedData, getPersistableWizardPlatforms(mergedData)));- }+ const persistStep = async (+ stepId: string,+ stepData: any,+ before: any,+ mergedData: any,+ ): Promise<WizardEnabledPlatformDelta> => {+ const mutations = buildWizardStepMutations({ stepId, before, stepData, after: mergedData });+ if (mutations.length > 0) await api.mutateConfig(mutations);+const discordGuildAllowlist = stepData?.discordGuildAllowlist;if (Array.isArray(discordGuildAllowlist) &&@@ -284,6 +214,7 @@ export const Wizard: React.FC = () => {}}}+ return collectWizardEnabledPlatformDelta(mutations);};const CurrentComponent = steps[currentStep].component;diff --git a/ui/src/components/settings/SettingsBackendsPage.tsx b/ui/src/components/settings/SettingsBackendsPage.tsxindex 2326b792d..63a4a2ff4 100644--- a/ui/src/components/settings/SettingsBackendsPage.tsx+++ b/ui/src/components/settings/SettingsBackendsPage.tsx@@ -10,6 +10,7 @@ import { SettingsPageShell } from './SettingsPageShell';import { useApi } from '@/context/ApiContext';import { useToast } from '@/context/ToastContext';import { AGENT_BACKENDS, DEFAULT_AGENT_STATE } from '@/lib/agentBackends';+import { configChanges } from '@/lib/configMutations';import { errorMessage } from '@/lib/errorMessage';// Mirrors design.pen qVHh4 (VR/CM/Backends): three horizontal cards@@ -107,11 +108,13 @@ export const SettingsBackendsPage: React.FC = () => {// eslint-disable-next-line react-hooks/exhaustive-deps}, [loaded]);- const persist = async (nextAgents: Record<string, AgentState>) => {+ // Patch-write shape: send only the edited backend's field. A whole+ // ``agents`` section round-tripped from mount-time state would+ // overwrite concurrent cross-process writes (e.g. an installer+ // updating another backend's cli_path) inside the locked merge.+ const persistBackendField = async (name: string, patch: Partial<AgentState>) => {try {- await api.saveConfig({- agents: nextAgents,- });+ await api.mutateConfig(configChanges({}, patch, ['agents', name]));showToast(t('common.saved'), 'success');} catch (e) {showToast(errorMessage(e) || t('common.saveFailed'), 'error');@@ -119,9 +122,8 @@ export const SettingsBackendsPage: React.FC = () => {};const handleToggle = async (name: string, enabled: boolean) => {- const nextAgents = { ...agents, [name]: { ...agents[name], enabled } };- setAgents(nextAgents);- await persist(nextAgents);+ setAgents((prev) => ({ ...prev, [name]: { ...prev[name], enabled } }));+ await persistBackendField(name, { enabled });};const refreshDetectionFor = async (name: string, cli_path: string) => {diff --git a/ui/src/components/settings/SettingsMessagingPage.test.tsx b/ui/src/components/settings/SettingsMessagingPage.test.tsxindex 00ebb5725..8e6d9b071 100644--- a/ui/src/components/settings/SettingsMessagingPage.test.tsx+++ b/ui/src/components/settings/SettingsMessagingPage.test.tsx@@ -11,10 +11,14 @@ import {type InstanceAuthorizationValue,} from '../../context/InstanceAuthorizationContext';import { OWNER_INSTANCE_CAPABILITIES } from '../../lib/sessionInfo';+import {+ configMutationsToPayload,+ type ConfigMutation,+} from '../../lib/configMutations';const api = vi.hoisted(() => ({getConfig: vi.fn(),- saveConfig: vi.fn(),+ mutateConfig: vi.fn(),}));const translate = vi.hoisted(() => (key: string) => key);@@ -126,10 +130,17 @@ function renderPage(context: InstanceAuthorizationValue) {);}+function mutationPayload(callIndex = 0) {+ const mutations = api.mutateConfig.mock.calls[callIndex]?.[0] as+ | readonly ConfigMutation[]+ | undefined;+ return mutations ? configMutationsToPayload(mutations) : undefined;+}+describe('SettingsMessagingPage locality gating', () => {beforeEach(() => {api.getConfig.mockResolvedValue(baseConfig);- api.saveConfig.mockResolvedValue(baseConfig);+ api.mutateConfig.mockResolvedValue(baseConfig);});afterEach(() => {@@ -207,7 +218,7 @@ describe('SettingsMessagingPage locality gating', () => {expect(toggle).toBeTruthy();await user.click(toggle!);- expect(api.saveConfig).toHaveBeenCalledWith({+ expect(mutationPayload()).toEqual({audio_asr: { enabled: false, enabled_configured: true },});});@@ -219,7 +230,7 @@ describe('SettingsMessagingPage locality gating', () => {const select = await screen.findByDisplayValue('dashboard.ackTyping');await user.selectOptions(select, 'message');- expect(api.saveConfig).toHaveBeenCalledWith({ ack_mode: 'message' });+ expect(mutationPayload()).toEqual({ ack_mode: 'message' });});it('hides Slack preview controls from Editors when they cannot manage the instance', async () => {@@ -245,17 +256,20 @@ describe('SettingsMessagingPage locality gating', () => {const row = screen.getByText('dashboard.slackLinkPreviews').closest('div.flex.flex-col.gap-3');await user.click(row?.querySelector('[role="switch"]') as HTMLButtonElement);- expect(api.saveConfig).toHaveBeenCalledWith({ slack: { disable_link_unfurl: true } });+ expect(mutationPayload()).toEqual({ slack: { disable_link_unfurl: true } });});- it('never posts an empty patch from any control an Editor is offered', async () => {+ it.each([+ ['Editor', remoteEditor],+ ['local Owner', localOwner],+ ])('never posts an empty mutation from any control offered to a %s', async (_label, context) => {// The property, not today's control list: a field-specific save carries only// the control's own patch, so any control rendered without one posts ``{}``// — a save that reports success and loses the change on reload. Sweeping// whatever is rendered catches the next control added without a patch; an// enumeration of the current controls never would.const user = userEvent.setup();- renderPage(remoteEditor);+ renderPage(context);await screen.findByText('dashboard.ackMode');const switches = () => screen.queryAllByRole('switch') as HTMLButtonElement[];@@ -267,11 +281,13 @@ describe('SettingsMessagingPage locality gating', () => {// ``persist`` and posts nothing, and both look identical at the end of a// sweep once a later control's successful save has cleared the state.const recordInteraction = async (label: string, act: () => Promise<void>) => {- const before = api.saveConfig.mock.calls.length;+ const before = api.mutateConfig.mock.calls.length;exercised.add(label);await act();- const patch = api.saveConfig.mock.calls[before]?.[0] as Record<string, unknown> | undefined;- if (!patch || Object.keys(patch).length === 0) unsaved.push(label);+ const mutations = api.mutateConfig.mock.calls[before]?.[0] as+ | readonly ConfigMutation[]+ | undefined;+ if (!mutations || mutations.length === 0) unsaved.push(label);};// Two rounds, re-querying every step: toggling a parent reveals a childdiff --git a/ui/src/components/settings/SettingsMessagingPage.tsx b/ui/src/components/settings/SettingsMessagingPage.tsxindex 2db9b77da..18cce7770 100644--- a/ui/src/components/settings/SettingsMessagingPage.tsx+++ b/ui/src/components/settings/SettingsMessagingPage.tsx@@ -25,42 +25,7 @@ import {MIN_CHAT_MESSAGE_FONT_SIZE,normalizeChatMessageFontSize,} from '@/lib/chatDisplay';--const OWNER_SAVE_KEYS = [- 'platforms',- 'ack_mode',- 'show_duration',- 'include_time_info',- 'include_user_info',- 'reply_enhancements',- 'show_pages_prompt',- 'agent_progress_style',- 'audio_asr',- 'slack',- 'discord',- 'telegram',- 'lark',- 'wechat',- 'agents',-] as const;--function buildMessagePatch(- config: any,- extraPatch: Record<string, unknown> = {},- { fieldSpecific }: { fieldSpecific: boolean },-) {- // Owners still send the existing messaging snapshot so a first-time save of- // an older page does not drop sibling fields. Editors send only the changed- // field so an unrelated autosave cannot overwrite a newer ASR value.- if (fieldSpecific) {- return extraPatch;- }- const patch: Record<string, unknown> = {};- for (const key of OWNER_SAVE_KEYS) {- patch[key] = config?.[key];- }- return { ...patch, ...extraPatch };-}+import { configChanges } from '@/lib/configMutations';function formatSavedAt(value: number | null, t: (key: string) => string) {if (!value) return t('settings.messagingStatusIdle');@@ -104,20 +69,17 @@ export const SettingsMessagingPage: React.FC = () => {);const persist = async (nextConfig: any, extraPatch?: Record<string, unknown>) => {- const fieldSpecific = !canUseSystem;- // A field-specific save carries only what the control passes, so a control- // without an explicit patch would post ``{}``: a silent success that drops- // the change on reload. Controls that write owner-only fields have no- // Editor patch by design and must be gated out below; reaching here means- // one was rendered anyway, so fail visibly instead of pretending to save.- if (fieldSpecific && !extraPatch) {+ // Field-specific for everyone (#1458 stage ③): the save carries only+ // the control's patch. A control without an explicit patch would post+ // ``{}`` (silent no-op success) — fail visibly instead.+ if (!extraPatch) {setSaveError(t('common.saveFailed'));return;}setConfig(nextConfig);setSaveError(null);try {- await api.saveConfig(buildMessagePatch(nextConfig, extraPatch, { fieldSpecific }));+ await api.mutateConfig(configChanges({}, extraPatch));setSavedAt(Date.now());} catch (error) {setSaveError(error instanceof Error ? error.message : t('common.saveFailed'));@@ -411,16 +373,23 @@ export const SettingsMessagingPage: React.FC = () => {value={config.agents?.opencode?.error_retry_limit ?? 1}onChange={(event) => {const limit = Math.max(0, Math.min(10, Number(event.target.value) || 0));- void persist({- ...config,- agents: {- ...(config.agents || {}),- opencode: {- ...(config.agents?.opencode || {}),- error_retry_limit: limit,+ void persist(+ {+ ...config,+ agents: {+ ...(config.agents || {}),+ opencode: {+ ...(config.agents?.opencode || {}),+ error_retry_limit: limit,+ },+ },+ },+ {+ agents: {+ opencode: { error_retry_limit: limit },},},- });+ );}}className="w-24 text-center font-mono"/>@@ -443,16 +412,23 @@ export const SettingsMessagingPage: React.FC = () => {0,Math.min(1440, Number(event.target.value) || 0));- void persist({- ...config,- agents: {- ...(config.agents || {}),- opencode: {- ...(config.agents?.opencode || {}),- active_turn_timeout_seconds: Math.round(minutes * 60),+ void persist(+ {+ ...config,+ agents: {+ ...(config.agents || {}),+ opencode: {+ ...(config.agents?.opencode || {}),+ active_turn_timeout_seconds: Math.round(minutes * 60),+ },+ },+ },+ {+ agents: {+ opencode: { active_turn_timeout_seconds: Math.round(minutes * 60) },},},- });+ );}}className="w-24 text-center font-mono"/>@@ -508,10 +484,13 @@ export const SettingsMessagingPage: React.FC = () => {<ToggleSwitchenabled={config.show_pages_prompt !== false}onClick={() =>- void persist({- ...config,- show_pages_prompt: !(config.show_pages_prompt !== false),- })+ void persist(+ {+ ...config,+ show_pages_prompt: !(config.show_pages_prompt !== false),+ },+ { show_pages_prompt: !(config.show_pages_prompt !== false) },+ )}/>}diff --git a/ui/src/components/settings/SettingsPlatformsPage.tsx b/ui/src/components/settings/SettingsPlatformsPage.tsxindex 4ba240710..e955abd3e 100644--- a/ui/src/components/settings/SettingsPlatformsPage.tsx+++ b/ui/src/components/settings/SettingsPlatformsPage.tsx@@ -5,6 +5,11 @@ import { Check, ChevronUp, Loader2, Pencil } from 'lucide-react';import { useApi } from '@/context/ApiContext';import { useToast } from '@/context/ToastContext';+import {+ configChanges,+ updateEnabledPlatforms,+ type ConfigMutation,+} from '@/lib/configMutations';import {getEnabledPlatforms,getImPlatforms,@@ -81,8 +86,9 @@ export const SettingsPlatformsPage: React.FC = () => {return togglablePlatforms.filter((p) => shown.has(p.id)).map((p) => p.id);}, [togglablePlatforms, enabledPlatforms, revealed]);- const saveConfig = async (nextData: any) => {- const savedConfig = await api.saveConfig(nextData);+ const saveMutations = async (mutations: readonly ConfigMutation[]) => {+ if (mutations.length === 0) return config;+ const savedConfig = await api.mutateConfig(mutations);setConfig(savedConfig);return savedConfig;};@@ -123,11 +129,21 @@ export const SettingsPlatformsPage: React.FC = () => {return true;};- const persistEnabled = async (nextEnabled: string[]) => {+ // Patch-write shape with list OPERATIONS: sending the whole enabled+ // list (even as a section patch) replaces it wholesale in the merge —+ // a stale browser snapshot would drop platforms another process+ // enabled (e.g. WeChat QR confirmation). The backend verb applies+ // add/remove against the lock-fresh persisted list instead.+ const persistEnabledChange = async (+ op: 'add' | 'remove',+ platform: string+ ): Promise<boolean> => {setRestartPhase('saving');try {try {- const savedConfig = await saveConfig({ ...config, platforms: { enabled: nextEnabled } });+ const savedConfig = await saveMutations([+ updateEnabledPlatforms({ [op]: [platform] }),+ ]);showApplyResult(savedConfig);} catch {showToast(t('common.saveFailed'), 'error');@@ -144,7 +160,7 @@ export const SettingsPlatformsPage: React.FC = () => {const doDisable = async (id: string) => {setBusyPlatform(id);try {- await persistEnabled(enabledPlatforms.filter((p) => p !== id));+ await persistEnabledChange('remove', id);setRevealed((prev) => prev.filter((p) => p !== id));setOpenConfig((prev) => (prev === id ? null : prev));} finally {@@ -170,7 +186,7 @@ export const SettingsPlatformsPage: React.FC = () => {// Already configured → checking enables it immediately.setBusyPlatform(id);try {- await persistEnabled([...enabledPlatforms, id]);+ await persistEnabledChange('add', id);} finally {setBusyPlatform(null);}@@ -191,7 +207,15 @@ export const SettingsPlatformsPage: React.FC = () => {try {let savedConfig: any;try {- savedConfig = await saveConfig({ ...nextData, platforms: { enabled: enabledPlatforms } });+ // Patch-write shape: ONLY the platform section this card owns.+ // The enabled list must never ride along as a stale snapshot —+ // replacing it wholesale would drop platforms another process+ // enabled (e.g. WeChat QR confirmation). Enablement changes go+ // through the list-operation verb below, which mutates the+ // lock-fresh persisted list.+ savedConfig = await saveMutations(+ configChanges(config?.[platform], nextData?.[platform], [platform]),+ );} catch {showToast(t('common.saveFailed'), 'error');return;@@ -211,9 +235,10 @@ export const SettingsPlatformsPage: React.FC = () => {}return;}- const nextEnabled = [...enabledPlatforms, platform];try {- savedConfig = await saveConfig({ ...savedConfig, platforms: { enabled: nextEnabled } });+ savedConfig = await saveMutations([+ updateEnabledPlatforms({ add: [platform] }),+ ]);} catch {showToast(t('platform.restartFailed'), 'error');return;diff --git a/ui/src/components/settings/SettingsServicePage.tsx b/ui/src/components/settings/SettingsServicePage.tsxindex 3a7a777dd..21ca46d99 100644--- a/ui/src/components/settings/SettingsServicePage.tsx+++ b/ui/src/components/settings/SettingsServicePage.tsx@@ -10,6 +10,7 @@ import { apiFetch } from '@/lib/apiFetch';import { SettingsPageShell } from './SettingsPageShell';import { CompactField, SettingsPanel, SettingsRow } from './SettingsPrimitives';import { Button } from '@/components/ui/button';+import { setConfigField } from '@/lib/configMutations';import { applyAppTitle } from '@/lib/documentTitle';// Mirrors design.pen mHUcm (VR/CM/Service): two cards.@@ -64,7 +65,10 @@ export const SettingsServicePage: React.FC = () => {// would persist any unsaved instance_name draft the user typed but// didn't Save on that row. The backend deep-merges config saves, so// instance_name and chat_message_font_size are preserved regardless.- await api.saveConfig({ ui: uiPayload });+ await api.mutateConfig([+ setConfigField(['ui', 'setup_host'], uiPayload.setup_host),+ setConfigField(['ui', 'setup_port'], uiPayload.setup_port),+ ]);await apiFetch('/api/ui/reload', {method: 'POST',headers: { 'Content-Type': 'application/json' },@@ -144,7 +148,7 @@ export const SettingsServicePage: React.FC = () => {// handleUiSaveRestart performs — so the running UI keeps the old bind// while the next restart silently moves to the unsaved address. The// backend deep-merges config saves, so host/port are preserved.- await api.saveConfig({ ui: { instance_name: instanceName } });+ await api.mutateConfig([setConfigField(['ui', 'instance_name'], instanceName)]);// Reflect the new title immediately. default_instance_name is the// read-only, server-computed fallback (unaffected by host/port edits).applyAppTitle({diff --git a/ui/src/components/settings/shared/useBackendRuntime.ts b/ui/src/components/settings/shared/useBackendRuntime.tsindex b36a5e799..139a56dad 100644--- a/ui/src/components/settings/shared/useBackendRuntime.ts+++ b/ui/src/components/settings/shared/useBackendRuntime.ts@@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next';import { useApi } from '@/context/ApiContext';import { useToast } from '@/context/ToastContext';+import { setConfigField } from '@/lib/configMutations';import { errorMessage } from '@/lib/errorMessage';export type CliStatus = 'unknown' | 'ok' | 'missing';@@ -62,11 +63,6 @@ export interface BackendRuntimeState {handleLifecycleChanged: (info: { installedPath?: string | null } | undefined | null) => Promise<void>;}-const withoutLegacyDefaultBackend = (agents: Record<string, any> | undefined | null) => {- const { default_backend: _legacyDefaultBackend, ...rest } = agents || {};- return rest;-};-type BackendRuntimeApplyResult = {hot_reconciled?: boolean;restart_scheduled?: boolean;@@ -201,16 +197,16 @@ export function useBackendRuntime({const onSaveRuntime = useCallback(async () => {setSavingRuntime(true);try {- const config = await api.getConfig();- const nextAgents = {- ...withoutLegacyDefaultBackend(config?.agents),- [backend]: {- ...(config?.agents?.[backend] || {}),- enabled,- cli_path: cliPath || defaultCli,- },- };- const saved = await api.saveConfig({ agents: nextAgents });+ // Patch-write shape: only THIS backend's fields. Rebuilding the+ // whole agents section from a pre-save GET would overwrite a+ // concurrent cross-process write (e.g. an installer updating+ // another backend's cli_path) inside the locked merge, and the+ // subsequent rolling refresh could switch the live backend to the+ // obsolete path.+ const saved = await api.mutateConfig([+ setConfigField(['agents', backend, 'enabled'], enabled),+ setConfigField(['agents', backend, 'cli_path'], cliPath || defaultCli),+ ]);// The config boundary owns both persistence and live runtime// reconciliation. A second route-level restart would refresh the backend// twice and could interrupt a transport that was just rebuilt.@@ -234,17 +230,10 @@ export function useBackendRuntime({void (async () => {let saved = false;try {- const config = await api.getConfig();- const nextAgents = {- ...withoutLegacyDefaultBackend(config?.agents),- [backend]: {- ...(config?.agents?.[backend] || {}),- enabled: next,- },- };- const savedConfig = await api.saveConfig({- agents: nextAgents,- });+ // Patch-write shape: only this backend's enabled flag.+ const savedConfig = await api.mutateConfig([+ setConfigField(['agents', backend, 'enabled'], next),+ ]);saved = true;assertBackendRuntimeApplied(savedConfig, t('common.saveFailed'));} catch (e) {diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsxindex 599079466..690c21e55 100644--- a/ui/src/components/steps/ChannelList.tsx+++ b/ui/src/components/steps/ChannelList.tsx@@ -22,6 +22,7 @@ import { useNavigate } from 'react-router-dom';import clsx from 'clsx';import { getEnabledPlatforms, platformSupportsChannels, platformSupportsToolcallDelivery } from '../../lib/platforms';import { hasUsableSecret } from '../../lib/secretFields';+import { setConfigField } from '../../lib/configMutations';import { EyebrowBadge, PlatformIcon, WizardCard } from '../visual';import { RoutingConfigPanel } from '../shared/RoutingConfigPanel';import { CompactSelect, SearchField, ToggleSwitch } from '../settings/SettingsPrimitives';@@ -190,9 +191,18 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBreturn configVersionRef.current;};- const saveLatestConfig = async (): Promise<boolean> => {+ // Patch-write shape: send only the platform flag being toggled. A+ // full ``configRef`` snapshot round-trip would treat every stale field+ // it carries as intentional inside the locked merge and could revert+ // concurrent cross-process writes (installer cli_path updates, auth+ // saves, unrelated platform edits).+ const savePlatformFlagPatch = async (+ key: string,+ field: string,+ value: boolean+ ): Promise<boolean> => {const saveTask = configSaveQueueRef.current.then(async () => {- await api.saveConfig(configRef.current);+ await api.mutateConfig([setConfigField([key, field], value)]);});configSaveQueueRef.current = saveTask.catch(() => {});try {@@ -1201,7 +1211,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB[key]: { ...(currentConfig as any)[key], [field]: !current },};const version = applyConfig(updated);- const saved = await saveLatestConfig();+ const saved = await savePlatformFlagPatch(key, field, !current);if (saved) {showToast(t('common.saved'), 'success');} else {diff --git a/ui/src/components/steps/PlatformSelection.tsx b/ui/src/components/steps/PlatformSelection.tsxindex 71fe2eefc..4684873a1 100644--- a/ui/src/components/steps/PlatformSelection.tsx+++ b/ui/src/components/steps/PlatformSelection.tsx@@ -1,4 +1,4 @@-import React, { useEffect, useMemo, useState } from 'react';+import React, { useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import clsx from 'clsx';import { ArrowLeft, ArrowRight, Check, Circle, CircleCheckBig, ExternalLink, Loader2, Lock, Plus, Smartphone } from 'lucide-react';@@ -86,6 +86,18 @@ export const PlatformSelection: React.FC<PlatformSelectionProps> = ({ data, onNeinitialPlatforms[0] || defaultCredentialPlatform);const [credentialDraft, setCredentialDraft] = useState<Record<string, any>>(() => buildInitialCredentialDraft(data));+ // Mount-time snapshot of the draft: a section differs from it only when+ // the USER typed into that platform's fields. Sections that match the+ // initial draft were never edited and must not ride along in the step+ // payload — resubmitting them would overwrite concurrent updates (e.g.+ // a WeChat QR token acquired after bootstrap) with stale mount-time+ // values inside the locked merge.+ const initialDraftRef = useRef<Record<string, any>>(buildInitialCredentialDraft(data));+ const dirtySections = Object.keys(credentialDraft).filter(+ (key) =>+ JSON.stringify((credentialDraft as Record<string, any>)[key]) !==+ JSON.stringify(initialDraftRef.current[key])+ );const [validating, setValidating] = useState(false);const [validationState, setValidationState] = useState<Record<string, ValidationState>>({});@@ -126,9 +138,17 @@ export const PlatformSelection: React.FC<PlatformSelectionProps> = ({ data, onNeenabled: normalized,},};+ // Only user-dirty credential sections join the step payload; the+ // untouched ones stay with their owners.+ const dirtyPayload: Record<string, any> = {};+ for (const key of dirtySections) {+ dirtyPayload[key] = credentialDraft[key];+ }const nextData = {- ...credentialDraft,- discord_client_id: credentialDraft.discord?.client_id || '',+ ...dirtyPayload,+ ...(dirtySections.includes('discord')+ ? { discord_client_id: credentialDraft.discord?.client_id || '' }+ : {}),...selectionData,};diff --git a/ui/src/components/steps/SlackConfig.tsx b/ui/src/components/steps/SlackConfig.tsxindex 6a1e93302..59680b3e3 100644--- a/ui/src/components/steps/SlackConfig.tsx+++ b/ui/src/components/steps/SlackConfig.tsx@@ -135,7 +135,6 @@ export const SlackConfig: React.FC<SlackConfigProps> = ({ data, onNext, onBack,...withSecretDrafts(data.slack, { bot_token: botToken, app_token: appToken }),proxy_url: proxyUrl || undefined,},- mode: 'self_host',});const handleApply = async () => {diff --git a/ui/src/components/steps/Summary.tsx b/ui/src/components/steps/Summary.tsxindex ba31bc2b4..df55e06c9 100644--- a/ui/src/components/steps/Summary.tsx+++ b/ui/src/components/steps/Summary.tsx@@ -18,7 +18,7 @@ import { useStatus } from '../../context/StatusContext';import { useToast } from '../../context/ToastContext';import { copyTextToClipboard } from '../../lib/utils';import { getEnabledPlatforms } from '../../lib/platforms';-import { withoutConfiguredSecretMarker, withSecretDraft, withSecretDrafts } from '../../lib/secretFields';+import { buildWizardFinishMutations } from '../../lib/wizardConfigMutations';import { EyebrowBadge, WizardCard } from '../visual';import { ToggleSwitch } from '../settings/SettingsPrimitives';import { Button } from '../ui/button';@@ -49,25 +49,6 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {: Array.isArray(data.discord?.guild_allowlist)? data.discord.guild_allowlist: [];- // ``require_mention`` is no longer toggled on the summary (it's configured in- // Settings); keep the data-derived defaults so buildConfigPayload still- // persists them. No setter — the value is read-only here.- const [requireMentionByPlatform] = useState<Record<string, boolean>>(- Object.fromEntries(- enabledPlatforms.map((platform) => [- platform,- platform === 'discord'- ? (data.discord?.require_mention || false)- : platform === 'telegram'- ? (data.telegram?.require_mention ?? true)- : platform === 'lark'- ? (data.lark?.require_mention || false)- : platform === 'wechat'- ? (data.wechat?.require_mention || false)- : (data.slack?.require_mention || false),- ])- )- );const [autoUpdate, setAutoUpdate] = useState(data.update?.auto_update ?? true);const navigate = useNavigate();@@ -86,51 +67,29 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {setSaving(true);setError(null);try {- const updatedData = {- ...data,- // No user-facing primary platform: the backend derives its internal- // default from ``platforms.enabled``.- platforms: {- enabled: enabledPlatforms,- },- slack: {- ...data.slack,- require_mention: requireMentionByPlatform.slack ?? data.slack?.require_mention,- },- discord: {- ...data.discord,- require_mention: requireMentionByPlatform.discord ?? data.discord?.require_mention,- },- telegram: {- ...data.telegram,- require_mention: requireMentionByPlatform.telegram ?? data.telegram?.require_mention,- },- lark: {- ...data.lark,- require_mention: requireMentionByPlatform.lark ?? data.lark?.require_mention,- },- wechat: {- ...data.wechat,- require_mention: requireMentionByPlatform.wechat ?? data.wechat?.require_mention,- },- update: {- ...data.update,- auto_update: autoUpdate,- },- };- const configPayload = buildConfigPayload(updatedData);- await api.saveConfig(configPayload);- const settingsByPlatform = buildSettingsPayload(updatedData);- await Promise.all(- Object.entries(settingsByPlatform).map(([platform, payload]) => api.saveSettings(payload, platform))- );+ // Platform credentials and channel/guild settings are persisted by their+ // own wizard steps. Finish owns only completion and final list intent;+ // replaying the accumulated settings snapshot here would overwrite+ // changes made by another browser after those steps completed.+ const savedConfig = await api.mutateConfig(buildWizardFinishMutations(data, autoUpdate));++ // The wizard can contain a selected platform that was never persisted+ // (for example, the user selected it and then used the global Skip+ // action before entering credentials). The config response is the+ // lock-fresh result after Finish, so use it for all post-save runtime+ // decisions instead of routing from that stale local selection.+ const committedData =+ savedConfig && typeof savedConfig === 'object' && !Array.isArray(savedConfig)+ ? { ...data, ...savedConfig }+ : data;+ const committedEnabledPlatforms = getEnabledPlatforms(committedData);await control('start');// ``enabledPlatforms`` only ever lists real IM platforms — the always-on// workbench is stripped by PlatformsConfig.validate() before any config// reaches the UI. An empty list is therefore a workbench-only setup.- if (enabledPlatforms.length === 0) {+ if (committedEnabledPlatforms.length === 0) {// Workbench-only setup — there is no external bot to bind, so finish// instead of falling through to a bogus bind-code flow.setSaving(false);@@ -139,7 +98,7 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {}, 1000);return;}- if (enabledPlatforms.every((platform) => platform === 'wechat')) {+ if (committedEnabledPlatforms.every((platform) => platform === 'wechat')) {setSaving(false);showToast(t('wechat.setupComplete'));setTimeout(() => {@@ -382,147 +341,3 @@ const countConfiguredChannels = (channelConfigsByPlatform: Record<string, Record(count, channels) => count + Object.values(channels || {}).filter((config: any) => config?.enabled).length,0);--const buildConfigPayload = (data: any) => {- const agents = data.agents || {};- const enabledPlatforms = getEnabledPlatforms(data);- return {- // No user-facing primary platform: the backend derives its internal default- // from ``platforms.enabled``.- platforms: {- enabled: enabledPlatforms,- },- mode: data.mode || 'self_host',- version: 'v2',- slack: {- ...withSecretDrafts(data.slack, {- bot_token: data.slack?.bot_token,- app_token: data.slack?.app_token,- }),- require_mention: data.slack?.require_mention || false,- },- discord: {- ...withSecretDraft(data.discord, 'bot_token', data.discord?.bot_token),- require_mention: data.discord?.require_mention || false,- },- telegram: {- ...withSecretDraft(data.telegram, 'bot_token', data.telegram?.bot_token),- require_mention: data.telegram?.require_mention ?? true,- forum_auto_topic: data.telegram?.forum_auto_topic ?? true,- use_webhook: data.telegram?.use_webhook ?? false,- },- lark: (() => {- const lark = data.lark || {};- const appId = lark.app_id || '';- const appIdChanged = Boolean(lark.original_app_id && appId && appId !== lark.original_app_id);- const base = appIdChanged ? withoutConfiguredSecretMarker(lark, 'app_secret') : lark;- return {- ...withSecretDraft(base, 'app_secret', lark.app_secret),- app_id: appId,- domain: lark.domain || 'feishu',- require_mention: lark.require_mention || false,- };- })(),- wechat: {- ...withSecretDraft(data.wechat, 'bot_token', data.wechat?.bot_token),- base_url: data.wechat?.base_url || '',- require_mention: data.wechat?.require_mention || false,- },- runtime: {- ...data.runtime,- default_cwd: data.default_cwd || data.runtime?.default_cwd || '_tmp',- },- agents: {- opencode: {- ...agents.opencode,- enabled: agents.opencode?.enabled ?? true,- cli_path: agents.opencode?.cli_path || 'opencode',- default_agent: data.opencode_default_agent ?? agents.opencode?.default_agent ?? null,- default_reasoning_effort:- data.opencode_default_reasoning_effort ?? agents.opencode?.default_reasoning_effort ?? null,- },- claude: {- ...agents.claude,- enabled: agents.claude?.enabled ?? true,- cli_path: agents.claude?.cli_path || 'claude',- },- codex: {- ...agents.codex,- enabled: agents.codex?.enabled ?? false,- cli_path: agents.codex?.cli_path || 'codex',- },- },- gateway: data.gateway,- ui: {- ...data.ui,- setup_host: data.ui?.setup_host || '127.0.0.1',- setup_port: data.ui?.setup_port || 5123,- },- update: data.update- ? {- ...data.update,- auto_update: data.update.auto_update,- }- : undefined,- ack_mode: data.ack_mode,- show_duration: data.show_duration ?? false,- language: data.language,- // Finishing the wizard is the explicit signal that setup is complete. Set- // here (Summary's own payload, the one saved on Finish) rather than in- // Wizard.tsx's intermediate-step payload so the flag is only persisted once- // the user actually reaches and completes the final step (including the- // Skip → Summary → Finish path).- setup_completed: true,- };-};--const buildSettingsPayload = (data: any) => {- const channelConfigsByPlatform = data.channelConfigsByPlatform || {};- const discordGuildAllowlist = Array.isArray(data.discordGuildAllowlist)- ? data.discordGuildAllowlist- : Array.isArray(data.discord?.guild_allowlist)- ? data.discord.guild_allowlist- : [];- const shouldPersistDiscordGuilds =- discordGuildAllowlist.length > 0 || data.discordGuildAllowlistTouched === true;- return Object.fromEntries(- Object.entries(channelConfigsByPlatform).map(([platform, channels]: any) => [- platform,- {- channels: Object.fromEntries(- Object.entries(channels || {}).map(([id, cfg]: any) => [- id,- {- enabled: cfg.enabled,- show_message_types: cfg.show_message_types || [],- custom_cwd: cfg.custom_cwd || null,- require_mention: cfg.require_mention ?? null,- require_bind: cfg.require_bind ?? null,- routing: {- agent_name: cfg.routing?.agent_name || null,- model: cfg.routing?.model || null,- reasoning_effort: cfg.routing?.reasoning_effort || null,- opencode_agent: cfg.routing?.opencode_agent || null,- opencode_model: cfg.routing?.opencode_model || null,- opencode_reasoning_effort: cfg.routing?.opencode_reasoning_effort || null,- claude_agent: cfg.routing?.claude_agent || null,- claude_model: cfg.routing?.claude_model || null,- claude_reasoning_effort: cfg.routing?.claude_reasoning_effort || null,- codex_agent: cfg.routing?.codex_agent || null,- codex_model: cfg.routing?.codex_model || null,- codex_reasoning_effort: cfg.routing?.codex_reasoning_effort || null,- },- },- ])- ),- ...(platform === 'discord' && shouldPersistDiscordGuilds- ? {- guilds: Object.fromEntries(- discordGuildAllowlist.map((guildId: string) => [guildId, { enabled: true }])- ),- }- : {}),- },- ])- );-};diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex 5ccc42e3b..3e33a27be 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -16,6 +16,7 @@ import type { SessionActivityItemKind, SessionActivityState, SessionRuntimeStateimport { apiFetch } from '../../lib/apiFetch';import { readChatViewMode, writeChatViewMode } from '../../lib/chatViewMemory';import { normalizeChatMessageFontSize } from '../../lib/chatDisplay';+import { setConfigField } from '../../lib/configMutations';import { annotationStandIn, annotationTitleKey, readAnnotationView } from '../../lib/annotationView';import { isTerminalAgentMessage, isTranscriptMessage, shouldRefreshAgentActivityForMessage } from '../../lib/chatMessageTypes';import { chatRowKind, drawsEmptyBodyPlaceholder, isAgentAuthored } from '../../lib/chatRowKind';@@ -639,7 +640,7 @@ export const ChatPage: React.FC = () => {const next = !prev;// Optimistic; persist the minimal ui patch (save_config deep-merges). A failed// save leaves the local flag as the user set it for this session.- void api.saveConfig({ ui: { show_tool_calls: next } }).catch(() => {});+ void api.mutateConfig([setConfigField(['ui', 'show_tool_calls'], next)]).catch(() => {});return next;});}, [api]);diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 4940367a6..d8beaaa5d 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -42,9 +42,14 @@ import {} from '../lib/sessionDraftPersistence';import { getExistingWebPushSubscription, getWebPushDeviceId } from '../lib/webPush';import { reportRemoteAuthorizationState, type RemoteAuthorizationState } from '../lib/remoteAuth';+import {+ configMutationsToPayload,+ type ConfigMutation,+} from '../lib/configMutations';export type { InstanceCapabilities, SessionInfo };export type { ShowPageAccess };+export type { ConfigMutation };// The workbench Dock API response shape ({ ok, dock }); the Dock document type// itself lives with the DockProvider that owns reconciliation.@@ -507,7 +512,7 @@ export type TunnelConnectivityDiagnostics = {export type ApiContextType = {getConfig: () => Promise<any>;getPlatformCatalog: () => Promise<any>;- saveConfig: (payload: any) => Promise<any>;+ mutateConfig: (mutations: readonly ConfigMutation[]) => Promise<any>;getSettings: (platform?: string) => Promise<any>;saveSettings: (payload: any, platform?: string) => Promise<any>;saveThreadSettings: (platform: string, channelId: string, threadId: string, settings: any) => Promise<any>;@@ -3590,7 +3595,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenconst value: ApiContextType = useMemo(() => ({getConfig: () => getCachedJson('/api/config', CONFIG_CACHE_TTL_MS),getPlatformCatalog: () => getJson('/api/platforms'),- saveConfig: (payload) => postJson('/api/config', payload),+ mutateConfig: (mutations) => postJson('/api/config', configMutationsToPayload(mutations)),getSettings: (platform) => getJson(platform ? `/api/settings?platform=${encodeURIComponent(platform)}` : '/api/settings'),saveSettings: (payload, platform) => postJson('/api/settings', platform ? { ...payload, platform } : payload),saveThreadSettings: (platform, channelId, threadId, settings) => postJson('/api/settings/thread', {diff --git a/ui/src/lib/configMutations.test.ts b/ui/src/lib/configMutations.test.tsnew file mode 100644index 000000000..8fd9ce5c4--- /dev/null+++ b/ui/src/lib/configMutations.test.ts@@ -0,0 +1,63 @@+import { describe, expect, it } from 'vitest';++import {+ configChanges,+ configMutationsToPayload,+ setConfigField,+ updateEnabledPlatforms,+} from './configMutations';++describe('config mutations', () => {+ it('derives only changed leaf fields from a stale UI snapshot', () => {+ const before = {+ agents: { opencode: { enabled: true, cli_path: '/old/opencode' } },+ ui: { show_tool_calls: true },+ };+ const after = {+ agents: { opencode: { enabled: false, cli_path: '/old/opencode' } },+ ui: { show_tool_calls: true },+ };++ expect(configMutationsToPayload(configChanges(before, after))).toEqual({+ agents: { opencode: { enabled: false } },+ });+ });++ it('serializes enabled-platform deltas separately from config data', () => {+ expect(+ configMutationsToPayload([+ setConfigField(['slack', 'bot_token'], 'token'),+ updateEnabledPlatforms({ add: ['slack', 'wechat'], remove: ['discord', 'slack'] }),+ ]),+ ).toEqual({+ slack: { bot_token: 'token' },+ __avibe_list_ops: {+ 'platforms.enabled': { add: ['slack', 'wechat'], remove: ['discord'] },+ },+ });+ });++ it('rejects snapshot-shaped enabled-list replacement', () => {+ expect(() =>+ configMutationsToPayload([setConfigField(['platforms', 'enabled'], ['slack'])]),+ ).toThrow('updateEnabledPlatforms');+ });++ it('rejects empty, unsafe, and conflicting mutation sets', () => {+ expect(() => configMutationsToPayload([])).toThrow('cannot be empty');+ expect(() =>+ configMutationsToPayload([+ setConfigField(['agents'], { opencode: { enabled: false } }),+ ]),+ ).toThrow('must target a leaf value');+ expect(() =>+ configMutationsToPayload([setConfigField(['__proto__', 'polluted'], true)]),+ ).toThrow('Invalid config mutation path');+ expect(() =>+ configMutationsToPayload([+ setConfigField(['ui'], 'invalid-parent'),+ setConfigField(['ui', 'show_tool_calls'], true),+ ]),+ ).toThrow('Conflicting config mutation path');+ });+});diff --git a/ui/src/lib/configMutations.ts b/ui/src/lib/configMutations.tsnew file mode 100644index 000000000..4e40d9f8a--- /dev/null+++ b/ui/src/lib/configMutations.ts@@ -0,0 +1,168 @@+export type ConfigPath = readonly [string, ...string[]];++export type ConfigSetMutation = {+ kind: 'set';+ path: ConfigPath;+ value: unknown;+};++export type EnabledPlatformsMutation = {+ kind: 'enabled-platforms';+ add: readonly string[];+ remove: readonly string[];+};++export type ConfigMutation = ConfigSetMutation | EnabledPlatformsMutation;++const RESERVED_PATH_SEGMENTS = new Set(['__proto__', 'prototype', 'constructor']);++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const valuesEqual = (left: unknown, right: unknown): boolean => {+ if (Object.is(left, right)) return true;+ if (Array.isArray(left) && Array.isArray(right)) {+ return left.length === right.length && left.every((value, index) => valuesEqual(value, right[index]));+ }+ if (isRecord(left) && isRecord(right)) {+ const leftKeys = Object.keys(left);+ const rightKeys = Object.keys(right);+ return (+ leftKeys.length === rightKeys.length &&+ leftKeys.every((key) => Object.hasOwn(right, key) && valuesEqual(left[key], right[key]))+ );+ }+ return false;+};++function validatePath(path: readonly string[]): asserts path is ConfigPath {+ if (path.length === 0) throw new Error('Config mutation path cannot be empty');+ for (const segment of path) {+ if (!segment || RESERVED_PATH_SEGMENTS.has(segment)) {+ throw new Error(`Invalid config mutation path segment: ${segment || '<empty>'}`);+ }+ }+}++const isEnabledPlatformsPath = (path: readonly string[]) =>+ path.length === 2 && path[0] === 'platforms' && path[1] === 'enabled';++export const setConfigField = (path: ConfigPath, value: unknown): ConfigSetMutation => ({+ kind: 'set',+ path,+ value,+});++export const updateEnabledPlatforms = ({+ add = [],+ remove = [],+}: {+ add?: readonly string[];+ remove?: readonly string[];+}): EnabledPlatformsMutation => ({+ kind: 'enabled-platforms',+ add,+ remove,+});++/**+ * Derive leaf-field mutations from one UI-owned before/after subtree.+ * Omitted keys mean unchanged; callers use null for an intentional clear.+ */+export const configChanges = (+ before: unknown,+ after: unknown,+ prefix: readonly string[] = [],+): ConfigMutation[] => {+ if (after === undefined || valuesEqual(before, after)) return [];++ if (isRecord(after)) {+ const previous = isRecord(before) ? before : {};+ return Object.entries(after).flatMap(([key, value]) =>+ configChanges(previous[key], value, [...prefix, key]),+ );+ }++ validatePath(prefix);+ if (isEnabledPlatformsPath(prefix)) {+ throw new Error('platforms.enabled must use updateEnabledPlatforms');+ }+ return [setConfigField(prefix, after)];+};++const assignPath = (+ payload: Record<string, unknown>,+ path: ConfigPath,+ value: unknown,+ seen: Set<string>,+) => {+ validatePath(path);+ if (isEnabledPlatformsPath(path)) {+ throw new Error('platforms.enabled must use updateEnabledPlatforms');+ }+ if (value === undefined) throw new Error(`Config mutation ${path.join('.')} has undefined value`);+ if (isRecord(value)) {+ throw new Error(`Config mutation ${path.join('.')} must target a leaf value`);+ }++ const identity = JSON.stringify(path);+ if (seen.has(identity)) throw new Error(`Duplicate config mutation path: ${path.join('.')}`);+ seen.add(identity);++ let node = payload;+ for (const segment of path.slice(0, -1)) {+ const current = node[segment];+ if (current === undefined) {+ node[segment] = {};+ } else if (!isRecord(current)) {+ throw new Error(`Conflicting config mutation path: ${path.join('.')}`);+ }+ node = node[segment] as Record<string, unknown>;+ }++ const leaf = path[path.length - 1];+ if (Object.hasOwn(node, leaf)) {+ throw new Error(`Conflicting config mutation path: ${path.join('.')}`);+ }+ node[leaf] = value;+};++/** Serialize explicit UI mutations to the existing merge-patch HTTP contract. */+export const configMutationsToPayload = (mutations: readonly ConfigMutation[]) => {+ const payload: Record<string, unknown> = {};+ const seen = new Set<string>();+ const additions = new Set<string>();+ const removals = new Set<string>();++ for (const mutation of mutations) {+ if (mutation.kind === 'set') {+ assignPath(payload, mutation.path, mutation.value, seen);+ continue;+ }++ for (const platform of mutation.remove) {+ if (!platform) continue;+ additions.delete(platform);+ removals.add(platform);+ }+ for (const platform of mutation.add) {+ if (!platform) continue;+ removals.delete(platform);+ additions.add(platform);+ }+ }++ if (additions.size > 0 || removals.size > 0) {+ payload.__avibe_list_ops = {+ 'platforms.enabled': {+ ...(additions.size > 0 ? { add: [...additions] } : {}),+ ...(removals.size > 0 ? { remove: [...removals] } : {}),+ },+ };+ }++ if (Object.keys(payload).length === 0) {+ throw new Error('Config mutation set cannot be empty');+ }+ return payload;+};diff --git a/ui/src/lib/wizardConfigMutations.test.ts b/ui/src/lib/wizardConfigMutations.test.tsnew file mode 100644index 000000000..e01481f46--- /dev/null+++ b/ui/src/lib/wizardConfigMutations.test.ts@@ -0,0 +1,211 @@+import { describe, expect, it } from 'vitest';++import { configMutationsToPayload } from './configMutations';+import {+ buildWizardFinishMutations,+ buildWizardStepMutations,+ collectWizardEnabledPlatformDelta,+} from './wizardConfigMutations';++describe('wizard config mutations', () => {+ it('tracks only the final intent for each wizard platform operation', () => {+ expect(collectWizardEnabledPlatformDelta([+ { kind: 'enabled-platforms', add: ['slack'], remove: ['discord'] },+ { kind: 'enabled-platforms', add: ['discord'], remove: ['slack'] },+ ])).toEqual({ add: ['discord'], remove: ['slack'] });+ });++ it('persists only fields owned by the Agents step', () => {+ const before = {+ agents: {+ opencode: { enabled: true, cli_path: 'old', default_agent: 'build' },+ claude: { enabled: true, cli_path: 'claude' },+ },+ };+ const stepData = {+ agents: {+ opencode: {+ enabled: false,+ cli_path: '/opt/opencode',+ default_agent: 'stale',+ status: 'ok',+ },+ claude: { enabled: true, cli_path: 'claude', status: 'missing' },+ },+ };++ expect(configMutationsToPayload(buildWizardStepMutations({+ stepId: 'agents',+ before,+ stepData,+ after: { ...before, ...stepData },+ }))).toEqual({+ agents: { opencode: { enabled: false } },+ });+ });++ it('does not replay an installer-owned cli path on Continue', () => {+ const before = {+ agents: { opencode: { enabled: true, cli_path: 'old-path' } },+ };+ const stepData = {+ agents: { opencode: { enabled: true, cli_path: '/newly-installed/opencode' } },+ };++ expect(buildWizardStepMutations({+ stepId: 'agents',+ before,+ stepData,+ after: { ...before, ...stepData },+ })).toEqual([]);+ });++ it('does not resend mount-time agents from a later platform step', () => {+ const before = {+ platforms: { enabled: ['slack'] },+ agents: { opencode: { cli_path: 'stale' } },+ slack: {+ has_bot_token: true,+ bot_token_length: 24,+ has_app_token: true,+ require_mention: false,+ },+ };+ const stepData = {+ platform: 'slack',+ slack: {+ has_bot_token: true,+ has_app_token: true,+ bot_token: '',+ app_token: '',+ require_mention: true,+ },+ };+ const after = { ...before, ...stepData };++ expect(configMutationsToPayload(buildWizardStepMutations({+ stepId: 'platform-slack', before, stepData, after,+ }))).toEqual({+ slack: { require_mention: true },+ });+ });++ it('adds a platform when its credentials become runnable during the wizard', () => {+ const before = {+ platforms: { enabled: ['slack'] },+ slack: {},+ };+ const stepData = {+ slack: { bot_token: 'xoxb-token', app_token: 'xapp-token' },+ };+ const after = { ...before, ...stepData };++ expect(configMutationsToPayload(buildWizardStepMutations({+ stepId: 'platform-slack', before, stepData, after,+ }))).toEqual({+ slack: { bot_token: 'xoxb-token', app_token: 'xapp-token' },+ __avibe_list_ops: { 'platforms.enabled': { add: ['slack'] } },+ });+ });++ it('encodes selection changes as operations', () => {+ const before = {+ platforms: { enabled: ['discord'] },+ discord: { has_bot_token: true },+ slack: { has_bot_token: true },+ };+ const stepData = { platforms: { enabled: ['slack'] } };+ const after = { ...before, ...stepData };++ expect(configMutationsToPayload(buildWizardStepMutations({+ stepId: 'platform', before, stepData, after,+ }))).toEqual({+ __avibe_list_ops: {+ 'platforms.enabled': { add: ['slack'], remove: ['discord'] },+ },+ });+ });++ it('finishes setup without resending agents or platform sections', () => {+ const data = {+ platforms: { enabled: ['slack'] },+ __wizardEnabledBaseline: ['discord', 'slack'],+ slack: { has_bot_token: true },+ agents: { opencode: { cli_path: 'stale' } },+ update: { auto_update: true },+ };++ expect(configMutationsToPayload(buildWizardFinishMutations(data, false))).toEqual({+ update: { auto_update: false },+ setup_completed: true,+ __avibe_list_ops: {+ 'platforms.enabled': { remove: ['discord'] },+ },+ });+ });++ it('does not re-enable a baseline platform changed by another browser', () => {+ const data = {+ platforms: { enabled: ['slack'] },+ __wizardEnabledBaseline: ['slack'],+ __wizardEnabledAdds: [],+ __wizardEnabledRemoves: [],+ slack: { has_bot_token: true, has_app_token: true },+ update: { auto_update: true },+ };++ expect(configMutationsToPayload(buildWizardFinishMutations(data, true))).toEqual({+ setup_completed: true,+ });+ });++ it('reasserts a platform that this wizard explicitly added', () => {+ const data = {+ platforms: { enabled: ['slack'] },+ __wizardEnabledBaseline: [],+ __wizardEnabledAdds: ['slack'],+ __wizardEnabledRemoves: [],+ slack: { has_bot_token: true, has_app_token: true },+ update: { auto_update: true },+ };++ expect(configMutationsToPayload(buildWizardFinishMutations(data, true))).toEqual({+ setup_completed: true,+ __avibe_list_ops: {+ 'platforms.enabled': { add: ['slack'] },+ },+ });+ });++ it('does not re-enable a selected platform skipped before persistence', () => {+ const data = {+ platforms: { enabled: ['slack'] },+ __wizardEnabledBaseline: [],+ __wizardEnabledAdds: [],+ __wizardEnabledRemoves: [],+ slack: {},+ update: { auto_update: true },+ };++ expect(configMutationsToPayload(buildWizardFinishMutations(data, true))).toEqual({+ setup_completed: true,+ });+ });++ it('persists the WeChat duration override from a loaded enabled value', () => {+ const data = {+ platforms: { enabled: ['wechat'] },+ __wizardEnabledBaseline: ['wechat'],+ __wizardEnabledAdds: [],+ __wizardEnabledRemoves: [],+ show_duration: true,+ wechat: {},+ update: { auto_update: true },+ };++ expect(configMutationsToPayload(buildWizardFinishMutations(data, true))).toEqual({+ show_duration: false,+ setup_completed: true,+ });+ });+});diff --git a/ui/src/lib/wizardConfigMutations.ts b/ui/src/lib/wizardConfigMutations.tsnew file mode 100644index 000000000..222916f69--- /dev/null+++ b/ui/src/lib/wizardConfigMutations.ts@@ -0,0 +1,229 @@+import {+ configChanges,+ setConfigField,+ updateEnabledPlatforms,+ type ConfigMutation,+} from './configMutations';+import { getEnabledPlatforms, platformHasRunnableConfig } from './platforms';+import {+ withoutConfiguredSecretMarker,+ withSecretDraft,+ withSecretDrafts,+} from './secretFields';++const WIZARD_PLATFORMS = ['slack', 'discord', 'telegram', 'lark', 'wechat'] as const;+const WIZARD_BACKENDS = ['opencode', 'claude', 'codex'] as const;++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const recordOrEmpty = (value: unknown): Record<string, unknown> =>+ isRecord(value) ? value : {};++const stringList = (value: unknown): string[] =>+ Array.isArray(value)+ ? value.filter((entry): entry is string => typeof entry === 'string')+ : [];++const normalizePlatformSection = (platform: string, section: unknown) => {+ if (!isRecord(section)) return section;++ let normalized = { ...section };+ if (platform === 'slack') {+ normalized = withSecretDrafts(normalized, {+ bot_token: typeof normalized.bot_token === 'string' ? normalized.bot_token : undefined,+ app_token: typeof normalized.app_token === 'string' ? normalized.app_token : undefined,+ });+ } else if (platform === 'lark') {+ const appIdChanged = Boolean(+ normalized.original_app_id &&+ normalized.app_id &&+ normalized.app_id !== normalized.original_app_id,+ );+ normalized = withSecretDraft(+ appIdChanged+ ? withoutConfiguredSecretMarker(normalized, 'app_secret')+ : normalized,+ 'app_secret',+ typeof normalized.app_secret === 'string' ? normalized.app_secret : undefined,+ );+ } else {+ normalized = withSecretDraft(+ normalized,+ 'bot_token',+ typeof normalized.bot_token === 'string' ? normalized.bot_token : undefined,+ );+ }++ for (const key of Object.keys(normalized)) {+ if (key.startsWith('has_') || key.endsWith('_length')) delete normalized[key];+ }+ delete normalized.original_app_id;+ if (platform === 'discord') delete normalized.client_id;+ return normalized;+};++const agentMutations = (before: unknown, stepData: unknown): ConfigMutation[] => {+ const submittedAgents = recordOrEmpty(recordOrEmpty(stepData).agents);+ const previousAgents = recordOrEmpty(recordOrEmpty(before).agents);++ return WIZARD_BACKENDS.flatMap((backend) => {+ const submitted = submittedAgents[backend];+ if (!isRecord(submitted)) return [];++ const owned: Record<string, unknown> = {};+ if (typeof submitted.enabled === 'boolean') owned.enabled = submitted.enabled;+ // ``cli_path`` has a different owner from the wizard's enable toggle:+ // install_agent and the provider runtime card persist it at the moment+ // they discover or edit the path. Replaying that asynchronously derived+ // value on Continue would turn an already-committed install result back+ // into a stale browser snapshot. Keep the field in the step data for+ // display, but never emit it from this mutation builder.+ return configChanges(previousAgents[backend], owned, ['agents', backend]);+ });+};++const platformSectionMutations = (+ before: unknown,+ stepData: unknown,+ platforms: readonly string[],+): ConfigMutation[] => {+ const previous = recordOrEmpty(before);+ const submitted = recordOrEmpty(stepData);+ return platforms.flatMap((platform) => {+ if (submitted[platform] === undefined) return [];+ return configChanges(+ previous[platform],+ normalizePlatformSection(platform, submitted[platform]),+ [platform],+ );+ });+};++export const buildWizardStepMutations = ({+ stepId,+ before,+ stepData,+ after,+}: {+ stepId: string;+ before: unknown;+ stepData: unknown;+ after: unknown;+}): ConfigMutation[] => {+ if (stepId === 'agents') return agentMutations(before, stepData);++ const previous = recordOrEmpty(before);+ const submitted = recordOrEmpty(stepData);+ const next = recordOrEmpty(after);+ const editedPlatforms = stepId === 'platform'+ ? WIZARD_PLATFORMS.filter((platform) => submitted[platform] !== undefined)+ : stepId.startsWith('platform-')+ ? [stepId.slice('platform-'.length)]+ : [];+ if (editedPlatforms.length === 0 && stepId !== 'platform') return [];++ const mutations = platformSectionMutations(before, stepData, editedPlatforms);+ const selectedBefore = getEnabledPlatforms(previous);+ const selectedAfter = getEnabledPlatforms(next);+ const newlySelected = selectedAfter.filter((platform) => !selectedBefore.includes(platform));+ // A platform that was already enabled and runnable when the wizard loaded is+ // not owned by a later credential edit. Only newly selected platforms, or a+ // selected platform whose credentials were not runnable before this step,+ // may acquire a wizard-owned add operation. This keeps a stale credential+ // snapshot from turning Finish into an implicit re-enable.+ const needsWizardEnablement = (platform: string) =>+ !selectedBefore.includes(platform) || !platformHasRunnableConfig(previous, platform);+ const addCandidates = stepId === 'platform'+ ? [...new Set([+ ...newlySelected,+ ...editedPlatforms.filter(needsWizardEnablement),+ ])]+ : editedPlatforms.filter(needsWizardEnablement);+ const add = addCandidates.filter(+ (platform) =>+ selectedAfter.includes(platform) && platformHasRunnableConfig(next, platform),+ );+ const remove = stepId === 'platform'+ ? selectedBefore.filter((platform) => !selectedAfter.includes(platform))+ : [];+ if (add.length > 0 || remove.length > 0) {+ mutations.push(updateEnabledPlatforms({ add, remove }));+ }++ if (stepId === 'platform' && next.show_duration !== previous.show_duration) {+ mutations.push(setConfigField(['show_duration'], next.show_duration));+ }+ return mutations;+};++export type WizardEnabledPlatformDelta = {+ add: string[];+ remove: string[];+};++/**+ * Collect the list intent from mutations that were actually submitted by a+ * wizard step. The ordering mirrors configMutationsToPayload: a later add or+ * remove wins for the same platform.+ */+export const collectWizardEnabledPlatformDelta = (+ mutations: readonly ConfigMutation[],+): WizardEnabledPlatformDelta => {+ const add = new Set<string>();+ const remove = new Set<string>();+ for (const mutation of mutations) {+ if (mutation.kind !== 'enabled-platforms') continue;+ for (const platform of mutation.remove) {+ if (!platform) continue;+ add.delete(platform);+ remove.add(platform);+ }+ for (const platform of mutation.add) {+ if (!platform) continue;+ remove.delete(platform);+ add.add(platform);+ }+ }+ return { add: [...add], remove: [...remove] };+};++export const buildWizardFinishMutations = (+ data: unknown,+ autoUpdate: boolean,+): ConfigMutation[] => {+ const config = recordOrEmpty(data);+ const update = recordOrEmpty(config.update);+ const selected = getEnabledPlatforms(config);+ const baseline: string[] = Array.isArray(config.__wizardEnabledBaseline)+ ? config.__wizardEnabledBaseline.filter(+ (platform): platform is string => typeof platform === 'string',+ )+ : [];+ // The loaded enabled list is an observation, not ownership. Finish may+ // reassert only list changes that this wizard actually submitted.+ const wizardAdds = stringList(config.__wizardEnabledAdds);+ const wizardRemoves = stringList(config.__wizardEnabledRemoves);+ const add = wizardAdds.filter(+ (platform) => selected.includes(platform) && platformHasRunnableConfig(config, platform),+ );+ const remove = [+ ...new Set([+ ...baseline.filter((platform) => !selected.includes(platform)),+ ...wizardRemoves.filter((platform) => !selected.includes(platform)),+ ]),+ ];+ const mutations: ConfigMutation[] = [];++ if (add.length > 0 || remove.length > 0) {+ mutations.push(updateEnabledPlatforms({ add, remove }));+ }+ if (update.auto_update !== autoUpdate) {+ mutations.push(setConfigField(['update', 'auto_update'], autoUpdate));+ }+ if (selected.includes('wechat') && config.show_duration !== false) {+ mutations.push(setConfigField(['show_duration'], false));+ }+ mutations.push(setConfigField(['setup_completed'], true));+ return mutations;+};diff --git a/vibe/api.py b/vibe/api.pyindex ae13a1f17..ebb213124 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -33,6 +33,7 @@ from config.v2_config import (MemoryConfigStaleWrite,V2Config,atomic_update_memory,+ config_file_lock,memory_config_from_payload,)from config.v2_settings import (@@ -704,13 +705,95 @@ def _config_recovery_message() -> Optional[str]:return config_recovery_notice(config)+_LIST_OPS_PAYLOAD_KEY = "__avibe_list_ops"+++_LIST_OPS_ALLOWED_PATHS = frozenset({"platforms.enabled"})+++def _apply_list_ops(base: dict, list_ops: dict) -> dict:+ """Apply add/remove operations to list-valued config paths.++ ``{"platforms.enabled": {"add": ["wechat"], "remove": ["discord"]}}``+ mutates the lock-fresh base's list instead of replacing it wholesale,+ so a stale browser snapshot of the list cannot drop entries another+ process added (#1458 stage ③: lists are replace-on-merge otherwise).+ Only whitelisted paths are accepted: resolving arbitrary dotted paths+ would let a client mutate lists whose owners need service-mediated+ synchronization (e.g. ``model_hub.sources`` must go through+ ModelHubService) — anything outside the whitelist raises.+ """+ import copy as _copy++ merged = _copy.deepcopy(base)++ def _resolve(container: dict, dotted: str):+ current = container+ for part in dotted.split("."):+ if not isinstance(current, dict):+ return None+ current = current.get(part)+ return current++ if not isinstance(list_ops, dict):+ raise ValueError("Config list operations must be an object")++ def _validated_operands(ops: dict, name: str) -> list[str]:+ if name not in ops:+ return []+ values = ops[name]+ if not isinstance(values, list) or any(+ not isinstance(value, str) or not value.strip() for value in values+ ):+ raise ValueError(+ f"Config list operation '{name}' must be an array of non-empty strings"+ )+ return values++ for dotted, ops in list_ops.items():+ if not isinstance(dotted, str) or dotted not in _LIST_OPS_ALLOWED_PATHS:+ raise ValueError(+ f"Config list operation path '{dotted}' is not supported"+ )+ if not isinstance(ops, dict):+ raise ValueError(f"Config list operation '{dotted}' must be an object")+ unknown = set(ops) - {"add", "remove"}+ if unknown:+ names = ", ".join(sorted(str(name) for name in unknown))+ raise ValueError(f"Config list operation '{dotted}' has unknown keys: {names}")+ target = _resolve(merged, dotted)+ if not isinstance(target, list):+ raise ValueError(f"Config list operation target '{dotted}' is not a list")+ additions = _validated_operands(ops, "add")+ removals = _validated_operands(ops, "remove")+ next_list = [item for item in target if item not in removals]+ for item in additions:+ if item not in next_list:+ next_list.append(item)+ # Write back through the dotted path.+ parts = dotted.split(".")+ node = merged+ for part in parts[:-1]:+ node = node[part]+ node[parts[-1]] = next_list+ return merged++def _deep_merge_dicts(base: dict, patch: dict) -> dict:+ list_ops = None+ if isinstance(patch, dict):+ raw_ops = patch.get(_LIST_OPS_PAYLOAD_KEY)+ if isinstance(raw_ops, dict):+ list_ops = raw_ops+ patch = {k: v for k, v in patch.items() if k != _LIST_OPS_PAYLOAD_KEY}merged = dict(base)for key, value in patch.items():if isinstance(value, dict) and isinstance(merged.get(key), dict):merged[key] = _deep_merge_dicts(merged[key], value)else:merged[key] = value+ if list_ops is not None:+ merged = _apply_list_ops(merged, list_ops)return merged@@ -962,12 +1045,28 @@ def save_config(payload = _strip_agent_auth_fields(payload)payload = _strip_preserved_config_secrets(payload)payload = _mark_explicit_audio_asr_enabled(payload)+ # The list-operations verb is a merge instruction, never config+ # state: pull it out before anything treats the payload as data —+ # but remember whether it touched the enabled list: credential+ # validation and runtime reconciliation gate on a ``platforms``+ # marker in the payload, and a bare operation payload must not+ # bypass them.+ raw_list_ops = payload.pop(_LIST_OPS_PAYLOAD_KEY, None)+ if raw_list_ops is not None and not isinstance(raw_list_ops, dict):+ raise ValueError("Config list operations must be an object")+ list_ops_touches_platforms = isinstance(raw_list_ops, dict) and any(+ str(key) in ("platforms.enabled", "platforms.primary") for key in raw_list_ops+ )- # Preserve the established in-process read -> merge -> validate -> write- # transaction. V2Config.save() nests the same RLock before taking Memory's- # cross-process file lock, so generic writers remain linearizable without- # changing the Memory transaction's lock order.- with CONFIG_LOCK:+ # Serialize the WHOLE read-merge-write cycle across processes+ # (#1458 stage ③): the base load, merge, validation, and write all+ # happen under the config file lock, so a controller commit between+ # our load and our write can no longer be overwritten. The in-lock+ # A lock-fresh base prevents overlapping read-modify-write cycles from+ # losing one another. It cannot identify stale fields a client explicitly+ # resubmits, so UI callers still declare field mutations instead of sending+ # config snapshots.+ with config_file_lock():base_payload: dict = {}base_config: Optional[V2Config] = Nonetry:@@ -994,7 +1093,20 @@ def save_config(base_payload.pop("platforms", None)base_payload.pop("platform", None)- merged_payload = _deep_merge_dicts(base_payload, payload) if base_payload else payload+ if base_payload:+ merged_payload = _deep_merge_dicts(base_payload, payload)+ if isinstance(raw_list_ops, dict) and raw_list_ops:+ merged_payload = _apply_list_ops(merged_payload, raw_list_ops)+ else:+ merged_payload = payload+ if list_ops_touches_platforms and isinstance(merged_payload.get("platforms"), dict):+ # Credential validation and runtime reconciliation gate on a+ # ``platforms`` marker in the payload; surface the FINAL+ # post-operation enabled list so a bare list-op payload is+ # validated and reconciled exactly like an explicit list save.+ final_platforms = dict(merged_payload["platforms"])+ if "enabled" in final_platforms or "primary" in final_platforms:+ payload["platforms"] = final_platformsmerged_payload = _merge_legacy_discord_guild_scope_fields(merged_payload, payload, base_config)sanitized_payload, guild_scope_update = _extract_settings_scopes_from_config_payload(merged_payload)config = V2Config.from_payload(sanitized_payload)@@ -6952,27 +7064,35 @@ def _run_install_command(# config entries, so they must not touch V2Config bookkeeping.if installed_path and is_agent_backend(name):try:- with CONFIG_LOCK:- try:- cfg = load_config()- except FileNotFoundError:- logger.debug(- "install_agent: config is not initialized; skipping cli_path persistence for %s",- name,- )- else:+ from config.v2_config import update_config_fields+ from config import paths as _paths++ if not _paths.get_config_path().exists():+ logger.debug(+ "install_agent: config is not initialized; skipping cli_path persistence for %s",+ name,+ )+ else:++ def _persist_cli_path(cfg) -> None:+ # Read-decide-write INSIDE the transaction (#1458+ # stage ③): the comparison runs on the+ # lock-fresh config, so a concurrent save cannot+ # be reverted by a stale snapshot.target = getattr(getattr(cfg, "agents", None), name, None)- if target is not None:- previous = getattr(target, "cli_path", "") or ""- if previous != installed_path:- target.cli_path = installed_path- cfg.save()- logger.info(- "install_agent: updated V2Config cli_path for %s: %s -> %s",- name,- previous or "<unset>",- installed_path,- )+ if target is None:+ return+ previous = getattr(target, "cli_path", "") or ""+ if previous != installed_path:+ target.cli_path = installed_path+ logger.info(+ "install_agent: updated V2Config cli_path for %s: %s -> %s",+ name,+ previous or "<unset>",+ installed_path,+ )++ update_config_fields(_persist_cli_path)except Exception as exc: # noqa: BLE001logger.warning("install_agent: failed to persist cli_path for %s: %s",@@ -7239,17 +7359,20 @@ def _persist_avault_cli_path(path: str) -> None:load_config()except FileNotFoundError:save_config({})- with CONFIG_LOCK:- cfg = load_config()+ from config.v2_config import update_config_fields++ def _apply_avault_cli_path(cfg) -> None:+ # Read-decide-write INSIDE the transaction (#1458 stage ③).previous = getattr(cfg.agents.avault, "cli_path", "") or ""if previous != path:cfg.agents.avault.cli_path = path- cfg.save()logger.info("install_avault: updated V2Config cli_path: %s -> %s",previous or "<unset>",path,)++ update_config_fields(_apply_avault_cli_path)except Exception as exc:logger.warning("install_avault: failed to persist cli_path: %s", exc)raise@@ -9741,36 +9864,36 @@ def remove_backend_api_key(backend: str) -> dict:# Clear V2Config api_key for both backends.try:- with CONFIG_LOCK:- try:- config = load_config()- except FileNotFoundError:- config = V2Config()- target = getattr(getattr(config, "agents", None), backend, None)- if target is not None:- target.auth_mode = "oauth"- target.api_key = None- # Drop base_url for both backends, not just Codex: a- # stale Claude relay URL stored in V2Config gets- # injected into the subprocess as ``ANTHROPIC_BASE_URL``- # on every launch via ``build_claude_subprocess_env``.- # After removing an API key (intent: fall back to- # OAuth), the OAuth credentials would still be routed- # to the api-key-only relay and silently 401.- target.base_url = None- # Remove key is an explicit OAuth choice — the relay- # marker goes with it, or a later refresh would- # repopulate the abandoned relay and reroute a freshly- # entered official key to it (Codex-only field).- if backend == "codex":- target.oauth_relay_marker = None- # User explicitly chose OAuth by clicking Remove key —- # mark the flag so legacy env-var fallback in- # ``build_claude_subprocess_env`` is bypassed and the- # inherited ``ANTHROPIC_*`` env actually gets stripped.- if backend == "claude":- target.auth_mode_set = True- config.save()+ from config.v2_config import update_config_fields++ def _clear_auth_fields(cfg: V2Config) -> None:+ target = getattr(getattr(cfg, "agents", None), backend, None)+ if target is None:+ return+ target.auth_mode = "oauth"+ target.api_key = None+ # Drop base_url for both backends, not just Codex: a+ # stale Claude relay URL stored in V2Config gets+ # injected into the subprocess as ``ANTHROPIC_BASE_URL``+ # on every launch via ``build_claude_subprocess_env``.+ # After removing an API key (intent: fall back to+ # OAuth), the OAuth credentials would still be routed+ # to the api-key-only relay and silently 401.+ target.base_url = None+ # Remove key is an explicit OAuth choice — the relay+ # marker goes with it, or a later refresh would+ # repopulate the abandoned relay and reroute a freshly+ # entered official key to it (Codex-only field).+ if backend == "codex":+ target.oauth_relay_marker = None+ # User explicitly chose OAuth by clicking Remove key —+ # mark the flag so legacy env-var fallback in+ # ``build_claude_subprocess_env`` is bypassed and the+ # inherited ``ANTHROPIC_*`` env actually gets stripped.+ if backend == "claude":+ target.auth_mode_set = True++ update_config_fields(_clear_auth_fields)except Exception as exc: # noqa: BLE001logger.warning("V2Config clear during remove-key failed for %s: %s", backend, exc)# The disk key is already gone (the user-visible truth — report@@ -10189,42 +10312,38 @@ def save_codex_auth(payload: dict) -> dict:logger.error("Failed to write Codex auth files: %s", exc, exc_info=True)return {"ok": False, "message": f"Failed to write Codex config: {exc}"}- with CONFIG_LOCK:- try:- config = load_config()- except FileNotFoundError:- config = V2Config()- config.agents.codex.auth_mode = auth_mode- config.agents.codex.api_key = api_key if auth_mode == "api_key" else None- config.agents.codex.base_url = effective_base_url+ from config.v2_config import update_config_fields++ def _apply_codex_auth(cfg: V2Config) -> None:+ cfg.agents.codex.auth_mode = auth_mode+ cfg.agents.codex.api_key = api_key if auth_mode == "api_key" else None+ cfg.agents.codex.base_url = effective_base_url# Marker lifecycle on save: an explicit API-key save consumes# the OAuth-transition marker (the user just chose their# endpoint — restored, typed fresh, or official-only); an OAuth# save applies the same retention semantics as the controller# path (#1449): fresh capture overwrites, the official-key# transition clears, a repeated pure-OAuth save retains.- # A failed save here only loses the V2Config mirror — the- # durable marker state was already recorded by the pre-persist- # above, and the on-disk codex files are authoritative.if auth_mode == "api_key":- config.agents.codex.oauth_relay_marker = None+ cfg.agents.codex.oauth_relay_marker = Noneelif captured_oauth_relay is not None:- config.agents.codex.oauth_relay_marker = captured_oauth_relay+ cfg.agents.codex.oauth_relay_marker = captured_oauth_relayelif observed_api_key_auth:- config.agents.codex.oauth_relay_marker = None- try:- config.save()- except Exception:- # The on-disk codex files are authoritative and the durable- # marker state was pre-persisted, but the V2Config mirror- # (auth_mode / base_url intent the controller reloads via- # ``_load_backend_runtime_config``) did NOT land — surface a- # partial-failure notice instead of silently reporting- # success while runtime reconciliation sees stale config.- logger.warning("V2Config mirror write failed during codex auth save", exc_info=True)- notices = notices + [- {"code": "v2_mirror_save_failed", "detail": "saved to codex files but not to Avibe config"}- ]+ cfg.agents.codex.oauth_relay_marker = None++ try:+ update_config_fields(_apply_codex_auth)+ except Exception:+ # The on-disk codex files are authoritative and the durable+ # marker state was pre-persisted, but the V2Config mirror+ # (auth_mode / base_url intent the controller reloads via+ # ``_load_backend_runtime_config``) did NOT land — surface a+ # partial-failure notice instead of silently reporting+ # success while runtime reconciliation sees stale config.+ logger.warning("V2Config mirror write failed during codex auth save", exc_info=True)+ notices = notices + [+ {"code": "v2_mirror_save_failed", "detail": "saved to codex files but not to Avibe config"}+ ]restart_result = restart_backend("codex",@@ -10507,23 +10626,22 @@ def save_claude_auth(payload: dict) -> dict:logger.error("Failed to write Claude settings.json: %s", exc, exc_info=True)return {"ok": False, "message": f"Failed to write Claude settings: {exc}"}- with CONFIG_LOCK:- try:- config = load_config()- except FileNotFoundError:- config = V2Config()- config.agents.claude.auth_mode = auth_mode+ from config.v2_config import update_config_fields++ def _apply_claude_auth(cfg: V2Config) -> None:+ cfg.agents.claude.auth_mode = auth_mode# Flip the explicit marker so ``build_claude_subprocess_env``# honors ``auth_mode`` strictly (strip inherited env in OAuth# mode) for this and subsequent launches. Legacy installs that# have never been through this save path keep the flag at its# ``False`` default and continue to inherit shell env vars.- config.agents.claude.auth_mode_set = True+ cfg.agents.claude.auth_mode_set = True# Secrets and endpoint overrides live in Claude's own settings.json.# Clear legacy cache fields so future reads do not have two writers.- config.agents.claude.api_key = None- config.agents.claude.base_url = None- config.save()+ cfg.agents.claude.api_key = None+ cfg.agents.claude.base_url = None++ update_config_fields(_apply_claude_auth)oauth_cleanup_result: dict | None = Noneif auth_mode == "api_key":@@ -11906,21 +12024,27 @@ async def _delete_opencode_provider_auth_async(provider_id: str) -> dict:def _clear_opencode_default_provider_if(provider_id: str) -> None:"""Clear the saved OpenCode default if it points at ``provider_id``."""- with CONFIG_LOCK:- try:- cfg = load_config()- except FileNotFoundError:- return+ from config import paths as _paths+ from config.v2_config import update_config_fields++ if not _paths.get_config_path().exists():+ return++ def _clear_if_matching(cfg) -> None:+ # Compare-and-clear INSIDE the transaction on the lock-fresh+ # config (#1458 stage ③): a concurrent default switch to another+ # provider must not be cleared by a stale comparison.opencode_cfg = getattr(getattr(cfg, "agents", None), "opencode", None)current_default = getattr(opencode_cfg, "default_provider", None)if isinstance(current_default, str) and current_default.strip() == provider_id:opencode_cfg.default_provider = None- cfg.save()logger.info("clear_opencode_default_provider: cleared default_provider after removing %s",provider_id,)+ update_config_fields(_clear_if_matching)+def delete_opencode_provider_auth(provider_id: str) -> dict:from vibe.async_bridge import run_coroutine_blockingdiff --git a/vibe/runtime.py b/vibe/runtime.pyindex 12912dc7a..ac6fc5417 100644--- a/vibe/runtime.py+++ b/vibe/runtime.py@@ -193,9 +193,17 @@ def ensure_config():guard_source_checkout_default_state_bootstrap()config_path = paths.get_config_path()- if not config_path.exists():- default = default_config()- default.save(config_path)+ from config.v2_config import config_file_lock++ # Create-if-absent under the cross-process file lock (#1458 stage+ # ③): the existence check and the seeding save are one atomic step,+ # so a first-run default snapshot cannot overwrite an initial+ # settings save another process completed between a lock-free check+ # and the write.+ with config_file_lock(config_path):+ if not config_path.exists():+ default = default_config()+ default.save(config_path)return V2Config.load(config_path)diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 68103af5a..b3648b206 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -1527,7 +1527,20 @@ def _platform_runtime_fields_changed(previous: V2Config | None, current: V2Confiif previous is None:return Falseplatform_config_keys = {descriptor.config_key for descriptor in im_platform_descriptors()}- if "platforms" not in payload and "platform" not in payload and not any(key in payload for key in platform_config_keys):+ # The list-operations verb mutates the enabled list without carrying a+ # literal ``platforms`` section. Treat it as a platforms edit so+ # enable/disable toggles still reach the comparison below, but do not+ # infer a runtime change from the verb alone: Finish may replay an+ # already-applied operation.+ from vibe.api import _LIST_OPS_PAYLOAD_KEY++ has_list_ops = _LIST_OPS_PAYLOAD_KEY in payload+ if (+ not has_list_ops+ and "platforms" not in payload+ and "platform" not in payload+ and not any(key in payload for key in platform_config_keys)+ ):return Falsereturn (set(previous.platforms.enabled) != set(current.platforms.enabled)@@ -7520,29 +7533,40 @@ def _persist_wechat_qr_credentials(result: dict) -> None:if not isinstance(token, str) or not token.strip():return+ from config.v2_config import config_file_lockfrom vibe import api as vibe_api- from core.services import settings as settings_service- config = settings_service.load_config(default_factory=settings_service.default_config)- current = vibe_api.config_to_payload(config, include_secrets=True)- wechat = dict(current.get("wechat") or {})- wechat["bot_token"] = token.strip()+ new_bot_token = token.strip()+ new_base_url = Noneif isinstance(result.get("base_url"), str) and result["base_url"].strip():- wechat["base_url"] = result["base_url"].strip()- elif not wechat.get("base_url"):- wechat["base_url"] = "https://ilinkai.weixin.qq.com"- current["wechat"] = wechat-- platforms = dict(current.get("platforms") or {})- enabled = list(platforms.get("enabled") or [])- if "wechat" not in enabled:- enabled.append("wechat")- platforms["enabled"] = enabled- if not platforms.get("primary") or platforms.get("primary") == "avibe":- platforms["primary"] = "wechat"- current["platforms"] = platforms-- vibe_api.save_config(current)+ new_base_url = result["base_url"].strip()++ # Patch-write shape (#1458 stage ③): the whole compute-and-save runs+ # under the config transaction — the wechat fields and the+ # enabled-list mutation are derived from the lock-fresh snapshot, so+ # a concurrent wechat/platform save between an earlier read and this+ # write can no longer be overwritten by stale section values.+ with config_file_lock():+ try:+ base = vibe_api.load_config()+ except FileNotFoundError:+ # Fresh install: seed the same default the settings loader+ # uses, exactly like the previous default_factory path.+ from core.services import settings as settings_service++ base = settings_service.default_config()+ wechat = {"bot_token": new_bot_token}+ if new_base_url:+ wechat["base_url"] = new_base_url+ elif not base.wechat.base_url:+ wechat["base_url"] = "https://ilinkai.weixin.qq.com"++ vibe_api.save_config(+ {+ "wechat": wechat,+ "__avibe_list_ops": {"platforms.enabled": {"add": ["wechat"]}},+ }+ )WECHAT_QR_LOGIN_BASE_URL = "https://ilinkai.weixin.qq.com"@@ -7583,7 +7607,11 @@ async def wechat_qr_login_poll():user_id = result["user_id"]try:- _persist_wechat_qr_credentials(result)+ # The persistence helper takes the cross-process config+ # lock and does synchronous file/DB work — keep it off the+ # ASGI event loop so other UI requests don't stall while it+ # waits on the lock.+ await asyncio.to_thread(_persist_wechat_qr_credentials, result)except Exception as exc:logger.error("Failed to persist WeChat QR credentials: %s", exc)return jsonify({"ok": False, "error": "failed_to_persist_wechat_credentials"}), 500@@ -12637,10 +12665,11 @@ if os.environ.get("E2E_TEST_MODE", "").lower() in ("true", "1", "yes"):# Merge CWD into existing config (load → modify → save)from vibe import api as vibe_api- current = vibe_api.config_to_payload(vibe_api.load_config())- current.setdefault("runtime", {})- current["runtime"]["default_cwd"] = modal_values.get("cwd", "/tmp")- result = vibe_api.save_config(current)+ # Patch-write shape (#1458 stage ③): only the field+ # this modal owns.+ result = vibe_api.save_config(+ {"runtime": {"default_cwd": modal_values.get("cwd", "/tmp")}}+ )return jsonify({"ok": True, "action": action})elif action == "routing_submit":