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.

fix(ui): paginate harness lists

cyh2bd67fc5629e
diff --git a/docs/plans/harness-pagination-counts.md b/docs/plans/harness-pagination-counts.md
new file mode 100644
index 000000000..a0cad5007
--- /dev/null
+++ b/docs/plans/harness-pagination-counts.md
@@ -0,0 +1,28 @@
+# Harness Pagination and Counts
+
+## Background
+
+The Workbench Harness page currently loads every scheduled task or watch, then
+filters and counts rows in React. Large inventories, especially old paused
+watches, make the page pay the cost of data the user is not viewing.
+
+## Goal
+
+- Fetch tasks and watches by the active filter instead of loading all rows.
+- Page task, watch, and run lists consistently.
+- Drive tab badges and filter summaries from backend counts, not loaded arrays.
+
+## Design
+
+- Keep existing store `list_*` methods as internal all-row APIs for scheduler
+ reconciliation.
+- Add dedicated page queries for scheduled definitions, watches, and runs.
+- Add aggregate count helpers that compute all/enabled/disabled buckets in SQL.
+- Update UI routes to return `{items, counts, page, limit, has_more, total}`.
+- Update the Harness page to keep page state per tab and refresh the active
+ tab/counts through server-side filters.
+
+## Validation
+
+- Focused Python tests for store pagination/counts and UI route payloads.
+- TypeScript build for the Workbench UI.
diff --git a/storage/background.py b/storage/background.py
index 63713ec46..41a2e3e28 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -9,7 +9,7 @@ from zoneinfo import ZoneInfo
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.date import DateTrigger
-from sqlalchemy import insert, or_, select, update
+from sqlalchemy import func, insert, or_, select, update
from config import paths
from storage.db import SqliteInvalidationProbe, create_sqlite_engine
@@ -88,6 +88,8 @@ RUN_STATUS_ALIASES: dict[str, str] = {
"canceled": "canceled",
}
_LIKE_ESCAPE = "\\"
+DEFINITION_STATUS_COUNTS = ("all", "enabled", "disabled")
+RUN_STATUS_COUNTS = ("all", "queued", "running", "succeeded", "failed", "canceled")
def normalize_run_status(status: Any) -> str:
@@ -141,6 +143,34 @@ class SQLiteBackgroundTaskStore:
)
return [self._enrich_task(self._scheduled_task_from_row(row), conn) for row in rows]
+ def list_scheduled_tasks_page(
+ self,
+ *,
+ status: Optional[str] = None,
+ query: Optional[str] = None,
+ page_request: PageRequest | None,
+ newest_first: bool = True,
+ ) -> PageResult[dict[str, Any]]:
+ stmt = self._definitions_query("scheduled", status=status, query=query)
+ activity = func.coalesce(
+ run_definitions.c.last_run_at,
+ run_definitions.c.updated_at,
+ run_definitions.c.created_at,
+ "",
+ )
+ if newest_first:
+ stmt = stmt.order_by(activity.desc(), run_definitions.c.id.desc())
+ else:
+ stmt = stmt.order_by(activity, run_definitions.c.id)
+ if page_request is not None:
+ stmt = stmt.offset(page_request.offset).limit(page_request.limit + 1)
+ with self.engine.connect() as conn:
+ rows = [self._enrich_task(self._scheduled_task_from_row(row), conn) for row in conn.execute(stmt).mappings()]
+ return page_result_from_limit_plus_one(rows, page_request)
+
+ def count_scheduled_tasks(self, *, query: Optional[str] = None) -> dict[str, int]:
+ return self._definition_counts("scheduled", query=query)
+
def get_scheduled_task(self, definition_id: str) -> Optional[dict[str, Any]]:
with self.engine.connect() as conn:
row = conn.execute(
@@ -204,6 +234,35 @@ class SQLiteBackgroundTaskStore:
)
return [self._enrich_watch(self._watch_from_row(row), conn) for row in rows]
+ def list_watches_page(
+ self,
+ *,
+ status: Optional[str] = None,
+ query: Optional[str] = None,
+ page_request: PageRequest | None,
+ newest_first: bool = True,
+ ) -> PageResult[dict[str, Any]]:
+ stmt = self._definitions_query("watch", status=status, query=query)
+ activity = func.coalesce(
+ run_definitions.c.last_event_at,
+ run_definitions.c.last_started_at,
+ run_definitions.c.updated_at,
+ run_definitions.c.created_at,
+ "",
+ )
+ if newest_first:
+ stmt = stmt.order_by(activity.desc(), run_definitions.c.id.desc())
+ else:
+ stmt = stmt.order_by(activity, run_definitions.c.id)
+ if page_request is not None:
+ stmt = stmt.offset(page_request.offset).limit(page_request.limit + 1)
+ with self.engine.connect() as conn:
+ rows = [self._enrich_watch(self._watch_from_row(row), conn) for row in conn.execute(stmt).mappings()]
+ return page_result_from_limit_plus_one(rows, page_request)
+
+ def count_watches(self, *, query: Optional[str] = None) -> dict[str, int]:
+ return self._definition_counts("watch", query=query)
+
def get_watch(self, watch_id: str) -> Optional[dict[str, Any]]:
with self.engine.connect() as conn:
row = conn.execute(
@@ -278,6 +337,68 @@ class SQLiteBackgroundTaskStore:
rows = [self._run_from_row(row) for row in conn.execute(stmt).mappings()]
return page_result_from_limit_plus_one(rows, page_request)
+ def count_runs(
+ self,
+ *,
+ status: Optional[str] = None,
+ run_type: Optional[str] = None,
+ agent_name: Optional[str] = None,
+ agent_backend: Optional[str] = None,
+ session_id: Optional[str] = None,
+ definition_id: Optional[str] = None,
+ created_after: Optional[str] = None,
+ created_before: Optional[str] = None,
+ query: Optional[str] = None,
+ ) -> int:
+ stmt = self._runs_query(
+ status=status,
+ run_type=run_type,
+ agent_name=agent_name,
+ agent_backend=agent_backend,
+ session_id=session_id,
+ definition_id=definition_id,
+ created_after=created_after,
+ created_before=created_before,
+ query=query,
+ count=True,
+ )
+ with self.engine.connect() as conn:
+ return int(conn.execute(stmt).scalar_one() or 0)
+
+ def count_runs_by_status(
+ self,
+ *,
+ run_type: Optional[str] = None,
+ agent_name: Optional[str] = None,
+ agent_backend: Optional[str] = None,
+ session_id: Optional[str] = None,
+ definition_id: Optional[str] = None,
+ created_after: Optional[str] = None,
+ created_before: Optional[str] = None,
+ query: Optional[str] = None,
+ ) -> dict[str, int]:
+ stmt = self._runs_query(
+ run_type=run_type,
+ agent_name=agent_name,
+ agent_backend=agent_backend,
+ session_id=session_id,
+ definition_id=definition_id,
+ created_after=created_after,
+ created_before=created_before,
+ query=query,
+ columns=(agent_runs.c.status, func.count()),
+ ).group_by(agent_runs.c.status)
+ counts = {key: 0 for key in RUN_STATUS_COUNTS}
+ with self.engine.connect() as conn:
+ for raw_status, count in conn.execute(stmt).all():
+ public_status = normalize_run_status(raw_status)
+ if public_status not in counts:
+ counts[public_status] = 0
+ value = int(count or 0)
+ counts[public_status] += value
+ counts["all"] += value
+ return counts
+
def _runs_query(
self,
*,
@@ -290,8 +411,15 @@ class SQLiteBackgroundTaskStore:
created_after: Optional[str] = None,
created_before: Optional[str] = None,
query: Optional[str] = None,
+ count: bool = False,
+ columns: Any = None,
):
- stmt = select(agent_runs)
+ if columns is not None:
+ stmt = select(*columns) if isinstance(columns, tuple) else select(columns)
+ elif count:
+ stmt = select(func.count()).select_from(agent_runs)
+ else:
+ stmt = select(agent_runs)
if status:
stmt = stmt.where(agent_runs.c.status.in_(_status_query_values(status)))
if run_type:
@@ -326,6 +454,72 @@ class SQLiteBackgroundTaskStore:
)
return stmt
+ def _definitions_query(
+ self,
+ definition_type: str,
+ *,
+ status: Optional[str] = None,
+ query: Optional[str] = None,
+ columns: Any = None,
+ ):
+ if columns is not None:
+ stmt = select(*columns) if isinstance(columns, tuple) else select(columns)
+ else:
+ stmt = select(run_definitions)
+ stmt = (
+ stmt.where(run_definitions.c.definition_type == definition_type)
+ .where(run_definitions.c.deleted_at.is_(None))
+ )
+ if status and status != "all":
+ if status not in {"enabled", "disabled"}:
+ raise ValueError("status must be one of: all, enabled, disabled")
+ stmt = stmt.where(run_definitions.c.enabled == (1 if status == "enabled" else 0))
+ if query:
+ pattern = _like_contains_pattern(query)
+ fields = [
+ run_definitions.c.id,
+ run_definitions.c.name,
+ run_definitions.c.agent_name,
+ run_definitions.c.session_id,
+ run_definitions.c.legacy_session_key,
+ run_definitions.c.message,
+ ]
+ if definition_type == "scheduled":
+ fields.extend(
+ [
+ run_definitions.c.prompt,
+ run_definitions.c.schedule_type,
+ run_definitions.c.cron,
+ run_definitions.c.run_at,
+ ]
+ )
+ elif definition_type == "watch":
+ fields.extend(
+ [
+ run_definitions.c.command_json,
+ run_definitions.c.shell_command,
+ run_definitions.c.prefix,
+ run_definitions.c.cwd,
+ ]
+ )
+ stmt = stmt.where(or_(*(field.like(pattern, escape=_LIKE_ESCAPE) for field in fields)))
+ return stmt
+
+ def _definition_counts(self, definition_type: str, *, query: Optional[str] = None) -> dict[str, int]:
+ stmt = self._definitions_query(
+ definition_type,
+ query=query,
+ columns=(run_definitions.c.enabled, func.count()),
+ ).group_by(run_definitions.c.enabled)
+ counts = {key: 0 for key in DEFINITION_STATUS_COUNTS}
+ with self.engine.connect() as conn:
+ for enabled, count in conn.execute(stmt).all():
+ key = "enabled" if bool(enabled) else "disabled"
+ value = int(count or 0)
+ counts[key] += value
+ counts["all"] += value
+ return counts
+
def get_run(self, run_id: str) -> Optional[dict[str, Any]]:
with self.engine.connect() as conn:
row = conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1)).mappings().first()
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index bebc6e892..d359b7ffe 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -801,6 +801,88 @@ def test_sqlite_run_listing_pages_and_filters(tmp_path: Path) -> None:
sqlite.close()
+def test_sqlite_definition_listing_pages_filter_and_count_without_loading_all(tmp_path: Path) -> None:
+ sqlite = SQLiteBackgroundTaskStore(tmp_path / "state" / "vibe.sqlite")
+ try:
+ for index in range(5):
+ sqlite.upsert_scheduled_task(
+ {
+ "id": f"task-{index}",
+ "name": f"Nightly task {index}",
+ "prompt": "run it",
+ "schedule_type": "cron",
+ "cron": "0 * * * *",
+ "enabled": index % 2 == 0,
+ "created_at": f"2026-05-25T00:0{index}:00+00:00",
+ "updated_at": f"2026-05-25T00:0{index}:00+00:00",
+ }
+ )
+ for index in range(6):
+ sqlite.upsert_watch(
+ {
+ "id": f"watch-{index}",
+ "name": f"Deploy watch {index}",
+ "shell_command": f"tail deploy-{index}.log",
+ "enabled": index < 2,
+ "created_at": f"2026-05-25T00:1{index}:00+00:00",
+ "updated_at": f"2026-05-25T00:1{index}:00+00:00",
+ }
+ )
+
+ enabled_tasks = sqlite.list_scheduled_tasks_page(
+ status="enabled",
+ page_request=PageRequest(page=1, limit=2),
+ )
+ disabled_watches = sqlite.list_watches_page(
+ status="disabled",
+ query="deploy",
+ page_request=PageRequest(page=1, limit=3),
+ )
+
+ assert [item["id"] for item in enabled_tasks.items] == ["task-4", "task-2"]
+ assert enabled_tasks.has_more is True
+ assert sqlite.count_scheduled_tasks() == {"all": 5, "enabled": 3, "disabled": 2}
+ assert [item["id"] for item in disabled_watches.items] == ["watch-5", "watch-4", "watch-3"]
+ assert disabled_watches.has_more is True
+ assert sqlite.count_watches(query="deploy") == {"all": 6, "enabled": 2, "disabled": 4}
+ finally:
+ sqlite.close()
+
+
+def test_sqlite_run_counts_respect_filters_and_public_status_aliases(tmp_path: Path) -> None:
+ sqlite = SQLiteBackgroundTaskStore(tmp_path / "state" / "vibe.sqlite")
+ try:
+ for run_id, status, run_type in [
+ ("run-queued", "pending", "watch"),
+ ("run-running", "processing", "watch"),
+ ("run-succeeded", "completed", "watch"),
+ ("run-failed", "failed", "scheduled"),
+ ("run-other", "completed", "hook_send"),
+ ]:
+ sqlite.enqueue_run(
+ {
+ "id": run_id,
+ "request_type": run_type,
+ "status": status,
+ "message": "deploy status",
+ "created_at": "2026-05-25T00:00:00+00:00",
+ "updated_at": "2026-05-25T00:00:00+00:00",
+ }
+ )
+
+ assert sqlite.count_runs(status="succeeded", run_type="watch", query="deploy") == 1
+ assert sqlite.count_runs_by_status(run_type="watch", query="deploy") == {
+ "all": 3,
+ "queued": 1,
+ "running": 1,
+ "succeeded": 1,
+ "failed": 0,
+ "canceled": 0,
+ }
+ finally:
+ sqlite.close()
+
+
def test_sqlite_run_query_filter_treats_like_wildcards_as_literals(tmp_path: Path) -> None:
sqlite = SQLiteBackgroundTaskStore(tmp_path / "state" / "vibe.sqlite")
try:
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 7f2931964..d5e3575c3 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -61,6 +61,82 @@ def test_normalize_response_supports_body_headers_tuple():
assert response.body == b"ok"
+def test_harness_routes_page_filter_and_return_counts(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(5):
+ store.upsert_scheduled_task(
+ {
+ "id": f"task-{index}",
+ "name": f"Task {index}",
+ "prompt": "run it",
+ "schedule_type": "cron",
+ "cron": "0 * * * *",
+ "enabled": index < 3,
+ "created_at": f"2026-06-04T00:0{index}:00+00:00",
+ "updated_at": f"2026-06-04T00:0{index}:00+00:00",
+ }
+ )
+ for index in range(6):
+ store.upsert_watch(
+ {
+ "id": f"watch-{index}",
+ "name": f"Deploy watch {index}",
+ "shell_command": f"tail deploy-{index}.log",
+ "enabled": index == 0,
+ "created_at": f"2026-06-04T00:1{index}:00+00:00",
+ "updated_at": f"2026-06-04T00:1{index}:00+00:00",
+ }
+ )
+ for index, status in enumerate(["pending", "processing", "completed", "failed"]):
+ store.enqueue_run(
+ {
+ "id": f"run-{index}",
+ "request_type": "watch",
+ "status": status,
+ "message": "deploy 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()
+ legacy_tasks = client.get("/api/harness/tasks").get_json()
+ legacy_watches = client.get("/api/harness/watches").get_json()
+ tasks = client.get("/api/harness/tasks?status=enabled&page=1&limit=2").get_json()
+ watches = client.get("/api/harness/watches?status=disabled&query=deploy&page=1&limit=2").get_json()
+ runs = client.get("/api/harness/runs?page=1&limit=2").get_json()
+ counts = client.get("/api/harness/counts").get_json()
+
+ assert len(legacy_tasks["tasks"]) == 5
+ assert legacy_tasks["has_more"] is False
+ assert len(legacy_watches["watches"]) == 6
+ assert legacy_watches["has_more"] is False
+ assert [item["id"] for item in tasks["tasks"]] == ["task-2", "task-1"]
+ assert tasks["counts"] == {"all": 5, "enabled": 3, "disabled": 2}
+ assert tasks["total"] == 3
+ assert tasks["has_more"] is True
+ assert [item["id"] for item in watches["watches"]] == ["watch-5", "watch-4"]
+ assert watches["counts"] == {"all": 6, "enabled": 1, "disabled": 5}
+ assert watches["total"] == 5
+ assert watches["has_more"] is True
+ assert [item["id"] for item in runs["runs"]] == ["run-3", "run-2"]
+ assert runs["total"] == 4
+ assert runs["counts"]["queued"] == 1
+ assert runs["counts"]["running"] == 1
+ assert runs["counts"]["succeeded"] == 1
+ assert runs["counts"]["failed"] == 1
+ assert counts["tasks"]["all"] == 5
+ assert counts["watches"]["disabled"] == 5
+ assert counts["runs"]["all"] == 4
+
+
def test_run_maybe_async_offloads_sync_handlers_without_losing_context():
import asyncio
import threading
diff --git a/ui/src/components/workbench/HarnessPage.tsx b/ui/src/components/workbench/HarnessPage.tsx
index dde264923..a0e8ecd5e 100644
--- a/ui/src/components/workbench/HarnessPage.tsx
+++ b/ui/src/components/workbench/HarnessPage.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
ArrowLeft,
@@ -28,7 +28,10 @@ import { Link } from 'react-router-dom';
import { useApi } from '../../context/ApiContext';
import type {
+ HarnessDefinitionCounts,
+ HarnessDefinitionStatus,
HarnessRun,
+ HarnessRunCounts,
HarnessRunStatus,
HarnessSessionSummary,
HarnessTask,
@@ -55,17 +58,6 @@ function displayTitle(value: string | null | undefined, fallbackId: string): str
return `${fallbackId.slice(0, 10)}…`;
}
-// Pick the most recent activity timestamp on a task so we can sort the
-// list. Falls back to update time, then create time, so brand-new tasks
-// still sort consistently.
-function taskTimestamp(t: HarnessTask): string {
- return t.last_run_at || t.updated_at || t.created_at || '';
-}
-
-function watchTimestamp(w: HarnessWatch): string {
- return w.last_event_at || w.last_started_at || w.updated_at || w.created_at || '';
-}
-
function formatSchedule(task: HarnessTask, t: (k: string, opts?: any) => string): string {
if (task.cron) return t('harness.schedule.cron', { value: task.cron });
if (task.run_at) return t('harness.schedule.oneShot', { value: task.run_at });
@@ -75,6 +67,16 @@ function formatSchedule(task: HarnessTask, t: (k: string, opts?: any) => string)
type TabKey = 'tasks' | 'watches' | 'webhooks' | 'runs';
const TAB_ORDER: TabKey[] = ['tasks', 'watches', 'webhooks', 'runs'];
+const PAGE_LIMIT = 30;
+const EMPTY_DEFINITION_COUNTS: HarnessDefinitionCounts = { all: 0, enabled: 0, disabled: 0 };
+const EMPTY_RUN_COUNTS: HarnessRunCounts = {
+ all: 0,
+ queued: 0,
+ running: 0,
+ succeeded: 0,
+ failed: 0,
+ canceled: 0,
+};
type Selection =
| { kind: 'task'; id: string }
@@ -89,7 +91,16 @@ export const HarnessPage: React.FC = () => {
const [tasks, setTasks] = useState<HarnessTask[]>([]);
const [watches, setWatches] = useState<HarnessWatch[]>([]);
const [runs, setRuns] = useState<HarnessRun[]>([]);
+ const [taskCounts, setTaskCounts] = useState<HarnessDefinitionCounts>(EMPTY_DEFINITION_COUNTS);
+ const [watchCounts, setWatchCounts] = useState<HarnessDefinitionCounts>(EMPTY_DEFINITION_COUNTS);
+ const [runCounts, setRunCounts] = useState<HarnessRunCounts>(EMPTY_RUN_COUNTS);
+ const [queryTaskCounts, setQueryTaskCounts] = useState<HarnessDefinitionCounts>(EMPTY_DEFINITION_COUNTS);
+ const [queryWatchCounts, setQueryWatchCounts] = useState<HarnessDefinitionCounts>(EMPTY_DEFINITION_COUNTS);
+ const [tasksHasMore, setTasksHasMore] = useState(false);
+ const [watchesHasMore, setWatchesHasMore] = useState(false);
const [runsHasMore, setRunsHasMore] = useState(false);
+ const [tasksPage, setTasksPage] = useState(1);
+ const [watchesPage, setWatchesPage] = useState(1);
const [runsPage, setRunsPage] = useState(1);
const [selection, setSelection] = useState<Selection>(null);
const [selectedRun, setSelectedRun] = useState<HarnessRun | null>(null);
@@ -107,29 +118,69 @@ export const HarnessPage: React.FC = () => {
// active tasks/watches first, not bury them among disabled leftovers. The
// user can still switch to "all"/"disabled"; the filtered-count hint makes
// the active filter obvious.
- const [statusFilter, setStatusFilter] = useState<'all' | 'enabled' | 'disabled'>('enabled');
+ const [statusFilter, setStatusFilter] = useState<HarnessDefinitionStatus>('enabled');
+ const [debouncedSearch, setDebouncedSearch] = useState('');
+ const refreshSeq = useRef(0);
+
+ useEffect(() => {
+ const timeout = window.setTimeout(() => setDebouncedSearch(search.trim()), 250);
+ return () => window.clearTimeout(timeout);
+ }, [search]);
const refresh = useCallback(async () => {
+ const seq = refreshSeq.current + 1;
+ refreshSeq.current = seq;
+ const isCurrent = () => refreshSeq.current === seq;
setLoading(true);
setError(null);
+ const query = debouncedSearch || undefined;
+ const countsPromise = api.getHarnessCounts().catch(() => null);
try {
if (tab === 'tasks') {
- const result = await api.listHarnessTasks();
+ 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();
+ const result = await api.listHarnessWatches({
+ status: statusFilter,
+ query,
+ page: watchesPage,
+ limit: PAGE_LIMIT,
+ });
+ 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: 30 });
+ 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);
+ }
} catch (err: any) {
+ if (!isCurrent()) return;
setError(err?.message ?? String(err));
} finally {
- setLoading(false);
+ if (isCurrent()) setLoading(false);
}
- }, [api, tab, runsPage]);
+ }, [api, tab, debouncedSearch, statusFilter, tasksPage, watchesPage, runsPage]);
useEffect(() => {
refresh();
@@ -170,13 +221,11 @@ export const HarnessPage: React.FC = () => {
const next = !task.enabled;
setTasks((prev) => prev.map((t) => (t.id === task.id ? { ...t, enabled: next } : t)));
try {
- const result = await api.setHarnessTaskEnabled(task.id, next);
- // Reconcile with the server's recomputed fields — next_run_at depends on
- // `enabled`, so the optimistic flip alone would leave it stale.
- if (result.task) {
- const updated = result.task;
- setTasks((prev) => prev.map((t) => (t.id === task.id ? updated : t)));
+ await api.setHarnessTaskEnabled(task.id, next);
+ if (statusFilter !== 'all' && ((statusFilter === 'enabled') !== next)) {
+ setSelection((prev) => (prev?.kind === 'task' && prev.id === task.id ? null : prev));
}
+ await refresh();
} catch (err: any) {
setError(err?.message ?? String(err));
setTasks((prev) => prev.map((t) => (t.id === task.id ? { ...t, enabled: task.enabled } : t)));
@@ -184,7 +233,7 @@ export const HarnessPage: React.FC = () => {
markPending(task.id, false);
}
},
- [api, markPending],
+ [api, markPending, refresh, statusFilter],
);
const deleteTask = useCallback(
@@ -196,15 +245,16 @@ export const HarnessPage: React.FC = () => {
markPending(task.id, true);
try {
await api.deleteHarnessTask(task.id);
- setTasks((prev) => prev.filter((t) => t.id !== task.id));
setSelection((prev) => (prev?.kind === 'task' && prev.id === task.id ? null : prev));
+ if (tasks.length === 1 && tasksPage > 1) setTasksPage((page) => Math.max(1, page - 1));
+ else await refresh();
} catch (err: any) {
setError(err?.message ?? String(err));
} finally {
markPending(task.id, false);
}
},
- [api, markPending, t],
+ [api, markPending, refresh, t, tasks.length, tasksPage],
);
const toggleWatchEnabled = useCallback(
@@ -213,12 +263,11 @@ export const HarnessPage: React.FC = () => {
const next = !watch.enabled;
setWatches((prev) => prev.map((w) => (w.id === watch.id ? { ...w, enabled: next } : w)));
try {
- const result = await api.setHarnessWatchEnabled(watch.id, next);
- // Reconcile with the server payload (refreshed runtime + session summary).
- if (result.watch) {
- const updated = result.watch;
- setWatches((prev) => prev.map((w) => (w.id === watch.id ? updated : w)));
+ await api.setHarnessWatchEnabled(watch.id, next);
+ if (statusFilter !== 'all' && ((statusFilter === 'enabled') !== next)) {
+ setSelection((prev) => (prev?.kind === 'watch' && prev.id === watch.id ? null : prev));
}
+ await refresh();
} catch (err: any) {
setError(err?.message ?? String(err));
setWatches((prev) => prev.map((w) => (w.id === watch.id ? { ...w, enabled: watch.enabled } : w)));
@@ -226,7 +275,7 @@ export const HarnessPage: React.FC = () => {
markPending(watch.id, false);
}
},
- [api, markPending],
+ [api, markPending, refresh, statusFilter],
);
const deleteWatch = useCallback(
@@ -238,15 +287,16 @@ export const HarnessPage: React.FC = () => {
markPending(watch.id, true);
try {
await api.deleteHarnessWatch(watch.id);
- setWatches((prev) => prev.filter((w) => w.id !== watch.id));
setSelection((prev) => (prev?.kind === 'watch' && prev.id === watch.id ? null : prev));
+ if (watches.length === 1 && watchesPage > 1) setWatchesPage((page) => Math.max(1, page - 1));
+ else await refresh();
} catch (err: any) {
setError(err?.message ?? String(err));
} finally {
markPending(watch.id, false);
}
},
- [api, markPending, t],
+ [api, markPending, refresh, t, watches.length, watchesPage],
);
// Fetch run detail (stdout/stderr) whenever a run is selected so the
@@ -272,12 +322,12 @@ export const HarnessPage: React.FC = () => {
const counts = useMemo(
() => ({
- tasks: tasks.length,
- watches: watches.length,
+ tasks: taskCounts.all,
+ watches: watchCounts.all,
webhooks: 0,
- runs: runs.length + (runsHasMore ? 1 : 0),
+ runs: runCounts.all,
}),
- [tasks.length, watches.length, runs.length, runsHasMore],
+ [taskCounts.all, watchCounts.all, runCounts.all],
);
const selectedTask = useMemo(
@@ -289,55 +339,11 @@ export const HarnessPage: React.FC = () => {
[selection, watches],
);
- // Sort by last activity desc so the most relevant rows surface first.
- // Brand-new rows (no activity yet) sort to the bottom intentionally —
- // the user knows about those because they just created them.
- const sortedTasks = useMemo(
- () => [...tasks].sort((a, b) => taskTimestamp(b).localeCompare(taskTimestamp(a))),
- [tasks],
- );
- const sortedWatches = useMemo(
- () => [...watches].sort((a, b) => watchTimestamp(b).localeCompare(watchTimestamp(a))),
- [watches],
- );
-
- // Search + status filter applied client-side. Searches name / id /
- // schedule snippets / command snippets — enough to find rows by any
- // identifying string a user would remember.
- const filteredTasks = useMemo(() => {
- const q = search.trim().toLowerCase();
- return sortedTasks.filter((task) => {
- if (statusFilter === 'enabled' && !task.enabled) return false;
- if (statusFilter === 'disabled' && task.enabled) return false;
- if (!q) return true;
- return (
- (task.name ?? '').toLowerCase().includes(q) ||
- task.id.toLowerCase().includes(q) ||
- (task.cron ?? '').toLowerCase().includes(q) ||
- (task.agent_name ?? '').toLowerCase().includes(q)
- );
- });
- }, [sortedTasks, search, statusFilter]);
- const filteredWatches = useMemo(() => {
- const q = search.trim().toLowerCase();
- return sortedWatches.filter((watch) => {
- if (statusFilter === 'enabled' && !watch.enabled) return false;
- if (statusFilter === 'disabled' && watch.enabled) return false;
- if (!q) return true;
- const cmd = watch.shell_command || (Array.isArray(watch.command) ? watch.command.join(' ') : '');
- return (
- (watch.name ?? '').toLowerCase().includes(q) ||
- watch.id.toLowerCase().includes(q) ||
- cmd.toLowerCase().includes(q) ||
- (watch.agent_name ?? '').toLowerCase().includes(q)
- );
- });
- }, [sortedWatches, search, statusFilter]);
-
const hasSelection = !!(selectedTask || selectedWatch || selectedRun);
const showSearchBar = tab === 'tasks' || tab === 'watches';
- const totalForTab = tab === 'tasks' ? sortedTasks.length : sortedWatches.length;
- const shownForTab = tab === 'tasks' ? filteredTasks.length : filteredWatches.length;
+ const queryCounts = tab === 'tasks' ? queryTaskCounts : queryWatchCounts;
+ const totalForTab = queryCounts.all;
+ const shownForTab = queryCounts[statusFilter] ?? 0;
return (
<div className="mx-auto flex w-full max-w-[1180px] flex-col gap-5 py-2">
@@ -416,7 +422,12 @@ export const HarnessPage: React.FC = () => {
<Search className="size-3.5 shrink-0 text-muted" />
<input
value={search}
- onChange={(e) => setSearch(e.target.value)}
+ onChange={(e) => {
+ setSearch(e.target.value);
+ setTasksPage(1);
+ setWatchesPage(1);
+ setSelection(null);
+ }}
placeholder={t('harness.searchPlaceholder')}
className="flex-1 bg-transparent text-[12px] text-foreground outline-none placeholder:text-muted"
/>
@@ -426,7 +437,12 @@ export const HarnessPage: React.FC = () => {
<button
key={opt}
type="button"
- onClick={() => setStatusFilter(opt)}
+ onClick={() => {
+ setStatusFilter(opt);
+ setTasksPage(1);
+ setWatchesPage(1);
+ setSelection(null);
+ }}
className={clsx(
'rounded px-2.5 py-1 text-[11px] font-medium transition',
statusFilter === opt
@@ -465,24 +481,36 @@ export const HarnessPage: React.FC = () => {
<div className={clsx('flex min-w-0 flex-col gap-2', hasSelection && 'max-lg:hidden')}>
{tab === 'tasks' && (
<TasksList
- tasks={filteredTasks}
+ tasks={tasks}
loading={loading}
selectedId={selection?.kind === 'task' ? selection.id : null}
onSelect={(id) => setSelection({ kind: 'task', id })}
onToggleEnabled={toggleTaskEnabled}
onDelete={deleteTask}
pending={pendingMutation}
+ page={tasksPage}
+ hasMore={tasksHasMore}
+ onPageChange={(page) => {
+ setTasksPage(page);
+ setSelection(null);
+ }}
/>
)}
{tab === 'watches' && (
<WatchesList
- watches={filteredWatches}
+ watches={watches}
loading={loading}
selectedId={selection?.kind === 'watch' ? selection.id : null}
onSelect={(id) => setSelection({ kind: 'watch', id })}
onToggleEnabled={toggleWatchEnabled}
onDelete={deleteWatch}
pending={pendingMutation}
+ page={watchesPage}
+ hasMore={watchesHasMore}
+ onPageChange={(page) => {
+ setWatchesPage(page);
+ setSelection(null);
+ }}
/>
)}
{tab === 'webhooks' && <WebhooksEmpty />}
@@ -494,7 +522,10 @@ export const HarnessPage: React.FC = () => {
onSelect={(id) => setSelection({ kind: 'run', id })}
page={runsPage}
hasMore={runsHasMore}
- onPageChange={setRunsPage}
+ onPageChange={(page) => {
+ setRunsPage(page);
+ setSelection(null);
+ }}
/>
)}
</div>
@@ -552,6 +583,42 @@ const HarnessTabIcon: React.FC<TabIconProps> = ({ tab, active }) => {
return <History className={cls} />;
};
+interface HarnessPagerProps {
+ page: number;
+ hasMore: boolean;
+ onPageChange: (page: number) => void;
+}
+
+const HarnessPager: React.FC<HarnessPagerProps> = ({ page, hasMore, onPageChange }) => {
+ const { t } = useTranslation();
+ if (page <= 1 && !hasMore) return null;
+ return (
+ <div className="mt-2 flex items-center justify-end gap-2 px-1">
+ <Button
+ type="button"
+ variant="outline"
+ size="xs"
+ disabled={page <= 1}
+ onClick={() => onPageChange(page - 1)}
+ className="h-7 px-2 font-mono text-[10px]"
+ >
+ {t('common.previous')}
+ </Button>
+ <span className="font-mono text-[10px] text-muted">{t('harness.pageLabel', { page })}</span>
+ <Button
+ type="button"
+ variant="outline"
+ size="xs"
+ disabled={!hasMore}
+ onClick={() => onPageChange(page + 1)}
+ className="h-7 px-2 font-mono text-[10px]"
+ >
+ {t('common.next')}
+ </Button>
+ </div>
+ );
+};
+
// ---------------------------------------------------------------------------
// Tasks tab
// ---------------------------------------------------------------------------
@@ -564,6 +631,9 @@ interface TasksListProps {
onToggleEnabled: (task: HarnessTask) => void;
onDelete: (task: HarnessTask) => void;
pending: Record<string, boolean>;
+ page: number;
+ hasMore: boolean;
+ onPageChange: (page: number) => void;
}
const TasksList: React.FC<TasksListProps> = ({
@@ -574,6 +644,9 @@ const TasksList: React.FC<TasksListProps> = ({
onToggleEnabled,
onDelete,
pending,
+ page,
+ hasMore,
+ onPageChange,
}) => {
const { t } = useTranslation();
if (tasks.length === 0 && !loading) return <EmptyState i18nKey="harness.emptyTasks" />;
@@ -631,6 +704,7 @@ const TasksList: React.FC<TasksListProps> = ({
</div>
);
})}
+ <HarnessPager page={page} hasMore={hasMore} onPageChange={onPageChange} />
</>
);
};
@@ -778,6 +852,9 @@ interface WatchesListProps {
onToggleEnabled: (watch: HarnessWatch) => void;
onDelete: (watch: HarnessWatch) => void;
pending: Record<string, boolean>;
+ page: number;
+ hasMore: boolean;
+ onPageChange: (page: number) => void;
}
const WatchesList: React.FC<WatchesListProps> = ({
@@ -788,6 +865,9 @@ const WatchesList: React.FC<WatchesListProps> = ({
onToggleEnabled,
onDelete,
pending,
+ page,
+ hasMore,
+ onPageChange,
}) => {
const { t } = useTranslation();
if (watches.length === 0 && !loading) return <EmptyState i18nKey="harness.emptyWatches" />;
@@ -850,6 +930,7 @@ const WatchesList: React.FC<WatchesListProps> = ({
);
})}
{watches.length === 0 && loading && <div className="px-4 py-6 text-[12px] text-muted">{t('common.loading')}</div>}
+ <HarnessPager page={page} hasMore={hasMore} onPageChange={onPageChange} />
</>
);
};
@@ -993,27 +1074,7 @@ const RunsList: React.FC<RunsListProps> = ({ runs, loading, selectedId, onSelect
</button>
);
})}
- {(page > 1 || hasMore) && (
- <div className="mt-2 flex items-center justify-end gap-2 px-1">
- <button
- type="button"
- disabled={page <= 1}
- onClick={() => onPageChange(page - 1)}
- className="rounded border border-border-strong px-2 py-1 font-mono text-[10px] text-muted hover:text-foreground disabled:opacity-40"
- >
- {t('common.previous')}
- </button>
- <span className="font-mono text-[10px] text-muted">{t('harness.pageLabel', { page })}</span>
- <button
- type="button"
- disabled={!hasMore}
- onClick={() => onPageChange(page + 1)}
- className="rounded border border-border-strong px-2 py-1 font-mono text-[10px] text-muted hover:text-foreground disabled:opacity-40"
- >
- {t('common.next')}
- </button>
- </div>
- )}
+ <HarnessPager page={page} hasMore={hasMore} onPageChange={onPageChange} />
</>
);
};
@@ -1251,4 +1312,3 @@ const EmptyState: React.FC<{ i18nKey: string }> = ({ i18nKey }) => {
</div>
);
};
-
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 084790f93..47f4785bf 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -181,13 +181,14 @@ export type ApiContextType = {
uploadSkillZip: (file: File, params?: { projectId?: string }) => Promise<SkillsUploadResult>;
checkSkills: (params?: { scope?: SkillScope; projectId?: string }) => Promise<SkillsCheckResult>;
updateSkill: (name: string, params?: { scope?: SkillScope; projectId?: string }) => Promise<SkillsMutationResult>;
- listHarnessTasks: () => Promise<{ tasks: HarnessTask[] }>;
+ getHarnessCounts: () => Promise<HarnessCountsResult>;
+ listHarnessTasks: (params?: HarnessDefinitionsParams) => Promise<HarnessTasksResult>;
setHarnessTaskEnabled: (taskId: string, enabled: boolean) => Promise<{ ok: boolean; task?: HarnessTask }>;
deleteHarnessTask: (taskId: string) => Promise<{ ok: boolean; id?: string }>;
- listHarnessWatches: () => Promise<{ watches: HarnessWatch[] }>;
+ listHarnessWatches: (params?: HarnessDefinitionsParams) => Promise<HarnessWatchesResult>;
setHarnessWatchEnabled: (watchId: string, enabled: boolean) => Promise<{ ok: boolean; watch?: HarnessWatch }>;
deleteHarnessWatch: (watchId: string) => Promise<{ ok: boolean; id?: string }>;
- listHarnessRuns: (params?: HarnessRunsParams) => Promise<{ runs: HarnessRun[]; page: number; limit: number; has_more: boolean }>;
+ listHarnessRuns: (params?: HarnessRunsParams) => Promise<HarnessRunsResult>;
getHarnessRun: (runId: string) => Promise<{ ok: boolean; run: HarnessRun }>;
remoteAccessStatus: () => Promise<any>;
pairVibeCloudRemoteAccess: (payload: { backend_url: string; pairing_key: string; device_name?: string }) => Promise<any>;
@@ -578,6 +579,24 @@ export type HarnessWatch = HarnessSessionSummary & {
export type HarnessRunStatus = 'queued' | 'running' | 'succeeded' | 'failed' | 'canceled' | (string & {});
+export type HarnessDefinitionStatus = 'all' | 'enabled' | 'disabled';
+
+export type HarnessDefinitionCounts = {
+ all: number;
+ enabled: number;
+ disabled: number;
+};
+
+export type HarnessRunCounts = {
+ all: number;
+ queued: number;
+ running: number;
+ succeeded: number;
+ failed: number;
+ canceled: number;
+ [key: string]: number;
+};
+
export type HarnessRun = {
id: string;
request_type: string | null;
@@ -629,6 +648,39 @@ export type HarnessRunsParams = {
limit?: number;
};
+export type HarnessDefinitionsParams = {
+ status?: HarnessDefinitionStatus;
+ query?: string;
+ page?: number;
+ limit?: number;
+};
+
+export type HarnessPageResultBase<TCounts> = {
+ counts: TCounts;
+ total: number;
+ page: number;
+ limit: number;
+ has_more: boolean;
+};
+
+export type HarnessTasksResult = HarnessPageResultBase<HarnessDefinitionCounts> & {
+ tasks: HarnessTask[];
+};
+
+export type HarnessWatchesResult = HarnessPageResultBase<HarnessDefinitionCounts> & {
+ watches: HarnessWatch[];
+};
+
+export type HarnessRunsResult = HarnessPageResultBase<HarnessRunCounts> & {
+ runs: HarnessRun[];
+};
+
+export type HarnessCountsResult = {
+ tasks: HarnessDefinitionCounts;
+ watches: HarnessDefinitionCounts;
+ runs: HarnessRunCounts;
+};
+
export type SessionInfo =
| { remote: false }
| { remote: true; authenticated: false }
@@ -1448,11 +1500,28 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
},
updateSkill: (name, params) =>
postJson('/api/skills/update', { name, scope: params?.scope, project_id: params?.projectId }),
- listHarnessTasks: () => getJson('/api/harness/tasks'),
+ getHarnessCounts: () => getJson('/api/harness/counts'),
+ listHarnessTasks: (params) => {
+ const search = new URLSearchParams();
+ 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 getJson(qs ? `/api/harness/tasks?${qs}` : '/api/harness/tasks');
+ },
setHarnessTaskEnabled: (taskId, enabled) =>
patchJson(`/api/harness/tasks/${encodeURIComponent(taskId)}`, { enabled }),
deleteHarnessTask: (taskId) => deleteJson(`/api/harness/tasks/${encodeURIComponent(taskId)}`),
- listHarnessWatches: () => getJson('/api/harness/watches'),
+ listHarnessWatches: (params) => {
+ const search = new URLSearchParams();
+ 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 getJson(qs ? `/api/harness/watches?${qs}` : '/api/harness/watches');
+ },
setHarnessWatchEnabled: (watchId, enabled) =>
patchJson(`/api/harness/watches/${encodeURIComponent(watchId)}`, { enabled }),
deleteHarnessWatch: (watchId) => deleteJson(`/api/harness/watches/${encodeURIComponent(watchId)}`),
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index d3e07d542..244e2abb3 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -4129,10 +4129,88 @@ def _harness_store():
store.close()
+def _harness_page_request(default_limit: int = 30):
+ from storage.pagination import make_page_request
+
+ try:
+ limit = int(request.args.get("limit") or default_limit)
+ page = int(request.args.get("page") or 1)
+ return make_page_request(page=page, limit=limit)
+ except (TypeError, ValueError) as exc:
+ raise ValueError(str(exc)) from exc
+
+
+def _harness_status_filter() -> str:
+ status = request.args.get("status") or "all"
+ if status not in {"all", "enabled", "disabled"}:
+ raise ValueError("status must be one of: all, enabled, disabled")
+ return status
+
+
+def _harness_query_filter() -> str | None:
+ query = (request.args.get("query") or "").strip()
+ return query or None
+
+
+def _harness_has_list_params() -> bool:
+ return any(key in request.args for key in ("page", "limit", "status", "query"))
+
+
+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 {
+ items_key: page_result.items,
+ "counts": counts,
+ "total": total,
+ "page": page_result.page,
+ "limit": page_result.limit,
+ "has_more": page_result.has_more,
+ }
+
+
[email protected]("/api/harness/counts", methods=["GET"])
+def harness_counts():
+ with _harness_store() as store:
+ return jsonify(
+ {
+ "tasks": store.count_scheduled_tasks(),
+ "watches": store.count_watches(),
+ "runs": store.count_runs_by_status(),
+ }
+ )
+
+
@app.route("/api/harness/tasks", methods=["GET"])
def harness_tasks_list():
+ if not _harness_has_list_params():
+ with _harness_store() as store:
+ tasks = store.list_scheduled_tasks()
+ counts = store.count_scheduled_tasks()
+ return jsonify(
+ {
+ "tasks": tasks,
+ "counts": counts,
+ "total": counts["all"],
+ "page": 1,
+ "limit": len(tasks),
+ "has_more": False,
+ }
+ )
+ try:
+ page_request = _harness_page_request()
+ status = _harness_status_filter()
+ query = _harness_query_filter()
+ except ValueError as exc:
+ return jsonify({"ok": False, "code": "invalid_pagination", "message": str(exc)}), 400
with _harness_store() as store:
- return jsonify({"tasks": store.list_scheduled_tasks()})
+ page_result = store.list_scheduled_tasks_page(
+ status=status,
+ query=query,
+ page_request=page_request,
+ newest_first=True,
+ )
+ counts = store.count_scheduled_tasks(query=query)
+ return jsonify(_harness_page_payload(page_result, items_key="tasks", counts=counts))
@app.route("/api/harness/tasks/<task_id>", methods=["PATCH"])
@@ -4160,12 +4238,41 @@ def harness_task_delete(task_id: str):
@app.route("/api/harness/watches", methods=["GET"])
def harness_watches_list():
+ if not _harness_has_list_params():
+ with _harness_store() as store:
+ watches = store.list_watches()
+ counts = store.count_watches()
+ runtime = store.load_watch_runtime().get("watches") or {}
+ for watch in watches:
+ watch["runtime"] = runtime.get(watch["id"]) or {"running": False}
+ return jsonify(
+ {
+ "watches": watches,
+ "counts": counts,
+ "total": counts["all"],
+ "page": 1,
+ "limit": len(watches),
+ "has_more": False,
+ }
+ )
+ try:
+ page_request = _harness_page_request()
+ status = _harness_status_filter()
+ query = _harness_query_filter()
+ except ValueError as exc:
+ return jsonify({"ok": False, "code": "invalid_pagination", "message": str(exc)}), 400
with _harness_store() as store:
- watches = store.list_watches()
+ page_result = store.list_watches_page(
+ status=status,
+ query=query,
+ page_request=page_request,
+ newest_first=True,
+ )
+ counts = store.count_watches(query=query)
runtime = store.load_watch_runtime().get("watches") or {}
- for watch in watches:
+ for watch in page_result.items:
watch["runtime"] = runtime.get(watch["id"]) or {"running": False}
- return jsonify({"watches": watches})
+ return jsonify(_harness_page_payload(page_result, items_key="watches", counts=counts))
@app.route("/api/harness/watches/<watch_id>", methods=["PATCH"])
@@ -4196,23 +4303,16 @@ def harness_watch_delete(watch_id: str):
@app.route("/api/harness/runs", methods=["GET"])
def harness_runs_list():
- from storage.pagination import make_page_request
-
- try:
- limit = int(request.args.get("limit") or 30)
- except (TypeError, ValueError):
- limit = 30
try:
- page = int(request.args.get("page") or 1)
- except (TypeError, ValueError):
- page = 1
+ page_request = _harness_page_request()
+ except ValueError as exc:
+ return jsonify({"ok": False, "code": "invalid_pagination", "message": str(exc)}), 400
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
- query = request.args.get("query") or None
+ query = _harness_query_filter()
- page_request = make_page_request(page=page, limit=limit)
with _harness_store() as store:
page_result = store.list_runs_page(
status=status,
@@ -4223,9 +4323,24 @@ def harness_runs_list():
page_request=page_request,
newest_first=True,
)
+ total = store.count_runs(
+ status=status,
+ run_type=run_type,
+ agent_name=agent_name,
+ definition_id=definition_id,
+ query=query,
+ )
+ counts = store.count_runs_by_status(
+ run_type=run_type,
+ agent_name=agent_name,
+ definition_id=definition_id,
+ query=query,
+ )
return jsonify(
{
"runs": page_result.items,
+ "counts": counts,
+ "total": total,
"page": page_result.page,
"limit": page_result.limit,
"has_more": page_result.has_more,