Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(settings): show each scope's effective route, save state, and new-session hint (#3052)
Call White4117c9147243
diff --git a/core/handlers/settings_handler.py b/core/handlers/settings_handler.pyindex 06c69b262..89d6666da 100644--- a/core/handlers/settings_handler.py+++ b/core/handlers/settings_handler.py@@ -704,6 +704,14 @@ class SettingsHandler(BaseHandler):def _routing_target_from_settings(self, routing) -> tuple[str, str, str, str, str]:agent_name = str(getattr(routing, "agent_name", None) or "").strip()+ if not agent_name:+ # A route that names no Agent runs the default one.+ try:+ default_agent = self.controller.vibe_agent_store.get_default_agent()+ except Exception:+ logger.debug("Failed to resolve the default Agent for a routing hint", exc_info=True)+ default_agent = None+ agent_name = str(getattr(default_agent, "name", None) or "").strip()backend = str(self._resolve_route_backend(agent_name) or agent_name).strip()variant = getattr(routing, f"{backend}_agent", None) if backend in NATIVE_CLI_BACKENDS else Nonevariant = str(variant or "").strip()@@ -729,6 +737,37 @@ class SettingsHandler(BaseHandler):# a new session to run.return bool(current_agent and next_agent and current_agent != next_agent)+ def scope_needs_new_session(self, *, platform: str, kind: str, native_id: str, thread_id: str = "") -> bool:+ """Whether this scope's current session runs another Agent than the route it stores.++ Such a session keeps its Agent, so the stored route applies only once a new+ session starts there. The IM routing form says so when it saves; the Web+ settings pages ask this after an Agent change to say the same.+ """+ is_dm = kind == "user"+ probe = MessageContext(+ user_id=native_id if is_dm else "",+ channel_id=native_id,+ platform=platform,+ platform_specific={"is_dm": is_dm, "platform": platform},+ )+ settings_manager = self._get_settings_manager(probe)+ channel_id = native_id+ if is_dm:+ # A DM session is anchored on the platform's DM channel, which some+ # platforms keep apart from the user id.+ user = settings_manager.get_store().get_user(native_id, platform=platform)+ channel_id = str(getattr(user, "dm_chat_id", "") or "") or native_id+ context = MessageContext(+ user_id=native_id if is_dm else "",+ channel_id=channel_id,+ thread_id=thread_id or None,+ platform=platform,+ platform_specific={"is_dm": is_dm, "platform": platform},+ )+ routing = settings_manager.get_channel_routing(self._get_settings_key(context))+ return self._routing_update_needs_new_session_hint(context, routing)+async def handle_settings_update(self,user_id: str,diff --git a/core/internal_server.py b/core/internal_server.pyindex 086733b53..e67dc18bf 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -1503,6 +1503,28 @@ def create_app(logger.exception("internal platform reconcile failed")return JSONResponse(status_code=500, content={"ok": False, "error": str(exc)})+ @app.post("/internal/scope-session-hint")+ async def _scope_session_hint(request: Request) -> Any:+ """Whether a scope's current session still runs another Agent than its route."""+ payload = await _safe_json(request)+ platform = str(payload.get("platform") or "").strip()+ kind = str(payload.get("scope") or "").strip()+ native_id = str(payload.get("id") or "").strip()+ if not platform or kind not in {"channel", "thread", "user"} or not native_id:+ return JSONResponse(status_code=400, content={"ok": False, "error": "platform, scope and id are required"})+ try:+ needed = await asyncio.to_thread(+ controller.settings_handler.scope_needs_new_session,+ platform=platform,+ kind=kind,+ native_id=native_id,+ thread_id=str(payload.get("thread_id") or "").strip(),+ )+ except Exception as exc:+ logger.warning("scope session hint failed: %s", exc)+ return JSONResponse(status_code=500, content={"ok": False, "error": str(exc)})+ return JSONResponse(status_code=200, content={"ok": True, "needs_new_session": bool(needed)})+@app.post("/internal/invalidate-activity-streaming")async def _invalidate_activity_streaming() -> Any:"""Drop the controller process's cached Agent Activity display flag."""diff --git a/docs/plans/scope-settings-patch.md b/docs/plans/scope-settings-patch.mdindex 70b7b1925..4137cf126 100644--- a/docs/plans/scope-settings-patch.md+++ b/docs/plans/scope-settings-patch.md@@ -90,10 +90,21 @@ reaches it through `SettingsManager.change_scope_settings`:uses `SettingsStore.update_user_fields`, which sets only those fields underthe write lock instead of writing back a cached copy of the user.+## What a settings row shows++- Each users/groups row summarizes the route the scope runs: its own model and+ effort over its Agent's, marked as the default when it names none of them.+- A save in flight shows on its row and on the route picker; only failures are+ announced.+- After a routing change, `PATCH /api/settings/scope` reports+ `needs_new_session`, asked of the controller over the internal socket+ (`/internal/scope-session-hint`), which owns session semantics: true when the+ scope's current session runs another Agent and is not replaced by the next+ message (a flat DM or chat), as the IM routing form says. `null` when the+ controller cannot answer. The row then says to send `/new` there.+## Out of scope- Removing the legacy per-backend `<backend>_model` / `<backend>_reasoning_effort`routing fields from the API, the Web types, and the stored routing JSON. Theyare 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/tests/test_internal_client.py b/tests/test_internal_client.pyindex 8af3f1967..072a5a9a5 100644--- a/tests/test_internal_client.py+++ b/tests/test_internal_client.py@@ -763,3 +763,39 @@ def test_backend_application_uses_verified_socket_and_real_projection(socket_patawait internal_client.backend_application("other", socket_path=socket_path)asyncio.run(run())+++def test_scope_session_hint_round_trip_through_the_controller_endpoint(socket_path):+ """The Web settings write asks the controller, which owns session semantics, about one scope."""+ from types import SimpleNamespace++ from core import internal_server+ from tests.test_internal_server import _build_controller_double++ asked: list[dict] = []++ def scope_needs_new_session(**kwargs):+ asked.append(kwargs)+ return kwargs["native_id"] == "flat-chat"++ controller = _build_controller_double()+ controller.settings_handler = SimpleNamespace(scope_needs_new_session=scope_needs_new_session)+ app = internal_server.create_app(controller)++ async def _go():+ fake_transport = httpx.ASGITransport(app=app)+ with patch("vibe.internal_client.httpx.AsyncHTTPTransport", return_value=fake_transport):+ return (+ await internal_client.scope_session_hint(+ platform="telegram", scope="thread", native_id="flat-chat", thread_id="7", socket_path=socket_path,+ ),+ await internal_client.scope_session_hint(+ platform="slack", scope="channel", native_id="C1", socket_path=socket_path,+ ),+ )++ assert asyncio.run(_go()) == (True, False)+ assert asked == [+ {"platform": "telegram", "kind": "thread", "native_id": "flat-chat", "thread_id": "7"},+ {"platform": "slack", "kind": "channel", "native_id": "C1", "thread_id": ""},+ ]diff --git a/tests/test_settings_handler.py b/tests/test_settings_handler.pyindex 31f357e13..67485b6b2 100644--- a/tests/test_settings_handler.py+++ b/tests/test_settings_handler.py@@ -43,6 +43,9 @@ class _AgentStore:def get(self, name):return next((agent for agent in self.agents if agent.name == name), None)+ def get_default_agent(self):+ return self.get("vibey")+class _StubSettingsManager:def __init__(self, routing: RoutingSettings | None):@@ -936,3 +939,52 @@ def test_a_routing_save_the_store_refuses_is_reported_not_confirmed(tmp_path, moassert manager.store.find_channel("-100123", platform="telegram").routing.agent_name is Nonefinally:SettingsStore.reset_instance()+++def test_scope_needs_new_session_answers_for_the_scope_the_web_saved() -> None:+ """A DM session is anchored on the platform's DM channel; only a flat scope's live session keeps its Agent."""+ rows = {"discord_D-chan": {"agent_name": "opencode", "agent_backend": "opencode"}}+ anchors: list[str] = []++ def find_session_for_anchor(session_key, anchor):+ anchors.append(anchor)+ return rows.get(anchor)++ def handler_for(*, threaded: bool, routing_agent: str):+ manager = SimpleNamespace(+ get_channel_routing=lambda key: RoutingSettings(agent_name=routing_agent),+ get_store=lambda: SimpleNamespace(+ get_user=lambda user_id, platform=None: SimpleNamespace(dm_chat_id="D-chan") if user_id == "U1" else None+ ),+ )+ controller = SimpleNamespace(+ config=SimpleNamespace(platform="discord", language="en"),+ im_client=SimpleNamespace(+ should_use_thread_for_reply=lambda: threaded,+ should_use_thread_for_dm_session=lambda: threaded,+ should_use_message_id_for_channel_session=lambda context=None: threaded,+ ),+ settings_manager=manager,+ sessions=SimpleNamespace(find_session_for_anchor=find_session_for_anchor),+ session_handler=SimpleNamespace(get_base_session_id=lambda context: f"{context.platform}_{context.channel_id}"),+ vibe_agent_store=_AgentStore(),+ _get_settings_key=lambda context: context.user_id or context.channel_id,+ _get_session_key=lambda context: f"{context.platform}::{context.channel_id}",+ _get_lang=lambda: "en",+ )+ return SettingsHandler(controller)++ flat = handler_for(threaded=False, routing_agent="vibey")+ assert flat.scope_needs_new_session(platform="discord", kind="user", native_id="U1") is True+ assert anchors[-1] == "discord_D-chan"+ assert handler_for(threaded=False, routing_agent="opencode").scope_needs_new_session(+ platform="discord", kind="user", native_id="U1"+ ) is False+ # A route back to the default Agent is compared as that Agent, with or without overrides.+ for inherited in (RoutingSettings(), RoutingSettings(model="m1", reasoning_effort="high")):+ flat.controller.settings_manager.get_channel_routing = lambda key, routing=inherited: routing+ assert flat.scope_needs_new_session(platform="discord", kind="user", native_id="U1") is True+ assert flat.scope_needs_new_session(platform="discord", kind="channel", native_id="C9") is False+ assert handler_for(threaded=True, routing_agent="vibey").scope_needs_new_session(+ platform="discord", kind="user", native_id="U1"+ ) is Falsediff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.pyindex 277c3758a..1b445dc2a 100644--- a/tests/test_ui_server_fastapi.py+++ b/tests/test_ui_server_fastapi.py@@ -570,6 +570,35 @@ def test_scope_settings_routes_report_localized_stale_agent_binding_conflicts(mo}+def test_scope_patch_reports_whether_the_session_keeps_its_agent_after_a_route_change(monkeypatch):+ from vibe import api, internal_client++ saved = {"ok": True, "platform": "telegram", "scope": "user", "id": "U1", "settings": {}}+ monkeypatch.setattr(api, "patch_scope_settings", lambda payload, user_context=None: dict(saved))+ asked = []+ answers = iter([True, internal_client.InternalServerUnavailable("controller down")])++ async def scope_session_hint(**kwargs):+ asked.append(kwargs)+ answer = next(answers)+ if isinstance(answer, Exception):+ raise answer+ return answer++ monkeypatch.setattr(internal_client, "scope_session_hint", scope_session_hint)+ client = app.test_client()+ headers = csrf_headers(client)++ def patch(changes):+ body = {"platform": "telegram", "scope": "user", "id": "U1", "changes": changes, "expected_agent_name": None}+ return client.patch("/api/settings/scope", json=body, headers=headers).get_json()++ assert patch({"routing": {"agent_name": "pm"}})["needs_new_session"] is True+ assert patch({"routing": {"agent_name": "qa"}})["needs_new_session"] is None+ assert "needs_new_session" not in patch({"custom_cwd": "/tmp"})+ assert asked == [{"platform": "telegram", "scope": "user", "native_id": "U1", "thread_id": ""}] * 2++def test_scope_settings_routes_localize_unavailable_agent_errors(monkeypatch):from core.services import settings as settings_servicefrom storage.settings_service import ScopeAgentUnavailableErrordiff --git a/ui/eslint-baseline.json b/ui/eslint-baseline.jsonindex 1837329ae..71749a0f9 100644--- a/ui/eslint-baseline.json+++ b/ui/eslint-baseline.json@@ -271,7 +271,7 @@},"src/components/steps/UserList.tsx": {"@typescript-eslint/no-explicit-any": 2,- "avibe/localized-user-text": 5,+ "avibe/localized-user-text": 4,"react-hooks/set-state-in-effect": 2},"src/components/steps/WeChatConfig.tsx": {diff --git a/ui/src/components/shared/RoutingConfigPanel.tsx b/ui/src/components/shared/RoutingConfigPanel.tsxindex 393fab041..b96a0b841 100644--- a/ui/src/components/shared/RoutingConfigPanel.tsx+++ b/ui/src/components/shared/RoutingConfigPanel.tsx@@ -55,6 +55,10 @@ export interface RoutingConfigPanelProps {footerActions?: React.ReactNode;/** Wrapper class — controls outer padding/border. Default: 'border-t border-border/60 px-5 py-4'. */containerClass?: string;+ /** A save of this scope is in flight — shown on the route picker. */+ saving?: boolean;+ /** Shown under the route picker, e.g. that the current session keeps its Agent. */+ routeNotice?: string | null;}/** Input that only commits value on blur */@@ -87,6 +91,8 @@ export const RoutingConfigPanel: React.FC<RoutingConfigPanelProps> = ({availableMessageTypes = ['assistant', 'toolcall'],footerActions,containerClass = 'border-t border-border/60 px-5 py-4',+ saving = false,+ routeNotice,}) => {const { capabilities } = useInstanceAuthorization();const canManageAccessMembers = capabilities.can_manage_access_members;@@ -182,64 +188,72 @@ export const RoutingConfigPanel: React.FC<RoutingConfigPanelProps> = ({</div>{/* Routing: one unified Agent picker (agent → model → effort), shared with- the workbench chat/create surfaces. Empty = inherit the global default. */}+ the workbench chat/create surfaces. Empty = inherit the global default.+ Capped like the users page's working directory, instead of a picker+ stretched across the row. */}<div className="space-y-1">- <label className="flex items-center gap-1.5 text-xs font-medium uppercase text-muted">- <Bot size={12} className="text-muted" />- {t('channelList.agent')}- </label>- <AgentRoutePicker- value={{- // Resolve the DISPLAYED route. An explicit agent with an empty- // model/effort means "inherit that agent's", so fall back to the- // selected agent's own model/effort — otherwise the effort column- // resolves options without the inherited Agent model (e.g. a Claude- // agent's xhigh/max would vanish).- // agent_backend also falls back to the default agent so the columns- // resolve while inheriting the global default.- agent_backend: selectedVibeAgent?.backend ?? defaultVibeAgent?.backend ?? null,- agent_name: value.routing.agent_name ?? null,- model: value.routing.model ?? selectedVibeAgent?.model ?? null,- reasoning_effort: value.routing.reasoning_effort ?? selectedVibeAgent?.reasoning_effort ?? null,- }}- agents={vibeAgents}- onChange={(patch) => {- // Concrete routes, matching the workbench picker + the other call- // sites: merge only the keys PRESENT in the (partial) patch. A- // present field wins (incl. an explicit null that clears it); an- // absent field keeps its stored value. We deliberately do NOT- // special-case agent picks to null model/effort — that discarded the- // first model pick on an inherited-default route, where the pick- // arrives as the materialized agent_name + the chosen model together.- const next = { ...value.routing };- if ('agent_name' in patch) next.agent_name = patch.agent_name ?? null;- if ('model' in patch) next.model = patch.model ?? null;- if ('reasoning_effort' in patch) next.reasoning_effort = patch.reasoning_effort ?? null;- onChange({ routing: clearLegacyOverrides(next) });- }}- defaultLabel={- defaultVibeAgent ? `${t('common.default')} · ${defaultVibeAgent.name}` : t('common.default')- }- defaultRoute={- defaultVibeAgent- ? {- agent_backend: defaultVibeAgent.backend,- agent_name: defaultVibeAgent.name,- model: defaultVibeAgent.model,- reasoning_effort: defaultVibeAgent.reasoning_effort,- }- : undefined- }- // Only a FULLY-inheriting scope (no overrides at all) displays the- // default route. A scope that inherits the agent but overrides- // model/effort must show its own values, not the default agent's,- // otherwise the override is masked and silently overwritten.- isDefaultRoute={- !value.routing.agent_name && !value.routing.model && !value.routing.reasoning_effort- }- align="start"- triggerClassName="w-full"- />+ <div className="space-y-1 md:max-w-[40%]">+ <label className="flex items-center gap-1.5 text-xs font-medium uppercase text-muted">+ <Bot size={12} className="text-muted" />+ {t('channelList.agent')}+ </label>+ <AgentRoutePicker+ value={{+ // Resolve the DISPLAYED route. An explicit agent with an empty+ // model/effort means "inherit that agent's", so fall back to the+ // selected agent's own model/effort — otherwise the effort column+ // resolves options without the inherited Agent model (e.g. a Claude+ // agent's xhigh/max would vanish).+ // agent_backend also falls back to the default agent so the columns+ // resolve while inheriting the global default.+ agent_backend: selectedVibeAgent?.backend ?? defaultVibeAgent?.backend ?? null,+ agent_name: value.routing.agent_name ?? null,+ model: value.routing.model ?? selectedVibeAgent?.model ?? null,+ reasoning_effort: value.routing.reasoning_effort ?? selectedVibeAgent?.reasoning_effort ?? null,+ }}+ agents={vibeAgents}+ onChange={(patch) => {+ // Concrete routes, matching the workbench picker + the other call+ // sites: merge only the keys PRESENT in the (partial) patch. A+ // present field wins (incl. an explicit null that clears it); an+ // absent field keeps its stored value. We deliberately do NOT+ // special-case agent picks to null model/effort — that discarded the+ // first model pick on an inherited-default route, where the pick+ // arrives as the materialized agent_name + the chosen model together.+ const next = { ...value.routing };+ if ('agent_name' in patch) next.agent_name = patch.agent_name ?? null;+ if ('model' in patch) next.model = patch.model ?? null;+ if ('reasoning_effort' in patch) next.reasoning_effort = patch.reasoning_effort ?? null;+ onChange({ routing: clearLegacyOverrides(next) });+ }}+ defaultLabel={+ defaultVibeAgent ? `${t('common.default')} · ${defaultVibeAgent.name}` : t('common.default')+ }+ defaultRoute={+ defaultVibeAgent+ ? {+ agent_backend: defaultVibeAgent.backend,+ agent_name: defaultVibeAgent.name,+ model: defaultVibeAgent.model,+ reasoning_effort: defaultVibeAgent.reasoning_effort,+ }+ : undefined+ }+ // Only a FULLY-inheriting scope (no overrides at all) displays the+ // default route. A scope that inherits the agent but overrides+ // model/effort must show its own values, not the default agent's,+ // otherwise the override is masked and silently overwritten.+ isDefaultRoute={+ !value.routing.agent_name && !value.routing.model && !value.routing.reasoning_effort+ }+ saving={saving}+ align="start"+ triggerClassName="w-full"+ />+ </div>+ {routeNotice && (+ <p role="status" className="pt-1 text-[11px] leading-snug text-gold-ink">{routeNotice}</p>+ )}</div>{/* Show message types chips */}diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsxindex e0f60c42a..82048d2ca 100644--- a/ui/src/components/steps/ChannelList.tsx+++ b/ui/src/components/steps/ChannelList.tsx@@ -10,6 +10,7 @@ import {Globe,Hash,HelpCircle,+ Loader2,MessageSquare,RefreshCw,Square,@@ -27,11 +28,11 @@ import { hasUsableSecret } from '../../lib/secretFields';import { setConfigField } from '../../lib/configMutations';import { EyebrowBadge, PlatformIcon, WizardCard } from '../visual';import { RoutingConfigPanel } from '../shared/RoutingConfigPanel';+import { scopeRouteSummary } from '../../lib/scopeRouteSummary';import { CHANNEL_SCOPE_FIELDS, scopeSettingsChange } from '../../lib/scopeSettingsPatch';import { CompactSelect, SearchField, ToggleSwitch } from '../settings/SettingsPrimitives';import { Button } from '../ui/button';import { TelegramTopicList } from './TelegramTopicList';-import { getBackendUiMeta } from '@/lib/agentBackends';const PLATFORM_BRAND_COLORS: Record<string, string> = {slack: '#4A154B',@@ -109,6 +110,10 @@ const addDiscordGuildToAllowlist = (allowlist: string[], selectedGuild: string):return merged;};+/** The key a channel or Telegram topic row is tracked by on the settings page. */+const scopeRowKey = (platformId: string, channelId: string, topicId?: string) =>+ topicId ? `${platformId}::${channelId}::${topicId}` : `${platformId}::${channelId}`;+export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBack, isPage, forcedPlatform, wizardPlatforms }) => {const { capabilities } = useInstanceAuthorization();const canManageAccessMembers = capabilities.can_manage_access_members;@@ -149,6 +154,11 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBconst channelRequestVersionRef = useRef(0);const allPlatformsRequestVersionRef = useRef(0);const scopeSaveVersionRef = useRef<Record<string, number>>({});+ const routeSaveVersionRef = useRef<Record<string, number>>({});+ // Per scope row (see scopeRowKey): saves in flight, and whether the last route+ // change left a session that keeps its previous Agent.+ const [savingRows, setSavingRows] = useState<Record<string, number>>({});+ const [newSessionRows, setNewSessionRows] = useState<Record<string, boolean>>({});const currentPlatformRef = useRef<string>('');// Directory browser state — tracks which channel's cwd picker is openconst [browsingCwdFor, setBrowsingCwdFor] = useState<string | null>(null);@@ -715,7 +725,8 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB// 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.+ // the platform), or a newer edit of the same scope owns the local row. The+ // row shows the save in progress; only a failure is announced.const persistScopeChange = async (platformId: string,scope: { kind: 'channel' | 'thread'; id: string; threadId?: string },@@ -725,9 +736,13 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB): 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 rowKey = scopeRowKey(platformId, scope.id, scope.threadId);const version = (scopeSaveVersionRef.current[rowKey] || 0) + 1;scopeSaveVersionRef.current[rowKey] = version;+ // The session note answers the latest route change, whatever else saved since.+ const routeVersion = 'routing' in change.changes ? (routeSaveVersionRef.current[rowKey] || 0) + 1 : null;+ if (routeVersion !== null) routeSaveVersionRef.current[rowKey] = routeVersion;+ setSavingRows((prev) => ({ ...prev, [rowKey]: (prev[rowKey] || 0) + 1 }));try {const result = await api.patchScopeSettings({platform: platformId,@@ -736,12 +751,17 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB...(scope.threadId ? { thread_id: scope.threadId } : {}),...change,});- showToast(t('channelList.settingsSaved'));- return scopeSaveVersionRef.current[rowKey] === version ? (result.settings as ChannelConfig) : null;+ if (routeVersion !== null && routeSaveVersionRef.current[rowKey] === routeVersion) {+ setNewSessionRows((prev) => ({ ...prev, [rowKey]: result.needs_new_session === true }));+ }+ if (scopeSaveVersionRef.current[rowKey] !== version) return null;+ return result.settings as ChannelConfig;} catch {showToast(t('channelList.settingsSaveFailed'), 'error');if (scopeSaveVersionRef.current[rowKey] === version) await reloadChannelConfigs(platformId);return null;+ } finally {+ setSavingRows((prev) => ({ ...prev, [rowKey]: Math.max(0, (prev[rowKey] || 1) - 1) }));}};@@ -1479,7 +1499,6 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBconst channelPlatform = row.platform;const rawConfig = row.config;const def = defaultConfig();- const defaultAgent = agentByName[defaultAgentName || ''] || null;const channelEnabled = rawConfig.enabled === true;const isUnavailable = channel.visibility_status === 'not_returned';const channelConfig = {@@ -1492,10 +1511,9 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBrequire_mention: rawConfig.require_mention !== undefined ? rawConfig.require_mention : def.require_mention,require_bind: rawConfig.require_bind !== undefined ? rawConfig.require_bind : def.require_bind,};- const rowKey = `${channelPlatform}::${channel.id}`;+ const rowKey = scopeRowKey(channelPlatform, channel.id);const expanded = expandedChannelId === rowKey;- const selectedAgent = agentByName[channelConfig.routing.agent_name || ''] || agentByName[defaultAgentName || ''];- const effectiveBackend = selectedAgent?.backend || defaultAgent?.backend || 'opencode';+ const saving = (savingRows[rowKey] || 0) > 0;const updateRow = (patch: Partial<ChannelConfig>) => {void updateConfigForPlatform(channelPlatform, channel.id, patch);@@ -1522,16 +1540,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBupdateRow(patch);};- const backendModel = channelConfig.routing.model || (- effectiveBackend === 'claude'- ? channelConfig.routing.claude_model- : effectiveBackend === 'codex'- ? channelConfig.routing.codex_model- : effectiveBackend === 'opencode' ? channelConfig.routing.opencode_model : undefined- );- const agentSummary = selectedAgent- ? `${selectedAgent.display_name || selectedAgent.name}${selectedAgent.model ? ` / ${selectedAgent.model}` : ''}`- : `${getBackendUiMeta(effectiveBackend).label}${backendModel ? ` / ${backendModel}` : ''}`;+ const agentSummary = scopeRouteSummary(channelConfig.routing, agentByName, defaultAgentName, t);return (<div@@ -1630,6 +1639,10 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB</button>)}+ {saving && (+ <Loader2 size={14} className="shrink-0 animate-spin text-muted" aria-label={t('common.saving')} />+ )}+{/* Chevron */}{expanded ? (<ChevronUp size={18} className="shrink-0 text-muted" />@@ -1651,6 +1664,8 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBavailableMessageTypes={availableMessageTypes(channelPlatform)}showRequireMention={true}inheritsFromKey={channelPlatform}+ saving={saving}+ routeNotice={newSessionRows[rowKey] ? t('channelList.newSessionHint') : null}/>{channelPlatform === 'telegram' && channel.supports_topics && (<TelegramTopicList<ChannelConfig>@@ -1684,7 +1699,13 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB<RoutingConfigPanelvalue={topicConfig}onChange={(patch) => void saveTelegramTopicConfig(channel.id, topicId, patch)}- onBrowseDirectory={() => setBrowsingCwdFor(`telegram::${channel.id}::${topicId}`)}+ onBrowseDirectory={() => setBrowsingCwdFor(scopeRowKey('telegram', channel.id, topicId))}+ saving={(savingRows[scopeRowKey('telegram', channel.id, topicId)] || 0) > 0}+ routeNotice={+ newSessionRows[scopeRowKey('telegram', channel.id, topicId)]+ ? t('channelList.newSessionHint')+ : null+ }globalConfig={config}vibeAgents={vibeAgents}defaultAgentName={defaultAgentName}diff --git a/ui/src/components/steps/UserList.tsx b/ui/src/components/steps/UserList.tsxindex 0a36dd40a..67acc6b14 100644--- a/ui/src/components/steps/UserList.tsx+++ b/ui/src/components/steps/UserList.tsx@@ -9,6 +9,7 @@ import {ChevronUp,Copy,KeyRound,+ Loader2,Plus,RefreshCw,Shield,@@ -18,12 +19,12 @@ import { useTranslation } from 'react-i18next';import clsx from 'clsx';import { useApi } from '../../context/ApiContext';import { useToast } from '../../context/ToastContext';-import { getBackendUiMeta } from '../../lib/agentBackends';import { getEnabledPlatforms, platformSupportsToolcallDelivery } from '../../lib/platforms';import { FolderBrowser } from '../ui/folder-browser';import { copyTextToClipboard } from '../../lib/utils';import { PlatformIcon } from '../visual';import { RoutingConfigPanel } from '../shared/RoutingConfigPanel';+import { scopeRouteSummary } from '../../lib/scopeRouteSummary';import { scopeSettingsChange, USER_SCOPE_FIELDS } from '../../lib/scopeSettingsPatch';import { SearchField, ToggleSwitch } from '../settings/SettingsPrimitives';import { Button } from '../ui/button';@@ -443,7 +444,8 @@ export const UserList: React.FC = () => {const { t } = useTranslation();const api = useApi();const { showToast } = useToast();- const [, setLoading] = useState(false);+ const [savingRows, setSavingRows] = useState<Record<string, number>>({});+ const [newSessionRows, setNewSessionRows] = useState<Record<string, boolean>>({});const [usersByPlatform, setUsersByPlatform] = useState<Record<string, Record<string, UserConfig>>>({});const [config, setConfig] = useState<any>({});const [browsingCwdFor, setBrowsingCwdFor] = useState<string | null>(null);@@ -452,6 +454,7 @@ export const UserList: React.FC = () => {const [expandedKey, setExpandedKey] = useState<string | null>(null);const [refreshTrigger, setRefreshTrigger] = useState(0);const userSaveVersionRef = useRef<Record<string, number>>({});+ const routeSaveVersionRef = useRef<Record<string, number>>({});const enabledPlatforms = useMemo(() => getEnabledPlatforms(config), [config]);const vibeAgents = config.agent_catalog?.agents || [];@@ -521,18 +524,25 @@ export const UserList: React.FC = () => {// 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.+ // The row shows the save in progress; only a failure is announced.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);+ // The session note answers the latest route change, whatever else saved since.+ const routeVersion = 'routing' in change.changes ? (routeSaveVersionRef.current[rowKey] || 0) + 1 : null;+ if (routeVersion !== null) routeSaveVersionRef.current[rowKey] = routeVersion;+ setSavingRows((prev) => ({ ...prev, [rowKey]: (prev[rowKey] || 0) + 1 }));try {const result = await api.patchScopeSettings({ platform, scope: 'user', id: userId, ...change });- showToast(t('userList.settingsSaved'));+ if (routeVersion !== null && routeSaveVersionRef.current[rowKey] === routeVersion) {+ setNewSessionRows((prev) => ({ ...prev, [rowKey]: result.needs_new_session === true }));+ }const stored = result.settings as UserConfig | undefined;- if (stored && userSaveVersionRef.current[rowKey] === version) {+ if (userSaveVersionRef.current[rowKey] !== version) return;+ if (stored) {setUsersByPlatform((prev) => ({ ...prev, [platform]: { ...(prev[platform] || {}), [userId]: stored } }));}} catch {@@ -542,7 +552,7 @@ export const UserList: React.FC = () => {setUsersByPlatform((prev) => ({ ...prev, [platform]: result.users || {} }));}} finally {- setLoading(false);+ setSavingRows((prev) => ({ ...prev, [rowKey]: Math.max(0, (prev[rowKey] || 1) - 1) }));}};@@ -687,25 +697,14 @@ export const UserList: React.FC = () => {visibleUsers.map((u) => {const expanded = expandedKey === u.key;const userConfig = u.config;- const defaultAgent = agentByName[defaultAgentName || ''] || null;- const selectedAgent = agentByName[userConfig.routing?.agent_name || ''] || agentByName[defaultAgentName || ''];- const effectiveBackend = selectedAgent?.backend || defaultAgent?.backend || 'opencode';const isBot = !userConfig.is_admin && (userConfig.display_name || u.userId).toLowerCase().includes('bot');const tone = AVATAR_TONES[hashCode(u.userId) % AVATAR_TONES.length];const initials = getInitials(userConfig.display_name, u.userId);- const backendModel = userConfig.routing.model || (- effectiveBackend === 'claude'- ? userConfig.routing.claude_model- : effectiveBackend === 'codex'- ? userConfig.routing.codex_model- : userConfig.routing.opencode_model- );const displayName = displayNameForUser(u);const metaPrefix = userConfig.enabled- ? selectedAgent- ? `${selectedAgent.display_name || selectedAgent.name}${selectedAgent.model ? `/${selectedAgent.model}` : ''}`- : `${getBackendUiMeta(effectiveBackend).label}${backendModel ? `/${backendModel}` : ''}`+ ? scopeRouteSummary(userConfig.routing, agentByName, defaultAgentName, t): t('userList.disabled');+ const saving = (savingRows[u.key] || 0) > 0;const updateRow = (patch: Partial<UserConfig>) => updateUser(u.platform, u.userId, patch);const toggleEnabled = () => updateRow({ enabled: !userConfig.enabled });@@ -810,6 +809,10 @@ export const UserList: React.FC = () => {</span>)}+ {saving && (+ <Loader2 size={14} className="shrink-0 animate-spin text-muted" aria-label={t('common.saving')} />+ )}+{/* Chevron */}{expanded ? (<ChevronUp size={18} className="shrink-0 text-muted" />@@ -829,6 +832,8 @@ export const UserList: React.FC = () => {defaultAgentName={defaultAgentName}availableMessageTypes={availableMessageTypes(u.platform)}showRequireMention={false}+ saving={saving}+ routeNotice={newSessionRows[u.key] ? t('channelList.newSessionHint') : null}footerActions={<Buttontype="button"diff --git a/ui/src/components/steps/scopeRouteVisibility.test.tsx b/ui/src/components/steps/scopeRouteVisibility.test.tsxnew file mode 100644index 000000000..d579e9dd0--- /dev/null+++ b/ui/src/components/steps/scopeRouteVisibility.test.tsx@@ -0,0 +1,148 @@+// @vitest-environment jsdom+import { cleanup, render, screen, waitFor, within } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { MemoryRouter } from 'react-router-dom';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { ChannelList } from './ChannelList';+import { UserList } from './UserList';++// What a settings row tells the user about its route: the route the scope runs+// (its own model and effort over its Agent's), a save still in flight, and+// whether the conversation's current session keeps its previous Agent.++const api = vi.hoisted(() => ({+ getConfig: vi.fn(), getSettings: vi.fn(), slackChannels: vi.fn(),+ getUsers: vi.fn(), getBindCodes: vi.fn(), patchScopeSettings: vi.fn(),+}));+const toast = vi.hoisted(() => vi.fn());+vi.mock('@/context/ApiContext', async (loadOriginal) => ({+ ...await loadOriginal<typeof import('@/context/ApiContext')>(), useApi: () => api,+}));+vi.mock('@/context/InstanceAuthorizationContext', () => ({+ useInstanceAuthorization: () => ({ capabilities: { can_manage_access_members: true } }),+}));+vi.mock('@/context/ToastContext', () => ({ useToast: () => ({ showToast: toast }) }));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('../shared/RoutingConfigPanel', () => ({+ RoutingConfigPanel: ({ value, onChange, saving, routeNotice }: {+ value: { routing: object }; onChange: (patch: object) => void; saving?: boolean; routeNotice?: string | null;+ }) => (+ <div data-testid="panel" data-saving={saving ? 'yes' : 'no'}>+ {['vibey', 'reviewer'].map((agent) => (+ <button key={agent} type="button" onClick={() => onChange({ routing: { ...value.routing, agent_name: agent } })}>+ {`route:${agent}`}+ </button>+ ))}+ <button type="button" onClick={() => onChange({ show_message_types: ['assistant', 'toolcall'] })}>types</button>+ {routeNotice && <p>{routeNotice}</p>}+ </div>+ ),+}));++const agentCatalog = {+ default_agent_name: 'vibey',+ agents: [+ { name: 'vibey', display_name: 'vibey', backend: 'vibey', model: 'claude-sonnet-5-5', reasoning_effort: null },+ { name: 'reviewer', display_name: 'reviewer', backend: 'vibey', model: 'gpt-6-astra', reasoning_effort: 'low' },+ ],+};+const user = (routing: object) => ({+ display_name: 'Liu', is_admin: true, bound_at: '', enabled: true, show_message_types: ['assistant'],+ custom_cwd: null, routing, expected_agent_name: null,+});+const deferred = <T,>() => {+ let resolve!: (value: T) => void;+ let reject!: (error: unknown) => void;+ const promise = new Promise<T>((ok, fail) => { resolve = ok; reject = fail; });+ return { promise, resolve, reject };+};++afterEach(cleanup);+beforeEach(() => {+ vi.resetAllMocks();+ api.getBindCodes.mockResolvedValue({ ok: true, bind_codes: [] });+ api.getConfig.mockResolvedValue({ platform: 'lark', platforms: { enabled: ['lark'] } });+ api.getSettings.mockResolvedValue({ agent_catalog: agentCatalog });+});++function serveUsers(users: Record<string, object>) {+ api.getUsers.mockImplementation(async (platform) => ({ ok: true, users: platform === 'lark' ? users : {} }));+}++describe('users page rows', () => {+ it('shows the route each user runs, marking an inherited one', async () => {+ serveUsers({+ ou_default: { ...user({ agent_name: null, model: null, reasoning_effort: null }), display_name: 'Default' },+ ou_custom: { ...user({ agent_name: null, model: 'gpt-6-astra', reasoning_effort: 'high' }), display_name: 'Custom' },+ ou_agent: { ...user({ agent_name: 'reviewer', model: null, reasoning_effort: null }), display_name: 'Agent' },+ });+ render(<UserList />);++ expect(await screen.findByText('common.default · vibey/claude-sonnet-5-5 · ou_default')).toBeTruthy();+ expect(screen.getByText('vibey/gpt-6-astra · chat.picker.effortOptions.high · ou_custom')).toBeTruthy();+ expect(screen.getByText('reviewer/gpt-6-astra · chat.picker.effortOptions.low · ou_agent')).toBeTruthy();+ });++ it('shows a save on its row, announces only failures, and says when the session keeps its Agent', async () => {+ serveUsers({ ou_1: user({ agent_name: 'vibey', model: null, reasoning_effort: null }) });+ const pending = deferred<object>();+ api.patchScopeSettings.mockReturnValueOnce(pending.promise);+ render(<UserList />);+ await userEvent.click(await screen.findByText('Liu'));++ await userEvent.click(screen.getByText('route:reviewer'));+ expect(screen.getByTestId('panel').dataset.saving).toBe('yes');+ expect(screen.getByLabelText('common.saving')).toBeTruthy();+ pending.resolve({ ok: true, settings: user({ agent_name: 'reviewer' }), needs_new_session: true });++ expect(await screen.findByText('channelList.newSessionHint')).toBeTruthy();+ expect(screen.getByTestId('panel').dataset.saving).toBe('no');+ expect(toast).not.toHaveBeenCalled();++ api.patchScopeSettings.mockRejectedValueOnce(new Error('settings_conflict'));+ await userEvent.click(screen.getByText('route:vibey'));+ await waitFor(() => expect(toast).toHaveBeenCalledWith('userList.settingsSaveFailed', 'error'));+ });+ it('keeps the session note of a route change answered after a later edit of the same row', async () => {+ serveUsers({ ou_1: user({ agent_name: 'vibey', model: null, reasoning_effort: null }) });+ const route = deferred<object>();+ api.patchScopeSettings.mockReturnValueOnce(route.promise)+ .mockResolvedValueOnce({ ok: true, settings: { ...user({ agent_name: 'reviewer' }), show_message_types: ['assistant', 'toolcall'] } });+ render(<UserList />);+ await userEvent.click(await screen.findByText('Liu'));++ await userEvent.click(screen.getByText('route:reviewer'));+ await userEvent.click(screen.getByText('types'));+ await waitFor(() => expect(api.patchScopeSettings).toHaveBeenCalledTimes(2));+ route.resolve({ ok: true, settings: user({ agent_name: 'reviewer' }), needs_new_session: true });++ expect(await screen.findByText('channelList.newSessionHint')).toBeTruthy();+ });+});++describe('groups page rows', () => {+ beforeEach(() => {+ api.getConfig.mockResolvedValue({ platform: 'slack', platforms: { enabled: ['slack'] }, slack: { bot_token: 'xoxb-test' } });+ api.slackChannels.mockResolvedValue({ ok: true, channels: [{ id: 'C1', name: 'general' }] });+ });++ it('shows the route a group runs and keeps the notice off when the session follows the route', async () => {+ const channel = {+ enabled: true, show_message_types: ['assistant'], custom_cwd: null, require_mention: null, require_bind: null,+ routing: { agent_name: null, model: 'gpt-6-astra', reasoning_effort: null }, expected_agent_name: null,+ };+ api.getSettings.mockResolvedValue({ agent_catalog: agentCatalog, channels: { C1: channel } });+ api.patchScopeSettings.mockResolvedValue({+ ok: true, settings: { ...channel, routing: { agent_name: 'reviewer' } }, needs_new_session: false,+ });+ render(<MemoryRouter><ChannelList isPage /></MemoryRouter>);++ expect(await screen.findByText('vibey/gpt-6-astra · ID: C1')).toBeTruthy();+ await userEvent.click(screen.getByText('general'));+ await userEvent.click(within(screen.getByTestId('panel')).getByText('route:reviewer'));+ await waitFor(() => expect(api.patchScopeSettings).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(screen.getByTestId('panel').dataset.saving).toBe('no'));+ expect(screen.queryByText('channelList.newSessionHint')).toBeNull();+ expect(toast).not.toHaveBeenCalled();+ });+});diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 1b911dcd7..386b82a34 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -62,11 +62,15 @@ export type ScopeSettingsPatchRequest = ScopeSettingsChange & {};export type ScopeSettingsPatchResult = {ok: boolean;+ platform: string;scope: ScopeKind;id: string;thread_id?: string;/** The scope's stored row, in the shape the settings reads return it. */settings: unknown;+ /** After a routing change: whether the scope's current session keeps another+ * Agent until a new session starts there; null when that is unknown. */+ needs_new_session?: boolean | null;};// Global workbench toggles persisted server-side in state_meta. Currently justdiff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 98fa7c15c..2cde26280 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -3937,6 +3937,7 @@"topicIdLabel": "Topic ID: {{id}}","topicCustomBadge": "Custom","topicInheritedBadge": "Inherits group",+ "newSessionHint": "This conversation's current session keeps its previous Agent. Send /new there to start a new session with this route.","topicCustomize": "Customize","topicReset": "Use group settings","topicExpand": "Expand topic settings",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 522e06e36..9ec662433 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -3937,6 +3937,7 @@"topicIdLabel": "话题 ID:{{id}}","topicCustomBadge": "单独设置","topicInheritedBadge": "继承群组",+ "newSessionHint": "该对话当前的会话仍使用原来的 Agent,在对话里发送 /new 开始新会话后,新设置才会生效。","topicCustomize": "单独配置","topicReset": "恢复群组设置","topicExpand": "展开 Topic 设置",diff --git a/ui/src/lib/scopeRouteSummary.ts b/ui/src/lib/scopeRouteSummary.tsnew file mode 100644index 000000000..6ff243e3f--- /dev/null+++ b/ui/src/lib/scopeRouteSummary.ts@@ -0,0 +1,31 @@+import type { TFunction } from 'i18next';++type AgentLike = { name: string; display_name?: string | null; model?: string | null; reasoning_effort?: string | null };+type ScopeRouting = { agent_name?: string | null; model?: string | null; reasoning_effort?: string | null } | null | undefined;++/**+ * The route a channel, topic, or DM user actually runs, as one line for its settings row.+ *+ * A scope's own model and effort win over its Agent's, and a scope that names+ * none of them runs the default Agent as it is, which the line marks as the+ * default — the same reading the route picker shows when the row is expanded.+ */+export function scopeRouteSummary(+ routing: ScopeRouting,+ agentsByName: Record<string, AgentLike>,+ defaultAgentName: string | null | undefined,+ t: TFunction,+): string {+ const inherited = !routing?.agent_name && !routing?.model && !routing?.reasoning_effort;+ const agentName = routing?.agent_name || defaultAgentName || '';+ const agent = agentsByName[agentName];+ const model = routing?.model || agent?.model || '';+ const effort = routing?.reasoning_effort || agent?.reasoning_effort || '';+ const route = [agent?.display_name || agentName, model].filter(Boolean).join('/');+ const parts = [+ inherited ? t('common.default') : '',+ route,+ effort ? t(`chat.picker.effortOptions.${effort}`, { defaultValue: effort }) : '',+ ];+ return parts.filter(Boolean).join(' · ');+}diff --git a/vibe/api.py b/vibe/api.pyindex 64cf19a61..53e2ea016 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -5920,7 +5920,7 @@ def patch_scope_settings(payload: dict, *, user_context: Any = None) -> dict: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}+ result = {"ok": True, "platform": platform, "scope": kind, "id": native_id, "settings": settings_payload}if kind == "thread":result["thread_id"] = thread_idreturn resultdiff --git a/vibe/internal_client.py b/vibe/internal_client.pyindex f2bb51376..509c10ab4 100644--- a/vibe/internal_client.py+++ b/vibe/internal_client.py@@ -615,6 +615,38 @@ async def reconcile_platforms(return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}+async def scope_session_hint(+ *,+ platform: str,+ scope: str,+ native_id: str,+ thread_id: str = "",+ socket_path: Optional[Path] = None,+ timeout: float = 5.0,+) -> bool:+ """Ask the controller whether a scope's current session runs another Agent than its route."""++ endpoint = await _resolve_endpoint_async(socket_path)+ transport = _async_transport(endpoint)+ try:+ async with httpx.AsyncClient(+ transport=transport,+ base_url=endpoint.base_url,+ headers=endpoint.headers,+ timeout=httpx.Timeout(timeout, connect=2.0),+ ) as client:+ resp = await client.post(+ "/internal/scope-session-hint",+ json={"platform": platform, "scope": scope, "id": native_id, "thread_id": thread_id},+ )+ _validate_response(resp, endpoint)+ except _SOCKET_ERRORS as exc:+ raise InternalServerUnavailable(str(exc)) from exc+ if resp.status_code != 200:+ raise InternalServerUnavailable(f"scope session hint returned {resp.status_code}")+ return bool((resp.json() or {}).get("needs_new_session"))++async def invalidate_activity_streaming(*,socket_path: Optional[Path] = None,diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex fb711370d..bea053dc3 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -8092,6 +8092,22 @@ async def thread_settings_post(starlette_request: FastAPIRequest):return await _dispatch_native_ui_request(starlette_request, handler)+async def _scope_needs_new_session(result: dict) -> bool | None:+ """The controller's answer for the saved scope; None when it cannot answer now."""+ from vibe import internal_client++ try:+ return await internal_client.scope_session_hint(+ platform=str(result.get("platform") or ""),+ scope=str(result.get("scope") or ""),+ native_id=str(result.get("id") or ""),+ thread_id=str(result.get("thread_id") or ""),+ )+ except Exception as exc:+ logger.debug("Scope session hint unavailable: %s", exc)+ return None++@app.patch("/api/settings/scope", include_in_schema=False)async def scope_settings_patch(starlette_request: FastAPIRequest):async def handler():@@ -8100,13 +8116,14 @@ async def scope_settings_patch(starlette_request: FastAPIRequest):body = await starlette_request.body()payload = await starlette_request.json() if body else {}+ payload = payload if isinstance(payload, dict) 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,- )+ result = await asyncio.to_thread(api.patch_scope_settings, payload, user_context=user_context)+ changes = payload.get("changes")+ if isinstance(changes, dict) and "routing" in changes:+ result["needs_new_session"] = await _scope_needs_new_session(result)+ return resultexcept api.ScopeSettingsRequestError as exc:return _coded_error_response(exc.code, exc.message, exc.status)except StaleScopeAgentBindingError as exc: