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.

feat(workbench): unified background-work banner — harness items join session activities (#924)

Call White094d2f7588ed
diff --git a/core/session_turns.py b/core/session_turns.py
index 72b5c9f0a..331e6ed8f 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -32,6 +32,7 @@ from core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED, dispatch_turn
from storage import messages_service
from storage.db import get_cached_sqlite_engine
from storage.models import messages
+from storage.workbench_sessions_service import derive_session_harness_activities
from core.message_output import terminal_turn_output
from vibe.i18n import t as i18n_t
@@ -40,6 +41,21 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
+
+def _as_backend_activity_item(item: dict[str, Any]) -> dict[str, Any]:
+ """Annotate a registry background activity with the unified banner fields.
+
+ The registry (``core/session_activities.py``) is left untouched; we only tag
+ its serialized output so a backend activity and a live-derived harness item
+ share one shape (``item_kind`` / ``label`` / ``since``) for the banner.
+ """
+ enriched = dict(item)
+ enriched["item_kind"] = "backend_activity"
+ enriched["since"] = str(item.get("started_at") or "")
+ enriched["label"] = str(item.get("description") or "")
+ return enriched
+
+
# A queued row's ``metadata[SCHEDULED_PROVENANCE_KEY]`` carries the scheduled run's
# context.platform_specific provenance that the gate must restore when the row is
# finally flushed — so a scheduled run enqueued behind an active turn keeps its
@@ -1105,9 +1121,14 @@ class SessionTurnManager:
if callable(started):
native_turn_started = started(entry.context) is True
pending_input_count = 0
+ harness_activities: list[dict[str, Any]] = []
try:
with self._sqlite_engine().begin() as conn:
pending_input_count = len(messages_service.list_queued(conn, session_id))
+ try:
+ harness_activities = derive_session_harness_activities(conn, session_id)
+ except Exception:
+ logger.debug("turn_state: failed to derive harness activities", exc_info=True)
except Exception:
logger.debug("turn_state: failed to read queued input count", exc_info=True)
activity_state: dict[str, Any] = {
@@ -1123,6 +1144,16 @@ class SessionTurnManager:
activity_state = project(session_id)
except Exception:
logger.debug("turn_state: failed to project Activity state", exc_info=True)
+ # Unified background-work banner: process-local backend activities from the
+ # registry, then live-derived harness items from the durable store. The
+ # registry is never mutated — harness items are appended only to this
+ # projection so the banner survives restarts correct-by-construction.
+ background_activities = [
+ _as_backend_activity_item(item)
+ for item in activity_state.get("background_activities", [])
+ if isinstance(item, dict)
+ ]
+ background_activities.extend(harness_activities)
result = {
"ok": True,
"session_id": session_id,
@@ -1130,7 +1161,7 @@ class SessionTurnManager:
"native_turn_started": native_turn_started,
"foreground": "running" if active else "idle",
"pending_input_count": pending_input_count,
- "background_activities": activity_state.get("background_activities", []),
+ "background_activities": background_activities,
"pending_activity_output_count": activity_state.get(
"pending_activity_output_count",
0,
diff --git a/core/workbench_prefs.py b/core/workbench_prefs.py
new file mode 100644
index 000000000..dc4b49d95
--- /dev/null
+++ b/core/workbench_prefs.py
@@ -0,0 +1,31 @@
+"""Global workbench preferences persisted in ``state_meta`` (KV).
+
+Small global toggles the Web UI flips and every session reads — distinct from
+the JSON config file (``config/v2_config.py``) and from per-session settings.
+Mirrors the Dock store pattern (``core/dock_store.py``) over the generic
+``state_meta`` helpers in ``core/chat_discovery.py``.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from core.chat_discovery import get_state_meta, set_state_meta
+
+# Global toggle for the workbench chat's unified background-work banner.
+# Default ON; when off the banner never renders in ANY session. The underlying
+# runtime-state data/API is unaffected — this only gates presentation.
+BACKGROUND_WORK_BANNER_KEY = "workbench.background_work_banner_enabled"
+
+
+def get_background_work_banner_enabled(*, db_path: Path | None = None) -> bool:
+ """Whether the background-work banner may render. Absent/malformed → ON."""
+ raw = get_state_meta(BACKGROUND_WORK_BANNER_KEY, db_path=db_path)
+ return raw if isinstance(raw, bool) else True
+
+
+def set_background_work_banner_enabled(enabled: bool, *, db_path: Path | None = None) -> bool:
+ """Persist the banner toggle. Returns the stored boolean."""
+ value = bool(enabled)
+ set_state_meta(BACKGROUND_WORK_BANNER_KEY, value, db_path=db_path)
+ return value
diff --git a/docs/plans/unified-background-work-banner.md b/docs/plans/unified-background-work-banner.md
new file mode 100644
index 000000000..d6550e7f4
--- /dev/null
+++ b/docs/plans/unified-background-work-banner.md
@@ -0,0 +1,72 @@
+# Unified Background-Work Banner (P1) — spec
+
+Owner decision (2026-07-16 20:51): the workbench chat's "后台工作 · N" banner must present ONE
+unified concept of background work for a session, regardless of where the work runs. Harness
+items (watches, scheduled tasks, delegated agent runs) join the same banner that today only
+shows backend-reported Activities (e.g. Claude background tasks).
+
+**P2 explicitly shelved (owner, same message):** an Avibe-owned cross-backend background-execution
+tool (MCP-delivered) is NOT being built now — revisit when Avibe develops its own Agent. Do not
+implement any execution-layer changes under this spec; this is presentation/projection only.
+
+## Model (the one rule)
+
+The banner's source of truth is a **union assembled at runtime-state build time**:
+
+1. **Backend activities** — the existing process-local `SessionActivityRegistry`
+ (`core/session_activities.py`, #864). Unchanged.
+2. **Harness items** — derived LIVE from the durable store at assembly time, never duplicated
+ into the registry (a watch survives restarts; the registry does not — deriving from the DB
+ keeps the banner correct-by-construction after a restart):
+ - enabled watches whose callback session is this session;
+ - pending/scheduled tasks targeting this session;
+ - running/queued delegated agent runs whose callback returns to this session (work this
+ session dispatched and is waiting on).
+
+Each unified item carries: `kind` (`backend_activity` | `watch` | `task` | `agent_run`),
+`label` (watch name / task summary / target agent + short message head / activity description),
+`since` timestamp, and a stable id. The banner count = union size. No controls (pause/cancel)
+in this phase — the expanded list links to the Harness page (watches/tasks) or run detail.
+
+## UX
+
+- Banner line unchanged: `后台工作 · N` (existing `chat.activities.running` string).
+- Expanded list: one row per item — kind icon + label + relative time. Rows for harness items
+ navigate to their Harness surface on click; backend-activity rows keep current behavior.
+- Empty union → banner hidden (current behavior).
+- All new strings through i18n (en + zh).
+
+## Code anchors
+
+- Runtime-state assembly: wherever `background_activities` is built for the session runtime
+ state payload (search `background_activities` producers in core/vibe; ChatPage consumes
+ `runtimeState.background_activities` at ui/src/components/workbench/ChatPage.tsx ~1632).
+- Registry: `core/session_activities.py` (`SessionActivity`, `SessionActivityRegistry`).
+- Harness state: `run_definitions` (watches), scheduled tasks store, `agent_runs`
+ (status running/queued, callback lineage) — read-only queries.
+- Banner UI: ChatPage banner block (~1626-1670) + `chat.activities.*` i18n keys.
+
+## Owner design review (2026-07-16 21:15) — five requirements folded in
+
+1. **Popover opens UPWARD.** The banner sits at the bottom of the chat (above the composer);
+ the expanded list anchors to the pill's TOP edge and grows upward. Never downward.
+2. **Harness-page toggle.** A switch on the Harness page ("后台工作横幅", default ON) hides the
+ banner entirely for users who don't want it. Global (not per-session), persisted server-side
+ (same `state_meta` family as other workbench prefs — lane picks the exact key, declares it).
+ When off, the banner never renders; the underlying data/API is unaffected.
+3. **Length discipline.** The pill has a max width (~420px); the first-item summary truncates
+ with ellipsis; the count badge is always visible. The expanded list has a max height
+ (~340px ≈ 5 rows); more items scroll inside the popover.
+4. **Row navigation = Harness with an automatic SESSION filter.** Clicking a Watch/task row
+ opens the Harness page's matching tab with a session filter applied (route param, e.g.
+ `?session=<id>`), shown as a removable chip ("仅看:本会话") — WITHOUT the filter the page
+ would show everything, which is wrong coming from a session context. A delegated-run row
+ opens the runs view similarly filtered/anchored to that run. **This adds Harness-page scope:
+ the route param + filter chip + filtered queries are part of this PR** (declare the files).
+5. Ordering inside the popover: active/running first, then by start time descending.
+
+## Non-goals (this phase)
+
+- No execution-layer unification (P2, shelved).
+- No controls on banner rows (pause/cancel/remove stay on their own pages).
+- No mobile-specific redesign — the banner behaves as today, just with more sources.
diff --git a/storage/background.py b/storage/background.py
index d1c1786f5..bd2fd9b13 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -538,10 +538,11 @@ class SQLiteBackgroundTaskStore:
*,
status: Optional[str] = None,
query: Optional[str] = None,
+ session_id: Optional[str] = None,
page_request: PageRequest | None,
newest_first: bool = True,
) -> PageResult[dict[str, Any]]:
- stmt = self._definitions_query("scheduled", status=status, query=query)
+ stmt = self._definitions_query("scheduled", status=status, query=query, session_id=session_id)
activity = func.coalesce(
run_definitions.c.last_run_at,
run_definitions.c.updated_at,
@@ -558,8 +559,10 @@ class SQLiteBackgroundTaskStore:
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 count_scheduled_tasks(
+ self, *, query: Optional[str] = None, session_id: Optional[str] = None
+ ) -> dict[str, int]:
+ return self._definition_counts("scheduled", query=query, session_id=session_id)
def get_scheduled_task(self, definition_id: str) -> Optional[dict[str, Any]]:
with self.engine.connect() as conn:
@@ -629,10 +632,11 @@ class SQLiteBackgroundTaskStore:
*,
status: Optional[str] = None,
query: Optional[str] = None,
+ session_id: Optional[str] = None,
page_request: PageRequest | None,
newest_first: bool = True,
) -> PageResult[dict[str, Any]]:
- stmt = self._definitions_query("watch", status=status, query=query)
+ stmt = self._definitions_query("watch", status=status, query=query, session_id=session_id)
activity = func.coalesce(
run_definitions.c.last_event_at,
run_definitions.c.last_started_at,
@@ -650,8 +654,10 @@ class SQLiteBackgroundTaskStore:
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 count_watches(
+ self, *, query: Optional[str] = None, session_id: Optional[str] = None
+ ) -> dict[str, int]:
+ return self._definition_counts("watch", query=query, session_id=session_id)
def get_watch(self, watch_id: str) -> Optional[dict[str, Any]]:
with self.engine.connect() as conn:
@@ -855,6 +861,7 @@ class SQLiteBackgroundTaskStore:
*,
status: Optional[str] = None,
query: Optional[str] = None,
+ session_id: Optional[str] = None,
columns: Any = None,
):
if columns is not None:
@@ -865,6 +872,10 @@ class SQLiteBackgroundTaskStore:
stmt.where(run_definitions.c.definition_type == definition_type)
.where(run_definitions.c.deleted_at.is_(None))
)
+ # Precise bound-session filter (ix_run_definitions_session) — powers the
+ # Harness "只看本会话" chip that background-work banner rows navigate into.
+ if session_id:
+ stmt = stmt.where(run_definitions.c.session_id == session_id)
if status and status != "all":
if status not in {"enabled", "disabled"}:
raise ValueError("status must be one of: all, enabled, disabled")
@@ -900,10 +911,17 @@ class SQLiteBackgroundTaskStore:
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]:
+ def _definition_counts(
+ self,
+ definition_type: str,
+ *,
+ query: Optional[str] = None,
+ session_id: Optional[str] = None,
+ ) -> dict[str, int]:
stmt = self._definitions_query(
definition_type,
query=query,
+ session_id=session_id,
columns=(run_definitions.c.enabled, func.count()),
).group_by(run_definitions.c.enabled)
counts = {key: 0 for key in DEFINITION_STATUS_COUNTS}
diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.py
index f92f0f127..9bd72fbc5 100644
--- a/storage/workbench_sessions_service.py
+++ b/storage/workbench_sessions_service.py
@@ -607,6 +607,193 @@ def count_bound_resources(conn: Connection, session_id: str) -> dict[str, int]:
}
+# Longest harness label carried in the banner payload; longer strings are
+# elided so one runaway prompt can't bloat the runtime-state response.
+_HARNESS_LABEL_MAX = 80
+
+
+def _banner_label(text: Any, limit: int = _HARNESS_LABEL_MAX) -> str:
+ """Collapse whitespace and clip a harness label to a banner-friendly head."""
+ cleaned = " ".join(str(text or "").split())
+ if len(cleaned) <= limit:
+ return cleaned
+ return cleaned[: limit - 1].rstrip() + "…"
+
+
+def _harness_banner_item(
+ *,
+ item_id: str,
+ item_kind: str,
+ session_id: str,
+ status: str,
+ label: str,
+ since: str,
+ updated_at: str,
+ backend: str = "",
+) -> dict[str, Any]:
+ """Shape one harness row like a serialized background activity.
+
+ The banner unions these with process-local backend activities
+ (``core/session_activities.SessionActivity.to_dict``), so a harness item
+ carries every key an existing ``background_activities`` consumer already
+ reads, plus the unified ``item_kind`` / ``label`` / ``since`` fields the
+ banner uses to render and route each row. Nothing here is written back into
+ the registry — the row is derived fresh on every runtime-state build.
+ """
+ return {
+ "id": item_id,
+ "backend": backend,
+ "runtime_key": "",
+ "session_id": session_id,
+ "kind": item_kind,
+ "status": status,
+ "description": label or None,
+ "foreground": False,
+ "detached_from_run": False,
+ "parent_activity_id": None,
+ "turn_id": None,
+ "run_id": None,
+ "metadata": {},
+ "started_at": since,
+ "updated_at": updated_at or since,
+ "completed_at": None,
+ # Unified background-work banner fields (spec: kind / label / since).
+ "item_kind": item_kind,
+ "label": label,
+ "since": since,
+ }
+
+
+def derive_session_harness_activities(conn: Connection, session_id: str) -> list[dict[str, Any]]:
+ """Live-derive the harness items the background-work banner unions in.
+
+ Read-only projection from the durable store — deliberately NOT mirrored into
+ the process-local ``SessionActivityRegistry`` so the banner stays correct by
+ construction across restarts (a watch survives a restart; the registry does
+ not). Three sources, all scoped to ``session_id``:
+
+ - enabled, live (not soft-deleted) watches bound to this session;
+ - enabled, live scheduled tasks bound to this session;
+ - queued/running delegated agent runs whose callback returns here (work this
+ session dispatched and is waiting on).
+
+ Each row is shaped like a serialized background activity plus the unified
+ ``item_kind`` / ``label`` / ``since`` fields (see ``_harness_banner_item``).
+ """
+ session_id = str(session_id or "").strip()
+ if not session_id:
+ return []
+ items: list[dict[str, Any]] = []
+
+ # Watches + scheduled tasks live in ``run_definitions``, discriminated by
+ # ``definition_type`` (see storage/background.py). Both must be enabled and
+ # not soft-deleted to count as ongoing background work for the session.
+ definition_rows = (
+ conn.execute(
+ select(
+ run_definitions.c.id,
+ run_definitions.c.definition_type,
+ run_definitions.c.name,
+ run_definitions.c.prompt,
+ run_definitions.c.message,
+ run_definitions.c.created_at,
+ run_definitions.c.updated_at,
+ )
+ .where(run_definitions.c.session_id == session_id)
+ .where(run_definitions.c.deleted_at.is_(None))
+ .where(run_definitions.c.enabled == 1)
+ .order_by(run_definitions.c.created_at, run_definitions.c.id)
+ )
+ .mappings()
+ .all()
+ )
+ for row in definition_rows:
+ definition_type = str(row["definition_type"] or "")
+ if definition_type == "watch":
+ item_kind, status = "watch", "enabled"
+ label = _banner_label(row["name"])
+ elif definition_type == "scheduled":
+ # A fired one-shot is disabled/removed by the scheduler, so an
+ # enabled scheduled definition is the pending-work proxy here.
+ item_kind, status = "task", "scheduled"
+ label = _banner_label(row["name"] or row["prompt"] or row["message"])
+ else:
+ continue
+ since = str(row["created_at"] or "")
+ items.append(
+ _harness_banner_item(
+ item_id=f"{item_kind}:{row['id']}",
+ item_kind=item_kind,
+ session_id=session_id,
+ status=status,
+ label=label,
+ since=since,
+ updated_at=str(row["updated_at"] or since),
+ )
+ )
+
+ # Delegated agent runs this session dispatched and is waiting on: the run
+ # executes elsewhere but its result returns here (``callback_session_id``)
+ # and it is not yet terminal. ``run_type='agent_run'`` excludes task/watch
+ # execution runs (already represented by their definitions above); the
+ # self-run guard keeps a session's OWN foreground turn — reported via
+ # ``foreground``, not the banner — out of the union. ``callback_status =
+ # 'pending'`` further limits this to async/detached runs that will actually
+ # post back: a synchronous ``--sync`` run carries ``callback_session_id`` but
+ # a null ``callback_status`` (the caller is waiting inline, no callback owed).
+ # Active-run cardinality is small, so the (run_type, status) index carries
+ # this without a dedicated ``callback_session_id`` index.
+ run_rows = (
+ conn.execute(
+ select(
+ agent_runs.c.id,
+ agent_runs.c.agent_name,
+ agent_runs.c.agent_backend,
+ agent_runs.c.message,
+ agent_runs.c.prompt,
+ agent_runs.c.status,
+ agent_runs.c.created_at,
+ agent_runs.c.started_at,
+ agent_runs.c.updated_at,
+ )
+ .where(agent_runs.c.callback_session_id == session_id)
+ .where(agent_runs.c.run_type == "agent_run")
+ .where(agent_runs.c.callback_status == "pending")
+ .where(agent_runs.c.status.in_(_ACTIVE_RUN_STATUSES))
+ .where(
+ or_(
+ agent_runs.c.session_id.is_(None),
+ agent_runs.c.session_id != agent_runs.c.callback_session_id,
+ )
+ )
+ .order_by(agent_runs.c.created_at, agent_runs.c.id)
+ )
+ .mappings()
+ .all()
+ )
+ for row in run_rows:
+ head = _banner_label(row["message"] or row["prompt"])
+ agent_name = str(row["agent_name"] or "").strip()
+ if agent_name and head:
+ label = _banner_label(f"{agent_name}: {head}")
+ else:
+ label = agent_name or head
+ since = str(row["started_at"] or row["created_at"] or "")
+ items.append(
+ _harness_banner_item(
+ item_id=f"agent_run:{row['id']}",
+ item_kind="agent_run",
+ session_id=session_id,
+ status=str(row["status"] or "running"),
+ label=label,
+ since=since,
+ updated_at=str(row["updated_at"] or since),
+ backend=str(row["agent_backend"] or ""),
+ )
+ )
+ return items
+
+
def archive_session(conn: Connection, session_id: str) -> dict[str, Any]:
"""Permanently archive a session and reclaim everything bound to it.
diff --git a/tests/test_background_work_banner.py b/tests/test_background_work_banner.py
new file mode 100644
index 000000000..3effdf123
--- /dev/null
+++ b/tests/test_background_work_banner.py
@@ -0,0 +1,330 @@
+"""Unified background-work banner — union derivation.
+
+Covers the presentation-layer union assembled at runtime-state build time
+(docs/plans/unified-background-work-banner.md): backend activities from the
+process-local ``SessionActivityRegistry`` joined with harness items
+(watches / scheduled tasks / delegated agent runs) derived LIVE from the durable
+store. The harness items must derive from the DB, never from the registry, so the
+banner stays correct across a restart.
+"""
+
+from __future__ import annotations
+
+from contextlib import nullcontext
+from pathlib import Path
+from types import SimpleNamespace
+
+from sqlalchemy import insert
+
+from core.session_activities import SessionActivityRegistry
+from core.session_turns import SessionTurnManager
+from storage.background import SQLiteBackgroundTaskStore
+from storage.db import create_sqlite_engine
+from storage.importer import ensure_sqlite_state
+from storage.models import agent_runs, run_definitions
+from storage.workbench_sessions_service import derive_session_harness_activities
+
+_NOW = "2026-07-16T00:00:00Z"
+
+
+def _make_engine(tmp_path: Path):
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ ensure_sqlite_state(db_path=db_path, primary_platform="avibe")
+ return create_sqlite_engine(db_path), db_path
+
+
+def _insert_definition(engine, **overrides) -> str:
+ values = {
+ "id": overrides.pop("id"),
+ "definition_type": overrides.pop("definition_type"),
+ "name": None,
+ "session_id": None,
+ "prompt": None,
+ "message": None,
+ "enabled": 1,
+ "deleted_at": None,
+ "created_at": _NOW,
+ "updated_at": _NOW,
+ "metadata_json": "{}",
+ }
+ values.update(overrides)
+ with engine.begin() as conn:
+ conn.execute(insert(run_definitions).values(**values))
+ return values["id"]
+
+
+def _insert_run(engine, **overrides) -> str:
+ values = {
+ "id": overrides.pop("id"),
+ "run_type": "agent_run",
+ "status": "running",
+ "agent_name": None,
+ "agent_backend": None,
+ "message": None,
+ "prompt": None,
+ "session_id": None,
+ "callback_session_id": None,
+ # Async delegated runs carry a pending callback while running; the banner
+ # only surfaces these (sync --sync runs leave callback_status null).
+ "callback_status": "pending",
+ "created_at": _NOW,
+ "started_at": _NOW,
+ "updated_at": _NOW,
+ "metadata_json": "{}",
+ }
+ values.update(overrides)
+ with engine.begin() as conn:
+ conn.execute(insert(agent_runs).values(**values))
+ return values["id"]
+
+
+def test_each_harness_source_contributes_one_row(tmp_path: Path):
+ engine, _ = _make_engine(tmp_path)
+ _insert_definition(
+ engine,
+ id="watch-1",
+ definition_type="watch",
+ name="deploy watch",
+ session_id="ses-1",
+ )
+ _insert_definition(
+ engine,
+ id="task-1",
+ definition_type="scheduled",
+ name="nightly report",
+ session_id="ses-1",
+ )
+ _insert_run(
+ engine,
+ id="run-1",
+ agent_name="worker",
+ message="audit the contract",
+ session_id="ses-delegate",
+ callback_session_id="ses-1",
+ )
+
+ with engine.connect() as conn:
+ items = derive_session_harness_activities(conn, "ses-1")
+
+ by_kind = {item["item_kind"]: item for item in items}
+ assert set(by_kind) == {"watch", "task", "agent_run"}
+ assert by_kind["watch"]["id"] == "watch:watch-1"
+ assert by_kind["watch"]["label"] == "deploy watch"
+ assert by_kind["task"]["id"] == "task:task-1"
+ assert by_kind["task"]["label"] == "nightly report"
+ assert by_kind["agent_run"]["id"] == "agent_run:run-1"
+ assert by_kind["agent_run"]["label"] == "worker: audit the contract"
+ # ``since`` and a stable id are present on every unified item.
+ assert all(item["since"] == _NOW for item in items)
+ assert all(item["id"] for item in items)
+
+
+def test_task_label_falls_back_to_prompt_when_unnamed(tmp_path: Path):
+ engine, _ = _make_engine(tmp_path)
+ _insert_definition(
+ engine,
+ id="task-2",
+ definition_type="scheduled",
+ name=None,
+ prompt="summarize the daily standup notes",
+ session_id="ses-1",
+ )
+ with engine.connect() as conn:
+ items = derive_session_harness_activities(conn, "ses-1")
+ assert len(items) == 1
+ assert items[0]["label"] == "summarize the daily standup notes"
+
+
+def test_excludes_disabled_deleted_and_foreign_and_terminal(tmp_path: Path):
+ engine, _ = _make_engine(tmp_path)
+ # Disabled watch: paused, not ongoing background work.
+ _insert_definition(
+ engine, id="w-off", definition_type="watch", session_id="ses-1", enabled=0
+ )
+ # Soft-deleted task.
+ _insert_definition(
+ engine,
+ id="t-del",
+ definition_type="scheduled",
+ session_id="ses-1",
+ deleted_at=_NOW,
+ )
+ # Watch bound to a different session.
+ _insert_definition(
+ engine, id="w-other", definition_type="watch", session_id="ses-2"
+ )
+ # Delegated run whose callback returns to a different session.
+ _insert_run(
+ engine, id="r-other", callback_session_id="ses-2", session_id="ses-x"
+ )
+ # Terminal delegated run (already finished) — not pending work.
+ _insert_run(
+ engine,
+ id="r-done",
+ status="succeeded",
+ callback_session_id="ses-1",
+ session_id="ses-x",
+ )
+ with engine.connect() as conn:
+ items = derive_session_harness_activities(conn, "ses-1")
+ assert items == []
+
+
+def test_self_run_is_not_counted_as_dispatched_work(tmp_path: Path):
+ # A run whose callback target equals its execution session is the session's
+ # own turn (reported via ``foreground``), not delegated background work.
+ engine, _ = _make_engine(tmp_path)
+ _insert_run(
+ engine, id="r-self", callback_session_id="ses-1", session_id="ses-1"
+ )
+ with engine.connect() as conn:
+ items = derive_session_harness_activities(conn, "ses-1")
+ assert items == []
+
+
+def test_sync_run_without_pending_callback_is_excluded(tmp_path: Path):
+ # A synchronous ``--sync`` delegated run carries callback_session_id but a
+ # null callback_status (caller waits inline; no callback owed), so it is NOT
+ # background work this session is waiting on.
+ engine, _ = _make_engine(tmp_path)
+ _insert_run(
+ engine,
+ id="r-sync",
+ callback_session_id="ses-1",
+ session_id="ses-delegate",
+ callback_status=None,
+ )
+ with engine.connect() as conn:
+ items = derive_session_harness_activities(conn, "ses-1")
+ assert items == []
+
+
+def test_items_derive_from_db_so_banner_survives_restart(tmp_path: Path):
+ # The registry is process-local and empty after a restart; harness items must
+ # come from the durable store. Simulate a restart by disposing the engine and
+ # opening a fresh one on the same DB file — the item must still derive.
+ engine, db_path = _make_engine(tmp_path)
+ _insert_definition(
+ engine, id="watch-r", definition_type="watch", name="w", session_id="ses-1"
+ )
+ engine.dispose()
+
+ reopened = create_sqlite_engine(db_path)
+ with reopened.connect() as conn:
+ items = derive_session_harness_activities(conn, "ses-1")
+ assert [item["id"] for item in items] == ["watch:watch-r"]
+ assert items[0]["item_kind"] == "watch"
+
+
+def test_turn_state_unions_backend_activities_and_harness_items(tmp_path: Path):
+ # End-to-end at the assembly point: registry backend activity + DB-derived
+ # harness items land in one ``background_activities`` list, tagged by kind.
+ engine, _ = _make_engine(tmp_path)
+ _insert_definition(
+ engine, id="watch-u", definition_type="watch", name="w", session_id="ses-1"
+ )
+ _insert_run(
+ engine,
+ id="run-u",
+ agent_name="worker",
+ message="go",
+ session_id="ses-delegate",
+ callback_session_id="ses-1",
+ )
+
+ registry = SessionActivityRegistry()
+ registry.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="ses-1",
+ activity_id="bg-1",
+ kind="background_task",
+ description="Running checks",
+ )
+ manager = SessionTurnManager(
+ controller=SimpleNamespace(agent_service=SimpleNamespace(activities=registry))
+ )
+ manager._engine = engine
+
+ state = manager.turn_state("ses-1")
+ activities = state["background_activities"]
+ kinds = [item["item_kind"] for item in activities]
+ assert kinds.count("backend_activity") == 1
+ assert kinds.count("watch") == 1
+ assert kinds.count("agent_run") == 1
+ backend_item = next(i for i in activities if i["item_kind"] == "backend_activity")
+ assert backend_item["id"] == "bg-1"
+ assert backend_item["label"] == "Running checks"
+ assert backend_item["since"] == backend_item["started_at"]
+
+
+def test_turn_state_survives_harness_derivation_failure(tmp_path: Path):
+ # A harness query failure must degrade to registry-only activities, never
+ # break the turn-state payload.
+ registry = SessionActivityRegistry()
+ registry.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="ses-1",
+ activity_id="bg-1",
+ kind="background_task",
+ )
+ manager = SessionTurnManager(
+ controller=SimpleNamespace(agent_service=SimpleNamespace(activities=registry))
+ )
+ # A bare object() as the connection makes derive_session_harness_activities
+ # raise inside turn_state's guarded block.
+ manager._engine = SimpleNamespace(begin=lambda: nullcontext(object()))
+
+ import core.session_turns as session_turns
+
+ original = session_turns.messages_service.list_queued
+ session_turns.messages_service.list_queued = lambda conn, sid: []
+ try:
+ state = manager.turn_state("ses-1")
+ finally:
+ session_turns.messages_service.list_queued = original
+
+ assert [item["id"] for item in state["background_activities"]] == ["bg-1"]
+ assert state["background_activities"][0]["item_kind"] == "backend_activity"
+
+
+def test_banner_enabled_pref_round_trip(tmp_path: Path):
+ # Global toggle (spec req 2): default ON, persisted in state_meta, hermetic
+ # via explicit db_path (never touches real state).
+ from core.workbench_prefs import (
+ get_background_work_banner_enabled,
+ set_background_work_banner_enabled,
+ )
+
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ ensure_sqlite_state(db_path=db_path, primary_platform="avibe")
+
+ assert get_background_work_banner_enabled(db_path=db_path) is True # default ON
+ assert set_background_work_banner_enabled(False, db_path=db_path) is False
+ assert get_background_work_banner_enabled(db_path=db_path) is False
+ assert set_background_work_banner_enabled(True, db_path=db_path) is True
+ assert get_background_work_banner_enabled(db_path=db_path) is True
+
+
+def test_definition_session_filter_scopes_watches_and_tasks(tmp_path: Path):
+ # Spec req 4: the Harness "只看本会话" chip filters definitions by bound
+ # session. Rows for session A must exclude session B's definitions.
+ engine, db_path = _make_engine(tmp_path)
+ _insert_definition(engine, id="w-a", definition_type="watch", name="wa", session_id="ses-A")
+ _insert_definition(engine, id="w-b", definition_type="watch", name="wb", session_id="ses-B")
+ _insert_definition(engine, id="t-a", definition_type="scheduled", name="ta", session_id="ses-A")
+ _insert_definition(engine, id="t-b", definition_type="scheduled", name="tb", session_id="ses-B")
+
+ store = SQLiteBackgroundTaskStore(db_path=db_path)
+ try:
+ watches_a = store.list_watches_page(session_id="ses-A", page_request=None)
+ assert [w["id"] for w in watches_a.items] == ["w-a"]
+ tasks_a = store.list_scheduled_tasks_page(session_id="ses-A", page_request=None)
+ assert [t["id"] for t in tasks_a.items] == ["t-a"]
+ assert store.count_watches(session_id="ses-A")["all"] == 1
+ assert store.count_scheduled_tasks(session_id="ses-B")["all"] == 1
+ # No filter → both sessions' definitions are returned.
+ assert len(store.list_watches_page(page_request=None).items) == 2
+ finally:
+ store.close()
diff --git a/tests/test_workbench_prefs_api.py b/tests/test_workbench_prefs_api.py
new file mode 100644
index 000000000..5b0c181ce
--- /dev/null
+++ b/tests/test_workbench_prefs_api.py
@@ -0,0 +1,88 @@
+"""Workbench prefs + Harness session-filter — route/api coverage.
+
+The background-work banner's global toggle (spec req 2) is a state_meta pref
+exposed at ``/api/workbench/prefs``; banner rows deep-link into a session-scoped
+Harness tab (spec req 4) via ``?session_id=`` on the harness bootstrap route.
+Mutations run at the ``vibe.api`` layer (like the Dock tests); the GET routes and
+the session filter are exercised through the Flask-compat test client.
+"""
+
+from tests.test_ui_remote_access_auth import _save_config
+from vibe import api
+from vibe.ui_server import app
+
+_BASE = "http://127.0.0.1:5123"
+_NOW = "2026-07-16T00:00:00Z"
+
+
+def test_banner_pref_api_round_trip(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ from storage.importer import ensure_sqlite_state
+
+ ensure_sqlite_state()
+
+ assert api.get_workbench_prefs()["background_work_banner_enabled"] is True # default ON
+ assert api.set_workbench_prefs(background_work_banner_enabled=False)[
+ "background_work_banner_enabled"
+ ] is False
+ assert api.get_workbench_prefs()["background_work_banner_enabled"] is False
+ # An omitted field leaves the stored value untouched.
+ assert api.set_workbench_prefs()["background_work_banner_enabled"] is False
+ assert api.set_workbench_prefs(background_work_banner_enabled=True)[
+ "background_work_banner_enabled"
+ ] is True
+
+
+def test_banner_pref_get_route_defaults_on(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ from storage.importer import ensure_sqlite_state
+
+ ensure_sqlite_state()
+
+ response = app.test_client().get("/api/workbench/prefs", base_url=_BASE)
+ assert response.status_code == 200
+ assert response.get_json()["background_work_banner_enabled"] is True
+
+
+def _seed_watch(engine, watch_id: str, session_id: str) -> None:
+ from storage.models import run_definitions
+
+ with engine.begin() as conn:
+ conn.execute(
+ run_definitions.insert().values(
+ id=watch_id,
+ definition_type="watch",
+ name=watch_id,
+ session_id=session_id,
+ enabled=1,
+ deleted_at=None,
+ created_at=_NOW,
+ updated_at=_NOW,
+ metadata_json="{}",
+ )
+ )
+
+
+def test_harness_bootstrap_scopes_watches_by_session(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ try:
+ _seed_watch(engine, "w-a", "ses-A")
+ _seed_watch(engine, "w-b", "ses-B")
+ finally:
+ engine.dispose()
+
+ client = app.test_client()
+ scoped = client.get("/api/harness/bootstrap?tab=watches&session_id=ses-A", base_url=_BASE)
+ assert scoped.status_code == 200
+ assert [w["id"] for w in scoped.get_json()["page"]["watches"]] == ["w-a"]
+
+ unscoped = client.get("/api/harness/bootstrap?tab=watches", base_url=_BASE)
+ assert {w["id"] for w in unscoped.get_json()["page"]["watches"]} == {"w-a", "w-b"}
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 4fb8d0fcf..09f759d77 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -1,21 +1,23 @@
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
-import { Activity, ArrowLeft, Bell, Bot, ChevronDown, Clock, GitFork, Info, Loader2, MessageSquare, Pencil, Presentation, Undo2, UploadCloud, X } from 'lucide-react';
+import { Activity, ArrowLeft, ArrowRight, Bell, Bot, ChevronDown, ChevronRight, Clock, Eye, GitFork, Info, Loader2, MessageSquare, Pencil, Presentation, Terminal, Undo2, UploadCloud, X } from 'lucide-react';
+import type { LucideIcon } from 'lucide-react';
import clsx from 'clsx';
import { useApi } from '../../context/ApiContext';
import { useToast } from '../../context/ToastContext';
import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';
import { useRegisterComposerTarget, type ComposerInsertTarget } from '../../context/ComposerBridgeContext';
-import type { SessionRuntimeState, VaultRequest, VibeAgentBrief, WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';
+import type { SessionActivityItemKind, SessionActivityState, SessionRuntimeState, VaultRequest, VibeAgentBrief, WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';
import { apiFetch } from '../../lib/apiFetch';
import { normalizeChatMessageFontSize } from '../../lib/chatDisplay';
import { isNotifyMessageType, isTerminalAgentMessage } from '../../lib/chatMessageTypes';
import { useIosKeyboardInset } from '../../lib/useIosKeyboardInset';
import { isProxyMediaUrl } from '../../lib/mediaProxy';
import { localPath, type ShowPageLinkInfo } from '../../lib/showPageLinks';
-import { formatLocalDateTime } from '../../lib/relativeTime';
+import { formatLocalDateTime, formatRelativeTime } from '../../lib/relativeTime';
+import { activityItemKind, harnessNavPath, resolveActivityLabel, sortBackgroundActivities } from '../../lib/backgroundActivity';
import { useFileDrop } from '../../lib/useFileDrop';
import { quoteText } from '../../lib/quoteText';
import { mergeById, insertMessageOrdered } from '../../lib/transcriptOrder';
@@ -30,6 +32,7 @@ import { ImageViewerProvider } from '../ui/image-viewer';
import { FileViewerProvider } from '../ui/file-viewer';
import { Input } from '../ui/input';
import { Markdown } from '../ui/markdown';
+import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import { VaultApprovalFloat, VaultChatRequests } from '../ui/vault-chat-requests';
import { StatusPill } from '../visual';
import { usePendingVaultRequests } from '../../lib/usePendingVaultRequests';
@@ -294,6 +297,11 @@ export const ChatPage: React.FC = () => {
// other origin we observe). Drives the thinking bubble + the Send→Stop swap.
const [working, setWorking] = useState(false);
const [runtimeState, setRuntimeState] = useState<SessionRuntimeState>(emptyRuntimeState);
+ // Global background-work banner toggle (spec req 2), persisted server-side.
+ // Tri-state: null = not yet known → suppress the banner so a stored "off"
+ // never flashes on first paint; resolves to the stored value (ON when absent),
+ // or ON on a fetch error so a transient failure can't hide live work.
+ const [bannerEnabled, setBannerEnabled] = useState<boolean | null>(null);
// Bumped on resume (tab visible again / network back) to force the transcript
// subscription effect to reopen a possibly-dead SSE stream — see the
// visibility effect below.
@@ -372,6 +380,22 @@ export const ChatPage: React.FC = () => {
useEffect(() => {
hasNativeRef.current = Boolean(session?.native_session_id);
}, [session]);
+ // Read the global banner toggle once per mount (cached GET). Absent/failed →
+ // default ON, so a transient prefs error never hides live background work.
+ useEffect(() => {
+ let cancelled = false;
+ api
+ .getWorkbenchPrefs()
+ .then((prefs) => {
+ if (!cancelled) setBannerEnabled(prefs?.background_work_banner_enabled !== false);
+ })
+ .catch(() => {
+ if (!cancelled) setBannerEnabled(true); // default ON on error
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [api]);
const refreshSessionRowUntilNativeBound = useCallback(async () => {
const id = sessionIdRef.current;
if (!id || hasNativeRef.current) return;
@@ -1527,7 +1551,7 @@ export const ChatPage: React.FC = () => {
) : null
}
/>
- <ActivityStrip state={runtimeState} />
+ <ActivityStrip state={runtimeState} sessionId={sessionId ?? ''} enabled={bannerEnabled === true} />
<QueueStrip queue={queue} onRemove={removeQueued} onRecall={recallQueued} onSendNow={sendQueueNow} />
{sessionId && pendingApprovals.length > 0 ? (
<VaultApprovalFloat offscreen={offscreenApprovals} pending={pendingApprovals} onResolved={refreshVaultRequests} />
@@ -1628,47 +1652,208 @@ const QueueRow: React.FC<{
);
};
-const ActivityStrip: React.FC<{ state: SessionRuntimeState }> = ({ state }) => {
+// Kind glyph + color tint per unified banner item. Backend activities and the
+// three harness sources each get a distinct icon and soft-tinted box (design:
+// mint / cyan / gold / violet, via the established bg-<color>/15 pattern).
+const ACTIVITY_ITEM_ICON: Record<SessionActivityItemKind, LucideIcon> = {
+ backend_activity: Terminal,
+ watch: Eye,
+ task: Clock,
+ agent_run: Bot,
+};
+
+const ACTIVITY_ITEM_TINT: Record<SessionActivityItemKind, string> = {
+ backend_activity: 'bg-mint/15 text-mint',
+ watch: 'bg-cyan/15 text-cyan',
+ task: 'bg-gold/15 text-gold',
+ agent_run: 'bg-violet/15 text-violet',
+};
+
+// item_kind (snake_case wire value) -> chat.activities.kind.* i18n leaf.
+const ACTIVITY_ITEM_I18N: Record<SessionActivityItemKind, string> = {
+ backend_activity: 'backendActivity',
+ watch: 'watch',
+ task: 'task',
+ agent_run: 'agentRun',
+};
+
+// One expanded popover row: colored kind icon box + two-line label / subtitle.
+// Backend activities are display-only with a colored status word (no landing
+// page); harness rows navigate to their Harness surface on click.
+const ActivityRow: React.FC<{
+ item: SessionActivityState;
+ onNavigate: (item: SessionActivityState) => void;
+}> = ({ item, onNavigate }) => {
+ const { t } = useTranslation();
+ const kind = activityItemKind(item);
+ const Icon = ACTIVITY_ITEM_ICON[kind];
+ const kindLabel = t(`chat.activities.kind.${ACTIVITY_ITEM_I18N[kind]}`);
+ const label = resolveActivityLabel(item, kindLabel);
+ const relative = formatRelativeTime(item.since ?? item.started_at, t);
+ const isHarness = kind !== 'backend_activity';
+ const subtitle =
+ kind === 'backend_activity' && item.backend ? `${item.backend} · ${relative}` : relative;
+ const body = (
+ <>
+ <span
+ className={clsx(
+ 'flex size-8 shrink-0 items-center justify-center rounded-lg',
+ ACTIVITY_ITEM_TINT[kind],
+ )}
+ >
+ <Icon className="size-4" aria-hidden="true" />
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col text-left">
+ <span className="truncate text-[13px] font-medium text-foreground">
+ <span className="text-muted">{kindLabel} · </span>
+ {label}
+ </span>
+ <span className="truncate text-[11px] text-muted">{subtitle}</span>
+ </span>
+ {isHarness ? (
+ <ChevronRight className="size-4 shrink-0 self-center text-muted" aria-hidden="true" />
+ ) : (
+ <span className="shrink-0 self-center text-[11px] font-medium text-mint">
+ {t('chat.activities.status.running')}
+ </span>
+ )}
+ </>
+ );
+ if (!isHarness) {
+ return <div className="flex items-center gap-2.5 rounded-lg px-2 py-1.5">{body}</div>;
+ }
+ return (
+ <button
+ type="button"
+ onClick={() => onNavigate(item)}
+ title={t('chat.activities.openHarness', { kind: kindLabel })}
+ aria-label={t('chat.activities.openHarness', { kind: kindLabel })}
+ className="flex w-full items-center gap-2.5 rounded-lg px-2 py-1.5 transition-colors hover:bg-surface-2"
+ >
+ {body}
+ </button>
+ );
+};
+
+// The unified background-work banner: always ONE pill (count = union size); a
+// click expands an UPWARD popover (req 1) of per-kind rows sorted running-first
+// (req 5), max-height ~340 with internal scroll (req 3). Hidden entirely when
+// the global toggle is off (req 2) or the union is empty (current behavior).
+const ActivityStrip: React.FC<{
+ state: SessionRuntimeState;
+ sessionId: string;
+ enabled: boolean;
+}> = ({ state, sessionId, enabled }) => {
const { t } = useTranslation();
- const active = state.background_activities;
+ const navigate = useNavigate();
+ const [open, setOpen] = useState(false);
+ const active = useMemo(
+ () => sortBackgroundActivities(state.background_activities),
+ [state.background_activities],
+ );
const pendingOutputs = state.pending_activity_output_count;
+ if (!enabled) return null;
if (active.length === 0 && pendingOutputs === 0) return null;
- const firstDescription = active.find((item) => item.description)?.description;
+ const first = active[0];
+ const firstLabel = first
+ ? resolveActivityLabel(first, t(`chat.activities.kind.${ACTIVITY_ITEM_I18N[activityItemKind(first)]}`))
+ : '';
const connectionVisible =
active.length > 0 &&
(state.connection === 'reconnecting' || state.connection === 'disconnected');
+ const expandable = active.length > 0;
+ const navigateTo = (path: string) => {
+ setOpen(false);
+ navigate(path);
+ };
+
+ const pill = (
+ <StatusPill
+ tone="running"
+ role="status"
+ aria-live="polite"
+ className={clsx(
+ 'min-h-7 min-w-0 max-w-[420px] gap-2 px-3 py-1 text-[11px] font-normal shadow-sm shadow-mint/5',
+ expandable && 'cursor-pointer select-none',
+ )}
+ indicator={
+ active.length > 0 ? (
+ <Activity className="size-3.5 shrink-0 text-mint" aria-hidden="true" />
+ ) : (
+ <Loader2 className="size-3.5 shrink-0 animate-spin text-mint" aria-hidden="true" />
+ )
+ }
+ label={
+ <>
+ <span className="min-w-0 truncate text-muted" title={firstLabel || undefined}>
+ {active.length > 0
+ ? t('chat.activities.running', { count: active.length })
+ : t('chat.activities.delivering', { count: pendingOutputs })}
+ {firstLabel ? ` · ${firstLabel}` : ''}
+ </span>
+ {connectionVisible ? (
+ <span className="shrink-0 border-l border-border-strong pl-2 text-gold">
+ {t(`chat.activities.connection.${state.connection}`)}
+ </span>
+ ) : null}
+ {expandable ? (
+ <ChevronDown
+ className={clsx('size-3.5 shrink-0 text-muted transition-transform', open && 'rotate-180')}
+ aria-hidden="true"
+ />
+ ) : null}
+ </>
+ }
+ />
+ );
+
return (
<div className="shrink-0 px-4 py-2 md:px-8">
- <div className="mx-auto flex w-full max-w-[1080px]">
- <StatusPill
- tone="running"
- role="status"
- aria-live="polite"
- className="min-h-7 min-w-0 max-w-full gap-2 px-3 py-1 text-[11px] font-normal shadow-sm shadow-mint/5"
- indicator={
- active.length > 0 ? (
- <Activity className="size-3.5 shrink-0 text-mint" aria-hidden="true" />
- ) : (
- <Loader2 className="size-3.5 shrink-0 animate-spin text-mint" aria-hidden="true" />
- )
- }
- label={
- <>
- <span className="min-w-0 truncate text-muted" title={firstDescription ?? undefined}>
- {active.length > 0
- ? t('chat.activities.running', { count: active.length })
- : t('chat.activities.delivering', { count: pendingOutputs })}
- {firstDescription ? ` · ${firstDescription}` : ''}
- </span>
- {connectionVisible ? (
- <span className="shrink-0 border-l border-border-strong pl-2 text-gold">
- {t(`chat.activities.connection.${state.connection}`)}
- </span>
- ) : null}
- </>
- }
- />
+ <div className="mx-auto w-full max-w-[1080px]">
+ {expandable ? (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ aria-label={t('chat.activities.toggle')}
+ className="block max-w-full rounded-full outline-none focus-visible:ring-2 focus-visible:ring-mint/40"
+ >
+ {pill}
+ </button>
+ </PopoverTrigger>
+ <PopoverContent
+ side="top"
+ align="start"
+ sideOffset={8}
+ // Spec req 1: anchor to the pill's top edge and never open downward
+ // (a downward flip would cover the composer). Disable Radix
+ // collision flipping so the popover stays above even when zoomed.
+ avoidCollisions={false}
+ className="flex max-h-[340px] w-[420px] max-w-[calc(100vw-2rem)] flex-col overflow-hidden rounded-lg border-border-strong p-0 shadow-lg"
+ >
+ <div className="flex max-h-[300px] flex-col gap-0.5 overflow-y-auto p-1">
+ {active.map((item) => (
+ <ActivityRow
+ key={item.id}
+ item={item}
+ onNavigate={(it) => navigateTo(harnessNavPath(it, sessionId))}
+ />
+ ))}
+ </div>
+ <button
+ type="button"
+ onClick={() => navigateTo('/harness')}
+ className="flex shrink-0 items-center justify-center gap-1 border-t border-border/60 px-2 py-2 text-[12px] font-medium text-cyan transition-colors hover:bg-surface-2"
+ >
+ {t('chat.activities.manageInHarness')}
+ <ArrowRight className="size-3.5" aria-hidden="true" />
+ </button>
+ </PopoverContent>
+ </Popover>
+ ) : (
+ pill
+ )}
</div>
</div>
);
diff --git a/ui/src/components/workbench/HarnessPage.tsx b/ui/src/components/workbench/HarnessPage.tsx
index d0111eecd..242446296 100644
--- a/ui/src/components/workbench/HarnessPage.tsx
+++ b/ui/src/components/workbench/HarnessPage.tsx
@@ -22,9 +22,11 @@ import {
Bot,
MessageSquare,
ArrowUpRight,
+ Filter,
+ X,
} from 'lucide-react';
import clsx from 'clsx';
-import { Link } from 'react-router-dom';
+import { Link, useSearchParams } from 'react-router-dom';
import { useApi } from '../../context/ApiContext';
import type {
@@ -121,12 +123,90 @@ export const HarnessPage: React.FC = () => {
const [statusFilter, setStatusFilter] = useState<HarnessDefinitionStatus>('enabled');
const [debouncedSearch, setDebouncedSearch] = useState('');
const refreshSeq = useRef(0);
+ // URL scope from the background-work banner (spec req 4): ?tab / ?session /
+ // ?run deep-link into a session-scoped tab (removable "只看本会话" chip) or a
+ // specific run. One-way URL -> state, keyed per-param so a user's tab click
+ // (which doesn't touch the URL) is never clobbered by a re-sync.
+ const [searchParams, setSearchParams] = useSearchParams();
+ const [sessionFilter, setSessionFilter] = useState<string | undefined>(undefined);
+ // Global background-work banner toggle (spec req 2), persisted server-side.
+ const [bannerEnabled, setBannerEnabled] = useState(true);
+ const [bannerPending, setBannerPending] = useState(false);
useEffect(() => {
const timeout = window.setTimeout(() => setDebouncedSearch(search.trim()), 250);
return () => window.clearTimeout(timeout);
}, [search]);
+ const tabParam = searchParams.get('tab');
+ const sessionParam = searchParams.get('session');
+ const runParam = searchParams.get('run');
+ useEffect(() => {
+ if (tabParam && (['tasks', 'watches', 'runs'] as string[]).includes(tabParam)) {
+ setTab(tabParam as TabKey);
+ }
+ }, [tabParam]);
+ useEffect(() => {
+ setSessionFilter(sessionParam || undefined);
+ setTasksPage(1);
+ setWatchesPage(1);
+ }, [sessionParam]);
+ useEffect(() => {
+ if (runParam) {
+ setSelection({ kind: 'run', id: runParam });
+ } else {
+ // A deep-link that drops ?run (e.g. browser back/forward from a run link
+ // to a watch/task session link) must not leave the previous run's detail
+ // panel open on the new tab. Only clear a stale RUN anchor — a task/watch
+ // row the user clicked stays selected.
+ setSelection((prev) => (prev?.kind === 'run' ? null : prev));
+ }
+ }, [runParam]);
+
+ // Global banner toggle: read once, default ON on any error.
+ useEffect(() => {
+ let cancelled = false;
+ api
+ .getWorkbenchPrefs()
+ .then((prefs) => {
+ if (!cancelled) setBannerEnabled(prefs?.background_work_banner_enabled !== false);
+ })
+ .catch(() => {
+ /* keep default ON */
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [api]);
+
+ const onToggleBanner = useCallback(
+ async (next: boolean) => {
+ setBannerEnabled(next); // optimistic
+ setBannerPending(true);
+ try {
+ const prefs = await api.setBackgroundWorkBannerEnabled(next);
+ setBannerEnabled(prefs?.background_work_banner_enabled !== false);
+ } catch {
+ setBannerEnabled(!next); // revert on failure
+ } finally {
+ setBannerPending(false);
+ }
+ },
+ [api],
+ );
+
+ const clearSessionFilter = useCallback(() => {
+ setSessionFilter(undefined);
+ setSearchParams(
+ (prev) => {
+ const next = new URLSearchParams(prev);
+ next.delete('session');
+ return next;
+ },
+ { replace: true },
+ );
+ }, [setSearchParams]);
+
const refresh = useCallback(async () => {
const seq = refreshSeq.current + 1;
refreshSeq.current = seq;
@@ -147,6 +227,8 @@ export const HarnessPage: React.FC = () => {
tab,
status: tab === 'runs' ? undefined : statusFilter,
query,
+ // Session scope applies to definition tabs; runs anchor by ?run instead.
+ session_id: tab === 'tasks' || tab === 'watches' ? sessionFilter : undefined,
page: tab === 'tasks' ? tasksPage : tab === 'watches' ? watchesPage : runsPage,
limit: PAGE_LIMIT,
});
@@ -175,7 +257,7 @@ export const HarnessPage: React.FC = () => {
} finally {
if (isCurrent()) setLoading(false);
}
- }, [api, tab, debouncedSearch, statusFilter, tasksPage, watchesPage, runsPage]);
+ }, [api, tab, debouncedSearch, statusFilter, sessionFilter, tasksPage, watchesPage, runsPage]);
useEffect(() => {
refresh();
@@ -377,6 +459,21 @@ export const HarnessPage: React.FC = () => {
</Button>
</div>
+ {/* Global background-work banner toggle (spec req 2). Off → the workbench
+ chat banner never renders in any session; data/API unaffected. */}
+ <div className="flex items-center justify-between gap-4 rounded-xl border border-border-strong bg-surface px-4 py-3">
+ <div className="min-w-0">
+ <div className="text-sm font-semibold text-foreground">{t('harness.bannerToggle.title')}</div>
+ <div className="text-[12px] text-muted">{t('harness.bannerToggle.description')}</div>
+ </div>
+ <Switch
+ checked={bannerEnabled}
+ onCheckedChange={onToggleBanner}
+ disabled={bannerPending}
+ label={t('harness.bannerToggle.title')}
+ />
+ </div>
+
{/* Tab row */}
<div className="flex items-center gap-0 overflow-x-auto border-b border-border">
{TAB_ORDER.map((key) => {
@@ -457,6 +554,23 @@ export const HarnessPage: React.FC = () => {
</button>
))}
</div>
+ {sessionFilter && (
+ <span className="inline-flex items-center gap-1.5 rounded-full border border-cyan/30 bg-cyan/[0.10] py-1 pl-2.5 pr-1.5 text-[11px] font-medium text-cyan">
+ <Filter className="size-3 shrink-0" />
+ <span className="max-w-[180px] truncate">
+ {t('harness.sessionFilter.chip', { id: sessionFilter })}
+ </span>
+ <button
+ type="button"
+ onClick={clearSessionFilter}
+ aria-label={t('harness.sessionFilter.clear')}
+ title={t('harness.sessionFilter.clear')}
+ className="rounded-full p-0.5 text-cyan/80 transition-colors hover:bg-cyan/20 hover:text-cyan"
+ >
+ <X className="size-3" />
+ </button>
+ </span>
+ )}
{(search || statusFilter !== 'all') && (
<span className="ml-auto font-mono text-[10px] text-muted">
{t('harness.filtered', { shown: shownForTab, total: totalForTab })}
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 3e6386827..3acd07c91 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -9,6 +9,11 @@ import type { DockDoc } from './DockContext';
// itself lives with the DockProvider that owns reconciliation.
export type DockResponse = { ok: boolean; dock: DockDoc };
+// Global workbench toggles persisted server-side in state_meta. Currently just
+// the background-work banner switch (spec req 2); read by ChatPage (to gate the
+// banner) and the Harness page (the toggle card).
+export type WorkbenchPrefs = { ok?: boolean; background_work_banner_enabled: boolean };
+
// One backend's *global* instructions file, surfaced by the Global Prompts
// editor. ``backend`` is an agent backend id (claude / opencode / codex).
export type GlobalPromptFile = {
@@ -421,6 +426,10 @@ export type ApiContextType = {
* reorder is rejected server-side and re-synced without a toast. Returns the
* payload; check ``ok``. */
setDockOrder: (order: string[], known?: string[]) => Promise<DockResponse>;
+ /** Global workbench toggles (state_meta-backed): banner on/off. */
+ getWorkbenchPrefs: () => Promise<WorkbenchPrefs>;
+ /** Persist the background-work banner global toggle; resolves to updated prefs. */
+ setBackgroundWorkBannerEnabled: (enabled: boolean) => Promise<WorkbenchPrefs>;
getBindCodes: () => Promise<any>;
createBindCode: (type: string, expiresAt?: string) => Promise<any>;
deleteBindCode: (code: string) => Promise<any>;
@@ -1012,6 +1021,14 @@ export type MessageSearchResult = {
session_count: number;
};
+// Union item for the background-work banner. Backend activities (from the
+// process-local SessionActivityRegistry) and live-derived harness items
+// (watches / scheduled tasks / delegated agent runs) share this shape. The
+// legacy fields stay for backward compatibility; `item_kind` / `label` /
+// `since` are the unified fields the banner renders and routes on. `item_kind`
+// is optional so a pre-union payload degrades to a backend activity.
+export type SessionActivityItemKind = 'backend_activity' | 'watch' | 'task' | 'agent_run';
+
export type SessionActivityState = {
id: string;
backend: string;
@@ -1022,6 +1039,9 @@ export type SessionActivityState = {
description: string | null;
started_at: string;
updated_at: string;
+ item_kind?: SessionActivityItemKind;
+ label?: string | null;
+ since?: string;
};
export type SessionRuntimeState = {
@@ -1266,6 +1286,8 @@ export type HarnessBootstrapParams = {
tab?: 'tasks' | 'watches' | 'runs';
status?: HarnessDefinitionStatus | HarnessRunStatus;
query?: string;
+ /** Scope tasks/watches to a bound session (background-work banner deep-link). */
+ session_id?: string;
page?: number;
limit?: number;
};
@@ -2211,6 +2233,22 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
);
return payloadJson;
},
+ getWorkbenchPrefs: () => getCachedJson('/api/workbench/prefs', 5_000),
+ setBackgroundWorkBannerEnabled: async (enabled) => {
+ // Default handleError:true — a non-2xx (auth/CSRF/server) throws so the
+ // caller reverts its optimistic switch instead of diverging from the
+ // persisted value.
+ const { payloadJson } = await requestJson(
+ '/api/workbench/prefs',
+ {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ background_work_banner_enabled: enabled }),
+ },
+ 'PUT /api/workbench/prefs',
+ );
+ return payloadJson;
+ },
getBindCodes: () => getJson('/api/bind-codes'),
createBindCode: (type, expiresAt) => postJson('/api/bind-codes', { type, expires_at: expiresAt }),
deleteBindCode: (code) => deleteJson(`/api/bind-codes/${encodeURIComponent(code)}`),
@@ -2611,6 +2649,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
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?.session_id) search.set('session_id', params.session_id);
if (params?.page) search.set('page', String(params.page));
if (params?.limit) search.set('limit', String(params.limit));
const qs = search.toString();
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 858c3a543..1b930dd17 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2139,6 +2139,14 @@
"disabled": "Disabled only"
},
"filtered": "{{shown}}/{{total}}",
+ "bannerToggle": {
+ "title": "Background-work banner",
+ "description": "Show in-progress background work at the bottom of chats."
+ },
+ "sessionFilter": {
+ "chip": "Only: this session {{id}}",
+ "clear": "Clear session filter"
+ },
"selectPrompt": "Select a row to view its full configuration.",
"emptyTasks": "No scheduled tasks. Ask an agent to create one.",
"emptyWatches": "No watches running. Ask an agent to start one.",
@@ -2330,6 +2338,18 @@
"activities": {
"running": "Background work · {{count}}",
"delivering": "Delivering background output · {{count}}",
+ "toggle": "Toggle background work",
+ "manageInHarness": "Manage in Harness",
+ "openHarness": "Open in Harness · {{kind}}",
+ "status": {
+ "running": "Running"
+ },
+ "kind": {
+ "backendActivity": "Background task",
+ "watch": "Watch",
+ "task": "Scheduled task",
+ "agentRun": "Agent run"
+ },
"connection": {
"reconnecting": "Reconnecting",
"disconnected": "Disconnected"
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 758da9343..4aec238df 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2139,6 +2139,14 @@
"disabled": "仅禁用"
},
"filtered": "{{shown}}/{{total}}",
+ "bannerToggle": {
+ "title": "后台工作横幅",
+ "description": "在会话底部显示进行中的后台工作。"
+ },
+ "sessionFilter": {
+ "chip": "仅看:本会话 {{id}}",
+ "clear": "移除会话筛选"
+ },
"selectPrompt": "选择左侧条目查看完整配置。",
"emptyTasks": "暂无定时任务。让 Agent 帮你创建一个。",
"emptyWatches": "没有正在运行的 Watch。让 Agent 帮你开启一个。",
@@ -2330,6 +2338,18 @@
"activities": {
"running": "后台工作 · {{count}}",
"delivering": "正在投递后台输出 · {{count}}",
+ "toggle": "展开后台工作",
+ "manageInHarness": "在 Harness 中管理",
+ "openHarness": "在 Harness 中打开 · {{kind}}",
+ "status": {
+ "running": "运行中"
+ },
+ "kind": {
+ "backendActivity": "后台任务",
+ "watch": "监视",
+ "task": "定时任务",
+ "agentRun": "Agent 运行"
+ },
"connection": {
"reconnecting": "重连中",
"disconnected": "已断开"
diff --git a/ui/src/lib/backgroundActivity.test.ts b/ui/src/lib/backgroundActivity.test.ts
new file mode 100644
index 000000000..5fb6c5471
--- /dev/null
+++ b/ui/src/lib/backgroundActivity.test.ts
@@ -0,0 +1,131 @@
+import { describe, expect, it } from 'vitest';
+
+import type { SessionActivityState } from '../context/ApiContext';
+import {
+ activityItemKind,
+ harnessItemNativeId,
+ harnessNavPath,
+ isHarnessActivity,
+ resolveActivityLabel,
+ sortBackgroundActivities,
+} from './backgroundActivity';
+
+// Minimal item factory — only the fields the pure helpers read.
+function item(partial: Partial<SessionActivityState>): SessionActivityState {
+ return {
+ id: 'x',
+ backend: '',
+ runtime_key: '',
+ session_id: null,
+ kind: '',
+ status: 'running',
+ description: null,
+ started_at: '2026-07-16T00:00:00Z',
+ updated_at: '2026-07-16T00:00:00Z',
+ ...partial,
+ };
+}
+
+describe('activityItemKind', () => {
+ it('returns the harness kind for watch / task / agent_run', () => {
+ expect(activityItemKind({ item_kind: 'watch' })).toBe('watch');
+ expect(activityItemKind({ item_kind: 'task' })).toBe('task');
+ expect(activityItemKind({ item_kind: 'agent_run' })).toBe('agent_run');
+ });
+
+ it('defaults missing / legacy / unknown item_kind to backend_activity', () => {
+ expect(activityItemKind({})).toBe('backend_activity');
+ expect(activityItemKind({ item_kind: 'backend_activity' })).toBe('backend_activity');
+ // A payload from before the union carried no item_kind at all.
+ expect(activityItemKind({ item_kind: undefined })).toBe('backend_activity');
+ // An unexpected value still degrades to a backend activity row.
+ expect(activityItemKind({ item_kind: 'mystery' as never })).toBe('backend_activity');
+ });
+});
+
+describe('isHarnessActivity', () => {
+ it('is true only for harness rows', () => {
+ expect(isHarnessActivity({ item_kind: 'watch' })).toBe(true);
+ expect(isHarnessActivity({ item_kind: 'task' })).toBe(true);
+ expect(isHarnessActivity({ item_kind: 'agent_run' })).toBe(true);
+ expect(isHarnessActivity({ item_kind: 'backend_activity' })).toBe(false);
+ expect(isHarnessActivity({})).toBe(false);
+ });
+});
+
+describe('resolveActivityLabel', () => {
+ it('prefers label, then description, then the fallback', () => {
+ expect(resolveActivityLabel({ label: 'deploy watch', description: 'desc' }, 'Watch')).toBe(
+ 'deploy watch',
+ );
+ expect(resolveActivityLabel({ label: '', description: 'from desc' }, 'Watch')).toBe('from desc');
+ expect(resolveActivityLabel({ label: null, description: null }, 'Watch')).toBe('Watch');
+ expect(resolveActivityLabel({}, 'Scheduled task')).toBe('Scheduled task');
+ });
+
+ it('treats a whitespace-only label as empty', () => {
+ expect(resolveActivityLabel({ label: ' ', description: '' }, 'Agent run')).toBe('Agent run');
+ });
+});
+
+describe('harnessItemNativeId', () => {
+ it('strips the kind namespace prefix', () => {
+ expect(harnessItemNativeId({ id: 'watch:abc123' })).toBe('abc123');
+ expect(harnessItemNativeId({ id: 'agent_run:run-9' })).toBe('run-9');
+ expect(harnessItemNativeId({ id: 'plain' })).toBe('plain');
+ });
+});
+
+describe('sortBackgroundActivities', () => {
+ it('orders running items first, then by start time descending', () => {
+ const items = [
+ item({ id: 'watch:w', item_kind: 'watch', status: 'enabled', since: '2026-07-16T05:00:00Z' }),
+ item({ id: 'run:new', item_kind: 'agent_run', status: 'running', since: '2026-07-16T09:00:00Z' }),
+ item({ id: 'run:old', item_kind: 'agent_run', status: 'running', since: '2026-07-16T02:00:00Z' }),
+ item({ id: 'task:t', item_kind: 'task', status: 'scheduled', since: '2026-07-16T08:00:00Z' }),
+ ];
+ expect(sortBackgroundActivities(items).map((i) => i.id)).toEqual([
+ 'run:new', // running, newest
+ 'run:old', // running, older
+ 'task:t', // pending, newest
+ 'watch:w', // pending, older
+ ]);
+ });
+
+ it('does not mutate the input array', () => {
+ const items = [item({ id: 'a', status: 'enabled' }), item({ id: 'b', status: 'running' })];
+ const copy = [...items];
+ sortBackgroundActivities(items);
+ expect(items).toEqual(copy);
+ });
+
+ it('treats the raw "processing" status as in-progress', () => {
+ const items = [
+ item({ id: 'task', status: 'scheduled', since: '2026-07-16T09:00:00Z' }),
+ item({ id: 'run', status: 'processing', since: '2026-07-16T02:00:00Z' }),
+ ];
+ // The processing run ranks above the (newer) scheduled task.
+ expect(sortBackgroundActivities(items).map((i) => i.id)).toEqual(['run', 'task']);
+ });
+});
+
+describe('harnessNavPath', () => {
+ it('sends watch/task rows to the matching tab with a session filter', () => {
+ expect(harnessNavPath({ id: 'watch:w1', item_kind: 'watch' }, 'ses-1')).toBe(
+ '/harness?tab=watches&session=ses-1',
+ );
+ expect(harnessNavPath({ id: 'task:t1', item_kind: 'task' }, 'ses-1')).toBe(
+ '/harness?tab=tasks&session=ses-1',
+ );
+ });
+
+ it('anchors a delegated run by id (no session filter — it runs elsewhere)', () => {
+ expect(harnessNavPath({ id: 'agent_run:r1', item_kind: 'agent_run' }, 'ses-1')).toBe(
+ '/harness?tab=runs&run=r1',
+ );
+ });
+
+ it('omits the session param when no session is given', () => {
+ expect(harnessNavPath({ id: 'watch:w1', item_kind: 'watch' }, null)).toBe('/harness?tab=watches');
+ });
+});
diff --git a/ui/src/lib/backgroundActivity.ts b/ui/src/lib/backgroundActivity.ts
new file mode 100644
index 000000000..87fd64b7e
--- /dev/null
+++ b/ui/src/lib/backgroundActivity.ts
@@ -0,0 +1,83 @@
+// Pure helpers for the unified background-work banner (ChatPage ActivityStrip).
+// The banner renders a union of backend activities and live-derived harness
+// items (watches / scheduled tasks / delegated agent runs); these functions
+// classify and label a row without pulling in the component.
+import type { SessionActivityItemKind, SessionActivityState } from '../context/ApiContext';
+
+const HARNESS_ITEM_KINDS: readonly SessionActivityItemKind[] = ['watch', 'task', 'agent_run'];
+
+// Resolve the union discriminator. A missing or unknown (e.g. pre-union) value
+// reads as a backend activity so the banner never drops a row.
+export function activityItemKind(
+ item: Pick<SessionActivityState, 'item_kind'>,
+): SessionActivityItemKind {
+ const kind = item.item_kind;
+ return kind && HARNESS_ITEM_KINDS.includes(kind) ? kind : 'backend_activity';
+}
+
+// Harness rows (watch / task / delegated run) navigate to the Harness surface;
+// backend activities keep their current non-navigating behavior.
+export function isHarnessActivity(item: Pick<SessionActivityState, 'item_kind'>): boolean {
+ return activityItemKind(item) !== 'backend_activity';
+}
+
+// Prefer the unified label, then the legacy description, then a kind fallback so
+// an unnamed watch/task still shows something meaningful.
+export function resolveActivityLabel(
+ item: Pick<SessionActivityState, 'label' | 'description'>,
+ fallback: string,
+): string {
+ return (item.label || item.description || '').trim() || fallback;
+}
+
+// A harness item id is namespaced (`watch:<id>` / `task:<id>` / `agent_run:<id>`).
+// Return the underlying entity id for deep-linking; backend ids pass through.
+export function harnessItemNativeId(item: Pick<SessionActivityState, 'id'>): string {
+ const id = item.id ?? '';
+ const idx = id.indexOf(':');
+ return idx >= 0 ? id.slice(idx + 1) : id;
+}
+
+// Status values that mean "actively executing" for banner ordering. ``running``
+// is the normalized form; ``processing`` is the raw/legacy alias the durable
+// store may still carry (see storage/background.RUN_STATUS_ALIASES) — both must
+// rank as in-progress or a live delegated run could sort below pending items.
+const RUNNING_STATUSES = new Set(['running', 'processing']);
+
+// Popover ordering (spec req 5): in-progress items first, then start time
+// descending. Backend activities and running/processing delegated runs are
+// "in progress"; watches (enabled), tasks (scheduled), and queued runs are
+// pending. Stable, pure copy — never mutates the input.
+export function sortBackgroundActivities(items: SessionActivityState[]): SessionActivityState[] {
+ const activeRank = (it: SessionActivityState) => (RUNNING_STATUSES.has(it.status) ? 0 : 1);
+ const sinceOf = (it: SessionActivityState) => it.since ?? it.started_at ?? '';
+ return [...items].sort((a, b) => {
+ const rank = activeRank(a) - activeRank(b);
+ if (rank !== 0) return rank;
+ return sinceOf(b).localeCompare(sinceOf(a));
+ });
+}
+
+// Where a harness banner row navigates (spec req 4). Watch/task rows open the
+// matching Harness tab filtered to the originating session (route param, shown
+// as a removable chip). A delegated run executes in another session, so it can't
+// be session-filtered — it opens the runs tab anchored to that run instead.
+// Backend activities never navigate (guarded by the caller); they fall back to
+// the bare Harness page.
+export function harnessNavPath(
+ item: Pick<SessionActivityState, 'id' | 'item_kind'>,
+ sessionId: string | null | undefined,
+): string {
+ const kind = activityItemKind(item);
+ const params = new URLSearchParams();
+ if (kind === 'watch' || kind === 'task') {
+ params.set('tab', kind === 'watch' ? 'watches' : 'tasks');
+ if (sessionId) params.set('session', sessionId);
+ } else if (kind === 'agent_run') {
+ params.set('tab', 'runs');
+ const runId = harnessItemNativeId(item);
+ if (runId) params.set('run', runId);
+ }
+ const qs = params.toString();
+ return qs ? `/harness?${qs}` : '/harness';
+}
diff --git a/vibe/api.py b/vibe/api.py
index f597630bf..72e443540 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1256,6 +1256,31 @@ def set_dock_order(order: list, known: list | None = None) -> dict:
return {"ok": True, "dock": _set_dock_order(order, known=known)}
+def get_workbench_prefs() -> dict:
+ """Global workbench toggles the UI reads (state_meta-backed)."""
+ from core.workbench_prefs import get_background_work_banner_enabled
+
+ return {
+ "ok": True,
+ "background_work_banner_enabled": get_background_work_banner_enabled(),
+ }
+
+
+def set_workbench_prefs(*, background_work_banner_enabled: Optional[bool] = None) -> dict:
+ """Persist provided workbench toggles; omitted fields are left untouched."""
+ from core.workbench_prefs import (
+ get_background_work_banner_enabled,
+ set_background_work_banner_enabled,
+ )
+
+ if background_work_banner_enabled is not None:
+ set_background_work_banner_enabled(bool(background_work_banner_enabled))
+ return {
+ "ok": True,
+ "background_work_banner_enabled": get_background_work_banner_enabled(),
+ }
+
+
def _vibe_agent_payload(agent, *, brief: bool = False) -> dict:
payload = agent.to_dict()
if brief:
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index ca9c22d01..c659e22be 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3697,6 +3697,23 @@ def dock_order_put():
return _dock_error_response(exc)
[email protected]("/api/workbench/prefs", methods=["GET"])
+def workbench_prefs_get():
+ from vibe import api
+
+ return jsonify(api.get_workbench_prefs())
+
+
[email protected]("/api/workbench/prefs", methods=["PUT"])
+def workbench_prefs_put():
+ from vibe import api
+
+ payload = request.json or {}
+ raw = payload.get("background_work_banner_enabled")
+ enabled = bool(raw) if raw is not None else None
+ return jsonify(api.set_workbench_prefs(background_work_banner_enabled=enabled))
+
+
@app.route("/api/csrf-token", methods=["GET"])
def csrf_token_get():
token = request.cookies.get(CSRF_COOKIE_NAME) or _new_csrf_token()
@@ -7541,8 +7558,15 @@ def _harness_query_filter() -> str | None:
return query or None
+def _harness_session_filter() -> str | None:
+ # ``?session=<id>`` — the background-work banner navigates here to scope a
+ # tab to its originating session (the removable "只看本会话" chip).
+ session_id = (request.args.get("session_id") or "").strip()
+ return session_id or None
+
+
def _harness_has_list_params() -> bool:
- return any(key in request.args for key in ("page", "limit", "status", "query"))
+ return any(key in request.args for key in ("page", "limit", "status", "query", "session_id"))
def _harness_page_payload(page_result, *, items_key: str, counts: dict[str, int]) -> dict[str, Any]:
@@ -7598,16 +7622,18 @@ def harness_tasks_list():
page_request = _harness_page_request()
status = _harness_status_filter()
query = _harness_query_filter()
+ session_id = _harness_session_filter()
except ValueError as exc:
return jsonify({"ok": False, "code": "invalid_pagination", "message": str(exc)}), 400
with _harness_store() as store:
page_result = store.list_scheduled_tasks_page(
status=status,
query=query,
+ session_id=session_id,
page_request=page_request,
newest_first=True,
)
- counts = store.count_scheduled_tasks(query=query)
+ counts = store.count_scheduled_tasks(query=query, session_id=session_id)
return jsonify(_harness_page_payload(page_result, items_key="tasks", counts=counts))
@@ -7657,16 +7683,18 @@ def harness_watches_list():
page_request = _harness_page_request()
status = _harness_status_filter()
query = _harness_query_filter()
+ session_id = _harness_session_filter()
except ValueError as exc:
return jsonify({"ok": False, "code": "invalid_pagination", "message": str(exc)}), 400
with _harness_store() as store:
page_result = store.list_watches_page(
status=status,
query=query,
+ session_id=session_id,
page_request=page_request,
newest_first=True,
)
- counts = store.count_watches(query=query)
+ counts = store.count_watches(query=query, session_id=session_id)
runtime = store.load_watch_runtime().get("watches") or {}
for watch in page_result.items:
watch["runtime"] = runtime.get(watch["id"]) or {"running": False}
@@ -7761,6 +7789,10 @@ def harness_bootstrap():
page_request = _harness_page_request()
definition_status = _harness_status_filter() if tab in {"tasks", "watches"} else "all"
query = _harness_query_filter()
+ # Session scope from the background-work banner (tasks/watches only; a
+ # delegated run is anchored by ``?run=`` on the client, not filtered by
+ # its execution session here).
+ session_id = _harness_session_filter() if tab in {"tasks", "watches"} else None
except ValueError as exc:
return jsonify({"ok": False, "code": "invalid_pagination", "message": str(exc)}), 400
@@ -7774,19 +7806,21 @@ def harness_bootstrap():
page_result = store.list_scheduled_tasks_page(
status=definition_status,
query=query,
+ session_id=session_id,
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),
+ counts=store.count_scheduled_tasks(query=query, session_id=session_id),
status=definition_status,
)
elif tab == "watches":
page_result = store.list_watches_page(
status=definition_status,
query=query,
+ session_id=session_id,
page_request=page_request,
newest_first=True,
)
@@ -7796,7 +7830,7 @@ def harness_bootstrap():
page_payload = _harness_page_payload_for_status(
page_result,
items_key="watches",
- counts=store.count_watches(query=query),
+ counts=store.count_watches(query=query, session_id=session_id),
status=definition_status,
)
else: