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
fix(settings): edit one scope's changed fields instead of saving whole copies (#3048)
Call White43b5d7788fd0
diff --git a/config/v2_settings.py b/config/v2_settings.pyindex edf148462..7a5ac6efb 100644--- a/config/v2_settings.py+++ b/config/v2_settings.py@@ -8,7 +8,7 @@ import threadingfrom dataclasses import dataclass, fieldfrom datetime import datetime, timezonefrom pathlib import Path-from typing import Dict, List, Optional, Tuple+from typing import Callable, Dict, List, Optional, Tuplefrom config import pathsfrom modules.agents.catalog import NATIVE_CLI_BACKENDS@@ -569,6 +569,23 @@ class SettingsStore:self._loaded_state = copy.deepcopy(self.settings)self._generation += 1+ def apply(self, mutate: Callable[[SettingsState], None], *, user_context=None) -> None:+ """Run ``mutate`` on the authoritative settings inside one write transaction.++ Unlike ``save``, nothing this store loaded earlier is written back, so an+ edit cannot revert what another writer changed in the meantime. The store+ then holds the committed snapshot.+ """+ with self._reload_lock:+ try:+ revision = self._service.save_state(self.settings, user_context=user_context, mutate=mutate)+ except Exception:+ self._load_with_revision()+ raise+ self._observed_revision = revision+ self._loaded_state = copy.deepcopy(self.settings)+ self._generation += 1+# --- Channel helpers ---def _channel_key(self, channel_id: str, platform: Optional[str] = None) -> str:diff --git a/core/handlers/base.py b/core/handlers/base.pyindex d4bea6341..90072e570 100644--- a/core/handlers/base.py+++ b/core/handlers/base.py@@ -58,6 +58,19 @@ class BaseHandler:def _t(self, key: str, **kwargs) -> str:return i18n_t(key, self._get_lang(), **kwargs)+ def _settings_error_text(self, error: Exception) -> str:+ """Describe a refused settings save the way the Web settings pages do."""+ code = getattr(error, "code", None)+ if code == "settings_conflict":+ return f"{self._t('error.settingsConflict.message')} {self._t('error.settingsConflict.hint')}"+ if code == "agent_unavailable":+ agent = getattr(error, "agent_name", "")+ return (+ f"{self._t('error.scopeAgentUnavailable.message', agent=agent)} "+ f"{self._t('error.scopeAgentUnavailable.hint')}"+ )+ return str(error)+def _context_can_start_fresh_session_without_reset(self, context: MessageContext) -> bool:im_client = self._get_im_client(context)is_dm = bool((context.platform_specific or {}).get("is_dm", False))diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.pyindex 2e5694409..d0595af5c 100644--- a/core/handlers/command_handlers.py+++ b/core/handlers/command_handlers.py@@ -715,7 +715,7 @@ class CommandHandlers(BaseHandler):except Exception as e:logger.error(f"Error setting cwd: {e}")channel_context = self._get_channel_context(context)- await im_client.send_message(channel_context, f"❌ {self._t('error.cwdSetFailed', error=str(e))}")+ await im_client.send_message(channel_context, f"❌ {self._t('error.cwdSetFailed', error=self._settings_error_text(e))}")async def handle_change_cwd_submission(self,diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.pyindex 952d7c75c..a2ab80512 100644--- a/core/handlers/session_handler.py+++ b/core/handlers/session_handler.py@@ -2169,7 +2169,7 @@ class SessionHandler(BaseHandler):)await self._get_im_client(context).send_message(context,- f"❌ {self._t('error.resumeSubmitFailed', error=str(e))}",+ f"❌ {self._t('error.resumeSubmitFailed', error=self._settings_error_text(e))}",)def _routing_matches_backend(self, routing, backend: str) -> bool:diff --git a/core/handlers/settings_handler.py b/core/handlers/settings_handler.pyindex 38808a14c..b9ad35b35 100644--- a/core/handlers/settings_handler.py+++ b/core/handlers/settings_handler.py@@ -362,7 +362,7 @@ class SettingsHandler(BaseHandler):logger.error(f"Error toggling message type {msg_type}: {e}")await self._get_im_client(context).send_message(context,- self._get_formatter(context).format_error(self._t("error.toggleSettingFailed", error=str(e))),+ self._get_formatter(context).format_error(self._t("error.toggleSettingFailed", error=self._settings_error_text(e))),)async def handle_info_message_types(self, context: MessageContext):@@ -799,7 +799,7 @@ class SettingsHandler(BaseHandler):)await self._get_im_client(context).send_message(context,- f"❌ {self._t('error.settingsUpdateFailed', error=str(e))}",+ f"❌ {self._t('error.settingsUpdateFailed', error=self._settings_error_text(e))}",)else:raise@@ -959,7 +959,7 @@ class SettingsHandler(BaseHandler):if notify_user:await self._get_im_client(context).send_message(context,- f"❌ {self._t('error.routingUpdateFailed', error=str(e))}",+ f"❌ {self._t('error.routingUpdateFailed', error=self._settings_error_text(e))}",)else:raisediff --git a/docs/plans/scope-settings-patch.md b/docs/plans/scope-settings-patch.mdnew file mode 100644index 000000000..0a9e3b12b--- /dev/null+++ b/docs/plans/scope-settings-patch.md@@ -0,0 +1,75 @@+# Single-scope settings edits++## Background++The Web settings pages for groups and DM users saved by posting their whole+in-memory copy back: every channel of a platform (`POST /api/settings`) or a+whole user row (`POST /api/users`). The server treated that copy as the truth,+so any edit from a page opened earlier:++- deleted channels another writer had enabled since the page loaded;+- reverted other fields and other channels to the page's old values;+- restored a user's admin or enabled flag that had been revoked in the meantime.++The only optimistic-concurrency check (`expected_agent_name`) covered the Agent+binding alone, and its token went stale after the page's own first autosave.++IM settings writes had a separate gap: `SettingsManager._save_settings` logged+and swallowed a refused save, so IM forms confirmed changes that never landed.++## Contract++`PATCH /api/settings/scope` (Member role, same access-policy checks as the+existing settings writes):++```json+{+ "platform": "lark",+ "scope": "channel | thread | user",+ "id": "<channel or user id>",+ "thread_id": "<topic id, thread scope only>",+ "changes": { "<field>": "<value>", "routing": { "<routing field>": "<value>" } },+ "expected_agent_name": "<required with a routing change>"+}+```++- Fields: channels and Telegram topics take `enabled`, `show_message_types`,+ `custom_cwd`, `require_mention`, `require_bind`, `routing`; DM users take+ `display_name`, `enabled`, `show_message_types`, `custom_cwd`, `routing`.+ Admin rights keep their dedicated endpoint. Unknown fields are refused (400).+- Only named fields are written. `routing` merges key by key into the stored+ route, and the result goes through the same Claude effort normalization as+ the existing save paths.+- The change is applied to the rows read under the SQLite write lock+ (`SettingsStore.apply`), so nothing the caller loaded earlier is written back.+- `expected_agent_name` is the Agent the caller's view of the route was based+ on. If the stored Agent differs, the change is refused with+ `settings_conflict` (409), unless it sets the stored Agent itself. A new+ binding must name an enabled Agent (`agent_unavailable`).+- A channel or topic without a row is created; a topic starts from its parent+ channel's stored settings and materializes the platform mention default, as+ the existing topic save did. A missing DM user is `user_not_found` (404).+- The response carries the stored row in the shape the settings reads return.++The bulk endpoints remain for the setup wizard and existing callers; the+settings pages no longer use them.++## Web pages++Users, groups, and Telegram topics send each edit as a diff of the row before+and after it, with the routing view's Agent as `expected_agent_name`. The+stored row in the response replaces the local one unless a newer edit of the+same scope is in flight; a refused edit reloads that platform's rows.++## IM++A refused settings save propagates to the IM handler, which reports it with the+same localized conflict or unavailable-Agent text as the Web pages, and the+runtime view is rebuilt from the committed rows.++## Out of scope++- IM writes still go through `SettingsManager`'s platform save; moving them to+ the single-scope path and unifying route normalization is the next step.+- Display fixes on the settings pages (effective model, inherited vs override,+ new-session hint) and per-row save status.diff --git a/modules/settings_manager.py b/modules/settings_manager.pyindex f243cd0d9..53b0106a7 100644--- a/modules/settings_manager.py+++ b/modules/settings_manager.py@@ -310,6 +310,12 @@ class SettingsManager:logger.info("Settings saved successfully")except Exception as e:logger.error(f"Error saving settings: {e}")+ # The store reloaded its committed rows; drop the unsaved edit from the+ # runtime view too, and let the caller tell the user it failed.+ with self._runtime_settings_lock:+ self._rebuild_runtime_settings(reason="save_failed")+ self._last_seen_store_generation = self.store.generation+ raisedef get_user_settings(self, user_id: Union[int, str]) -> UserSettings:"""Get settings for a specific user/channel context.diff --git a/storage/settings_service.py b/storage/settings_service.pyindex c75b1df01..0fd59bede 100644--- a/storage/settings_service.py+++ b/storage/settings_service.py@@ -1,10 +1,11 @@from __future__ import annotations+import copyimport jsonfrom dataclasses import asdict, fields, replacefrom datetime import datetime, timezonefrom pathlib import Path-from typing import Any+from typing import Any, Callablefrom sqlalchemy import Connection, selectfrom sqlalchemy.dialects.sqlite import insert as sqlite_insert@@ -190,8 +191,20 @@ class SQLiteSettingsService:)def save_state(- self, state: SettingsState, *, user_context: Any = None, baseline: SettingsState | None = None+ self,+ state: SettingsState,+ *,+ user_context: Any = None,+ baseline: SettingsState | None = None,+ mutate: Callable[[SettingsState], None] | None = None,) -> str:+ """Persist ``state``, or apply ``mutate`` to the state held under the write lock.++ With ``baseline``, only the scopes ``state`` changed since that load are+ written. With ``mutate``, ``state`` only receives the committed snapshot:+ the edit runs against the authoritative rows, so it cannot carry stale+ copies of anything it did not change.+ """from vibe.authorization import require_instance_role# General config still accepts Editor preferences and may round-trip@@ -203,12 +216,15 @@ class SQLiteSettingsService:with self.engine.begin() as conn:reserve_write_lock(conn)current = self._load_state(conn)- if baseline is not None and not context.can_manage_access_members:- # A protected-field echo may equal the loaded value but no- # longer equal the authoritative value. Reject that stale- # snapshot before delta merging could silently drop the echo.- _require_preserved_access_policy(current, baseline)- if baseline is not None:+ if mutate is not None:+ state = copy.deepcopy(current)+ mutate(state)+ elif baseline is not None:+ if not context.can_manage_access_members:+ # A protected-field echo may equal the loaded value but no+ # longer equal the authoritative value. Reject that stale+ # snapshot before delta merging could silently drop the echo.+ _require_preserved_access_policy(current, baseline)state = _merge_settings_changes(current, draft, baseline)if not context.can_manage_access_members:_require_preserved_access_policy(current, state)diff --git a/tests/test_member_management_parity.py b/tests/test_member_management_parity.pyindex 946c8572b..2e47566bc 100644--- a/tests/test_member_management_parity.py+++ b/tests/test_member_management_parity.py@@ -118,7 +118,7 @@ def test_complete_registered_api_management_inventory():for method in (getattr(route, "methods", None) or ())if method not in {"HEAD", "OPTIONS"}}- assert len(endpoints) == 295+ assert len(endpoints) == 296# Editors who use Vault read avault's authorization state; the handler admits only# instance managers to raise the Keychain dialog on the host.for method in ("GET", "POST"):@@ -440,6 +440,32 @@ def test_member_channel_and_dm_preferences_preserve_access_state(management_httpassert not store.get_user("bound", platform="telegram").enabled+def test_member_scope_patch_preserves_access_state(management_http):+ """PERMISSIONS-013: the single-scope settings PATCH keeps the same Member boundary."""++ store = SettingsStore.get_instance()+ store.set_channels_for_platform("telegram", {"chat": ChannelSettings(enabled=True, require_bind=True)})+ store.set_users_for_platform("telegram", {"bound": UserSettings(is_admin=True, enabled=False, bound_at="old")})+ store.save()+ request = management_http()++ def patch(scope, native_id, changes):+ return request("PATCH", "/api/settings/scope", payload={+ "platform": "telegram", "scope": scope, "id": native_id, "changes": changes,+ })++ assert patch("channel", "chat", {"custom_cwd": "/tmp/ordinary"}).status_code == 200+ assert patch("user", "bound", {"display_name": "成员", "custom_cwd": "/tmp/dm"}).status_code == 200+ assert patch("channel", "chat", {"require_bind": False}).status_code == 403+ assert patch("user", "bound", {"enabled": True}).status_code == 403+ refused = patch("user", "bound", {"is_admin": False})+ assert refused.status_code == 400 and refused.get_json()["code"] == "invalid_changes"+ store = SettingsStore.get_instance()+ channel, user = store.find_channel("chat", platform="telegram"), store.get_user("bound", platform="telegram")+ assert (channel.custom_cwd, channel.require_bind) == ("/tmp/ordinary", True)+ assert (user.display_name, user.custom_cwd, user.is_admin, user.enabled) == ("成员", "/tmp/dm", True, False)++@pytest.mark.parametrize("channels", [{}, {"chat": {}}, {"chat": {"require_bind": None}}, {"chat": {"require_bind": False}}])diff --git a/tests/test_scope_settings_patch.py b/tests/test_scope_settings_patch.pynew file mode 100644index 000000000..c368ef5e7--- /dev/null+++ b/tests/test_scope_settings_patch.py@@ -0,0 +1,130 @@+"""PATCH /api/settings/scope: one edit changes only the fields it names on one scope.++The Web settings pages hold a copy of every channel and user from when they+loaded. Saving that copy back reverted other writers' changes, deleted channels+enabled since, and restored revoked admin rights; these tests pin the contract+that replaced it.+"""++from __future__ import annotations++import pytest++from config.v2_settings import ChannelSettings, RoutingSettings, SettingsStore, UserSettings+from core.vibe_agents import VibeAgentStore+from storage.settings_service import ScopeAgentUnavailableError, StaleScopeAgentBindingError+from vibe import api+++def store(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ SettingsStore.reset_instance()+ agents = VibeAgentStore()+ agents.create(name="pm", backend="claude")+ agents.create(name="qa", backend="claude")+ agents.close()+ store = SettingsStore.get_instance()+ yield store+ SettingsStore.reset_instance()+++def _patch(scope: str, native_id: str, changes: dict, *, platform: str = "slack", **extra) -> dict:+ return api.patch_scope_settings({"platform": platform, "scope": scope, "id": native_id, "changes": changes, **extra})+++def test_an_edit_writes_only_its_fields_of_its_scope(store):+ store.set_channels_for_platform("slack", {"A": ChannelSettings(enabled=True, custom_cwd="/a")})+ store.set_users_for_platform("slack", {"U": UserSettings(display_name="Pat", is_admin=True)})+ store.save()+ # Written elsewhere after a settings page loaded: a new channel, A's workdir,+ # and the user's admin and enabled flags.+ store.set_channels_for_platform("slack", {+ "A": ChannelSettings(enabled=True, custom_cwd="/a-elsewhere"),+ "B": ChannelSettings(enabled=True, custom_cwd="/b"),+ })+ store.set_users_for_platform("slack", {"U": UserSettings(display_name="Pat", is_admin=False, enabled=False)})+ store.save()++ channel = _patch("channel", "A", {"require_mention": True})+ user = _patch("user", "U", {"custom_cwd": "/u"})++ assert channel["settings"]["require_mention"] is True+ assert channel["settings"]["custom_cwd"] == "/a-elsewhere"+ store = SettingsStore.get_instance() # reloads what the request committed+ assert store.find_channel("B", platform="slack").custom_cwd == "/b"+ saved_user = store.get_user("U", platform="slack")+ assert (saved_user.custom_cwd, saved_user.is_admin, saved_user.enabled) == ("/u", False, False)+ assert user["settings"]["custom_cwd"] == "/u"+++ ("stored_agent", "expected", "routing", "outcome"),+ [+ # The page's own earlier save bound the Agent its next edit is based on.+ (None, None, {"agent_name": "pm", "model": "m1"}, ("pm", "m1", None)),+ ("pm", "pm", {"reasoning_effort": "high"}, ("pm", "m0", "high")),+ # Another writer moved the scope to pm: a model picked for the old Agent is refused...+ ("pm", None, {"model": "m1"}, StaleScopeAgentBindingError),+ ("pm", "qa", {"agent_name": "qa", "model": "m1"}, StaleScopeAgentBindingError),+ # ...unless the edit itself sets the stored Agent.+ ("pm", None, {"agent_name": "pm", "model": "m1"}, ("pm", "m1", None)),+ # A new binding still needs an enabled Agent.+ ("pm", "pm", {"agent_name": "missing"}, ScopeAgentUnavailableError),+ ],+)+def test_a_routing_edit_names_the_agent_its_view_was_based_on(store, stored_agent, expected, routing, outcome):+ store.set_channels_for_platform("slack", {+ "A": ChannelSettings(enabled=True, routing=RoutingSettings(agent_name=stored_agent, model="m0")),+ })+ store.save()++ request = {"routing": routing}+ if isinstance(outcome, type):+ with pytest.raises(outcome):+ _patch("channel", "A", request, expected_agent_name=expected)+ saved = SettingsStore.get_instance().find_channel("A", platform="slack").routing+ assert (saved.agent_name, saved.model) == (stored_agent, "m0")+ else:+ result = _patch("channel", "A", request, expected_agent_name=expected)["settings"]+ assert (result["routing"]["agent_name"], result["routing"]["model"], result["routing"]["reasoning_effort"]) == outcome+ assert result["expected_agent_name"] == outcome[0]+++def test_a_topic_override_starts_from_its_channel(store, monkeypatch):+ monkeypatch.setattr(api, "_stored_platform_config", lambda _platform: type("Config", (), {"require_mention": False}))+ store.set_channels_for_platform("telegram", {+ "chat": ChannelSettings(enabled=True, custom_cwd="/chat", routing=RoutingSettings(agent_name="qa")),+ })+ store.save()++ created = _patch("thread", "chat", {}, platform="telegram", thread_id="7")["settings"]+ edited = _patch("thread", "chat", {"custom_cwd": "/topic"}, platform="telegram", thread_id="7")["settings"]++ assert (created["routing"]["agent_name"], created["custom_cwd"], created["require_mention"]) == ("qa", "/chat", False)+ assert (edited["routing"]["agent_name"], edited["custom_cwd"]) == ("qa", "/topic")+ assert SettingsStore.get_instance().find_channel("chat", platform="telegram").custom_cwd == "/chat"+++ ("request_fields", "code", "status"),+ [+ ({"scope": "guild", "id": "G", "changes": {}}, "invalid_scope", 400),+ ({"scope": "thread", "id": "C", "thread_id": "1", "changes": {}}, "invalid_scope", 400),+ ({"scope": "channel", "id": "A", "changes": {"is_admin": True}}, "invalid_changes", 400),+ ({"scope": "user", "id": "U", "changes": {"require_bind": True}}, "invalid_changes", 400),+ ({"scope": "channel", "id": "A", "changes": {"enabled": "yes"}}, "invalid_changes", 400),+ ({"scope": "channel", "id": "A", "changes": {"routing": {"agent_name": "pm"}}}, "invalid_changes", 400),+ ({"scope": "channel", "id": "A", "changes": {"routing": {"agent": "pm"}}, "expected_agent_name": None},+ "invalid_changes", 400),+ ({"scope": "user", "id": "nobody", "changes": {"custom_cwd": "/x"}}, "user_not_found", 404),+ ],+)+def test_requests_the_api_cannot_apply_are_refused_without_writing(store, request_fields, code, status):+ revision = store._service.current_revision()++ with pytest.raises(api.ScopeSettingsRequestError) as refused:+ api.patch_scope_settings({"platform": "slack", **request_fields})++ assert (refused.value.code, refused.value.status) == (code, status)+ assert store._service.current_revision() == revisiondiff --git a/tests/test_settings_handler.py b/tests/test_settings_handler.pyindex f36f9f46b..ec2c7e1a5 100644--- a/tests/test_settings_handler.py+++ b/tests/test_settings_handler.py@@ -924,3 +924,37 @@ def test_handle_routing_modal_update_uses_the_visible_current_agent() -> None:assert len(update_calls) == 1assert update_calls[0]["routing"].current_agent == "id-opencode"assert update_calls[0]["selected_agent"] == "id-opencode"+++def test_a_routing_save_the_store_refuses_is_reported_not_confirmed(tmp_path, monkeypatch) -> None:+ """IM forms used to confirm a routing change whose save had failed, because the save swallowed errors."""+ from config import paths+ from config.v2_settings import ChannelSettings, SettingsStore+ from modules.settings_manager import SettingsManager++ monkeypatch.setattr(paths, "ensure_data_dirs", lambda: None)+ SettingsStore.reset_instance()+ manager = SettingsManager(settings_file=str(tmp_path / "settings.json"), platform="telegram")+ try:+ manager.store.update_channel("-100123", ChannelSettings(enabled=True), platform="telegram")+ handler, send_message = _make_handler(manager)+ handler.controller._get_settings_key = lambda _context: "-100123"+ # Listed by the form, but not an enabled Agent the store can bind.+ handler.controller.vibe_agent_store.agents.append(+ SimpleNamespace(id="id-gone", name="gone", backend="claude", model=None, enabled=True)+ )++ with patch.object(handler, "_routing_update_needs_new_session_hint", return_value=False):+ asyncio.run(+ handler.handle_routing_update(+ user_id="42", channel_id="-100123", agent_id="id-gone", platform="telegram"+ )+ )++ text = send_message.await_args.args[1]+ assert text.startswith("❌"), text+ assert "Agent `gone` is unavailable for this route." in text+ assert manager.get_channel_routing("-100123").agent_name is None+ assert manager.store.find_channel("-100123", platform="telegram").routing.agent_name is None+ finally:+ SettingsStore.reset_instance()diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.pyindex 3dfe150e5..277c3758a 100644--- a/tests/test_ui_server_fastapi.py+++ b/tests/test_ui_server_fastapi.py@@ -536,6 +536,7 @@ def test_scope_settings_routes_report_localized_stale_agent_binding_conflicts(momonkeypatch.setattr(api, "save_settings", stale)monkeypatch.setattr(api, "save_thread_settings", stale)monkeypatch.setattr(api, "save_users", stale)+ monkeypatch.setattr(api, "patch_scope_settings", stale)client = app.test_client()headers = csrf_headers(client)@@ -547,6 +548,11 @@ def test_scope_settings_routes_report_localized_stale_agent_binding_conflicts(moheaders=headers,),client.post("/api/users", json={"platform": "slack", "users": {}}, headers=headers),+ client.patch(+ "/api/settings/scope",+ json={"platform": "slack", "scope": "channel", "id": "C1", "changes": {}},+ headers=headers,+ ),)for response in responses:@@ -580,6 +586,7 @@ def test_scope_settings_routes_localize_unavailable_agent_errors(monkeypatch):monkeypatch.setattr(api, "save_settings", unavailable)monkeypatch.setattr(api, "save_thread_settings", unavailable)monkeypatch.setattr(api, "save_users", unavailable)+ monkeypatch.setattr(api, "patch_scope_settings", unavailable)client = app.test_client()headers = csrf_headers(client)@@ -591,6 +598,11 @@ def test_scope_settings_routes_localize_unavailable_agent_errors(monkeypatch):headers=headers,),client.post("/api/users", json={"platform": "slack", "users": {}}, headers=headers),+ client.patch(+ "/api/settings/scope",+ json={"platform": "slack", "scope": "channel", "id": "C1", "changes": {}},+ headers=headers,+ ),)for response in responses:diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsxindex aca723983..e0f60c42a 100644--- a/ui/src/components/steps/ChannelList.tsx+++ b/ui/src/components/steps/ChannelList.tsx@@ -27,6 +27,7 @@ import { hasUsableSecret } from '../../lib/secretFields';import { setConfigField } from '../../lib/configMutations';import { EyebrowBadge, PlatformIcon, WizardCard } from '../visual';import { RoutingConfigPanel } from '../shared/RoutingConfigPanel';+import { CHANNEL_SCOPE_FIELDS, scopeSettingsChange } from '../../lib/scopeSettingsPatch';import { CompactSelect, SearchField, ToggleSwitch } from '../settings/SettingsPrimitives';import { Button } from '../ui/button';import { TelegramTopicList } from './TelegramTopicList';@@ -147,7 +148,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBconst refreshFollowupVersionRef = useRef(0);const channelRequestVersionRef = useRef(0);const allPlatformsRequestVersionRef = useRef(0);- const channelSaveVersionRef = useRef<Record<string, number>>({});+ const scopeSaveVersionRef = useRef<Record<string, number>>({});const currentPlatformRef = useRef<string>('');// Directory browser state — tracks which channel's cwd picker is openconst [browsingCwdFor, setBrowsingCwdFor] = useState<string | null>(null);@@ -649,23 +650,8 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBreturn channel ? channel.enabled !== false : false;};- const persistConfigs = async (nextConfigs: Record<string, ChannelConfig>) => {- if (!isPage) {- setConfigs(nextConfigs);- return;- }-- setLoading(true);- try {- await api.saveSettings({ channels: nextConfigs }, platform);- showToast(t('channelList.settingsSaved'));- } catch {- showToast(t('channelList.settingsSaveFailed'), 'error');- } finally {- setLoading(false);- }- };-+ // Setup-wizard edits stay local until the wizard saves them; the settings+ // page edits through updateConfigForPlatform.const updateConfig = (channelId: string, patch: Partial<ChannelConfig>) => {const base = configs[channelId] || defaultConfig();const next = { ...base, ...patch };@@ -675,9 +661,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBif (!next.routing || typeof next.routing !== 'object') {next.routing = { agent_name: null };}- const nextConfigs = { ...configs, [channelId]: next };- setConfigs(nextConfigs);- void persistConfigs(nextConfigs);+ setConfigs({ ...configs, [channelId]: next });};const defaultConfig = (): ChannelConfig => ({@@ -720,6 +704,47 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB}, [currentRefreshMeta, t]);// ---- Page-mode all-platforms aggregation ----+ const reloadChannelConfigs = async (platformId: string) => {+ const settings = await api.getSettings(platformId).catch(() => null);+ if (!settings) return;+ const stored = (settings.channels || {}) as Record<string, ChannelConfig>;+ setAllConfigsByPlatform((prev) => ({ ...prev, [platformId]: stored }));+ if (currentPlatformRef.current === platformId) setConfigs(stored);+ if (platformId === 'telegram') setThreadConfigs(settings.threads || {});+ };++ // Each edit sends only what it changed on one scope. Resolves to the stored+ // row, or null when nothing was sent, the save failed (the page then reloads+ // the platform), or a newer edit of the same scope owns the local row.+ const persistScopeChange = async (+ platformId: string,+ scope: { kind: 'channel' | 'thread'; id: string; threadId?: string },+ base: ChannelConfig,+ next: ChannelConfig,+ { create = false }: { create?: boolean } = {},+ ): Promise<ChannelConfig | null> => {+ const change = scopeSettingsChange(base, next, CHANNEL_SCOPE_FIELDS) || (create ? { changes: {} } : null);+ if (!change) return null;+ const rowKey = `${platformId}::${scope.id}::${scope.threadId || ''}`;+ const version = (scopeSaveVersionRef.current[rowKey] || 0) + 1;+ scopeSaveVersionRef.current[rowKey] = version;+ try {+ const result = await api.patchScopeSettings({+ platform: platformId,+ scope: scope.kind,+ id: scope.id,+ ...(scope.threadId ? { thread_id: scope.threadId } : {}),+ ...change,+ });+ showToast(t('channelList.settingsSaved'));+ return scopeSaveVersionRef.current[rowKey] === version ? (result.settings as ChannelConfig) : null;+ } catch {+ showToast(t('channelList.settingsSaveFailed'), 'error');+ if (scopeSaveVersionRef.current[rowKey] === version) await reloadChannelConfigs(platformId);+ return null;+ }+ };+const updateConfigForPlatform = async (platformId: string,channelId: string,@@ -737,53 +762,61 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBif (!next.routing || typeof next.routing !== 'object') {next.routing = { agent_name: null };}- const nextPlatformConfigs = { ...platformConfigs, [channelId]: next };- setAllConfigsByPlatform((prev) => ({ ...prev, [platformId]: nextPlatformConfigs }));+ setAllConfigsByPlatform((prev) => ({+ ...prev,+ [platformId]: { ...(prev[platformId] || platformConfigs), [channelId]: next },+ }));if (platformId === platform) {- setConfigs(nextPlatformConfigs);+ setConfigs((prev) => ({ ...prev, [channelId]: next }));}if (!isPage) return;- const version = (channelSaveVersionRef.current[platformId] || 0) + 1;- channelSaveVersionRef.current[platformId] = version;- let stored: Record<string, ChannelConfig> | null;- try {- const result = await api.saveSettings({ channels: nextPlatformConfigs }, platformId);- stored = result?.channels || null;- showToast(t('channelList.settingsSaved'));- } catch {- showToast(t('channelList.settingsSaveFailed'), 'error');- const settings = await api.getSettings(platformId).catch(() => null);- stored = settings ? settings.channels || {} : null;+ const stored = await persistScopeChange(platformId, { kind: 'channel', id: channelId }, base, next);+ if (!stored) return;+ // The stored row replaces the page's copy on whichever views hold that platform.+ setAllConfigsByPlatform((prev) => ({+ ...prev,+ [platformId]: { ...(prev[platformId] || {}), [channelId]: stored },+ }));+ if (currentPlatformRef.current === platformId) {+ setConfigs((prev) => ({ ...prev, [channelId]: stored }));}- // Adopt the stored rows so each routing keeps the expected_agent_name read- // with it; a newer save on this platform owns the state instead.- if (!stored || channelSaveVersionRef.current[platformId] !== version) return;- const latest = stored;- setAllConfigsByPlatform((prev) => ({ ...prev, [platformId]: latest }));- if (currentPlatformRef.current === platformId) setConfigs(latest);};+ // A topic without an override shows its channel's settings; customizing it+ // creates the override from the channel's stored settings.const saveTelegramTopicConfig = async (channelId: string,topicId: string,- next: ChannelConfig,+ patch: Partial<ChannelConfig>,+ inherited?: ChannelConfig,) => {- setThreadConfigs((current) => ({+ const existing = threadConfigs[channelId]?.[topicId];+ const base = existing || inherited || defaultConfig();+ const next = { ...base, ...patch };+ const setTopic = (config: ChannelConfig) => setThreadConfigs((current) => ({...current,- [channelId]: { ...(current[channelId] || {}), [topicId]: next },+ [channelId]: { ...(current[channelId] || {}), [topicId]: config },}));- try {- const result = await api.saveThreadSettings('telegram', channelId, topicId, next);- const saved = (result.settings || next) as ChannelConfig;- setThreadConfigs((current) => ({- ...current,- [channelId]: { ...(current[channelId] || {}), [topicId]: saved },- }));- showToast(t('channelList.settingsSaved'));- } catch {- const settings = await api.getSettings('telegram').catch(() => null);- if (settings) setThreadConfigs(settings.threads || {});- showToast(t('channelList.settingsSaveFailed'), 'error');+ setTopic(next);+ const stored = await persistScopeChange(+ 'telegram',+ { kind: 'thread', id: channelId, threadId: topicId },+ base,+ next,+ { create: !existing },+ );+ if (stored) setTopic(stored);+ };++ // Page mode keys the open directory picker by `${platform}::${channelId}[::${topicId}]`.+ const selectBrowsedDirectory = (path: string) => {+ const [browsePlatform, browseChannelId, browseTopicId] = (browsingCwdFor || '').split('::');+ setBrowsingCwdFor(null);+ if (!browsePlatform || !browseChannelId) return;+ if (browseTopicId && threadConfigs[browseChannelId]?.[browseTopicId]) {+ void saveTelegramTopicConfig(browseChannelId, browseTopicId, { custom_cwd: path });+ } else {+ void updateConfigForPlatform(browsePlatform, browseChannelId, { custom_cwd: path });}};@@ -1079,23 +1112,29 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBshowToast(t('channelList.settingsSaveFailed'), 'error');return;}- let changed = false;- const nextPlatformConfigs = { ...platformConfigs };- for (const [cid, cfg] of Object.entries(platformConfigs)) {- if (cfg?.enabled === true && (cfg.require_mention === null || cfg.require_mention === undefined)) {- nextPlatformConfigs[cid] = { ...cfg, require_mention: current };- changed = true;- }- }- if (changed) {+ const inheriting = Object.keys(platformConfigs).filter((cid) => {+ const cfg = platformConfigs[cid];+ return cfg?.enabled === true && (cfg.require_mention === null || cfg.require_mention === undefined);+ });+ if (inheriting.length) {+ const nextPlatformConfigs = { ...platformConfigs };try {- await api.saveSettings({ channels: nextPlatformConfigs }, key);+ const results = await Promise.all(inheriting.map((cid) => api.patchScopeSettings({+ platform: key,+ scope: 'channel',+ id: cid,+ changes: { require_mention: current },+ })));+ inheriting.forEach((cid, index) => {+ nextPlatformConfigs[cid] = (results[index].settings as ChannelConfig) || nextPlatformConfigs[cid];+ });} catch {showToast(t('channelList.settingsSaveFailed'), 'error');+ await reloadChannelConfigs(key);return;}setAllConfigsByPlatform((prev) => ({ ...prev, [key]: nextPlatformConfigs }));- if (key === platform) setConfigs(nextPlatformConfigs);+ if (currentPlatformRef.current === key) setConfigs(nextPlatformConfigs);}}@@ -1632,19 +1671,19 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBshow_message_types: [...channelConfig.show_message_types],routing: { ...channelConfig.routing },};- void saveTelegramTopicConfig(channel.id, topicId, snapshot);+ void saveTelegramTopicConfig(channel.id, topicId, {}, snapshot);setExpandedTopicKey(`${channel.id}::${topicId}`);}}onReset={(topicId) => void resetTelegramTopicConfig(channel.id, topicId)}onSetEnabled={(topicId, enabled) => {const topicConfig = threadConfigs[channel.id]?.[topicId];- if (topicConfig) void saveTelegramTopicConfig(channel.id, topicId, { ...topicConfig, enabled });+ if (topicConfig) void saveTelegramTopicConfig(channel.id, topicId, { enabled });}}renderEditor={(topicId, topicConfig) => {return (<RoutingConfigPanelvalue={topicConfig}- onChange={(patch) => void saveTelegramTopicConfig(channel.id, topicId, { ...topicConfig, ...patch })}+ onChange={(patch) => void saveTelegramTopicConfig(channel.id, topicId, patch)}onBrowseDirectory={() => setBrowsingCwdFor(`telegram::${channel.id}::${topicId}`)}globalConfig={config}vibeAgents={vibeAgents}@@ -1677,14 +1716,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBreturn (<FolderBrowserinitialPath={selectedConfig?.custom_cwd || config.runtime?.default_cwd || '~/work'}- onSelect={(path) => {- if (browseTopicId && selectedConfig) {- void saveTelegramTopicConfig(browseChannelId, browseTopicId, { ...selectedConfig, custom_cwd: path });- } else {- void updateConfigForPlatform(browsePlatform, browseChannelId, { custom_cwd: path });- }- setBrowsingCwdFor(null);- }}+ onSelect={selectBrowsedDirectory}onClose={() => setBrowsingCwdFor(null)}/>);diff --git a/ui/src/components/steps/UserList.tsx b/ui/src/components/steps/UserList.tsxindex cc18e6a7f..0a36dd40a 100644--- a/ui/src/components/steps/UserList.tsx+++ b/ui/src/components/steps/UserList.tsx@@ -24,6 +24,7 @@ import { FolderBrowser } from '../ui/folder-browser';import { copyTextToClipboard } from '../../lib/utils';import { PlatformIcon } from '../visual';import { RoutingConfigPanel } from '../shared/RoutingConfigPanel';+import { scopeSettingsChange, USER_SCOPE_FIELDS } from '../../lib/scopeSettingsPatch';import { SearchField, ToggleSwitch } from '../settings/SettingsPrimitives';import { Button } from '../ui/button';import { Dialog, DialogContent, DialogTitle } from '../ui/dialog';@@ -518,42 +519,41 @@ export const UserList: React.FC = () => {});}, [aggregated, searchQuery, showDisabled]);- const persistUsers = async (platform: string, next: Record<string, Partial<UserConfig>>) => {- const version = (userSaveVersionRef.current[platform] || 0) + 1;- userSaveVersionRef.current[platform] = version;+ // Each edit sends only what it changed on one user; the stored row it gets+ // back replaces the local one unless a newer edit of that user is in flight.+ const persistUser = async (platform: string, userId: string, base: UserConfig, next: UserConfig) => {+ const change = scopeSettingsChange(base, next, USER_SCOPE_FIELDS);+ if (!change) return;+ const rowKey = `${platform}::${userId}`;+ const version = (userSaveVersionRef.current[rowKey] || 0) + 1;+ userSaveVersionRef.current[rowKey] = version;setLoading(true);- let stored: Record<string, UserConfig> | null;try {- const result = await api.saveUsers({ users: next }, platform);- stored = result?.users || null;+ const result = await api.patchScopeSettings({ platform, scope: 'user', id: userId, ...change });showToast(t('userList.settingsSaved'));+ const stored = result.settings as UserConfig | undefined;+ if (stored && userSaveVersionRef.current[rowKey] === version) {+ setUsersByPlatform((prev) => ({ ...prev, [platform]: { ...(prev[platform] || {}), [userId]: stored } }));+ }} catch {showToast(t('userList.settingsSaveFailed'), 'error');const result = await api.getUsers(platform).catch(() => null);- stored = result?.ok ? result.users || {} : null;+ if (result?.ok && userSaveVersionRef.current[rowKey] === version) {+ setUsersByPlatform((prev) => ({ ...prev, [platform]: result.users || {} }));+ }} finally {setLoading(false);}- // Adopt the stored rows so each routing keeps the expected_agent_name read- // with it; a newer save on this platform owns the state instead.- if (!stored || userSaveVersionRef.current[platform] !== version) return;- const latest = stored;- setUsersByPlatform((prev) => ({ ...prev, [platform]: latest }));};const updateUser = (platform: string, userId: string, patch: Partial<UserConfig>) => {- const platformUsers = usersByPlatform[platform] || {};- const base = platformUsers[userId] || defaultUserConfig();+ const base = (usersByPlatform[platform] || {})[userId] || defaultUserConfig();const next = { ...base, ...patch };if (!next.routing || typeof next.routing !== 'object') {next.routing = { agent_name: null };}- const nextPlatformUsers = { ...platformUsers, [userId]: next };- setUsersByPlatform((prev) => ({ ...prev, [platform]: nextPlatformUsers }));- void persistUsers(platform, { [userId]: canManageAccessMembers ? next : {- display_name: next.display_name, custom_cwd: next.custom_cwd,- routing: next.routing, show_message_types: next.show_message_types,- } });+ setUsersByPlatform((prev) => ({ ...prev, [platform]: { ...(prev[platform] || {}), [userId]: next } }));+ void persistUser(platform, userId, base, next);};const handleToggleAdmin = async (platform: string, userId: string, isAdmin: boolean) => {diff --git a/ui/src/components/steps/scopeRoutingSave.test.tsx b/ui/src/components/steps/scopeRoutingSave.test.tsxindex 18a02a9de..d20347be1 100644--- a/ui/src/components/steps/scopeRoutingSave.test.tsx+++ b/ui/src/components/steps/scopeRoutingSave.test.tsx@@ -6,13 +6,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { ChannelList } from './ChannelList';import { UserList } from './UserList';-// Each scope save carries expected_agent_name, the Agent binding the form last read.-// The server refuses a binding change whose token is outdated, so after every save-// attempt the page must hold the stored row, keeping routing and token read together.+// Each settings edit sends only what it changed on one scope, with the Agent the+// edited view was based on. Sending the page's whole copy back reverted other+// writers' changes and deleted channels enabled since the page loaded.const api = vi.hoisted(() => ({- getConfig: vi.fn(), getSettings: vi.fn(), saveSettings: vi.fn(), slackChannels: vi.fn(),- getUsers: vi.fn(), saveUsers: vi.fn(), getBindCodes: vi.fn(),+ getConfig: vi.fn(), getSettings: vi.fn(), slackChannels: vi.fn(), telegramChats: vi.fn(),+ getUsers: vi.fn(), getBindCodes: vi.fn(), patchScopeSettings: vi.fn(),}));vi.mock('@/context/ApiContext', async (loadOriginal) => ({...await loadOriginal<typeof import('@/context/ApiContext')>(), useApi: () => api,@@ -35,14 +35,17 @@ vi.mock('../shared/RoutingConfigPanel', () => ({}));const agentCatalog = { default_agent_name: 'vibey', agents: [{ name: 'vibey', backend: 'vibey' }, { name: 'reviewer', backend: 'vibey' }] };-const scope = (agent: string | null) => ({+const row = (agent: string | null) => ({display_name: 'Liu', is_admin: true, bound_at: '', enabled: true, show_message_types: ['assistant'], custom_cwd: null,- require_mention: null, require_bind: null, routing: { agent_name: agent }, expected_agent_name: agent,+ require_mention: null, require_bind: null, routing: { agent_name: agent, model: null }, expected_agent_name: agent,});-/** The server stores the posted rows and reports each row's binding as its new token. */-const stored = (rows: Record<string, { routing: { agent_name: string | null } }>) => Object.fromEntries(- Object.entries(rows).map(([id, row]) => [id, { ...row, expected_agent_name: row.routing.agent_name }]),-);+type Patch = { changes: { routing?: { agent_name?: string | null } }; expected_agent_name?: string | null };+/** The server applies the routing change to the scope's row and reports the stored row. */+const storedAfter = (request: Patch, before = row(null)) => {+ const agent = request.changes.routing?.agent_name ?? before.routing.agent_name;+ return { ok: true, settings: { ...before, ...row(agent) } };+};+const sent = (index: number) => api.patchScopeSettings.mock.calls[index][0];afterEach(cleanup);beforeEach(() => {@@ -50,9 +53,6 @@ beforeEach(() => {api.getBindCodes.mockResolvedValue({ ok: true, bind_codes: [] });});-const savedToken = (call: unknown[], kind: 'users' | 'channels', id: string) =>- (call[0] as Record<string, Record<string, { expected_agent_name: string | null }>>)[kind][id].expected_agent_name;-describe('users page', () => {beforeEach(() => {api.getConfig.mockResolvedValue({ platform: 'lark', platforms: { enabled: ['lark'] } });@@ -62,7 +62,7 @@ describe('users page', () => {/** Lark is the only enabled platform; the page reads others before its config loads. */function serveUsers(agent: string | null) {- api.getUsers.mockImplementation(async (platform) => ({ ok: true, users: platform === 'lark' ? { ou_1: scope(agent) } : {} }));+ api.getUsers.mockImplementation(async (platform) => ({ ok: true, users: platform === 'lark' ? { ou_1: row(agent) } : {} }));}const larkReads = () => api.getUsers.mock.calls.filter(([platform]) => platform === 'lark').length;@@ -72,35 +72,42 @@ describe('users page', () => {await userEvent.click(await screen.findByText('Liu'));}- it('sends the stored token after its own save changed the binding', async () => {- api.saveUsers.mockImplementation(async (payload) => ({ ok: true, users: stored(payload.users) }));+ it('sends only the changed routing, based on the Agent its own last save stored', async () => {+ api.patchScopeSettings.mockImplementation(async (request) => storedAfter(request));await openUser();await userEvent.click(screen.getByText('route:vibey'));- await waitFor(() => expect(api.saveUsers).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(api.patchScopeSettings).toHaveBeenCalledTimes(1));await userEvent.click(screen.getByText('route:reviewer'));- await waitFor(() => expect(api.saveUsers).toHaveBeenCalledTimes(2));- expect(savedToken(api.saveUsers.mock.calls[0], 'users', 'ou_1')).toBeNull();- expect(savedToken(api.saveUsers.mock.calls[1], 'users', 'ou_1')).toBe('vibey');+ await waitFor(() => expect(api.patchScopeSettings).toHaveBeenCalledTimes(2));++ expect(sent(0)).toEqual({+ platform: 'lark', scope: 'user', id: 'ou_1',+ changes: { routing: { agent_name: 'vibey' } }, expected_agent_name: null,+ });+ expect(sent(1)).toMatchObject({ changes: { routing: { agent_name: 'reviewer' } }, expected_agent_name: 'vibey' });});it('reloads the stored rows after a refused save', async () => {- api.saveUsers.mockRejectedValueOnce(new Error('settings_conflict'))- .mockImplementation(async (payload) => ({ ok: true, users: stored(payload.users) }));+ api.patchScopeSettings.mockRejectedValueOnce(new Error('settings_conflict'))+ .mockImplementation(async (request) => storedAfter(request, row('vibey')));await openUser();serveUsers('vibey');await userEvent.click(screen.getByText('route:reviewer'));await waitFor(() => expect(larkReads()).toBe(2));await userEvent.click(screen.getByText('route:reviewer'));- await waitFor(() => expect(api.saveUsers).toHaveBeenCalledTimes(2));- expect(savedToken(api.saveUsers.mock.calls[1], 'users', 'ou_1')).toBe('vibey');+ await waitFor(() => expect(api.patchScopeSettings).toHaveBeenCalledTimes(2));+ expect(sent(1)).toMatchObject({ changes: { routing: { agent_name: 'reviewer' } }, expected_agent_name: 'vibey' });});});describe('channels page', () => {beforeEach(() => {api.getConfig.mockResolvedValue({ platform: 'slack', platforms: { enabled: ['slack'] }, slack: { bot_token: 'xoxb-test' } });- api.getSettings.mockResolvedValue({ agent_catalog: agentCatalog, channels: { C1: { ...scope(null), enabled: true } } });- api.slackChannels.mockResolvedValue({ ok: true, channels: [{ id: 'C1', name: 'general' }] });+ api.getSettings.mockResolvedValue({+ agent_catalog: agentCatalog,+ channels: { C1: { ...row(null), enabled: true }, C2: { ...row(null), enabled: true, custom_cwd: '/c2' } },+ });+ api.slackChannels.mockResolvedValue({ ok: true, channels: [{ id: 'C1', name: 'general' }, { id: 'C2', name: 'random' }] });});async function openChannel() {@@ -108,27 +115,64 @@ describe('channels page', () => {await userEvent.click(await screen.findByText('general'));}- it('sends the stored token after its own save changed the binding', async () => {- api.saveSettings.mockImplementation(async (payload) => ({ channels: stored(payload.channels) }));+ it('sends only the edited channel and fields, based on the Agent its own last save stored', async () => {+ api.patchScopeSettings.mockImplementation(async (request) => storedAfter(request, { ...row(null), enabled: true }));await openChannel();await userEvent.click(screen.getByText('route:vibey'));- await waitFor(() => expect(api.saveSettings).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(api.patchScopeSettings).toHaveBeenCalledTimes(1));await userEvent.click(screen.getByText('route:reviewer'));- await waitFor(() => expect(api.saveSettings).toHaveBeenCalledTimes(2));- expect(savedToken(api.saveSettings.mock.calls[0], 'channels', 'C1')).toBeNull();- expect(savedToken(api.saveSettings.mock.calls[1], 'channels', 'C1')).toBe('vibey');+ await waitFor(() => expect(api.patchScopeSettings).toHaveBeenCalledTimes(2));++ expect(sent(0)).toEqual({+ platform: 'slack', scope: 'channel', id: 'C1',+ changes: { routing: { agent_name: 'vibey' } }, expected_agent_name: null,+ });+ expect(sent(1)).toMatchObject({ id: 'C1', changes: { routing: { agent_name: 'reviewer' } }, expected_agent_name: 'vibey' });});it('reloads the stored rows after a refused save', async () => {- api.saveSettings.mockRejectedValueOnce(new Error('settings_conflict'))- .mockImplementation(async (payload) => ({ channels: stored(payload.channels) }));+ api.patchScopeSettings.mockRejectedValueOnce(new Error('settings_conflict'))+ .mockImplementation(async (request) => storedAfter(request, { ...row('vibey'), enabled: true }));await openChannel();const reads = api.getSettings.mock.calls.length;- api.getSettings.mockResolvedValue({ agent_catalog: agentCatalog, channels: { C1: { ...scope('vibey'), enabled: true } } });+ api.getSettings.mockResolvedValue({ agent_catalog: agentCatalog, channels: { C1: { ...row('vibey'), enabled: true } } });await userEvent.click(screen.getByText('route:reviewer'));await waitFor(() => expect(api.getSettings.mock.calls.length).toBeGreaterThan(reads));await userEvent.click(screen.getByText('route:reviewer'));- await waitFor(() => expect(api.saveSettings).toHaveBeenCalledTimes(2));- expect(savedToken(api.saveSettings.mock.calls[1], 'channels', 'C1')).toBe('vibey');+ await waitFor(() => expect(api.patchScopeSettings).toHaveBeenCalledTimes(2));+ expect(sent(1)).toMatchObject({ changes: { routing: { agent_name: 'reviewer' } }, expected_agent_name: 'vibey' });+ });+});++describe('telegram topics', () => {+ beforeEach(() => {+ api.getConfig.mockResolvedValue({ platform: 'telegram', platforms: { enabled: ['telegram'] }, telegram: { bot_token: 'bot-test' } });+ api.getSettings.mockResolvedValue({+ agent_catalog: agentCatalog, channels: { '-1001': { ...row('vibey'), enabled: true } }, threads: {},+ });+ api.telegramChats.mockResolvedValue({+ ok: true, channels: [{ id: '-1001', name: 'forum', supports_topics: true, topics: [{ id: '7', name: 'Releases' }] }],+ });+ });++ it('creates an override from the stored channel, then edits only what changed', async () => {+ api.patchScopeSettings.mockImplementation(async (request) => storedAfter(request, { ...row('vibey'), enabled: true }));+ render(<MemoryRouter><ChannelList isPage /></MemoryRouter>);+ await userEvent.click(await screen.findByText('forum'));+ await userEvent.click(await screen.findByText('channelList.topicCustomize'));+ await waitFor(() => expect(api.patchScopeSettings).toHaveBeenCalledTimes(1));+ const topicEditor = await waitFor(() => {+ const buttons = screen.getAllByText('route:reviewer');+ expect(buttons).toHaveLength(2);+ return buttons[1];+ });+ await userEvent.click(topicEditor);+ await waitFor(() => expect(api.patchScopeSettings).toHaveBeenCalledTimes(2));++ expect(sent(0)).toEqual({ platform: 'telegram', scope: 'thread', id: '-1001', thread_id: '7', changes: {} });+ expect(sent(1)).toEqual({+ platform: 'telegram', scope: 'thread', id: '-1001', thread_id: '7',+ changes: { routing: { agent_name: 'reviewer' } }, expected_agent_name: 'vibey',+ });});});diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 15c15f3a8..1b911dcd7 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -8,6 +8,7 @@ import { isAuthorizationSensitiveReadPath } from '../lib/authorizationCache';import type { TurnActivityGroupWire } from '../lib/agentActivity';import type { AgentGraphParams, AgentGraphResult, AgentGraphVisibility } from '../lib/agentGraph';import { onPageReactivated, type PageReactivationListener } from '../lib/pageActivity';+import type { ScopeKind, ScopeSettingsChange } from '../lib/scopeSettingsPatch';import type { ShowPagePayload } from '../lib/showPageLinks';import { visibilityActivityEvents } from '../lib/sessionVisibilityEvents';import { normalizeSessionInfo, type InstanceCapabilities, type SessionInfo } from '../lib/sessionInfo';@@ -53,6 +54,20 @@ export type { ConfigMutation };// The workbench Dock API response shape ({ ok, dock }); the Dock document type// itself lives with the DockProvider that owns reconciliation.export type DockResponse = { ok: boolean; dock: DockDoc };+export type ScopeSettingsPatchRequest = ScopeSettingsChange & {+ platform: string;+ scope: ScopeKind;+ id: string;+ thread_id?: string;+};+export type ScopeSettingsPatchResult = {+ ok: boolean;+ scope: ScopeKind;+ id: string;+ thread_id?: string;+ /** The scope's stored row, in the shape the settings reads return it. */+ settings: unknown;+};// Global workbench toggles persisted server-side in state_meta. Currently just// the background-work banner switch (spec req 2); read by ChatPage (to gate the@@ -549,6 +564,7 @@ export type ApiContextType = {getSettings: (platform?: string) => Promise<any>;saveSettings: (payload: any, platform?: string) => Promise<any>;saveThreadSettings: (platform: string, channelId: string, threadId: string, settings: any) => Promise<any>;+ patchScopeSettings: (request: ScopeSettingsPatchRequest) => Promise<ScopeSettingsPatchResult>;deleteThreadSettings: (platform: string, channelId: string, threadId: string) => Promise<any>;getUsers: (platform?: string) => Promise<any>;saveUsers: (payload: any, platform?: string) => Promise<any>;@@ -3507,6 +3523,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenthread_id: threadId,settings,}),+ patchScopeSettings: (request) => patchJson('/api/settings/scope', request),deleteThreadSettings: (platform, channelId, threadId) => deleteJson(`/api/settings/thread?platform=${encodeURIComponent(platform)}&channel_id=${encodeURIComponent(channelId)}&thread_id=${encodeURIComponent(threadId)}`,),diff --git a/ui/src/lib/scopeSettingsPatch.ts b/ui/src/lib/scopeSettingsPatch.tsnew file mode 100644index 000000000..4d38339bb--- /dev/null+++ b/ui/src/lib/scopeSettingsPatch.ts@@ -0,0 +1,52 @@+// One settings edit on a channel, Telegram topic, or bound DM user, as the+// PATCH /api/settings/scope contract takes it: only the fields the edit+// changed, so a page holding an older copy of a scope never writes back what+// it did not touch.++export type ScopeKind = 'channel' | 'thread' | 'user';++export const CHANNEL_SCOPE_FIELDS = [+ 'enabled',+ 'show_message_types',+ 'custom_cwd',+ 'require_mention',+ 'require_bind',+] as const;++export const USER_SCOPE_FIELDS = ['display_name', 'enabled', 'show_message_types', 'custom_cwd'] as const;++type Routing = Record<string, string | null | undefined>;++export interface ScopeSettingsChange {+ changes: Record<string, unknown>;+ /** The Agent the edited view's routing was based on; sent with any routing change. */+ expected_agent_name?: string | null;+}++const same = (left: unknown, right: unknown) => JSON.stringify(left ?? null) === JSON.stringify(right ?? null);++/** The fields `next` changes on `base`, or null when it changes nothing. */+export function scopeSettingsChange<Row extends { routing?: object | null }>(+ base: Row,+ next: Row,+ fields: readonly string[],+): ScopeSettingsChange | null {+ const changes: Record<string, unknown> = {};+ const baseFields = base as Record<string, unknown>;+ const nextFields = next as Record<string, unknown>;+ for (const field of fields) {+ if (!same(baseFields[field], nextFields[field])) changes[field] = nextFields[field] ?? null;+ }+ const before = (base.routing || {}) as Routing;+ const after = (next.routing || {}) as Routing;+ const routing: Record<string, string | null> = {};+ for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {+ if (!same(before[key], after[key])) routing[key] = after[key] ?? null;+ }+ const result: ScopeSettingsChange = { changes };+ if (Object.keys(routing).length) {+ changes.routing = routing;+ result.expected_agent_name = before.agent_name ?? null;+ }+ return Object.keys(changes).length ? result : null;+}diff --git a/vibe/api.py b/vibe/api.pyindex 7fb7fcf77..939874ce6 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -1,6 +1,8 @@import asyncioimport base64import contextlib+import copy+import dataclassesimport hashlibimport jsonimport logging@@ -5876,6 +5878,190 @@ def save_thread_settings(payload: dict, *, user_context: Any = None) -> dict:}+class ScopeSettingsRequestError(ValueError):+ """A scope settings change the API cannot apply as asked."""++ def __init__(self, code: str, message: str, *, status: int = 400) -> None:+ super().__init__(message)+ self.code = code+ self.message = message+ self.status = status+++_CHANNEL_PATCH_FIELDS = frozenset(+ {"enabled", "show_message_types", "custom_cwd", "require_mention", "require_bind", "routing"}+)+_SCOPE_PATCH_FIELDS = {+ "channel": _CHANNEL_PATCH_FIELDS,+ "thread": _CHANNEL_PATCH_FIELDS,+ "user": frozenset({"display_name", "enabled", "show_message_types", "custom_cwd", "routing"}),+}+_ROUTING_PATCH_FIELDS = frozenset(field.name for field in dataclasses.fields(RoutingSettings))+_MISSING = object()+++def _scope_patch_value_error(name: str, value: Any) -> Optional[str]:+ if name == "enabled":+ return None if isinstance(value, bool) else "must be a boolean"+ if name in {"require_mention", "require_bind"}:+ return None if value is None or isinstance(value, bool) else "must be a boolean or null"+ if name == "custom_cwd":+ return None if value is None or isinstance(value, str) else "must be a string or null"+ if name == "display_name":+ return None if isinstance(value, str) else "must be a string"+ if name == "show_message_types":+ valid = isinstance(value, list) and all(isinstance(item, str) for item in value)+ return None if valid else "must be a list of strings"+ if name == "routing":+ if not isinstance(value, dict):+ return "must be an object"+ unknown = sorted(set(value) - _ROUTING_PATCH_FIELDS)+ if unknown:+ return f"has unknown fields: {', '.join(unknown)}"+ if any(item is not None and not isinstance(item, str) for item in value.values()):+ return "values must be strings or null"+ return None+++def _stored_agent_name(settings: ChannelSettings | UserSettings) -> Optional[str]:+ stored = settings._agent_name_at_load+ return settings.routing.agent_name if stored is _UNSET_AGENT_BINDING else stored+++def patch_scope_settings(payload: dict, *, user_context: Any = None) -> dict:+ """Change only the named fields of one channel, Telegram topic, or bound DM user.++ Fields a request does not name are never written, so a page holding an old+ copy of a scope cannot revert or delete what another writer changed since.+ A routing change names the Agent its caller's view of the scope was based on+ (``expected_agent_name``). When the stored Agent differs, the chosen model or+ effort may belong to another Agent, so the change is refused unless it sets+ the stored Agent itself.+ """+ from vibe.authorization import require_instance_role+ from storage.settings_service import StaleScopeAgentBindingError, make_scope_id+ from config.v2_settings import _make_scoped_key, make_thread_native_id, normalize_routing_settings++ require_instance_role(user_context, "member")+ platform = str(payload.get("platform") or _current_platform())+ kind = payload.get("scope")+ native_id = str(payload.get("id") or "").strip()+ thread_id = str(payload.get("thread_id") or "").strip()+ changes = payload.get("changes")+ if kind not in _SCOPE_PATCH_FIELDS:+ raise ScopeSettingsRequestError("invalid_scope", "scope must be channel, thread, or user")+ if not native_id or (kind == "thread" and not thread_id):+ raise ScopeSettingsRequestError("invalid_scope", "id (and thread_id for a thread) is required")+ if kind == "thread" and platform != "telegram":+ raise ScopeSettingsRequestError("invalid_scope", "thread settings currently support Telegram only")+ if not isinstance(changes, dict):+ raise ScopeSettingsRequestError("invalid_changes", "changes must be an object")+ unknown = sorted(set(changes) - _SCOPE_PATCH_FIELDS[kind])+ if unknown:+ raise ScopeSettingsRequestError("invalid_changes", f"unknown {kind} fields: {', '.join(unknown)}")+ for name, value in changes.items():+ problem = _scope_patch_value_error(name, value)+ if problem:+ raise ScopeSettingsRequestError("invalid_changes", f"{name} {problem}")+ routing_patch = changes.get("routing")+ expected_agent_name = payload.get("expected_agent_name", _MISSING)+ if routing_patch is not None and (+ expected_agent_name is _MISSING+ or (expected_agent_name is not None and not isinstance(expected_agent_name, str))+ ):+ raise ScopeSettingsRequestError(+ "invalid_changes", "a routing change requires expected_agent_name (a string or null)"+ )++ if kind == "user":+ key = _make_scoped_key(platform, native_id)+ scope_id = make_scope_id(platform, "user", native_id)+ elif kind == "channel":+ key = _make_scoped_key(platform, native_id)+ scope_id = make_scope_id(platform, "channel", native_id)+ else:+ key = _make_scoped_key(platform, make_thread_native_id(native_id, thread_id))+ scope_id = make_scope_id(platform, "thread", make_thread_native_id(native_id, thread_id))+ parent_key = _make_scoped_key(platform, native_id)++ def rows(state):+ return {"user": state.users, "channel": state.channels, "thread": state.threads}[kind]++ def source_of(state):+ """The scope's stored settings, or what a new row starts from."""+ existing = rows(state).get(key)+ if existing is not None:+ return existing+ if kind == "user":+ raise ScopeSettingsRequestError("user_not_found", "User not found", status=404)+ if kind == "thread":+ parent = state.channels.get(parent_key)+ if parent is not None:+ return parent+ return ChannelSettings()++ # A new topic override keeps the mention gate it showed while inheriting.+ new_topic_require_mention = None+ if kind == "thread":+ platform_config = _stored_platform_config(platform)+ new_topic_require_mention = bool(getattr(platform_config, "require_mention", True))+ # The routing a change stores is resolved before the write lock: normalizing+ # an effort reads Agent and model catalogs, which must not hold writers up.+ routing_changes: Optional[dict] = None+ with contextlib.closing(SettingsStore()) as store:+ if routing_patch is not None:+ stored_routing = routing_to_compat_dict(source_of(store.settings).routing)+ normalized = _normalize_backend_routing_payload({**stored_routing, **routing_patch})+ routing_changes = {+ name: value+ for name, value in normalized.items()+ if name in routing_patch or value != stored_routing.get(name)+ }++ def mutate(state) -> None:+ existing = rows(state).get(key)+ source = source_of(state)+ if routing_changes is not None and expected_agent_name != _stored_agent_name(source):+ if routing_patch.get("agent_name", _MISSING) != _stored_agent_name(source):+ raise StaleScopeAgentBindingError(scope_id=scope_id)+ if existing is not None:+ updated = existing+ else:+ updated = ChannelSettings(+ enabled=source.enabled,+ show_message_types=list(source.show_message_types),+ custom_cwd=source.custom_cwd,+ routing=copy.deepcopy(source.routing),+ require_mention=source.require_mention,+ require_bind=source.require_bind,+ # A new row's Agent is a new binding: the save validates it.+ _agent_name_at_load=None,+ )+ for name, value in changes.items():+ if name == "routing":+ continue+ if name == "show_message_types":+ value = _normalize_show_message_types_for_platform(value, platform)+ setattr(updated, name, value)+ if routing_changes:+ merged = {**_routing_to_dict(updated.routing), **routing_changes}+ updated.routing = normalize_routing_settings(RoutingSettings(**merged))+ if kind == "thread" and existing is None and updated.require_mention is None:+ updated.require_mention = new_topic_require_mention+ rows(state)[key] = updated++ store.apply(mutate, user_context=user_context)+ saved = rows(store.settings).get(key)+ if kind == "user":+ settings_payload = _user_settings_payload(saved, platform)+ else:+ settings_payload = _scope_settings_payload(saved, platform)+ result = {"ok": True, "scope": kind, "id": native_id, "settings": settings_payload}+ if kind == "thread":+ result["thread_id"] = thread_id+ return result++def delete_thread_settings(platform: str, channel_id: str, thread_id: str, *, user_context: Any = None) -> dict:"""Remove one child-thread override so it inherits its parent channel again."""from vibe.authorization import require_instance_role@@ -6762,6 +6948,19 @@ def _scope_settings_payload(settings: ChannelSettings, platform: str) -> dict:}+def _user_settings_payload(settings: UserSettings, platform: str) -> dict:+ return {+ "display_name": settings.display_name,+ "is_admin": settings.is_admin,+ "bound_at": settings.bound_at,+ "enabled": settings.enabled,+ "show_message_types": _normalize_show_message_types_for_platform(settings.show_message_types, platform),+ "custom_cwd": settings.custom_cwd,+ "routing": routing_to_compat_dict(settings.routing),+ "expected_agent_name": _agent_binding_expectation(settings),+ }++def _agent_binding_expectation(settings: ChannelSettings | UserSettings) -> Optional[str]:expected_agent_name = settings._agent_name_at_loadif expected_agent_name is _UNSET_AGENT_BINDING:@@ -6797,16 +6996,7 @@ def _settings_to_payload(store: SettingsStore, platform: str) -> dict:guild_id for guild_id, settings in payload["guilds"].items() if settings.get("enabled")]for user_id, u in store.get_users_for_platform(platform).items():- payload["users"][user_id] = {- "display_name": u.display_name,- "is_admin": u.is_admin,- "bound_at": u.bound_at,- "enabled": u.enabled,- "show_message_types": _normalize_show_message_types_for_platform(u.show_message_types, platform),- "custom_cwd": u.custom_cwd,- "routing": routing_to_compat_dict(u.routing),- "expected_agent_name": _agent_binding_expectation(u),- }+ payload["users"][user_id] = _user_settings_payload(u, platform)for bc in store.settings.bind_codes:payload["bind_codes"].append({@@ -14494,16 +14684,7 @@ def get_users(platform: Optional[str] = None) -> dict:platform = platform or _current_platform()users = {}for user_id, u in store.get_users_for_platform(platform).items():- users[user_id] = {- "display_name": u.display_name,- "is_admin": u.is_admin,- "bound_at": u.bound_at,- "enabled": u.enabled,- "show_message_types": _normalize_show_message_types_for_platform(u.show_message_types, platform),- "custom_cwd": u.custom_cwd,- "routing": routing_to_compat_dict(u.routing),- "expected_agent_name": _agent_binding_expectation(u),- }+ users[user_id] = _user_settings_payload(u, platform)return {"ok": True, "users": users}diff --git a/vibe/authorization.py b/vibe/authorization.pyindex 6a7ebe1ab..3283a7d26 100644--- a/vibe/authorization.py+++ b/vibe/authorization.py@@ -582,6 +582,7 @@ _MEMBER_HTTP_RULES = tuple(("POST", r"^/api/settings$"),("POST", r"^/api/settings/thread$"),("DELETE", r"^/api/settings/thread$"),+ ("PATCH", r"^/api/settings/scope$"),("POST", r"^/api/slack/auth_test$"),("POST", r"^/api/slack/channels$"),("POST", r"^/api/discord/auth_test$"),diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 68197ba1c..fb711370d 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -8092,6 +8092,31 @@ async def thread_settings_post(starlette_request: FastAPIRequest):return await _dispatch_native_ui_request(starlette_request, handler)[email protected]("/api/settings/scope", include_in_schema=False)+async def scope_settings_patch(starlette_request: FastAPIRequest):+ async def handler():+ from vibe import api+ from storage.settings_service import ScopeAgentUnavailableError, StaleScopeAgentBindingError++ body = await starlette_request.body()+ payload = await starlette_request.json() if body else {}+ user_context = _request_authorization_context()+ try:+ return await asyncio.to_thread(+ api.patch_scope_settings,+ payload if isinstance(payload, dict) else {},+ user_context=user_context,+ )+ except api.ScopeSettingsRequestError as exc:+ return _coded_error_response(exc.code, exc.message, exc.status)+ except StaleScopeAgentBindingError as exc:+ return _settings_conflict_response(exc)+ except ScopeAgentUnavailableError as exc:+ return _scope_agent_unavailable_response(exc)++ return await _dispatch_native_ui_request(starlette_request, handler)++@app.delete("/api/settings/thread", include_in_schema=False)async def thread_settings_delete(starlette_request: FastAPIRequest):async def handler():