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): pin project sessions (#984)

Call Whiteaff8751def1e
diff --git a/docs/plans/project-session-pinning.md b/docs/plans/project-session-pinning.md
new file mode 100644
index 000000000..3605c5a65
--- /dev/null
+++ b/docs/plans/project-session-pinning.md
@@ -0,0 +1,48 @@
+# Project Session Pinning
+
+## Background
+
+Project session lists are currently ordered only by recent activity. Users need
+to keep any number of important sessions at the top of their current project,
+with the preference persisted by the Avibe backend and reflected across open
+clients.
+
+## Goal
+
+- Add Pin / Unpin as the first session action on desktop and mobile.
+- Keep every pinned session ahead of unpinned sessions within its project.
+- Preserve recent-activity ordering inside the pinned and unpinned groups.
+- Persist the state in SQLite and broadcast changes over the existing
+ `session.activity` stream.
+- Keep cursor pagination correct when a project has more pinned sessions than a
+ single page.
+
+## Design
+
+`agent_sessions.pinned` is the aggregate-owned state. It is a non-null boolean
+column (SQLite integer) because pinning belongs to a Session and a Session has at
+most one current project. Moving a session carries its pin state to its new
+project; archiving naturally removes it from active lists.
+
+The session list order becomes:
+
+1. `pinned DESC`
+2. `last_active_at DESC`
+3. `created_at DESC`
+4. `id DESC`
+
+The cursor predicate includes the pinned group before the existing activity
+tuple. `PATCH /api/sessions/:id` accepts a strict boolean `pinned` field and the
+canonical `session.activity` update includes the resulting state. Clients patch
+the visible row immediately and reconcile the loaded project window so pinning
+an older session, or unpinning the last visible pinned session, cannot leave a
+stale page.
+
+## Verification
+
+- Migration adds the column and list index without changing existing rows.
+- Service tests cover unlimited pinned rows, group ordering, and pagination
+ across the pinned/unpinned boundary.
+- API tests cover persistence, validation, and SSE payloads.
+- UI build and focused unit tests cover client-side ordering.
+- Browser verification covers menu placement and live row movement.
diff --git a/storage/alembic/versions/20260724_0034_session_pinning.py b/storage/alembic/versions/20260724_0034_session_pinning.py
new file mode 100644
index 000000000..596d18a7e
--- /dev/null
+++ b/storage/alembic/versions/20260724_0034_session_pinning.py
@@ -0,0 +1,66 @@
+"""add persisted project session pinning
+
+Revision ID: 20260724_0034
+Revises: 20260723_0033
+Create Date: 2026-07-24
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "20260724_0034"
+down_revision = "20260723_0033"
+branch_labels = None
+depends_on = None
+
+
+def _tables(bind) -> set[str]:
+ return {
+ str(row[0])
+ for row in bind.exec_driver_sql(
+ "select name from sqlite_master where type = 'table'"
+ )
+ }
+
+
+def _columns(bind, table: str) -> set[str]:
+ return {
+ str(row[1])
+ for row in bind.exec_driver_sql(f'pragma table_info("{table}")').fetchall()
+ }
+
+
+def _indexes(bind, table: str) -> set[str]:
+ return {
+ str(row[1])
+ for row in bind.exec_driver_sql(f'pragma index_list("{table}")').fetchall()
+ }
+
+
+def upgrade() -> None:
+ bind = op.get_bind()
+ if "agent_sessions" not in _tables(bind):
+ return
+ if "pinned" not in _columns(bind, "agent_sessions"):
+ op.add_column(
+ "agent_sessions",
+ sa.Column("pinned", sa.Integer(), nullable=False, server_default="0"),
+ )
+ if "ix_agent_sessions_scope_status_pinned_activity" not in _indexes(bind, "agent_sessions"):
+ op.create_index(
+ "ix_agent_sessions_scope_status_pinned_activity",
+ "agent_sessions",
+ ["scope_id", "status", "pinned", "last_active_at", "created_at", "id"],
+ )
+
+
+def downgrade() -> None:
+ bind = op.get_bind()
+ if "agent_sessions" not in _tables(bind):
+ return
+ if "ix_agent_sessions_scope_status_pinned_activity" in _indexes(bind, "agent_sessions"):
+ op.drop_index("ix_agent_sessions_scope_status_pinned_activity", table_name="agent_sessions")
+ if "pinned" in _columns(bind, "agent_sessions"):
+ op.drop_column("agent_sessions", "pinned")
diff --git a/storage/migrations.py b/storage/migrations.py
index 5ab3cca9e..13967bea9 100644
--- a/storage/migrations.py
+++ b/storage/migrations.py
@@ -68,7 +68,7 @@ PRE_SHOW_SESSION_EVENTS_HEAD_TABLES = INITIAL_TABLES | {
HEAD_REQUIRED_COLUMNS = {
"agents": {"enabled"},
"scope_settings": {"agent_name"},
- "agent_sessions": {"agent_id", "agent_name", "visibility"},
+ "agent_sessions": {"agent_id", "agent_name", "visibility", "pinned"},
"messages": {"type", "source"},
"run_definitions": {
"deleted_at",
@@ -605,6 +605,12 @@ def _repair_initial_required_columns(conn: sqlite3.Connection, tables: set[str])
"VARCHAR not null default 'foreground'"
)
changed = True
+ if "pinned" not in columns:
+ conn.execute(
+ 'alter table "agent_sessions" add column "pinned" '
+ "INTEGER not null default 0"
+ )
+ changed = True
return changed
@@ -632,6 +638,10 @@ def _ensure_messages_query_indexes(conn: sqlite3.Connection, tables: set[str]) -
"create index if not exists ix_agent_sessions_scope_status_activity "
"on agent_sessions (scope_id, status, last_active_at, created_at, id)"
)
+ conn.execute(
+ "create index if not exists ix_agent_sessions_scope_status_pinned_activity "
+ "on agent_sessions (scope_id, status, pinned, last_active_at, created_at, id)"
+ )
if "messages" not in tables:
return
conn.execute('create index if not exists ix_messages_session_created_id on messages (session_id, created_at, id)')
diff --git a/storage/models.py b/storage/models.py
index eb0ab0062..8d7d936d2 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -121,6 +121,7 @@ agent_sessions = Table(
Column("title", Text, nullable=True),
Column("status", String, nullable=False),
Column("visibility", String, nullable=False, server_default="foreground"),
+ Column("pinned", Integer, nullable=False, server_default="0"),
# Live agent-runtime status, distinct from the lifecycle ``status``
# (active/archived). One of ``idle`` / ``running`` / ``failed`` —
# ``running`` while a turn is in flight, ``failed`` when the most recent
@@ -135,6 +136,15 @@ agent_sessions = Table(
Index("ix_agent_sessions_status_activity", "status", "last_active_at"),
Index("ix_agent_sessions_visibility", "visibility"),
Index("ix_agent_sessions_scope_status_activity", "scope_id", "status", "last_active_at", "created_at", "id"),
+ Index(
+ "ix_agent_sessions_scope_status_pinned_activity",
+ "scope_id",
+ "status",
+ "pinned",
+ "last_active_at",
+ "created_at",
+ "id",
+ ),
Index("ix_agent_sessions_native_session", "native_session_id"),
)
diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.py
index 78c5026b0..383b0b071 100644
--- a/storage/workbench_sessions_service.py
+++ b/storage/workbench_sessions_service.py
@@ -85,6 +85,7 @@ def _row_to_payload(row: dict[str, Any]) -> dict[str, Any]:
"reasoning_effort": row.get("reasoning_effort"),
"status": row.get("status"),
"visibility": row.get("visibility") or "foreground",
+ "pinned": bool(row.get("pinned")),
# Live agent-runtime status (idle/running/failed), separate from the
# lifecycle ``status``. Older rows predating the column read as ``idle``.
"agent_status": row.get("agent_status") or "idle",
@@ -124,9 +125,10 @@ def list_sessions(
) -> dict[str, Any]:
"""Return sessions for the workbench list. Cursor pagination via ``before_id``.
- ``status`` accepts ``active`` / ``archived`` (or omit for both). The
- cursor is the row id; results are sorted by ``last_active_at DESC``
- so the cursor row is "the last id you already saw".
+ ``status`` accepts ``active`` / ``archived`` (or omit for both). Project
+ lists put pinned sessions first, then preserve the existing activity order
+ inside each group. The cursor is the row id and resolves the complete sort
+ tuple so a page can cross the pinned/unpinned boundary without skipping.
``title_query`` powers the chat composer ``#``-mention global search: a
case-insensitive title LIKE match (LIKE metacharacters escaped).
@@ -143,17 +145,22 @@ def list_sessions(
like = escape_sql_like(title_query.strip())
if like:
query = query.where(agent_sessions.c.title.ilike(f"%{like}%", escape="\\"))
+ order_by_pinned = scope_id is not None
if before_id is not None:
cursor_row = conn.execute(
- select(agent_sessions.c.last_active_at, agent_sessions.c.created_at).where(agent_sessions.c.id == before_id)
+ select(
+ agent_sessions.c.pinned,
+ agent_sessions.c.last_active_at,
+ agent_sessions.c.created_at,
+ ).where(agent_sessions.c.id == before_id)
).first()
if cursor_row is not None:
- cursor_active, cursor_created = cursor_row
+ cursor_pinned, cursor_active, cursor_created = cursor_row
# ``last_active_at`` + ``created_at`` are both second-granularity
# ISO strings, so multiple sessions can share the same pair and
# become unreachable on later pages without an ``id`` tie-breaker
# that matches the ORDER BY shape.
- query = query.where(
+ activity_after_cursor = (
(agent_sessions.c.last_active_at < cursor_active)
| (
(agent_sessions.c.last_active_at == cursor_active)
@@ -165,15 +172,29 @@ def list_sessions(
& (agent_sessions.c.id < before_id)
)
)
+ if order_by_pinned:
+ pinned_value = int(cursor_pinned or 0)
+ query = query.where(
+ (agent_sessions.c.pinned < pinned_value)
+ | (
+ (agent_sessions.c.pinned == pinned_value)
+ & activity_after_cursor
+ )
+ )
+ else:
+ query = query.where(activity_after_cursor)
effective_limit = min(max(int(limit), 1), 200)
- query = (
- query.order_by(
+ order_columns = []
+ if order_by_pinned:
+ order_columns.append(agent_sessions.c.pinned.desc())
+ order_columns.extend(
+ [
agent_sessions.c.last_active_at.desc(),
agent_sessions.c.created_at.desc(),
agent_sessions.c.id.desc(),
- )
- .limit(effective_limit)
+ ]
)
+ query = query.order_by(*order_columns).limit(effective_limit)
rows = [dict(row) for row in conn.execute(query).mappings().all()]
sessions = [_row_to_payload(row) for row in rows]
# Use the clamped page size for the cursor check — comparing against
@@ -376,6 +397,7 @@ def update_session(
model: Any = _UNSET,
reasoning_effort: Any = _UNSET,
visibility: Any = _UNSET,
+ pinned: Any = _UNSET,
scope_id: Any = _UNSET,
) -> dict[str, Any]:
existing = conn.execute(
@@ -465,6 +487,10 @@ def update_session(
if visibility_value not in SESSION_VISIBILITIES:
raise ValueError(f"invalid session visibility: {visibility!r}")
values["visibility"] = visibility_value
+ if pinned is not _UNSET:
+ if not isinstance(pinned, bool):
+ raise ValueError("pinned must be a boolean")
+ values["pinned"] = int(pinned)
if scope_id is not _UNSET:
target_scope_id = str(scope_id) if scope_id is not None else None
target_scope = None
diff --git a/tests/test_core_services_sessions.py b/tests/test_core_services_sessions.py
index 80dcb1559..fd057e041 100644
--- a/tests/test_core_services_sessions.py
+++ b/tests/test_core_services_sessions.py
@@ -172,6 +172,70 @@ def test_update_then_list_reflects_changes(isolated_state):
assert page["sessions"][0]["model"] == "claude-sonnet-4-6"
+def test_project_session_pins_sort_first_and_paginate_across_groups(isolated_state):
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_avibe_scope(conn)
+
+ def create(title: str, last_active_at: str, *, pinned: bool = False) -> dict:
+ row = sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend="claude",
+ title=title,
+ )
+ conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == row["id"])
+ .values(last_active_at=last_active_at)
+ )
+ if pinned:
+ row = sessions_service.update_session(conn, row["id"], pinned=True)
+ return row
+
+ create("unpinned-new", "2026-07-24T05:00:00Z")
+ create("pinned-old", "2026-07-24T01:00:00Z", pinned=True)
+ create("pinned-new", "2026-07-24T04:00:00Z", pinned=True)
+ create("unpinned-old", "2026-07-24T02:00:00Z")
+ create("pinned-mid", "2026-07-24T03:00:00Z", pinned=True)
+
+ with engine.connect() as conn:
+ first = sessions_service.list_sessions(conn, scope_id=scope_id, limit=2)
+ second = sessions_service.list_sessions(
+ conn,
+ scope_id=scope_id,
+ limit=2,
+ before_id=first["next_before_id"],
+ )
+ third = sessions_service.list_sessions(
+ conn,
+ scope_id=scope_id,
+ limit=2,
+ before_id=second["next_before_id"],
+ )
+
+ assert [(row["title"], row["pinned"]) for row in first["sessions"]] == [
+ ("pinned-new", True),
+ ("pinned-mid", True),
+ ]
+ assert [(row["title"], row["pinned"]) for row in second["sessions"]] == [
+ ("pinned-old", True),
+ ("unpinned-new", False),
+ ]
+ assert [(row["title"], row["pinned"]) for row in third["sessions"]] == [
+ ("unpinned-old", False),
+ ]
+
+
+def test_update_session_requires_boolean_pin_state(isolated_state):
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_avibe_scope(conn)
+ session = sessions_service.create_session(conn, scope_id=scope_id, agent_backend="claude")
+ with pytest.raises(ValueError, match="pinned must be a boolean"):
+ sessions_service.update_session(conn, session["id"], pinned="true")
+
+
def test_session_lists_only_include_foreground_sessions(isolated_state):
engine = create_sqlite_engine()
with engine.begin() as conn:
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index c76d63e74..e021cc304 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -19,7 +19,7 @@ from storage.models import metadata
from storage.settings_service import SQLiteSettingsService
-HEAD_REVISION = "20260723_0033"
+HEAD_REVISION = "20260724_0034"
def _index_sql(conn: sqlite3.Connection, name: str) -> str:
@@ -118,6 +118,12 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
)
}
assert "ix_agent_sessions_scope_status_activity" in agent_session_indexes
+ assert "ix_agent_sessions_scope_status_pinned_activity" in agent_session_indexes
+ agent_session_columns = {
+ row[1]: row for row in conn.execute("pragma table_info(agent_sessions)")
+ }
+ assert agent_session_columns["pinned"][3] == 1
+ assert str(agent_session_columns["pinned"][4]).strip("'") == "0"
media_columns = {
row[1] for row in conn.execute("pragma table_info(media_objects)")
}
@@ -139,6 +145,56 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
assert version == (HEAD_REVISION,)
+def test_session_pinning_migration_preserves_existing_sessions_as_unpinned(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260723_0033")
+ now = "2026-07-24T00:00:00Z"
+
+ with sqlite3.connect(db_path) as conn:
+ conn.execute(
+ """
+ insert into scopes (
+ id, platform, scope_type, native_id, native_type, is_private,
+ supports_threads, metadata_json, first_seen_at, last_seen_at, updated_at
+ ) values (
+ 'scope_pin', 'avibe', 'project', 'proj_pin', null, 0,
+ 0, '{}', ?, ?, ?
+ )
+ """,
+ (now, now, now),
+ )
+ conn.execute(
+ """
+ insert into agent_sessions (
+ id, scope_id, agent_backend, agent_variant, session_anchor,
+ workdir, native_session_id, title, status, visibility, agent_status,
+ metadata_json, created_at, updated_at, last_active_at
+ ) values (
+ 'ses_existing', 'scope_pin', 'codex', 'codex', 'ses_existing',
+ '/tmp/project', '', 'Existing session', 'active', 'foreground', 'idle',
+ '{}', ?, ?, ?
+ )
+ """,
+ (now, now, now),
+ )
+ conn.commit()
+
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ pinned = conn.execute(
+ "select pinned from agent_sessions where id = 'ses_existing'"
+ ).fetchone()
+ indexes = {
+ row[1] for row in conn.execute("pragma index_list('agent_sessions')")
+ }
+ version = conn.execute("select version_num from alembic_version").fetchone()
+
+ assert pinned == (0,)
+ assert "ix_agent_sessions_scope_status_pinned_activity" in indexes
+ assert version == (HEAD_REVISION,)
+
+
def test_session_visibility_migration_reparents_legacy_runs_and_self_anchors(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"
run_migrations(db_path, revision="20260721_0031")
diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.py
index bf9d86990..9f8ed545d 100644
--- a/tests/test_ui_session_stream.py
+++ b/tests/test_ui_session_stream.py
@@ -890,6 +890,54 @@ def test_patch_session_visibility_and_scope_are_independent(isolated_state, tmp_
assert activity[-1]["scope_id"] == original_scope_id
+def test_patch_session_pin_persists_and_broadcasts(isolated_state, tmp_path, monkeypatch):
+ import vibe.sse_broker as sse_broker
+ from vibe.ui_server import app
+
+ scope_id, session_id = _make_session(tmp_path)
+ published: list[tuple[str, dict]] = []
+ monkeypatch.setattr(sse_broker.broker, "publish", lambda topic, data: published.append((topic, data)))
+
+ client = app.test_client()
+ response = client.patch(
+ f"/api/sessions/{session_id}",
+ json={"pinned": True},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 200
+ assert response.get_json()["pinned"] is True
+ activity = [data for topic, data in published if topic == "session.activity"]
+ assert activity == [
+ {
+ "session_id": session_id,
+ "scope_id": scope_id,
+ "event": "updated",
+ "title": None,
+ "visibility": "foreground",
+ "pinned": True,
+ }
+ ]
+
+ get_response = client.get(f"/api/sessions/{session_id}")
+ assert get_response.get_json()["pinned"] is True
+
+
+def test_patch_session_rejects_non_boolean_pin(isolated_state, tmp_path):
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+ client = app.test_client()
+ response = client.patch(
+ f"/api/sessions/{session_id}",
+ json={"pinned": "true"},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 400
+ assert response.get_json()["error"] == "pinned must be a boolean"
+
+
def test_patch_session_rejects_invalid_visibility(isolated_state, tmp_path):
from vibe.ui_server import app
diff --git a/ui/src/components/workbench/ProjectsPage.tsx b/ui/src/components/workbench/ProjectsPage.tsx
index d5e76fadb..b66b77978 100644
--- a/ui/src/components/workbench/ProjectsPage.tsx
+++ b/ui/src/components/workbench/ProjectsPage.tsx
@@ -13,6 +13,8 @@ import {
GitFork,
Loader2,
Pencil,
+ Pin,
+ PinOff,
Plus,
RotateCw,
Settings2,
@@ -246,7 +248,7 @@ const MobileSessionRow: React.FC<{
onOpen: () => void;
}> = ({ projectId, session, unread, onOpen }) => {
const { t } = useTranslation();
- const { renameSession, archiveSession, forkSession } = useWorkbenchProjectsTree();
+ const { renameSession, setSessionPinned, archiveSession, forkSession } = useWorkbenchProjectsTree();
const navigate = useNavigate();
const [menuOpen, setMenuOpen] = useState(false);
const [archiveOpen, setArchiveOpen] = useState(false);
@@ -255,6 +257,7 @@ const MobileSessionRow: React.FC<{
const inputRef = useRef<HTMLInputElement | null>(null);
const handledRef = useRef(false);
const forkingRef = useRef(false);
+ const pinningRef = useRef(false);
useEffect(() => {
if (renaming) inputRef.current?.focus();
@@ -309,6 +312,15 @@ const MobileSessionRow: React.FC<{
<span className="min-w-0 flex-1 truncate text-[13px] font-medium">
{session.title || `#${session.id.slice(-6)}`}
</span>
+ {session.pinned && (
+ <span
+ className="flex shrink-0 text-cyan"
+ aria-label={t('workbench.sessionPinned')}
+ title={t('workbench.sessionPinned')}
+ >
+ <Pin className="size-3.5" aria-hidden="true" />
+ </span>
+ )}
{unread > 0 ? (
<span className="shrink-0 rounded-full bg-mint px-1.5 py-0.5 font-mono text-[10px] font-bold text-background">
{unread > 99 ? '99+' : unread}
@@ -332,6 +344,23 @@ const MobileSessionRow: React.FC<{
</Button>
</PopoverTrigger>
<PopoverContent align="end" className="w-[176px] p-1">
+ <MenuItem
+ icon={session.pinned ? PinOff : Pin}
+ onClick={() => {
+ setMenuOpen(false);
+ if (pinningRef.current) return;
+ pinningRef.current = true;
+ void setSessionPinned(projectId, session.id, !session.pinned)
+ .catch(() => {
+ // apiFetch already surfaced the error toast.
+ })
+ .finally(() => {
+ pinningRef.current = false;
+ });
+ }}
+ >
+ {t(session.pinned ? 'workbench.sessionUnpin' : 'workbench.sessionPin')}
+ </MenuItem>
<MenuItem
icon={Pencil}
onClick={() => {
diff --git a/ui/src/components/workbench/WorkbenchSidebar.tsx b/ui/src/components/workbench/WorkbenchSidebar.tsx
index 1bd182b63..d01c8038d 100644
--- a/ui/src/components/workbench/WorkbenchSidebar.tsx
+++ b/ui/src/components/workbench/WorkbenchSidebar.tsx
@@ -21,6 +21,8 @@ import {
KeyRound,
Loader2,
Pencil,
+ Pin,
+ PinOff,
Plus,
Search,
Settings2,
@@ -208,9 +210,10 @@ const SessionRow: React.FC<{
session: WorkbenchSession;
unread: number;
onForkSession: (sessionId: string) => Promise<WorkbenchSession | null>;
+ onSetPinned: (sessionId: string, pinned: boolean) => Promise<void>;
onRenameSession: (sessionId: string, title: string) => Promise<void>;
onArchiveSession: (sessionId: string) => Promise<void>;
-}> = ({ session, unread, onForkSession, onRenameSession, onArchiveSession }) => {
+}> = ({ session, unread, onForkSession, onSetPinned, onRenameSession, onArchiveSession }) => {
const { t } = useTranslation();
const navigate = useNavigate();
const api = useApi();
@@ -225,6 +228,7 @@ const SessionRow: React.FC<{
const [menuOpen, setMenuOpen] = useState(false);
const [archiveOpen, setArchiveOpen] = useState(false);
const [forking, setForking] = useState(false);
+ const [pinning, setPinning] = useState(false);
const [renaming, setRenaming] = useState(false);
const [draft, setDraft] = useState(session.title ?? '');
const inputRef = useRef<HTMLInputElement | null>(null);
@@ -316,6 +320,15 @@ const SessionRow: React.FC<{
>
{displayName}
</span>
+ {session.pinned && (
+ <span
+ className="flex shrink-0 text-cyan"
+ aria-label={t('workbench.sessionPinned')}
+ title={t('workbench.sessionPinned')}
+ >
+ <Pin className="size-3" aria-hidden="true" />
+ </span>
+ )}
{unread > 0 && (
<span className="inline-flex min-w-[1.1rem] items-center justify-center rounded-full bg-mint px-1.5 font-mono text-[9px] font-bold text-[#080812]">
{unread > 99 ? '99+' : unread}
@@ -324,6 +337,32 @@ const SessionRow: React.FC<{
</button>
</PopoverAnchor>
<PopoverContent align="start" className="w-[176px] p-1">
+ <button
+ type="button"
+ disabled={pinning}
+ onClick={async () => {
+ if (pinning) return;
+ setMenuOpen(false);
+ setPinning(true);
+ try {
+ await onSetPinned(session.id, !session.pinned);
+ } catch {
+ // apiFetch already surfaced the error toast.
+ } finally {
+ setPinning(false);
+ }
+ }}
+ className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground transition hover:bg-foreground/[0.04] disabled:cursor-not-allowed disabled:text-muted"
+ >
+ {pinning ? (
+ <Loader2 className="size-3 animate-spin text-muted" />
+ ) : session.pinned ? (
+ <PinOff className="size-3 text-muted" />
+ ) : (
+ <Pin className="size-3 text-muted" />
+ )}
+ {t(session.pinned ? 'workbench.sessionUnpin' : 'workbench.sessionPin')}
+ </button>
{canReference && (
<button
type="button"
@@ -448,6 +487,7 @@ const ProjectRow: React.FC<{
onRename: (next: string) => Promise<void>;
onArchive: () => Promise<void>;
onForkSession: (sessionId: string) => Promise<WorkbenchSession | null>;
+ onSetPinned: (sessionId: string, pinned: boolean) => Promise<void>;
onRenameSession: (sessionId: string, title: string) => Promise<void>;
onArchiveSession: (sessionId: string) => Promise<void>;
}> = ({
@@ -465,6 +505,7 @@ const ProjectRow: React.FC<{
onRename,
onArchive,
onForkSession,
+ onSetPinned,
onRenameSession,
onArchiveSession,
}) => {
@@ -661,6 +702,7 @@ const ProjectRow: React.FC<{
session={session}
unread={unreadBySession[session.id] || 0}
onForkSession={onForkSession}
+ onSetPinned={onSetPinned}
onRenameSession={onRenameSession}
onArchiveSession={onArchiveSession}
/>
@@ -714,6 +756,7 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
renameProject,
archiveProject,
renameSession,
+ setSessionPinned,
archiveSession,
upsertProjectToTop,
} = useWorkbenchProjectsTree();
@@ -955,6 +998,7 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
onRename={(next) => renameProject(project.id, next)}
onArchive={() => archiveProject(project.id)}
onForkSession={(sessionId) => forkSession(project.id, sessionId)}
+ onSetPinned={(sessionId, pinned) => setSessionPinned(project.id, sessionId, pinned)}
onRenameSession={(sessionId, title) => renameSession(project.id, sessionId, title)}
onArchiveSession={(sessionId) => archiveSession(project.id, sessionId)}
/>
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 7ba9fcca4..768b2db4f 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -754,6 +754,7 @@ export type WorkbenchSession = {
model: string | null;
reasoning_effort: string | null;
status: string;
+ pinned: boolean;
/** Live agent-runtime status driving the sidebar dot: idle (gray) /
* running (green) / failed (red). Distinct from the lifecycle ``status``. */
agent_status: 'idle' | 'running' | 'failed';
@@ -787,6 +788,7 @@ export type WorkbenchSessionUpdate = {
agent_variant: string;
model: string | null;
reasoning_effort: string | null;
+ pinned: boolean;
};
// One Vibe Agent row from ``/agents`` (brief view used in list rendering).
@@ -941,6 +943,7 @@ export type WorkbenchEventHandlers = {
event: string;
title?: string | null;
visibility?: 'foreground' | 'background';
+ pinned?: boolean;
// Client-synthesized marker (never on a real backend event): a foreground
// restore, so the projects tree grows its window to bring the row back.
restored?: boolean;
diff --git a/ui/src/context/WorkbenchProjectsContext.tsx b/ui/src/context/WorkbenchProjectsContext.tsx
index 5e3cf58d0..2d6000da4 100644
--- a/ui/src/context/WorkbenchProjectsContext.tsx
+++ b/ui/src/context/WorkbenchProjectsContext.tsx
@@ -4,6 +4,7 @@ import type { ReactNode } from 'react';
import { useApi } from './ApiContext';
import type { ProjectDefaultAgent, WorkbenchProject, WorkbenchSession, WorkbenchSessionCreate } from './ApiContext';
import { createdReconcileMinCount } from '../lib/sessionVisibilityEvents';
+import { orderProjectSessions } from '../lib/sessionPinning';
// How many sessions to load per page under a project. The server clamps the
// /api/sessions limit (to 200) and returns a cursor (next_before_id); both the
@@ -65,6 +66,8 @@ export interface WorkbenchProjectsTree {
archiveProject: (projectId: string) => Promise<void>;
/** Throws on failure so the row's inline editor can fall back; patches title on success. */
renameSession: (projectId: string, sessionId: string, title: string) => Promise<void>;
+ /** Persist pin state and keep the session in the project's pinned-first order. */
+ setSessionPinned: (projectId: string, sessionId: string, pinned: boolean) => Promise<void>;
/** Permanently archive a session: calls the API (which reclaims its bound
* tasks/watches/runs) then drops the row from the tree. Throws on failure. */
archiveSession: (projectId: string, sessionId: string) => Promise<void>;
@@ -80,6 +83,7 @@ function patchSessionRow(
prev: Record<string, ProjectSessionsState>,
sessionId: string,
patch: (session: WorkbenchSession) => WorkbenchSession,
+ reorder = false,
): Record<string, ProjectSessionsState> {
let changed = false;
const next: Record<string, ProjectSessionsState> = {};
@@ -95,7 +99,9 @@ function patchSessionRow(
if (updated !== s) rowChanged = true;
return updated;
});
- next[projectId] = rowChanged ? { ...state, sessions: rows } : state;
+ next[projectId] = rowChanged
+ ? { ...state, sessions: reorder ? orderProjectSessions(rows) : rows }
+ : state;
if (rowChanged) changed = true;
}
return changed ? next : prev;
@@ -403,11 +409,35 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
setSessions((prev) => removeSessionRow(prev, data.session_id));
return;
}
- if (data.event === 'updated' && Object.prototype.hasOwnProperty.call(data, 'title')) {
+ if (data.event === 'updated') {
+ const hasTitle = Object.prototype.hasOwnProperty.call(data, 'title');
+ const hasPinned = typeof data.pinned === 'boolean';
+ if (!hasTitle && !hasPinned) return;
const nextTitle = data.title ?? null;
setSessions((prev) =>
- patchSessionRow(prev, data.session_id, (s) => (s.title === nextTitle ? s : { ...s, title: nextTitle })),
+ patchSessionRow(
+ prev,
+ data.session_id,
+ (session) => {
+ const titleChanged = hasTitle && session.title !== nextTitle;
+ const pinnedChanged = hasPinned && session.pinned !== data.pinned;
+ if (!titleChanged && !pinnedChanged) return session;
+ return {
+ ...session,
+ ...(titleChanged ? { title: nextTitle } : {}),
+ ...(pinnedChanged ? { pinned: data.pinned as boolean } : {}),
+ };
+ },
+ hasPinned,
+ ),
);
+ if (hasPinned) {
+ const projectId = projectsRef.current?.find((project) => project.scope_id === data.scope_id)?.id;
+ if (projectId) {
+ const loaded = sessionsRef.current[projectId]?.sessions?.length ?? 0;
+ void reconcileSessions(projectId, { minCount: loaded });
+ }
+ }
return;
}
if (!REORDER_ACTIVITY_EVENTS.has(data.event)) return;
@@ -475,7 +505,13 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
setSessions((prev) => {
const cur = prev[projectId] ?? EMPTY_SESSIONS;
const rows = cur.sessions ?? [];
- return { ...prev, [projectId]: { ...cur, sessions: [session, ...rows.filter((s) => s.id !== session.id)] } };
+ return {
+ ...prev,
+ [projectId]: {
+ ...cur,
+ sessions: orderProjectSessions([session, ...rows.filter((s) => s.id !== session.id)]),
+ },
+ };
});
}
setExpanded((prev) => {
@@ -521,7 +557,13 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
setSessions((prev) => {
const cur = prev[projectId] ?? EMPTY_SESSIONS;
const rows = cur.sessions ?? [];
- return { ...prev, [projectId]: { ...cur, sessions: [session, ...rows.filter((s) => s.id !== session.id)] } };
+ return {
+ ...prev,
+ [projectId]: {
+ ...cur,
+ sessions: orderProjectSessions([session, ...rows.filter((s) => s.id !== session.id)]),
+ },
+ };
});
}
setExpanded((prev) => {
@@ -596,6 +638,16 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
[api],
);
+ const setSessionPinned = useCallback(
+ async (projectId: string, sessionId: string, pinned: boolean) => {
+ const updated = await api.updateSession(sessionId, { pinned });
+ setSessions((prev) => patchSessionRow(prev, sessionId, () => updated, true));
+ const loaded = sessionsRef.current[projectId]?.sessions?.length ?? 0;
+ void reconcileSessions(projectId, { minCount: loaded });
+ },
+ [api, reconcileSessions],
+ );
+
const archiveSession = useCallback(
async (projectId: string, sessionId: string) => {
// Archive is terminal — the API reclaims bound tasks/watches/runs server-side.
@@ -655,6 +707,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
setProjectDefaultAgent,
archiveProject,
renameSession,
+ setSessionPinned,
archiveSession,
upsertProjectToTop,
}),
@@ -675,6 +728,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
setProjectDefaultAgent,
archiveProject,
renameSession,
+ setSessionPinned,
archiveSession,
upsertProjectToTop,
],
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index b10cb842e..4299e1213 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1263,6 +1263,9 @@
"projectRenamePlaceholder": "New name",
"sessionRename": "Rename",
"sessionRenamePlaceholder": "Session name",
+ "sessionPin": "Pin to top",
+ "sessionUnpin": "Unpin",
+ "sessionPinned": "Pinned",
"sessionReference": "Reference this session",
"sessionFork": "Fork session",
"sessionForkUnavailable": "This session has no native agent session to fork yet.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 57ae0c89e..11188ecb3 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1263,6 +1263,9 @@
"projectRenamePlaceholder": "新名字",
"sessionRename": "重命名",
"sessionRenamePlaceholder": "会话名称",
+ "sessionPin": "置顶",
+ "sessionUnpin": "取消置顶",
+ "sessionPinned": "已置顶",
"sessionReference": "引用该会话",
"sessionFork": "复刻会话",
"sessionForkUnavailable": "此会话还没有可复刻的原生 Agent 会话。",
diff --git a/ui/src/lib/sessionPinning.test.ts b/ui/src/lib/sessionPinning.test.ts
new file mode 100644
index 000000000..933fde581
--- /dev/null
+++ b/ui/src/lib/sessionPinning.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from 'vitest';
+
+import type { WorkbenchSession } from '../context/ApiContext';
+import { orderProjectSessions } from './sessionPinning';
+
+const session = (id: string, pinned: boolean, lastActive: string): WorkbenchSession => ({
+ id,
+ scope_id: 'avibe::project::proj_test',
+ project_id: 'proj_test',
+ title: id,
+ agent_id: null,
+ agent_name: null,
+ agent_backend: null,
+ agent_variant: null,
+ model: null,
+ reasoning_effort: null,
+ status: 'active',
+ agent_status: 'idle',
+ workdir: '/tmp/project',
+ native_session_id: null,
+ pinned,
+ created_at: lastActive,
+ updated_at: lastActive,
+ last_active_at: lastActive,
+ metadata: {},
+});
+
+describe('orderProjectSessions', () => {
+ it('keeps every pinned session above newer unpinned sessions', () => {
+ const rows = orderProjectSessions([
+ session('new-unpinned', false, '2026-07-24T03:00:00Z'),
+ session('old-pinned', true, '2026-07-24T01:00:00Z'),
+ session('new-pinned', true, '2026-07-24T02:00:00Z'),
+ ]);
+
+ expect(rows.map((row) => row.id)).toEqual(['new-pinned', 'old-pinned', 'new-unpinned']);
+ });
+});
diff --git a/ui/src/lib/sessionPinning.ts b/ui/src/lib/sessionPinning.ts
new file mode 100644
index 000000000..9f47490fd
--- /dev/null
+++ b/ui/src/lib/sessionPinning.ts
@@ -0,0 +1,16 @@
+import type { WorkbenchSession } from '../context/ApiContext';
+
+const compareDesc = (left: string | null, right: string | null): number =>
+ (right ?? '').localeCompare(left ?? '');
+
+export const compareProjectSessions = (left: WorkbenchSession, right: WorkbenchSession): number => {
+ if (left.pinned !== right.pinned) return left.pinned ? -1 : 1;
+ return (
+ compareDesc(left.last_active_at, right.last_active_at) ||
+ compareDesc(left.created_at, right.created_at) ||
+ compareDesc(left.id, right.id)
+ );
+};
+
+export const orderProjectSessions = (sessions: WorkbenchSession[]): WorkbenchSession[] =>
+ [...sessions].sort(compareProjectSessions);
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 4804408be..bb732fb5d 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -6371,6 +6371,7 @@ def _publish_session_update_activity(
"event": "updated",
"title": session.get("title"),
"visibility": session.get("visibility"),
+ "pinned": bool(session.get("pinned")),
},
)
if previous_session is None:
@@ -6431,6 +6432,7 @@ async def sessions_update(session_id: str):
"model",
"reasoning_effort",
"visibility",
+ "pinned",
"scope_id",
)
if key in payload