Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(harness): state-first Watch and Task rows (#1033)

Call White9b1af0a5dcc6
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index d4dbe35fc..4b4c89319 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -53,6 +53,7 @@ from storage.background import (
SWEEP_REASON_QUEUE_HOLD_EXPIRED,
SWEEP_REASON_TRANSPORT_UNAVAILABLE,
SweptRun,
+ resolve_run_at,
)
from storage.models import agent_sessions, scope_settings, scopes
from storage.pagination import PageRequest, PageResult, page_sequence
@@ -2323,7 +2324,9 @@ class ScheduledTaskService:
if task.schedule_type == "at":
if not task.run_at:
raise ValueError(f"scheduled task {task.id} is missing run_at timestamp")
- return DateTrigger(run_date=datetime.fromisoformat(task.run_at).astimezone(tz))
+ # Same resolver the harness payload's ``next_run_at`` uses, so the
+ # time the row shows is the time this trigger fires.
+ return DateTrigger(run_date=resolve_run_at(task.run_at, task.timezone))
raise ValueError(f"unknown schedule type: {task.schedule_type}")
async def _run_task(self, task_id: str) -> None:
diff --git a/core/services/agent_graph.py b/core/services/agent_graph.py
index bf183d9ae..c1e01c082 100644
--- a/core/services/agent_graph.py
+++ b/core/services/agent_graph.py
@@ -37,6 +37,7 @@ from typing import Any, Iterable, Mapping, Optional, Sequence
from sqlalchemy import select
from sqlalchemy.engine import Engine
+from storage.agent_session_rows import session_openable_in_chat
from storage.background import _status_query_values, normalize_run_status
from storage.db import create_sqlite_engine
from storage.models import agent_runs, agent_sessions, run_definitions, scope_settings, scopes
@@ -651,9 +652,9 @@ def _build_nodes(
"scope_label": scope_label,
"platform": platform,
"workdir": row.get("workdir"),
- # Every persisted session is openable in chat EXCEPT the internal
- # private-agent-run pseudo-scope sessions (M1 retires those).
- "openable_in_chat": not is_private_run,
+ "openable_in_chat": session_openable_in_chat(
+ session_id=session_id, scope_native_type=row.get("scope_native_type")
+ ),
"created_at": _iso_z(row.get("created_at")),
"last_active_at": _iso_z(row.get("last_active_at")),
"elapsed_seconds": (live or {}).get("elapsed_seconds") if is_live else None,
diff --git a/core/services/running_agents.py b/core/services/running_agents.py
index 7e676ec11..ccebc44b2 100644
--- a/core/services/running_agents.py
+++ b/core/services/running_agents.py
@@ -413,6 +413,9 @@ def _enrich_from_db(rows: list[dict[str, Any]]) -> None:
scopes.c.platform.label("scope_platform"),
scopes.c.scope_type.label("scope_scope_type"),
scopes.c.display_name.label("scope_display_name"),
+ # Only so ``openable_in_chat`` can ask the shared predicate
+ # rather than answer "it exists, so yes" on its own.
+ scopes.c.native_type.label("scope_native_type"),
)
.select_from(agent_sessions.outerjoin(scopes, scopes.c.id == agent_sessions.c.scope_id))
.where(agent_sessions.c.session_anchor.in_(anchors))
@@ -457,6 +460,8 @@ def _apply_session_meta(r: dict[str, Any], meta: dict[str, Any]) -> None:
Pure (no I/O) so it can be unit-tested without a DB.
"""
+ from storage.agent_session_rows import session_openable_in_chat
+
scope_id = meta.get("scope_id")
# Canonical scopes columns win; fall back to splitting scope_id when the
# scope row is missing (FK is nullable / SET NULL).
@@ -475,7 +480,9 @@ def _apply_session_meta(r: dict[str, Any], meta: dict[str, Any]) -> None:
# Run lineage owns precise trigger provenance; this live-process view only
# distinguishes whether a persisted Session exists.
r["trigger_source"] = r.get("trigger_source") or "human"
- r["openable_in_chat"] = bool(meta.get("id"))
+ r["openable_in_chat"] = session_openable_in_chat(
+ session_id=meta.get("id"), scope_native_type=meta.get("scope_native_type")
+ )
async def _end_orphan_pid(pid: int) -> dict[str, Any]:
diff --git a/core/watches.py b/core/watches.py
index 2f0fd5d9d..8fe253e2a 100644
--- a/core/watches.py
+++ b/core/watches.py
@@ -33,7 +33,11 @@ from core.process_isolation import (
terminate_process_tree_by_pid,
)
from core.scheduled_tasks import TaskExecutionStore
-from storage.background import SQLiteBackgroundTaskStore
+from storage.background import (
+ DEFINITION_CYCLE_COLUMNS,
+ SQLiteBackgroundTaskStore,
+ definition_resume_clear_columns,
+)
from vibe import runtime
from vibe.i18n import t as i18n_t
@@ -149,6 +153,7 @@ class ManagedWatch:
updated_at: str = field(default_factory=_utc_now_iso)
last_started_at: Optional[str] = None
last_finished_at: Optional[str] = None
+ retired_at: Optional[str] = None
last_event_at: Optional[str] = None
last_error: Optional[str] = None
last_exit_code: Optional[int] = None
@@ -183,6 +188,7 @@ class ManagedWatch:
updated_at=str(payload.get("updated_at") or _utc_now_iso()),
last_started_at=payload.get("last_started_at"),
last_finished_at=payload.get("last_finished_at"),
+ retired_at=payload.get("retired_at"),
last_event_at=payload.get("last_event_at"),
last_error=payload.get("last_error"),
last_exit_code=(int(payload["last_exit_code"]) if payload.get("last_exit_code") is not None else None),
@@ -377,11 +383,13 @@ class ManagedWatchStore:
def set_enabled(self, watch_id: str, enabled: bool) -> ManagedWatch:
watch = self._watches[watch_id]
- if enabled and not watch.enabled and watch.mode == "once":
- # A resumed one-shot starts a new lifecycle. Keep historical runs in
- # the run store, but do not let the prior cycle make a later pause
- # look completed and disappear from the default definition list.
- self._clear_cycle_state(watch)
+ if enabled and not watch.enabled:
+ # Same field split the storage layer applies to the Harness UI's
+ # toggle, so the two doorways cannot drift apart again.
+ self._clear_cycle_state(
+ watch,
+ definition_resume_clear_columns("watch", watch.mode),
+ )
watch.enabled = enabled
watch.updated_at = _utc_now_iso()
if self._sqlite is not None:
@@ -418,7 +426,7 @@ class ManagedWatchStore:
# A mode change starts a new lifecycle. Completion and failure
# metadata from the old mode remains available in run history, but
# must not determine the definition state under the new mode.
- self._clear_cycle_state(watch)
+ self._clear_cycle_state(watch, DEFINITION_CYCLE_COLUMNS)
watch.name = name
watch.session_key = session_key
watch.session_id = session_id
@@ -448,12 +456,11 @@ class ManagedWatchStore:
return watch
@staticmethod
- def _clear_cycle_state(watch: ManagedWatch) -> None:
- watch.last_started_at = None
- watch.last_finished_at = None
- watch.last_event_at = None
- watch.last_exit_code = None
- watch.last_error = None
+ def _clear_cycle_state(watch: ManagedWatch, columns: tuple[str, ...]) -> None:
+ # The same columns ``set_definition_enabled`` nulls out, applied to the
+ # in-memory mirror.
+ for column in columns:
+ setattr(watch, column, None)
def mark_cycle_start(self, watch_id: str) -> bool:
self.maybe_reload()
@@ -482,11 +489,19 @@ class ManagedWatchStore:
watch = self._watches.get(watch_id)
if watch is None:
return False
- watch.last_finished_at = _utc_now_iso()
+ now = _utc_now_iso()
+ # Retirement is state, not a conclusion drawn from cycle history.
+ # Only the cycle that changes enabled -> disabled may write it. A cycle
+ # landing after a manual pause must preserve that pause; a later result
+ # must likewise not erase a genuine earlier retirement.
+ was_enabled = watch.enabled
+ if was_enabled:
+ watch.last_finished_at = now if disable else None
+ watch.retired_at = now if disable else None
watch.last_exit_code = exit_code
watch.last_error = error
if event_detected:
- watch.last_event_at = watch.last_finished_at
+ watch.last_event_at = now
if disable:
watch.enabled = False
watch.updated_at = _utc_now_iso()
@@ -1091,9 +1106,14 @@ class ManagedWatchService:
self._watch_store_call(
watch.id,
"mark_cycle_result",
+ # Running out of lifetime is a timeout, and the row has
+ # to be able to say so: ``definition_lifecycle_detail``
+ # reads the exit code, and a ``None`` here made the
+ # supervisor's own deadline read as a normal ending.
+ # 124 is the same convention the per-cycle timeout uses.
lambda: self.store.mark_cycle_result(
watch.id,
- exit_code=None,
+ exit_code=124,
error=None,
disable=True,
),
diff --git a/docs/plans/harness-watch-task-readability.md b/docs/plans/harness-watch-task-readability.md
new file mode 100644
index 000000000..dfcd2964c
--- /dev/null
+++ b/docs/plans/harness-watch-task-readability.md
@@ -0,0 +1,278 @@
+# Harness Watches & Tasks — state-first rows
+
+Status: **approved, unblocked** — owner sign-off 2026-07-26.
+Owner decisions: D3 = replace the enabled/disabled filter with a lifecycle
+vocabulary and align the tab badges; D4 = hide the Webhooks placeholder tab.
+
+Companion spec: `docs/plans/harness-runs-readability.md` (LANE R1), merged as
+`3c00490365` ("feat(workbench): readable harness run rows with linkable
+sessions (#1023)"). R1 fixed the same class of defect on the Runs tab. **Branch
+from a master that contains it** — all three tabs live in one component, and R2
+reuses R1's title helper, duration helper, and `_session_summary` semantics.
+
+## 1. Problem
+
+Three defects, each verified against both the rendered UI and the live store.
+
+**1.1 A waiting watch shows no time, and a dead waiter looks alive.**
+`HarnessPage.tsx:1034` renders the watch timestamp as
+`{watch.last_event_at && (...)}` — the whole block disappears when the field is
+null. A one-shot waiter produces no output until it fires, so `last_event_at`
+stays null for exactly the watches that have been waiting longest. Measured:
+**3 of 4 enabled watches render a blank timestamp**, while `last_started_at` is
+populated on all 4.
+
+The backend already knows better: `list_watches_page` *orders* by
+`coalesce(last_event_at, last_started_at, updated_at, created_at)`. The fallback
+chain exists for sorting and was never applied to display.
+
+Liveness is also already stored — `write_watch_runtime` persists a
+`runtime:<watch_id>` row carrying `running` and `pid` — and is shown in the
+Watch detail panel but not in the list. A crashed waiter and a healthy one are
+visually identical.
+
+**1.2 The watch row spends its second line on mechanism.**
+The subtitle is the raw start command: for 3 of 4 enabled watches the full
+`wait_pr.py` argv including absolute developer paths, for the 4th a 790-character
+inline `bash` loop. The detail panel already carries this verbatim.
+
+**1.3 Task rows are titled by a hash, and never say when they run next.**
+40 of 54 live scheduled definitions have no `name`, so the row falls back to the
+id — the same defect R1 fixes on Runs. Time is printed raw: `17 10 * * *` for
+cron, `2026-07-26T13:35:00+08:00` for one-shots. `HarnessPage.tsx:809` gates the
+timestamp on `last_run_at`, so a task that has never run shows nothing at all —
+and **next fire time is absent from the row entirely**, which for a scheduler is
+the one question worth answering.
+
+**1.4 (cross-cutting) The status axis conflates two different things.**
+`全部 / 仅启用 / 仅禁用` puts "I paused this" and "it finished on its own" in one
+bucket. The second case dominates: of 1,180 disabled watches, **1,156 are
+one-shot waiters that fired and retired**. Calling them "disabled" is wrong —
+they completed. The tab badges compound it by counting the whole population
+(54 / 1,174) next to a default view showing 4 and 4.
+
+## 2. Measured facts (2026-07-26, developer machine)
+
+The lifecycle state is derived from persisted facts. Review established that
+watch retirement was not one of those facts: `last_finished_at` is history, not
+proof that a watch retired. A nullable `retired_at` marker is therefore added
+without a backfill; legacy disabled watches remain truthfully `paused`.
+
+| State | Derivation | Measured |
+| --- | --- | ---: |
+| `running` | an in-flight run exists for this definition | live |
+| `waiting` | `enabled = 1` and no in-flight run | watches 4, tasks 3 |
+| `paused` | `enabled = 0` and it did **not** end on its own | 4 |
+| `finished` | `enabled = 0` and it ended on its own | 1,228 |
+
+`paused` vs `finished`, per type:
+
+| Type | Rule for `finished` | Rows |
+| --- | --- | ---: |
+| watch, `mode = once` | `retired_at IS NOT NULL` | forward writes |
+| watch, `mode = forever` | `retired_at IS NOT NULL` | forward writes |
+| scheduled, `schedule_type = at` | no future fire remains | 50 |
+| watch, `mode = once`, never fired | → `paused` | 2 |
+| scheduled, `schedule_type = cron`, disabled | → `paused` | 2 |
+
+Within `finished`, the exit tells three different stories — and today all three
+render as "禁用":
+
+| Detail | Rule | Rows |
+| --- | --- | ---: |
+| `normal` | `last_exit_code = 0` | 5 + 50 + 1,156 |
+| `timeout` | `last_exit_code = 124` (lifetime timeout — the designed end for a `forever` watch that never fired) | 14 |
+| `error` | any other non-zero exit (`rc=7` api_error, spawn failure, utf-8 decode crash) | 3 |
+
+**A watch that timed out or crashed instead of firing is currently
+indistinguishable from one the user switched off.** That is the finding worth
+surfacing, and it costs one word on the row.
+
+Cron shapes in the store — only 4 distinct expressions, 3 of them `M H * * *`.
+A small formatter covers them; **no new dependency is needed**, and APScheduler
+(already a dependency, `pyproject.toml:48`) computes next fire times.
+
+## 3. Contract — new fields on the task/watch payload (FROZEN)
+
+Produced by `storage/background.py`, consumed by `HarnessPage.tsx`. Present on
+list and detail for **both** `scheduled` and `watch` definitions.
+
+```
+lifecycle_state: 'running' | 'waiting' | 'paused' | 'finished'
+lifecycle_detail: 'normal' | 'timeout' | 'error' | null # non-null only when finished
+next_run_at: string | null # ISO-8601; cron via APScheduler CronTrigger, one-shot = run_at
+waiting_since: string | null # last_started_at, when waiting
+running_since: string | null # started_at of the in-flight run, when running
+process_alive: boolean | null # watches only; from the runtime:<watch_id> row. null = unknown
+retired_at: string | null # watches only; supervisor persisted retirement marker
+```
+
+`running_since` was added during review, and is the one change to this frozen
+list. It cannot be `last_started_at`: that column is the *definition's* last
+cycle, so a `forever` watch that fired yesterday and began a fresh run a minute
+ago would report a day of running — a duration stitched together from two
+cycles. It comes from the same in-flight `agent_runs` row that made the state
+`running`, and is `null` while that run is merely queued, because a queued run
+has not started and there is no duration to show.
+
+Counts gain per-state buckets so the filter chips and the tab badge can each
+show a real number:
+
+```
+counts: { running, waiting, paused, finished, total }
+```
+
+**Non-goals.** The one nullable retirement marker and its forward-only migration
+are the complete schema change; there is no backfill and no inferred legacy
+retirement. The row **title** is computed client-side by reusing R1's fallback
+helper — it is deliberately not a server field.
+
+### 3.2 Two write-side corrections review forced (behavior changes)
+
+Deriving states only works where a column actually carries the fact. Review
+found two write-side gaps, and the honest fix was to persist the facts rather
+than guess harder at read time:
+
+1. **`retired_at` is the watch retirement state.** `last_finished_at` was
+ written under older rules and cannot prove why a disabled watch stopped.
+ `mark_cycle_result` now sets both timestamps only when the same call switches
+ the watch off, and clears them when a cycle continues. The lifecycle reads
+ only `retired_at`. The migration deliberately leaves legacy rows null:
+ "paused" is provable for every disabled row, while "retired" is not.
+2. **A `forever` watch retired by `lifetime_timeout_seconds` now records exit
+ code 124.** It recorded none, so the ending classifier fell through to
+ `normal` and a watch its own supervisor cut off reported a clean finish. 124
+ is the convention the per-cycle timeout already uses.
+
+### 3.3 One resolver for a naive `run_at` (behavior change)
+
+A `run_at` with no UTC offset is a wall-clock reading, and two places decided
+independently which zone to read it in: `compute_next_run_at` attached the
+task's own `timezone`, while `core/scheduled_tasks.py::_build_trigger` called
+`.astimezone()`, which reads a naive value in the **host** zone first. Any task
+whose timezone is not the machine's therefore displayed a fire time the
+scheduler would not honour, off by the offset between the two.
+
+`storage/background.py::resolve_run_at` is now the single resolver, imported by
+both, and it resolves in the task's declared timezone — the field exists for
+exactly that, and the alternative makes when a task fires depend on which
+machine runs it. **This changes the fire time of existing naive one-shot tasks
+whose `timezone` differs from the host's.** Tasks with an offset in `run_at` are
+unaffected: both paths already agreed on those.
+
+### 3.1 Dependency on R1 — read before implementing
+
+`write_watch_runtime` stores watcher liveness as `watch_runtime` run rows keyed
+`runtime:<watch_id>`. R1 hides that run type from the **Runs list by default**
+(D1). Hiding is a list filter, not a deletion: these rows remain the source for
+`process_alive`. Do not "clean them up", and do not read liveness from anywhere
+else.
+
+## 4. Behavior
+
+### 4.1 State vocabulary (D3)
+
+The filter offers four buckets — `全部 / 进行中 / 已暂停 / 已结束` — each with
+its own count. `进行中` is the default and combines `waiting + running`; the row
+itself names which of those states it is in. The store still accepts `waiting`
+and `running` as exact API and CLI filters, but they are not separate toolbar
+chips because the list already answers that distinction and the additional
+controls do not fit a 320px viewport.
+
+The row prints the precise word from the same vocabulary, so `finished` reads as
+one of **正常结束 / 已超时 / 出错结束**. No extra filter chip: one concept, the
+filter groups, the row specifies. An `error` row is visually marked; `timeout`
+is marked distinctly from `normal` because a watch that timed out never did its
+job.
+
+### 4.2 Row anatomy
+
+Line 1: state dot · title · `一次性`/`持续` chip (from `mode`, watches) or
+schedule chip (tasks).
+Line 2 carries **state, not mechanism**:
+
+| Case | Line 2 |
+| --- | --- |
+| watch, waiting, `once` | `已等 <since waiting_since>` · `进程在跑` / `进程已退出` |
+| watch, waiting, `forever` | `最近一次 <last_event_at>` · liveness |
+| watch, finished | `<正常结束 / 已超时 / 出错结束>` · `<last_finished_at>` |
+| task, waiting, one-shot | `还有 <until next_run_at>` · `<humanized next_run_at>` |
+| task, waiting, cron | `下次 <humanized next_run_at>` · `上次 <last_run_at>` |
+| any, paused | `已暂停` · `<last activity>` |
+
+Time is never printed raw. `17 10 * * *` → `每天 10:17`;
+`2026-07-26T13:35:00+08:00` → `今天 13:35`. The raw cron expression and the full
+timestamp stay in the detail panel.
+
+Never gate a whole block on one nullable field (defect 1.1). Fall back through
+`waiting_since` → `last_event_at` → `updated_at`, mirroring the ordering
+`coalesce` that `list_watches_page` already uses.
+
+### 4.3 Title
+
+Reuse R1's fallback helper verbatim:
+`name` → first non-empty line of the message → type label. Truncate with CSS,
+not by slicing — detail and search need the full text.
+
+### 4.4 Tab badge
+
+The badge shows `waiting + running` — how many things are working for the user
+right now. It must never show a total the default view excludes.
+
+### 4.5 Linkability parity — inherited from R1
+
+`core/services/agent_graph.py::openable_in_chat` is looser than the rule Tasks
+and Watches apply when deciding whether a row's session is openable. R1 found
+it, correctly left it alone (cross-surface, outside its scope), and handed it
+here — Tasks/Watches linkability is this lane's subject.
+
+Reconcile the two into one predicate rather than copying either. A row that
+offers a chat link must open a session that exists and is reachable; a row whose
+session was deleted says so (R1 made `_session_summary` honest about this — do
+not re-introduce the delivery-key fallback for a run that carries a concrete
+`session_id`). Same rule on both surfaces, declared once.
+
+**One projection site R1 left raw**, found in the post-merge browser pass and
+assigned here because it is the same predicate: the Run detail panel's 来源
+field prints `source_actor` verbatim, and when `source_kind == 'agent'` that
+value is a session id — `ses53w9zb8ba6` where a title and a link belong. It is a
+real `agent_runs` column, so R1's "strings the projection invents" enumeration
+test correctly did not flag it; a raw column can still be a foreign key to a
+name. Resolve it through the same summary path, apply the same linkability
+predicate, and extend the enumeration to cover id-shaped columns, not only
+invented fields.
+
+### 4.6 Webhooks (D4)
+
+Remove `webhooks` from `TabKey` / `TAB_ORDER` and delete `WebhooksEmpty` and its
+icon branch (`HarnessPage.tsx:69, 71, 218, 412, 497, 509, 633, 699`). Deep links
+carrying `?tab=webhooks` must fall back to `tasks` rather than render blank.
+
+## 5. Implementation notes
+
+- One enrichment chokepoint per type, batched over the page — mirror R1's
+ `_enrich_runs`. A 30-row page must not issue 30+ queries; `process_alive` is
+ one batched lookup over `runtime:<id>` for the page's watch ids.
+- Next fire time uses APScheduler's `CronTrigger.get_next_fire_time()` with the
+ definition's stored `timezone`. Do not hand-roll cron arithmetic.
+- The cron humanizer handles `M H * * *`, `M H * * <dow>`, `*/N * * * *`,
+ `* * * * *`, and falls back to the raw expression. Keep it a pure function
+ with unit tests; **do not add a dependency for it**.
+- Frontend: reuse R1's title and duration helpers, the existing filter row, the
+ existing `DetailSession`, and `ui/src/components/ui/` primitives. All new
+ strings via `ui/src/i18n/en.json` + `zh.json`.
+
+## 6. Evidence expected
+
+- **Unit (python):** the full state-derivation matrix from §2, including all
+ three `finished` details and both `paused` cases; `next_run_at` for cron
+ (across a DST boundary) and one-shot; `process_alive` true / false / unknown;
+ batched (no N+1); per-state counts consistent with the listed rows.
+- **Unit (ui):** cron humanizer for each supported shape plus the raw fallback;
+ a watch with `last_event_at = null` still renders a time; a `?tab=webhooks`
+ deep link falls back to `tasks`.
+- **Build gate:** `cd ui && npm run build`.
+- **Residual manual:** real-browser check — the three enabled watches show
+ elapsed time and liveness; a task row shows its next fire time; each filter
+ chip's count matches the rows it lists. Deferred to the orchestrator's
+ integration pass.
diff --git a/storage/agent_session_rows.py b/storage/agent_session_rows.py
index 4f27dd1d8..3fe2808ed 100644
--- a/storage/agent_session_rows.py
+++ b/storage/agent_session_rows.py
@@ -14,6 +14,36 @@ SESSION_ID_ALPHABET = "23456789abcdefghjkmnpqrstuvwxyz"
JSON_VALUE_PREFIX = "__json__:"
SESSION_VISIBILITIES = frozenset({"foreground", "background"})
+PRIVATE_AGENT_RUN_SCOPE_TYPE = "private_agent_run"
+
+
+def session_openable_in_chat(*, session_id: Any, scope_native_type: Any = None) -> bool:
+ """Whether ``/chat/<session_id>`` will actually open this session.
+
+ One predicate for the three surfaces that each carried their own answer: the
+ agent graph excluded private agent-run scopes, the running-agents list
+ accepted anything with an id, and the harness cards linked only *workbench*
+ sessions. Three rules for one question, so the same session could be a link
+ in one view and a bare id in the next.
+
+ The harness rule was the wrong one, and it is the one this replaces.
+ ``GET /api/sessions/<id>`` resolves through
+ ``workbench_sessions_service.get_session``, which filters on neither scope
+ nor status: an IM-bound session opens in chat exactly as a workbench one
+ does, and an archived session opens read-only (only *sending* into it is
+ refused, with 409 ``session_archived``). Declining to link them hid working
+ destinations behind unreadable ids.
+
+ Only two things genuinely do not open: a row with no id, and the legacy
+ ``private_agent_run`` pseudo-scope, which is deliberately kept off the chat
+ surface. Callers with no cheap join to ``scopes`` may omit
+ ``scope_native_type``; the result is then "openable if it exists", which is
+ what the running-agents list already assumed.
+ """
+ if not session_id:
+ return False
+ return str(scope_native_type or "").strip() != PRIVATE_AGENT_RUN_SCOPE_TYPE
+
def utc_now_iso() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
diff --git a/storage/alembic/versions/20260726_0036_run_definition_retired_at.py b/storage/alembic/versions/20260726_0036_run_definition_retired_at.py
new file mode 100644
index 000000000..ceda13ac5
--- /dev/null
+++ b/storage/alembic/versions/20260726_0036_run_definition_retired_at.py
@@ -0,0 +1,51 @@
+"""persist watch retirement state
+
+Revision ID: 20260726_0036
+Revises: 20260726_0035
+Create Date: 2026-07-26
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "20260726_0036"
+down_revision = "20260726_0035"
+branch_labels = None
+depends_on = None
+
+
+def _tables(bind) -> set[str]:
+ return {
+ str(row[0])
+ for row in bind.exec_driver_sql(
+ "select name from sqlite_master where type = 'table'"
+ )
+ }
+
+
+def _columns(bind, table: str) -> set[str]:
+ return {
+ str(row[1])
+ for row in bind.exec_driver_sql(f'pragma table_info("{table}")').fetchall()
+ }
+
+
+def upgrade() -> None:
+ bind = op.get_bind()
+ if "run_definitions" not in _tables(bind):
+ return
+ if "retired_at" not in _columns(bind, "run_definitions"):
+ op.add_column(
+ "run_definitions",
+ sa.Column("retired_at", sa.String(), nullable=True),
+ )
+
+
+def downgrade() -> None:
+ bind = op.get_bind()
+ if "run_definitions" not in _tables(bind):
+ return
+ if "retired_at" in _columns(bind, "run_definitions"):
+ op.drop_column("run_definitions", "retired_at")
diff --git a/storage/background.py b/storage/background.py
index ae231c813..a69cace36 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -6,14 +6,15 @@ from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from pathlib import Path
-from typing import Any, Iterable, Optional, Sequence
+from typing import Any, Callable, Iterable, Optional, Sequence, TypeVar
from zoneinfo import ZoneInfo
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.date import DateTrigger
-from sqlalchemy import and_, func, insert, or_, select, update
+from sqlalchemy import and_, case, func, insert, or_, select, update
from config import paths
+from storage.agent_session_rows import session_openable_in_chat
from storage.db import SqliteInvalidationProbe, create_sqlite_engine
from storage.migrations import (
background_tables_ready,
@@ -43,6 +44,28 @@ def _utc_now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
+def resolve_run_at(run_at: str, timezone_name: Optional[str]) -> datetime:
+ """The instant a one-shot ``run_at`` names, in the task's own timezone.
+
+ A ``run_at`` with no UTC offset is not an instant — it is a wall-clock
+ reading, and something has to say which zone to read it in. The task
+ carries a ``timezone`` for exactly that, so that is the answer; resolving
+ it any other way makes when a task fires depend on the machine.
+
+ ``datetime.astimezone()`` is the other way, and it is the wrong one: on a
+ naive value it silently assumes the *host* zone first. The scheduler used
+ it while the payload used this rule, so the two disagreed by the offset
+ between host and task zone and the UI promised a fire time the scheduler
+ would not honour. One resolver, imported by both, is why that cannot come
+ back — the scheduler at ``core/scheduled_tasks.py::_build_trigger`` and
+ ``compute_next_run_at`` below are its two callers.
+ """
+
+ tz = ZoneInfo(timezone_name or "UTC")
+ instant = datetime.fromisoformat(run_at)
+ return instant.replace(tzinfo=tz) if instant.tzinfo is None else instant.astimezone(tz)
+
+
def compute_next_run_at(
*,
enabled: bool,
@@ -69,8 +92,7 @@ def compute_next_run_at(
elif schedule_type == "at":
if not run_at:
return None
- instant = datetime.fromisoformat(run_at)
- instant = instant.replace(tzinfo=tz) if instant.tzinfo is None else instant.astimezone(tz)
+ instant = resolve_run_at(run_at, timezone_name)
if instant <= now:
# A one-shot whose time has already passed has no next run.
return None
@@ -94,7 +116,28 @@ RUN_STATUS_ALIASES: dict[str, str] = {
"canceled": "canceled",
}
_LIKE_ESCAPE = "\\"
-DEFINITION_STATUS_COUNTS = ("all", "enabled", "disabled")
+# What a task/watch is *doing*, which is not what ``enabled`` records.
+#
+# ``enabled`` is a switch: it says whether the scheduler may fire the row, and
+# nothing else. Reading it as a state made two different things look identical —
+# a one-shot watch that finished on its own and a watch the user paused both
+# store ``enabled = 0`` — and left the states users actually ask about
+# ("what is running right now?", "what is still waiting?") unnameable. These
+# four are derived per row from columns that already exist; no migration.
+DEFINITION_LIFECYCLE_STATES = ("running", "waiting", "paused", "finished")
+DEFINITION_STATUS_COUNTS = ("total",) + DEFINITION_LIFECYCLE_STATES
+# The status filters the API accepts, and which states each one selects. An
+# empty tuple means "no restriction". ``active`` is the default view: waiting and
+# running are one question ("is this thing still live?"), and the row itself says
+# which of the two it is, so it is a filter value without being a count key.
+DEFINITION_STATUS_FILTERS: dict[str, tuple[str, ...]] = {
+ "all": (),
+ "active": ("waiting", "running"),
+ "running": ("running",),
+ "waiting": ("waiting",),
+ "paused": ("paused",),
+ "finished": ("finished",),
+}
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.
@@ -104,6 +147,214 @@ _BLANK_DEFINITION_SUMMARY: dict[str, Any] = {
"definition_kind": None,
"definition_deleted": False,
}
+# Where a definition's session binding hides when it has no ``session_id``: a
+# legacy IM binding, then a ``create_per_run`` delivery target. Precedence order.
+_DEFINITION_SESSION_KEY_FIELDS = ("session_key", "deliver_key")
+# The exit code a waiter that ran out of lifetime carries. Written by
+# ``core/watches.py`` (the ``timeout`` convention), read here to tell an ending
+# that ran out of time from one that failed.
+_TIMEOUT_EXIT_CODE = 124
+# The runs a definition's own executions are recorded as. A watch's supervisor
+# heartbeat is *also* an ``agent_runs`` row and is ``running`` for as long as the
+# waiter lives, so counting it as an execution would make every healthy waiter
+# read as "running" and leave "waiting" unreachable. Waiter liveness is a
+# separate field (``process_alive``), not a state.
+_WATCH_RUNTIME_RUN_TYPE = "watch_runtime"
+# SQLite caps how many parameters one statement may bind (999 on builds before
+# 3.32). Paged lookups stay far under it, but the unpaged harness lists resolve
+# every row in the store at once, so batch resolvers chunk their id lists: a few
+# queries on a large store instead of one that fails.
+#
+# The cap counts *bound parameters*, not values. A resolver that binds one
+# parameter per value can take 400 of them; one that matches on a three-column
+# tuple binds three, so 400 values would be 1200 parameters and the same "too
+# many SQL variables" error the batching exists to prevent. Callers declare
+# their cost via ``params_per_value`` and the chunk size follows from it.
+_MAX_BOUND_PARAMS = 400
+# Ids here are usually strings, but a resolver keyed on a composite (platform,
+# scope_type, native_id) batches tuples through the same helper.
+_BatchValue = TypeVar("_BatchValue")
+
+
+def _id_batches(values: Iterable[_BatchValue], *, params_per_value: int = 1) -> list[list[_BatchValue]]:
+ """De-duplicated, non-empty ids in chunks small enough to bind."""
+
+ size = max(1, _MAX_BOUND_PARAMS // max(1, params_per_value))
+ ids = [value for value in dict.fromkeys(values) if value]
+ return [ids[start : start + size] for start in range(0, len(ids), size)]
+
+
+def definition_lifecycle_expression(definition_type: str):
+ """The single declaration of a task/watch lifecycle state, as SQL.
+
+ The row select and the filter counts both read this expression, so a row can
+ never land in a bucket its own chip did not count. That is why it is SQL and
+ not Python: counts are a ``GROUP BY`` over the whole table while rows are one
+ page of it, and a Python twin of this rule would have to be kept in step by
+ hand — the same shape of drift ``_RunProjection`` exists to prevent.
+
+ Branch order is the priority: an execution in flight outranks everything,
+ then a definition that can never fire again, then the switch. ``finished``
+ has to outrank ``waiting`` because ``enabled`` is not a promise of a future
+ fire — re-enabling a one-shot that already fired flips the switch back on
+ without giving it anything left to do, and reading the switch first parked
+ such a row in the default Active view forever.
+
+ Both ``ended`` branches read a fact written by whatever ends the definition,
+ never a proxy for one: a watch retires when its supervisor says so, and a
+ one-shot when the clock passes the instant it names. A history column —
+ "it has run at least once" — looks like either and is neither.
+ """
+
+ in_flight = (
+ select(agent_runs.c.id)
+ .where(agent_runs.c.definition_id == run_definitions.c.id)
+ .where(
+ or_(
+ agent_runs.c.run_type.is_(None),
+ agent_runs.c.run_type != _WATCH_RUNTIME_RUN_TYPE,
+ )
+ )
+ .where(agent_runs.c.status.in_([*_status_query_values("queued"), *_status_query_values("running")]))
+ .exists()
+ )
+ if definition_type == "watch":
+ # Retirement is persisted only by the supervisor branch that switches
+ # the watch off. Legacy rows have no marker and therefore read paused:
+ # their history cannot prove whether the old writer retired them or a
+ # user paused them after a cycle.
+ ended = and_(
+ run_definitions.c.enabled == 0,
+ run_definitions.c.retired_at.is_not(None),
+ )
+ else:
+ # A cron task cannot retire itself, so a disabled one is always someone
+ # having paused it. A one-shot is over when the instant it names has
+ # passed — not when it last ran. ``vibe task run`` executes an armed
+ # task early and records ``last_run_at`` without consuming the schedule,
+ # so reading history here retired a task that was still going to fire.
+ #
+ # This is the same question ``compute_next_run_at`` answers — it returns
+ # ``None`` exactly when the instant is behind us — so the state and the
+ # time printed beside it cannot contradict each other.
+ #
+ # ``datetime()`` normalises offset-carrying timestamps before comparing
+ # the scheduled instant with SQLite's current UTC clock.
+ ended = and_(
+ run_definitions.c.schedule_type == "at",
+ run_definitions.c.run_at.is_not(None),
+ func.datetime(run_definitions.c.run_at) <= func.datetime("now"),
+ )
+ return case(
+ (in_flight, "running"),
+ (ended, "finished"),
+ (run_definitions.c.enabled != 0, "waiting"),
+ else_="paused",
+ )
+
+
+# One completed cycle's worth of state: when the row last ran, how that ending
+# went, and what it caught.
+DEFINITION_RETIREMENT_COLUMNS = (
+ "retired_at",
+ "last_finished_at",
+ "last_exit_code",
+ "last_error",
+)
+DEFINITION_CYCLE_COLUMNS = (
+ "retired_at",
+ "last_started_at",
+ "last_finished_at",
+ "last_event_at",
+ "last_exit_code",
+ "last_error",
+)
+
+
+def definition_resume_clear_columns(
+ definition_type: Optional[str], mode: Optional[str]
+) -> tuple[str, ...]:
+ """Which lifecycle fields switching this definition back on clears.
+
+ Retirement is state, not history: every resumed watch clears the finish,
+ exit, and error that described its previous retirement. A one-shot also
+ clears its prior start/event history because it begins a distinct cycle.
+
+ A ``forever`` watch keeps continuous history: "last fired 2h ago" is
+ precisely what its row exists to show, and a pause does not make it untrue.
+ Scheduled tasks keep all history because a fired one-shot has no future fire
+ to protect, and a cron task still needs to report its last run.
+
+ Lives here, next to the single UPDATE, because two doorways must agree on
+ it: the Harness UI writes through ``set_definition_enabled`` while the CLI
+ and supervisor write through ``core/watches.py``.
+ """
+
+ if definition_type != "watch":
+ return ()
+ return DEFINITION_RETIREMENT_COLUMNS if mode == "forever" else DEFINITION_CYCLE_COLUMNS
+
+
+def _row_lifecycle_state(row: Any) -> Optional[str]:
+ """The state the query resolved for this row, if the query selected it.
+
+ Every harness read path goes through ``_definitions_query`` and so carries
+ the column. Importers and other direct ``select(run_definitions)`` readers do
+ not, and get ``None`` — an absent state, which the UI renders as unknown
+ rather than as a wrong one.
+ """
+
+ try:
+ return row["lifecycle_state"]
+ except (KeyError, IndexError):
+ return None
+
+
+def definition_lifecycle_detail(
+ *,
+ lifecycle_state: Optional[str],
+ definition_type: Optional[str] = None,
+ last_run_at: Any = None,
+ last_exit_code: Any = None,
+ last_error: Any = None,
+) -> Optional[str]:
+ """How a finished task/watch ended: ``normal``, ``timeout``, or ``error``.
+
+ Non-null only for ``finished``; the other three states are still in play and
+ have no ending to report yet. Python rather than SQL because it has exactly
+ one consumer — the row — and never a ``GROUP BY``: the filter groups by
+ state, and the row alone says which of the three endings it was.
+ """
+
+ if lifecycle_state != "finished":
+ return None
+ if definition_type == "scheduled" and last_run_at is None:
+ return None
+ if last_exit_code == _TIMEOUT_EXIT_CODE:
+ return "timeout"
+ if last_exit_code not in (None, 0):
+ return "error"
+ # Scheduled tasks never write an exit code, so the code alone would report
+ # every failed one as a normal ending; ``last_error`` is where their failure
+ # lands. Same pair ``vibe/cli.py`` already reads to call a watch clean.
+ if str(last_error or "").strip():
+ return "error"
+ return "normal"
+
+
+def definition_status_total(counts: dict[str, int], status: Optional[str]) -> int:
+ """How many rows a status filter selects, from the per-state counts.
+
+ The API's ``total`` used to be ``counts[status]``, which only worked while
+ every filter was also a count key. ``active`` spans two states, so the sum
+ is declared here — beside the filter table it sums — instead of being
+ re-derived by each caller.
+ """
+
+ states = DEFINITION_STATUS_FILTERS.get(status or "all")
+ if not states:
+ return int(counts.get("total", 0))
+ return sum(int(counts.get(state, 0)) for state in states)
@dataclass(frozen=True)
@@ -161,6 +412,15 @@ _RUN_PROJECTIONS: tuple[_RunProjection, ...] = (
id_field="callback_session_id",
id_column="callback_session_id",
),
+ # The run's 来源. Its payload field reads a *derived* id (agent-sourced runs
+ # only) while its SQL column is the raw ``source_actor`` — the projection's
+ # two-name design exists for exactly this.
+ _RunProjection(
+ source="session",
+ payload_key="source_session",
+ id_field="source_session_id",
+ id_column="source_actor",
+ ),
_RunProjection(
source="definition",
payload_key=None,
@@ -672,16 +932,12 @@ class SQLiteBackgroundTaskStore:
return self._probe.has_external_write()
def list_scheduled_tasks(self) -> list[dict[str, Any]]:
+ stmt = self._definitions_query("scheduled").order_by(
+ run_definitions.c.created_at, run_definitions.c.id
+ )
with self.engine.connect() as conn:
- rows = list(
- conn.execute(
- select(run_definitions)
- .where(run_definitions.c.definition_type == "scheduled")
- .where(run_definitions.c.deleted_at.is_(None))
- .order_by(run_definitions.c.created_at, run_definitions.c.id)
- ).mappings()
- )
- return [self._enrich_task(self._scheduled_task_from_row(row), conn) for row in rows]
+ rows = [self._scheduled_task_from_row(row) for row in conn.execute(stmt).mappings()]
+ return self._enrich_definitions(rows, conn, definition_type="scheduled")
def list_scheduled_tasks_page(
self,
@@ -706,7 +962,8 @@ 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._enrich_task(self._scheduled_task_from_row(row), conn) for row in conn.execute(stmt).mappings()]
+ rows = [self._scheduled_task_from_row(row) for row in conn.execute(stmt).mappings()]
+ self._enrich_definitions(rows, conn, definition_type="scheduled")
return page_result_from_limit_plus_one(rows, page_request)
def count_scheduled_tasks(
@@ -715,15 +972,14 @@ class SQLiteBackgroundTaskStore:
return self._definition_counts("scheduled", query=query, session_id=session_id)
def get_scheduled_task(self, definition_id: str) -> Optional[dict[str, Any]]:
+ stmt = self._definitions_query("scheduled").where(run_definitions.c.id == definition_id).limit(1)
with self.engine.connect() as conn:
- row = conn.execute(
- select(run_definitions)
- .where(run_definitions.c.definition_type == "scheduled")
- .where(run_definitions.c.id == definition_id)
- .where(run_definitions.c.deleted_at.is_(None))
- .limit(1)
- ).mappings().first()
- return self._enrich_task(self._scheduled_task_from_row(row), conn) if row else None
+ row = conn.execute(stmt).mappings().first()
+ if row is None:
+ return None
+ return self._enrich_definitions(
+ [self._scheduled_task_from_row(row)], conn, definition_type="scheduled"
+ )[0]
def upsert_scheduled_task(self, payload: dict[str, Any]) -> None:
values = self._scheduled_task_values(payload)
@@ -754,11 +1010,37 @@ class SQLiteBackgroundTaskStore:
definition_type: Optional[str] = None,
) -> bool:
with self.engine.begin() as conn:
+ values: dict[str, Any] = {"enabled": 1 if enabled else 0, "updated_at": _utc_now_iso()}
+ if enabled:
+ # Resuming may start a new lifecycle, and the old one must stop
+ # deciding the row's state when it does. The rule needs to know
+ # what the row *is*, so read before writing — and do it here, at
+ # the single UPDATE every caller reaches, rather than asking each
+ # caller to remember. The Harness UI toggle skipping this is what
+ # made a resumed-then-paused watch vanish from its own list.
+ current = (
+ conn.execute(
+ select(
+ run_definitions.c.definition_type,
+ run_definitions.c.mode,
+ run_definitions.c.enabled,
+ )
+ .where(run_definitions.c.id == definition_id)
+ .where(run_definitions.c.deleted_at.is_(None))
+ )
+ .mappings()
+ .first()
+ )
+ if current is not None and not current["enabled"]:
+ clear_columns = definition_resume_clear_columns(
+ current["definition_type"], current["mode"]
+ )
+ values.update(dict.fromkeys(clear_columns, None))
stmt = (
update(run_definitions)
.where(run_definitions.c.id == definition_id)
.where(run_definitions.c.deleted_at.is_(None))
- .values(enabled=1 if enabled else 0, updated_at=_utc_now_iso())
+ .values(**values)
)
if definition_type is not None:
stmt = stmt.where(run_definitions.c.definition_type == definition_type)
@@ -766,16 +1048,12 @@ class SQLiteBackgroundTaskStore:
return bool(result.rowcount)
def list_watches(self) -> list[dict[str, Any]]:
+ stmt = self._definitions_query("watch").order_by(
+ run_definitions.c.created_at, run_definitions.c.id
+ )
with self.engine.connect() as conn:
- rows = list(
- conn.execute(
- select(run_definitions)
- .where(run_definitions.c.definition_type == "watch")
- .where(run_definitions.c.deleted_at.is_(None))
- .order_by(run_definitions.c.created_at, run_definitions.c.id)
- ).mappings()
- )
- return [self._enrich_watch(self._watch_from_row(row), conn) for row in rows]
+ rows = [self._watch_from_row(row) for row in conn.execute(stmt).mappings()]
+ return self._enrich_definitions(rows, conn, definition_type="watch")
def list_watches_page(
self,
@@ -801,7 +1079,8 @@ 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._enrich_watch(self._watch_from_row(row), conn) for row in conn.execute(stmt).mappings()]
+ rows = [self._watch_from_row(row) for row in conn.execute(stmt).mappings()]
+ self._enrich_definitions(rows, conn, definition_type="watch")
return page_result_from_limit_plus_one(rows, page_request)
def count_watches(
@@ -810,15 +1089,12 @@ class SQLiteBackgroundTaskStore:
return self._definition_counts("watch", query=query, session_id=session_id)
def get_watch(self, watch_id: str) -> Optional[dict[str, Any]]:
+ stmt = self._definitions_query("watch").where(run_definitions.c.id == watch_id).limit(1)
with self.engine.connect() as conn:
- row = conn.execute(
- select(run_definitions)
- .where(run_definitions.c.definition_type == "watch")
- .where(run_definitions.c.id == watch_id)
- .where(run_definitions.c.deleted_at.is_(None))
- .limit(1)
- ).mappings().first()
- return self._enrich_watch(self._watch_from_row(row), conn) if row else None
+ row = conn.execute(stmt).mappings().first()
+ if row is None:
+ return None
+ return self._enrich_definitions([self._watch_from_row(row)], conn, definition_type="watch")[0]
def upsert_watch(self, payload: dict[str, Any]) -> None:
values = self._watch_values(payload)
@@ -1114,9 +1390,13 @@ class SQLiteBackgroundTaskStore:
]
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]))
+ # resolves to. Both read ``id_column``: ``id_field`` is the payload
+ # name, which for a derived site is not a column at all.
+ predicates.append(like(agent_runs.c[site.id_column]))
+ projected_text = agent_runs.c[site.id_column].in_(matching_ids[site.source])
+ if site.payload_key == "source_session":
+ projected_text = and_(agent_runs.c.source_kind == "agent", projected_text)
+ predicates.append(projected_text)
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
@@ -1134,10 +1414,13 @@ class SQLiteBackgroundTaskStore:
session_id: Optional[str] = None,
columns: Any = None,
):
+ lifecycle = definition_lifecycle_expression(definition_type)
if columns is not None:
stmt = select(*columns) if isinstance(columns, tuple) else select(columns)
else:
- stmt = select(run_definitions)
+ # Every row carries its state, resolved by the same expression the
+ # counts group by.
+ stmt = select(run_definitions, lifecycle.label("lifecycle_state"))
stmt = (
stmt.where(run_definitions.c.definition_type == definition_type)
.where(run_definitions.c.deleted_at.is_(None))
@@ -1147,9 +1430,10 @@ class SQLiteBackgroundTaskStore:
if session_id:
stmt = stmt.where(run_definitions.c.session_id == session_id)
if status and status != "all":
- if status not in {"enabled", "disabled"}:
- raise ValueError("status must be one of: all, enabled, disabled")
- stmt = stmt.where(run_definitions.c.enabled == (1 if status == "enabled" else 0))
+ states = DEFINITION_STATUS_FILTERS.get(status)
+ if not states:
+ raise ValueError("status must be one of: " + ", ".join(DEFINITION_STATUS_FILTERS))
+ stmt = stmt.where(lifecycle.in_(states))
if query:
pattern = _like_contains_pattern(query)
fields = [
@@ -1188,19 +1472,20 @@ class SQLiteBackgroundTaskStore:
query: Optional[str] = None,
session_id: Optional[str] = None,
) -> dict[str, int]:
+ lifecycle = definition_lifecycle_expression(definition_type)
stmt = self._definitions_query(
definition_type,
query=query,
session_id=session_id,
- columns=(run_definitions.c.enabled, func.count()),
- ).group_by(run_definitions.c.enabled)
+ columns=(lifecycle.label("lifecycle_state"), func.count()),
+ ).group_by(lifecycle)
counts = {key: 0 for key in DEFINITION_STATUS_COUNTS}
with self.engine.connect() as conn:
- for enabled, count in conn.execute(stmt).all():
- key = "enabled" if bool(enabled) else "disabled"
+ for state, count in conn.execute(stmt).all():
value = int(count or 0)
- counts[key] += value
- counts["all"] += value
+ if state in counts:
+ counts[state] += value
+ counts["total"] += value
return counts
def get_run(self, run_id: str) -> Optional[dict[str, Any]]:
@@ -2302,6 +2587,7 @@ class SQLiteBackgroundTaskStore:
"updated_at": payload.get("updated_at") or payload.get("created_at"),
"last_started_at": None,
"last_finished_at": None,
+ "retired_at": None,
"last_event_at": None,
"last_run_at": payload.get("last_run_at"),
"last_run_id": payload.get("last_run_id"),
@@ -2343,8 +2629,10 @@ class SQLiteBackgroundTaskStore:
"updated_at": payload.get("updated_at") or payload.get("created_at"),
"last_started_at": payload.get("last_started_at"),
"last_finished_at": payload.get("last_finished_at"),
+ "retired_at": payload.get("retired_at"),
"last_event_at": payload.get("last_event_at"),
"last_run_at": None,
+ "last_run_id": None,
"last_error": payload.get("last_error"),
"last_exit_code": payload.get("last_exit_code"),
"metadata_json": _json_dumps(payload.get("metadata") or {}),
@@ -2422,6 +2710,7 @@ class SQLiteBackgroundTaskStore:
"last_run_id": row["last_run_id"],
"last_error": row["last_error"],
"metadata": _json_loads(row["metadata_json"], {}),
+ "lifecycle_state": _row_lifecycle_state(row),
}
@staticmethod
@@ -2451,10 +2740,12 @@ class SQLiteBackgroundTaskStore:
"updated_at": row["updated_at"],
"last_started_at": row["last_started_at"],
"last_finished_at": row["last_finished_at"],
+ "retired_at": row["retired_at"],
"last_event_at": row["last_event_at"],
"last_error": row["last_error"],
"last_exit_code": row["last_exit_code"],
"metadata": _json_loads(row["metadata_json"], {}),
+ "lifecycle_state": _row_lifecycle_state(row),
}
@staticmethod
@@ -2469,6 +2760,14 @@ class SQLiteBackgroundTaskStore:
"task_id": row["definition_id"],
"source_kind": row["source_kind"],
"source_actor": row["source_actor"],
+ # ``source_actor`` is polymorphic: a *session id* when another agent
+ # spawned this run, but a parent run id, a "vault:<request>" handle
+ # or an activity id for every other ``source_kind``. Narrowing it to
+ # the one case that names a session — the same guard the agent graph
+ # applies when it draws spawn edges — is what lets the projection
+ # below resolve it without trying to look up "vault:abc" as a
+ # session and reporting it deleted.
+ "source_session_id": row["source_actor"] if row["source_kind"] == "agent" else None,
"parent_run_id": row["parent_run_id"],
"agent_name": row["agent_name"],
"agent_id": row["agent_id"],
@@ -2507,28 +2806,210 @@ class SQLiteBackgroundTaskStore:
"ok": None if row["completed_at"] is None else normalize_run_status(row["status"]) == "succeeded",
}
- def _enrich_task(self, task: dict[str, Any], conn: Any) -> dict[str, Any]:
- task.update(
- self._session_summary(
- conn, task.get("session_id"), task.get("session_key"), task.get("deliver_key")
- )
+ def _enrich_definitions(
+ self, rows: list[dict[str, Any]], conn: Any, *, definition_type: str
+ ) -> list[dict[str, Any]]:
+ """Project a page of task/watch rows into the fields the Harness UI reads.
+
+ The single chokepoint every list and get path goes through, so a field
+ cannot exist on one surface and be missing on another. Batched like
+ ``_enrich_runs``: a fixed number of round trips whatever the page size.
+ The per-row version this replaces was called from six sites and resolved
+ one row per query, which a 30-row page paid thirty times over — and the
+ unpaged list once per row in the whole store.
+
+ Beyond the stored columns it adds what the row actually shows: how a
+ finished row ended, when a waiting task fires next, since when it has
+ been waiting, and — for watches — whether the waiter process is still
+ alive. The last one is a fact about the *process*, deliberately not a
+ state: a waiter that died leaves a row that is still armed, and the
+ difference between those two is the whole point of showing it.
+ """
+
+ if not rows:
+ return rows
+ # One guard per lookup, not one around all of them. These are
+ # independent questions — who owns this row, where it is delivered, and
+ # whether its waiter is alive — and a single ``try`` made the first
+ # failure blank out the other two. That is how a lookup problem could
+ # silently take ``process_alive`` with it and leave every watch row
+ # saying "liveness unknown" for a reason nothing on screen named.
+ #
+ # ``warning``, not ``debug``: degrading to blanks is a visible loss of
+ # information, so it belongs in a log the operator actually reads.
+ def _lookup(what: str, fetch: Callable[[], dict[str, Any]]) -> dict[str, Any]:
+ try:
+ return fetch()
+ except Exception:
+ logger.warning("harness definition enrichment failed: %s", what, exc_info=True)
+ return {}
+
+ summaries = _lookup(
+ "session summaries",
+ lambda: self._session_summaries(
+ conn, {value for row in rows if (value := row.get("session_id"))}
+ ),
)
- task["next_run_at"] = compute_next_run_at(
- enabled=bool(task.get("enabled")),
- schedule_type=task.get("schedule_type"),
- cron=task.get("cron"),
- run_at=task.get("run_at"),
- timezone_name=task.get("timezone"),
+ # Only rows 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.
+ key_summaries = _lookup(
+ "session keys",
+ lambda: self._key_summaries(
+ conn,
+ {
+ value
+ for row in rows
+ if not row.get("session_id")
+ for field in _DEFINITION_SESSION_KEY_FIELDS
+ if (value := row.get(field))
+ },
+ ),
)
- return task
-
- def _enrich_watch(self, watch: dict[str, Any], conn: Any) -> dict[str, Any]:
- watch.update(
- self._session_summary(
- conn, watch.get("session_id"), watch.get("session_key"), watch.get("deliver_key")
+ runtimes: dict[str, dict[str, Any]] = {}
+ started: dict[str, str] = {}
+ if definition_type == "watch":
+ runtimes = _lookup(
+ "watch runtimes",
+ lambda: self._watch_runtimes(conn, [row.get("id") for row in rows]),
)
- )
- return watch
+ if any(row.get("lifecycle_state") == "running" for row in rows):
+ started = _lookup(
+ "in-flight run starts",
+ lambda: self._in_flight_started_at(
+ conn,
+ [
+ row.get("id")
+ for row in rows
+ if row.get("lifecycle_state") == "running"
+ ],
+ ),
+ )
+ for row in rows:
+ session_id = row.get("session_id")
+ row.update(
+ self._pick_session_summary(
+ summaries.get(session_id or ""),
+ []
+ if session_id
+ else [key_summaries.get(row.get(field) or "") for field in _DEFINITION_SESSION_KEY_FIELDS],
+ )
+ )
+ state = row.get("lifecycle_state")
+ row["lifecycle_detail"] = definition_lifecycle_detail(
+ lifecycle_state=state,
+ definition_type=definition_type,
+ last_run_at=row.get("last_run_at"),
+ last_exit_code=row.get("last_exit_code"),
+ last_error=row.get("last_error"),
+ )
+ row["next_run_at"] = compute_next_run_at(
+ enabled=bool(row.get("enabled")),
+ schedule_type=row.get("schedule_type"),
+ cron=row.get("cron"),
+ run_at=row.get("run_at"),
+ timezone_name=row.get("timezone"),
+ )
+ # Only meaningful while waiting: a paused row's last start is history,
+ # not a wait anyone is still in.
+ row["waiting_since"] = row.get("last_started_at") if state == "waiting" else None
+ # And only meaningful while running — from the run that *is* running,
+ # never from ``last_started_at``. That column is the definition's last
+ # cycle, which for a watch that fired yesterday and started a fresh run
+ # a minute ago would render "running 1d". Null while the run is merely
+ # queued: it has not started, so no duration exists to print.
+ row["running_since"] = started.get(row.get("id") or "") if state == "running" else None
+ if definition_type == "watch":
+ runtime = runtimes.get(row.get("id") or "")
+ row["runtime"] = runtime or {"running": False}
+ # ``None``, not ``False``: no heartbeat row at all means we have
+ # never seen this waiter, which is not the same as having seen it
+ # exit — and the row must not claim a waiter is dead on the
+ # strength of never having looked.
+ row["process_alive"] = None if runtime is None else bool(runtime.get("running"))
+ return rows
+
+ @staticmethod
+ def _watch_runtimes(conn: Any, watch_ids: Iterable[str]) -> dict[str, dict[str, Any]]:
+ """Each watch's supervisor heartbeat row, for many watches at once.
+
+ ``load_watch_runtime`` cannot serve this: it selects only *running*
+ heartbeats, which is what the supervisor wants (live waiters) but
+ collapses the two answers a row has to tell apart — a waiter that exited
+ and a waiter never seen. Absent from this result means the latter.
+ """
+
+ runtimes: dict[str, dict[str, Any]] = {}
+ for batch in _id_batches(watch_ids):
+ rows = conn.execute(
+ select(
+ agent_runs.c.definition_id,
+ agent_runs.c.status,
+ agent_runs.c.pid,
+ agent_runs.c.started_at,
+ agent_runs.c.updated_at,
+ agent_runs.c.metadata_json,
+ )
+ .where(agent_runs.c.run_type == _WATCH_RUNTIME_RUN_TYPE)
+ .where(agent_runs.c.definition_id.in_(batch))
+ ).mappings()
+ for row in rows:
+ payload = _json_loads(row["metadata_json"], {})
+ runtime = {
+ "pid": row["pid"],
+ "started_at": row["started_at"],
+ "updated_at": row["updated_at"],
+ **(payload if isinstance(payload, dict) else {}),
+ }
+ # The heartbeat's metadata was written while the waiter was up and
+ # is never rewritten when it exits, so the row's own status — not
+ # the stored payload — is what says whether it is still alive.
+ runtime["running"] = normalize_run_status(row["status"]) == "running"
+ runtimes[row["definition_id"]] = runtime
+ return runtimes
+
+ @staticmethod
+ def _in_flight_started_at(conn: Any, definition_ids: Iterable[str]) -> dict[str, str]:
+ """When each definition's in-flight run started, for many at once.
+
+ Deliberately the *same* set of runs ``definition_lifecycle_expression``
+ tests for: same ``run_type`` exclusion, same statuses. A row is
+ ``running`` because one of these exists, so the duration it shows has to
+ come from one of these too — reading ``run_definitions.last_started_at``
+ instead would date the row's previous cycle and print a duration nothing
+ is actually spending.
+
+ Missing means the run has not started (a queued run has no
+ ``started_at``), which callers must render as no duration rather than as
+ a zero-length one.
+ """
+
+ started: dict[str, str] = {}
+ for batch in _id_batches(definition_ids):
+ rows = conn.execute(
+ select(agent_runs.c.definition_id, agent_runs.c.started_at)
+ .where(agent_runs.c.definition_id.in_(batch))
+ .where(
+ or_(
+ agent_runs.c.run_type.is_(None),
+ agent_runs.c.run_type != _WATCH_RUNTIME_RUN_TYPE,
+ )
+ )
+ .where(
+ agent_runs.c.status.in_(
+ [*_status_query_values("queued"), *_status_query_values("running")]
+ )
+ )
+ .where(agent_runs.c.started_at.is_not(None))
+ # Concurrent runs against one definition are possible; the row
+ # asks how long *this* burst of work has been going, so the
+ # earliest start is the honest answer. Descending order plus the
+ # last-write-wins loop below leaves exactly that one.
+ .order_by(agent_runs.c.started_at.desc())
+ ).mappings()
+ for row in rows:
+ started[row["definition_id"]] = row["started_at"]
+ return started
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.
@@ -2627,6 +3108,7 @@ class SQLiteBackgroundTaskStore:
"session_scope_kind": None,
"session_label": None,
"session_is_workbench": False,
+ "session_openable": False,
}
@staticmethod
@@ -2700,12 +3182,15 @@ class SQLiteBackgroundTaskStore:
scopes.c.scope_type,
scopes.c.native_id,
scopes.c.display_name,
+ scopes.c.native_type,
).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()
+ # A presentation fact only — which icon and which label to render. It is
+ # deliberately *not* the link rule any more: see ``session_openable``.
is_workbench = row["scope_id"] is None or platform == "avibe" or scope_type == "project"
return {
"session_title": row["title"],
@@ -2713,19 +3198,23 @@ class SQLiteBackgroundTaskStore:
"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,
+ "session_openable": session_openable_in_chat(
+ session_id=row["id"], scope_native_type=row["native_type"]
+ ),
}
@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}
+ """``_session_summary``'s id branch for many ids at once. Ids with no
+ surviving session row are simply absent from the result."""
+ summaries: dict[str, dict[str, Any]] = {}
+ for batch in _id_batches(session_ids):
+ rows = conn.execute(
+ SQLiteBackgroundTaskStore._session_summary_query().where(agent_sessions.c.id.in_(batch))
+ ).mappings()
+ for row in rows:
+ summaries[row["id"]] = SQLiteBackgroundTaskStore._summary_from_session_row(row)
+ return summaries
@staticmethod
def _summary_from_session_key(conn: Any, key: Optional[str]) -> Optional[dict[str, Any]]:
@@ -2754,23 +3243,27 @@ class SQLiteBackgroundTaskStore:
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,
+ display_names: dict[tuple[str, str, str], Any] = {}
+ # Three bound parameters per triple, so the batches are a third the size
+ # of an id resolver's. An unpaged harness list on a store with a few
+ # hundred legacy-keyed rows is exactly the case that overflows.
+ for batch in _id_batches(triples, params_per_value=3):
+ 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 batch
)
- 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
- }
+ ).mappings()
+ for row in rows:
+ display_names[(row["platform"], row["scope_type"], row["native_id"])] = row["display_name"]
return {
key: SQLiteBackgroundTaskStore._summary_from_key_parts(parts, display_names.get(parts))
for key, parts in parsed.items()
@@ -2797,6 +3290,9 @@ class SQLiteBackgroundTaskStore:
"session_scope_kind": scope_type,
"session_label": display_name or native_id,
"session_is_workbench": False,
+ # A delivery key names a channel, not a session; there is no id to
+ # open even though the label reads like one.
+ "session_openable": False,
}
@staticmethod
diff --git a/storage/migrations.py b/storage/migrations.py
index 13967bea9..ce3028a51 100644
--- a/storage/migrations.py
+++ b/storage/migrations.py
@@ -78,6 +78,7 @@ HEAD_REQUIRED_COLUMNS = {
"message",
"message_payload_json",
"last_run_id",
+ "retired_at",
},
"agent_runs": {
"definition_id",
@@ -445,6 +446,7 @@ def _repair_head_required_columns(conn: sqlite3.Connection, tables: set[str]) ->
"message": "TEXT",
"message_payload_json": "TEXT",
"last_run_id": "VARCHAR",
+ "retired_at": "VARCHAR",
}.items():
if column not in definition_columns:
conn.execute(f'alter table "run_definitions" add column "{column}" {column_type}')
diff --git a/storage/models.py b/storage/models.py
index 8f7a4335f..01cb782ef 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -201,6 +201,7 @@ run_definitions = Table(
Column("updated_at", String, nullable=False),
Column("last_started_at", String, nullable=True),
Column("last_finished_at", String, nullable=True),
+ Column("retired_at", String, nullable=True),
Column("last_event_at", String, nullable=True),
Column("last_run_at", String, nullable=True),
Column("last_error", Text, nullable=True),
diff --git a/tests/test_background_work_banner.py b/tests/test_background_work_banner.py
index 4023f46aa..78c31b283 100644
--- a/tests/test_background_work_banner.py
+++ b/tests/test_background_work_banner.py
@@ -354,8 +354,8 @@ def test_definition_session_filter_scopes_watches_and_tasks(tmp_path: Path):
assert [w["id"] for w in watches_a.items] == ["w-a"]
tasks_a = store.list_scheduled_tasks_page(session_id="ses-A", page_request=None)
assert [t["id"] for t in tasks_a.items] == ["t-a"]
- assert store.count_watches(session_id="ses-A")["all"] == 1
- assert store.count_scheduled_tasks(session_id="ses-B")["all"] == 1
+ assert store.count_watches(session_id="ses-A")["total"] == 1
+ assert store.count_scheduled_tasks(session_id="ses-B")["total"] == 1
# No filter → both sessions' definitions are returned.
assert len(store.list_watches_page(page_request=None).items) == 2
finally:
diff --git a/tests/test_harness_definition_lifecycle.py b/tests/test_harness_definition_lifecycle.py
new file mode 100644
index 000000000..a66617f0e
--- /dev/null
+++ b/tests/test_harness_definition_lifecycle.py
@@ -0,0 +1,915 @@
+"""Harness Tasks/Watches lifecycle: what a row is *doing*, not whether it is on.
+
+``enabled`` is a switch, and the harness read it as a state. That made a
+one-shot watch that finished on its own indistinguishable from one the user
+paused (both store ``enabled = 0``), left "still waiting" and "running right
+now" unnameable, and let a waiter whose process had died keep rendering as a
+healthy armed watch.
+
+``definition_lifecycle_expression`` derives the four states from persisted
+facts and is the single declaration both the row select and the filter counts
+read, so a row cannot land in a bucket its own chip did not count.
+
+See ``docs/plans/harness-watch-task-readability.md`` §2 (derivation), §3 (frozen
+payload contract) and §5.
+"""
+
+from __future__ import annotations
+
+import re
+import sys
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+from zoneinfo import ZoneInfo
+
+import pytest
+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 (
+ DEFINITION_CYCLE_COLUMNS,
+ DEFINITION_RETIREMENT_COLUMNS,
+ DEFINITION_STATUS_COUNTS,
+ DEFINITION_STATUS_FILTERS,
+ SQLiteBackgroundTaskStore,
+ _id_batches,
+ compute_next_run_at,
+ definition_lifecycle_detail,
+ definition_resume_clear_columns,
+ definition_status_total,
+)
+from storage.db import create_sqlite_engine
+from storage.models import agent_sessions, run_definitions
+from storage.pagination import PageRequest
+from storage.settings_service import upsert_scope
+
+NOW = "2026-07-26T00:00:00+00:00"
+
+# A one-shot's state is now a question about the clock, so these two are
+# relative to the real one: the SQL compares ``run_at`` against SQLite's
+# ``now``, and a fixed literal would decide the answer by the calendar.
+FUTURE = (datetime.now(timezone.utc) + timedelta(days=2)).isoformat()
+PAST = (datetime.now(timezone.utc) - timedelta(days=2)).isoformat()
+
+
+def store(tmp_path: Path):
+ sqlite = SQLiteBackgroundTaskStore(tmp_path / "state" / "vibe.sqlite")
+ try:
+ yield sqlite
+ finally:
+ sqlite.close()
+
+
+def _task(store: SQLiteBackgroundTaskStore, task_id: str, **overrides) -> None:
+ payload = {
+ "id": task_id,
+ "name": task_id,
+ "prompt": "run it",
+ "schedule_type": "cron",
+ "cron": "0 * * * *",
+ "enabled": True,
+ "created_at": NOW,
+ "updated_at": NOW,
+ }
+ payload.update(overrides)
+ store.upsert_scheduled_task(payload)
+
+
+def _watch(store: SQLiteBackgroundTaskStore, watch_id: str, **overrides) -> None:
+ payload = {
+ "id": watch_id,
+ "name": watch_id,
+ "shell_command": "tail -f deploy.log",
+ "enabled": True,
+ "created_at": NOW,
+ "updated_at": NOW,
+ }
+ payload.update(overrides)
+ store.upsert_watch(payload)
+
+
+def _run(store: SQLiteBackgroundTaskStore, run_id: str, definition_id: str, **overrides) -> None:
+ payload = {
+ "id": run_id,
+ "request_type": "watch",
+ "status": "running",
+ "definition_id": definition_id,
+ "created_at": NOW,
+ "updated_at": NOW,
+ }
+ payload.update(overrides)
+ store.enqueue_run(payload)
+
+
+def _state(store: SQLiteBackgroundTaskStore, watch_id: str) -> str:
+ return store.get_watch(watch_id)["lifecycle_state"]
+
+
+def test_definition_serializers_cover_every_persisted_column(store) -> None:
+ """A schema addition must make both definition writers explicit."""
+ columns = {column.name for column in run_definitions.columns}
+
+ assert set(store._scheduled_task_values({"id": "scheduled"})) == columns
+ assert set(store._watch_values({"id": "watch"})) == columns
+
+
+def test_watch_row_serializer_covers_every_managed_watch_field(store) -> None:
+ """The API row must expose every persisted field the supervisor writes."""
+ from dataclasses import fields
+
+ from core.watches import ManagedWatch
+
+ _watch(store, "w")
+ row = store.get_watch("w")
+
+ assert {field.name for field in fields(ManagedWatch)} <= set(row)
+
+
+def test_watch_states_separate_the_switch_from_the_history(store) -> None:
+ """The four states, one fixture per rule (plan §2)."""
+ _watch(store, "armed")
+ _watch(store, "executing")
+ _run(store, "run-1", "executing", status="running")
+ # Switched off after completing a lifetime: it retired itself.
+ _watch(store, "retired", enabled=False, last_finished_at=NOW, retired_at=NOW)
+ # Switched off having never finished: someone paused it.
+ _watch(store, "paused", enabled=False)
+
+ assert _state(store, "armed") == "waiting"
+ assert _state(store, "executing") == "running"
+ assert _state(store, "retired") == "finished"
+ assert _state(store, "paused") == "paused"
+
+
+def test_a_switched_on_watch_that_already_finished_once_is_waiting_again(store) -> None:
+ """A ``forever`` watch that finished a lifetime and was re-armed is waiting
+ for its next one, not permanently retired.
+
+ Also the guard for rows written before ``last_finished_at`` meant
+ "retired": a watch the scheduler may still fire has not retired, whatever
+ stamp an earlier cycle left on it.
+ """
+ _watch(store, "rearmed", mode="forever", last_finished_at=NOW)
+
+ assert _state(store, "rearmed") == "waiting"
+
+
+def test_a_live_waiter_heartbeat_is_not_an_execution(store) -> None:
+ """The rule the whole ``waiting`` state depends on.
+
+ A watch's supervisor heartbeat is an ``agent_runs`` row with status
+ ``running`` for as long as the waiter process lives. Counting it as an
+ execution would make every healthy waiter read as ``running`` and leave
+ ``waiting`` unreachable — which is why waiter liveness is a separate field.
+ """
+ _watch(store, "healthy")
+ store.write_watch_runtime(
+ {"watches": {"healthy": {"running": True, "pid": 4242, "started_at": NOW}}},
+ updated_at=NOW,
+ )
+
+ watch = store.get_watch("healthy")
+ assert watch["lifecycle_state"] == "waiting"
+ assert watch["process_alive"] is True
+ assert watch["runtime"]["pid"] == 4242
+
+
+def test_process_alive_tells_a_dead_waiter_from_one_never_seen(store) -> None:
+ """The defect this field exists for: an armed watch whose waiter died looks
+ exactly like a healthy one. ``False`` means we watched it exit; ``None``
+ means we have never seen it, and the row must not claim it is dead on the
+ strength of never having looked."""
+ _watch(store, "died")
+ _watch(store, "never-started")
+ store.write_watch_runtime(
+ {"watches": {"died": {"running": True, "pid": 99, "started_at": NOW}}},
+ updated_at=NOW,
+ )
+ # The next supervisor write with no entry for it terminalizes the heartbeat.
+ store.write_watch_runtime({"watches": {}}, updated_at=NOW)
+
+ died = store.get_watch("died")
+ never = store.get_watch("never-started")
+ assert (died["lifecycle_state"], died["process_alive"]) == ("waiting", False)
+ assert (never["lifecycle_state"], never["process_alive"]) == ("waiting", None)
+ # The stale heartbeat metadata still says ``running: true``; the row's own
+ # status is what decides, so the payload must not repeat the stale claim.
+ assert died["runtime"]["running"] is False
+
+
+def test_a_disabled_cron_task_is_paused_and_a_fired_one_shot_is_finished(store) -> None:
+ """A cron task cannot retire itself, so switching one off is always a pause.
+ A one-shot whose scheduled instant is past is done whichever way its switch
+ points; the switch cannot create another fire."""
+ _task(store, "cron-off", enabled=False)
+ _task(store, "cron-on")
+ _task(store, "one-shot-fired-off", schedule_type="at", run_at=PAST, enabled=False, last_run_at=NOW)
+ _task(store, "one-shot-fired-on", schedule_type="at", run_at=PAST, enabled=True, last_run_at=NOW)
+ _task(store, "one-shot-pending", schedule_type="at", run_at="2099-01-01T00:00:00+00:00", enabled=False)
+
+ states = {task["id"]: task["lifecycle_state"] for task in store.list_scheduled_tasks()}
+ assert states == {
+ "cron-off": "paused",
+ "cron-on": "waiting",
+ "one-shot-fired-off": "finished",
+ "one-shot-fired-on": "finished",
+ "one-shot-pending": "paused",
+ }
+
+
+def test_counts_and_rows_come_from_one_expression(store) -> None:
+ """The invariant that makes a chip trustworthy: every filter returns exactly
+ the rows its own count promised, for every filter, including the ``active``
+ one that spans two states."""
+ _watch(store, "w-waiting")
+ _watch(store, "w-running")
+ _run(store, "run-1", "w-running", status="running")
+ _watch(store, "w-paused", enabled=False)
+ _watch(store, "w-finished-a", enabled=False, last_finished_at=NOW, retired_at=NOW)
+ _watch(store, "w-finished-b", enabled=False, last_finished_at=NOW, retired_at=NOW)
+
+ counts = store.count_watches()
+ assert counts == {"total": 5, "running": 1, "waiting": 1, "paused": 1, "finished": 2}
+ assert set(counts) == set(DEFINITION_STATUS_COUNTS)
+
+ for status in DEFINITION_STATUS_FILTERS:
+ rows = store.list_watches_page(status=status, page_request=PageRequest(page=1, limit=50)).items
+ assert len(rows) == definition_status_total(counts, status), status
+ expected = DEFINITION_STATUS_FILTERS[status]
+ if expected:
+ assert {row["lifecycle_state"] for row in rows} <= set(expected), status
+
+
+def test_an_unknown_status_is_rejected_rather_than_silently_ignored(store) -> None:
+ with pytest.raises(ValueError):
+ store.list_watches_page(status="enabled", page_request=PageRequest(page=1, limit=5))
+
+
+ ("exit_code", "error", "expected"),
+ [
+ (0, None, "normal"),
+ (None, None, "normal"),
+ (124, "waiter timed out", "timeout"),
+ (1, "boom", "error"),
+ # Scheduled tasks never write an exit code, so the code alone would call
+ # every failed one a normal ending.
+ (None, "boom", "error"),
+ (0, " ", "normal"),
+ ],
+)
+def test_lifecycle_detail_names_how_a_finished_row_ended(exit_code, error, expected) -> None:
+ assert (
+ definition_lifecycle_detail(lifecycle_state="finished", last_exit_code=exit_code, last_error=error)
+ == expected
+ )
+
+
[email protected]("state", ["running", "waiting", "paused", None])
+def test_only_a_finished_row_reports_an_ending(state) -> None:
+ """A row still in play has no ending yet; reporting one would let the UI
+ print "出错结束" beside a watch that is currently waiting."""
+ assert definition_lifecycle_detail(lifecycle_state=state, last_exit_code=1, last_error="boom") is None
+
+
+def test_a_missed_one_shot_without_run_evidence_claims_no_ending() -> None:
+ assert (
+ definition_lifecycle_detail(
+ lifecycle_state="finished",
+ definition_type="scheduled",
+ last_run_at=None,
+ last_exit_code=None,
+ last_error=None,
+ )
+ is None
+ )
+ assert (
+ definition_lifecycle_detail(
+ lifecycle_state="finished",
+ definition_type="scheduled",
+ last_run_at=NOW,
+ last_exit_code=None,
+ last_error=None,
+ )
+ == "normal"
+ )
+
+
+def test_next_run_at_and_waiting_since_are_on_the_row(store) -> None:
+ """Both frozen fields (plan §3) come from the enrichment, so every list and
+ get path has them without the caller computing anything."""
+ _task(store, "hourly", cron="0 * * * *", timezone="UTC")
+ _task(store, "switched-off", cron="0 * * * *", enabled=False)
+ _watch(store, "armed", last_started_at="2026-07-26T09:00:00+00:00")
+ _watch(store, "stopped", enabled=False, last_started_at="2026-07-26T09:00:00+00:00")
+
+ tasks = {task["id"]: task for task in store.list_scheduled_tasks()}
+ assert tasks["hourly"]["next_run_at"] is not None
+ # A task the scheduler may not fire has no next run to promise.
+ assert tasks["switched-off"]["next_run_at"] is None
+
+ watches = {watch["id"]: watch for watch in store.list_watches()}
+ assert watches["armed"]["waiting_since"] == "2026-07-26T09:00:00+00:00"
+ # A paused row's last start is history, not a wait anyone is still in.
+ assert watches["stopped"]["waiting_since"] is None
+
+
+def _seed_session(db_path: Path, *, platform: str, scope_type: str, title: str, native_type=None) -> str:
+ """A session in a scope of the caller's choosing, returning its id."""
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform=platform,
+ scope_type=scope_type,
+ native_id=title,
+ now=NOW,
+ display_name="#dev-ops",
+ native_type=native_type,
+ )
+ 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"]
+ finally:
+ engine.dispose()
+
+
+def test_a_watch_links_every_session_chat_actually_serves(tmp_path: Path) -> None:
+ """Plan §4.5, and a deliberate change in what the Watches/Tasks panel links.
+
+ This surface used to link only *workbench* sessions, so an IM-bound watch
+ printed a channel the reader could see and not open — even though
+ ``/chat/<id>`` serves it, which is what the agent graph already assumed.
+ Two rules for one question; the harness one was the wrong one.
+
+ Presentation and linkability are now separate fields:
+ ``session_is_workbench`` still decides whether the row reads as a title or
+ as a channel, while ``session_openable`` alone decides whether it opens.
+ """
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ db_path.parent.mkdir(parents=True, exist_ok=True)
+ SQLiteBackgroundTaskStore(db_path).close()
+
+ workbench = _seed_session(db_path, platform="avibe", scope_type="project", title="巡检构建产物")
+ im = _seed_session(db_path, platform="slack", scope_type="channel", title="周报推送")
+ private = _seed_session(
+ db_path,
+ platform="avibe",
+ scope_type="project",
+ title="spawned",
+ native_type="private_agent_run",
+ )
+
+ store = SQLiteBackgroundTaskStore(db_path)
+ try:
+ _watch(store, "w-workbench", session_id=workbench)
+ _watch(store, "w-im", session_id=im)
+ _watch(store, "w-private", session_id=private)
+ rows = {watch["id"]: watch for watch in store.list_watches()}
+ finally:
+ store.close()
+
+ # An IM watch reads as IM and opens: both, not one or the other.
+ assert rows["w-im"]["session_is_workbench"] is False
+ assert rows["w-im"]["session_label"] == "#dev-ops"
+ assert rows["w-im"]["session_openable"] is True
+
+ assert rows["w-workbench"]["session_is_workbench"] is True
+ assert rows["w-workbench"]["session_openable"] is True
+
+ # The one destination /chat/<id> genuinely refuses. The row still names it.
+ assert rows["w-private"]["session_openable"] is False
+ assert rows["w-private"]["session_title"] == "spawned"
+
+
+NEW_YORK = "America/New_York"
+
+
+def test_next_run_at_carries_the_offset_of_the_fire_time_not_of_today() -> None:
+ """A daily task fires at the same wall-clock time year round, and the row
+ prints that instant on the reader's clock.
+
+ The failure this guards is invisible for 363 days a year: computing the
+ zone's offset *now* and stamping it onto a fire time on the other side of a
+ DST transition, which slides the task an hour and — because the UI renders
+ the instant, not the cron — silently mislabels when it will run. Asserted as
+ a property rather than against a frozen clock so it also holds on the two
+ days it can actually break.
+ """
+ tz = ZoneInfo(NEW_YORK)
+ for cron, hour, minute in (("30 2 * * *", 2, 30), ("15 13 * * 3", 13, 15)):
+ iso = compute_next_run_at(
+ enabled=True, schedule_type="cron", cron=cron, run_at=None, timezone_name=NEW_YORK
+ )
+ assert iso is not None, cron
+ fire = datetime.fromisoformat(iso)
+ local = fire.astimezone(tz)
+ assert (local.hour, local.minute) == (hour, minute), cron
+ # The offset stamped on the payload must be the zone's offset at that
+ # instant — not at the moment the payload was built.
+ assert fire.utcoffset() == tz.utcoffset(local.replace(tzinfo=None)), cron
+
+
+def test_a_naive_one_shot_is_read_in_its_own_zone_on_its_own_date() -> None:
+ """``run_at`` is stored without an offset, so the zone has to supply one —
+ and which one depends on the date it names, not on today's."""
+ winter = f"{datetime.now().year + 1}-01-15T12:00:00"
+ summer = f"{datetime.now().year + 1}-07-01T12:00:00"
+
+ def offset(run_at: str) -> str:
+ iso = compute_next_run_at(
+ enabled=True, schedule_type="at", cron=None, run_at=run_at, timezone_name=NEW_YORK
+ )
+ assert iso is not None, run_at
+ return iso[-6:]
+
+ assert offset(winter) == "-05:00"
+ assert offset(summer) == "-04:00"
+
+
+def test_the_ui_chips_ask_for_filters_this_store_actually_serves() -> None:
+ """The chips are declared twice — once here, once in the client that draws
+ them — and a chip whose states the store buckets differently is a count that
+ does not match its own list.
+
+ MIRROR of ``DEFINITION_STATUS_FILTER_STATES`` in
+ ``ui/src/components/workbench/harnessLifecycle.ts``. The client offers four
+ of the six filters this store accepts (``running`` and ``waiting`` are
+ reachable through the API and the CLI but merged into one chip); what it
+ must never do is name a filter this store rejects, or select a different set
+ of states under the same name.
+ """
+ source = Path("ui/src/components/workbench/harnessLifecycle.ts").read_text(encoding="utf-8")
+
+ block = re.search(
+ r"DEFINITION_STATUS_FILTER_STATES[^=]*=\s*\{(.*?)\n\};", source, re.DOTALL
+ )
+ assert block, "could not find DEFINITION_STATUS_FILTER_STATES"
+ client_states = {
+ key: tuple(re.findall(r"'([a-z_]+)'", values))
+ for key, values in re.findall(r"(\w+):\s*\[([^\]]*)\]", block.group(1))
+ }
+ assert client_states, "parsed no chips out of the client"
+
+ for chip, states in client_states.items():
+ assert chip in DEFINITION_STATUS_FILTERS, chip
+ assert set(states) == set(DEFINITION_STATUS_FILTERS[chip]), chip
+
+ # The chip list and the default landing view, same file, same names.
+ chips = re.search(r"DEFINITION_STATUS_FILTERS\s*=\s*\[([^\]]*)\]", source)
+ assert chips and set(re.findall(r"'([a-z_]+)'", chips.group(1))) == set(client_states)
+ default = re.search(r"DEFAULT_DEFINITION_STATUS\s*=\s*'([a-z_]+)'", source)
+ assert default and default.group(1) in client_states
+
+
+def test_the_ui_numbers_weekdays_the_way_the_scheduler_does() -> None:
+ """The client turns a cron day-of-week field into words, and it is the only
+ place in the product that does. If it uses crontab(5)'s numbering — Sunday
+ is 0 — while ``CronTrigger.from_crontab`` uses APScheduler's — Monday is 0 —
+ every weekly row is off by a day, and it reads as a correct schedule.
+
+ MIRROR of ``WEEKDAY_NAMES`` in
+ ``ui/src/components/workbench/harnessLifecycle.ts``, pinned to the library's
+ own table rather than to a copy of it, so an APScheduler upgrade that
+ renumbered the week would fail here instead of on screen.
+ """
+ from apscheduler.triggers.cron.expressions import WEEKDAYS
+
+ source = Path("ui/src/components/workbench/harnessLifecycle.ts").read_text(encoding="utf-8")
+ block = re.search(r"const WEEKDAY_NAMES = \[([^\]]*)\]", source)
+ assert block, "could not find WEEKDAY_NAMES"
+ assert re.findall(r"'([a-z]+)'", block.group(1)) == list(WEEKDAYS)
+
+
[email protected]("field", ["7", "5-1", "0-7"])
+def test_the_day_of_week_forms_the_ui_refuses_are_the_ones_that_never_fire(field: str) -> None:
+ """The client hands these back as raw expressions instead of describing
+ them. This is why: the scheduler will not build a trigger for them at all,
+ so a task carrying one never fires, and a plain-English weekly phrase would
+ be a promise nothing can keep."""
+ from apscheduler.triggers.cron import CronTrigger
+
+ with pytest.raises(ValueError):
+ CronTrigger.from_crontab(f"0 8 * * {field}")
+
+
+def test_resuming_a_one_shot_watch_clears_the_cycle_that_ended_it(store) -> None:
+ """Both doorways write ``enabled``; only one used to know that resuming
+ starts a new lifecycle. Leaving the old cycle behind makes the *next* pause
+ render as "finished" — the row drops out of the default list and out of the
+ paused chip, so it is nowhere the user would look for it."""
+ _watch(store, "w", mode="once", enabled=False, last_finished_at=NOW, retired_at=NOW, last_exit_code=0)
+ assert _state(store, "w") == "finished"
+
+ # The Harness UI's path, which bypassed ``core/watches.py`` entirely.
+ store.set_definition_enabled("w", True, definition_type="watch")
+ row = store.get_watch("w")
+ assert row["lifecycle_state"] == "waiting"
+ assert [row[column] for column in DEFINITION_CYCLE_COLUMNS] == [None] * len(
+ DEFINITION_CYCLE_COLUMNS
+ )
+
+ store.set_definition_enabled("w", False, definition_type="watch")
+ assert _state(store, "w") == "paused"
+
+
+def test_resuming_keeps_the_history_a_forever_watch_exists_to_show(store) -> None:
+ """Continuous history survives resume; a stale retirement does not."""
+ _watch(
+ store,
+ "w",
+ mode="forever",
+ enabled=False,
+ last_started_at=PAST,
+ last_finished_at=NOW,
+ retired_at=NOW,
+ last_event_at=NOW,
+ last_exit_code=124,
+ last_error="lifetime timeout",
+ )
+ assert _state(store, "w") == "finished"
+
+ store.set_definition_enabled("w", True, definition_type="watch")
+ row = store.get_watch("w")
+ assert row["lifecycle_state"] == "waiting"
+ assert row["last_started_at"] == PAST
+ assert row["last_event_at"] == NOW
+ assert [row[column] for column in DEFINITION_RETIREMENT_COLUMNS] == [None] * len(
+ DEFINITION_RETIREMENT_COLUMNS
+ )
+
+ store.set_definition_enabled("w", False, definition_type="watch")
+ row = store.get_watch("w")
+ assert row["lifecycle_state"] == "paused"
+ assert row["lifecycle_detail"] is None
+
+ assert definition_resume_clear_columns("watch", "once") == DEFINITION_CYCLE_COLUMNS
+ assert definition_resume_clear_columns("watch", "forever") == DEFINITION_RETIREMENT_COLUMNS
+ assert definition_resume_clear_columns("scheduled", None) == ()
+
+
+def test_a_running_row_is_timed_from_the_run_that_is_running(store) -> None:
+ """``last_started_at`` is the definition's previous cycle. A watch that fired
+ yesterday and started a fresh run a minute ago would report a day of running
+ if the row read that column — a duration assembled from two cycles, which
+ nothing is actually spending."""
+ yesterday = "2026-07-25T00:00:00+00:00"
+ started = "2026-07-26T09:00:00+00:00"
+ _watch(store, "w", mode="forever", last_started_at=yesterday, last_event_at=yesterday)
+ _run(store, "r", "w", status="running", started_at=started)
+
+ row = store.get_watch("w")
+ assert row["lifecycle_state"] == "running"
+ assert row["running_since"] == started
+
+
+def test_a_queued_run_has_no_start_to_report(store) -> None:
+ """``running`` covers queued-or-running. A queued run has not started, so
+ there is no duration — and the row must say nothing rather than reach back to
+ a column that would answer with the last cycle."""
+ _watch(store, "w", last_started_at="2026-07-25T00:00:00+00:00")
+ _run(store, "r", "w", status="queued", started_at=None)
+
+ row = store.get_watch("w")
+ assert row["lifecycle_state"] == "running"
+ assert row["running_since"] is None
+
+
+def test_running_since_is_only_set_while_running(store) -> None:
+ _watch(store, "w", enabled=True, last_started_at=NOW)
+ assert store.get_watch("w")["lifecycle_state"] == "waiting"
+ assert store.get_watch("w")["running_since"] is None
+
+
+def test_batches_are_sized_by_bound_parameters_not_by_values() -> None:
+ """SQLite's cap counts parameters. A resolver matching a three-column tuple
+ binds three per value, so a batch sized in values overflows at a third of the
+ count it was checked at — the failure only shows up on a store big enough to
+ reach it, which is the one place nobody tests."""
+ values = [f"id-{index}" for index in range(1000)]
+
+ assert all(len(batch) <= 400 for batch in _id_batches(values))
+ assert all(len(batch) * 3 <= 400 for batch in _id_batches(values, params_per_value=3))
+ # Every value still lands in exactly one batch, whatever the chunking.
+ assert [item for batch in _id_batches(values, params_per_value=3) for item in batch] == values
+
+
+def test_one_failing_lookup_does_not_blank_the_others(store, monkeypatch) -> None:
+ """These are independent questions, and they used to share one ``except``.
+ A failure resolving session keys took ``process_alive`` down with it, so
+ every watch row said "liveness unknown" for a reason nothing named."""
+ _watch(store, "w", legacy_session_key="slack::channel::C1")
+ store.write_watch_runtime({"watches": {"w": {"running": True, "pid": 42}}}, updated_at=NOW)
+
+ def _boom(*args, **kwargs):
+ raise RuntimeError("session key lookup failed")
+
+ monkeypatch.setattr(SQLiteBackgroundTaskStore, "_key_summaries", staticmethod(_boom))
+
+ row = store.get_watch("w")
+ assert row["process_alive"] is True
+
+
+def test_a_page_costs_a_fixed_number_of_queries(store) -> None:
+ """The reason enrichment is batched: the per-row version this replaced
+ issued a query per row, which a 30-row page paid thirty times over."""
+ for index in range(30):
+ _watch(store, f"watch-{index}", session_id=f"session-{index}")
+ store.write_watch_runtime(
+ {"watches": {f"watch-{index}": {"running": True, "pid": index} for index in range(30)}},
+ updated_at=NOW,
+ )
+
+ statements: list[str] = []
+
+ @event.listens_for(store.engine, "before_cursor_execute")
+ def _record(conn, cursor, statement, parameters, context, executemany): # noqa: ANN001
+ statements.append(statement)
+
+ try:
+ page = store.list_watches_page(status="all", page_request=PageRequest(page=1, limit=30))
+ finally:
+ event.remove(store.engine, "before_cursor_execute", _record)
+
+ assert len(page.items) == 30
+ assert len(statements) <= 4, statements
+
+
+ ("name", "mode", "last_finished_at", "retired_at", "last_event_at", "expected"),
+ [
+ ("legacy-stamped-and-paused", "forever", NOW, None, NOW, "paused"),
+ ("newly-retired-forever", "forever", NOW, NOW, NOW, "finished"),
+ ("newly-paused-forever", "forever", None, None, NOW, "paused"),
+ ("never-run-forever", "forever", None, None, None, "paused"),
+ ("newly-retired-once", "once", NOW, NOW, NOW, "finished"),
+ ("newly-paused-once", "once", NOW, None, NOW, "paused"),
+ ],
+)
+def test_watch_retirement_is_explicit_state(
+ store,
+ name: str,
+ mode: str,
+ last_finished_at: str | None,
+ retired_at: str | None,
+ last_event_at: str | None,
+ expected: str,
+) -> None:
+ """History cannot prove retirement; the dedicated marker can."""
+ _watch(
+ store,
+ name,
+ mode=mode,
+ enabled=False,
+ last_finished_at=last_finished_at,
+ retired_at=retired_at,
+ last_event_at=last_event_at,
+ )
+
+ assert _state(store, name) == expected
+
+
+def test_pausing_a_forever_watch_that_has_been_running_is_a_pause(store) -> None:
+ """The distinction ``retired_at`` exists to make.
+
+ A ``forever`` watch ends a cycle every time it fires or retries and keeps
+ watching. While cycle history was treated as a finish, a watch the user
+ paused after any successful cycle read as *finished* — it left the Paused
+ filter and claimed an ending, with a "normal" or "error" verdict invented
+ from whatever the last cycle happened to exit with.
+
+ The store writes ``retired_at`` only when it also switches the watch off,
+ so pause and retirement are finally two different facts.
+ """
+ _watch(store, "paused-after-cycles", mode="forever", enabled=False, last_exit_code=0, last_event_at=NOW)
+ _watch(store, "paused-mid-retry", mode="forever", enabled=False, last_exit_code=1, last_error="boom")
+ _watch(
+ store,
+ "retired-on-error",
+ mode="forever",
+ enabled=False,
+ last_finished_at=NOW,
+ retired_at=NOW,
+ last_exit_code=1,
+ )
+
+ assert _state(store, "paused-after-cycles") == "paused"
+ assert _state(store, "paused-mid-retry") == "paused"
+ assert _state(store, "retired-on-error") == "finished"
+
+
+def test_a_forever_watch_retired_by_its_lifetime_says_it_timed_out(store) -> None:
+ """Running out of lifetime is the supervisor's deadline, not a clean stop.
+
+ The retirement path wrote no exit code, so the ending classifier fell
+ through to ``normal`` and a watch the supervisor cut off reported having
+ finished normally. It carries the same 124 the per-cycle timeout uses.
+ """
+ _watch(
+ store,
+ "expired",
+ mode="forever",
+ enabled=False,
+ last_finished_at=NOW,
+ retired_at=NOW,
+ last_exit_code=124,
+ )
+
+ row = store.get_watch("expired")
+ assert row["lifecycle_state"] == "finished"
+ assert definition_lifecycle_detail(
+ lifecycle_state=row["lifecycle_state"],
+ last_exit_code=row["last_exit_code"],
+ last_error=row["last_error"],
+ ) == "timeout"
+
+
+def test_re_enabling_a_fired_one_shot_task_does_not_make_it_waiting_again(store) -> None:
+ """``enabled`` is not a promise of a future fire.
+
+ Switching a one-shot back on leaves its ``run_at`` in the past, so
+ ``compute_next_run_at`` has nothing to offer it. Reading the switch before
+ history parked such a task in the default Active view forever, inflating the
+ badge with a row that will never run.
+ """
+ _task(store, "fired-then-re-enabled", schedule_type="at", run_at=NOW, enabled=True, last_run_at=NOW)
+
+ assert store.get_scheduled_task("fired-then-re-enabled")["lifecycle_state"] == "finished"
+ assert compute_next_run_at(
+ enabled=True, schedule_type="at", cron=None, run_at=NOW, timezone_name="UTC"
+ ) is None
+
+
+def test_running_a_future_one_shot_by_hand_leaves_it_waiting(store) -> None:
+ """``vibe task run`` does not consume the schedule.
+
+ A manual run records ``last_run_at`` and deliberately leaves the task armed
+ (``mark_task_result(disable_one_shot=False)``), so treating "has run once"
+ as "is over" retired a task APScheduler was still holding a future fire for
+ — and dropped it out of the default Active view on its way out.
+ """
+ _task(store, "run-early", schedule_type="at", run_at=FUTURE, enabled=True, last_run_at=NOW)
+
+ assert store.get_scheduled_task("run-early")["lifecycle_state"] == "waiting"
+ # The state and the time printed next to it come from one fact.
+ assert compute_next_run_at(
+ enabled=True, schedule_type="at", cron=None, run_at=FUTURE, timezone_name="UTC"
+ ) is not None
+
+
+def test_a_one_shot_whose_moment_has_passed_is_finished_even_if_it_never_ran(store) -> None:
+ """The instant is the fact, not the run history.
+
+ A task whose moment went by while the service was down has nothing left to
+ do, and saying *waiting* would promise a fire that can never come.
+ """
+ _task(store, "missed-it", schedule_type="at", run_at=PAST, enabled=True, last_run_at=None)
+
+ assert store.get_scheduled_task("missed-it")["lifecycle_state"] == "finished"
+ assert compute_next_run_at(
+ enabled=True, schedule_type="at", cron=None, run_at=PAST, timezone_name="UTC"
+ ) is None
+
+
+def test_pausing_a_one_shot_before_its_moment_is_a_pause(store) -> None:
+ """Switched off with the instant still ahead: the user's doing, and undoable."""
+ _task(store, "held-back", schedule_type="at", run_at=FUTURE, enabled=False)
+
+ assert store.get_scheduled_task("held-back")["lifecycle_state"] == "paused"
+
+
+def test_one_shot_states_and_counts_agree_on_the_clock(store) -> None:
+ """Whatever the clock decides, the chips and the rows decide it together.
+
+ Both read ``definition_lifecycle_expression``; this pins that the ``at``
+ branch's time comparison survives the trip through ``GROUP BY``.
+ """
+ _task(store, "ahead", schedule_type="at", run_at=FUTURE, enabled=True, last_run_at=NOW)
+ _task(store, "behind", schedule_type="at", run_at=PAST, enabled=True)
+ _task(store, "paused-ahead", schedule_type="at", run_at=FUTURE, enabled=False)
+
+ page = store.list_scheduled_tasks_page(page_request=PageRequest(limit=50))
+ states = {row["id"]: row["lifecycle_state"] for row in page.items}
+ assert states == {"ahead": "waiting", "behind": "finished", "paused-ahead": "paused"}
+
+ counts = store.count_scheduled_tasks()
+ assert (counts["waiting"], counts["finished"], counts["paused"]) == (1, 1, 1)
+
+
+def test_mark_cycle_result_stamps_a_finish_only_when_it_retires_the_watch(tmp_path: Path) -> None:
+ """Only the cycle that changes enabled -> disabled owns retirement state."""
+ from core.watches import ManagedWatchStore
+
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ paused = store.add_watch(
+ name="w",
+ session_key="",
+ command=[],
+ shell_command="true",
+ prefix=None,
+ cwd=None,
+ mode="forever",
+ timeout_seconds=0.0,
+ lifetime_timeout_seconds=0.0,
+ retry_exit_codes=[1],
+ retry_delay_seconds=0.0,
+ post_to=None,
+ deliver_key=None,
+ )
+
+ # A result landing after a manual pause cannot turn it into retirement.
+ store.set_enabled(paused.id, False)
+ before = (paused.last_finished_at, paused.retired_at)
+ store.mark_cycle_result(paused.id, exit_code=0, error=None, disable=True)
+ assert (paused.last_finished_at, paused.retired_at) == before == (None, None)
+
+ retiring = store.add_watch(
+ name="retiring",
+ session_key="",
+ command=[],
+ shell_command="true",
+ prefix=None,
+ cwd=None,
+ mode="forever",
+ timeout_seconds=0.0,
+ lifetime_timeout_seconds=0.0,
+ retry_exit_codes=[1],
+ retry_delay_seconds=0.0,
+ post_to=None,
+ deliver_key=None,
+ )
+ store.mark_cycle_result(retiring.id, exit_code=124, error=None, disable=True)
+ retired = store.get_watch(retiring.id)
+ assert retired.last_finished_at is not None
+ assert retired.retired_at is not None
+ assert retired.last_error is None
+ assert retired.enabled is False
+
+ # A later non-disabling result cannot erase a genuine retirement.
+ before = (retired.last_finished_at, retired.retired_at)
+ store.mark_cycle_result(retiring.id, exit_code=0, error=None, event_detected=True, disable=False)
+ assert (retired.last_finished_at, retired.retired_at) == before
+
+ continuing = store.add_watch(
+ name="continuing",
+ session_key="",
+ command=[],
+ shell_command="true",
+ prefix=None,
+ cwd=None,
+ mode="forever",
+ timeout_seconds=0.0,
+ lifetime_timeout_seconds=0.0,
+ retry_exit_codes=[1],
+ retry_delay_seconds=0.0,
+ post_to=None,
+ deliver_key=None,
+ )
+ continuing.last_finished_at = NOW
+ continuing.retired_at = NOW
+ store.upsert_watch(continuing)
+ store.mark_cycle_result(continuing.id, exit_code=1, error="retrying", disable=False)
+ assert continuing.last_finished_at is None
+ assert continuing.retired_at is None
+
+
+def test_the_scheduler_and_the_row_read_a_naive_run_at_the_same_way() -> None:
+ """One resolver, two callers — the defect this closes was two of them.
+
+ ``compute_next_run_at`` attached the task's own zone to a naive ``run_at``
+ while ``_build_trigger`` called ``.astimezone()``, which reads a naive value
+ in the *host* zone first. The row then promised a fire time the scheduler
+ would not honour, off by the offset between the two zones — a gap that only
+ opens on rows whose timezone is not the machine's, so it never showed up on
+ the developer's own tasks.
+ """
+ from core.scheduled_tasks import ScheduledTask, ScheduledTaskService
+
+ run_at = f"{datetime.now().year + 1}-01-15T12:00:00"
+ task = ScheduledTask(
+ id="t",
+ name="t",
+ session_key="",
+ prompt="go",
+ schedule_type="at",
+ run_at=run_at,
+ timezone=NEW_YORK,
+ )
+
+ trigger = ScheduledTaskService._build_trigger(object(), task)
+ shown = compute_next_run_at(
+ enabled=True, schedule_type="at", cron=None, run_at=run_at, timezone_name=NEW_YORK
+ )
+
+ assert shown is not None
+ assert trigger.run_date == datetime.fromisoformat(shown)
+ # And that instant is noon in New York, whatever zone the host is in.
+ assert trigger.run_date.astimezone(ZoneInfo(NEW_YORK)).hour == 12
diff --git a/tests/test_harness_run_projection.py b/tests/test_harness_run_projection.py
index 2f32ee39e..8659397e1 100644
--- a/tests/test_harness_run_projection.py
+++ b/tests/test_harness_run_projection.py
@@ -124,7 +124,12 @@ def test_run_payload_resolves_every_session_state(tmp_path: Path) -> None:
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_is_workbench"] is False # reads as a channel, not as a session title
+ # A ``session_key`` names a scope, not a session row, so there is no
+ # ``/chat/<id>`` to offer. An IM run bound by ``session_id`` *is* linkable
+ # (plan §4.5) — what makes this one unlinkable is the missing id, not the
+ # platform.
+ assert im["session_openable"] is False
assert im["session_platform"] == "slack"
assert im["session_label"] == "#dev-ops" # display name, not the raw channel id
@@ -490,6 +495,124 @@ def test_every_projected_label_is_searchable(tmp_path: Path) -> None:
assert _UI_VOCABULARY <= present, f"search exclusion no longer projected: {_UI_VOCABULARY - present}"
+def _flat_strings(payload: dict) -> set[str]:
+ """Every string anywhere in the payload, nested objects included."""
+ found: set[str] = set()
+
+ def walk(node: dict) -> None:
+ for value in node.values():
+ if isinstance(value, dict):
+ walk(value)
+ elif isinstance(value, str) and value:
+ found.add(value)
+
+ walk(payload)
+ return found
+
+
+def test_no_displayed_id_is_left_as_a_bare_foreign_key(tmp_path: Path) -> None:
+ """The gap the projection test above could not see.
+
+ ``_projected_text`` asks which strings the *enrichment* invented, so it
+ skipped everything that is a real ``agent_runs`` column — and one of those
+ columns, ``source_actor``, is a foreign key to a session. The Run detail's
+ 来源 field rendered it verbatim, so the panel printed ``ses53w9zb8ba6`` where
+ a title and a link belonged: precisely the raw-hash defect the projection
+ exists to remove, hiding inside a column that looked stored rather than
+ resolved.
+
+ Stated without naming fields: **if a payload string is the id of a session
+ we could have named, the payload must also carry that session's name.** A
+ future column that holds a session id fails here on the day it is added,
+ whether it is projected or stored.
+ """
+ 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_bound", "被调度会话")
+ caller = _make_workbench_session(conn, tmp_path, "proj_caller", "发起方编排会话")
+ reporter = _make_workbench_session(conn, tmp_path, "proj_report", "回调汇报会话")
+ finally:
+ engine.dispose()
+
+ titles = {bound: "被调度会话", caller: "发起方编排会话", reporter: "回调汇报会话"}
+
+ store = SQLiteBackgroundTaskStore(db_path)
+ try:
+ store.enqueue_run(
+ _run(
+ "run_spawned",
+ session_id=bound,
+ callback_session_id=reporter,
+ source_kind="agent",
+ source_actor=caller,
+ message="delegated work",
+ )
+ )
+ listed = store.list_runs_page(page_request=None).items[0]
+ detail = store.get_run("run_spawned")
+ # A caller session is a session like any other: findable by its name.
+ by_caller_title = _search_run_ids(store, "发起方编排")
+ finally:
+ store.close()
+
+ for payload, where in ((listed, "list"), (detail, "detail")):
+ strings = _flat_strings(payload)
+ for session_id, title in titles.items():
+ if session_id in strings:
+ assert title in strings, (
+ f"{where} payload shows session id {session_id!r} with no resolved name — "
+ f"the UI can only print the hash"
+ )
+
+ # Not vacuous: the fixture really did put all three ids on the row.
+ assert titles.keys() <= _flat_strings(listed) | {bound, caller, reporter}
+ assert listed["source_session"]["session_title"] == "发起方编排会话"
+ assert listed["source_session"]["session_openable"] is True
+ assert by_caller_title == {"run_spawned"}
+
+
+def test_source_session_resolves_only_when_the_actor_is_a_session(tmp_path: Path) -> None:
+ """``source_actor`` is polymorphic. Only ``source_kind == "agent"`` puts a
+ session id in it; a callback stores the parent run id and a vault approval
+ stores ``vault:<request>``. Resolving those as sessions would report every
+ one of them as a *deleted* session — and matching their raw handles against
+ session titles would make search find text the row does not display."""
+ db_path = tmp_path / "vibe.sqlite"
+ _build_schema(db_path)
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ caller = _make_workbench_session(conn, tmp_path, "proj_poly", "编排会话")
+ finally:
+ engine.dispose()
+
+ store = SQLiteBackgroundTaskStore(db_path)
+ try:
+ store.enqueue_run(_run("run_agent", source_kind="agent", source_actor=caller))
+ # Deliberate id collision: only the agent-sourced row may resolve or
+ # search through the matching session title.
+ store.enqueue_run(_run("run_callback", source_kind="callback", source_actor=caller))
+ store.enqueue_run(_run("run_vault", source_kind="vault", source_actor="vault:req_42"))
+ store.enqueue_run(_run("run_human", source_kind="human", source_actor="cyh"))
+ store.enqueue_run(_run("run_bare"))
+ runs = {run["id"]: run for run in store.list_runs_page(page_request=None).items}
+ by_title = _search_run_ids(store, "编排会话")
+ finally:
+ store.close()
+
+ assert runs["run_agent"]["source_session"]["session_title"] == "编排会话"
+ assert by_title == {"run_agent"}
+ for run_id in ("run_callback", "run_vault", "run_human", "run_bare"):
+ assert runs[run_id]["source_session"] is None, run_id
+ # The raw handle survives — it is still the only identity these have.
+ assert runs[run_id]["source_actor"] == (
+ None if run_id == "run_bare" else runs[run_id]["source_actor"]
+ )
+
+
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
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index 01ff269bc..07193077f 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -1142,22 +1142,36 @@ def test_sqlite_definition_listing_pages_filter_and_count_without_loading_all(tm
}
)
- enabled_tasks = sqlite.list_scheduled_tasks_page(
- status="enabled",
+ waiting_tasks = sqlite.list_scheduled_tasks_page(
+ status="waiting",
page_request=PageRequest(page=1, limit=2),
)
- disabled_watches = sqlite.list_watches_page(
- status="disabled",
+ paused_watches = sqlite.list_watches_page(
+ status="paused",
query="deploy",
page_request=PageRequest(page=1, limit=3),
)
- assert [item["id"] for item in enabled_tasks.items] == ["task-4", "task-2"]
- assert enabled_tasks.has_more is True
- assert sqlite.count_scheduled_tasks() == {"all": 5, "enabled": 3, "disabled": 2}
- assert [item["id"] for item in disabled_watches.items] == ["watch-5", "watch-4", "watch-3"]
- assert disabled_watches.has_more is True
- assert sqlite.count_watches(query="deploy") == {"all": 6, "enabled": 2, "disabled": 4}
+ assert [item["id"] for item in waiting_tasks.items] == ["task-4", "task-2"]
+ assert waiting_tasks.has_more is True
+ # Nothing here has ever run, so nothing is finished: a switched-off cron
+ # task and a never-started watch are both someone having paused them.
+ assert sqlite.count_scheduled_tasks() == {
+ "total": 5,
+ "running": 0,
+ "waiting": 3,
+ "paused": 2,
+ "finished": 0,
+ }
+ assert [item["id"] for item in paused_watches.items] == ["watch-5", "watch-4", "watch-3"]
+ assert paused_watches.has_more is True
+ assert sqlite.count_watches(query="deploy") == {
+ "total": 6,
+ "running": 0,
+ "waiting": 2,
+ "paused": 4,
+ "finished": 0,
+ }
finally:
sqlite.close()
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index 308b21004..6b71e36a8 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -8,6 +8,7 @@ import threading
from pathlib import Path
import pytest
+from alembic.script import ScriptDirectory
from config import paths
from config.v2_settings import ChannelSettings, RoutingSettings, SettingsState, SettingsStore
@@ -19,7 +20,7 @@ from storage.models import metadata
from storage.settings_service import SQLiteSettingsService
-HEAD_REVISION = "20260726_0035"
+HEAD_REVISION = "20260726_0036"
def _index_sql(conn: sqlite3.Connection, name: str) -> str:
@@ -28,6 +29,13 @@ def _index_sql(conn: sqlite3.Connection, name: str) -> str:
return str(row[0] or "")
+def test_alembic_script_directory_has_exactly_one_head() -> None:
+ heads = ScriptDirectory.from_config(migrations.alembic_config()).get_heads()
+
+ assert len(heads) == 1
+ assert heads[0] == HEAD_REVISION
+
+
def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"
@@ -201,6 +209,46 @@ def test_show_dispatch_state_migration_accepts_legacy_rows_and_defaults_new_rows
assert new_state == ('{"state":"none"}',)
+def test_retirement_marker_migration_is_forward_only(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260726_0035")
+
+ with sqlite3.connect(db_path) as conn:
+ assert "retired_at" not in {
+ row[1] for row in conn.execute("pragma table_info(run_definitions)")
+ }
+ conn.execute(
+ """
+ insert into run_definitions (
+ id, definition_type, mode, enabled, last_finished_at,
+ created_at, updated_at, metadata_json
+ ) values (
+ 'legacy-paused-watch', 'watch', 'forever', 0,
+ '2026-07-26T00:00:00+00:00',
+ '2026-07-26T00:00:00+00:00',
+ '2026-07-26T00:00:00+00:00', '{}'
+ )
+ """
+ )
+ conn.commit()
+
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ columns = {
+ row[1] for row in conn.execute("pragma table_info(run_definitions)")
+ }
+ row = conn.execute(
+ "select last_finished_at, retired_at from run_definitions where id = ?",
+ ("legacy-paused-watch",),
+ ).fetchone()
+ version = conn.execute("select version_num from alembic_version").fetchone()
+
+ assert "retired_at" in columns
+ assert row == ("2026-07-26T00:00:00+00:00", None)
+ assert version == (HEAD_REVISION,)
+
+
def test_session_pinning_migration_preserves_existing_sessions_as_unpinned(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"
run_migrations(db_path, revision="20260723_0033")
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 2cb1fd1cf..0f7c71193 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -313,8 +313,8 @@ def test_harness_routes_page_filter_and_return_counts(monkeypatch, tmp_path):
client = app.test_client()
legacy_tasks = client.get("/api/harness/tasks").get_json()
legacy_watches = client.get("/api/harness/watches").get_json()
- tasks = client.get("/api/harness/tasks?status=enabled&page=1&limit=2").get_json()
- watches = client.get("/api/harness/watches?status=disabled&query=deploy&page=1&limit=2").get_json()
+ tasks = client.get("/api/harness/tasks?status=waiting&page=1&limit=2").get_json()
+ watches = client.get("/api/harness/watches?status=paused&query=deploy&page=1&limit=2").get_json()
runs = client.get("/api/harness/runs?page=1&limit=2").get_json()
counts = client.get("/api/harness/counts").get_json()
@@ -323,13 +323,25 @@ def test_harness_routes_page_filter_and_return_counts(monkeypatch, tmp_path):
assert len(legacy_watches["watches"]) == 6
assert legacy_watches["has_more"] is False
assert [item["id"] for item in tasks["tasks"]] == ["task-2", "task-1"]
- assert tasks["counts"] == {"all": 5, "enabled": 3, "disabled": 2}
+ assert tasks["counts"] == {"total": 5, "running": 0, "waiting": 3, "paused": 2, "finished": 0}
assert tasks["total"] == 3
assert tasks["has_more"] is True
assert [item["id"] for item in watches["watches"]] == ["watch-5", "watch-4"]
- assert watches["counts"] == {"all": 6, "enabled": 1, "disabled": 5}
+ assert watches["counts"] == {"total": 6, "running": 0, "waiting": 1, "paused": 5, "finished": 0}
assert watches["total"] == 5
assert watches["has_more"] is True
+ # The default view spans two states, so its total is a sum rather than a
+ # count key — the one place a wrong "total" would show a number the list
+ # cannot produce.
+ active = client.get("/api/harness/watches?status=active&page=1&limit=10").get_json()
+ assert active["total"] == 1
+ assert len(active["watches"]) == 1
+ # The frozen row contract (plan §3) reaches the client over HTTP, not just
+ # out of the store.
+ assert active["watches"][0]["lifecycle_state"] == "waiting"
+ assert active["watches"][0]["lifecycle_detail"] is None
+ assert active["watches"][0]["process_alive"] is None
+ assert tasks["tasks"][0]["next_run_at"]
assert [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.
@@ -342,8 +354,8 @@ def test_harness_routes_page_filter_and_return_counts(monkeypatch, tmp_path):
assert runs["counts"]["running"] == 1
assert runs["counts"]["succeeded"] == 1
assert runs["counts"]["failed"] == 1
- assert counts["tasks"]["all"] == 5
- assert counts["watches"]["disabled"] == 5
+ assert counts["tasks"]["total"] == 5
+ assert counts["watches"]["paused"] == 5
assert counts["runs"]["all"] == 4
@@ -382,12 +394,18 @@ def test_harness_bootstrap_returns_counts_and_selected_page(monkeypatch, tmp_pat
store.close()
client = app.test_client()
- response = client.get("/api/harness/bootstrap?tab=tasks&status=enabled&page=1&limit=1")
+ response = client.get("/api/harness/bootstrap?tab=tasks&status=waiting&page=1&limit=1")
assert response.status_code == 200
assert response.headers["X-Vibe-Request-Ms"]
payload = response.get_json()
- assert payload["counts"]["tasks"] == {"all": 4, "enabled": 2, "disabled": 2}
+ assert payload["counts"]["tasks"] == {
+ "total": 4,
+ "running": 0,
+ "waiting": 2,
+ "paused": 2,
+ "finished": 0,
+ }
assert payload["counts"]["runs"]["all"] == 2
assert payload["page"]["tasks"][0]["id"] == "task-1"
assert payload["page"]["total"] == 2
diff --git a/ui/src/components/workbench/AgentGraphDetail.tsx b/ui/src/components/workbench/AgentGraphDetail.tsx
index c41cb826d..0ebfab228 100644
--- a/ui/src/components/workbench/AgentGraphDetail.tsx
+++ b/ui/src/components/workbench/AgentGraphDetail.tsx
@@ -91,7 +91,7 @@ export const AgentGraphDetail: React.FC<AgentGraphDetailProps> = ({
const meta = statusMeta(node.status);
const background = isBackground(node);
const timeLabel = node.live
- ? formatElapsed(node.elapsed_seconds)
+ ? formatElapsed(node.elapsed_seconds, t)
: formatRelativeTime(node.last_active_at ?? node.created_at, t);
const callerTitle = (sessionId: string): string => {
@@ -287,7 +287,7 @@ export const AgentGraphDetail: React.FC<AgentGraphDetailProps> = ({
<code className="font-mono text-foreground">{run.id}</code>
<span className="text-muted">{t(statusMeta(runStatus(run.status)).labelKey)}</span>
<span className="flex-1" />
- <span className="font-mono text-[10px] text-muted">{formatElapsed(runElapsedSeconds(run))}</span>
+ <span className="font-mono text-[10px] text-muted">{formatElapsed(runElapsedSeconds(run), t)}</span>
</Link>
))}
</div>
diff --git a/ui/src/components/workbench/AgentGraphNodeCard.tsx b/ui/src/components/workbench/AgentGraphNodeCard.tsx
index a81c33baa..0114adbae 100644
--- a/ui/src/components/workbench/AgentGraphNodeCard.tsx
+++ b/ui/src/components/workbench/AgentGraphNodeCard.tsx
@@ -50,7 +50,7 @@ export const AgentGraphNodeCard: React.FC<AgentGraphNodeCardProps> = ({
const backendClass = BACKEND_TEXT[node.agent_backend as Backend] ?? 'text-muted';
const background = isBackground(node);
const timeLabel = node.live
- ? formatElapsed(node.elapsed_seconds)
+ ? formatElapsed(node.elapsed_seconds, t)
: formatRelativeTime(node.last_active_at ?? node.created_at, t);
return (
diff --git a/ui/src/components/workbench/AgentGraphOrphanStrip.tsx b/ui/src/components/workbench/AgentGraphOrphanStrip.tsx
index 913e5f308..10643ace7 100644
--- a/ui/src/components/workbench/AgentGraphOrphanStrip.tsx
+++ b/ui/src/components/workbench/AgentGraphOrphanStrip.tsx
@@ -132,7 +132,7 @@ const OrphanRow: React.FC<{ row: RunningAgent; onEnd: (r: RunningAgent) => Promi
)}
<span className="flex-1" />
{row.elapsed_seconds != null && (
- <span className="shrink-0 font-mono text-[10px] text-muted">{formatElapsed(row.elapsed_seconds)}</span>
+ <span className="shrink-0 font-mono text-[10px] text-muted">{formatElapsed(row.elapsed_seconds, t)}</span>
)}
<Button
type="button"
diff --git a/ui/src/components/workbench/HarnessPage.test.tsx b/ui/src/components/workbench/HarnessPage.test.tsx
index 59018bdd9..bd046355c 100644
--- a/ui/src/components/workbench/HarnessPage.test.tsx
+++ b/ui/src/components/workbench/HarnessPage.test.tsx
@@ -6,8 +6,8 @@ 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 type { HarnessRun, HarnessSessionSummary, HarnessWatch } from '../../context/ApiContext';
+import { DetailSession, RunTriggerChip, WatchDetail, harnessEmptyStateKey, harnessTabFromParam } from './HarnessPage';
import { RUN_TYPES, harnessSessionState, runRowTitle, runStatusLabel, runTypeLabel, runTypeOptions } from './harnessRuns';
const i18n = createInstance();
@@ -31,6 +31,7 @@ const NO_SESSION: HarnessSessionSummary = {
session_scope_kind: null,
session_label: null,
session_is_workbench: false,
+ session_openable: false,
};
const run = (overrides: Partial<HarnessRun>): HarnessRun =>
@@ -50,10 +51,76 @@ const run = (overrides: Partial<HarnessRun>): HarnessRun =>
...overrides,
}) as HarnessRun;
+const watch = (overrides: Partial<HarnessWatch>): HarnessWatch => ({
+ id: 'watch-1',
+ name: 'CI watcher',
+ agent_name: null,
+ session_policy: null,
+ session_id: null,
+ session_key: '',
+ command: [],
+ shell_command: 'true',
+ prefix: null,
+ message: null,
+ message_payload: null,
+ cwd: null,
+ mode: 'once',
+ timeout_seconds: 0,
+ lifetime_timeout_seconds: 0,
+ retry_exit_codes: [],
+ retry_delay_seconds: 0,
+ post_to: null,
+ deliver_key: null,
+ enabled: false,
+ created_at: null,
+ updated_at: null,
+ last_started_at: null,
+ last_finished_at: null,
+ retired_at: null,
+ last_event_at: null,
+ last_error: null,
+ last_exit_code: null,
+ lifecycle_state: 'paused',
+ lifecycle_detail: null,
+ next_run_at: null,
+ waiting_since: null,
+ running_since: null,
+ runtime: { running: false },
+ process_alive: null,
+ ...NO_SESSION,
+ ...overrides,
+});
+
// Translation-free stand-in: proves the mappers pick the right key without
// depending on the copy.
const key = (k: string) => k;
+describe('harnessTabFromParam', () => {
+ it('opens the tab a link names', () => {
+ expect(harnessTabFromParam('watches')).toBe('watches');
+ expect(harnessTabFromParam('runs')).toBe('runs');
+ });
+
+ it('lands a link to a tab that no longer exists on Tasks', () => {
+ // ?tab=webhooks is still in bookmarks and in old chat messages. It must
+ // open a real tab, not a page with nothing lit.
+ expect(harnessTabFromParam('webhooks')).toBe('tasks');
+ expect(harnessTabFromParam('')).toBe('tasks');
+ expect(harnessTabFromParam(null)).toBe('tasks');
+ });
+});
+
+describe('harnessEmptyStateKey', () => {
+ it.each([
+ ['tasks', 'harness.emptyTasks', 'harness.noTaskMatches'],
+ ['watches', 'harness.emptyWatches', 'harness.noWatchMatches'],
+ ['runs', 'harness.emptyRuns', 'harness.noRunMatches'],
+ ] as const)('distinguishes an empty store from an empty %s view', (kind, emptyKey, filteredKey) => {
+ expect(harnessEmptyStateKey(kind, false)).toBe(emptyKey);
+ expect(harnessEmptyStateKey(kind, true)).toBe(filteredKey);
+ });
+});
+
describe('runRowTitle', () => {
it("uses the message's first non-empty line, whitespace collapsed", () => {
expect(
@@ -141,7 +208,12 @@ 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' }}
+ summary={{
+ ...NO_SESSION,
+ session_is_workbench: true,
+ session_openable: true,
+ session_title: 'Weekly digest',
+ }}
sessionId="sess-1"
/>,
);
@@ -159,12 +231,34 @@ describe('DetailSession', () => {
expect(html).not.toContain('/chat/');
});
- it('shows an IM session without linking it', () => {
+ // Linkability is one predicate now (plan §4.5): /chat/<id> serves an
+ // IM-bound session exactly as it serves a workbench one, so the row that
+ // names it also opens it. What stays IM-specific is only how it *reads* —
+ // platform icon and channel label instead of a session title.
+ it('links an IM session while still showing it as IM', () => {
const html = render(
- <DetailSession summary={{ ...NO_SESSION, session_platform: 'slack', session_label: '#ops' }} sessionId="sess-2" />,
+ <DetailSession
+ summary={{ ...NO_SESSION, session_platform: 'slack', session_label: '#ops', session_openable: true }}
+ sessionId="sess-2"
+ />,
);
expect(html).toContain('#ops');
+ expect(html).toContain('slack');
+ expect(html).toContain('href="/chat/sess-2"');
+ });
+
+ it('names a session it must not link without pretending it is gone', () => {
+ // The one thing /chat/<id> genuinely refuses: the legacy private_agent_run
+ // pseudo-scope. The server clears session_openable; the label stays.
+ const html = render(
+ <DetailSession
+ summary={{ ...NO_SESSION, session_is_workbench: true, session_title: 'Spawned run' }}
+ sessionId="sess-3"
+ />,
+ );
+
+ expect(html).toContain('Spawned run');
expect(html).not.toContain('<a ');
});
@@ -176,6 +270,33 @@ describe('DetailSession', () => {
});
});
+describe('WatchDetail runtime', () => {
+ it.each([
+ [
+ 'disabled and stopped',
+ watch({ enabled: false, process_alive: false }),
+ { runtime: false, line: null, pid: null },
+ ],
+ [
+ 'enabled and stopped',
+ watch({ enabled: true, process_alive: false }),
+ { runtime: true, line: '<span class="text-[12px] text-pink">process exited</span>', pid: null },
+ ],
+ [
+ 'disabled and alive',
+ watch({ enabled: false, process_alive: true, runtime: { running: true, pid: 4321 } }),
+ { runtime: true, line: '<span class="text-[12px] text-foreground">process running</span>', pid: 'pid 4321' },
+ ],
+ ] as const)('renders %s consistently with the row', (_name, value, expected) => {
+ const html = render(<WatchDetail watch={value} onToggleEnabled={() => undefined} pending={false} />);
+
+ expect(html.includes('>Runtime<')).toBe(expected.runtime);
+ if (expected.line) expect(html).toContain(expected.line);
+ else expect(html).not.toContain('process exited');
+ if (expected.pid) expect(html).toContain(expected.pid);
+ });
+});
+
describe('RunTriggerChip', () => {
it('links a live watch back to its definition row', () => {
const html = render(
diff --git a/ui/src/components/workbench/HarnessPage.tsx b/ui/src/components/workbench/HarnessPage.tsx
index 5f6e69bbd..cb8c4519d 100644
--- a/ui/src/components/workbench/HarnessPage.tsx
+++ b/ui/src/components/workbench/HarnessPage.tsx
@@ -5,7 +5,6 @@ import {
Activity,
Calendar,
Eye,
- Webhook,
History,
Plus,
Play,
@@ -44,6 +43,7 @@ import type {
import { formatRelativeTime } from '../../lib/relativeTime';
import { formatLocalDateTime } from '../../lib/datetime';
import { formatElapsed, runElapsedSeconds } from '../../lib/agentGraph';
+import { useVisibleNow } from '../../lib/useVisibleNow';
import { PlatformIcon } from '../visual/PlatformIcon';
import { CreateViaChatDialog } from './CreateViaChatDialog';
import type { CreateViaChatKind } from './CreateViaChatDialog';
@@ -57,31 +57,53 @@ import {
runTypeLabel,
runTypeOptions,
} from './harnessRuns';
+import {
+ DEFAULT_DEFINITION_STATUS,
+ DEFINITION_STATUS_FILTERS,
+ definitionActiveCount,
+ definitionChipLabel,
+ definitionRowLine,
+ definitionRowTitle,
+ definitionStatusCount,
+ definitionSurvivesToggle,
+ formatWallTime,
+ humanizeCron,
+ humanizeTime,
+ isWallClockTimestamp,
+ lifecycleLabel,
+ waiterExpectedAlive,
+} from './harnessLifecycle';
+import type {
+ HarnessDefinitionKind,
+ HarnessLifecycleState,
+ HarnessRowAlert,
+} from './harnessLifecycle';
import { Badge } from '../ui/badge';
import { Button } from '../ui/button';
import { Switch } from '../ui/switch';
-// Task/watch rows fall back to their id when no name is set, and those
-// ids are 32-char hex strings that wreck the row layout. Show the first
-// 10 chars + ellipsis so the row still hints at "id-shaped" without
-// dominating.
-function displayTitle(value: string | null | undefined, fallbackId: string): string {
- if (value && value.trim()) return value;
- if (fallbackId.length <= 13) return fallbackId;
- return `${fallbackId.slice(0, 10)}…`;
-}
-
+// Detail-panel schedule, in words. The literal it was derived from is printed
+// beside it by the caller — humanizing must never be the only copy of a value
+// an operator may need to paste back into a CLI.
function formatSchedule(task: HarnessTask, t: (k: string, opts?: any) => string): string {
- if (task.cron) return t('harness.schedule.cron', { value: task.cron });
- if (task.run_at) return t('harness.schedule.oneShot', { value: task.run_at });
+ if (task.cron) return humanizeCron(task.cron, t);
+ // A one-shot's ``run_at`` is stored as the user typed it, which is usually a
+ // wall-clock reading in ``task.timezone`` with no offset. The scheduler has
+ // already resolved it against that zone — take its answer. Only when it
+ // promises nothing (already fired, or paused) fall back to the literal, and
+ // then say which zone the clock belongs to instead of implying the viewer's.
+ if (task.run_at) {
+ if (task.next_run_at) return humanizeTime(task.next_run_at, t);
+ if (isWallClockTimestamp(task.run_at)) return formatWallTime(task.run_at, task.timezone, t);
+ return humanizeTime(task.run_at, t);
+ }
return task.schedule_type || t('harness.unknownSchedule');
}
-type TabKey = 'tasks' | 'watches' | 'webhooks' | 'runs';
+type TabKey = 'tasks' | 'watches' | 'runs';
-// Status segments per tab. Definitions filter by enabled/disabled; runs by
+// Status segments per tab. Definitions filter by what they are doing; 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
@@ -92,9 +114,35 @@ const RUN_STATUS_FILTERS = ['all', 'queued', 'running', 'succeeded', 'failed', '
// built-in name for, and those are just as selectable.
type RunTypeFilter = string;
-const TAB_ORDER: TabKey[] = ['tasks', 'watches', 'webhooks', 'runs'];
+const TAB_ORDER: TabKey[] = ['tasks', 'watches', 'runs'];
+const DEFAULT_TAB: TabKey = 'tasks';
+
+// Which tab a ``?tab=`` param opens. Anything that is not a tab opens the
+// default rather than selecting nothing — ``?tab=webhooks`` still arrives from
+// links and bookmarks made before the Webhooks tab was removed, and must land
+// on Tasks, not on an empty page with no tab lit.
+//
+// One function rather than a guard here and a ``useState`` initializer three
+// hundred lines away, so removing a tab later cannot strand its old links.
+export function harnessTabFromParam(param: string | null | undefined): TabKey {
+ return (TAB_ORDER as string[]).includes(param ?? '') ? (param as TabKey) : DEFAULT_TAB;
+}
+
+export function harnessEmptyStateKey(kind: TabKey, hasStoredRows: boolean): string {
+ if (!hasStoredRows) {
+ return kind === 'tasks' ? 'harness.emptyTasks' : kind === 'watches' ? 'harness.emptyWatches' : 'harness.emptyRuns';
+ }
+ return kind === 'tasks' ? 'harness.noTaskMatches' : kind === 'watches' ? 'harness.noWatchMatches' : 'harness.noRunMatches';
+}
+
const PAGE_LIMIT = 30;
-const EMPTY_DEFINITION_COUNTS: HarnessDefinitionCounts = { all: 0, enabled: 0, disabled: 0 };
+const EMPTY_DEFINITION_COUNTS: HarnessDefinitionCounts = {
+ total: 0,
+ running: 0,
+ waiting: 0,
+ paused: 0,
+ finished: 0,
+};
const EMPTY_RUN_COUNTS: HarnessRunCounts = {
all: 0,
queued: 0,
@@ -113,7 +161,8 @@ type Selection =
export const HarnessPage: React.FC = () => {
const { t } = useTranslation();
const api = useApi();
- const [tab, setTab] = useState<TabKey>('tasks');
+ const now = useVisibleNow();
+ const [tab, setTab] = useState<TabKey>(DEFAULT_TAB);
const [tasks, setTasks] = useState<HarnessTask[]>([]);
const [watches, setWatches] = useState<HarnessWatch[]>([]);
const [runs, setRuns] = useState<HarnessRun[]>([]);
@@ -146,11 +195,12 @@ export const HarnessPage: React.FC = () => {
// for tasks and watches; reset between tab switches happens via
// setSelection(null) below.
const [search, setSearch] = useState('');
- // Default to enabled-only: the Harness landing view should surface the
- // active tasks/watches first, not bury them among disabled leftovers. The
- // user can still switch to "all"/"disabled"; the filtered-count hint makes
- // the active filter obvious.
- const [statusFilter, setStatusFilter] = useState<HarnessDefinitionStatus>('enabled');
+ // Default to what is actually working right now (waiting + running). The
+ // previous default was "enabled", which read a switch as a state: it buried a
+ // running task among rows merely left switched on, and swept 1,156 retired
+ // one-shots into the same "disabled" bucket as the handful the user paused
+ // on purpose. The filtered-count hint keeps the narrowing visible.
+ const [statusFilter, setStatusFilter] = useState<HarnessDefinitionStatus>(DEFAULT_DEFINITION_STATUS);
// 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.
@@ -178,9 +228,7 @@ export const HarnessPage: React.FC = () => {
const runParam = searchParams.get('run');
const definitionParam = searchParams.get('definition');
useEffect(() => {
- if (tabParam && (['tasks', 'watches', 'runs'] as string[]).includes(tabParam)) {
- setTab(tabParam as TabKey);
- }
+ setTab(harnessTabFromParam(tabParam));
}, [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
@@ -281,14 +329,6 @@ export const HarnessPage: React.FC = () => {
setError(null);
const query = debouncedSearch || undefined;
try {
- if (tab === 'webhooks') {
- const counts = await api.getHarnessCounts();
- if (!isCurrent()) return;
- setTaskCounts(counts.tasks);
- setWatchCounts(counts.watches);
- setRunCounts(counts.runs);
- return;
- }
const result = await api.getHarnessBootstrap({
tab,
status: tab === 'runs' ? (runStatusFilter === 'all' ? undefined : runStatusFilter) : statusFilter,
@@ -388,7 +428,7 @@ export const HarnessPage: React.FC = () => {
setTasks((prev) => prev.map((t) => (t.id === task.id ? { ...t, enabled: next } : t)));
try {
await api.setHarnessTaskEnabled(task.id, next);
- if (statusFilter !== 'all' && ((statusFilter === 'enabled') !== next)) {
+ if (!definitionSurvivesToggle(statusFilter, next, task)) {
setSelection((prev) => (prev?.kind === 'task' && prev.id === task.id ? null : prev));
}
await refresh();
@@ -430,7 +470,7 @@ export const HarnessPage: React.FC = () => {
setWatches((prev) => prev.map((w) => (w.id === watch.id ? { ...w, enabled: next } : w)));
try {
await api.setHarnessWatchEnabled(watch.id, next);
- if (statusFilter !== 'all' && ((statusFilter === 'enabled') !== next)) {
+ if (!definitionSurvivesToggle(statusFilter, next, watch)) {
setSelection((prev) => (prev?.kind === 'watch' && prev.id === watch.id ? null : prev));
}
await refresh();
@@ -486,14 +526,17 @@ export const HarnessPage: React.FC = () => {
};
}, [api, selection]);
+ // A tab badge counts what the tab opens on, never more. Tasks and watches
+ // open on 进行中, so their badges say how much is live — not how many rows
+ // exist, most of which are retired one-shots nobody is waiting on. Runs open
+ // unfiltered, so ``all`` already is that tab's default view.
const counts = useMemo(
() => ({
- tasks: taskCounts.all,
- watches: watchCounts.all,
- webhooks: 0,
+ tasks: definitionActiveCount(taskCounts),
+ watches: definitionActiveCount(watchCounts),
runs: runCounts.all,
}),
- [taskCounts.all, watchCounts.all, runCounts.all],
+ [taskCounts, watchCounts, runCounts.all],
);
const selectedTask = useMemo(
@@ -506,16 +549,27 @@ export const HarnessPage: React.FC = () => {
);
const hasSelection = !!(selectedTask || selectedWatch || selectedRun);
- 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 as Record<string, number>)[activeStatus] ?? 0;
+ const queryDefinitionCounts = tab === 'tasks' ? queryTaskCounts : queryWatchCounts;
+ const totalForTab = isRunsTab ? queryRunCounts.all : queryDefinitionCounts.total;
+ // How many rows a chip stands for. A definition chip is a *set* of lifecycle
+ // states, so its size is a sum rather than a lookup — ``definitionStatusCount``
+ // owns that arithmetic. Every chip carries this (§4.1): a filter row that
+ // shows only labels makes the user click each one in turn to learn what the
+ // server already told the page.
+ const statusCount = useCallback(
+ (option: string) =>
+ isRunsTab
+ ? (queryRunCounts as Record<string, number>)[option] ?? 0
+ : definitionStatusCount(queryDefinitionCounts, option),
+ [isRunsTab, queryRunCounts, queryDefinitionCounts],
+ );
+ const shownForTab = statusCount(activeStatus);
// 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.
@@ -601,106 +655,107 @@ export const HarnessPage: React.FC = () => {
>
<HarnessTabIcon tab={key} active={active} />
{t(`harness.tabs.${key}`)}
- {key !== 'webhooks' && (
- <span
- className={clsx(
- 'rounded-full border px-1.5 py-0 font-mono text-[9px] font-bold',
- active
- ? 'border-violet/30 bg-violet/[0.10] text-violet'
- : 'border-border-strong bg-foreground/[0.04] text-muted',
- )}
- >
- {count}
- </span>
- )}
- {key === 'webhooks' && (
- <span className="font-mono text-[9px] text-muted">{t('harness.soon')}</span>
- )}
+ <span
+ className={clsx(
+ 'rounded-full border px-1.5 py-0 font-mono text-[9px] font-bold',
+ active
+ ? 'border-violet/30 bg-violet/[0.10] text-violet'
+ : 'border-border-strong bg-foreground/[0.04] text-muted',
+ )}
+ >
+ {count}
+ </span>
</button>
);
})}
</div>
{/* 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]">
- <Search className="size-3.5 shrink-0 text-muted" />
- <input
- value={search}
- onChange={(e) => {
- setSearch(e.target.value);
- resetPaging();
- }}
- 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">
- {statusOptions.map((opt) => (
- <button
- key={opt}
- type="button"
- onClick={() => onStatusFilterChange(opt)}
+ lifecycle segments for outcome statuses and add a type selector; all
+ three narrow server-side. */}
+ <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]">
+ <Search className="size-3.5 shrink-0 text-muted" />
+ <input
+ value={search}
+ onChange={(e) => {
+ setSearch(e.target.value);
+ resetPaging();
+ }}
+ 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">
+ {statusOptions.map((opt) => (
+ <button
+ key={opt}
+ type="button"
+ onClick={() => onStatusFilterChange(opt)}
+ className={clsx(
+ 'rounded px-2.5 py-1 text-[11px] font-medium transition',
+ activeStatus === opt
+ ? 'bg-violet/[0.12] text-violet'
+ : 'text-muted hover:text-foreground',
+ )}
+ >
+ {t(`${statusLabelPrefix}.${opt}`)}
+ <span
className={clsx(
- 'rounded px-2.5 py-1 text-[11px] font-medium transition',
- activeStatus === opt
- ? 'bg-violet/[0.12] text-violet'
- : 'text-muted hover:text-foreground',
+ 'ml-1 tabular-nums',
+ activeStatus === opt ? 'text-violet/70' : 'text-muted/70',
)}
>
- {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" />
- <span className="max-w-[180px] truncate">
- {t('harness.sessionFilter.chip', { id: sessionFilter })}
+ {statusCount(opt)}
</span>
- <button
- type="button"
- onClick={clearSessionFilter}
- aria-label={t('harness.sessionFilter.clear')}
- title={t('harness.sessionFilter.clear')}
- className="rounded-full p-0.5 text-cyan/80 transition-colors hover:bg-cyan/20 hover:text-cyan"
- >
- <X className="size-3" />
- </button>
- </span>
- )}
- {filtersActive && (
- <span className="ml-auto font-mono text-[10px] text-muted">
- {t('harness.filtered', { shown: shownForTab, total: totalForTab })}
- </span>
- )}
+ </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" />
+ <span className="max-w-[180px] truncate">
+ {t('harness.sessionFilter.chip', { id: sessionFilter })}
+ </span>
+ <button
+ type="button"
+ onClick={clearSessionFilter}
+ aria-label={t('harness.sessionFilter.clear')}
+ title={t('harness.sessionFilter.clear')}
+ className="rounded-full p-0.5 text-cyan/80 transition-colors hover:bg-cyan/20 hover:text-cyan"
+ >
+ <X className="size-3" />
+ </button>
+ </span>
+ )}
+ {filtersActive && (
+ <span className="ml-auto font-mono text-[10px] text-muted">
+ {t('harness.filtered', { shown: shownForTab, total: totalForTab })}
+ </span>
+ )}
+ </div>
{error && (
<div className="rounded-md border border-destructive/40 bg-destructive/[0.06] px-3 py-2 text-[12px] text-destructive">
@@ -723,11 +778,13 @@ export const HarnessPage: React.FC = () => {
<TasksList
tasks={tasks}
loading={loading}
+ hasStoredRows={taskCounts.total > 0}
selectedId={selection?.kind === 'task' ? selection.id : null}
onSelect={(id) => setSelection({ kind: 'task', id })}
onToggleEnabled={toggleTaskEnabled}
onDelete={deleteTask}
pending={pendingMutation}
+ now={now}
page={tasksPage}
hasMore={tasksHasMore}
onPageChange={(page) => {
@@ -740,11 +797,13 @@ export const HarnessPage: React.FC = () => {
<WatchesList
watches={watches}
loading={loading}
+ hasStoredRows={watchCounts.total > 0}
selectedId={selection?.kind === 'watch' ? selection.id : null}
onSelect={(id) => setSelection({ kind: 'watch', id })}
onToggleEnabled={toggleWatchEnabled}
onDelete={deleteWatch}
pending={pendingMutation}
+ now={now}
page={watchesPage}
hasMore={watchesHasMore}
onPageChange={(page) => {
@@ -753,13 +812,14 @@ export const HarnessPage: React.FC = () => {
}}
/>
)}
- {tab === 'webhooks' && <WebhooksEmpty />}
{tab === 'runs' && (
<RunsList
runs={runs}
loading={loading}
+ hasStoredRows={runCounts.all > 0}
selectedId={selection?.kind === 'run' ? selection.id : null}
onSelect={(id) => setSelection({ kind: 'run', id })}
+ now={now}
page={runsPage}
hasMore={runsHasMore}
onPageChange={(page) => {
@@ -819,7 +879,6 @@ const HarnessTabIcon: React.FC<TabIconProps> = ({ tab, active }) => {
const cls = clsx('size-3.5', active ? 'text-violet' : 'text-muted');
if (tab === 'tasks') return <Calendar className={cls} />;
if (tab === 'watches') return <Eye className={cls} />;
- if (tab === 'webhooks') return <Webhook className={cls} />;
return <History className={cls} />;
};
@@ -866,11 +925,13 @@ const HarnessPager: React.FC<HarnessPagerProps> = ({ page, hasMore, onPageChange
interface TasksListProps {
tasks: HarnessTask[];
loading: boolean;
+ hasStoredRows: boolean;
selectedId: string | null;
onSelect: (id: string) => void;
onToggleEnabled: (task: HarnessTask) => void;
onDelete: (task: HarnessTask) => void;
pending: Record<string, boolean>;
+ now: number;
page: number;
hasMore: boolean;
onPageChange: (page: number) => void;
@@ -879,76 +940,129 @@ interface TasksListProps {
const TasksList: React.FC<TasksListProps> = ({
tasks,
loading,
+ hasStoredRows,
selectedId,
onSelect,
onToggleEnabled,
onDelete,
pending,
+ now,
page,
hasMore,
onPageChange,
}) => {
const { t } = useTranslation();
- if (tasks.length === 0 && !loading) return <EmptyState i18nKey="harness.emptyTasks" />;
+ if (tasks.length === 0 && !loading) return <EmptyState i18nKey={harnessEmptyStateKey('tasks', hasStoredRows)} />;
return (
<>
- {tasks.map((task) => {
- const active = selectedId === task.id;
- const isPending = !!pending[task.id];
- const title = displayTitle(task.name, task.id);
- return (
- <div
- key={task.id}
- className={clsx(
- 'group/row flex min-w-0 items-center gap-3 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]',
- )}
- >
- <button
- type="button"
- onClick={() => onSelect(task.id)}
- className="flex min-w-0 flex-1 items-center gap-3 text-left"
- >
- <div className="flex min-w-0 flex-1 flex-col gap-1">
- <div className="flex items-center gap-2">
- <span className="truncate text-[14px] font-semibold text-foreground" title={task.name || task.id}>
- {title}
- </span>
- <Badge
- variant={task.enabled ? 'success' : 'secondary'}
- className="font-mono text-[9px] uppercase"
- >
- {task.enabled ? t('harness.runtime.enabled') : t('harness.runtime.disabled')}
- </Badge>
- </div>
- <div className="flex items-center gap-3 truncate text-[11px] text-muted">
- <span className="inline-flex items-center gap-1 truncate font-mono">
- <Clock className="size-3 shrink-0" />
- {formatSchedule(task, t)}
- </span>
- {task.agent_name && <span className="shrink-0">· {task.agent_name}</span>}
- </div>
- </div>
- {task.last_run_at && (
- <span className="shrink-0 font-mono text-[10px] text-muted">
- {formatRelativeTime(task.last_run_at, t)}
- </span>
- )}
- </button>
- <RowActions
- enabled={task.enabled}
- pending={isPending}
- onToggle={() => onToggleEnabled(task)}
- onDelete={() => onDelete(task)}
- />
- </div>
- );
- })}
+ {tasks.map((task) => (
+ <DefinitionRow
+ key={task.id}
+ row={task}
+ kind="task"
+ active={selectedId === task.id}
+ pending={!!pending[task.id]}
+ now={now}
+ onSelect={() => onSelect(task.id)}
+ onToggle={() => onToggleEnabled(task)}
+ onDelete={() => onDelete(task)}
+ />
+ ))}
+ {tasks.length === 0 && loading && <div className="px-4 py-6 text-[12px] text-muted">{t('common.loading')}</div>}
<HarnessPager page={page} hasMore={hasMore} onPageChange={onPageChange} />
</>
);
};
+// One row shape for both definition tabs: a task and a watch differ in what
+// their second line *says*, never in how the row is built. ``definitionRowLine``
+// owns that difference so this component stays a single anatomy.
+const STATE_DOT_CLASS: Record<HarnessLifecycleState, string> = {
+ running: 'bg-mint shadow-[0_0_5px_rgba(52,211,153,0.7)]',
+ waiting: 'bg-cyan',
+ paused: 'bg-muted/70',
+ finished: 'bg-border-strong',
+};
+
+// A state this client has no colour for still gets a dot — the row keeps its
+// shape, and the second line names the state in words either way.
+function stateDotClass(state: HarnessLifecycleState | null): string {
+ return (state && STATE_DOT_CLASS[state]) || 'bg-muted/70';
+}
+
+const ALERT_CLASS: Record<HarnessRowAlert, string> = {
+ error: 'text-pink',
+ timeout: 'text-amber',
+ // A waiter that is supposed to be waiting but whose process is gone. It is
+ // not an error the store recorded — it is the absence of one, which is
+ // exactly why nothing used to show it.
+ dead: 'text-pink',
+};
+
+interface DefinitionRowProps {
+ row: HarnessTask | HarnessWatch;
+ kind: HarnessDefinitionKind;
+ active: boolean;
+ pending: boolean;
+ now: number;
+ onSelect: () => void;
+ onToggle: () => void;
+ onDelete: () => void;
+}
+
+const DefinitionRow: React.FC<DefinitionRowProps> = ({
+ row,
+ kind,
+ active,
+ pending,
+ now,
+ onSelect,
+ onToggle,
+ onDelete,
+}) => {
+ const { t } = useTranslation();
+ const title = definitionRowTitle(row, t(`harness.kind.${kind}`));
+ const chip = definitionChipLabel(row, kind, t);
+ const line = definitionRowLine(row, kind, t, now);
+ return (
+ <div
+ className={clsx(
+ 'group/row flex min-w-0 items-center gap-3 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]',
+ )}
+ >
+ <button type="button" onClick={onSelect} className="flex min-w-0 flex-1 items-center gap-3 text-left">
+ <span
+ aria-hidden
+ className={clsx('size-2 shrink-0 rounded-full', stateDotClass(row.lifecycle_state))}
+ />
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
+ <div className="flex min-w-0 items-center gap-2">
+ {/* Truncation is CSS, never a slice: search matches the full
+ title and the detail panel shows it whole. */}
+ <span className="truncate text-[14px] font-semibold text-foreground" title={title}>
+ {title}
+ </span>
+ {chip && (
+ <Badge variant="secondary" className="shrink-0 font-mono text-[9px] uppercase">
+ {chip}
+ </Badge>
+ )}
+ </div>
+ <div className="flex min-w-0 items-center gap-2 text-[11px] text-muted">
+ {line.alert && <AlertTriangle className={clsx('size-3 shrink-0', ALERT_CLASS[line.alert])} />}
+ <span className={clsx('truncate', line.alert && ALERT_CLASS[line.alert])}>{line.primary}</span>
+ {line.secondary && (
+ <span className="shrink-0 truncate font-mono text-[10px] text-muted">· {line.secondary}</span>
+ )}
+ </div>
+ </div>
+ </button>
+ <RowActions enabled={row.enabled} pending={pending} onToggle={onToggle} onDelete={onDelete} />
+ </div>
+ );
+};
+
interface RowActionsProps {
enabled: boolean;
pending: boolean;
@@ -1017,15 +1131,15 @@ interface TaskDetailProps {
const TaskDetail: React.FC<TaskDetailProps> = ({ task, agent, onToggleEnabled, pending }) => {
const { t } = useTranslation();
- const title = displayTitle(task.name, task.id);
+ const title = definitionRowTitle(task, t('harness.kind.task'));
return (
<div className="flex min-w-0 flex-col gap-4">
<div className="flex min-w-0 items-center gap-2">
<Calendar className="size-4 shrink-0 text-violet" />
- <div className="min-w-0 flex-1 truncate text-[15px] font-bold text-foreground" title={task.name || task.id}>
+ <div className="min-w-0 flex-1 truncate text-[15px] font-bold text-foreground" title={title}>
{title}
</div>
- <StatusPill enabled={task.enabled} />
+ <LifecyclePill row={task} />
<Switch
checked={task.enabled}
onCheckedChange={onToggleEnabled}
@@ -1033,15 +1147,21 @@ const TaskDetail: React.FC<TaskDetailProps> = ({ task, agent, onToggleEnabled, p
disabled={pending}
/>
</div>
+ {/* The row humanizes the schedule; this is where the literal lives, so
+ an operator can still read and copy the exact expression. */}
<DetailField label={t('harness.detail.schedule')}>
- <span className="font-mono text-[12px] text-foreground">
- {task.cron ?? task.run_at ?? task.schedule_type ?? '—'}
- </span>
+ <span className="text-[12px] text-foreground">{formatSchedule(task, t)}</span>
+ {(task.cron || task.run_at) && (
+ <span className="ml-2 font-mono text-[10px] text-muted">{task.cron ?? task.run_at}</span>
+ )}
{task.timezone && <span className="ml-2 text-[10px] text-muted">{task.timezone}</span>}
</DetailField>
{task.next_run_at && (
<DetailField label={t('harness.detail.nextRun')}>
- <span className="font-mono text-[12px] text-foreground">{formatLocalDateTime(task.next_run_at)}</span>
+ <span className="text-[12px] text-foreground">{humanizeTime(task.next_run_at, t)}</span>
+ <span className="ml-2 font-mono text-[10px] text-muted">
+ {formatLocalDateTime(task.next_run_at)}
+ </span>
</DetailField>
)}
<DetailField label={t('harness.detail.agent')}>
@@ -1087,11 +1207,13 @@ const TaskDetail: React.FC<TaskDetailProps> = ({ task, agent, onToggleEnabled, p
interface WatchesListProps {
watches: HarnessWatch[];
loading: boolean;
+ hasStoredRows: boolean;
selectedId: string | null;
onSelect: (id: string) => void;
onToggleEnabled: (watch: HarnessWatch) => void;
onDelete: (watch: HarnessWatch) => void;
pending: Record<string, boolean>;
+ now: number;
page: number;
hasMore: boolean;
onPageChange: (page: number) => void;
@@ -1100,75 +1222,36 @@ interface WatchesListProps {
const WatchesList: React.FC<WatchesListProps> = ({
watches,
loading,
+ hasStoredRows,
selectedId,
onSelect,
onToggleEnabled,
onDelete,
pending,
+ now,
page,
hasMore,
onPageChange,
}) => {
const { t } = useTranslation();
- if (watches.length === 0 && !loading) return <EmptyState i18nKey="harness.emptyWatches" />;
+ if (watches.length === 0 && !loading) {
+ return <EmptyState i18nKey={harnessEmptyStateKey('watches', hasStoredRows)} />;
+ }
return (
<>
- {watches.map((watch) => {
- const active = selectedId === watch.id;
- const isPending = !!pending[watch.id];
- const cmd = watch.shell_command || (Array.isArray(watch.command) ? watch.command.join(' ') : '') || '—';
- const title = displayTitle(watch.name, watch.id);
- return (
- <div
- key={watch.id}
- className={clsx(
- 'group/row flex min-w-0 items-center gap-3 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]',
- )}
- >
- <button
- type="button"
- onClick={() => onSelect(watch.id)}
- className="flex min-w-0 flex-1 items-center gap-3 text-left"
- >
- <div className="flex min-w-0 flex-1 flex-col gap-1">
- <div className="flex items-center gap-2">
- <span className="truncate text-[14px] font-semibold text-foreground" title={watch.name || watch.id}>
- {title}
- </span>
- {watch.runtime.running ? (
- <Badge variant="success" className="font-mono text-[9px] uppercase">
- <span className="size-1.5 rounded-full bg-mint" />
- {t('harness.runtime.running')}
- </Badge>
- ) : !watch.enabled ? (
- <Badge variant="secondary" className="font-mono text-[9px] uppercase">
- <PauseCircle className="size-2.5" />
- {t('harness.runtime.paused')}
- </Badge>
- ) : (
- <Badge variant="secondary" className="font-mono text-[9px] uppercase">
- {t('harness.runtime.idle')}
- </Badge>
- )}
- </div>
- <div className="truncate font-mono text-[11px] text-muted">{cmd}</div>
- </div>
- {watch.last_event_at && (
- <span className="shrink-0 font-mono text-[10px] text-muted">
- {formatRelativeTime(watch.last_event_at, t)}
- </span>
- )}
- </button>
- <RowActions
- enabled={watch.enabled}
- pending={isPending}
- onToggle={() => onToggleEnabled(watch)}
- onDelete={() => onDelete(watch)}
- />
- </div>
- );
- })}
+ {watches.map((watch) => (
+ <DefinitionRow
+ key={watch.id}
+ row={watch}
+ kind="watch"
+ active={selectedId === watch.id}
+ pending={!!pending[watch.id]}
+ now={now}
+ onSelect={() => onSelect(watch.id)}
+ onToggle={() => onToggleEnabled(watch)}
+ onDelete={() => onDelete(watch)}
+ />
+ ))}
{watches.length === 0 && loading && <div className="px-4 py-6 text-[12px] text-muted">{t('common.loading')}</div>}
<HarnessPager page={page} hasMore={hasMore} onPageChange={onPageChange} />
</>
@@ -1182,18 +1265,20 @@ interface WatchDetailProps {
pending: boolean;
}
-const WatchDetail: React.FC<WatchDetailProps> = ({ watch, agent, onToggleEnabled, pending }) => {
+export const WatchDetail: React.FC<WatchDetailProps> = ({ watch, agent, onToggleEnabled, pending }) => {
const { t } = useTranslation();
const cmd = watch.shell_command || (Array.isArray(watch.command) ? watch.command.join(' ') : '') || '—';
- const title = displayTitle(watch.name, watch.id);
+ const title = definitionRowTitle(watch, t('harness.kind.watch'));
+ const showRuntime =
+ watch.process_alive === true || (watch.process_alive === false && waiterExpectedAlive(watch));
return (
<div className="flex min-w-0 flex-col gap-4">
<div className="flex min-w-0 items-center gap-2">
<Eye className="size-4 shrink-0 text-violet" />
- <div className="min-w-0 flex-1 truncate text-[15px] font-bold text-foreground" title={watch.name || watch.id}>
+ <div className="min-w-0 flex-1 truncate text-[15px] font-bold text-foreground" title={title}>
{title}
</div>
- <StatusPill enabled={watch.enabled} runtimeRunning={watch.runtime.running} />
+ <LifecyclePill row={watch} />
<Switch
checked={watch.enabled}
onCheckedChange={onToggleEnabled}
@@ -1231,11 +1316,29 @@ const WatchDetail: React.FC<WatchDetailProps> = ({ watch, agent, onToggleEnabled
{watch.message || watch.prefix || '—'}
</pre>
</DetailField>
- {watch.runtime.running && watch.runtime.pid != null && (
+ {watch.waiting_since && (
+ <DetailField label={t('harness.detail.waitingSince')}>
+ <span className="text-[12px] text-foreground">{humanizeTime(watch.waiting_since, t)}</span>
+ <span className="ml-2 font-mono text-[10px] text-muted">
+ {formatLocalDateTime(watch.waiting_since)}
+ </span>
+ </DetailField>
+ )}
+ {/* A live process remains useful diagnostics. A stopped process is news
+ only while the shared predicate says this waiter should be running. */}
+ {showRuntime && (
<DetailField label={t('harness.detail.runtime')}>
- <span className="font-mono text-[11px] text-muted">
- pid {watch.runtime.pid} · {formatLocalDateTime(watch.runtime.started_at)}
+ <span
+ className={clsx('text-[12px]', watch.process_alive ? 'text-foreground' : 'text-pink')}
+ >
+ {t(watch.process_alive ? 'harness.row.processAlive' : 'harness.row.processDead')}
</span>
+ {watch.runtime.pid != null && (
+ <span className="ml-2 font-mono text-[10px] text-muted">
+ pid {watch.runtime.pid}
+ {watch.runtime.started_at && ` · ${formatLocalDateTime(watch.runtime.started_at)}`}
+ </span>
+ )}
</DetailField>
)}
{watch.last_error && (
@@ -1252,21 +1355,6 @@ const WatchDetail: React.FC<WatchDetailProps> = ({ watch, agent, onToggleEnabled
);
};
-// ---------------------------------------------------------------------------
-// Webhooks tab — coming soon
-// ---------------------------------------------------------------------------
-
-const WebhooksEmpty: React.FC = () => {
- const { t } = useTranslation();
- return (
- <div className="flex flex-col items-center gap-3 rounded-xl border border-dashed border-border bg-surface px-6 py-16 text-center">
- <Webhook className="size-8 text-muted" />
- <div className="text-[14px] font-semibold text-foreground">{t('harness.webhooksSoon')}</div>
- <div className="max-w-md text-[12px] text-muted">{t('harness.webhooksSoonBody')}</div>
- </div>
- );
-};
-
// ---------------------------------------------------------------------------
// Runs tab
// ---------------------------------------------------------------------------
@@ -1274,23 +1362,35 @@ const WebhooksEmpty: React.FC = () => {
interface RunsListProps {
runs: HarnessRun[];
loading: boolean;
+ hasStoredRows: boolean;
selectedId: string | null;
onSelect: (id: string) => void;
+ now: number;
page: number;
hasMore: boolean;
onPageChange: (page: number) => void;
}
-const RunsList: React.FC<RunsListProps> = ({ runs, loading, selectedId, onSelect, page, hasMore, onPageChange }) => {
+const RunsList: React.FC<RunsListProps> = ({
+ runs,
+ loading,
+ hasStoredRows,
+ selectedId,
+ onSelect,
+ now,
+ page,
+ hasMore,
+ onPageChange,
+}) => {
const { t } = useTranslation();
- if (runs.length === 0 && !loading) return <EmptyState i18nKey="harness.emptyRuns" />;
+ if (runs.length === 0 && !loading) return <EmptyState i18nKey={harnessEmptyStateKey('runs', hasStoredRows)} />;
return (
<>
{runs.map((run) => {
const active = selectedId === run.id;
const typeLabel = runTypeLabel(run.run_type, t);
const title = runRowTitle(run, typeLabel);
- const elapsed = runElapsedSeconds(run);
+ const elapsed = runElapsedSeconds(run, now);
// 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
@@ -1331,8 +1431,10 @@ const RunsList: React.FC<RunsListProps> = ({ runs, loading, selectedId, onSelect
</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>}
+ {elapsed != null && <span className="shrink-0 font-mono">{formatElapsed(elapsed, t)}</span>}
+ {run.created_at && (
+ <span className="shrink-0">{formatRelativeTime(run.created_at, t, now)}</span>
+ )}
</div>
</div>
</div>
@@ -1461,11 +1563,17 @@ const RunDetail: React.FC<RunDetailProps> = ({ run }) => {
{run.source_kind}
</span>
)}
- {run.source_actor && (
- // 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>
+ {/* ``source_actor`` is a session id exactly when another agent
+ spawned this run; the projection resolves that case, so the
+ field says who — not ``ses53w9zb8ba6``. Every other kind
+ (parent run, vault request, activity) has no name to look up
+ and stays the plain string it is. */}
+ {run.source_session ? (
+ <DetailSession summary={run.source_session} sessionId={run.source_session_id} />
+ ) : (
+ run.source_actor && (
+ <span className="font-mono text-[11px] text-muted">{run.source_actor}</span>
+ )
)}
</span>
</DetailField>
@@ -1573,24 +1681,22 @@ const RunStatusIcon: React.FC<{ status: HarnessRunStatus }> = ({ status }) => {
return <Activity className={clsx(cls, 'text-muted')} />;
};
-interface StatusPillProps {
- enabled: boolean;
- runtimeRunning?: boolean;
-}
-
-const StatusPill: React.FC<StatusPillProps> = ({ enabled, runtimeRunning }) => {
+// The detail-panel counterpart of the row's state dot. Same four words as the
+// filter chips, so a row found under 已结束 says 已结束 when opened.
+const LifecyclePill: React.FC<{ row: HarnessTask | HarnessWatch }> = ({ row }) => {
const { t } = useTranslation();
- if (runtimeRunning) {
- return (
- <Badge variant="success" className="font-mono text-[9px] uppercase">
- <span className="size-1.5 rounded-full bg-mint" />
- {t('harness.runtime.running')}
- </Badge>
- );
- }
+ const state = row.lifecycle_state;
return (
- <Badge variant="secondary" className="font-mono text-[9px] uppercase">
- {enabled ? t('harness.runtime.enabled') : t('harness.runtime.disabled')}
+ <Badge
+ variant={state === 'running' ? 'success' : 'secondary'}
+ className="shrink-0 font-mono text-[9px] uppercase"
+ >
+ {state === 'running' ? (
+ <span className="size-1.5 rounded-full bg-mint" />
+ ) : state === 'paused' ? (
+ <PauseCircle className="size-2.5" />
+ ) : null}
+ {lifecycleLabel(state, row.lifecycle_detail, t)}
</Badge>
);
};
@@ -1640,11 +1746,18 @@ const DetailAgent: React.FC<{ agentName: string | null; agent?: VibeAgentBrief }
);
};
-// 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.
+// Bound session, in the four states a harness row can be in. A session id that
+// no longer resolves says so instead of rendering a raw id that looks like a
+// name.
+//
+// Two independent questions, deliberately answered by two fields:
+// - *how it reads* — ``session_is_workbench`` picks the icon and whether the
+// label is the session title or the IM channel;
+// - *whether it opens* — ``session_openable`` alone, the one predicate the
+// Agents graph and this page now share
+// (``storage/agent_session_rows.py::session_openable_in_chat``).
+// They used to be the same field, which is why an IM-bound task rendered a
+// title the user could see but not click, even though ``/chat/<id>`` serves it.
export const DetailSession: React.FC<{ summary: HarnessSessionSummary; sessionId: string | null }> = ({
summary,
sessionId,
@@ -1663,35 +1776,35 @@ export const DetailSession: React.FC<{ summary: HarnessSessionSummary; sessionId
</div>
);
}
- if (state === 'workbench') {
- const label = summary.session_title || sessionId || '—';
- const body = (
+ const body =
+ state === 'workbench' ? (
<>
<MessageSquare className="size-3.5 shrink-0 text-cyan" />
- <span className="min-w-0 flex-1 truncate text-[12px] font-medium text-foreground">{label}</span>
- {sessionId && <ArrowUpRight className="size-3.5 shrink-0 text-cyan" />}
+ <span className="min-w-0 flex-1 truncate text-[12px] font-medium text-foreground">
+ {summary.session_title || sessionId || '—'}
+ </span>
</>
- );
- return sessionId ? (
- <Link to={`/chat/${sessionId}`} className="flex min-w-0 items-center gap-2 hover:underline">
- {body}
- </Link>
) : (
- <div className="flex min-w-0 items-center gap-2">{body}</div>
+ <>
+ {summary.session_platform && <PlatformIcon platform={summary.session_platform} size={14} />}
+ <span className="min-w-0 flex-1 truncate text-[12px] font-medium text-foreground">
+ {summary.session_label || summary.session_title || sessionId || '—'}
+ </span>
+ {summary.session_platform && (
+ <span className="shrink-0 font-mono text-[10px] uppercase tracking-wide text-muted">
+ {summary.session_platform}
+ </span>
+ )}
+ </>
);
+ if (!summary.session_openable || !sessionId) {
+ return <div className="flex min-w-0 items-center gap-2">{body}</div>;
}
return (
- <div className="flex min-w-0 items-center gap-2">
- {summary.session_platform && <PlatformIcon platform={summary.session_platform} size={14} />}
- <span className="min-w-0 flex-1 truncate text-[12px] font-medium text-foreground">
- {summary.session_label || summary.session_title || sessionId || '—'}
- </span>
- {summary.session_platform && (
- <span className="shrink-0 font-mono text-[10px] uppercase tracking-wide text-muted">
- {summary.session_platform}
- </span>
- )}
- </div>
+ <Link to={`/chat/${sessionId}`} className="flex min-w-0 items-center gap-2 hover:underline">
+ {body}
+ <ArrowUpRight className="size-3.5 shrink-0 text-cyan" />
+ </Link>
);
};
diff --git a/ui/src/components/workbench/harnessLifecycle.test.ts b/ui/src/components/workbench/harnessLifecycle.test.ts
new file mode 100644
index 000000000..3652c8127
--- /dev/null
+++ b/ui/src/components/workbench/harnessLifecycle.test.ts
@@ -0,0 +1,676 @@
+import { describe, expect, it } from 'vitest';
+
+import en from '../../i18n/en.json';
+import zh from '../../i18n/zh.json';
+import {
+ DEFAULT_DEFINITION_STATUS,
+ DEFINITION_STATUS_FILTERS,
+ definitionActiveCount,
+ definitionActivityAt,
+ definitionChipLabel,
+ definitionRowLine,
+ definitionRowTitle,
+ definitionStateSince,
+ definitionStatusCount,
+ definitionSurvivesToggle,
+ formatWallTime,
+ humanizeCron,
+ humanizeGap,
+ humanizeTime,
+ isWallClockTimestamp,
+ LIFECYCLE_DETAILS,
+ lifecycleLabel,
+} from './harnessLifecycle';
+
+// Translation-free stand-in: proves a mapper picked the right key without
+// pinning the copy. Interpolations are appended so a test can assert the value
+// reached the string.
+//
+// Duration units are the exception, resolved from the real bundle: "3h" is a
+// value these mappers *compose*, not a key they choose, so leaving it as a
+// dotted path would make every row assertion below unreadable and would assert
+// nothing about what the reader sees.
+const key = (k: string, opts?: Record<string, unknown>) => {
+ if (k.startsWith('common.duration.')) return en.common.duration[k.replace('common.duration.', '')];
+ return opts ? `${k}(${Object.values(opts).join(',')})` : k;
+};
+
+// The real bundles, so a key a mapper can emit but nobody translated fails
+// here rather than shipping as its own dotted path. Both locales, because a
+// key added to one side only is the same defect in the other language.
+const BUNDLES: Record<string, unknown> = { en, zh };
+
+// Asserts that every key these mappers can produce resolves to real copy, in
+// every language. Reports the missing ones together — a run that names one
+// key per re-run is what makes this class of fix take five rounds.
+const expectCopy = (prefix: string, leaves: readonly string[]) => {
+ const missing = Object.entries(BUNDLES).flatMap(([lng, bundle]) =>
+ leaves
+ .filter(
+ (leaf) =>
+ typeof `${prefix}.${leaf}`
+ .split('.')
+ .reduce<any>((node, part) => node?.[part], bundle) !== 'string',
+ )
+ .map((leaf) => `${lng}: ${prefix}.${leaf}`),
+ );
+ expect(missing).toEqual([]);
+};
+
+// A fixed "now" so every relative phrase is deterministic: 2026-07-26 13:00
+// local, whatever timezone the runner is in.
+const NOW = new Date(2026, 6, 26, 13, 0, 0).getTime();
+const at = (offsetMs: number) => new Date(NOW + offsetMs).toISOString();
+const MINUTE = 60_000;
+const HOUR = 60 * MINUTE;
+const DAY = 24 * HOUR;
+
+describe('lifecycleLabel', () => {
+ const outcomes = [
+ ['normal', 'harness.lifecycle.normal'],
+ ['timeout', 'harness.lifecycle.timeout'],
+ ['error', 'harness.lifecycle.error'],
+ [null, 'harness.lifecycle.finished'],
+ ['missed', 'harness.lifecycle.finished'],
+ ] as const;
+
+ it.each(outcomes)('maps finished detail %s to %s', (detail, expected) => {
+ expect(lifecycleLabel('finished', detail, key)).toBe(expected);
+ });
+
+ it('enumerates every recognised outcome', () => {
+ expect(
+ outcomes
+ .filter(([detail, expected]) => detail !== null && expected !== 'harness.lifecycle.finished')
+ .map(([detail]) => detail),
+ ).toEqual(LIFECYCLE_DETAILS);
+ });
+
+ it('names the live states directly, and never renders a bare state string', () => {
+ expect(lifecycleLabel('waiting', null, key)).toBe('harness.lifecycle.waiting');
+ expect(lifecycleLabel('running', null, key)).toBe('harness.lifecycle.running');
+ expect(lifecycleLabel('paused', null, key)).toBe('harness.lifecycle.paused');
+ // A state this client has no word for must not leak into the UI as itself.
+ expect(lifecycleLabel('quiesced', null, key)).toBe('harness.lifecycle.unknown');
+ expect(lifecycleLabel(null, null, key)).toBe('harness.lifecycle.unknown');
+ });
+
+ it('has real copy behind every key it can produce', () => {
+ expectCopy('harness.lifecycle', [
+ 'running',
+ 'waiting',
+ 'paused',
+ 'finished',
+ 'normal',
+ 'timeout',
+ 'error',
+ 'unknown',
+ ]);
+ });
+});
+
+describe('definitionStatusCount', () => {
+ const counts = { total: 1180, running: 2, waiting: 22, paused: 0, finished: 1156 };
+
+ it('sums the states a chip selects', () => {
+ expect(definitionStatusCount(counts, 'active')).toBe(24);
+ expect(definitionStatusCount(counts, 'finished')).toBe(1156);
+ expect(definitionStatusCount(counts, 'paused')).toBe(0);
+ });
+
+ it('offers the four owner-approved lifecycle chips', () => {
+ // Exact ``waiting`` and ``running`` filters remain on the server for API and
+ // CLI callers; the toolbar combines them under Active because each row
+ // already names which one it is.
+ expect([...DEFINITION_STATUS_FILTERS]).toEqual(['all', 'active', 'paused', 'finished']);
+ });
+
+ it('reads total for "all" rather than summing the states it knows', () => {
+ // So a state added server-side still counts toward All here.
+ expect(definitionStatusCount({ ...counts, quiesced: 7, total: 1187 }, 'all')).toBe(1187);
+ });
+
+ it('is the tab badge, by construction', () => {
+ expect(definitionActiveCount(counts)).toBe(definitionStatusCount(counts, DEFAULT_DEFINITION_STATUS));
+ // §4.4: the badge must never promise rows the landing view excludes.
+ expect(definitionActiveCount(counts)).toBeLessThan(counts.total);
+ });
+
+ it('survives a server that sends nothing', () => {
+ expect(definitionStatusCount(undefined, 'active')).toBe(0);
+ expect(definitionStatusCount(null, 'all')).toBe(0);
+ });
+
+ it('has copy for every chip it offers', () => {
+ expectCopy('harness.statusFilter', DEFINITION_STATUS_FILTERS);
+ });
+});
+
+describe('definitionSurvivesToggle', () => {
+ it('keeps a row under All whichever way the switch goes', () => {
+ expect(definitionSurvivesToggle('all', true)).toBe(true);
+ expect(definitionSurvivesToggle('all', false)).toBe(true);
+ });
+
+ it('drops a row the user just switched out of the current chip', () => {
+ expect(definitionSurvivesToggle('active', false)).toBe(false);
+ expect(definitionSurvivesToggle('paused', true)).toBe(false);
+ expect(definitionSurvivesToggle('finished', true)).toBe(false);
+ });
+
+ it('keeps a row the switch moved into the current chip', () => {
+ expect(definitionSurvivesToggle('active', true)).toBe(true);
+ expect(definitionSurvivesToggle('paused', false)).toBe(true);
+ });
+
+ it('leaves a running row alone, because the switch does not stop it', () => {
+ // An in-flight run outranks ``enabled`` in the lifecycle case, so switching
+ // a running row off does not move it out of Active — it keeps running until
+ // that run ends.
+ expect(definitionSurvivesToggle('active', false, { lifecycle_state: 'running' })).toBe(true);
+ expect(definitionSurvivesToggle('active', true, { lifecycle_state: 'running' })).toBe(true);
+ });
+
+ it('keeps a fired one-shot detail open when re-enabling cannot create a future fire', () => {
+ const fired = {
+ lifecycle_state: 'finished' as const,
+ schedule_type: 'at',
+ next_run_at: null,
+ };
+ expect(definitionSurvivesToggle('finished', true, fired)).toBe(true);
+ expect(definitionSurvivesToggle('active', true, fired)).toBe(false);
+
+ const retiredWatch = { lifecycle_state: 'finished' as const, next_run_at: null };
+ expect(definitionSurvivesToggle('finished', true, retiredWatch)).toBe(false);
+ });
+});
+
+describe('humanizeTime', () => {
+ it('says today, tomorrow and yesterday with the clock time', () => {
+ expect(humanizeTime(at(35 * MINUTE), key, NOW)).toBe('harness.when.today(13:35)');
+ expect(humanizeTime(at(20 * HOUR), key, NOW)).toBe('harness.when.tomorrow(09:00)');
+ expect(humanizeTime(at(-14 * HOUR), key, NOW)).toBe('harness.when.yesterday(23:00)');
+ });
+
+ it('counts calendar days, not 24-hour blocks', () => {
+ // 23:50 today and 00:10 tomorrow are 20 minutes apart and two dates apart.
+ const lateTonight = new Date(2026, 6, 26, 23, 50).getTime();
+ const justAfterMidnight = new Date(2026, 6, 27, 0, 10).toISOString();
+ expect(humanizeTime(justAfterMidnight, key, lateTonight)).toBe('harness.when.tomorrow(00:10)');
+ });
+
+ it('drops to a date once it is further out, and adds the year across one', () => {
+ expect(humanizeTime(at(4 * DAY), key, NOW)).toBe('harness.when.dateTime(07-30,13:00)');
+ expect(humanizeTime(new Date(2027, 0, 1, 0, 0).toISOString(), key, NOW)).toBe(
+ 'harness.when.dateTime(2027-01-01,00:00)',
+ );
+ });
+
+ it('hands back garbage unchanged instead of printing "Invalid Date"', () => {
+ expect(humanizeTime('not-a-time', key, NOW)).toBe('not-a-time');
+ expect(humanizeTime(null, key, NOW)).toBe('—');
+ });
+});
+
+describe('humanizeGap', () => {
+ it('measures distance in either direction', () => {
+ expect(humanizeGap(at(20 * MINUTE), NOW, key)).toBe('20m');
+ expect(humanizeGap(at(-3 * HOUR), NOW, key)).toBe('3h');
+ });
+
+ it('reports nothing rather than zero when there is no timestamp', () => {
+ expect(humanizeGap(null, NOW, key)).toBeNull();
+ expect(humanizeGap('not-a-time', NOW, key)).toBeNull();
+ });
+});
+
+describe('wall-clock timestamps', () => {
+ it('tells an instant from a clock face', () => {
+ expect(isWallClockTimestamp('2026-08-01T09:00:00Z')).toBe(false);
+ expect(isWallClockTimestamp('2026-08-01T09:00:00+08:00')).toBe(false);
+ expect(isWallClockTimestamp('2026-08-01T09:00:00+0800')).toBe(false);
+ // What ``vibe task add --at "2026-08-01 09:00"`` stores: a reading on some
+ // other zone's clock, which ``new Date`` would resolve against the viewer's.
+ expect(isWallClockTimestamp('2026-08-01T09:00:00')).toBe(true);
+ expect(isWallClockTimestamp('2026-08-01 09:00')).toBe(true);
+ expect(isWallClockTimestamp(null)).toBe(false);
+ });
+
+ it('prints the clock face with the zone it belongs to, and converts nothing', () => {
+ expect(formatWallTime('2026-08-01T09:00:00', 'Asia/Tokyo', key)).toBe(
+ 'harness.when.wallClock(2026-08-01 09:00,Asia/Tokyo)',
+ );
+ // No zone to name: still the clock as written, never shifted.
+ expect(formatWallTime('2026-08-01T09:00:00', null, key)).toBe('2026-08-01 09:00');
+ // Not timestamp-shaped: verbatim rather than reformatted into a guess.
+ expect(formatWallTime('whenever', null, key)).toBe('whenever');
+ expect(formatWallTime(null, 'Asia/Tokyo', key)).toBe('—');
+ });
+
+ it('has copy for the zone-qualified form', () => {
+ expectCopy('harness.when', ['wallClock']);
+ });
+});
+
+describe('humanizeCron', () => {
+ it('speaks the shapes the store actually holds', () => {
+ expect(humanizeCron('17 10 * * *', key)).toBe('harness.cron.daily(10:17)');
+ expect(humanizeCron('*/5 * * * *', key)).toBe('harness.cron.everyMinutes(5)');
+ expect(humanizeCron('* * * * *', key)).toBe('harness.cron.everyMinute');
+ });
+
+ // The days a weekly phrase names, pulled back out of the stand-in's output.
+ // Splits on the *key* the separator now resolves to, which is what the
+ // stand-in emits in place of the copy — the hardcoded "、" this used to split
+ // on was the bug: it shipped a Chinese separator into English rows.
+ const SEPARATOR = 'harness.cron.weekdaySeparator';
+ const cronDays = (expr: string) =>
+ /weekly\((.*),\d\d:\d\d\)$/
+ .exec(humanizeCron(expr, key))?.[1]
+ .split(SEPARATOR)
+ .map((day) => day.replace('harness.cron.weekday.', '')) ?? null;
+
+ // APScheduler's numbering, which ``CronTrigger.from_crontab`` imposes on every
+ // expression this app stores: Monday is 0, Sunday is 6. NOT crontab(5)'s. The
+ // Python mirror test pins this table against the library itself.
+ it('numbers weekdays the way the scheduler that fires them does', () => {
+ expect(cronDays('0 8 * * 0')).toEqual(['mon']);
+ expect(cronDays('0 8 * * 6')).toEqual(['sun']);
+ expect(cronDays('0 8 * * SUN')).toEqual(['sun']);
+ expect(cronDays('0 8 * * mon,wed,fri')).toEqual(['mon', 'wed', 'fri']);
+ // The case that matters most: someone writing crontab(5)'s "weekdays" gets
+ // Tue–Sat out of APScheduler. Saying "Mon–Fri" would hide a real surprise
+ // behind a familiar phrase; the row shows what will actually happen.
+ expect(cronDays('0 9 * * 1-5')).toEqual(['tue', 'wed', 'thu', 'fri', 'sat']);
+ expect(cronDays('0 9 * * 0-4')).toEqual(['mon', 'tue', 'wed', 'thu', 'fri']);
+ });
+
+ it('lists days once, in week order, however they were written', () => {
+ expect(cronDays('0 8 * * 4,0,0,SAT')).toEqual(['mon', 'fri', 'sat']);
+ });
+
+ it('collapses an every-weekday expression back to daily', () => {
+ expect(humanizeCron('0 8 * * 0-6', key)).toBe('harness.cron.daily(08:00)');
+ });
+
+ it('hands back anything it cannot say plainly, rather than guessing', () => {
+ // A wrong plain-English schedule is worse than a raw one; the detail panel
+ // prints the expression either way.
+ for (const expr of [
+ '0 0 1 * *', // day-of-month
+ '0 0 * 3 *', // month
+ '0 9-17 * * *', // hour range
+ '0 0 * * 1#2', // nth weekday
+ '@daily', // non-standard
+ '1 2 3 4', // too few fields
+ '0 99 * * *', // out of range
+ ]) {
+ expect(humanizeCron(expr, key)).toBe(expr);
+ }
+ });
+
+ it('refuses the day-of-week forms APScheduler will not schedule', () => {
+ // Both are legal crontab(5) and both raise in ``CronTrigger.from_crontab``:
+ // ``7`` exceeds the maximum of 6, and a descending range is rejected rather
+ // than wrapped. A task carrying either never fires, so describing it as a
+ // weekly schedule would put a promise on screen that nothing can keep.
+ expect(humanizeCron('0 8 * * 7', key)).toBe('0 8 * * 7');
+ expect(humanizeCron('0 8 * * 5-1', key)).toBe('0 8 * * 5-1');
+ });
+
+ it('has copy behind every phrase and weekday it can produce', () => {
+ expectCopy('harness.cron', [
+ 'everyMinute',
+ 'everyMinutes',
+ 'daily',
+ 'weekly',
+ 'weekdaySeparator',
+ ]);
+ expectCopy('harness.cron.weekday', ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']);
+ });
+
+ it('separates weekdays with copy, not a hardcoded Chinese comma', () => {
+ // en and zh punctuate lists differently, and the separator was baked into
+ // the mapper — "Mon、Wed、Fri" reached English rows.
+ expect(en.harness.cron.weekdaySeparator).not.toBe(zh.harness.cron.weekdaySeparator);
+ });
+});
+
+describe('definitionRowTitle', () => {
+ it('prefers the name the user gave it', () => {
+ expect(definitionRowTitle({ name: 'Nightly digest', message: 'ignored' }, 'Task')).toBe('Nightly digest');
+ });
+
+ it('falls back to the first real line of the message it sends', () => {
+ // 40 of 54 live tasks have no name; without this they render as a hash.
+ expect(definitionRowTitle({ name: null, message: '\n\n Summarize #ops\nand post it ' }, 'Task')).toBe(
+ 'Summarize #ops',
+ );
+ });
+
+ it('collapses whitespace so a wrapped line stays one line', () => {
+ expect(definitionRowTitle({ name: ' Weekly\t\tdigest ' }, 'Task')).toBe('Weekly digest');
+ });
+
+ it('never slices — truncation is the row\'s CSS job, not the title\'s', () => {
+ const long = 'x'.repeat(400);
+ expect(definitionRowTitle({ name: long }, 'Task')).toBe(long);
+ });
+
+ it('names the kind when there is nothing else to say', () => {
+ expect(definitionRowTitle({ name: null, message: ' \n\t' }, 'Watch')).toBe('Watch');
+ });
+});
+
+describe('definitionActivityAt', () => {
+ it('walks the fallback chain instead of gating on one nullable field', () => {
+ expect(definitionActivityAt({ waiting_since: 'a', last_event_at: 'b', updated_at: 'z' })).toBe('a');
+ expect(definitionActivityAt({ last_event_at: 'b', last_run_at: 'c', updated_at: 'z' })).toBe('b');
+ expect(definitionActivityAt({ last_run_at: 'c', updated_at: 'z' })).toBe('c');
+ expect(definitionActivityAt({ last_finished_at: 'd', updated_at: 'z' })).toBe('d');
+ // updated_at is non-null for every row, so the chain always lands.
+ expect(definitionActivityAt({ updated_at: 'z' })).toBe('z');
+ });
+});
+
+describe('definitionChipLabel', () => {
+ it('says whether a watch fires once or keeps watching', () => {
+ expect(definitionChipLabel({ mode: 'forever' }, 'watch', key)).toBe('harness.row.modeForever');
+ expect(definitionChipLabel({ mode: 'once' }, 'watch', key)).toBe('harness.row.modeOnce');
+ expect(definitionChipLabel({}, 'watch', key)).toBe('harness.row.modeOnce');
+ });
+
+ it('says when a task fires, in words', () => {
+ expect(definitionChipLabel({ cron: '17 10 * * *' }, 'task', key)).toBe('harness.cron.daily(10:17)');
+ expect(definitionChipLabel({ schedule_type: 'at', run_at: at(HOUR) }, 'task', key)).toBe('harness.row.modeOnce');
+ });
+});
+
+describe('definitionRowLine', () => {
+ it('tells a dead waiter from a healthy one', () => {
+ const dead = definitionRowLine(
+ { lifecycle_state: 'waiting', mode: 'once', waiting_since: at(-3 * HOUR), process_alive: false },
+ 'watch',
+ key,
+ NOW,
+ );
+ expect(dead.primary).toBe('harness.row.waitingFor(3h)');
+ expect(dead.secondary).toBe('harness.row.processDead');
+ expect(dead.alert).toBe('dead');
+
+ const alive = definitionRowLine(
+ { lifecycle_state: 'waiting', mode: 'once', waiting_since: at(-3 * HOUR), process_alive: true },
+ 'watch',
+ key,
+ NOW,
+ );
+ expect(alive.secondary).toBe('harness.row.processAlive');
+ expect(alive.alert).toBeNull();
+ });
+
+ it('never claims a waiter is dead just because nobody looked', () => {
+ const unknown = definitionRowLine(
+ { lifecycle_state: 'waiting', mode: 'once', waiting_since: at(-HOUR), process_alive: null },
+ 'watch',
+ key,
+ NOW,
+ );
+ expect(unknown.secondary).toBeNull();
+ expect(unknown.alert).toBeNull();
+ });
+
+ it('still prints a time for a forever watch that has never caught anything', () => {
+ // The defect this replaces: the whole block was gated on last_event_at, so
+ // a watch that had waited three days showed no time at all.
+ const line = definitionRowLine(
+ { lifecycle_state: 'waiting', mode: 'forever', last_event_at: null, waiting_since: at(-3 * DAY) },
+ 'watch',
+ key,
+ NOW,
+ );
+ expect(line.primary).toBe('harness.row.waitingFor(3d)');
+ });
+
+ it('leads a forever watch with its most recent catch once it has one', () => {
+ const line = definitionRowLine(
+ { lifecycle_state: 'waiting', mode: 'forever', last_event_at: at(-2 * HOUR), waiting_since: at(-3 * DAY) },
+ 'watch',
+ key,
+ NOW,
+ );
+ expect(line.primary).toBe('harness.row.lastEvent(harness.when.today(11:00))');
+ });
+
+ it('says how a finished row ended, and when', () => {
+ const timedOut = definitionRowLine(
+ { lifecycle_state: 'finished', lifecycle_detail: 'timeout', last_finished_at: at(-DAY) },
+ 'watch',
+ key,
+ NOW,
+ );
+ expect(timedOut.primary).toBe('harness.lifecycle.timeout');
+ expect(timedOut.secondary).toBe('harness.when.yesterday(13:00)');
+ expect(timedOut.alert).toBe('timeout');
+
+ const ok = definitionRowLine(
+ { lifecycle_state: 'finished', lifecycle_detail: 'normal', last_finished_at: at(-DAY) },
+ 'watch',
+ key,
+ NOW,
+ );
+ expect(ok.alert).toBeNull();
+ });
+
+ it('counts down a one-shot task and names its next fire for a cron one', () => {
+ const oneShot = definitionRowLine(
+ { lifecycle_state: 'waiting', schedule_type: 'at', run_at: at(20 * MINUTE), next_run_at: at(20 * MINUTE) },
+ 'task',
+ key,
+ NOW,
+ );
+ expect(oneShot.primary).toBe('harness.row.nextIn(20m)');
+ expect(oneShot.secondary).toBe('harness.when.today(13:20)');
+
+ const recurring = definitionRowLine(
+ {
+ lifecycle_state: 'waiting',
+ cron: '17 10 * * *',
+ next_run_at: at(21 * HOUR + 17 * MINUTE),
+ last_run_at: at(-2 * HOUR - 43 * MINUTE),
+ },
+ 'task',
+ key,
+ NOW,
+ );
+ expect(recurring.primary).toBe('harness.row.nextAt(harness.when.tomorrow(10:17))');
+ expect(recurring.secondary).toBe('harness.row.lastRun(harness.when.today(10:17))');
+ });
+
+ it('does not count upward after a one-shot deadline passes', () => {
+ const line = definitionRowLine(
+ { lifecycle_state: 'waiting', schedule_type: 'at', run_at: at(-MINUTE), next_run_at: at(-MINUTE) },
+ 'task',
+ key,
+ NOW,
+ );
+
+ expect(line.primary).toBe('harness.when.today(12:59)');
+ expect(line.primary).not.toContain('harness.row.nextIn');
+ });
+
+ it('still says something for a waiting task the scheduler has not dated yet', () => {
+ const line = definitionRowLine(
+ { lifecycle_state: 'waiting', cron: '17 10 * * *', next_run_at: null, updated_at: at(-45 * MINUTE) },
+ 'task',
+ key,
+ NOW,
+ );
+ expect(line.primary).toBe('harness.row.waitingFor(45m)');
+ });
+
+ it('reports how long a running row has been running', () => {
+ const line = definitionRowLine(
+ { lifecycle_state: 'running', running_since: at(-12 * MINUTE), process_alive: true },
+ 'watch',
+ key,
+ NOW,
+ );
+ expect(line.primary).toBe('harness.row.runningFor(12m)');
+ expect(line.secondary).toBe('harness.row.processAlive');
+ });
+
+ it('times a running row from the run that is running, not from its last cycle', () => {
+ // A forever watch that caught something yesterday and started a fresh run a
+ // minute ago. The activity chain would answer "1d" — a duration nothing is
+ // spending, assembled from two different cycles.
+ const line = definitionRowLine(
+ {
+ lifecycle_state: 'running',
+ running_since: at(-MINUTE),
+ last_event_at: at(-DAY),
+ last_started_at: at(-DAY),
+ waiting_since: at(-DAY),
+ mode: 'forever',
+ },
+ 'watch',
+ key,
+ NOW,
+ );
+ expect(line.primary).toBe('harness.row.runningFor(1m)');
+ });
+
+ it('prints no duration for a run that is queued rather than started', () => {
+ // ``running`` covers queued-or-running, and a queued run has no start. The
+ // state alone is the whole truth; inventing "running 0s" or reaching back to
+ // the previous cycle would not be.
+ const line = definitionRowLine(
+ { lifecycle_state: 'running', running_since: null, last_started_at: at(-DAY) },
+ 'task',
+ key,
+ NOW,
+ );
+ expect(line.primary).toBe('harness.lifecycle.running');
+ });
+
+ it('withholds an unrecorded pause time but keeps future-state activity', () => {
+ const paused = definitionRowLine({ lifecycle_state: 'paused', updated_at: at(-DAY) }, 'task', key, NOW);
+ expect(paused.primary).toBe('harness.lifecycle.paused');
+ expect(definitionStateSince({ updated_at: at(-DAY) }, 'paused')).toBeNull();
+ expect(paused.secondary).toBeNull();
+ expect(`${paused.primary} ${paused.secondary ?? ''}`).not.toContain('—');
+
+ const unknown = definitionRowLine({ lifecycle_state: 'quiesced', updated_at: at(-DAY) }, 'task', key, NOW);
+ expect(unknown.primary).toBe('harness.lifecycle.unknown');
+ expect(unknown.secondary).toBe('harness.when.yesterday(13:00)');
+ });
+
+ it('prints a time in every branch that has a state-specific fact', () => {
+ // ``running`` carries ``running_since`` here rather than leaning on
+ // ``updated_at`` like the others: it is the one branch with a real source
+ // for its duration, and reaching past it to the activity chain is the very
+ // thing that let a row claim a duration from a previous cycle. A running row
+ // with no start is covered above — it prints the state and no time, on
+ // purpose.
+ const cases: Array<[string, Parameters<typeof definitionRowLine>[0], 'task' | 'watch']> = [
+ ['waiting once watch', { lifecycle_state: 'waiting', mode: 'once', updated_at: at(-HOUR) }, 'watch'],
+ ['waiting forever watch', { lifecycle_state: 'waiting', mode: 'forever', updated_at: at(-HOUR) }, 'watch'],
+ ['finished watch', { lifecycle_state: 'finished', updated_at: at(-HOUR) }, 'watch'],
+ ['running watch', { lifecycle_state: 'running', running_since: at(-HOUR) }, 'watch'],
+ ['waiting task', { lifecycle_state: 'waiting', updated_at: at(-HOUR) }, 'task'],
+ ['stateless row', { updated_at: at(-HOUR) }, 'task'],
+ ];
+ for (const [name, row, kind] of cases) {
+ const line = definitionRowLine(row, kind, key, NOW);
+ expect(`${name}: ${line.primary} ${line.secondary ?? ''}`).toMatch(/harness\.(when|row)\./);
+ }
+ });
+
+ it('gives every state its own timestamp instead of one shared chain', () => {
+ // Every state must name a stored fact or explicitly withhold the time.
+ const row = {
+ running_since: at(-MINUTE),
+ waiting_since: at(-HOUR),
+ last_finished_at: at(-DAY),
+ updated_at: at(-2 * MINUTE),
+ last_run_at: at(-3 * DAY),
+ };
+ expect(definitionStateSince(row, 'running')).toBe(row.running_since);
+ expect(definitionStateSince(row, 'waiting')).toBe(row.waiting_since);
+ expect(definitionStateSince(row, 'finished')).toBe(row.last_finished_at);
+ expect(definitionStateSince(row, 'paused')).toBeNull();
+ // A queued run has not started, so ``running`` has no duration to offer and
+ // must not borrow one.
+ expect(definitionStateSince({ last_run_at: at(-3 * DAY) }, 'running')).toBeNull();
+ });
+
+ it.each([
+ [
+ 'an executed one-shot',
+ { schedule_type: 'at', run_at: at(-2 * DAY), last_run_at: at(-DAY), updated_at: at(-3 * DAY) },
+ at(-DAY),
+ ],
+ [
+ 'a one-shot with no recorded run or finish',
+ { schedule_type: 'at', run_at: at(-DAY), updated_at: at(-3 * DAY) },
+ at(-DAY),
+ ],
+ ['a retired watch', { mode: 'once', last_finished_at: at(-DAY), updated_at: at(-3 * DAY) }, at(-DAY)],
+ ['a cron task', { cron: '0 * * * *', last_run_at: at(-HOUR), updated_at: at(-3 * DAY) }, at(-HOUR)],
+ ])('dates finished %s by the exact available fact', (_name, row, expected) => {
+ expect(definitionStateSince(row, 'finished')).toBe(expected);
+ });
+
+ it('does not report an intentionally retired waiter as dead', () => {
+ // A one-shot watch that just fired: the same call that recorded the catch
+ // stopped its waiter, and the agent run it spawned is still queued, so the
+ // row is ``running`` with a stopped process. That is the success path —
+ // warning here reports a working watch as a monitoring failure.
+ const retired = definitionRowLine(
+ { lifecycle_state: 'running', mode: 'once', enabled: false, process_alive: false, running_since: at(-MINUTE) },
+ 'watch',
+ key,
+ NOW,
+ );
+ expect(retired.alert).toBeNull();
+ expect(retired.secondary).toBeNull();
+
+ // Still armed and the process is gone: that contradiction is the alert.
+ const armed = definitionRowLine(
+ { lifecycle_state: 'waiting', mode: 'forever', enabled: true, process_alive: false, waiting_since: at(-HOUR) },
+ 'watch',
+ key,
+ NOW,
+ );
+ expect(armed.alert).toBe('dead');
+ expect(armed.secondary).toBe('harness.row.processDead');
+
+ // A payload that does not state the switch is not evidence of a shutdown.
+ const unstated = definitionRowLine(
+ { lifecycle_state: 'waiting', mode: 'once', process_alive: false, waiting_since: at(-HOUR) },
+ 'watch',
+ key,
+ NOW,
+ );
+ expect(unstated.alert).toBe('dead');
+ });
+
+ it('has copy behind every row phrase it can produce', () => {
+ expectCopy('harness.row', [
+ 'modeOnce',
+ 'modeForever',
+ 'processAlive',
+ 'processDead',
+ 'runningFor',
+ 'waitingFor',
+ 'lastEvent',
+ 'nextIn',
+ 'nextAt',
+ 'lastRun',
+ ]);
+ expectCopy('harness.when', ['today', 'tomorrow', 'yesterday', 'dateTime']);
+ // Every duration these rows print goes through the same four leaves, so a
+ // unit added in English only fails here instead of shipping "3d" to a
+ // Chinese reader.
+ expectCopy('common.duration', ['seconds', 'minutes', 'hours', 'days']);
+ });
+});
diff --git a/ui/src/components/workbench/harnessLifecycle.ts b/ui/src/components/workbench/harnessLifecycle.ts
new file mode 100644
index 000000000..851425c7f
--- /dev/null
+++ b/ui/src/components/workbench/harnessLifecycle.ts
@@ -0,0 +1,542 @@
+import { formatElapsed } from '../../lib/agentGraph';
+
+// Pure mappers behind the Harness task/watch rows (plan §4.1–§4.3). Like
+// harnessRuns.ts they take ``t`` rather than calling useTranslation, so every
+// branch is unit-testable without a router or an i18n provider, and ``now`` is
+// injectable so the time humanizers are deterministic in tests.
+
+// ---------------------------------------------------------------------------
+// Lifecycle vocabulary
+// ---------------------------------------------------------------------------
+
+export type HarnessLifecycleState = 'running' | 'waiting' | 'paused' | 'finished';
+export type HarnessLifecycleDetail = 'normal' | 'timeout' | 'error';
+
+// The filter chips, and the lifecycle states each one selects.
+//
+// Four chips rather than one per state: ``waiting`` and ``running`` answer a
+// single question — "is this still live?" — and the row's own dot and second
+// line say which of the two it is, exactly as one ``finished`` chip covers
+// three different endings. §4.4 also requires the tab badge to equal the
+// default view, and a chip per state would leave the landing view (waiting +
+// running) matching no chip at all.
+//
+// MIRROR of ``DEFINITION_STATUS_FILTERS`` in ``storage/background.py``, which
+// maps the same names to the same states for the query. Both sides are pinned
+// by a test naming the other file, so a one-sided edit fails instead of quietly
+// listing rows the chip never counted.
+export const DEFINITION_STATUS_FILTER_STATES: Record<string, readonly HarnessLifecycleState[]> = {
+ all: [],
+ active: ['waiting', 'running'],
+ paused: ['paused'],
+ finished: ['finished'],
+};
+
+export const DEFINITION_STATUS_FILTERS = ['all', 'active', 'paused', 'finished'] as const;
+
+// The landing view: what is working for the user right now. The previous
+// default was "enabled only", which read a switch as a state and buried a
+// running task among rows that had merely been left switched on.
+export const DEFAULT_DEFINITION_STATUS = 'active';
+
+// How many rows a chip lists, from the per-state counts the server sends.
+// ``all`` reads ``total`` rather than summing, so a state the server adds later
+// still counts toward it here.
+export function definitionStatusCount(
+ counts: Record<string, number> | null | undefined,
+ status: string,
+): number {
+ const states = DEFINITION_STATUS_FILTER_STATES[status];
+ if (!states || states.length === 0) return counts?.total ?? 0;
+ return states.reduce((sum, state) => sum + (counts?.[state] ?? 0), 0);
+}
+
+// The tab badge (§4.4): how many things are working for the user right now. It
+// is the default view's count by construction — reading it off the same table
+// is what stops the badge promising rows the landing view excludes.
+export function definitionActiveCount(counts: Record<string, number> | null | undefined): number {
+ return definitionStatusCount(counts, DEFAULT_DEFINITION_STATUS);
+}
+
+// The states a *switched-on* row can be in. Flipping the switch moves a row
+// across this line and nowhere else, which is all the optimistic toggle needs
+// to know.
+const LIVE_STATES: readonly HarnessLifecycleState[] = ['waiting', 'running'];
+
+// Whether a row still belongs under ``status`` once its switch reads
+// ``enabled``. Used to drop the detail panel for a row the user just toggled
+// out of the current view — leaving it open would show a row the list no
+// longer contains.
+export function definitionSurvivesToggle(
+ status: string,
+ enabled: boolean,
+ row?: HarnessDefinitionFacts | null,
+): boolean {
+ const states = DEFINITION_STATUS_FILTER_STATES[status];
+ if (!states || states.length === 0) return true;
+ const state = row?.lifecycle_state;
+ // An in-flight run outranks ``enabled`` in the lifecycle case, so flipping
+ // the switch on a running row leaves it exactly where it is until that run
+ // ends. Without this the ``running`` chip would close the panel for a row
+ // that never moved.
+ if (state === 'running') return states.includes('running');
+ // A finished one-shot has no future fire, and the switch cannot invent one.
+ // Ask the same question as the server from the resolved schedule fact instead
+ // of treating ``enabled`` as a promise: re-enabling this row leaves it under
+ // Finished, so its open detail panel stays there too.
+ if (state === 'finished' && row?.schedule_type === 'at' && !row.next_run_at) {
+ return states.includes('finished');
+ }
+ // Otherwise the switch *is* the state: on makes the row ``waiting``; off
+ // takes it out of every live chip, into ``paused`` or ``finished`` — which of
+ // the two is the server's call, and the refresh that follows settles it.
+ if (enabled) return states.includes('waiting');
+ return !states.some((live) => LIVE_STATES.includes(live));
+}
+
+// A finished row names its outcome only when the store provides one. Missing or
+// unrecognised detail still proves the lifecycle state, but not how it ended.
+export function lifecycleLabel(
+ state: string | null | undefined,
+ detail: string | null | undefined,
+ t: (k: string) => string,
+): string {
+ if (state === 'finished') return t(`harness.lifecycle.${detail && DETAILS.has(detail) ? detail : 'finished'}`);
+ if (state && STATES.has(state)) return t(`harness.lifecycle.${state}`);
+ return t('harness.lifecycle.unknown');
+}
+
+const STATES = new Set<string>(['running', 'waiting', 'paused', 'finished']);
+export const LIFECYCLE_DETAILS = ['normal', 'timeout', 'error'] as const;
+const DETAILS = new Set<string>(LIFECYCLE_DETAILS);
+
+// ---------------------------------------------------------------------------
+// Time, never printed raw (§4.2)
+// ---------------------------------------------------------------------------
+
+const pad = (n: number) => String(n).padStart(2, '0');
+
+// Whole calendar days from ``from`` to ``to``, in the reader's local timezone —
+// not (ms / 86400000), which calls 23:59 and 00:01 the same day when they are
+// two minutes and two dates apart.
+function calendarDayDelta(target: Date, now: Date): number {
+ const a = Date.UTC(target.getFullYear(), target.getMonth(), target.getDate());
+ const b = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate());
+ return Math.round((a - b) / 86_400_000);
+}
+
+// An ISO instant as a phrase on the reader's own clock: "today 13:35",
+// "tomorrow 09:00", "07-30 10:17", "2027-01-01 00:00". Unparseable input comes
+// back verbatim rather than as "Invalid Date"; the detail panel still shows the
+// full timestamp.
+export function humanizeTime(
+ iso: string | null | undefined,
+ t: (k: string, opts?: any) => string,
+ now: number = Date.now(),
+): string {
+ if (!iso) return '—';
+ const d = new Date(iso);
+ if (Number.isNaN(d.getTime())) return iso;
+ const time = `${pad(d.getHours())}:${pad(d.getMinutes())}`;
+ const nowDate = new Date(now);
+ const delta = calendarDayDelta(d, nowDate);
+ if (delta === 0) return t('harness.when.today', { time });
+ if (delta === 1) return t('harness.when.tomorrow', { time });
+ if (delta === -1) return t('harness.when.yesterday', { time });
+ const date =
+ d.getFullYear() === nowDate.getFullYear()
+ ? `${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
+ : `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
+ return t('harness.when.dateTime', { date, time });
+}
+
+// Compact magnitude between an instant and now, in R1's duration vocabulary
+// ("42s" / "7m" / "3h"). Callers using direction-bearing copy must compare
+// the instant with ``now`` before naming it. The unit words come from the locale,
+// so ``t`` travels with the number rather than being bolted on later.
+export function humanizeGap(
+ iso: string | null | undefined,
+ now: number,
+ t: (key: string) => string,
+): string | null {
+ if (!iso) return null;
+ const at = Date.parse(iso);
+ if (Number.isNaN(at)) return null;
+ return formatElapsed(Math.abs(at - now) / 1000, t);
+}
+
+// A timestamp with no UTC offset is not an instant — it is a wall-clock reading
+// in some zone the string does not name. ``new Date(...)`` resolves it against
+// the *browser's* zone, so a one-shot stored as "09:00 in Asia/Tokyo" renders as
+// 09:00 to a viewer in Los Angeles, who is 16 hours out. The scheduler resolves
+// these against the row's own ``timezone``; the browser must not guess.
+const UTC_OFFSET_SUFFIX = /(?:Z|[+-]\d{2}:?\d{2})$/i;
+
+export function isWallClockTimestamp(iso: string | null | undefined): boolean {
+ return !!iso && !UTC_OFFSET_SUFFIX.test(iso.trim());
+}
+
+// Print a wall-clock reading as what it is: the clock face, plus the zone it
+// belongs to. No "today/tomorrow", because which day it falls on depends on the
+// zone, and no conversion, because converting is the bug.
+export function formatWallTime(
+ iso: string | null | undefined,
+ timezone: string | null | undefined,
+ t: (k: string, opts?: any) => string,
+): string {
+ if (!iso) return '—';
+ const raw = iso.trim();
+ // Date and hh:mm only; seconds are noise on a schedule. Anything that is not
+ // shaped like a timestamp is printed verbatim rather than reformatted.
+ const parts = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2})/.exec(raw);
+ const clock = parts ? `${parts[1]} ${parts[2]}` : raw;
+ return timezone ? t('harness.when.wallClock', { time: clock, timezone }) : clock;
+}
+
+// ---------------------------------------------------------------------------
+// Cron, in words
+// ---------------------------------------------------------------------------
+
+// APScheduler's week numbering, which is NOT crontab(5)'s.
+//
+// ``CronTrigger.from_crontab`` — what ``compute_next_run_at`` and the scheduler
+// itself use — hands the day-of-week field straight to APScheduler's own parser,
+// where Monday is 0 and Sunday is 6. Under crontab(5) Sunday is 0. Describing
+// ``0 9 * * 1-5`` as "Mon–Fri" while the task actually fires Tue–Sat is exactly
+// the class of lie this surface exists to remove, so the words follow the
+// scheduler rather than the convention the expression was probably written in.
+//
+// Pinned to APScheduler's own ``WEEKDAYS`` constant by a test in
+// ``tests/test_harness_definition_lifecycle.py`` — upgrade the library's
+// numbering and that test fails rather than the rows quietly shifting a day.
+const WEEKDAY_NAMES = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
+const WEEKDAY_INDEX: Record<string, number> = WEEKDAY_NAMES.reduce(
+ (map, name, index) => ({ ...map, [name]: index }),
+ {},
+);
+
+function weekdayNumber(token: string): number | null {
+ const named = WEEKDAY_INDEX[token.toLowerCase()];
+ if (named != null) return named;
+ if (!/^\d+$/.test(token)) return null;
+ const value = Number(token);
+ // No ``7``: APScheduler raises on it ("higher than the maximum value (6)"),
+ // so an expression containing it never fires and must not be described as a
+ // schedule that does.
+ return value >= 0 && value <= 6 ? value : null;
+}
+
+// "1", "1-5", "1,3,5", "MON-FRI" → the days, ascending and de-duplicated.
+// ``null`` for anything else, which sends the whole expression to the raw
+// fallback rather than to a guess.
+function weekdays(field: string): number[] | null {
+ const days = new Set<number>();
+ for (const part of field.split(',')) {
+ const range = part.split('-');
+ if (range.length === 1) {
+ const day = weekdayNumber(range[0]);
+ if (day == null) return null;
+ days.add(day);
+ continue;
+ }
+ if (range.length !== 2) return null;
+ const start = weekdayNumber(range[0]);
+ const end = weekdayNumber(range[1]);
+ if (start == null || end == null) return null;
+ // No wrap-around: crontab(5) accepts FRI-MON, APScheduler rejects it ("the
+ // minimum value in a range must not be higher than the maximum"). A range
+ // it refuses to schedule gets described as the raw expression it is.
+ if (start > end) return null;
+ for (let day = start; day <= end; day += 1) days.add(day);
+ }
+ return days.size ? [...days].sort((a, b) => a - b) : null;
+}
+
+function clockTime(hour: string, minute: string): string | null {
+ if (!/^\d{1,2}$/.test(hour) || !/^\d{1,2}$/.test(minute)) return null;
+ const h = Number(hour);
+ const m = Number(minute);
+ if (h > 23 || m > 59) return null;
+ return `${pad(h)}:${pad(m)}`;
+}
+
+// A cron expression as a phrase: "17 10 * * *" → "every day at 10:17".
+//
+// Covers the shapes the store actually holds (plan §2 measured four distinct
+// expressions, three of them ``M H * * *``) and hands anything else back
+// unchanged — a wrong plain-English schedule is worse than a raw one, and the
+// detail panel prints the expression either way. Deliberately not a dependency:
+// the whole grammar we need is four cases.
+export function humanizeCron(expr: string | null | undefined, t: (k: string, opts?: any) => string): string {
+ const raw = (expr ?? '').trim();
+ if (!raw) return '';
+ const fields = raw.split(/\s+/);
+ if (fields.length !== 5) return raw;
+ const [minute, hour, dayOfMonth, month, dayOfWeek] = fields;
+ if (dayOfMonth !== '*' || month !== '*') return raw;
+
+ if (hour === '*' && dayOfWeek === '*') {
+ if (minute === '*') return t('harness.cron.everyMinute');
+ const step = /^\*\/(\d+)$/.exec(minute);
+ if (step && Number(step[1]) > 0) return t('harness.cron.everyMinutes', { count: Number(step[1]) });
+ return raw;
+ }
+
+ const time = clockTime(hour, minute);
+ if (!time) return raw;
+ if (dayOfWeek === '*') return t('harness.cron.daily', { time });
+ const days = weekdays(dayOfWeek);
+ if (!days) return raw;
+ if (days.length === 7) return t('harness.cron.daily', { time });
+ return t('harness.cron.weekly', {
+ days: days
+ .map((day) => t(`harness.cron.weekday.${WEEKDAY_NAMES[day]}`))
+ .join(t('harness.cron.weekdaySeparator')),
+ time,
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Rows
+// ---------------------------------------------------------------------------
+
+export type HarnessDefinitionKind = 'task' | 'watch';
+
+// The subset of a task/watch payload the row reads. Structural rather than the
+// two concrete types so one set of helpers serves both lists, and so a test can
+// state a case in four fields instead of thirty.
+export type HarnessDefinitionFacts = {
+ lifecycle_state?: HarnessLifecycleState | string | null;
+ lifecycle_detail?: HarnessLifecycleDetail | string | null;
+ next_run_at?: string | null;
+ waiting_since?: string | null;
+ running_since?: string | null;
+ process_alive?: boolean | null;
+ enabled?: boolean | null;
+ timezone?: string | null;
+ mode?: string | null;
+ schedule_type?: string | null;
+ cron?: string | null;
+ run_at?: string | null;
+ last_event_at?: string | null;
+ last_run_at?: string | null;
+ last_started_at?: string | null;
+ last_finished_at?: string | null;
+ updated_at?: string | null;
+};
+
+const WHITESPACE_RUN = /\s+/g;
+
+// One uniform row title for a task or a watch (§4.3): its name, else the first
+// non-empty line of the message it sends, else the kind. ``name`` wins here —
+// unlike a run, a definition's name is the thing the user named it — and the
+// message is what 40 of 54 live tasks have instead of a name, which is why they
+// currently render as a hash.
+//
+// Never slices: the row truncates with CSS so the detail panel and the
+// server-side search index keep the full text.
+export function definitionRowTitle(
+ row: { name?: string | null; message?: string | null; prompt?: string | null },
+ kindLabel: string,
+): string {
+ const name = (row.name ?? '').trim().replace(WHITESPACE_RUN, ' ');
+ if (name) return name;
+ for (const line of (row.message || row.prompt || '').split('\n')) {
+ const collapsed = line.trim().replace(WHITESPACE_RUN, ' ');
+ if (collapsed) return collapsed;
+ }
+ return kindLabel;
+}
+
+// The last moment this row is known to have done anything.
+//
+// §4.2: never gate a whole block on one nullable field. Each candidate is the
+// most precise answer for some row shape — a waiting watch has
+// ``waiting_since``, a ``forever`` watch has ``last_event_at``, a task has
+// ``last_run_at``, a retired row has ``last_finished_at`` — and ``updated_at``
+// is non-null for every row, so the chain always lands. Mirrors the ordering
+// coalesce ``list_watches_page`` already sorts by.
+export function definitionActivityAt(row: HarnessDefinitionFacts): string | null {
+ return (
+ row.waiting_since ||
+ row.last_event_at ||
+ row.last_run_at ||
+ row.last_finished_at ||
+ row.updated_at ||
+ null
+ );
+}
+
+// The moment each state is measured *from*.
+//
+// The activity chain above answers one question — "when did this row last do
+// anything". States with a more precise stored fact use it; paused has no
+// transition timestamp in the store, so it deliberately returns no time.
+export function definitionStateSince(
+ row: HarnessDefinitionFacts,
+ state: HarnessLifecycleState | string | null | undefined,
+): string | null {
+ switch (state) {
+ // Derived from the run that *is* running. Null while that run is queued —
+ // it has not started, so there is no duration, and the state alone is the
+ // honest answer.
+ case 'running':
+ return row.running_since ?? null;
+ // ``waiting_since`` is the server's answer and heads the chain; the chain's
+ // remaining candidates cover a row that has never started.
+ case 'waiting':
+ return row.waiting_since ?? definitionActivityAt(row);
+ // ``updated_at`` also moves on edits while disabled, so no persisted field
+ // can prove when the pause began.
+ case 'paused':
+ return null;
+ // Prefer the most specific recorded event. A one-shot deadline is only the
+ // fallback when neither a stored finish nor an actual run exists.
+ case 'finished':
+ return (
+ row.last_finished_at ??
+ row.last_run_at ??
+ (row.schedule_type === 'at' ? (row.run_at ?? null) : null) ??
+ definitionActivityAt(row)
+ );
+ default:
+ return definitionActivityAt(row);
+ }
+}
+
+// Whether this row still expects its waiter process to be up.
+//
+// A stopped waiter is only news while the switch says "keep watching". A
+// one-shot watch that fired has its waiter stopped on purpose — by the same
+// call that switched it off — and may well still be ``running`` because the
+// agent run it spawned is queued. Warning there reports a successful catch as
+// a monitoring failure. ``undefined`` means the payload did not say, and an
+// unstated switch is not evidence of an intentional shutdown.
+export function waiterExpectedAlive(row: HarnessDefinitionFacts): boolean {
+ return row.enabled !== false;
+}
+
+// Line 1's chip: what kind of schedule this is, in words. A watch says whether
+// it fires once or keeps watching; a task says when it fires.
+export function definitionChipLabel(
+ row: HarnessDefinitionFacts,
+ kind: HarnessDefinitionKind,
+ t: (k: string, opts?: any) => string,
+): string {
+ if (kind === 'watch') {
+ return t(row.mode === 'forever' ? 'harness.row.modeForever' : 'harness.row.modeOnce');
+ }
+ if (row.cron) return humanizeCron(row.cron, t);
+ if (row.schedule_type === 'at' || row.run_at) return t('harness.row.modeOnce');
+ return row.schedule_type || t('harness.unknownSchedule');
+}
+
+// What the row warns about, if anything: how a finished row ended, or a waiter
+// whose process is gone while the row still claims to be armed. ``null`` when
+// there is nothing to warn about — including when liveness is simply unknown,
+// which must not be dressed up as "dead".
+export type HarnessRowAlert = 'error' | 'timeout' | 'dead';
+
+export type HarnessDefinitionLine = {
+ primary: string;
+ secondary: string | null;
+ alert: HarnessRowAlert | null;
+};
+
+function livenessLabel(
+ row: HarnessDefinitionFacts,
+ t: (k: string) => string,
+): string | null {
+ if (row.process_alive === true) return t('harness.row.processAlive');
+ // Report an exit only where an exit is unexpected. A retired waiter did stop,
+ // but saying so reads as a fault report on a row that did its job.
+ if (row.process_alive === false && waiterExpectedAlive(row)) return t('harness.row.processDead');
+ // ``null`` means we have never seen this waiter, which is not the same as
+ // having seen it exit — say nothing rather than claim it is dead.
+ return null;
+}
+
+// Line 2 of a task/watch row: state, not mechanism (§4.2).
+//
+// This is the line that used to print a wait's raw ``wait_pr.py`` argv, complete
+// with a developer's absolute paths, or 790 characters of inline bash. None of
+// that says whether the thing is still working; all of it is still one click
+// away in the detail panel.
+export function definitionRowLine(
+ row: HarnessDefinitionFacts,
+ kind: HarnessDefinitionKind,
+ t: (k: string, opts?: any) => string,
+ now: number = Date.now(),
+): HarnessDefinitionLine {
+ const state = row.lifecycle_state;
+ // Every branch below reads this, never the activity chain directly: the state
+ // decides which timestamp describes it. See ``definitionStateSince``.
+ const since = definitionStateSince(row, state);
+ const liveness = kind === 'watch' ? livenessLabel(row, t) : null;
+ const dead =
+ kind === 'watch' && row.process_alive === false && waiterExpectedAlive(row) ? ('dead' as const) : null;
+
+ if (state === 'finished') {
+ const detail = row.lifecycle_detail;
+ return {
+ primary: lifecycleLabel('finished', detail, t),
+ secondary: humanizeTime(since, t, now),
+ alert: detail === 'error' || detail === 'timeout' ? detail : null,
+ };
+ }
+
+ if (state === 'running') {
+ const duration = humanizeGap(since, now, t);
+ return {
+ primary: duration ? t('harness.row.runningFor', { duration }) : t('harness.lifecycle.running'),
+ secondary: liveness,
+ alert: dead,
+ };
+ }
+
+ if (state === 'waiting') {
+ if (kind === 'watch') {
+ // A ``forever`` watch reports its most recent catch; a ``once`` watch has
+ // nothing to report until it fires, so it reports how long it has been
+ // waiting. Either way the fallback chain guarantees a time.
+ const primary =
+ row.mode === 'forever' && row.last_event_at
+ ? t('harness.row.lastEvent', { when: humanizeTime(row.last_event_at, t, now) })
+ : t('harness.row.waitingFor', { duration: humanizeGap(since, now, t) ?? '—' });
+ return { primary, secondary: liveness, alert: dead };
+ }
+ if (row.next_run_at) {
+ const gap = humanizeGap(row.next_run_at, now, t);
+ const when = humanizeTime(row.next_run_at, t, now);
+ const nextRunMs = Date.parse(row.next_run_at);
+ const isFuture = Number.isFinite(nextRunMs) && nextRunMs > now;
+ // A one-shot's headline is how long is left; a recurring task's is when
+ // it next fires, with its previous fire as the secondary.
+ if (row.schedule_type === 'at' || (!row.cron && row.run_at)) {
+ return {
+ primary: gap && isFuture ? t('harness.row.nextIn', { duration: gap }) : when,
+ secondary: when,
+ alert: null,
+ };
+ }
+ return {
+ primary: t('harness.row.nextAt', { when }),
+ secondary: row.last_run_at ? t('harness.row.lastRun', { when: humanizeTime(row.last_run_at, t, now) }) : null,
+ alert: null,
+ };
+ }
+ return {
+ primary: t('harness.row.waitingFor', { duration: humanizeGap(since, now, t) ?? '—' }),
+ secondary: row.last_run_at ? t('harness.row.lastRun', { when: humanizeTime(row.last_run_at, t, now) }) : null,
+ alert: null,
+ };
+ }
+
+ // Paused has no transition timestamp in today's schema. Unknown future states
+ // still keep the activity fallback so a newer server does not lose context.
+ return {
+ primary: lifecycleLabel(state ?? 'paused', null, t),
+ secondary: since ? humanizeTime(since, t, now) : null,
+ alert: null,
+ };
+}
diff --git a/ui/src/components/workbench/harnessRuns.ts b/ui/src/components/workbench/harnessRuns.ts
index f347eb26f..dcc98f121 100644
--- a/ui/src/components/workbench/harnessRuns.ts
+++ b/ui/src/components/workbench/harnessRuns.ts
@@ -78,6 +78,7 @@ export const BLANK_SESSION_SUMMARY: HarnessSessionSummary = {
session_scope_kind: null,
session_label: null,
session_is_workbench: false,
+ session_openable: false,
};
// Which of the four states a bound session is in (plan §4.2).
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 1c80b6574..bb887c280 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -1154,17 +1154,47 @@ export type InboxFeedResult = {
// =============================================================================
// Server-resolved view of a task/watch's bound session, for the cards. A
-// workbench session carries a title and is linkable to its chat; an IM session
-// resolves to its platform + channel display name and is not linkable.
+// workbench session carries a title; an IM session resolves to its platform +
+// channel display name.
+//
+// ``session_is_workbench`` chooses the icon and which label to show.
+// ``session_openable`` — and only it — decides whether the label is a link:
+// ``/chat/<id>`` opens IM-bound sessions too, so linking on "is workbench" hid
+// working destinations behind a bare id. One predicate answers it for every
+// surface (``storage/agent_session_rows.py::session_openable_in_chat``).
export type HarnessSessionSummary = {
session_title: string | null;
session_platform: string | null;
session_scope_kind: string | null;
session_label: string | null;
session_is_workbench: boolean;
+ session_openable: boolean;
};
-export type HarnessTask = HarnessSessionSummary & {
+// What a task/watch is *doing*, derived server-side from columns that already
+// exist. ``enabled`` is a switch and was being read as a state, which made a
+// one-shot that finished on its own indistinguishable from one the user paused.
+// ``lifecycle_detail`` is set only on ``finished`` rows and says how they ended.
+export type HarnessLifecycleState = 'running' | 'waiting' | 'paused' | 'finished';
+export type HarnessLifecycleDetail = 'normal' | 'timeout' | 'error';
+
+// The fields every task/watch row reads to describe its state.
+export type HarnessDefinitionState = {
+ lifecycle_state: HarnessLifecycleState | null;
+ lifecycle_detail: HarnessLifecycleDetail | null;
+ // When the scheduler will fire this next; null when nothing is promised.
+ next_run_at: string | null;
+ // When the current wait began — set only while ``waiting``, so a paused row's
+ // last start reads as history rather than a wait anyone is still in.
+ waiting_since: string | null;
+ // When the run that makes this row ``running`` actually started. Null while
+ // that run is still queued, and null in every other state — a duration for
+ // "how long has this been running" must come from the run that is running,
+ // not from whenever the row last did anything.
+ running_since: string | null;
+};
+
+export type HarnessTask = HarnessSessionSummary & HarnessDefinitionState & {
id: string;
name: string | null;
agent_name: string | null;
@@ -1186,7 +1216,6 @@ export type HarnessTask = HarnessSessionSummary & {
last_run_at: string | null;
last_run_id: string | null;
last_error: string | null;
- next_run_at: string | null;
};
export type HarnessWatchRuntime = {
@@ -1196,7 +1225,7 @@ export type HarnessWatchRuntime = {
updated_at?: string | null;
};
-export type HarnessWatch = HarnessSessionSummary & {
+export type HarnessWatch = HarnessSessionSummary & HarnessDefinitionState & {
id: string;
name: string | null;
agent_name: string | null;
@@ -1221,20 +1250,40 @@ export type HarnessWatch = HarnessSessionSummary & {
updated_at: string | null;
last_started_at: string | null;
last_finished_at: string | null;
+ retired_at: string | null;
last_event_at: string | null;
last_error: string | null;
last_exit_code: number | null;
runtime: HarnessWatchRuntime;
+ // Whether the waiter process is alive. ``null`` means we have never seen a
+ // heartbeat for it, which is not the same as having seen it exit — the row
+ // must not report a dead waiter on the strength of never having looked.
+ process_alive: boolean | null;
};
export type HarnessRunStatus = 'queued' | 'running' | 'succeeded' | 'failed' | 'canceled' | (string & {});
-export type HarnessDefinitionStatus = 'all' | 'enabled' | 'disabled';
-
+// Everything the list endpoint accepts. The UI offers four of these as chips
+// (see ``harnessLifecycle.ts``); the per-state values stay valid so a deep link
+// can name one exactly.
+export type HarnessDefinitionStatus =
+ | 'all'
+ | 'active'
+ | 'running'
+ | 'waiting'
+ | 'paused'
+ | 'finished';
+
+// Counts are per *state*, one bucket per lifecycle value plus the total, so a
+// chip spanning two states sums them client-side rather than asking the server
+// for a bucket named after a chip.
export type HarnessDefinitionCounts = {
- all: number;
- enabled: number;
- disabled: number;
+ total: number;
+ running: number;
+ waiting: number;
+ paused: number;
+ finished: number;
+ [key: string]: number;
};
export type HarnessRunCounts = {
@@ -1265,7 +1314,15 @@ export type HarnessRun = HarnessSessionSummary & {
callback_session: HarnessSessionSummary | null;
task_id: string | null;
source_kind: string | null;
+ // Polymorphic: a session id when ``source_kind === 'agent'``, otherwise a
+ // parent run id, a vault request handle, or a human's name. Render it raw
+ // only when ``source_session`` is null — that is the resolved form, and it is
+ // non-null exactly when the actor names a session.
source_actor: string | null;
+ // ``source_actor`` narrowed to the session case, so the UI never has to
+ // re-derive "is this string an id?" from ``source_kind``.
+ source_session_id: string | null;
+ source_session: HarnessSessionSummary | null;
parent_run_id: string | null;
// Callback (report-back) lineage — serialized by the backend run row but
// previously unrendered; the run detail surfaces these (Part B).
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index f0ab953f9..4986281c3 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -104,7 +104,13 @@
"step": "Step",
"proxyUrl": "Proxy URL (optional)",
"proxyUrlHint": "SOCKS5, SOCKS4, HTTP or HTTPS proxy. Leave empty to fall back to system SOCKS proxy detection or direct connection.",
- "proxyUrlCollapsedHint": "(blank → system proxy if set, else direct)"
+ "proxyUrlCollapsedHint": "(blank → system proxy if set, else direct)",
+ "duration": {
+ "seconds": "s",
+ "minutes": "m",
+ "hours": "h",
+ "days": "d"
+ }
},
"nav": {
"dashboard": "Dashboard",
@@ -2588,15 +2594,17 @@
},
"harness": {
"title": "Harness",
- "subtitle": "Scheduled tasks, watches, webhooks, and the run history of all three.",
- "soon": "soon",
+ "subtitle": "Scheduled tasks, watches, and the run history of both.",
"create": "Create",
"searchPlaceholder": "Search…",
"searchRunsPlaceholder": "Search runs…",
"statusFilter": {
"all": "All",
- "enabled": "Enabled only",
- "disabled": "Disabled only"
+ "active": "Live",
+ "waiting": "Waiting",
+ "running": "Running",
+ "paused": "Paused",
+ "finished": "Finished"
},
"runStatus": {
"all": "All",
@@ -2634,25 +2642,14 @@
"emptyTasks": "No scheduled tasks. Ask an agent to create one.",
"emptyWatches": "No watches running. Ask an agent to start one.",
"emptyRuns": "No runs yet. They appear here once a task or watch fires.",
- "webhooksSoon": "Webhooks are coming soon",
- "webhooksSoonBody": "Inbound HTTP triggers will land in a follow-up release. Tasks and watches cover scheduled and event-driven runs today.",
+ "noTaskMatches": "No tasks match this view. Clear the filters or search.",
+ "noWatchMatches": "No watches match this view. Clear the filters or search.",
+ "noRunMatches": "No runs match this view. Clear the filters or search.",
"unknownSchedule": "unknown schedule",
- "schedule": {
- "cron": "cron · {{value}}",
- "oneShot": "one-shot · {{value}}"
- },
"pageLabel": "page {{page}}",
- "runtime": {
- "running": "Running",
- "paused": "Paused",
- "idle": "Idle",
- "enabled": "Enabled",
- "disabled": "Disabled"
- },
"tabs": {
"tasks": "Tasks",
"watches": "Watches",
- "webhooks": "Webhooks",
"runs": "Runs"
},
"detail": {
@@ -2683,7 +2680,8 @@
"source": "Source",
"parentRun": "Parent run",
"callback": "Callback",
- "effort": "effort {{value}}"
+ "effort": "effort {{value}}",
+ "waitingSince": "Waiting since"
},
"sessionPolicy": {
"createPerRun": "New session each run",
@@ -2700,7 +2698,17 @@
"disable": "Disable",
"delete": "Delete",
"deleteConfirmTask": "Delete \"{{name}}\"? It will stop running.",
- "deleteConfirmWatch": "Delete \"{{name}}\"? The watch will stop immediately."
+ "deleteConfirmWatch": "Delete \"{{name}}\"? The watch will stop immediately.",
+ "modeOnce": "one-shot",
+ "modeForever": "continuous",
+ "processAlive": "process running",
+ "processDead": "process exited",
+ "runningFor": "running {{duration}}",
+ "waitingFor": "waiting {{duration}}",
+ "lastEvent": "last fired {{when}}",
+ "nextIn": "fires in {{duration}}",
+ "nextAt": "next {{when}}",
+ "lastRun": "last {{when}}"
},
"createDialog": {
"title": "Talk to an agent to set up background work",
@@ -2719,6 +2727,43 @@
},
"run": {
"definitionDeleted": "(deleted)"
+ },
+ "lifecycle": {
+ "running": "Running",
+ "waiting": "Waiting",
+ "paused": "Paused",
+ "finished": "Finished",
+ "normal": "Finished",
+ "timeout": "Timed out",
+ "error": "Failed",
+ "unknown": "Unknown"
+ },
+ "kind": {
+ "task": "Scheduled task",
+ "watch": "Watch"
+ },
+ "when": {
+ "today": "today {{time}}",
+ "tomorrow": "tomorrow {{time}}",
+ "yesterday": "yesterday {{time}}",
+ "dateTime": "{{date}} {{time}}",
+ "wallClock": "{{time}} ({{timezone}})"
+ },
+ "cron": {
+ "everyMinute": "every minute",
+ "everyMinutes": "every {{count}} min",
+ "daily": "every day at {{time}}",
+ "weekly": "{{days}} at {{time}}",
+ "weekday": {
+ "sun": "Sun",
+ "mon": "Mon",
+ "tue": "Tue",
+ "wed": "Wed",
+ "thu": "Thu",
+ "fri": "Fri",
+ "sat": "Sat"
+ },
+ "weekdaySeparator": ", "
}
},
"chat": {
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 7a458d85c..17d543f78 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -104,7 +104,13 @@
"step": "步骤",
"proxyUrl": "代理地址(可选)",
"proxyUrlHint": "SOCKS5、SOCKS4、HTTP 或 HTTPS 代理。留空则回退到系统 SOCKS 代理探测,未配置时直连。",
- "proxyUrlCollapsedHint": "(留空则尝试系统代理,否则直连)"
+ "proxyUrlCollapsedHint": "(留空则尝试系统代理,否则直连)",
+ "duration": {
+ "seconds": "秒",
+ "minutes": "分",
+ "hours": "小时",
+ "days": "天"
+ }
},
"nav": {
"dashboard": "控制台",
@@ -2588,15 +2594,17 @@
},
"harness": {
"title": "Harness",
- "subtitle": "定时任务、Watch、Webhook 及其运行历史。",
- "soon": "敬请期待",
+ "subtitle": "定时任务、Watch 及其运行历史。",
"create": "创建",
"searchPlaceholder": "搜索…",
"searchRunsPlaceholder": "搜索运行记录…",
"statusFilter": {
"all": "全部",
- "enabled": "仅启用",
- "disabled": "仅禁用"
+ "active": "进行中",
+ "waiting": "在等",
+ "running": "在跑",
+ "paused": "已暂停",
+ "finished": "已结束"
},
"runStatus": {
"all": "全部",
@@ -2634,25 +2642,14 @@
"emptyTasks": "暂无定时任务。让 Agent 帮你创建一个。",
"emptyWatches": "没有正在运行的 Watch。让 Agent 帮你开启一个。",
"emptyRuns": "暂无运行记录。任务或 Watch 触发后会出现在这里。",
- "webhooksSoon": "Webhook 即将上线",
- "webhooksSoonBody": "入站 HTTP 触发将在后续版本中落地。Tasks 和 Watches 已覆盖定时与事件驱动的运行。",
+ "noTaskMatches": "当前视图没有匹配的任务。请清除筛选或搜索。",
+ "noWatchMatches": "当前视图没有匹配的 Watch。请清除筛选或搜索。",
+ "noRunMatches": "当前视图没有匹配的运行记录。请清除筛选或搜索。",
"unknownSchedule": "未知计划",
- "schedule": {
- "cron": "周期 · {{value}}",
- "oneShot": "一次性 · {{value}}"
- },
"pageLabel": "第 {{page}} 页",
- "runtime": {
- "running": "运行中",
- "paused": "已暂停",
- "idle": "空闲",
- "enabled": "已启用",
- "disabled": "已禁用"
- },
"tabs": {
"tasks": "Tasks",
"watches": "Watches",
- "webhooks": "Webhooks",
"runs": "Runs"
},
"detail": {
@@ -2683,7 +2680,8 @@
"source": "来源",
"parentRun": "父 Run",
"callback": "回传",
- "effort": "推理 {{value}}"
+ "effort": "推理 {{value}}",
+ "waitingSince": "开始等待"
},
"sessionPolicy": {
"createPerRun": "每次运行新建会话",
@@ -2700,7 +2698,17 @@
"disable": "禁用",
"delete": "删除",
"deleteConfirmTask": "确定要删除「{{name}}」吗?该任务将不再运行。",
- "deleteConfirmWatch": "确定要删除「{{name}}」吗?Watch 会被立即停止。"
+ "deleteConfirmWatch": "确定要删除「{{name}}」吗?Watch 会被立即停止。",
+ "modeOnce": "一次性",
+ "modeForever": "持续",
+ "processAlive": "进程在跑",
+ "processDead": "进程已退出",
+ "runningFor": "已跑 {{duration}}",
+ "waitingFor": "已等 {{duration}}",
+ "lastEvent": "最近一次 {{when}}",
+ "nextIn": "还有 {{duration}}",
+ "nextAt": "下次 {{when}}",
+ "lastRun": "上次 {{when}}"
},
"createDialog": {
"title": "和 Agent 对话来创建后台任务",
@@ -2719,6 +2727,43 @@
},
"run": {
"definitionDeleted": "(已删除)"
+ },
+ "lifecycle": {
+ "running": "运行中",
+ "waiting": "等待中",
+ "paused": "已暂停",
+ "finished": "已结束",
+ "normal": "正常结束",
+ "timeout": "已超时",
+ "error": "出错结束",
+ "unknown": "未知"
+ },
+ "kind": {
+ "task": "定时任务",
+ "watch": "Watch"
+ },
+ "when": {
+ "today": "今天 {{time}}",
+ "tomorrow": "明天 {{time}}",
+ "yesterday": "昨天 {{time}}",
+ "dateTime": "{{date}} {{time}}",
+ "wallClock": "{{time}}({{timezone}})"
+ },
+ "cron": {
+ "everyMinute": "每分钟",
+ "everyMinutes": "每 {{count}} 分钟",
+ "daily": "每天 {{time}}",
+ "weekly": "每周{{days}} {{time}}",
+ "weekday": {
+ "sun": "日",
+ "mon": "一",
+ "tue": "二",
+ "wed": "三",
+ "thu": "四",
+ "fri": "五",
+ "sat": "六"
+ },
+ "weekdaySeparator": "、"
}
},
"chat": {
diff --git a/ui/src/lib/agentGraph.test.ts b/ui/src/lib/agentGraph.test.ts
index b700f8079..f4ff87d2a 100644
--- a/ui/src/lib/agentGraph.test.ts
+++ b/ui/src/lib/agentGraph.test.ts
@@ -1,5 +1,7 @@
import { describe, expect, it } from 'vitest';
+import en from '../i18n/en.json';
+import zh from '../i18n/zh.json';
import {
type AgentGraphEdge,
type AgentGraphNode,
@@ -47,13 +49,39 @@ const trigger: AgentGraphTriggerNode = {
enabled: true,
};
+// Resolves against a real bundle: the unit is user-visible copy composed into
+// the value, so a test that stubbed it would assert the formatter agrees with
+// itself rather than with what ships.
+const unit = (bundle: { common: { duration: Record<string, string> } }) => (k: string) =>
+ bundle.common.duration[k.replace('common.duration.', '')];
+const t = unit(en);
+
describe('formatElapsed', () => {
it('humanizes seconds/minutes/hours', () => {
- expect(formatElapsed(12)).toBe('12s');
- expect(formatElapsed(185)).toBe('3m');
- expect(formatElapsed(3700)).toBe('1h');
- expect(formatElapsed(null)).toBe('—');
- expect(formatElapsed(-5)).toBe('0s');
+ expect(formatElapsed(12, t)).toBe('12s');
+ expect(formatElapsed(185, t)).toBe('3m');
+ expect(formatElapsed(3700, t)).toBe('1h');
+ expect(formatElapsed(null, t)).toBe('—');
+ expect(formatElapsed(-5, t)).toBe('0s');
+ });
+
+ it('switches to days rather than counting past 24 hours', () => {
+ // A Harness watch waits for days on end; "168h" is a number the reader has
+ // to divide before it means anything.
+ expect(formatElapsed(86_399, t)).toBe('23h');
+ expect(formatElapsed(86_400, t)).toBe('1d');
+ expect(formatElapsed(7 * 86_400 + 3600, t)).toBe('7d');
+ });
+
+ it('takes every unit from the locale instead of hardcoding English', () => {
+ // The whole formatter, not just the day branch: "等待 3h" was already
+ // shipping before the day unit was added, so fixing one suffix would have
+ // left the same defect in the other three.
+ const zhT = unit(zh);
+ expect(formatElapsed(12, zhT)).toBe('12秒');
+ expect(formatElapsed(185, zhT)).toBe('3分');
+ expect(formatElapsed(3700, zhT)).toBe('1小时');
+ expect(formatElapsed(3 * 86_400, zhT)).toBe('3天');
});
});
diff --git a/ui/src/lib/agentGraph.ts b/ui/src/lib/agentGraph.ts
index fd17267cc..d157868ba 100644
--- a/ui/src/lib/agentGraph.ts
+++ b/ui/src/lib/agentGraph.ts
@@ -206,25 +206,37 @@ export function isBackground(node: Pick<AgentGraphNode, 'visibility'>): boolean
return node.visibility === 'background';
}
-// Human-friendly duration: 12 → "12s", 185 → "3m", 3700 → "1h". Mirrors the
-// running-list formatter so the graph and list read consistently.
-export function formatElapsed(seconds: number | null | undefined): string {
+// Human-friendly duration: 12 → "12s", 185 → "3m", 3700 → "1h", 259200 → "3d".
+// One formatter for every duration the workbench prints, so the graph, the run
+// rows and the Harness rows read consistently.
+//
+// The day unit exists because a Harness watch is not a run: a ``forever`` watch
+// waits until something happens, which is routinely days, and "waiting 168h" is
+// a number the reader has to divide before it means anything. Runs inherit it
+// for free — a three-day run reads the same way.
+//
+// ``t`` is required rather than optional because the unit is user-visible text:
+// an optional translator would leave a path that silently prints English into a
+// Chinese UI, which is how "等待 3h" shipped in the first place.
+export function formatElapsed(seconds: number | null | undefined, t: (key: string) => string): string {
if (seconds == null) return '—';
const s = Math.max(0, seconds);
- if (s < 60) return `${Math.round(s)}s`;
- if (s < 3600) return `${Math.floor(s / 60)}m`;
- return `${Math.floor(s / 3600)}h`;
+ if (s < 60) return `${Math.round(s)}${t('common.duration.seconds')}`;
+ if (s < 3600) return `${Math.floor(s / 60)}${t('common.duration.minutes')}`;
+ if (s < 86_400) return `${Math.floor(s / 3600)}${t('common.duration.hours')}`;
+ return `${Math.floor(s / 86_400)}${t('common.duration.days')}`;
}
// Elapsed seconds for a run row: completed − started, or now − started while
// still open. Derived client-side since A1 carries timestamps, not a duration.
export function runElapsedSeconds(
run: Pick<AgentGraphRunRow, 'started_at' | 'completed_at'>,
+ now: number = Date.now(),
): number | null {
if (!run.started_at) return null;
const start = Date.parse(run.started_at);
if (Number.isNaN(start)) return null;
- const end = run.completed_at ? Date.parse(run.completed_at) : Date.now();
+ const end = run.completed_at ? Date.parse(run.completed_at) : now;
return Math.max(0, (end - start) / 1000);
}
diff --git a/ui/src/lib/relativeTime.ts b/ui/src/lib/relativeTime.ts
index a4690d514..1c7bac944 100644
--- a/ui/src/lib/relativeTime.ts
+++ b/ui/src/lib/relativeTime.ts
@@ -3,11 +3,15 @@
// English suffixes; centralise here so the i18n strings live in one place.
import type { TFunction } from 'i18next';
-export function formatRelativeTime(iso: string | null | undefined, t: TFunction): string {
+export function formatRelativeTime(
+ iso: string | null | undefined,
+ t: TFunction,
+ now: number = Date.now(),
+): string {
if (!iso) return '—';
const then = new Date(iso).getTime();
if (Number.isNaN(then)) return iso;
- const diffSec = Math.round((Date.now() - then) / 1000);
+ const diffSec = Math.round((now - then) / 1000);
if (diffSec < 60) return t('common.relative.justNow');
const mins = Math.round(diffSec / 60);
if (mins < 60) return t('common.relative.minutesAgo', { count: mins });
diff --git a/ui/src/lib/useVisibleNow.test.ts b/ui/src/lib/useVisibleNow.test.ts
new file mode 100644
index 000000000..1859088ce
--- /dev/null
+++ b/ui/src/lib/useVisibleNow.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { startVisibleTicker, VISIBLE_NOW_INTERVAL_MS } from './useVisibleNow';
+import type { VisibleTickerHost } from './useVisibleNow';
+
+describe('startVisibleTicker', () => {
+ it('ticks every 30s only while visible and re-syncs on return', () => {
+ let visible = true;
+ let visibilityListener: (() => void) | null = null;
+ let intervalCallback: (() => void) | null = null;
+ const tick = vi.fn();
+ const host: VisibleTickerHost = {
+ isVisible: () => visible,
+ setInterval: vi.fn((callback, intervalMs) => {
+ expect(intervalMs).toBe(VISIBLE_NOW_INTERVAL_MS);
+ intervalCallback = callback;
+ return 7;
+ }),
+ clearInterval: vi.fn(),
+ addVisibilityListener: vi.fn((callback) => {
+ visibilityListener = callback;
+ }),
+ removeVisibilityListener: vi.fn(),
+ };
+
+ const cleanup = startVisibleTicker(tick, VISIBLE_NOW_INTERVAL_MS, host);
+ expect(tick).toHaveBeenCalledTimes(1);
+ intervalCallback?.();
+ expect(tick).toHaveBeenCalledTimes(2);
+
+ visible = false;
+ visibilityListener?.();
+ expect(host.clearInterval).toHaveBeenCalledWith(7);
+
+ visible = true;
+ visibilityListener?.();
+ expect(tick).toHaveBeenCalledTimes(3);
+ expect(host.setInterval).toHaveBeenCalledTimes(2);
+
+ cleanup();
+ expect(host.removeVisibilityListener).toHaveBeenCalledWith(visibilityListener);
+ });
+
+ it('does not start a timer in a hidden document', () => {
+ let visibilityListener: (() => void) | null = null;
+ const tick = vi.fn();
+ const host: VisibleTickerHost = {
+ isVisible: () => false,
+ setInterval: vi.fn(() => 9),
+ clearInterval: vi.fn(),
+ addVisibilityListener: vi.fn((callback) => {
+ visibilityListener = callback;
+ }),
+ removeVisibilityListener: vi.fn(),
+ };
+
+ const cleanup = startVisibleTicker(tick, VISIBLE_NOW_INTERVAL_MS, host);
+ expect(tick).not.toHaveBeenCalled();
+ expect(host.setInterval).not.toHaveBeenCalled();
+ cleanup();
+ expect(host.removeVisibilityListener).toHaveBeenCalledWith(visibilityListener);
+ });
+});
diff --git a/ui/src/lib/useVisibleNow.ts b/ui/src/lib/useVisibleNow.ts
new file mode 100644
index 000000000..603c1dd25
--- /dev/null
+++ b/ui/src/lib/useVisibleNow.ts
@@ -0,0 +1,57 @@
+import { useEffect, useState } from 'react';
+
+export const VISIBLE_NOW_INTERVAL_MS = 30_000;
+
+export interface VisibleTickerHost {
+ isVisible: () => boolean;
+ setInterval: (callback: () => void, intervalMs: number) => number;
+ clearInterval: (timer: number) => void;
+ addVisibilityListener: (callback: () => void) => void;
+ removeVisibilityListener: (callback: () => void) => void;
+}
+
+const browserHost: VisibleTickerHost = {
+ isVisible: () => document.visibilityState === 'visible',
+ setInterval: (callback, intervalMs) => window.setInterval(callback, intervalMs),
+ clearInterval: (timer) => window.clearInterval(timer),
+ addVisibilityListener: (callback) => document.addEventListener('visibilitychange', callback),
+ removeVisibilityListener: (callback) => document.removeEventListener('visibilitychange', callback),
+};
+
+export function startVisibleTicker(
+ onTick: () => void,
+ intervalMs: number = VISIBLE_NOW_INTERVAL_MS,
+ host: VisibleTickerHost = browserHost,
+): () => void {
+ let timer: number | null = null;
+
+ const stop = () => {
+ if (timer === null) return;
+ host.clearInterval(timer);
+ timer = null;
+ };
+ const sync = () => {
+ if (!host.isVisible()) {
+ stop();
+ return;
+ }
+ onTick();
+ if (timer === null) timer = host.setInterval(onTick, intervalMs);
+ };
+
+ sync();
+ host.addVisibilityListener(sync);
+ return () => {
+ stop();
+ host.removeVisibilityListener(sync);
+ };
+}
+
+export function useVisibleNow(intervalMs: number = VISIBLE_NOW_INTERVAL_MS): number {
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(
+ () => startVisibleTicker(() => setNow(Date.now()), intervalMs),
+ [intervalMs],
+ );
+ return now;
+}
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 6d28a3359..809c06a85 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -8161,9 +8161,14 @@ def _harness_page_request(default_limit: int = 30):
def _harness_status_filter() -> str:
+ """``?status=`` for tasks/watches, validated against the store's own filter
+ table so the route cannot accept a value the query would reject (or reject
+ one it would accept)."""
+ from storage.background import DEFINITION_STATUS_FILTERS
+
status = request.args.get("status") or "all"
- if status not in {"all", "enabled", "disabled"}:
- raise ValueError("status must be one of: all, enabled, disabled")
+ if status not in DEFINITION_STATUS_FILTERS:
+ raise ValueError("status must be one of: " + ", ".join(DEFINITION_STATUS_FILTERS))
return status
@@ -8201,7 +8206,10 @@ def _harness_page_payload(page_result, *, items_key: str, counts: dict[str, int]
def _harness_page_payload_for_status(page_result, *, items_key: str, counts: dict[str, int], status: str) -> dict[str, Any]:
- total = int(counts.get(status or "all", 0))
+ # Tasks/watches only — runs build their payload from their own count call.
+ from storage.background import definition_status_total
+
+ total = definition_status_total(counts, status)
return {
items_key: page_result.items,
"counts": counts,
@@ -8234,7 +8242,7 @@ def harness_tasks_list():
{
"tasks": tasks,
"counts": counts,
- "total": counts["all"],
+ "total": counts["total"],
"page": 1,
"limit": len(tasks),
"has_more": False,
@@ -8288,14 +8296,11 @@ def harness_watches_list():
with _harness_store() as store:
watches = store.list_watches()
counts = store.count_watches()
- runtime = store.load_watch_runtime().get("watches") or {}
- for watch in watches:
- watch["runtime"] = runtime.get(watch["id"]) or {"running": False}
return jsonify(
{
"watches": watches,
"counts": counts,
- "total": counts["all"],
+ "total": counts["total"],
"page": 1,
"limit": len(watches),
"has_more": False,
@@ -8317,9 +8322,6 @@ def harness_watches_list():
newest_first=True,
)
counts = store.count_watches(query=query, session_id=session_id)
- runtime = store.load_watch_runtime().get("watches") or {}
- for watch in page_result.items:
- watch["runtime"] = runtime.get(watch["id"]) or {"running": False}
return jsonify(_harness_page_payload(page_result, items_key="watches", counts=counts))
@@ -8334,9 +8336,6 @@ def harness_watch_patch(watch_id: str):
return jsonify({"ok": False, "code": "watch_not_found"}), 404
store.set_definition_enabled(watch_id, enabled, definition_type="watch")
watch = store.get_watch(watch_id)
- runtime = store.load_watch_runtime().get("watches") or {}
- if watch:
- watch["runtime"] = runtime.get(watch_id) or {"running": False}
return jsonify({"ok": True, "watch": watch})
@@ -8454,9 +8453,6 @@ def harness_bootstrap():
page_request=page_request,
newest_first=True,
)
- runtime = store.load_watch_runtime().get("watches") or {}
- for watch in page_result.items:
- watch["runtime"] = runtime.get(watch["id"]) or {"running": False}
page_payload = _harness_page_payload_for_status(
page_result,
items_key="watches",