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): optimize remote UI hot paths (#465)

Call White7447df8e0c9f
diff --git a/storage/alembic/versions/20260606_0018_messages_session_indexes.py b/storage/alembic/versions/20260606_0018_messages_session_indexes.py
new file mode 100644
index 000000000..534b76cc2
--- /dev/null
+++ b/storage/alembic/versions/20260606_0018_messages_session_indexes.py
@@ -0,0 +1,63 @@
+"""add workbench query indexes
+
+Revision ID: 20260606_0018
+Revises: 20260604_0017
+Create Date: 2026-06-06
+"""
+
+from __future__ import annotations
+
+from alembic import op
+
+revision = "20260606_0018"
+down_revision = "20260604_0017"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ op.create_index(
+ "ix_agent_sessions_scope_status_activity",
+ "agent_sessions",
+ ["scope_id", "status", "last_active_at", "created_at", "id"],
+ if_not_exists=True,
+ )
+ op.create_index(
+ "ix_messages_session_created_id",
+ "messages",
+ ["session_id", "created_at", "id"],
+ if_not_exists=True,
+ )
+ op.create_index(
+ "ix_messages_session_type_created_id",
+ "messages",
+ ["session_id", "type", "created_at", "id"],
+ if_not_exists=True,
+ )
+ op.create_index(
+ "ix_messages_platform_session_created_id",
+ "messages",
+ ["platform", "session_id", "created_at", "id"],
+ if_not_exists=True,
+ )
+ op.create_index(
+ "ix_messages_unread_session",
+ "messages",
+ ["platform", "type", "author", "read_at", "session_id"],
+ if_not_exists=True,
+ )
+ op.create_index(
+ "ix_messages_mark_read",
+ "messages",
+ ["session_id", "author", "read_at", "created_at", "id"],
+ if_not_exists=True,
+ )
+
+
+def downgrade() -> None:
+ op.drop_index("ix_messages_mark_read", table_name="messages")
+ op.drop_index("ix_messages_unread_session", table_name="messages")
+ op.drop_index("ix_messages_platform_session_created_id", table_name="messages")
+ op.drop_index("ix_messages_session_type_created_id", table_name="messages")
+ op.drop_index("ix_messages_session_created_id", table_name="messages")
+ op.drop_index("ix_agent_sessions_scope_status_activity", table_name="agent_sessions")
diff --git a/storage/migrations.py b/storage/migrations.py
index 1d51ad74e..17796657b 100644
--- a/storage/migrations.py
+++ b/storage/migrations.py
@@ -12,7 +12,7 @@ from config import paths
from storage.db import create_sqlite_engine, sqlite_url
INITIAL_REVISION = "20260501_0001"
-LATEST_SCHEMA_REVISION = "20260604_0017"
+LATEST_SCHEMA_REVISION = "20260606_0018"
REMOVE_LEGACY_DEFAULT_AGENT_REVISION = "20260530_0008"
INITIAL_TABLES = {
"state_meta",
@@ -220,6 +220,8 @@ def _stamp_existing_initial_schema(db_path: Path, cfg: Config) -> None:
if not _head_schema_ready(conn, tables):
missing = _missing_head_schema_description(conn, tables)
raise RuntimeError(f"existing SQLite head schema is incomplete; missing: {missing}")
+ _ensure_head_indexes(conn, tables)
+ conn.commit()
_run_remove_legacy_default_agent_migration(db_path)
command.stamp(cfg, LATEST_SCHEMA_REVISION)
_run_post_stamp_data_migrations(db_path)
@@ -395,7 +397,7 @@ def _repair_head_required_columns(conn: sqlite3.Connection, tables: set[str]) ->
conn.execute('alter table "web_push_subscriptions" add column "device_id" VARCHAR')
changed = True
- _ensure_new_background_indexes(conn)
+ _ensure_head_indexes(conn, tables)
return changed
@@ -474,6 +476,33 @@ def _ensure_new_background_indexes(conn: sqlite3.Connection) -> None:
conn.execute('create index if not exists ix_agent_runs_agent_created on agent_runs (agent_name, created_at)')
+def _ensure_messages_query_indexes(conn: sqlite3.Connection, tables: set[str]) -> None:
+ if "agent_sessions" in tables:
+ conn.execute(
+ "create index if not exists ix_agent_sessions_scope_status_activity "
+ "on agent_sessions (scope_id, status, 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)')
+ conn.execute('create index if not exists ix_messages_session_type_created_id on messages (session_id, type, created_at, id)')
+ conn.execute('create index if not exists ix_messages_platform_session_created_id on messages (platform, session_id, created_at, id)')
+ conn.execute(
+ 'create index if not exists ix_messages_unread_session '
+ 'on messages (platform, type, author, read_at, session_id)'
+ )
+ conn.execute(
+ 'create index if not exists ix_messages_mark_read '
+ 'on messages (session_id, author, read_at, created_at, id)'
+ )
+
+
+def _ensure_head_indexes(conn: sqlite3.Connection, tables: set[str]) -> None:
+ if {"run_definitions", "agent_runs"}.issubset(tables):
+ _ensure_new_background_indexes(conn)
+ _ensure_messages_query_indexes(conn, tables)
+
+
def _missing_head_schema_description(conn: sqlite3.Connection, tables: set[str]) -> str:
missing_parts = [f"tables {', '.join(sorted(HEAD_TABLES - tables))}"] if not HEAD_TABLES.issubset(tables) else []
for table, required_columns in (HEAD_REQUIRED_COLUMNS | HEAD_ONLY_REQUIRED_COLUMNS).items():
diff --git a/storage/models.py b/storage/models.py
index 1ddb3e861..bd83f82a5 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -128,6 +128,7 @@ agent_sessions = Table(
Index("ix_agent_sessions_scope_anchor_workdir", "scope_id", "session_anchor", "workdir"),
Index("ix_agent_sessions_backend_variant", "agent_backend", "agent_variant"),
Index("ix_agent_sessions_status_activity", "status", "last_active_at"),
+ Index("ix_agent_sessions_scope_status_activity", "scope_id", "status", "last_active_at", "created_at", "id"),
Index("ix_agent_sessions_native_session", "native_session_id"),
)
@@ -314,6 +315,11 @@ messages = Table(
Column("read_at", String, nullable=True),
UniqueConstraint("platform", "native_message_id", name="uq_messages_platform_native"),
Index("ix_messages_session_created", "session_id", "created_at"),
+ Index("ix_messages_session_created_id", "session_id", "created_at", "id"),
+ Index("ix_messages_session_type_created_id", "session_id", "type", "created_at", "id"),
+ Index("ix_messages_platform_session_created_id", "platform", "session_id", "created_at", "id"),
+ Index("ix_messages_unread_session", "platform", "type", "author", "read_at", "session_id"),
+ Index("ix_messages_mark_read", "session_id", "author", "read_at", "created_at", "id"),
Index("ix_messages_scope_created", "scope_id", "created_at"),
Index("ix_messages_scope_unread", "scope_id", "read_at"),
Index("ix_messages_author_created", "author", "created_at"),
diff --git a/tests/test_internal_client.py b/tests/test_internal_client.py
index 95635a56d..8a88c4ba4 100644
--- a/tests/test_internal_client.py
+++ b/tests/test_internal_client.py
@@ -122,3 +122,29 @@ def test_turn_state_os_error_raises_unavailable(tmp_path):
asyncio.run(internal_client.turn_state("ses_x", socket_path=sock))
assert "Operation not supported" in str(exc.value)
+
+
+def test_turn_state_uses_short_timeout(tmp_path):
+ sock = tmp_path / "dispatch.sock"
+ sock.touch()
+ captured: dict = {}
+
+ class CapturingClient:
+ def __init__(self, *args, **kwargs):
+ captured["timeout"] = kwargs.get("timeout")
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args):
+ return None
+
+ async def get(self, _path):
+ raise httpx.ReadTimeout("slow internal turn-state")
+
+ with patch("vibe.internal_client.httpx.AsyncClient", CapturingClient):
+ with pytest.raises(internal_client.InternalServerTimeout):
+ asyncio.run(internal_client.turn_state("ses_x", socket_path=sock))
+
+ assert captured["timeout"].connect == 0.2
+ assert captured["timeout"].read == 1.0
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index fa21cb674..b2ef42ef6 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -16,7 +16,7 @@ from storage.models import metadata
from storage.settings_service import SQLiteSettingsService
-HEAD_REVISION = "20260604_0017"
+HEAD_REVISION = "20260606_0018"
def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
@@ -42,6 +42,24 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
assert "show_session_events" in tables
assert "media_objects" in tables
assert "web_push_subscriptions" in tables
+ message_indexes = {
+ row[1]
+ for row in conn.execute(
+ "select seq, name from pragma_index_list('messages')",
+ )
+ }
+ assert "ix_messages_session_created_id" in message_indexes
+ assert "ix_messages_session_type_created_id" in message_indexes
+ assert "ix_messages_platform_session_created_id" in message_indexes
+ assert "ix_messages_unread_session" in message_indexes
+ assert "ix_messages_mark_read" in message_indexes
+ agent_session_indexes = {
+ row[1]
+ for row in conn.execute(
+ "select seq, name from pragma_index_list('agent_sessions')",
+ )
+ }
+ assert "ix_agent_sessions_scope_status_activity" in agent_session_indexes
media_columns = {
row[1] for row in conn.execute("pragma table_info(media_objects)")
}
@@ -97,6 +115,49 @@ def test_run_migrations_stamps_existing_initial_schema(tmp_path: Path) -> None:
assert version == (HEAD_REVISION,)
+def test_run_migrations_repairs_head_indexes_before_stamping_head(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ engine = create_sqlite_engine(db_path)
+ try:
+ metadata.create_all(engine)
+ finally:
+ engine.dispose()
+
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("drop index if exists ix_agent_sessions_scope_status_activity")
+ conn.execute("drop index if exists ix_messages_session_created_id")
+ conn.execute("drop index if exists ix_messages_session_type_created_id")
+ conn.execute("drop index if exists ix_messages_platform_session_created_id")
+ conn.execute("drop index if exists ix_messages_unread_session")
+ conn.execute("drop index if exists ix_messages_mark_read")
+ conn.commit()
+ assert conn.execute("select name from sqlite_master where name = 'alembic_version'").fetchone() is None
+
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ version = conn.execute("select version_num from alembic_version").fetchone()
+ message_indexes = {
+ row[1]
+ for row in conn.execute(
+ "select seq, name from pragma_index_list('messages')",
+ )
+ }
+ agent_session_indexes = {
+ row[1]
+ for row in conn.execute(
+ "select seq, name from pragma_index_list('agent_sessions')",
+ )
+ }
+ assert version == (HEAD_REVISION,)
+ assert "ix_messages_session_created_id" in message_indexes
+ assert "ix_messages_session_type_created_id" in message_indexes
+ assert "ix_messages_platform_session_created_id" in message_indexes
+ assert "ix_messages_unread_session" in message_indexes
+ assert "ix_messages_mark_read" in message_indexes
+ assert "ix_agent_sessions_scope_status_activity" in agent_session_indexes
+
+
def test_run_migrations_runs_legacy_default_cleanup_when_stamping_existing_head_schema(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"
engine = create_sqlite_engine(db_path)
@@ -304,6 +365,9 @@ def test_background_tables_ready_requires_messages_type(tmp_path: Path) -> None:
engine.dispose()
with sqlite3.connect(db_path) as conn:
+ conn.execute("drop index if exists ix_messages_session_type")
+ conn.execute("drop index if exists ix_messages_session_type_created_id")
+ conn.execute("drop index if exists ix_messages_unread_session")
conn.execute('alter table "messages" drop column "type"')
conn.execute("create table if not exists alembic_version (version_num varchar(32) not null)")
conn.execute("delete from alembic_version")
diff --git a/tests/test_sse_broker.py b/tests/test_sse_broker.py
index 2a5d48d3c..9d7358b07 100644
--- a/tests/test_sse_broker.py
+++ b/tests/test_sse_broker.py
@@ -11,6 +11,7 @@ take down whichever caller was publishing the event. The lock added to
from __future__ import annotations
import asyncio
+import json
import sys
import threading
from pathlib import Path
@@ -20,6 +21,38 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from vibe.sse_broker import SSEBroker
+def test_publish_preserves_repeated_payloads_and_omits_ts():
+ broker = SSEBroker()
+
+ async def scenario():
+ _sub_id, queue = broker.subscribe()
+ broker.publish("queue.updated", {"session_id": "ses1"})
+ broker.publish("queue.updated", {"session_id": "ses1"})
+ broker.publish("queue.updated", {"session_id": "ses2"})
+
+ first_event, first_payload = await asyncio.wait_for(queue.get(), timeout=1)
+ second_event, second_payload = await asyncio.wait_for(queue.get(), timeout=1)
+ third_event, third_payload = await asyncio.wait_for(queue.get(), timeout=1)
+ return (
+ first_event,
+ json.loads(first_payload),
+ second_event,
+ json.loads(second_payload),
+ third_event,
+ json.loads(third_payload),
+ )
+
+ first_event, first_payload, second_event, second_payload, third_event, third_payload = asyncio.run(scenario())
+
+ assert first_event == "queue.updated"
+ assert first_payload == {"type": "queue.updated", "data": {"session_id": "ses1"}}
+ assert "ts" not in first_payload
+ assert second_event == "queue.updated"
+ assert second_payload == {"type": "queue.updated", "data": {"session_id": "ses1"}}
+ assert third_event == "queue.updated"
+ assert third_payload == {"type": "queue.updated", "data": {"session_id": "ses2"}}
+
+
def test_publish_survives_concurrent_subscribe_churn():
broker = SSEBroker()
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 89921f17d..cc5f29f89 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -169,6 +169,32 @@ def test_config_get_on_fresh_install_returns_default_needing_setup(monkeypatch,
assert not paths.get_config_path().exists(), "GET must not persist a config file"
+def test_static_ui_assets_use_cache_headers(monkeypatch, tmp_path):
+ ui_dist = tmp_path / "dist"
+ assets_dir = ui_dist / "assets"
+ assets_dir.mkdir(parents=True)
+ (ui_dist / "index.html").write_text("<html></html>", encoding="utf-8")
+ (ui_dist / "manifest.webmanifest").write_text("{}", encoding="utf-8")
+ (assets_dir / "app-abc123.js").write_text("console.log('ok')", encoding="utf-8")
+
+ monkeypatch.setattr(ui_server, "get_ui_dist_path", lambda: ui_dist)
+
+ client = app.test_client()
+ asset_response = client.get("/assets/app-abc123.js")
+ manifest_response = client.get("/manifest.webmanifest")
+ index_response = client.get("/")
+ spa_response = client.get("/workbench/session-1")
+
+ assert asset_response.status_code == 200
+ assert asset_response.headers["Cache-Control"] == "public, max-age=31536000, immutable"
+ assert manifest_response.status_code == 200
+ assert manifest_response.headers["Cache-Control"] == "public, max-age=3600"
+ assert index_response.status_code == 200
+ assert index_response.headers["Cache-Control"] == "no-store, private"
+ assert spa_response.status_code == 200
+ assert spa_response.headers["Cache-Control"] == "no-store, private"
+
+
def test_run_maybe_async_offloads_sync_handlers_without_losing_context():
import asyncio
import threading
diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.py
index 450b8ee79..0b65f17a3 100644
--- a/tests/test_ui_session_stream.py
+++ b/tests/test_ui_session_stream.py
@@ -208,3 +208,20 @@ def test_cancel_route_returns_503_when_socket_unavailable(isolated_state, tmp_pa
body = response.json()
assert body["ok"] is False
assert body["code"] == "internal_unavailable"
+
+
+def test_turn_state_route_returns_504_on_probe_timeout(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):
+ client = app.test_client()
+ response = client.get(f"/api/sessions/{session_id}/turn-state")
+
+ assert response.status_code == 504
+ assert response.get_json()["error"]["code"] == "turn_state_timeout"
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 9744ff4c6..2e9af0803 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -193,7 +193,7 @@ export const ChatPage: React.FC = () => {
try {
// tail: the RECENT window (not the oldest page), so a missed latest row in
// a long chat is actually recovered (Codex P2).
- const res = await api.listSessionMessages(sessionId, { limit: 50, tail: true });
+ const res = await api.listSessionMessages(sessionId, { limit: 50, tail: true, cache: false });
if (sessionId !== sessionIdRef.current) return; // switched chats mid-fetch
const fresh = res.messages.filter(isTranscriptMessage);
if (fresh.length) {
@@ -219,7 +219,7 @@ export const ChatPage: React.FC = () => {
const refreshQueue = useCallback(async () => {
if (!sessionId) return;
try {
- const res = await api.listSessionQueue(sessionId);
+ const res = await api.listSessionQueue(sessionId, { cache: false });
if (sessionId !== sessionIdRef.current) return; // switched chats mid-fetch
setQueue(res.queued ?? []);
} catch {
@@ -297,6 +297,7 @@ export const ChatPage: React.FC = () => {
try {
const res = await api.getTurnState(sessionId);
if (sessionId !== sessionIdRef.current) return;
+ if (res.in_flight === null) return;
if (res.in_flight) {
// markWorking (not setWorking): bump the epoch + timestamp so an OLDER
// overlapping sync whose idle response lands AFTER this one can't clear
@@ -349,7 +350,7 @@ export const ChatPage: React.FC = () => {
api.listSessionMessages(sessionId, { limit: 50, tail: true }),
api.listSessionQueue(sessionId),
api.getSessionDraft(sessionId),
- api.getTurnState(sessionId).catch(() => ({ in_flight: false })),
+ api.getTurnState(sessionId).catch(() => ({ in_flight: null })),
]);
// Dropped if the user switched chats while this load was in flight.
if (sessionId !== sessionIdRef.current) return;
@@ -368,7 +369,7 @@ export const ChatPage: React.FC = () => {
// 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 setWorking(false);
+ else if (turnState.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.
@@ -468,7 +469,7 @@ export const ChatPage: React.FC = () => {
onError: () => {
// Browser EventSource auto-reconnects; keep the page usable.
},
- });
+ }, { reconnect: connectionEpoch > 0 });
return disconnect;
}, [api, sessionId, appendMessage, reconcile, refreshQueue, syncTurnState, markWorking, connectionEpoch]);
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 133c3f0b1..890e85f55 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -1,4 +1,4 @@
-import React, { createContext, useContext, useMemo } from 'react';
+import React, { createContext, useContext, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useToast } from './ToastContext';
import { apiFetch } from '../lib/apiFetch';
@@ -134,7 +134,7 @@ export type ApiContextType = {
browseDirectory: (path: string, showHidden?: boolean) => Promise<{ ok: boolean; path?: string; parent?: string | null; dirs?: { name: string; path: string }[]; error?: string }>;
browseFavorites: () => Promise<{ ok: boolean; system?: string; favorites?: { key: string; path: string }[]; error?: string }>;
browseMkdir: (path: string) => Promise<{ path: string }>;
- listProjects: (includeArchived?: boolean) => Promise<{ projects: WorkbenchProject[] }>;
+ listProjects: (includeArchived?: boolean, options?: { cache?: boolean }) => Promise<{ projects: WorkbenchProject[] }>;
createProject: (payload: { folder_path: string; display_name?: string }) => Promise<WorkbenchProject>;
// Default-Agent fields accept null to CLEAR the project default (back to the
// global default); omit a field to leave it untouched.
@@ -165,24 +165,24 @@ export type ApiContextType = {
saveGlobalPrompts: (
payload: { content: string; backends: string[] },
) => Promise<{ ok: boolean; backends: GlobalPromptFile[] }>;
- listSessions: (params?: { projectId?: string; status?: 'active' | 'archived' | 'all'; limit?: number; beforeId?: string }) => Promise<{ sessions: WorkbenchSession[]; next_before_id: string | null }>;
+ 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>;
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 }) => Promise<{ messages: WorkbenchMessage[]; next_after_id: string | null; next_before_id?: string | null }>;
+ 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 }>;
sendSessionMessage: (sessionId: string, payload: { text?: string; content?: Record<string, unknown>; metadata?: Record<string, unknown>; author_id?: string; author_name?: string }) => Promise<WorkbenchMessage>;
markSessionRead: (sessionId: string, untilMessageId?: string) => Promise<{ updated: number; unread_counts: Record<string, number>; unread_by_session: Record<string, number> }>;
cancelSession: (sessionId: string) => Promise<{ ok: boolean; status?: string; code?: string; detail?: string }>;
// Send-while-busy queue (messages sent while a turn runs) + per-session draft.
- listSessionQueue: (sessionId: string) => Promise<{ queued: WorkbenchMessage[] }>;
+ listSessionQueue: (sessionId: string, options?: { cache?: boolean }) => Promise<{ queued: WorkbenchMessage[] }>;
removeQueuedMessage: (sessionId: string, messageId: string) => Promise<{ removed: boolean }>;
sendQueuedNow: (sessionId: string, messageId: string) => Promise<{ ok: boolean; status?: string; code?: string; detail?: string }>;
- getTurnState: (sessionId: string) => Promise<{ in_flight: boolean }>;
+ getTurnState: (sessionId: string) => Promise<{ in_flight: boolean | null }>;
getSessionDraft: (sessionId: string) => Promise<{ text: string }>;
setSessionDraft: (sessionId: string, text: string) => Promise<{ ok: boolean }>;
- listInbox: (params?: { platform?: string; unreadOnly?: boolean; limit?: number; before?: string }) => Promise<InboxFeedResult>;
- connectWorkbenchEvents: (handlers: WorkbenchEventHandlers) => () => void;
+ listInbox: (params?: { platform?: string; unreadOnly?: boolean; limit?: number; before?: string; cache?: boolean }) => Promise<InboxFeedResult>;
+ connectWorkbenchEvents: (handlers: WorkbenchEventHandlers, options?: { reconnect?: boolean }) => () => void;
listVibeAgents: (params?: { backend?: string; includeDisabled?: boolean }) => Promise<{ ok: boolean; agents: VibeAgentBrief[]; default_agent_name: string | null }>;
getVibeAgent: (name: string) => Promise<{ ok: boolean; agent: VibeAgentFull; default_agent_name: string | null }>;
createVibeAgent: (payload: VibeAgentCreatePayload) => Promise<{ ok: boolean; agent: VibeAgentFull }>;
@@ -419,13 +419,13 @@ export type VibeAgentUpdatePayload = {
};
// Events streamed by ``GET /api/events`` — the broker JSON-encodes each
-// payload as ``{type, data, ts}``. ``connectWorkbenchEvents`` parses and
-// dispatches to type-specific handlers; subscribers can also catch any
-// event via ``onAny`` for logging/analytics.
+// payload as ``{type, data}`` (older servers may include ``ts``).
+// ``connectWorkbenchEvents`` parses and dispatches to type-specific handlers;
+// subscribers can also catch any event via ``onAny`` for logging/analytics.
export type WorkbenchEventEnvelope<T = unknown> = {
type: string;
data: T;
- ts: number;
+ ts?: number;
};
export type WorkbenchEventHandlers = {
@@ -1090,6 +1090,10 @@ export const useApi = () => {
export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const { showToast } = useToast();
const { t } = useTranslation();
+ const readCacheRef = useRef(new Map<string, { expiresAt: number; promise: Promise<any> }>());
+ const eventSourceRef = useRef<EventSource | null>(null);
+ const eventHandlersRef = useRef(new Set<WorkbenchEventHandlers>());
+ const eventConnectionRef = useRef<{ sub_id: number } | null>(null);
const handleApiError = async (res: Response, path: string) => {
let errorMessage = `Request failed: ${path} (${res.status})`;
@@ -1136,25 +1140,208 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
return res.json();
};
+ const getCachedJson = (path: string, ttlMs = 1500) => {
+ const now = Date.now();
+ const cached = readCacheRef.current.get(path);
+ if (cached && cached.expiresAt > now) {
+ return cached.promise;
+ }
+
+ const promise = getJson(path).catch((err) => {
+ readCacheRef.current.delete(path);
+ throw err;
+ });
+ readCacheRef.current.set(path, { expiresAt: now + ttlMs, promise });
+ return promise;
+ };
+
+ const clearReadCache = () => {
+ readCacheRef.current.clear();
+ };
+
+ const clearReadCacheMatching = (predicate: (path: string) => boolean) => {
+ for (const path of readCacheRef.current.keys()) {
+ if (predicate(path)) {
+ readCacheRef.current.delete(path);
+ }
+ }
+ };
+
+ const clearSessionReadCache = (sessionId: string) => {
+ const encoded = encodeURIComponent(sessionId);
+ const sessionPrefix = `/api/sessions/${encoded}`;
+ clearReadCacheMatching((path) =>
+ path === sessionPrefix ||
+ path.startsWith(`${sessionPrefix}/`) ||
+ path.startsWith('/api/sessions?') ||
+ path === '/api/sessions' ||
+ path.startsWith('/api/inbox?') ||
+ path === '/api/inbox',
+ );
+ };
+
+ const dispatchToWorkbenchHandlers = (dispatch: (handlers: WorkbenchEventHandlers) => void) => {
+ for (const handlers of Array.from(eventHandlersRef.current)) {
+ dispatch(handlers);
+ }
+ };
+
+ const parseWorkbenchEnvelope = <T,>(raw: string): WorkbenchEventEnvelope<T> | null => {
+ try {
+ return JSON.parse(raw) as WorkbenchEventEnvelope<T>;
+ } catch (err) {
+ console.error('[workbench-events] parse failed', err, raw);
+ return null;
+ }
+ };
+
+ const closeWorkbenchEventSource = () => {
+ eventSourceRef.current?.close();
+ eventSourceRef.current = null;
+ eventConnectionRef.current = null;
+ };
+
+ const ensureWorkbenchEventSource = (options?: { reconnect?: boolean }) => {
+ if (options?.reconnect) {
+ closeWorkbenchEventSource();
+ }
+ if (eventSourceRef.current) return;
+
+ const source = new EventSource('/api/events');
+ eventSourceRef.current = source;
+ source.addEventListener('connected', (e: MessageEvent) => {
+ try {
+ eventConnectionRef.current = JSON.parse(e.data) as { sub_id: number };
+ } catch (err) {
+ console.error('[workbench-events] connected parse failed', err, e.data);
+ eventConnectionRef.current = null;
+ }
+ if (eventConnectionRef.current) {
+ const connected = eventConnectionRef.current;
+ dispatchToWorkbenchHandlers((handlers) => handlers.onConnected?.(connected));
+ }
+ });
+ source.addEventListener('message.new', (e: MessageEvent) => {
+ const envelope = parseWorkbenchEnvelope<WorkbenchMessage>(e.data);
+ if (!envelope) return;
+ if (envelope.data.session_id) {
+ clearSessionReadCache(envelope.data.session_id);
+ } else {
+ clearReadCacheMatching((path) => path.startsWith('/api/inbox') || path.startsWith('/api/sessions'));
+ }
+ dispatchToWorkbenchHandlers((handlers) => {
+ handlers.onAny?.(envelope);
+ handlers.onMessageNew?.(envelope.data);
+ });
+ });
+ source.addEventListener('session.activity', (e: MessageEvent) => {
+ const envelope = parseWorkbenchEnvelope<any>(e.data);
+ if (!envelope) return;
+ if (envelope.data.session_id) {
+ clearSessionReadCache(envelope.data.session_id);
+ } else {
+ clearReadCacheMatching((path) => path.startsWith('/api/inbox') || path.startsWith('/api/sessions'));
+ }
+ dispatchToWorkbenchHandlers((handlers) => {
+ handlers.onAny?.(envelope);
+ handlers.onSessionActivity?.(envelope.data);
+ });
+ });
+ source.addEventListener('inbox.unread.changed', (e: MessageEvent) => {
+ const envelope = parseWorkbenchEnvelope<any>(e.data);
+ if (!envelope) return;
+ clearReadCacheMatching((path) => path.startsWith('/api/inbox') || path.startsWith('/api/sessions'));
+ dispatchToWorkbenchHandlers((handlers) => {
+ handlers.onAny?.(envelope);
+ handlers.onInboxUnreadChanged?.(envelope.data);
+ });
+ });
+ source.addEventListener('inbox.session.updated', (e: MessageEvent) => {
+ const envelope = parseWorkbenchEnvelope<InboxSession>(e.data);
+ if (!envelope) return;
+ clearSessionReadCache(envelope.data.session_id);
+ dispatchToWorkbenchHandlers((handlers) => {
+ handlers.onAny?.(envelope);
+ handlers.onInboxSessionUpdated?.(envelope.data);
+ });
+ });
+ source.addEventListener('turn.start', (e: MessageEvent) => {
+ const envelope = parseWorkbenchEnvelope<{ session_id: string }>(e.data);
+ if (!envelope) return;
+ clearSessionReadCache(envelope.data.session_id);
+ dispatchToWorkbenchHandlers((handlers) => {
+ handlers.onAny?.(envelope);
+ handlers.onTurnStart?.(envelope.data);
+ });
+ });
+ source.addEventListener('turn.end', (e: MessageEvent) => {
+ const envelope = parseWorkbenchEnvelope<{ session_id: string }>(e.data);
+ if (!envelope) return;
+ clearSessionReadCache(envelope.data.session_id);
+ dispatchToWorkbenchHandlers((handlers) => {
+ handlers.onAny?.(envelope);
+ handlers.onTurnEnd?.(envelope.data);
+ });
+ });
+ source.addEventListener('session.status', (e: MessageEvent) => {
+ const envelope = parseWorkbenchEnvelope<{
+ session_id: string;
+ agent_status: 'idle' | 'running' | 'failed';
+ }>(e.data);
+ if (!envelope) return;
+ clearSessionReadCache(envelope.data.session_id);
+ dispatchToWorkbenchHandlers((handlers) => {
+ handlers.onAny?.(envelope);
+ handlers.onSessionStatus?.(envelope.data);
+ });
+ });
+ source.addEventListener('queue.updated', (e: MessageEvent) => {
+ const envelope = parseWorkbenchEnvelope<{ session_id: string }>(e.data);
+ if (!envelope) return;
+ clearSessionReadCache(envelope.data.session_id);
+ dispatchToWorkbenchHandlers((handlers) => {
+ handlers.onAny?.(envelope);
+ handlers.onQueueUpdated?.(envelope.data);
+ });
+ });
+ source.onerror = (err) => {
+ dispatchToWorkbenchHandlers((handlers) => handlers.onError?.(err));
+ };
+ };
+
+ const requestJson = async (
+ path: string,
+ init: RequestInit,
+ errorPath = path,
+ { clearCache = true, handleError = true }: { clearCache?: boolean; handleError?: boolean } = {},
+ ) => {
+ const res = await apiFetch(path, init);
+ if (!res.ok && handleError) {
+ await handleApiError(res, errorPath);
+ }
+ const payloadJson = await res.json().catch(() => ({}));
+ if (res.ok && clearCache) {
+ clearReadCache();
+ }
+ return { res, payloadJson };
+ };
+
const postJson = async (path: string, payload: any) => {
- const res = await apiFetch(path, {
+ const { payloadJson } = await requestJson(path, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
- if (!res.ok) {
- await handleApiError(res, path);
- }
- return res.json();
+ return payloadJson;
};
// DELETE wrapper that routes 4xx/5xx through ``handleApiError`` so the
// global toast and console-error surface stay consistent with
- // ``getJson``/``postJson``. Legacy callers (removeUser, deleteBindCode)
- // still call ``apiFetch().then(r => r.json())`` directly — that's a
- // separate cleanup; new endpoints should use this helper.
+ // ``getJson``/``postJson``. New mutating helpers should route through
+ // requestJson/postJson/patchJson/deleteJson so successful mutations always
+ // invalidate reusable GET promises.
const deleteJson = async (path: string, payload?: any) => {
- const res = await apiFetch(path, {
+ const { payloadJson } = await requestJson(path, {
method: 'DELETE',
...(payload === undefined
? {}
@@ -1163,22 +1350,16 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
body: JSON.stringify(payload),
}),
});
- if (!res.ok) {
- await handleApiError(res, path);
- }
- return res.json();
+ return payloadJson;
};
const patchJson = async (path: string, payload: any) => {
- const res = await apiFetch(path, {
+ const { payloadJson } = await requestJson(path, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
- if (!res.ok) {
- await handleApiError(res, path);
- }
- return res.json();
+ return payloadJson;
};
const sleep = (ms: number) => new Promise((resolve) => window.setTimeout(resolve, ms));
@@ -1249,7 +1430,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
// is correct (cached error messages would otherwise stay in the
// old language).
const value: ApiContextType = useMemo(() => ({
- getConfig: () => getJson('/api/config'),
+ getConfig: () => getCachedJson('/api/config'),
getPlatformCatalog: () => getJson('/api/platforms'),
saveConfig: (payload) => postJson('/api/config', payload),
getSettings: (platform) => getJson(platform ? `/api/settings?platform=${encodeURIComponent(platform)}` : '/api/settings'),
@@ -1257,7 +1438,8 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
getUsers: (platform) => getJson(platform ? `/api/users?platform=${encodeURIComponent(platform)}` : '/api/users'),
saveUsers: (payload, platform) => postJson('/api/users', platform ? { ...payload, platform } : payload),
toggleAdmin: (userId, isAdmin, platform) => postJson(`/api/users/${encodeURIComponent(userId)}/admin`, platform ? { is_admin: isAdmin, platform } : { is_admin: isAdmin }),
- removeUser: (userId, platform) => apiFetch(platform ? `/api/users/${encodeURIComponent(userId)}?platform=${encodeURIComponent(platform)}` : `/api/users/${encodeURIComponent(userId)}`, { method: 'DELETE' }).then(r => r.json()),
+ removeUser: (userId, platform) =>
+ deleteJson(platform ? `/api/users/${encodeURIComponent(userId)}?platform=${encodeURIComponent(platform)}` : `/api/users/${encodeURIComponent(userId)}`),
getShowPages: () => getJson('/api/show-pages'),
getWebPushStatus: (payload) =>
payload ? postJson('/api/web-push/status', payload) : getJson('/api/web-push/status'),
@@ -1275,7 +1457,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
rotateShowPageShare: (sessionId) => postJson(`/api/show-pages/${encodeURIComponent(sessionId)}/rotate-share`, {}),
getBindCodes: () => getJson('/api/bind-codes'),
createBindCode: (type, expiresAt) => postJson('/api/bind-codes', { type, expires_at: expiresAt }),
- deleteBindCode: (code) => apiFetch(`/api/bind-codes/${encodeURIComponent(code)}`, { method: 'DELETE' }).then(r => r.json()),
+ deleteBindCode: (code) => deleteJson(`/api/bind-codes/${encodeURIComponent(code)}`),
getFirstBindCode: () => getJson('/api/setup/first-bind-code'),
detectCli: (binary) => getJson(`/api/cli/detect?binary=${encodeURIComponent(binary)}`),
installAgent: (name) => startAndPollAgentInstall(name),
@@ -1369,50 +1551,43 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
codexAgents: (cwd) => cwd ? getJson(`/api/codex/agents?cwd=${encodeURIComponent(cwd)}`) : getJson('/api/codex/agents'),
codexModels: () => getJson('/api/codex/models'),
getLogs: (lines = 500, source) => postJson('/api/logs', source ? { lines, source } : { lines }),
- getVersion: () => getJson('/api/version'),
+ getVersion: () => getCachedJson('/api/version', 10_000),
doUpgrade: () => postJson('/api/upgrade', {}),
browseDirectory: (path, showHidden) => postJson('/api/browse', { path, show_hidden: showHidden || false }),
browseFavorites: () => getJson('/api/browse/favorites'),
browseMkdir: (path) => postJson('/api/browse/mkdir', { path }),
- listProjects: (includeArchived) =>
- getJson(`/api/projects${includeArchived ? '?include_archived=1' : ''}`),
+ listProjects: (includeArchived, options) => {
+ const path = `/api/projects${includeArchived ? '?include_archived=1' : ''}`;
+ return options?.cache === false ? getJson(path) : getCachedJson(path);
+ },
createProject: (payload) => postJson('/api/projects', payload),
updateProject: async (projectId, payload) => {
- const res = await apiFetch(`/api/projects/${encodeURIComponent(projectId)}`, {
+ const { payloadJson } = await requestJson(`/api/projects/${encodeURIComponent(projectId)}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
- });
- if (!res.ok) {
- await handleApiError(res, `PATCH /api/projects/${projectId}`);
- }
- return res.json();
+ }, `PATCH /api/projects/${projectId}`);
+ return payloadJson;
},
archiveProject: (projectId) => deleteJson(`/api/projects/${encodeURIComponent(projectId)}`),
getProjectAgentsMd: (projectId) =>
getJson(`/api/projects/${encodeURIComponent(projectId)}/agents-md`),
saveProjectAgentsMd: async (projectId, payload) => {
- const res = await apiFetch(`/api/projects/${encodeURIComponent(projectId)}/agents-md`, {
+ const { payloadJson } = await requestJson(`/api/projects/${encodeURIComponent(projectId)}/agents-md`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
- });
- if (!res.ok) {
- await handleApiError(res, `PUT /api/projects/${projectId}/agents-md`);
- }
- return res.json();
+ }, `PUT /api/projects/${projectId}/agents-md`);
+ return payloadJson;
},
getGlobalPrompts: () => getJson('/api/global-prompts'),
saveGlobalPrompts: async (payload) => {
- const res = await apiFetch('/api/global-prompts', {
+ const { payloadJson } = await requestJson('/api/global-prompts', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
- if (!res.ok) {
- await handleApiError(res, 'PUT /api/global-prompts');
- }
- return res.json();
+ return payloadJson;
},
listSessions: (params) => {
const search = new URLSearchParams();
@@ -1421,20 +1596,18 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
if (params?.limit) search.set('limit', String(params.limit));
if (params?.beforeId) search.set('before_id', params.beforeId);
const qs = search.toString();
- return getJson(qs ? `/api/sessions?${qs}` : '/api/sessions');
+ const path = qs ? `/api/sessions?${qs}` : '/api/sessions';
+ return params?.cache === false ? getJson(path) : getCachedJson(path);
},
createSession: (payload) => postJson('/api/sessions', payload),
- getSession: (sessionId) => getJson(`/api/sessions/${encodeURIComponent(sessionId)}`),
+ getSession: (sessionId) => getCachedJson(`/api/sessions/${encodeURIComponent(sessionId)}`),
updateSession: async (sessionId, payload) => {
- const res = await apiFetch(`/api/sessions/${encodeURIComponent(sessionId)}`, {
+ const { payloadJson } = await requestJson(`/api/sessions/${encodeURIComponent(sessionId)}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
- });
- if (!res.ok) {
- await handleApiError(res, `PATCH /api/sessions/${sessionId}`);
- }
- return res.json();
+ }, `PATCH /api/sessions/${sessionId}`);
+ return payloadJson;
},
archiveSession: (sessionId) => deleteJson(`/api/sessions/${encodeURIComponent(sessionId)}`),
listSessionMessages: (sessionId, params) => {
@@ -1445,7 +1618,8 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
if (params?.tail) search.set('tail', '1');
const qs = search.toString();
const base = `/api/sessions/${encodeURIComponent(sessionId)}/messages`;
- return getJson(qs ? `${base}?${qs}` : base);
+ const path = qs ? `${base}?${qs}` : base;
+ return params?.cache === false ? getJson(path) : getCachedJson(path);
},
sendSessionMessage: (sessionId, payload) =>
postJson(`/api/sessions/${encodeURIComponent(sessionId)}/messages`, payload),
@@ -1455,35 +1629,49 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
untilMessageId ? { until_message_id: untilMessageId } : {},
),
cancelSession: async (sessionId) => {
- const res = await apiFetch(`/api/sessions/${encodeURIComponent(sessionId)}/cancel`, {
+ const { res, payloadJson } = await requestJson(`/api/sessions/${encodeURIComponent(sessionId)}/cancel`, {
method: 'POST',
- });
+ }, `/api/sessions/${sessionId}/cancel`, { handleError: false });
// 503 + 404 are surfaced to the caller as plain payloads so the
// UI can render a sensible "nothing to stop" / "socket down"
// state without throwing.
- const body = await res.json().catch(() => ({}));
- return { ok: res.ok, ...body };
+ return { ok: res.ok, ...payloadJson };
+ },
+ listSessionQueue: (sessionId, options) => {
+ const path = `/api/sessions/${encodeURIComponent(sessionId)}/queue`;
+ return options?.cache === false ? getJson(path) : getCachedJson(path);
},
- listSessionQueue: (sessionId) => getJson(`/api/sessions/${encodeURIComponent(sessionId)}/queue`),
removeQueuedMessage: (sessionId, messageId) =>
deleteJson(`/api/sessions/${encodeURIComponent(sessionId)}/queue/${encodeURIComponent(messageId)}`),
sendQueuedNow: async (sessionId, messageId) => {
- const res = await apiFetch(
+ const { res, payloadJson } = await requestJson(
`/api/sessions/${encodeURIComponent(sessionId)}/queue/${encodeURIComponent(messageId)}/send-now`,
{ method: 'POST' },
+ `/api/sessions/${sessionId}/queue/${messageId}/send-now`,
+ { handleError: false },
);
- const body = await res.json().catch(() => ({}));
- return { ok: res.ok, ...body };
+ return { ok: res.ok, ...payloadJson };
},
- getTurnState: (sessionId) => getJson(`/api/sessions/${encodeURIComponent(sessionId)}/turn-state`),
- getSessionDraft: (sessionId) => getJson(`/api/sessions/${encodeURIComponent(sessionId)}/draft`),
+ getTurnState: async (sessionId) => {
+ const path = `/api/sessions/${encodeURIComponent(sessionId)}/turn-state`;
+ const res = await apiFetch(path);
+ if (res.status === 504) {
+ readCacheRef.current.delete(path);
+ return { in_flight: null };
+ }
+ if (!res.ok) {
+ await handleApiError(res, path);
+ }
+ return res.json();
+ },
+ getSessionDraft: (sessionId) => getCachedJson(`/api/sessions/${encodeURIComponent(sessionId)}/draft`),
setSessionDraft: async (sessionId, text) => {
- const res = await apiFetch(`/api/sessions/${encodeURIComponent(sessionId)}/draft`, {
+ const { res, payloadJson } = await requestJson(`/api/sessions/${encodeURIComponent(sessionId)}/draft`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text }),
- });
- return res.ok ? res.json() : { ok: false };
+ }, `/api/sessions/${sessionId}/draft`, { handleError: false });
+ return res.ok ? payloadJson : { ok: false };
},
listInbox: (params) => {
const search = new URLSearchParams();
@@ -1492,25 +1680,25 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
if (params?.limit) search.set('limit', String(params.limit));
if (params?.before) search.set('before', params.before);
const qs = search.toString();
- return getJson(qs ? `/api/inbox?${qs}` : '/api/inbox');
+ const path = qs ? `/api/inbox?${qs}` : '/api/inbox';
+ return params?.cache === false ? getJson(path) : getCachedJson(path);
},
listVibeAgents: (params) => {
const search = new URLSearchParams();
if (params?.backend) search.set('backend', params.backend);
if (params?.includeDisabled) search.set('include_disabled', '1');
const qs = search.toString();
- return getJson(qs ? `/api/agents?${qs}` : '/api/agents');
+ return getCachedJson(qs ? `/api/agents?${qs}` : '/api/agents', 5_000);
},
- getVibeAgent: (name) => getJson(`/api/agents/${encodeURIComponent(name)}`),
+ getVibeAgent: (name) => getCachedJson(`/api/agents/${encodeURIComponent(name)}`, 5_000),
createVibeAgent: (payload) => postJson('/api/agents', payload),
updateVibeAgent: async (name, payload) => {
- const res = await apiFetch(`/api/agents/${encodeURIComponent(name)}`, {
+ const { payloadJson } = await requestJson(`/api/agents/${encodeURIComponent(name)}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
- });
- if (!res.ok) await handleApiError(res, `PATCH /api/agents/${name}`);
- return res.json();
+ }, `PATCH /api/agents/${name}`);
+ return payloadJson;
},
setDefaultVibeAgent: (name) => postJson('/api/agents/default', { name }),
removeVibeAgent: (name) => deleteJson(`/api/agents/${encodeURIComponent(name)}`),
@@ -1521,7 +1709,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
if (params?.projectId) search.set('project_id', params.projectId);
if (params?.backends?.length) search.set('backends', params.backends.join(','));
const qs = search.toString();
- return getJson(qs ? `/api/skills?${qs}` : '/api/skills');
+ return getCachedJson(qs ? `/api/skills?${qs}` : '/api/skills', 5_000);
},
previewSkillSource: (source, params) =>
postJson('/api/skills/preview', { source, project_id: params?.projectId }),
@@ -1565,11 +1753,11 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
if (params?.scope) search.set('scope', params.scope);
if (params?.projectId) search.set('project_id', params.projectId);
const qs = search.toString();
- return getJson(qs ? `/api/skills/check?${qs}` : '/api/skills/check');
+ return getCachedJson(qs ? `/api/skills/check?${qs}` : '/api/skills/check', 5_000);
},
updateSkill: (name, params) =>
postJson('/api/skills/update', { name, scope: params?.scope, project_id: params?.projectId }),
- getHarnessCounts: () => getJson('/api/harness/counts'),
+ getHarnessCounts: () => getCachedJson('/api/harness/counts'),
listHarnessTasks: (params) => {
const search = new URLSearchParams();
if (params?.status) search.set('status', params.status);
@@ -1577,7 +1765,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
if (params?.page) search.set('page', String(params.page));
if (params?.limit) search.set('limit', String(params.limit));
const qs = search.toString();
- return getJson(qs ? `/api/harness/tasks?${qs}` : '/api/harness/tasks');
+ return getCachedJson(qs ? `/api/harness/tasks?${qs}` : '/api/harness/tasks');
},
setHarnessTaskEnabled: (taskId, enabled) =>
patchJson(`/api/harness/tasks/${encodeURIComponent(taskId)}`, { enabled }),
@@ -1589,7 +1777,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
if (params?.page) search.set('page', String(params.page));
if (params?.limit) search.set('limit', String(params.limit));
const qs = search.toString();
- return getJson(qs ? `/api/harness/watches?${qs}` : '/api/harness/watches');
+ return getCachedJson(qs ? `/api/harness/watches?${qs}` : '/api/harness/watches');
},
setHarnessWatchEnabled: (watchId, enabled) =>
patchJson(`/api/harness/watches/${encodeURIComponent(watchId)}`, { enabled }),
@@ -1604,134 +1792,25 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
if (params?.page) search.set('page', String(params.page));
if (params?.limit) search.set('limit', String(params.limit));
const qs = search.toString();
- return getJson(qs ? `/api/harness/runs?${qs}` : '/api/harness/runs');
+ return getCachedJson(qs ? `/api/harness/runs?${qs}` : '/api/harness/runs');
},
- getHarnessRun: (runId) => getJson(`/api/harness/runs/${encodeURIComponent(runId)}`),
- connectWorkbenchEvents: (handlers) => {
- // EventSource auto-reconnects on transient drops, so callers don't
- // have to implement their own retry. Returns a `disconnect` thunk so
- // React effects can clean up.
- const source = new EventSource('/api/events');
- const safeDispatch = <T,>(handler: ((data: T) => void) | undefined, raw: string) => {
- if (!handler) return;
- try {
- handler(JSON.parse(raw));
- } catch (err) {
- console.error('[workbench-events] parse failed', err, raw);
- }
- };
- source.addEventListener('connected', (e: MessageEvent) =>
- safeDispatch(handlers.onConnected, e.data),
- );
- source.addEventListener('message.new', (e: MessageEvent) => {
- const envelope = (() => {
- try {
- return JSON.parse(e.data) as WorkbenchEventEnvelope<WorkbenchMessage>;
- } catch {
- return null;
- }
- })();
- if (envelope) {
- handlers.onAny?.(envelope);
- handlers.onMessageNew?.(envelope.data);
- }
- });
- source.addEventListener('session.activity', (e: MessageEvent) => {
- const envelope = (() => {
- try {
- return JSON.parse(e.data) as WorkbenchEventEnvelope<any>;
- } catch {
- return null;
+ getHarnessRun: (runId) => getCachedJson(`/api/harness/runs/${encodeURIComponent(runId)}`),
+ connectWorkbenchEvents: (handlers, options) => {
+ eventHandlersRef.current.add(handlers);
+ ensureWorkbenchEventSource(options);
+ if (eventConnectionRef.current) {
+ queueMicrotask(() => {
+ if (eventHandlersRef.current.has(handlers) && eventConnectionRef.current) {
+ handlers.onConnected?.(eventConnectionRef.current);
}
- })();
- if (envelope) {
- handlers.onAny?.(envelope);
- handlers.onSessionActivity?.(envelope.data);
- }
- });
- source.addEventListener('inbox.unread.changed', (e: MessageEvent) => {
- const envelope = (() => {
- try {
- return JSON.parse(e.data) as WorkbenchEventEnvelope<any>;
- } catch {
- return null;
- }
- })();
- if (envelope) {
- handlers.onAny?.(envelope);
- handlers.onInboxUnreadChanged?.(envelope.data);
- }
- });
- source.addEventListener('inbox.session.updated', (e: MessageEvent) => {
- const envelope = (() => {
- try {
- return JSON.parse(e.data) as WorkbenchEventEnvelope<InboxSession>;
- } catch {
- return null;
- }
- })();
- if (envelope) {
- handlers.onAny?.(envelope);
- handlers.onInboxSessionUpdated?.(envelope.data);
- }
- });
- source.addEventListener('turn.start', (e: MessageEvent) => {
- const envelope = (() => {
- try {
- return JSON.parse(e.data) as WorkbenchEventEnvelope<{ session_id: string }>;
- } catch {
- return null;
- }
- })();
- if (envelope) {
- handlers.onAny?.(envelope);
- handlers.onTurnStart?.(envelope.data);
- }
- });
- source.addEventListener('turn.end', (e: MessageEvent) => {
- const envelope = (() => {
- try {
- return JSON.parse(e.data) as WorkbenchEventEnvelope<{ session_id: string }>;
- } catch {
- return null;
- }
- })();
- if (envelope) {
- handlers.onAny?.(envelope);
- handlers.onTurnEnd?.(envelope.data);
- }
- });
- source.addEventListener('session.status', (e: MessageEvent) => {
- const envelope = (() => {
- try {
- return JSON.parse(e.data) as WorkbenchEventEnvelope<{
- session_id: string;
- agent_status: 'idle' | 'running' | 'failed';
- }>;
- } catch {
- return null;
- }
- })();
- if (envelope) {
- handlers.onAny?.(envelope);
- handlers.onSessionStatus?.(envelope.data);
- }
- });
- source.addEventListener('queue.updated', (e: MessageEvent) => {
- const envelope = (() => {
- try {
- return JSON.parse(e.data) as WorkbenchEventEnvelope<{ session_id: string }>;
- } catch {
- return null;
- }
- })();
- if (envelope) {
- handlers.onAny?.(envelope);
- handlers.onQueueUpdated?.(envelope.data);
+ });
+ }
+ return () => {
+ eventHandlersRef.current.delete(handlers);
+ if (eventHandlersRef.current.size === 0) {
+ closeWorkbenchEventSource();
}
- });
- source.onerror = (err) => handlers.onError?.(err);
- return () => source.close();
+ };
},
remoteAccessStatus: () => getJson('/api/remote-access/status'),
pairVibeCloudRemoteAccess: (payload) => postJson('/api/remote-access/vibe-cloud/pair', payload),
diff --git a/ui/src/context/WorkbenchInboxContext.tsx b/ui/src/context/WorkbenchInboxContext.tsx
index 0554a1321..d5fd80f46 100644
--- a/ui/src/context/WorkbenchInboxContext.tsx
+++ b/ui/src/context/WorkbenchInboxContext.tsx
@@ -143,7 +143,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
const loadedIds = new Set(inboxSessionsRef.current.map((s) => s.session_id));
const limit = Math.min(Math.max(loadedIds.size, PAGE_SIZE), 100);
try {
- const result = await api.listInbox({ platform: 'avibe', limit });
+ const result = await api.listInbox({ platform: 'avibe', limit, cache: false });
setInboxSessions((prev) => {
const incoming = new Map(result.sessions.map((s) => [s.session_id, s]));
const merged = prev.map((s) => incoming.get(s.session_id) ?? s);
@@ -207,7 +207,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
// log, not a crash, so the workbench stays usable.
console.debug('[inbox] sse error', err);
},
- });
+ }, { reconnect: connectionEpoch > 0 });
return disconnect;
}, [api, refresh, reconcile, connectionEpoch]);
diff --git a/ui/src/context/WorkbenchProjectsContext.tsx b/ui/src/context/WorkbenchProjectsContext.tsx
index a966f66ac..7bf8aefbd 100644
--- a/ui/src/context/WorkbenchProjectsContext.tsx
+++ b/ui/src/context/WorkbenchProjectsContext.tsx
@@ -140,9 +140,9 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
return pending;
}, []);
- const fetchProjects = useCallback(async () => {
+ const fetchProjects = useCallback(async (options?: { cache?: boolean }) => {
try {
- const result = await api.listProjects();
+ const result = await api.listProjects(undefined, options);
setProjects(result.projects);
setProjectsError(null);
} catch (err: any) {
@@ -178,7 +178,13 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
let before: string | undefined;
let nextBeforeId: string | null = null;
do {
- const res = await api.listSessions({ projectId, status: 'active', limit: SESSIONS_PAGE_SIZE, beforeId: before });
+ const res = await api.listSessions({
+ projectId,
+ status: 'active',
+ limit: SESSIONS_PAGE_SIZE,
+ beforeId: before,
+ cache: false,
+ });
for (const s of res.sessions) {
if (!seen.has(s.id)) {
seen.add(s.id);
@@ -264,7 +270,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
useEffect(() => {
const disconnect = api.connectWorkbenchEvents({
onConnected: () => {
- void fetchProjects();
+ void fetchProjects({ cache: false });
for (const [projectId, state] of Object.entries(sessionsRef.current)) {
if (state.sessions !== null) void reconcileSessions(projectId);
}
diff --git a/vibe/internal_client.py b/vibe/internal_client.py
index 4c2bf518f..96202ddc6 100644
--- a/vibe/internal_client.py
+++ b/vibe/internal_client.py
@@ -29,7 +29,8 @@ from config import paths
logger = logging.getLogger(__name__)
-_SOCKET_ERRORS = (httpx.ConnectError, OSError)
+_SOCKET_ERRORS = (httpx.ConnectError, httpx.TimeoutException, OSError)
+_SOCKET_CONNECT_ERRORS = (httpx.ConnectError, httpx.ConnectTimeout, OSError)
class InternalServerUnavailable(Exception):
@@ -41,6 +42,10 @@ class InternalServerUnavailable(Exception):
"""
+class InternalServerTimeout(Exception):
+ """Raised when the internal server accepts a probe but does not answer in time."""
+
+
def default_socket_path() -> Path:
"""Mirror ``core.internal_server.default_socket_path`` without an
import cycle.
@@ -280,10 +285,12 @@ async def turn_state(session_id: str, *, socket_path: Optional[Path] = None) ->
async with httpx.AsyncClient(
transport=transport,
base_url="http://localhost",
- timeout=httpx.Timeout(5.0, connect=1.0),
+ timeout=httpx.Timeout(1.0, connect=0.2),
) as client:
resp = await client.get(f"/internal/turn-state/{session_id}")
- except _SOCKET_ERRORS as exc:
+ except httpx.ReadTimeout as exc:
+ raise InternalServerTimeout(str(exc)) from exc
+ except _SOCKET_CONNECT_ERRORS as exc:
raise InternalServerUnavailable(str(exc)) from exc
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
diff --git a/vibe/sse_broker.py b/vibe/sse_broker.py
index fed5d2293..ae4e13682 100644
--- a/vibe/sse_broker.py
+++ b/vibe/sse_broker.py
@@ -1,9 +1,9 @@
"""In-process pub/sub for workbench Server-Sent Events.
-Every workbench browser opens a long-lived ``GET /api/events`` request
-and the handler subscribes here. The REST routes that mutate messages
-/ sessions / unread counts publish events back through ``broker.publish``;
-the broker fans them out to every subscriber.
+The workbench UI opens a long-lived ``GET /api/events`` request and the
+handler subscribes here. The REST routes that mutate messages / sessions /
+unread counts publish events back through ``broker.publish``; the broker fans
+them out to every subscriber.
Why SSE over WebSocket (per Cloudflare Tunnel research, 2026-05-24):
SSE rides on plain HTTP, has automatic browser reconnect via
@@ -25,7 +25,6 @@ import asyncio
import json
import logging
import threading
-import time
from typing import Any
logger = logging.getLogger(__name__)
@@ -79,11 +78,11 @@ class SSEBroker:
return
# Snapshot under the lock so a concurrent subscribe/unsubscribe on
# the event loop thread cannot mutate the dict mid-iteration.
+ payload = json.dumps({"type": event_type, "data": data}, sort_keys=True, separators=(",", ":"))
with self._lock:
if not self._subscribers:
return
queues = list(self._subscribers.values())
- payload = json.dumps({"type": event_type, "data": data, "ts": time.time()})
for queue in queues:
try:
loop.call_soon_threadsafe(self._put_nowait, queue, event_type, payload)
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 164268ce5..d8164e6ba 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -4071,6 +4071,18 @@ async def sessions_turn_state(session_id: str):
result = await internal_client.turn_state(session_id)
except internal_client.InternalServerUnavailable:
return jsonify({"in_flight": False})
+ except internal_client.InternalServerTimeout:
+ return (
+ jsonify(
+ {
+ "error": {
+ "code": "turn_state_timeout",
+ "message": "Turn state probe timed out",
+ },
+ }
+ ),
+ 504,
+ )
body = result.get("body") or {}
return jsonify({"in_flight": bool(body.get("in_flight"))})
@@ -4194,7 +4206,7 @@ async def workbench_events():
headers={
# Disable nginx/cloudflare body buffering on the response side
# so chunks reach the client immediately.
- "Cache-Control": "no-cache",
+ "Cache-Control": "no-cache, no-store, must-revalidate",
"X-Accel-Buffering": "no",
},
)
@@ -5462,13 +5474,22 @@ def serve_static(path):
if resolved_path.exists() and resolved_path.is_file():
mime_type, _ = mimetypes.guess_type(str(resolved_path))
- return send_file(resolved_path, mimetype=mime_type or "application/octet-stream")
+ response = send_file(resolved_path, mimetype=mime_type or "application/octet-stream")
+ if path.startswith("assets/"):
+ response.headers["Cache-Control"] = "public, max-age=31536000, immutable"
+ elif resolved_path.name == "index.html":
+ response.headers["Cache-Control"] = "no-store, private"
+ else:
+ response.headers["Cache-Control"] = "public, max-age=3600"
+ return response
# SPA fallback: serve index.html for routes without file extension
if "." not in path:
index_path = ui_dist / "index.html"
if index_path.exists():
- return send_file(index_path, mimetype="text/html")
+ response = send_file(index_path, mimetype="text/html")
+ response.headers["Cache-Control"] = "no-store, private"
+ return response
return jsonify({"error": "not_found"}), 404