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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(workbench): readable harness run rows with linkable sessions (#1023)
Call White3c00490365be
diff --git a/docs/plans/harness-runs-readability.md b/docs/plans/harness-runs-readability.mdnew file mode 100644index 000000000..6968b8217--- /dev/null+++ b/docs/plans/harness-runs-readability.md@@ -0,0 +1,203 @@+# Harness Runs — readable rows, linkable sessions, working filters++Status: **approved, in implementation** (owner sign-off 2026-07-26)+Owner decisions: D1 = default-hide `watch_runtime`; D2 = message first line may be used as the row title.++## 1. Problem++The Harness → Runs surface is the only harness view that never received a+human-readable projection. Tasks and Watches were enriched with a resolved+session summary and given search + status filters (#431). The Agents graph got+`openable_in_chat` (#956). Runs still renders the raw `agent_runs` row:++- **Row headline is the run id hash.** `8246ff808e8c` tells the user nothing.+ The only other text on the row is the agent name and a relative timestamp.+- **The bound session is dead grey text.** `RunDetail` prints `run.session_id`+ as a `<code>` because the runs payload carries neither the session title nor+ any signal about whether that session can be opened. This silently deviates+ from `docs/plans/agents-run-graph-and-session-visibility.md` Part B, which+ specified "`session_id` + open-chat link"; the implementation retreated to+ plain text out of dead-link fear.+- **No filters at all.** `showSearchBar` is gated to `tasks | watches`, and the+ status filter is explicitly dropped for runs (`status: tab === 'runs' ?+ undefined : statusFilter`) — even though `GET /api/harness/runs` already+ accepts `status`, `run_type`, `agent_name`, `definition_id`, and `query`.+ 11k+ rows are navigable only by paging 30 at a time.++Root cause is single: **the runs payload is unprojected.** Both visible+symptoms fall out of that one gap, and the fix is to reuse the projection the+sibling surfaces already have rather than to special-case the frontend.++## 2. Ledger facts (measured 2026-07-26, developer machine, 11,230 runs)++| `run_type` | rows | has `session_id` | has `definition_id` | has message text |+| --- | ---: | ---: | ---: | ---: |+| `watch` | 3,636 | 3,629 | 3,636 | 3,636 |+| `watch_runtime` | 3,005 | 0 | 3,004 | **0** |+| `hook_send` | 2,995 | 110 | 0 | 2,995 |+| `agent_run` | 1,384 | 1,384 | 0 | 1,384 |+| `scheduled` | 208 | 52 | 208 | 208 |+| `task_run` | 2 | 0 | 2 | 0 |++Two facts drive the design:++1. **Every run type except `watch_runtime` and `task_run` carries message+ text.** A single uniform title rule therefore covers ~99.97% of rows; no+ per-type title logic is needed.+2. **Zero runs point at a `private_agent_run` pseudo-scope session** (M1's+ re-parenting is complete). The only real dead-link risk is **422 runs whose+ `session_id` names a session row that no longer exists** — which a server-side+ resolve detects exactly, per row.++## 3. Contract — new fields on the run payload (FROZEN)++Produced by `storage/background.py`; consumed by `ui/src/components/workbench/HarnessPage.tsx`.+Present on **both** `GET /api/harness/runs` (list) and `GET /api/harness/runs/<id>` (detail).++### 3.1 Bound session — reuse `HarnessSessionSummary` verbatim++The five existing fields, same names, same semantics, produced by the **same**+`SQLiteBackgroundTaskStore._session_summary(conn, session_id, session_key, deliver_key)`+that already backs `_enrich_task` / `_enrich_watch`:++```+session_title: string | null+session_platform: string | null+session_scope_kind: string | null+session_label: string | null+session_is_workbench: boolean+```++Consequences that are **by design**, not gaps:++- A workbench session resolves with `session_is_workbench = true` and a title →+ the existing `DetailSession` component links it to `/chat/<session_id>`.+ **This is the owner's headline fix and it requires no new frontend logic.**+- An IM-scope session shows platform + channel and is **not** linked, exactly as+ on Tasks/Watches today. Workbench chat renders workbench sessions; IM+ transcripts are scope-keyed (#535), so an unconditional `/chat` link would+ open an empty transcript. Out of scope here: the Agents graph's laxer+ `openable_in_chat` (`not is_private_run`) is inconsistent with this rule —+ report it, do not change it in this lane.+- A **deleted** session resolves to the all-null summary. The frontend must then+ render an explicit "session deleted" label, not a bare hash — see §4.2.++### 3.2 Originating definition++```+definition_name: string | null # run_definitions.name, even when soft-deleted+definition_kind: 'task' | 'watch' | null # from run_definitions.definition_type+definition_deleted: boolean # run_definitions.deleted_at is not null+```++### 3.3 Callback (report-back) session++```+callback_session: HarnessSessionSummary | null+```++A nested object rather than five more prefixed fields, so it drops straight into+`DetailSession` alongside the primary session. `null` when `callback_session_id`+is null.++### 3.4 Non-goals for the contract++No new columns, no migration, no change to `_run_from_row`'s existing keys.+Nothing is removed from the payload. `count_runs` / `count_runs_by_status` keep+their shape; they only gain the `exclude_run_type` filter argument (§4.3) so+their counts stay consistent with what the list shows.++## 4. Behavior++### 4.1 Row title — one uniform rule++```+title = first non-empty line of `message` (trimmed, collapsed whitespace)+ || definition_name+ || run_type label+```++Truncate to one line with CSS, not by slicing the string (the detail panel and+the search index must keep the full text). D2 explicitly permits the message+first line to appear in the list.++Row anatomy (replacing the hash headline):++- **Line 1:** status icon · title · run-type chip+- **Line 2:** trigger chip (`definition_name`, links to its Watch/Task when+ `definition_kind && !definition_deleted`) · agent name · session label ·+ duration · relative time+- The run id moves to the detail panel. Keep it copyable there.++### 4.2 Session field — link, label, or honest dead end++| Resolved state | Render |+| --- | --- |+| workbench session | `DetailSession` → link to `/chat/<id>` (title as label) |+| IM session | `DetailSession` → platform icon + channel label, not linked |+| `session_id` set, nothing resolved | muted "session deleted" label + the id, not linked |+| no `session_id` | existing `harness.detail.sessionNone` |++New i18n key required for the deleted case (en + zh).++### 4.3 Filters on the Runs tab++Reuse the Tasks/Watches filter row — do not build a second one.++- **Search** — bind to the existing `query` param. Remove the+ `showSearchBar = tab === 'tasks' || tab === 'watches'` gate.+- **Status** — stop dropping it for runs (`status: tab === 'runs' ? undefined :+ statusFilter`); `count_runs_by_status` already feeds the counts.+- **Run type** — a type selector bound to the existing `run_type` param.+ `HarnessRunsParams.runType` is already typed.+- **One new API param, `exclude_run_type`** (comma-separated) — required by D1+ and the only server-side addition. `run_type` is an equality match, so+ "everything except heartbeats" is not expressible today. An exclusion param+ keeps the default future-proof: a run type added later shows up by default+ instead of silently vanishing from a hardcoded include-list. Thread it through+ `_runs_query`, `list_runs_page`, `count_runs`, `count_runs_by_status`, the+ `/api/harness/runs` handler, and `HarnessRunsParams.excludeRunType`.++### 4.4 D1 — `watch_runtime` hidden by default++`watch_runtime` rows are watcher-process heartbeats: 3,005 rows (27%), no+session, no agent, no message. Their content (pid, start time) is already shown+in the owning Watch's detail panel.++- Default state of the Runs tab sends `exclude_run_type=watch_runtime`.+- The run-type selector can bring them back explicitly (selecting the+ `watch_runtime` type clears the exclusion).+- The default must be **visible and reversible in the UI**, never a silent+ truncation: the type selector shows which types are being shown.+- Status counts must stay consistent with what is listed (the same `run_type`+ filter feeds `count_runs_by_status`).++## 5. Implementation notes++- **Enrichment chokepoint:** add one `_enrich_runs(rows, conn)` to+ `SQLiteBackgroundTaskStore`, called from `list_runs_page` and `get_run`. It+ performs **two batched queries per page** over the page's distinct ids — one+ for sessions (reusing `_session_summary`'s join, or a batched variant of it),+ one for definitions. No N+1: a 30-row page must not issue 30+ queries. Add a+ test that asserts the query count or at least that a page of N rows resolves+ through a batched path.+- Do **not** enrich `_run_from_row` (a staticmethod with no connection) and do+ not enrich the SSE publish path — `_publish_run_rows_updated` emits a thin+ notification and the UI responds with a full refetch, so there is no+ stale-row-blanking hazard.+- Frontend: reuse `DetailSession`, the existing filter row, and+ `ui/src/components/ui/` primitives. New user-visible strings go through+ `ui/src/i18n/en.json` + `zh.json`.++## 6. Evidence expected++- **Unit (python):** `_enrich_runs` resolves workbench / IM / deleted-session /+ no-session cases; definition name + kind + deleted flag; batched (no N+1);+ `watch_runtime` filtering leaves counts consistent.+- **Unit (ui):** title fallback chain (message → definition name → run type);+ deleted-session renders the label, not a link.+- **Build gate:** `cd ui && npm run build`.+- **Residual manual:** real-browser check of the Runs tab — a watch run's+ session link opens the right chat; the type selector restores heartbeats;+ search + status narrow the list. Deferred to the orchestrator's integration+ pass.diff --git a/storage/background.py b/storage/background.pyindex 9ad8b912b..ae231c813 100644--- a/storage/background.py+++ b/storage/background.py@@ -6,12 +6,12 @@ from contextlib import contextmanagerfrom dataclasses import dataclassfrom datetime import datetime, timedelta, timezonefrom pathlib import Path-from typing import Any, Optional+from typing import Any, Iterable, Optional, Sequencefrom zoneinfo import ZoneInfofrom apscheduler.triggers.cron import CronTriggerfrom apscheduler.triggers.date import DateTrigger-from sqlalchemy import func, insert, or_, select, update+from sqlalchemy import and_, func, insert, or_, select, updatefrom config import pathsfrom storage.db import SqliteInvalidationProbe, create_sqlite_engine@@ -96,6 +96,78 @@ RUN_STATUS_ALIASES: dict[str, str] = {_LIKE_ESCAPE = "\\"DEFINITION_STATUS_COUNTS = ("all", "enabled", "disabled")RUN_STATUS_COUNTS = ("all", "queued", "running", "succeeded", "failed", "canceled")+# run_definitions.definition_type -> the user-facing kind the UI routes on.+# The column says "scheduled"; every surface calls that thing a task.+_DEFINITION_KINDS = {"scheduled": "task", "watch": "watch"}+_BLANK_DEFINITION_SUMMARY: dict[str, Any] = {+ "definition_name": None,+ "definition_kind": None,+ "definition_deleted": False,+}+++@dataclass(frozen=True)+class _RunProjection:+ """One place ``_enrich_runs`` writes resolved, user-visible text onto a run.++ Two consumers have to agree on this list, and kept not agreeing: the+ enrichment that *fills* a projected field, and the search predicate that has+ to *find* what it filled in. Review caught the mismatch one field at a time+ — first the definition name, then the session label — because the list only+ existed as parallel code in two functions, so each fix closed one field and+ left the next one open.++ It exists once now. ``_enrich_runs`` and ``_run_search_predicates`` both+ read it, so a projection added here is searchable by construction rather+ than by remembering, and one added *without* coming through here fails+ ``test_every_projected_label_is_searchable`` instead of costing a review+ round.+ """++ source: str+ """Which batch resolver fills it. Sites sharing a source resolve together in+ one query — that is what keeps a page at a fixed number of round trips+ however many sites there are."""++ payload_key: Optional[str]+ """Where the resolved summary lands. ``None`` merges it into the run row+ itself; a key nests it under that name, and nests ``None`` when the run has+ nothing to resolve there."""++ id_field: str+ id_column: Any+ """The run column naming the row to resolve — payload name and SQL column,+ which differ for the legacy key below."""++ key_fields: tuple[str, ...] = ()+ key_columns: tuple[str, ...] = ()+ """Scope-key fallbacks in precedence order, consulted only when ``id_field``+ resolves to nothing. Column names rather than columns: ``session_key`` is+ stored as ``legacy_session_key``."""+++_RUN_PROJECTIONS: tuple[_RunProjection, ...] = (+ _RunProjection(+ source="session",+ payload_key=None,+ id_field="session_id",+ id_column="session_id",+ key_fields=("session_key", "deliver_key"),+ key_columns=("legacy_session_key", "deliver_key"),+ ),+ _RunProjection(+ source="session",+ payload_key="callback_session",+ id_field="callback_session_id",+ id_column="callback_session_id",+ ),+ _RunProjection(+ source="definition",+ payload_key=None,+ id_field="definition_id",+ id_column="definition_id",+ ),+)_DEFERRED_RUN_EVENT_ROWS_KEY = "avibe.deferred_run_event_rows"_TERMINAL_STATUS_PRIORITY = {"succeeded": 0,@@ -280,12 +352,25 @@ def _defer_run_ids_updated_from_connection(conn: Any, run_ids: list[str]) -> Nondef _like_contains_pattern(value: str) -> str:- escaped = (- value.replace(_LIKE_ESCAPE, _LIKE_ESCAPE + _LIKE_ESCAPE)- .replace("%", _LIKE_ESCAPE + "%")- .replace("_", _LIKE_ESCAPE + "_")- )- return f"%{escaped}%"+ """A contains-match pattern that tolerates whatever whitespace the row shows.++ Rows do not display stored text verbatim: a run title is the message's first+ non-empty line with whitespace runs collapsed, and HTML collapses the rest+ anyway. So the phrase a user reads — and types, or pastes — can differ from+ the column by exactly its spacing, and a literal LIKE finds nothing.++ Each whitespace run in the term becomes a wildcard, which makes the search+ match what is on screen. A single-token term is unchanged.+ """+ def escape(part: str) -> str:+ return (+ part.replace(_LIKE_ESCAPE, _LIKE_ESCAPE + _LIKE_ESCAPE)+ .replace("%", _LIKE_ESCAPE + "%")+ .replace("_", _LIKE_ESCAPE + "_")+ )++ parts = value.split() or [value]+ return "%" + "%".join(escape(part) for part in parts) + "%"def _coalesced_agent_run_metadata(rows: dict[str, Any], run_ids: list[str]) -> dict[str, Any]:@@ -772,6 +857,7 @@ class SQLiteBackgroundTaskStore:*,status: Optional[str] = None,run_type: Optional[str] = None,+ exclude_run_type: Optional[Sequence[str]] = None,agent_name: Optional[str] = None,agent_backend: Optional[str] = None,session_id: Optional[str] = None,@@ -785,6 +871,7 @@ class SQLiteBackgroundTaskStore:stmt = self._runs_query(status=status,run_type=run_type,+ exclude_run_type=exclude_run_type,agent_name=agent_name,agent_backend=agent_backend,session_id=session_id,@@ -800,7 +887,9 @@ class SQLiteBackgroundTaskStore: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._run_from_row(row) for row in conn.execute(stmt).mappings()]+ rows = self._enrich_runs(+ [self._run_from_row(row) for row in conn.execute(stmt).mappings()], conn+ )return page_result_from_limit_plus_one(rows, page_request)def count_runs(@@ -808,6 +897,7 @@ class SQLiteBackgroundTaskStore:*,status: Optional[str] = None,run_type: Optional[str] = None,+ exclude_run_type: Optional[Sequence[str]] = None,agent_name: Optional[str] = None,agent_backend: Optional[str] = None,session_id: Optional[str] = None,@@ -819,6 +909,7 @@ class SQLiteBackgroundTaskStore:stmt = self._runs_query(status=status,run_type=run_type,+ exclude_run_type=exclude_run_type,agent_name=agent_name,agent_backend=agent_backend,session_id=session_id,@@ -835,6 +926,7 @@ class SQLiteBackgroundTaskStore:self,*,run_type: Optional[str] = None,+ exclude_run_type: Optional[Sequence[str]] = None,agent_name: Optional[str] = None,agent_backend: Optional[str] = None,session_id: Optional[str] = None,@@ -845,6 +937,7 @@ class SQLiteBackgroundTaskStore:) -> dict[str, int]:stmt = self._runs_query(run_type=run_type,+ exclude_run_type=exclude_run_type,agent_name=agent_name,agent_backend=agent_backend,session_id=session_id,@@ -865,11 +958,35 @@ class SQLiteBackgroundTaskStore:counts["all"] += valuereturn counts+ def list_run_types(self) -> list[str]:+ """The run types actually present in the ledger, for the type selector.++ The UI knows the types it has words for, but not the ones it does not:+ ``webhook`` is written by the scheduler and preserved by the+ compatibility importer, yet a hardcoded option list omits it, and search+ deliberately skips ``run_type`` because it is a translated chip. Between+ them a row was visible under All and unreachable by any filter.++ Reading the distinct values closes that by construction. Unfiltered on+ purpose — a facet that narrows to the current filter would delete the+ option the user needs to switch to — and index-only over+ ``ix_agent_runs_type_status_created``.+ """+ stmt = (+ select(agent_runs.c.run_type)+ .where(agent_runs.c.run_type.is_not(None))+ .distinct()+ .order_by(agent_runs.c.run_type)+ )+ with self.engine.connect() as conn:+ return [value for (value,) in conn.execute(stmt).all() if value]+def _runs_query(self,*,status: Optional[str] = None,run_type: Optional[str] = None,+ exclude_run_type: Optional[Sequence[str]] = None,agent_name: Optional[str] = None,agent_backend: Optional[str] = None,session_id: Optional[str] = None,@@ -890,6 +1007,15 @@ class SQLiteBackgroundTaskStore:stmt = stmt.where(agent_runs.c.status.in_(_status_query_values(status)))if run_type:stmt = stmt.where(agent_runs.c.run_type == run_type)+ # Exclusion, not an include-list: the Runs tab hides watcher heartbeats by+ # default, and a run type added later must still show up by default rather+ # than silently vanish. Every count path takes the same argument so the+ # status badges never disagree with the rows on screen.+ excluded = [value for value in (exclude_run_type or []) if value]+ if excluded:+ stmt = stmt.where(+ or_(agent_runs.c.run_type.is_(None), agent_runs.c.run_type.notin_(excluded))+ )if agent_name:stmt = stmt.where(agent_runs.c.agent_name == agent_name)if agent_backend:@@ -903,22 +1029,101 @@ class SQLiteBackgroundTaskStore:if created_before:stmt = stmt.where(agent_runs.c.created_at <= created_before)if query:- pattern = _like_contains_pattern(query)- stmt = stmt.where(- or_(- agent_runs.c.id.like(pattern, escape=_LIKE_ESCAPE),- agent_runs.c.definition_id.like(pattern, escape=_LIKE_ESCAPE),- agent_runs.c.agent_name.like(pattern, escape=_LIKE_ESCAPE),- agent_runs.c.session_id.like(pattern, escape=_LIKE_ESCAPE),- agent_runs.c.prompt.like(pattern, escape=_LIKE_ESCAPE),- agent_runs.c.message.like(pattern, escape=_LIKE_ESCAPE),- agent_runs.c.result_text.like(pattern, escape=_LIKE_ESCAPE),- agent_runs.c.error.like(pattern, escape=_LIKE_ESCAPE),- agent_runs.c.stdout.like(pattern, escape=_LIKE_ESCAPE),- agent_runs.c.stderr.like(pattern, escape=_LIKE_ESCAPE),+ stmt = stmt.where(or_(*self._run_search_predicates(_like_contains_pattern(query))))+ return stmt++ @staticmethod+ def _run_search_predicates(pattern: str) -> list[Any]:+ """Everything the Runs search can match, in one place.++ The rule: **a run is findable by every value its row displays.** The+ list projects more than it stores (plan §3) — the originating task/watch+ name and the resolved session labels are joins, not columns — and a list+ that cannot find what it shows on screen is worse than no search at all.++ The projected half is generated from ``_RUN_PROJECTIONS`` rather than+ listed here, so it cannot fall behind the enrichment that produces it:+ a new projection site is matched the moment it is declared. All of it is+ semi-joins/EXISTS inside the one statement — no extra round trip, no+ N+1 — and the count paths inherit it because every caller goes through+ ``_runs_query``.++ Deliberately *not* matched: values that are translated UI labels rather+ than data — the run-type chip ("Agent run"), the status chip, and the+ platform/scope-kind of a session. Each has its own selector, and a+ search box that matched English label text would find nothing for a user+ reading the UI in Chinese.+ """+ def like(column: Any) -> Any:+ return column.like(pattern, escape=_LIKE_ESCAPE)++ # The scope key an IM binding is stored under, rebuilt from the scope row+ # so a resolved channel name can be matched back to the key naming it.+ scope_key = scopes.c.platform + "::" + scopes.c.scope_type + "::" + scopes.c.native_id++ def bound_to_named_scope(key_column: Any) -> Any:+ """Runs whose scope key belongs to a scope whose display name matches.++ Not equality: a threaded key appends "::thread::<id>", which is the+ common shape, not the exception. Not a bare prefix either — Telegram+ "-100123" is a prefix of "-1001234", so the "::" boundary has to be+ part of the comparison or one channel's name finds another's runs.+ """+ return (+ select(1)+ .select_from(scopes)+ .where(like(scopes.c.display_name))+ .where(+ or_(+ key_column == scope_key,+ func.substr(key_column, 1, func.length(scope_key) + 2) == scope_key + "::",+ ))+ .correlate(agent_runs)+ .exists())- return stmt++ # Ids of rows whose own user-visible text matches, per projection source.+ # A workbench session shows its title; an IM one shows the channel's+ # display name, falling back to the native id. Soft-deleted definitions+ # match for the same reason _definition_summaries returns them — the run+ # still displays the name.+ matching_ids = {+ "session": select(agent_sessions.c.id)+ .select_from(SQLiteBackgroundTaskStore._session_scope_join())+ .where(+ or_(+ like(agent_sessions.c.title),+ like(scopes.c.display_name),+ like(scopes.c.native_id),+ )+ ),+ "definition": select(run_definitions.c.id).where(like(run_definitions.c.name)),+ }++ predicates = [+ # Text stored on the run itself.+ like(agent_runs.c.id),+ like(agent_runs.c.agent_name),+ like(agent_runs.c.prompt),+ like(agent_runs.c.message),+ like(agent_runs.c.result_text),+ like(agent_runs.c.error),+ like(agent_runs.c.stdout),+ like(agent_runs.c.stderr),+ ]+ for site in _RUN_PROJECTIONS:+ # The raw id, so pasting one still works, and the projected text it+ # resolves to.+ predicates.append(like(agent_runs.c[site.id_field]))+ predicates.append(agent_runs.c[site.id_column].in_(matching_ids[site.source]))+ for column in site.key_columns:+ # An IM binding stores "<platform>::<kind>::<native_id>", so the+ # raw match covers typing the platform or channel id, and the+ # scope match covers the display name the row actually shows.+ predicates.append(like(agent_runs.c[column]))+ predicates.append(bound_to_named_scope(agent_runs.c[column]))+ return predicatesdef _definitions_query(self,@@ -1001,7 +1206,9 @@ class SQLiteBackgroundTaskStore: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()- return self._run_from_row(row) if row else None+ if row is None:+ return None+ return self._enrich_runs([self._run_from_row(row)], conn)[0]def list_deferred_runs(self) -> list[dict[str, Any]]:"""Return non-terminal Runs carrying a durable terminal intent."""@@ -2323,6 +2530,115 @@ class SQLiteBackgroundTaskStore:)return watch+ def _enrich_runs(self, runs: list[dict[str, Any]], conn: Any) -> list[dict[str, Any]]:+ """Project a page of raw run rows into the fields the Harness UI reads.++ Runs were the last harness payload rendered raw: the row headline was+ the run id and the bound session was an unresolvable hash. This is the+ single chokepoint that gives them the same resolved session summary+ Tasks/Watches already get (``_session_summary`` semantics, so a+ workbench session stays linkable and an IM session stays labelled),+ plus the originating definition's name.++ Batched by construction — three queries for the whole page regardless+ of its size — because the list endpoint pages 30 rows at a time and a+ per-row resolve would be 60+ round trips. Sites are grouped by source+ rather than resolved one at a time, so adding a site to+ ``_RUN_PROJECTIONS`` costs no extra round trip.+ """+ if not runs:+ return runs+ session_sites = [site for site in _RUN_PROJECTIONS if site.source == "session"]+ definition_sites = [site for site in _RUN_PROJECTIONS if site.source == "definition"]+ try:+ summaries = self._session_summaries(+ conn,+ {+ value+ for run in runs+ for site in session_sites+ if (value := run.get(site.id_field))+ },+ )+ # Only sites with no id at all fall back to the legacy key /+ # delivery target, exactly as _session_summary does: a named session+ # that fails to resolve is deleted, not re-labelled as its channel.+ keys = {+ value+ for run in runs+ for site in session_sites+ if not run.get(site.id_field)+ for field in site.key_fields+ if (value := run.get(field))+ }+ key_summaries = self._key_summaries(conn, keys)+ definitions = self._definition_summaries(+ conn,+ {+ value+ for run in runs+ for site in definition_sites+ if (value := run.get(site.id_field))+ },+ )+ for run in runs:+ for site in _RUN_PROJECTIONS:+ if site.source == "session":+ session_id = run.get(site.id_field)+ summary = self._pick_session_summary(+ summaries.get(session_id or ""),+ []+ if session_id+ else [key_summaries.get(run.get(field) or "") for field in site.key_fields],+ )+ else:+ summary = definitions.get(run.get(site.id_field) or "") or _BLANK_DEFINITION_SUMMARY+ if site.payload_key is None:+ run.update(summary)+ else:+ # A nested site says "there is nothing here" with None.+ # The all-null summary means the opposite — the row was+ # referenced and is gone — and the UI renders that+ # differently, so the two must not collapse.+ run[site.payload_key] = summary if run.get(site.id_field) else None+ except Exception:+ # Degrade to the shape the UI expects rather than a KeyError: every+ # site still produces its field, just empty. Derived from the same+ # table, so a new site cannot leave a hole only the error path hits.+ logger.debug("harness run enrichment failed", exc_info=True)+ blanks = {"session": self._blank_session_summary, "definition": lambda: _BLANK_DEFINITION_SUMMARY}+ for run in runs:+ for site in _RUN_PROJECTIONS:+ if site.payload_key is not None:+ run.setdefault(site.payload_key, None)+ continue+ for field, blank in blanks[site.source]().items():+ run.setdefault(field, blank)+ return runs++ @staticmethod+ def _blank_session_summary() -> dict[str, Any]:+ """The all-null summary: no session resolved. A run whose ``session_id``+ is set but lands here names a session row that no longer exists, and the+ UI says so instead of printing the bare id."""+ return {+ "session_title": None,+ "session_platform": None,+ "session_scope_kind": None,+ "session_label": None,+ "session_is_workbench": False,+ }++ @staticmethod+ def _pick_session_summary(+ by_id: Optional[dict[str, Any]], by_key: list[Optional[dict[str, Any]]]+ ) -> dict[str, Any]:+ """``_session_summary``'s precedence, applied to pre-resolved lookups."""+ for candidate in (by_id, *by_key):+ if candidate:+ return dict(candidate)+ return SQLiteBackgroundTaskStore._blank_session_summary()+@staticmethoddef _session_summary(conn: Any,@@ -2340,54 +2656,76 @@ class SQLiteBackgroundTaskStore:fallback for the platform + channel label. Key-based targets are neverlinkable (no concrete session to open). Best-effort: never raises intothe harness list.++ The key fallback applies only when there is no ``session_id`` at all. A+ row that names a session is describing *that* session, and an id that no+ longer resolves means it was deleted — one of the four states the UI+ renders (plan §4.2). Falling through to the delivery key would relabel a+ vanished session as a live IM channel, which matters because a+ ``create_per_run`` execution stores both: its own fresh ``session_id``+ and the definition's ``deliver_key``."""- summary: dict[str, Any] = {- "session_title": None,- "session_platform": None,- "session_scope_kind": None,- "session_label": None,- "session_is_workbench": False,- }try:if session_id:row = conn.execute(- select(- agent_sessions.c.scope_id,- agent_sessions.c.title,- scopes.c.platform,- scopes.c.scope_type,- scopes.c.native_id,- scopes.c.display_name,- )- .select_from(- agent_sessions.join(scopes, scopes.c.id == agent_sessions.c.scope_id, isouter=True)- )- .where(agent_sessions.c.id == session_id)- .limit(1)+ SQLiteBackgroundTaskStore._session_summary_query().where(+ agent_sessions.c.id == session_id+ ).limit(1)).mappings().first()if row is not None:- platform = (row["platform"] or "").strip()- scope_type = (row["scope_type"] or "").strip()- is_workbench = (- row["scope_id"] is None- or platform == "avibe"- or scope_type == "project"- )- summary["session_platform"] = platform or None- summary["session_scope_kind"] = scope_type or None- summary["session_is_workbench"] = is_workbench- summary["session_title"] = row["title"]- summary["session_label"] = (- row["title"] if is_workbench else (row["display_name"] or row["native_id"])- )- return summary- for key in (session_key, deliver_key):- resolved = SQLiteBackgroundTaskStore._summary_from_session_key(conn, key)- if resolved is not None:- return resolved+ return SQLiteBackgroundTaskStore._summary_from_session_row(row)+ else:+ for key in (session_key, deliver_key):+ resolved = SQLiteBackgroundTaskStore._summary_from_session_key(conn, key)+ if resolved is not None:+ return resolvedexcept Exception:logger.debug("harness session summary resolution failed", exc_info=True)- return summary+ return SQLiteBackgroundTaskStore._blank_session_summary()++ @staticmethod+ def _session_scope_join():+ """A session with its scope, outer-joined — a workbench session may have+ no scope row at all. Shared so the summary projection and the search+ predicate that has to find those same labels cannot drift apart."""+ return agent_sessions.join(scopes, scopes.c.id == agent_sessions.c.scope_id, isouter=True)++ @staticmethod+ def _session_summary_query():+ return select(+ agent_sessions.c.id,+ agent_sessions.c.scope_id,+ agent_sessions.c.title,+ scopes.c.platform,+ scopes.c.scope_type,+ scopes.c.native_id,+ scopes.c.display_name,+ ).select_from(SQLiteBackgroundTaskStore._session_scope_join())++ @staticmethod+ def _summary_from_session_row(row: Any) -> dict[str, Any]:+ platform = (row["platform"] or "").strip()+ scope_type = (row["scope_type"] or "").strip()+ is_workbench = row["scope_id"] is None or platform == "avibe" or scope_type == "project"+ return {+ "session_title": row["title"],+ "session_platform": platform or None,+ "session_scope_kind": scope_type or None,+ "session_label": row["title"] if is_workbench else (row["display_name"] or row["native_id"]),+ "session_is_workbench": is_workbench,+ }++ @staticmethod+ def _session_summaries(conn: Any, session_ids: Iterable[str]) -> dict[str, dict[str, Any]]:+ """``_session_summary``'s id branch for many ids in one query. Ids with+ no surviving session row are simply absent from the result."""+ ids = [value for value in dict.fromkeys(session_ids) if value]+ if not ids:+ return {}+ rows = conn.execute(+ SQLiteBackgroundTaskStore._session_summary_query().where(agent_sessions.c.id.in_(ids))+ ).mappings()+ return {row["id"]: SQLiteBackgroundTaskStore._summary_from_session_row(row) for row in rows}@staticmethoddef _summary_from_session_key(conn: Any, key: Optional[str]) -> Optional[dict[str, Any]]:@@ -2395,13 +2733,10 @@ class SQLiteBackgroundTaskStore:into a non-linkable session summary, resolving the channel display name.Shared by the legacy ``session_key`` and the ``create_per_run````deliver_key`` paths. Returns None when ``key`` is empty/malformed."""- if not key:+ parts = SQLiteBackgroundTaskStore._parse_session_key(key)+ if parts is None:return None- parts = key.split("::")- if len(parts) < 3 or not parts[0] or not parts[2]:- return None- platform, scope_type, native_id = parts[0], parts[1], parts[2]- label = native_id+ platform, scope_type, native_id = partsdrow = conn.execute(select(scopes.c.display_name).where(scopes.c.platform == platform)@@ -2409,16 +2744,90 @@ class SQLiteBackgroundTaskStore:.where(scopes.c.native_id == native_id).limit(1)).mappings().first()- if drow is not None and drow["display_name"]:- label = drow["display_name"]+ display_name = drow["display_name"] if drow is not None else None+ return SQLiteBackgroundTaskStore._summary_from_key_parts(parts, display_name)++ @staticmethod+ def _key_summaries(conn: Any, keys: Iterable[str]) -> dict[str, dict[str, Any]]:+ """``_summary_from_session_key`` for many keys in one query."""+ parsed = {key: SQLiteBackgroundTaskStore._parse_session_key(key) for key in dict.fromkeys(keys)}+ triples = {parts for parts in parsed.values() if parts is not None}+ if not triples:+ return {}+ rows = conn.execute(+ select(scopes.c.platform, scopes.c.scope_type, scopes.c.native_id, scopes.c.display_name).where(+ or_(+ *(+ and_(+ scopes.c.platform == platform,+ scopes.c.scope_type == scope_type,+ scopes.c.native_id == native_id,+ )+ for platform, scope_type, native_id in triples+ )+ )+ )+ ).mappings()+ display_names = {+ (row["platform"], row["scope_type"], row["native_id"]): row["display_name"] for row in rows+ }+ return {+ key: SQLiteBackgroundTaskStore._summary_from_key_parts(parts, display_names.get(parts))+ for key, parts in parsed.items()+ if parts is not None+ }++ @staticmethod+ def _parse_session_key(key: Optional[str]) -> Optional[tuple[str, str, str]]:+ if not key:+ return None+ parts = key.split("::")+ if len(parts) < 3 or not parts[0] or not parts[2]:+ return None+ return parts[0], parts[1], parts[2]++ @staticmethod+ def _summary_from_key_parts(+ parts: tuple[str, str, str], display_name: Optional[str]+ ) -> dict[str, Any]:+ platform, scope_type, native_id = partsreturn {"session_title": None,"session_platform": platform,"session_scope_kind": scope_type,- "session_label": label,+ "session_label": display_name or native_id,"session_is_workbench": False,}+ @staticmethod+ def _definition_summaries(conn: Any, definition_ids: Iterable[str]) -> dict[str, dict[str, Any]]:+ """Name the task/watch a run came from, in one query.++ Soft-deleted definitions are included on purpose: a run outlives the+ definition that produced it, and "from 夜间巡检 (deleted)" is more+ useful than an orphan id. ``definition_deleted`` lets the UI drop the+ link instead of pointing at a row that is gone.+ """+ ids = [value for value in dict.fromkeys(definition_ids) if value]+ if not ids:+ return {}+ rows = conn.execute(+ select(+ run_definitions.c.id,+ run_definitions.c.name,+ run_definitions.c.definition_type,+ run_definitions.c.deleted_at,+ ).where(run_definitions.c.id.in_(ids))+ ).mappings()+ return {+ row["id"]: {+ "definition_name": row["name"],+ "definition_kind": _DEFINITION_KINDS.get(row["definition_type"]),+ "definition_deleted": row["deleted_at"] is not None,+ }+ for row in rows+ }+@staticmethoddef _message_payload_json(payload: dict[str, Any]) -> Optional[str]:return SQLiteBackgroundTaskStore._payload_json(payload, "message_payload", "message_payload_json")diff --git a/tests/test_harness_run_projection.py b/tests/test_harness_run_projection.pynew file mode 100644index 000000000..2f32ee39e--- /dev/null+++ b/tests/test_harness_run_projection.py@@ -0,0 +1,737 @@+"""Harness Runs payload projection: resolved session, originating definition.++Runs were the last harness list rendered straight from the raw ``agent_runs``+row — the headline was a run-id hash and the bound session was an unresolvable+string. ``SQLiteBackgroundTaskStore._enrich_runs`` closes that gap with the same+session summary Tasks/Watches already get, so a workbench run links to its chat,+an IM run shows its channel, and a run whose session was deleted says so.++See ``docs/plans/harness-runs-readability.md`` §3 (frozen contract) and §5.+"""++from __future__ import annotations++import sys+from pathlib import Path++from sqlalchemy import event, update++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from storage import workbench_sessions_service+from storage.background import SQLiteBackgroundTaskStore+from storage.db import create_sqlite_engine+from storage.models import agent_runs, agent_sessions, scope_settings+from storage.sessions_service import SQLiteSessionsService+from storage.settings_service import upsert_scope++NOW = "2026-07-26T00:00:00Z"++# Tables the projection reads. Counting statements that touch them separates+# enrichment cost from the list query itself (which only reads agent_runs).+_ENRICHMENT_TABLES = ("agent_sessions", "scopes", "run_definitions")+++def _build_schema(db_path: Path) -> None:+ SQLiteSessionsService(db_path).close()+++def _make_workbench_session(conn, tmp_path: Path, native_id: str, title: str) -> str:+ scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id=native_id, now=NOW)+ conn.execute(+ scope_settings.insert().values(+ scope_id=scope_id,+ enabled=1,+ role=None,+ workdir=str(tmp_path),+ agent_name=None,+ agent_backend=None,+ agent_variant=None,+ model=None,+ reasoning_effort=None,+ require_mention=None,+ settings_version=1,+ settings_json="{}",+ created_at=NOW,+ updated_at=NOW,+ )+ )+ session = workbench_sessions_service.create_session(+ conn, scope_id=scope_id, agent_backend="claude", agent_name="default"+ )+ conn.execute(update(agent_sessions).where(agent_sessions.c.id == session["id"]).values(title=title))+ return session["id"]+++def _run(run_id: str, **overrides) -> dict:+ payload = {+ "id": run_id,+ "run_type": "agent_run",+ "status": "succeeded",+ "created_at": NOW,+ "updated_at": NOW,+ }+ payload.update(overrides)+ return payload+++def _enrichment_query_count(store: SQLiteBackgroundTaskStore, call) -> int:+ """Statements the projection issues against the tables it joins."""+ seen: list[str] = []++ def _record(conn, cursor, statement, parameters, context, executemany):+ lowered = statement.lower()+ if any(table in lowered for table in _ENRICHMENT_TABLES):+ seen.append(statement)++ event.listen(store.engine, "before_cursor_execute", _record)+ try:+ call()+ finally:+ event.remove(store.engine, "before_cursor_execute", _record)+ return len(seen)+++def test_run_payload_resolves_every_session_state(tmp_path: Path) -> None:+ """Workbench / IM / deleted / unbound — the four states §4.2 renders."""+ db_path = tmp_path / "vibe.sqlite"+ _build_schema(db_path)+ engine = create_sqlite_engine(db_path)+ try:+ with engine.begin() as conn:+ workbench_id = _make_workbench_session(conn, tmp_path, "proj_runs", "重构鉴权模块")+ upsert_scope(+ conn, platform="slack", scope_type="channel", native_id="C0123", now=NOW, display_name="#dev-ops"+ )+ finally:+ engine.dispose()++ store = SQLiteBackgroundTaskStore(db_path)+ try:+ store.enqueue_run(_run("run_wb", session_id=workbench_id, message="巡检构建产物"))+ store.enqueue_run(_run("run_im", session_key="slack::channel::C0123", message="周报推送"))+ store.enqueue_run(_run("run_gone", session_id="ses_deleted_forever", message="orphan"))+ store.enqueue_run(_run("run_none", message="no session at all"))+ runs = {run["id"]: run for run in store.list_runs_page(page_request=None).items}+ finally:+ store.close()++ workbench = runs["run_wb"]+ assert workbench["session_is_workbench"] is True+ assert workbench["session_title"] == "重构鉴权模块"+ assert workbench["session_label"] == "重构鉴权模块"+ assert workbench["session_platform"] == "avibe"+ assert workbench["session_scope_kind"] == "project"++ im = runs["run_im"]+ assert im["session_is_workbench"] is False # IM transcripts are scope-keyed; never linked+ assert im["session_platform"] == "slack"+ assert im["session_label"] == "#dev-ops" # display name, not the raw channel id++ # A run outlives its session. The summary stays all-null so the UI can say+ # "session deleted" instead of printing an id that opens nothing.+ deleted = runs["run_gone"]+ assert deleted["session_id"] == "ses_deleted_forever"+ assert deleted["session_label"] is None+ assert deleted["session_title"] is None+ assert deleted["session_is_workbench"] is False++ unbound = runs["run_none"]+ assert unbound["session_id"] is None+ assert unbound["session_label"] is None+++def test_run_payload_falls_back_to_deliver_key(tmp_path: Path) -> None:+ """``create_per_run`` runs mint a session per fire, so the target scope lives+ in ``deliver_key`` — same precedence as ``_session_summary``."""+ db_path = tmp_path / "vibe.sqlite"+ _build_schema(db_path)+ engine = create_sqlite_engine(db_path)+ try:+ with engine.begin() as conn:+ upsert_scope(+ conn, platform="feishu", scope_type="channel", native_id="oc_9", now=NOW, display_name="值班群"+ )+ finally:+ engine.dispose()++ store = SQLiteBackgroundTaskStore(db_path)+ try:+ store.enqueue_run(_run("run_deliver", deliver_key="feishu::channel::oc_9", message="hi"))+ run = store.get_run("run_deliver")+ finally:+ store.close()++ assert run["session_platform"] == "feishu"+ assert run["session_label"] == "值班群"+ assert run["session_is_workbench"] is False+++def test_run_payload_names_originating_definition(tmp_path: Path) -> None:+ db_path = tmp_path / "vibe.sqlite"+ _build_schema(db_path)++ store = SQLiteBackgroundTaskStore(db_path)+ try:+ store.upsert_watch(+ {+ "id": "watch_ci",+ "name": "CI 红灯监听",+ "command": "true",+ "prompt": "hello",+ "enabled": True,+ "created_at": NOW,+ "updated_at": NOW,+ }+ )+ store.upsert_scheduled_task(+ {+ "id": "task_nightly",+ "name": "夜间巡检",+ "prompt": "hello",+ "schedule_type": "cron",+ "cron": "0 3 * * *",+ "timezone": "UTC",+ "enabled": True,+ "created_at": NOW,+ "updated_at": NOW,+ }+ )+ store.remove_task("task_nightly") # soft delete; the run must still name it++ store.enqueue_run(_run("run_w", run_type="watch", definition_id="watch_ci"))+ store.enqueue_run(_run("run_t", run_type="scheduled", definition_id="task_nightly"))+ store.enqueue_run(_run("run_orphan", definition_id="definition_that_never_existed"))+ store.enqueue_run(_run("run_free"))+ runs = {run["id"]: run for run in store.list_runs_page(page_request=None).items}+ finally:+ store.close()++ assert runs["run_w"]["definition_name"] == "CI 红灯监听"+ assert runs["run_w"]["definition_kind"] == "watch"+ assert runs["run_w"]["definition_deleted"] is False++ # definition_type is "scheduled" in the column; every surface calls it a task.+ assert runs["run_t"]["definition_name"] == "夜间巡检"+ assert runs["run_t"]["definition_kind"] == "task"+ assert runs["run_t"]["definition_deleted"] is True # so the UI drops the link++ for orphan in ("run_orphan", "run_free"):+ assert runs[orphan]["definition_name"] is None+ assert runs[orphan]["definition_kind"] is None+ assert runs[orphan]["definition_deleted"] is False+++def test_run_payload_resolves_callback_session(tmp_path: Path) -> None:+ db_path = tmp_path / "vibe.sqlite"+ _build_schema(db_path)+ engine = create_sqlite_engine(db_path)+ try:+ with engine.begin() as conn:+ reporter = _make_workbench_session(conn, tmp_path, "proj_cb", "编排会话")+ finally:+ engine.dispose()++ store = SQLiteBackgroundTaskStore(db_path)+ try:+ store.enqueue_run(_run("run_cb", callback_session_id=reporter, message="delegated work"))+ store.enqueue_run(_run("run_no_cb", message="no callback"))+ runs = {run["id"]: run for run in store.list_runs_page(page_request=None).items}+ finally:+ store.close()++ callback = runs["run_cb"]["callback_session"]+ assert callback["session_title"] == "编排会话"+ assert callback["session_is_workbench"] is True+ assert runs["run_no_cb"]["callback_session"] is None+++def test_get_run_enriches_identically_to_the_list(tmp_path: Path) -> None:+ db_path = tmp_path / "vibe.sqlite"+ _build_schema(db_path)+ engine = create_sqlite_engine(db_path)+ try:+ with engine.begin() as conn:+ session_id = _make_workbench_session(conn, tmp_path, "proj_detail", "详情会话")+ finally:+ engine.dispose()++ store = SQLiteBackgroundTaskStore(db_path)+ try:+ store.upsert_watch(+ {+ "id": "watch_detail",+ "name": "磁盘水位",+ "command": "true",+ "prompt": "hello",+ "enabled": True,+ "created_at": NOW,+ "updated_at": NOW,+ }+ )+ store.enqueue_run(+ _run("run_detail", run_type="watch", definition_id="watch_detail", session_id=session_id)+ )+ listed = store.list_runs_page(page_request=None).items[0]+ detail = store.get_run("run_detail")+ finally:+ store.close()++ projected = ("session_title", "session_label", "session_is_workbench", "definition_name", "definition_kind")+ assert {key: detail[key] for key in projected} == {key: listed[key] for key in projected}+++def test_run_enrichment_is_batched(tmp_path: Path) -> None:+ """No N+1: doubling the page must not double the projection's queries."""+ db_path = tmp_path / "vibe.sqlite"+ _build_schema(db_path)+ engine = create_sqlite_engine(db_path)+ session_ids: list[str] = []+ try:+ with engine.begin() as conn:+ for index in range(24):+ session_ids.append(_make_workbench_session(conn, tmp_path, f"proj_{index}", f"会话 {index}"))+ finally:+ engine.dispose()++ store = SQLiteBackgroundTaskStore(db_path)+ try:+ for index, session_id in enumerate(session_ids):+ store.upsert_watch(+ {+ "id": f"watch_{index}",+ "name": f"监听 {index}",+ "command": "true",+ "prompt": "hello",+ "enabled": True,+ "created_at": NOW,+ "updated_at": NOW,+ }+ )+ store.enqueue_run(+ _run(+ f"run_{index:02d}",+ run_type="watch",+ definition_id=f"watch_{index}",+ session_id=session_id,+ session_key=f"slack::channel::C{index}",+ )+ )++ def _page(limit: int):+ from storage.pagination import make_page_request++ return lambda: store.list_runs_page(page_request=make_page_request(page=1, limit=limit))++ small = _enrichment_query_count(store, _page(6))+ large = _enrichment_query_count(store, _page(24))+ page = store.list_runs_page(page_request=None)+ finally:+ store.close()++ assert small == large, f"query count grew with page size ({small} → {large}): the projection is N+1"+ assert large <= 4, f"expected a handful of batched queries, got {large}"+ # The batch actually resolved every row — a constant query count would also+ # be satisfied by resolving nothing.+ assert len(page.items) == 24+ assert all(run["session_title"] and run["definition_name"] for run in page.items)+++def test_exclude_run_type_keeps_list_and_counts_consistent(tmp_path: Path) -> None:+ """D1 hides watcher heartbeats by default; the badges must agree with the rows."""+ db_path = tmp_path / "vibe.sqlite"+ _build_schema(db_path)++ store = SQLiteBackgroundTaskStore(db_path)+ try:+ for index in range(5):+ store.enqueue_run(_run(f"noise_{index}", run_type="watch_runtime", status="succeeded"))+ store.enqueue_run(_run("real_ok", run_type="watch", status="succeeded"))+ store.enqueue_run(_run("real_bad", run_type="agent_run", status="failed"))+ # A run type nobody has heard of yet must survive the default exclusion.+ store.enqueue_run(_run("future", run_type="brand_new_kind", status="succeeded"))++ unfiltered = store.count_runs_by_status()+ listed = store.list_runs_page(exclude_run_type=["watch_runtime"], page_request=None).items+ counts = store.count_runs_by_status(exclude_run_type=["watch_runtime"])+ total = store.count_runs(exclude_run_type=["watch_runtime"])+ failed_only = store.list_runs_page(+ status="failed", exclude_run_type=["watch_runtime"], page_request=None+ ).items+ heartbeats = store.list_runs_page(run_type="watch_runtime", page_request=None).items+ finally:+ store.close()++ assert unfiltered["all"] == 8 # nothing is deleted, only hidden+ assert {run["id"] for run in listed} == {"real_ok", "real_bad", "future"}+ assert total == len(listed) == 3+ assert counts["all"] == 3+ assert counts["succeeded"] == 2+ assert counts["failed"] == 1+ assert [run["id"] for run in failed_only] == ["real_bad"]+ # Selecting the type explicitly brings the hidden rows back — reversible, not truncated.+ assert len(heartbeats) == 5+++# Projected values that are UI vocabulary rather than the user's own text: the+# UI renders each through i18n as an icon or a chip, and each has its own filter+# control. Matching the raw English token would find nothing for someone reading+# the interface in Chinese, so search deliberately skips them.+# ``request_type`` is the legacy alias of the ``run_type`` column — same value,+# same translated chip, so it is excluded for the same reason.+_UI_VOCABULARY = {"request_type", "session_platform", "session_scope_kind", "definition_kind"}+++def _projected_text(payload: dict) -> dict[str, str]:+ """Every user-visible string on a run row that ``_enrich_runs`` invented.++ Derived by subtracting the ``agent_runs`` columns from the payload rather+ than by listing field names, so a projection added later turns up here on+ its own. Nested objects (``callback_session``) are walked, because a label+ is no less visible for being one level down.+ """+ stored = {column.name for column in agent_runs.columns}+ found: dict[str, str] = {}++ def walk(node: dict, prefix: str) -> None:+ for key, value in node.items():+ path = f"{prefix}{key}"+ if isinstance(value, dict):+ walk(value, f"{path}.")+ elif isinstance(value, str) and value and key not in stored and key not in _UI_VOCABULARY:+ found[path] = value++ walk(payload, "")+ return found+++def test_every_projected_label_is_searchable(tmp_path: Path) -> None:+ """The loop-ender.++ Review found search missing one projected field per round — the definition+ name, then the session label, with ``callback_session`` next in line —+ because the predicate list and the enrichment list were maintained by hand+ in two places. This test checks no list of names. It enriches a row, asks+ the payload which strings the projection invented, and requires every one of+ them to be findable by typing it. A projection added without a matching+ predicate fails here instead of costing a review round.+ """+ db_path = tmp_path / "vibe.sqlite"+ _build_schema(db_path)+ engine = create_sqlite_engine(db_path)+ try:+ with engine.begin() as conn:+ bound = _make_workbench_session(conn, tmp_path, "proj_probe", "重构鉴权模块")+ reporter = _make_workbench_session(conn, tmp_path, "proj_reporter", "编排调度会话")+ upsert_scope(+ conn, platform="slack", scope_type="channel", native_id="C0123", now=NOW, display_name="#dev-ops"+ )+ finally:+ engine.dispose()++ store = SQLiteBackgroundTaskStore(db_path)+ try:+ store.upsert_watch(+ {+ "id": "watch_probe",+ "name": "磁盘水位巡检",+ "command": "true",+ "prompt": "hello",+ "enabled": True,+ "created_at": NOW,+ "updated_at": NOW,+ }+ )+ # One run touching every projection site at once, and one on the+ # key-bound path, which resolves a label the run never stores.+ store.enqueue_run(+ _run(+ "run_probe",+ run_type="watch",+ definition_id="watch_probe",+ session_id=bound,+ callback_session_id=reporter,+ )+ )+ store.enqueue_run(_run("run_keyed", session_key="slack::channel::C0123::thread::1712.9"))+ payloads = {run["id"]: run for run in store.list_runs_page(page_request=None).items}+ projected = {run_id: _projected_text(payload) for run_id, payload in payloads.items()}+ hits = {+ (run_id, path): _search_run_ids(store, value)+ for run_id, fields in projected.items()+ for path, value in fields.items()+ }+ finally:+ store.close()++ # The walk is not vacuous: it reached every site, including the nested one.+ # Asserted against the fixture's values, not against field names, so this+ # keeps holding when a site is renamed or a new one appears.+ planted = {"重构鉴权模块", "编排调度会话", "磁盘水位巡检", "#dev-ops"}+ seen = {value for fields in projected.values() for value in fields.values()}+ assert planted <= seen, f"projection walk missed {planted - seen}"++ # The whole point: every invented string finds its own row, and only it.+ for (run_id, path), found in sorted(hits.items()):+ assert found == {run_id}, f"{run_id}.{path} is displayed but search returns {found or 'nothing'}"++ # A stale exclusion is a bug too — if one of these stops being projected, the+ # reason to skip it went with it, and the next reader inherits a name that+ # explains nothing. Checked against the raw payload: `projected` is the+ # already-filtered view, so asking it would only confirm the filter ran.+ present = {key for payload in payloads.values() for key in payload}+ present |= {+ key+ for payload in payloads.values()+ for value in payload.values()+ if isinstance(value, dict)+ for key in value+ }+ assert _UI_VOCABULARY <= present, f"search exclusion no longer projected: {_UI_VOCABULARY - present}"+++def _search_run_ids(store: SQLiteBackgroundTaskStore, term: str) -> set[str]:+ """Rows for a search term, cross-checked against the two count paths the+ status badges read. All three go through ``_runs_query``, so a predicate that+ reaches the list but not the counts is a bug the badges would expose."""+ found = store.list_runs_page(query=term, page_request=None).items+ total = store.count_runs(query=term)+ assert store.count_runs_by_status(query=term)["all"] == total == len(found), (+ f"list/count disagreement for {term!r}"+ )+ return {run["id"] for run in found}+++def test_search_finds_runs_by_the_session_label_they_display(tmp_path: Path) -> None:+ """§4.2 renders a resolved session label, not the stored id/key. Searching+ that label has to find the row — the id it is stored under is exactly the+ string the projection exists to stop showing the user."""+ db_path = tmp_path / "vibe.sqlite"+ _build_schema(db_path)+ engine = create_sqlite_engine(db_path)+ try:+ with engine.begin() as conn:+ workbench_id = _make_workbench_session(conn, tmp_path, "proj_search", "重构鉴权模块")+ other_id = _make_workbench_session(conn, tmp_path, "proj_other", "无关会话")+ upsert_scope(+ conn, platform="slack", scope_type="channel", native_id="C0123", now=NOW, display_name="#dev-ops"+ )+ # Prefix-collides with the channel above on the native id, and its+ # own native id is a prefix of the Telegram pair below.+ upsert_scope(+ conn, platform="telegram", scope_type="channel", native_id="-100123", now=NOW, display_name="值班群"+ )+ upsert_scope(+ conn,+ platform="telegram",+ scope_type="channel",+ native_id="-1001234",+ now=NOW,+ display_name="产品群",+ )+ finally:+ engine.dispose()++ store = SQLiteBackgroundTaskStore(db_path)+ try:+ store.enqueue_run(_run("run_wb", session_id=workbench_id))+ store.enqueue_run(_run("run_other", session_id=other_id))+ store.enqueue_run(_run("run_im", session_key="slack::channel::C0123"))+ # The common shape: a threaded key, whose scope key is only a prefix.+ store.enqueue_run(_run("run_thread", session_key="slack::channel::C0123::thread::1712.9"))+ store.enqueue_run(_run("run_duty", session_key="telegram::channel::-100123"))+ store.enqueue_run(_run("run_product", session_key="telegram::channel::-1001234"))+ # No session_key at all — create_per_run mints one per fire, so the label+ # comes from deliver_key.+ store.enqueue_run(_run("run_deliver", deliver_key="slack::channel::C0123"))++ by_title = _search_run_ids(store, "重构鉴权")+ by_display_name = _search_run_ids(store, "dev-ops")+ by_native_id = _search_run_ids(store, "C0123")+ by_duty = _search_run_ids(store, "值班群")+ by_product = _search_run_ids(store, "产品群")+ by_nothing = _search_run_ids(store, "no-such-channel-anywhere")+ labels = {run["id"]: run["session_label"] for run in store.list_runs_page(page_request=None).items}+ finally:+ store.close()++ # A workbench run is found by the title the row shows, and does not drag in+ # the other workbench run — the semi-join filters, it does not just exist.+ assert by_title == {"run_wb"}++ # Every run bound to #dev-ops, however it is bound: session-keyed, threaded,+ # or deliver-keyed. The display name is a scopes column the run never stores.+ assert by_display_name == {"run_im", "run_thread", "run_deliver"}+ # Typing the raw id still works (it is in the key), and finds the same set.+ assert by_native_id == by_display_name++ # Prefix collision: "-100123" is a prefix of "-1001234". Matching on the key+ # prefix alone would make 值班群 return the 产品群 run as well.+ assert by_duty == {"run_duty"}+ assert by_product == {"run_product"}++ assert by_nothing == set()++ # The searched strings are the rendered ones — otherwise this test could+ # pass while the UI displays something else entirely.+ assert labels["run_wb"] == "重构鉴权模块"+ assert labels["run_thread"] == labels["run_deliver"] == "#dev-ops"+ assert (labels["run_duty"], labels["run_product"]) == ("值班群", "产品群")+++def test_search_finds_runs_by_the_definition_name_they_display(tmp_path: Path) -> None:+ """A textless run shows its task/watch name as the headline (§4.1), so that+ name has to be searchable — otherwise the list cannot find what it shows."""+ db_path = tmp_path / "vibe.sqlite"+ _build_schema(db_path)++ store = SQLiteBackgroundTaskStore(db_path)+ try:+ store.upsert_watch(+ {+ "id": "watch_disk",+ "name": "磁盘水位巡检",+ "command": "true",+ "prompt": "hello",+ "enabled": True,+ "created_at": NOW,+ "updated_at": NOW,+ }+ )+ store.upsert_scheduled_task(+ {+ "id": "task_digest",+ "name": "夜间日报",+ "prompt": "hello",+ "schedule_type": "cron",+ "cron": "0 3 * * *",+ "timezone": "UTC",+ "enabled": True,+ "created_at": NOW,+ "updated_at": NOW,+ }+ )+ store.remove_task("task_digest") # the run still displays the name, so it stays searchable++ # No message/prompt text: the name is the only thing these rows show.+ store.enqueue_run(_run("run_disk", run_type="watch_runtime", definition_id="watch_disk"))+ store.enqueue_run(_run("run_digest", run_type="task_run", definition_id="task_digest"))+ store.enqueue_run(_run("run_other", message="unrelated work"))++ by_watch_name = _search_run_ids(store, "磁盘水位")+ by_deleted_task_name = _search_run_ids(store, "夜间日报")+ by_message = _search_run_ids(store, "unrelated")+ by_nothing = _search_run_ids(store, "no-such-text-anywhere")+ headlines = {+ run["id"]: run["definition_name"]+ for run in store.list_runs_page(page_request=None).items+ }+ finally:+ store.close()++ assert by_watch_name == {"run_disk"}+ assert by_deleted_task_name == {"run_digest"} # soft-deleted, still displayed, still findable+ assert by_message == {"run_other"} # the raw-column predicate still works+ # A definition-less run must not be dragged in by the semi-join, and an+ # unmatched term must still return nothing (the predicate is not always-true).+ assert by_nothing == set()++ # The thing searched for is the thing rendered: every hit's search term is+ # the headline the row actually shows.+ assert headlines["run_disk"] == "磁盘水位巡检"+ assert headlines["run_digest"] == "夜间日报"+++def test_a_named_but_missing_session_stays_deleted(tmp_path: Path) -> None:+ """A run that names a session is describing *that* session.++ A ``create_per_run`` execution stores both its own fresh ``session_id`` and+ the definition's ``deliver_key``. When that session is later deleted, the+ key fallback used to resolve the delivery channel and fill+ ``session_platform``, so the row read as a live IM binding — the UI's+ "deleted" state (plan §4.2) was unreachable for exactly the runs that reach+ it most often. The fallback is for runs that never named a session.+ """+ db_path = tmp_path / "vibe.sqlite"+ _build_schema(db_path)+ engine = create_sqlite_engine(db_path)+ try:+ with engine.begin() as conn:+ upsert_scope(+ conn, platform="slack", scope_type="channel", native_id="C9", now=NOW, display_name="#releases"+ )+ finally:+ engine.dispose()++ deliver_key = "slack::channel::C9"+ store = SQLiteBackgroundTaskStore(db_path)+ try:+ store.enqueue_run(_run("run_gone", session_id="sess_deleted", deliver_key=deliver_key))+ store.enqueue_run(_run("run_keyonly", deliver_key=deliver_key))+ rows = {run["id"]: run for run in store.list_runs_page(page_request=None).items}++ gone = rows["run_gone"]+ assert gone["session_id"] == "sess_deleted", "the id the user needs to see is still on the row"+ assert gone["session_platform"] is None, "a deleted session must not borrow the delivery channel"+ assert gone["session_label"] is None+ assert gone["session_title"] is None++ # The same key on a run that never named a session still resolves --+ # this is the create_per_run definition's own label, not a fallback.+ assert rows["run_keyonly"]["session_label"] == "#releases"+ assert rows["run_keyonly"]["session_platform"] == "slack"++ # Both are still findable by the channel they deliver to.+ assert _search_run_ids(store, "#releases") == {"run_gone", "run_keyonly"}+ finally:+ store.close()+++def test_search_matches_the_whitespace_the_row_displays(tmp_path: Path) -> None:+ """Row titles collapse whitespace; the stored message does not.++ ``runRowTitle`` shows the message's first non-empty line with runs of+ whitespace collapsed, and HTML would collapse them anyway. So the phrase on+ screen can differ from the column by its spacing, and a literal LIKE finds+ nothing for a user typing what they just read.+ """+ db_path = tmp_path / "vibe.sqlite"+ _build_schema(db_path)+ store = SQLiteBackgroundTaskStore(db_path)+ try:+ store.enqueue_run(_run("run_spaced", message="Summarize\tyesterday's PRs\nand the rest"))+ store.enqueue_run(_run("run_other", message="Nothing to see"))++ # Typed exactly as the row renders it.+ assert _search_run_ids(store, "Summarize yesterday's PRs") == {"run_spaced"}+ # A single token is unaffected by the flexible pattern.+ assert _search_run_ids(store, "Summarize") == {"run_spaced"}+ # Wildcards in the term are still escaped, not honoured as syntax.+ assert _search_run_ids(store, "Summarize%PRs") == set()+ finally:+ store.close()+++def test_run_types_facet_reports_what_the_ledger_holds(tmp_path: Path) -> None:+ """The selector's options come from the data, not only from a hardcoded list.++ ``webhook`` is written by the scheduler and preserved by the compatibility+ importer, but the UI's list omitted it — and search skips ``run_type`` on+ purpose (it is a translated chip), so those rows were visible under All and+ reachable by no filter at all.+ """+ db_path = tmp_path / "vibe.sqlite"+ _build_schema(db_path)+ store = SQLiteBackgroundTaskStore(db_path)+ try:+ assert store.list_run_types() == []+ for index, run_type in enumerate(["watch", "webhook", "agent_run", "webhook"]):+ store.enqueue_run(_run(f"run_{index}", run_type=run_type))+ # Distinct and ordered, so the option list is stable between loads.+ assert store.list_run_types() == ["agent_run", "watch", "webhook"]+ # Unfiltered on purpose: a facet narrowed to the current filter would+ # remove the very option the user needs to switch to.+ assert store.count_runs(run_type="webhook") == 2+ assert store.list_run_types() == ["agent_run", "watch", "webhook"]+ finally:+ store.close()diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.pyindex 862005e38..2cb1fd1cf 100644--- a/tests/test_ui_server_fastapi.py+++ b/tests/test_ui_server_fastapi.py@@ -332,6 +332,12 @@ def test_harness_routes_page_filter_and_return_counts(monkeypatch, tmp_path):assert watches["has_more"] is Trueassert [item["id"] for item in runs["runs"]] == ["run-3", "run-2"]assert runs["total"] == 4+ # The type facet, so the selector can offer a type the UI has no name for.+ # Asserted on both endpoints because the Runs tab loads through either one+ # and a facet present on only one of them is a selector that comes and goes.+ assert runs["run_types"] == ["watch"]+ bootstrap_runs = client.get("/api/harness/bootstrap?tab=runs&page=1&limit=2").get_json()+ assert bootstrap_runs["page"]["run_types"] == runs["run_types"]assert runs["counts"]["queued"] == 1assert runs["counts"]["running"] == 1assert runs["counts"]["succeeded"] == 1diff --git a/ui/src/components/workbench/HarnessPage.test.tsx b/ui/src/components/workbench/HarnessPage.test.tsxnew file mode 100644index 000000000..59018bdd9--- /dev/null+++ b/ui/src/components/workbench/HarnessPage.test.tsx@@ -0,0 +1,226 @@+import { createInstance } from 'i18next';+import type { ReactElement } from 'react';+import { renderToStaticMarkup } from 'react-dom/server';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { MemoryRouter } from 'react-router-dom';+import { describe, expect, it } from 'vitest';++import en from '../../i18n/en.json';+import type { HarnessRun, HarnessSessionSummary } from '../../context/ApiContext';+import { DetailSession, RunTriggerChip } from './HarnessPage';+import { RUN_TYPES, harnessSessionState, runRowTitle, runStatusLabel, runTypeLabel, runTypeOptions } from './harnessRuns';++const i18n = createInstance();+void i18n.use(initReactI18next).init({+ lng: 'en',+ fallbackLng: 'en',+ resources: { en: { translation: en } },+ interpolation: { escapeValue: false },+});++const render = (ui: ReactElement) =>+ renderToStaticMarkup(+ <I18nextProvider i18n={i18n}>+ <MemoryRouter>{ui}</MemoryRouter>+ </I18nextProvider>,+ );++const NO_SESSION: HarnessSessionSummary = {+ session_title: null,+ session_platform: null,+ session_scope_kind: null,+ session_label: null,+ session_is_workbench: false,+};++const run = (overrides: Partial<HarnessRun>): HarnessRun =>+ ({+ id: 'run-1',+ status: 'succeeded',+ run_type: 'agent_run',+ message: null,+ prompt: null,+ definition_id: null,+ definition_name: null,+ definition_kind: null,+ definition_deleted: false,+ session_id: null,+ callback_session: null,+ ...NO_SESSION,+ ...overrides,+ }) as HarnessRun;++// Translation-free stand-in: proves the mappers pick the right key without+// depending on the copy.+const key = (k: string) => k;++describe('runRowTitle', () => {+ it("uses the message's first non-empty line, whitespace collapsed", () => {+ expect(+ runRowTitle({ message: '\n\n Summarize yesterday\'s PRs \nmore detail', prompt: null, definition_name: 'Digest' }, 'Agent run'),+ ).toBe("Summarize yesterday's PRs");+ });++ it('falls back to prompt when the run carries no message', () => {+ expect(runRowTitle({ message: null, prompt: 'check CI', definition_name: 'Digest' }, 'Agent run')).toBe('check CI');+ });++ it('falls back to the originating definition name when there is no text', () => {+ expect(runRowTitle({ message: ' \n ', prompt: null, definition_name: 'Nightly digest' }, 'Agent run')).toBe(+ 'Nightly digest',+ );+ });++ it('falls back to the run-type label when nothing else names the run', () => {+ expect(runRowTitle({ message: null, prompt: null, definition_name: null }, 'Watcher heartbeat')).toBe(+ 'Watcher heartbeat',+ );+ });++ it('never slices the title — truncation is the row layout\'s job', () => {+ const long = 'x'.repeat(400);+ expect(runRowTitle({ message: long, prompt: null, definition_name: null }, 'Agent run')).toBe(long);+ });+});++describe('runTypeLabel / runStatusLabel', () => {+ it('maps known internal values to translation keys', () => {+ expect(runTypeLabel('hook_send', key)).toBe('harness.runType.hook_send');+ expect(runTypeLabel(null, key)).toBe('harness.runType.unknown');+ expect(runStatusLabel('canceled', key)).toBe('harness.runStatus.canceled');+ });++ it('shows an unknown value rather than blanking it out', () => {+ expect(runTypeLabel('brand_new_kind', key)).toBe('brand_new_kind');+ expect(runStatusLabel('weird', key)).toBe('weird');+ });++ it('never leaks a raw run_type into user copy for the types the store writes', () => {+ // Driven off RUN_TYPES rather than a copy of it, so declaring a type+ // without translating it fails here.+ for (const value of RUN_TYPES) {+ expect(i18n.t(`harness.runType.${value}`)).not.toBe(`harness.runType.${value}`);+ }+ });+});++describe('runTypeOptions', () => {+ it('offers a type the ledger holds that the UI has no name for', () => {+ // Otherwise the row shows under All and no filter can isolate it: search+ // skips run_type on purpose, so the selector is the only way in.+ expect(runTypeOptions(['agent_run', 'legacy_import'])).toContain('legacy_import');+ expect(runTypeLabel('legacy_import', key)).toBe('legacy_import');+ });++ it('keeps the declared types in their declared order, extras after', () => {+ const options = runTypeOptions(['zeta', 'alpha', 'agent_run']);+ expect(options.slice(0, RUN_TYPES.length)).toEqual([...RUN_TYPES]);+ expect(options.slice(RUN_TYPES.length)).toEqual(['alpha', 'zeta']);+ });++ it('never duplicates a type, and survives a server that omits the facet', () => {+ expect(runTypeOptions(['agent_run', 'dup', 'dup'])).toEqual([...RUN_TYPES, 'dup']);+ expect(runTypeOptions(undefined)).toEqual([...RUN_TYPES]);+ });++ it('lists webhook, which the scheduler writes and the importer preserves', () => {+ expect(runTypeOptions([])).toContain('webhook');+ });+});++describe('harnessSessionState', () => {+ it('reports workbench, im, deleted, and none distinctly', () => {+ expect(harnessSessionState({ ...NO_SESSION, session_is_workbench: true }, 'sess-1')).toBe('workbench');+ expect(harnessSessionState({ ...NO_SESSION, session_platform: 'slack' }, 'sess-1')).toBe('im');+ expect(harnessSessionState(NO_SESSION, 'sess-gone')).toBe('deleted');+ expect(harnessSessionState(NO_SESSION, null)).toBe('none');+ });+});++describe('DetailSession', () => {+ it('links a workbench session to its chat', () => {+ const html = render(+ <DetailSession+ summary={{ ...NO_SESSION, session_is_workbench: true, session_title: 'Weekly digest' }}+ sessionId="sess-1"+ />,+ );++ expect(html).toContain('href="/chat/sess-1"');+ expect(html).toContain('Weekly digest');+ });++ it('renders a deleted session as a label, not a link', () => {+ const html = render(<DetailSession summary={NO_SESSION} sessionId="sess-gone" />);++ expect(html).toContain('Session deleted');+ expect(html).toContain('sess-gone');+ expect(html).not.toContain('<a ');+ expect(html).not.toContain('/chat/');+ });++ it('shows an IM session without linking it', () => {+ const html = render(+ <DetailSession summary={{ ...NO_SESSION, session_platform: 'slack', session_label: '#ops' }} sessionId="sess-2" />,+ );++ expect(html).toContain('#ops');+ expect(html).not.toContain('<a ');+ });++ it('says so when nothing is bound', () => {+ const html = render(<DetailSession summary={NO_SESSION} sessionId={null} />);++ expect(html).toContain('No bound session');+ expect(html).not.toContain('<a ');+ });+});++describe('RunTriggerChip', () => {+ it('links a live watch back to its definition row', () => {+ const html = render(+ <RunTriggerChip run={run({ definition_id: 'def-1', definition_name: 'CI watcher', definition_kind: 'watch' })} />,+ );++ expect(html).toContain('href="/harness?tab=watches&definition=def-1"');+ expect(html).toContain('CI watcher');+ });++ it('routes a scheduled definition to the tasks tab', () => {+ const html = render(+ <RunTriggerChip run={run({ definition_id: 'def-2', definition_name: 'Nightly', definition_kind: 'task' })} />,+ );++ expect(html).toContain('href="/harness?tab=tasks&definition=def-2"');+ });++ it('keeps naming a deleted definition but stops linking to it', () => {+ const html = render(+ <RunTriggerChip+ run={run({ definition_id: 'def-3', definition_name: 'Old digest', definition_kind: 'task', definition_deleted: true })}+ />,+ );++ expect(html).toContain('Old digest');+ expect(html).toContain('(deleted)');+ expect(html).not.toContain('<a ');+ });++ it('renders nothing for a run with no originating definition', () => {+ expect(render(<RunTriggerChip run={run({})} />)).toBe('');+ });++ it('drops the run anchor so the destination list is not hidden behind a detail panel', () => {+ // The chip means "show me this definition in the list". Carrying ?run+ // forward would re-select the run on arrival, and below `lg` an open+ // selection hides the list — the link would show everything except the+ // thing it promised. (The clicked-row case has no ?run to drop; the+ // HarnessPage effect that consumes ?definition clears the selection.)+ const html = render(+ <RunTriggerChip run={run({ definition_id: 'def-4', definition_name: 'Hourly sync', definition_kind: 'task' })} />,+ );++ expect(html).toContain('definition=def-4');+ expect(html).not.toContain('run=');+ });+});diff --git a/ui/src/components/workbench/HarnessPage.tsx b/ui/src/components/workbench/HarnessPage.tsxindex 598fff51c..5f6e69bbd 100644--- a/ui/src/components/workbench/HarnessPage.tsx+++ b/ui/src/components/workbench/HarnessPage.tsx@@ -21,6 +21,7 @@ import {Search,Bot,MessageSquare,+ MessageSquareOff,ArrowUpRight,Filter,X,@@ -42,10 +43,20 @@ import type {} from '../../context/ApiContext';import { formatRelativeTime } from '../../lib/relativeTime';import { formatLocalDateTime } from '../../lib/datetime';+import { formatElapsed, runElapsedSeconds } from '../../lib/agentGraph';import { PlatformIcon } from '../visual/PlatformIcon';import { CreateViaChatDialog } from './CreateViaChatDialog';import type { CreateViaChatKind } from './CreateViaChatDialog';import { CapabilityTabs } from './CapabilityTabs';+import {+ BLANK_SESSION_SUMMARY,+ DEFAULT_HIDDEN_RUN_TYPES,+ harnessSessionState,+ runRowTitle,+ runStatusLabel,+ runTypeLabel,+ runTypeOptions,+} from './harnessRuns';import { Badge } from '../ui/badge';import { Button } from '../ui/button';import { Switch } from '../ui/switch';@@ -68,6 +79,19 @@ function formatSchedule(task: HarnessTask, t: (k: string, opts?: any) => string)type TabKey = 'tasks' | 'watches' | 'webhooks' | 'runs';+// Status segments per tab. Definitions filter by enabled/disabled; runs by+// execution outcome. One control renders whichever set the tab needs.+const DEFINITION_STATUS_FILTERS = ['all', 'enabled', 'disabled'] as const;+const RUN_STATUS_FILTERS = ['all', 'queued', 'running', 'succeeded', 'failed', 'canceled'] as const;++// ``default`` hides heartbeats, ``all`` shows every type, anything else is an+// exact run_type match. Kept as one value so the selector has a single source+// of truth for what is on screen.+// 'default', 'all', or a run_type. Deliberately not a union over RUN_TYPES: the+// selector also offers types read back from the ledger that the UI has no+// built-in name for, and those are just as selectable.+type RunTypeFilter = string;+const TAB_ORDER: TabKey[] = ['tasks', 'watches', 'webhooks', 'runs'];const PAGE_LIMIT = 30;const EMPTY_DEFINITION_COUNTS: HarnessDefinitionCounts = { all: 0, enabled: 0, disabled: 0 };@@ -98,9 +122,15 @@ export const HarnessPage: React.FC = () => {const [runCounts, setRunCounts] = useState<HarnessRunCounts>(EMPTY_RUN_COUNTS);const [queryTaskCounts, setQueryTaskCounts] = useState<HarnessDefinitionCounts>(EMPTY_DEFINITION_COUNTS);const [queryWatchCounts, setQueryWatchCounts] = useState<HarnessDefinitionCounts>(EMPTY_DEFINITION_COUNTS);+ // Filter-scoped run counts (the tab badge stays global). Same filters feed+ // this and the list, so the "shown / total" hint can never contradict the rows.+ const [queryRunCounts, setQueryRunCounts] = useState<HarnessRunCounts>(EMPTY_RUN_COUNTS);const [tasksHasMore, setTasksHasMore] = useState(false);const [watchesHasMore, setWatchesHasMore] = useState(false);const [runsHasMore, setRunsHasMore] = useState(false);+ // Run types the ledger actually holds, so the selector can offer one that+ // predates or postdates RUN_TYPES instead of stranding those rows under All.+ const [presentRunTypes, setPresentRunTypes] = useState<string[]>([]);const [tasksPage, setTasksPage] = useState(1);const [watchesPage, setWatchesPage] = useState(1);const [runsPage, setRunsPage] = useState(1);@@ -121,6 +151,11 @@ export const HarnessPage: React.FC = () => {// user can still switch to "all"/"disabled"; the filtered-count hint makes// the active filter obvious.const [statusFilter, setStatusFilter] = useState<HarnessDefinitionStatus>('enabled');+ // Runs filter by outcome, not by enabled/disabled, so they need their own+ // status state. Default "all": a run history with the failures filtered out+ // by default would hide exactly what the user came to look at.+ const [runStatusFilter, setRunStatusFilter] = useState<HarnessRunStatus | 'all'>('all');+ const [runTypeFilter, setRunTypeFilter] = useState<RunTypeFilter>('default');const [debouncedSearch, setDebouncedSearch] = useState('');const refreshSeq = useRef(0);// URL scope from the background-work banner (spec req 4): ?tab / ?session /@@ -141,11 +176,42 @@ export const HarnessPage: React.FC = () => {const tabParam = searchParams.get('tab');const sessionParam = searchParams.get('session');const runParam = searchParams.get('run');+ const definitionParam = searchParams.get('definition');useEffect(() => {if (tabParam && (['tasks', 'watches', 'runs'] as string[]).includes(tabParam)) {setTab(tabParam as TabKey);}}, [tabParam]);+ // ?definition=<id> — a run row's trigger chip pointing back at the task/watch+ // that produced it. Seeding the search box (rather than a hidden filter) keeps+ // the narrowing visible and removable; the definition search already matches+ // on id. "all" is required because the originating definition may well be+ // disabled by now. The param is consumed on arrival so clicking the same chip+ // again re-applies it after the user has cleared the box by hand.+ useEffect(() => {+ if (!definitionParam) return;+ setSearch(definitionParam);+ setDebouncedSearch(definitionParam);+ setStatusFilter('all');+ setTasksPage(1);+ setWatchesPage(1);+ // The point of the link is to reveal the definition in the list, so the run+ // detail the user came from has to close. Below `lg`, `hasSelection` hides+ // the list outright — leaving it open means the link shows everything+ // except the thing it promised. The ?run effect below can't cover this: a+ // row click selects without writing ?run, so the param never changes and+ // that effect never re-fires. Clearing here is what makes the chip work+ // from a clicked row, which is how it is actually reached.+ setSelection(null);+ setSearchParams(+ (prev) => {+ const next = new URLSearchParams(prev);+ next.delete('definition');+ return next;+ },+ { replace: true },+ );+ }, [definitionParam, setSearchParams]);useEffect(() => {setSessionFilter(sessionParam || undefined);setTasksPage(1);@@ -213,7 +279,7 @@ export const HarnessPage: React.FC = () => {const isCurrent = () => refreshSeq.current === seq;setLoading(true);setError(null);- const query = tab === 'tasks' || tab === 'watches' ? debouncedSearch || undefined : undefined;+ const query = debouncedSearch || undefined;try {if (tab === 'webhooks') {const counts = await api.getHarnessCounts();@@ -225,7 +291,9 @@ export const HarnessPage: React.FC = () => {}const result = await api.getHarnessBootstrap({tab,- status: tab === 'runs' ? undefined : statusFilter,+ status: tab === 'runs' ? (runStatusFilter === 'all' ? undefined : runStatusFilter) : statusFilter,+ run_type: tab === 'runs' && runTypeFilter !== 'default' && runTypeFilter !== 'all' ? runTypeFilter : undefined,+ exclude_run_type: tab === 'runs' && runTypeFilter === 'default' ? DEFAULT_HIDDEN_RUN_TYPES : undefined,query,// Session scope applies to definition tabs; runs anchor by ?run instead.session_id: tab === 'tasks' || tab === 'watches' ? sessionFilter : undefined,@@ -249,7 +317,9 @@ export const HarnessPage: React.FC = () => {} else if (tab === 'runs') {const page = result.page as Awaited<ReturnType<typeof api.listHarnessRuns>>;setRuns(page.runs);+ setQueryRunCounts(page.counts);setRunsHasMore(page.has_more);+ if (page.run_types) setPresentRunTypes(page.run_types);}} catch (err: any) {if (!isCurrent()) return;@@ -257,7 +327,18 @@ export const HarnessPage: React.FC = () => {} finally {if (isCurrent()) setLoading(false);}- }, [api, tab, debouncedSearch, statusFilter, sessionFilter, tasksPage, watchesPage, runsPage]);+ }, [+ api,+ tab,+ debouncedSearch,+ statusFilter,+ runStatusFilter,+ runTypeFilter,+ sessionFilter,+ tasksPage,+ watchesPage,+ runsPage,+ ]);useEffect(() => {refresh();@@ -425,10 +506,36 @@ export const HarnessPage: React.FC = () => {);const hasSelection = !!(selectedTask || selectedWatch || selectedRun);- const showSearchBar = tab === 'tasks' || tab === 'watches';- const queryCounts = tab === 'tasks' ? queryTaskCounts : queryWatchCounts;+ const showSearchBar = tab !== 'webhooks';+ const isRunsTab = tab === 'runs';+ // One filter row, three tabs. Runs swap in outcome statuses and add a type+ // selector; everything else (search, the shown/total hint) is shared.+ const statusOptions: readonly string[] = isRunsTab ? RUN_STATUS_FILTERS : DEFINITION_STATUS_FILTERS;+ const activeStatus: string = isRunsTab ? runStatusFilter : statusFilter;+ const statusLabelPrefix = isRunsTab ? 'harness.runStatus' : 'harness.statusFilter';+ const queryCounts = isRunsTab ? queryRunCounts : tab === 'tasks' ? queryTaskCounts : queryWatchCounts;const totalForTab = queryCounts.all;- const shownForTab = queryCounts[statusFilter] ?? 0;+ const shownForTab = (queryCounts as Record<string, number>)[activeStatus] ?? 0;+ // The shown/total hint only says something when a status narrows the set.+ // The run-type default is stated by the selector itself ("Default (no+ // heartbeats)"), so it needs no second, always-equal "3200/3200" readout.+ const filtersActive = !!search || activeStatus !== 'all';++ const resetPaging = useCallback(() => {+ setTasksPage(1);+ setWatchesPage(1);+ setRunsPage(1);+ setSelection(null);+ }, []);++ const onStatusFilterChange = useCallback(+ (option: string) => {+ if (isRunsTab) setRunStatusFilter(option as HarnessRunStatus | 'all');+ else setStatusFilter(option as HarnessDefinitionStatus);+ resetPaging();+ },+ [isRunsTab, resetPaging],+ );return (<div className="mx-auto flex w-full max-w-[1180px] flex-col gap-5 py-2">@@ -514,8 +621,9 @@ export const HarnessPage: React.FC = () => {})}</div>- {/* Search + status filter — only meaningful for tasks/watches. The- runs tab has its own server-side query in /api/harness/runs. */}+ {/* Search + status filter, shared by every list tab. Runs swap the+ enabled/disabled segments for outcome statuses and add a type+ selector; all three narrow server-side. */}{showSearchBar && (<div className="flex flex-wrap items-center gap-2.5"><div className="flex h-9 w-full items-center gap-2 rounded-md border border-input bg-background px-3 transition-colors focus-within:border-ring focus-within:ring-2 focus-within:ring-ring sm:w-[320px]">@@ -524,36 +632,51 @@ export const HarnessPage: React.FC = () => {value={search}onChange={(e) => {setSearch(e.target.value);- setTasksPage(1);- setWatchesPage(1);- setSelection(null);+ resetPaging();}}- placeholder={t('harness.searchPlaceholder')}+ placeholder={t(isRunsTab ? 'harness.searchRunsPlaceholder' : 'harness.searchPlaceholder')}className="flex-1 bg-transparent text-[12px] text-foreground outline-none placeholder:text-muted"/></div><div className="flex rounded-md border border-border-strong bg-surface p-0.5">- {(['all', 'enabled', 'disabled'] as const).map((opt) => (+ {statusOptions.map((opt) => (<buttonkey={opt}type="button"- onClick={() => {- setStatusFilter(opt);- setTasksPage(1);- setWatchesPage(1);- setSelection(null);- }}+ onClick={() => onStatusFilterChange(opt)}className={clsx('rounded px-2.5 py-1 text-[11px] font-medium transition',- statusFilter === opt+ activeStatus === opt? 'bg-violet/[0.12] text-violet': 'text-muted hover:text-foreground',)}>- {t(`harness.statusFilter.${opt}`)}+ {t(`${statusLabelPrefix}.${opt}`)}</button>))}</div>+ {isRunsTab && (+ // Heartbeat rows are hidden by default (plan D1). The selector is+ // where that default is stated and undone — it must never read as+ // an unfiltered list that happens to be short.+ <select+ value={runTypeFilter}+ onChange={(e) => {+ setRunTypeFilter(e.target.value as RunTypeFilter);+ resetPaging();+ }}+ aria-label={t('harness.runTypeFilter.label')}+ className="h-9 rounded-md border border-input bg-background px-2.5 text-[11px] font-medium text-foreground outline-none transition-colors focus:border-ring focus:ring-2 focus:ring-ring"+ >+ <option value="default">{t('harness.runTypeFilter.default')}</option>+ <option value="all">{t('harness.runTypeFilter.all')}</option>+ {runTypeOptions(presentRunTypes).map((type) => (+ <option key={type} value={type}>+ {runTypeLabel(type, t)}+ </option>+ ))}+ </select>+ )}{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" />@@ -571,7 +694,7 @@ export const HarnessPage: React.FC = () => {</button></span>)}- {(search || statusFilter !== 'all') && (+ {filtersActive && (<span className="ml-auto font-mono text-[10px] text-muted">{t('harness.filtered', { shown: shownForTab, total: totalForTab })}</span>@@ -1165,30 +1288,55 @@ const RunsList: React.FC<RunsListProps> = ({ runs, loading, selectedId, onSelect<>{runs.map((run) => {const active = selectedId === run.id;+ const typeLabel = runTypeLabel(run.run_type, t);+ const title = runRowTitle(run, typeLabel);+ const elapsed = runElapsedSeconds(run);+ // The whole row selects the run, but the trigger chip is its own link,+ // so the row can't be a <button> (no interactive descendants). An+ // absolutely-positioned overlay button takes the row click instead, and+ // the content opts out of pointer events except where it links.return (- <button+ <divkey={run.id}- type="button"- onClick={() => onSelect(run.id)}className={clsx(- 'flex items-center gap-3 rounded-lg border px-4 py-3 text-left transition',+ 'relative rounded-lg border px-4 py-3 transition',active ? 'border-violet/40 bg-violet/[0.05]' : 'border-border bg-surface hover:bg-foreground/[0.03]',)}>- <RunStatusIcon status={run.status} />- <div className="flex flex-1 flex-col gap-1">- <div className="flex items-center gap-2">- <span className="font-mono text-[12px] font-semibold text-foreground">{run.id}</span>- <span className="rounded border border-border-strong bg-foreground/[0.04] px-1.5 py-0 font-mono text-[9px] text-muted">- {run.run_type || 'run'}- </span>- </div>- <div className="flex items-center gap-3 text-[11px] text-muted">- <span>{run.agent_name || '—'}</span>- {run.created_at && <span>· {formatRelativeTime(run.created_at, t)}</span>}+ <button+ type="button"+ onClick={() => onSelect(run.id)}+ aria-label={title}+ className="absolute inset-0 z-0 rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ />+ <div className="pointer-events-none relative z-10 flex items-start gap-3">+ <span className="mt-0.5">+ <RunStatusIcon status={run.status} />+ </span>+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ <div className="flex min-w-0 items-center gap-2">+ {/* CSS truncation, never a slice: the detail panel and the+ server-side search keep the full message. */}+ <span className="min-w-0 flex-1 truncate text-[13px] font-semibold text-foreground">{title}</span>+ <span className="shrink-0 rounded border border-border-strong bg-foreground/[0.04] px-1.5 py-0 text-[9px] font-medium uppercase tracking-wide text-muted">+ {typeLabel}+ </span>+ </div>+ <div className="flex min-w-0 flex-wrap items-center gap-x-2.5 gap-y-1 text-[11px] text-muted">+ <RunTriggerChip run={run} />+ {run.agent_name && (+ <span className="inline-flex min-w-0 items-center gap-1">+ <Bot className="size-3 shrink-0" />+ <span className="truncate">{run.agent_name}</span>+ </span>+ )}+ <RunSessionLabel run={run} />+ {elapsed != null && <span className="shrink-0 font-mono">{formatElapsed(elapsed)}</span>}+ {run.created_at && <span className="shrink-0">{formatRelativeTime(run.created_at, t)}</span>}+ </div></div></div>- </button>+ </div>);})}<HarnessPager page={page} hasMore={hasMore} onPageChange={onPageChange} />@@ -1196,51 +1344,115 @@ const RunsList: React.FC<RunsListProps> = ({ runs, loading, selectedId, onSelect);};+// The task/watch a run came from, named. Links back to it unless the+// definition was deleted — a run outlives its definition, and the name is still+// worth showing even when there is nothing left to open.+export const RunTriggerChip: React.FC<{ run: HarnessRun }> = ({ run }) => {+ const { t } = useTranslation();+ if (!run.definition_name && !run.definition_id) return null;+ const label = run.definition_name || run.definition_id || '';+ const linkable = !!run.definition_kind && !run.definition_deleted && !!run.definition_id;+ const body = (+ <>+ {run.definition_kind === 'watch' ? (+ <Eye className="size-3 shrink-0" />+ ) : (+ <Calendar className="size-3 shrink-0" />+ )}+ <span className="max-w-[180px] truncate">{label}</span>+ {run.definition_deleted && <span className="shrink-0">{t('harness.run.definitionDeleted')}</span>}+ </>+ );+ if (!linkable) return <span className="inline-flex min-w-0 items-center gap-1">{body}</span>;+ return (+ <Link+ to={`/harness?tab=${run.definition_kind === 'watch' ? 'watches' : 'tasks'}&definition=${encodeURIComponent(run.definition_id!)}`}+ onClick={(e) => e.stopPropagation()}+ className="pointer-events-auto inline-flex min-w-0 items-center gap-1 text-violet hover:underline"+ >+ {body}+ </Link>+ );+};++// Compact session label for a run row. The row is for scanning; the actionable+// chat link lives in the detail panel's DetailSession.+const RunSessionLabel: React.FC<{ run: HarnessRun }> = ({ run }) => {+ const { t } = useTranslation();+ const state = harnessSessionState(run, run.session_id);+ if (state === 'none') return null;+ if (state === 'deleted') {+ return (+ <span className="inline-flex min-w-0 items-center gap-1 text-muted/70">+ <MessageSquareOff className="size-3 shrink-0" />+ <span className="truncate">{t('harness.detail.sessionDeleted')}</span>+ </span>+ );+ }+ return (+ <span className="inline-flex min-w-0 items-center gap-1">+ {state === 'workbench' ? (+ <MessageSquare className="size-3 shrink-0" />+ ) : (+ run.session_platform && <PlatformIcon platform={run.session_platform} size={12} />+ )}+ <span className="max-w-[200px] truncate">{run.session_label || run.session_title || '—'}</span>+ </span>+ );+};+interface RunDetailProps {run: HarnessRun;}const RunDetail: React.FC<RunDetailProps> = ({ run }) => {const { t } = useTranslation();+ const typeLabel = runTypeLabel(run.run_type || run.request_type, t);return (<div className="flex flex-col gap-4">- <div className="flex items-center gap-2">- <RunStatusIcon status={run.status} />- <code className="flex-1 truncate font-mono text-[13px] font-bold text-foreground">{run.id}</code>+ <div className="flex items-start gap-2">+ <span className="mt-0.5">+ <RunStatusIcon status={run.status} />+ </span>+ <span className="min-w-0 flex-1 text-[13px] font-semibold text-foreground">+ {runRowTitle(run, typeLabel)}+ </span><spanclassName={clsx(- 'rounded border px-2 py-0 font-mono text-[9px] font-bold uppercase',+ 'shrink-0 rounded border px-2 py-0 text-[9px] font-bold uppercase tracking-wide',STATUS_PILL_CLASS[run.status as HarnessRunStatus] ?? 'border-border-strong bg-foreground/[0.04] text-muted',)}>- {run.status}+ {runStatusLabel(run.status, t)}</span></div>+ {/* The run id left the row headline (plan §4.1) — it lives here, one+ click from the clipboard, for the ``vibe runs show <id>`` handoff. */}+ <DetailField label={t('harness.detail.id')}>+ <code className="block select-all break-all font-mono text-[11px] text-muted">{run.id}</code>+ </DetailField><DetailField label={t('harness.detail.type')}>- <span className="font-mono text-[11px] text-muted">{run.run_type || run.request_type || '—'}</span>+ <span className="text-[12px] text-foreground">{typeLabel}</span></DetailField><DetailField label={t('harness.detail.agent')}><span className="text-[12px] text-foreground">{run.agent_name || '—'}</span>{run.agent_backend && <span className="ml-2 font-mono text-[10px] text-muted">{run.agent_backend}</span>}{run.model && <span className="ml-2 font-mono text-[10px] text-muted">{run.model}</span>}</DetailField>- {run.definition_id && (- <DetailField label={t('harness.detail.definition')}>- <code className="font-mono text-[11px] text-muted">{run.definition_id}</code>+ {(run.definition_name || run.definition_id) && (+ <DetailField label={t('harness.detail.triggeredBy')}>+ <div className="flex min-w-0 items-center text-[12px] text-muted">+ <RunTriggerChip run={run} />+ </div></DetailField>)}{/* Session + lineage (Part B): the run row already carries these; surfacethem instead of hiding the who-started-whom / where-it-reports story.- Render the id as plain text — the run payload has no openability flag,- and a private ``vibe agent run`` session lives on the internal- private_agent_run pseudo-scope that is intentionally NOT chat-openable,- so an unconditional /chat link would dead-link. The openable-gated- chat entry point lives in the Agents 运行 graph detail panel. */}- {run.session_id && (- <DetailField label={t('harness.detail.session')}>- <code className="min-w-0 truncate font-mono text-[11px] text-muted">{run.session_id}</code>- </DetailField>- )}+ DetailSession owns the four session states, so a deleted session says+ so and an IM session stays deliberately unlinked. */}+ <DetailField label={t('harness.detail.session')}>+ <DetailSession summary={run} sessionId={run.session_id} />+ </DetailField>{(run.source_kind || run.source_actor) && (<DetailField label={t('harness.detail.source')}><span className="inline-flex min-w-0 flex-wrap items-center gap-1.5 text-[12px] text-foreground">@@ -1250,9 +1462,9 @@ const RunDetail: React.FC<RunDetailProps> = ({ run }) => {</span>)}{run.source_actor && (- // Lineage id only — the run payload carries no openable_in_chat- // signal, and a stale/imported or internal (non-openable) session- // id would deep-link to a dead /chat target, so render it plain.+ // A free-form actor id (session, hook, CLI caller) that the run+ // projection does not resolve to a session — plain text, so it+ // never pretends to be an openable chat.<span className="font-mono text-[11px] text-muted">{run.source_actor}</span>)}</span>@@ -1271,17 +1483,19 @@ const RunDetail: React.FC<RunDetailProps> = ({ run }) => {)}{run.callback_session_id && (<DetailField label={t('harness.detail.callback')}>- <span className="inline-flex min-w-0 flex-wrap items-center gap-1.5">- {/* Lineage id only (see source above) — plain text, not a /chat link. */}- <span className="min-w-0 truncate font-mono text-[11px] text-muted">- {run.callback_session_id}- </span>+ <div className="flex min-w-0 flex-col gap-1">+ {/* Where the result reports back to — the same four session states,+ so "who gets told" is as openable as "who ran it". */}+ <DetailSession+ summary={run.callback_session ?? BLANK_SESSION_SUMMARY}+ sessionId={run.callback_session_id}+ />{run.callback_status && (- <span className="rounded border border-border-strong bg-foreground/[0.04] px-1.5 py-0 font-mono text-[10px] uppercase text-muted">+ <span className="w-fit rounded border border-border-strong bg-foreground/[0.04] px-1.5 py-0 font-mono text-[10px] uppercase text-muted">{run.callback_status}</span>)}- </span>+ </div>{run.callback_error && (<div className="mt-1 rounded-md border border-destructive/40 bg-destructive/[0.06] px-2 py-1 text-[11px] text-destructive">{run.callback_error}@@ -1426,17 +1640,30 @@ const DetailAgent: React.FC<{ agentName: string | null; agent?: VibeAgentBrief });};-// Bound session. Workbench sessions show their title and link to the chat; IM-// sessions show platform + channel and are intentionally not linkable.-const DetailSession: React.FC<{ summary: HarnessSessionSummary; sessionId: string | null }> = ({+// Bound session, in the four states a harness row can be in. Workbench+// sessions show their title and link to the chat; IM sessions show platform ++// channel and are intentionally not linkable (there is no in-app destination);+// a session id that no longer resolves says so instead of rendering a raw id+// that looks like a name.+export const DetailSession: React.FC<{ summary: HarnessSessionSummary; sessionId: string | null }> = ({summary,sessionId,}) => {const { t } = useTranslation();- if (!summary.session_is_workbench && !summary.session_platform && !sessionId) {+ const state = harnessSessionState(summary, sessionId);+ if (state === 'none') {return <span className="text-[12px] text-muted">{t('harness.detail.sessionNone')}</span>;}- if (summary.session_is_workbench) {+ if (state === 'deleted') {+ return (+ <div className="flex min-w-0 items-center gap-2">+ <MessageSquareOff className="size-3.5 shrink-0 text-muted" />+ <span className="shrink-0 text-[12px] text-muted">{t('harness.detail.sessionDeleted')}</span>+ <span className="min-w-0 flex-1 truncate font-mono text-[10px] text-muted/70">{sessionId}</span>+ </div>+ );+ }+ if (state === 'workbench') {const label = summary.session_title || sessionId || '—';const body = (<>diff --git a/ui/src/components/workbench/harnessRuns.ts b/ui/src/components/workbench/harnessRuns.tsnew file mode 100644index 000000000..f347eb26f--- /dev/null+++ b/ui/src/components/workbench/harnessRuns.ts@@ -0,0 +1,96 @@+import type { HarnessRun, HarnessSessionSummary } from '../../context/ApiContext';++// Pure mappers behind the Harness run rows (plan §4.1/§4.2). They take ``t``+// rather than calling useTranslation, so the branching is unit-testable without+// a router or an i18n provider — same shape as lib/chatTrigger.ts.++// The run types the store writes today, in the order the type selector lists+// them. Membership is what decides whether a type has a translated label — an+// unknown or newly-added type still renders (as its raw value) rather than+// vanishing, which is also why the default filter is an exclusion, not an+// include-list. ``watch_runtime`` is hidden by default (plan D1): it is a+// watcher-process heartbeat with no session, agent, or message.+export const RUN_TYPES = [+ 'agent_run',+ 'watch',+ 'scheduled',+ 'task_run',+ 'hook_send',+ 'webhook',+ 'watch_runtime',+] as const;+export const DEFAULT_HIDDEN_RUN_TYPES = ['watch_runtime'];+const KNOWN_RUN_TYPES = new Set<string>(RUN_TYPES);++// Options for the type selector: the types we have words for, then anything+// else the ledger actually holds.+//+// A hardcoded list alone strands rows. Search skips ``run_type`` on purpose (it+// is a translated chip, not the user's text), so a type with no option is a row+// visible under All and reachable by no filter at all — which is what happened+// to ``webhook``. Naming the known types *and* reading the rest from the server+// means a type invented later is filterable the day it first appears.+export function runTypeOptions(present: readonly string[] | undefined): string[] {+ const extras = (present ?? []).filter((type) => type && !KNOWN_RUN_TYPES.has(type));+ return [...RUN_TYPES, ...[...new Set(extras)].sort()];+}++// Human words for an internal run_type. Same map feeds the row chip and the+// type selector, so the two can never disagree.+export function runTypeLabel(runType: string | null | undefined, t: (k: string) => string): string {+ if (!runType) return t('harness.runType.unknown');+ return KNOWN_RUN_TYPES.has(runType) ? t(`harness.runType.${runType}`) : runType;+}++const RUN_STATUSES = ['queued', 'running', 'succeeded', 'failed', 'canceled'];++// Human words for a run status. Same map feeds the detail pill and the status+// segments; an unrecognised status still prints rather than blanking out.+export function runStatusLabel(status: string | null | undefined, t: (k: string) => string): string {+ if (!status) return '—';+ return RUN_STATUSES.includes(status) ? t(`harness.runStatus.${status}`) : status;+}++const WHITESPACE_RUN = /\s+/g;++// One uniform row title for every run type (plan §4.1): the message's first+// non-empty line, else the originating task/watch name, else the type label.+// Never slices — the row truncates with CSS so the detail panel and the+// server-side search index keep the full text.+export function runRowTitle(+ run: Pick<HarnessRun, 'message' | 'prompt' | 'definition_name'>,+ typeLabel: string,+): string {+ for (const line of (run.message || run.prompt || '').split('\n')) {+ const collapsed = line.trim().replace(WHITESPACE_RUN, ' ');+ if (collapsed) return collapsed;+ }+ return run.definition_name?.trim() || typeLabel;+}++export type HarnessSessionState = 'none' | 'workbench' | 'im' | 'deleted';++// The all-null summary the server sends for a session id that no longer+// resolves. Used when a payload carries the id but not its own summary object.+export const BLANK_SESSION_SUMMARY: HarnessSessionSummary = {+ session_title: null,+ session_platform: null,+ session_scope_kind: null,+ session_label: null,+ session_is_workbench: false,+};++// Which of the four states a bound session is in (plan §4.2).+//+// ``deleted`` is the state this surface used to get wrong: a run/task whose+// session row is gone resolves to the all-null summary, fell through to the IM+// branch, and printed a bare hash that opens nothing. Naming the state lets the+// UI say so instead.+export function harnessSessionState(+ summary: HarnessSessionSummary,+ sessionId: string | null | undefined,+): HarnessSessionState {+ if (summary.session_is_workbench) return 'workbench';+ if (summary.session_platform) return 'im';+ return sessionId ? 'deleted' : 'none';+}diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 9743d6d71..5c1db79c4 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -1243,12 +1243,22 @@ export type HarnessRunCounts = {[key: string]: number;};-export type HarnessRun = {+// A run carries the same resolved session summary as a task/watch, so the same+// DetailSession component renders all three. ``callback_session`` is nested+// rather than prefix-flattened for exactly that reason.+export type HarnessRun = HarnessSessionSummary & {id: string;request_type: string | null;run_type: string | null;status: HarnessRunStatus;definition_id: string | null;+ // The task/watch this run came from, named. Present even when soft-deleted —+ // a run outlives its definition — with ``definition_deleted`` telling the UI+ // to show the name without a link.+ definition_name: string | null;+ definition_kind: 'task' | 'watch' | null;+ definition_deleted: boolean;+ callback_session: HarnessSessionSummary | null;task_id: string | null;source_kind: string | null;source_actor: string | null;@@ -1293,6 +1303,10 @@ export type HarnessRun = {export type HarnessRunsParams = {status?: HarnessRunStatus;runType?: string;+ // Comma-serialized server-side exclusion. ``run_type`` is an equality match,+ // so "everything except watcher heartbeats" needs its own param — and an+ // exclusion keeps a future run type visible by default instead of dropping it.+ excludeRunType?: string[];agentName?: string;definitionId?: string;query?: string;@@ -1325,6 +1339,9 @@ export type HarnessWatchesResult = HarnessPageResultBase<HarnessDefinitionCountsexport type HarnessRunsResult = HarnessPageResultBase<HarnessRunCounts> & {runs: HarnessRun[];+ // Every run_type present in the ledger, so the selector can offer a type the+ // UI has no built-in name for. Optional: an older server omits it.+ run_types?: string[];};export type HarnessCountsResult = {@@ -1336,6 +1353,11 @@ export type HarnessCountsResult = {export type HarnessBootstrapParams = {tab?: 'tasks' | 'watches' | 'runs';status?: HarnessDefinitionStatus | HarnessRunStatus;+ /** Runs tab only — mirrors the dedicated /api/harness/runs filters so the+ * first paint already reflects the active filter instead of flashing an+ * unfiltered page. */+ run_type?: string;+ exclude_run_type?: string[];query?: string;/** Scope tasks/watches to a bound session (background-work banner deep-link). */session_id?: string;@@ -2820,6 +2842,8 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenconst search = new URLSearchParams();if (params?.tab) search.set('tab', params.tab);if (params?.status) search.set('status', params.status);+ if (params?.run_type) search.set('run_type', params.run_type);+ if (params?.exclude_run_type?.length) search.set('exclude_run_type', params.exclude_run_type.join(','));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));@@ -2855,6 +2879,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenconst search = new URLSearchParams();if (params?.status) search.set('status', params.status);if (params?.runType) search.set('run_type', params.runType);+ if (params?.excludeRunType?.length) search.set('exclude_run_type', params.excludeRunType.join(','));if (params?.agentName) search.set('agent_name', params.agentName);if (params?.definitionId) search.set('definition_id', params.definitionId);if (params?.query) search.set('query', params.query);diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex b5f33cf37..7aee68325 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -2569,11 +2569,35 @@"soon": "soon","create": "Create","searchPlaceholder": "Search…",+ "searchRunsPlaceholder": "Search runs…","statusFilter": {"all": "All","enabled": "Enabled only","disabled": "Disabled only"},+ "runStatus": {+ "all": "All",+ "queued": "Queued",+ "running": "Running",+ "succeeded": "Succeeded",+ "failed": "Failed",+ "canceled": "Canceled"+ },+ "runType": {+ "agent_run": "Agent run",+ "watch": "Watch check",+ "scheduled": "Scheduled task",+ "task_run": "Task run",+ "hook_send": "Message delivery",+ "webhook": "Webhook trigger",+ "watch_runtime": "Watcher heartbeat",+ "unknown": "Run"+ },+ "runTypeFilter": {+ "label": "Run type",+ "default": "Default (no heartbeats)",+ "all": "All types"+ },"filtered": "{{shown}}/{{total}}","bannerToggle": {"title": "Background task banner",@@ -2621,7 +2645,7 @@"runtime": "Runtime","lastError": "Last error","type": "Type",- "definition": "Definition",+ "triggeredBy": "Triggered by","result": "Result","error": "Error","timing": "Timing",@@ -2632,6 +2656,7 @@"openInAgents": "Open in Agents","agentInherit": "Inherits default agent","sessionNone": "No bound session",+ "sessionDeleted": "Session deleted","source": "Source","parentRun": "Parent run","callback": "Callback",@@ -2668,6 +2693,9 @@"kindWatch": "Watch","promptTask": "Help me create a scheduled task. What I want: [describe here, e.g. \"every weekday at 9:30am summarize yesterday's PR comments\"]. Once parameters look right, run vibe task add and bind it to this project.","promptWatch": "Help me create a watch. I want to wait for: [describe here, e.g. \"CI workflow #1234 to finish\"]. Notify me when the condition is met. Once parameters look right, run vibe watch add."+ },+ "run": {+ "definitionDeleted": "(deleted)"}},"chat": {diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex cd8d9b68b..99587c615 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -2569,11 +2569,35 @@"soon": "敬请期待","create": "创建","searchPlaceholder": "搜索…",+ "searchRunsPlaceholder": "搜索运行记录…","statusFilter": {"all": "全部","enabled": "仅启用","disabled": "仅禁用"},+ "runStatus": {+ "all": "全部",+ "queued": "排队中",+ "running": "运行中",+ "succeeded": "已成功",+ "failed": "已失败",+ "canceled": "已取消"+ },+ "runType": {+ "agent_run": "Agent 运行",+ "watch": "监听检查",+ "scheduled": "定时任务",+ "task_run": "任务运行",+ "hook_send": "消息投递",+ "webhook": "Webhook 触发",+ "watch_runtime": "监听心跳",+ "unknown": "运行"+ },+ "runTypeFilter": {+ "label": "运行类型",+ "default": "默认(隐藏心跳)",+ "all": "全部类型"+ },"filtered": "{{shown}}/{{total}}","bannerToggle": {"title": "后台任务横幅",@@ -2621,7 +2645,7 @@"runtime": "运行时","lastError": "上次错误","type": "类型",- "definition": "定义",+ "triggeredBy": "触发来源","result": "结果","error": "错误","timing": "时间线",@@ -2632,6 +2656,7 @@"openInAgents": "在 Agents 打开","agentInherit": "继承默认 Agent","sessionNone": "未绑定会话",+ "sessionDeleted": "会话已删除","source": "来源","parentRun": "父 Run","callback": "回传",@@ -2668,6 +2693,9 @@"kindWatch": "等待器","promptTask": "请帮我创建一个后台任务。我的需求是:[在这里描述,例如「每个工作日早上 9:30 总结昨天的 PR 评论」]。请确认参数后用 vibe task add 创建,并把任务挂到当前项目。","promptWatch": "请帮我创建一个等待器(watch)。我希望监听:[在这里描述,例如「等 CI 工作流 #1234 跑完」]。条件满足后通知我。请确认参数后用 vibe watch add 创建。"+ },+ "run": {+ "definitionDeleted": "(已删除)"}},"chat": {diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex ce30ac410..aae369946 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -8072,6 +8072,14 @@ def _harness_query_filter() -> str | None:return query or None+def _harness_exclude_run_type() -> list[str]:+ """``?exclude_run_type=a,b`` — the one parsing site for the Runs tab's+ "hide watcher heartbeats" default. An exclusion (rather than a hardcoded+ include-list) keeps a future run type visible by default."""+ raw = request.args.get("exclude_run_type") or ""+ return [value for value in (part.strip() for part in raw.split(",")) if value]++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).@@ -8249,6 +8257,7 @@ def harness_runs_list():return jsonify({"ok": False, "code": "invalid_pagination", "message": str(exc)}), 400status = request.args.get("status") or Nonerun_type = request.args.get("run_type") or None+ exclude_run_type = _harness_exclude_run_type()agent_name = request.args.get("agent_name") or Nonedefinition_id = request.args.get("definition_id") or Nonequery = _harness_query_filter()@@ -8257,6 +8266,7 @@ def harness_runs_list():page_result = store.list_runs_page(status=status,run_type=run_type,+ exclude_run_type=exclude_run_type,agent_name=agent_name,definition_id=definition_id,query=query,@@ -8266,20 +8276,26 @@ def harness_runs_list():total = store.count_runs(status=status,run_type=run_type,+ exclude_run_type=exclude_run_type,agent_name=agent_name,definition_id=definition_id,query=query,)counts = store.count_runs_by_status(run_type=run_type,+ exclude_run_type=exclude_run_type,agent_name=agent_name,definition_id=definition_id,query=query,)+ # The types present in the ledger, so the selector can offer one the UI+ # has no built-in name for instead of stranding those rows under All.+ run_types = store.list_run_types()return jsonify({"runs": page_result.items,"counts": counts,+ "run_types": run_types,"total": total,"page": page_result.page,"limit": page_result.limit,@@ -8350,11 +8366,13 @@ def harness_bootstrap():else:run_status = request.args.get("status") or Nonerun_type = request.args.get("run_type") or None+ exclude_run_type = _harness_exclude_run_type()agent_name = request.args.get("agent_name") or Nonedefinition_id = request.args.get("definition_id") or Nonepage_result = store.list_runs_page(status=run_status,run_type=run_type,+ exclude_run_type=exclude_run_type,agent_name=agent_name,definition_id=definition_id,query=query,@@ -8365,13 +8383,18 @@ def harness_bootstrap():"runs": page_result.items,"counts": store.count_runs_by_status(run_type=run_type,+ exclude_run_type=exclude_run_type,agent_name=agent_name,definition_id=definition_id,query=query,),+ # Same facet as /api/harness/runs — the tab loads through+ # whichever of the two the caller reached, so both must carry it.+ "run_types": store.list_run_types(),"total": store.count_runs(status=run_status,run_type=run_type,+ exclude_run_type=exclude_run_type,agent_name=agent_name,definition_id=definition_id,query=query,