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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(workbench): fork sessions from sidebar
cyhf28d0db25ec9
diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.pyindex e961459dc..7f7512aae 100644--- a/tests/test_ui_session_stream.py+++ b/tests/test_ui_session_stream.py@@ -172,6 +172,63 @@ def test_create_session_without_backend_defers_to_default_agent(isolated_state,assert not response.get_json().get("agent_backend")+def test_fork_session_creates_new_workbench_session(isolated_state, tmp_path):+ """POST /api/sessions/<id>/fork reserves a new Avibe Session row that is+ ready for the native backend fork on the first turn, and returns the row the+ sidebar needs to prepend/navigate immediately.+ """++ from sqlalchemy import update++ from storage.db import create_sqlite_engine+ from storage.models import agent_sessions+ from vibe.ui_server import app++ scope_id, session_id = _make_session(tmp_path)+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ conn.execute(+ update(agent_sessions)+ .where(agent_sessions.c.id == session_id)+ .values(native_session_id="native-source-1", title="Source session")+ )++ with patch("vibe.sse_broker.broker.publish") as publish:+ client = app.test_client()+ headers = csrf_headers(client)+ response = client.post(f"/api/sessions/{session_id}/fork", json={}, headers=headers)++ assert response.status_code == 201+ payload = response.get_json()+ assert payload["id"] != session_id+ assert payload["scope_id"] == scope_id+ assert payload["project_id"] == "proj_stream"+ assert payload["title"] == "Source session"+ assert payload["agent_backend"] == "claude"+ assert payload["agent_name"] == "worker"+ assert payload["native_session_id"] == ""+ assert payload["metadata"]["created_via"] == "session_fork"+ assert payload["metadata"]["fork_source_session_id"] == session_id+ assert payload["metadata"]["fork_source_native_session_id"] == "native-source-1"+ publish.assert_called_with(+ "session.activity",+ {"session_id": payload["id"], "scope_id": scope_id, "event": "created"},+ )+++def test_fork_session_rejects_unbound_source_session(isolated_state, tmp_path):+ from vibe.ui_server import app++ _, session_id = _make_session(tmp_path)++ client = app.test_client()+ headers = csrf_headers(client)+ response = client.post(f"/api/sessions/{session_id}/fork", json={}, headers=headers)++ assert response.status_code == 409+ assert response.get_json()["code"] == "session_not_bound"++def test_chat_bootstrap_returns_first_screen_payload(isolated_state, tmp_path):from storage import messages_servicefrom storage.db import create_sqlite_enginediff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex 28889be03..9650927dc 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -1,7 +1,7 @@import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import { useLocation, useNavigate, useParams } from 'react-router-dom';-import { AppWindow, ArrowLeft, Bell, Bot, ChevronDown, Clock, Info, Loader2, MessageSquare, Pencil, UploadCloud, X } from 'lucide-react';+import { Link, useLocation, useNavigate, useParams } from 'react-router-dom';+import { AppWindow, ArrowLeft, Bell, Bot, ChevronDown, Clock, GitFork, Info, Loader2, MessageSquare, Pencil, UploadCloud, X } from 'lucide-react';import clsx from 'clsx';import { useApi } from '../../context/ApiContext';@@ -1404,6 +1404,11 @@ const Transcript: React.FC<TranscriptProps> = ({onQuickReply,}) => {const { t } = useTranslation();+ const forkSourceSessionId =+ typeof session.metadata?.fork_source_session_id === 'string'+ ? session.metadata.fork_source_session_id+ : null;+ const isForkedSession = session.metadata?.created_via === 'session_fork';const scrollRef = useRef<HTMLDivElement | null>(null);const contentRef = useRef<HTMLDivElement | null>(null);// ``true`` while the viewport is FOLLOWING the bottom (at/near it) — drives the@@ -1535,6 +1540,21 @@ const Transcript: React.FC<TranscriptProps> = ({}, [empty]);if (empty) {+ if (isForkedSession && forkSourceSessionId) {+ return (+ <div className="flex flex-1 flex-col items-center justify-center gap-3 px-6 text-center text-muted">+ <GitFork className="size-8 opacity-70" />+ <div className="max-w-[360px] text-[13px] font-semibold text-foreground">{t('chat.forkedEmptyTitle')}</div>+ <div className="max-w-[440px] text-[12px] leading-relaxed">{t('chat.forkedEmptyBody')}</div>+ <Link+ to={`/chat/${encodeURIComponent(forkSourceSessionId)}`}+ className="text-[12px] font-medium text-cyan hover:underline"+ >+ {t('chat.forkedSource')}+ </Link>+ </div>+ );+ }return (<div className="flex flex-1 flex-col items-center justify-center gap-3 px-6 text-center text-muted"><MessageSquare className="size-8 opacity-60" />diff --git a/ui/src/components/workbench/WorkbenchSidebar.tsx b/ui/src/components/workbench/WorkbenchSidebar.tsxindex 299770baa..6bb61f0b7 100644--- a/ui/src/components/workbench/WorkbenchSidebar.tsx+++ b/ui/src/components/workbench/WorkbenchSidebar.tsx@@ -13,6 +13,7 @@ import {Folder,FolderOpen,FolderPlus,+ GitFork,Hash,Inbox,KeyRound,@@ -187,17 +188,17 @@ const STATUS_DOT_CLASS: Record<string, string> = {};// One session row under a project. Left-click opens the chat; right-click opens-// a small menu whose action is Rename — an inline edit equivalent to the chat-// header's title field. Rename calls api.updateSession({ title }); the live+// the session action menu. Rename calls api.updateSession({ title }); the live// session.activity 'updated' event then patches the title in this list (see the// onSessionActivity handler in WorkbenchSidebar), so no manual local patch here.const SessionRow: React.FC<{session: WorkbenchSession;unread: number;onSessionMarkRead: (sessionId: string) => void;+ onForkSession: (sessionId: string) => Promise<WorkbenchSession | null>;onRenameSession: (sessionId: string, title: string) => Promise<void>;onArchiveSession: (sessionId: string) => Promise<void>;-}> = ({ session, unread, onSessionMarkRead, onRenameSession, onArchiveSession }) => {+}> = ({ session, unread, onSessionMarkRead, onForkSession, onRenameSession, onArchiveSession }) => {const { t } = useTranslation();const navigate = useNavigate();const location = useLocation();@@ -208,6 +209,7 @@ const SessionRow: React.FC<{const canReference = insertTarget != null && insertTarget.sessionId !== session.id;const [menuOpen, setMenuOpen] = useState(false);const [archiveOpen, setArchiveOpen] = useState(false);+ const [forking, setForking] = useState(false);const [renaming, setRenaming] = useState(false);const [draft, setDraft] = useState(session.title ?? '');const inputRef = useRef<HTMLInputElement | null>(null);@@ -265,6 +267,7 @@ const SessionRow: React.FC<{}const displayName = session.title?.trim() || t('workbench.untitledSession');+ const canFork = !forking;return (<><Popover open={menuOpen} onOpenChange={setMenuOpen}>@@ -322,6 +325,25 @@ const SessionRow: React.FC<{{t('workbench.sessionReference')}</button>)}+ <button+ type="button"+ disabled={!canFork}+ onClick={async () => {+ if (!canFork) return;+ setMenuOpen(false);+ setForking(true);+ try {+ const forked = await onForkSession(session.id);+ if (forked) navigate(`/chat/${encodeURIComponent(forked.id)}`);+ } finally {+ setForking(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 disabled:hover:bg-transparent"+ >+ {forking ? <Loader2 className="size-3 animate-spin text-muted" /> : <GitFork className="size-3 text-muted" />}+ {t('workbench.sessionFork')}+ </button><buttontype="button"onClick={() => {@@ -383,6 +405,7 @@ const ProjectRow: React.FC<{onSessionMarkRead: (sessionId: string) => void;onRename: (next: string) => Promise<void>;onArchive: () => Promise<void>;+ onForkSession: (sessionId: string) => Promise<WorkbenchSession | null>;onRenameSession: (sessionId: string, title: string) => Promise<void>;onArchiveSession: (sessionId: string) => Promise<void>;}> = ({@@ -400,6 +423,7 @@ const ProjectRow: React.FC<{onSessionMarkRead,onRename,onArchive,+ onForkSession,onRenameSession,onArchiveSession,}) => {@@ -580,6 +604,7 @@ const ProjectRow: React.FC<{session={session}unread={unreadBySession[session.id] || 0}onSessionMarkRead={onSessionMarkRead}+ onForkSession={onForkSession}onRenameSession={onRenameSession}onArchiveSession={onArchiveSession}/>@@ -628,6 +653,7 @@ export const WorkbenchSidebar: React.FC = () => {loadMore,creatingSession,createSessionForProject,+ forkSession,renameProject,archiveProject,renameSession,@@ -827,6 +853,7 @@ export const WorkbenchSidebar: React.FC = () => {onSessionMarkRead={markRead}onRename={(next) => renameProject(project.id, next)}onArchive={() => archiveProject(project.id)}+ onForkSession={(sessionId) => forkSession(project.id, sessionId)}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.tsxindex b6efa0b57..ea3e68266 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -176,6 +176,7 @@ export type ApiContextType = {) => Promise<{ ok: boolean; backends: GlobalPromptFile[] }>;listSessions: (params?: { projectId?: string; status?: 'active' | 'archived' | 'all'; limit?: number; beforeId?: string; q?: string; cache?: boolean }) => Promise<{ sessions: WorkbenchSession[]; next_before_id: string | null }>;createSession: (payload: WorkbenchSessionCreate) => Promise<WorkbenchSession>;+ forkSession: (sessionId: string) => Promise<WorkbenchSession>;getSession: (sessionId: string, params?: { cache?: boolean }) => Promise<WorkbenchSession>;getSessionBootstrap: (sessionId: string) => Promise<WorkbenchSessionBootstrap>;updateSession: (sessionId: string, payload: Partial<WorkbenchSessionUpdate>) => Promise<WorkbenchSession>;@@ -1675,6 +1676,8 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenreturn params?.cache === false ? getJson(path) : getCachedJson(path);},createSession: (payload) => postJson('/api/sessions', payload),+ forkSession: (sessionId) =>+ postJson(`/api/sessions/${encodeURIComponent(sessionId)}/fork`, {}),getSession: (sessionId, params) =>params?.cache === false? getJson(`/api/sessions/${encodeURIComponent(sessionId)}`)diff --git a/ui/src/context/WorkbenchProjectsContext.tsx b/ui/src/context/WorkbenchProjectsContext.tsxindex 90d46ff62..eea7fd577 100644--- a/ui/src/context/WorkbenchProjectsContext.tsx+++ b/ui/src/context/WorkbenchProjectsContext.tsx@@ -53,6 +53,8 @@ export interface WorkbenchProjectsTree {* the caller navigates (this provider is mounted outside the router). null on failure.* `overrides` lets the create surfaces pin an agent/backend; omit for the server default. */createSessionForProject: (projectId: string, overrides?: Partial<WorkbenchSessionCreate>) => Promise<WorkbenchSession | null>;+ /** Fork an existing session, prepend the new row to the source project, and return it for navigation. */+ forkSession: (projectId: string, sessionId: string) => Promise<WorkbenchSession | null>;renameProject: (projectId: string, name: string) => Promise<void>;/** Persist the project's default Agent route (Project Settings) and patch the* shared cache so the sidebar + Projects page reflect it. Pass an all-null@@ -478,6 +480,34 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c[api],);+ const forkSession = useCallback(+ async (projectId: string, sessionId: string): Promise<WorkbenchSession | null> => {+ const alreadyLoaded = sessionsRef.current[projectId]?.sessions != null;+ try {+ const session = await api.forkSession(sessionId);+ if (alreadyLoaded) {+ 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)] } };+ });+ }+ setExpanded((prev) => {+ if (prev.has(projectId)) return prev;+ const next = new Set(prev);+ next.add(projectId);+ return next;+ });+ if (!alreadyLoaded) void fetchSessions(projectId);+ return session;+ } catch (err) {+ console.error('[workbench] fork session failed', err);+ return null;+ }+ },+ [api, fetchSessions],+ );+const setProjectDefaultAgent = useCallback(async (projectId: string, route: ProjectDefaultAgent) => {// Always send the full 5-field route: a complete set is coherent whether@@ -589,6 +619,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ creloadSessions,creatingSession,createSessionForProject,+ forkSession,renameProject,setProjectDefaultAgent,archiveProject,@@ -608,6 +639,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ creloadSessions,creatingSession,createSessionForProject,+ forkSession,renameProject,setProjectDefaultAgent,archiveProject,diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 75e1a002e..a3cda2610 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -583,6 +583,7 @@"sessionRename": "Rename","sessionRenamePlaceholder": "Session name","sessionReference": "Reference this session",+ "sessionFork": "Fork session","sessionArchive": "Archive session","archiveSession": {"title": "Archive this session permanently?",@@ -1773,6 +1774,9 @@"notFound": "Session not found.","missingSessionId": "Missing session id in the URL.","transcriptEmpty": "Type a message below to start the conversation",+ "forkedEmptyTitle": "Forked session ready",+ "forkedEmptyBody": "The native agent context was forked from the source session. This transcript starts clean and will only show new messages sent here.",+ "forkedSource": "Open source session","scrollToBottom": "Scroll to latest","streaming": "Streaming","thinking": "Thinking…",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 59d1a61a7..f5762540c 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -583,6 +583,7 @@"sessionRename": "重命名","sessionRenamePlaceholder": "会话名称","sessionReference": "引用该会话",+ "sessionFork": "Fork 会话","sessionArchive": "归档会话","archiveSession": {"title": "永久归档此会话?",@@ -1772,6 +1773,9 @@"notFound": "未找到该会话。","missingSessionId": "URL 缺少 session id。","transcriptEmpty": "在下方输入消息开始对话",+ "forkedEmptyTitle": "Fork 会话已创建",+ "forkedEmptyBody": "底层 Agent 上下文已从源会话 fork 过来。这里的聊天记录从空白开始,只显示此会话里的新消息。",+ "forkedSource": "打开源会话","scrollToBottom": "回到最新","streaming": "实时输出中","thinking": "思考中…",diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 4eef546f1..fc9f506a6 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -4208,6 +4208,41 @@ def sessions_create():return jsonify(session), 201+def _session_fork_error_response(err: Exception):+ message = str(err)+ if "id not found" in message:+ return jsonify({"error": message, "code": "session_not_found"}), 404+ if "is archived" in message:+ return jsonify({"error": message, "code": "session_archived"}), 409+ if "no native session id" in message:+ return jsonify({"error": message, "code": "session_not_bound"}), 409+ if "backend cannot be forked" in message:+ return jsonify({"error": message, "code": "session_backend_unsupported"}), 409+ if "backend does not match" in message:+ return jsonify({"error": message, "code": "session_backend_mismatch"}), 409+ return jsonify({"error": message, "code": "session_fork_failed"}), 400++[email protected]("/api/sessions/<session_id>/fork", methods=["POST"])+def sessions_fork(session_id: str):+ from core.services import sessions as workbench_sessions_service+ from core.services.session_fork import SessionForkError, reserve_forked_session+ from vibe.sse_broker import broker++ try:+ result = reserve_forked_session(source_session_id=session_id)+ engine = _projects_engine()+ with engine.connect() as conn:+ session = workbench_sessions_service.get_session(conn, result.session_id)+ except SessionForkError as err:+ return _session_fork_error_response(err)+ except LookupError as err:+ return jsonify({"error": str(err), "code": "session_not_found"}), 404++ broker.publish("session.activity", {"session_id": session["id"], "scope_id": session["scope_id"], "event": "created"})+ return jsonify(session), 201++@app.route("/api/sessions/<session_id>", methods=["GET"])def sessions_get(session_id: str):from core.services import sessions as workbench_sessions_service