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-mini): 增加稳定主会话接口 (#2637)

Max2e71e68d1e98
diff --git a/core/controller.py b/core/controller.py
index 19d99f337..a0380552a 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -1687,6 +1687,7 @@ class Controller:
from core.services import sessions as workbench_sessions_service
from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID
from storage.db import create_sqlite_engine
+ from storage.workbench_sessions_service import MAIN_SESSION_ID
if (
not isinstance(raw_session_id, str)
@@ -1694,7 +1695,10 @@ class Controller:
or raw_session_id != raw_session_id.strip()
):
raise ValueError("invalid Workbench session ID")
- if raw_session_id == WORKSPACE_NOTICE_SESSION_ID:
+ if raw_session_id in {
+ WORKSPACE_NOTICE_SESSION_ID,
+ MAIN_SESSION_ID,
+ }:
raise workbench_sessions_service.ReservedSessionError(raw_session_id)
async def retire_computer_use_session() -> None:
diff --git a/docs/plans/2026-10-15-desktop-mini-main-session-mvp.md b/docs/plans/2026-10-15-desktop-mini-main-session-mvp.md
new file mode 100644
index 000000000..face8c700
--- /dev/null
+++ b/docs/plans/2026-10-15-desktop-mini-main-session-mvp.md
@@ -0,0 +1,21 @@
+# Desktop Mini Main Session MVP
+
+## Change Contract
+
+- **Intent:** Make the desktop mini resolve one stable built-in Vibey session through `GET /api/sessions/main`.
+- **Backend boundary:** Resolve or recreate `ses_main` under the SQLite writer lock. The row has `scope_id=NULL`, `metadata.kind=main`, the built-in Vibey Agent, and a principal-safe `~/.avibe/main/<principal>/` workdir created on first use. Return `can_chat=true` for an authorized caller even without a Project.
+- **Frontend boundary:** `ApiContext.getMainSession()` calls the new endpoint. `PetPage` uses that result to bind the main session on startup and through its Vibey switcher path, while existing bindings continue to validate through `getSessionResult(session_id)`.
+- **Compatibility:** Keep `POST /api/desktop-mini/session` unchanged. Preserve existing standalone session behavior by using the new explicit `workdir` only for the main-session path.
+- **Validation contract:** Cover first create, reuse, row recreation, non-Show-Page workdir, no-Project creation, and the frontend request path. Run focused pytest, changed-file Ruff, and `ui` build.
+- **Out of scope:** Permissions, Inbox, Show Page, IM, native desktop code, context rotation, and migration of old desktop-mini bindings.
+
+## Repair Contract
+
+- Keep the fixed `ses_main` identity and serve only the instance Owner. Do not add
+ principal-to-session mapping or editor access for standalone main sessions in this slice.
+- Validate every built-in invariant before reusing an existing row. A corrupted row
+ returns a coded conflict instead of being silently repaired.
+- Treat an archived `ses_main` row as terminal. Normal archive and update paths refuse
+ the reserved ID, and the main-session endpoint never reactivates an archived row.
+- Prepare the main workdir before reserving the SQLite writer lock. Ordinary standalone
+ sessions keep their existing Show Page workdir behavior.
diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.py
index 86f0be523..70a689c6d 100644
--- a/storage/workbench_sessions_service.py
+++ b/storage/workbench_sessions_service.py
@@ -36,6 +36,7 @@ from storage.agent_session_rows import (
WORKSPACE_NOTICE_SESSION_ID,
create_agent_session_row,
new_session_id,
+ normalize_workdir,
normalize_session_project_base,
reserve_write_lock,
snapshot_scope_workdir,
@@ -448,6 +449,7 @@ def create_session(
conn: Connection,
*,
scope_id: Optional[str],
+ session_id: Optional[str] = None,
agent_backend: str,
agent_name: Optional[str] = None,
agent_id: Optional[str] = None,
@@ -455,10 +457,12 @@ def create_session(
model: Optional[str] = None,
reasoning_effort: Optional[str] = None,
title: Optional[str] = None,
+ workdir: Optional[str] = None,
visibility: str = "foreground",
metadata: Optional[dict[str, Any]] = None,
authorization_context: AuthorizationContext | Mapping[str, Any] | None = None,
user_context: Any = None,
+ workdir_prepared: bool = False,
) -> dict[str, Any]:
"""Create a session in a Scope or as a standalone session.
@@ -611,11 +615,14 @@ def create_session(
if metadata:
metadata_payload.update(metadata)
- session_id = new_session_id(conn)
- workdir = scope_row.get("workdir") or os.getcwd()
+ session_id = str(session_id or new_session_id(conn))
if scope_id is None:
- workdir = str(paths.get_show_page_dir(session_id))
- Path(workdir).mkdir(parents=True, exist_ok=True)
+ provided_workdir = normalize_workdir(workdir)
+ workdir = provided_workdir or str(paths.get_show_page_dir(session_id))
+ if provided_workdir is None or not workdir_prepared:
+ Path(workdir).mkdir(parents=True, exist_ok=True)
+ else:
+ workdir = scope_row.get("workdir") or os.getcwd()
create_agent_session_row(
conn,
session_id=session_id,
@@ -637,11 +644,138 @@ 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.
+MAIN_SESSION_ID = "ses_main"
+MAIN_SESSION_METADATA_KEY = "kind"
+MAIN_SESSION_METADATA_VALUE = "main"
+MAIN_SESSION_WORKDIR_DIRNAME = "main"
+MAIN_SESSION_WORKDIR_COMPONENT = "owner"
+MAIN_SESSION_UPDATABLE_FIELDS = frozenset({"model", "reasoning_effort", "title", "pinned"})
+
+
+class MainSessionArchivedError(PermissionError):
+ """Raised when the fixed main-session row is already archived."""
+
+ code = "main_session_archived"
+
+ def __init__(self) -> None:
+ super().__init__(self.code)
+
+
+class MainSessionInvariantError(RuntimeError):
+ """Raised when the fixed main-session row no longer has its built-in shape."""
+
+ code = "main_session_invalid"
+
+ def __init__(self, reason: str) -> None:
+ self.reason = str(reason)
+ super().__init__(self.code)
+
+
+def main_session_workdir() -> str:
+ """Return the fixed singleton main-session workdir."""
+
+ return str(paths.get_vibe_remote_dir() / MAIN_SESSION_WORKDIR_DIRNAME / MAIN_SESSION_WORKDIR_COMPONENT)
+
+
+def _main_builtin_agent(conn: Connection, agent_name: str) -> dict[str, Any]:
+ from core.vibe_agents import VibeAgentStore, is_builtin_default_agent
+
+ row = conn.execute(
+ select(agents)
+ .where(
+ agents.c.name == str(agent_name or "").strip(),
+ agents.c.backend == "vibey",
+ agents.c.enabled == 1,
+ agents.c.archived_at.is_(None),
+ agents.c.source == "builtin",
+ )
+ .limit(1)
+ ).mappings().first()
+ if row is None or not is_builtin_default_agent(VibeAgentStore._from_row(row)):
+ raise MainSessionInvariantError("built-in Vibey Agent is unavailable")
+ return dict(row)
+
+
+def _validate_main_session_row(
+ row: Mapping[str, Any],
+ *,
+ agent: Mapping[str, Any],
+ workdir: str,
+) -> None:
+ if row.get("status") == "archived":
+ raise MainSessionArchivedError()
+ metadata = _load_metadata(row.get("metadata_json"))
+ expected = {
+ "id": MAIN_SESSION_ID,
+ "scope_id": None,
+ "agent_id": agent["id"],
+ "agent_name": agent["name"],
+ "agent_backend": "vibey",
+ "agent_variant": "vibey",
+ "session_anchor": MAIN_SESSION_ID,
+ "workdir": workdir,
+ "status": "active",
+ "visibility": "foreground",
+ }
+ for field, value in expected.items():
+ if row.get(field) != value:
+ raise MainSessionInvariantError(f"{field} does not match the built-in main session")
+ if metadata.get(MAIN_SESSION_METADATA_KEY) != MAIN_SESSION_METADATA_VALUE:
+ raise MainSessionInvariantError("metadata.kind does not identify the main session")
+
+
+def ensure_main_session(
+ conn: Connection,
+ *,
+ agent_name: str,
+ title: Optional[str] = None,
+ authorization_context: AuthorizationContext | Mapping[str, Any] | None = None,
+) -> dict[str, Any]:
+ """Resolve the stable built-in main session, creating it on first use."""
+
+ context = require_instance_role(authorization_context, "owner")
+ if desktop_mini_owner_key(context) is None:
+ raise ProjectAccessDeniedError
+ workdir = main_session_workdir()
+ row = conn.execute(
+ select(agent_sessions).where(agent_sessions.c.id == MAIN_SESSION_ID)
+ ).mappings().first()
+ if row is not None and row.get("status") == "archived":
+ raise MainSessionArchivedError()
+ builtin_agent = _main_builtin_agent(conn, agent_name)
+ if row is not None:
+ _validate_main_session_row(row, agent=builtin_agent, workdir=workdir)
+ return get_session(conn, MAIN_SESSION_ID, authorization_context=context)
+
+ Path(workdir).mkdir(parents=True, exist_ok=True)
+ # The fixed primary key makes deletion idempotent, while the write lock closes
+ # the read/insert race when two first turns arrive together.
+ reserve_write_lock(conn)
+ row = conn.execute(
+ select(agent_sessions).where(agent_sessions.c.id == MAIN_SESSION_ID)
+ ).mappings().first()
+ if row is not None:
+ _validate_main_session_row(row, agent=builtin_agent, workdir=workdir)
+ return get_session(conn, MAIN_SESSION_ID, authorization_context=context)
+
+ return create_session(
+ conn,
+ scope_id=None,
+ session_id=MAIN_SESSION_ID,
+ agent_backend="",
+ agent_name=agent_name,
+ title=title,
+ workdir=workdir,
+ metadata={MAIN_SESSION_METADATA_KEY: MAIN_SESSION_METADATA_VALUE},
+ authorization_context=context,
+ workdir_prepared=True,
+ )
+
+
+# Legacy desktop mini conversation support. 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:"
@@ -868,13 +1002,37 @@ def update_session(
machine-owned chat in every user's session list — and also ``scope_id``, which would
mint a fake project row and put the session inside a scoped clear's reach. Each of
those is silent until the next notice's heal, so an ack could be earned against a
- surface showing nothing in between.
+ surface showing nothing in between. The fixed main session has a narrower exception:
+ its title, model, reasoning effort and pin state remain user-editable, while identity,
+ placement and lifecycle fields stay reserved.
``system`` itself is not assignable in the other direction either: see the
``visibility`` branch below.
"""
- authorization = require_instance_role(authorization_context, "editor")
- if str(session_id) == WORKSPACE_NOTICE_SESSION_ID:
+ is_main_session = str(session_id) == MAIN_SESSION_ID
+ authorization = require_instance_role(
+ authorization_context,
+ "owner" if is_main_session else "editor",
+ )
+ requested_fields = {
+ name
+ for name, value in (
+ ("title", title),
+ ("agent_id", agent_id),
+ ("agent_name", agent_name),
+ ("agent_backend", agent_backend),
+ ("agent_variant", agent_variant),
+ ("model", model),
+ ("reasoning_effort", reasoning_effort),
+ ("visibility", visibility),
+ ("pinned", pinned),
+ ("scope_id", scope_id),
+ )
+ if value is not _UNSET
+ }
+ if str(session_id) == WORKSPACE_NOTICE_SESSION_ID or (
+ is_main_session and not requested_fields.issubset(MAIN_SESSION_UPDATABLE_FIELDS)
+ ):
raise ReservedSessionError(str(session_id))
reserve_write_lock(conn)
existing = conn.execute(
@@ -1657,7 +1815,7 @@ def archive_session(
Checked BEFORE the existence lookup so the answer is the same on every install,
whether or not the lazily-created row exists yet.
"""
- if str(session_id) == WORKSPACE_NOTICE_SESSION_ID:
+ if str(session_id) in {WORKSPACE_NOTICE_SESSION_ID, MAIN_SESSION_ID}:
raise ReservedSessionError(str(session_id))
context = require_instance_role(authorization_context, "editor")
existing = conn.execute(
diff --git a/tests/fixtures/member_management_existing_read_roles.json b/tests/fixtures/member_management_existing_read_roles.json
index ceb9fd37c..76fb1554f 100644
--- a/tests/fixtures/member_management_existing_read_roles.json
+++ b/tests/fixtures/member_management_existing_read_roles.json
@@ -55,6 +55,7 @@
"GET /api/sessions/example/messages": "viewer",
"GET /api/sessions/example/queue": "editor",
"GET /api/sessions/example/turn-state": "viewer",
+ "GET /api/sessions/main": "viewer",
"GET /api/show-pages": "viewer",
"GET /api/show-pages/example": "editor",
"GET /api/show-pages/example/access": "viewer",
diff --git a/tests/test_desktop_mini_session.py b/tests/test_desktop_mini_session.py
index 23a8e46cc..3f0a05e1b 100644
--- a/tests/test_desktop_mini_session.py
+++ b/tests/test_desktop_mini_session.py
@@ -1,11 +1,9 @@
-"""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).
-"""
+"""The desktop mini's legacy and stable main-session contracts."""
from __future__ import annotations
+from pathlib import Path
+
import pytest
from storage.importer import ensure_sqlite_state
@@ -60,6 +58,19 @@ def _ensure(principal: str, agent_name: str):
)
+def _ensure_main(principal: str, agent_name: str):
+ from storage.db import create_sqlite_engine
+ from storage.workbench_sessions_service import ensure_main_session
+
+ with create_sqlite_engine().begin() as conn:
+ return ensure_main_session(
+ conn,
+ agent_name=agent_name,
+ title="Vibey",
+ authorization_context=_context(principal),
+ )
+
+
def _touch(project_id: str, when: str) -> None:
from sqlalchemy import update
@@ -139,6 +150,206 @@ def test_route_explains_a_missing_project(state):
assert response.get_json()["error"]["code"] == "no_chat_project"
+def test_main_session_is_created_reused_and_recreated_without_a_project(state):
+ from sqlalchemy import delete
+
+ from config import paths
+ from storage.db import create_sqlite_engine
+ from storage.models import agent_sessions
+ from storage.workbench_sessions_service import MAIN_SESSION_ID
+
+ tmp_path, vibey = state
+ first = _ensure_main("local", vibey.name)
+ assert first["id"] == MAIN_SESSION_ID
+ assert first["scope_id"] is None
+ assert first["agent_name"] == vibey.name
+ assert first["agent_backend"] == "vibey"
+ assert first["metadata"]["kind"] == "main"
+ expected_workdir = str(paths.get_vibe_remote_dir() / "main" / "owner")
+ assert first["workdir"] == expected_workdir
+ assert (tmp_path / "main" / "owner").is_dir()
+ assert _ensure_main("local", vibey.name)["id"] == first["id"]
+ remote = _ensure_main("remote:3c6111ab", vibey.name)
+ assert remote["id"] == first["id"]
+ assert remote["workdir"] == expected_workdir
+
+ with create_sqlite_engine().begin() as conn:
+ conn.execute(delete(agent_sessions).where(agent_sessions.c.id == MAIN_SESSION_ID))
+ rebuilt = _ensure_main("local", vibey.name)
+ assert rebuilt["id"] == MAIN_SESSION_ID
+ assert rebuilt["workdir"] == first["workdir"]
+
+
+ ("field", "value"),
+ [
+ ("scope_id", "avibe::project::proj_invalid"),
+ ("agent_id", "agent_invalid"),
+ ("agent_name", "agent_invalid"),
+ ("agent_backend", "claude"),
+ ("agent_variant", "claude"),
+ ("session_anchor", "ses_other"),
+ ("workdir", "/tmp/not-the-main-workdir"),
+ ("visibility", "background"),
+ ("metadata_json", '{"kind":"other"}'),
+ ],
+)
+def test_existing_main_session_must_keep_all_built_in_invariants(state, field, value):
+ from sqlalchemy import update
+
+ from storage.db import create_sqlite_engine
+ from storage.models import agent_sessions
+ from storage.workbench_sessions_service import MainSessionInvariantError
+
+ tmp_path, vibey = state
+ first = _ensure_main("local", vibey.name)
+ if field == "scope_id":
+ value = _project(tmp_path, "invariant-scope")["scope_id"]
+ with create_sqlite_engine().begin() as conn:
+ conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == first["id"])
+ .values(**{field: value})
+ )
+
+ with pytest.raises(MainSessionInvariantError) as exc:
+ _ensure_main("local", vibey.name)
+ assert exc.value.code == "main_session_invalid"
+
+
+def test_archived_main_session_is_terminal_and_cannot_be_reopened(state):
+ from sqlalchemy import select, update
+
+ from core.services import sessions as workbench_sessions_service
+ from storage.db import create_sqlite_engine
+ from storage.models import agent_sessions
+ from storage.workbench_sessions_service import MainSessionArchivedError
+
+ _tmp_path, vibey = state
+ first = _ensure_main("local", vibey.name)
+ with create_sqlite_engine().begin() as conn:
+ with pytest.raises(workbench_sessions_service.ReservedSessionError):
+ workbench_sessions_service.update_session(
+ conn,
+ first["id"],
+ visibility="background",
+ )
+
+ with create_sqlite_engine().begin() as conn:
+ conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == first["id"])
+ .values(status="archived")
+ )
+
+ with pytest.raises(MainSessionArchivedError):
+ _ensure_main("local", vibey.name)
+ with create_sqlite_engine().connect() as conn:
+ assert conn.execute(
+ select(agent_sessions.c.status).where(agent_sessions.c.id == first["id"])
+ ).scalar_one() == "archived"
+
+ response = app.test_client().get("/api/sessions/main")
+ assert response.status_code == 409
+ assert response.get_json()["error"]["code"] == "main_session_archived"
+
+ with create_sqlite_engine().begin() as conn:
+ with pytest.raises(workbench_sessions_service.ReservedSessionError):
+ workbench_sessions_service.archive_session(conn, first["id"])
+
+
+def test_main_session_is_owner_only(state):
+ from vibe.authorization import AuthorizationContext, InstanceAuthorizationError
+ from storage.db import create_sqlite_engine
+ from storage.workbench_sessions_service import ensure_main_session
+
+ _tmp_path, vibey = state
+ with create_sqlite_engine().begin() as conn:
+ with pytest.raises(InstanceAuthorizationError):
+ ensure_main_session(
+ conn,
+ agent_name=vibey.name,
+ authorization_context=AuthorizationContext(
+ instance_role="editor",
+ is_remote=True,
+ subject="member",
+ ),
+ )
+
+
+ ("field", "value"),
+ [
+ ("model", "vibey-model"),
+ ("reasoning_effort", "high"),
+ ("title", "Renamed main"),
+ ("pinned", True),
+ ],
+)
+def test_main_session_allows_user_settings_updates(state, field, value):
+ from storage.workbench_sessions_service import MAIN_SESSION_ID
+
+ _tmp_path, vibey = state
+ _ensure_main("local", vibey.name)
+ client = app.test_client()
+ response = client.patch(
+ f"/api/sessions/{MAIN_SESSION_ID}",
+ json={field: value},
+ headers=csrf_headers(client),
+ )
+ assert response.status_code == 200, response.get_json()
+ assert response.get_json()[field] == value
+
+
+def test_main_session_rejects_protected_patch_fields_with_403(state):
+ from storage.workbench_sessions_service import MAIN_SESSION_ID
+
+ _tmp_path, vibey = state
+ _ensure_main("local", vibey.name)
+ client = app.test_client()
+ response = client.patch(
+ f"/api/sessions/{MAIN_SESSION_ID}",
+ json={"visibility": "background"},
+ headers=csrf_headers(client),
+ )
+ assert response.status_code == 403
+ assert response.get_json()["error"]["code"] == "reserved_session"
+
+
+def test_main_workdir_is_prepared_before_writer_lock(state, monkeypatch):
+ from storage import workbench_sessions_service
+
+ _tmp_path, vibey = state
+ lock_acquired = False
+ original_reserve = workbench_sessions_service.reserve_write_lock
+ original_mkdir = Path.mkdir
+
+ def reserve(conn):
+ nonlocal lock_acquired
+ original_reserve(conn)
+ lock_acquired = True
+
+ def mkdir(path, *args, **kwargs):
+ assert not lock_acquired
+ return original_mkdir(path, *args, **kwargs)
+
+ monkeypatch.setattr(workbench_sessions_service, "reserve_write_lock", reserve)
+ monkeypatch.setattr(Path, "mkdir", mkdir)
+ _ensure_main("local", vibey.name)
+
+
+def test_main_route_returns_the_stable_session_and_can_chat_without_a_project(state):
+ from storage.workbench_sessions_service import MAIN_SESSION_ID
+
+ client = app.test_client()
+ response = client.get("/api/sessions/main")
+ assert response.status_code == 200, response.get_json()
+ body = response.get_json()
+ assert body["session"]["id"] == MAIN_SESSION_ID
+ assert body["session"]["scope_id"] is None
+ assert body["capabilities"] == {"can_chat": True}
+
+
def test_route_is_an_editor_write():
from vibe.authorization import required_instance_role
diff --git a/tests/test_member_management_parity.py b/tests/test_member_management_parity.py
index 9268b7478..e154f9c65 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) == 287
+ assert len(endpoints) == 288
+ assert ("GET", "/api/sessions/main") in endpoints
assert http_authorization_policy("POST", "/api/vault/requests/{request_id}/approve-delete").minimum_role == "editor"
for method in ("PUT", "DELETE"):
assert (method, "/api/vault/secrets/{name}/fields/{field}") in endpoints
diff --git a/ui/src/context/ApiContext.desktopMini.test.tsx b/ui/src/context/ApiContext.desktopMini.test.tsx
index 50562db4b..28dac7796 100644
--- a/ui/src/context/ApiContext.desktopMini.test.tsx
+++ b/ui/src/context/ApiContext.desktopMini.test.tsx
@@ -60,3 +60,21 @@ describe('ensureDesktopMiniSession', () => {
expect(showToast).not.toHaveBeenCalled();
});
});
+
+describe('getMainSession', () => {
+ it('reads the stable main session from the main-session endpoint', async () => {
+ render(<ApiProvider><CaptureApi /></ApiProvider>);
+ await waitFor(() => expect(capturedApi).not.toBeNull());
+ apiFetch.mockResolvedValueOnce(response({
+ session: { id: 'ses_main', title: 'Vibey', capabilities: { can_chat: true } },
+ capabilities: { can_chat: true },
+ }));
+ const result = await capturedApi!.getMainSession();
+ expect(result).toMatchObject({
+ status: 200,
+ session: { id: 'ses_main', title: 'Vibey' },
+ capabilities: { can_chat: true },
+ });
+ expect(apiFetch).toHaveBeenCalledWith('/api/sessions/main');
+ });
+});
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 48de9a3c1..ee245bb6c 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -749,8 +749,7 @@ export type ApiContextType = {
createSession: (payload: WorkbenchSessionCreate) => Promise<WorkbenchSession>;
forkSession: (sessionId: string) => Promise<WorkbenchSession>;
getSession: (sessionId: string, params?: { cache?: boolean; handleError?: boolean }) => Promise<WorkbenchSession>;
- /** Main-agent lookup seam. The endpoint is not shipped yet; the pet client
- * currently resolves the session bound to its native window here. */
+ /** Resolve the stable main session for the current authorization context. */
getMainSession: () => Promise<WorkbenchSessionReadResult>;
/** The caller's desktop mini conversation with Vibey, created on first use
* in their most recently active chat Project. */
@@ -3773,16 +3772,17 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
return sessionRowFromPayload(payload);
},
getMainSession: async () => {
- const binding = (window as unknown as { __AVIBE_PET_BINDING__?: unknown }).__AVIBE_PET_BINDING__;
- if (typeof binding !== 'string' || !binding) return { status: 404, session: null };
- const res = await apiFetch(`/api/sessions/${encodeURIComponent(binding)}`);
+ const res = await apiFetch('/api/sessions/main');
const payload = await res.json().catch(() => null);
- if (!(res.ok && payload && typeof payload.id === 'string')) {
+ const sessionPayload = payload && typeof payload === 'object' && 'session' in payload
+ ? (payload as { session?: unknown }).session
+ : payload;
+ if (!(res.ok && sessionPayload && typeof sessionPayload === 'object' && typeof (sessionPayload as { id?: unknown }).id === 'string')) {
return { status: res.status, session: null };
}
return {
status: res.status,
- session: sessionRowFromPayload(payload),
+ session: sessionRowFromPayload(sessionPayload as WorkbenchSession & { capabilities?: unknown }),
capabilities: sessionCanChatFromPayload(payload),
};
},
diff --git a/ui/src/pet/PetPage.test.tsx b/ui/src/pet/PetPage.test.tsx
index 5363ac612..d3dca7b46 100644
--- a/ui/src/pet/PetPage.test.tsx
+++ b/ui/src/pet/PetPage.test.tsx
@@ -120,9 +120,12 @@ const markRead = vi.fn(async (): Promise<boolean> => {
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'); }),
+ getMainSession: vi.fn(() => {
+ const binding = (window as unknown as { __AVIBE_PET_BINDING__?: unknown }).__AVIBE_PET_BINDING__;
+ return typeof binding === 'string' && binding
+ ? api.getSessionResult(binding)
+ : Promise.resolve({ status: 404, session: null });
+ }),
getConfig: vi.fn(async () => (setupDone
? { mode: 'self_host', setup_state: { needs_setup: false } }
: { mode: 'self_host', setup_state: { needs_setup: true } })),
@@ -234,8 +237,13 @@ 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'); });
+ api.getMainSession.mockReset();
+ api.getMainSession.mockImplementation(() => {
+ const binding = (window as unknown as { __AVIBE_PET_BINDING__?: unknown }).__AVIBE_PET_BINDING__;
+ return typeof binding === 'string' && binding
+ ? api.getSessionResult(binding)
+ : Promise.resolve({ status: 404, session: null });
+ });
window.localStorage.clear();
});
@@ -321,43 +329,53 @@ 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' }));
+ const mainResult = (id = 'V'): WorkbenchSessionReadResult => ({
+ status: 200,
+ session: session(id, { agent_name: 'vibey', agent_backend: 'vibey' }),
+ capabilities: { can_chat: true },
+ });
+
+ it('binds the stable main session when nothing is bound', async () => {
+ api.getMainSession.mockResolvedValue(mainResult());
render(<PetPage />);
await waitFor(() => expect(devBinding().binding).toBe('V'));
- expect(api.ensureDesktopMiniSession).toHaveBeenCalledTimes(1);
+ expect(api.getMainSession).toHaveBeenCalled();
});
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'));
+ api.getMainSession.mockResolvedValueOnce(mainResult());
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 () => {
+ it('offers the stable main session in the switcher without requiring a project', async () => {
switcherSessions = [session('B', { title: 'Another session' })];
+ api.getMainSession.mockResolvedValueOnce({ status: 404, session: null });
+ api.getMainSession.mockResolvedValue(mainResult());
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('shows an error when the main-session endpoint resolves without a session', async () => {
+ api.getMainSession.mockResolvedValue({ status: 409, session: null });
+ render(<PetPage />);
+ summon('show');
+ await userEvent.click(await screen.findByText('pet.talkToVibey'));
+ expect(await screen.findByText('pet.vibeyUnavailable')).toBeTruthy();
+ });
+
it('does not offer Vibey to someone who cannot chat', async () => {
canChat = false;
switcherSessions = [session('B', { title: 'Another session' })];
@@ -365,7 +383,7 @@ describe('PetPage Vibey conversation', () => {
summon('show');
expect(await screen.findByText('Another session')).toBeTruthy();
expect(screen.queryByText('pet.talkToVibey')).toBeNull();
- expect(api.ensureDesktopMiniSession).not.toHaveBeenCalled();
+ expect(api.getMainSession).not.toHaveBeenCalled();
});
it('shows a turn the agent could not run, with the way to fix it', async () => {
diff --git a/ui/src/pet/PetPage.tsx b/ui/src/pet/PetPage.tsx
index 6877f84ec..4e0946884 100644
--- a/ui/src/pet/PetPage.tsx
+++ b/ui/src/pet/PetPage.tsx
@@ -148,8 +148,7 @@ 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
+ // Bind the stable main session when the shell has no current session. 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 });
@@ -162,7 +161,9 @@ const PetSurface: React.FC = () => {
if (ensured.current.inFlight) return;
const current = ensured.current;
current.inFlight = true;
- void api.ensureDesktopMiniSession().then((session) => {
+ void api.getMainSession().then((result) => {
+ const session = result.session;
+ if (!session || result.capabilities?.can_chat === false) return;
if (!epoch.isCurrent() || current.ids.has(session.id)) return;
current.ids.add(session.id);
petShell.pick(session.id, epoch.isAuthorizationCurrent);
@@ -626,8 +627,12 @@ const SessionPicker: React.FC<{ onPick: (sessionId: string) => void; onBack?: ()
if (vibeyPending) return;
setVibeyPending(true);
setVibeyError(null);
- api.ensureDesktopMiniSession().then((session) => {
- if (mounted.current) onPick(session.id);
+ api.getMainSession().then((result) => {
+ if (!result.session) {
+ if (mounted.current) setVibeyError(t('pet.vibeyUnavailable'));
+ return;
+ }
+ if (mounted.current) onPick(result.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); });
diff --git a/ui/src/pet/usePetSession.ts b/ui/src/pet/usePetSession.ts
index 1952d9789..7c3f4e183 100644
--- a/ui/src/pet/usePetSession.ts
+++ b/ui/src/pet/usePetSession.ts
@@ -126,7 +126,7 @@ export function usePetSession(sessionId: string | null, onInvalid: (sessionId: s
const sources = useMemo(() => ({
session: new FencedSource<string, WorkbenchSessionReadResult>({
- read: () => api.getMainSession(),
+ read: (key) => api.getSessionResult(key),
apply: (key, { status, session: row, capabilities }) => {
// A binding is valid only while S is writable: missing, archived and
// Runtime-owned sessions all clear it.
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 506a61c62..0ab929719 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -1732,7 +1732,10 @@
"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."
+ "builtinAgentUnavailable": "The built-in Agent is not available, so the desktop mini has no one to talk to.",
+ "mainSessionArchived": "The desktop mini's main session is archived and cannot be reopened.",
+ "mainSessionInvalid": "The desktop mini's main session is invalid and cannot be opened.",
+ "mainSessionProtected": "The desktop mini's main session is managed by Avibe and cannot be archived or edited."
},
"hostedTools": {
"errorCode": {
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 3b1948333..3d3006d9e 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -1732,7 +1732,10 @@
"desktopMini": {
"sessionTitle": "歪比 · 桌宠",
"noChatProject": "先在 Avibe 里建一个项目,桌宠的对话需要放在项目里。",
- "builtinAgentUnavailable": "内置 Agent 当前不可用,桌宠暂时没有对话对象。"
+ "builtinAgentUnavailable": "内置 Agent 当前不可用,桌宠暂时没有对话对象。",
+ "mainSessionArchived": "桌宠主会话已归档,无法重新打开。",
+ "mainSessionInvalid": "桌宠主会话状态无效,暂时无法打开。",
+ "mainSessionProtected": "桌宠主会话由 Avibe 管理,不能归档或编辑。"
},
"hostedTools": {
"errorCode": {
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 55879079a..a393d0433 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -9613,6 +9613,66 @@ def desktop_mini_session_ensure():
return jsonify({**session, "capabilities": {"can_chat": can_chat}})
[email protected]("/api/sessions/main", methods=["GET"])
+def sessions_main():
+ """Return the caller's stable built-in main session, creating it on first use."""
+
+ from core.services import sessions as workbench_sessions_service
+ from core.vibe_agents import VibeAgentAccessError, VibeAgentStore
+ from vibe.authorization import InstanceAuthorizationError
+ from storage.workbench_sessions_service import (
+ MainSessionArchivedError,
+ MainSessionInvariantError,
+ ensure_main_session,
+ )
+
+ 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_main_session(
+ conn,
+ agent_name=vibey.name,
+ title=t("desktopMini.sessionTitle", lang),
+ authorization_context=authorization_context,
+ )
+ except InstanceAuthorizationError:
+ return jsonify(
+ {"ok": False, "error": "instance_access_forbidden", "required_role": "owner"}
+ ), 403
+ except (VibeAgentAccessError, workbench_sessions_service.ProjectAccessDeniedError):
+ return _coded_error_response("project_access_denied", t("error.projectAccessDenied", lang), 403)
+ except MainSessionArchivedError:
+ return _coded_error_response(
+ MainSessionArchivedError.code,
+ t("desktopMini.mainSessionArchived", lang),
+ 409,
+ )
+ except MainSessionInvariantError:
+ return _coded_error_response(
+ MainSessionInvariantError.code,
+ t("desktopMini.mainSessionInvalid", lang),
+ 409,
+ )
+ return jsonify(
+ {
+ "session": session,
+ "capabilities": {
+ "can_chat": bool(getattr(authorization_context, "can_chat", False)),
+ },
+ }
+ )
+
+
def _session_fork_error_response(err: Exception):
"""Map a ``SessionForkError`` to its machine code, in the STRUCTURED body.
@@ -10026,6 +10086,7 @@ def _session_archived_response():
#: The archive/edit refusal's copy: the row exists to receive notices and cannot be
#: torn down or re-labelled. Used by the DELETE and PATCH guards.
RESERVED_SESSION_PROTECTED_I18N_KEY = "harness.notice.workspaceSessionProtected"
+MAIN_SESSION_PROTECTED_I18N_KEY = "desktopMini.mainSessionProtected"
#: The send refusal's copy. A SEPARATE key on purpose: "cannot be archived or modified"
#: is not an answer to "why did my message not send", and the composer's own inert-state
#: notice has to say the same thing this body says.
@@ -10133,6 +10194,7 @@ def _publish_session_update_activity(
@app.route("/api/sessions/<session_id>", methods=["PATCH"])
async def sessions_update(session_id: str):
from core.services import sessions as workbench_sessions_service
+ from storage.workbench_sessions_service import MAIN_SESSION_ID, MAIN_SESSION_UPDATABLE_FIELDS
from vibe import internal_client
from vibe.sse_broker import broker
@@ -10155,6 +10217,13 @@ async def sessions_update(session_id: str):
}
if not updatable:
return jsonify({"error": "no updatable fields supplied"}), 400
+ if str(session_id) == MAIN_SESSION_ID and not set(updatable).issubset(
+ MAIN_SESSION_UPDATABLE_FIELDS
+ ):
+ return _reserved_session_response(
+ MAIN_SESSION_PROTECTED_I18N_KEY,
+ code="reserved_session",
+ )
engine = _projects_engine()
# Archive is TERMINAL, so it outranks every transient conflict below — most
@@ -10262,7 +10331,9 @@ async def sessions_update(session_id: str):
# un-project the system surface until the next heal. Mirror the DELETE
# route's 403 + localized copy so the two guards read as one contract.
return _reserved_session_response(
- RESERVED_SESSION_PROTECTED_I18N_KEY,
+ MAIN_SESSION_PROTECTED_I18N_KEY
+ if str(session_id) == MAIN_SESSION_ID
+ else RESERVED_SESSION_PROTECTED_I18N_KEY,
code=getattr(err, "code", "reserved_session"),
)
except ValueError as err:
@@ -10451,6 +10522,7 @@ async def sessions_archive(session_id: str):
from core.show_pages import ShowPageError, require_show_page_management
from sqlalchemy import select
from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID
+ from storage.workbench_sessions_service import MAIN_SESSION_ID
from storage.models import show_pages
from vibe.sse_broker import broker
@@ -10460,6 +10532,11 @@ async def sessions_archive(session_id: str):
RESERVED_SESSION_PROTECTED_I18N_KEY,
code="reserved_session",
)
+ if str(session_id) == MAIN_SESSION_ID:
+ return _reserved_session_response(
+ MAIN_SESSION_PROTECTED_I18N_KEY,
+ code="reserved_session",
+ )
try:
with engine.connect() as conn:
existing_session = workbench_sessions_service.get_session(
@@ -10496,7 +10573,9 @@ async def sessions_archive(session_id: str):
code = getattr(err, "code", "forbidden")
if code == "reserved_session":
return _reserved_session_response(
- RESERVED_SESSION_PROTECTED_I18N_KEY,
+ MAIN_SESSION_PROTECTED_I18N_KEY
+ if str(session_id) == MAIN_SESSION_ID
+ else RESERVED_SESSION_PROTECTED_I18N_KEY,
code=code,
)
return _coded_error_response(code, str(err), 403)
@@ -10525,7 +10604,9 @@ async def sessions_archive(session_id: str):
return jsonify({"error": f"Session not found: {session_id}"}), 404
if status_code == 403 and body.get("error") == "reserved_session":
return _reserved_session_response(
- RESERVED_SESSION_PROTECTED_I18N_KEY,
+ MAIN_SESSION_PROTECTED_I18N_KEY
+ if str(session_id) == MAIN_SESSION_ID
+ else RESERVED_SESSION_PROTECTED_I18N_KEY,
code="reserved_session",
)
candidate = body.get("session")