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(workbench): stable project order with direct animated dragging (#1930)

Call White5a89f83afb8c
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index d6ca02e45..e80829065 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -51,11 +51,12 @@ jobs:
npm run typecheck:tests
npm test
- - name: Test model catalog browser interactions
+ - name: Test browser interactions
working-directory: ui
run: |
npx playwright install --with-deps chromium
npm run test:model-catalog
+ npm run test:project-order
build-linux-artifacts:
runs-on: ubuntu-latest
diff --git a/docs/plans/project-order.md b/docs/plans/project-order.md
new file mode 100644
index 000000000..27a155986
--- /dev/null
+++ b/docs/plans/project-order.md
@@ -0,0 +1,72 @@
+# Stable Project Order
+
+## Contract
+
+Project navigation retains its order independently of activity, names, or
+session state. Without a saved order, projects follow creation time ascending
+with their stable id as the tie-breaker. Newly created projects append. Saved
+positions survive archiving and restoration. Creation appends to the same saved
+order in its write transaction, independently of timestamp precision or id values.
+
+The existing project service owns the order in `state_meta` under
+`workbench.project_order.v1`. `PUT /api/projects/order` accepts `order` and
+`expected_order`, both arrays of visible active project ids. The new order is
+a permutation of the baseline. A changed baseline returns 409. Instance
+members and owners may reorder; hidden and archived projects keep their slots.
+Responses contain the authorized project list in navigation order. Generic
+`GET /api/projects` retains recency order; only navigation bootstrap and the
+reorder response opt into saved positions. Consumers choosing a default project
+from the navigation tree select by recency explicitly. `projects.changed`
+broadcasts only an invalidation, never private project ids.
+
+Desktop and mobile share one sortable-list component. The existing project
+header activates dragging; it has no additional handle or toolbar. Touch uses
+a deliberate hold, allowing an ordinary swipe to scroll. Click/tap still
+expands. The dragged project lifts, neighbors animate into their new slots,
+and release animates into the optimistically updated order. Escape
+and touch cancellation abandon the move. Keyboard access uses the same header.
+Reduced-motion preferences disable decorative transitions.
+
+## Verification
+
+- [x] Storage: stable default, saved order, stale-write rejection, visibility.
+- [x] Shared provider: optimistic save, failure recovery, incoming refreshes.
+- [x] Desktop and mobile: click, scroll, drag, cancellation, animation.
+- [x] Focused tests and production UI build.
+- [x] Final lint gate; no new violations or suppressions.
+- [ ] Installed-environment regression: local Incus daemon unavailable.
+
+Run `npm run test:project-order` from `ui/` for the hermetic browser suite.
+It mounts the real sidebar, mobile page, API client, and project provider with
+fixture-only transport. Desktop and mobile-emulated Chromium cover persistence,
+cross-page invalidation, expanded projects, keyboard cancellation, touch scroll,
+touch cancellation, and reduced motion. Storage tests exercise the real HTTP
+route and SQLite persistence independently of the browser fixture.
+
+Implementation uses dnd-kit for touch activation, collision detection,
+auto-scrolling, keyboard movement, and sortable transforms. It is recorded in
+the UI manifest and lockfile; existing layout and visual tokens are reused.
+
+## Review Inventory
+
+Head `5c7ef040a3`, review `5128930144`: three findings, one reviewed head.
+Root-cause classes are the second SSE visibility gate, timestamp-based insertion
+ordering, and untranslated API fallback messages. No repeated-class threshold
+has been reached. The scoped fixes use the existing global-invalidation path
+with an empty-payload policy, the existing order record during creation, and
+the backend translation catalogs. Regression tests cover the real SSE generator
+for every non-owner instance role, creation under a fixed/backwards clock with
+adversarial ids, and every error branch in both supported languages.
+
+Head `caaa2b7e02`, review `5129127836`: one finding, two findings-bearing heads
+in total. The new class is navigation ordering leaking into operation defaults;
+none of the first head's three classes recurred. All 17 exact-head lint checks
+passed and the first three threads are resolved. The orchestrator inspected
+both list routes and all first-project consumers: Skills uses the generic API,
+Files and FilePicker use the navigation provider, and new-session creation
+already explicitly sorts by recency. The smallest complete fix restores generic
+list recency, opts navigation reads into saved order, and reuses the new-session
+recency helper for both file surfaces. This preserves the storage/API payload
+contract without an architecture or data-model rewrite. HTTP and rendered
+consumer tests prove navigation permutations cannot change operation defaults,
+while explicit picker paths and home-directory fallbacks retain precedence.
diff --git a/storage/projects_service.py b/storage/projects_service.py
index d81648838..fe7c89d47 100644
--- a/storage/projects_service.py
+++ b/storage/projects_service.py
@@ -19,11 +19,12 @@ from pathlib import Path
from typing import Any, Mapping, Optional
from sqlalchemy import select, update
+from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from sqlalchemy.engine import Connection
from storage.agent_session_rows import reserve_write_lock
from storage import project_access_service
-from storage.models import agents, scope_settings, scopes
+from storage.models import agents, scope_settings, scopes, state_meta
from vibe.authorization import (
AuthorizationContext,
require_instance_role,
@@ -32,6 +33,42 @@ from vibe.authorization import (
PROJECT_PLATFORM = "avibe"
PROJECT_SCOPE_TYPE = "project"
+PROJECT_ORDER_KEY = "workbench.project_order.v1"
+
+
+class ProjectOrderConflict(ValueError):
+ """The visible order changed since the client began its drag."""
+
+
+def _saved_project_order(conn: Connection) -> list[str]:
+ raw = conn.execute(select(state_meta.c.value_json).where(state_meta.c.key == PROJECT_ORDER_KEY)).scalar_one_or_none()
+ try:
+ order = json.loads(raw) if raw else []
+ except (TypeError, json.JSONDecodeError):
+ return []
+ return list(dict.fromkeys(item for item in order if isinstance(item, str))) if isinstance(order, list) else []
+
+
+def _complete_project_order(conn: Connection) -> list[str]:
+ all_ids = conn.execute(
+ select(scopes.c.native_id)
+ .where(scopes.c.platform == PROJECT_PLATFORM, scopes.c.scope_type == PROJECT_SCOPE_TYPE)
+ .order_by(scopes.c.first_seen_at.asc(), scopes.c.id.asc())
+ ).scalars().all()
+ known = set(all_ids)
+ saved = [project_id for project_id in _saved_project_order(conn) if project_id in known]
+ saved_set = set(saved)
+ return saved + [project_id for project_id in all_ids if project_id not in saved_set]
+
+
+def _save_project_order(conn: Connection, order: list[str]) -> None:
+ statement = sqlite_insert(state_meta).values(
+ key=PROJECT_ORDER_KEY, value_json=json.dumps(order), 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},
+ ))
def _utc_now_iso() -> str:
@@ -284,9 +321,10 @@ def list_projects(
conn: Connection,
*,
include_archived: bool = False,
+ navigation_order: bool = False,
authorization_context: AuthorizationContext | Mapping[str, Any] | None = None,
) -> list[dict[str, Any]]:
- """Return all avibe projects sorted by recency, optionally including archived ones."""
+ """Return projects by recency unless a navigation consumer requests saved order."""
query = (
select(*_PROJECT_COLUMNS)
@@ -295,7 +333,10 @@ def list_projects(
.outerjoin(agents, agents.c.name == scope_settings.c.agent_name)
)
.where(scopes.c.platform == PROJECT_PLATFORM, scopes.c.scope_type == PROJECT_SCOPE_TYPE)
- .order_by(scopes.c.last_seen_at.desc())
+ .order_by(
+ scopes.c.first_seen_at.asc() if navigation_order else scopes.c.last_seen_at.desc(),
+ scopes.c.id.asc(),
+ )
)
rows = conn.execute(query).mappings().all()
out: list[dict[str, Any]] = []
@@ -305,12 +346,46 @@ def list_projects(
continue
out.append(_project_dict(row))
context = require_instance_role(authorization_context, "viewer")
+ if navigation_order:
+ positions = {project_id: index for index, project_id in enumerate(_saved_project_order(conn))}
+ out.sort(key=lambda project: positions.get(project["id"], len(positions)))
return [
_project_for_context(conn, context, project)
for project in project_access_service.filter_accessible_projects(conn, context, out)
]
+def reorder_projects(
+ conn: Connection,
+ order: Any,
+ *,
+ expected_order: Any,
+ authorization_context: AuthorizationContext | Mapping[str, Any] | None = None,
+) -> list[dict[str, Any]]:
+ """Reorder visible active projects while preserving every other project's slot."""
+ context = require_instance_role(authorization_context, "member")
+ for ids in (order, expected_order):
+ if not isinstance(ids, list) or not all(isinstance(item, str) for item in ids):
+ raise ValueError("Project order must be a list of project ids.")
+ if len(ids) != len(set(ids)):
+ raise ValueError("Project order must not contain duplicate ids.")
+ if set(order) != set(expected_order):
+ raise ValueError("Project order must contain the same projects as its baseline.")
+ reserve_write_lock(conn)
+ visible = list_projects(conn, navigation_order=True, authorization_context=context)
+ if expected_order != [project["id"] for project in visible]:
+ raise ProjectOrderConflict("Project order changed. Refresh the list and try again.")
+
+ # Keep hidden and archived slots; a restricted caller can only permute the
+ # projects they can currently see. New projects follow all existing slots.
+ complete = _complete_project_order(conn)
+ visible_ids = set(order)
+ replacement = iter(order)
+ merged = [next(replacement) if project_id in visible_ids else project_id for project_id in complete]
+ _save_project_order(conn, merged)
+ return list_projects(conn, navigation_order=True, authorization_context=context)
+
+
def _require_visible_project(
conn: Connection,
context: AuthorizationContext,
@@ -398,6 +473,7 @@ def create_project(
context = require_instance_role(authorization_context, "member")
folder = _resolve_folder(folder_path)
+ reserve_write_lock(conn)
now = _utc_now_iso()
existing = _find_project_by_workdir(conn, context, str(folder))
@@ -409,7 +485,7 @@ def create_project(
.where(scope_settings.c.scope_id == scope_id)
.values(enabled=1, updated_at=now)
)
- # Treat (re)opening as recent activity so the project sorts to the top.
+ # Keep the activity timestamp for consumers outside the fixed project tree.
conn.execute(
update(scopes)
.where(scopes.c.id == scope_id)
@@ -420,6 +496,7 @@ def create_project(
project_id = _new_project_id()
scope_id = _make_scope_id(project_id)
name = (display_name or folder.name).strip() or project_id
+ order = _complete_project_order(conn)
conn.execute(
scopes.insert().values(
@@ -455,6 +532,7 @@ def create_project(
updated_at=now,
)
)
+ _save_project_order(conn, [*order, project_id])
return _project_for_context(conn, context, _project_payload(conn, scope_id))
diff --git a/tests/test_projects_service.py b/tests/test_projects_service.py
index 3074285c7..9c2cfac63 100644
--- a/tests/test_projects_service.py
+++ b/tests/test_projects_service.py
@@ -8,6 +8,8 @@ project is restored after archiving, without a dedicated unarchive endpoint.
from __future__ import annotations
+import asyncio
+import json
from pathlib import Path
import pytest
@@ -23,7 +25,7 @@ from storage import (
)
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
-from storage.models import scope_settings, scopes
+from storage.models import scope_settings, scopes, state_meta
from vibe.authorization import AuthorizationContext, InstanceAuthorizationError
@@ -46,6 +48,222 @@ def _ensure_agent(name: str, backend: str) -> str:
store.close()
+def _ordered_projects(conn, tmp_path, count=4):
+ rows = []
+ for index in range(count):
+ folder = tmp_path / f"ordered-{index}"
+ folder.mkdir()
+ row = projects_service.create_project(conn, str(folder))
+ conn.execute(scopes.update().where(scopes.c.id == row["scope_id"]).values(
+ first_seen_at=f"2026-01-0{index + 1}T00:00:00Z"
+ ))
+ rows.append(row)
+ return rows
+
+
+def test_project_creation_appends_independently_of_clock_and_random_id(engine, tmp_path, monkeypatch):
+ clock = "2026-01-01T00:00:00Z"
+ monkeypatch.setattr(projects_service, "_utc_now_iso", lambda: clock)
+ generated = iter(["proj_z", "proj_a", "proj_m"])
+ monkeypatch.setattr(projects_service, "_new_project_id", lambda: next(generated))
+ created = []
+ for index in range(3):
+ folder = tmp_path / f"same-second-{index}"
+ folder.mkdir()
+ with engine.begin() as conn:
+ created.append(projects_service.create_project(conn, str(folder))["id"])
+ with engine.connect() as conn:
+ assert [p["id"] for p in projects_service.list_projects(conn, navigation_order=True)] == created
+ # Even a backwards wall-clock adjustment cannot insert the next row ahead.
+ if index == 1:
+ clock = "2025-12-31T23:59:59Z"
+
+
+def test_first_creation_preserves_legacy_project_order(engine, tmp_path):
+ with engine.begin() as conn:
+ rows = _ordered_projects(conn, tmp_path)
+ ids = [row["id"] for row in rows]
+ conn.execute(state_meta.delete().where(state_meta.c.key == projects_service.PROJECT_ORDER_KEY))
+ assert [p["id"] for p in projects_service.list_projects(conn, navigation_order=True)] == ids
+ folder = tmp_path / "post-upgrade"
+ folder.mkdir()
+ new = projects_service.create_project(conn, str(folder))
+ assert [p["id"] for p in projects_service.list_projects(conn, navigation_order=True)] == [*ids, new["id"]]
+
+
+def test_project_positions_survive_activity_metadata_and_restoration(engine, tmp_path):
+ with engine.begin() as conn:
+ rows = _ordered_projects(conn, tmp_path)
+ ids = [row["id"] for row in rows]
+ assert [p["id"] for p in projects_service.list_projects(conn, navigation_order=True)] == ids
+ for row in rows:
+ projects_service.update_project(conn, row["id"], display_name="Renamed")
+ projects_service.create_project(conn, row["folder_path"])
+ assert [p["id"] for p in projects_service.list_projects(conn, navigation_order=True)] == ids
+ saved = list(reversed(ids))
+ projects_service.reorder_projects(conn, saved, expected_order=ids)
+ with engine.begin() as conn:
+ projects_service.archive_project(conn, rows[1]["id"])
+ assert [p["id"] for p in projects_service.list_projects(conn, navigation_order=True)] == [i for i in saved if i != ids[1]]
+ projects_service.create_project(conn, rows[1]["folder_path"])
+ assert [p["id"] for p in projects_service.list_projects(conn, navigation_order=True)] == saved
+ fresh = tmp_path / "fresh-project"
+ fresh.mkdir()
+ new = projects_service.create_project(conn, str(fresh))
+ assert [p["id"] for p in projects_service.list_projects(conn, navigation_order=True)] == [*saved, new["id"]]
+
+
+def test_project_reorder_preserves_hidden_and_archived_slots(engine, tmp_path):
+ with engine.begin() as conn:
+ rows = _ordered_projects(conn, tmp_path)
+ ids = [row["id"] for row in rows]
+ _restrict_project_to(conn, ids[1], "[email protected]")
+ projects_service.archive_project(conn, ids[2])
+ context = _acl_context("member", email="[email protected]")
+ result = projects_service.reorder_projects(
+ conn, [ids[3], ids[0]], expected_order=[ids[0], ids[3]], authorization_context=context
+ )
+ assert [p["id"] for p in result] == [ids[3], ids[0]]
+ assert [p["id"] for p in projects_service.list_projects(conn, include_archived=True, navigation_order=True)] == [
+ ids[3], ids[1], ids[2], ids[0]
+ ]
+
+
+def test_project_reorder_rejects_stale_view_without_changing_saved_order(engine, tmp_path):
+ with engine.begin() as conn:
+ ids = [row["id"] for row in _ordered_projects(conn, tmp_path)]
+ saved = list(reversed(ids))
+ projects_service.reorder_projects(conn, saved, expected_order=ids)
+ with pytest.raises(projects_service.ProjectOrderConflict):
+ projects_service.reorder_projects(conn, ids[1:] + ids[:1], expected_order=ids)
+ assert [p["id"] for p in projects_service.list_projects(conn, navigation_order=True)] == saved
+
+
[email protected]("role", ["viewer", "editor"])
+def test_project_reorder_requires_project_management(engine, tmp_path, role):
+ with engine.begin() as conn:
+ ids = [row["id"] for row in _ordered_projects(conn, tmp_path)]
+ with pytest.raises(InstanceAuthorizationError):
+ projects_service.reorder_projects(conn, ids[::-1], expected_order=ids, authorization_context=_remote_context(role))
+ assert [p["id"] for p in projects_service.list_projects(conn, navigation_order=True)] == ids
+
+
[email protected]("order,expected", [(None, []), ([1], [1]), (["x", "x"], ["x", "x"]), (["x"], []), ([], ["x"])])
+def test_project_reorder_accepts_only_a_permutation(engine, order, expected):
+ with engine.begin() as conn:
+ with pytest.raises(ValueError):
+ projects_service.reorder_projects(conn, order, expected_order=expected)
+
+
+def test_project_reorder_http_roundtrip_and_invalidation(engine, tmp_path, monkeypatch):
+ from vibe.ui_server import app
+ from tests.ui_server_test_helpers import csrf_headers
+
+ events = []
+ monkeypatch.setattr("vibe.sse_broker.broker.publish", lambda *args: events.append(args))
+ with engine.begin() as conn:
+ ids = [row["id"] for row in _ordered_projects(conn, tmp_path)]
+ client = app.test_client()
+ response = client.put("/api/projects/order", json={"order": ids[::-1], "expected_order": ids}, headers=csrf_headers(client))
+ assert response.status_code == 200
+ assert [p["id"] for p in response.get_json()["projects"]] == ids[::-1]
+ assert ("projects.changed", {}) in events
+ bootstrap = client.get("/api/workbench/projects-bootstrap").get_json()
+ assert [p["id"] for p in bootstrap["projects"]] == ids[::-1]
+ stale = client.put("/api/projects/order", json={"order": ids, "expected_order": ids}, headers=csrf_headers(client))
+ assert stale.status_code == 409
+ malformed = client.put("/api/projects/order", json=["project"], headers=csrf_headers(client))
+ assert malformed.status_code == 400
+
+
[email protected]("include_archived", [False, True])
[email protected]("reordered", [False, True])
+def test_generic_project_list_retains_recency_independently_of_navigation(engine, tmp_path, include_archived, reordered):
+ from vibe.ui_server import app
+
+ with engine.begin() as conn:
+ rows = _ordered_projects(conn, tmp_path)
+ ids = [row["id"] for row in rows]
+ for row, day in zip(rows, [2, 4, 1, 3]):
+ conn.execute(scopes.update().where(scopes.c.id == row["scope_id"]).values(
+ last_seen_at=f"2026-02-0{day}T00:00:00Z"
+ ))
+ navigation = [ids[2], ids[0], ids[3], ids[1]] if reordered else ids
+ if reordered:
+ projects_service.reorder_projects(conn, navigation, expected_order=ids)
+ projects_service.archive_project(conn, ids[3])
+
+ client = app.test_client()
+ suffix = "?include_archived=1" if include_archived else ""
+ generic = client.get(f"/api/projects{suffix}").get_json()["projects"]
+ tree = client.get(f"/api/workbench/projects-bootstrap{suffix}").get_json()["projects"]
+ expected_navigation = navigation if include_archived else [p for p in navigation if p != ids[3]]
+ assert [p["id"] for p in tree] == expected_navigation
+ assert generic == sorted(tree, key=lambda p: p["last_active_at"], reverse=True)
+ assert generic[0]["id"] == ids[1]
+
+ with engine.begin() as conn:
+ projects_service.create_project(conn, rows[0]["folder_path"])
+ assert client.get(f"/api/projects{suffix}").get_json()["projects"][0]["id"] == ids[0]
+ assert [p["id"] for p in client.get(f"/api/workbench/projects-bootstrap{suffix}").get_json()["projects"]] == expected_navigation
+
+
[email protected]("lang", ["en", "zh"])
[email protected]("payload,key,code,status", [
+ (["invalid"], "orderInvalid", "invalid_project_order", 400),
+ ({}, "orderInvalid", "invalid_project_order", 400),
+ ({"order": [1], "expected_order": [1]}, "orderInvalid", "invalid_project_order", 400),
+ ({"order": ["x", "x"], "expected_order": ["x", "x"]}, "orderInvalid", "invalid_project_order", 400),
+ ({"order": ["x"], "expected_order": []}, "orderInvalid", "invalid_project_order", 400),
+ ({"order": [], "expected_order": []}, "orderConflict", "project_order_conflict", 409),
+])
+def test_project_order_api_errors_keep_codes_and_localized_fallbacks(engine, tmp_path, lang, payload, key, code, status):
+ from tests.ui_server_test_helpers import csrf_headers
+ from vibe.i18n import t
+ from vibe.ui_server import app
+
+ with engine.begin() as conn:
+ _ordered_projects(conn, tmp_path, count=1)
+ client = app.test_client()
+ response = client.put("/api/projects/order", json=payload, headers={
+ **csrf_headers(client), "Accept-Language": lang,
+ })
+ assert response.status_code == status
+ expected = t(f"projects.{key}", lang)
+ assert expected != f"projects.{key}"
+ assert t(f"projects.{key}", "en") != t(f"projects.{key}", "zh")
+ assert response.get_json()["error"] == {"code": code, "message": expected}
+
+
[email protected]("role", ["viewer", "editor", "member"])
+def test_remote_project_order_invalidation_reaches_the_real_event_stream(role):
+ from vibe import ui_server
+ from vibe.sse_broker import broker
+ from vibe.ui_compat import g
+
+ async def collect():
+ with ui_server.app.test_request_context("/api/events"):
+ g.authorization_context = _remote_context(role)
+ response = await ui_server.workbench_events()
+ iterator = response.body_iterator.__aiter__()
+ try:
+ for _ in range(3):
+ await iterator.__anext__()
+ broker.publish("projects.changed", {"project_ids": ["hidden-project"]})
+ broker.publish("projects.changed", {})
+ return await asyncio.wait_for(iterator.__anext__(), timeout=1)
+ finally:
+ await iterator.aclose()
+
+ frame = asyncio.run(collect())
+ if isinstance(frame, bytes):
+ frame = frame.decode("utf-8")
+ assert "event: projects.changed\n" in frame
+ assert "hidden-project" not in frame
+ data = next(line.removeprefix("data: ") for line in frame.splitlines() if line.startswith("data: "))
+ assert json.loads(data)["data"] == {}
+
+
def _remote_context(role: str) -> AuthorizationContext:
return AuthorizationContext(
instance_role=role,
diff --git a/ui/e2e/project-order/fixture.html b/ui/e2e/project-order/fixture.html
new file mode 100644
index 000000000..a57a154b0
--- /dev/null
+++ b/ui/e2e/project-order/fixture.html
@@ -0,0 +1,2 @@
+<!doctype html>
+<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Project order regression</title></head><body><div id="root"></div><script type="module" src="./fixture.tsx"></script></body></html>
diff --git a/ui/e2e/project-order/fixture.tsx b/ui/e2e/project-order/fixture.tsx
new file mode 100644
index 000000000..c28cb64c0
--- /dev/null
+++ b/ui/e2e/project-order/fixture.tsx
@@ -0,0 +1,85 @@
+import { createRoot } from 'react-dom/client';
+import { createHashRouter, RouterProvider } from 'react-router-dom';
+import { ApiProvider, type WorkbenchProject } from '../../src/context/ApiContext';
+import { WorkbenchProjectsProvider } from '../../src/context/WorkbenchProjectsProvider';
+import { WorkbenchInboxContext } from '../../src/context/WorkbenchInboxContext';
+import { InstanceAuthorizationContext } from '../../src/context/InstanceAuthorizationContext';
+import { ToastContext } from '../../src/context/ToastContext';
+import { WindowManagerContext, type WindowManagerValue } from '../../src/context/WindowManagerContext';
+import { UnsavedChangesProvider } from '../../src/context/UnsavedChangesProvider';
+import { WorkbenchSidebar } from '../../src/components/workbench/WorkbenchSidebar';
+import { ProjectsPage } from '../../src/components/workbench/ProjectsPage';
+import { OWNER_INSTANCE_CAPABILITIES } from '../../src/lib/sessionInfo';
+import '../../src/i18n';
+import '../../src/index.css';
+
+const noop = () => {};
+const names = ['Avibe', 'chainbot', 'Research', 'Documents', 'Design', 'Infrastructure', 'Sandbox', 'Archive'];
+const projects: WorkbenchProject[] = names.map((display_name, index) => ({
+ id: `project-${index}`, scope_id: `scope-${index}`, display_name, folder_path: `/fixture/${index}`,
+ created_at: `2026-01-0${index + 1}T00:00:00Z`, last_active_at: null, archived: false,
+ capabilities: { can_chat: true, has_folder: true },
+}));
+const storageKey = 'project-order-fixture';
+const readProjects = () => {
+ const saved = JSON.parse(localStorage.getItem(storageKey) ?? 'null') as string[] | null;
+ return saved ? saved.map((id) => projects.find((p) => p.id === id)!) : projects;
+};
+const streams = new Set<EventTarget>();
+class FixtureEvents extends EventTarget {
+ readyState = 1;
+ constructor() { super(); streams.add(this); }
+ close() { streams.delete(this); this.readyState = 2; }
+}
+Object.defineProperty(window, 'EventSource', { value: FixtureEvents });
+const invalidate = () => streams.forEach((stream) => stream.dispatchEvent(new MessageEvent('projects.changed', {
+ data: JSON.stringify({ type: 'projects.changed', data: {} }),
+})));
+window.addEventListener('storage', (event) => { if (event.key === storageKey) invalidate(); });
+
+// Hermetic transport: the actual API client/provider and both real project
+// surfaces run here, but no request can reach a workstation Avibe service.
+window.fetch = async (input, init) => {
+ const url = new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url, location.origin);
+ const reply = (data: unknown, status = 200) => new Response(JSON.stringify(data), { status, headers: { 'Content-Type': 'application/json' } });
+ if (url.pathname === '/api/csrf-token') return reply({ csrf_token: 'fixture' });
+ if (url.pathname === '/api/projects/order') {
+ const payload = JSON.parse(String(init?.body));
+ if (JSON.stringify(payload.expected_order) !== JSON.stringify(readProjects().map((p) => p.id))) {
+ return reply({ code: 'project_order_conflict', error: 'stale' }, 409);
+ }
+ localStorage.setItem(storageKey, JSON.stringify(payload.order));
+ invalidate();
+ return reply({ projects: readProjects() });
+ }
+ if (url.pathname === '/api/projects' || url.pathname === '/api/workbench/projects-bootstrap') return reply({ projects: readProjects(), sessions: {} });
+ if (url.pathname === '/api/sessions') {
+ const projectId = url.searchParams.get('project_id');
+ return reply({ sessions: Array.from({ length: 8 }, (_, index) => ({
+ id: `${projectId}-session-${index}`, title: `Conversation ${index + 1}`, project_id: projectId,
+ scope_id: projects.find((p) => p.id === projectId)?.scope_id, status: 'active', agent_status: 'idle',
+ pinned: false, visibility: 'foreground', created_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:00:00Z',
+ last_active_at: '2026-01-01T00:00:00Z', metadata: {},
+ })), next_before_id: null });
+ }
+ return reply({});
+};
+
+export function Fixture() {
+ return <InstanceAuthorizationContext.Provider value={{
+ remote: false, instanceKind: null, instanceRole: 'owner',
+ capabilities: { ...OWNER_INSTANCE_CAPABILITIES, can_read_instance: false },
+ }}><ToastContext.Provider value={{ showToast: noop }}><ApiProvider><UnsavedChangesProvider>
+ <WorkbenchProjectsProvider><WorkbenchInboxContext.Provider value={{
+ inboxSessions: [], unreadBySession: {}, totalUnread: 0, unreadSessions: 0, nextCursor: null,
+ loading: false, loadingMore: false, refresh: async () => {}, loadMore: async () => {},
+ markRead: async () => {}, activateFeed: () => noop,
+ }}><WindowManagerContext.Provider value={{ focusedId: null, focusCanvas: noop, openApp: noop } as unknown as WindowManagerValue}>
+ <div className="flex h-dvh overflow-hidden bg-background text-foreground">
+ <aside className="hidden h-full w-64 shrink-0 border-r border-border md:flex" data-testid="desktop-tree"><WorkbenchSidebar /></aside>
+ <main id="app-shell-scroll" className="min-h-0 min-w-0 flex-1 overflow-y-auto p-4 md:hidden" data-testid="mobile-tree"><ProjectsPage /></main>
+ </div>
+ </WindowManagerContext.Provider></WorkbenchInboxContext.Provider></WorkbenchProjectsProvider>
+ </UnsavedChangesProvider></ApiProvider></ToastContext.Provider></InstanceAuthorizationContext.Provider>;
+}
+createRoot(document.getElementById('root')!).render(<RouterProvider router={createHashRouter([{ path: '*', element: <Fixture /> }])} />);
diff --git a/ui/e2e/project-order/order.spec.ts b/ui/e2e/project-order/order.spec.ts
new file mode 100644
index 000000000..b41d585ab
--- /dev/null
+++ b/ui/e2e/project-order/order.spec.ts
@@ -0,0 +1,154 @@
+import { expect, test, type Page } from '@playwright/test';
+
+const tree = (page: Page) => page.getByTestId('desktop-tree').or(page.getByTestId('mobile-tree')).filter({ visible: true });
+const rows = (page: Page) => tree(page).locator('[data-project-id]');
+const header = (page: Page, index: number) => rows(page).nth(index).locator('.project-drag-header');
+const ids = (page: Page) => rows(page).evaluateAll((elements) => elements.map((el) => el.getAttribute('data-project-id')));
+
+test.beforeEach(async ({ page }) => {
+ await page.goto('/e2e/project-order/fixture.html');
+ await expect(rows(page)).toHaveCount(8);
+});
+
+test('header click expands; a direct drag animates neighbors and persists across reload', async ({ page, isMobile }, testInfo) => {
+ await header(page, 0).click();
+ await expect(rows(page).first().getByText('Conversation 1', { exact: true })).toBeVisible();
+ await header(page, 0).click();
+ const first = (await header(page, 0).boundingBox())!;
+ const third = (await header(page, 2).boundingBox())!;
+ const x = first.x + first.width / 2;
+ const startY = first.y + first.height / 2;
+ const endY = third.y + third.height / 2;
+ const cdp = isMobile ? await page.context().newCDPSession(page) : null;
+ if (cdp) {
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y: startY }] });
+ await expect(page.locator('[data-project-drag-preview]')).toBeVisible();
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x, y: endY }] });
+ } else {
+ await page.mouse.move(x, startY);
+ await page.mouse.down();
+ await page.mouse.move(x, endY, { steps: 12 });
+ }
+ await expect(page.locator('[data-project-drag-preview]')).toBeVisible();
+ await expect.poll(() => rows(page).nth(1).evaluate((el) => getComputedStyle(el).transform)).not.toBe('none');
+ expect(await rows(page).nth(1).evaluate((el) => getComputedStyle(el).transitionDuration)).toBe('0.22s');
+ await page.screenshot({ path: testInfo.outputPath('project-drag.png'), scale: 'css' });
+ if (cdp) await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
+ else await page.mouse.up();
+ await expect.poll(() => ids(page)).toEqual(['project-1', 'project-2', 'project-0', 'project-3', 'project-4', 'project-5', 'project-6', 'project-7']);
+ await expect(page.locator('[data-project-drag-preview]')).toHaveCount(0);
+ await expect(rows(page).nth(2).getByText('Conversation 1', { exact: true })).not.toBeVisible();
+ await page.reload();
+ await expect.poll(() => ids(page)).toEqual(['project-1', 'project-2', 'project-0', 'project-3', 'project-4', 'project-5', 'project-6', 'project-7']);
+ await page.screenshot({ path: testInfo.outputPath('project-order.png'), scale: 'css' });
+});
+
+test('keyboard movement and cancellation use the existing header', async ({ page }) => {
+ const original = await ids(page);
+ await header(page, 0).focus();
+ // The sensor installs document listeners on the next task after pickup.
+ await page.keyboard.press('Space', { delay: 80 });
+ await expect(page.locator('[data-project-drag-preview]')).toBeVisible();
+ await page.keyboard.press('ArrowDown');
+ await page.keyboard.press('Escape');
+ await expect(page.locator('[data-project-drag-preview]')).toHaveCount(0);
+ expect(await ids(page)).toEqual(original);
+ await header(page, 0).focus();
+ await page.keyboard.press('Space', { delay: 80 });
+ await expect(page.locator('[data-project-drag-preview]')).toBeVisible();
+ await page.keyboard.press('ArrowDown');
+ await expect.poll(() => rows(page).nth(1).evaluate((el) => getComputedStyle(el).transform)).not.toBe('matrix(1, 0, 0, 1, 0, 0)');
+ await page.keyboard.press('Space');
+ await expect.poll(() => ids(page)).toEqual([original[1], original[0], ...original.slice(2)]);
+});
+
+test('an expanded project carries its sessions through a drag', async ({ page, isMobile }) => {
+ await header(page, 0).click();
+ await expect(rows(page).first().getByText('Conversation 1', { exact: true })).toBeVisible();
+ const source = (await header(page, 0).boundingBox())!;
+ const target = (await header(page, 1).boundingBox())!;
+ const x = source.x + source.width / 2;
+ const y = source.y + source.height / 2;
+ const dest = target.y + target.height / 2;
+ if (isMobile) {
+ const cdp = await page.context().newCDPSession(page);
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y }] });
+ await expect(page.locator('[data-project-drag-preview]')).toBeVisible();
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x, y: dest }] });
+ await expect.poll(() => rows(page).nth(1).evaluate((el) => getComputedStyle(el).transform)).not.toBe('none');
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
+ } else {
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ await page.mouse.move(x, dest, { steps: 15 });
+ await page.mouse.up();
+ }
+ await expect.poll(async () => (await ids(page)).indexOf('project-0')).toBe(1);
+ await expect(tree(page).locator('[data-project-id="project-0"]').getByText('Conversation 1', { exact: true })).toBeVisible();
+});
+
+test('a normal touch swipe scrolls without changing order', async ({ page, isMobile }) => {
+ test.skip(!isMobile);
+ await header(page, 0).click();
+ await expect(rows(page).first().getByText('Conversation 1', { exact: true })).toBeVisible();
+ const original = await ids(page);
+ const box = (await header(page, 1).boundingBox())!;
+ const x = box.x + box.width / 2;
+ const y = box.y + box.height / 2;
+ const cdp = await page.context().newCDPSession(page);
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y }] });
+ for (let offset = 20; offset <= 180; offset += 20) {
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x, y: y - offset }] });
+ }
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
+ await expect.poll(() => page.locator('#app-shell-scroll').evaluate((el) => el.scrollTop)).toBeGreaterThan(40);
+ await expect(page.locator('[data-project-drag-preview]')).toHaveCount(0);
+ expect(await ids(page)).toEqual(original);
+});
+
+test('touch cancellation abandons the move without expanding the project', async ({ page, isMobile }) => {
+ test.skip(!isMobile);
+ const original = await ids(page);
+ const first = (await header(page, 0).boundingBox())!;
+ const second = (await header(page, 1).boundingBox())!;
+ const x = first.x + first.width / 2;
+ const cdp = await page.context().newCDPSession(page);
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y: first.y + first.height / 2 }] });
+ await expect(page.locator('[data-project-drag-preview]')).toBeVisible();
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x, y: second.y + second.height / 2 }] });
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchCancel', touchPoints: [] });
+ await expect(page.locator('[data-project-drag-preview]')).toHaveCount(0);
+ expect(await ids(page)).toEqual(original);
+ await expect(rows(page).first().getByText('Conversation 1', { exact: true })).not.toBeVisible();
+});
+
+test('reduced motion disables pickup, keyboard movement, and neighbor animations', async ({ page }) => {
+ await page.emulateMedia({ reducedMotion: 'reduce' });
+ await page.reload();
+ await expect(rows(page)).toHaveCount(8);
+ await header(page, 0).focus();
+ await page.keyboard.press('Space', { delay: 80 });
+ const preview = page.locator('[data-project-drag-preview]');
+ await expect(preview).toBeVisible();
+ await page.keyboard.press('ArrowDown');
+ await expect.poll(() => rows(page).nth(1).evaluate((el) => getComputedStyle(el).transform)).toMatch(/-\d/);
+ expect(await rows(page).nth(1).evaluate((el) => getComputedStyle(el).transitionDuration)).toBe('0s');
+ expect(await preview.evaluate((el) => getComputedStyle(el).animationName)).toBe('none');
+ expect(await preview.evaluate((el) => getComputedStyle(el.parentElement!).transitionDuration)).toBe('0s');
+ await page.keyboard.press('Space');
+ await expect.poll(() => ids(page)).toEqual(['project-1', 'project-0', 'project-2', 'project-3', 'project-4', 'project-5', 'project-6', 'project-7']);
+});
+
+test('another open page receives the saved order without reloading', async ({ page, context }) => {
+ const other = await context.newPage();
+ await other.goto('/e2e/project-order/fixture.html');
+ await expect(rows(other)).toHaveCount(8);
+ await header(page, 0).focus();
+ await page.keyboard.press('Space', { delay: 80 });
+ await expect(page.locator('[data-project-drag-preview]')).toBeVisible();
+ await page.keyboard.press('ArrowDown');
+ await expect.poll(() => rows(page).nth(1).evaluate((el) => getComputedStyle(el).transform)).toMatch(/-\d/);
+ await page.keyboard.press('Space');
+ await expect.poll(() => ids(other)).toEqual(['project-1', 'project-0', 'project-2', 'project-3', 'project-4', 'project-5', 'project-6', 'project-7']);
+ await other.close();
+});
diff --git a/ui/e2e/project-order/tsconfig.json b/ui/e2e/project-order/tsconfig.json
new file mode 100644
index 000000000..04df74efc
--- /dev/null
+++ b/ui/e2e/project-order/tsconfig.json
@@ -0,0 +1,9 @@
+{
+ "extends": "../../tsconfig.app.json",
+ "compilerOptions": { "types": ["vite/client", "node"] },
+ "include": [
+ "*.ts", "*.tsx", "../../playwright.project-order.config.ts",
+ "../../src/context/WorkbenchProjectOrder.test.tsx", "../../agentation.d.ts"
+ ],
+ "exclude": []
+}
diff --git a/ui/package-lock.json b/ui/package-lock.json
index 5e17ea495..179c58eda 100644
--- a/ui/package-lock.json
+++ b/ui/package-lock.json
@@ -9,6 +9,9 @@
"version": "0.0.0",
"dependencies": {
"@dagrejs/dagre": "^1.1.8",
+ "@dnd-kit/core": "^6.3.1",
+ "@dnd-kit/sortable": "^10.0.0",
+ "@dnd-kit/utilities": "^3.2.2",
"@hpke/core": "^1.9.0",
"@hpke/dhkem-x25519": "^1.8.0",
"@lexical/react": "^0.45.0",
@@ -570,6 +573,60 @@
"node": ">17.0.0"
}
},
+ "node_modules/@dnd-kit/accessibility": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz",
+ "integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==",
+ "license": "MIT",
+ "dependencies": {
+ "tslib": "^2.0.0"
+ },
+ "peerDependencies": {
+ "react": ">=16.8.0"
+ }
+ },
+ "node_modules/@dnd-kit/core": {
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
+ "integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "@dnd-kit/accessibility": "^3.1.1",
+ "@dnd-kit/utilities": "^3.2.2",
+ "tslib": "^2.0.0"
+ },
+ "peerDependencies": {
+ "react": ">=16.8.0",
+ "react-dom": ">=16.8.0"
+ }
+ },
+ "node_modules/@dnd-kit/sortable": {
+ "version": "10.0.0",
+ "resolved": "https://registry.npmjs.org/@dnd-kit/sortable/-/sortable-10.0.0.tgz",
+ "integrity": "sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==",
+ "license": "MIT",
+ "dependencies": {
+ "@dnd-kit/utilities": "^3.2.2",
+ "tslib": "^2.0.0"
+ },
+ "peerDependencies": {
+ "@dnd-kit/core": "^6.3.0",
+ "react": ">=16.8.0"
+ }
+ },
+ "node_modules/@dnd-kit/utilities": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz",
+ "integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==",
+ "license": "MIT",
+ "dependencies": {
+ "tslib": "^2.0.0"
+ },
+ "peerDependencies": {
+ "react": ">=16.8.0"
+ }
+ },
"node_modules/@emnapi/core": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz",
diff --git a/ui/package.json b/ui/package.json
index 9a4576e1c..882e4c36d 100644
--- a/ui/package.json
+++ b/ui/package.json
@@ -21,12 +21,16 @@
"e2e:headed": "playwright test --headed",
"test:chat-paging": "tsc -p e2e/chat-paging/tsconfig.json --noEmit && playwright test --config playwright.chat-paging.config.ts",
"test:inbox-return": "tsc -p e2e/inbox-return/tsconfig.json --noEmit && playwright test --config playwright.inbox-return.config.ts",
+ "test:project-order": "tsc -p e2e/project-order/tsconfig.json --noEmit && playwright test --config playwright.project-order.config.ts",
"test:model-catalog": "tsc -p e2e/model-catalog/tsconfig.json --noEmit && playwright test --config playwright.model-catalog.config.ts",
"validate:catalog": "node scripts/validate-scenario-catalog.mjs",
"validate:theme": "node scripts/validate-theme.mjs"
},
"dependencies": {
"@dagrejs/dagre": "^1.1.8",
+ "@dnd-kit/core": "^6.3.1",
+ "@dnd-kit/sortable": "^10.0.0",
+ "@dnd-kit/utilities": "^3.2.2",
"@hpke/core": "^1.9.0",
"@hpke/dhkem-x25519": "^1.8.0",
"@lexical/react": "^0.45.0",
diff --git a/ui/playwright.project-order.config.ts b/ui/playwright.project-order.config.ts
new file mode 100644
index 000000000..2160888ec
--- /dev/null
+++ b/ui/playwright.project-order.config.ts
@@ -0,0 +1,19 @@
+import { defineConfig, devices } from '@playwright/test';
+
+export default defineConfig({
+ testDir: './e2e/project-order',
+ outputDir: './e2e/.artifacts/project-order',
+ workers: 1,
+ retries: 0,
+ use: { baseURL: 'http://127.0.0.1:5208', locale: 'en-US', trace: 'retain-on-failure' },
+ webServer: {
+ command: 'npm run dev -- --host 127.0.0.1 --port 5208 --strictPort',
+ env: { VIBE_UI_BACKEND: 'http://127.0.0.1:9' },
+ url: 'http://127.0.0.1:5208/e2e/project-order/fixture.html',
+ reuseExistingServer: true,
+ },
+ projects: [
+ { name: 'desktop', use: { ...devices['Desktop Chrome'] } },
+ { name: 'mobile', use: { ...devices['iPhone 13'], browserName: 'chromium' } },
+ ],
+});
diff --git a/ui/src/components/workbench/AppsFileBrowserPage.tsx b/ui/src/components/workbench/AppsFileBrowserPage.tsx
index 233669b27..ca5d5eeb8 100644
--- a/ui/src/components/workbench/AppsFileBrowserPage.tsx
+++ b/ui/src/components/workbench/AppsFileBrowserPage.tsx
@@ -39,6 +39,7 @@ import { useRouteSurfaceWindowEvent } from '../../lib/routeSurfaceActivity';
import clsx from 'clsx';
import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
+import { sortProjectsByRecent } from '../../lib/projectOrder';
import { useWindowManager } from '../../context/WindowManagerContext';
import { useStandaloneAppTab } from '../../context/StandaloneAppTabContext';
import { isEditableFile, isEditableMeta, previewWindowKind } from '../../lib/filePreview';
@@ -294,7 +295,7 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
useEffect(() => {
if (cwd) return;
if (projects === null) return;
- const initial = projects?.[0]?.folder_path || sysFavs.find((f) => f.key === 'home')?.path;
+ const initial = sortProjectsByRecent(projects)[0]?.folder_path || sysFavs.find((f) => f.key === 'home')?.path;
if (initial) navigate(initial);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [projects, sysFavs]);
diff --git a/ui/src/components/workbench/FilePicker.tsx b/ui/src/components/workbench/FilePicker.tsx
index fb374a6a2..162941b3a 100644
--- a/ui/src/components/workbench/FilePicker.tsx
+++ b/ui/src/components/workbench/FilePicker.tsx
@@ -4,6 +4,7 @@ import { ChevronRight, File as FileIcon, Folder, FolderPlus, Loader2, X } from '
import clsx from 'clsx';
import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
+import { sortProjectsByRecent } from '../../lib/projectOrder';
import {
fileBrowserErrorMessage,
isPlainEntryName,
@@ -31,7 +32,7 @@ function sortEntries(entries: FsEntry[]): FsEntry[] {
// (dark-locked) Editor window, so it inherits that theme and stays scoped to the window.
export const FilePicker: React.FC<{
mode: FilePickerMode;
- /** Folder to start in; falls back to the first project, then the home favorite. */
+ /** Folder to start in; falls back to the most recent project, then the home favorite. */
initialPath?: string | null;
/** save-file: pre-filled filename. */
defaultName?: string;
@@ -82,7 +83,7 @@ export const FilePicker: React.FC<{
[showHidden, t],
);
- // Pick a sensible starting folder once: the caller's initial path, else the first project, else
+ // Pick a sensible starting folder once: the caller's initial path, else the most recent project, else
// the home favorite.
useEffect(() => {
let cancelled = false;
@@ -94,7 +95,7 @@ export const FilePicker: React.FC<{
.then((favs) => {
if (cancelled) return;
setSysFavs(favs);
- const start = projects?.[0]?.folder_path || favs.find((f) => f.key === 'home')?.path;
+ const start = sortProjectsByRecent(projects ?? [])[0]?.folder_path || favs.find((f) => f.key === 'home')?.path;
if (start) navigate(start);
})
.catch(() => {});
diff --git a/ui/src/components/workbench/ProjectDefaultFolder.test.tsx b/ui/src/components/workbench/ProjectDefaultFolder.test.tsx
new file mode 100644
index 000000000..63d7a6e91
--- /dev/null
+++ b/ui/src/components/workbench/ProjectDefaultFolder.test.tsx
@@ -0,0 +1,74 @@
+/* @vitest-environment jsdom */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { cleanup, render, waitFor } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+
+import type { WorkbenchProject } from '../../context/ApiContext';
+import { AppsFileBrowserPage } from './AppsFileBrowserPage';
+import { FilePicker } from './FilePicker';
+
+const state = vi.hoisted(() => ({
+ projects: [] as WorkbenchProject[],
+ listDir: vi.fn(),
+}));
+
+vi.mock('../../context/WorkbenchProjectsContext', () => ({
+ useWorkbenchProjectsTree: () => ({ projects: state.projects }),
+}));
+vi.mock('../../context/WindowManagerContext', () => ({ useWindowManager: () => null }));
+vi.mock('../../context/StandaloneAppTabContext', () => ({ useStandaloneAppTab: () => false }));
+vi.mock('../../lib/useIsDesktop', () => ({ useIsDesktop: () => true, isDesktopViewport: () => true }));
+vi.mock('../../lib/routeSurfaceActivity', () => ({ useRouteSurfaceWindowEvent: () => {} }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('../../lib/filesApi', async (importOriginal) => ({
+ ...await importOriginal<typeof import('../../lib/filesApi')>(),
+ listDir: state.listDir,
+ systemFavorites: async () => [{ key: 'home', label: 'Home', path: '/tmp/home' }],
+}));
+
+function project(id: string, day: number): WorkbenchProject {
+ return {
+ id,
+ scope_id: `avibe::project::${id}`,
+ display_name: id,
+ folder_path: `/tmp/${id}`,
+ created_at: '2026-01-01T00:00:00Z',
+ last_active_at: `2026-02-0${day}T00:00:00Z`,
+ archived: false,
+ capabilities: { can_chat: true, has_folder: true },
+ };
+}
+
+beforeEach(() => {
+ state.projects = [project('older', 1), project('recent', 2)];
+ state.listDir.mockReset().mockImplementation(async (path: string) => ({ path, entries: [] }));
+});
+afterEach(cleanup);
+
+describe.each(['browser', 'picker'] as const)('%s default folder', (surface) => {
+ function mount() {
+ return render(<MemoryRouter>{surface === 'browser'
+ ? <AppsFileBrowserPage />
+ : <FilePicker mode="open-directory" onCancel={() => {}} onConfirm={() => {}} />
+ }</MemoryRouter>);
+ }
+
+ it.each([false, true])('opens the most recent project, independently of reversed navigation: %s', async (reversed) => {
+ if (reversed) state.projects.reverse();
+ mount();
+ await waitFor(() => expect(state.listDir).toHaveBeenCalledWith('/tmp/recent', false));
+ expect(state.listDir.mock.calls.every(([path]) => path === '/tmp/recent')).toBe(true);
+ });
+
+ it('retains the home fallback with no projects', async () => {
+ state.projects = [];
+ mount();
+ await waitFor(() => expect(state.listDir).toHaveBeenCalledWith('/tmp/home', false));
+ });
+});
+
+it('keeps an explicit picker path ahead of project defaults', async () => {
+ render(<FilePicker mode="open-directory" initialPath="/tmp/explicit" onCancel={() => {}} onConfirm={() => {}} />);
+ await waitFor(() => expect(state.listDir).toHaveBeenCalledWith('/tmp/explicit', false));
+});
diff --git a/ui/src/components/workbench/ProjectsPage.tsx b/ui/src/components/workbench/ProjectsPage.tsx
index 2f529171f..cb4c33bfa 100644
--- a/ui/src/components/workbench/ProjectsPage.tsx
+++ b/ui/src/components/workbench/ProjectsPage.tsx
@@ -52,6 +52,7 @@ import { mobileSessionActions } from './chatSessionActions';
import { SessionActionMenuContent, SessionActionsTrigger } from './sessionActions';
import { useSessionActions } from './useSessionActions';
import { SessionPinIndicator } from './SessionPinIndicator';
+import { SortableProjectList, type ProjectDragHandle } from './SortableProjectList';
const DOT: Record<string, string> = {
running: 'bg-mint shadow-glow-dot-mint',
@@ -93,7 +94,8 @@ const MobileProjectRow: React.FC<{
state: ProjectSessionsState;
onToggle: () => void;
onLeaveToChat: () => void;
-}> = ({ project, open, state, onToggle, onLeaveToChat }) => {
+ dragHandle?: ProjectDragHandle;
+}> = ({ project, open, state, onToggle, onLeaveToChat, dragHandle }) => {
const { t } = useTranslation();
const navigate = useNavigate();
const { capabilities } = useInstanceAuthorization();
@@ -163,9 +165,10 @@ const MobileProjectRow: React.FC<{
<>
<div className="flex items-center pr-1.5">
<button
+ {...dragHandle}
type="button"
onClick={onToggle}
- className="flex min-w-0 flex-1 items-center gap-2.5 px-4 py-3.5 text-left"
+ className="project-drag-header flex min-w-0 flex-1 items-center gap-2.5 px-4 py-3.5 text-left"
>
{open ? <FolderOpen className="size-4 shrink-0 text-cyan-ink" /> : <Folder className="size-4 shrink-0 text-muted" />}
<span className="min-w-0 flex-1 truncate text-sm font-semibold">{project.display_name}</span>
@@ -415,6 +418,8 @@ export const ProjectsPage: React.FC = () => {
toggleExpanded,
loadMore,
reloadSessions,
+ reorderProjects,
+ isReorderingProjects,
} = useWorkbenchProjectsTree();
const [showNewProject, setShowNewProject] = useState(false);
const [visibleSessionCounts, setVisibleSessionCounts] = useState<MobileProjectsVisibleCounts>(
@@ -515,7 +520,11 @@ export const ProjectsPage: React.FC = () => {
</div>
)}
- {list.map((project) => {
+ <SortableProjectList projects={list} mobile
+ disabled={!capabilities.can_manage_projects || isReorderingProjects}
+ onReorder={reorderProjects}
+ >
+ {(project, dragHandle) => {
const open = isExpanded(project.id);
const state = sessionsOf(project.id);
const allSessionRows = state.sessions ?? [];
@@ -526,6 +535,7 @@ export const ProjectsPage: React.FC = () => {
return (
<div key={project.id} className="overflow-hidden rounded-xl border border-border bg-surface">
<MobileProjectRow
+ dragHandle={dragHandle}
project={project}
open={open}
state={state}
@@ -581,7 +591,8 @@ export const ProjectsPage: React.FC = () => {
)}
</div>
);
- })}
+ }}
+ </SortableProjectList>
{showNewProject && canCreateProject && (
<NewProjectDialog
diff --git a/ui/src/components/workbench/SortableProjectList.tsx b/ui/src/components/workbench/SortableProjectList.tsx
new file mode 100644
index 000000000..05dee868d
--- /dev/null
+++ b/ui/src/components/workbench/SortableProjectList.tsx
@@ -0,0 +1,131 @@
+import { useState, type ComponentPropsWithRef, type ReactNode } from 'react';
+import { createPortal } from 'react-dom';
+import {
+ DndContext, DragOverlay, KeyboardSensor, MouseSensor, TouchSensor,
+ closestCenter, defaultDropAnimationSideEffects, useSensor, useSensors,
+ type Modifier,
+} from '@dnd-kit/core';
+import { SortableContext, arrayMove, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable';
+import { CSS } from '@dnd-kit/utilities';
+import { useReducedMotion } from 'framer-motion';
+import { Folder } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import type { WorkbenchProject } from '../../context/ApiContext';
+import { orderProjects } from '../../lib/projectOrder';
+import { cn } from '../../lib/utils';
+
+export type ProjectDragHandle = ComponentPropsWithRef<'button'>;
+
+const verticalOnly: Modifier = ({ transform }) => ({ ...transform, x: 0 });
+
+function SortableProject({ project, disabled, children }: {
+ project: WorkbenchProject;
+ disabled: boolean;
+ children: (handle: ProjectDragHandle) => ReactNode;
+}) {
+ const reducedMotion = useReducedMotion();
+ const { attributes, listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging } = useSortable({
+ id: project.id,
+ disabled,
+ transition: reducedMotion ? null : { duration: 220, easing: 'ease' },
+ });
+ return (
+ <div
+ ref={setNodeRef}
+ data-project-id={project.id}
+ className={cn('project-sortable relative min-w-0', isDragging && 'opacity-0')}
+ style={{ transform: CSS.Translate.toString(transform), transition }}
+ >
+ {children(disabled ? {} : { ...attributes, ...listeners, ref: setActivatorNodeRef })}
+ </div>
+ );
+}
+
+/** The existing project header is the activator on both workbench surfaces. */
+export function SortableProjectList({ projects, disabled, mobile = false, onReorder, children }: {
+ projects: WorkbenchProject[];
+ disabled: boolean;
+ mobile?: boolean;
+ onReorder: (order: string[], expectedOrder: string[]) => Promise<void>;
+ children: (project: WorkbenchProject, handle: ProjectDragHandle) => ReactNode;
+}) {
+ const { t } = useTranslation();
+ const reducedMotion = useReducedMotion();
+ const [activeProject, setActiveProject] = useState<WorkbenchProject | null>(null);
+ const [baseline, setBaseline] = useState<string[] | null>(null);
+ const sensors = useSensors(
+ useSensor(MouseSensor, { activationConstraint: { distance: 6 } }),
+ useSensor(TouchSensor, { activationConstraint: { delay: 300, tolerance: 8 } }),
+ useSensor(KeyboardSensor, {
+ coordinateGetter: sortableKeyboardCoordinates,
+ keyboardCodes: { start: ['Space'], cancel: ['Escape'], end: ['Space'] },
+ }),
+ );
+ const list = baseline ? orderProjects(projects, baseline) : projects;
+ const ids = list.map((project) => project.id);
+ const name = (id: string | number) => projects.find((project) => project.id === id)?.display_name ?? '';
+ const finish = () => { setActiveProject(null); setBaseline(null); };
+
+ return (
+ <DndContext
+ sensors={sensors}
+ collisionDetection={closestCenter}
+ modifiers={[verticalOnly]}
+ accessibility={{
+ screenReaderInstructions: { draggable: t('projects.reorderInstructions') },
+ announcements: {
+ onDragStart: ({ active }) => t('projects.reorderPickedUp', { name: name(active.id) }),
+ onDragOver: ({ active, over }) => over
+ ? t('projects.reorderPosition', { name: name(active.id), position: ids.indexOf(String(over.id)) + 1, count: ids.length })
+ : undefined,
+ onDragEnd: ({ active }) => t('projects.reorderDropped', { name: name(active.id) }),
+ onDragCancel: () => t('projects.reorderCancelled'),
+ },
+ }}
+ onDragStart={({ active }) => {
+ setBaseline(ids);
+ setActiveProject(projects.find((project) => project.id === active.id) ?? null);
+ }}
+ onDragCancel={finish}
+ onDragEnd={({ active, over }) => {
+ const expected = baseline ?? ids;
+ const from = expected.indexOf(String(active.id));
+ const to = expected.indexOf(String(over?.id));
+ finish();
+ if (from >= 0 && to >= 0 && from !== to) void onReorder(arrayMove(expected, from, to), expected);
+ }}
+ >
+ <SortableContext items={ids} strategy={verticalListSortingStrategy}>
+ {list.map((project) => (
+ <SortableProject key={project.id} project={project} disabled={disabled || list.length < 2}>
+ {(handle) => children(project, handle)}
+ </SortableProject>
+ ))}
+ </SortableContext>
+ {createPortal(
+ <DragOverlay
+ transition={reducedMotion ? '' : undefined}
+ dropAnimation={reducedMotion ? null : {
+ duration: 220,
+ easing: 'ease',
+ sideEffects: defaultDropAnimationSideEffects({ styles: { active: { opacity: '0' } } }),
+ }}
+ >
+ {activeProject && (
+ <div
+ data-project-drag-preview
+ className={cn(
+ 'project-drag-preview flex cursor-grabbing items-center gap-2 rounded-md border border-border-strong bg-surface-2 text-foreground shadow-lg',
+ mobile ? 'px-4 py-3.5 text-sm font-semibold' : 'px-2 py-1.5 text-xs font-medium',
+ )}
+ >
+ <Folder className={cn('shrink-0 text-cyan-ink', mobile ? 'size-4' : 'size-3.5')} />
+ <span className="min-w-0 truncate">{activeProject.display_name}</span>
+ </div>
+ )}
+ </DragOverlay>,
+ document.body,
+ )}
+ </DndContext>
+ );
+}
diff --git a/ui/src/components/workbench/WorkbenchSidebar.tsx b/ui/src/components/workbench/WorkbenchSidebar.tsx
index 250bf4396..8745708d1 100644
--- a/ui/src/components/workbench/WorkbenchSidebar.tsx
+++ b/ui/src/components/workbench/WorkbenchSidebar.tsx
@@ -45,6 +45,7 @@ import { Markdown } from '../ui/markdown';
import { NewProjectDialog } from './NewProjectDialog';
import { ProjectAgentsMdDialog } from './ProjectAgentsMdDialog';
import { ProjectSettingsDialog } from './ProjectSettingsDialog';
+import { SortableProjectList, type ProjectDragHandle } from './SortableProjectList';
interface CapabilityNavItem {
to: string;
@@ -399,6 +400,7 @@ const ProjectRow: React.FC<{
canEditAgentsMd: boolean;
unreadBySession: Record<string, number>;
onRename: (next: string) => Promise<void>;
+ dragHandle?: ProjectDragHandle;
onArchive: () => Promise<void>;
}> = ({
project,
@@ -419,6 +421,7 @@ const ProjectRow: React.FC<{
canEditAgentsMd,
unreadBySession,
onRename,
+ dragHandle,
onArchive,
}) => {
const { t } = useTranslation();
@@ -483,9 +486,10 @@ const ProjectRow: React.FC<{
</div>
) : (
<button
+ {...dragHandle}
type="button"
onClick={onToggle}
- className="flex min-w-0 flex-1 items-center gap-1.5 text-left"
+ className="project-drag-header flex min-w-0 flex-1 items-center gap-1.5 text-left"
>
<Chevron className="size-3 shrink-0 text-muted" />
{expanded ? (
@@ -685,6 +689,8 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
createSessionForProject,
renameProject,
archiveProject,
+ reorderProjects,
+ isReorderingProjects,
} = useWorkbenchProjectsTree();
const [popoverOpen, setPopoverOpen] = useState(false);
const closeTimer = useRef<number | null>(null);
@@ -896,12 +902,17 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
<div className="text-[11px] text-muted">{t('workbench.projectsEmpty')}</div>
</div>
)}
- {projects !== null &&
- projects.map((project) => {
+ {projects !== null && <SortableProjectList
+ projects={projects}
+ disabled={!canManageProjects || isReorderingProjects}
+ onReorder={reorderProjects}
+ >
+ {(project, dragHandle) => {
const state = sessionsOf(project.id);
return (
<ProjectRow
key={project.id}
+ dragHandle={dragHandle}
project={project}
expanded={isExpanded(project.id)}
sessions={state.sessions}
@@ -932,7 +943,8 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
onArchive={() => archiveProject(project.id)}
/>
);
- })}
+ }}
+ </SortableProjectList>}
</div>
</div>
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index ea114aa4e..11564d3b6 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -693,6 +693,7 @@ export type ApiContextType = {
browseFavorites: () => Promise<{ ok: boolean; system?: string; favorites?: { key: string; path: string }[]; error?: string }>;
browseMkdir: (path: string) => Promise<{ path: string }>;
listProjects: (includeArchived?: boolean, options?: { cache?: boolean }) => Promise<{ projects: WorkbenchProject[] }>;
+ reorderProjects: (order: string[], expectedOrder: string[]) => Promise<{ projects: WorkbenchProject[] }>;
getWorkbenchProjectsBootstrap: (params?: {
includeArchived?: boolean;
projectIds?: string[];
@@ -1213,6 +1214,7 @@ export type WorkbenchEventHandlers = {
* one twice.
*/
onConnected?: () => void;
+ onProjectsChanged?: () => void;
onConnectionState?: (state: WorkbenchEventConnectionState) => void;
onEventBridgeStatus?: (data: { connected: boolean }) => void;
onAuthorizationChanged?: (data: {
@@ -3096,6 +3098,15 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
handlers.onAuthorizationChanged?.(envelope.data);
});
});
+ source.addEventListener('projects.changed', (e: MessageEvent) => {
+ const envelope = parseWorkbenchEnvelope<Record<string, never>>(e.data);
+ if (!envelope) return;
+ clearReadCacheMatching((path) => path.startsWith('/api/projects') || path.startsWith('/api/workbench/projects-bootstrap'));
+ dispatchToWorkbenchHandlers((handlers) => {
+ handlers.onAny?.(envelope);
+ handlers.onProjectsChanged?.();
+ });
+ });
source.addEventListener('remote.authorization', (e: MessageEvent) => {
try {
const payload = JSON.parse(e.data) as { state?: RemoteAuthorizationState };
@@ -3916,6 +3927,19 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
return params?.cache === false ? getJson(path) : getCachedJson(path);
},
createProject: (payload) => postJson('/api/projects', payload),
+ reorderProjects: async (order, expectedOrder) => {
+ try {
+ const { payloadJson } = await requestJson('/api/projects/order', {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ order, expected_order: expectedOrder }),
+ });
+ return payloadJson;
+ } catch (error) {
+ if (!(error instanceof ApiError)) showToast(t('errors.invalid_project_order'), 'error');
+ throw error;
+ }
+ },
updateProject: async (projectId, payload) => {
const { payloadJson } = await requestJson(`/api/projects/${encodeURIComponent(projectId)}`, {
method: 'PATCH',
diff --git a/ui/src/context/WorkbenchProjectOrder.test.tsx b/ui/src/context/WorkbenchProjectOrder.test.tsx
new file mode 100644
index 000000000..883b4b894
--- /dev/null
+++ b/ui/src/context/WorkbenchProjectOrder.test.tsx
@@ -0,0 +1,72 @@
+// @vitest-environment jsdom
+import { act, cleanup, render, waitFor } from '@testing-library/react';
+import { useEffect } from 'react';
+import { afterEach, expect, it, vi } from 'vitest';
+import { WorkbenchProjectsProvider } from './WorkbenchProjectsProvider';
+import { useWorkbenchProjectsTree } from './WorkbenchProjectsContext';
+import type { WorkbenchEventHandlers, WorkbenchProject } from './ApiContext';
+
+let handlers: WorkbenchEventHandlers;
+const api = {
+ getWorkbenchProjectsBootstrap: vi.fn(),
+ listProjects: vi.fn(),
+ reorderProjects: vi.fn(),
+ updateProject: vi.fn(),
+ connectWorkbenchEvents: (next: WorkbenchEventHandlers) => { handlers = next; return () => {}; },
+};
+vi.mock('./ApiContext', () => ({ useApi: () => api }));
+vi.mock('./ToastContext', () => ({ useToast: () => ({ showToast: vi.fn() }) }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+
+const rows = ['a', 'b', 'c'].map((id) => ({
+ id, display_name: id, scope_id: `scope_${id}`, folder_path: `/tmp/${id}`,
+ created_at: '2026-01-01T00:00:00Z', last_active_at: null, archived: false,
+ capabilities: { can_chat: true, has_folder: true },
+})) satisfies WorkbenchProject[];
+let tree: ReturnType<typeof useWorkbenchProjectsTree>;
+function Probe() {
+ const value = useWorkbenchProjectsTree();
+ useEffect(() => { tree = value; }, [value]);
+ return null;
+}
+const ids = () => tree.projects?.map((p) => p.id);
+async function mount() {
+ api.getWorkbenchProjectsBootstrap.mockResolvedValue({ projects: rows, sessions: {} });
+ api.listProjects.mockResolvedValue({ projects: rows });
+ render(<WorkbenchProjectsProvider><Probe /></WorkbenchProjectsProvider>);
+ await waitFor(() => expect(ids()).toEqual(['a', 'b', 'c']));
+}
+afterEach(() => { cleanup(); vi.clearAllMocks(); });
+
+it('holds the drag order across reads and commits only positions over a concurrent rename', async () => {
+ await mount();
+ let finish!: (value: { projects: WorkbenchProject[] }) => void;
+ api.reorderProjects.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
+ let pending!: Promise<void>;
+ act(() => { pending = tree.reorderProjects(['c', 'a', 'b'], ['a', 'b', 'c']); });
+ expect(ids()).toEqual(['c', 'a', 'b']);
+ expect(tree.isReorderingProjects).toBe(true);
+ await act(async () => { handlers.onProjectsChanged?.(); });
+ expect(ids()).toEqual(['c', 'a', 'b']);
+ api.updateProject.mockResolvedValue({ ...rows[0], display_name: 'renamed' });
+ await act(async () => { await tree.renameProject('a', 'renamed'); });
+ const refreshed = [rows[2], { ...rows[0], display_name: 'renamed' }, rows[1]];
+ api.listProjects.mockResolvedValue({ projects: refreshed });
+ api.getWorkbenchProjectsBootstrap.mockResolvedValue({ projects: refreshed, sessions: {} });
+ await act(async () => { finish({ projects: [rows[2], rows[0], rows[1]] }); await pending; });
+ expect(ids()).toEqual(['c', 'a', 'b']);
+ expect(tree.projects?.find((p) => p.id === 'a')?.display_name).toBe('renamed');
+ expect(tree.isReorderingProjects).toBe(false);
+});
+
+it('recovers the server order after a refused save and accepts another device update', async () => {
+ await mount();
+ api.reorderProjects.mockRejectedValue(new Error('conflict'));
+ await act(async () => { await tree.reorderProjects(['c', 'a', 'b'], ['a', 'b', 'c']); });
+ await waitFor(() => expect(ids()).toEqual(['a', 'b', 'c']));
+ const elsewhere = [rows[1], rows[2], rows[0]];
+ api.listProjects.mockResolvedValue({ projects: elsewhere });
+ api.getWorkbenchProjectsBootstrap.mockResolvedValue({ projects: elsewhere, sessions: {} });
+ await act(async () => { handlers.onProjectsChanged?.(); });
+ await waitFor(() => expect(ids()).toEqual(['b', 'c', 'a']));
+});
diff --git a/ui/src/context/WorkbenchProjectsContext.ts b/ui/src/context/WorkbenchProjectsContext.ts
index 8dc10fefb..90ae037a7 100644
--- a/ui/src/context/WorkbenchProjectsContext.ts
+++ b/ui/src/context/WorkbenchProjectsContext.ts
@@ -43,6 +43,8 @@ export interface WorkbenchProjectsActions {
* i.e. no project-bound scope) forks with `null` and simply has no row to place. */
forkSession: (projectId: string | null, sessionId: string) => Promise<WorkbenchSession | null>;
renameProject: (projectId: string, name: string) => Promise<void>;
+ reorderProjects: (order: string[], expectedOrder: string[]) => Promise<void>;
+ isReorderingProjects: boolean;
/** Set the project's default Agent route (Project Settings): patches the shared
* cache FIRST, so the sidebar + Projects page + the picker's own highlight move
* within the click, then persists behind it. Pass an all-null route to clear
@@ -69,7 +71,7 @@ export interface WorkbenchProjectsActions {
* tasks/watches/runs) then drops the row from the tree. Throws on failure.
* `null` project = standalone session (nothing to drop from the tree). */
archiveSession: (projectId: string | null, sessionId: string) => Promise<void>;
- /** Create a project AND place it in the shared tree (dedup-by-id, hoist to top,
+ /** Create a project AND place it in the shared tree (dedup-by-id, append new,
* expand, fetch sessions), then return it so the caller can navigate/select.
*
* The commit lives here rather than at the call site because a write is the
diff --git a/ui/src/context/WorkbenchProjectsProvider.tsx b/ui/src/context/WorkbenchProjectsProvider.tsx
index 4a50ed656..9c97d43fb 100644
--- a/ui/src/context/WorkbenchProjectsProvider.tsx
+++ b/ui/src/context/WorkbenchProjectsProvider.tsx
@@ -12,6 +12,7 @@ import {
} from './WorkbenchProjectsContext';
import { createdReconcileMinCount } from '../lib/sessionVisibilityEvents';
import { orderProjectSessions } from '../lib/sessionPinning';
+import { orderProjects } from '../lib/projectOrder';
import { overwritesRefusedFields, useCoalescedWrite } from '../lib/useCoalescedWrite';
import { errorMessage } from '@/lib/errorMessage';
import { useConsumerActivation } from '@/lib/useConsumerActivation';
@@ -153,6 +154,8 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
const { active, isActive, activate } = useConsumerActivation();
const [projects, setProjects] = useState<WorkbenchProject[] | null>(null);
const [projectsError, setProjectsError] = useState<string | null>(null);
+ const [isReorderingProjects, setIsReorderingProjects] = useState(false);
+ const pendingProjectOrderRef = useRef<string[] | null>(null);
const [expanded, setExpanded] = useState<Set<string>>(new Set());
const [sessions, setSessions] = useState<Record<string, ProjectSessionsState>>({});
const [creating, setCreating] = useState<Set<string>>(new Set());
@@ -247,7 +250,10 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
| ((prev: WorkbenchProject[] | null) => WorkbenchProject[] | null),
options?: { confirmed?: ProjectRouteConfirmation[] | null },
) => {
- const requested = typeof next === 'function' ? next(projectsRef.current) : next;
+ const incoming = typeof next === 'function' ? next(projectsRef.current) : next;
+ const requested = incoming && pendingProjectOrderRef.current
+ ? orderProjects(incoming, pendingProjectOrderRef.current)
+ : incoming;
// ── The in-flight pick outranks every incoming row ────────────────────
// A read that STARTS after a pick still answers with what the server held
// before the PATCH committed, and its read stamp is legitimately current —
@@ -991,6 +997,10 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
onConnected: () => {
void reconcileProjectTree();
},
+ onProjectsChanged: () => {
+ acceptProjectsMutation();
+ if (isActive()) void fetchProjects({ cache: false });
+ },
// An authorization change is invalidation rather than revalidation, and the
// two answer different questions. Demand decides whether a replacement READ
// is worth issuing; it never decides whether the cache the change voided is
@@ -1081,9 +1091,11 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
return disconnect;
}, [
acceptSessionMutation,
+ acceptProjectsMutation,
api,
discardAuthorizedTree,
isActive,
+ fetchProjects,
projectIdForSession,
readTreeForActiveConsumer,
reconcileProjectTree,
@@ -1424,18 +1436,20 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
[acceptSessionMutation, api],
);
- const upsertProjectToTop = useCallback(
+ const upsertProject = useCallback(
(project: WorkbenchProject) => {
acceptProjectsMutation();
// create_project is find-or-create by path: opening a tracked folder returns
- // the existing project, refreshed. Drop any stale copy, hoist to top, expand.
+ // the existing project, refreshed. Keep its slot, append new rows, expand.
// The route this snapshot carries can be older than a pick still in flight;
// defending that is ``commitProjects``' job now, not this call site's. Only
// the CONFIRMATION stays here: this is a mutation response, so it may not
// record a token for a route whose write has not answered yet.
const routeInFlight = latestProjectRouteRef.current.has(project.id);
commitProjects(
- (prev) => (prev ? [project, ...prev.filter((p) => p.id !== project.id)] : [project]),
+ (prev) => prev?.some((p) => p.id === project.id)
+ ? prev.map((p) => p.id === project.id ? project : p)
+ : [...(prev ?? []), project],
routeInFlight ? undefined : { confirmed: [project] },
);
setExpanded((prev) => {
@@ -1468,12 +1482,45 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
const write = readOwnershipRef.current.beginRead('projects-authorization');
const project = await api.createProject(payload);
if (!readOwnershipRef.current.isMutationCurrent(write, 'projects-authorization')) return null;
- upsertProjectToTop(project);
+ const alreadyVisible = projectsRef.current?.some((p) => p.id === project.id);
+ upsertProject(project);
+ // A restored project may have a saved slot outside the currently visible
+ // list. Reopening a visible project already has the right slot locally.
+ if (!alreadyVisible) void fetchProjects({ cache: false });
return project;
},
- [api, upsertProjectToTop],
+ [api, upsertProject, fetchProjects],
);
+ const reorderProjects = useCallback(async (order: string[], expectedOrder: string[]) => {
+ if (pendingProjectOrderRef.current || order.every((id, index) => id === expectedOrder[index])) return;
+ const write = readOwnershipRef.current.beginRead('projects-authorization');
+ pendingProjectOrderRef.current = order;
+ setIsReorderingProjects(true);
+ acceptProjectsMutation();
+ commitProjects((prev) => prev);
+ try {
+ const result = await api.reorderProjects(order, expectedOrder);
+ if (!readOwnershipRef.current.isMutationCurrent(write, 'projects-authorization')) return;
+ pendingProjectOrderRef.current = null;
+ acceptProjectsMutation();
+ // A reorder owns positions only. A concurrent rename/route save owns its
+ // fields, even if this response was captured before that save completed.
+ commitProjects((prev) => prev && orderProjects(prev, result.projects.map((p) => p.id)));
+ } catch {
+ pendingProjectOrderRef.current = null;
+ if (readOwnershipRef.current.isMutationCurrent(write, 'projects-authorization')) {
+ commitProjects((prev) => prev && orderProjects(prev, expectedOrder));
+ }
+ // The shared API layer reports the failure; re-read also resolves an
+ // ambiguous transport failure where the server may have saved the move.
+ } finally {
+ pendingProjectOrderRef.current = null;
+ setIsReorderingProjects(false);
+ void fetchProjects({ cache: false });
+ }
+ }, [acceptProjectsMutation, api, commitProjects, fetchProjects]);
+
const sessionsOf = useCallback((projectId: string) => sessions[projectId] ?? EMPTY_SESSIONS, [sessions]);
const isExpanded = useCallback((projectId: string) => expanded.has(projectId), [expanded]);
const creatingSession = useCallback((projectId: string) => creating.has(projectId), [creating]);
@@ -1496,6 +1543,8 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
createSessionForProject,
forkSession,
renameProject,
+ reorderProjects,
+ isReorderingProjects,
setProjectDefaultAgent,
isSavingDefaultAgent,
archiveProject,
@@ -1519,6 +1568,8 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
createSessionForProject,
forkSession,
renameProject,
+ reorderProjects,
+ isReorderingProjects,
setProjectDefaultAgent,
isSavingDefaultAgent,
archiveProject,
diff --git a/ui/src/context/shellBootstrapDemand.test.tsx b/ui/src/context/shellBootstrapDemand.test.tsx
index e2bbe073c..ca11ac86e 100644
--- a/ui/src/context/shellBootstrapDemand.test.tsx
+++ b/ui/src/context/shellBootstrapDemand.test.tsx
@@ -1549,7 +1549,10 @@ describe('Demand-driven shell bootstrap', () => {
getWorkbenchProjectsBootstrap: bootstrap,
listSessions,
connectWorkbenchEvents: vi.fn(() => vi.fn()),
- createProject: vi.fn().mockResolvedValue(newProject),
+ createProject: vi.fn().mockImplementation(async () => {
+ bootstrap.mockResolvedValue({ projects: [project, newProject], sessions: {} });
+ return newProject;
+ }),
};
let tree: WorkbenchProjectsTree | null = null;
const captureTree = (next: WorkbenchProjectsTree) => {
@@ -1565,8 +1568,8 @@ describe('Demand-driven shell bootstrap', () => {
await settle();
expect(tree?.projects).toEqual([project]);
- // Opening a tracked folder hoists the project and asks for its sessions in the
- // same statement.
+ // Opening a new folder appends the project and asks for its sessions in the
+ // same statement. Subsequent reads observe the completed creation.
await act(async () => {
await tree?.createProject({ folder_path: newProject.folder_path });
});
@@ -1574,6 +1577,7 @@ describe('Demand-driven shell bootstrap', () => {
expect(listSessions).toHaveBeenCalledTimes(1);
expect(listSessions.mock.calls[0][0]).toMatchObject({ projectId: newProject.id });
+ expect(tree?.projects).toEqual([project, newProject]);
expect(tree?.sessionsOf(newProject.id).sessions).toEqual([newSession]);
});
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 641beff21..3d9008807 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -157,6 +157,11 @@
},
"projects": {
"title": "Projects",
+ "reorderInstructions": "Press Space to pick up a project, use arrow keys to move it, Space to drop, or Escape to cancel.",
+ "reorderPickedUp": "Picked up {{name}}.",
+ "reorderPosition": "{{name}}, position {{position}} of {{count}}.",
+ "reorderDropped": "Dropped {{name}}.",
+ "reorderCancelled": "Project move cancelled.",
"empty": "No projects yet",
"newProject": "New project",
"noSessions": "No sessions",
@@ -2056,6 +2061,8 @@
"project_no_folder": "This project has no local folder configured.",
"project_not_found": "Project not found.",
"project_agent_conflict": "The project's Agent changed elsewhere. Reloading it — apply your change again.",
+ "project_order_conflict": "Project order changed elsewhere. The list has been refreshed; move the project again.",
+ "invalid_project_order": "Project order could not be saved. Refresh the list and try again.",
"remote_access_host_mismatch": "This address can't open the Avibe control panel. Open it from your https://<your-slug>.avibe.bot link, or http://127.0.0.1:5123 on the machine running Avibe.",
"remote_access_config_unavailable": "Avibe couldn't read its configuration. Check that the service is healthy and try again.",
"remote_access_public_url_invalid": "Remote access is misconfigured (the public URL is invalid). Re-pair this device or fix the remote-access settings.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index f08c688ea..c5f5008c1 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -157,6 +157,11 @@
},
"projects": {
"title": "项目",
+ "reorderInstructions": "按空格键抓取项目,方向键移动,空格键放下,Escape 取消。",
+ "reorderPickedUp": "已抓取 {{name}}。",
+ "reorderPosition": "{{name}},第 {{position}} 项,共 {{count}} 项。",
+ "reorderDropped": "已放下 {{name}}。",
+ "reorderCancelled": "已取消移动项目。",
"empty": "还没有项目",
"newProject": "新建项目",
"noSessions": "暂无会话",
@@ -2056,6 +2061,8 @@
"project_no_folder": "这个项目没有配置本地文件夹。",
"project_not_found": "找不到这个项目。",
"project_agent_conflict": "该项目的 Agent 已在别处变更,正在重新加载,请再次修改。",
+ "project_order_conflict": "项目顺序已在别处变更,列表已刷新,请重新拖动。",
+ "invalid_project_order": "无法保存项目顺序,请刷新列表后重试。",
"remote_access_host_mismatch": "这个地址无法打开 Avibe 控制台。请用你的 https://<你的子域>.avibe.bot 链接打开,或在运行 Avibe 的机器上访问 http://127.0.0.1:5123。",
"remote_access_config_unavailable": "Avibe 无法读取配置。请确认服务运行正常后重试。",
"remote_access_public_url_invalid": "远程访问配置有误(公网地址无效)。请重新配对此设备或修正远程访问设置。",
diff --git a/ui/src/index.css b/ui/src/index.css
index cd6e9b0d2..789f633aa 100644
--- a/ui/src/index.css
+++ b/ui/src/index.css
@@ -889,3 +889,21 @@ pre,
font-size: inherit;
}
.vr-fileview-text .vr-fileview-md pre code { font-size: 0.92em; }
+
+/* The project header remains a scroll/tap target until a touch hold activates. */
+.project-drag-header {
+ touch-action: manipulation;
+ -webkit-touch-callout: none;
+ user-select: none;
+}
+.project-drag-header[aria-describedby] { cursor: grab; }
+.project-drag-header[aria-pressed="true"] { cursor: grabbing; }
+.project-drag-preview { animation: project-pickup 140ms ease-out; }
+@keyframes project-pickup {
+ from { opacity: 0.75; transform: scale(0.98); }
+ to { opacity: 1; transform: scale(1); }
+}
+@media (prefers-reduced-motion: reduce) {
+ .project-drag-preview { animation: none; }
+ .project-sortable { transition: none !important; }
+}
diff --git a/ui/src/lib/projectOrder.test.ts b/ui/src/lib/projectOrder.test.ts
new file mode 100644
index 000000000..2687aaf91
--- /dev/null
+++ b/ui/src/lib/projectOrder.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest';
+
+import type { WorkbenchProject } from '../context/ApiContext';
+import { orderProjects, sortProjectsByRecent } from './projectOrder';
+
+const project = (id: string, lastActiveAt: string | null): WorkbenchProject => ({
+ id,
+ scope_id: `avibe::project::${id}`,
+ display_name: id,
+ folder_path: `/tmp/${id}`,
+ created_at: '2026-01-01T00:00:00Z',
+ last_active_at: lastActiveAt,
+ archived: false,
+ capabilities: { can_chat: true, has_folder: true },
+});
+
+describe('project ordering policies', () => {
+ it('selects the same recent defaults regardless of navigation positions, including ties', () => {
+ const rows = [project('older', null), project('recent-b', '2026-02-01T00:00:00Z'), project('recent-a', '2026-02-01T00:00:00Z')];
+ const expected = [rows[2], rows[1], rows[0]];
+ for (const ids of [['older', 'recent-b', 'recent-a'], ['recent-a', 'older', 'recent-b'], ['recent-b', 'recent-a', 'older']]) {
+ const navigation = orderProjects(rows, ids);
+ expect(sortProjectsByRecent(navigation)).toEqual(expected);
+ expect(navigation.map((row) => row.id)).toEqual(ids);
+ }
+ expect(sortProjectsByRecent([])).toEqual([]);
+ });
+});
diff --git a/ui/src/lib/projectOrder.ts b/ui/src/lib/projectOrder.ts
new file mode 100644
index 000000000..d4e6db7c5
--- /dev/null
+++ b/ui/src/lib/projectOrder.ts
@@ -0,0 +1,14 @@
+import type { WorkbenchProject } from '../context/ApiContext';
+
+/** Operation defaults follow recency, independently of the navigation order. */
+export function sortProjectsByRecent(projects: readonly WorkbenchProject[]): WorkbenchProject[] {
+ return [...projects].sort((a, b) =>
+ (b.last_active_at || b.created_at).localeCompare(a.last_active_at || a.created_at) || a.id.localeCompare(b.id),
+ );
+}
+
+/** Apply only order, preserving current row data and appending new projects. */
+export function orderProjects<T extends { id: string }>(projects: T[], order: readonly string[]): T[] {
+ const positions = new Map(order.map((id, index) => [id, index]));
+ return [...projects].sort((a, b) => (positions.get(a.id) ?? order.length) - (positions.get(b.id) ?? order.length));
+}
diff --git a/ui/src/lib/useNewSession.ts b/ui/src/lib/useNewSession.ts
index 0fe57452d..8164dd2d8 100644
--- a/ui/src/lib/useNewSession.ts
+++ b/ui/src/lib/useNewSession.ts
@@ -3,6 +3,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react';
import { useApi } from '../context/ApiContext';
import { useWorkbenchProjectsTree } from '../context/WorkbenchProjectsContext';
import type { ApiContextType, VibeAgentBrief, WorkbenchProject, WorkbenchSessionCreate } from '../context/ApiContext';
+import { sortProjectsByRecent } from './projectOrder';
interface UseNewSessionOptions {
/** Re-run the per-open reset on the rising edge — sheets pass their `open`. Default true. */
@@ -80,11 +81,6 @@ export function projectDefaultAgentRoute(
: {};
}
-const sortByRecent = (list: WorkbenchProject[]) =>
- list
- .slice()
- .sort((a, b) => (b.last_active_at || b.created_at).localeCompare(a.last_active_at || a.created_at));
-
type AgentProjectionResponse = Awaited<ReturnType<ApiContextType['listVibeAgents']>>;
export function createLatestAgentProjectionLoader(
@@ -148,7 +144,7 @@ export function useNewSession({ active = true, loadErrorText, createFailedText }
const [userPick, setUserPick] = useState<AgentRouteSelection>({});
const projects = useMemo(
- () => (rawProjects ? sortByRecent(rawProjects.filter((project) => project.capabilities.can_chat)) : []),
+ () => (rawProjects ? sortProjectsByRecent(rawProjects.filter((project) => project.capabilities.can_chat)) : []),
[rawProjects],
);
const projectsLoaded = rawProjects !== null;
diff --git a/vibe/authorization.py b/vibe/authorization.py
index f45d1f6a4..db80bb883 100644
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@ -66,6 +66,7 @@ _VIEWER_WORKBENCH_EVENTS = frozenset(
"inbox.session.updated",
"inbox.unread.changed",
"message.new",
+ "projects.changed",
"session.activity",
"session.status",
"show.event",
@@ -487,6 +488,7 @@ _MEMBER_HTTP_RULES = tuple(
# can_manage_projects. Project ACL lives under /api/permissions and is
# Owner; agents-md is project content.
("POST", r"^/api/projects$"),
+ ("PUT", r"^/api/projects/order$"),
("PATCH", r"^/api/projects/[^/]+$"),
("DELETE", r"^/api/projects/[^/]+$"),
("GET", r"^/api/projects/[^/]+/agents-md$"),
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 1d9d84b05..331418bf8 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -8,6 +8,10 @@
"steps": "{count} st",
"tokens": "{count} tok"
},
+ "projects": {
+ "orderInvalid": "Project order could not be saved. Refresh the list and try again.",
+ "orderConflict": "Project order changed elsewhere. Refresh the list and move the project again."
+ },
"fork": {
"title": "Fork {title}",
"titleUntitled": "Fork"
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index dd45e30be..d3cf072b0 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -8,6 +8,10 @@
"steps": "{count} 步",
"tokens": "{count} tok"
},
+ "projects": {
+ "orderInvalid": "无法保存项目顺序。请刷新列表后重试。",
+ "orderConflict": "项目顺序已在其他地方修改。请刷新列表后重新拖动。"
+ },
"fork": {
"title": "复刻 {title}",
"titleUntitled": "复刻"
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 27d34de56..ace9c783d 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -8333,6 +8333,30 @@ def projects_create():
return jsonify(project), 201
[email protected]("/api/projects/order", methods=["PUT"])
+def projects_order_put():
+ from storage import projects_service
+ from vibe.sse_broker import broker
+
+ payload = request.json or {}
+ if not isinstance(payload, dict):
+ return _coded_error_response("invalid_project_order", t("projects.orderInvalid", _request_ui_language()), 400)
+ try:
+ with _projects_engine().begin() as conn:
+ projects = projects_service.reorder_projects(
+ conn,
+ payload.get("order"),
+ expected_order=payload.get("expected_order"),
+ authorization_context=getattr(g, "authorization_context", None),
+ )
+ except projects_service.ProjectOrderConflict:
+ return _coded_error_response("project_order_conflict", t("projects.orderConflict", _request_ui_language()), 409)
+ except ValueError:
+ return _coded_error_response("invalid_project_order", t("projects.orderInvalid", _request_ui_language()), 400)
+ broker.publish("projects.changed", {})
+ return jsonify({"projects": projects})
+
+
@app.route("/api/projects/<project_id>", methods=["GET"])
def projects_get(project_id: str):
from storage import projects_service
@@ -8909,6 +8933,7 @@ def workbench_projects_bootstrap():
projects = projects_service.list_projects(
conn,
include_archived=include_archived,
+ navigation_order=True,
authorization_context=authorization_context,
)
project_id_set = {project["id"] for project in projects}
@@ -11831,6 +11856,9 @@ def _workbench_event_visible_to_context(context, event_type: str, payload: str)
if event_type in {"authorization.changed", "workbench.events.bridge.status"}:
return True
data = _workbench_event_data(payload)
+ if event_type == "projects.changed":
+ # This global invalidation is safe only while it carries no project data.
+ return context.has_role("viewer") and data == {}
if data is None:
return False