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.

fix(ui): restore settings sidebar hierarchy (#1682)

Call White359ddb738a3a
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index 7b6c29e81..54616b485 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -2291,16 +2291,25 @@ def test_disabled_model_hub_rest_surface_returns_feature_disabled_without_runtim
assert supervisor_calls == []
[email protected]("method", ["get", "post"])
@pytest.mark.parametrize(("env_value", "expected"), [(None, False), ("0", False), ("1", True)])
-def test_config_capability_exactly_projects_backend_model_hub_gate(monkeypatch, env_value, expected):
+def test_config_capability_exactly_projects_backend_model_hub_gate(
+ monkeypatch, tmp_path, method, env_value, expected
+):
from config.v2_config import is_model_hub_enabled
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
if env_value is None:
monkeypatch.delenv("VIBE_MODEL_HUB_ENABLED", raising=False)
else:
monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", env_value)
- response = app.test_client().get("/api/config")
+ client = app.test_client()
+ response = (
+ client.get("/api/config")
+ if method == "get"
+ else client.post("/api/config", json={}, headers=csrf_headers(client))
+ )
assert response.status_code == 200
enabled = response.get_json()["capabilities"]["model_hub"]["enabled"]
diff --git a/ui/src/components/AppShell.test.tsx b/ui/src/components/AppShell.test.tsx
index 552891aa0..9992449db 100644
--- a/ui/src/components/AppShell.test.tsx
+++ b/ui/src/components/AppShell.test.tsx
@@ -1,7 +1,7 @@
/* @vitest-environment jsdom */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { cleanup, render, screen } from '@testing-library/react';
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, Route, Routes, useNavigate } from 'react-router-dom';
import type { ReactNode } from 'react';
@@ -39,6 +39,11 @@ const api = vi.hoisted(() => ({
}));
const status = vi.hoisted(() => ({ state: 'ready' as const }));
const inbox = vi.hoisted(() => ({ totalUnread: 0 }));
+const i18n = vi.hoisted(() => ({
+ language: 'en',
+ options: { resources: { en: {}, zh: {} } },
+ changeLanguage: vi.fn(),
+}));
const instanceAuth = vi.hoisted(() => ({
remote: true,
instanceKind: null as 'personal' | 'organization' | null,
@@ -97,11 +102,7 @@ vi.mock('./workbench/search/SearchPalette', () => ({ SearchPalette: () => null }
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string) => key,
- i18n: {
- language: 'en',
- options: { resources: { en: {}, zh: {} } },
- changeLanguage: vi.fn(),
- },
+ i18n,
}),
}));
@@ -112,6 +113,8 @@ beforeEach(() => {
instanceAuth.capabilities.can_manage_instance = true;
instanceAuth.capabilities.can_chat = true;
instanceAuth.capabilities.can_use_show_pages = true;
+ i18n.language = 'en';
+ i18n.changeLanguage.mockResolvedValue(undefined);
api.getConfig.mockResolvedValue({ platforms: { enabled: [] } });
api.getMemorySettings.mockResolvedValue({
status: 'failed',
@@ -226,11 +229,30 @@ describe('AppShell workbench sidebar', () => {
});
describe('AppShell persistent Workbench chrome', () => {
+ it('applies the instance language while Settings controls stay unmounted', async () => {
+ viewport.isDesktop = true;
+ api.getConfig.mockResolvedValue({ language: 'zh', platforms: { enabled: [] } });
+
+ render(
+ <MemoryRouter initialEntries={['/']}>
+ <Routes>
+ <Route element={<AppShell />}>
+ <Route index element={<div data-testid="workbench" />} />
+ </Route>
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ expect(await screen.findByTestId('workbench')).toBeTruthy();
+ expect(screen.queryByTestId('language-switcher')).toBeNull();
+ await waitFor(() => expect(i18n.changeLanguage).toHaveBeenCalledWith('zh'));
+ });
+
it.each([
'personal',
null,
'organization',
- ] as const)('keeps Settings and preferences in the Workbench sidebar for %s instances', async (instanceKind) => {
+ ] as const)('keeps Settings in the Workbench sidebar without preference controls for %s instances', async (instanceKind) => {
viewport.isDesktop = true;
instanceAuth.instanceKind = instanceKind;
@@ -248,12 +270,9 @@ describe('AppShell persistent Workbench chrome', () => {
expect(screen.getByRole('link', { name: 'appShell.openControlPanel' }).getAttribute('href')).toBe(
'/settings/replies',
);
- expect(screen.getByTestId('language-switcher')).toBeTruthy();
- expect(screen.getByTestId('theme-toggle')).toBeTruthy();
- expect(screen.getByTestId('account-menu')).toBeTruthy();
- const preferencesRow = screen.getByTestId('language-switcher').parentElement!;
- const appsRow = screen.getByTestId('apps-launcher').parentElement!;
- expect(preferencesRow.compareDocumentPosition(appsRow) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ expect(screen.queryByTestId('language-switcher')).toBeNull();
+ expect(screen.queryByTestId('theme-toggle')).toBeNull();
+ expect(screen.queryByTestId('account-menu')).toBeNull();
});
it('uses the Settings button to close an open Settings surface', async () => {
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index 28447e69f..1db8749cb 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -10,9 +10,6 @@ import { useApi } from '../context/ApiContext';
import { useStatus } from '../context/StatusContext';
import { useWorkbenchInbox } from '../context/WorkbenchInboxContext';
import { useInstanceAuthorization } from '../context/InstanceAuthorizationContext';
-import { AccountMenu } from './AccountMenu';
-import { LanguageSwitcher } from './LanguageSwitcher';
-import { ThemeToggle } from './ThemeToggle';
import { VersionBadge } from './VersionBadge';
import { WorkbenchSidebar } from './workbench/WorkbenchSidebar';
import { AppsLauncher } from './AppsLauncher';
@@ -159,7 +156,7 @@ const ConfigRecoveryNotice: React.FC<{ config: ConfigRecoveryProjection | null }
};
export const AppShell: React.FC = () => {
- const { t } = useTranslation();
+ const { t, i18n } = useTranslation();
const { status } = useStatus();
// Badge only — the shell is mounted on every route and renders no feed.
const { totalUnread } = useWorkbenchInbox({ feed: false });
@@ -201,8 +198,11 @@ export const AppShell: React.FC = () => {
if (!capabilities.can_manage_instance) return;
api.getConfig().then((c: any) => {
setConfig(c);
+ if (c.language && c.language !== i18n.language) {
+ void i18n.changeLanguage(c.language);
+ }
}).catch(() => {});
- }, [api, capabilities.can_manage_instance]);
+ }, [api, capabilities.can_manage_instance, i18n]);
// Global ⌘K / Ctrl+K toggles the message-search palette. Intercept the chord
// everywhere (it's a deliberate command, so it wins even from the composer);
@@ -389,18 +389,12 @@ export const AppShell: React.FC = () => {
{isDesktop && <WorkbenchSidebar onOpenSearch={() => setSearchOpen(true)} />}
</div>
- {/* Bottom (design.pen NbPMq): persistent preferences, Apps + Settings,
- then run state + version. The whole bottom cluster sits at the
+ {/* Bottom (design.pen NbPMq): Apps + Settings, then run state + version.
+ Preferences now live with the rest of Settings. The whole bottom cluster sits at the
sidebar's level (z-10) and is covered by a maximized window. The
outer container no longer owns padding (the brand band is flush to
the top edge), so this cluster carries its own px-4 + bottom pad. */}
<div className="relative flex flex-col gap-3 px-4 pb-4">
- <div className="flex items-center gap-2">
- <LanguageSwitcher openUpward />
- <ThemeToggle />
- <AccountMenu openUpward />
- </div>
-
<div className="flex items-stretch gap-2">
{canUseApps && <AppsLauncher />}
<Link
diff --git a/ui/src/components/LanguageSwitcher.test.tsx b/ui/src/components/LanguageSwitcher.test.tsx
index 6f0fe7230..b083b3a84 100644
--- a/ui/src/components/LanguageSwitcher.test.tsx
+++ b/ui/src/components/LanguageSwitcher.test.tsx
@@ -1,6 +1,6 @@
/* @vitest-environment jsdom */
-import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -51,10 +51,14 @@ describe('LanguageSwitcher role-aware persistence', () => {
expect(api.mutateConfig).not.toHaveBeenCalled();
});
- it('loads the instance default for an owner', async () => {
- api.getConfig.mockResolvedValue({ language: 'zh' });
+ it('persists an owner language change to the instance config', async () => {
+ const user = userEvent.setup();
render(<LanguageSwitcher />);
- await waitFor(() => expect(i18n.changeLanguage).toHaveBeenCalledWith('zh'));
+ await user.click(screen.getByRole('button', { name: 'language.en' }));
+ await user.click(screen.getByRole('option', { name: 'language.zh' }));
+
+ expect(i18n.changeLanguage).toHaveBeenCalledWith('zh');
+ expect(api.mutateConfig).toHaveBeenCalledOnce();
});
});
diff --git a/ui/src/components/LanguageSwitcher.tsx b/ui/src/components/LanguageSwitcher.tsx
index ba6d171cb..84c184e1a 100644
--- a/ui/src/components/LanguageSwitcher.tsx
+++ b/ui/src/components/LanguageSwitcher.tsx
@@ -8,26 +8,11 @@ import { setConfigField } from '../lib/configMutations';
export const LanguageSwitcher: React.FC<{ openUpward?: boolean }> = ({ openUpward = false }) => {
const { i18n, t } = useTranslation();
- const { getConfig, mutateConfig } = useApi();
+ const { mutateConfig } = useApi();
const { capabilities } = useInstanceAuthorization();
const [isOpen, setIsOpen] = useState(false);
const wrapRef = useRef<HTMLDivElement>(null);
- useEffect(() => {
- if (!capabilities.can_manage_instance) return;
- const loadConfig = async () => {
- try {
- const cfg = await getConfig();
- if (cfg.language && cfg.language !== i18n.language) {
- i18n.changeLanguage(cfg.language);
- }
- } catch {
- // Ignore errors on config load
- }
- };
- loadConfig();
- }, [capabilities.can_manage_instance, getConfig, i18n]);
-
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (wrapRef.current && !wrapRef.current.contains(event.target as Node)) {
diff --git a/ui/src/components/settings/SettingsLayout.test.tsx b/ui/src/components/settings/SettingsLayout.test.tsx
index 264d42838..5bb19319a 100644
--- a/ui/src/components/settings/SettingsLayout.test.tsx
+++ b/ui/src/components/settings/SettingsLayout.test.tsx
@@ -2,14 +2,23 @@
import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { MemoryRouter, Route, Routes } from 'react-router-dom';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter, Route, Routes, useNavigate } from 'react-router-dom';
import { SettingsLayout } from './SettingsLayout';
-const api = vi.hoisted(() => ({
- getConfig: vi.fn(),
- getMemorySettings: vi.fn(),
-}));
+const api = vi.hoisted(() => {
+ const configChangedHandlers = new Set<(config: unknown) => void>();
+ return {
+ configChangedHandlers,
+ getConfig: vi.fn(),
+ getMemorySettings: vi.fn(),
+ onConfigChanged: vi.fn((handler: (config: unknown) => void) => {
+ configChangedHandlers.add(handler);
+ return () => configChangedHandlers.delete(handler);
+ }),
+ };
+});
const authorization = vi.hoisted(() => ({
capabilities: { can_manage_instance: true },
}));
@@ -25,12 +34,45 @@ vi.mock('@/context/InstanceAuthorizationContext', () => ({
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
+vi.mock('../LanguageSwitcher', () => ({
+ LanguageSwitcher: ({ openUpward }: { openUpward?: boolean }) => (
+ <div data-testid="language-switcher" data-open-upward={String(openUpward)} />
+ ),
+}));
+vi.mock('../ThemeToggle', () => ({ ThemeToggle: () => <div data-testid="theme-toggle" /> }));
+vi.mock('../AccountMenu', () => ({
+ AccountMenu: ({ openUpward }: { openUpward?: boolean }) => (
+ <div data-testid="account-menu" data-open-upward={String(openUpward)} />
+ ),
+}));
+
+const NavigationProbe = () => {
+ const navigate = useNavigate();
+ return (
+ <div>
+ <button type="button" onClick={() => navigate('/settings/service')}>go-service</button>
+ <button type="button" onClick={() => navigate('/settings/platforms/groups')}>go-groups</button>
+ <button type="button" onClick={() => navigate(-1)}>go-back</button>
+ </div>
+ );
+};
+
+const SettingsLayoutHarness = () => (
+ <>
+ <SettingsLayout />
+ <NavigationProbe />
+ </>
+);
const renderLayout = (path: string) => render(
<MemoryRouter initialEntries={[path]}>
<Routes>
- <Route path="/settings" element={<SettingsLayout />}>
+ <Route path="/settings" element={<SettingsLayoutHarness />}>
<Route path="replies" element={<div>replies-body</div>} />
+ <Route path="service" element={<div>service-body</div>} />
+ <Route path="platforms" element={<div>platforms-body</div>} />
+ <Route path="platforms/users" element={<div>users-body</div>} />
+ <Route path="platforms/groups" element={<div>groups-body</div>} />
</Route>
</Routes>
</MemoryRouter>,
@@ -41,6 +83,7 @@ beforeEach(() => {
authorization.capabilities.can_manage_instance = true;
media.matches = false;
media.listeners.clear();
+ api.configChangedHandlers.clear();
api.getConfig.mockResolvedValue({ capabilities: { model_hub: { enabled: true } } });
api.getMemorySettings.mockResolvedValue({ status: 'ok', enabled: true });
vi.stubGlobal('matchMedia', vi.fn().mockReturnValue({
@@ -72,6 +115,105 @@ describe('SettingsLayout', () => {
});
});
+ it('opens Messaging Platforms by default and still allows manual collapse', async () => {
+ const user = userEvent.setup();
+ renderLayout('/settings/service');
+
+ const platforms = screen.getByRole('button', { name: 'nav.messagingPlatforms' });
+ expect(platforms.getAttribute('aria-expanded')).toBe('true');
+ expect(screen.getByRole('link', { name: 'settings.sections.platformConnections' })).toBeTruthy();
+ expect(screen.getByRole('link', { name: 'nav.users' })).toBeTruthy();
+ await waitFor(() => expect(screen.getByRole('link', { name: 'nav.channels' })).toBeTruthy());
+
+ await user.click(platforms);
+ expect(platforms.getAttribute('aria-expanded')).toBe('false');
+ expect(screen.queryByRole('link', { name: 'settings.sections.platformConnections' })).toBeNull();
+
+ await user.click(platforms);
+ expect(platforms.getAttribute('aria-expanded')).toBe('true');
+ });
+
+ it('auto-expands Platforms and selects the matching nested destination', async () => {
+ renderLayout('/settings/platforms/groups');
+
+ expect(screen.getByText('groups-body')).toBeTruthy();
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'nav.messagingPlatforms' }).getAttribute('aria-expanded')).toBe('true');
+ });
+ expect(screen.getByRole('link', { name: 'nav.channels' }).className).toContain('bg-mint/[0.09]');
+ expect(screen.getByRole('link', { name: 'settings.sections.platformConnections' }).className).not.toContain('bg-mint/[0.09]');
+ expect(screen.getByRole('link', { name: 'settings.sections.platformConnections' }).getAttribute('aria-current')).toBeNull();
+ });
+
+ it('hides Groups when no enabled platform supports group settings', async () => {
+ api.getConfig.mockResolvedValue({
+ capabilities: { model_hub: { enabled: true } },
+ platforms: { enabled: ['wechat'] },
+ });
+ renderLayout('/settings/replies');
+
+ expect(screen.getByRole('link', { name: 'settings.sections.platformConnections' })).toBeTruthy();
+ expect(screen.getByRole('link', { name: 'nav.users' })).toBeTruthy();
+ await waitFor(() => expect(screen.queryByRole('link', { name: 'nav.channels' })).toBeNull());
+ });
+
+ it('refreshes Groups visibility after successful platform config changes', async () => {
+ api.getConfig.mockResolvedValue({
+ capabilities: { model_hub: { enabled: true } },
+ platforms: { enabled: ['wechat'] },
+ });
+ renderLayout('/settings/replies');
+
+ await waitFor(() => expect(screen.queryByRole('link', { name: 'nav.channels' })).toBeNull());
+ expect(screen.getByRole('link', { name: 'settings.sections.models' })).toBeTruthy();
+
+ act(() => {
+ api.configChangedHandlers.forEach((handler) => handler({
+ capabilities: { model_hub: { enabled: true } },
+ platforms: { enabled: ['slack'] },
+ }));
+ });
+ expect(screen.getByRole('link', { name: 'nav.channels' })).toBeTruthy();
+ expect(screen.getByRole('link', { name: 'settings.sections.models' })).toBeTruthy();
+
+ act(() => {
+ api.configChangedHandlers.forEach((handler) => handler({
+ capabilities: { model_hub: { enabled: true } },
+ platforms: { enabled: ['wechat'] },
+ }));
+ });
+ expect(screen.queryByRole('link', { name: 'nav.channels' })).toBeNull();
+ expect(screen.getByRole('link', { name: 'settings.sections.models' })).toBeTruthy();
+ });
+
+ it('restores the default expanded disclosure after navigation', async () => {
+ const user = userEvent.setup();
+ renderLayout('/settings/replies');
+
+ expect(screen.getByRole('button', { name: 'nav.messagingPlatforms' }).getAttribute('aria-expanded')).toBe('true');
+ await user.click(screen.getByRole('button', { name: 'nav.messagingPlatforms' }));
+ expect(screen.getByRole('button', { name: 'nav.messagingPlatforms' }).getAttribute('aria-expanded')).toBe('false');
+ await user.click(screen.getByRole('button', { name: 'go-service' }));
+ await user.click(screen.getByRole('button', { name: 'go-back' }));
+ expect(screen.getByRole('button', { name: 'nav.messagingPlatforms' }).getAttribute('aria-expanded')).toBe('true');
+
+ await user.click(screen.getByRole('button', { name: 'go-groups' }));
+ expect(screen.getByRole('button', { name: 'nav.messagingPlatforms' }).getAttribute('aria-expanded')).toBe('true');
+ await user.click(screen.getByRole('button', { name: 'nav.messagingPlatforms' }));
+ expect(screen.getByRole('button', { name: 'nav.messagingPlatforms' }).getAttribute('aria-expanded')).toBe('false');
+ await user.click(screen.getByRole('button', { name: 'go-service' }));
+ await user.click(screen.getByRole('button', { name: 'go-back' }));
+ expect(screen.getByRole('button', { name: 'nav.messagingPlatforms' }).getAttribute('aria-expanded')).toBe('true');
+ });
+
+ it('keeps language, theme, and account preferences in the Settings rail', () => {
+ renderLayout('/settings/replies');
+
+ expect(screen.getByTestId('language-switcher').getAttribute('data-open-upward')).toBe('true');
+ expect(screen.getByTestId('theme-toggle')).toBeTruthy();
+ expect(screen.getByTestId('account-menu').getAttribute('data-open-upward')).toBe('true');
+ });
+
it('keeps member preferences, Replies, and Access while preserving the phase-2 permission gate', () => {
authorization.capabilities.can_manage_instance = false;
renderLayout('/settings/replies');
diff --git a/ui/src/components/settings/SettingsLayout.tsx b/ui/src/components/settings/SettingsLayout.tsx
index 9d2e1b88c..eb4b615d2 100644
--- a/ui/src/components/settings/SettingsLayout.tsx
+++ b/ui/src/components/settings/SettingsLayout.tsx
@@ -3,9 +3,12 @@ import { NavLink, Outlet, useLocation, useNavigate } from 'react-router-dom';
import {
Bot,
Brain,
+ ChevronDown,
ChevronLeft,
Cpu,
Globe,
+ Hash,
+ MessageCircle,
MessageSquare,
Package,
PlugZap,
@@ -22,7 +25,11 @@ import { useApi } from '@/context/ApiContext';
import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';
import { memoryNavShouldBeVisible } from '@/lib/memorySettings';
import { rememberSettingsPath, settingsLandingPath } from '@/lib/adminNavigation';
+import { getEnabledPlatforms, platformSupportsChannels } from '@/lib/platforms';
import { useIsDesktop } from '@/lib/useIsDesktop';
+import { AccountMenu } from '../AccountMenu';
+import { LanguageSwitcher } from '../LanguageSwitcher';
+import { ThemeToggle } from '../ThemeToggle';
import { modelHubEnabledFromConfig } from './models/featureFlags';
type SettingsItem = {
@@ -30,7 +37,10 @@ type SettingsItem = {
labelKey: string;
icon: React.ComponentType<{ className?: string }>;
ownerOnly?: boolean;
- feature?: 'models' | 'memory';
+ feature?: 'models' | 'memory' | 'channels';
+ children?: SettingsItem[];
+ defaultOpen?: boolean;
+ exact?: boolean;
};
type SettingsGroup = {
@@ -51,7 +61,28 @@ const SETTINGS_GROUPS: SettingsGroup[] = [
{
labelKey: 'settings.groups.connections',
items: [
- { path: '/settings/platforms', labelKey: 'settings.sections.platforms', icon: PlugZap, ownerOnly: true },
+ {
+ path: '/settings/platforms',
+ labelKey: 'nav.messagingPlatforms',
+ icon: PlugZap,
+ ownerOnly: true,
+ defaultOpen: true,
+ children: [
+ {
+ path: '/settings/platforms',
+ labelKey: 'settings.sections.platformConnections',
+ icon: PlugZap,
+ exact: true,
+ },
+ { path: '/settings/platforms/users', labelKey: 'nav.users', icon: MessageCircle },
+ {
+ path: '/settings/platforms/groups',
+ labelKey: 'nav.channels',
+ icon: Hash,
+ feature: 'channels',
+ },
+ ],
+ },
{ path: '/settings/remote-access', labelKey: 'settings.sections.remoteAccess', icon: Globe, ownerOnly: true },
],
},
@@ -69,6 +100,79 @@ const SETTINGS_GROUPS: SettingsGroup[] = [
const pathMatches = (pathname: string, itemPath: string): boolean =>
pathname === itemPath || pathname.startsWith(`${itemPath}/`);
+const itemMatches = (pathname: string, item: SettingsItem): boolean =>
+ item.exact ? pathname === item.path : pathMatches(pathname, item.path);
+
+const SettingsNavLink: React.FC<{ item: SettingsItem }> = ({ item }) => {
+ const { t } = useTranslation();
+ const location = useLocation();
+ const active = itemMatches(location.pathname, item);
+ const Icon = item.icon;
+
+ return (
+ <NavLink
+ to={item.path}
+ end={item.exact}
+ title={t(item.labelKey)}
+ className={clsx(
+ 'flex items-center gap-2 rounded-lg px-2 py-2 text-[12.5px] font-medium transition-colors',
+ 'md:justify-center lg:justify-start',
+ active
+ ? 'bg-mint/[0.09] text-foreground'
+ : 'text-muted hover:bg-foreground/[0.04] hover:text-foreground',
+ )}
+ >
+ <Icon className={clsx('size-4 shrink-0', active ? 'text-mint-ink' : 'text-muted')} />
+ <span className="truncate md:hidden lg:block">{t(item.labelKey)}</span>
+ </NavLink>
+ );
+};
+
+const SettingsNavGroup: React.FC<{ item: SettingsItem }> = ({ item }) => {
+ const { t } = useTranslation();
+ const location = useLocation();
+ const children = item.children ?? [];
+ const childActive = children.some((child) => itemMatches(location.pathname, child));
+ const [manualOpen, setManualOpen] = useState<boolean | null>(null);
+ const open = manualOpen ?? item.defaultOpen ?? childActive;
+ const Icon = item.icon;
+
+ return (
+ <div className="flex flex-col gap-0.5">
+ <button
+ type="button"
+ title={t(item.labelKey)}
+ aria-expanded={open}
+ onClick={() => setManualOpen(!open)}
+ className={clsx(
+ 'flex w-full items-center gap-2 rounded-lg px-2 py-2 text-[12.5px] font-medium transition-colors',
+ 'md:justify-center lg:justify-start',
+ childActive
+ ? 'text-foreground'
+ : 'text-muted hover:bg-foreground/[0.04] hover:text-foreground',
+ )}
+ >
+ <Icon className={clsx('size-4 shrink-0', childActive ? 'text-mint-ink' : 'text-muted')} />
+ <span className="min-w-0 flex-1 truncate text-left md:hidden lg:block">{t(item.labelKey)}</span>
+ <ChevronDown
+ className={clsx(
+ 'size-3.5 shrink-0 text-muted transition-transform md:hidden lg:block',
+ open && 'rotate-180',
+ )}
+ />
+ </button>
+ {open && (
+ <div className="ml-3 flex flex-col gap-0.5 border-l border-border pl-2 md:ml-0 md:border-l-0 md:pl-0 lg:ml-3 lg:border-l lg:pl-2">
+ {children.map((child) => <SettingsNavLink key={child.path} item={child} />)}
+ </div>
+ )}
+ </div>
+ );
+};
+
+const SettingsNavItem: React.FC<{ item: SettingsItem }> = ({ item }) =>
+ item.children?.length ? <SettingsNavGroup item={item} /> : <SettingsNavLink item={item} />;
+
export const SettingsLayout: React.FC = () => {
const { t } = useTranslation();
const api = useApi();
@@ -78,12 +182,25 @@ export const SettingsLayout: React.FC = () => {
const isDesktop = useIsDesktop();
const [modelHubVisible, setModelHubVisible] = useState(false);
const [memoryVisible, setMemoryVisible] = useState(false);
+ const [channelSettingsVisible, setChannelSettingsVisible] = useState(false);
const atRoot = location.pathname === '/settings' || location.pathname === '/settings/';
useEffect(() => {
if (!capabilities.can_manage_instance) return;
let cancelled = false;
let memoryRequest = 0;
+ let configVersion = 0;
+ const applyConfigVisibility = (config: unknown) => {
+ setModelHubVisible(modelHubEnabledFromConfig(config));
+ setChannelSettingsVisible(
+ getEnabledPlatforms(config).some((platform) => platformSupportsChannels(config, platform)),
+ );
+ };
+ const stopConfigChanges = api.onConfigChanged((config) => {
+ if (cancelled) return;
+ configVersion += 1;
+ applyConfigVisibility(config);
+ });
const refreshMemoryVisibility = () => {
const request = ++memoryRequest;
void api.getMemorySettings()
@@ -96,17 +213,22 @@ export const SettingsLayout: React.FC = () => {
if (!cancelled && request === memoryRequest) setMemoryVisible(false);
});
};
+ const requestedConfigVersion = configVersion;
void api.getConfig()
.then((config) => {
- if (!cancelled) setModelHubVisible(modelHubEnabledFromConfig(config));
+ if (!cancelled && requestedConfigVersion === configVersion) applyConfigVisibility(config);
})
.catch(() => {
- if (!cancelled) setModelHubVisible(false);
+ if (!cancelled && requestedConfigVersion === configVersion) {
+ setModelHubVisible(false);
+ setChannelSettingsVisible(false);
+ }
});
refreshMemoryVisibility();
window.addEventListener('avibe:memory-settings-changed', refreshMemoryVisibility);
return () => {
cancelled = true;
+ stopConfigChanges();
window.removeEventListener('avibe:memory-settings-changed', refreshMemoryVisibility);
};
}, [api, capabilities.can_manage_instance]);
@@ -114,16 +236,31 @@ export const SettingsLayout: React.FC = () => {
const visibleGroups = useMemo(
() => SETTINGS_GROUPS.map((group) => ({
...group,
- items: group.items.filter((item) => {
- if (item.ownerOnly && !capabilities.can_manage_instance) return false;
- if (item.feature === 'models') return modelHubVisible;
- if (item.feature === 'memory') return memoryVisible;
- return true;
+ items: group.items.flatMap((item) => {
+ if (item.ownerOnly && !capabilities.can_manage_instance) return [];
+ if (item.feature === 'models' && !modelHubVisible) return [];
+ if (item.feature === 'memory' && !memoryVisible) return [];
+ return [{
+ ...item,
+ children: item.children?.filter((child) =>
+ child.feature !== 'channels' || channelSettingsVisible),
+ }];
}),
})).filter((group) => group.items.length > 0),
- [capabilities.can_manage_instance, memoryVisible, modelHubVisible],
+ [capabilities.can_manage_instance, channelSettingsVisible, memoryVisible, modelHubVisible],
);
+ const activeTrail = useMemo(() => {
+ for (const group of visibleGroups) {
+ for (const item of group.items) {
+ const child = item.children?.find((candidate) => itemMatches(location.pathname, candidate));
+ if (child) return [item, child];
+ if (pathMatches(location.pathname, item.path)) return [item];
+ }
+ }
+ return [];
+ }, [location.pathname, visibleGroups]);
+
useEffect(() => {
if (atRoot || !location.pathname.startsWith('/settings/')) return;
rememberSettingsPath(location.pathname);
@@ -144,10 +281,7 @@ export const SettingsLayout: React.FC = () => {
<>
<span className="text-border-strong">/</span>
<span className="truncate font-normal text-muted">
- {t(
- visibleGroups.flatMap((group) => group.items)
- .find((item) => pathMatches(location.pathname, item.path))?.labelKey ?? 'nav.settings',
- )}
+ {activeTrail.map((item) => t(item.labelKey)).join(' / ') || t('nav.settings')}
</span>
</>
)}
@@ -165,43 +299,35 @@ export const SettingsLayout: React.FC = () => {
<nav
aria-label={t('settings.navigationLabel')}
className={clsx(
- 'min-h-0 shrink-0 overflow-y-auto border-r border-border bg-surface/70 px-2 pb-[calc(0.75rem+env(safe-area-inset-bottom))] pt-3 md:pb-3',
- 'w-full md:flex md:w-14 md:flex-col lg:w-[196px]',
- !atRoot && 'hidden',
+ 'min-h-0 shrink-0 border-r border-border bg-surface/70 px-2 pb-[calc(0.75rem+env(safe-area-inset-bottom))] pt-3 md:pb-3',
+ 'w-full flex-col md:w-14 lg:w-[196px]',
+ atRoot ? 'flex' : 'hidden md:flex',
)}
>
- {visibleGroups.map((group) => (
- <div key={group.labelKey} className="mb-2 last:mb-0">
- <div className="px-2 pb-1 pt-1 font-mono text-[9px] font-bold uppercase tracking-[0.16em] text-muted md:hidden lg:block">
- {t(group.labelKey)}
- </div>
- <div className="flex flex-col gap-0.5">
- {group.items.map((item) => {
- const Icon = item.icon;
- return (
- <NavLink
- key={item.path}
- to={item.path}
- title={t(item.labelKey)}
- className={({ isActive }) => clsx(
- 'flex items-center gap-2 rounded-lg px-2 py-2 text-[12.5px] font-medium transition-colors',
- 'md:justify-center lg:justify-start',
- isActive || pathMatches(location.pathname, item.path)
- ? 'bg-mint/[0.09] text-foreground'
- : 'text-muted hover:bg-foreground/[0.04] hover:text-foreground',
- )}
- >
- <Icon className={clsx(
- 'size-4 shrink-0',
- pathMatches(location.pathname, item.path) ? 'text-mint-ink' : 'text-muted',
- )} />
- <span className="truncate md:hidden lg:block">{t(item.labelKey)}</span>
- </NavLink>
- );
- })}
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ {visibleGroups.map((group) => (
+ <div key={group.labelKey} className="mb-2 last:mb-0">
+ <div className="px-2 pb-1 pt-1 font-mono text-[9px] font-bold uppercase tracking-[0.16em] text-muted md:hidden lg:block">
+ {t(group.labelKey)}
+ </div>
+ <div className="flex flex-col gap-0.5">
+ {/* A manual disclosure choice belongs to this route visit only. */}
+ {group.items.map((item) => (
+ <SettingsNavItem
+ key={item.children?.length ? `${item.path}:${location.pathname}` : item.path}
+ item={item}
+ />
+ ))}
+ </div>
</div>
- </div>
- ))}
+ ))}
+ </div>
+
+ <div className="mt-3 flex shrink-0 items-center gap-2 border-t border-border px-2 pt-3 md:flex-col lg:flex-row">
+ <LanguageSwitcher openUpward />
+ <ThemeToggle />
+ <AccountMenu openUpward />
+ </div>
</nav>
<section className={clsx('min-w-0 flex-1 overflow-y-auto', atRoot && 'hidden md:block')}>
diff --git a/ui/src/context/ApiContext.configChanges.test.tsx b/ui/src/context/ApiContext.configChanges.test.tsx
new file mode 100644
index 000000000..e36458cdb
--- /dev/null
+++ b/ui/src/context/ApiContext.configChanges.test.tsx
@@ -0,0 +1,82 @@
+/* @vitest-environment jsdom */
+
+import { useEffect } from 'react';
+import { cleanup, render, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const apiFetch = vi.hoisted(() => vi.fn());
+
+vi.mock('../lib/apiFetch', () => ({ apiFetch }));
+vi.mock('./ToastContext', () => ({ useToast: () => ({ showToast: vi.fn() }) }));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+import { setConfigField } from '../lib/configMutations';
+import { ApiProvider, useApi } from './ApiContext';
+
+let capturedApi: ReturnType<typeof useApi> | null = null;
+
+const CaptureApi = () => {
+ const api = useApi();
+ useEffect(() => {
+ capturedApi = api;
+ }, [api]);
+ return null;
+};
+
+const response = (payload: unknown, status = 200) => new Response(JSON.stringify(payload), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+});
+
+beforeEach(() => {
+ capturedApi = null;
+ apiFetch.mockReset();
+});
+
+afterEach(() => {
+ cleanup();
+});
+
+describe('ApiProvider config convergence', () => {
+ it('invalidates a cached config read after a successful mutation', async () => {
+ render(<ApiProvider><CaptureApi /></ApiProvider>);
+ await waitFor(() => expect(capturedApi).not.toBeNull());
+
+ apiFetch
+ .mockResolvedValueOnce(response({ language: 'en' }))
+ .mockResolvedValueOnce(response({ language: 'zh' }))
+ .mockResolvedValueOnce(response({ language: 'zh' }));
+
+ await expect(capturedApi!.getConfig()).resolves.toEqual({ language: 'en' });
+ await capturedApi!.mutateConfig([setConfigField(['language'], 'zh')]);
+ await expect(capturedApi!.getConfig()).resolves.toEqual({ language: 'zh' });
+
+ expect(apiFetch.mock.calls.map(([path]) => path)).toEqual([
+ '/api/config',
+ '/api/config',
+ '/api/config',
+ ]);
+ });
+
+ it('publishes the saved config after a successful mutation', async () => {
+ render(<ApiProvider><CaptureApi /></ApiProvider>);
+ await waitFor(() => expect(capturedApi).not.toBeNull());
+
+ const changed = vi.fn();
+ const stop = capturedApi!.onConfigChanged(changed);
+ const savedConfig = { language: 'zh', platforms: { enabled: ['slack'] } };
+ apiFetch.mockResolvedValueOnce(response(savedConfig));
+
+ await expect(capturedApi!.mutateConfig([setConfigField(['language'], 'zh')]))
+ .resolves.toEqual(savedConfig);
+ expect(changed).toHaveBeenCalledOnce();
+ expect(changed).toHaveBeenCalledWith(savedConfig);
+
+ stop();
+ apiFetch.mockResolvedValueOnce(response({ ...savedConfig, language: 'en' }));
+ await capturedApi!.mutateConfig([setConfigField(['language'], 'en')]);
+ expect(changed).toHaveBeenCalledOnce();
+ });
+});
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 2849a52e4..6c3283726 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -513,6 +513,7 @@ export type ApiContextType = {
getConfig: () => Promise<any>;
getPlatformCatalog: () => Promise<any>;
mutateConfig: (mutations: readonly ConfigMutation[]) => Promise<any>;
+ onConfigChanged: (handler: (config: unknown) => void) => () => void;
getSettings: (platform?: string) => Promise<any>;
saveSettings: (payload: any, platform?: string) => Promise<any>;
saveThreadSettings: (platform: string, channelId: string, threadId: string, settings: any) => Promise<any>;
@@ -2651,6 +2652,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
const { showToast } = useToast();
const { t } = useTranslation();
const readCacheRef = useRef(new Map<string, { expiresAt: number; promise: Promise<any> }>());
+ const configChangedHandlersRef = useRef(new Set<(config: unknown) => void>());
const eventSourceRef = useRef<EventSource | null>(null);
const eventHandlersRef = useRef(new Set<WorkbenchEventHandlers>());
const eventConnectionRef = useRef<{ sub_id: number; source?: 'browser' | 'controller' } | null>(null);
@@ -2761,6 +2763,23 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
};
};
+ const onConfigChanged = (handler: (config: unknown) => void) => {
+ configChangedHandlersRef.current.add(handler);
+ return () => {
+ configChangedHandlersRef.current.delete(handler);
+ };
+ };
+
+ const convergeConfig = (config: unknown) => {
+ for (const handler of Array.from(configChangedHandlersRef.current)) {
+ try {
+ handler(config);
+ } catch (err) {
+ console.error('[API] config-changed subscriber failed', err);
+ }
+ }
+ };
+
const getJson = async (
path: string,
{ handleError = true, expectedCodes }: { handleError?: boolean; expectedCodes?: readonly string[] } = {},
@@ -3598,7 +3617,12 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
const value: ApiContextType = useMemo(() => ({
getConfig: () => getCachedJson('/api/config', CONFIG_CACHE_TTL_MS),
getPlatformCatalog: () => getJson('/api/platforms'),
- mutateConfig: (mutations) => postJson('/api/config', configMutationsToPayload(mutations)),
+ mutateConfig: async (mutations) => {
+ const config = await postJson('/api/config', configMutationsToPayload(mutations));
+ convergeConfig(config);
+ return config;
+ },
+ onConfigChanged,
getSettings: (platform) => getJson(platform ? `/api/settings?platform=${encodeURIComponent(platform)}` : '/api/settings'),
saveSettings: (payload, platform) => postJson('/api/settings', platform ? { ...payload, platform } : payload),
saveThreadSettings: (platform, channelId, threadId, settings) => postJson('/api/settings/thread', {
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 6d7bd4edb..ca9606544 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -279,6 +279,7 @@
"memory": "Memory",
"replies": "Replies",
"platforms": "Platforms",
+ "platformConnections": "Platform Connections",
"remoteAccess": "Remote Access",
"service": "Service",
"dependencies": "Dependencies",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index fe363b97a..86ce1e1d1 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -279,6 +279,7 @@
"memory": "记忆",
"replies": "回复",
"platforms": "通讯平台",
+ "platformConnections": "平台接入",
"remoteAccess": "远程访问",
"service": "服务",
"dependencies": "依赖",
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index b6f41efc9..172a1ae8c 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -4445,8 +4445,6 @@ def doctor_get():
@app.route("/api/config", methods=["GET"])
def config_get():
- from vibe import api
- from config.v2_config import is_model_hub_enabled
from core.services import settings as settings_service
# On a truly fresh install no config file exists yet, but the setup
@@ -4457,8 +4455,7 @@ def config_get():
# (``save_config``) already creates the file on the first real save.
config = settings_service.load_config_or_default()
authorization_context = getattr(g, "authorization_context", None)
- payload = _config_payload_for_context(config, authorization_context)
- payload["capabilities"] = {"model_hub": {"enabled": is_model_hub_enabled()}}
+ payload = _config_api_payload_for_context(config, authorization_context)
return jsonify(payload)
@@ -4472,6 +4469,16 @@ def _config_payload_for_context(config: Any, authorization_context: Any) -> dict
return api.non_owner_config_payload(config)
+def _config_api_payload_for_context(config: Any, authorization_context: Any) -> dict[str, Any]:
+ """Return the complete payload exposed by the config API."""
+
+ from config.v2_config import is_model_hub_enabled
+
+ payload = _config_payload_for_context(config, authorization_context)
+ payload["capabilities"] = {"model_hub": {"enabled": is_model_hub_enabled()}}
+ return payload
+
+
_MODEL_HUB_SERVICE = None
@@ -6760,7 +6767,7 @@ async def config_post():
else:
agent_backend_runtime["apply_on_next_start"] = True
authorization_context = getattr(g, "authorization_context", None)
- response_payload = _config_payload_for_context(config, authorization_context)
+ response_payload = _config_api_payload_for_context(config, authorization_context)
if remote_access_runtime is not None:
response_payload["remote_access_runtime"] = remote_access_runtime
if platform_runtime is not None: