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(ui): Bots in the Web UI: strip, add dialog, conversations, typed mentions (#3121)
Call Whitec21933427c4c
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.ymlindex 57f992d13..1b4b349f2 100644--- a/.github/workflows/lint.yml+++ b/.github/workflows/lint.yml@@ -238,7 +238,7 @@ jobs:suites: |npm run test:project-ordernpm run test:inbox-return- npm run test:workbench-general -- sidebar-floating.spec.ts desktop-window-chrome.spec.ts composer-route-trigger.spec.ts skills-dialog.spec.ts+ npm run test:workbench-general -- sidebar-floating.spec.ts desktop-window-chrome.spec.ts composer-route-trigger.spec.ts skills-dialog.spec.ts bots.spec.tsnpm run test:chat-interactionsnpm run test:pdf-previewsteps:diff --git a/ui/e2e/workbench-general/bots.spec.ts b/ui/e2e/workbench-general/bots.spec.tsnew file mode 100644index 000000000..a175b7e84--- /dev/null+++ b/ui/e2e/workbench-general/bots.spec.ts@@ -0,0 +1,458 @@+import { expect, test, type Page } from '@playwright/test';++import { DESKTOP, open, serveProduct, type Lang } from './support';++// The Bots surfaces (docs/plans/bots.md D3, D5) against a hermetic fixture: the+// strip in the Inbox's old place with the Inbox as the brand row's icon, the+// hover card and context menu, the add dialog, a Bot's conversation, Bot rows in+// the Inbox. The typed `@<bot:handle>` marker is MentionEditor's own unit test.++const SHOTS = 'e2e/.artifacts/workbench-general/shots';++type FixtureBot = {+ handle: string;+ display_name: string;+ avatar: { kind: 'mascot' } | { kind: 'emoji'; emoji: string; hue: number } | null;+ role: string;+ running?: boolean;+};++const MAIN: FixtureBot = { handle: 'main', display_name: '', avatar: { kind: 'mascot' }, role: "The user's main Bot and first point of contact." };+const CSO: FixtureBot = { handle: 'cso', display_name: '首席安全官', avatar: { kind: 'emoji', emoji: '🛡️', hue: 200 }, role: '依赖与权限的安全审计,每周汇报' };+const PM: FixtureBot = { handle: 'pm', display_name: 'Product Lead', avatar: { kind: 'emoji', emoji: '🧭', hue: 42 }, role: 'Owns the backlog and its priorities', running: true };+const EXTRA: FixtureBot[] = [+ { handle: 'finance', display_name: '财务助理', avatar: null, role: '账单、报销与预算' },+ { handle: 'designer', display_name: 'Designer', avatar: { kind: 'emoji', emoji: '🎨', hue: 330 }, role: 'Interface and visual design' },+ { handle: 'research', display_name: '市场研究员', avatar: { kind: 'emoji', emoji: '🔭', hue: 265 }, role: '竞品与市场动态' },+];++const payload = (bot: FixtureBot, position: number) => ({+ handle: bot.handle,+ display_name: bot.display_name,+ avatar: bot.avatar,+ role: bot.role,+ agent_name: bot.handle,+ session_id: `ses_${bot.handle}`,+ position,+ builtin: bot.handle === 'main',+});++const AGENTS = [+ { id: 'agt-main', name: 'main', backend: 'vibey', enabled: true, archived: false, source: 'builtin', model: 'gpt-6-astra', reasoning_effort: 'high', description: MAIN.role, bot: { handle: 'main', display_name: '', builtin: true } },+ { id: 'agt-vibey', name: 'vibey', backend: 'vibey', enabled: true, archived: false, source: 'builtin', model: 'gpt-6-astra', reasoning_effort: 'high', description: 'Default Agent for the Vibey backend.', bot: null },+ { id: 'agt-auditor', name: 'security-auditor', backend: 'vibey', enabled: true, archived: false, source: 'user', model: 'gpt-6-astra', reasoning_effort: 'medium', description: 'Dependency and permission audits', bot: null },+ { id: 'agt-cso', name: 'cso', backend: 'vibey', enabled: true, archived: false, source: 'user', model: 'gpt-6-astra', reasoning_effort: 'medium', description: CSO.role, bot: { handle: 'cso', display_name: CSO.display_name, builtin: false } },+ { id: 'agt-reviewer', name: 'reviewer', backend: 'claude', enabled: true, archived: false, source: 'user', model: 'claude-opus-4-7', reasoning_effort: 'high', description: 'Reviews pull requests', bot: null },+];++const NOW = new Date('2026-11-01T08:00:00Z').getTime();+const ago = (minutes: number) => new Date(NOW - minutes * 60_000).toISOString();++const INBOX = {+ sessions: [+ { session_id: 'ses_cso', scope_id: null, project_id: null, project_name: null, title: CSO.display_name, last_activity_at: ago(12), last_message_author: 'agent', replied: false, preview_text: 'avault 依赖里发现 2 个高危漏洞,已整理修复建议和影响范围。', preview_at: ago(12), unread_count: 2, unread: true },+ { session_id: 'ses4project1', scope_id: 'scope-1', project_id: 'proj-1', project_name: '中文项目', title: 'Fix the cache break', last_activity_at: ago(21), last_message_author: 'agent', replied: false, preview_text: 'The prefix broke when old tool results were cleared; the PR is open.', preview_at: ago(21), unread_count: 3, unread: true },+ { session_id: 'ses_main', scope_id: null, project_id: null, project_name: null, title: 'Vibey', last_activity_at: ago(110), last_message_author: 'agent', replied: false, preview_text: 'The weekly report draft is in Feishu, waiting for your go-ahead.', preview_at: ago(110), unread_count: 0, unread: false },+ ],+ next_cursor: null,+ unread_by_session: { ses_cso: 2, ses4project1: 3 },+ unread_total: 5,+ unread_sessions: 2,+};++async function serveBots(page: Page, lang: Lang, bots: FixtureBot[]) {+ const denied = await serveProduct(page, lang);+ await page.clock.setFixedTime(NOW);+ await page.route('**/api/bots', (route) => route.fulfill({ json: { ok: true, bots: bots.map(payload) } }));+ await page.route('**/api/agents**', (route) => route.fulfill({ json: { ok: true, agents: AGENTS, default_agent_name: 'vibey' } }));+ await page.route('**/api/inbox**', (route) => {+ const only = new URL(route.request().url()).searchParams.get('session');+ return route.fulfill({ json: only ? { ...INBOX, sessions: INBOX.sessions.filter((row) => row.session_id === only) } : INBOX });+ });+ await page.route('**/api/bots/handle-suggestion', async (route) => {+ const body = route.request().postDataJSON() as { display_name: string };+ // The model's answer takes a moment; the dialog shows that it is coming.+ await new Promise((resolve) => setTimeout(resolve, 900));+ return route.fulfill({ json: { ok: true, handle: /[^ -~]/.test(body.display_name) ? 'cso-2' : body.display_name.toLowerCase(), source: 'model' } });+ });+ for (const bot of bots) {+ const sessionId = `ses_${bot.handle}`;+ const session = {+ id: sessionId, scope_id: null, project_id: null, title: bot.display_name || 'Vibey',+ agent_id: `agt-${bot.handle}`, agent_name: bot.handle, agent_backend: 'vibey', agent_variant: 'vibey',+ model: 'gpt-6-astra', reasoning_effort: 'high', speed: null, status: 'active',+ agent_status: bot.running ? 'running' : 'idle', pinned: false, visibility: 'foreground',+ workdir: `/fixture/.avibe/bots/${bot.handle}`, native_session_id: null, metadata: { kind: bot.handle === 'main' ? 'main' : 'bot' },+ created_at: ago(600), updated_at: ago(12),+ };+ const turnState = {+ in_flight: false, foreground: 'idle', native_turn_started: false, pending_input_count: 0,+ background_activities: [], pending_activity_output_count: 0, connection: 'connected',+ };+ await page.route(`**/api/sessions/${sessionId}/bootstrap`, (route) => route.fulfill({ json: {+ session, capabilities: { can_chat: true }, agents: AGENTS, default_agent_name: 'vibey', config: { ui: {} },+ messages: [], queued: [], next_after_id: null, next_before_id: null,+ draft: { text: '', updated_at: null }, turn_state: turnState,+ } }));+ await page.route(`**/api/sessions/${sessionId}`, (route) => route.fulfill({ json: session }));+ await page.route(`**/api/sessions/${sessionId}/queue`, (route) => route.fulfill({ json: [] }));+ await page.route(`**/api/sessions/${sessionId}/turn-state`, (route) => route.fulfill({ json: turnState }));+ await page.route(`**/api/sessions/${sessionId}/activity**`, (route) => route.fulfill({ json: { groups: [] } }));+ await page.route(`**/api/sessions/${sessionId}/mark-read`, (route) => route.fulfill({ json: { ok: true } }));+ await page.route(`**/api/sessions/${sessionId}/draft`, (route) => route.fulfill({ json: { ok: true, draft: { text: '', updated_at: null } } }));+ }+ await page.route('**/api/asr/status', (route) => route.fulfill({ json: { available: false } }));+ return { denied };+}++const sidebarOf = (page: Page) => page.locator('aside').filter({ has: page.locator('#workbench-capability-nav') });++for (const theme of ['light', 'dark'] as const) {+ test(`the Bots strip takes the Inbox's place, with its hover card and menu (${theme})`, async ({ page }) => {+ const { denied } = await serveBots(page, 'zh', [MAIN, CSO, PM]);+ await page.setViewportSize(DESKTOP);+ await open(page, '/', { lang: 'zh', theme });+ const sidebar = sidebarOf(page);+ const strip = sidebar.getByRole('region', { name: '伙伴' });+ await expect(strip).toBeVisible();++ // The brand reads "Agent OS" alone, and the Inbox is the icon at its right.+ await expect(sidebar.getByText('Agent OS', { exact: true })).toBeVisible();+ const inbox = sidebar.getByRole('link', { name: '收件箱,5 条未读' });+ await expect(inbox).toHaveText('5');+ const brand = (await sidebar.locator('a[href="/"]').boundingBox())!;+ const inboxBox = (await inbox.boundingBox())!;+ expect(Math.abs(inboxBox.y + inboxBox.height / 2 - (brand.y + brand.height / 2))).toBeLessThan(2);+ expect((await strip.boundingBox())!.y).toBeGreaterThan(brand.y + brand.height);++ // The main Bot first, under its localized default name; Add follows inline.+ const slots = strip.locator('[data-bot-handle]');+ await expect(slots).toHaveCount(3);+ await expect(slots.first()).toHaveAttribute('data-bot-handle', 'main');+ await expect(slots.first()).toContainText('歪比');+ await expect(strip.getByRole('button', { name: '首席安全官,2 条未读' })).toContainText('2');+ const add = strip.getByRole('button', { name: '添加伙伴' });+ expect((await add.boundingBox())!.x).toBeGreaterThan((await slots.last().boundingBox())!.x);+ // Three Bots and Add fit the default column: nothing scrolls or fades.+ const row = slots.first().locator('xpath=..');+ expect(await row.evaluate((node) => node.scrollWidth <= node.clientWidth)).toBe(true);+ await expect(row).not.toHaveClass(/bot-strip-fade/);+ await page.mouse.move(900, 600);+ await sidebar.screenshot({ animations: 'disabled', path: `${SHOTS}/bots-strip-${theme}.png` });++ await strip.getByRole('button', { name: 'Product Lead' }).hover();+ const card = page.getByRole('dialog').filter({ hasText: '@pm' });+ await expect(card).toBeVisible();+ await expect(card).toContainText('Owns the backlog and its priorities');+ await expect(card).toContainText('运行中');+ await page.screenshot({ animations: 'disabled', path: `${SHOTS}/bots-hover-${theme}.png`, clip: { x: 0, y: 0, width: 620, height: 460 } });++ await strip.getByRole('button', { name: '首席安全官,2 条未读' }).click({ button: 'right' });+ const menu = page.getByRole('menu');+ await expect(menu.getByRole('menuitem', { name: '编辑资料' })).toBeVisible();+ await expect(menu.getByRole('menuitem', { name: '移出伙伴' })).toBeVisible();+ await expect(menu).toContainText('对话和记忆都会保留');+ await page.screenshot({ animations: 'disabled', path: `${SHOTS}/bots-menu-${theme}.png`, clip: { x: 0, y: 0, width: 620, height: 460 } });+ await page.keyboard.press('Escape');++ // The main Bot has no remove.+ await slots.first().getByRole('button').click({ button: 'right' });+ await expect(page.getByRole('menu').getByRole('menuitem', { name: '编辑资料' })).toBeVisible();+ await expect(page.getByRole('menu').getByRole('menuitem', { name: '移出伙伴' })).toHaveCount(0);+ await page.keyboard.press('Escape');++ // The Inbox popover: a Bot row is the Bot, with its tag.+ await inbox.hover();+ const popover = page.getByRole('dialog', { name: '收件箱' });+ await expect(popover).toBeVisible();+ await expect(popover.getByRole('button').filter({ hasText: '首席安全官' })).toContainText('伙伴');+ await expect(popover.getByRole('button').filter({ hasText: '中文项目' })).toContainText('Fix the cache break');+ await page.screenshot({ animations: 'disabled', path: `${SHOTS}/bots-inbox-${theme}.png`, clip: { x: 0, y: 0, width: 680, height: 560 } });+ expect(denied).toEqual([]);+ });++ test(`the add dialog generates a handle and offers existing Agents (${theme})`, async ({ page }) => {+ const { denied } = await serveBots(page, 'zh', [MAIN, CSO, PM]);+ await page.setViewportSize(DESKTOP);+ await open(page, '/', { lang: 'zh', theme });+ await sidebarOf(page).getByRole('button', { name: '添加伙伴' }).click();+ const dialog = page.getByRole('dialog', { name: '添加伙伴' });+ await expect(dialog).toBeVisible();++ await dialog.getByRole('textbox').first().fill('首席安全官');+ await expect(dialog.getByRole('status')).toContainText('正在生成代号');+ await page.screenshot({ animations: 'disabled', path: `${SHOTS}/bots-add-generating-${theme}.png` });+ await expect(dialog.getByText('@cso-2')).toBeVisible();+ await dialog.getByPlaceholder('例如:负责依赖与权限的安全审计,每周一汇报一次').fill('负责依赖与权限的安全审计,每周一早上汇报一次。');+ await expect(dialog).toContainText('也可以直接跟歪比说');+ await page.screenshot({ animations: 'disabled', path: `${SHOTS}/bots-add-ready-${theme}.png` });++ await dialog.getByRole('button', { name: '选择头像' }).click();+ await page.getByRole('radio', { name: '🛡️' }).click();+ await page.screenshot({ animations: 'disabled', path: `${SHOTS}/bots-add-avatar-${theme}.png` });+ await page.getByRole('radio', { name: '上传图片' }).click();+ await expect(page.getByText('拖入图片,或点击选择')).toBeVisible();+ await page.screenshot({ animations: 'disabled', path: `${SHOTS}/bots-add-upload-${theme}.png` });+ await page.keyboard.press('Escape');++ await dialog.getByRole('radio', { name: '从已有 Agent 设为伙伴' }).click();+ // Only Vibey Agents that are not Bots: never the main Bot, a Bot, a Claude+ // Agent, or the built-in `vibey` worker.+ const choices = dialog.getByRole('radiogroup', { name: '从已有 Agent 设为伙伴' }).getByRole('radio');+ await expect(choices).toHaveText([/^security-auditor/]);+ await choices.filter({ hasText: 'security-auditor' }).click();+ await expect(dialog.getByText('@security-auditor')).toBeVisible();+ await expect(dialog.getByRole('button', { name: '设为伙伴' })).toBeEnabled();+ await page.screenshot({ animations: 'disabled', path: `${SHOTS}/bots-add-agent-${theme}.png` });+ expect(denied).toEqual([]);+ });++ test(`a Bot's conversation shows the Bot, its role, and no rename (${theme})`, async ({ page }) => {+ const { denied } = await serveBots(page, 'en', [MAIN, CSO, PM]);+ await page.setViewportSize(DESKTOP);+ await open(page, '/chat/ses_cso', { lang: 'en', theme });+ const header = page.locator('[data-chat-header]');+ await expect(header).toContainText('首席安全官');+ await expect(header.getByRole('button', { name: 'Edit profile' })).toBeVisible();+ // No rename: the name is not a click-to-edit title, and the menu offers no+ // rename, archive, pin, or hide.+ await expect(header.locator('input')).toHaveCount(0);+ await header.getByRole('button', { name: 'Session actions' }).first().click();+ const actions = page.getByRole('group', { name: 'Session actions' });+ await expect(actions.getByRole('button')).toHaveText(['Fork session']);+ await page.keyboard.press('Escape');+ // The empty conversation shows the Bot's role; the open Bot carries the ring.+ await expect(page.locator('main')).toContainText('依赖与权限的安全审计,每周汇报');+ await expect(page.getByRole('button', { name: '首席安全官, 2 unread', exact: true })).toHaveAttribute('aria-current', 'page');+ // The composer moves the model only: the Agent is the Bot's, named but not offered.+ await page.locator('main').getByRole('button', { name: /^cso/ }).click();+ await expect(page.getByText('Model', { exact: true })).toBeVisible();+ await expect(page.getByRole('button', { name: /^Agent/ })).toHaveCount(0);+ await expect(page.getByRole('button', { name: 'New agent' })).toHaveCount(0);+ await page.keyboard.press('Escape');+ await page.mouse.move(900, 300);+ await page.screenshot({ animations: 'disabled', path: `${SHOTS}/bots-conversation-${theme}.png` });++ await header.getByRole('button', { name: 'Edit profile' }).click();+ const dialog = page.getByRole('dialog', { name: 'Edit profile' });+ await expect(dialog.getByRole('textbox').first()).toHaveValue('首席安全官');+ await expect(dialog.getByText('@cso')).toBeVisible();+ await expect(dialog.getByText('Fixed once the Bot exists')).toBeVisible();+ await page.screenshot({ animations: 'disabled', path: `${SHOTS}/bots-edit-${theme}.png` });+ expect(denied).toEqual([]);+ });+}++test('adding a Bot sends the generated handle, its role, and the emoji avatar, then opens its conversation', async ({ page }) => {+ const { denied } = await serveBots(page, 'en', [MAIN, CSO, PM]);+ const created: unknown[] = [];+ await page.route('**/api/bots', (route) => {+ if (route.request().method() !== 'POST') return route.fallback();+ const body = route.request().postDataJSON() as { display_name: string; handle: string };+ created.push(body);+ return route.fulfill({ status: 201, json: { ok: true, bot: payload({ handle: body.handle, display_name: body.display_name, avatar: null, role: '' }, 3) } });+ });+ await page.setViewportSize(DESKTOP);+ await open(page, '/', { lang: 'en' });+ await sidebarOf(page).getByRole('button', { name: 'Add a Bot' }).click();+ const dialog = page.getByRole('dialog', { name: 'Add a Bot' });+ await dialog.getByRole('textbox').first().fill('首席安全官');+ await dialog.getByPlaceholder('e.g. Audits dependencies and permissions, and reports every Monday').fill('Audits dependencies weekly.');+ await dialog.getByRole('button', { name: 'Choose an avatar' }).click();+ await page.getByRole('radio', { name: '🛡️' }).click();+ await page.keyboard.press('Escape');+ await expect(dialog.getByText('@cso-2')).toBeVisible();+ await dialog.getByRole('button', { name: 'Add Bot' }).click();+ await expect(page).toHaveURL(/\/chat\/ses_cso-2$/);+ // The model follows the main Bot unless Advanced chose one, so none is sent.+ expect(created).toEqual([{+ display_name: '首席安全官', handle: 'cso-2', role: 'Audits dependencies weekly.', avatar: { emoji: '🛡️', hue: 200 },+ }]);+ expect(denied).toEqual([]);+});++test('adding before the handle arrives waits for it and creates with it', async ({ page }) => {+ const { denied } = await serveBots(page, 'en', [MAIN, CSO, PM]);+ const created: { handle?: string }[] = [];+ await page.route('**/api/bots', (route) => {+ if (route.request().method() !== 'POST') return route.fallback();+ const body = route.request().postDataJSON() as { display_name: string; handle: string };+ created.push(body);+ return route.fulfill({ status: 201, json: { ok: true, bot: payload({ handle: body.handle, display_name: body.display_name, avatar: null, role: '' }, 3) } });+ });+ await page.setViewportSize(DESKTOP);+ await open(page, '/', { lang: 'en' });+ await sidebarOf(page).getByRole('button', { name: 'Add a Bot' }).click();+ const dialog = page.getByRole('dialog', { name: 'Add a Bot' });+ await dialog.getByRole('textbox').first().fill('首席安全官');+ await dialog.getByRole('button', { name: 'Add Bot' }).click();+ await expect(page).toHaveURL(/\/chat\/ses_cso-2$/);+ expect(created.map((body) => body.handle)).toEqual(['cso-2']);+ expect(denied).toEqual([]);+});++test('closing the dialog while a create waits for its handle sends nothing', async ({ page }) => {+ const { denied } = await serveBots(page, 'en', [MAIN, CSO, PM]);+ const created: unknown[] = [];+ await page.route('**/api/bots', (route) => {+ if (route.request().method() !== 'POST') return route.fallback();+ created.push(route.request().postDataJSON());+ return route.fulfill({ status: 201, json: { ok: true, bot: payload(CSO, 3) } });+ });+ await page.setViewportSize(DESKTOP);+ await open(page, '/', { lang: 'en' });+ await sidebarOf(page).getByRole('button', { name: 'Add a Bot' }).click();+ const dialog = page.getByRole('dialog', { name: 'Add a Bot' });+ await dialog.getByRole('textbox').first().fill('首席安全官');+ // Add before the handle exists: the create waits for one, then the user leaves.+ await dialog.getByRole('button', { name: 'Add Bot' }).click();+ await page.keyboard.press('Escape');+ await expect(dialog).toBeHidden();+ await page.waitForTimeout(2000);+ expect(created).toEqual([]);+ await expect(page).toHaveURL(/\/$/);+ expect(denied).toEqual([]);+});++test('Settings opening over the dialog suspends it with the form intact', async ({ page }) => {+ const { denied } = await serveBots(page, 'en', [MAIN, CSO, PM]);+ await page.setViewportSize(DESKTOP);+ await open(page, '/', { lang: 'en' });+ await sidebarOf(page).getByRole('button', { name: 'Add a Bot' }).click();+ const dialog = page.getByRole('dialog', { name: 'Add a Bot' });+ await dialog.getByRole('textbox').first().fill('Researcher');+ // The model picker's Add model exit is an in-app route change to Settings; the+ // sidebar's Settings link makes the same one (clicked through the modal's inert layer).+ await page.locator('aside [data-settings-toggle="true"]').evaluate((node: HTMLElement) => node.click());+ await expect(page.locator('[data-settings-overlay="true"]')).toBeVisible();+ await expect(dialog).toBeHidden();+ await page.keyboard.press('Escape');+ await expect(page.locator('[data-settings-overlay="true"]')).toBeHidden();+ await expect(dialog).toBeVisible();+ await expect(dialog.getByRole('textbox').first()).toHaveValue('Researcher');+ expect(denied).toEqual([]);+});++test('on a short window the dialog scrolls to its footer', async ({ page }) => {+ const { denied } = await serveBots(page, 'en', [MAIN, CSO, PM]);+ await page.setViewportSize({ width: 1000, height: 420 });+ await open(page, '/', { lang: 'en' });+ await sidebarOf(page).getByRole('button', { name: 'Add a Bot' }).click();+ const dialog = page.getByRole('dialog', { name: 'Add a Bot' });+ await expect(dialog).toBeVisible();+ expect(await dialog.evaluate((node) => node.scrollHeight > node.clientHeight && getComputedStyle(node).overflowY === 'auto')).toBe(true);+ const add = dialog.getByRole('button', { name: 'Add Bot' });+ await add.scrollIntoViewIfNeeded();+ await expect(add).toBeInViewport();+ expect(denied).toEqual([]);+});++test('with more Bots than fit, the strip scrolls and Add stays pinned at the right', async ({ page }) => {+ const { denied } = await serveBots(page, 'en', [MAIN, CSO, PM, ...EXTRA]);+ await page.setViewportSize(DESKTOP);+ await open(page, '/', { lang: 'en', theme: 'light' });+ const strip = sidebarOf(page).getByRole('region', { name: 'Bots' });+ const add = strip.getByRole('button', { name: 'Add a Bot' });+ const stripBox = (await strip.boundingBox())!;+ const addBox = (await add.boundingBox())!;+ expect(addBox.x + addBox.width).toBeGreaterThan(stripBox.x + stripBox.width - 12);+ const scroller = strip.locator('[data-bot-handle]').first().locator('xpath=..');+ expect(await scroller.evaluate((node) => node.scrollWidth > node.clientWidth)).toBe(true);+ await expect(scroller).toHaveClass(/bot-strip-fade/);+ await page.mouse.move(900, 600);+ await sidebarOf(page).screenshot({ animations: 'disabled', path: `${SHOTS}/bots-strip-overflow-light.png` });+ expect(denied).toEqual([]);+});++test('only the Owner sees the Bots strip', async ({ page }) => {+ const { denied } = await serveBots(page, 'en', [MAIN, CSO]);+ await page.route('**/api/session', (route) => route.fulfill({ json: {+ remote: true, authenticated: true, authorization_state: 'current', instance_kind: 'organization', instance_role: 'member',+ capabilities: { is_instance_owner: false, can_read_instance: true, can_chat: true, can_use_agents: true },+ } }));+ await page.setViewportSize(DESKTOP);+ await open(page, '/', { lang: 'en' });+ const sidebar = sidebarOf(page);+ await expect(sidebar.getByText('Agent OS', { exact: true })).toBeVisible();+ await expect(sidebar.getByRole('region', { name: 'Bots' })).toHaveCount(0);+ expect(denied.filter((request) => request.includes('/api/bots'))).toEqual([]);+});++test('dragging a Bot along the strip moves it, and the main Bot stays first', async ({ page }) => {+ const { denied } = await serveBots(page, 'en', [MAIN, CSO, PM]);+ const moves: unknown[] = [];+ await page.route('**/api/bots/pm', async (route) => {+ moves.push(route.request().postDataJSON());+ // The server now holds the new order, and the refetch reads it back.+ await page.route('**/api/bots', (list) => list.fulfill({ json: { ok: true, bots: [payload(MAIN, 0), payload(PM, 1), payload(CSO, 2)] } }));+ return route.fulfill({ json: { ok: true, bot: payload(PM, 1) } });+ });+ await page.setViewportSize(DESKTOP);+ await open(page, '/', { lang: 'en' });+ const strip = sidebarOf(page).getByRole('region', { name: 'Bots' });+ const from = (await strip.locator('[data-bot-handle="pm"] button').boundingBox())!;+ const to = (await strip.locator('[data-bot-handle="cso"] button').boundingBox())!;+ await page.mouse.move(from.x + from.width / 2, from.y + from.height / 2);+ await page.mouse.down();+ await page.mouse.move(from.x + from.width / 2 - 10, from.y + from.height / 2, { steps: 4 });+ await page.mouse.move(to.x + to.width / 2 - 8, to.y + to.height / 2, { steps: 8 });+ await page.mouse.up();+ await expect.poll(() => moves).toEqual([{ position: 1 }]);+ await expect(strip.locator('[data-bot-handle]')).toHaveCount(3);+ expect(await strip.locator('[data-bot-handle]').evaluateAll((nodes) => nodes.map((node) => node.getAttribute('data-bot-handle'))))+ .toEqual(['main', 'pm', 'cso']);+ expect(denied).toEqual([]);+});++for (const theme of ['light', 'dark'] as const) {+ test(`the Agents page marks Bots and offers "Set as Bot" on eligible Vibey Agents (${theme})`, async ({ page }) => {+ const { denied } = await serveBots(page, 'en', [MAIN, CSO, PM]);+ for (const agent of AGENTS) {+ await page.route(`**/api/agents/${agent.name}`, (route) => route.fulfill({ json: {+ ok: true,+ agent: { ...agent, display_name: agent.name, archived_at: null, updated_at: ago(60), system_prompt: null, metadata: {}, created_at: ago(600) },+ } }));+ }+ await page.setViewportSize(DESKTOP);+ await open(page, '/agents', { lang: 'en', theme });+ const row = page.getByRole('button', { name: /^cso/ });+ await expect(row.getByText('Bot', { exact: true })).toBeVisible();+ // The built-in worker is never offered as a Bot (D9).+ await page.getByRole('button', { name: /^vibey/ }).click();+ await expect(page.getByText('Vibe Agent · Vibey backend')).toBeVisible();+ await expect(page.getByRole('button', { name: 'Set as Bot' })).toHaveCount(0);+ await row.click();+ const detail = page.getByText('This Agent is the Bot 首席安全官');+ await expect(detail).toBeVisible();+ // While it is a Bot it keeps its name and stays enabled; no delete is offered.+ await expect(page.locator('input[value="cso"]')).toBeDisabled();+ await expect(page.getByRole('switch')).toBeDisabled();+ await expect(page.getByRole('button', { name: 'Delete' })).toHaveCount(0);+ await page.screenshot({ animations: 'disabled', path: `${SHOTS}/bots-agents-bot-${theme}.png` });++ // A Bot's role is its Agent's description: saving it reads the Bots again.+ if (theme === 'light') {+ let botReads = 0;+ page.on('request', (request) => {+ if (request.method() === 'GET' && new URL(request.url()).pathname === '/api/bots') botReads += 1;+ });+ await page.route('**/api/agents/cso', (route) => (route.request().method() === 'PATCH'+ ? route.fulfill({ json: { ok: true, agent: { ...AGENTS[3], description: 'Weekly audits', display_name: 'cso', archived_at: null, updated_at: ago(1), system_prompt: null, metadata: {}, created_at: ago(600) } } })+ : route.fallback()));+ const description = page.locator('textarea').first();+ await description.fill('Weekly audits');+ await description.blur();+ await expect.poll(() => botReads).toBeGreaterThan(0);+ }++ await page.getByRole('button', { name: /^security-auditor/ }).click();+ const set = page.getByRole('button', { name: 'Set as Bot' });+ await expect(set).toBeEnabled();+ await page.screenshot({ animations: 'disabled', path: `${SHOTS}/bots-agents-set-${theme}.png` });+ await set.click();+ const dialog = page.getByRole('dialog', { name: 'Add a Bot' });+ await expect(dialog.getByRole('radio', { name: /security-auditor/ })).toHaveAttribute('aria-checked', 'true');+ await expect(dialog.getByText('@security-auditor')).toBeVisible();+ expect(denied).toEqual([]);+ });+}diff --git a/ui/e2e/workbench-general/sidebar-capabilities.spec.ts b/ui/e2e/workbench-general/sidebar-capabilities.spec.tsindex 68982940f..6cbc46b5a 100644--- a/ui/e2e/workbench-general/sidebar-capabilities.spec.ts+++ b/ui/e2e/workbench-general/sidebar-capabilities.spec.ts@@ -4,9 +4,9 @@ import { DESKTOP, open, serveProduct } from './support';for (const copy of [{ lang: 'en', capabilities: 'Capabilities', search: 'Search', inbox: 'Inbox', close: 'Close Settings',- brand: 'Agent OS · Workbench', add: 'Open project' },+ brand: 'Agent OS', add: 'Open project' },{ lang: 'zh', capabilities: '能力', search: '搜索', inbox: '收件箱', close: '关闭设置',- brand: 'Agent OS · 工作台', add: '打开项目' },+ brand: 'Agent OS', add: '打开项目' },] as const) {test(`capability navigation survives retained Settings (${copy.lang})`, async ({ page }, info) => {const denied = await serveProduct(page, copy.lang);diff --git a/ui/e2e/workbench-general/sidebar-floating.spec.ts b/ui/e2e/workbench-general/sidebar-floating.spec.tsindex 43cf9ce73..99bd6f47a 100644--- a/ui/e2e/workbench-general/sidebar-floating.spec.ts+++ b/ui/e2e/workbench-general/sidebar-floating.spec.ts@@ -23,7 +23,7 @@ async function serveProduct(page: Page, lang: Lang = 'en') {'/api/session', '/api/config', '/api/csrf-token', '/api/projects','/api/workbench/projects-bootstrap', '/api/sessions', '/api/agents','/api/inbox', '/api/version', '/api/events', '/api/macos/login-session',- '/api/desktop/computer-use/status',+ '/api/desktop/computer-use/status', '/api/bots', '/api/sessions/ses_main',]);await page.route('**/api/**', (route) => {const request = route.request();diff --git a/ui/e2e/workbench-general/support.ts b/ui/e2e/workbench-general/support.tsindex c536a839c..b847db7df 100644--- a/ui/e2e/workbench-general/support.ts+++ b/ui/e2e/workbench-general/support.ts@@ -62,6 +62,16 @@ const PROJECTS = {sessions: {},};+// The Owner always has the main Bot (docs/plans/bots.md D9); the server creates it+// on first read, so the shell never shows an empty Bots strip.+const BOTS = {+ ok: true,+ bots: [{+ handle: 'main', display_name: '', avatar: { kind: 'mascot' }, role: "The user's main Bot and first point of contact.",+ agent_name: 'main', session_id: 'ses_main', position: 0, builtin: true,+ }],+};+const AGENTS = {ok: true,agents: [@@ -99,6 +109,7 @@ export async function serveProduct(page: Page, lang: Lang = 'en') {await page.route('**/api/workbench/projects-bootstrap**', (route) => route.fulfill({ json: PROJECTS }));await page.route('**/api/sessions**', (route) => route.fulfill({ json: { sessions: [] } }));await page.route('**/api/agents**', (route) => route.fulfill({ json: AGENTS }));+ await page.route('**/api/bots', (route) => route.fulfill({ json: BOTS }));await page.route('**/api/inbox**', (route) => route.fulfill({ json: { sessions: [], unread: {} } }));// The service badge polls the bare `/status`, not an `/api` path.await page.route('**/status', (route) => route.fulfill({ json: { state: 'running' } }));diff --git a/ui/src/App.tsx b/ui/src/App.tsxindex e547b0b2d..969c908fa 100644--- a/ui/src/App.tsx+++ b/ui/src/App.tsx@@ -44,6 +44,7 @@ import { StatusProvider } from './context/StatusProvider';import { ApiProvider, useApi, ApiError } from './context/ApiContext';import type { SessionInfo } from './context/ApiContext';import { InstanceAuthorizationProvider } from './context/InstanceAuthorizationProvider';+import { BotsProvider } from './context/BotsProvider';import { useWindowManager } from './context/WindowManagerContext';import { ToastProvider } from './context/ToastProvider';import { ThemeProvider } from './context/ThemeProvider';@@ -845,14 +846,16 @@ const router = createBrowserRouter(<ErrorBoundary variant="page"><PetWindow><AuthGuard>- <Suspense fallback={null}><PetPage /></Suspense>+ <BotsProvider>+ <Suspense fallback={null}><PetPage /></Suspense>+ </BotsProvider></AuthGuard></PetWindow></ErrorBoundary>)}/><Route element={<ErrorBoundary variant="page"><RouterRoot /></ErrorBoundary>}>- <Route element={<AuthGuard><AppShell /></AuthGuard>}>+ <Route element={<AuthGuard><BotsProvider><AppShell /></BotsProvider></AuthGuard>}><Route path="*" element={<WorkbenchRouteSurface />} /></Route></Route>diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsxindex 87ffe8ebf..0851dae00 100644--- a/ui/src/components/AppShell.tsx+++ b/ui/src/components/AppShell.tsx@@ -16,6 +16,7 @@ import { useWorkbenchInbox } from '../context/WorkbenchInboxContext';import { useInstanceAuthorization } from '../context/InstanceAuthorizationContext';import { VersionBadge } from './VersionBadge';import { WorkbenchSidebar } from './workbench/WorkbenchSidebar';+import { BotProfileDialogHost } from './workbench/bots/BotProfileDialog';import { SidebarResizer } from './SidebarResizer';import { AppsLauncher } from './AppsLauncher';import { ErrorBoundary } from './ui/error-boundary';@@ -732,6 +733,14 @@ export const AppShell: React.FC = () => {</RouteSurfaceActivityBoundary>)}+ {/* The Bots add/edit dialog (docs/plans/bots.md D5), opened from the strip,+ a Bot's conversation, or the Agents page. It is modal over the whole+ shell, so any Settings placement suspends it with its form intact (the+ model picker's Add model exit opens Settings over it). */}+ <RouteSurfaceActivityBoundary active={!settingsOpen}>+ <BotProfileDialogHost />+ </RouteSurfaceActivityBoundary>+{/* ⌘K message-search palette. Mounted shell-wide; the sidebar field is theWorkbench entry point. */}<RouteSurfaceActivityBoundary active={!settingsCoversSidebar}>diff --git a/ui/src/components/ui/bot-avatar.tsx b/ui/src/components/ui/bot-avatar.tsxnew file mode 100644index 000000000..9399d993c--- /dev/null+++ b/ui/src/components/ui/bot-avatar.tsx@@ -0,0 +1,64 @@+import type { CSSProperties } from 'react';++import vibeyMascot from '@/assets/pet/vibey.png';+import { cn } from '@/lib/utils';+import { nameHue, nameInitial, type BotAvatar as BotAvatarSpec } from '@/lib/bots';++export interface BotAvatarProps {+ /** The Bot's avatar, or `null` for the default: the name's first character on+ * a color derived from the name (D5). */+ avatar: BotAvatarSpec | null;+ /** The name the default avatar is drawn from. */+ name: string;+ /** Diameter in px. */+ size: number;+ /** An unsaved upload's preview URL; wins over `avatar`. */+ previewUrl?: string | null;+ className?: string;+}++/** One Bot's round avatar: the Vibey mascot on a theme-following well, an emoji on+ * its hue, an uploaded image cropped to a circle, or the name's first character. */+export const BotAvatar: React.FC<BotAvatarProps> = ({ avatar, name, size, previewUrl, className }) => {+ const box: CSSProperties = { width: size, height: size };+ const shell = cn('grid shrink-0 select-none place-items-center overflow-hidden rounded-full', className);+ if (previewUrl || avatar?.kind === 'image') {+ return (+ <span className={cn(shell, 'bg-surface-3')} style={box} aria-hidden="true">+ <img+ src={previewUrl || (avatar as { url: string }).url}+ alt=""+ draggable={false}+ className="size-full object-cover"+ />+ </span>+ );+ }+ if (avatar?.kind === 'mascot') {+ return (+ <span className={cn(shell, 'bot-avatar-mascot')} style={box} aria-hidden="true">+ <img src={vibeyMascot} alt="" draggable={false} className="size-full scale-[1.12] object-contain" />+ </span>+ );+ }+ if (avatar?.kind === 'emoji') {+ return (+ <span+ className={cn(shell, 'bot-avatar-emoji leading-none')}+ style={{ ...box, fontSize: Math.round(size * 0.48), ['--bot-hue' as string]: avatar.hue }}+ aria-hidden="true"+ >+ {avatar.emoji}+ </span>+ );+ }+ return (+ <span+ className={cn(shell, 'bot-avatar-initial font-semibold leading-none')}+ style={{ ...box, fontSize: Math.round(size * 0.42), ['--bot-hue' as string]: nameHue(name) }}+ aria-hidden="true"+ >+ {nameInitial(name)}+ </span>+ );+};diff --git a/ui/src/components/ui/bot-mention-chip.tsx b/ui/src/components/ui/bot-mention-chip.tsxnew file mode 100644index 000000000..6d44ffca1--- /dev/null+++ b/ui/src/components/ui/bot-mention-chip.tsx@@ -0,0 +1,32 @@+import type { ReactNode } from 'react';+import { useTranslation } from 'react-i18next';++import { useBots } from '../../context/BotsContext';+import { cn } from '../../lib/utils';+import { BotAvatar } from './bot-avatar';+import { badgeVariants } from './badge-variants';++/** A `@<bot:handle>` mention as a chip: the Bot's avatar and its current display+ * name (D3). Off the Owner's surfaces, or for a Bot since removed, it keeps the+ * label the message was sent with. */+export const BotMentionChip: React.FC<{ handle: string; fallback: ReactNode; className?: string }> = ({+ handle,+ fallback,+ className,+}) => {+ const { t } = useTranslation();+ const { botForHandle, displayName } = useBots();+ const bot = botForHandle(handle);+ return (+ <span className={cn(badgeVariants({ variant: 'success' }), 'gap-1 py-px pl-0.5 align-baseline font-medium', className)}>+ {bot ? (+ <>+ <BotAvatar avatar={bot.avatar} name={displayName(bot)} size={16} />+ <span className="truncate">{t('bots.mentionName', { name: displayName(bot) })}</span>+ </>+ ) : (+ <span className="truncate pl-1.5">{fallback}</span>+ )}+ </span>+ );+};diff --git a/ui/src/components/ui/markdown.tsx b/ui/src/components/ui/markdown.tsxindex 48018f4b6..b6d95f566 100644--- a/ui/src/components/ui/markdown.tsx+++ b/ui/src/components/ui/markdown.tsx@@ -35,6 +35,7 @@ import {parseMentionHref,type MentionReference,} from '@/lib/mentions';+import { BotMentionChip } from './bot-mention-chip';import { cn, copyTextToClipboard } from '@/lib/utils';// Shared markdown renderer. react-markdown + remark-gfm (tables, strikethrough,@@ -595,6 +596,9 @@ export const Markdown: React.FC<{// interactive and non-interactive contexts — a chip is a span, safe inside// a clickable row, and never triggers a fetch or navigation.const mention = parseMentionHref(url);+ if (mention?.target === 'bot') {+ return <BotMentionChip handle={mention.value} fallback={children} className="max-w-[18rem]" />;+ }if (mention) {return (<Badgediff --git a/ui/src/components/workbench/AgentRoutePicker.test.tsx b/ui/src/components/workbench/AgentRoutePicker.test.tsxindex ebcedc421..dacb5d62d 100644--- a/ui/src/components/workbench/AgentRoutePicker.test.tsx+++ b/ui/src/components/workbench/AgentRoutePicker.test.tsx@@ -132,8 +132,9 @@ const OptimisticOwner: React.FC<{defaultRoute?: AgentRouteValue;defaultLabel?: string;presentation?: 'columns' | 'compact';+ agentLocked?: boolean;onWrite: (patch: AgentRoutePatch) => void;-}> = ({ initial = CLAUDE_ROUTE, isDefaultRoute, defaultRoute, defaultLabel, presentation, onWrite }) => {+}> = ({ initial = CLAUDE_ROUTE, isDefaultRoute, defaultRoute, defaultLabel, presentation, agentLocked, onWrite }) => {const [route, setRoute] = useState<AgentRouteValue>(initial);const [saving, setSaving] = useState(false);return (@@ -146,6 +147,7 @@ const OptimisticOwner: React.FC<{defaultRoute={defaultRoute}defaultLabel={defaultLabel}presentation={presentation}+ agentLocked={agentLocked}onChange={(patch) => {setRoute((prev) => ({ ...prev, ...patch }));setSaving(true);@@ -760,6 +762,24 @@ describe('AgentRoutePicker compact presentation', () => {expect(screen.queryByRole('button', { name: 'chat.picker.newAgent' })).toBeNull();});+ // A Bot's conversation (docs/plans/bots.md D5): the server refuses any Agent+ // write on a Bot's Session, so the menu must not offer one, only the model.+ it('names a locked Agent without offering another, while the model still moves', async () => {+ const user = userEvent.setup();+ const onWrite = vi.fn();+ render(<OptimisticOwner presentation="compact" agentLocked onWrite={onWrite} />);+ await openMenu(user);++ expect(screen.queryByRole('button', { name: /chat\.picker\.agent/ })).toBeNull();+ expect(screen.getByText('chat.picker.agent').parentElement?.textContent).toContain('claude');+ await user.click(screen.getByText('chat.picker.agent'));+ expect(screen.queryByRole('button', { name: /^codex/ })).toBeNull();+ expect(screen.queryByRole('button', { name: 'chat.picker.newAgent' })).toBeNull();++ await user.click(screen.getByRole('button', { name: /^opus/ }));+ expect(onWrite.mock.calls).toEqual([[{ model: 'opus' }]]);+ });+it('names an inherited route by its Agent on the trigger and says Default only in the menu', async () => {const user = userEvent.setup();render(diff --git a/ui/src/components/workbench/AgentRoutePicker.tsx b/ui/src/components/workbench/AgentRoutePicker.tsxindex 947bdee5c..b89b40ee8 100644--- a/ui/src/components/workbench/AgentRoutePicker.tsx+++ b/ui/src/components/workbench/AgentRoutePicker.tsx@@ -85,6 +85,10 @@ interface AgentRoutePickerProps {* ``onChange``. */speed?: SessionSpeed;onSpeedChange?: (speed: SessionSpeed) => void;+ /** The Agent is fixed (a Bot's conversation, where the Bot is the Agent): the+ * menu names it but offers no other Agent, no default, and no New Agent exit;+ * only the model, effort, and speed move. */+ agentLocked?: boolean;}type ReasoningOption = { value: string; label: string };@@ -115,6 +119,7 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({onNavigateAway,speed = null,onSpeedChange,+ agentLocked = false,}) => {const { t } = useTranslation();const api = useApi();@@ -618,20 +623,29 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({</div></div>);+ const agentRowContent = (+ <>+ <span className="text-[10px] font-bold uppercase tracking-[0.1em] text-muted">{t('chat.picker.agent')}</span>+ <span className="ml-auto flex min-w-0 items-center gap-1.5">+ {backend && <BackendAvatar backend={backend} className="size-3.5 shrink-0" />}+ <span className="truncate text-[12px] font-semibold text-foreground">{agentRowLabel}</span>+ {!agentLocked && <ChevronRight className="size-3.5 shrink-0 text-muted" />}+ </span>+ </>+ );const routeMenu = (<div className="flex flex-col">- <button- type="button"- onClick={() => setAgentPage(true)}- className="flex items-center gap-2 px-3 py-2.5 text-left transition-colors hover:bg-foreground/[0.03]"- >- <span className="text-[10px] font-bold uppercase tracking-[0.1em] text-muted">{t('chat.picker.agent')}</span>- <span className="ml-auto flex min-w-0 items-center gap-1.5">- {backend && <BackendAvatar backend={backend} className="size-3.5 shrink-0" />}- <span className="truncate text-[12px] font-semibold text-foreground">{agentRowLabel}</span>- <ChevronRight className="size-3.5 shrink-0 text-muted" />- </span>- </button>+ {agentLocked ? (+ <div className="flex items-center gap-2 px-3 py-2.5">{agentRowContent}</div>+ ) : (+ <button+ type="button"+ onClick={() => setAgentPage(true)}+ className="flex items-center gap-2 px-3 py-2.5 text-left transition-colors hover:bg-foreground/[0.03]"+ >+ {agentRowContent}+ </button>+ )}<RouteColumn title={t('chat.picker.model')} className="max-h-[40vh] border-t border-border">{modelListBody((model) => {const label = modelOptionLabel(model, modelLabels);@@ -738,7 +752,7 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({align={align}modal={modal}>- {agentPage ? agentList : routeMenu}+ {agentPage && !agentLocked ? agentList : routeMenu}</ResponsiveMenu>);}@@ -762,6 +776,13 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({>{/* Column 1 — Agent */}<RouteColumn title={t('chat.picker.agent')}>+ {agentLocked ? (+ <div className="flex items-center gap-2 rounded bg-cyan/[0.10] px-2 py-1.5 text-[12px] text-cyan-ink">+ {backend && <BackendAvatar backend={backend} className="size-3.5 shrink-0" />}+ <span className="flex-1 truncate font-semibold">{agentLabel}</span>+ </div>+ ) : (+ <>{/* Default option: clears the route back to inherited defaults afterpicking an explicit agent, without a page refresh. */}{defaultLabel && (@@ -792,6 +813,8 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({</div>))}<PickerExitButton label={t('chat.picker.newAgent')} onClick={openNewAgent} />+ </>+ )}</RouteColumn>{/* Column 2 — Model (lazy-loaded for the active backend). Its owndiff --git a/ui/src/components/workbench/AgentsPage.tsx b/ui/src/components/workbench/AgentsPage.tsxindex 5efa9a708..8a8b6b829 100644--- a/ui/src/components/workbench/AgentsPage.tsx+++ b/ui/src/components/workbench/AgentsPage.tsx@@ -1,6 +1,6 @@import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import { useSearchParams } from 'react-router-dom';+import { useNavigate, useSearchParams } from 'react-router-dom';import {Bot,ChevronDown,@@ -34,6 +34,9 @@ import type {VibeAgentUpdatePayload,} from '../../context/ApiContext';import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';+import { useBots } from '../../context/BotsContext';+import { BotAvatar } from '../ui/bot-avatar';+import { eligibleForBot } from '../../lib/bots';import { AgentGraphTab } from './AgentGraphTab';import { useToast } from '../../context/ToastContext';import { NewAgentDialog } from './NewAgentDialog';@@ -278,6 +281,7 @@ export const AgentsPage: React.FC = () => {tRef.current = t;const api = useApi();const { showToast } = useToast();+ const { refresh: refreshBots } = useBots();const {capabilities,} = useInstanceAuthorization();@@ -1216,6 +1220,11 @@ export const AgentsPage: React.FC = () => {onAuthorizationChanged: () => {void reconcileGap();},+ // A Bot is Agent metadata (docs/plans/bots.md D1): its badge and locks ride+ // on the Agent rows, so a Bot change is a definitions change here.+ onBotsChanged: () => {+ void reconcileGap();+ },});}, [api, capabilities.can_use_agents, fetchRunningActiveCount, reconcileGap, refreshOnboarding]);@@ -1339,10 +1348,15 @@ export const AgentsPage: React.FC = () => {const updateField = async (patch: VibeAgentUpdatePayload): Promise<void> => {if (!selected) return;const name = selected.name;+ const isBot = Boolean(selected.bot);const operation = beginSelectedMutation(name);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();const settled = await settleSelectedMutation(operation, result.ok ? undefined : result);mutationSettled = true;if (!settled.ok) throw settled.error;@@ -1839,6 +1853,11 @@ const AgentRow: React.FC<AgentRowProps> = ({ agent, isSelected, isDefault, model{t('common.systemSession')}</Badge>)}+ {agent.bot && (+ <Badge variant="success" className="px-1.5 py-0 text-[9px] font-mono uppercase" title={agent.bot.display_name || undefined}>+ {t('bots.agents.badge')}+ </Badge>+ )}</div>{description && <div className="text-[11px] text-muted">{description}</div>}</div>@@ -1972,6 +1991,10 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, ca// System agents are locked everywhere; remote access locks every agent.const locked = isSystemAgent(agent) || !canEdit;const system = isSystemAgent(agent);+ // While an Agent is a Bot it stays enabled and keeps its name and row+ // (docs/plans/bots.md D1); the server refuses those writes, so they are not offered.+ const isBot = Boolean(agent.bot);+ const nameLocked = locked || isBot;// The built-in Agent of the built-in backend is part of the platform: it stays enabled.const alwaysEnabled = agent.source === 'builtin' && isBuiltinAgent(agent) && getBackendUiMeta(agent.backend).builtin;const [name, setName] = useState(agent.name);@@ -2325,7 +2348,7 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, cacancelFieldEdit('name', serverSnapshotRef.current.name);return;}- if (locked) {+ if (nameLocked) {cancelFieldEdit('name', serverSnapshotRef.current.name);return;}@@ -2383,6 +2406,8 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, ca</Button></div>+ <AgentBotCard agent={agent} canEdit={canEdit} />+{/* Enable toggle — design.pen EWTY7 */}<divclassName={clsx(@@ -2403,8 +2428,8 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, caonCheckedChange={(next) => {consumeBackgroundMutation(onChange({ enabled: next }));}}- disabled={!canEdit || alwaysEnabled}- title={canEdit ? undefined : t('agents.remoteReadOnlyHint')}+ disabled={!canEdit || alwaysEnabled || isBot}+ title={canEdit ? (isBot ? t('bots.agents.isBotHint') : undefined) : t('agents.remoteReadOnlyHint')}label={t('agents.detail.enabled')}/></div>@@ -2428,7 +2453,7 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, ca<Star className="size-3" />{t('agents.detail.defaultActive')}</Badge>- ) : !canEdit ? null : (+ ) : !canEdit || isBot ? null : (<Buttontype="button"variant="outline"@@ -2458,11 +2483,11 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, caif (e.key === 'Enter') (e.target as HTMLInputElement).blur();if (e.key === 'Escape') cancelFieldEdit('name', serverSnapshotRef.current.name);}}- disabled={locked || renaming}- title={lockHint}+ disabled={nameLocked || renaming}+ title={isBot && !locked ? t('bots.agents.isBotHint') : lockHint}className="flex-1 bg-transparent text-[13px] font-medium text-foreground outline-none disabled:cursor-not-allowed disabled:opacity-70"/>- {!locked && <Pencil className="size-3 shrink-0 text-muted" />}+ {nameLocked ? (isBot && !locked ? <Lock className="size-3 shrink-0 text-muted" /> : null) : <Pencil className="size-3 shrink-0 text-muted" />}</div></Field>@@ -2716,7 +2741,8 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, ca)}<div className="flex-1" />{canEdit ? (- !system ? (+ // A Bot's Agent cannot be deleted; the card at the top says why.+ isBot ? null : !system ? (<Buttontype="button"variant="destructive-soft"@@ -2774,6 +2800,68 @@ 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 }) => {+ const { t } = useTranslation();+ const navigate = useNavigate();+ const { enabled, botForAgent, displayName, openProfile } = useBots();+ if (!enabled) return null;+ const bot = botForAgent(agent.name);+ if (agent.bot || bot) {+ const name = bot ? displayName(bot) : agent.bot?.display_name || agent.name;+ const builtin = bot?.builtin ?? agent.bot?.builtin ?? false;+ return (+ <div className="flex flex-col gap-2.5 rounded-[10px] border border-mint/40 bg-mint-soft px-3.5 py-3">+ <div className="flex items-center gap-2.5">+ {bot && <BotAvatar avatar={bot.avatar} name={name} size={32} />}+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">+ <span className="truncate text-[13px] font-bold text-foreground">{t('bots.agents.isBotTitle', { name })}</span>+ <span className="text-[11px] leading-relaxed text-muted">+ {builtin ? t('bots.agents.isMainBotHint') : t('bots.agents.isBotHint')}+ </span>+ </div>+ </div>+ {bot && (+ <div className="flex flex-wrap items-center gap-2">+ <Button type="button" variant="outline" size="xs" onClick={() => navigate(`/chat/${encodeURIComponent(bot.session_id)}`)}>+ {t('bots.agents.openConversation')}+ </Button>+ {canEdit && (+ <Button type="button" variant="ghost" size="xs" onClick={() => openProfile({ kind: 'edit', handle: bot.handle })}>+ {t('bots.agents.editProfile')}+ </Button>+ )}+ </div>+ )}+ </div>+ );+ }+ // Disabled Agents still show the way in, with what to do first.+ if (!canEdit || !eligibleForBot({ ...agent, enabled: true })) return null;+ 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>+ </div>+ <Button+ type="button"+ variant="outline"+ size="xs"+ disabled={!agent.enabled}+ onClick={() => openProfile({ kind: 'create', tab: 'agent', agentName: agent.name })}+ >+ {t('bots.agents.setAsBot')}+ </Button>+ </div>+ );+};+const Field: React.FC<{ label: string; labelRight?: React.ReactNode; children: React.ReactNode }> = ({label,labelRight,diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex 710b76bba..b29672ee7 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -4,7 +4,7 @@ import { useDesktopWindowChrome } from '../../context/DesktopWindowChromeContextimport { Fragment, forwardRef, memo, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { Link, useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';-import { Activity, ArrowLeft, ArrowRight, ArrowUpRight, Bell, Bot, ChevronDown, ChevronRight, Clock, Eye, GitFork, Image as ImageIcon, Info, Loader2, MapPin, MessageSquare, MessageSquareQuote, Terminal, Undo2, UploadCloud, X } from 'lucide-react';+import { Activity, ArrowLeft, ArrowRight, ArrowUpRight, Bell, Bot, ChevronDown, ChevronRight, Clock, Eye, GitFork, Image as ImageIcon, Info, Loader2, MapPin, MessageSquare, MessageSquareQuote, Pencil, Terminal, Undo2, UploadCloud, X } from 'lucide-react';import type { LucideIcon } from 'lucide-react';import clsx from 'clsx';@@ -13,6 +13,9 @@ import { selectApiErrorFields } from '../../context/apiErrorParse';import { useToast } from '../../context/ToastContext';import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';+import { useBots } from '../../context/BotsContext';+import { isBotSessionId, type BotAvatar as BotAvatarSpec } from '../../lib/bots';+import { BotAvatar } from '../ui/bot-avatar';import { useRegisterComposerTarget, type ComposerInsertTarget } from '../../context/ComposerBridgeContext';import { useWindowManager } from '../../context/WindowManagerContext';import type { SessionActivityItemKind, SessionActivityState, SessionRuntimeState, VaultRequest, VibeAgentBrief, WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';@@ -82,6 +85,7 @@ import {} from '../../lib/transcriptOrder';import { pickScrollAnchor, resolveScrollAnchor, type ScrollAnchor } from '../../lib/transcriptScrollAnchor';import { AgentRoutePicker } from './AgentRoutePicker';+import type { MentionSearchResult } from './MentionEditor';import {archiveSessionShortcutLabel,isArchiveSessionChord,@@ -260,6 +264,11 @@ export const ChatPage: React.FC = () => {const {capabilities,} = useInstanceAuthorization();+ // A Bot's permanent conversation (docs/plans/bots.md D5): the header shows the+ // Bot, and the Session cannot be archived or renamed. The id namespace says so+ // before the Bot list has answered; the list supplies the face.+ const { bots, loaded: botsLoaded, displayName: botDisplayName } = useBots();+ const botConversation = isBotSessionId(sessionId);const [sessionCanChat, setSessionCanChat] = useState(false);const canChat = capabilities.can_chat && sessionCanChat;const canManageShowPageAsInstance = capabilities.can_use_show_pages;@@ -2091,20 +2100,28 @@ export const ChatPage: React.FC = () => {],);- // @ mention source: all enabled Agents, filtered client-side (the set is small- // and already loaded for this session via bootstrap).+ // @ mention source (docs/plans/bots.md D3): the Owner's Bots first, then every+ // enabled Agent, filtered client-side (both sets are small and already loaded).+ // An Agent that is a Bot appears once, as the Bot.const searchAgents = useCallback(- async (query: string) => {+ async (query: string): Promise<MentionSearchResult[]> => {const q = query.trim().toLowerCase();- return agents- .filter((a) => a.enabled)+ // The live Bot list decides which Agents are Bots: this page's Agent rows are+ // a bootstrap snapshot, and a Bot removed since then is an Agent again.+ const botAgents = new Set(botsLoaded ? bots.map((bot) => bot.agent_name) : agents.filter((a) => a.bot).map((a) => a.name));+ const botResults: MentionSearchResult[] = bots+ .filter((bot) => !q || botDisplayName(bot).toLowerCase().includes(q) || bot.handle.includes(q))+ .map((bot) => ({ kind: 'bot', handle: bot.handle, display_name: botDisplayName(bot), avatar: bot.avatar }));+ const agentResults: MentionSearchResult[] = agents+ .filter((a) => a.enabled && !botAgents.has(a.name))// Names with the marker terminator (`>`) or a newline can't round-trip- // through @<name>, so they aren't mentionable.+ // through @<agent:name>, so they aren't mentionable..filter((a) => !/[>\n]/.test(a.name)).filter((a) => !q || a.name.toLowerCase().includes(q))- .map((a) => ({ name: a.name, agent_id: a.id, backend: a.backend, description: a.description }));+ .map((a) => ({ kind: 'agent', name: a.name, agent_id: a.id, backend: a.backend, description: a.description }));+ return [...botResults, ...agentResults];},- [agents],+ [agents, bots, botsLoaded, botDisplayName],);// # reference source: recent active sessions machine-wide (excluding the current@@ -2703,6 +2720,7 @@ export const ChatPage: React.FC = () => {session,writable: metadataWritable,lifecycleWritable: writable,+ botSession: botConversation,// Rename focuses the header's existing click-to-edit title instead of adding// a second editor for the same field.onRenameStart: () => titleFieldRef.current?.startEditing(),@@ -3101,6 +3119,7 @@ export const ChatPage: React.FC = () => {onPatch={patch}patchSaving={patchSaving}working={working}+ lockAgent={botConversation}/>) : null}/>}@@ -3649,6 +3668,20 @@ interface TitleFieldHandle {startEditing: () => void;}+// A Bot's empty conversation shows who it is: there is no automatic+// self-introduction, so its role is what the user reads first (D5).+const BotConversationEmpty: React.FC<{ name: string; avatar: BotAvatarSpec | null; role: string }> = ({ name, avatar, role }) => {+ const { t } = useTranslation();+ return (+ <div className="flex flex-1 flex-col items-center justify-center gap-3 px-6 text-center">+ <BotAvatar avatar={avatar} name={name} size={64} />+ <div className="max-w-[420px] text-[15px] font-semibold text-foreground">{t('bots.conversation.emptyTitle', { name })}</div>+ {role && <div className="max-w-[440px] text-[13px] leading-relaxed text-foreground/80">{role}</div>}+ <div className="max-w-[440px] text-[12px] leading-relaxed text-muted">{t('bots.conversation.emptyBody', { name })}</div>+ </div>+ );+};+interface ChatRoutePickerProps {session: WorkbenchSession;agents: VibeAgentBrief[];@@ -3658,12 +3691,15 @@ interface ChatRoutePickerProps {/** A queued ``onPatch`` write is still in flight. */patchSaving?: boolean;working: boolean;+ /** A Bot's conversation: its Agent is the Bot, so only the model, effort, and+ * speed move (docs/plans/bots.md D5); the server refuses any other route. */+ lockAgent?: boolean;}// The live session's agent/model/effort picker, hosted by the composer's action// row: the route is "who answers the next message", so it sits beside Send.// Read-only sessions never mount it — their header names the frozen route.-const ChatRoutePicker: React.FC<ChatRoutePickerProps> = ({ session, agents, defaultAgentName, onPatch, patchSaving, working }) => {+const ChatRoutePicker: React.FC<ChatRoutePickerProps> = ({ session, agents, defaultAgentName, onPatch, patchSaving, working, lockAgent = false }) => {const { t } = useTranslation();const api = useApi();const defaultAgent = defaultAgentName ? agents.find((agent) => agent.name === defaultAgentName) : null;@@ -3698,8 +3734,11 @@ const ChatRoutePicker: React.FC<ChatRoutePickerProps> = ({ session, agents, defa: null;const backendLocked =(nativeBound && concreteBackend === 'vibey') || working || Boolean(pendingForkBackend);- const pinnedBackend = pendingForkBackend ?? (backendLocked ? concreteBackend : null);- const canClearToDefault = !backendLocked && !nativeBound;+ const pinnedBackend = lockAgent+ ? concreteBackend+ : pendingForkBackend ?? (backendLocked ? concreteBackend : null);+ const canClearToDefault = !lockAgent && !backendLocked && !nativeBound;+ const pickableAgents = lockAgent ? agents.filter((agent) => agent.name === session.agent_name) : agents;const pickerDisabled = working && !concreteBackend && !pendingForkBackend;const defaultRoute = defaultAgent? {@@ -3716,7 +3755,8 @@ const ChatRoutePicker: React.FC<ChatRoutePickerProps> = ({ session, agents, defa<AgentRoutePickerpresentation="compact"value={session}- agents={agents}+ agents={pickableAgents}+ agentLocked={lockAgent}onChange={onPatch}saving={patchSaving}disabled={pickerDisabled}@@ -3783,6 +3823,12 @@ interface ChatHeaderBarProps {// which renders the header alone rather than mounting the whole page.export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, onBack, showPageMode, showPageBusy, onToggleShowPage, onPrepareShowPageLaunch, onShowPageVisibilityChange, onShareOpenChange, annotation, onAnnotateOpenChange, readOnlyReason, writable = readOnlyReason === null, showPageAccess = null, canOpenShowPage = true, canManageShowPage = true, canManageInstance = false, canPinToDock = false, sessionActions, titleFieldRef }) => {const { t } = useTranslation();+ // A Bot's conversation (docs/plans/bots.md D5) shows the Bot — avatar, display+ // name, and "Edit profile" — in place of the editable title. Its id says it is+ // a Bot's before the Bot list answers; until then the title stays static.+ const { botForSession, displayName: botDisplayName, openProfile: openBotProfile } = useBots();+ const conversationBot = botForSession(session.id);+ const botConversation = isBotSessionId(session.id);const windowChrome = useDesktopWindowChrome();const readOnly = !writable;const sessionReadOnly = readOnlyReason !== null;@@ -3827,13 +3873,34 @@ export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, d><ArrowLeft className="size-3.5" /></Button>- <TitleField- key={session.id}- ref={titleFieldRef}- title={session.title}- onCommit={(title) => onPatch({ title })}- readOnly={readOnly}- />+ {conversationBot ? (+ <div className="flex min-w-0 items-center gap-2">+ <BotAvatar avatar={conversationBot.avatar} name={botDisplayName(conversationBot)} size={26} />+ <span className="min-w-0 truncate text-[16px] font-bold text-foreground">{botDisplayName(conversationBot)}</span>+ {writable && (+ <Button+ type="button"+ variant="ghost"+ size="xs"+ onClick={() => openBotProfile({ kind: 'edit', handle: conversationBot.handle })}+ aria-label={t('bots.conversation.editProfile')}+ className="shrink-0 text-muted hover:text-foreground"+ >+ <Pencil className="size-3" />+ {/* A phone's header keeps the pencil alone; the name needs the room. */}+ <span className="max-md:hidden">{t('bots.conversation.editProfile')}</span>+ </Button>+ )}+ </div>+ ) : (+ <TitleField+ key={session.id}+ ref={titleFieldRef}+ title={session.title}+ onCommit={(title) => onPatch({ title })}+ readOnly={readOnly || botConversation}+ />+ )}{/* Desktop: the session menu belongs to the session's name, so it sitsright after the title rather than among the page-level controls onthe right. Mobile keeps its own trigger at the far right below. */}@@ -4150,6 +4217,9 @@ export const Transcript: React.FC<TranscriptProps> = ({const { t } = useTranslation();const { instanceKind } = useInstanceAuthorization();const recovery = useModelHubRecovery(modelRecovery, working);+ // A Bot's empty conversation shows who it is (docs/plans/bots.md D5).+ const { botForSession, displayName: botDisplayName } = useBots();+ const conversationBot = botForSession(session.id);const navigate = useNavigate();const { openApp } = useWindowManager();const fileViewer = useFileViewer();@@ -4657,6 +4727,12 @@ export const Transcript: React.FC<TranscriptProps> = ({<div className="max-w-[440px] text-[12px] leading-relaxed">{t('chat.forkedEmptyBody')}</div></div></>+ ) : conversationBot ? (+ <BotConversationEmpty+ name={botDisplayName(conversationBot)}+ avatar={conversationBot.avatar}+ role={conversationBot.role}+ />) : (<div className="flex flex-1 flex-col items-center justify-center gap-3 px-6 text-center text-muted"><MessageSquare className="size-8 opacity-60" />diff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsxindex 61781d5ca..0522fd31b 100644--- a/ui/src/components/workbench/Composer.tsx+++ b/ui/src/components/workbench/Composer.tsx@@ -67,7 +67,7 @@ import { inForegroundSurface } from './chatShortcuts';import { useRouteSurfaceWindowEvent } from '../../lib/routeSurfaceActivity';import {MentionEditor,- type AgentSearchResult,+ type MentionSearchResult,type MentionEditorHandle,type SessionSearchResult,} from './MentionEditor';@@ -421,7 +421,7 @@ export interface ComposerProps {/** When BOTH are provided, the input upgrades to the rich mention editor:* `@` autocompletes enabled Agents, `#` autocompletes Sessions. Leaving them* unset keeps the plain textarea (e.g. the Workbench home). */- onSearchAgents?: (query: string) => Promise<AgentSearchResult[]>;+ onSearchAgents?: (query: string) => Promise<MentionSearchResult[]>;onSearchSessions?: (query: string) => Promise<SessionSearchResult[]>;/** The chat's latest Agent reply, read once when dictation starts and sent to* realtime recognition as context. Surfaces without one leave it unset. */diff --git a/ui/src/components/workbench/InboxPage.tsx b/ui/src/components/workbench/InboxPage.tsxindex ffac824a7..bb9be2b9e 100644--- a/ui/src/components/workbench/InboxPage.tsx+++ b/ui/src/components/workbench/InboxPage.tsx@@ -6,12 +6,15 @@ import clsx from 'clsx';import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';+import { useBots } from '../../context/BotsContext';import type { InboxSession } from '../../context/ApiContext';import { formatRelativeTime } from '../../lib/relativeTime';import { Markdown } from '../ui/markdown';import { Button } from '../ui/button';import { WebPushControl } from './WebPushControl';import { useInboxScrollRestoration } from './useInboxScrollRestoration';+import { BotAvatar } from '../ui/bot-avatar';+import { BotTag } from './bots/BotTag';import {readInboxFilter,writeInboxFilter,@@ -25,6 +28,7 @@ export const InboxPage: React.FC<{ onOpenSearch: () => void }> = ({ onOpenSearchconst navigate = useNavigate();const location = useLocation();const listRef = useRef<HTMLDivElement>(null);+ const { botForSession, displayName: botName } = useBots();const {capabilities,} = useInstanceAuthorization();@@ -256,6 +260,9 @@ export const InboxPage: React.FC<{ onOpenSearch: () => void }> = ({ onOpenSearchconst unread = unreadOf(s);const projectLabel = s.project_name || s.project_id || 'avibe';const sessionLabel = s.title?.trim() || s.session_id;+ // A Bot's conversation reads as the Bot: avatar, name, and a small Bot+ // tag in place of "project · title" (docs/plans/bots.md D5).+ const bot = botForSession(s.session_id);return (<articlekey={s.session_id}@@ -268,13 +275,24 @@ export const InboxPage: React.FC<{ onOpenSearch: () => void }> = ({ onOpenSearch)}><div className="flex items-center gap-2 text-[11px]">- <span className="inline-flex max-w-[40%] items-center gap-1 truncate rounded-md border border-border-strong bg-surface-2 px-2 py-0.5 font-semibold text-cyan-ink">- {projectLabel}- </span>- <span className="text-muted">·</span>- <span className="flex-1 truncate text-[13px] font-semibold text-foreground">- {sessionLabel}- </span>+ {bot ? (+ <>+ <BotAvatar avatar={bot.avatar} name={botName(bot)} size={24} />+ <span className="min-w-0 truncate text-[13px] font-semibold text-foreground">{botName(bot)}</span>+ <BotTag />+ <span className="flex-1" />+ </>+ ) : (+ <>+ <span className="inline-flex max-w-[40%] items-center gap-1 truncate rounded-md border border-border-strong bg-surface-2 px-2 py-0.5 font-semibold text-cyan-ink">+ {projectLabel}+ </span>+ <span className="text-muted">·</span>+ <span className="flex-1 truncate text-[13px] font-semibold text-foreground">+ {sessionLabel}+ </span>+ </>+ )}{s.replied && (<span className="inline-flex items-center gap-1 rounded-md border border-cyan/30 bg-cyan/[0.08] px-1.5 py-0.5 text-[10px] font-semibold text-cyan-ink"><MessageSquareReply className="size-2.5" />diff --git a/ui/src/components/workbench/MentionEditor.mentions.test.tsx b/ui/src/components/workbench/MentionEditor.mentions.test.tsxnew file mode 100644index 000000000..a619343ae--- /dev/null+++ b/ui/src/components/workbench/MentionEditor.mentions.test.tsx@@ -0,0 +1,59 @@+/* @vitest-environment jsdom */++import { createRef } from 'react';+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++vi.hoisted(() => {+ Object.defineProperty(window, 'matchMedia', {+ configurable: true,+ value: vi.fn().mockReturnValue({ matches: false }),+ });+});++import { MentionEditor, type MentionEditorHandle } from './MentionEditor';++afterEach(cleanup);++// The editor owns the marker a picked mention becomes (docs/plans/bots.md D3):+// a Bot's chip shows its display name while the text carries its frozen handle,+// and an Agent's marker names its kind, so the two never read alike.+describe('MentionEditor typed mentions', () => {+ it('serializes a Bot by handle and an Agent by name, each with its kind', async () => {+ const ref = createRef<MentionEditorHandle>();+ const onChange = vi.fn();+ render(+ <MentionEditor+ ref={ref}+ placeholder="Message"+ onChange={onChange}+ onSubmit={vi.fn()}+ onSearchAgents={async () => []}+ onSearchSessions={async () => []}+ />,+ );+ const editor = screen.getByLabelText('Message');+ await waitFor(() => expect(ref.current).not.toBeNull());++ act(() => {+ ref.current?.setText('Ask ');+ ref.current?.insertMention('@', '首席安全官', { kind: 'bot', handle: 'cso' });+ });+ await waitFor(() => expect(editor.querySelector('[data-beautiful-mention="@首席安全官"]')).not.toBeNull());+ act(() => {+ ref.current?.insertMention('@', 'reviewer', { kind: 'agent', agentId: 'agt-reviewer', backend: 'claude' });+ });++ await waitFor(() => {+ const [text, references] = onChange.mock.calls.at(-1)!;+ expect(text).toBe('Ask @<bot:cso> @<agent:reviewer> ');+ expect(references).toEqual([+ { kind: 'bot', handle: 'cso', display_name: '首席安全官' },+ { kind: 'agent', name: 'reviewer', agent_id: 'agt-reviewer', backend: 'claude' },+ ]);+ });+ // The chip reads as the Bot, not as its handle.+ expect(editor.textContent).toContain('@首席安全官');+ expect(editor.textContent).not.toContain('cso');+ });+});diff --git a/ui/src/components/workbench/MentionEditor.tsx b/ui/src/components/workbench/MentionEditor.tsxindex e56a7ba3f..0d7e25194 100644--- a/ui/src/components/workbench/MentionEditor.tsx+++ b/ui/src/components/workbench/MentionEditor.tsx@@ -40,16 +40,25 @@ import {BeautifulMentionsPlugin,BeautifulMentionNode,$isBeautifulMentionNode,+ createBeautifulMentionNode,useBeautifulMentions,+ type BeautifulMentionComponentProps,type BeautifulMentionsItem,type BeautifulMentionsMenuProps,type BeautifulMentionsMenuItemProps,} from 'lexical-beautiful-mentions';+import { useTranslation } from 'react-i18next';+import { filesFromClipboard } from '../../lib/clipboardFiles';import { isSoftKeyboardOpen, isTouchCapableDevice } from '../../lib/softKeyboard';import { cn } from '../../lib/utils';import { dedupeReferences, type MentionReference } from '../../lib/mentions';+import type { BotAvatar as BotAvatarSpec } from '../../lib/bots';+import { useBots } from '../../context/BotsContext';+import { BotAvatar } from '../ui/bot-avatar';+import { BackendAvatar } from '../visual';+import type { BackendId } from '../../lib/agentBackends';import {applyVoiceInsertionWithSnapshot,voiceInsertionSnapshot,@@ -59,11 +68,20 @@ import { isComposingKey } from '@/lib/imeComposition';import { useLatestRef } from '@/lib/useLatestRef';export type AgentSearchResult = {+ kind?: 'agent';name: string;agent_id?: string | null;backend?: string | null;description?: string | null;};+/** A Bot in the `@` list (docs/plans/bots.md D3): it leads the list, with its avatar. */+export type BotSearchResult = {+ kind: 'bot';+ handle: string;+ display_name: string;+ avatar: BotAvatarSpec | null;+};+export type MentionSearchResult = AgentSearchResult | BotSearchResult;export type SessionSearchResult = { session_id: string; title?: string | null };export interface MentionEditorHandle {@@ -119,7 +137,8 @@ export interface MentionEditorProps {isVoicePreview?: boolean,) => void;onSubmit: () => void;- onSearchAgents: (query: string) => Promise<AgentSearchResult[]>;+ /** The `@` list: Bots first, then Agents. */+ onSearchAgents: (query: string) => Promise<MentionSearchResult[]>;onSearchSessions: (query: string) => Promise<SessionSearchResult[]>;/** Pasting a file into the editor (clipboard screenshot or OS-copied file)* hands it here instead of pasting as text. Unset → paste behaves as plain@@ -145,6 +164,12 @@ function nodeToMarkerText(node: LexicalNode, refs: MentionReference[]): string {const value = node.getValue();const data = (node.getData() ?? {}) as Record<string, string | number | boolean | null>;if (trigger === '@') {+ // The kind decides the meaning (D3): a Bot's chip shows its display name+ // but its marker carries the frozen handle, so a rename never alters it.+ if (data.kind === 'bot' && typeof data.handle === 'string' && data.handle) {+ refs.push({ kind: 'bot', handle: data.handle, display_name: value });+ return `@<bot:${data.handle}>`;+ }// The marker terminates at the first `>`; a name containing `>` (or a// newline) would serialize to an ambiguous `@<a>b>`. Such names can't be// round-tripped, so fall back to plain text rather than a broken marker.@@ -156,7 +181,7 @@ function nodeToMarkerText(node: LexicalNode, refs: MentionReference[]): string {agent_id: data.agentId != null ? String(data.agentId) : undefined,backend: data.backend != null ? String(data.backend) : undefined,});- return `@<${value}>`;+ return `@<agent:${value}>`;}if (trigger === '#') {const sessionId = data.sessionId != null ? String(data.sessionId) : value;@@ -782,27 +807,72 @@ MentionMenu.displayName = 'MentionMenu';const MentionMenuItem = forwardRef<HTMLLIElement, BeautifulMentionsMenuItemProps>(({ selected, item, itemValue: _itemValue, label: _label, ...props }, ref) => {+ const { t } = useTranslation();const data = (item.data ?? {}) as Record<string, string | number | boolean | null>;+ const isBot = item.trigger === '@' && data.kind === 'bot';// Agents show their backend as a secondary hint; sessions show only the title.- const secondary = item.trigger === '@' && data.backend != null ? String(data.backend) : '';+ const secondary = item.trigger === '@' && !isBot && data.backend != null ? String(data.backend) : '';return (<liref={ref}className={cn('flex cursor-pointer select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none',selected ? 'bg-accent/10 text-accent-ink' : 'text-text',+ // Bots lead the list; a hairline separates them from the Agents (D3).+ data.groupStart === true && 'relative mt-1.5 before:absolute before:inset-x-1 before:-top-1 before:h-px before:bg-border',)}{...props}>- <span className="shrink-0 text-muted">{item.trigger}</span>+ {isBot ? (+ <MentionBotAvatar handle={String(data.handle ?? '')} name={item.value} />+ ) : item.trigger === '@' && data.backend != null ? (+ <BackendAvatar backend={String(data.backend) as BackendId} size={16} className="size-4 shrink-0 text-muted" />+ ) : (+ <span className="shrink-0 text-muted">{item.trigger}</span>+ )}<span className="truncate">{item.value}</span>- {secondary ? <span className="ml-auto shrink-0 text-xs text-muted">{secondary}</span> : null}+ {isBot ? (+ <span className="ml-auto shrink-0 font-mono text-xs text-muted">{t('bots.handle', { handle: String(data.handle ?? '') })}</span>+ ) : secondary ? (+ <span className="ml-auto shrink-0 text-xs text-muted">{secondary}</span>+ ) : null}</li>);},);MentionMenuItem.displayName = 'MentionMenuItem';+/** A Bot's avatar in the `@` list or a chip, read live so it follows edits. */+const MentionBotAvatar: React.FC<{ handle: string; name: string; size?: number }> = ({ handle, name, size = 18 }) => {+ const { botForHandle } = useBots();+ return <BotAvatar avatar={botForHandle(handle)?.avatar ?? null} name={name} size={size} />;+};++// The chip a picked mention becomes. A Bot's chip carries its avatar beside the+// display name (D3); every other chip renders exactly as the default node did.+const MentionChip = forwardRef<HTMLSpanElement, BeautifulMentionComponentProps<Record<string, string | number | boolean | null>>>(+ ({ trigger, value, data, children, className, ...rest }, ref) => {+ if (trigger === '@' && data?.kind === 'bot' && typeof data.handle === 'string') {+ return (+ <span ref={ref} className={cn(className, 'inline-flex items-center gap-1 pl-0.5 align-bottom')} {...rest}>+ <MentionBotAvatar handle={data.handle} name={value} size={14} />+ <span>{children}</span>+ </span>+ );+ }+ return (+ <span ref={ref} className={className} {...rest}>+ {children}+ </span>+ );+ },+);+MentionChip.displayName = 'MentionChip';++// One custom node class per app (the library keeps it as a singleton), so the+// replacement is built once at module load rather than per editor.+const MENTION_NODES = createBeautifulMentionNode(MentionChip);+// A Lexical-backed text input with `@` (agent) / `#` (session) inline-chip// mentions. Owns only the editor; the surrounding composer shell (send button,// attachment chips, voice) stays in Composer.@@ -840,12 +910,23 @@ export const MentionEditor = forwardRef<MentionEditorHandle, MentionEditorProps>async (trigger: string, queryString?: string | null): Promise<BeautifulMentionsItem[]> => {const query = (queryString ?? '').trim();if (trigger === '@') {- const agents = await onSearchAgents(query);- return agents.map((a) => ({- value: a.name,- agentId: a.agent_id ?? null,- backend: a.backend ?? null,- }));+ const results = await onSearchAgents(query);+ const hasBots = results.some((result) => result.kind === 'bot');+ let firstAgent = true;+ return results.map((result): BeautifulMentionsItem => {+ if (result.kind === 'bot') {+ return { value: result.display_name, kind: 'bot', handle: result.handle };+ }+ const groupStart = hasBots && firstAgent;+ firstAgent = false;+ return {+ value: result.name,+ kind: 'agent',+ agentId: result.agent_id ?? null,+ backend: result.backend ?? null,+ groupStart,+ };+ });}if (trigger === '#') {const sessions = await onSearchSessions(query);@@ -867,7 +948,7 @@ export const MentionEditor = forwardRef<MentionEditorHandle, MentionEditorProps>const [initialConfig] = useState(() => ({namespace: 'avibe-mention-composer',theme: { beautifulMentions: MENTION_THEME },- nodes: [BeautifulMentionNode],+ nodes: [...MENTION_NODES],editable: !disabled,onError: (error: Error) => {// Surface in dev; never throw out of the editor and wipe the box.@@ -899,7 +980,7 @@ export const MentionEditor = forwardRef<MentionEditorHandle, MentionEditorProps>triggers={['@', '#']}onSearch={onSearch}searchDelay={150}- menuItemLimit={8}+ menuItemLimit={12}// Allow `@`/`#` after a word boundary without a leading space (including// CJK, which has no inter-word spaces) but NOT inside a Latin word / number// / `_` token, so ordinary text like `name@host` or `C#` doesn't open thediff --git a/ui/src/components/workbench/WorkbenchSidebar.inbox.test.tsx b/ui/src/components/workbench/WorkbenchSidebar.inbox.test.tsxindex 9ac73e981..c35ca5828 100644--- a/ui/src/components/workbench/WorkbenchSidebar.inbox.test.tsx+++ b/ui/src/components/workbench/WorkbenchSidebar.inbox.test.tsx@@ -94,7 +94,7 @@ const sidebarElement = (active = true, onOpenSearch?: () => void) => ();const renderSidebar = (active = true, onOpenSearch?: () => void) => render(sidebarElement(active, onOpenSearch));-const inboxIcon = () => screen.getByRole('link', { name: en.workbench.nav.inbox }).querySelector('svg')!;+const inboxIcon = () => screen.getByRole('link', { name: (name) => name.startsWith(en.workbench.nav.inbox) }).querySelector('svg')!;const projectsToggle = () => screen.getByRole('button', { name: en.workbench.projectsLabel });beforeEach(() => {@@ -127,7 +127,8 @@ describe('Workbench sidebar inbox counter', () => {const link = screen.getByRole('link', { name: en.workbench.nav.inbox });// A zero badge is still a badge — an empty inbox draws no attention at all.- expect(link.textContent).toBe(en.workbench.nav.inbox);+ // The entry is the brand row's icon (docs/plans/bots.md D5), so it holds no text.+ expect(link.textContent).toBe('');// Cyan is the unread read; the resting row is plain foreground ink.expect(inboxIcon().getAttribute('class')).toContain('text-foreground');expect(inboxIcon().getAttribute('class')).not.toContain('text-cyan-ink');@@ -139,7 +140,8 @@ describe('Workbench sidebar inbox counter', () => {inbox.unreadBySession = { ses_a: 4, ses_b: 3 };renderSidebar();- expect(screen.getByRole('link', { name: en.workbench.nav.inbox }).textContent).toBe(`${en.workbench.nav.inbox}7`);+ const link = screen.getByRole('link', { name: en.workbench.inbox.navUnread.replace('{{count}}', '7') });+ expect(link.textContent).toBe('7');expect(inboxIcon().getAttribute('class')).toContain('text-cyan-ink');});@@ -147,7 +149,7 @@ describe('Workbench sidebar inbox counter', () => {inbox.totalUnread = 150;renderSidebar();- expect(screen.getByRole('link', { name: en.workbench.nav.inbox }).textContent).toBe(`${en.workbench.nav.inbox}99+`);+ expect(screen.getByRole('link', { name: en.workbench.inbox.navUnread.replace('{{count}}', '150') }).textContent).toBe('99+');});it('keeps Search in the Projects header, before New Project and without needing it', async () => {diff --git a/ui/src/components/workbench/WorkbenchSidebar.tsx b/ui/src/components/workbench/WorkbenchSidebar.tsxindex a33caaa5a..964bae0d1 100644--- a/ui/src/components/workbench/WorkbenchSidebar.tsx+++ b/ui/src/components/workbench/WorkbenchSidebar.tsx@@ -56,6 +56,10 @@ import { NewProjectDialog } from './NewProjectDialog';import { ProjectAgentsMdDialog } from './ProjectAgentsMdDialog';import { ProjectSettingsDialog } from './ProjectSettingsDialog';import { SortableProjectList, type ProjectDragHandle } from './SortableProjectList';+import { BotStrip } from './bots/BotStrip';+import { BotAvatar } from '../ui/bot-avatar';+import { BotTag } from './bots/BotTag';+import { useBots } from '../../context/BotsContext';import logoImg from '../../assets/logo.png';interface CapabilityNavItem {@@ -137,6 +141,7 @@ const InboxHoverPopover: React.FC<{}) => {const { t } = useTranslation();const navigate = useNavigate();+ const { botForSession, displayName: botName } = useBots();// The unread map is authoritative; a session absent from it has 0 unread// (don't fall back to the card's stale unread_count — see InboxPage).const unreadOf = (s: InboxSession) => unreadBySession[s.session_id] ?? 0;@@ -221,6 +226,54 @@ const InboxHoverPopover: React.FC<{{shown.map((s) => {const unread = unreadOf(s);const projectLabel = s.project_name || s.project_id || 'avibe';+ const bot = botForSession(s.session_id);+ const replied = s.replied ? (+ <span className="shrink-0 font-semibold text-cyan-ink" title={t('workbench.inbox.replied')}>+ ↩+ </span>+ ) : null;+ const preview = s.preview_text ? (+ <div+ className={clsx(+ 'line-clamp-2 text-[11.5px] leading-relaxed',+ unread > 0 ? 'text-foreground' : 'text-muted',+ )}+ >+ <Markdown content={s.preview_text} interactive={false} className="vr-markdown--preview" />+ </div>+ ) : (+ <div className="text-[11.5px] leading-relaxed text-muted">—</div>+ );+ if (bot) {+ // A Bot's conversation reads as the Bot: its avatar and name with a+ // small Bot tag, instead of "project · title" (docs/plans/bots.md D5).+ const name = botName(bot);+ return (+ <button+ key={s.session_id}+ type="button"+ onClick={() => onItemClick(s)}+ className={clsx(+ 'flex gap-2.5 rounded-lg px-3 py-2.5 text-left transition',+ unread > 0+ ? 'border-l-2 border-mint bg-mint/[0.06] hover:bg-mint/[0.10]'+ : 'hover:bg-foreground/[0.04]',+ )}+ >+ <BotAvatar avatar={bot.avatar} name={name} size={28} className="mt-0.5" />+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ <div className="flex items-center gap-1.5 text-[11px]">+ <span className="truncate font-bold text-foreground">{name}</span>+ <BotTag />+ <span className="flex-1" />+ {replied}+ <span className="shrink-0 font-mono text-[10px] text-muted">{formatRelativeTime(s.last_activity_at, t)}</span>+ </div>+ {preview}+ </div>+ </button>+ );+ }return (<buttonkey={s.session_id}@@ -239,25 +292,10 @@ const InboxHoverPopover: React.FC<{<span className="flex-1 truncate font-semibold text-foreground">{s.title?.trim() || s.session_id}</span>- {s.replied && (- <span className="shrink-0 font-semibold text-cyan-ink" title={t('workbench.inbox.replied')}>- ↩- </span>- )}+ {replied}<span className="font-mono text-muted">{formatRelativeTime(s.last_activity_at, t)}</span></div>- {s.preview_text ? (- <div- className={clsx(- 'line-clamp-2 text-[11.5px] leading-relaxed',- unread > 0 ? 'text-foreground' : 'text-muted',- )}- >- <Markdown content={s.preview_text} interactive={false} className="vr-markdown--preview" />- </div>- ) : (- <div className="text-[11.5px] leading-relaxed text-muted">—</div>- )}+ {preview}</button>);})}@@ -873,8 +911,11 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOpmark keeps the approved chip treatment (32px, mint hairline over amint well, resting glow that strengthens on hover) inside thissidebar's own padding, so the adjustable width still governs the- column. Search is a compact icon in the Projects header below. */}- <div className="flex shrink-0 items-center pb-3">+ column. The Inbox is the icon at the row's right end (docs/plans/bots.md+ D5): hover opens the same floating popover, a click the full Inbox. At+ zero unread there is no badge node at all and the icon stays+ uncoloured; both reads come from the same real counter. */}+ <div className="flex shrink-0 items-center gap-2 pb-3"><Linkto="/"className="group flex min-w-0 items-center gap-2.5 rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mint/60"@@ -892,59 +933,56 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp<div className="truncate text-[11px] text-muted">{t('appShell.subtitle')}</div></div></Link>+ <Popover open={popoverOpen} onOpenChange={(open) => { if (!open) setPopoverOpen(false); }}>+ <PopoverAnchor asChild>+ <div className="ml-auto shrink-0" onMouseEnter={openPopover} onMouseLeave={queueClose}>+ <NavLink+ to="/inbox"+ aria-label={badge ? t('workbench.inbox.navUnread', { count: totalUnread }) : t('workbench.nav.inbox')}+ title={t('workbench.nav.inbox')}+ className={({ isActive }) =>+ clsx(+ 'relative grid size-8 place-items-center rounded-lg border transition-colors',+ // Cyan active state per design.pen ze15A — mint is reserved+ // for sessions / projects so the two reads stay distinct.+ isActive+ ? 'border-cyan/40 bg-cyan-soft shadow-glow-sm-cyan'+ : 'border-transparent hover:bg-foreground/[0.04]',+ )+ }+ >+ {({ isActive }) => (+ <>+ {/* Cyan is what unread means here, so the counter colours the+ icon on any route — not only while Inbox is the open one. */}+ <Inbox className={clsx('size-[18px]', badge || isActive ? 'text-cyan-ink' : 'text-foreground')} />+ {badge && (+ <span className="absolute -right-1 -top-1 inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-cyan px-1 font-mono text-[9px] font-bold text-accent-foreground shadow-glow-xs-cyan">+ {badge}+ </span>+ )}+ </>+ )}+ </NavLink>+ </div>+ </PopoverAnchor>+ <InboxHoverPopover+ sessions={inboxSessions}+ unreadBySession={unreadBySession}+ unreadSessions={unreadSessions}+ totalUnread={totalUnread}+ canMarkRead={canChat}+ onItemClick={onItemClick}+ onMarkAllRead={onMarkAllRead}+ onMouseEnter={openPopover}+ onMouseLeave={queueClose}+ />+ </Popover></div>- {/* Inbox entry — hover opens the floating popover (portaled above the chat).- Search is a compact icon in the Projects header below, so this row keeps- the full width the approved design gives it. At zero unread there is no- badge node at all and the icon stays uncoloured; both reads come from- the same real counter. */}- <Popover open={popoverOpen} onOpenChange={(open) => { if (!open) setPopoverOpen(false); }}>- <PopoverAnchor asChild>- <div className="w-full" onMouseEnter={openPopover} onMouseLeave={queueClose}>- <NavLink- to="/inbox"- aria-label={t('workbench.nav.inbox')}- className={({ isActive }) =>- clsx(- 'group flex w-full items-center gap-2.5 rounded-lg border px-3 py-2.5 text-[13px] font-semibold transition-colors',- // Cyan active state per design.pen ze15A — mint is reserved- // for sessions / projects so the two reads stay distinct.- isActive- ? 'border-cyan/40 bg-cyan-soft text-foreground shadow-glow-sm-cyan'- : 'border-border-strong text-foreground hover:bg-foreground/[0.04]',- )- }- >- {({ isActive }) => (- <>- {/* Cyan is what unread means here, so the counter colours the- icon on any route — not only while Inbox is the open one. */}- <Inbox className={clsx('size-4', badge || isActive ? 'text-cyan-ink' : 'text-foreground')} />- <span className="flex-1">{t('workbench.nav.inbox')}</span>- {badge && (- <span className="inline-flex min-w-[1.25rem] items-center justify-center rounded-full bg-cyan px-1.5 py-0.5 font-mono text-[9px] font-bold text-accent-foreground shadow-glow-xs-cyan">- {badge}- </span>- )}- <ChevronRight className="size-3.5 text-muted opacity-0 transition-opacity group-hover:opacity-100" />- </>- )}- </NavLink>- </div>- </PopoverAnchor>- <InboxHoverPopover- sessions={inboxSessions}- unreadBySession={unreadBySession}- unreadSessions={unreadSessions}- totalUnread={totalUnread}- canMarkRead={canChat}- onItemClick={onItemClick}- onMarkAllRead={onMarkAllRead}- onMouseEnter={openPopover}- onMouseLeave={queueClose}- />- </Popover>+ {/* Bots — the Owner's standing members take the Inbox row's old place+ (docs/plans/bots.md D5). Nobody else sees the strip. */}+ <BotStrip unreadBySession={unreadBySession} />{/* Capabilities m8K59 — a collapsible group, so a long project list canreclaim the rows. The label leads and the chevron closes the row on thediff --git a/ui/src/components/workbench/bots/BotAvatarPicker.tsx b/ui/src/components/workbench/bots/BotAvatarPicker.tsxnew file mode 100644index 000000000..279017002--- /dev/null+++ b/ui/src/components/workbench/bots/BotAvatarPicker.tsx@@ -0,0 +1,164 @@+import { useRef, useState } from 'react';+import type { CSSProperties } from 'react';+import { useTranslation } from 'react-i18next';+import { RotateCcw, Upload } from 'lucide-react';+import clsx from 'clsx';++import { BOT_AVATAR_EMOJIS, BOT_AVATAR_HUES } from '@/lib/bots';+import { SegmentedRadio } from '../../ui/segmented';++/** What the user picked in the dialog, before anything is saved. */+export type BotAvatarChoice =+ | { kind: 'keep' }+ | { kind: 'default' }+ | { kind: 'emoji'; emoji: string; hue: number }+ | { kind: 'image'; file: File; previewUrl: string };++/** The server scales an upload to 256px; it refuses anything over 10 MB. */+export const BOT_AVATAR_MAX_BYTES = 10 * 1024 * 1024;+const ACCEPTED_TYPES = ['image/png', 'image/jpeg', 'image/webp'];++interface BotAvatarPickerProps {+ /** The emoji avatar the picker starts from, if the current choice is one. */+ current: { emoji: string; hue: number } | null;+ onPick: (choice: BotAvatarChoice) => void;+ /** Offered only when the Bot has something other than its default to undo. */+ canUseDefault: boolean;+ onError: (message: string) => void;+}++/** The avatar picker the add/edit dialog opens: an emoji on a hue, or an uploaded+ * image that the server crops to a circle (D5). AI-generated avatars are out of+ * the first version. */+export const BotAvatarPicker: React.FC<BotAvatarPickerProps> = ({ current, onPick, canUseDefault, onError }) => {+ const { t } = useTranslation();+ const [tab, setTab] = useState<'emoji' | 'upload'>('emoji');+ const [emoji, setEmoji] = useState<string>(current?.emoji ?? BOT_AVATAR_EMOJIS[0]);+ const [hue, setHue] = useState<number>(current?.hue ?? BOT_AVATAR_HUES[0]);+ const [dragging, setDragging] = useState(false);+ const inputRef = useRef<HTMLInputElement | null>(null);++ const pickEmoji = (nextEmoji: string, nextHue: number) => {+ setEmoji(nextEmoji);+ setHue(nextHue);+ onPick({ kind: 'emoji', emoji: nextEmoji, hue: nextHue });+ };++ const takeFile = (file: File | undefined) => {+ if (!file) return;+ if (!ACCEPTED_TYPES.includes(file.type)) {+ onError(t('bots.avatarPicker.unsupported'));+ return;+ }+ if (file.size > BOT_AVATAR_MAX_BYTES) {+ onError(t('bots.avatarPicker.tooLarge'));+ return;+ }+ onPick({ kind: 'image', file, previewUrl: URL.createObjectURL(file) });+ };++ return (+ <div className="flex flex-col gap-3">+ <SegmentedRadio+ value={tab}+ onChange={setTab}+ ariaLabel={t('bots.dialog.avatar')}+ options={[+ { id: 'emoji', label: t('bots.avatarPicker.emoji') },+ { id: 'upload', label: t('bots.avatarPicker.upload') },+ ]}+ />+ {tab === 'emoji' ? (+ <>+ <div className="grid grid-cols-8 gap-1.5" role="radiogroup" aria-label={t('bots.avatarPicker.emoji')}>+ {BOT_AVATAR_EMOJIS.map((value) => {+ const selected = current !== null && value === emoji;+ return (+ <button+ key={value}+ type="button"+ role="radio"+ aria-checked={selected}+ onClick={() => pickEmoji(value, hue)}+ className={clsx(+ 'grid aspect-square place-items-center rounded-lg text-[17px] transition',+ selected ? 'bg-mint-soft ring-[1.5px] ring-inset ring-mint' : 'hover:bg-foreground/[0.05]',+ )}+ >+ {value}+ </button>+ );+ })}+ </div>+ <div className="flex flex-col gap-1.5">+ <span className="text-[11px] font-semibold text-muted">{t('bots.avatarPicker.background')}</span>+ <div className="flex flex-wrap gap-2" role="radiogroup" aria-label={t('bots.avatarPicker.background')}>+ {BOT_AVATAR_HUES.map((value) => {+ const selected = current !== null && value === hue;+ return (+ <button+ key={value}+ type="button"+ role="radio"+ aria-checked={selected}+ aria-label={t('bots.avatarPicker.hue', { hue: value })}+ onClick={() => pickEmoji(emoji, value)}+ className={clsx(+ 'bot-avatar-emoji size-6 rounded-full transition',+ selected && 'ring-2 ring-mint ring-offset-2 ring-offset-surface-2',+ )}+ style={{ ['--bot-hue' as string]: value } as CSSProperties}+ />+ );+ })}+ </div>+ </div>+ <p className="text-[11px] leading-relaxed text-muted">{t('bots.avatarPicker.defaultHint')}</p>+ </>+ ) : (+ <button+ type="button"+ onClick={() => inputRef.current?.click()}+ onDragOver={(event) => {+ event.preventDefault();+ setDragging(true);+ }}+ onDragLeave={() => setDragging(false)}+ onDrop={(event) => {+ event.preventDefault();+ setDragging(false);+ takeFile(event.dataTransfer.files?.[0]);+ }}+ className={clsx(+ 'flex flex-col items-center gap-2 rounded-xl border border-dashed px-4 py-6 text-center transition',+ dragging ? 'border-mint bg-mint-soft' : 'border-border-strong hover:bg-foreground/[0.03]',+ )}+ >+ <Upload className="size-5 text-muted" />+ <span className="text-[12px] font-semibold text-foreground">{t('bots.avatarPicker.dropHint')}</span>+ <span className="text-[11px] text-muted">{t('bots.avatarPicker.formats')}</span>+ <input+ ref={inputRef}+ type="file"+ accept={ACCEPTED_TYPES.join(',')}+ className="hidden"+ onChange={(event) => {+ takeFile(event.target.files?.[0]);+ event.target.value = '';+ }}+ />+ </button>+ )}+ {canUseDefault && (+ <button+ type="button"+ onClick={() => onPick({ kind: 'default' })}+ className="flex items-center gap-1.5 self-start rounded-md px-1 text-[11px] font-medium text-muted transition hover:text-foreground"+ >+ <RotateCcw className="size-3" />+ {t('bots.avatarPicker.useDefault')}+ </button>+ )}+ </div>+ );+};diff --git a/ui/src/components/workbench/bots/BotProfileDialog.tsx b/ui/src/components/workbench/bots/BotProfileDialog.tsxnew file mode 100644index 000000000..769063d95--- /dev/null+++ b/ui/src/components/workbench/bots/BotProfileDialog.tsx@@ -0,0 +1,606 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { useNavigate } from 'react-router-dom';+import { Bot as BotIcon, Check, ChevronRight, Loader2, Lock, Pencil } from 'lucide-react';+import clsx from 'clsx';++import { useApi, type VibeAgentBrief } from '../../../context/ApiContext';+import { useBots, type BotProfileRequest } from '../../../context/BotsContext';+import { useToast } from '../../../context/ToastContext';+import { errorMessage } from '@/lib/errorMessage';+import { BOT_HANDLE_RE, botSessionPath, eligibleForBot, type Bot, type BotEmojiAvatarInput } from '@/lib/bots';+import { Button } from '../../ui/button';+import { Dialog, DialogContent, DialogDescription, DialogTitle } from '../../ui/dialog';+import { Input } from '../../ui/input';+import { Popover, PopoverContent, PopoverTrigger } from '../../ui/popover';+import { SegmentedRadio } from '../../ui/segmented';+import { Textarea } from '../../ui/textarea';+import { AgentRoutePicker, type AgentRoutePatch } from '../AgentRoutePicker';+import { BotAvatar } from '../../ui/bot-avatar';+import { BotAvatarPicker, type BotAvatarChoice } from './BotAvatarPicker';+++type HandleState =+ | { status: 'idle' }+ | { status: 'generating' }+ /** `forName` is the display name the handle was generated from. */+ | { status: 'ready'; handle: string; forName: string };++/** The server's `normalize_handle`, to show the handle an existing Agent will keep. */+function agentNameHandle(name: string): string {+ const candidate = name+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '')+ .replace(/^[^a-z]+/, '')+ .slice(0, 24)+ .replace(/-+$/, '');+ return candidate || name.toLowerCase();+}++++/** The add/edit dialog wherever the shell mounts it: open on the provider's request. */+export const BotProfileDialogHost: React.FC = () => {+ const { enabled, profileRequest, closeProfile } = useBots();+ if (!enabled) return null;+ return <BotProfileDialog request={profileRequest} onClose={closeProfile} />;+};++export const BotProfileDialog: React.FC<{ request: BotProfileRequest | null; onClose: () => void }> = ({+ request,+ onClose,+}) => {+ // A fresh form per request: the state below is the form's own, not the last one's.+ const key = request ? (request.kind === 'edit' ? `edit:${request.handle}` : `create:${request.tab ?? 'new'}:${request.agentName ?? ''}`) : 'closed';+ return (+ <Dialog open={request !== null} onOpenChange={(open) => { if (!open) onClose(); }}>+ {request && <BotProfileForm key={key} request={request} onClose={onClose} />}+ </Dialog>+ );+};++const BotProfileForm: React.FC<{ request: BotProfileRequest; onClose: () => void }> = ({ request, onClose }) => {+ const { t } = useTranslation();+ const api = useApi();+ const navigate = useNavigate();+ const { showToast } = useToast();+ const { mainBot, botForHandle, displayName, refresh } = 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 [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 ?? '');+ const [avatar, setAvatar] = useState<BotAvatarChoice>(editing ? { kind: 'keep' } : { kind: 'default' });+ const [pickerOpen, setPickerOpen] = useState(false);+ const [handle, setHandle] = useState<HandleState>({ status: 'idle' });+ const [handleDraft, setHandleDraft] = useState<string | null>(null);+ const [handleEdited, setHandleEdited] = useState(false);+ const [advancedOpen, setAdvancedOpen] = useState(false);+ const [route, setRoute] = useState<{ model: string | null; reasoning_effort: string | null } | null>(null);+ const [submitting, setSubmitting] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const suggestionRef = useRef<{ controller: AbortController; promise: Promise<string | null> } | null>(null);++ const mainName = mainBot ? displayName(mainBot) : t('bots.mainDefaultName');+ const mainAgent = useMemo(+ () => (agents && mainBot ? agents.find((agent) => agent.name === mainBot.agent_name) ?? null : null),+ [agents, mainBot],+ );+ const eligibleAgents = useMemo(() => (agents ?? []).filter(eligibleForBot), [agents]);+ const pickedAgent = eligibleAgents.find((agent) => agent.name === agentName) ?? null;++ useEffect(() => {+ let live = true;+ api+ .listVibeAgents({ cache: false })+ .then((result) => {+ if (live) setAgents(result.agents ?? []);+ })+ .catch(() => {+ if (live) setAgents([]);+ });+ return () => {+ live = false;+ };+ }, [api]);++ // The existing-Agent tab's display name starts as the Agent's name until the user types one.+ const nameTouchedRef = useRef(Boolean(editing));+ useEffect(() => {+ if (tab === 'agent' && pickedAgent && !nameTouchedRef.current) setName(pickedAgent.name);+ }, [tab, pickedAgent]);++ // An unsaved upload's preview URL is released when it is replaced or the form closes.+ const previewUrl = avatar.kind === 'image' ? avatar.previewUrl : null;+ useEffect(() => () => {+ if (previewUrl) URL.revokeObjectURL(previewUrl);+ }, [previewUrl]);++ // D2: the handle is generated in the background once a name is entered — the+ // server normalizes an ASCII name and asks the main Bot's model for any other.+ // A handle the user edited is theirs; the name no longer drives it.+ const suggest = useCallback(+ (displayNameValue: string, roleValue: string): Promise<string | null> => {+ suggestionRef.current?.controller.abort();+ const trimmed = displayNameValue.trim();+ if (!trimmed) {+ suggestionRef.current = null;+ setHandle({ status: 'idle' });+ return Promise.resolve(null);+ }+ const controller = new AbortController();+ setHandle({ status: 'generating' });+ const promise = api+ .suggestBotHandle({ display_name: trimmed, role: roleValue.trim() }, { signal: controller.signal })+ .then((result) => {+ if (controller.signal.aborted) return null;+ setHandle(result.handle ? { status: 'ready', handle: result.handle, forName: trimmed } : { status: 'idle' });+ return result.handle || null;+ })+ .catch(() => {+ if (!controller.signal.aborted) setHandle({ status: 'idle' });+ return null;+ });+ suggestionRef.current = { controller, promise };+ return promise;+ },+ [api],+ );+ const creatingNew = request.kind === 'create' && tab === 'new';+ // The role refines a model's codename but does not ask for a new one per keystroke.+ const roleRef = useRef(role);+ useEffect(() => {+ roleRef.current = role;+ }, [role]);+ useEffect(() => {+ if (!creatingNew || handleEdited) return;+ const timer = window.setTimeout(() => void suggest(name, roleRef.current), 600);+ return () => window.clearTimeout(timer);+ }, [creatingNew, handleEdited, name, suggest]);+ // Closing the form cancels what it was doing: a suggestion in flight, and a+ // create still waiting for its handle, which then never sends.+ const closedRef = useRef(false);+ const submitControllerRef = useRef<AbortController | null>(null);+ useEffect(() => {+ // Set on every mount: StrictMode replays this effect, and only a real unmount+ // may leave the form closed.+ closedRef.current = false;+ return () => {+ closedRef.current = true;+ suggestionRef.current?.controller.abort();+ submitControllerRef.current?.abort();+ };+ }, []);++ const handleError = handleDraft !== null && handleDraft !== '' && !BOT_HANDLE_RE.test(handleDraft)+ ? t('bots.dialog.handleInvalid')+ : null;++ const emojiInput: BotEmojiAvatarInput | null = avatar.kind === 'emoji' ? { emoji: avatar.emoji, hue: avatar.hue } : null;++ const uploadAvatar = async (bot: Bot) => {+ if (avatar.kind !== 'image') return bot;+ try {+ return await api.uploadBotAvatar(bot.handle, avatar.file);+ } catch (err) {+ // The Bot exists; only its picture did not land. Say so and keep going.+ showToast(errorMessage(err) || t('bots.dialog.avatarUploadFailed'), 'error');+ return bot;+ }+ };++ const submit = async () => {+ if (submitting) return;+ setError(null);+ const trimmedName = name.trim();+ if (!trimmedName && !(editing?.builtin)) {+ setError(t('bots.dialog.nameRequired'));+ return;+ }+ if (handleError) return;+ setSubmitting(true);+ try {+ if (request.kind === 'edit') {+ if (!editing) return;+ const patch: { display_name?: string; avatar?: BotEmojiAvatarInput | null } = {};+ if (trimmedName !== editing.display_name) patch.display_name = trimmedName;+ if (avatar.kind === 'emoji') patch.avatar = emojiInput;+ if (avatar.kind === 'default') patch.avatar = null;+ const bot = Object.keys(patch).length > 0 ? await api.updateBot(editing.handle, patch) : editing;+ await uploadAvatar(bot);+ if (!editing.builtin && role.trim() !== editing.role.trim()) {+ await api.updateVibeAgent(editing.agent_name, { description: role.trim() || null });+ }+ await refresh();+ onClose();+ return;+ }+ if (tab === 'agent') {+ if (!pickedAgent) {+ setError(t('bots.dialog.pickAgent'));+ return;+ }+ let bot = await api.setBot({ agent_name: pickedAgent.name, display_name: trimmedName, avatar: emojiInput });+ bot = await uploadAvatar(bot);+ await refresh();+ onClose();+ navigate(botSessionPath(bot));+ return;+ }+ // The handle shown for this exact name, else a fresh one: a suggestion is+ // worth its few seconds, since without it the server falls back to+ // transliteration, which reads worse for a CJK name.+ let chosenHandle: string | null = handleEdited ? handleDraft?.trim() || null : null;+ if (!handleEdited) {+ if (handle.status === 'ready' && handle.forName === trimmedName) {+ chosenHandle = handle.handle;+ } else {+ // Its own request, not the field's: a later keystroke's suggestion must not+ // cancel the create, and only closing the form may.+ const controller = new AbortController();+ submitControllerRef.current = controller;+ try {+ const suggestion = await api.suggestBotHandle(+ { display_name: trimmedName, role: role.trim() },+ { signal: controller.signal },+ );+ chosenHandle = suggestion.handle || null;+ } catch {+ // A failed suggestion leaves the handle to the server.+ chosenHandle = null;+ }+ if (closedRef.current || controller.signal.aborted) return;+ }+ }+ let bot = await api.createBot({+ display_name: trimmedName,+ handle: chosenHandle,+ role: role.trim() || null,+ avatar: emojiInput,+ ...(route ? { model: route.model, reasoning_effort: route.reasoning_effort } : {}),+ });+ bot = await uploadAvatar(bot);+ await refresh();+ onClose();+ navigate(botSessionPath(bot));+ } catch (err) {+ setError(errorMessage(err) || t('bots.dialog.saveFailed'));+ } finally {+ setSubmitting(false);+ }+ };++ // The avatar shown: the pick, else what the Bot has, else the name's default.+ const shownAvatar = avatar.kind === 'emoji'+ ? { kind: 'emoji' as const, emoji: avatar.emoji, hue: avatar.hue }+ : avatar.kind === 'keep'+ ? editing?.avatar ?? null+ : avatar.kind === 'default' && editing?.builtin+ ? { kind: 'mascot' as const }+ : null;+ const avatarName = name.trim() || (editing ? displayName(editing) : '') || (tab === 'agent' ? pickedAgent?.name ?? '' : '');+ const hasNonDefaultAvatar = avatar.kind === 'emoji' || avatar.kind === 'image'+ || (avatar.kind === 'keep' && Boolean(editing?.avatar) && editing?.avatar?.kind !== 'mascot');++ const title = request.kind === 'edit' ? t('bots.dialog.editTitle') : t('bots.dialog.addTitle');+ const primary = request.kind === 'edit'+ ? t('bots.dialog.save')+ : tab === 'agent'+ ? t('bots.dialog.set')+ : t('bots.dialog.create');+ const footerHint = request.kind === 'edit'+ ? null+ : tab === 'agent'+ ? t('bots.dialog.fromAgentHint')+ : t('bots.dialog.chatHint', { name: mainName });++ const avatarButton = (+ <Popover open={pickerOpen} onOpenChange={setPickerOpen} modal>+ <PopoverTrigger asChild>+ <button+ type="button"+ aria-label={t('bots.dialog.avatar')}+ className="relative shrink-0 rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mint/60"+ >+ <BotAvatar avatar={shownAvatar} name={avatarName} size={64} previewUrl={previewUrl} />+ <span className="absolute -bottom-0.5 -right-0.5 grid size-6 place-items-center rounded-full border border-border-strong bg-surface-2 text-foreground">+ <Pencil className="size-3" />+ </span>+ </button>+ </PopoverTrigger>+ <PopoverContent align="start" className="w-[300px] rounded-2xl border-border-strong bg-surface-2 p-3.5">+ <BotAvatarPicker+ current={avatar.kind === 'emoji'+ ? { emoji: avatar.emoji, hue: avatar.hue }+ : shownAvatar?.kind === 'emoji'+ ? { emoji: shownAvatar.emoji, hue: shownAvatar.hue }+ : null}+ canUseDefault={hasNonDefaultAvatar}+ onPick={(choice) => {+ setAvatar(choice);+ if (choice.kind !== 'emoji') setPickerOpen(false);+ }}+ onError={(message) => setError(message)}+ />+ </PopoverContent>+ </Popover>+ );++ const nameField = (label: string) => (+ <label className="flex min-w-0 flex-col gap-1.5">+ <span className="text-[12px] font-semibold text-foreground">{label}</span>+ <Input+ value={name}+ autoFocus+ maxLength={64}+ onChange={(event) => {+ nameTouchedRef.current = true;+ const next = event.target.value;+ setName(next);+ // A handle made for another name is stale at once; a new one follows (D2).+ if (creatingNew && !handleEdited) {+ setHandle((current) => (current.status === 'ready' && current.forName === next.trim()+ ? current+ : next.trim() ? { status: 'generating' } : { status: 'idle' }));+ }+ }}+ placeholder={editing?.builtin ? t('bots.mainDefaultName') : t('bots.dialog.namePlaceholder')}+ className="text-[13px]"+ />+ </label>+ );++ const roleField = (+ <label className="flex flex-col gap-1.5">+ <span className="text-[12px] font-semibold text-foreground">{t('bots.dialog.role')}</span>+ <Textarea+ value={role}+ onChange={(event) => setRole(event.target.value)}+ rows={3}+ placeholder={t('bots.dialog.rolePlaceholder')}+ className="min-h-[60px] text-[13px]"+ />+ <span className="text-[11px] leading-relaxed text-muted">{t('bots.dialog.roleHint')}</span>+ </label>+ );++ return (+ <DialogContent+ className="max-w-[460px] gap-0 p-0 max-md:p-0"+ closeLabel={t('common.close')}+ onOpenAutoFocus={(event) => {+ // The name field asks for focus itself; on the Agent tab the list leads.+ if (tab === 'agent') event.preventDefault();+ }}+ >+ <div className="flex flex-col gap-1 px-5 pt-5">+ <DialogTitle className="text-[16px] font-bold">{title}</DialogTitle>+ <DialogDescription className="text-[12px] leading-relaxed">{t('bots.dialog.description')}</DialogDescription>+ </div>++ {request.kind === 'create' && (+ <div className="px-5 pt-4">+ <SegmentedRadio+ value={tab}+ onChange={(next) => {+ setTab(next);+ setError(null);+ }}+ ariaLabel={title}+ options={[+ { id: 'new', label: t('bots.dialog.tabNew') },+ { id: 'agent', label: t('bots.dialog.tabFromAgent') },+ ]}+ />+ </div>+ )}++ <div className="flex flex-col gap-4 px-5 py-4">+ {request.kind === 'create' && tab === 'agent' && (+ agents === null ? (+ <div className="flex items-center gap-2 text-[12px] text-muted">+ <Loader2 className="size-3.5 animate-spin" />+ {t('common.loading')}+ </div>+ ) : eligibleAgents.length === 0 ? (+ <div className="rounded-lg border border-dashed border-border px-3 py-4 text-center text-[12px] leading-relaxed text-muted">+ {t('bots.dialog.noEligibleAgents')}+ </div>+ ) : (+ <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;+ return (+ <button+ key={agent.id}+ type="button"+ role="radio"+ aria-checked={picked}+ 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]',+ )}+ >+ <span className={clsx('grid size-4 shrink-0 place-items-center rounded-full border', picked ? 'border-mint' : 'border-border-strong')}>+ {picked && <span className="size-2 rounded-full bg-mint" />}+ </span>+ <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>}+ </span>+ </button>+ );+ })}+ </div>+ )+ )}++ {(request.kind === 'edit' || tab === 'new' || pickedAgent) && (+ <div className="flex items-start gap-4">+ {avatarButton}+ <div className="flex min-w-0 flex-1 flex-col gap-2">+ {nameField(tab === 'agent' || editing ? t('bots.dialog.displayName') : t('bots.dialog.name'))}+ {request.kind === 'edit' && editing ? (+ <HandleLine handle={editing.handle} note={t('bots.dialog.handleFrozen')} locked />+ ) : tab === 'agent' && pickedAgent ? (+ <HandleLine handle={agentNameHandle(pickedAgent.name)} note={t('bots.dialog.handleLocked')} locked />+ ) : handleEdited || handleDraft !== null ? (+ <div className="flex flex-col gap-1">+ <div className="flex items-center gap-1.5">+ <span className="font-mono text-[12px] font-semibold text-muted">{t('bots.handlePrefix')}</span>+ <Input+ value={handleDraft ?? ''}+ autoFocus+ aria-label={t('bots.dialog.handleEdit')}+ aria-invalid={handleError ? true : undefined}+ onChange={(event) => {+ setHandleEdited(true);+ setHandleDraft(event.target.value.toLowerCase());+ }}+ className="h-7 flex-1 px-2 font-mono text-[12px]"+ />+ </div>+ <span className={clsx('text-[11px]', handleError ? 'text-destructive-ink' : 'text-muted')}>+ {handleError ?? t('bots.dialog.handleHint')}+ </span>+ </div>+ ) : handle.status === 'generating' ? (+ <div className="flex items-center gap-1.5 text-[12px] text-muted" role="status">+ <Loader2 className="size-3.5 animate-spin" />+ {t('bots.dialog.handleGenerating')}+ </div>+ ) : handle.status === 'ready' ? (+ <HandleLine+ handle={handle.handle}+ note={t('bots.dialog.handleHint')}+ onEdit={() => setHandleDraft(handle.handle)}+ editLabel={t('bots.dialog.handleEdit')}+ />+ ) : null}+ </div>+ </div>+ )}++ {(request.kind === 'edit' ? !editing?.builtin : tab === 'new') && roleField}+ {request.kind === 'edit' && editing?.builtin && editing.role && (+ <div className="flex flex-col gap-1.5">+ <span className="text-[12px] font-semibold text-foreground">{t('bots.dialog.role')}</span>+ <p className="text-[12px] leading-relaxed text-muted">{editing.role}</p>+ </div>+ )}++ {request.kind === 'create' && tab === 'new' && mainAgent && (+ <div className="flex flex-col gap-2">+ <button+ type="button"+ aria-expanded={advancedOpen}+ onClick={() => setAdvancedOpen((open) => !open)}+ className="flex items-center gap-1.5 self-start text-[12px] text-muted transition hover:text-foreground"+ >+ <ChevronRight className={clsx('size-3.5 transition-transform', advancedOpen && 'rotate-90')} />+ {route+ ? t('bots.dialog.advancedModel', { model: [route.model, route.reasoning_effort].filter(Boolean).join(' · ') })+ : t('bots.dialog.advancedFollows', {+ name: mainName,+ model: [mainAgent.model, mainAgent.reasoning_effort].filter(Boolean).join(' · ') || t('newSession.defaultAgent'),+ })}+ </button>+ {advancedOpen && (+ <div className="flex flex-col gap-1.5 pl-5">+ <AgentRoutePicker+ presentation="compact"+ modal+ align="start"+ value={{+ agent_name: mainAgent.name,+ agent_backend: mainAgent.backend,+ agent_variant: mainAgent.backend,+ model: route ? route.model : mainAgent.model,+ reasoning_effort: route ? route.reasoning_effort : mainAgent.reasoning_effort,+ }}+ agents={[mainAgent]}+ agentLocked+ // Any exit the picker offers leaves the dialog behind it closed.+ onNavigateAway={onClose}+ onChange={(patch: AgentRoutePatch) => {+ setRoute({+ model: patch.model ?? (route ? route.model : mainAgent.model),+ reasoning_effort: patch.reasoning_effort !== undefined+ ? patch.reasoning_effort+ : route ? route.reasoning_effort : mainAgent.reasoning_effort,+ });+ }}+ triggerClassName="max-w-full"+ />+ {route && (+ <button+ type="button"+ onClick={() => setRoute(null)}+ className="self-start text-[11px] font-medium text-muted transition hover:text-foreground"+ >+ {t('bots.dialog.followMain', { name: mainName })}+ </button>+ )}+ </div>+ )}+ </div>+ )}++ {error && (+ <p role="alert" className="rounded-lg border border-destructive/40 bg-destructive/[0.06] px-3 py-2 text-[12px] text-destructive-ink">+ {error}+ </p>+ )}+ </div>++ <div className="flex items-center gap-2 border-t border-border px-5 py-3">+ <p className="min-w-0 flex-1 text-[11px] leading-relaxed text-muted">{footerHint}</p>+ <Button type="button" variant="outline" size="sm" onClick={onClose}>+ {t('common.cancel')}+ </Button>+ <Button+ type="button"+ size="sm"+ onClick={() => void submit()}+ disabled={submitting || (request.kind === 'create' && tab === 'agent' && !pickedAgent) || Boolean(handleError)}+ >+ {submitting ? <Loader2 className="size-3.5 animate-spin" /> : <Check className="size-3.5" />}+ {primary}+ </Button>+ </div>+ </DialogContent>+ );+};++const HandleLine: React.FC<{+ handle: string;+ note: string;+ locked?: boolean;+ onEdit?: () => void;+ editLabel?: string;+}> = ({ handle, note, locked, onEdit, editLabel }) => {+ const { t } = useTranslation();+ return (+ <div className="flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-[12px] text-muted">+ <span className="whitespace-nowrap font-mono font-semibold text-foreground">{t('bots.handle', { handle })}</span>+ <span className="min-w-0 flex-1">{note}</span>+ {locked ? (+ <Lock className="size-3.5 shrink-0" aria-hidden="true" />+ ) : (+ <button+ type="button"+ onClick={onEdit}+ aria-label={editLabel}+ title={editLabel}+ className="grid size-5 shrink-0 place-items-center rounded transition hover:bg-foreground/[0.06] hover:text-foreground"+ >+ <Pencil className="size-3.5" />+ </button>+ )}+ </div>+ );+};diff --git a/ui/src/components/workbench/bots/BotStrip.tsx b/ui/src/components/workbench/bots/BotStrip.tsxnew file mode 100644index 000000000..b5692f5e8--- /dev/null+++ b/ui/src/components/workbench/bots/BotStrip.tsx@@ -0,0 +1,458 @@+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { useLocation, useNavigate } from 'react-router-dom';+import {+ DndContext,+ KeyboardSensor,+ MouseSensor,+ TouchSensor,+ closestCenter,+ useSensor,+ useSensors,+ type Modifier,+} from '@dnd-kit/core';+import { SortableContext, horizontalListSortingStrategy, sortableKeyboardCoordinates, useSortable } from '@dnd-kit/sortable';+import { CSS } from '@dnd-kit/utilities';+import { GripVertical, MessageCircle, Pencil, Plus, UserMinus } from 'lucide-react';+import clsx from 'clsx';++import { useApi, type InboxSession } from '../../../context/ApiContext';+import { useBots, type BotRuntimeStatus } from '../../../context/BotsContext';+import { useToast } from '../../../context/ToastContext';+import { useUnsavedChangesActionGuard } from '../../../context/useUnsavedChangesActionGuard';+import { botSessionPath, type Bot } from '@/lib/bots';+import { errorMessage } from '@/lib/errorMessage';+import { formatRelativeTime } from '@/lib/relativeTime';+import { Markdown } from '../../ui/markdown';+import { Popover, PopoverAnchor, PopoverContent } from '../../ui/popover';+import { BotAvatar } from '../../ui/bot-avatar';++// A slot is 50px wide (the 40px avatar, its 2px ring, and room for the name) with+// 4px between slots and 2px of padding at either end: the main Bot, two more,+// and "Add" fill the default 216px sidebar column exactly.+const SLOT_WIDTH = 50;+const SLOT_GAP = 4;+const STRIP_PADDING = 4;++const horizontalOnly: Modifier = ({ transform }) => ({ ...transform, y: 0 });++const unreadLabel = (count: number) => (count > 99 ? '99+' : String(count));++// The Bots strip (docs/plans/bots.md D5): the Owner's standing members as a row+// of 40px avatars in the Inbox's old place, the main Bot first. The open Bot has+// a mint ring, unread is a cyan count, a running Turn a pulsing mint dot. With+// room to spare "Add" follows the avatars; once they overflow they scroll+// sideways with a fading right edge and "Add" stays pinned at the right.+export const BotStrip: React.FC<{+ /** The Inbox's per-session unread map: a Bot's count is its Session's (D5). */+ unreadBySession: Record<string, number>;+}> = ({ unreadBySession }) => {+ const { t } = useTranslation();+ const { enabled, bots, statusBySession, displayName, openProfile, moveBot } = useBots();+ const [rowWidth, setRowWidth] = useState<number | null>(null);+ const [fade, setFade] = useState(false);+ const rowRef = useRef<HTMLDivElement | null>(null);+ const scrollerRef = useRef<HTMLDivElement | null>(null);+ const [draggingHandle, setDraggingHandle] = useState<string | null>(null);++ useLayoutEffect(() => {+ const row = rowRef.current;+ if (!row) return;+ const measure = () => setRowWidth(row.clientWidth);+ measure();+ if (typeof ResizeObserver === 'undefined') return;+ const observer = new ResizeObserver(measure);+ observer.observe(row);+ return () => observer.disconnect();+ }, [enabled]);++ // Inline while every avatar and "Add" fit; pinned "Add" once they do not.+ const slots = bots.length + 1;+ const inline = rowWidth === null || slots * SLOT_WIDTH + (slots - 1) * SLOT_GAP + STRIP_PADDING <= rowWidth;++ const updateFade = useCallback(() => {+ const scroller = scrollerRef.current;+ if (!scroller) return;+ setFade(scroller.scrollLeft + scroller.clientWidth < scroller.scrollWidth - 2);+ }, []);+ useEffect(() => {+ updateFade();+ }, [updateFade, bots.length, inline, rowWidth]);++ const sensors = useSensors(+ useSensor(MouseSensor, { activationConstraint: { distance: 6 } }),+ useSensor(TouchSensor, { activationConstraint: { delay: 300, tolerance: 8 } }),+ useSensor(KeyboardSensor, {+ coordinateGetter: sortableKeyboardCoordinates,+ keyboardCodes: { start: ['Space'], cancel: ['Escape'], end: ['Space'] },+ }),+ );++ if (!enabled) return null;++ const main = bots.filter((bot) => bot.builtin);+ const others = bots.filter((bot) => !bot.builtin);+ const ids = others.map((bot) => bot.handle);+ const nameOf = (handle: string | number) => {+ const bot = others.find((item) => item.handle === handle);+ return bot ? displayName(bot) : '';+ };++ const slotProps = (bot: Bot) => ({+ bot,+ name: displayName(bot),+ unread: unreadBySession[bot.session_id] ?? 0,+ status: statusBySession[bot.session_id],+ suppressHover: draggingHandle !== null,+ });++ const addSlot = (+ <div className="flex w-[50px] shrink-0 flex-col items-center gap-1">+ <button+ type="button"+ onClick={() => openProfile({ kind: 'create' })}+ aria-label={t('bots.addLabel')}+ className="group rounded-full p-[2px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mint/60"+ >+ <span className="grid size-10 place-items-center rounded-full border border-dashed border-border-strong text-muted transition group-hover:border-mint group-hover:bg-mint-soft group-hover:text-mint-ink">+ <Plus className="size-4" />+ </span>+ </button>+ <span className="text-[11px] leading-tight text-muted">{t('bots.add')}</span>+ </div>+ );++ return (+ <section aria-label={t('bots.sectionLabel')} className="flex shrink-0 flex-col gap-1">+ <div className="flex h-4 items-center px-1">+ <span className="font-mono text-[10px] font-bold uppercase tracking-[0.18em] text-muted">+ {t('bots.sectionLabel')}+ </span>+ </div>+ <div ref={rowRef} className="flex min-w-0 items-start">+ <div+ ref={scrollerRef}+ onScroll={updateFade}+ className={clsx(+ 'flex min-w-0 items-start gap-1 overflow-x-auto px-0.5 pb-0.5 pt-1.5 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden',+ !inline && 'flex-1',+ !inline && fade && 'bot-strip-fade',+ )}+ >+ {main.map((bot) => <BotSlot key={bot.handle} {...slotProps(bot)} />)}+ <DndContext+ sensors={sensors}+ collisionDetection={closestCenter}+ modifiers={[horizontalOnly]}+ accessibility={{+ screenReaderInstructions: { draggable: t('bots.reorderInstructions') },+ announcements: {+ onDragStart: ({ active }) => t('bots.reorderPickedUp', { name: nameOf(active.id) }),+ onDragOver: ({ active, over }) => over+ ? t('bots.reorderPosition', { name: nameOf(active.id), position: ids.indexOf(String(over.id)) + 1, count: ids.length })+ : undefined,+ onDragEnd: ({ active }) => t('bots.reorderDropped', { name: nameOf(active.id) }),+ onDragCancel: () => t('bots.reorderCancelled'),+ },+ }}+ onDragStart={({ active }) => setDraggingHandle(String(active.id))}+ onDragCancel={() => setDraggingHandle(null)}+ onDragEnd={({ active, over }) => {+ setDraggingHandle(null);+ const from = ids.indexOf(String(active.id));+ const to = ids.indexOf(String(over?.id));+ if (from >= 0 && to >= 0 && from !== to) void moveBot(String(active.id), to + 1);+ }}+ >+ <SortableContext items={ids} strategy={horizontalListSortingStrategy}>+ {others.map((bot) => (+ <SortableBotSlot key={bot.handle} sortable={others.length > 1} {...slotProps(bot)} />+ ))}+ </SortableContext>+ </DndContext>+ {inline && addSlot}+ </div>+ {!inline && <div className="shrink-0 pt-1.5">{addSlot}</div>}+ </div>+ </section>+ );+};++const RUNNING_DOT = (+ <span className="absolute -bottom-0.5 -right-0.5 grid size-3.5 place-items-center rounded-full bg-[var(--sidebar-background)]">+ <span className="relative size-2">+ <span className="absolute inset-0 animate-ping rounded-full bg-mint opacity-70 motion-reduce:animate-none" />+ <span className="relative block size-2 rounded-full bg-mint shadow-glow-dot-mint" />+ </span>+ </span>+);++type BotSlotProps = {+ bot: Bot;+ name: string;+ unread: number;+ status: BotRuntimeStatus | undefined;+ suppressHover: boolean;+};++type SlotDrag = Pick<ReturnType<typeof useSortable>, 'attributes' | 'listeners' | 'setNodeRef' | 'transform' | 'transition' | 'isDragging'>;++/** A Bot other than the main one: draggable along the strip once there are two. */+const SortableBotSlot: React.FC<BotSlotProps & { sortable: boolean }> = ({ sortable, ...props }) => {+ const drag = useSortable({ id: props.bot.handle, disabled: !sortable });+ return <BotSlot {...props} drag={sortable ? drag : undefined} />;+};++const BotSlot: React.FC<BotSlotProps & { drag?: SlotDrag }> = ({ bot, name, unread, status, suppressHover, drag }) => {+ const { t } = useTranslation();+ const api = useApi();+ const navigate = useNavigate();+ const location = useLocation();+ const { showToast } = useToast();+ const { openProfile, refresh } = useBots();+ const authorizeRouteAction = useUnsavedChangesActionGuard();+ const path = botSessionPath(bot);+ const selected = location.pathname === path;+ const running = status === 'running';+ const [hoverOpen, setHoverOpen] = useState(false);+ const [menuOpen, setMenuOpen] = useState(false);+ const [latest, setLatest] = useState<InboxSession | null | undefined>(undefined);+ const openTimer = useRef<number | null>(null);+ const closeTimer = useRef<number | null>(null);+ const isDragging = drag?.isDragging ?? false;+ const slotRef = useRef<HTMLDivElement | null>(null);+ const setDragNode = drag?.setNodeRef;+ const setSlotNode = useCallback((node: HTMLDivElement | null) => {+ slotRef.current = node;+ setDragNode?.(node);+ }, [setDragNode]);+ // The open Bot stays in view on a strip that scrolls sideways.+ useEffect(() => {+ if (selected) slotRef.current?.scrollIntoView?.({ block: 'nearest', inline: 'nearest' });+ }, [selected]);++ const clearTimers = () => {+ if (openTimer.current !== null) window.clearTimeout(openTimer.current);+ if (closeTimer.current !== null) window.clearTimeout(closeTimer.current);+ openTimer.current = null;+ closeTimer.current = null;+ };+ useEffect(() => clearTimers, []);+ // A drag anywhere on the strip takes the card away; its timers stop with it.+ useEffect(() => {+ if (suppressHover || isDragging) clearTimers();+ }, [suppressHover, isDragging]);++ const queueOpen = () => {+ if (suppressHover || menuOpen) return;+ if (closeTimer.current !== null) window.clearTimeout(closeTimer.current);+ closeTimer.current = null;+ if (hoverOpen || openTimer.current !== null) return;+ openTimer.current = window.setTimeout(() => {+ openTimer.current = null;+ setHoverOpen(true);+ }, 350);+ };+ const queueClose = () => {+ if (openTimer.current !== null) window.clearTimeout(openTimer.current);+ openTimer.current = null;+ if (closeTimer.current !== null) window.clearTimeout(closeTimer.current);+ closeTimer.current = window.setTimeout(() => {+ closeTimer.current = null;+ setHoverOpen(false);+ }, 180);+ };++ // The latest message is read when the card opens, so the strip itself costs+ // nothing per Bot. A Bot that has said nothing yet shows its role alone.+ useEffect(() => {+ if (!hoverOpen) return;+ let live = true;+ api+ .listInbox({ onlySession: bot.session_id, limit: 1, handleError: false })+ .then((feed) => {+ if (live) setLatest(feed.sessions.find((row) => row.session_id === bot.session_id) ?? null);+ })+ .catch(() => {+ if (live) setLatest(null);+ });+ return () => {+ live = false;+ };+ }, [api, bot.session_id, hoverOpen]);++ const open = () => {+ clearTimers();+ setHoverOpen(false);+ const authorization = authorizeRouteAction();+ if (!authorization) return;+ authorization.runNavigation(() => navigate(path));+ };++ const remove = async () => {+ setMenuOpen(false);+ try {+ await api.removeBot(bot.handle);+ showToast(t('bots.removed', { name }), 'success');+ if (selected) navigate('/');+ } catch (err) {+ showToast(errorMessage(err) || t('bots.removeFailed'), 'error');+ } finally {+ void refresh();+ }+ };++ const label = unread > 0 ? t('bots.slotLabelUnread', { name, count: unread }) : name;+ const showCard = hoverOpen && !menuOpen && !isDragging && !suppressHover;+ return (+ <Popover+ open={showCard || menuOpen}+ onOpenChange={(next) => {+ if (!next) {+ setHoverOpen(false);+ setMenuOpen(false);+ }+ }}+ >+ <PopoverAnchor asChild>+ <div+ ref={setSlotNode}+ data-bot-handle={bot.handle}+ className={clsx('flex w-[50px] shrink-0 flex-col items-center gap-1', isDragging && 'z-10 opacity-80')}+ style={drag ? { transform: CSS.Translate.toString(drag.transform), transition: drag.transition } : undefined}+ onMouseEnter={queueOpen}+ onMouseLeave={queueClose}+ >+ <button+ type="button"+ {...(drag?.attributes ?? {})}+ {...(drag?.listeners ?? {})}+ onClick={open}+ onContextMenu={(event) => {+ event.preventDefault();+ clearTimers();+ setHoverOpen(false);+ setMenuOpen(true);+ }}+ aria-label={label}+ aria-current={selected ? 'page' : undefined}+ className={clsx(+ 'relative rounded-full p-[2px] transition-shadow focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mint/60',+ selected ? 'shadow-[0_0_0_2px_var(--mint)]' : 'hover:shadow-[0_0_0_2px_var(--border-strong)]',+ drag && 'touch-none',+ )}+ >+ <BotAvatar avatar={bot.avatar} name={name} size={40} />+ {unread > 0 && (+ <span className="absolute -right-1.5 -top-1 inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-cyan px-1 font-mono text-[9px] font-bold text-accent-foreground shadow-glow-xs-cyan">+ {unreadLabel(unread)}+ </span>+ )}+ {running && RUNNING_DOT}+ </button>+ <span+ className={clsx(+ 'w-full truncate text-center text-[11px] leading-tight',+ selected ? 'font-semibold text-foreground' : 'text-muted',+ )}+ title={name}+ >+ {name}+ </span>+ </div>+ </PopoverAnchor>+ {menuOpen ? (+ <PopoverContent+ side="bottom"+ align="start"+ sideOffset={6}+ role="menu"+ aria-label={t('bots.menu.label', { name })}+ data-settings-interaction-owner="true"+ onOpenAutoFocus={(event) => event.preventDefault()}+ className="flex w-[208px] flex-col gap-0.5 rounded-2xl border-border-strong bg-surface-2 p-1.5 shadow-[0_24px_64px_-12px_rgba(0,0,0,0.6)]"+ >+ <button+ type="button"+ role="menuitem"+ onClick={() => {+ setMenuOpen(false);+ openProfile({ kind: 'edit', handle: bot.handle });+ }}+ className="flex items-center gap-2.5 rounded-md px-2.5 py-2 text-left text-[13px] text-foreground transition hover:bg-foreground/[0.05]"+ >+ <Pencil className="size-4 text-muted" />+ {t('bots.menu.editProfile')}+ </button>+ {!bot.builtin && (+ <>+ {/* Reordering is the drag itself; this row says how. */}+ <div className="flex items-center gap-2.5 px-2.5 py-2 text-[13px] text-muted">+ <GripVertical className="size-4" />+ {t('bots.menu.dragToReorder')}+ </div>+ <div className="my-1 h-px bg-border" />+ <button+ type="button"+ role="menuitem"+ onClick={() => void remove()}+ className="flex items-center gap-2.5 rounded-md px-2.5 py-2 text-left text-[13px] text-destructive-ink transition hover:bg-destructive/[0.08]"+ >+ <UserMinus className="size-4" />+ {t('bots.menu.remove')}+ </button>+ <p className="px-2.5 pb-1.5 text-[11px] leading-relaxed text-muted">{t('bots.menu.removeNote')}</p>+ </>+ )}+ </PopoverContent>+ ) : (+ <PopoverContent+ side="right"+ align="start"+ sideOffset={10}+ data-settings-interaction-owner="true"+ onOpenAutoFocus={(event) => event.preventDefault()}+ onMouseEnter={queueOpen}+ onMouseLeave={queueClose}+ className="w-[248px] rounded-2xl border-border-strong bg-surface-2 p-0 shadow-[0_24px_64px_-12px_rgba(0,0,0,0.6)]"+ >+ <button+ type="button"+ onClick={open}+ className="flex w-full flex-col gap-3 rounded-2xl p-3.5 text-left"+ >+ <span className="flex items-center gap-3">+ <BotAvatar avatar={bot.avatar} name={name} size={44} />+ <span className="min-w-0 flex-1 leading-tight">+ <span className="block truncate text-[14px] font-bold text-foreground">{name}</span>+ <span className="mt-0.5 block font-mono text-[11px] text-muted">{t('bots.handle', { handle: bot.handle })}</span>+ </span>+ </span>+ {bot.role && <span className="line-clamp-3 text-[12px] leading-relaxed text-muted">{bot.role}</span>}+ {(running || latest) && (+ <span className="block rounded-lg bg-foreground/[0.04] px-2.5 py-2 text-[12px] leading-relaxed text-foreground">+ <span className={clsx('mb-0.5 block text-[10px] font-semibold', running ? 'text-mint-ink' : 'text-muted')}>+ {latest+ ? t('bots.statusAt', {+ status: running ? t('bots.running') : t('bots.latest'),+ time: formatRelativeTime(latest.last_activity_at, t),+ })+ : running ? t('bots.running') : t('bots.latest')}+ </span>+ {latest?.preview_text && (+ <span className="line-clamp-2 block">+ <Markdown content={latest.preview_text} interactive={false} className="vr-markdown--preview" />+ </span>+ )}+ </span>+ )}+ <span className="flex items-center gap-1.5 text-[12px] font-semibold text-cyan-ink">+ <MessageCircle className="size-3.5" />+ {t('bots.openConversation')}+ </span>+ </button>+ </PopoverContent>+ )}+ </Popover>+ );+};diff --git a/ui/src/components/workbench/bots/BotTag.tsx b/ui/src/components/workbench/bots/BotTag.tsxnew file mode 100644index 000000000..39498fdc1--- /dev/null+++ b/ui/src/components/workbench/bots/BotTag.tsx@@ -0,0 +1,12 @@+import { useTranslation } from 'react-i18next';+import clsx from 'clsx';++/** The small "Bot" tag an Inbox row carries when the conversation is a Bot's (D5). */+export const BotTag: React.FC<{ className?: string }> = ({ className }) => {+ const { t } = useTranslation();+ return (+ <span className={clsx('shrink-0 rounded bg-mint-soft px-1 text-[9px] font-semibold leading-[14px] text-mint-ink', className)}>+ {t('bots.tag')}+ </span>+ );+};diff --git a/ui/src/components/workbench/useSessionActions.tsx b/ui/src/components/workbench/useSessionActions.tsxindex 5cd19432d..e32ee7974 100644--- a/ui/src/components/workbench/useSessionActions.tsx+++ b/ui/src/components/workbench/useSessionActions.tsx@@ -50,6 +50,10 @@ export interface SessionActionsOptions {onSessionPatched?: (changes: Partial<WorkbenchSession>, sessionId: string) => void;/** Keyboard hint for the archive row (see chatShortcuts). */archiveHint?: string;+ /** A Bot's permanent conversation (docs/plans/bots.md D5): it is never archived,+ * renamed, pinned, or hidden — the server refuses those writes — so only the+ * rows that continue from it (reference, fork) remain. */+ botSession?: boolean;}export interface SessionActionsHandle {@@ -74,6 +78,7 @@ export const useSessionActions = ({onArchived,onSessionPatched,archiveHint,+ botSession = false,}: SessionActionsOptions): SessionActionsHandle => {const { t } = useTranslation();const api = useApi();@@ -195,7 +200,7 @@ export const useSessionActions = ({// cannot reference the session you are already typing in, which is also why// the chat header never shows this row for its own session.const canReference = insertTarget != null && insertTarget.sessionId !== target.id;- const rows: SessionActionDescriptor[] = [+ const rows: SessionActionDescriptor[] = botSession ? [] : [{id: 'pin',group: 'organize',@@ -206,7 +211,7 @@ export const useSessionActions = ({onSelect: () => void togglePinned(),},];- if (onRenameStart) {+ if (onRenameStart && !botSession) {rows.push({id: 'rename',group: 'organize',@@ -239,7 +244,7 @@ export const useSessionActions = ({onSelect: () => void fork(),});}- rows.push({+ if (!botSession) rows.push({id: 'visibility',group: 'continue',icon: inBackground ? Eye : EyeOff,@@ -248,7 +253,7 @@ export const useSessionActions = ({disabled: movingVisibility,onSelect: () => void toggleVisibility(),});- if (lifecycleWritable) {+ if (lifecycleWritable && !botSession) {rows.push({id: 'archive',group: 'lifecycle',@@ -275,9 +280,10 @@ export const useSessionActions = ({requestArchive,archiveHint,lifecycleWritable,+ botSession,]);- const archiveDialog = lifecycleWritable && target ? (+ const archiveDialog = lifecycleWritable && target && !botSession ? (<ArchiveSessionDialogsessionId={archiveOpen ? archiveRequestId : null}sessionTitle={target.title}@@ -290,5 +296,10 @@ export const useSessionActions = ({/>) : null;- return { actions, archiveDialog, requestArchive, canArchive: lifecycleWritable && target != null };+ return {+ actions,+ archiveDialog,+ requestArchive,+ canArchive: lifecycleWritable && target != null && !botSession,+ };};diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 1b05da60d..4e08a0482 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -5,6 +5,7 @@ import type { PickerAgentCatalog } from '../components/settings/models/types';import type { AgentBackendId, NativeCliBackend, WebOAuthBackend } from '../lib/agentBackends';import { apiFetch, recoverRemoteAuthFromSessionProbe, withApiDeadline } from '../lib/apiFetch';import { isAuthorizationSensitiveReadPath } from '../lib/authorizationCache';+import { parseBot, type AgentBotSummary, type Bot, type BotEmojiAvatarInput } from '../lib/bots';import type { TurnActivityGroupWire } from '../lib/agentActivity';import type { AgentGraphParams, AgentGraphResult, AgentGraphVisibility } from '../lib/agentGraph';import { onPageReactivated, type PageReactivationListener } from '../lib/pageActivity';@@ -888,6 +889,29 @@ export type ApiContextType = {recoverSessionDraftAfterRejectedSend: (sessionId: string) => Promise<void>;listInbox: (params?: { platform?: string; unreadOnly?: boolean; limit?: number; before?: string; onlySession?: string; cache?: boolean; handleError?: boolean; backgroundPush?: boolean }) => Promise<InboxFeedResult>;connectWorkbenchEvents: (handlers: WorkbenchEventHandlers) => () => void;+ // Bots (docs/plans/bots.md "Web API"): every route is the instance Owner's. The+ // writes reject with an ``ApiError`` carrying the server's localized message and+ // code, and raise no toast: the Bot dialogs show the refusal where it was made.+ listBots: (params?: { cache?: boolean }) => Promise<Bot[]>;+ createBot: (payload: {+ display_name: string;+ handle?: string | null;+ role?: string | null;+ avatar?: BotEmojiAvatarInput | null;+ model?: string | null;+ reasoning_effort?: string | null;+ }) => Promise<Bot>;+ setBot: (payload: { agent_name: string; display_name: string; avatar?: BotEmojiAvatarInput | null }) => Promise<Bot>;+ updateBot: (+ handle: string,+ payload: { display_name?: string; avatar?: BotEmojiAvatarInput | null; position?: number },+ ) => Promise<Bot>;+ removeBot: (handle: string) => Promise<void>;+ uploadBotAvatar: (handle: string, image: Blob) => Promise<Bot>;+ suggestBotHandle: (+ payload: { display_name: string; role?: string },+ options?: { signal?: AbortSignal },+ ) => Promise<{ handle: string; source: string }>;listVibeAgents: (params?: {backend?: string;includeDisabled?: boolean;@@ -1154,6 +1178,8 @@ export type VibeAgentBrief = {archived_at: string | null;source: string;updated_at: string;+ /** The Bot this Agent is, if any (docs/plans/bots.md D1). Absent on older servers. */+ bot?: AgentBotSummary | null;};export type VibeAgentFull = VibeAgentBrief & {@@ -1344,6 +1370,9 @@ export type WorkbenchEventHandlers = {*/onConnected?: () => void;onProjectsChanged?: () => void;+ /** The Owner's Bots changed (created, set, edited, reordered, removed): refetch+ * ``GET /api/bots``. ``handle`` is a hint, not a filter. */+ onBotsChanged?: (data: { handle?: string }) => void;onConnectionState?: (state: WorkbenchEventConnectionState) => void;onEventBridgeStatus?: (data: { connected: boolean }) => void;onAuthorizationChanged?: (data: {@@ -3090,6 +3119,16 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenhandlers.onProjectsChanged?.();});});+ source.addEventListener('bots.changed', (e: MessageEvent) => {+ const envelope = parseWorkbenchEnvelope<{ handle?: string }>(e.data);+ if (!envelope) return;+ // A Bot is Agent metadata (D1), so the Agents reads carry it too.+ clearReadCacheMatching((path) => path.startsWith('/api/bots') || path.startsWith('/api/agents'));+ dispatchToWorkbenchHandlers((handlers) => {+ handlers.onAny?.(envelope);+ handlers.onBotsChanged?.(envelope.data ?? {});+ });+ });source.addEventListener('remote.authorization', (e: MessageEvent) => {try {const payload = JSON.parse(e.data) as { state?: RemoteAuthorizationState };@@ -3537,6 +3576,25 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenreturn payloadJson;};+ // The Bot routes answer a refusal with a coded, already-localized body+ // (``_bot_error_response``). Read it here and reject with it, without the global+ // toast: the dialog that asked shows the refusal in place.+ const botRequest = async (path: string, init: RequestInit): Promise<Record<string, unknown>> => {+ const { res, payloadJson } = await requestJson(path, init, path, { handleError: false });+ if (!res.ok || payloadJson?.ok === false) {+ const parsed = payloadJson && typeof payloadJson === 'object'+ ? selectApiErrorFields(payloadJson, `Request failed: ${path} (${res.status})`)+ : null;+ throw new ApiError(parsed?.fallback ?? `Request failed: ${path} (${res.status})`, res.status, parsed?.code ?? null);+ }+ return payloadJson as Record<string, unknown>;+ };+ const botFromResponse = (payload: Record<string, unknown>): Bot => {+ const bot = parseBot(payload.bot);+ if (!bot) throw new ApiError('The server returned no Bot', 0, null);+ return bot;+ };+const sleep = (ms: number) => new Promise((resolve) => window.setTimeout(resolve, ms));const startAndPollDependencyInstall = async (dep: string): Promise<InstallResult> => {@@ -4249,6 +4307,47 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenconst options = { handleError: params?.handleError };return params?.cache === false ? getJson(path, options) : getCachedJson(path, 1500, options);},+ listBots: async (params) => {+ const payload = params?.cache === false+ ? await getJson('/api/bots', { handleError: false })+ : await getCachedJson('/api/bots', 1500, { handleError: false });+ if (!payload || payload.ok === false || !Array.isArray(payload.bots)) {+ const parsed = payload ? selectApiErrorFields(payload, 'Request failed: /api/bots') : null;+ throw new ApiError(parsed?.fallback ?? 'Request failed: /api/bots', 0, parsed?.code ?? null);+ }+ return (payload.bots as unknown[]).map(parseBot).filter((bot): bot is Bot => bot !== null);+ },+ createBot: async (payload) => botFromResponse(await botRequest('/api/bots', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(payload),+ })),+ setBot: async (payload) => botFromResponse(await botRequest('/api/bots/set', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(payload),+ })),+ updateBot: async (handle, payload) => botFromResponse(await botRequest(`/api/bots/${encodeURIComponent(handle)}`, {+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(payload),+ })),+ removeBot: async (handle) => {+ await botRequest(`/api/bots/${encodeURIComponent(handle)}`, { method: 'DELETE' });+ },+ uploadBotAvatar: async (handle, image) => botFromResponse(await botRequest(+ `/api/bots/${encodeURIComponent(handle)}/avatar`,+ { method: 'PUT', headers: { 'Content-Type': image.type || 'application/octet-stream' }, body: image },+ )),+ suggestBotHandle: async (payload, options) => {+ const body = await botRequest('/api/bots/handle-suggestion', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(payload),+ signal: options?.signal,+ });+ return { handle: String(body.handle ?? ''), source: String(body.source ?? '') };+ },listVibeAgents: (params) => {const search = new URLSearchParams();if (params?.backend) search.set('backend', params.backend);diff --git a/ui/src/context/BotsContext.ts b/ui/src/context/BotsContext.tsnew file mode 100644index 000000000..d0a584c39--- /dev/null+++ b/ui/src/context/BotsContext.ts@@ -0,0 +1,65 @@+import { createContext, useContext } from 'react';++import type { Bot } from '../lib/bots';++/** What the shared add/edit dialog opens on (see `BotProfileDialog`). */+export type BotProfileRequest =+ | { kind: 'create'; tab?: 'new' | 'agent'; agentName?: string }+ | { kind: 'edit'; handle: string };++export type BotRuntimeStatus = 'idle' | 'running' | 'failed';++// The Owner's Bots (docs/plans/bots.md D1, D5) and the live state the avatar strip+// draws from. `BotsProvider.tsx` owns the read, the SSE subscription and the+// writes; this module is the component-free handle consumers import.+export interface BotsState {+ /** Bots are the instance Owner's: everyone else gets an empty, inert state. */+ enabled: boolean;+ /** In display order: the main Bot first. */+ bots: Bot[];+ /** The first read has answered (successfully or not). */+ loaded: boolean;+ mainBot: Bot | null;+ /** Each Bot Session's agent status; a Session not yet read is absent. */+ statusBySession: Record<string, BotRuntimeStatus>;+ botForSession: (sessionId: string | null | undefined) => Bot | undefined;+ botForAgent: (agentName: string | null | undefined) => Bot | undefined;+ 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>;+ /** 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>;+ /** Open the one add/edit dialog: the strip's Add slot, a Bot's Edit profile, and+ * the Agents page's "Set as Bot" all land here. */+ openProfile: (request: BotProfileRequest) => void;+ /** What the dialog is open on, if anything. The shell mounts the dialog under+ * its route-activity boundary, so Settings opening over it suspends it. */+ profileRequest: BotProfileRequest | null;+ closeProfile: () => void;+}++const EMPTY: BotsState = {+ enabled: false,+ bots: [],+ loaded: false,+ mainBot: null,+ statusBySession: {},+ botForSession: () => undefined,+ botForAgent: () => undefined,+ botForHandle: () => undefined,+ displayName: (bot) => bot.display_name || bot.handle,+ refresh: async () => undefined,+ moveBot: async () => false,+ openProfile: () => undefined,+ profileRequest: null,+ closeProfile: () => undefined,+};++export const BotsContext = createContext<BotsState>(EMPTY);++/** The Owner's Bots. Outside a `BotsProvider` (a Show Page, a test harness) this is+ * the empty state, so a surface that merely decorates with Bot identity — a+ * mention chip, an Inbox row — degrades to its plain rendering. */+export const useBots = (): BotsState => useContext(BotsContext);diff --git a/ui/src/context/BotsProvider.tsx b/ui/src/context/BotsProvider.tsxnew file mode 100644index 000000000..89ebb3f77--- /dev/null+++ b/ui/src/context/BotsProvider.tsx@@ -0,0 +1,148 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import type { ReactNode } from 'react';+import { useTranslation } from 'react-i18next';++import { useApi } from './ApiContext';+import { BotsContext, type BotProfileRequest, type BotRuntimeStatus, type BotsState } from './BotsContext';+import { useInstanceAuthorization } from './InstanceAuthorizationContext';+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+ * 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 }) => {+ const api = useApi();+ const { t } = useTranslation();+ const { capabilities } = useInstanceAuthorization();+ const enabled = capabilities.is_instance_owner === true;+ const [ownerBots, setBots] = useState<Bot[]>([]);+ const [loaded, setLoaded] = useState(false);+ const [ownerStatuses, setStatusBySession] = useState<Record<string, BotRuntimeStatus>>({});+ const [profileRequest, setProfileRequest] = useState<BotProfileRequest | null>(null);+ const readRef = useRef(0);+ const sessionIdsRef = useRef<Set<string>>(new Set());++ const readStatuses = useCallback(+ async (sessionIds: string[]) => {+ await Promise.all(+ sessionIds.map(async (sessionId) => {+ try {+ const session = await api.getSession(sessionId, { cache: false, handleError: false });+ const status = session?.agent_status;+ if (status === 'idle' || status === 'running' || status === 'failed') {+ setStatusBySession((prev) => (prev[sessionId] === status ? prev : { ...prev, [sessionId]: status }));+ }+ } catch {+ // A Bot's dot is decoration; an unreadable Session just shows none.+ }+ }),+ );+ },+ [api],+ );++ const refresh = useCallback(async () => {+ if (!enabled) return;+ const read = ++readRef.current;+ try {+ const next = await api.listBots({ cache: false });+ if (read !== readRef.current) return;+ setBots(orderBots(next));+ const known = sessionIdsRef.current;+ const fresh = next.map((bot) => bot.session_id).filter((id) => !known.has(id));+ sessionIdsRef.current = new Set(next.map((bot) => bot.session_id));+ if (fresh.length > 0) void readStatuses(fresh);+ } catch {+ // Keep the last list: a failed refetch is not "no Bots".+ } finally {+ if (read === readRef.current) setLoaded(true);+ }+ }, [api, enabled, readStatuses]);++ useEffect(() => {+ if (!enabled) {+ // A reader who is not the Owner gets nothing (the value below withholds+ // it), and a read still in flight for an earlier Owner session is dropped.+ readRef.current += 1;+ sessionIdsRef.current = new Set();+ return;+ }+ // 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({+ onConnected: () => {+ // Nothing replays the gap: re-read the list and every Bot's status.+ void refresh().then(() => readStatuses([...sessionIdsRef.current]));+ },+ onBotsChanged: () => {+ void refresh();+ },+ onSessionStatus: ({ session_id: sessionId, agent_status: status }) => {+ if (!sessionIdsRef.current.has(sessionId)) return;+ setStatusBySession((prev) => (prev[sessionId] === status ? prev : { ...prev, [sessionId]: status }));+ },+ onTurnStart: ({ session_id: sessionId }) => {+ if (!sessionIdsRef.current.has(sessionId)) return;+ setStatusBySession((prev) => (prev[sessionId] === 'running' ? prev : { ...prev, [sessionId]: 'running' }));+ },+ });+ }, [api, enabled, refresh, readStatuses]);++ const moveBot = useCallback(+ async (handle: string, position: number) => {+ const previous = ownerBots;+ const others = previous.filter((bot) => !bot.builtin);+ const moving = others.find((bot) => bot.handle === handle);+ if (!moving) return false;+ const reordered = others.filter((bot) => bot.handle !== handle);+ reordered.splice(Math.max(0, Math.min(position - 1, reordered.length)), 0, moving);+ setBots([+ ...previous.filter((bot) => bot.builtin),+ ...reordered.map((bot, index) => ({ ...bot, position: index + 1 })),+ ]);+ try {+ await api.updateBot(handle, { position });+ return true;+ } catch {+ setBots(previous);+ return false;+ } finally {+ void refresh();+ }+ },+ [api, ownerBots, refresh],+ );++ const mainDefault = t('bots.mainDefaultName');+ const value = useMemo<BotsState>(() => {+ const bots = enabled ? ownerBots : [];+ const statusBySession = enabled ? ownerStatuses : {};+ const bySession = new Map(bots.map((bot) => [bot.session_id, bot]));+ const byAgent = new Map(bots.map((bot) => [bot.agent_name, bot]));+ const byHandle = new Map(bots.map((bot) => [bot.handle, bot]));+ return {+ enabled,+ bots,+ loaded: enabled && loaded,+ mainBot: bots.find((bot) => bot.builtin) ?? null,+ statusBySession,+ botForSession: (sessionId) => (sessionId ? bySession.get(sessionId) : undefined),+ botForAgent: (agentName) => (agentName ? byAgent.get(agentName) : undefined),+ botForHandle: (handle) => (handle ? byHandle.get(handle) : undefined),+ displayName: (bot) => botDisplayName(bot, mainDefault),+ refresh,+ moveBot,+ openProfile: (request) => {+ if (enabled) setProfileRequest(request);+ },+ profileRequest: enabled ? profileRequest : null,+ closeProfile: () => setProfileRequest(null),+ };+ }, [enabled, ownerBots, loaded, ownerStatuses, mainDefault, refresh, moveBot, profileRequest]);++ return <BotsContext.Provider value={value}>{children}</BotsContext.Provider>;+};diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 40f7e226a..48fb664cf 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -3342,7 +3342,7 @@},"appShell": {"title": "Avibe",- "subtitle": "Agent OS · Workbench",+ "subtitle": "Agent OS","workspaceLabel": "Settings","moreSettings": "More Settings","openControlPanel": "Settings",@@ -3551,7 +3551,8 @@"testSent": "Test notification sent","testFailed": "Test notification failed","normalBlocked": "normal notifications are currently skipped for you ({{policy}} policy: {{disposition}})"- }+ },+ "navUnread": "Inbox, {{count}} unread"},"modules": {"comingSoonEyebrow": "Coming soon",@@ -4660,6 +4661,96 @@"submit": "Create agent"}},+ "bots": {+ "sectionLabel": "Bots",+ "mainDefaultName": "Vibey",+ "tag": "Bot",+ "handle": "@{{handle}}",+ "handlePrefix": "@",+ "mentionName": "@{{name}}",+ "add": "Add",+ "addLabel": "Add a Bot",+ "slotLabelUnread": "{{name}}, {{count}} unread",+ "running": "Running",+ "latest": "Latest",+ "statusAt": "{{status}} · {{time}}",+ "openConversation": "Open conversation",+ "removed": "{{name}} was removed from Bots",+ "removeFailed": "Could not remove this Bot",+ "reorderInstructions": "Press Space to pick up a Bot, use arrow keys to move it, Space to drop, or Escape to cancel.",+ "reorderPickedUp": "Picked up {{name}}.",+ "reorderPosition": "{{name}}, position {{position}} of {{count}}.",+ "reorderDropped": "Dropped {{name}}.",+ "reorderCancelled": "Reordering cancelled.",+ "menu": {+ "label": "{{name}} actions",+ "editProfile": "Edit profile",+ "dragToReorder": "Drag to reorder",+ "remove": "Remove from Bots",+ "removeNote": "Its conversation and memory are kept; set it as a Bot again to reconnect them."+ },+ "dialog": {+ "addTitle": "Add a Bot",+ "editTitle": "Edit profile",+ "description": "A Bot has a name and its own memory, and your conversation with it carries on.",+ "tabNew": "New",+ "tabFromAgent": "From an existing Agent",+ "name": "Name",+ "displayName": "Display name",+ "namePlaceholder": "e.g. Chief Security Officer",+ "nameRequired": "Give the Bot a name.",+ "avatar": "Choose an avatar",+ "role": "What it handles",+ "rolePlaceholder": "e.g. Audits dependencies and permissions, and reports every Monday",+ "roleHint": "Goes into its instructions; you can change it later on the Agents page.",+ "handleGenerating": "Generating a handle…",+ "handleHint": "Generated for @ mentions and the CLI",+ "handleLocked": "The Agent name, locked while it is a Bot",+ "handleFrozen": "Fixed once the Bot exists",+ "handleEdit": "Edit handle",+ "handleInvalid": "Use 2 to 24 lowercase letters, digits, or hyphens, starting with a letter and not ending with a hyphen.",+ "advancedFollows": "Advanced: model follows {{name}} ({{model}})",+ "advancedModel": "Advanced: model {{model}}",+ "followMain": "Follow {{name}}'s model",+ "chatHint": "You can also ask {{name}} to add one, e.g. “Add a Bot that handles security.”",+ "fromAgentHint": "Only Vibey Agents that are not Bots yet are listed.",+ "noEligibleAgents": "No Vibey Agent can be set as a Bot. Create one on the Agents page first.",+ "pickAgent": "Choose an Agent.",+ "create": "Add Bot",+ "set": "Set as Bot",+ "save": "Save",+ "saveFailed": "Could not save the Bot.",+ "avatarUploadFailed": "The Bot was saved, but its avatar did not upload."+ },+ "avatarPicker": {+ "emoji": "Emoji",+ "upload": "Upload image",+ "background": "Background",+ "hue": "Hue {{hue}}",+ "defaultHint": "Optional: by default it shows the name's first character on a color the name decides.",+ "dropHint": "Drop an image here, or click to choose",+ "formats": "PNG, JPG, or WebP, cropped to a circle",+ "unsupported": "Choose a PNG, JPG, or WebP image.",+ "tooLarge": "The image is larger than 10 MB.",+ "useDefault": "Use the default"+ },+ "conversation": {+ "editProfile": "Edit profile",+ "emptyTitle": "This is the start of your conversation with {{name}}",+ "emptyBody": "It carries on from here: {{name}} keeps what matters in its memory and handles messages in order."+ },+ "agents": {+ "badge": "Bot",+ "setAsBot": "Set as Bot",+ "setAsBotHint": "Give it a name, an avatar, and one permanent conversation with memory.",+ "setAsBotNeedsEnabled": "Enable the Agent first, then set it as a Bot.",+ "isBotTitle": "This Agent is the Bot {{name}}",+ "isBotHint": "While it is a Bot it stays enabled and keeps its name; it cannot be archived or deleted. Remove it from Bots first.",+ "isMainBotHint": "The main Bot's Agent is built in: it stays enabled and cannot be removed.",+ "openConversation": "Open conversation",+ "editProfile": "Edit profile"+ }+ },"editor": {"modeLabel": "Editor mode","edit": "Edit",diff --git a/ui/src/i18n/keyCoverage.test.ts b/ui/src/i18n/keyCoverage.test.tsindex e814e9749..479543ccf 100644--- a/ui/src/i18n/keyCoverage.test.ts+++ b/ui/src/i18n/keyCoverage.test.ts@@ -846,6 +846,7 @@ const NON_KEY_LITERALS = [// Event-channel names. `ApiContext.tsx` publishes and subscribes by these.'authorization.changed',+ 'bots.changed','definitions.updated','inbox.session.updated','inbox.unread.changed',diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex be7bdd1a4..3b2cb6e53 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -3342,7 +3342,7 @@},"appShell": {"title": "Avibe",- "subtitle": "Agent OS · 工作台",+ "subtitle": "Agent OS","workspaceLabel": "设置","moreSettings": "更多设置","openControlPanel": "设置",@@ -3551,7 +3551,8 @@"testSent": "测试通知已发送","testFailed": "测试通知发送失败","normalBlocked": "但普通通知当前会跳过你({{policy}} 策略:{{disposition}})"- }+ },+ "navUnread": "收件箱,{{count}} 条未读"},"modules": {"comingSoonEyebrow": "即将就位",@@ -4660,6 +4661,96 @@"submit": "创建 Agent"}},+ "bots": {+ "sectionLabel": "伙伴",+ "mainDefaultName": "歪比",+ "tag": "伙伴",+ "handle": "@{{handle}}",+ "handlePrefix": "@",+ "mentionName": "@{{name}}",+ "add": "添加",+ "addLabel": "添加伙伴",+ "slotLabelUnread": "{{name}},{{count}} 条未读",+ "running": "运行中",+ "latest": "最近",+ "statusAt": "{{status}} · {{time}}",+ "openConversation": "进入对话",+ "removed": "已将{{name}}移出伙伴",+ "removeFailed": "未能移出这个伙伴",+ "reorderInstructions": "按空格键拿起伙伴,用方向键移动,再按空格键放下,或按 Esc 取消。",+ "reorderPickedUp": "已拿起{{name}}。",+ "reorderPosition": "{{name}},第 {{position}} 位,共 {{count}} 位。",+ "reorderDropped": "已放下{{name}}。",+ "reorderCancelled": "已取消调整顺序。",+ "menu": {+ "label": "{{name}}的操作",+ "editProfile": "编辑资料",+ "dragToReorder": "拖动调整顺序",+ "remove": "移出伙伴",+ "removeNote": "对话和记忆都会保留,重新设为伙伴即可接回。"+ },+ "dialog": {+ "addTitle": "添加伙伴",+ "editTitle": "编辑资料",+ "description": "伙伴有名字、有自己的记忆,和它的对话会一直延续。",+ "tabNew": "新建",+ "tabFromAgent": "从已有 Agent 设为伙伴",+ "name": "名称",+ "displayName": "显示名称",+ "namePlaceholder": "例如:首席安全官",+ "nameRequired": "请给伙伴起个名字。",+ "avatar": "选择头像",+ "role": "它负责什么",+ "rolePlaceholder": "例如:负责依赖与权限的安全审计,每周一汇报一次",+ "roleHint": "会写进它的设定,之后可以在 Agents 页修改。",+ "handleGenerating": "正在生成代号…",+ "handleHint": "自动生成,用于 @ 和命令行",+ "handleLocked": "沿用 Agent 名,设为伙伴期间锁定",+ "handleFrozen": "创建后固定不变",+ "handleEdit": "修改代号",+ "handleInvalid": "请使用 2 到 24 个小写字母、数字或连字符,以字母开头,且不以连字符结尾。",+ "advancedFollows": "高级:模型跟随{{name}}({{model}})",+ "advancedModel": "高级:模型 {{model}}",+ "followMain": "改回跟随{{name}}的模型",+ "chatHint": "也可以直接跟{{name}}说「帮我加一个负责安全的伙伴」。",+ "fromAgentHint": "只列出 vibey 后端、还不是伙伴的 Agent。",+ "noEligibleAgents": "没有可以设为伙伴的 Vibey Agent,可以先在 Agents 页新建一个。",+ "pickAgent": "请选择一个 Agent。",+ "create": "添加伙伴",+ "set": "设为伙伴",+ "save": "保存",+ "saveFailed": "未能保存伙伴。",+ "avatarUploadFailed": "伙伴已保存,但头像没有上传成功。"+ },+ "avatarPicker": {+ "emoji": "表情",+ "upload": "上传图片",+ "background": "底色",+ "hue": "色相 {{hue}}",+ "defaultHint": "不选也行:默认用名称的第一个字配一个由名称决定的颜色。",+ "dropHint": "拖入图片,或点击选择",+ "formats": "PNG、JPG、WebP,自动裁成圆形",+ "unsupported": "请选择 PNG、JPG 或 WebP 图片。",+ "tooLarge": "图片超过 10 MB。",+ "useDefault": "恢复默认"+ },+ "conversation": {+ "editProfile": "编辑资料",+ "emptyTitle": "这是你和{{name}}对话的开始",+ "emptyBody": "这段对话会一直延续:{{name}}会把重要的事记在自己的记忆里,并按顺序处理消息。"+ },+ "agents": {+ "badge": "伙伴",+ "setAsBot": "设为伙伴",+ "setAsBotHint": "给它一个名字、一个头像,以及一段带记忆的常驻对话。",+ "setAsBotNeedsEnabled": "请先启用这个 Agent,再设为伙伴。",+ "isBotTitle": "这个 Agent 是伙伴「{{name}}」",+ "isBotHint": "设为伙伴期间,它保持启用、名字不变,也不能归档或删除;如需这样做,请先移出伙伴。",+ "isMainBotHint": "主伙伴的 Agent 是内置的:始终启用,不能移出。",+ "openConversation": "进入对话",+ "editProfile": "编辑资料"+ }+ },"editor": {"modeLabel": "编辑器模式","edit": "编辑",diff --git a/ui/src/index.css b/ui/src/index.cssindex 132acde7f..efb36eede 100644--- a/ui/src/index.css+++ b/ui/src/index.css@@ -303,6 +303,17 @@is #10B98114 against --mint-soft's #10B98124. They happen to coincide in Dark,which is exactly why collapsing them there would look correct and render wrongin the other theme. */+ /* Bot avatars (docs/plans/bots.md D5). The main Bot's mascot sits on a well+ that follows the theme: dark here, white with a hairline ring in Light. An+ emoji avatar keeps one hue and takes its well's saturation and lightness+ from the theme; the default (the name's first character) is a deeper fill. */+ --bot-mascot-well: #16172b;+ --bot-mascot-ring: rgba(255, 255, 255, 0.1);+ --bot-mascot-shadow: none;+ --bot-emoji-well-saturation: 35%;+ --bot-emoji-well-lightness: 20%;+ --bot-initial-saturation: 45%;+ --bot-initial-lightness: 38%;--sidebar-background: #0e0e18;--nav-selected-bg: #5bffa029;--nav-selected-border: #5bffa059;@@ -465,6 +476,14 @@from the fill, which is why they carry the fill's hex. *//* Mirrors the dark block's note: the sidebar fill and the selected nav washare the two that genuinely differ from --surface and --mint-soft here. */+ /* Bot avatar wells; see the dark block. */+ --bot-mascot-well: #ffffff;+ --bot-mascot-ring: rgba(8, 8, 18, 0.1);+ --bot-mascot-shadow: drop-shadow(0 1px 1.5px rgba(8, 8, 18, 0.28));+ --bot-emoji-well-saturation: 85%;+ --bot-emoji-well-lightness: 92%;+ --bot-initial-saturation: 70%;+ --bot-initial-lightness: 45%;--sidebar-background: #fcfcfe;--nav-selected-bg: #10b98114;--nav-selected-border: #10b98160;@@ -590,6 +609,15 @@/* Mirrors the @media light block above; see the note there. */--ring: rgba(16, 185, 129, 0.5);+ /* Bot avatar wells; mirrors the @media light block above. */+ --bot-mascot-well: #ffffff;+ --bot-mascot-ring: rgba(8, 8, 18, 0.1);+ --bot-mascot-shadow: drop-shadow(0 1px 1.5px rgba(8, 8, 18, 0.28));+ --bot-emoji-well-saturation: 85%;+ --bot-emoji-well-lightness: 92%;+ --bot-initial-saturation: 70%;+ --bot-initial-lightness: 45%;+/* Mirrors the @media light block above; see the note in the dark block. */--sidebar-background: #fcfcfe;--nav-selected-bg: #10b98114;@@ -1134,3 +1162,23 @@ pre,.project-drag-preview { animation: none; }.project-sortable { transition: none !important; }}++/* Bot avatars: `--bot-hue` is set per avatar; the theme supplies the rest. */+.bot-avatar-emoji {+ background: hsl(var(--bot-hue) var(--bot-emoji-well-saturation) var(--bot-emoji-well-lightness));+}+.bot-avatar-initial {+ background: hsl(var(--bot-hue) var(--bot-initial-saturation) var(--bot-initial-lightness));+ color: #ffffff;+}+.bot-avatar-mascot {+ background: var(--bot-mascot-well);+ box-shadow: inset 0 0 0 1px var(--bot-mascot-ring);+}+.bot-avatar-mascot > img {+ filter: var(--bot-mascot-shadow);+}+/* The strip scrolls sideways once it overflows; its right edge fades out. */+.bot-strip-fade {+ mask-image: linear-gradient(to right, #000 calc(100% - 28px), transparent);+}diff --git a/ui/src/lib/bots.ts b/ui/src/lib/bots.tsnew file mode 100644index 000000000..846ed8a16--- /dev/null+++ b/ui/src/lib/bots.ts@@ -0,0 +1,139 @@+// Bots (docs/plans/bots.md): an enabled Vibey Agent plus one permanent Session.+// The Web contract is `GET /api/bots`; this module holds the pure parts every+// surface shares — the payload shapes, the Session-id namespace, and the+// default avatar a Bot shows before one is chosen.++/** What `GET /api/bots` says a Bot looks like. `null` means no avatar chosen. */+export type BotAvatar =+ | { kind: 'mascot' }+ | { kind: 'emoji'; emoji: string; hue: number }+ | { kind: 'image'; url: string };++export type Bot = {+ /** Lowercase ASCII, frozen once the Bot exists (D2). */+ handle: string;+ /** Any language. Empty means the main Bot's localized default name. */+ display_name: string;+ avatar: BotAvatar | null;+ /** The Agent's description (D1). */+ role: string;+ agent_name: string;+ /** Always `ses_<handle>`. */+ session_id: string;+ position: number;+ /** The main Bot: always first, never removed. */+ builtin: boolean;+};++/** The Bot an Agent is, as Agent lists carry it. */+export type AgentBotSummary = {+ handle: string;+ display_name: string;+ builtin: boolean;+};++/** An emoji avatar as the API accepts it (`PATCH`/`POST` `avatar`). */+export type BotEmojiAvatarInput = { emoji: string; hue: number };++/** Generated Session ids are `ses` plus characters without `_`, so `ses_` is the+ * Bots' namespace alone (D2). Whether a Bot still owns the id is the list's call. */+export const BOT_SESSION_ID_PREFIX = 'ses_';+export const MAIN_BOT_SESSION_ID = 'ses_main';++export function isBotSessionId(sessionId: string | null | undefined): boolean {+ return typeof sessionId === 'string' && sessionId.startsWith(BOT_SESSION_ID_PREFIX);+}++/** Whether an Agent can be set as a Bot from the Web (D1, D5): an enabled Vibey+ * Agent that is not archived and not a Bot already. Built-in Agents are left+ * out: the default `vibey` Agent stays an ordinary worker (D9), and the main+ * Bot's Agent is one already. */+export function eligibleForBot(agent: {+ backend: string;+ enabled: boolean;+ archived?: boolean;+ source?: string;+ bot?: AgentBotSummary | null;+}): boolean {+ return agent.backend === 'vibey' && agent.enabled && !agent.archived && !agent.bot && agent.source !== 'builtin';+}++/** The name a Bot goes by: its display name, the localized default for the main+ * Bot, else its handle. */+export function botDisplayName(bot: Pick<Bot, 'display_name' | 'builtin' | 'handle'>, mainDefault: string): string {+ return bot.display_name.trim() || (bot.builtin ? mainDefault : bot.handle);+}++export function botSessionPath(bot: Pick<Bot, 'session_id'>): string {+ return `/chat/${encodeURIComponent(bot.session_id)}`;+}++/** D2's handle grammar, for the pre-creation edit: 2 to 24 characters, a letter+ * first, and no trailing hyphen (an Agent name never ends in one). */+export const BOT_HANDLE_RE = /^[a-z][a-z0-9-]{0,22}[a-z0-9]$/;++/** The hues the avatar picker offers; a name-derived default draws from them too. */+export const BOT_AVATAR_HUES = [200, 42, 150, 330, 265, 12, 180, 90] as const;++export const BOT_AVATAR_EMOJIS = [+ '🛡️', '🧭', '📊', '🎨', '🔭', '🧪', '📚', '💼',+ '🛠️', '📝', '🌐', '🎯', '🤖', '🦉', '🐳', '🚀',+] as const;++/** A stable hue from the name, so the default avatar keeps its color as the+ * Bot is renamed only when the name itself changes. */+export function nameHue(name: string): number {+ let hash = 0;+ for (const char of name.trim()) {+ hash = (hash * 31 + (char.codePointAt(0) ?? 0)) >>> 0;+ }+ return BOT_AVATAR_HUES[hash % BOT_AVATAR_HUES.length];+}++/** The first character of the name (a whole grapheme for CJK and emoji). */+export function nameInitial(name: string): string {+ const trimmed = name.trim();+ if (!trimmed) return '?';+ const Segmenter = (Intl as { Segmenter?: typeof Intl.Segmenter }).Segmenter;+ const first = Segmenter+ ? new Segmenter(undefined, { granularity: 'grapheme' }).segment(trimmed)[Symbol.iterator]().next().value?.segment+ : Array.from(trimmed)[0];+ return (first ?? '?').toLocaleUpperCase();+}++/** Display order: the main Bot first, then by position (the server's order, restated+ * so a local reorder renders without waiting for the refetch). */+export function orderBots(bots: Bot[]): Bot[] {+ return [...bots].sort((a, b) => {+ if (a.builtin !== b.builtin) return a.builtin ? -1 : 1;+ if (a.position !== b.position) return a.position - b.position;+ return a.handle.localeCompare(b.handle);+ });+}++export function parseBot(value: unknown): Bot | null {+ if (!value || typeof value !== 'object') return null;+ const raw = value as Record<string, unknown>;+ if (typeof raw.handle !== 'string' || !raw.handle) return null;+ return {+ handle: raw.handle,+ display_name: typeof raw.display_name === 'string' ? raw.display_name : '',+ avatar: parseBotAvatar(raw.avatar),+ role: typeof raw.role === 'string' ? raw.role : '',+ agent_name: typeof raw.agent_name === 'string' ? raw.agent_name : raw.handle,+ session_id: typeof raw.session_id === 'string' ? raw.session_id : `${BOT_SESSION_ID_PREFIX}${raw.handle}`,+ position: typeof raw.position === 'number' ? raw.position : 0,+ builtin: raw.builtin === true,+ };+}++function parseBotAvatar(value: unknown): BotAvatar | null {+ if (!value || typeof value !== 'object') return null;+ const raw = value as Record<string, unknown>;+ if (raw.kind === 'mascot') return { kind: 'mascot' };+ if (raw.kind === 'emoji' && typeof raw.emoji === 'string' && typeof raw.hue === 'number') {+ return { kind: 'emoji', emoji: raw.emoji, hue: raw.hue };+ }+ if (raw.kind === 'image' && typeof raw.url === 'string') return { kind: 'image', url: raw.url };+ return null;+}diff --git a/ui/src/lib/mentions.test.ts b/ui/src/lib/mentions.test.tsindex 8c3aa3a5c..7a684a895 100644--- a/ui/src/lib/mentions.test.ts+++ b/ui/src/lib/mentions.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { linkifyMentions, type MentionReference } from './mentions';+import { linkifyMentions, parseMentionHref, referenceToMarker, type MentionReference } from './mentions';const REFERENCES: MentionReference[] = [{ kind: 'agent', name: 'claude' },@@ -92,4 +92,38 @@ describe('linkifyMentions', () => {const replaced = verifyEdits(input, text, edits);expect(replaced[0][1]).toBe('[#ses6jr7c5h2q6](avibe-mention:session:ses6jr7c5h2q6)');});++ // Typed markers (docs/plans/bots.md D3): the marker carries the kind and the+ // frozen handle; the chip label is the Bot's display name from the sidecar,+ // so a rename never has to rewrite a stored message.+ it('reads typed Bot and Agent markers, and an untyped legacy one as an Agent', () => {+ const input = 'Ask @<bot:cso>, @<agent:reviewer>, and @<claude>.';+ const { text, edits } = linkifyMentions(input, [+ ...REFERENCES,+ { kind: 'bot', handle: 'cso', display_name: '首席安全官' },+ ]);++ const replaced = verifyEdits(input, text, edits);+ expect(replaced.map(([, to]) => to)).toEqual([+ '[@首席安全官](avibe-mention:bot:cso)',+ '[@reviewer](avibe-mention:agent:reviewer)',+ '[@claude](avibe-mention:agent:claude)',+ ]);+ expect(parseMentionHref('avibe-mention:bot:cso')).toEqual({ kind: '@', target: 'bot', value: 'cso' });+ expect(parseMentionHref('avibe-mention:agent:reviewer')).toEqual({ kind: '@', target: 'agent', value: 'reviewer' });+ });++ it('labels a Bot by its handle when the message carried no display name', () => {+ const { text } = linkifyMentions('Ask @<bot:cso>.', [{ kind: 'bot', handle: 'cso' }]);++ expect(text).toBe('Ask [@cso](avibe-mention:bot:cso).');+ });+});++describe('referenceToMarker', () => {+ it('writes the kind into every @ marker', () => {+ expect(referenceToMarker({ kind: 'bot', handle: 'cso', display_name: '首席安全官' })).toBe('@<bot:cso>');+ expect(referenceToMarker({ kind: 'agent', name: 'reviewer' })).toBe('@<agent:reviewer>');+ expect(referenceToMarker({ kind: 'session', session_id: 'ses6jr7c5h2q6' })).toBe('#<ses6jr7c5h2q6>');+ });});diff --git a/ui/src/lib/mentions.ts b/ui/src/lib/mentions.tsindex ab0f5b643..196a2a074 100644--- a/ui/src/lib/mentions.ts+++ b/ui/src/lib/mentions.ts@@ -1,9 +1,13 @@-// Shared contract for @-agent / #-session mentions in the chat composer.+// Shared contract for @-mentions (Bots and Agents) and #-session references in+// the chat composer.//-// Marker convention (the agent-facing, transport-stable form): `@<agent-name>`-// and `#<session-id>` live inline in the message text. A structured sidecar in-// `message.content.references` carries the resolved data (ids, session titles)-// for faithful chip rendering and backend context — see docs/plans.+// Marker convention (the agent-facing, transport-stable form) lives inline in the+// message text and carries the kind (docs/plans/bots.md D3): `@<bot:handle>`+// points at a Bot's permanent conversation, `@<agent:name>` at an Agent (a fresh+// Session each run), and `#<session-id>` at a Session. An untyped `@<name>` in+// older messages means an Agent. A structured sidecar in+// `message.content.references` carries the resolved data (ids, display names,+// session titles) for faithful chip rendering and backend context — see docs/plans.//// Humans never read the raw markers (the bubble renders chips), so the format is// optimized for LLM legibility + robust parsing. The `<…>` form is excised from@@ -30,7 +34,26 @@ export type SessionReference = {title?: string | null;};-export type MentionReference = AgentReference | SessionReference;+export type BotReference = {+ kind: 'bot';+ /** The frozen handle — the marker and `vibe agent run --bot <handle>` target. */+ handle: string;+ /** Snapshot of the display name at send time — the chip's fallback label. */+ display_name?: string | null;+};++export type MentionReference = AgentReference | BotReference | SessionReference;++/** What a `@` marker points at. */+export type MentionTarget = 'agent' | 'bot' | 'session';++/** Split the inside of an `@<…>` marker into its kind and name. Untyped markers+ * from before typed mentions mean an Agent. */+export function parseAtMarker(inner: string): { target: 'agent' | 'bot'; name: string } {+ if (inner.startsWith('bot:')) return { target: 'bot', name: inner.slice(4) };+ if (inner.startsWith('agent:')) return { target: 'agent', name: inner.slice(6) };+ return { target: 'agent', name: inner };+}export const MENTION_TRIGGERS = ['@', '#'] as const;export type MentionTrigger = (typeof MENTION_TRIGGERS)[number];@@ -44,7 +67,9 @@ export const MENTION_LINK_SCHEME = 'avibe-mention';/** The inline text marker for a reference. */export function referenceToMarker(ref: MentionReference): string {- return ref.kind === 'agent' ? `@<${ref.name}>` : `#<${ref.session_id}>`;+ if (ref.kind === 'bot') return `@<bot:${ref.handle}>`;+ if (ref.kind === 'agent') return `@<agent:${ref.name}>`;+ return `#<${ref.session_id}>`;}/** Dedupe references by (kind, id) so a marker repeated in the text yields one entry. */@@ -52,7 +77,11 @@ export function dedupeReferences(refs: MentionReference[]): MentionReference[] {const seen = new Set<string>();const out: MentionReference[] = [];for (const ref of refs) {- const key = ref.kind === 'agent' ? `agent:${ref.name}` : `session:${ref.session_id}`;+ const key = ref.kind === 'agent'+ ? `agent:${ref.name}`+ : ref.kind === 'bot'+ ? `bot:${ref.handle}`+ : `session:${ref.session_id}`;if (seen.has(key)) continue;seen.add(key);out.push(ref);@@ -82,17 +111,29 @@ const CODE_SEGMENT_RE = /(```[\s\S]*?```|`[^`]*`)/g;export function linkifyMentions(text: string, references?: MentionReference[]): EditedText {const sessionTitles = new Map<string, string>();+ const botNames = new Map<string, string>();for (const ref of references ?? []) {if (ref.kind === 'session' && ref.title) sessionTitles.set(ref.session_id, ref.title);+ if (ref.kind === 'bot' && ref.display_name) botNames.set(ref.handle, ref.display_name);}const edits: TextEdit[] = [];const rewrite = (segment: string, base: number): string =>segment.replace(MENTION_MARKER_RE, (full: string, trigger: string, inner: string, at: number) => {- const label = trigger === '@'- ? escapeMarkdownLabel(`@${inner}`)- : escapeMarkdownLabel(`#${sessionTitles.get(inner) || inner}`);- const kind = trigger === '@' ? 'agent' : 'session';- const link = `[${label}](${MENTION_LINK_SCHEME}:${kind}:${encodeURIComponent(inner)})`;+ let kind: MentionTarget = 'session';+ let value = inner;+ let label: string;+ if (trigger === '@') {+ const marker = parseAtMarker(inner);+ kind = marker.target;+ value = marker.name;+ // A Bot's chip shows its display name (the marker keeps the handle, so a+ // rename never alters old messages); the renderer refreshes it from the+ // live Bot when there is one.+ label = escapeMarkdownLabel(`@${kind === 'bot' ? botNames.get(value) || value : value}`);+ } else {+ label = escapeMarkdownLabel(`#${sessionTitles.get(inner) || inner}`);+ }+ const link = `[${label}](${MENTION_LINK_SCHEME}:${kind}:${encodeURIComponent(value)})`;edits.push({ start: base + at, end: base + at + full.length, inserted: link.length });return link;});@@ -113,7 +154,7 @@ export function linkifyMentions(text: string, references?: MentionReference[]):}/** Parse an `avibe-mention:<kind>:<value>` href back into its parts. */-export function parseMentionHref(href: string): { kind: MentionTrigger; value: string } | null {+export function parseMentionHref(href: string): { kind: MentionTrigger; target: MentionTarget; value: string } | null {const prefix = `${MENTION_LINK_SCHEME}:`;if (!href.startsWith(prefix)) return null;const rest = href.slice(prefix.length);@@ -126,8 +167,9 @@ export function parseMentionHref(href: string): { kind: MentionTrigger; value: s} catch {value = rest.slice(sep + 1);}- if (kindStr === 'agent') return { kind: '@', value };- if (kindStr === 'session') return { kind: '#', value };+ if (kindStr === 'agent') return { kind: '@', target: 'agent', value };+ if (kindStr === 'bot') return { kind: '@', target: 'bot', value };+ if (kindStr === 'session') return { kind: '#', target: 'session', value };return null;}diff --git a/ui/src/pet/PetPage.tsx b/ui/src/pet/PetPage.tsxindex 0aa9946c0..b8bdea529 100644--- a/ui/src/pet/PetPage.tsx+++ b/ui/src/pet/PetPage.tsx@@ -18,6 +18,7 @@ import { readMessageAttachments } from '@/lib/messageAttachments';import { usePendingVaultRequests } from '@/lib/usePendingVaultRequests';import { useVaultRequestRefresh } from '@/lib/useVaultRequestRefresh';import { vaultRequestType } from '@/lib/vaultRequestPlacement';+import { useBots } from '@/context/BotsContext';import { referenceToMarker, type MentionReference, type SessionReference } from '@/lib/mentions';import { ShowPageVoiceDictation } from '@/lib/showPageVoiceDictation';import { VoiceTranscriptionError } from '@/lib/voiceTranscription';@@ -1613,6 +1614,11 @@ function useWidthMorph(key: unknown, reducedMotion: boolean) {const MainReplyBubble: React.FC<Omit<MainDetailProps, 'visible'> & { open: boolean; onToggle: () => void; pinnedReply?: WorkbenchMessage | null; reducedMotion: boolean }> = ({ open, onToggle, pinnedReply, reducedMotion, ...props }) => {const { t } = useTranslation();+ // The bubble speaks as the main Bot, by the name the user gave it (docs/plans/+ // bots.md D5); the mascot art stays Vibey's. Until the Bot list answers, and+ // for anyone but the Owner, it is the localized default name.+ const { mainBot, displayName } = useBots();+ const speaker = mainBot ? displayName(mainBot) : t('pet.mainAgent');// A lingering reply keeps its summary even if a later result (a background// completion) arrives while it lingers.const last = pinnedReply ?? props.exchange.results.at(-1);@@ -1633,7 +1639,7 @@ const MainReplyBubble: React.FC<Omit<MainDetailProps, 'visible'> & { open: boolereturn (<div ref={bubbleRef} className={clsx('pet-mini-reply-bubble is-main', compact && 'is-compact')} data-pet-hit><button type="button" className="pet-mini-reply-toggle" onClick={onToggle} aria-expanded={open} aria-controls={detailId}>- <span className="pet-mini-bubble-speaker">{t('pet.mainAgent')}<span>{t(open ? 'pet.collapseHistory' : 'pet.recentTurns')}<ChevronUp size={11} /></span></span>+ <span className="pet-mini-bubble-speaker">{speaker}<span>{t(open ? 'pet.collapseHistory' : 'pet.recentTurns')}<ChevronUp size={11} /></span></span><p title={summary}>{props.running && <span className="pet-mini-running-dot" aria-hidden />}<span className="pet-mini-reply-summary">{summary}</span></p></button><div id={detailId} className={clsx('pet-mini-detail', open && 'is-open')}>