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(api): sessions + messages REST + inbox feed

cyh1cb4e3b18376
diff --git a/storage/messages_service.py b/storage/messages_service.py
new file mode 100644
index 000000000..ef02722c8
--- /dev/null
+++ b/storage/messages_service.py
@@ -0,0 +1,251 @@
+"""CRUD over the platform-agnostic ``messages`` table.
+
+The workbench Inbox + per-session history both read through this
+module so they get a consistent shape regardless of which platform
+originated the row. ``append`` is the canonical write path —
+adapters and REST routes call it instead of touching the table
+directly so future invariants (e.g. SSE fan-out hooks, audit logging)
+land in one place.
+"""
+
+from __future__ import annotations
+
+import json
+import uuid
+from datetime import datetime, timezone
+from typing import Any, Iterable, Optional
+
+from sqlalchemy import and_, func, or_, select, update
+from sqlalchemy.engine import Connection
+
+from storage.models import messages
+
+
+def _utc_now_iso() -> str:
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _new_message_id() -> str:
+ return f"msg_{uuid.uuid4().hex[:16]}"
+
+
+def _row_to_payload(row: dict[str, Any]) -> dict[str, Any]:
+ try:
+ content = json.loads(row.get("content_json") or "{}")
+ except json.JSONDecodeError:
+ content = {}
+ try:
+ metadata = json.loads(row.get("metadata_json") or "{}")
+ except json.JSONDecodeError:
+ metadata = {}
+ return {
+ "id": row["id"],
+ "scope_id": row.get("scope_id"),
+ "session_id": row.get("session_id"),
+ "platform": row.get("platform"),
+ "author": row.get("author"),
+ "author_id": row.get("author_id"),
+ "author_name": row.get("author_name"),
+ "native_message_id": row.get("native_message_id"),
+ "parent_native_message_id": row.get("parent_native_message_id"),
+ "text": row.get("content_text") or content.get("text") or "",
+ "content": content,
+ "metadata": metadata,
+ "created_at": row.get("created_at"),
+ "updated_at": row.get("updated_at"),
+ "delivered_at": row.get("delivered_at"),
+ "read_at": row.get("read_at"),
+ }
+
+
+def append(
+ conn: Connection,
+ *,
+ scope_id: str,
+ session_id: Optional[str],
+ platform: str,
+ author: str,
+ text: Optional[str] = None,
+ content: Optional[dict[str, Any]] = None,
+ metadata: Optional[dict[str, Any]] = None,
+ author_id: Optional[str] = None,
+ author_name: Optional[str] = None,
+ native_message_id: Optional[str] = None,
+ parent_native_message_id: Optional[str] = None,
+ delivered_at: Optional[str] = None,
+ read_at: Optional[str] = None,
+) -> dict[str, Any]:
+ """Insert a new message row and return its payload.
+
+ ``content`` is the rich blob (text + attachments + tool_calls); if
+ ``text`` is omitted we project ``content['text']`` into
+ ``content_text`` so plain-text search keeps working.
+ """
+
+ body: dict[str, Any] = {}
+ if content:
+ body.update(content)
+ if text is not None:
+ body.setdefault("text", text)
+ plain = text if text is not None else body.get("text") or None
+
+ now = _utc_now_iso()
+ payload = {
+ "id": _new_message_id(),
+ "scope_id": scope_id,
+ "session_id": session_id,
+ "platform": platform,
+ "author": author,
+ "author_id": author_id,
+ "author_name": author_name,
+ "native_message_id": native_message_id,
+ "parent_native_message_id": parent_native_message_id,
+ "content_text": plain,
+ "content_json": json.dumps(body),
+ "metadata_json": json.dumps(metadata or {}),
+ "created_at": now,
+ "updated_at": now,
+ "delivered_at": delivered_at,
+ "read_at": read_at,
+ }
+ conn.execute(messages.insert().values(**payload))
+ return _row_to_payload(payload)
+
+
+def list_session_messages(
+ conn: Connection,
+ *,
+ session_id: str,
+ after_id: Optional[str] = None,
+ limit: int = 50,
+) -> dict[str, Any]:
+ """Return messages for one session in chronological order with cursor pagination."""
+
+ query = select(messages).where(messages.c.session_id == session_id)
+ if after_id:
+ anchor = conn.execute(
+ select(messages.c.created_at).where(messages.c.id == after_id)
+ ).scalar_one_or_none()
+ if anchor is not None:
+ query = query.where(
+ or_(
+ messages.c.created_at > anchor,
+ and_(messages.c.created_at == anchor, messages.c.id > after_id),
+ )
+ )
+ query = query.order_by(messages.c.created_at.asc(), messages.c.id.asc()).limit(
+ min(max(int(limit), 1), 500)
+ )
+ rows = [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]
+ next_after = rows[-1]["id"] if len(rows) == limit else None
+ return {"messages": rows, "next_after_id": next_after}
+
+
+def list_inbox(
+ conn: Connection,
+ *,
+ platform: Optional[str] = None,
+ unread_only: bool = False,
+ limit: int = 30,
+ before_id: Optional[str] = None,
+) -> dict[str, Any]:
+ """Cross-session feed for the workbench Inbox.
+
+ Returns the most recent agent-authored messages first (the human
+ sent them, they don't need to see their own as "new"). The
+ ``platform`` filter defaults to nothing so users opting into
+ cross-platform mirroring see Slack/Discord here too; per the
+ workbench scope the UI passes ``platform='avibe'`` to scope it
+ down.
+ """
+
+ query = select(messages).where(messages.c.author == "agent")
+ if platform is not None:
+ query = query.where(messages.c.platform == platform)
+ if unread_only:
+ query = query.where(messages.c.read_at.is_(None))
+ if before_id:
+ anchor = conn.execute(
+ select(messages.c.created_at).where(messages.c.id == before_id)
+ ).scalar_one_or_none()
+ if anchor is not None:
+ query = query.where(
+ or_(
+ messages.c.created_at < anchor,
+ and_(messages.c.created_at == anchor, messages.c.id < before_id),
+ )
+ )
+ query = query.order_by(messages.c.created_at.desc(), messages.c.id.desc()).limit(
+ min(max(int(limit), 1), 200)
+ )
+ rows = [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]
+ next_before = rows[-1]["id"] if len(rows) == limit else None
+ return {"messages": rows, "next_before_id": next_before}
+
+
+def unread_counts(
+ conn: Connection,
+ *,
+ platform: Optional[str] = None,
+) -> dict[str, int]:
+ """Return ``{scope_id: count}`` for unread agent messages.
+
+ Used by the sidebar / hover popover to show per-session unread dots
+ plus the global count without dragging every row through Python.
+ """
+
+ query = (
+ select(messages.c.scope_id, func.count(messages.c.id))
+ .where(messages.c.author == "agent")
+ .where(messages.c.read_at.is_(None))
+ .group_by(messages.c.scope_id)
+ )
+ if platform is not None:
+ query = query.where(messages.c.platform == platform)
+ return {scope: int(count) for scope, count in conn.execute(query).all()}
+
+
+def mark_session_read(
+ conn: Connection,
+ session_id: str,
+ *,
+ until_message_id: Optional[str] = None,
+) -> int:
+ """Mark unread agent messages in a session as read, up to ``until_message_id``.
+
+ Returns the number of rows updated.
+ """
+
+ now = _utc_now_iso()
+ base = (
+ update(messages)
+ .where(messages.c.session_id == session_id)
+ .where(messages.c.author == "agent")
+ .where(messages.c.read_at.is_(None))
+ .values(read_at=now, updated_at=now)
+ )
+ if until_message_id:
+ anchor = conn.execute(
+ select(messages.c.created_at).where(messages.c.id == until_message_id)
+ ).scalar_one_or_none()
+ if anchor is not None:
+ base = base.where(messages.c.created_at <= anchor)
+ result = conn.execute(base)
+ return result.rowcount or 0
+
+
+def list_messages_for_inbox_scope(
+ conn: Connection,
+ scope_id: str,
+ *,
+ limit: int = 1,
+) -> Iterable[dict[str, Any]]:
+ """Return the latest N messages for a given scope (for inbox previews)."""
+
+ query = (
+ select(messages)
+ .where(messages.c.scope_id == scope_id)
+ .order_by(messages.c.created_at.desc(), messages.c.id.desc())
+ .limit(min(max(int(limit), 1), 50))
+ )
+ return [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]
diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.py
new file mode 100644
index 000000000..dad18452d
--- /dev/null
+++ b/storage/workbench_sessions_service.py
@@ -0,0 +1,247 @@
+"""Workbench-scoped session CRUD over ``agent_sessions``.
+
+``storage/sessions_service.py`` exposes the runtime-facing primitives
+that IM dispatchers use to reserve sessions during message handling.
+The workbench REST API needs different shapes — listing sessions in a
+project, creating one with explicit Agent / model / effort, renaming,
+archiving — so this module wraps the same ``agent_sessions`` table
+with workbench-friendly queries instead of bolting another concern
+onto ``SQLiteSessionsService``.
+
+Avibe scope_ids look like ``avibe::project::proj_<hex12>`` — see
+``storage/projects_service.py``.
+"""
+
+from __future__ import annotations
+
+import json
+import secrets
+from datetime import datetime, timezone
+from typing import Any, Optional
+
+from sqlalchemy import select, update
+from sqlalchemy.engine import Connection
+
+from storage.models import agent_sessions, scope_settings, scopes
+
+
+SESSION_ID_ALPHABET = "23456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
+
+
+def _utc_now_iso() -> str:
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _new_session_id(conn: Connection) -> str:
+ used = {str(value) for value in conn.execute(select(agent_sessions.c.id)).scalars()}
+ while True:
+ candidate = "ses" + "".join(secrets.choice(SESSION_ID_ALPHABET) for _ in range(10))
+ if candidate not in used:
+ return candidate
+
+
+def _row_to_payload(row: dict[str, Any]) -> dict[str, Any]:
+ try:
+ metadata = json.loads(row.get("metadata_json") or "{}")
+ except json.JSONDecodeError:
+ metadata = {}
+ return {
+ "id": row["id"],
+ "scope_id": row.get("scope_id"),
+ "project_id": (row.get("scope_id") or "").rsplit("::", 1)[-1] or None,
+ "title": row.get("title"),
+ "agent_id": row.get("agent_id"),
+ "agent_name": row.get("agent_name"),
+ "agent_backend": row.get("agent_backend"),
+ "agent_variant": row.get("agent_variant"),
+ "model": row.get("model"),
+ "reasoning_effort": row.get("reasoning_effort"),
+ "status": row.get("status"),
+ "workdir": row.get("workdir"),
+ "native_session_id": row.get("native_session_id"),
+ "created_at": row.get("created_at"),
+ "updated_at": row.get("updated_at"),
+ "last_active_at": row.get("last_active_at"),
+ "metadata": metadata,
+ }
+
+
+def list_sessions(
+ conn: Connection,
+ *,
+ scope_id: Optional[str] = None,
+ status: Optional[str] = None,
+ limit: int = 50,
+ before_id: Optional[str] = None,
+) -> dict[str, Any]:
+ """Return sessions for the workbench list. Cursor pagination via ``before_id``.
+
+ ``status`` accepts ``active`` / ``archived`` (or omit for both). The
+ cursor is the row id; results are sorted by ``last_active_at DESC``
+ so the cursor row is "the last id you already saw".
+ """
+
+ query = select(agent_sessions)
+ if scope_id is not None:
+ query = query.where(agent_sessions.c.scope_id == scope_id)
+ if status is not None and status != "all":
+ query = query.where(agent_sessions.c.status == status)
+ if before_id is not None:
+ cursor_row = conn.execute(
+ select(agent_sessions.c.last_active_at, agent_sessions.c.created_at).where(agent_sessions.c.id == before_id)
+ ).first()
+ if cursor_row is not None:
+ cursor_active, cursor_created = cursor_row
+ query = query.where(
+ (agent_sessions.c.last_active_at < cursor_active)
+ | (
+ (agent_sessions.c.last_active_at == cursor_active)
+ & (agent_sessions.c.created_at < cursor_created)
+ )
+ )
+ query = (
+ query.order_by(
+ agent_sessions.c.last_active_at.desc(),
+ agent_sessions.c.created_at.desc(),
+ )
+ .limit(min(max(int(limit), 1), 200))
+ )
+ rows = [dict(row) for row in conn.execute(query).mappings().all()]
+ sessions = [_row_to_payload(row) for row in rows]
+ next_cursor = sessions[-1]["id"] if len(sessions) == limit else None
+ return {"sessions": sessions, "next_before_id": next_cursor}
+
+
+def get_session(conn: Connection, session_id: str) -> dict[str, Any]:
+ row = conn.execute(
+ select(agent_sessions).where(agent_sessions.c.id == session_id)
+ ).mappings().first()
+ if row is None:
+ raise LookupError(f"Session not found: {session_id}")
+ return _row_to_payload(dict(row))
+
+
+def create_session(
+ conn: Connection,
+ *,
+ scope_id: str,
+ agent_backend: str,
+ agent_name: Optional[str] = None,
+ agent_id: Optional[str] = None,
+ agent_variant: Optional[str] = None,
+ model: Optional[str] = None,
+ reasoning_effort: Optional[str] = None,
+ title: Optional[str] = None,
+ metadata: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ """Create a workbench session inside the given project scope.
+
+ Pulls ``workdir`` from ``scope_settings`` so Agent runs already know
+ where to cd. ``native_session_id`` stays empty — Claude / OpenCode /
+ Codex fill it on their first turn.
+ """
+
+ scope_row = conn.execute(
+ select(scopes.c.id, scope_settings.c.workdir, scope_settings.c.enabled)
+ .select_from(scopes.outerjoin(scope_settings, scope_settings.c.scope_id == scopes.c.id))
+ .where(scopes.c.id == scope_id)
+ ).mappings().first()
+ if scope_row is None:
+ raise LookupError(f"Scope not found: {scope_id}")
+ if scope_row.get("enabled") == 0:
+ raise PermissionError(f"Scope is archived: {scope_id}")
+ workdir = scope_row.get("workdir")
+
+ now = _utc_now_iso()
+ session_id = _new_session_id(conn)
+ variant = agent_variant or agent_name or "default"
+ metadata_payload = {"created_via": "workbench"}
+ if metadata:
+ metadata_payload.update(metadata)
+
+ conn.execute(
+ agent_sessions.insert().values(
+ id=session_id,
+ scope_id=scope_id,
+ agent_id=agent_id,
+ agent_name=agent_name,
+ agent_backend=agent_backend,
+ agent_variant=str(variant),
+ model=model,
+ reasoning_effort=reasoning_effort,
+ session_anchor=session_id, # workbench sessions self-anchor; IM platforms use the parent message ts
+ workdir=workdir,
+ native_session_id="",
+ title=title.strip() if (title or "").strip() else None,
+ status="active",
+ metadata_json=json.dumps(metadata_payload),
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+ return get_session(conn, session_id)
+
+
+def update_session(
+ conn: Connection,
+ session_id: str,
+ *,
+ title: Optional[str] = None,
+ agent_id: Optional[str] = None,
+ agent_name: Optional[str] = None,
+ agent_backend: Optional[str] = None,
+ agent_variant: Optional[str] = None,
+ model: Optional[str] = None,
+ reasoning_effort: Optional[str] = None,
+) -> dict[str, Any]:
+ existing = conn.execute(
+ select(agent_sessions.c.id).where(agent_sessions.c.id == session_id)
+ ).scalar_one_or_none()
+ if existing is None:
+ raise LookupError(f"Session not found: {session_id}")
+
+ values: dict[str, Any] = {"updated_at": _utc_now_iso()}
+ if title is not None:
+ cleaned = title.strip()
+ values["title"] = cleaned or None
+ if agent_id is not None:
+ values["agent_id"] = agent_id or None
+ if agent_name is not None:
+ values["agent_name"] = agent_name or None
+ if agent_backend is not None:
+ values["agent_backend"] = agent_backend
+ if agent_variant is not None:
+ values["agent_variant"] = str(agent_variant)
+ if model is not None:
+ values["model"] = model or None
+ if reasoning_effort is not None:
+ values["reasoning_effort"] = reasoning_effort or None
+
+ conn.execute(update(agent_sessions).where(agent_sessions.c.id == session_id).values(**values))
+ return get_session(conn, session_id)
+
+
+def archive_session(conn: Connection, session_id: str) -> dict[str, Any]:
+ existing = conn.execute(
+ select(agent_sessions.c.id).where(agent_sessions.c.id == session_id)
+ ).scalar_one_or_none()
+ if existing is None:
+ raise LookupError(f"Session not found: {session_id}")
+ now = _utc_now_iso()
+ conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == session_id)
+ .values(status="archived", updated_at=now)
+ )
+ return get_session(conn, session_id)
+
+
+def touch_session(conn: Connection, session_id: str) -> None:
+ """Bump ``last_active_at`` after a new message arrives."""
+
+ conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == session_id)
+ .values(last_active_at=_utc_now_iso(), updated_at=_utc_now_iso())
+ )
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index e40835f02..90e928476 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -44,7 +44,7 @@ type GuardStatus = 'loading' | 'ready' | 'needs-setup' | 'remote-login-required'
// Wrapper to check if setup is needed
const AuthGuard = ({ children }: { children: ReactNode }) => {
- const { getConfig, getSession } = useApi();
+ const { getConfig, getAuthSession } = useApi();
const location = useLocation();
const guardTarget = location.pathname + location.search;
const [guardState, setGuardState] = useState<{ target: string; status: GuardStatus }>({
@@ -60,7 +60,7 @@ const AuthGuard = ({ children }: { children: ReactNode }) => {
return;
}
- getSession().then(session => {
+ getAuthSession().then(session => {
if (cancelled) return;
if (session.remote && !session.authenticated) {
setGuardState({ target: guardTarget, status: 'remote-login-required' });
@@ -79,7 +79,7 @@ const AuthGuard = ({ children }: { children: ReactNode }) => {
});
}).catch(async (error) => {
if (cancelled) return;
- const session = await getSession().catch(() => null);
+ const session = await getAuthSession().catch(() => null);
if (cancelled) return;
if (session?.remote && !session.authenticated) {
setGuardState({ target: guardTarget, status: 'remote-login-required' });
@@ -94,7 +94,7 @@ const AuthGuard = ({ children }: { children: ReactNode }) => {
return () => {
cancelled = true;
};
- }, [bypassSetupGuard, getConfig, getSession, guardTarget]);
+ }, [bypassSetupGuard, getConfig, getAuthSession, guardTarget]);
if (bypassSetupGuard) return children;
if (guardState.target !== guardTarget || guardState.status === 'loading') {
diff --git a/ui/src/components/AccountMenu.tsx b/ui/src/components/AccountMenu.tsx
index 0a0628753..dd59e76dd 100644
--- a/ui/src/components/AccountMenu.tsx
+++ b/ui/src/components/AccountMenu.tsx
@@ -13,7 +13,7 @@ const initialFor = (email: string): string => {
export const AccountMenu: React.FC<{ openUpward?: boolean }> = ({ openUpward = false }) => {
const { t } = useTranslation();
- const { getSession, signOut } = useApi();
+ const { getAuthSession, signOut } = useApi();
const [email, setEmail] = useState<string | null>(null);
const [isOpen, setIsOpen] = useState(false);
const [signingOut, setSigningOut] = useState(false);
@@ -21,7 +21,7 @@ export const AccountMenu: React.FC<{ openUpward?: boolean }> = ({ openUpward = f
useEffect(() => {
let cancelled = false;
- getSession()
+ getAuthSession()
.then((session) => {
if (cancelled) return;
if (session.remote && session.authenticated) {
@@ -36,7 +36,7 @@ export const AccountMenu: React.FC<{ openUpward?: boolean }> = ({ openUpward = f
return () => {
cancelled = true;
};
- }, [getSession]);
+ }, [getAuthSession]);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 25b994d4c..59c482192 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -96,11 +96,20 @@ export type ApiContextType = {
createProject: (payload: { folder_path: string; display_name?: string }) => Promise<WorkbenchProject>;
updateProject: (projectId: string, payload: { display_name?: string; folder_path?: string }) => Promise<WorkbenchProject>;
archiveProject: (projectId: string) => Promise<WorkbenchProject>;
+ listSessions: (params?: { projectId?: string; status?: 'active' | 'archived' | 'all'; limit?: number; beforeId?: string }) => Promise<{ sessions: WorkbenchSession[]; next_before_id: string | null }>;
+ createSession: (payload: WorkbenchSessionCreate) => Promise<WorkbenchSession>;
+ getSession: (sessionId: string) => Promise<WorkbenchSession>;
+ updateSession: (sessionId: string, payload: Partial<WorkbenchSessionUpdate>) => Promise<WorkbenchSession>;
+ archiveSession: (sessionId: string) => Promise<WorkbenchSession>;
+ listSessionMessages: (sessionId: string, params?: { afterId?: string; limit?: number }) => Promise<{ messages: WorkbenchMessage[]; next_after_id: string | null }>;
+ sendSessionMessage: (sessionId: string, payload: { text?: string; content?: Record<string, unknown>; metadata?: Record<string, unknown>; author_id?: string; author_name?: string }) => Promise<WorkbenchMessage>;
+ markSessionRead: (sessionId: string, untilMessageId?: string) => Promise<{ updated: number }>;
+ listInbox: (params?: { platform?: string; unreadOnly?: boolean; limit?: number; beforeId?: string }) => Promise<{ messages: WorkbenchMessage[]; next_before_id: string | null; unread_counts: Record<string, number> }>;
remoteAccessStatus: () => Promise<any>;
pairVibeCloudRemoteAccess: (payload: { backend_url: string; pairing_key: string; device_name?: string }) => Promise<any>;
startRemoteAccess: () => Promise<any>;
stopRemoteAccess: () => Promise<any>;
- getSession: () => Promise<SessionInfo>;
+ getAuthSession: () => Promise<SessionInfo>;
signOut: () => Promise<{ ok: boolean }>;
};
@@ -118,6 +127,70 @@ export type WorkbenchProject = {
metadata?: Record<string, unknown>;
};
+// Workbench session — a row in ``agent_sessions`` created via /api/sessions.
+// ``project_id`` is the short ``proj_<hex>`` suffix of ``scope_id``.
+export type WorkbenchSession = {
+ id: string;
+ scope_id: string | null;
+ project_id: string | null;
+ title: string | null;
+ agent_id: string | null;
+ agent_name: string | null;
+ agent_backend: string | null;
+ agent_variant: string | null;
+ model: string | null;
+ reasoning_effort: string | null;
+ status: string;
+ workdir: string | null;
+ native_session_id: string | null;
+ created_at: string;
+ updated_at: string;
+ last_active_at: string | null;
+ metadata: Record<string, unknown>;
+};
+
+export type WorkbenchSessionCreate = {
+ project_id: string;
+ agent_backend: string;
+ agent_id?: string;
+ agent_name?: string;
+ agent_variant?: string;
+ model?: string;
+ reasoning_effort?: string;
+ title?: string;
+ metadata?: Record<string, unknown>;
+};
+
+export type WorkbenchSessionUpdate = {
+ title: string | null;
+ agent_id: string | null;
+ agent_name: string | null;
+ agent_backend: string;
+ agent_variant: string;
+ model: string | null;
+ reasoning_effort: string | null;
+};
+
+// One row from the platform-agnostic ``messages`` table.
+export type WorkbenchMessage = {
+ id: string;
+ scope_id: string | null;
+ session_id: string | null;
+ platform: string;
+ author: 'user' | 'agent' | 'system' | string;
+ author_id: string | null;
+ author_name: string | null;
+ native_message_id: string | null;
+ parent_native_message_id: string | null;
+ text: string;
+ content: Record<string, unknown>;
+ metadata: Record<string, unknown>;
+ created_at: string;
+ updated_at: string;
+ delivered_at: string | null;
+ read_at: string | null;
+};
+
export type SessionInfo =
| { remote: false }
| { remote: true; authenticated: false }
@@ -641,11 +714,58 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
return res.json();
},
archiveProject: (projectId) => deleteJson(`/api/projects/${encodeURIComponent(projectId)}`),
+ listSessions: (params) => {
+ const search = new URLSearchParams();
+ if (params?.projectId) search.set('project_id', params.projectId);
+ if (params?.status) search.set('status', params.status);
+ if (params?.limit) search.set('limit', String(params.limit));
+ if (params?.beforeId) search.set('before_id', params.beforeId);
+ const qs = search.toString();
+ return getJson(qs ? `/api/sessions?${qs}` : '/api/sessions');
+ },
+ createSession: (payload) => postJson('/api/sessions', payload),
+ getSession: (sessionId) => getJson(`/api/sessions/${encodeURIComponent(sessionId)}`),
+ updateSession: async (sessionId, payload) => {
+ const res = await apiFetch(`/api/sessions/${encodeURIComponent(sessionId)}`, {
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(payload),
+ });
+ if (!res.ok) {
+ await handleApiError(res, `PATCH /api/sessions/${sessionId}`);
+ }
+ return res.json();
+ },
+ archiveSession: (sessionId) => deleteJson(`/api/sessions/${encodeURIComponent(sessionId)}`),
+ listSessionMessages: (sessionId, params) => {
+ const search = new URLSearchParams();
+ if (params?.afterId) search.set('after_id', params.afterId);
+ if (params?.limit) search.set('limit', String(params.limit));
+ const qs = search.toString();
+ const base = `/api/sessions/${encodeURIComponent(sessionId)}/messages`;
+ return getJson(qs ? `${base}?${qs}` : base);
+ },
+ sendSessionMessage: (sessionId, payload) =>
+ postJson(`/api/sessions/${encodeURIComponent(sessionId)}/messages`, payload),
+ markSessionRead: (sessionId, untilMessageId) =>
+ postJson(
+ `/api/sessions/${encodeURIComponent(sessionId)}/mark-read`,
+ untilMessageId ? { until_message_id: untilMessageId } : {},
+ ),
+ listInbox: (params) => {
+ const search = new URLSearchParams();
+ if (params?.platform) search.set('platform', params.platform);
+ if (params?.unreadOnly) search.set('unread_only', '1');
+ if (params?.limit) search.set('limit', String(params.limit));
+ if (params?.beforeId) search.set('before_id', params.beforeId);
+ const qs = search.toString();
+ return getJson(qs ? `/api/inbox?${qs}` : '/api/inbox');
+ },
remoteAccessStatus: () => getJson('/remote-access/status'),
pairVibeCloudRemoteAccess: (payload) => postJson('/remote-access/vibe-cloud/pair', payload),
startRemoteAccess: () => postJson('/remote-access/start', {}),
stopRemoteAccess: () => postJson('/remote-access/stop', {}),
- getSession: () => getJson('/api/session'),
+ getAuthSession: () => getJson('/api/session'),
signOut: () => postJson('/auth/logout', {}),
// eslint-disable-next-line react-hooks/exhaustive-deps
}), [showToast, t]);
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index d07934eea..cd4ff8763 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -2418,6 +2418,248 @@ def browse_mkdir():
return jsonify({"path": resolved}), 201
+# =============================================================================
+# Workbench: Sessions + Messages + Inbox
+# =============================================================================
+# All endpoints below talk directly to the SQLite store via the workbench
+# service modules — ORM all the way down, no CLI shell-outs.
+# ``project_id`` (short ``proj_<hex>`` form) is the public id; we expand to
+# the full scope_id ``avibe::project::proj_xxx`` inside.
+
+
+def _project_to_scope_id(project_id: str) -> str:
+ return f"avibe::project::{project_id}"
+
+
[email protected]("/api/sessions", methods=["GET"])
+def sessions_list():
+ from storage import workbench_sessions_service
+
+ project_id = request.args.get("project_id")
+ scope_id = _project_to_scope_id(project_id) if project_id else None
+ status = request.args.get("status") or "active"
+ try:
+ limit = int(request.args.get("limit") or 50)
+ except (TypeError, ValueError):
+ limit = 50
+ before_id = request.args.get("before_id") or None
+
+ engine = _projects_engine()
+ with engine.connect() as conn:
+ result = workbench_sessions_service.list_sessions(
+ conn,
+ scope_id=scope_id,
+ status=status,
+ limit=limit,
+ before_id=before_id,
+ )
+ return jsonify(result)
+
+
[email protected]("/api/sessions", methods=["POST"])
+def sessions_create():
+ from storage import workbench_sessions_service
+
+ payload = request.json or {}
+ project_id = (payload.get("project_id") or "").strip()
+ agent_backend = (payload.get("agent_backend") or "").strip()
+ if not project_id:
+ return jsonify({"error": "project_id is required"}), 400
+ if not agent_backend:
+ return jsonify({"error": "agent_backend is required"}), 400
+
+ scope_id = _project_to_scope_id(project_id)
+ engine = _projects_engine()
+ try:
+ with engine.begin() as conn:
+ session = workbench_sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend=agent_backend,
+ agent_id=payload.get("agent_id"),
+ agent_name=payload.get("agent_name"),
+ agent_variant=payload.get("agent_variant"),
+ model=payload.get("model"),
+ reasoning_effort=payload.get("reasoning_effort"),
+ title=payload.get("title"),
+ metadata=payload.get("metadata"),
+ )
+ except LookupError as err:
+ return jsonify({"error": str(err)}), 404
+ except PermissionError as err:
+ return jsonify({"error": str(err)}), 403
+ return jsonify(session), 201
+
+
[email protected]("/api/sessions/<session_id>", methods=["GET"])
+def sessions_get(session_id: str):
+ from storage import workbench_sessions_service
+
+ engine = _projects_engine()
+ try:
+ with engine.connect() as conn:
+ return jsonify(workbench_sessions_service.get_session(conn, session_id))
+ except LookupError as err:
+ return jsonify({"error": str(err)}), 404
+
+
[email protected]("/api/sessions/<session_id>", methods=["PATCH"])
+def sessions_update(session_id: str):
+ from storage import workbench_sessions_service
+
+ payload = request.json or {}
+ updatable = {
+ key: payload[key]
+ for key in (
+ "title",
+ "agent_id",
+ "agent_name",
+ "agent_backend",
+ "agent_variant",
+ "model",
+ "reasoning_effort",
+ )
+ if key in payload
+ }
+ if not updatable:
+ return jsonify({"error": "no updatable fields supplied"}), 400
+
+ engine = _projects_engine()
+ try:
+ with engine.begin() as conn:
+ session = workbench_sessions_service.update_session(conn, session_id, **updatable)
+ except LookupError as err:
+ return jsonify({"error": str(err)}), 404
+ return jsonify(session)
+
+
[email protected]("/api/sessions/<session_id>", methods=["DELETE"])
+def sessions_archive(session_id: str):
+ from storage import workbench_sessions_service
+
+ engine = _projects_engine()
+ try:
+ with engine.begin() as conn:
+ session = workbench_sessions_service.archive_session(conn, session_id)
+ except LookupError as err:
+ return jsonify({"error": str(err)}), 404
+ return jsonify(session)
+
+
[email protected]("/api/sessions/<session_id>/messages", methods=["GET"])
+def sessions_messages_list(session_id: str):
+ from storage import messages_service, workbench_sessions_service
+
+ after_id = request.args.get("after_id") or None
+ try:
+ limit = int(request.args.get("limit") or 50)
+ except (TypeError, ValueError):
+ limit = 50
+
+ engine = _projects_engine()
+ with engine.connect() as conn:
+ try:
+ workbench_sessions_service.get_session(conn, session_id)
+ except LookupError as err:
+ return jsonify({"error": str(err)}), 404
+ result = messages_service.list_session_messages(
+ conn,
+ session_id=session_id,
+ after_id=after_id,
+ limit=limit,
+ )
+ return jsonify(result)
+
+
[email protected]("/api/sessions/<session_id>/messages", methods=["POST"])
+def sessions_messages_create(session_id: str):
+ """Persist a user message under a session and touch its activity.
+
+ The actual Agent dispatch (calling into ``core/controller`` to run the
+ backend CLI) wires up in commit 13 alongside the IM-mirror change so
+ every platform funnels through one entry point. For now the message
+ lands in the table and the session's ``last_active_at`` bumps — UI
+ can render the user's turn immediately.
+ """
+
+ from storage import messages_service, workbench_sessions_service
+
+ payload = request.json or {}
+ text = payload.get("text")
+ content = payload.get("content")
+ if text is None and not content:
+ return jsonify({"error": "text or content is required"}), 400
+
+ engine = _projects_engine()
+ try:
+ with engine.begin() as conn:
+ session = workbench_sessions_service.get_session(conn, session_id)
+ message = messages_service.append(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ text=text if isinstance(text, str) else None,
+ content=content if isinstance(content, dict) else None,
+ metadata=payload.get("metadata") or {},
+ author_id=payload.get("author_id"),
+ author_name=payload.get("author_name"),
+ )
+ workbench_sessions_service.touch_session(conn, session_id)
+ except LookupError as err:
+ return jsonify({"error": str(err)}), 404
+ return jsonify(message), 201
+
+
[email protected]("/api/sessions/<session_id>/mark-read", methods=["POST"])
+def sessions_mark_read(session_id: str):
+ from storage import messages_service, workbench_sessions_service
+
+ payload = request.json or {}
+ until_message_id = payload.get("until_message_id")
+
+ engine = _projects_engine()
+ try:
+ with engine.begin() as conn:
+ workbench_sessions_service.get_session(conn, session_id)
+ updated = messages_service.mark_session_read(
+ conn, session_id, until_message_id=until_message_id
+ )
+ except LookupError as err:
+ return jsonify({"error": str(err)}), 404
+ return jsonify({"updated": updated})
+
+
[email protected]("/api/inbox", methods=["GET"])
+def inbox_list():
+ """Cross-session inbox feed. Defaults to avibe-only per workbench scope."""
+
+ from storage import messages_service
+
+ platform = request.args.get("platform") or "avibe"
+ unread_only = request.args.get("unread_only") in {"1", "true", "yes"}
+ try:
+ limit = int(request.args.get("limit") or 30)
+ except (TypeError, ValueError):
+ limit = 30
+ before_id = request.args.get("before_id") or None
+
+ engine = _projects_engine()
+ with engine.connect() as conn:
+ result = messages_service.list_inbox(
+ conn,
+ platform=platform if platform != "all" else None,
+ unread_only=unread_only,
+ limit=limit,
+ before_id=before_id,
+ )
+ result["unread_counts"] = messages_service.unread_counts(
+ conn, platform=platform if platform != "all" else None
+ )
+ return jsonify(result)
+
+
# =============================================================================
# User & Bind Code Endpoints
# =============================================================================