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): projects REST + folder-picker mkdir endpoint

cyh832fe5c43607
diff --git a/storage/projects_service.py b/storage/projects_service.py
new file mode 100644
index 000000000..9d10dc9ac
--- /dev/null
+++ b/storage/projects_service.py
@@ -0,0 +1,249 @@
+"""CRUD service for avibe projects.
+
+Projects are first-class entities in the workbench but reuse the
+existing ``scopes`` + ``scope_settings`` tables instead of introducing
+a parallel store: an avibe project is just a scope row with
+``platform='avibe'`` and ``scope_type='project'``. The local folder
+path lives in ``scope_settings.workdir`` so Agent runs can pick it up
+without a second lookup, and "archived" is modelled as
+``scope_settings.enabled = 0`` for parity with how other scopes get
+disabled.
+"""
+
+from __future__ import annotations
+
+import json
+import uuid
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Optional
+
+from sqlalchemy import select, update
+from sqlalchemy.engine import Connection
+
+from storage.models import scope_settings, scopes
+
+
+PROJECT_PLATFORM = "avibe"
+PROJECT_SCOPE_TYPE = "project"
+
+
+def _utc_now_iso() -> str:
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _new_project_id() -> str:
+ # 12 hex chars = 48 bits → plenty for a single-user installation, and
+ # the prefix keeps the id self-documenting in logs / UI tooltips.
+ return f"proj_{uuid.uuid4().hex[:12]}"
+
+
+def _make_scope_id(native_id: str) -> str:
+ # Mirrors ``storage.settings_service.make_scope_id`` — kept inline so
+ # this module stays decoupled from the broader settings surface.
+ return f"{PROJECT_PLATFORM}::{PROJECT_SCOPE_TYPE}::{native_id}"
+
+
+def _resolve_folder(folder_path: str) -> Path:
+ folder = Path(folder_path).expanduser().resolve()
+ if not folder.exists():
+ raise FileNotFoundError(f"Folder does not exist: {folder}")
+ if not folder.is_dir():
+ raise NotADirectoryError(f"Not a directory: {folder}")
+ return folder
+
+
+def list_projects(conn: Connection, *, include_archived: bool = False) -> list[dict[str, Any]]:
+ """Return all avibe projects sorted by recency, optionally including archived ones."""
+
+ query = (
+ select(
+ scopes.c.id.label("scope_id"),
+ scopes.c.native_id,
+ scopes.c.display_name,
+ scopes.c.metadata_json,
+ scopes.c.first_seen_at,
+ scopes.c.last_seen_at,
+ scope_settings.c.enabled,
+ scope_settings.c.workdir,
+ scope_settings.c.updated_at.label("settings_updated_at"),
+ )
+ .select_from(scopes.outerjoin(scope_settings, scope_settings.c.scope_id == scopes.c.id))
+ .where(scopes.c.platform == PROJECT_PLATFORM, scopes.c.scope_type == PROJECT_SCOPE_TYPE)
+ .order_by(scopes.c.last_seen_at.desc())
+ )
+ rows = conn.execute(query).mappings().all()
+ out: list[dict[str, Any]] = []
+ for row in rows:
+ enabled = bool(row["enabled"]) if row["enabled"] is not None else True
+ if not include_archived and not enabled:
+ continue
+ try:
+ metadata = json.loads(row["metadata_json"] or "{}")
+ except json.JSONDecodeError:
+ metadata = {}
+ out.append({
+ "id": row["native_id"],
+ "scope_id": row["scope_id"],
+ "display_name": row["display_name"] or row["native_id"],
+ "folder_path": row["workdir"] or "",
+ "created_at": row["first_seen_at"],
+ "last_active_at": row["last_seen_at"],
+ "archived": not enabled,
+ "metadata": metadata,
+ })
+ return out
+
+
+def get_project(conn: Connection, project_id: str) -> dict[str, Any]:
+ scope_id = _make_scope_id(project_id)
+ return _project_payload(conn, scope_id)
+
+
+def create_project(
+ conn: Connection,
+ folder_path: str,
+ display_name: Optional[str] = None,
+) -> dict[str, Any]:
+ folder = _resolve_folder(folder_path)
+
+ project_id = _new_project_id()
+ scope_id = _make_scope_id(project_id)
+ now = _utc_now_iso()
+ name = (display_name or folder.name).strip() or project_id
+
+ conn.execute(
+ scopes.insert().values(
+ id=scope_id,
+ platform=PROJECT_PLATFORM,
+ scope_type=PROJECT_SCOPE_TYPE,
+ native_id=project_id,
+ parent_scope_id=None,
+ display_name=name,
+ native_type="project",
+ is_private=1,
+ supports_threads=1,
+ metadata_json=json.dumps({}),
+ first_seen_at=now,
+ last_seen_at=now,
+ updated_at=now,
+ )
+ )
+ conn.execute(
+ scope_settings.insert().values(
+ scope_id=scope_id,
+ enabled=1,
+ role=None,
+ workdir=str(folder),
+ agent_name=None,
+ agent_backend=None,
+ agent_variant=None,
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=1,
+ settings_json=json.dumps({}),
+ created_at=now,
+ updated_at=now,
+ )
+ )
+ return _project_payload(conn, scope_id)
+
+
+def update_project(
+ conn: Connection,
+ project_id: str,
+ *,
+ display_name: Optional[str] = None,
+ folder_path: Optional[str] = None,
+) -> dict[str, Any]:
+ scope_id = _make_scope_id(project_id)
+ existing = conn.execute(select(scopes.c.id).where(scopes.c.id == scope_id)).scalar_one_or_none()
+ if existing is None:
+ raise LookupError(f"Project not found: {project_id}")
+
+ now = _utc_now_iso()
+ if display_name is not None:
+ cleaned = display_name.strip()
+ if cleaned:
+ conn.execute(
+ update(scopes)
+ .where(scopes.c.id == scope_id)
+ .values(display_name=cleaned, updated_at=now, last_seen_at=now)
+ )
+ if folder_path is not None:
+ folder = _resolve_folder(folder_path)
+ conn.execute(
+ update(scope_settings)
+ .where(scope_settings.c.scope_id == scope_id)
+ .values(workdir=str(folder), updated_at=now)
+ )
+
+ return _project_payload(conn, scope_id)
+
+
+def archive_project(conn: Connection, project_id: str) -> dict[str, Any]:
+ scope_id = _make_scope_id(project_id)
+ existing = conn.execute(select(scopes.c.id).where(scopes.c.id == scope_id)).scalar_one_or_none()
+ if existing is None:
+ raise LookupError(f"Project not found: {project_id}")
+
+ now = _utc_now_iso()
+ conn.execute(
+ update(scope_settings)
+ .where(scope_settings.c.scope_id == scope_id)
+ .values(enabled=0, updated_at=now)
+ )
+ conn.execute(
+ update(scopes)
+ .where(scopes.c.id == scope_id)
+ .values(updated_at=now)
+ )
+ return _project_payload(conn, scope_id)
+
+
+def _project_payload(conn: Connection, scope_id: str) -> dict[str, Any]:
+ row = conn.execute(
+ select(
+ scopes.c.id.label("scope_id"),
+ scopes.c.native_id,
+ scopes.c.display_name,
+ scopes.c.metadata_json,
+ scopes.c.first_seen_at,
+ scopes.c.last_seen_at,
+ scope_settings.c.enabled,
+ scope_settings.c.workdir,
+ )
+ .select_from(scopes.outerjoin(scope_settings, scope_settings.c.scope_id == scopes.c.id))
+ .where(scopes.c.id == scope_id)
+ ).mappings().first()
+ if row is None:
+ raise LookupError(f"Project not found: {scope_id}")
+ enabled = bool(row["enabled"]) if row["enabled"] is not None else True
+ try:
+ metadata = json.loads(row["metadata_json"] or "{}")
+ except json.JSONDecodeError:
+ metadata = {}
+ return {
+ "id": row["native_id"],
+ "scope_id": row["scope_id"],
+ "display_name": row["display_name"] or row["native_id"],
+ "folder_path": row["workdir"] or "",
+ "created_at": row["first_seen_at"],
+ "last_active_at": row["last_seen_at"],
+ "archived": not enabled,
+ "metadata": metadata,
+ }
+
+
+def make_directory(path: str) -> str:
+ """Create a directory (with parents) and return its absolute path.
+
+ Mirrors the folder picker's expectation that mkdir errors when the
+ target already exists — that keeps the UI from silently overwriting
+ a different folder when the user supplies an existing name.
+ """
+
+ folder = Path(path).expanduser().resolve()
+ folder.mkdir(parents=True, exist_ok=False)
+ return str(folder)
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index bb0ee0b24..25b994d4c 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -91,6 +91,11 @@ export type ApiContextType = {
getVersion: () => Promise<VersionInfo>;
doUpgrade: () => Promise<UpgradeResult>;
browseDirectory: (path: string, showHidden?: boolean) => Promise<{ ok: boolean; path?: string; parent?: string | null; dirs?: { name: string; path: string }[]; error?: string }>;
+ browseMkdir: (path: string) => Promise<{ path: string }>;
+ listProjects: (includeArchived?: boolean) => Promise<{ projects: WorkbenchProject[] }>;
+ 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>;
remoteAccessStatus: () => Promise<any>;
pairVibeCloudRemoteAccess: (payload: { backend_url: string; pairing_key: string; device_name?: string }) => Promise<any>;
startRemoteAccess: () => Promise<any>;
@@ -99,6 +104,20 @@ export type ApiContextType = {
signOut: () => Promise<{ ok: boolean }>;
};
+// Workbench project — a scope row with platform='avibe' / scope_type='project'.
+// ``folder_path`` mirrors ``scope_settings.workdir`` and is what Agent runs
+// pick up as their cwd.
+export type WorkbenchProject = {
+ id: string;
+ scope_id: string;
+ display_name: string;
+ folder_path: string;
+ created_at: string;
+ last_active_at: string | null;
+ archived: boolean;
+ metadata?: Record<string, unknown>;
+};
+
export type SessionInfo =
| { remote: false }
| { remote: true; authenticated: false }
@@ -606,6 +625,22 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
getVersion: () => getJson('/version'),
doUpgrade: () => postJson('/upgrade', {}),
browseDirectory: (path, showHidden) => postJson('/browse', { path, show_hidden: showHidden || false }),
+ browseMkdir: (path) => postJson('/api/browse/mkdir', { path }),
+ listProjects: (includeArchived) =>
+ getJson(`/api/projects${includeArchived ? '?include_archived=1' : ''}`),
+ createProject: (payload) => postJson('/api/projects', payload),
+ updateProject: async (projectId, payload) => {
+ const res = await apiFetch(`/api/projects/${encodeURIComponent(projectId)}`, {
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(payload),
+ });
+ if (!res.ok) {
+ await handleApiError(res, `PATCH /api/projects/${projectId}`);
+ }
+ return res.json();
+ },
+ archiveProject: (projectId) => deleteJson(`/api/projects/${encodeURIComponent(projectId)}`),
remoteAccessStatus: () => getJson('/remote-access/status'),
pairVibeCloudRemoteAccess: (payload) => postJson('/remote-access/vibe-cloud/pair', payload),
startRemoteAccess: () => postJson('/remote-access/start', {}),
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 19a42b3dc..d07934eea 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -2293,6 +2293,131 @@ def browse_directory():
)
+# =============================================================================
+# Workbench: Projects + folder-picker helpers
+# =============================================================================
+# Projects are stored as avibe scopes (platform='avibe', scope_type='project')
+# with the local folder path on ``scope_settings.workdir``. See
+# ``storage/projects_service.py`` for the CRUD semantics; the routes below
+# are a thin REST surface over the same service so the workbench UI and any
+# future CLI both round-trip the same shape.
+
+
+def _projects_engine():
+ from storage.db import create_sqlite_engine
+
+ return create_sqlite_engine()
+
+
[email protected]("/api/projects", methods=["GET"])
+def projects_list():
+ from storage import projects_service
+
+ include_archived = request.args.get("include_archived") in {"1", "true", "yes"}
+ engine = _projects_engine()
+ with engine.connect() as conn:
+ return jsonify({"projects": projects_service.list_projects(conn, include_archived=include_archived)})
+
+
[email protected]("/api/projects", methods=["POST"])
+def projects_create():
+ from storage import projects_service
+
+ payload = request.json or {}
+ folder_path = (payload.get("folder_path") or "").strip()
+ if not folder_path:
+ return jsonify({"error": "folder_path is required"}), 400
+ display_name = payload.get("display_name")
+ engine = _projects_engine()
+ try:
+ with engine.begin() as conn:
+ project = projects_service.create_project(conn, folder_path, display_name=display_name)
+ except (FileNotFoundError, NotADirectoryError) as err:
+ return jsonify({"error": str(err)}), 400
+ return jsonify(project), 201
+
+
[email protected]("/api/projects/<project_id>", methods=["GET"])
+def projects_get(project_id: str):
+ from storage import projects_service
+
+ engine = _projects_engine()
+ try:
+ with engine.connect() as conn:
+ return jsonify(projects_service.get_project(conn, project_id))
+ except LookupError as err:
+ return jsonify({"error": str(err)}), 404
+
+
[email protected]("/api/projects/<project_id>", methods=["PATCH"])
+def projects_update(project_id: str):
+ from storage import projects_service
+
+ payload = request.json or {}
+ display_name = payload.get("display_name")
+ folder_path = payload.get("folder_path")
+ if display_name is None and folder_path is None:
+ return jsonify({"error": "display_name or folder_path is required"}), 400
+ engine = _projects_engine()
+ try:
+ with engine.begin() as conn:
+ project = projects_service.update_project(
+ conn,
+ project_id,
+ display_name=display_name,
+ folder_path=folder_path,
+ )
+ except LookupError as err:
+ return jsonify({"error": str(err)}), 404
+ except (FileNotFoundError, NotADirectoryError) as err:
+ return jsonify({"error": str(err)}), 400
+ return jsonify(project)
+
+
[email protected]("/api/projects/<project_id>", methods=["DELETE"])
+def projects_archive(project_id: str):
+ """Soft-delete a project by marking ``scope_settings.enabled = 0``.
+
+ The scope row itself sticks around so any related agent_sessions /
+ messages keep their foreign-key target. Pass ``include_archived=1``
+ on the list endpoint to surface archived projects in the UI.
+ """
+
+ from storage import projects_service
+
+ engine = _projects_engine()
+ try:
+ with engine.begin() as conn:
+ project = projects_service.archive_project(conn, project_id)
+ except LookupError as err:
+ return jsonify({"error": str(err)}), 404
+ return jsonify(project)
+
+
[email protected]("/api/browse/mkdir", methods=["POST"])
+def browse_mkdir():
+ """Create a new folder for the directory picker.
+
+ Used by the workbench folder picker's "New Folder" button. Errors
+ when the target already exists so the UI never silently selects
+ someone else's data dir.
+ """
+
+ from storage import projects_service
+
+ payload = request.json or {}
+ path = (payload.get("path") or "").strip()
+ if not path:
+ return jsonify({"error": "path is required"}), 400
+ try:
+ resolved = projects_service.make_directory(path)
+ except FileExistsError:
+ return jsonify({"error": f"Folder already exists: {path}"}), 409
+ except OSError as err:
+ return jsonify({"error": str(err)}), 400
+ return jsonify({"path": resolved}), 201
+
+
# =============================================================================
# User & Bind Code Endpoints
# =============================================================================