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.

perf(workbench): bootstrap chat session load (#471)

Call Whiteb47f137d57b2
diff --git a/docs/plans/chat-bootstrap-api.md b/docs/plans/chat-bootstrap-api.md
new file mode 100644
index 000000000..bd8cb77c7
--- /dev/null
+++ b/docs/plans/chat-bootstrap-api.md
@@ -0,0 +1,18 @@
+# Chat Bootstrap API Plan
+
+## Goal
+
+Reduce Workbench Chat first-screen latency over remote links by replacing the current fan-out of session/messages/queue/draft/turn-state/config/agents requests with one chat bootstrap request for the ChatPage initial load.
+
+## Scope
+
+- Add a read-only `GET /api/sessions/<session_id>/bootstrap` endpoint.
+- Return the same shapes ChatPage already consumes: session, recent visible messages, queue, draft, turn state, enabled agents, default agent name, and config.
+- Keep reconnect/gap recovery endpoints separate; bootstrap is for initial session load only.
+- Preserve turn-state timeout semantics: timeout is `in_flight: null`, not idle.
+
+## Validation
+
+- Backend route test for success and timeout shape.
+- Frontend production build.
+- Ruff on touched Python files.
diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.py
index 0b65f17a3..45fcfdb04 100644
--- a/tests/test_ui_session_stream.py
+++ b/tests/test_ui_session_stream.py
@@ -172,6 +172,113 @@ def test_create_session_without_backend_defers_to_default_agent(isolated_state,
assert not response.get_json().get("agent_backend")
+def test_chat_bootstrap_returns_first_screen_payload(isolated_state, tmp_path):
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+ from vibe.ui_server import app
+
+ scope_id, session_id = _make_session(tmp_path)
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ message_type="user",
+ text="question",
+ )
+ messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="agent",
+ message_type="assistant",
+ text="thinking",
+ )
+ messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="agent",
+ message_type="tool_call",
+ text="ran tool",
+ )
+ messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="agent",
+ message_type="result",
+ text="answer",
+ )
+ messages_service.enqueue_queued(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ text="follow-up",
+ )
+ messages_service.set_draft(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ text="draft text",
+ )
+
+ async def in_flight(session_id_inner):
+ assert session_id_inner == session_id
+ return {"status_code": 200, "body": {"in_flight": True}}
+
+ with (
+ patch("vibe.internal_client.turn_state", in_flight),
+ patch(
+ "vibe.api.get_vibe_agents",
+ return_value={
+ "agents": [{"name": "worker", "backend": "claude", "enabled": True}],
+ "default_agent_name": "worker",
+ },
+ ),
+ ):
+ client = app.test_client()
+ response = client.get(f"/api/sessions/{session_id}/bootstrap")
+
+ assert response.status_code == 200
+ body = response.get_json()
+ assert body["session"]["id"] == session_id
+ assert body["default_agent_name"] == "worker"
+ assert body["agents"][0]["name"] == "worker"
+ assert body["config"]["setup_state"]["needs_setup"] is True
+ assert [message["text"] for message in body["messages"]] == ["question", "answer"]
+ assert [message["type"] for message in body["messages"]] == ["user", "result"]
+ assert body["queued"][0]["text"] == "follow-up"
+ assert body["draft"]["text"] == "draft text"
+ assert body["turn_state"]["in_flight"] is True
+
+
+def test_chat_bootstrap_keeps_timeout_turn_state_unknown(isolated_state, tmp_path):
+ from vibe import internal_client
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+
+ async def timeout(session_id_inner):
+ raise internal_client.InternalServerTimeout("slow internal turn-state")
+
+ with (
+ patch("vibe.internal_client.turn_state", timeout),
+ patch("vibe.api.get_vibe_agents", return_value={"agents": [], "default_agent_name": None}),
+ ):
+ client = app.test_client()
+ response = client.get(f"/api/sessions/{session_id}/bootstrap")
+
+ assert response.status_code == 200
+ assert response.get_json()["turn_state"]["in_flight"] is None
+
+
def test_cancel_route_proxies_to_internal_socket(isolated_state, tmp_path):
_, session_id = _make_session(tmp_path)
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 2e9af0803..97bcd1787 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -341,35 +341,28 @@ export const ChatPage: React.FC = () => {
setLoading(true);
setError(null);
try {
- const [fetched, agentList, config, msgs, queued, draft, turnState] = await Promise.all([
- api.getSession(sessionId),
- api.listVibeAgents({ includeDisabled: false }),
- api.getConfig().catch(() => null),
- // Recent window (tail), so opening a long chat shows the latest
- // conversation, not its oldest page (Codex P2).
- api.listSessionMessages(sessionId, { limit: 50, tail: true }),
- api.listSessionQueue(sessionId),
- api.getSessionDraft(sessionId),
- api.getTurnState(sessionId).catch(() => ({ in_flight: null })),
- ]);
+ // Initial chat open needs the same recent tail window, queue, draft,
+ // route/config state, and current turn state. Fetch them as one bootstrap
+ // payload so remote links don't pay a tunnel round-trip per widget.
+ const bootstrap = await api.getSessionBootstrap(sessionId);
// Dropped if the user switched chats while this load was in flight.
if (sessionId !== sessionIdRef.current) return;
- setSession(fetched);
- setAgents(agentList.agents);
- setDefaultAgentName(agentList.default_agent_name);
- setMessageFontSize(normalizeChatMessageFontSize(config?.ui?.chat_message_font_size));
+ setSession(bootstrap.session);
+ setAgents(bootstrap.agents);
+ setDefaultAgentName(bootstrap.default_agent_name);
+ setMessageFontSize(normalizeChatMessageFontSize(bootstrap.config?.ui?.chat_message_font_size));
// Merge (not replace) so a row that arrived over the stream during the
// load isn't clobbered; the session-change reset keeps prior sessions out.
- setMessages((prev) => mergeById(msgs.messages, prev));
- setOlderCursor(msgs.next_before_id ?? null);
- setQueue(queued.queued ?? []);
- setInitialDraft(draft.text ?? '');
+ setMessages((prev) => mergeById(bootstrap.messages, prev));
+ setOlderCursor(bootstrap.next_before_id ?? null);
+ setQueue(bootstrap.queued ?? []);
+ setInitialDraft(bootstrap.draft?.text ?? '');
// Restore Stop for a turn that is still running (e.g. opened in another tab
// or reloaded mid-turn). markWorking on the live branch so a racing
// syncTurnState idle response can't clear it; an idle load is authoritative
// for the fresh page, so clear directly (Codex P2).
- if (turnState.in_flight) markWorking();
- else if (turnState.in_flight === false) setWorking(false);
+ if (bootstrap.turn_state.in_flight) markWorking();
+ else if (bootstrap.turn_state.in_flight === false) setWorking(false);
} catch (err: any) {
// Only surface the error if we're still on the session that failed — a
// stale failure must not stamp an error onto the chat the user moved to.
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 890e85f55..dfe1e4b57 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -168,6 +168,7 @@ export type ApiContextType = {
listSessions: (params?: { projectId?: string; status?: 'active' | 'archived' | 'all'; limit?: number; beforeId?: string; cache?: boolean }) => Promise<{ sessions: WorkbenchSession[]; next_before_id: string | null }>;
createSession: (payload: WorkbenchSessionCreate) => Promise<WorkbenchSession>;
getSession: (sessionId: string) => Promise<WorkbenchSession>;
+ getSessionBootstrap: (sessionId: string) => Promise<WorkbenchSessionBootstrap>;
updateSession: (sessionId: string, payload: Partial<WorkbenchSessionUpdate>) => Promise<WorkbenchSession>;
archiveSession: (sessionId: string) => Promise<WorkbenchSession>;
listSessionMessages: (sessionId: string, params?: { afterId?: string; beforeId?: string; limit?: number; tail?: boolean; cache?: boolean }) => Promise<{ messages: WorkbenchMessage[]; next_after_id: string | null; next_before_id?: string | null }>;
@@ -486,6 +487,19 @@ export type WorkbenchMessage = {
read_at: string | null;
};
+export type WorkbenchSessionBootstrap = {
+ session: WorkbenchSession;
+ agents: VibeAgentBrief[];
+ default_agent_name: string | null;
+ config: any | null;
+ messages: WorkbenchMessage[];
+ next_after_id: string | null;
+ next_before_id?: string | null;
+ queued: WorkbenchMessage[];
+ draft: { text: string };
+ turn_state: { in_flight: boolean | null };
+};
+
// One row of the per-session ("Slack-like") inbox feed from ``GET /api/inbox``.
// Aggregated per session at query time: ``preview_text`` is the session's latest
// agent ``result`` (aligned with the avibe chat, which only shows results),
@@ -1601,6 +1615,8 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
},
createSession: (payload) => postJson('/api/sessions', payload),
getSession: (sessionId) => getCachedJson(`/api/sessions/${encodeURIComponent(sessionId)}`),
+ getSessionBootstrap: (sessionId) =>
+ getJson(`/api/sessions/${encodeURIComponent(sessionId)}/bootstrap`),
updateSession: async (sessionId, payload) => {
const { payloadJson } = await requestJson(`/api/sessions/${encodeURIComponent(sessionId)}`, {
method: 'PATCH',
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index d8164e6ba..13c05cbee 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3441,6 +3441,75 @@ def sessions_get(session_id: str):
return jsonify({"error": str(err)}), 404
[email protected]("/api/sessions/<session_id>/bootstrap", methods=["GET"])
+async def sessions_bootstrap(session_id: str):
+ """First-screen payload for the Workbench Chat page.
+
+ This combines the read-only resources ChatPage needs on initial load so a
+ remote UI does not pay one tunnel round-trip per independent widget.
+ Reconnect/gap recovery still uses the smaller dedicated endpoints so those
+ reads can bypass cache precisely.
+ """
+ from core.services import sessions as workbench_sessions_service
+ from core.services import settings as settings_service
+ from storage import messages_service
+ from vibe import api as vibe_api
+ from vibe import internal_client
+
+ engine = _projects_engine()
+ with engine.connect() as conn:
+ try:
+ session = workbench_sessions_service.get_session(conn, session_id)
+ except LookupError as err:
+ return jsonify({"error": str(err)}), 404
+ messages_result = messages_service.list_session_messages(
+ conn,
+ session_id=session_id,
+ limit=50,
+ types=messages_service.TRANSCRIPT_TYPES,
+ include_metadata_sources=("show_page",),
+ tail=True,
+ )
+ queued = messages_service.list_queued(conn, session_id)
+ draft = messages_service.get_draft(conn, session_id)
+
+ try:
+ agents_payload = vibe_api.get_vibe_agents(include_disabled=False)
+ except Exception:
+ logger.exception("sessions_bootstrap: failed to load Vibe Agents")
+ agents_payload = {"agents": [], "default_agent_name": None}
+
+ try:
+ config_payload = vibe_api.config_to_payload(settings_service.load_config_or_default())
+ except Exception:
+ logger.exception("sessions_bootstrap: failed to load config")
+ config_payload = None
+
+ try:
+ turn_result = await internal_client.turn_state(session_id)
+ turn_body = turn_result.get("body") or {}
+ turn_state = {"in_flight": bool(turn_body.get("in_flight"))}
+ except internal_client.InternalServerUnavailable:
+ turn_state = {"in_flight": False}
+ except internal_client.InternalServerTimeout:
+ turn_state = {"in_flight": None}
+
+ return jsonify(
+ {
+ "session": session,
+ "agents": agents_payload.get("agents") or [],
+ "default_agent_name": agents_payload.get("default_agent_name"),
+ "config": config_payload,
+ "messages": messages_result["messages"],
+ "next_after_id": messages_result.get("next_after_id"),
+ "next_before_id": messages_result.get("next_before_id"),
+ "queued": queued,
+ "draft": {"text": (draft or {}).get("text") or ""},
+ "turn_state": turn_state,
+ }
+ )
+
+
@app.route("/api/sessions/<session_id>", methods=["PATCH"])
def sessions_update(session_id: str):
from core.services import sessions as workbench_sessions_service