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): consolidate secondary page reads (#476)

Call White9680c1e81dd2
diff --git a/docs/plans/workbench-request-consolidation.md b/docs/plans/workbench-request-consolidation.md
new file mode 100644
index 000000000..a56033035
--- /dev/null
+++ b/docs/plans/workbench-request-consolidation.md
@@ -0,0 +1,48 @@
+# Workbench request consolidation
+
+## Background
+
+The prior performance work reduced the hottest chat and inbox paths:
+
+- `/api/sessions/<id>/bootstrap` folds the Chat first-screen reads into one request.
+- `/api/config` is cached longer on the client.
+- `/api/inbox` has query-specific SQLite indexes.
+
+The remaining avoidable cost is request fan-out around secondary Workbench
+surfaces: the project tree reconnect path and the Harness page. These hurt most
+over Cloudflare Tunnel because each small request pays extra round-trip cost.
+
+## Goals
+
+- Keep first-screen payloads bounded.
+- Collapse initial Harness reads into one request.
+- Rebuild already-loaded project session windows with fewer requests after SSE
+ reconnects.
+- Add lightweight API timing headers/logs so future slow-path reports can be
+ separated into network, handler, DB, and payload-size questions.
+
+## Non-goals
+
+- No new DB migration unless query-plan evidence shows it is needed.
+- No change to paging contracts or visible UI behavior.
+- No restart of the local Vibe Remote service for verification.
+
+## Plan
+
+1. Add a Workbench projects bootstrap endpoint that returns projects plus
+ optional per-project session pages for requested expanded projects.
+2. Add a Harness bootstrap endpoint that returns counts and the current tab's
+ first page in one payload.
+3. Update the Workbench projects provider to use the bootstrap endpoint for
+ project refresh/reconnect recovery, while preserving 8-row first-page loads.
+4. Update the Harness page to use bootstrap for refreshes, then keep dedicated
+ endpoints for mutations, pagination, and run details.
+5. Add request timing response headers and slow-request logs for `/api/*`
+ routes.
+
+## Validation
+
+- Focused FastAPI tests for new bootstrap routes.
+- Existing Harness route tests.
+- Frontend type/build check.
+- Ruff on changed Python files.
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index cc5f29f89..41104143a 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -146,6 +146,85 @@ def test_harness_routes_page_filter_and_return_counts(monkeypatch, tmp_path):
assert counts["runs"]["all"] == 4
+def test_harness_bootstrap_returns_counts_and_selected_page(monkeypatch, tmp_path):
+ from storage.background import SQLiteBackgroundTaskStore
+
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ store = SQLiteBackgroundTaskStore()
+ try:
+ for index in range(4):
+ store.upsert_scheduled_task(
+ {
+ "id": f"task-{index}",
+ "name": f"Task {index}",
+ "prompt": "run it",
+ "schedule_type": "cron",
+ "cron": "0 * * * *",
+ "enabled": index < 2,
+ "created_at": f"2026-06-04T00:0{index}:00+00:00",
+ "updated_at": f"2026-06-04T00:0{index}:00+00:00",
+ }
+ )
+ for index, status in enumerate(["pending", "completed"]):
+ store.enqueue_run(
+ {
+ "id": f"run-{index}",
+ "request_type": "task",
+ "status": status,
+ "message": "run status",
+ "created_at": f"2026-06-04T00:2{index}:00+00:00",
+ "updated_at": f"2026-06-04T00:2{index}:00+00:00",
+ }
+ )
+ finally:
+ store.close()
+
+ client = app.test_client()
+ response = client.get("/api/harness/bootstrap?tab=tasks&status=enabled&page=1&limit=1")
+
+ assert response.status_code == 200
+ assert response.headers["X-Vibe-Request-Ms"]
+ payload = response.get_json()
+ assert payload["counts"]["tasks"] == {"all": 4, "enabled": 2, "disabled": 2}
+ assert payload["counts"]["runs"]["all"] == 2
+ assert payload["page"]["tasks"][0]["id"] == "task-1"
+ assert payload["page"]["total"] == 2
+ assert payload["page"]["has_more"] is True
+
+
+def test_workbench_projects_bootstrap_returns_requested_session_pages(monkeypatch, tmp_path):
+ from storage.db import create_sqlite_engine
+ from storage.projects_service import create_project
+ from storage.workbench_sessions_service import create_session
+
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ project_a_dir = tmp_path / "project-a"
+ project_b_dir = tmp_path / "project-b"
+ project_a_dir.mkdir()
+ project_b_dir.mkdir()
+ with engine.begin() as conn:
+ project_a = create_project(conn, str(project_a_dir), display_name="Project A")
+ project_b = create_project(conn, str(project_b_dir), display_name="Project B")
+ create_session(conn, scope_id=project_a["scope_id"], agent_backend="", title="First")
+ create_session(conn, scope_id=project_a["scope_id"], agent_backend="", title="Second")
+ create_session(conn, scope_id=project_b["scope_id"], agent_backend="", title="Other")
+
+ client = app.test_client()
+ response = client.get(f"/api/workbench/projects-bootstrap?project_id={project_a['id']}&limit=1")
+
+ assert response.status_code == 200
+ assert response.headers["Server-Timing"].startswith("app;dur=")
+ payload = response.get_json()
+ assert {project["id"] for project in payload["projects"]} == {project_a["id"], project_b["id"]}
+ assert set(payload["sessions"]) == {project_a["id"]}
+ page = payload["sessions"][project_a["id"]]
+ assert len(page["sessions"]) == 1
+ assert page["next_before_id"] == page["sessions"][0]["id"]
+
+
def test_config_get_on_fresh_install_returns_default_needing_setup(monkeypatch, tmp_path):
# Fresh install edge: no config file exists yet, but the setup wizard
# (and the reused provider-config modal that calls getConfig()) must be
diff --git a/ui/src/components/workbench/HarnessPage.tsx b/ui/src/components/workbench/HarnessPage.tsx
index 4ca635c77..3e8e71292 100644
--- a/ui/src/components/workbench/HarnessPage.tsx
+++ b/ui/src/components/workbench/HarnessPage.tsx
@@ -133,46 +133,41 @@ export const HarnessPage: React.FC = () => {
const isCurrent = () => refreshSeq.current === seq;
setLoading(true);
setError(null);
- const query = debouncedSearch || undefined;
- const countsPromise = api.getHarnessCounts().catch(() => null);
+ const query = tab === 'tasks' || tab === 'watches' ? debouncedSearch || undefined : undefined;
try {
- if (tab === 'tasks') {
- const result = await api.listHarnessTasks({
- status: statusFilter,
- query,
- page: tasksPage,
- limit: PAGE_LIMIT,
- });
- if (!isCurrent()) return;
- setTasks(result.tasks);
- setQueryTaskCounts(result.counts);
- setTasksHasMore(result.has_more);
- if (!query) setTaskCounts(result.counts);
- } else if (tab === 'watches') {
- const result = await api.listHarnessWatches({
- status: statusFilter,
- query,
- page: watchesPage,
- limit: PAGE_LIMIT,
- });
+ if (tab === 'webhooks') {
+ const counts = await api.getHarnessCounts();
if (!isCurrent()) return;
- setWatches(result.watches);
- setQueryWatchCounts(result.counts);
- setWatchesHasMore(result.has_more);
- if (!query) setWatchCounts(result.counts);
- } else if (tab === 'runs') {
- const result = await api.listHarnessRuns({ page: runsPage, limit: PAGE_LIMIT });
- if (!isCurrent()) return;
- setRuns(result.runs);
- setRunCounts(result.counts);
- setRunsHasMore(result.has_more);
- }
- const counts = await countsPromise;
- if (!isCurrent()) return;
- if (counts) {
setTaskCounts(counts.tasks);
setWatchCounts(counts.watches);
setRunCounts(counts.runs);
+ return;
+ }
+ const result = await api.getHarnessBootstrap({
+ tab,
+ status: tab === 'runs' ? undefined : statusFilter,
+ query,
+ page: tab === 'tasks' ? tasksPage : tab === 'watches' ? watchesPage : runsPage,
+ limit: PAGE_LIMIT,
+ });
+ if (!isCurrent()) return;
+ setTaskCounts(result.counts.tasks);
+ setWatchCounts(result.counts.watches);
+ setRunCounts(result.counts.runs);
+ if (tab === 'tasks') {
+ const page = result.page as Awaited<ReturnType<typeof api.listHarnessTasks>>;
+ setTasks(page.tasks);
+ setQueryTaskCounts(page.counts);
+ setTasksHasMore(page.has_more);
+ } else if (tab === 'watches') {
+ const page = result.page as Awaited<ReturnType<typeof api.listHarnessWatches>>;
+ setWatches(page.watches);
+ setQueryWatchCounts(page.counts);
+ setWatchesHasMore(page.has_more);
+ } else if (tab === 'runs') {
+ const page = result.page as Awaited<ReturnType<typeof api.listHarnessRuns>>;
+ setRuns(page.runs);
+ setRunsHasMore(page.has_more);
}
} catch (err: any) {
if (!isCurrent()) return;
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index ab2e37523..9b1c9ece4 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -135,6 +135,13 @@ export type ApiContextType = {
browseFavorites: () => Promise<{ ok: boolean; system?: string; favorites?: { key: string; path: string }[]; error?: string }>;
browseMkdir: (path: string) => Promise<{ path: string }>;
listProjects: (includeArchived?: boolean, options?: { cache?: boolean }) => Promise<{ projects: WorkbenchProject[] }>;
+ getWorkbenchProjectsBootstrap: (params?: {
+ includeArchived?: boolean;
+ projectIds?: string[];
+ status?: 'active' | 'archived' | 'all';
+ limit?: number;
+ cache?: boolean;
+ }) => Promise<WorkbenchProjectsBootstrap>;
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.
@@ -201,6 +208,7 @@ export type ApiContextType = {
checkSkills: (params?: { scope?: SkillScope; projectId?: string }) => Promise<SkillsCheckResult>;
updateSkill: (name: string, params?: { scope?: SkillScope; projectId?: string }) => Promise<SkillsMutationResult>;
getHarnessCounts: () => Promise<HarnessCountsResult>;
+ getHarnessBootstrap: (params?: HarnessBootstrapParams) => Promise<HarnessBootstrapResult>;
listHarnessTasks: (params?: HarnessDefinitionsParams) => Promise<HarnessTasksResult>;
setHarnessTaskEnabled: (taskId: string, enabled: boolean) => Promise<{ ok: boolean; task?: HarnessTask }>;
deleteHarnessTask: (taskId: string) => Promise<{ ok: boolean; id?: string }>;
@@ -243,6 +251,16 @@ export type WorkbenchProject = {
metadata?: Record<string, unknown>;
};
+export type ProjectSessionsPage = {
+ sessions: WorkbenchSession[];
+ next_before_id: string | null;
+};
+
+export type WorkbenchProjectsBootstrap = {
+ projects: WorkbenchProject[];
+ sessions: Record<string, ProjectSessionsPage | undefined>;
+};
+
// Workbench session — a row in ``agent_sessions`` created via /api/sessions.
// ``project_id`` is the short ``proj_<hex>`` suffix of ``scope_id``.
export type WorkbenchSession = {
@@ -713,6 +731,20 @@ export type HarnessCountsResult = {
runs: HarnessRunCounts;
};
+export type HarnessBootstrapParams = {
+ tab?: 'tasks' | 'watches' | 'runs';
+ status?: HarnessDefinitionStatus | HarnessRunStatus;
+ query?: string;
+ page?: number;
+ limit?: number;
+};
+
+export type HarnessBootstrapResult = {
+ counts: HarnessCountsResult;
+ tab: 'tasks' | 'watches' | 'runs';
+ page: HarnessTasksResult | HarnessWatchesResult | HarnessRunsResult;
+};
+
export type SessionInfo =
| { remote: false }
| { remote: true; authenticated: false }
@@ -1190,6 +1222,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
path.startsWith(`${sessionPrefix}/`) ||
path.startsWith('/api/sessions?') ||
path === '/api/sessions' ||
+ path.startsWith('/api/workbench/projects-bootstrap') ||
path.startsWith('/api/inbox?') ||
path === '/api/inbox',
);
@@ -1575,6 +1608,18 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
const path = `/api/projects${includeArchived ? '?include_archived=1' : ''}`;
return options?.cache === false ? getJson(path) : getCachedJson(path);
},
+ getWorkbenchProjectsBootstrap: (params) => {
+ const search = new URLSearchParams();
+ if (params?.includeArchived) search.set('include_archived', '1');
+ if (params?.status) search.set('status', params.status);
+ if (params?.limit) search.set('limit', String(params.limit));
+ for (const projectId of params?.projectIds ?? []) {
+ search.append('project_id', projectId);
+ }
+ const qs = search.toString();
+ const path = qs ? `/api/workbench/projects-bootstrap?${qs}` : '/api/workbench/projects-bootstrap';
+ return params?.cache === false ? getJson(path) : getCachedJson(path);
+ },
createProject: (payload) => postJson('/api/projects', payload),
updateProject: async (projectId, payload) => {
const { payloadJson } = await requestJson(`/api/projects/${encodeURIComponent(projectId)}`, {
@@ -1775,6 +1820,16 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
updateSkill: (name, params) =>
postJson('/api/skills/update', { name, scope: params?.scope, project_id: params?.projectId }),
getHarnessCounts: () => getCachedJson('/api/harness/counts'),
+ getHarnessBootstrap: (params) => {
+ const search = new URLSearchParams();
+ if (params?.tab) search.set('tab', params.tab);
+ if (params?.status) search.set('status', params.status);
+ if (params?.query) search.set('query', params.query);
+ if (params?.page) search.set('page', String(params.page));
+ if (params?.limit) search.set('limit', String(params.limit));
+ const qs = search.toString();
+ return getCachedJson(qs ? `/api/harness/bootstrap?${qs}` : '/api/harness/bootstrap');
+ },
listHarnessTasks: (params) => {
const search = new URLSearchParams();
if (params?.status) search.set('status', params.status);
diff --git a/ui/src/context/WorkbenchProjectsContext.tsx b/ui/src/context/WorkbenchProjectsContext.tsx
index 7bf8aefbd..045870dcb 100644
--- a/ui/src/context/WorkbenchProjectsContext.tsx
+++ b/ui/src/context/WorkbenchProjectsContext.tsx
@@ -12,6 +12,7 @@ import type { ProjectDefaultAgent, WorkbenchProject, WorkbenchSession, Workbench
// longer histories. Both surfaces share a single per-project cache, so the page
// size has to be one shared value (it can't differ per surface).
const SESSIONS_PAGE_SIZE = 8;
+const RECONNECT_SESSIONS_PAGE_SIZE = 200;
export interface ProjectSessionsState {
/** null = not loaded yet. [] = loaded-but-empty (or a first-page failure, with `error`). */
@@ -140,17 +141,37 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
return pending;
}, []);
+ const applyBootstrapSessions = useCallback((pages: Record<string, { sessions: WorkbenchSession[]; next_before_id: string | null } | undefined>) => {
+ setSessions((prev) => {
+ let changed = false;
+ const next = { ...prev };
+ for (const [projectId, page] of Object.entries(pages)) {
+ if (!page) continue;
+ next[projectId] = {
+ sessions: page.sessions,
+ cursor: page.next_before_id,
+ loading: false,
+ loadingMore: false,
+ error: false,
+ };
+ changed = true;
+ }
+ return changed ? next : prev;
+ });
+ }, []);
+
const fetchProjects = useCallback(async (options?: { cache?: boolean }) => {
try {
- const result = await api.listProjects(undefined, options);
+ const result = await api.getWorkbenchProjectsBootstrap({ cache: options?.cache });
setProjects(result.projects);
+ applyBootstrapSessions(result.sessions ?? {});
setProjectsError(null);
} catch (err: any) {
// Don't strand consumers on an empty-state for a transient failure — keep
// any list we had and surface the error (mobile shows a retry).
setProjectsError(err?.message ?? String(err));
}
- }, [api]);
+ }, [api, applyBootstrapSessions]);
useEffect(() => {
void fetchProjects();
@@ -211,6 +232,66 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
[api, queueReconcile, takePendingReconcile],
);
+ const reconcileProjectTree = useCallback(async () => {
+ const bootstrapGroups = new Map<number, string[]>();
+ const largeProjectIds: string[] = [];
+ for (const [projectId, state] of Object.entries(sessionsRef.current)) {
+ if (!state || state.sessions === null) continue;
+ const loadedCount = state.sessions.length;
+ if (inFlightRef.current.has(projectId)) {
+ queueReconcile(projectId, loadedCount);
+ continue;
+ }
+ if (state.sessions.length > RECONNECT_SESSIONS_PAGE_SIZE) {
+ largeProjectIds.push(projectId);
+ continue;
+ }
+ const limit = Math.max(SESSIONS_PAGE_SIZE, Math.min(RECONNECT_SESSIONS_PAGE_SIZE, loadedCount || SESSIONS_PAGE_SIZE));
+ const group = bootstrapGroups.get(limit) ?? [];
+ group.push(projectId);
+ bootstrapGroups.set(limit, group);
+ }
+ try {
+ const groups = Array.from(bootstrapGroups.entries());
+ if (groups.length === 0) {
+ const result = await api.getWorkbenchProjectsBootstrap({ cache: false });
+ setProjects(result.projects);
+ } else {
+ let nextProjects: WorkbenchProject[] | null = null;
+ const pages: Record<string, { sessions: WorkbenchSession[]; next_before_id: string | null }> = {};
+ for (const [limit, projectIds] of groups) {
+ const result = await api.getWorkbenchProjectsBootstrap({
+ projectIds,
+ status: 'active',
+ limit,
+ cache: false,
+ });
+ nextProjects = result.projects;
+ for (const [projectId, page] of Object.entries(result.sessions ?? {})) {
+ const currentCount = sessionsRef.current[projectId]?.sessions?.length ?? 0;
+ if (page && !inFlightRef.current.has(projectId) && currentCount <= limit) {
+ pages[projectId] = page;
+ } else {
+ queueReconcile(projectId, currentCount);
+ }
+ }
+ }
+ if (nextProjects) setProjects(nextProjects);
+ applyBootstrapSessions(pages);
+ }
+ setProjectsError(null);
+ for (const projectId of largeProjectIds) {
+ void reconcileSessions(projectId);
+ }
+ } catch (err: any) {
+ setProjectsError(err?.message ?? String(err));
+ const projectIds = [...bootstrapGroups.values()].flat();
+ for (const projectId of [...projectIds, ...largeProjectIds]) {
+ void reconcileSessions(projectId);
+ }
+ }
+ }, [api, applyBootstrapSessions, queueReconcile, reconcileSessions]);
+
// Load the first page (append=false) or the next page (append=true) of a
// project's sessions, with dedupe + per-project serialisation.
const fetchSessions = useCallback(
@@ -270,10 +351,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
useEffect(() => {
const disconnect = api.connectWorkbenchEvents({
onConnected: () => {
- void fetchProjects({ cache: false });
- for (const [projectId, state] of Object.entries(sessionsRef.current)) {
- if (state.sessions !== null) void reconcileSessions(projectId);
- }
+ void reconcileProjectTree();
},
onSessionActivity: (data) => {
if (data.event === 'updated' && Object.prototype.hasOwnProperty.call(data, 'title')) {
@@ -295,7 +373,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
},
});
return disconnect;
- }, [api, fetchProjects, reconcileSessions]);
+ }, [api, reconcileProjectTree, reconcileSessions]);
const toggleExpanded = useCallback(
(projectId: string) => {
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 13c05cbee..63607278d 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -51,6 +51,7 @@ app = CompatApp(title="Vibe Remote UI", docs_url=None, redoc_url=None, openapi_u
# Global server instance for graceful shutdown on reload
_server = None
+SLOW_API_REQUEST_MS = float(os.environ.get("VIBE_UI_SLOW_API_MS", "2000"))
_SHOW_RUNTIME_REQUEST_HEADER_ALLOWLIST = {
"accept",
"accept-language",
@@ -1100,6 +1101,13 @@ def _restart_vibe_cloud_login_from_state(config: V2Config, state: str | None):
return response
+def start_api_request_timer():
+ if request.path.startswith("/api/"):
+ g.api_request_started_at = time.perf_counter()
+ return None
+
+
@app.before_request
def enforce_remote_access_cookie():
config = _load_remote_access_config()
@@ -1163,6 +1171,28 @@ def protect_mutating_ui_requests():
return None
+def add_api_timing_headers(response: Response) -> Response:
+ started_at = getattr(g, "api_request_started_at", None)
+ if started_at is None:
+ return response
+ elapsed_ms = max(0.0, (time.perf_counter() - started_at) * 1000.0)
+ elapsed_text = f"{elapsed_ms:.1f}"
+ response.headers["Server-Timing"] = f"app;dur={elapsed_text}"
+ response.headers["X-Vibe-Request-Ms"] = elapsed_text
+ if elapsed_ms >= SLOW_API_REQUEST_MS:
+ payload_size = response.headers.get("Content-Length")
+ logger.warning(
+ "slow api request path=%s method=%s status=%s duration_ms=%.1f size=%s",
+ request.path,
+ request.method,
+ response.status_code,
+ elapsed_ms,
+ payload_size or "unknown",
+ )
+ return response
+
+
@app.after_request
def add_csrf_cookie(response: Response) -> Response:
return _ensure_csrf_cookie(response)
@@ -3386,6 +3416,43 @@ def sessions_list():
return jsonify(result)
[email protected]("/api/workbench/projects-bootstrap", methods=["GET"])
+def workbench_projects_bootstrap():
+ """Projects tree payload with optional first/restored session pages.
+
+ The sidebar and mobile projects page share one provider. This endpoint lets
+ that provider refresh projects and any already-expanded project windows with
+ one tunnel round-trip, while preserving the dedicated `/api/sessions`
+ endpoint for normal pagination.
+ """
+ from core.services import sessions as workbench_sessions_service
+ from storage import projects_service
+
+ include_archived = request.args.get("include_archived") in {"1", "true", "yes"}
+ status = request.args.get("status") or "active"
+ try:
+ limit = int(request.args.get("limit") or 8)
+ except (TypeError, ValueError):
+ limit = 8
+ project_ids = [value.strip() for value in request.args.getlist("project_id") if value.strip()]
+
+ engine = _projects_engine()
+ with engine.connect() as conn:
+ projects = projects_service.list_projects(conn, include_archived=include_archived)
+ project_id_set = {project["id"] for project in projects}
+ sessions: dict[str, Any] = {}
+ for project_id in project_ids:
+ if project_id not in project_id_set:
+ continue
+ sessions[project_id] = workbench_sessions_service.list_sessions(
+ conn,
+ scope_id=_project_to_scope_id(project_id),
+ status=status,
+ limit=limit,
+ )
+ return jsonify({"projects": projects, "sessions": sessions})
+
+
@app.route("/api/sessions", methods=["POST"])
def sessions_create():
from core.services import sessions as workbench_sessions_service
@@ -4370,7 +4437,16 @@ def _harness_has_list_params() -> bool:
def _harness_page_payload(page_result, *, items_key: str, counts: dict[str, int]) -> dict[str, Any]:
- total = int(counts.get(request.args.get("status") or "all", 0))
+ return _harness_page_payload_for_status(
+ page_result,
+ items_key=items_key,
+ counts=counts,
+ status=request.args.get("status") or "all",
+ )
+
+
+def _harness_page_payload_for_status(page_result, *, items_key: str, counts: dict[str, int], status: str) -> dict[str, Any]:
+ total = int(counts.get(status or "all", 0))
return {
items_key: page_result.items,
"counts": counts,
@@ -4561,6 +4637,95 @@ def harness_runs_list():
)
[email protected]("/api/harness/bootstrap", methods=["GET"])
+def harness_bootstrap():
+ """Initial Harness page payload.
+
+ Counts are global for tab badges; ``page`` mirrors the selected tab's
+ existing endpoint shape so follow-up pagination and refreshes can keep using
+ the dedicated routes.
+ """
+ tab = request.args.get("tab") or "tasks"
+ if tab not in {"tasks", "watches", "runs"}:
+ return jsonify({"ok": False, "code": "invalid_tab", "message": "tab must be one of: tasks, watches, runs"}), 400
+ try:
+ page_request = _harness_page_request()
+ definition_status = _harness_status_filter() if tab in {"tasks", "watches"} else "all"
+ query = _harness_query_filter()
+ except ValueError as exc:
+ return jsonify({"ok": False, "code": "invalid_pagination", "message": str(exc)}), 400
+
+ with _harness_store() as store:
+ counts_payload = {
+ "tasks": store.count_scheduled_tasks(),
+ "watches": store.count_watches(),
+ "runs": store.count_runs_by_status(),
+ }
+ if tab == "tasks":
+ page_result = store.list_scheduled_tasks_page(
+ status=definition_status,
+ query=query,
+ page_request=page_request,
+ newest_first=True,
+ )
+ page_payload = _harness_page_payload_for_status(
+ page_result,
+ items_key="tasks",
+ counts=store.count_scheduled_tasks(query=query),
+ status=definition_status,
+ )
+ elif tab == "watches":
+ page_result = store.list_watches_page(
+ status=definition_status,
+ query=query,
+ page_request=page_request,
+ newest_first=True,
+ )
+ runtime = store.load_watch_runtime().get("watches") or {}
+ for watch in page_result.items:
+ watch["runtime"] = runtime.get(watch["id"]) or {"running": False}
+ page_payload = _harness_page_payload_for_status(
+ page_result,
+ items_key="watches",
+ counts=store.count_watches(query=query),
+ status=definition_status,
+ )
+ else:
+ run_status = request.args.get("status") or None
+ run_type = request.args.get("run_type") or None
+ agent_name = request.args.get("agent_name") or None
+ definition_id = request.args.get("definition_id") or None
+ page_result = store.list_runs_page(
+ status=run_status,
+ run_type=run_type,
+ agent_name=agent_name,
+ definition_id=definition_id,
+ query=query,
+ page_request=page_request,
+ newest_first=True,
+ )
+ page_payload = {
+ "runs": page_result.items,
+ "counts": store.count_runs_by_status(
+ run_type=run_type,
+ agent_name=agent_name,
+ definition_id=definition_id,
+ query=query,
+ ),
+ "total": store.count_runs(
+ status=run_status,
+ run_type=run_type,
+ agent_name=agent_name,
+ definition_id=definition_id,
+ query=query,
+ ),
+ "page": page_result.page,
+ "limit": page_result.limit,
+ "has_more": page_result.has_more,
+ }
+ return jsonify({"counts": counts_payload, "tab": tab, "page": page_payload})
+
+
@app.route("/api/harness/runs/<run_id>", methods=["GET"])
def harness_run_detail(run_id: str):
with _harness_store() as store: