Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(desktop): the mini talks to a per-person Vibey conversation (#2546)

Max748be1c30a95
diff --git a/docs/plans/2026-10-12-desktop-mini-main-agent.md b/docs/plans/2026-10-12-desktop-mini-main-agent.md
index a3e77700c..60a19e840 100644
--- a/docs/plans/2026-10-12-desktop-mini-main-agent.md
+++ b/docs/plans/2026-10-12-desktop-mini-main-agent.md
@@ -477,6 +477,45 @@ sessions.
binding writes. Older `pet.json` files that contain `binding` must still
load; ignore the field (persisted-shape rule).
+### 10.1 Interim: the mini talks to Vibey (owner decision, 2026-10-13)
+
+Until the `main` type exists, the mini's main agent is a Vibey conversation
+(the built-in Agent, `backend: vibey`).
+
+- **One per person, created on first use.** `POST /api/desktop-mini/session`
+ (Editor) returns the caller's conversation, creating it the first time in
+ their most recently active Project they can chat in. A session needs a
+ Project so it has a Workbench sidebar home and "在 Avibe 中打开" lands on it.
+ It is an ordinary foreground session, so the Workbench shows and manages it
+ like any other. Which session belongs to whom is recorded server-side in
+ `state_meta` (`desktop_mini_session:<principal>`, principal `local` or
+ `remote:<sub>`), never in session metadata a client can write or a fork can
+ copy.
+- **Who the caller is.** The principal comes from the request's authorization
+ context, never from a second lookup that could fall back: a remote context
+ without a subject owns nothing and is refused.
+- **Reuse.** The same session is returned while it is still what creation
+ would produce: active, foreground, a Project the caller can chat in, still on
+ the built-in Agent (a Workbench route change makes it an ordinary chat), which
+ the caller may use. Title, model and effort are the user's to change. An archived session, an archived Project or lost
+ access gets a new one. With no chat Project at all the answer is
+ `409 no_chat_project`, and the mini asks the user to create a Project.
+- **Binding.** The mini binds that session whenever nothing is bound. An
+ existing binding is kept; the switcher offers "和歪比对话" to move to it.
+ A session the mini already bound and then cleared as invalid is not
+ re-bound automatically, so a bad answer cannot loop.
+- **A turn Vibey cannot run is shown.** When the latest exchange ended in a
+ backend failure notice (for example no model source), the main card's
+ subtitle reads "没跑起来:<notice>" (the exchange ends at its foreground
+ terminal row, by the transcript's own rule, so detached completions and
+ replayed failures never decide it), and the detail shows the notice as plain
+ text with "在 Avibe 中处理" when it names a next step. That opens the session,
+ where the Workbench draws "Open Models" for those who manage the instance.
+- **Not in this change.** A live step label ("Ran command", …) for the main
+ card still waits on §11.1; the server already computes `status_label` for
+ the IM status bubble and can expose it later.
+- When `main` lands, this endpoint is replaced by `GET /api/sessions/main`.
+
## 11. Backend gaps (not in this delivery; degrade gracefully)
1. **No "current step" text.**
diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.py
index b544fe471..86f0be523 100644
--- a/storage/workbench_sessions_service.py
+++ b/storage/workbench_sessions_service.py
@@ -21,6 +21,7 @@ from pathlib import Path
from typing import Any, Mapping, Optional
from sqlalchemy import Integer, and_, cast, func, or_, select, update
+from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from sqlalchemy.engine import Connection
from config import paths
@@ -56,6 +57,7 @@ from storage.models import (
scope_settings,
scopes,
show_pages,
+ state_meta,
agents,
)
@@ -635,6 +637,148 @@ def create_session(
return get_session(conn, session_id, authorization_context=authorization)
+# The desktop mini's conversation, until sessions get a built-in ``main`` type
+# (docs/plans/2026-10-12-desktop-mini-main-agent.md §10.1). The association lives in
+# server-owned ``state_meta``, one key per principal, never in client-writable
+# session metadata: a marker any editor can set on their own session (or inherit by
+# forking) would let them hand someone else's mini a conversation they control.
+DESKTOP_MINI_SESSION_META_PREFIX = "desktop_mini_session:"
+
+
+class NoChatProjectError(LookupError):
+ """The caller has no active Project they can chat in, so there is no home for the session."""
+
+ code = "no_chat_project"
+
+
+def _desktop_mini_session_id(conn: Connection, key: str) -> Optional[str]:
+ raw = conn.execute(select(state_meta.c.value_json).where(state_meta.c.key == key)).scalar_one_or_none()
+ try:
+ value = json.loads(raw) if raw else None
+ except (TypeError, json.JSONDecodeError):
+ return None
+ return value if isinstance(value, str) and value else None
+
+
+def desktop_mini_owner_key(context: AuthorizationContext) -> Optional[str]:
+ """The principal a desktop mini conversation belongs to, from the request's authority.
+
+ Same identity the Workbench writes a reader's rows as: ``remote:<sub>`` for a
+ Cloud session, ``local`` otherwise. A remote context without a subject has no
+ identity to own anything, so it gets none rather than falling back to ``local``.
+ """
+
+ if context.is_remote:
+ subject = str(context.subject or "").strip()
+ return f"remote:{subject}" if subject else None
+ return "local"
+
+
+def _usable_desktop_mini_session(
+ conn: Connection,
+ context: AuthorizationContext,
+ session_id: str,
+ agent_id: Optional[str],
+) -> bool:
+ """Whether ``session_id`` is still what ``ensure_desktop_mini_session`` would create.
+
+ One predicate for the whole contract, so reuse cannot drift from creation: an
+ active foreground session, in an enabled Project the caller can chat in, still
+ on the requested Agent (a Workbench route change makes it an ordinary chat that
+ the mini no longer owns), which the caller may still use. The title, model and
+ effort are the user's to change.
+ """
+ row = conn.execute(
+ select(
+ agent_sessions.c.status,
+ agent_sessions.c.visibility,
+ agent_sessions.c.scope_id,
+ agent_sessions.c.agent_name,
+ agent_sessions.c.agent_id,
+ scope_settings.c.enabled,
+ )
+ .select_from(agent_sessions.outerjoin(scope_settings, scope_settings.c.scope_id == agent_sessions.c.scope_id))
+ .where(agent_sessions.c.id == session_id)
+ ).mappings().first()
+ if row is None or row["status"] != "active" or row["visibility"] != "foreground" or row["enabled"] == 0:
+ return False
+ project_id = project_access_service.project_id_from_scope_id(row["scope_id"])
+ if project_id is None or not project_access_service.can_chat_project(conn, context, project_id):
+ return False
+ if not agent_id or row["agent_id"] != agent_id:
+ return False
+ if row["agent_name"] or row["agent_id"]:
+ from core.vibe_agents import (
+ VibeAgentAccessError,
+ ensure_agent_selection_access,
+ resolve_resource_access_context,
+ )
+
+ try:
+ ensure_agent_selection_access(
+ conn,
+ agent_name=row["agent_name"],
+ agent_id=row["agent_id"],
+ user_context=resolve_resource_access_context(None),
+ )
+ except (VibeAgentAccessError, ValueError):
+ return False
+ return True
+
+
+def ensure_desktop_mini_session(
+ conn: Connection,
+ *,
+ agent_name: str,
+ title: Optional[str] = None,
+ authorization_context: AuthorizationContext | Mapping[str, Any] | None = None,
+) -> dict[str, Any]:
+ """Return the caller's desktop mini session, creating it on first use.
+
+ The recorded session is reused while the caller can still chat in it: active,
+ foreground, in an enabled Project they can chat in. Otherwise a new one is
+ created for ``agent_name`` in the caller's most recently active chat Project,
+ so it has a sidebar home and "Open in Avibe" lands on it, and the record moves
+ to it.
+ """
+
+ context = require_instance_role(authorization_context, "editor")
+ owner_key = desktop_mini_owner_key(context)
+ if owner_key is None:
+ raise ProjectAccessDeniedError
+ reserve_write_lock(conn)
+ key = f"{DESKTOP_MINI_SESSION_META_PREFIX}{owner_key}"
+ recorded = _desktop_mini_session_id(conn, key)
+ agent_id = conn.execute(
+ select(agents.c.id).where(agents.c.name == agent_name, agents.c.archived_at.is_(None))
+ ).scalar_one_or_none()
+ if recorded and _usable_desktop_mini_session(conn, context, recorded, agent_id):
+ return get_session(conn, recorded, authorization_context=context)
+
+ from storage import projects_service
+
+ for project in projects_service.list_projects(conn, authorization_context=context):
+ if project.get("archived") or not (project.get("capabilities") or {}).get("can_chat"):
+ continue
+ session = create_session(
+ conn,
+ scope_id=project["scope_id"],
+ agent_backend="",
+ agent_name=agent_name,
+ title=title,
+ authorization_context=context,
+ )
+ statement = sqlite_insert(state_meta).values(
+ key=key, value_json=json.dumps(session["id"]), updated_at=_utc_now_iso()
+ )
+ conn.execute(statement.on_conflict_do_update(
+ index_elements=[state_meta.c.key],
+ set_={"value_json": statement.excluded.value_json, "updated_at": statement.excluded.updated_at},
+ ))
+ return session
+ raise NoChatProjectError("No project to start the desktop mini conversation in")
+
+
class ReservedSessionError(PermissionError):
"""Raised when a caller tries to tear down or edit a session the runtime reserves.
diff --git a/tests/fixtures/member_management_existing_read_roles.json b/tests/fixtures/member_management_existing_read_roles.json
index 15e4a63b5..739fffec9 100644
--- a/tests/fixtures/member_management_existing_read_roles.json
+++ b/tests/fixtures/member_management_existing_read_roles.json
@@ -87,6 +87,7 @@
"POST /api/asr/telemetry": "editor",
"POST /api/asr/transcribe": "editor",
"POST /api/config": "editor",
+ "POST /api/desktop-mini/session": "editor",
"POST /api/dock/pins": "editor",
"POST /api/files/copy": "editor",
"POST /api/files/delete": "editor",
diff --git a/tests/test_desktop_mini_session.py b/tests/test_desktop_mini_session.py
new file mode 100644
index 000000000..23a8e46cc
--- /dev/null
+++ b/tests/test_desktop_mini_session.py
@@ -0,0 +1,243 @@
+"""The desktop mini's Vibey conversation: created on first use, then reused.
+
+Interim rule until sessions get a built-in ``main`` type
+(docs/plans/2026-10-12-desktop-mini-main-agent.md §10.1).
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from storage.importer import ensure_sqlite_state
+from tests.ui_server_test_helpers import csrf_headers
+from vibe.ui_server import app
+
+
+def state(monkeypatch, tmp_path):
+ from core.vibe_agents import VibeAgentStore
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ store = VibeAgentStore()
+ try:
+ store.ensure_builtin_default_agents([])
+ vibey = store.get_builtin_default_agent_for_backend("vibey")
+ finally:
+ store.close()
+ assert vibey is not None
+ yield tmp_path, vibey
+
+
+def _project(tmp_path, name: str):
+ from storage.db import create_sqlite_engine
+ from storage.projects_service import create_project
+
+ folder = tmp_path / name
+ folder.mkdir()
+ with create_sqlite_engine().begin() as conn:
+ return create_project(conn, str(folder), display_name=name)
+
+
+def _context(principal: str):
+ from vibe.authorization import AuthorizationContext, instance_owner_context
+
+ if principal == "local":
+ return instance_owner_context()
+ return AuthorizationContext(instance_role="owner", is_remote=True, subject=principal.removeprefix("remote:"))
+
+
+def _ensure(principal: str, agent_name: str):
+ from storage.db import create_sqlite_engine
+ from storage.workbench_sessions_service import ensure_desktop_mini_session
+
+ with create_sqlite_engine().begin() as conn:
+ return ensure_desktop_mini_session(
+ conn,
+ agent_name=agent_name,
+ title="Vibey",
+ authorization_context=_context(principal),
+ )
+
+
+def _touch(project_id: str, when: str) -> None:
+ from sqlalchemy import update
+
+ from storage.db import create_sqlite_engine
+ from storage.models import scopes
+
+ with create_sqlite_engine().begin() as conn:
+ conn.execute(update(scopes).where(scopes.c.native_id == project_id).values(last_seen_at=when))
+
+
+def test_first_use_creates_a_vibey_session_in_the_most_recent_project_then_reuses_it(state):
+ tmp_path, vibey = state
+ older = _project(tmp_path, "older")
+ recent = _project(tmp_path, "recent")
+ _touch(older["id"], "2026-01-01T00:00:00Z")
+ _touch(recent["id"], "2026-10-01T00:00:00Z")
+
+ first = _ensure("local", vibey.name)
+ assert first["project_id"] == recent["id"]
+ assert first["agent_name"] == vibey.name
+ assert first["agent_backend"] == "vibey"
+ assert first["visibility"] == "foreground"
+
+ # Recency moving later does not move the conversation.
+ _touch(older["id"], "2026-12-01T00:00:00Z")
+ assert _ensure("local", vibey.name)["id"] == first["id"]
+
+
+def test_each_principal_gets_its_own_session(state):
+ tmp_path, vibey = state
+ _project(tmp_path, "p")
+ mine = _ensure("local", vibey.name)
+ theirs = _ensure("remote:someone", vibey.name)
+ assert mine["id"] != theirs["id"]
+ assert _ensure("remote:someone", vibey.name)["id"] == theirs["id"]
+
+
+def test_an_archived_session_is_replaced(state):
+ from storage.db import create_sqlite_engine
+ from storage.workbench_sessions_service import archive_session
+
+ tmp_path, vibey = state
+ _project(tmp_path, "p")
+ first = _ensure("local", vibey.name)
+ with create_sqlite_engine().begin() as conn:
+ archive_session(conn, first["id"])
+ second = _ensure("local", vibey.name)
+ assert second["id"] != first["id"]
+ assert second["status"] == "active"
+
+
+def test_without_a_chat_project_there_is_no_session(state):
+ from storage.workbench_sessions_service import NoChatProjectError
+
+ _tmp_path, vibey = state
+ with pytest.raises(NoChatProjectError):
+ _ensure("local", vibey.name)
+
+
+def test_route_returns_the_session_with_its_chat_grant(state):
+ tmp_path, _vibey = state
+ _project(tmp_path, "p")
+ client = app.test_client()
+ first = client.post("/api/desktop-mini/session", json={}, headers=csrf_headers(client))
+ assert first.status_code == 200, first.get_json()
+ body = first.get_json()
+ assert body["agent_backend"] == "vibey"
+ assert body["capabilities"] == {"can_chat": True}
+ again = client.post("/api/desktop-mini/session", json={}, headers=csrf_headers(client))
+ assert again.get_json()["id"] == body["id"]
+
+
+def test_route_explains_a_missing_project(state):
+ client = app.test_client()
+ response = client.post("/api/desktop-mini/session", json={}, headers=csrf_headers(client))
+ assert response.status_code == 409
+ assert response.get_json()["error"]["code"] == "no_chat_project"
+
+
+def test_route_is_an_editor_write():
+ from vibe.authorization import required_instance_role
+
+ assert required_instance_role("POST", "/api/desktop-mini/session") == "editor"
+
+
+def test_client_metadata_cannot_claim_someone_elses_conversation(state):
+ """Ownership is server-owned: a session carrying a look-alike marker is never handed out."""
+ from storage.db import create_sqlite_engine
+ from storage.workbench_sessions_service import create_session
+
+ tmp_path, vibey = state
+ project = _project(tmp_path, "shared")
+ with create_sqlite_engine().begin() as conn:
+ planted = create_session(
+ conn,
+ scope_id=project["scope_id"],
+ agent_backend="",
+ agent_name=vibey.name,
+ metadata={"desktop_mini_owner": "local", "desktop_mini_session": "local"},
+ )
+ assert _ensure("local", vibey.name)["id"] != planted["id"]
+
+
+def test_unrelated_malformed_metadata_does_not_break_the_lookup(state):
+ from sqlalchemy import update
+
+ from storage.db import create_sqlite_engine
+ from storage.models import agent_sessions
+ from storage.workbench_sessions_service import create_session
+
+ tmp_path, vibey = state
+ project = _project(tmp_path, "p")
+ with create_sqlite_engine().begin() as conn:
+ junk = create_session(conn, scope_id=project["scope_id"], agent_backend="", agent_name=vibey.name)
+ conn.execute(update(agent_sessions).where(agent_sessions.c.id == junk["id"]).values(metadata_json="{not json"))
+ first = _ensure("local", vibey.name)
+ assert _ensure("local", vibey.name)["id"] == first["id"]
+
+
+def test_owner_comes_from_the_authorization_context():
+ from vibe.authorization import AuthorizationContext, instance_owner_context
+ from storage.workbench_sessions_service import desktop_mini_owner_key
+
+ assert desktop_mini_owner_key(instance_owner_context()) == "local"
+ assert desktop_mini_owner_key(AuthorizationContext(instance_role="editor", is_remote=True, subject="u1")) == "remote:u1"
+ # A remote caller without a subject is nobody, never the local owner.
+ assert desktop_mini_owner_key(AuthorizationContext(instance_role="editor", is_remote=True)) is None
+
+
+def test_a_remote_caller_without_a_subject_is_refused(state):
+ from storage.db import create_sqlite_engine
+ from storage.workbench_sessions_service import ProjectAccessDeniedError, ensure_desktop_mini_session
+ from vibe.authorization import AuthorizationContext
+
+ tmp_path, vibey = state
+ _project(tmp_path, "p")
+ _ensure("local", vibey.name)
+ with pytest.raises(ProjectAccessDeniedError), create_sqlite_engine().begin() as conn:
+ ensure_desktop_mini_session(
+ conn,
+ agent_name=vibey.name,
+ authorization_context=AuthorizationContext(instance_role="owner", is_remote=True),
+ )
+
+
+def test_a_recorded_session_whose_agent_the_caller_lost_is_not_reused(state, monkeypatch):
+ from core import vibe_agents
+
+ tmp_path, vibey = state
+ _project(tmp_path, "p")
+ _ensure("local", vibey.name)
+
+ def refuse(*_args, **_kwargs):
+ raise vibe_agents.VibeAgentAccessError("Agent access is not permitted.")
+
+ monkeypatch.setattr(vibe_agents, "ensure_agent_selection_access", refuse)
+ # Not reused; a new one is refused by the same check instead of being handed out.
+ with pytest.raises(vibe_agents.VibeAgentAccessError):
+ _ensure("local", vibey.name)
+
+
+def test_a_session_moved_to_another_agent_is_not_reused(state):
+ from core.vibe_agents import VibeAgentStore
+ from storage.db import create_sqlite_engine
+ from storage.workbench_sessions_service import update_session
+ from vibe.authorization import instance_owner_context
+
+ tmp_path, vibey = state
+ _project(tmp_path, "p")
+ first = _ensure("local", vibey.name)
+ store = VibeAgentStore()
+ try:
+ store.create(name="reviewer", backend="vibey")
+ finally:
+ store.close()
+ with create_sqlite_engine().begin() as conn:
+ update_session(conn, first["id"], agent_name="reviewer", authorization_context=instance_owner_context())
+ second = _ensure("local", vibey.name)
+ assert second["id"] != first["id"]
+ assert second["agent_name"] == vibey.name
+ assert _ensure("local", vibey.name)["id"] == second["id"]
diff --git a/tests/test_member_management_parity.py b/tests/test_member_management_parity.py
index 5495a9e17..2b45c8bc2 100644
--- a/tests/test_member_management_parity.py
+++ b/tests/test_member_management_parity.py
@@ -118,7 +118,8 @@ def test_complete_registered_api_management_inventory():
for method in (getattr(route, "methods", None) or ())
if method not in {"HEAD", "OPTIONS"}
}
- assert len(endpoints) == 280
+ assert len(endpoints) == 281
+ assert http_authorization_policy("POST", "/api/desktop-mini/session").minimum_role == "editor"
assert http_authorization_policy("GET", "/api/desktop/capabilities").minimum_role == "member"
assert http_authorization_policy("GET", "/api/desktop/computer-use/status").minimum_role == "member"
# Additive read-only backend projection inherits native backend-management
diff --git a/ui/src/context/ApiContext.desktopMini.test.tsx b/ui/src/context/ApiContext.desktopMini.test.tsx
new file mode 100644
index 000000000..50562db4b
--- /dev/null
+++ b/ui/src/context/ApiContext.desktopMini.test.tsx
@@ -0,0 +1,62 @@
+/* @vitest-environment jsdom */
+
+import { useEffect } from 'react';
+import { cleanup, render, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const apiFetch = vi.hoisted(() => vi.fn());
+const showToast = vi.hoisted(() => vi.fn());
+
+vi.mock('../lib/apiFetch', () => ({ apiFetch }));
+vi.mock('./ToastContext', () => ({ useToast: () => ({ showToast }) }));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+import { ApiError, ApiProvider, useApi } from './ApiContext';
+
+let capturedApi: ReturnType<typeof useApi> | null = null;
+const CaptureApi = () => {
+ const api = useApi();
+ useEffect(() => { capturedApi = api; }, [api]);
+ return null;
+};
+const response = (payload: unknown, status = 200) => new Response(JSON.stringify(payload), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+});
+
+beforeEach(() => {
+ capturedApi = null;
+ apiFetch.mockReset();
+ showToast.mockReset();
+});
+afterEach(cleanup);
+
+describe('ensureDesktopMiniSession', () => {
+ it('returns the session row without its capabilities', async () => {
+ render(<ApiProvider><CaptureApi /></ApiProvider>);
+ await waitFor(() => expect(capturedApi).not.toBeNull());
+ apiFetch.mockResolvedValueOnce(response({ id: 'V', title: 'Vibey', capabilities: { can_chat: true } }));
+ const session = await capturedApi!.ensureDesktopMiniSession();
+ expect(session).toMatchObject({ id: 'V', title: 'Vibey' });
+ expect(session).not.toHaveProperty('capabilities');
+ expect(apiFetch).toHaveBeenCalledWith('/api/desktop-mini/session', expect.objectContaining({ method: 'POST' }));
+ });
+
+ it('rejects with the structured code and no global toast', async () => {
+ render(<ApiProvider><CaptureApi /></ApiProvider>);
+ await waitFor(() => expect(capturedApi).not.toBeNull());
+ apiFetch.mockResolvedValueOnce(response({
+ ok: false,
+ error: { code: 'no_chat_project', message: 'Create a project first.' },
+ code: 'no_chat_project',
+ message: 'Create a project first.',
+ }, 409));
+ const error = await capturedApi!.ensureDesktopMiniSession().catch((caught: unknown) => caught);
+ expect(error).toBeInstanceOf(ApiError);
+ expect((error as ApiError).status).toBe(409);
+ expect((error as ApiError).code).toBe('no_chat_project');
+ expect(showToast).not.toHaveBeenCalled();
+ });
+});
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index d2a9ab864..e9de3f840 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -726,6 +726,9 @@ export type ApiContextType = {
/** Main-agent lookup seam. The endpoint is not shipped yet; the pet client
* currently resolves the session bound to its native window here. */
getMainSession: () => Promise<WorkbenchSessionReadResult>;
+ /** The caller's desktop mini conversation with Vibey, created on first use
+ * in their most recently active chat Project. */
+ ensureDesktopMiniSession: () => Promise<WorkbenchSession>;
getSessionResult: (sessionId: string) => Promise<WorkbenchSessionReadResult>;
getSessionBootstrap: (sessionId: string) => Promise<WorkbenchSessionBootstrap>;
updateSession: (sessionId: string, payload: Partial<WorkbenchSessionUpdate>) => Promise<WorkbenchSession>;
@@ -3746,6 +3749,21 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
capabilities: sessionCanChatFromPayload(payload),
};
},
+ ensureDesktopMiniSession: async () => {
+ // No global toast: the pet shows its own copy. Errors still reject, with the code.
+ const res = await apiFetch('/api/desktop-mini/session', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({}),
+ });
+ const payload = await res.json().catch(() => null);
+ if (!res.ok || !payload || typeof payload.id !== 'string') {
+ const parsed = selectApiErrorFields(payload, `Request failed: /api/desktop-mini/session (${res.status})`);
+ throw new ApiError(parsed?.fallback ?? `Request failed (${res.status})`, res.status, parsed?.code ?? null);
+ }
+ clearReadCacheMatching((path) => path.startsWith('/api/sessions') || path.startsWith('/api/workbench/projects-bootstrap'));
+ return sessionRowFromPayload(payload);
+ },
getSessionResult: async (sessionId) => {
const res = await apiFetch(`/api/sessions/${encodeURIComponent(sessionId)}`);
const payload = await res.json().catch(() => null);
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 168f88e2f..f4d738515 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -5644,6 +5644,11 @@
"stopped": "Stopped",
"paused": "Paused",
"failed": "Could not stop; try again later"
- }
+ },
+ "failedPrefix": "Didn't run:",
+ "fixInAvibe": "Fix it in Avibe",
+ "talkToVibey": "Talk to Vibey",
+ "noChatProject": "Create a project in Avibe first, so Vibey has a place for this conversation.",
+ "vibeyUnavailable": "Couldn't open the conversation with Vibey. Try again in a moment."
}
}
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index d58afb584..afbfa4aa2 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -5644,6 +5644,11 @@
"stopped": "已停止",
"paused": "已暂停",
"failed": "没停下来,稍后再试"
- }
+ },
+ "failedPrefix": "没跑起来:",
+ "fixInAvibe": "在 Avibe 中处理",
+ "talkToVibey": "和歪比对话",
+ "noChatProject": "先在 Avibe 里建一个项目,和歪比的对话需要放在项目里。",
+ "vibeyUnavailable": "没能打开和歪比的对话,请稍后再试。"
}
}
diff --git a/ui/src/pet/PetPage.test.tsx b/ui/src/pet/PetPage.test.tsx
index 9a2ebc514..70f255acd 100644
--- a/ui/src/pet/PetPage.test.tsx
+++ b/ui/src/pet/PetPage.test.tsx
@@ -120,6 +120,8 @@ const api = {
setHarnessWatchEnabled: vi.fn(async () => ({ ok: true })),
setHarnessTaskEnabled: vi.fn(async () => ({ ok: true })),
getMainSession: vi.fn(() => api.getSessionResult((window as unknown as { __AVIBE_PET_BINDING__: string }).__AVIBE_PET_BINDING__)),
+ // Default: no project to put the Vibey conversation in, so an unbound pet keeps the switcher.
+ ensureDesktopMiniSession: vi.fn(async (): Promise<WorkbenchSession> => { throw new ApiError('no project', 409, 'no_chat_project'); }),
getConfig: vi.fn(async () => (setupDone
? { mode: 'self_host', setup_state: { needs_setup: false } }
: { mode: 'self_host', setup_state: { needs_setup: true } })),
@@ -231,6 +233,8 @@ beforeEach(async () => {
inboxVersion = 0;
api.getSessionResult.mockClear();
api.listSessions.mockClear();
+ api.ensureDesktopMiniSession.mockReset();
+ api.ensureDesktopMiniSession.mockImplementation(async () => { throw new ApiError('no project', 409, 'no_chat_project'); });
window.localStorage.clear();
});
@@ -315,6 +319,72 @@ describe('PetPage binding', () => {
});
});
+describe('PetPage Vibey conversation', () => {
+ it('binds the Vibey conversation the server ensures when nothing is bound', async () => {
+ api.ensureDesktopMiniSession.mockResolvedValue(session('V', { agent_name: 'vibey', agent_backend: 'vibey' }));
+ render(<PetPage />);
+ await waitFor(() => expect(devBinding().binding).toBe('V'));
+ expect(api.ensureDesktopMiniSession).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves an existing binding alone', async () => {
+ devBind('S');
+ render(<PetPage />);
+ await waitFor(() => expect(api.getSessionResult).toHaveBeenCalledWith('S'));
+ expect(api.ensureDesktopMiniSession).not.toHaveBeenCalled();
+ });
+
+ it('never re-binds a conversation that was cleared as invalid', async () => {
+ api.ensureDesktopMiniSession.mockResolvedValue(session('V'));
+ sessionReads.V = async () => ({ status: 404, session: null });
+ render(<PetPage />);
+ await waitFor(() => expect(api.getSessionResult).toHaveBeenCalledWith('V'));
+ await waitFor(() => expect(devBinding().binding).toBeNull());
+ await waitFor(() => expect(api.ensureDesktopMiniSession).toHaveBeenCalledTimes(2));
+ await act(async () => new Promise((resolve) => setTimeout(resolve, 30)));
+ expect(devBinding().binding).toBeNull();
+ expect(api.ensureDesktopMiniSession).toHaveBeenCalledTimes(2);
+ });
+
+ it('offers Vibey in the switcher, and says why when there is no project', async () => {
+ switcherSessions = [session('B', { title: 'Another session' })];
+ render(<PetPage />);
+ summon('show');
+ await userEvent.click(await screen.findByText('pet.talkToVibey'));
+ expect(await screen.findByText('pet.noChatProject')).toBeTruthy();
+ api.ensureDesktopMiniSession.mockResolvedValue(session('V'));
+ await userEvent.click(screen.getByText('pet.talkToVibey'));
+ await waitFor(() => expect(devBinding().binding).toBe('V'));
+ });
+
+ it('does not offer Vibey to someone who cannot chat', async () => {
+ canChat = false;
+ switcherSessions = [session('B', { title: 'Another session' })];
+ render(<PetPage />);
+ summon('show');
+ expect(await screen.findByText('Another session')).toBeTruthy();
+ expect(screen.queryByText('pet.talkToVibey')).toBeNull();
+ expect(api.ensureDesktopMiniSession).not.toHaveBeenCalled();
+ });
+
+ it('shows a turn the agent could not run, with the way to fix it', async () => {
+ tails.S = [
+ message('u', 'S', { author: 'user', type: 'user', text: 'hello' }),
+ message('n', 'S', {
+ type: 'notify',
+ text: 'No model source yet.',
+ metadata: { event: 'backend_failure', failure_id: 'f', turn_id: 't', failure_next_step: 'models' },
+ }),
+ ];
+ devBind('S');
+ render(<PetPage />);
+ expect(await screen.findByText('pet.failedPrefix No model source yet.')).toBeTruthy();
+ await showDetail();
+ expect(await screen.findByText('No model source yet.')).toBeTruthy();
+ expect(screen.getByText('pet.fixInAvibe')).toBeTruthy();
+ });
+});
+
describe('PetPage state', () => {
it('offers an open quick-reply group in the panel without asking for attention', async () => {
const asking = message('q', 'S', { content: { quick_replies: ['Yes', 'No'] } });
diff --git a/ui/src/pet/PetPage.tsx b/ui/src/pet/PetPage.tsx
index 299a1e9f7..5324389e3 100644
--- a/ui/src/pet/PetPage.tsx
+++ b/ui/src/pet/PetPage.tsx
@@ -19,7 +19,7 @@ import { petBridge, sessionLink, vaultRequestLink } from './petBridge';
import { petPanel, usePetPanel } from './petPanel';
import { petComposer, usePetComposer } from './petComposer';
import { petShell, useOnSummon, usePetBinding, usePetDismissed } from './petShell';
-import { derivePetPose, derivePetState, latestExchange, openQuickReplies } from './petState';
+import { derivePetPose, derivePetState, latestExchange, latestFailureNotice, openQuickReplies } from './petState';
import { useConversationAgentWorking } from './useConversationAgentWorking';
import { usePetSession, type PetSurfaceEpoch } from './usePetSession';
import { usePetSetup } from './usePetSetup';
@@ -138,7 +138,8 @@ const PetSetupPending: React.FC<{ recheck: () => void }> = ({ recheck }) => {
const PetSurface: React.FC = () => {
const { t } = useTranslation();
const api = useApi();
- const binding = usePetBinding() ?? null;
+ const rawBinding = usePetBinding();
+ const binding = rawBinding ?? null;
const { capabilities } = useInstanceAuthorization();
const inbox = useWorkbenchInbox({ feed: false });
const { expanded, setPanel } = usePetPanel();
@@ -146,6 +147,26 @@ const PetSurface: React.FC = () => {
const data = usePetSession(binding, petShell.unbind);
const epoch = data.epoch;
const canChat = capabilities.can_chat && data.canChat === true;
+ // Interim main-agent rule (spec §10.1): with nothing bound, the mini binds the
+ // caller's Vibey conversation, which the server creates on first use. A session
+ // it already handed out is never re-bound once it was cleared as invalid, so a
+ // bad answer cannot turn into a bind/clear loop.
+ const ensured = useRef<{ generation: number; ids: Set<string>; inFlight: boolean }>({ generation: -1, ids: new Set(), inFlight: false });
+ useEffect(() => {
+ if (rawBinding !== null || !capabilities.can_chat) return;
+ const state = ensured.current;
+ if (state.generation !== epoch.authorizationGeneration) {
+ ensured.current = { generation: epoch.authorizationGeneration, ids: new Set(), inFlight: false };
+ }
+ if (ensured.current.inFlight) return;
+ const current = ensured.current;
+ current.inFlight = true;
+ void api.ensureDesktopMiniSession().then((session) => {
+ if (!epoch.isCurrent() || current.ids.has(session.id)) return;
+ current.ids.add(session.id);
+ petShell.pick(session.id, epoch.isAuthorizationCurrent);
+ }, () => undefined).finally(() => { current.inFlight = false; });
+ }, [rawBinding, capabilities.can_chat, api, epoch]);
const { requests: vaultRequests } = usePendingVaultRequests(binding ?? '');
const unreadCount = binding ? inbox.unreadBySession[binding] ?? 0 : 0;
const state = derivePetState({
@@ -155,6 +176,7 @@ const PetSurface: React.FC = () => {
unreadCount,
});
const exchange = useMemo(() => latestExchange(data.messages, data.hasOlder, unreadCount), [data.messages, data.hasOlder, unreadCount]);
+ const failure = useMemo(() => latestFailureNotice(data.messages), [data.messages]);
const quickReplies = openQuickReplies(data.messages);
const activeActivities = data.turn?.background_activities ?? EMPTY_ACTIVITIES;
const activeSubtasks = activeActivities.filter(isRunning);
@@ -216,15 +238,17 @@ const PetSurface: React.FC = () => {
const mainCard = useMemo<PetCard | null>(() => {
const user = exchange.user;
const latest = exchange.results.at(-1);
- if (!user && !latest && !optimisticTitle && !(uncertain && draft.trim())) return null;
+ if (!user && !latest && !failure && !optimisticTitle && !(uncertain && draft.trim())) return null;
const title = optimisticTitle || (uncertain ? draft.trim() : '') || user?.text?.trim() || t('pet.mainAgentTitle');
const subtitle = data.running
? t('pet.thinking')
- : latest?.text?.trim()
+ : failure
+ ? `${t('pet.failedPrefix')} ${failure.text.trim()}`
+ : latest?.text?.trim()
? `${t('pet.repliedPrefix')} ${latest.text.trim()}`
: t('pet.waiting');
return { id: 'main-agent', title, kind: 'backend_activity', status: subtitle, running: data.running, canPause: false, main: true };
- }, [data.running, exchange.results, exchange.user, optimisticTitle, uncertain, draft, t]);
+ }, [data.running, exchange.results, exchange.user, failure, optimisticTitle, uncertain, draft, t]);
useEffect(() => {
if (exchange.user?.text?.trim() === optimisticTitle) setOptimisticTitle('');
}, [exchange.user, optimisticTitle]);
@@ -515,7 +539,7 @@ const PetSurface: React.FC = () => {
<div className={clsx('pet-mini-cards', voice.listening && 'is-hidden')} inert={voice.listening || undefined} aria-label={expanded ? t('pet.panel') : undefined} style={{ height: expanded ? STACK_HEIGHT : collapsedHeight }}>
<div ref={collapsedRef} key={expanded ? 'expanded' : 'collapsed'} className="pet-mini-swap is-switching" onAnimationEnd={(event) => { if (event.target === event.currentTarget) event.currentTarget.classList.remove('is-switching'); }}>
{expanded && (!binding || switcherOpen || visibleCards.length === 0) ? (
- <SessionPicker onPick={(sessionId) => {
+ <SessionPicker canStartVibey={capabilities.can_chat} onPick={(sessionId) => {
if (!epoch.isCurrent()) return;
petShell.pick(sessionId, epoch.isAuthorizationCurrent);
setSwitcherOpen(false);
@@ -532,7 +556,7 @@ const PetSurface: React.FC = () => {
stops={stops}
onStop={setStop}
t={(key, options) => String(t(key as never, options as never))}
- detail={binding ? <MainDetail epoch={epoch} voiceNeedsCloud={voice.cloudRequired} canChat={canChat} visible={detailOpen && !voice.listening} onSwitch={() => setSwitcherOpen(true)} binding={binding} exchange={exchange} running={data.running} queued={(data.turn?.pending_input_count ?? 0) > 0} markRead={inbox.markRead} onRead={data.refreshTail} vaultRequestIds={vaultRequests.map((request) => request.id)} quickReplies={quickReplies} onChoose={choose} uncertain={uncertain} onInspect={() => { void petBridge.open(sessionLink(binding)).then(() => { if (epoch.isCurrent()) setUncertain(binding, false); }).catch(() => undefined); }} /> : null}
+ detail={binding ? <MainDetail epoch={epoch} voiceNeedsCloud={voice.cloudRequired} canChat={canChat} visible={detailOpen && !voice.listening} onSwitch={() => setSwitcherOpen(true)} binding={binding} exchange={exchange} failure={data.running ? null : failure} running={data.running} queued={(data.turn?.pending_input_count ?? 0) > 0} markRead={inbox.markRead} onRead={data.refreshTail} vaultRequestIds={vaultRequests.map((request) => request.id)} quickReplies={quickReplies} onChoose={choose} uncertain={uncertain} onInspect={() => { void petBridge.open(sessionLink(binding)).then(() => { if (epoch.isCurrent()) setUncertain(binding, false); }).catch(() => undefined); }} /> : null}
/>
) : (
<CollapsedCards cards={visibleCards} onOpen={() => void setPanel(true)} t={(key) => String(t(key as never))} />
@@ -568,13 +592,33 @@ const PetSurface: React.FC = () => {
);
};
-const SessionPicker: React.FC<{ onPick: (sessionId: string) => void }> = ({ onPick }) => {
+const SessionPicker: React.FC<{ onPick: (sessionId: string) => void; canStartVibey: boolean }> = ({ onPick, canStartVibey }) => {
const { t } = useTranslation();
+ const api = useApi();
const { sessions, loading } = useSessionSwitcher(true);
+ const [vibeyError, setVibeyError] = useState<string | null>(null);
+ const [vibeyPending, setVibeyPending] = useState(false);
+ const mounted = useRef(true);
+ useEffect(() => {
+ mounted.current = true;
+ return () => { mounted.current = false; };
+ }, []);
+ const pickVibey = () => {
+ if (vibeyPending) return;
+ setVibeyPending(true);
+ setVibeyError(null);
+ api.ensureDesktopMiniSession().then((session) => {
+ if (mounted.current) onPick(session.id);
+ }, (error: unknown) => {
+ if (mounted.current) setVibeyError(error instanceof ApiError && error.code === 'no_chat_project' ? t('pet.noChatProject') : t('pet.vibeyUnavailable'));
+ }).finally(() => { if (mounted.current) setVibeyPending(false); });
+ };
return (
<div className="pet-mini-panel" aria-label={t('pet.chooseSession')}>
<div className="pet-mini-scroll">
<div className="pet-mini-session-picker" data-pet-hit>
+ {canStartVibey && <button type="button" onClick={pickVibey} disabled={vibeyPending} className="pet-mini-session-option">{t('pet.talkToVibey')}</button>}
+ {vibeyError && <p className="pet-mini-detail-muted">{vibeyError}</p>}
{sessions.length === 0 && <p className="pet-mini-detail-muted">{loading ? t('common.loading') : t('pet.noSessions')}</p>}
{sessions.map((session) => (
<button key={session.id} type="button" onClick={() => onPick(session.id)} className="pet-mini-session-option">
@@ -844,7 +888,7 @@ const CardBody: React.FC<{ card: PetCard; expanded: boolean; t: (key: string, op
);
};
-const MainDetail: React.FC<{ epoch: PetSurfaceEpoch; voiceNeedsCloud: boolean; canChat: boolean; visible: boolean; onSwitch: () => void; binding: string; exchange: ReturnType<typeof latestExchange>; running: boolean; queued: boolean; markRead: (sessionId: string, untilMessageId?: string) => Promise<boolean>; onRead: () => void; vaultRequestIds: string[]; quickReplies: ReturnType<typeof openQuickReplies>; onChoose: (message: WorkbenchMessage, choice: string) => Promise<boolean>; uncertain: boolean; onInspect: () => void }> = (props) => {
+const MainDetail: React.FC<{ epoch: PetSurfaceEpoch; voiceNeedsCloud: boolean; canChat: boolean; visible: boolean; onSwitch: () => void; binding: string; exchange: ReturnType<typeof latestExchange>; failure: WorkbenchMessage | null; running: boolean; queued: boolean; markRead: (sessionId: string, untilMessageId?: string) => Promise<boolean>; onRead: () => void; vaultRequestIds: string[]; quickReplies: ReturnType<typeof openQuickReplies>; onChoose: (message: WorkbenchMessage, choice: string) => Promise<boolean>; uncertain: boolean; onInspect: () => void }> = (props) => {
const { t } = useTranslation();
const lastResultRef = useRef<HTMLDivElement>(null);
const resultKey = `${props.binding}\u0000${props.exchange.results.at(-1)?.id ?? ''}`;
@@ -867,6 +911,12 @@ const MainDetail: React.FC<{ epoch: PetSurfaceEpoch; voiceNeedsCloud: boolean; c
<Button variant="link" size="sm" aria-label={t('pet.switchSession')} onClick={props.onSwitch}>{t('pet.switchSession')}</Button>
{props.exchange.user && <div className="pet-mini-detail-user"><Markdown content={props.exchange.user.text} softBreaks /></div>}
{props.exchange.results.map((message, index) => <div ref={index === props.exchange.results.length - 1 ? lastResultRef : undefined} key={message.id} className="pet-mini-detail-result"><Markdown content={message.text} softBreaks /></div>)}
+ {props.failure && (
+ <div className="pet-mini-detail-notice" role="status">
+ <p>{props.failure.text}</p>
+ {props.failure.metadata?.failure_next_step === 'models' && <Button variant="link" size="sm" className="px-0" onClick={() => void petBridge.open(sessionLink(props.binding))}>{t('pet.fixInAvibe')}</Button>}
+ </div>
+ )}
{props.running && <p className="pet-mini-detail-muted">{t('pet.thinking')}</p>}
{props.voiceNeedsCloud && <p className="pet-mini-detail-muted">{t('pet.voice.cloudRequired')}</p>}
{props.queued && <p className="pet-mini-detail-muted">{t('pet.queued')}</p>}
diff --git a/ui/src/pet/petPanel.test.tsx b/ui/src/pet/petPanel.test.tsx
index 8ecec647d..3bd40b369 100644
--- a/ui/src/pet/petPanel.test.tsx
+++ b/ui/src/pet/petPanel.test.tsx
@@ -12,6 +12,7 @@ vi.mock('react-i18next', () => ({
const api = {
getConfig: vi.fn(async () => ({ mode: 'self_host', setup_state: { needs_setup: true } })),
getMainSession: vi.fn(async () => ({ status: 200, session: null })),
+ ensureDesktopMiniSession: vi.fn(async () => { throw new Error('no project'); }),
listSessionMessages: vi.fn(async () => ({ messages: [], next_after_id: null, next_before_id: null })),
getTurnState: vi.fn(async () => ({
in_flight: false, foreground: 'idle', native_turn_started: false,
diff --git a/ui/src/pet/petState.test.ts b/ui/src/pet/petState.test.ts
index 95a79b218..e78ea1fe0 100644
--- a/ui/src/pet/petState.test.ts
+++ b/ui/src/pet/petState.test.ts
@@ -7,6 +7,7 @@ import {
derivePetPose,
derivePetState,
latestExchange,
+ latestFailureNotice,
openQuickReplies,
type PetState,
type PetStateInputs,
@@ -202,3 +203,34 @@ describe('derivePetPose', () => {
expect(derivePetPose('idle', { othersWorking: false, asleep: false })).toBe('idle');
});
});
+
+describe('latestFailureNotice', () => {
+ const failure = () => row({ type: 'notify', metadata: { event: 'backend_failure', failure_id: 'f', turn_id: 't' } });
+
+ it('is the failure that ended the latest exchange', () => {
+ const notice = failure();
+ expect(latestFailureNotice([user(), notice])).toBe(notice);
+ });
+
+ it('is cleared by a later result or a new user message', () => {
+ expect(latestFailureNotice([user(), failure(), result()])).toBeNull();
+ expect(latestFailureNotice([user(), failure(), user('retry')])).toBeNull();
+ });
+
+ it('ignores detached or replayed failures, which report work outside this exchange', () => {
+ const detached = row({ type: 'notify', metadata: { event: 'backend_failure', failure_id: 'f', turn_id: 't', detached: true } });
+ const replayed = row({ type: 'notify', metadata: { event: 'backend_failure', failure_id: 'f', turn_id: 't', replayed: true } });
+ expect(latestFailureNotice([user(), detached])).toBeNull();
+ expect(latestFailureNotice([user(), replayed])).toBeNull();
+ });
+
+ it('is not hidden by a detached result from background work', () => {
+ const notice = failure();
+ const detachedResult = result({ metadata: { detached: true } });
+ expect(latestFailureNotice([user(), notice, detachedResult])).toBe(notice);
+ });
+
+ it('ignores notices that are not backend failures', () => {
+ expect(latestFailureNotice([user(), row({ type: 'notify', metadata: {} })])).toBeNull();
+ });
+});
diff --git a/ui/src/pet/petState.ts b/ui/src/pet/petState.ts
index 5265f7863..784f65ec5 100644
--- a/ui/src/pet/petState.ts
+++ b/ui/src/pet/petState.ts
@@ -4,7 +4,7 @@ import type {
WorkbenchMessage,
WorkbenchSession,
} from '@/context/ApiContext';
-import { isTranscriptMessage } from '@/lib/chatMessageTypes';
+import { isBackendFailureNotice, isTerminalAgentMessage, isTranscriptMessage } from '@/lib/chatMessageTypes';
import { specFor } from '@/lib/messageTypes';
import type { PetPose } from './PetAvatar';
@@ -45,6 +45,22 @@ const isAgentResult = (message: WorkbenchMessage): boolean =>
const isUserInput = (message: WorkbenchMessage): boolean =>
message.author === 'user' && specFor(message.type).inputAuthors.includes('user');
+/**
+ * The backend failure notice that ended the latest exchange, or null: a notice
+ * after the last user input with no result since. A turn the agent could not run
+ * (Vibey with no model source, say) ends with one of these instead of a result.
+ */
+export const latestFailureNotice = (messages: WorkbenchMessage[]): WorkbenchMessage | null => {
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
+ const message = messages[index];
+ if (isUserInput(message)) return null;
+ // The foreground exchange ends at its terminal row, by the transcript's own rule:
+ // detached completions and replayed failures report work outside it and are skipped.
+ if (isTerminalAgentMessage(message)) return isBackendFailureNotice(message) ? message : null;
+ }
+ return null;
+};
+
/** The latest agent result in the tail, or null. */
export const latestAgentResult = (messages: WorkbenchMessage[]): WorkbenchMessage | null => {
for (let index = messages.length - 1; index >= 0; index -= 1) {
diff --git a/vibe/authorization.py b/vibe/authorization.py
index 757582fbe..0231f1eef 100644
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@ -671,6 +671,7 @@ _EDITOR_HTTP_RULES = tuple(
("GET", r"^/api/asr/status$"),
("GET", r"^/api/sessions/[^/]+/(?:archive-preview|queue|draft)$"),
("POST", r"^/api/sessions$"),
+ ("POST", r"^/api/desktop-mini/session$"),
("POST", r"^/api/sessions/[^/]+/cli-activity$"),
("POST", r"^/api/sessions/[^/]+/fork$"),
("PATCH", r"^/api/sessions/[^/]+$"),
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index b10cc4f8f..3e8d21390 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -1711,5 +1711,10 @@
"internal": "{backend} stopped because of an internal error. Try again; if it happens again, the service log names the cause.",
"generic": "{backend}'s run failed."
}
+ },
+ "desktopMini": {
+ "sessionTitle": "Vibey · Desktop mini",
+ "noChatProject": "Create a project in Avibe first, so the desktop mini has a place for its conversation.",
+ "builtinAgentUnavailable": "The built-in Agent is not available, so the desktop mini has no one to talk to."
}
}
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index b9508dfb1..dfcf2c632 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -1711,5 +1711,10 @@
"internal": "{backend} 因内部错误而停止。可以重试;如果再次出现,服务日志里记录了原因。",
"generic": "{backend} 运行失败。"
}
+ },
+ "desktopMini": {
+ "sessionTitle": "歪比 · 桌宠",
+ "noChatProject": "先在 Avibe 里建一个项目,桌宠的对话需要放在项目里。",
+ "builtinAgentUnavailable": "内置 Agent 当前不可用,桌宠暂时没有对话对象。"
}
}
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index be08f416f..586a48d63 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -9421,6 +9421,45 @@ def sessions_create():
return jsonify(session), 201
[email protected]("/api/desktop-mini/session", methods=["POST"])
+def desktop_mini_session_ensure():
+ """The caller's desktop mini conversation with the built-in Agent, created on first use.
+
+ Interim rule until sessions get a built-in ``main`` type: see
+ docs/plans/2026-10-12-desktop-mini-main-agent.md §10.1.
+ """
+ from core.services import sessions as workbench_sessions_service
+ from core.vibe_agents import VibeAgentAccessError, VibeAgentStore
+ from storage.workbench_sessions_service import NoChatProjectError, ensure_desktop_mini_session
+ from vibe.sse_broker import broker
+
+ store = VibeAgentStore()
+ try:
+ vibey = store.get_builtin_default_agent_for_backend("vibey")
+ finally:
+ store.close()
+ lang = _request_ui_language()
+ if vibey is None:
+ return _coded_error_response("builtin_agent_unavailable", t("desktopMini.builtinAgentUnavailable", lang), 409)
+ authorization_context = getattr(g, "authorization_context", None)
+ engine = _projects_engine()
+ try:
+ with engine.begin() as conn:
+ session = ensure_desktop_mini_session(
+ conn,
+ agent_name=vibey.name,
+ title=t("desktopMini.sessionTitle", lang),
+ authorization_context=authorization_context,
+ )
+ can_chat = _session_can_chat(conn, authorization_context, session["id"])
+ except NoChatProjectError:
+ return _coded_error_response(NoChatProjectError.code, t("desktopMini.noChatProject", lang), 409)
+ except (VibeAgentAccessError, workbench_sessions_service.ProjectAccessDeniedError):
+ return _coded_error_response("project_access_denied", t("error.projectAccessDenied", lang), 403)
+ broker.publish("session.activity", {"session_id": session["id"], "scope_id": session["scope_id"], "event": "created"})
+ return jsonify({**session, "capabilities": {"can_chat": can_chat}})
+
+
def _session_fork_error_response(err: Exception):
"""Map a ``SessionForkError`` to its machine code, in the STRUCTURED body.