Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(settings): keep scope Agent binding tokens current across autosaves (#3045)
Call White2ff70e94f804
diff --git a/storage/settings_service.py b/storage/settings_service.pyindex f16459979..c75b1df01 100644--- a/storage/settings_service.py+++ b/storage/settings_service.py@@ -393,14 +393,17 @@ class SQLiteSettingsService:current = conn.execute(select(scope_settings.c.agent_name).where(scope_settings.c.scope_id == scope_id)).scalar_one_or_none()+ if item.routing.agent_name == current:+ # Writing back the stored binding cannot overwrite another writer's+ # change, so an outdated token alone is not a conflict.+ return item.routingif current == expected:- if item.routing.agent_name != current:- canonical_agent_name = SQLiteSettingsService._require_enabled_agent_binding(- conn,- item.routing.agent_name,- )- if canonical_agent_name != item.routing.agent_name:- return replace(item.routing, agent_name=canonical_agent_name)+ canonical_agent_name = SQLiteSettingsService._require_enabled_agent_binding(+ conn,+ item.routing.agent_name,+ )+ if canonical_agent_name != item.routing.agent_name:+ return replace(item.routing, agent_name=canonical_agent_name)return item.routingif item.routing.agent_name == expected:return replace(item.routing, agent_name=current)diff --git a/tests/test_sqlite_settings_store.py b/tests/test_sqlite_settings_store.pyindex 6295f765f..c91ed5e7e 100644--- a/tests/test_sqlite_settings_store.py+++ b/tests/test_sqlite_settings_store.py@@ -817,6 +817,52 @@ def test_client_binding_expectation_survives_server_reload_before_scope_save(tmpagent_store.close()+def test_outdated_binding_token_conflicts_only_when_the_agent_would_change(tmp_path: Path) -> None:+ # A settings form opened while the user was unbound keeps sending its load-time+ # token after its own autosave bound an Agent; follow-up edits must still save.+ settings_path = tmp_path / "settings.json"+ store = SettingsStore(settings_path)+ agent_store = VibeAgentStore(tmp_path / "vibe.sqlite")+ try:+ agent_store.create(name="pm", backend="claude")+ agent_store.create(name="qa", backend="claude")+ store.update_user("U1", UserSettings(display_name="Pat"), platform="lark")+ store.update_user(+ "U1",+ UserSettings(display_name="Pat", routing=RoutingSettings(agent_name="pm"), _agent_name_at_load=None),+ platform="lark",+ )++ same_agent = UserSettings(+ display_name="Pat",+ routing=RoutingSettings(agent_name="pm", model="follow-up-model"),+ _agent_name_at_load=None,+ )+ store.set_users_for_platform("lark", {"U1": same_agent})+ store.save()++ other_agent = UserSettings(+ display_name="Pat",+ routing=RoutingSettings(agent_name="qa"),+ _agent_name_at_load=None,+ )+ store.set_users_for_platform("lark", {"U1": other_agent})+ with pytest.raises(StaleScopeAgentBindingError) as conflict:+ store.save()+ assert conflict.value.scope_id == "lark::user::U1"++ with agent_store.engine.connect() as conn:+ stored = conn.execute(+ select(scope_settings.c.agent_name, scope_settings.c.model).where(+ scope_settings.c.scope_id == "lark::user::U1"+ )+ ).one()+ assert tuple(stored) == ("pm", "follow-up-model")+ finally:+ store.close()+ agent_store.close()++def test_settings_save_rejects_new_archived_binding_but_preserves_existing(tmp_path: Path) -> None:settings_path = tmp_path / "settings.json"store = SettingsStore(settings_path)diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsxindex 3b5a918c7..aca723983 100644--- a/ui/src/components/steps/ChannelList.tsx+++ b/ui/src/components/steps/ChannelList.tsx@@ -147,6 +147,8 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBconst refreshFollowupVersionRef = useRef(0);const channelRequestVersionRef = useRef(0);const allPlatformsRequestVersionRef = useRef(0);+ const channelSaveVersionRef = useRef<Record<string, number>>({});+ const currentPlatformRef = useRef<string>('');// Directory browser state — tracks which channel's cwd picker is openconst [browsingCwdFor, setBrowsingCwdFor] = useState<string | null>(null);// Page-mode tab/search/collapse state (only used when isPage is true)@@ -285,6 +287,9 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBconst platform = isWizardMultiPlatform? wizardActivePlatform: (forcedPlatform || pagePlatform || config.platform || data.platform || 'slack');+ useEffect(() => {+ currentPlatformRef.current = platform;+ }, [platform]);const channelPlatforms = getEnabledPlatforms(config).filter((p) => platformSupportsChannels(config, p));const knownDiscordGuilds = [...guilds,@@ -738,12 +743,24 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBsetConfigs(nextPlatformConfigs);}if (!isPage) return;+ const version = (channelSaveVersionRef.current[platformId] || 0) + 1;+ channelSaveVersionRef.current[platformId] = version;+ let stored: Record<string, ChannelConfig> | null;try {- await api.saveSettings({ channels: nextPlatformConfigs }, platformId);+ const result = await api.saveSettings({ channels: nextPlatformConfigs }, platformId);+ stored = result?.channels || null;showToast(t('channelList.settingsSaved'));} catch {showToast(t('channelList.settingsSaveFailed'), 'error');+ const settings = await api.getSettings(platformId).catch(() => null);+ stored = settings ? settings.channels || {} : null;}+ // Adopt the stored rows so each routing keeps the expected_agent_name read+ // with it; a newer save on this platform owns the state instead.+ if (!stored || channelSaveVersionRef.current[platformId] !== version) return;+ const latest = stored;+ setAllConfigsByPlatform((prev) => ({ ...prev, [platformId]: latest }));+ if (currentPlatformRef.current === platformId) setConfigs(latest);};const saveTelegramTopicConfig = async (diff --git a/ui/src/components/steps/UserList.tsx b/ui/src/components/steps/UserList.tsxindex e2ec1b4b7..cc18e6a7f 100644--- a/ui/src/components/steps/UserList.tsx+++ b/ui/src/components/steps/UserList.tsx@@ -1,7 +1,7 @@import { platformText } from '@/lib/platforms';import type { TFunction } from 'i18next';import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';-import React, { useEffect, useMemo, useState } from 'react';+import React, { useEffect, useMemo, useRef, useState } from 'react';import {Bot,Check,@@ -450,6 +450,7 @@ export const UserList: React.FC = () => {const [showDisabled, setShowDisabled] = useState(false);const [expandedKey, setExpandedKey] = useState<string | null>(null);const [refreshTrigger, setRefreshTrigger] = useState(0);+ const userSaveVersionRef = useRef<Record<string, number>>({});const enabledPlatforms = useMemo(() => getEnabledPlatforms(config), [config]);const vibeAgents = config.agent_catalog?.agents || [];@@ -518,15 +519,26 @@ export const UserList: React.FC = () => {}, [aggregated, searchQuery, showDisabled]);const persistUsers = async (platform: string, next: Record<string, Partial<UserConfig>>) => {+ const version = (userSaveVersionRef.current[platform] || 0) + 1;+ userSaveVersionRef.current[platform] = version;setLoading(true);+ let stored: Record<string, UserConfig> | null;try {- await api.saveUsers({ users: next }, platform);+ const result = await api.saveUsers({ users: next }, platform);+ stored = result?.users || null;showToast(t('userList.settingsSaved'));} catch {showToast(t('userList.settingsSaveFailed'), 'error');+ const result = await api.getUsers(platform).catch(() => null);+ stored = result?.ok ? result.users || {} : null;} finally {setLoading(false);}+ // Adopt the stored rows so each routing keeps the expected_agent_name read+ // with it; a newer save on this platform owns the state instead.+ if (!stored || userSaveVersionRef.current[platform] !== version) return;+ const latest = stored;+ setUsersByPlatform((prev) => ({ ...prev, [platform]: latest }));};const updateUser = (platform: string, userId: string, patch: Partial<UserConfig>) => {diff --git a/ui/src/components/steps/scopeRoutingSave.test.tsx b/ui/src/components/steps/scopeRoutingSave.test.tsxnew file mode 100644index 000000000..18a02a9de--- /dev/null+++ b/ui/src/components/steps/scopeRoutingSave.test.tsx@@ -0,0 +1,134 @@+// @vitest-environment jsdom+import { cleanup, render, screen, waitFor } 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';++// Each scope save carries expected_agent_name, the Agent binding the form last read.+// The server refuses a binding change whose token is outdated, so after every save+// attempt the page must hold the stored row, keeping routing and token read together.++const api = vi.hoisted(() => ({+ getConfig: vi.fn(), getSettings: vi.fn(), saveSettings: vi.fn(), slackChannels: vi.fn(),+ getUsers: vi.fn(), saveUsers: vi.fn(), getBindCodes: vi.fn(),+}));+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: vi.fn() }) }));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('../shared/RoutingConfigPanel', () => ({+ RoutingConfigPanel: ({ value, onChange }: { value: { routing: object }; onChange: (patch: object) => void }) => (+ <>+ {['vibey', 'reviewer'].map((agent) => (+ <button key={agent} type="button" onClick={() => onChange({ routing: { ...value.routing, agent_name: agent } })}>+ {`route:${agent}`}+ </button>+ ))}+ </>+ ),+}));++const agentCatalog = { default_agent_name: 'vibey', agents: [{ name: 'vibey', backend: 'vibey' }, { name: 'reviewer', backend: 'vibey' }] };+const scope = (agent: string | null) => ({+ display_name: 'Liu', is_admin: true, bound_at: '', enabled: true, show_message_types: ['assistant'], custom_cwd: null,+ require_mention: null, require_bind: null, routing: { agent_name: agent }, expected_agent_name: agent,+});+/** The server stores the posted rows and reports each row's binding as its new token. */+const stored = (rows: Record<string, { routing: { agent_name: string | null } }>) => Object.fromEntries(+ Object.entries(rows).map(([id, row]) => [id, { ...row, expected_agent_name: row.routing.agent_name }]),+);++afterEach(cleanup);+beforeEach(() => {+ vi.clearAllMocks();+ api.getBindCodes.mockResolvedValue({ ok: true, bind_codes: [] });+});++const savedToken = (call: unknown[], kind: 'users' | 'channels', id: string) =>+ (call[0] as Record<string, Record<string, { expected_agent_name: string | null }>>)[kind][id].expected_agent_name;++describe('users page', () => {+ beforeEach(() => {+ api.getConfig.mockResolvedValue({ platform: 'lark', platforms: { enabled: ['lark'] } });+ api.getSettings.mockResolvedValue({ agent_catalog: agentCatalog });+ serveUsers(null);+ });++ /** Lark is the only enabled platform; the page reads others before its config loads. */+ function serveUsers(agent: string | null) {+ api.getUsers.mockImplementation(async (platform) => ({ ok: true, users: platform === 'lark' ? { ou_1: scope(agent) } : {} }));+ }+ const larkReads = () => api.getUsers.mock.calls.filter(([platform]) => platform === 'lark').length;++ async function openUser() {+ render(<UserList />);+ await waitFor(() => expect(larkReads()).toBe(1));+ await userEvent.click(await screen.findByText('Liu'));+ }++ it('sends the stored token after its own save changed the binding', async () => {+ api.saveUsers.mockImplementation(async (payload) => ({ ok: true, users: stored(payload.users) }));+ await openUser();+ await userEvent.click(screen.getByText('route:vibey'));+ await waitFor(() => expect(api.saveUsers).toHaveBeenCalledTimes(1));+ await userEvent.click(screen.getByText('route:reviewer'));+ await waitFor(() => expect(api.saveUsers).toHaveBeenCalledTimes(2));+ expect(savedToken(api.saveUsers.mock.calls[0], 'users', 'ou_1')).toBeNull();+ expect(savedToken(api.saveUsers.mock.calls[1], 'users', 'ou_1')).toBe('vibey');+ });++ it('reloads the stored rows after a refused save', async () => {+ api.saveUsers.mockRejectedValueOnce(new Error('settings_conflict'))+ .mockImplementation(async (payload) => ({ ok: true, users: stored(payload.users) }));+ await openUser();+ serveUsers('vibey');+ await userEvent.click(screen.getByText('route:reviewer'));+ await waitFor(() => expect(larkReads()).toBe(2));+ await userEvent.click(screen.getByText('route:reviewer'));+ await waitFor(() => expect(api.saveUsers).toHaveBeenCalledTimes(2));+ expect(savedToken(api.saveUsers.mock.calls[1], 'users', 'ou_1')).toBe('vibey');+ });+});++describe('channels page', () => {+ beforeEach(() => {+ api.getConfig.mockResolvedValue({ platform: 'slack', platforms: { enabled: ['slack'] }, slack: { bot_token: 'xoxb-test' } });+ api.getSettings.mockResolvedValue({ agent_catalog: agentCatalog, channels: { C1: { ...scope(null), enabled: true } } });+ api.slackChannels.mockResolvedValue({ ok: true, channels: [{ id: 'C1', name: 'general' }] });+ });++ async function openChannel() {+ render(<MemoryRouter><ChannelList isPage /></MemoryRouter>);+ await userEvent.click(await screen.findByText('general'));+ }++ it('sends the stored token after its own save changed the binding', async () => {+ api.saveSettings.mockImplementation(async (payload) => ({ channels: stored(payload.channels) }));+ await openChannel();+ await userEvent.click(screen.getByText('route:vibey'));+ await waitFor(() => expect(api.saveSettings).toHaveBeenCalledTimes(1));+ await userEvent.click(screen.getByText('route:reviewer'));+ await waitFor(() => expect(api.saveSettings).toHaveBeenCalledTimes(2));+ expect(savedToken(api.saveSettings.mock.calls[0], 'channels', 'C1')).toBeNull();+ expect(savedToken(api.saveSettings.mock.calls[1], 'channels', 'C1')).toBe('vibey');+ });++ it('reloads the stored rows after a refused save', async () => {+ api.saveSettings.mockRejectedValueOnce(new Error('settings_conflict'))+ .mockImplementation(async (payload) => ({ channels: stored(payload.channels) }));+ await openChannel();+ const reads = api.getSettings.mock.calls.length;+ api.getSettings.mockResolvedValue({ agent_catalog: agentCatalog, channels: { C1: { ...scope('vibey'), enabled: true } } });+ await userEvent.click(screen.getByText('route:reviewer'));+ await waitFor(() => expect(api.getSettings.mock.calls.length).toBeGreaterThan(reads));+ await userEvent.click(screen.getByText('route:reviewer'));+ await waitFor(() => expect(api.saveSettings).toHaveBeenCalledTimes(2));+ expect(savedToken(api.saveSettings.mock.calls[1], 'channels', 'C1')).toBe('vibey');+ });+});