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(ui): the default Agent says why it cannot be a Bot, and a Bot write is read once (#3126)
Call Whitedff9146dc5d7
diff --git a/ui/e2e/workbench-general/bots.spec.ts b/ui/e2e/workbench-general/bots.spec.tsindex 695c4faa1..7c51f96e8 100644--- a/ui/e2e/workbench-general/bots.spec.ts+++ b/ui/e2e/workbench-general/bots.spec.ts@@ -477,3 +477,34 @@ for (const theme of ['light', 'dark'] as const) {expect(denied).toEqual([]);});}++test('the default Agent is offered as a Bot nowhere, and both ways in say what to do first', async ({ page }) => {+ const { denied } = await serveBots(page, 'en', [MAIN, CSO, PM]);+ // The user made their own Agent the default; the server refuses it as a Bot+ // (`bot_agent_default`) until another Agent is the default.+ const auditor = AGENTS[2];+ await page.route(+ (url) => url.pathname === '/api/agents',+ (route) => route.fulfill({ json: { ok: true, agents: AGENTS, default_agent_name: auditor.name } }),+ );+ await page.route(`**/api/agents/${auditor.name}`, (route) => route.fulfill({ json: {+ ok: true,+ agent: { ...auditor, display_name: auditor.name, archived_at: null, updated_at: ago(60), system_prompt: null, metadata: {}, created_at: ago(600) },+ } }));+ await page.setViewportSize(DESKTOP);+ const reason = 'It is the default Agent. Make another Agent the default first, then set it as a Bot.';++ await open(page, '/agents', { lang: 'en', theme: 'light' });+ await page.getByRole('button', { name: /^security-auditor/ }).click();+ await expect(page.getByText(reason)).toBeVisible();+ await expect(page.getByRole('button', { name: 'Set as Bot' })).toBeDisabled();++ await sidebarOf(page).getByRole('button', { name: 'Add a Bot' }).click();+ const dialog = page.getByRole('dialog', { name: 'Add a Bot' });+ await dialog.getByRole('radio', { name: 'From an existing Agent' }).click();+ const choice = dialog.getByRole('radiogroup', { name: 'From an existing Agent' }).getByRole('radio', { name: /security-auditor/ });+ await expect(choice).toBeDisabled();+ await expect(choice).toContainText(reason);+ await expect(dialog.getByRole('button', { name: 'Set as Bot' })).toBeDisabled();+ expect(denied).toEqual([]);+});diff --git a/ui/src/components/workbench/AgentsPage.tsx b/ui/src/components/workbench/AgentsPage.tsxindex 8a8b6b829..e7d6bcde9 100644--- a/ui/src/components/workbench/AgentsPage.tsx+++ b/ui/src/components/workbench/AgentsPage.tsx@@ -281,7 +281,7 @@ export const AgentsPage: React.FC = () => {tRef.current = t;const api = useApi();const { showToast } = useToast();- const { refresh: refreshBots } = useBots();+ const { afterWrite: afterBotWrite } = useBots();const {capabilities,} = useInstanceAuthorization();@@ -1353,10 +1353,9 @@ export const AgentsPage: React.FC = () => {let mutationSettled = false;try {const result = await api.updateVibeAgent(name, patch);- // A Bot's role is its Agent's description (docs/plans/bots.md D1), and an- // Agent write publishes no Bot event: read the Bots again so the strip, its- // card, and Edit profile show what was saved.- if (result.ok && isBot && 'description' in patch) void refreshBots();+ // A Bot's role is its Agent's description (docs/plans/bots.md D1): the strip,+ // its card, and Edit profile show what was saved once the Bots are read again.+ if (result.ok && isBot && 'description' in patch) void afterBotWrite();const settled = await settleSelectedMutation(operation, result.ok ? undefined : result);mutationSettled = true;if (!settled.ok) throw settled.error;@@ -2406,7 +2405,7 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, ca</Button></div>- <AgentBotCard agent={agent} canEdit={canEdit} />+ <AgentBotCard agent={agent} canEdit={canEdit} isDefault={isDefault} />{/* Enable toggle — design.pen EWTY7 */}<div@@ -2803,8 +2802,9 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, ca// The Agent's Bot side (docs/plans/bots.md D1, D5): who it is as a Bot, with the// way into its conversation, or — for an eligible Vibey Agent — "Set as Bot",// which opens the add dialog's existing-Agent tab. Bots are the Owner's, so the-// card is absent for everyone else.-const AgentBotCard: React.FC<{ agent: VibeAgentFull; canEdit: boolean }> = ({ agent, canEdit }) => {+// card is absent for everyone else. The default Agent keeps the card, unavailable,+// with what to do first: the server refuses it until another Agent is the default.+const AgentBotCard: React.FC<{ agent: VibeAgentFull; canEdit: boolean; isDefault: boolean }> = ({ agent, canEdit, isDefault }) => {const { t } = useTranslation();const navigate = useNavigate();const { enabled, botForAgent, displayName, openProfile } = useBots();@@ -2841,19 +2841,20 @@ const AgentBotCard: React.FC<{ agent: VibeAgentFull; canEdit: boolean }> = ({ ag}// Disabled Agents still show the way in, with what to do first.if (!canEdit || !eligibleForBot({ ...agent, enabled: true })) return null;+ const blocker = isDefault+ ? t('bots.notForDefaultAgent')+ : agent.enabled ? null : t('bots.agents.setAsBotNeedsEnabled');return (<div className="flex items-center justify-between gap-3 rounded-[10px] border border-border-strong bg-surface-2 px-3.5 py-3"><div className="flex min-w-0 flex-col gap-0.5"><span className="text-[13px] font-bold text-foreground">{t('bots.agents.setAsBot')}</span>- <span className="text-[11px] text-muted">- {agent.enabled ? t('bots.agents.setAsBotHint') : t('bots.agents.setAsBotNeedsEnabled')}- </span>+ <span className="text-[11px] text-muted">{blocker ?? t('bots.agents.setAsBotHint')}</span></div><Buttontype="button"variant="outline"size="xs"- disabled={!agent.enabled}+ disabled={blocker !== null}onClick={() => openProfile({ kind: 'create', tab: 'agent', agentName: agent.name })}>{t('bots.agents.setAsBot')}diff --git a/ui/src/components/workbench/bots/BotProfileDialog.tsx b/ui/src/components/workbench/bots/BotProfileDialog.tsxindex 769063d95..451cf0f71 100644--- a/ui/src/components/workbench/bots/BotProfileDialog.tsx+++ b/ui/src/components/workbench/bots/BotProfileDialog.tsx@@ -65,10 +65,11 @@ const BotProfileForm: React.FC<{ request: BotProfileRequest; onClose: () => voidconst api = useApi();const navigate = useNavigate();const { showToast } = useToast();- const { mainBot, botForHandle, displayName, refresh } = useBots();+ const { mainBot, botForHandle, displayName, afterWrite } = useBots();const editing = request.kind === 'edit' ? botForHandle(request.handle) ?? null : null;const [tab, setTab] = useState<'new' | 'agent'>(request.kind === 'create' ? request.tab ?? 'new' : 'new');const [agents, setAgents] = useState<VibeAgentBrief[] | null>(null);+ const [defaultAgentName, setDefaultAgentName] = useState<string | null>(null);const [agentName, setAgentName] = useState<string | null>(request.kind === 'create' ? request.agentName ?? null : null);const [name, setName] = useState(editing?.display_name ?? '');const [role, setRole] = useState(editing?.role ?? '');@@ -89,14 +90,18 @@ const BotProfileForm: React.FC<{ request: BotProfileRequest; onClose: () => void[agents, mainBot],);const eligibleAgents = useMemo(() => (agents ?? []).filter(eligibleForBot), [agents]);- const pickedAgent = eligibleAgents.find((agent) => agent.name === agentName) ?? null;+ // The default Agent is listed but cannot be picked: the server refuses it until+ // another Agent is the default, so the row says so instead of failing on submit.+ const pickedAgent = eligibleAgents.find((agent) => agent.name === agentName && agent.name !== defaultAgentName) ?? null;useEffect(() => {let live = true;api.listVibeAgents({ cache: false }).then((result) => {- if (live) setAgents(result.agents ?? []);+ if (!live) return;+ setAgents(result.agents ?? []);+ setDefaultAgentName(result.default_agent_name ?? null);}).catch(() => {if (live) setAgents([]);@@ -213,7 +218,7 @@ const BotProfileForm: React.FC<{ request: BotProfileRequest; onClose: () => voidif (!editing.builtin && role.trim() !== editing.role.trim()) {await api.updateVibeAgent(editing.agent_name, { description: role.trim() || null });}- await refresh();+ await afterWrite();onClose();return;}@@ -224,7 +229,7 @@ const BotProfileForm: React.FC<{ request: BotProfileRequest; onClose: () => void}let bot = await api.setBot({ agent_name: pickedAgent.name, display_name: trimmedName, avatar: emojiInput });bot = await uploadAvatar(bot);- await refresh();+ await afterWrite();onClose();navigate(botSessionPath(bot));return;@@ -262,7 +267,7 @@ const BotProfileForm: React.FC<{ request: BotProfileRequest; onClose: () => void...(route ? { model: route.model, reasoning_effort: route.reasoning_effort } : {}),});bot = await uploadAvatar(bot);- await refresh();+ await afterWrite();onClose();navigate(botSessionPath(bot));} catch (err) {@@ -411,17 +416,22 @@ const BotProfileForm: React.FC<{ request: BotProfileRequest; onClose: () => void) : (<div className="flex max-h-[180px] flex-col gap-1.5 overflow-y-auto" role="radiogroup" aria-label={t('bots.dialog.tabFromAgent')}>{eligibleAgents.map((agent) => {- const picked = agent.name === agentName;+ const unavailable = agent.name === defaultAgentName;+ const picked = !unavailable && agent.name === agentName;+ const note = unavailable ? t('bots.notForDefaultAgent') : agent.description;return (<buttonkey={agent.id}type="button"role="radio"aria-checked={picked}+ disabled={unavailable}onClick={() => setAgentName(agent.name)}className={clsx('flex items-center gap-2.5 rounded-lg border px-3 py-2 text-left transition',- picked ? 'border-mint bg-mint-soft' : 'border-border hover:bg-foreground/[0.03]',+ unavailable+ ? 'cursor-not-allowed border-border opacity-60'+ : picked ? 'border-mint bg-mint-soft' : 'border-border hover:bg-foreground/[0.03]',)}><span className={clsx('grid size-4 shrink-0 place-items-center rounded-full border', picked ? 'border-mint' : 'border-border-strong')}>@@ -430,7 +440,7 @@ const BotProfileForm: React.FC<{ request: BotProfileRequest; onClose: () => void<BotIcon className="size-4 shrink-0 text-muted" /><span className="min-w-0 flex-1 leading-tight"><span className="block truncate font-mono text-[12px] font-semibold text-foreground">{agent.name}</span>- {agent.description && <span className="block truncate text-[11px] text-muted">{agent.description}</span>}+ {note && <span className={clsx('block text-[11px] text-muted', !unavailable && 'truncate')}>{note}</span>}</span></button>);diff --git a/ui/src/components/workbench/bots/BotStrip.tsx b/ui/src/components/workbench/bots/BotStrip.tsxindex b5692f5e8..5963066ce 100644--- a/ui/src/components/workbench/bots/BotStrip.tsx+++ b/ui/src/components/workbench/bots/BotStrip.tsx@@ -209,7 +209,7 @@ const BotSlot: React.FC<BotSlotProps & { drag?: SlotDrag }> = ({ bot, name, unreconst navigate = useNavigate();const location = useLocation();const { showToast } = useToast();- const { openProfile, refresh } = useBots();+ const { openProfile, afterWrite } = useBots();const authorizeRouteAction = useUnsavedChangesActionGuard();const path = botSessionPath(bot);const selected = location.pathname === path;@@ -298,7 +298,7 @@ const BotSlot: React.FC<BotSlotProps & { drag?: SlotDrag }> = ({ bot, name, unre} catch (err) {showToast(errorMessage(err) || t('bots.removeFailed'), 'error');} finally {- void refresh();+ void afterWrite();}};diff --git a/ui/src/context/BotsContext.ts b/ui/src/context/BotsContext.tsindex d0a584c39..1691df940 100644--- a/ui/src/context/BotsContext.ts+++ b/ui/src/context/BotsContext.ts@@ -27,7 +27,10 @@ export interface BotsState {botForHandle: (handle: string | null | undefined) => Bot | undefined;/** The name a Bot goes by, with the main Bot's localized default. */displayName: (bot: Bot) => string;- refresh: () => Promise<void>;+ /** Call after this page writes a Bot or a Bot's Agent. Every such write+ * publishes `bots.changed` once it commits, and that event is the one refetch;+ * only while the event stream is not live does this read the list itself. */+ afterWrite: () => Promise<void>;/** Move a Bot (not the main one) to `position` (1-based among the others),* optimistically; resolves false when the server refused it. */moveBot: (handle: string, position: number) => Promise<boolean>;@@ -50,7 +53,7 @@ const EMPTY: BotsState = {botForAgent: () => undefined,botForHandle: () => undefined,displayName: (bot) => bot.display_name || bot.handle,- refresh: async () => undefined,+ afterWrite: async () => undefined,moveBot: async () => false,openProfile: () => undefined,profileRequest: null,diff --git a/ui/src/context/BotsProvider.test.tsx b/ui/src/context/BotsProvider.test.tsxnew file mode 100644index 000000000..50bf36c0f--- /dev/null+++ b/ui/src/context/BotsProvider.test.tsx@@ -0,0 +1,121 @@+// @vitest-environment jsdom++import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';+import { useEffect, useRef } from 'react';+import { MemoryRouter } from 'react-router-dom';+import { afterEach, describe, expect, it, vi } from 'vitest';++import type { WorkbenchEventHandlers } from './ApiContext';+import { BotsProvider } from './BotsProvider';+import { useBots } from './BotsContext';+import { InstanceAuthorizationContext } from './InstanceAuthorizationContext';+import { ToastContext } from './ToastContext';+import { BotProfileDialogHost } from '../components/workbench/bots/BotProfileDialog';+import type { Bot } from '../lib/bots';+import { DENIED_INSTANCE_CAPABILITIES } from '../lib/sessionInfo';+import type { WorkbenchEventConnectionState } from '../lib/workbenchEventConnection';++vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));++const apiRef = { current: null as unknown };+vi.mock('./ApiContext', async () => {+ const actual = await vi.importActual<typeof import('./ApiContext')>('./ApiContext');+ return { ...actual, useApi: () => apiRef.current };+});++const MAIN: Bot = {+ handle: 'main', display_name: '', avatar: { kind: 'mascot' }, role: 'First point of contact',+ agent_name: 'main', session_id: 'ses_main', position: 0, builtin: true,+};+const CSO: Bot = {+ handle: 'cso', display_name: 'Security Lead', avatar: null, role: 'Audits',+ agent_name: 'cso', session_id: 'ses_cso', position: 1, builtin: false,+};++function fakeApi() {+ const stream: { handlers: WorkbenchEventHandlers | null } = { handlers: null };+ const api = {+ listBots: vi.fn(async () => [MAIN, CSO]),+ getSession: vi.fn(async () => ({ agent_status: 'idle' })),+ listVibeAgents: vi.fn(async () => ({ ok: true, agents: [], default_agent_name: null })),+ updateBot: vi.fn(async (_handle: string, patch: { display_name?: string }) => ({ ...CSO, ...patch })),+ connectWorkbenchEvents: vi.fn((handlers: WorkbenchEventHandlers) => {+ stream.handlers = handlers;+ return () => {+ stream.handlers = null;+ };+ }),+ };+ return { api, stream };+}++const OpenEdit = () => {+ const { loaded, openProfile } = useBots();+ const opened = useRef(false);+ useEffect(() => {+ if (!loaded || opened.current) return;+ opened.current = true;+ openProfile({ kind: 'edit', handle: 'cso' });+ }, [loaded, openProfile]);+ return null;+};++async function flush() {+ await act(async () => {+ for (let i = 0; i < 5; i += 1) await Promise.resolve();+ });+}++afterEach(() => {+ cleanup();+ apiRef.current = null;+});++// A Bot write from this page reaches the list through the server's `bots.changed`+// once it commits. With the stream live that event is the one refetch, so a save+// from the dialog reads `GET /api/bots` once, not once for the save and again for+// the event. Without a live stream nothing else would read it, so the write does.+describe('saving a Bot from the dialog reads the Bots once', () => {+ it.each<[WorkbenchEventConnectionState, number]>([+ ['connected', 1],+ ['reconnecting', 1],+ ])('with the event stream %s', async (state, expectedReads) => {+ const { api, stream } = fakeApi();+ apiRef.current = api;+ render(+ <MemoryRouter>+ <ToastContext.Provider value={{ showToast: () => undefined }}>+ <InstanceAuthorizationContext.Provider+ value={{+ remote: false,+ instanceKind: null,+ instanceRole: null,+ capabilities: { ...DENIED_INSTANCE_CAPABILITIES, is_instance_owner: true },+ }}+ >+ <BotsProvider>+ <OpenEdit />+ <BotProfileDialogHost />+ </BotsProvider>+ </InstanceAuthorizationContext.Provider>+ </ToastContext.Provider>+ </MemoryRouter>,+ );+ await flush();+ act(() => stream.handlers?.onConnectionState?.(state));+ const name = await screen.findByDisplayValue('Security Lead');+ const readsBefore = api.listBots.mock.calls.length;++ fireEvent.change(name, { target: { value: 'Security Chief' } });+ fireEvent.click(screen.getByRole('button', { name: 'bots.dialog.save' }));+ await flush();+ expect(api.updateBot).toHaveBeenCalledWith('cso', { display_name: 'Security Chief' });+ // The server publishes the write; a live stream delivers it.+ if (state === 'connected') {+ act(() => stream.handlers?.onBotsChanged?.({ handle: 'cso' }));+ await flush();+ }++ expect(api.listBots.mock.calls.length - readsBefore).toBe(expectedReads);+ });+});diff --git a/ui/src/context/BotsProvider.tsx b/ui/src/context/BotsProvider.tsxindex 89ebb3f77..738dd185b 100644--- a/ui/src/context/BotsProvider.tsx+++ b/ui/src/context/BotsProvider.tsx@@ -10,7 +10,9 @@ import { botDisplayName, orderBots, type Bot } from '../lib/bots';/** Owns the Owner's Bot list (`GET /api/bots`) and each Bot Session's running state.** The list is refetched on `bots.changed` and on every stream (re)connect, since- * the broker replays nothing. Unread counts are not here: they come from the+ * the broker replays nothing. That event is also how this page's own writes+ * arrive: `afterWrite` reads the list itself only while the stream is not live,+ * so a write is never read twice. Unread counts are not here: they come from the* Inbox's per-session map by Session id, as the plan's Web API says. Running state* is read once per Bot Session and then kept by `session.status` frames. */export const BotsProvider = ({ children }: { children: ReactNode }) => {@@ -24,6 +26,7 @@ export const BotsProvider = ({ children }: { children: ReactNode }) => {const [profileRequest, setProfileRequest] = useState<BotProfileRequest | null>(null);const readRef = useRef(0);const sessionIdsRef = useRef<Set<string>>(new Set());+ const streamLiveRef = useRef(false);const readStatuses = useCallback(async (sessionIds: string[]) => {@@ -62,6 +65,10 @@ export const BotsProvider = ({ children }: { children: ReactNode }) => {}}, [api, enabled, readStatuses]);+ const afterWrite = useCallback(async () => {+ if (!streamLiveRef.current) await refresh();+ }, [refresh]);+useEffect(() => {if (!enabled) {// A reader who is not the Owner gets nothing (the value below withholds@@ -73,7 +80,10 @@ export const BotsProvider = ({ children }: { children: ReactNode }) => {// The first read does not wait for the stream: a stream that never connects// must not leave the Owner without Bots.queueMicrotask(() => void refresh());- return api.connectWorkbenchEvents({+ const disconnect = api.connectWorkbenchEvents({+ onConnectionState: (state) => {+ streamLiveRef.current = state === 'connected';+ },onConnected: () => {// Nothing replays the gap: re-read the list and every Bot's status.void refresh().then(() => readStatuses([...sessionIdsRef.current]));@@ -90,6 +100,10 @@ export const BotsProvider = ({ children }: { children: ReactNode }) => {setStatusBySession((prev) => (prev[sessionId] === 'running' ? prev : { ...prev, [sessionId]: 'running' }));},});+ return () => {+ streamLiveRef.current = false;+ disconnect();+ };}, [api, enabled, refresh, readStatuses]);const moveBot = useCallback(@@ -111,10 +125,10 @@ export const BotsProvider = ({ children }: { children: ReactNode }) => {setBots(previous);return false;} finally {- void refresh();+ void afterWrite();}},- [api, ownerBots, refresh],+ [api, ownerBots, afterWrite],);const mainDefault = t('bots.mainDefaultName');@@ -134,7 +148,7 @@ export const BotsProvider = ({ children }: { children: ReactNode }) => {botForAgent: (agentName) => (agentName ? byAgent.get(agentName) : undefined),botForHandle: (handle) => (handle ? byHandle.get(handle) : undefined),displayName: (bot) => botDisplayName(bot, mainDefault),- refresh,+ afterWrite,moveBot,openProfile: (request) => {if (enabled) setProfileRequest(request);@@ -142,7 +156,7 @@ export const BotsProvider = ({ children }: { children: ReactNode }) => {profileRequest: enabled ? profileRequest : null,closeProfile: () => setProfileRequest(null),};- }, [enabled, ownerBots, loaded, ownerStatuses, mainDefault, refresh, moveBot, profileRequest]);+ }, [enabled, ownerBots, loaded, ownerStatuses, mainDefault, afterWrite, moveBot, profileRequest]);return <BotsContext.Provider value={value}>{children}</BotsContext.Provider>;};diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 48fb664cf..1f1594373 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -4682,6 +4682,7 @@"reorderPosition": "{{name}}, position {{position}} of {{count}}.","reorderDropped": "Dropped {{name}}.","reorderCancelled": "Reordering cancelled.",+ "notForDefaultAgent": "It is the default Agent. Make another Agent the default first, then set it as a Bot.","menu": {"label": "{{name}} actions","editProfile": "Edit profile",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 3b2cb6e53..6c10ae0df 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -4682,6 +4682,7 @@"reorderPosition": "{{name}},第 {{position}} 位,共 {{count}} 位。","reorderDropped": "已放下{{name}}。","reorderCancelled": "已取消调整顺序。",+ "notForDefaultAgent": "它是默认 Agent,先把默认换成别的 Agent 才能设为伙伴。","menu": {"label": "{{name}}的操作","editProfile": "编辑资料",