Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

refactor(settings): route IM settings writes through the single-scope service (#3049)

Call Whitec9d36b3171c4
diff --git a/config/v2_settings.py b/config/v2_settings.py
index 7a5ac6efb..3984a0ee5 100644
--- a/config/v2_settings.py
+++ b/config/v2_settings.py
@@ -885,6 +885,26 @@ class SettingsStore:
self.settings.users[key] = settings
self.save()
+ def update_user_fields(self, user_id: str, *, platform: Optional[str] = None, **values) -> bool:
+ """Set only these fields of a bound user; False when the user is not bound.
+
+ Runtime bookkeeping (a DM channel id, a one-shot hint) must not write
+ back a cached copy of the rest of the row, such as a revoked admin flag.
+ """
+ key = self._user_key(user_id, platform)
+ found = []
+
+ def mutate(state: SettingsState) -> None:
+ user = state.users.get(key)
+ if user is None:
+ return
+ for name, value in values.items():
+ setattr(user, name, value)
+ found.append(True)
+
+ self.apply(mutate)
+ return bool(found)
+
@staticmethod
def _carry_agent_binding_expectation(previous: object, current: object) -> None:
current_expected = getattr(current, "_agent_name_at_load", _UNSET_AGENT_BINDING)
diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.py
index d0595af5c..caa1b7c2e 100644
--- a/core/handlers/command_handlers.py
+++ b/core/handlers/command_handlers.py
@@ -1,5 +1,6 @@
"""Command handlers for bot commands like /start, /new, /cwd, etc."""
+import asyncio
import logging
import os
import time
@@ -701,7 +702,7 @@ class CommandHandlers(BaseHandler):
# Save to user settings
settings_key = self._get_settings_key(context)
- settings_manager.set_custom_cwd(settings_key, absolute_path)
+ await asyncio.to_thread(settings_manager.set_custom_cwd, settings_key, absolute_path)
logger.info(f"User {context.user_id} changed cwd to: {absolute_path}")
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index a2ab80512..aceab4c20 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -2047,7 +2047,7 @@ class SessionHandler(BaseHandler):
claude_agent=current_routing.claude_agent if current_routing else None,
codex_agent=current_routing.codex_agent if current_routing else None,
)
- settings_manager.set_channel_routing(settings_key, routing)
+ await asyncio.to_thread(settings_manager.set_channel_routing, settings_key, routing)
agent_label = agent.capitalize()
preview = self._get_resume_preview(context, agent=agent, session_id=session_id)
diff --git a/core/handlers/settings_handler.py b/core/handlers/settings_handler.py
index b9ad35b35..06c69b262 100644
--- a/core/handlers/settings_handler.py
+++ b/core/handlers/settings_handler.py
@@ -24,7 +24,6 @@ from core.modals import (
RoutingModalData,
RoutingModalSelection,
)
-from vibe import backend_model_catalog
from .base import BaseHandler
@@ -316,7 +315,7 @@ class SettingsHandler(BaseHandler):
message_types = settings_manager.get_available_message_types()
if msg_type not in message_types:
return
- is_shown = settings_manager.toggle_show_message_type(settings_key, msg_type)
+ is_shown = await asyncio.to_thread(settings_manager.toggle_show_message_type, settings_key, msg_type)
# Update the keyboard
user_settings = settings_manager.get_user_settings(settings_key)
@@ -756,12 +755,12 @@ class SettingsHandler(BaseHandler):
im_client = self._get_im_client(context)
settings_manager = self._get_settings_manager(context)
+ # One write: a DM has no mention gate, and a topic's first override
+ # materializes the gate it inherited.
+ changes = {"show_message_types": show_message_types}
if not is_dm:
- settings_manager.set_require_mention(settings_key, require_mention)
-
- user_settings = settings_manager.get_user_settings(settings_key)
- user_settings.show_message_types = show_message_types
- settings_manager.update_user_settings(settings_key, user_settings)
+ changes["require_mention"] = require_mention
+ await asyncio.to_thread(settings_manager.change_scope_settings, settings_key, changes)
language_saved = True
if language is not None and language != self.config.language:
@@ -868,7 +867,6 @@ class SettingsHandler(BaseHandler):
agents always stay, so switching back finds them.
"""
from config.v2_settings import RoutingSettings
- from modules.agents.opencode.utils import normalize_claude_reasoning_effort
try:
context = MessageContext(
@@ -902,32 +900,28 @@ class SettingsHandler(BaseHandler):
}
if backend in variants and variant is not _UNSET:
variants[backend] = variant
- if backend == "claude":
- # Claude Code rejects an effort its model does not support.
- effective_model = model or agent.model
- reasoning_effort = normalize_claude_reasoning_effort(
- effective_model,
- reasoning_effort,
- backend_model_catalog.catalog_reasoning_efforts_for_model("claude", effective_model),
- )
- routing = RoutingSettings(
- agent_name=agent.name,
- model=model,
- reasoning_effort=reasoning_effort,
- **{f"{native}_agent": value for native, value in variants.items()},
+ # The settings write stores the route as the Web would: an effort
+ # the model cannot take is dropped there, for every surface.
+ routing = await asyncio.to_thread(
+ settings_manager.set_channel_routing,
+ settings_key,
+ RoutingSettings(
+ agent_name=agent.name,
+ model=model,
+ reasoning_effort=reasoning_effort,
+ **{f"{native}_agent": value for native, value in variants.items()},
+ ),
)
-
- settings_manager.set_channel_routing(settings_key, routing)
needs_new_session_hint = self._routing_update_needs_new_session_hint(context, routing)
backend_name = display_name_for_backend(backend)
parts = []
for label, value in (
(self._t("routing.label.agent"), f"{agent.name} · {backend_name}"),
- (self._t("modal.routing.backendAgent", backend=backend_name), variants.get(backend)),
- (self._t("routing.label.model"), model),
- (self._t("routing.label.reasoningEffort"), reasoning_effort),
+ (self._t("modal.routing.backendAgent", backend=backend_name), getattr(routing, f"{backend}_agent", None)),
+ (self._t("routing.label.model"), routing.model),
+ (self._t("routing.label.reasoningEffort"), routing.reasoning_effort),
):
if value:
# Route values are opaque and unbounded; a confirmation must fit any platform's message.
@@ -944,8 +938,9 @@ class SettingsHandler(BaseHandler):
)
logger.info(
- f"Routing updated for {settings_key}: agent={agent.name}, variant={variants.get(backend)}, "
- f"model={model}, reasoning_effort={reasoning_effort}"
+ f"Routing updated for {settings_key}: agent={routing.agent_name}, "
+ f"variant={getattr(routing, f'{backend}_agent', None)}, "
+ f"model={routing.model}, reasoning_effort={routing.reasoning_effort}"
)
except Exception as e:
diff --git a/core/services/scope_settings.py b/core/services/scope_settings.py
new file mode 100644
index 000000000..28925d521
--- /dev/null
+++ b/core/services/scope_settings.py
@@ -0,0 +1,228 @@
+"""One settings change to one channel, Telegram topic, or bound DM user.
+
+Every surface that edits a scope writes through ``apply_scope_change``: the Web
+settings pages (``PATCH /api/settings/scope``) and the IM settings handlers
+(through ``SettingsManager``). It writes only the fields a change names, on the
+rows read under the settings write lock, and stores a route through the one
+``normalize_scope_routing``, so the same choice is stored the same way whichever
+surface made it. See ``docs/plans/scope-settings-patch.md``.
+"""
+
+from __future__ import annotations
+
+import copy
+import logging
+from dataclasses import fields
+from typing import Any, Optional
+
+from config.platform_registry import get_platform_descriptor
+from config.v2_settings import (
+ ChannelSettings,
+ RoutingSettings,
+ SettingsState,
+ SettingsStore,
+ UserSettings,
+ _UNSET_AGENT_BINDING,
+ _make_scoped_key,
+ _parse_routing,
+ _routing_to_dict,
+ make_thread_native_id,
+ normalize_routing_settings,
+ normalize_show_message_types,
+ routing_to_compat_dict,
+)
+
+logger = logging.getLogger(__name__)
+
+SCOPE_KINDS = ("channel", "thread", "user")
+CHANNEL_FIELDS = frozenset({"enabled", "show_message_types", "custom_cwd", "require_mention", "require_bind", "routing"})
+SCOPE_FIELDS = {
+ "channel": CHANNEL_FIELDS,
+ "thread": CHANNEL_FIELDS,
+ "user": frozenset({"display_name", "enabled", "show_message_types", "custom_cwd", "routing"}),
+}
+ROUTING_FIELDS = frozenset(field.name for field in fields(RoutingSettings))
+MISSING: Any = object()
+
+
+class ScopeNotFoundError(LookupError):
+ """A change names a DM user that is not bound."""
+
+ def __init__(self, scope_id: str) -> None:
+ super().__init__(scope_id)
+ self.scope_id = scope_id
+
+
+def normalize_scope_message_types(show_message_types: Optional[list], platform: str) -> list[str]:
+ """The message types a scope on ``platform`` can show."""
+ normalized = normalize_show_message_types(show_message_types)
+ if not get_platform_descriptor(platform).capabilities.supports_toolcall_delivery:
+ return [msg_type for msg_type in normalized if msg_type != "toolcall"]
+ return normalized
+
+
+def _route_agent_backend_and_model(agent_name: Optional[str]) -> tuple[Optional[str], Optional[str]]:
+ from core.vibe_agents import VibeAgentStore
+ from modules.agents.catalog import is_agent_backend
+
+ name = str(agent_name or "").strip()
+ if not name:
+ return None, None
+ store = VibeAgentStore()
+ try:
+ agent = store.get(name)
+ if agent is not None:
+ return agent.backend, agent.model
+ except Exception:
+ logger.debug("Failed to resolve Agent backend while normalizing routing payload", exc_info=True)
+ finally:
+ store.close()
+ return (name, None) if is_agent_backend(name) else (None, None)
+
+
+def normalize_scope_routing(routing_payload: dict) -> dict:
+ """The route a scope stores for ``routing_payload``.
+
+ Claude Code rejects an effort its model does not support, so a Claude
+ route keeps an effort only when that model offers it: from the Model Hub
+ catalog when Claude runs through the Hub, else from the native catalog.
+ """
+ from config.v2_config import is_model_hub_enabled
+ from core.handlers.model_hub.service import V2ModelHubConfigStore
+ from modules.agents.opencode.utils import normalize_claude_reasoning_effort
+ from vibe import backend_model_catalog
+
+ routing = _parse_routing(routing_payload or {})
+ backend, agent_model = _route_agent_backend_and_model(routing.agent_name)
+ if backend == "claude" and routing.reasoning_effort:
+ model = routing.model or agent_model
+ catalog_efforts = None
+ agent_catalog = V2ModelHubConfigStore().load().agents["claude"] if is_model_hub_enabled() else None
+ if agent_catalog is not None and agent_catalog.mode == "hub":
+ row = next((row for row in agent_catalog.models if row.id == model), None)
+ if row is not None:
+ # Match the picker: a present empty list (or non-reasoning
+ # model) is authoritative, not a request for backend tiers.
+ catalog_efforts = [] if row.supports_reasoning is False else row.reasoning_efforts
+ # Unknown Hub rows retain the existing generic normalization;
+ # a same-named native model must not grant them Off support.
+ else:
+ catalog_efforts = backend_model_catalog.catalog_reasoning_efforts_for_model("claude", model)
+ routing.reasoning_effort = normalize_claude_reasoning_effort(
+ model,
+ routing.reasoning_effort,
+ catalog_efforts,
+ )
+ return _routing_to_dict(routing)
+
+
+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 apply_scope_change(
+ store: SettingsStore,
+ *,
+ platform: str,
+ kind: str,
+ native_id: str,
+ thread_id: str = "",
+ changes: dict,
+ expected_agent_name: Any = MISSING,
+ new_topic_require_mention: Optional[bool] = None,
+ user_context: Any = None,
+) -> ChannelSettings | UserSettings:
+ """Write ``changes`` to one scope and return its stored row.
+
+ Only the named fields are written, so a caller holding an old copy of the
+ scope cannot revert what another writer changed since. ``routing`` merges
+ key by key into the stored route. A routing change names the Agent the
+ caller's view of the route was based on (``expected_agent_name``): when the
+ stored Agent differs, a model or effort chosen for the old Agent must not
+ land, so the change is refused unless it sets the stored Agent itself.
+
+ A channel or topic without a row is created; a topic starts from its parent
+ channel and keeps the mention gate it inherited, the parent's or else
+ ``new_topic_require_mention``. A DM user must already be bound.
+ """
+ from storage.settings_service import StaleScopeAgentBindingError, make_scope_id
+
+ if kind not in SCOPE_KINDS:
+ raise ValueError(f"unknown scope kind: {kind}")
+ unknown = sorted(set(changes) - SCOPE_FIELDS[kind])
+ if unknown:
+ raise ValueError(f"unknown {kind} fields: {', '.join(unknown)}")
+ routing_patch = changes.get("routing")
+ if routing_patch is not None and expected_agent_name is MISSING:
+ raise ValueError("a routing change names the Agent it was based on")
+ stored_native_id = make_thread_native_id(native_id, thread_id) if kind == "thread" else native_id
+ key = _make_scoped_key(platform, stored_native_id)
+ scope_id = make_scope_id(platform, kind, stored_native_id)
+ parent_key = _make_scoped_key(platform, native_id)
+
+ def rows(state: SettingsState) -> dict:
+ return {"user": state.users, "channel": state.channels, "thread": state.threads}[kind]
+
+ def source_of(state: SettingsState) -> ChannelSettings | UserSettings:
+ """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 ScopeNotFoundError(scope_id)
+ if kind == "thread":
+ parent = state.channels.get(parent_key)
+ if parent is not None:
+ return parent
+ return ChannelSettings()
+
+ # The route is resolved before the write lock: normalizing an effort reads
+ # Agent and model catalogs, which must not hold other writers up.
+ routing_changes: Optional[dict] = None
+ if routing_patch is not None:
+ stored_routing = routing_to_compat_dict(source_of(store.settings).routing)
+ normalized = normalize_scope_routing({**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: SettingsState) -> None:
+ existing = rows(state).get(key)
+ source = source_of(state)
+ stored_agent = _stored_agent_name(source)
+ if routing_changes is not None and expected_agent_name != stored_agent:
+ if routing_patch.get("agent_name", MISSING) != stored_agent:
+ 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_scope_message_types(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:
+ # An inheriting topic's first override keeps the gate it showed.
+ inherited = source.require_mention
+ updated.require_mention = inherited if inherited is not None else new_topic_require_mention
+ rows(state)[key] = updated
+
+ store.apply(mutate, user_context=user_context)
+ return rows(store.settings)[key]
diff --git a/docs/plans/scope-settings-patch.md b/docs/plans/scope-settings-patch.md
index 0a9e3b12b..70b7b1925 100644
--- a/docs/plans/scope-settings-patch.md
+++ b/docs/plans/scope-settings-patch.md
@@ -61,15 +61,39 @@ 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.
+## One write path
+
+`core.services.scope_settings.apply_scope_change` owns the change; the Web
+PATCH route validates the request and calls it, and every IM settings write
+reaches it through `SettingsManager.change_scope_settings`:
+
+| IM surface | Change |
+| --- | --- |
+| routing form (all platforms), resume | `routing`, as the form's complete route |
+| settings form | `show_message_types`, plus `require_mention` outside DMs, in one write |
+| message-type toggle | `show_message_types` |
+| set working directory | `custom_cwd` |
+
+- Routes go through one `normalize_scope_routing`, so a Claude effort is kept
+ or dropped by the Model Hub catalog when Claude runs through the Hub, whichever
+ surface saved it. IM previously checked only the native catalog.
+- An IM routing form submits a complete route; its `expected_agent_name` is the
+ Agent the scope runs when the form is saved, so only a concurrent change in
+ that window conflicts.
+- A topic's first override keeps the mention gate it showed while inheriting:
+ the parent channel's explicit gate, else the platform default.
+- A refused save raises to the IM handler, which reports it with the same
+ localized conflict or unavailable-Agent text as the Web pages; the runtime
+ view is rebuilt from the committed rows.
+- IM handlers run these writes on a worker thread, not the controller loop.
+- Runtime bookkeeping on bound users (Slack DM channel id, WeChat bind hint)
+ uses `SettingsStore.update_user_fields`, which sets only those fields under
+ the write lock instead of writing back a cached copy of the user.
## 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.
+- Removing the legacy per-backend `<backend>_model` / `<backend>_reasoning_effort`
+ routing fields from the API, the Web types, and the stored routing JSON. They
+ are read-only aliases today; removing them is a separate contract cleanup.
- Display fixes on the settings pages (effective model, inherited vs override,
new-session hint) and per-row save status.
diff --git a/modules/im/slack.py b/modules/im/slack.py
index c243caea1..5a7c94235 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -208,9 +208,7 @@ class SlackBot(BaseIMClient):
logger.debug("Failed to access settings store for Slack DM persistence", exc_info=True)
return
try:
- store.update_user(user_id, record, platform="slack")
- except TypeError:
- store.update_user(user_id, record)
+ store.update_user_fields(user_id, platform="slack", dm_chat_id=normalized_channel_id)
except Exception:
logger.debug("Failed to persist Slack dm_chat_id for %s", user_id, exc_info=True)
return
diff --git a/modules/im/wechat.py b/modules/im/wechat.py
index 3ece9dd06..9f4fb5824 100644
--- a/modules/im/wechat.py
+++ b/modules/im/wechat.py
@@ -1334,7 +1334,7 @@ class WeChatBot(BaseIMClient):
try:
store = store_getter()
user.pending_bind_menu_hint = False
- store.update_user(user_id, user, platform="wechat")
+ store.update_user_fields(user_id, platform="wechat", pending_bind_menu_hint=False)
manager_reload = getattr(manager, "_reload_if_changed", None)
if callable(manager_reload):
manager_reload()
diff --git a/modules/settings_manager.py b/modules/settings_manager.py
index 53b0106a7..fcd1478b8 100644
--- a/modules/settings_manager.py
+++ b/modules/settings_manager.py
@@ -10,6 +10,7 @@ from config.v2_sessions import SessionsStore
from config.v2_settings import SettingsStore, ChannelSettings, GuildSettings, RoutingSettings, SCOPED_KEY_SEP
from config.v2_settings import normalize_routing_settings, split_thread_settings_key
from config.v2_settings import UserSettings as BoundUserSettings
+from core.services import scope_settings
from modules.sessions_facade import SessionsFacade
@@ -187,25 +188,6 @@ class SettingsManager:
enabled=bound_user.enabled,
)
- def _to_channel_settings(self, settings: UserSettings) -> ChannelSettings:
- routing = _clone_routing(settings.channel_routing)
- return ChannelSettings(
- enabled=settings.enabled,
- show_message_types=self._normalize_show_message_types(settings.show_message_types),
- custom_cwd=settings.custom_cwd,
- routing=routing,
- )
-
- def _sync_to_bound_user(self, user_id: str, settings: UserSettings) -> None:
- """Sync runtime UserSettings back to the bound-user record in store.settings.users."""
- bound = self.store.get_user(user_id, platform=self.platform)
- if not bound:
- return
- bound.enabled = settings.enabled
- bound.show_message_types = self._normalize_show_message_types(settings.show_message_types)
- bound.custom_cwd = settings.custom_cwd
- bound.routing = _clone_routing(settings.channel_routing)
-
def _load_settings(self):
"""Load runtime settings from the shared settings store."""
self.store = SettingsStore.get_instance(self.settings_file)
@@ -282,41 +264,6 @@ class SettingsManager:
"dm_users": len(self.dm_user_settings),
}
- def _save_settings(self):
- """Save settings to JSON file.
-
- Writes channel-keyed entries from ``self.channel_settings`` back to
- ``store.settings.channels``, and syncs DM user entries from
- ``self.dm_user_settings`` back to ``store.settings.users``.
- """
- try:
- channels: Dict[str, ChannelSettings] = {}
- existing_platform_channels = self.store.get_channels_for_platform(self.platform)
- for cid, s in self.channel_settings.items():
- existing = existing_platform_channels.get(cid)
- cs = self._to_channel_settings(s)
- if existing is not None:
- cs.enabled = existing.enabled
- cs.require_mention = existing.require_mention
- cs.require_bind = existing.require_bind
- channels[cid] = cs
- self.store.set_channels_for_platform(self.platform, channels)
- for uid, s in self.dm_user_settings.items():
- self._sync_to_bound_user(uid, s)
- self.store.save()
- # Keep the local generation in sync so _reload_if_changed doesn't
- # trigger an unnecessary rebuild right after our own save.
- self._last_seen_store_generation = self.store.generation
- 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
- raise
-
def get_user_settings(self, user_id: Union[int, str]) -> UserSettings:
"""Get settings for a specific user/channel context.
@@ -360,59 +307,69 @@ class SettingsManager:
# when someone enables it explicitly.
return UserSettings()
- def update_user_settings(self, user_id: Union[int, str], settings: UserSettings):
- """Update settings for a specific user"""
- normalized_id = self._normalize_user_id(user_id)
+ def _scope_of(self, settings_key: str) -> tuple[str, str, str]:
+ """The stored scope a runtime settings key names: (kind, id, thread id)."""
+ thread_ref = split_thread_settings_key(settings_key)
+ if thread_ref is not None:
+ return "thread", thread_ref[0], thread_ref[1]
+ if settings_key in self.store.get_users_for_platform(self.platform):
+ return "user", settings_key, ""
+ return "channel", settings_key, ""
- settings.show_message_types = self._normalize_show_message_types(settings.show_message_types)
+ def change_scope_settings(
+ self,
+ user_id: Union[int, str],
+ changes: dict,
+ *,
+ expected_agent_name: Any = scope_settings.MISSING,
+ ):
+ """Write only ``changes`` to the scope this key names; return its stored row.
- thread_ref = split_thread_settings_key(normalized_id)
- if thread_ref is not None:
- channel_id, thread_id = thread_ref
- existing_thread = self.store.find_thread(channel_id, thread_id, platform=self.platform)
- existing = existing_thread
- if existing_thread is None:
- existing = self.store.find_channel(channel_id, platform=self.platform)
- updated = self._to_channel_settings(settings)
- if existing is not None:
- updated.require_mention = existing.require_mention
- updated.require_bind = existing.require_bind
- if existing_thread is None and updated.require_mention is None:
- updated.require_mention = bool(self.require_mention_default())
- self.store.update_thread(channel_id, thread_id, updated, platform=self.platform)
- self._last_seen_store_generation = self.store.generation
- return
+ The one IM write path, shared with the Web settings pages. A refused
+ save raises, and the runtime view then holds the committed rows.
+ """
+ normalized_id = self._normalize_user_id(user_id)
+ self._reload_if_changed()
+ kind, native_id, thread_id = self._scope_of(normalized_id)
+ # A DM has no mention or binding gate; those settings belong to channels.
+ changes = {name: value for name, value in changes.items() if name in scope_settings.SCOPE_FIELDS[kind]}
+ try:
+ return scope_settings.apply_scope_change(
+ self.store,
+ platform=self.platform,
+ kind=kind,
+ native_id=native_id,
+ thread_id=thread_id,
+ changes=changes,
+ expected_agent_name=expected_agent_name,
+ new_topic_require_mention=bool(self.require_mention_default()) if kind == "thread" else None,
+ )
+ except Exception as e:
+ logger.error(f"Error saving settings: {e}")
+ raise
+ finally:
+ self._reload_if_changed()
- if normalized_id in self.dm_user_settings:
- self.dm_user_settings[normalized_id] = settings
- elif normalized_id in self.channel_settings:
- self.channel_settings[normalized_id] = settings
- elif normalized_id in self.store.get_users_for_platform(self.platform):
- self.dm_user_settings[normalized_id] = settings
- else:
- self.channel_settings[normalized_id] = settings
- self._save_settings()
+ def set_show_message_types(self, user_id: Union[int, str], show_message_types: List[str]) -> None:
+ self.change_scope_settings(
+ user_id, {"show_message_types": self._normalize_show_message_types(show_message_types)}
+ )
def toggle_show_message_type(self, user_id: Union[int, str], message_type: str) -> bool:
"""Toggle a message type in show list, returns new state (True if now shown)"""
message_type = self._canonicalize_message_type(message_type)
- settings = self.get_user_settings(user_id)
-
- if message_type in settings.show_message_types:
- settings.show_message_types.remove(message_type)
- is_shown = False
+ shown = list(self.get_user_settings(user_id).show_message_types)
+ is_shown = message_type not in shown
+ if is_shown:
+ shown.append(message_type)
else:
- settings.show_message_types.append(message_type)
- is_shown = True
-
- self.update_user_settings(user_id, settings)
+ shown.remove(message_type)
+ self.set_show_message_types(user_id, shown)
return is_shown
def set_custom_cwd(self, user_id: Union[int, str], cwd: str):
"""Set custom working directory for user"""
- settings = self.get_user_settings(user_id)
- settings.custom_cwd = cwd
- self.update_user_settings(user_id, settings)
+ self.change_scope_settings(user_id, {"custom_cwd": cwd})
def get_custom_cwd(self, user_id: Union[int, str]) -> Optional[str]:
"""Get custom working directory for user"""
@@ -467,10 +424,6 @@ class SettingsManager:
settings = self.get_user_settings(user_id)
return message_type not in settings.show_message_types
- def save_user_settings(self, user_id: Union[int, str], settings: UserSettings):
- """Save settings for a specific user (alias for update_user_settings)"""
- self.update_user_settings(user_id, settings)
-
def get_available_message_types(self) -> List[str]:
"""Get list of available message types that can be hidden.
@@ -526,25 +479,26 @@ class SettingsManager:
settings = self.get_user_settings(settings_key)
return settings.channel_routing
- def set_channel_routing(self, settings_key: Union[int, str], routing: ChannelRouting):
- """Set channel routing override."""
- settings = self.get_user_settings(settings_key)
- settings.channel_routing = routing
- self.update_user_settings(settings_key, settings)
+ def set_channel_routing(self, settings_key: Union[int, str], routing: ChannelRouting) -> ChannelRouting:
+ """Store a complete route for this scope and return the stored route.
+
+ The route is the caller's whole choice, so it is based on the Agent the
+ scope runs now.
+ """
+ current = self.get_channel_routing(settings_key)
+ saved = self.change_scope_settings(
+ settings_key,
+ {"routing": asdict(normalize_routing_settings(routing))},
+ expected_agent_name=current.agent_name if current else None,
+ )
logger.info(
- f"Updated channel routing for {settings_key}: "
- f"agent={routing.agent_name}, "
- f"opencode_agent={routing.opencode_agent}, "
- f"opencode_model={routing.opencode_model}"
+ "Updated channel routing for %s: agent=%s, model=%s, reasoning_effort=%s",
+ settings_key,
+ saved.routing.agent_name,
+ saved.routing.model,
+ saved.routing.reasoning_effort,
)
-
- def clear_channel_routing(self, settings_key: Union[int, str]):
- """Clear channel routing override (fall back to the default Agent)."""
- settings = self.get_user_settings(settings_key)
- if settings.channel_routing:
- settings.channel_routing = None
- self.update_user_settings(settings_key, settings)
- logger.info(f"Cleared channel routing for {settings_key}")
+ return _clone_routing(saved.routing)
# ---------------------------------------------
# Per-channel require_mention management
@@ -583,31 +537,11 @@ class SettingsManager:
Args:
channel_id: The channel to configure
- value: True=require mention, False=don't require, None=use global default
+ value: True=require mention, False=don't require, None=use global default.
+ A topic's first override keeps the gate it inherited.
"""
- key = str(channel_id)
- thread_ref = split_thread_settings_key(key)
- if thread_ref is not None:
- parent_id, thread_id = thread_ref
- channel_settings = self.store.find_thread(parent_id, thread_id, platform=self.platform)
- if channel_settings is None:
- parent = self.store.find_channel(parent_id, platform=self.platform)
- channel_settings = ChannelSettings(**vars(parent)) if parent is not None else ChannelSettings()
- if value is None:
- value = (
- parent.require_mention
- if parent is not None and parent.require_mention is not None
- else bool(self.require_mention_default())
- )
- channel_settings.require_mention = value
- self.store.update_thread(parent_id, thread_id, channel_settings, platform=self.platform)
- self._last_seen_store_generation = self.store.generation
- logger.info("Updated require_mention for thread %s/%s: %s", parent_id, thread_id, value)
- return
- channel_settings = self.store.get_channel(key, platform=self.platform)
- channel_settings.require_mention = value
- self.store.update_channel(key, channel_settings, platform=self.platform)
- logger.info(f"Updated require_mention for channel {key}: {value}")
+ self.change_scope_settings(channel_id, {"require_mention": value})
+ logger.info("Updated require_mention for %s: %s", channel_id, value)
def get_require_mention_override(self, channel_id: Union[int, str]) -> Optional[bool]:
"""Get the raw per-channel require_mention override (may be None)."""
@@ -730,9 +664,13 @@ class MultiSettingsManager:
manager, raw = self._resolve(settings_key)
return manager.get_user_settings(raw)
- def update_user_settings(self, settings_key: Union[int, str], settings: UserSettings):
+ def change_scope_settings(self, settings_key: Union[int, str], changes: dict, **kwargs):
+ manager, raw = self._resolve(settings_key)
+ return manager.change_scope_settings(raw, changes, **kwargs)
+
+ def set_show_message_types(self, settings_key: Union[int, str], show_message_types: List[str]) -> None:
manager, raw = self._resolve(settings_key)
- return manager.update_user_settings(raw, settings)
+ return manager.set_show_message_types(raw, show_message_types)
def toggle_show_message_type(self, settings_key: Union[int, str], message_type: str) -> bool:
manager, raw = self._resolve(settings_key)
@@ -770,10 +708,6 @@ class MultiSettingsManager:
manager, raw = self._resolve(settings_key)
return manager.is_message_type_hidden(raw, message_type)
- def save_user_settings(self, settings_key: Union[int, str], settings: UserSettings):
- manager, raw = self._resolve(settings_key)
- return manager.save_user_settings(raw, settings)
-
def get_available_message_types(self) -> List[str]:
return self.managers[self.primary_platform].get_available_message_types()
@@ -791,10 +725,6 @@ class MultiSettingsManager:
manager, raw = self._resolve(settings_key)
return manager.set_channel_routing(raw, routing)
- def clear_channel_routing(self, settings_key: Union[int, str]):
- manager, raw = self._resolve(settings_key)
- return manager.clear_channel_routing(raw)
-
def get_require_mention(self, settings_key: Union[int, str], global_default: bool = False) -> bool:
manager, raw = self._resolve(settings_key)
return manager.get_require_mention(raw, global_default=global_default)
diff --git a/tests/test_settings_handler.py b/tests/test_settings_handler.py
index ec2c7e1a5..31f357e13 100644
--- a/tests/test_settings_handler.py
+++ b/tests/test_settings_handler.py
@@ -53,9 +53,10 @@ class _StubSettingsManager:
assert settings_key == "telegram::-100123"
return self.routing
- def set_channel_routing(self, settings_key: str, routing: RoutingSettings) -> None:
+ def set_channel_routing(self, settings_key: str, routing: RoutingSettings) -> RoutingSettings:
assert settings_key == "telegram::-100123"
self.saved_routing = routing
+ return routing
def _make_handler(settings_manager: _StubSettingsManager) -> tuple[SettingsHandler, AsyncMock]:
@@ -71,51 +72,54 @@ def _make_handler(settings_manager: _StubSettingsManager) -> tuple[SettingsHandl
return SettingsHandler(controller), send_message
-def test_settings_update_materializes_topic_mention_before_saving_other_fields() -> None:
- calls: list[str] = []
- user_settings = SimpleNamespace(show_message_types=[])
-
- class TopicSettingsManager:
- sessions = object()
-
- def set_require_mention(self, settings_key: str, value: bool | None) -> None:
- assert settings_key == "thread::-100123::1"
- assert value is None
- calls.append("mention")
-
- def get_user_settings(self, settings_key: str):
- assert settings_key == "thread::-100123::1"
- calls.append("read")
- return user_settings
-
- def update_user_settings(self, settings_key: str, settings) -> None:
- assert settings_key == "thread::-100123::1"
- assert settings.show_message_types == ["assistant"]
- calls.append("save")
-
- manager = TopicSettingsManager()
- controller = SimpleNamespace(
- config=SimpleNamespace(platform="telegram", language="en"),
- im_client=SimpleNamespace(send_message=AsyncMock()),
- settings_manager=manager,
- _get_settings_key=lambda _context: "thread::-100123::1",
- _get_lang=lambda: "en",
- )
- handler = SettingsHandler(controller)
+def test_settings_update_saves_a_topic_override_in_one_write(tmp_path, monkeypatch) -> None:
+ """A topic's first settings form saves its types and the mention gate it inherited, together."""
+ from config import paths
+ from config.v2_settings import ChannelSettings, SettingsStore, make_thread_settings_key
+ from modules.settings_manager import SettingsManager
- asyncio.run(
- handler.handle_settings_update(
- user_id="42",
- channel_id="-100123",
- thread_id="1",
- show_message_types=["assistant"],
- require_mention=None,
- notify_user=False,
+ monkeypatch.setattr(paths, "ensure_data_dirs", lambda: None)
+ SettingsStore.reset_instance()
+ manager = SettingsManager(settings_file=str(tmp_path / "settings.json"), platform="telegram")
+ manager.require_mention_default = lambda: False
+ try:
+ manager.store.update_channel(
+ "-100123",
+ ChannelSettings(enabled=True, show_message_types=["assistant", "toolcall"], require_mention=True),
platform="telegram",
)
- )
+ writes = []
+ save_state = manager.store._service.save_state
+ monkeypatch.setattr(
+ manager.store._service, "save_state", lambda *args, **kwargs: writes.append(1) or save_state(*args, **kwargs)
+ )
+ controller = SimpleNamespace(
+ config=SimpleNamespace(platform="telegram", language="en"),
+ im_client=SimpleNamespace(send_message=AsyncMock()),
+ settings_manager=manager,
+ _get_settings_key=lambda _context: make_thread_settings_key("-100123", "1"),
+ _get_lang=lambda: "en",
+ )
+
+ asyncio.run(
+ SettingsHandler(controller).handle_settings_update(
+ user_id="42",
+ channel_id="-100123",
+ thread_id="1",
+ show_message_types=["assistant"],
+ require_mention=None,
+ notify_user=False,
+ platform="telegram",
+ )
+ )
- assert calls == ["mention", "read", "save"]
+ topic = manager.store.find_thread("-100123", "1", platform="telegram")
+ # The form's "default" gate on a new topic keeps the channel's explicit gate.
+ assert (topic.show_message_types, topic.require_mention, topic.enabled) == (["assistant"], True, True)
+ assert manager.store.find_channel("-100123", platform="telegram").show_message_types == ["assistant", "toolcall"]
+ assert len(writes) == 1
+ finally:
+ SettingsStore.reset_instance()
class _FlatScopeSessions:
@@ -137,9 +141,10 @@ class _FlatScopeSettingsManager:
assert settings_key == "58181121"
return self.routing
- def set_channel_routing(self, settings_key: str, routing: RoutingSettings) -> None:
+ def set_channel_routing(self, settings_key: str, routing: RoutingSettings) -> RoutingSettings:
assert settings_key == "58181121"
self.saved_routing = routing
+ return routing
def _make_flat_scope_handler(
@@ -261,33 +266,6 @@ def test_handle_routing_update_handles_first_codex_save_without_existing_routing
send_message.assert_not_awaited()
-def test_handle_routing_update_preserves_catalog_claude_effort() -> None:
- settings_manager = _StubSettingsManager(None)
- handler, send_message = _make_handler(settings_manager)
-
- with patch(
- "core.handlers.settings_handler.backend_model_catalog.catalog_reasoning_efforts_for_model",
- return_value=["low", "ultra"],
- ):
- asyncio.run(
- handler.handle_routing_update(
- user_id="42",
- channel_id="-100123",
- agent_id="id-claude",
- variant="reviewer",
- model="claude-future-6",
- reasoning_effort="ultra",
- notify_user=False,
- platform="telegram",
- )
- )
-
- assert settings_manager.saved_routing is not None
- assert settings_manager.saved_routing.model == "claude-future-6"
- assert settings_manager.saved_routing.reasoning_effort == "ultra"
- send_message.assert_not_awaited()
-
-
def test_handle_routing_update_routes_to_the_chosen_agent_with_its_overrides() -> None:
settings_manager = _StubSettingsManager(
RoutingSettings(agent_name="opencode", model="openai/gpt-5", opencode_agent="build", claude_agent="helper")
diff --git a/tests/test_slack_dm_mentions.py b/tests/test_slack_dm_mentions.py
index 99bb78b56..d45440e48 100644
--- a/tests/test_slack_dm_mentions.py
+++ b/tests/test_slack_dm_mentions.py
@@ -809,8 +809,8 @@ class SlackDmMentionTests(unittest.IsolatedAsyncioTestCase):
return SimpleNamespace(dm_chat_id="")
return None
- def update_user(self, user_id, settings, platform=None):
- updates.append((user_id, getattr(settings, "dm_chat_id", ""), platform))
+ def update_user_fields(self, user_id, *, platform=None, **values):
+ updates.append((user_id, values.get("dm_chat_id", ""), platform))
def is_bound_user(self, user_id, platform=None):
return user_id == "U123"
@@ -865,8 +865,8 @@ class SlackDmMentionTests(unittest.IsolatedAsyncioTestCase):
return SimpleNamespace(dm_chat_id="")
return None
- def update_user(self, user_id, settings, platform=None):
- return None
+ def update_user_fields(self, user_id, *, platform=None, **values):
+ return True
def is_bound_user(self, user_id, platform=None):
return user_id == "U123"
@@ -1856,8 +1856,8 @@ class SlackReactionDmRecoveryTests(unittest.IsolatedAsyncioTestCase):
def get_user(self, user_id, platform=None):
return record
- def update_user(self, user_id, settings, platform=None):
- updates.append((user_id, settings.dm_chat_id))
+ def update_user_fields(self, user_id, *, platform=None, **values):
+ updates.append((user_id, values["dm_chat_id"]))
slack.settings_manager = SimpleNamespace(get_store=lambda: _Store(), reload_from_disk=lambda: None)
return slack, record, updates
diff --git a/tests/test_sqlite_settings_store.py b/tests/test_sqlite_settings_store.py
index c91ed5e7e..98db09f09 100644
--- a/tests/test_sqlite_settings_store.py
+++ b/tests/test_sqlite_settings_store.py
@@ -262,9 +262,7 @@ def test_settings_manager_runtime_save_preserves_require_bind(tmp_path: Path, mo
ChannelSettings(enabled=True, require_mention=True, require_bind=True, custom_cwd="/old"),
platform="slack",
)
- settings = manager.get_user_settings("C-bind")
- settings.custom_cwd = "/new"
- manager.update_user_settings("C-bind", settings)
+ manager.set_custom_cwd("C-bind", "/new")
reloaded = manager.store.find_channel("C-bind", platform="slack")
assert reloaded is not None
@@ -291,10 +289,8 @@ def test_settings_manager_topic_override_materializes_inherited_mention_default(
platform="telegram",
)
settings_key = v2_settings.make_thread_settings_key("-1001", "42")
- settings = manager.get_user_settings(settings_key)
- settings.custom_cwd = "/topic"
- manager.update_user_settings(settings_key, settings)
+ manager.set_custom_cwd(settings_key, "/topic")
topic = manager.store.find_thread("-1001", "42", platform="telegram")
assert topic is not None
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.py
index da7f4b4ba..4df46dced 100644
--- a/tests/test_ui_api.py
+++ b/tests/test_ui_api.py
@@ -27,6 +27,7 @@ from config import paths
from config.v2_settings import ChannelSettings, SettingsStore
from core.vibe_agents import VibeAgentStore
from core import chat_discovery
+from core.services import scope_settings
from modules.agents.catalog import AGENT_BACKENDS
from vibe import api, backend_model_catalog, cli_paths
from vibe.opencode_config import parse_jsonc_object
@@ -1436,8 +1437,8 @@ def test_opencode_provider_catalog_keeps_custom_provider_without_vibe_meta(
assert provider["api_key_masked"] == "••••••elay"
-def test_normalize_backend_routing_payload_prefers_canonical_claude_overrides() -> None:
- result = api._normalize_backend_routing_payload(
+def test_normalize_scope_routing_prefers_canonical_claude_overrides() -> None:
+ result = scope_settings.normalize_scope_routing(
{
"agent_backend": "claude",
"model": "claude-opus-4-8",
@@ -1453,8 +1454,8 @@ def test_normalize_backend_routing_payload_prefers_canonical_claude_overrides()
assert result["claude_reasoning_effort"] is None
-def test_normalize_backend_routing_payload_prefers_canonical_over_round_trip_aliases() -> None:
- result = api._normalize_backend_routing_payload(
+def test_normalize_scope_routing_prefers_canonical_over_round_trip_aliases() -> None:
+ result = scope_settings.normalize_scope_routing(
{
"agent_name": "claude",
"model": "claude-sonnet-4-6",
@@ -1470,8 +1471,8 @@ def test_normalize_backend_routing_payload_prefers_canonical_over_round_trip_ali
assert result["claude_reasoning_effort"] is None
-def test_normalize_backend_routing_payload_lifts_aliases_for_builtin_agent_name() -> None:
- result = api._normalize_backend_routing_payload(
+def test_normalize_scope_routing_lifts_aliases_for_builtin_agent_name() -> None:
+ result = scope_settings.normalize_scope_routing(
{
"agent_name": "claude",
"claude_model": "claude-opus-4-8",
@@ -1483,8 +1484,8 @@ def test_normalize_backend_routing_payload_lifts_aliases_for_builtin_agent_name(
assert result["reasoning_effort"] == "max"
-def test_normalize_backend_routing_payload_preserves_explicit_canonical_clears() -> None:
- result = api._normalize_backend_routing_payload(
+def test_normalize_scope_routing_preserves_explicit_canonical_clears() -> None:
+ result = scope_settings.normalize_scope_routing(
{
"agent_name": "claude",
"model": None,
@@ -1500,8 +1501,8 @@ def test_normalize_backend_routing_payload_preserves_explicit_canonical_clears()
assert result["claude_reasoning_effort"] is None
-def test_normalize_backend_routing_payload_ignores_deprecated_backend_for_alias_lifting() -> None:
- result = api._normalize_backend_routing_payload(
+def test_normalize_scope_routing_ignores_deprecated_backend_for_alias_lifting() -> None:
+ result = scope_settings.normalize_scope_routing(
{
"agent_backend": "claude",
"claude_model": "claude-opus-4-8",
@@ -1515,8 +1516,8 @@ def test_normalize_backend_routing_payload_ignores_deprecated_backend_for_alias_
assert result["claude_reasoning_effort"] == "max"
-def test_normalize_backend_routing_payload_preserves_legacy_overrides_without_backend() -> None:
- result = api._normalize_backend_routing_payload(
+def test_normalize_scope_routing_preserves_legacy_overrides_without_backend() -> None:
+ result = scope_settings.normalize_scope_routing(
{
"claude_model": "claude-opus-4-8",
"claude_reasoning_effort": "max",
@@ -1529,7 +1530,7 @@ def test_normalize_backend_routing_payload_preserves_legacy_overrides_without_ba
assert result["claude_reasoning_effort"] == "max"
[email protected]("surface", ["channel", "user", "thread"])
[email protected]("surface", ["channel", "user", "thread", "im"])
@pytest.mark.parametrize("inherit_model", [False, True])
@pytest.mark.parametrize(
("efforts", "supports_reasoning", "requested", "expected"),
@@ -1567,6 +1568,30 @@ def test_routing_save_roundtrips_exact_hub_model_effort(
}
if surface == "channel":
api.save_settings({"platform": "telegram", "channels": {"-1001": {"routing": route}}})
+ elif surface == "im":
+ # The IM routing form saves through the same write as the Web pages.
+ from types import SimpleNamespace
+ from unittest.mock import AsyncMock, patch
+
+ from core.handlers.settings_handler import SettingsHandler
+ from modules.settings_manager import SettingsManager
+
+ api.save_settings({"platform": "telegram", "channels": {"-1001": {"enabled": True}}})
+ agent = agent_store.get("routing-claude")
+ handler = SettingsHandler(SimpleNamespace(
+ config=SimpleNamespace(platform="telegram", language="en"),
+ im_client=SimpleNamespace(send_message=AsyncMock()),
+ settings_manager=SettingsManager(platform="telegram"),
+ vibe_agent_store=agent_store,
+ _get_settings_key=lambda _context: "-1001",
+ _get_lang=lambda: "en",
+ ))
+ with patch.object(handler, "_routing_update_needs_new_session_hint", return_value=False):
+ asyncio.run(handler.handle_routing_update(
+ user_id="42", channel_id="-1001", agent_id=agent.id, model=route["model"],
+ reasoning_effort=requested, platform="telegram",
+ ))
+ assert handler.controller.im_client.send_message.await_args.args[1].startswith("✅")
elif surface == "user":
api.save_users({"platform": "telegram", "users": {"U123": {"routing": route}}})
else:
@@ -1583,7 +1608,7 @@ def test_routing_save_roundtrips_exact_hub_model_effort(
settings = api.get_settings("telegram")
saved = (
settings["channels"]["-1001"]["routing"]
- if surface == "channel"
+ if surface in {"channel", "im"}
else settings["threads"]["-1001"]["42"]["routing"]
)
assert saved["reasoning_effort"] == expected
@@ -1611,7 +1636,7 @@ def test_routing_normalization_retains_native_fallback_without_cross_model_leaks
monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", "0" if mode == "disabled" else "1")
monkeypatch.setattr(api.V2Config, "load", staticmethod(lambda: config))
monkeypatch.setattr(backend_model_catalog, "catalog_reasoning_efforts_for_model", lambda *_args: efforts)
- result = api._normalize_backend_routing_payload({
+ result = scope_settings.normalize_scope_routing({
"agent_name": "claude", "model": "native-model", "reasoning_effort": requested,
})
allowed = (
diff --git a/tests/test_vibey_backend_registration.py b/tests/test_vibey_backend_registration.py
index c070420c9..eef5058a3 100644
--- a/tests/test_vibey_backend_registration.py
+++ b/tests/test_vibey_backend_registration.py
@@ -450,7 +450,7 @@ def test_an_im_picker_routes_to_exactly_the_agent_it_lists(tmp_path, sqlite_db_f
saved: dict[str, RoutingSettings] = {}
settings_manager = SimpleNamespace(
get_channel_routing=lambda key: saved.get(key),
- set_channel_routing=lambda key, routing: saved.__setitem__(key, routing),
+ set_channel_routing=lambda key, routing: saved.__setitem__(key, routing) or routing,
)
config = V2Config.from_payload(_full_config_payload())
controller = Controller.__new__(Controller)
diff --git a/tests/test_wechat_bot.py b/tests/test_wechat_bot.py
index 6612f5670..a2d6fa579 100644
--- a/tests/test_wechat_bot.py
+++ b/tests/test_wechat_bot.py
@@ -502,6 +502,45 @@ class WeChatBotTests(unittest.IsolatedAsyncioTestCase):
self.assertIs(context.is_original_human_attachment, True)
self.assertEqual([file.mimetype for file in context.files or []], ["audio/silk", "video/mp4"])
+ async def test_clearing_the_bind_menu_hint_keeps_a_concurrent_admin_change(self):
+ """The hint is runtime bookkeeping: clearing it must not write back the bot's cached copy of the user."""
+ SettingsStore.reset_instance()
+ store = SettingsStore.get_instance()
+ store.set_users_for_platform(
+ "wechat",
+ {"user-1": UserSettings(display_name="WeChat User", is_admin=True, pending_bind_menu_hint=True)},
+ )
+ store.save()
+ bot = self._make_bot()
+ bot.set_settings_manager(SettingsManager(platform="wechat"))
+ bot.check_authorization = lambda **kwargs: AuthResult(allowed=True, is_dm=True)
+ bot.dispatch_text_command = AsyncMock(return_value=False)
+ bot._process_media_items = AsyncMock(return_value=None)
+ bot.on_message_callback = AsyncMock()
+ bot.send_message = AsyncMock(return_value="wc-hint")
+ # The Web settings process demotes the user after the bot loaded it.
+ web = SettingsStore()
+ try:
+ web.set_admin("user-1", False, platform="wechat")
+ finally:
+ web.close()
+
+ await bot._process_inbound_message({
+ "message_id": "mid-hint-admin",
+ "from_user_id": "user-1",
+ "context_token": "ctx-1",
+ "item_list": [{"type": 1, "text_item": {"text": "hi"}}],
+ })
+ await asyncio.gather(*tuple(bot._message_callback_tasks))
+
+ bot.send_message.assert_awaited_once()
+ reread = SettingsStore()
+ try:
+ user = reread.get_user("user-1", platform="wechat")
+ finally:
+ reread.close()
+ self.assertEqual((user.is_admin, user.pending_bind_menu_hint), (False, False)) # type: ignore[union-attr]
+
async def test_process_inbound_message_sends_pending_bind_menu_hint_once(self):
SettingsStore.reset_instance()
store = SettingsStore.get_instance()
diff --git a/vibe/api.py b/vibe/api.py
index 939874ce6..64cf19a61 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1,8 +1,6 @@
import asyncio
import base64
import contextlib
-import copy
-import dataclasses
import hashlib
import json
import logging
@@ -56,6 +54,7 @@ from config.platform_registry import get_platform_descriptor
from core import latest_version_cache
from core.backend_restart import NativeCredentialLease, NativeMigrationBlockedError, finish_native_operation
from core.install_integrity import verify_python_environment
+from core.services import scope_settings
from vibe.opencode_config import (
get_opencode_config_paths,
load_first_opencode_user_config,
@@ -5738,60 +5737,6 @@ def get_settings(platform: Optional[str] = None, *, user_context: Any = None) ->
return payload
-def _normalize_backend_routing_payload(routing_payload: dict) -> dict:
- from config.v2_config import is_model_hub_enabled
- from core.handlers.model_hub.service import V2ModelHubConfigStore
- from modules.agents.opencode.utils import normalize_claude_reasoning_effort
-
- routing = _parse_routing(routing_payload or {})
- backend, agent_model = _routing_agent_backend_and_model(routing.agent_name)
- if backend == "claude" and routing.reasoning_effort:
- model = routing.model or agent_model
- catalog_efforts = None
- agent_catalog = (
- V2ModelHubConfigStore().load().agents["claude"] if is_model_hub_enabled() else None
- )
- if agent_catalog is not None and agent_catalog.mode == "hub":
- row = next((row for row in agent_catalog.models if row.id == model), None)
- if row is not None:
- # Match the picker: a present empty list (or non-reasoning
- # model) is authoritative, not a request for backend tiers.
- catalog_efforts = [] if row.supports_reasoning is False else row.reasoning_efforts
- # Unknown Hub rows retain the existing generic normalization;
- # a same-named native model must not grant them Off support.
- else:
- catalog_efforts = backend_model_catalog.catalog_reasoning_efforts_for_model("claude", model)
- routing.reasoning_effort = normalize_claude_reasoning_effort(
- model,
- routing.reasoning_effort,
- catalog_efforts,
- )
- return _routing_to_dict(routing)
-
-
-def _routing_agent_backend_and_model(agent_name: Optional[str]) -> tuple[Optional[str], Optional[str]]:
- name = str(agent_name or "").strip()
- if not name:
- return None, None
- store = VibeAgentStore()
- try:
- agent = store.get(name)
- if agent is not None:
- return agent.backend, agent.model
- except Exception:
- logger.debug("Failed to resolve Agent backend while normalizing routing payload", exc_info=True)
- finally:
- store.close()
- return (name, None) if is_agent_backend(name) else (None, None)
-
-
-def _normalize_show_message_types_for_platform(show_message_types: Optional[list], platform: str) -> list[str]:
- normalized = normalize_show_message_types(show_message_types)
- if not get_platform_descriptor(platform).capabilities.supports_toolcall_delivery:
- return [msg_type for msg_type in normalized if msg_type != "toolcall"]
- return normalized
-
-
def save_settings(payload: dict, *, user_context: Any = None) -> dict:
from vibe.authorization import require_instance_role
@@ -5806,11 +5751,11 @@ def save_settings(payload: dict, *, user_context: Any = None) -> dict:
existing = store.find_channel(channel_id, platform=platform)
channels[channel_id] = ChannelSettings(
enabled=channel_payload.get("enabled", True),
- show_message_types=_normalize_show_message_types_for_platform(
+ show_message_types=scope_settings.normalize_scope_message_types(
channel_payload.get("show_message_types"), platform
),
custom_cwd=channel_payload.get("custom_cwd"),
- routing=_parse_routing(_normalize_backend_routing_payload(channel_payload.get("routing") or {})),
+ routing=_parse_routing(scope_settings.normalize_scope_routing(channel_payload.get("routing") or {})),
require_mention=channel_payload.get("require_mention"),
require_bind=channel_payload.get("require_bind", existing.require_bind if existing else None),
_agent_name_at_load=channel_payload.get(
@@ -5847,7 +5792,7 @@ def save_thread_settings(payload: dict, *, user_context: Any = None) -> dict:
base = store.find_channel(channel_id, platform=platform) or ChannelSettings()
routing_payload = settings_payload.get("routing")
routing = (
- _parse_routing(_normalize_backend_routing_payload(routing_payload))
+ _parse_routing(scope_settings.normalize_scope_routing(routing_payload))
if isinstance(routing_payload, dict)
else base.routing
)
@@ -5857,7 +5802,7 @@ def save_thread_settings(payload: dict, *, user_context: Any = None) -> dict:
require_mention = bool(getattr(platform_config, "require_mention", True))
settings = ChannelSettings(
enabled=bool(settings_payload.get("enabled", base.enabled)),
- show_message_types=_normalize_show_message_types_for_platform(
+ show_message_types=scope_settings.normalize_scope_message_types(
settings_payload.get("show_message_types", base.show_message_types),
platform,
),
@@ -5888,18 +5833,6 @@ class ScopeSettingsRequestError(ValueError):
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"
@@ -5915,7 +5848,7 @@ def _scope_patch_value_error(name: str, value: Any) -> Optional[str]:
if name == "routing":
if not isinstance(value, dict):
return "must be an object"
- unknown = sorted(set(value) - _ROUTING_PATCH_FIELDS)
+ unknown = sorted(set(value) - scope_settings.ROUTING_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()):
@@ -5923,24 +5856,14 @@ def _scope_patch_value_error(name: str, value: Any) -> Optional[str]:
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.
+ The request contract of ``core.services.scope_settings.apply_scope_change``,
+ which every settings surface writes through. A routing change must name the
+ Agent its view of the route was based on (``expected_agent_name``).
"""
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())
@@ -5948,7 +5871,7 @@ def patch_scope_settings(payload: dict, *, user_context: Any = None) -> dict:
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:
+ if kind not in scope_settings.SCOPE_KINDS:
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")
@@ -5956,102 +5879,43 @@ def patch_scope_settings(payload: dict, *, user_context: Any = None) -> dict:
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])
+ unknown = sorted(set(changes) - scope_settings.SCOPE_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
+ expected_agent_name = payload.get("expected_agent_name", scope_settings.MISSING)
+ if "routing" in changes and (
+ expected_agent_name is scope_settings.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
+ # Keep unvalidated request candidates out of the process-wide cache.
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)
+ try:
+ saved = scope_settings.apply_scope_change(
+ store,
+ platform=platform,
+ kind=kind,
+ native_id=native_id,
+ thread_id=thread_id,
+ changes=changes,
+ expected_agent_name=expected_agent_name,
+ new_topic_require_mention=new_topic_require_mention,
+ user_context=user_context,
+ )
+ except scope_settings.ScopeNotFoundError as exc:
+ raise ScopeSettingsRequestError("user_not_found", "User not found", status=404) from exc
if kind == "user":
settings_payload = _user_settings_payload(saved, platform)
else:
@@ -6939,7 +6803,7 @@ def _current_platform() -> str:
def _scope_settings_payload(settings: ChannelSettings, platform: str) -> dict:
return {
"enabled": settings.enabled,
- "show_message_types": _normalize_show_message_types_for_platform(settings.show_message_types, platform),
+ "show_message_types": scope_settings.normalize_scope_message_types(settings.show_message_types, platform),
"custom_cwd": settings.custom_cwd,
"require_mention": settings.require_mention,
"require_bind": settings.require_bind,
@@ -6954,7 +6818,7 @@ def _user_settings_payload(settings: UserSettings, platform: str) -> dict:
"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),
+ "show_message_types": scope_settings.normalize_scope_message_types(settings.show_message_types, platform),
"custom_cwd": settings.custom_cwd,
"routing": routing_to_compat_dict(settings.routing),
"expected_agent_name": _agent_binding_expectation(settings),
@@ -14708,9 +14572,9 @@ def save_users(payload: dict, *, user_context: Any = None) -> dict:
is_admin=up.get("is_admin", existing.is_admin if existing else False),
bound_at=up.get("bound_at", existing.bound_at if existing else ""),
enabled=up.get("enabled", existing.enabled if existing else True),
- show_message_types=_normalize_show_message_types_for_platform(up.get("show_message_types"), platform),
+ show_message_types=scope_settings.normalize_scope_message_types(up.get("show_message_types"), platform),
custom_cwd=up.get("custom_cwd"),
- routing=_parse_routing(_normalize_backend_routing_payload(up.get("routing") or {})),
+ routing=_parse_routing(scope_settings.normalize_scope_routing(up.get("routing") or {})),
dm_chat_id=existing.dm_chat_id if existing else "",
pending_bind_menu_hint=existing.pending_bind_menu_hint if existing else False,
_agent_name_at_load=up.get("expected_agent_name", _UNSET_AGENT_BINDING),