The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(kanban): run clock ticks from the current run, not the task's first start
Kevin Rajan0ebaf162cc82
diff --git a/apps/desktop/src/plugins/kanban/run-clock.test.tsx b/apps/desktop/src/plugins/kanban/run-clock.test.tsxnew file mode 100644index 00000000000..c4556b1af55--- /dev/null+++ b/apps/desktop/src/plugins/kanban/run-clock.test.tsx@@ -0,0 +1,65 @@+import { cleanup, render, screen } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++// Test harness supplies the host's locale registration, as plugin loading does.+// eslint-disable-next-line no-restricted-imports+import { registerPluginLocales } from '@/i18n/plugin-i18n'++import { en, KANBAN_LOCALES } from './i18n'+import type { KanbanTask } from './types'+import { RunClock } from './ui'++let disposeLocales: () => void++beforeEach(() => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date('2026-09-16T18:00:00Z'))+ disposeLocales = registerPluginLocales('kanban', KANBAN_LOCALES)+})++afterEach(() => {+ cleanup()+ disposeLocales()+ vi.useRealTimers()+})++// #99819: a retried task's first start is hours old while the fresh run is+// minutes old — the clock must tick from the current run, not task.started_at.+describe('RunClock', () => {+ it('ticks from the current run start instead of the task first start', () => {+ const now = Math.floor(Date.now() / 1000)++ const task: KanbanTask = {+ id: 't1',+ title: 'retried',+ status: 'running',+ started_at: now - 7200, // first start: 2h ago+ current_run_started_at: now - 90 // retry run: 90s ago+ }++ render(<RunClock task={task} />)++ expect(screen.getByText(`${en.working} · 1m`)).toBeTruthy()+ })++ it('falls back to started_at when the backend predates the field', () => {+ const now = Math.floor(Date.now() / 1000)++ const task: KanbanTask = {+ id: 't1',+ title: 'legacy',+ status: 'running',+ started_at: now - 7200+ }++ render(<RunClock task={task} />)++ expect(screen.getByText(`${en.working} · 2h`)).toBeTruthy()+ })++ it('renders nothing when neither timestamp is present', () => {+ const { container } = render(<RunClock task={{ id: 't1', title: 'bare', status: 'running' }} />)++ expect(container.textContent).toBe('')+ })+})diff --git a/apps/desktop/src/plugins/kanban/types.ts b/apps/desktop/src/plugins/kanban/types.tsindex 4d6e1b5dd94..251c33d1c22 100644--- a/apps/desktop/src/plugins/kanban/types.ts+++ b/apps/desktop/src/plugins/kanban/types.ts@@ -21,6 +21,9 @@ export interface KanbanTask {warnings?: null | { count: number; highest_severity?: null | string }/** Worker liveness (present on running cards) — drives the arc + run clock. */started_at?: null | number+ /** Start of the CURRENT run row; null/absent when the task has no active+ * run (or the backend predates it) — the clock falls back to started_at. */+ current_run_started_at?: null | numberworker_pid?: null | numberlast_heartbeat_at?: null | number}diff --git a/apps/desktop/src/plugins/kanban/ui.tsx b/apps/desktop/src/plugins/kanban/ui.tsxindex 91622f9ebc5..82fa1cfa523 100644--- a/apps/desktop/src/plugins/kanban/ui.tsx+++ b/apps/desktop/src/plugins/kanban/ui.tsx@@ -143,7 +143,9 @@ export function arcState(task: KanbanTask, fallbackAssignee: string): ArcState |/** Ticking "working · 34s" line for running cards (elapsed since claim). */export function RunClock({ task }: { task: KanbanTask }) {const k = useKanban()- const elapsed = useTicking(task.started_at)+ // Current run's start; a retried task's started_at is its first-ever start,+ // so tick from the fresh run. Older backends omit the field — fall back.+ const elapsed = useTicking(task.current_run_started_at ?? task.started_at)if (!elapsed) {return nulldiff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.pyindex 326f1c4d172..8061801c2df 100644--- a/hermes_cli/kanban_db.py+++ b/hermes_cli/kanban_db.py@@ -4470,6 +4470,22 @@ def latest_summaries(conn: sqlite3.Connection, task_ids: Iterable[str]) -> dict[return {r["task_id"]: r["summary"] for r in rows}+def current_run_started_ats(conn: sqlite3.Connection, task_ids: Iterable[str]) -> dict[str, int]:+ """``{task_id: started_at of the run ``tasks.current_run_id`` points at}``+ in one query; tasks with no active run (NULL or dangling pointer) are omitted."""+ ids = list(task_ids)+ if not ids:+ return {}+ placeholders = ",".join("?" for _ in ids)+ rows = conn.execute(+ "SELECT t.id AS task_id, r.started_at AS started_at FROM tasks t "+ "JOIN task_runs r ON r.id = t.current_run_id "+ f"WHERE t.id IN ({placeholders})",+ ids,+ ).fetchall()+ return {r["task_id"]: r["started_at"] for r in rows}++# --- Split modules (imported at the tail: they import this module as ``_kb``) ---from hermes_cli.kanban_db_connect import ( # noqa: E402_INITIALIZED_PATHS,diff --git a/plugins/kanban/dashboard/plugin_api.py b/plugins/kanban/dashboard/plugin_api.pyindex d01836d8dc8..6995d49be81 100644--- a/plugins/kanban/dashboard/plugin_api.py+++ b/plugins/kanban/dashboard/plugin_api.py@@ -171,7 +171,8 @@ BOARD_COLUMNS: list[str] = ["triage", "todo", "scheduled", "ready", "running", "_CARD_SUMMARY_PREVIEW_CHARS = 200-def _task_dict(task: kanban_db.Task, *, latest_summary: Optional[str] = None) -> dict[str, Any]:+def _task_dict(task: kanban_db.Task, *, latest_summary: Optional[str] = None,+ current_run_started_at: Optional[int] = None) -> dict[str, Any]:d = asdict(task)# Derived age metrics so the UI can colour stale cards without client deltas.try:@@ -180,6 +181,9 @@ def _task_dict(task: kanban_db.Task, *, latest_summary: Optional[str] = None) ->d["age"] = {"created_age_seconds": None, "started_age_seconds": None, "time_to_complete_seconds": None}# Latest non-null run summary (workers hand off via ``task_runs.summary``, not ``tasks.result``).d["latest_summary"] = latest_summary+ # Start of the current task_runs row (``tasks.started_at`` is the FIRST-EVER+ # start; after a retry the run clock must tick from the fresh run).+ d["current_run_started_at"] = current_run_started_atreturn d@@ -309,9 +313,13 @@ def get_board(# One window-function query for latest summaries (avoids N+1); cards get a# truncated preview, the full text comes from /tasks/:id.summary_map = kanban_db.latest_summaries(conn, [t.id for t in tasks])+ # One query for the active run's start per card (avoids N+1); the run+ # clock ticks from this, not the task's first-ever start.+ run_start_map = kanban_db.current_run_started_ats(conn, [t.id for t in tasks])for t in tasks:full = summary_map.get(t.id)- d = _task_dict(t, latest_summary=(full[:_CARD_SUMMARY_PREVIEW_CHARS] if full else None))+ d = _task_dict(t, latest_summary=(full[:_CARD_SUMMARY_PREVIEW_CHARS] if full else None),+ current_run_started_at=run_start_map.get(t.id))d["link_counts"] = link_counts.get(t.id, {"parents": 0, "children": 0})d["comment_count"] = comment_counts.get(t.id, 0)d["progress"] = progress.get(t.id) # None when the task has no children@@ -369,7 +377,9 @@ def get_task(raise HTTPException(status_code=400, detail="run_state_type must be 'status' or 'outcome'")task = _require_task(conn, task_id)# Drawer returns the FULL summary (cards on /board carry a 200-char preview).- task_d = _task_dict(task, latest_summary=kanban_db.latest_summary(conn, task_id))+ task_d = _task_dict(+ task, latest_summary=kanban_db.latest_summary(conn, task_id),+ current_run_started_at=kanban_db.current_run_started_ats(conn, [task_id]).get(task_id))links = _links_for(conn, task_id)child_summaries = kanban_db.latest_summaries(conn, links["children"])children = filter(None, (kanban_db.get_task(conn, cid) for cid in links["children"]))@@ -416,7 +426,9 @@ def create_task(payload: CreateTaskBody, board: Optional[str] = Query(None)):# CreateTaskBody field names match create_task's keyword parameters.task_id = kanban_db.create_task(conn, created_by="dashboard", board=board, **payload.model_dump())task = kanban_db.get_task(conn, task_id)- body: dict[str, Any] = {"task": _task_dict(task) if task else None}+ body: dict[str, Any] = {"task": _task_dict(+ task, current_run_started_at=kanban_db.current_run_started_ats(conn, [task_id]).get(task_id)+ ) if task else None}# Dispatcher-presence warning so the UI can banner a ready+assigned task that would# otherwise sit idle (no gateway / dispatch_in_gateway=false); triage/todo are expected# to wait, unassigned tasks can't dispatch anyway. Probe the request's active home: the@@ -687,7 +699,9 @@ def update_task(task_id: str, payload: UpdateTaskBody, board: Optional[str] = Quif payload.title is not None or payload.body is not None:_patch_title_body(conn, task_id, payload, board)updated = kanban_db.get_task(conn, task_id)- return {"task": _task_dict(updated) if updated else None}+ return {"task": _task_dict(+ updated, current_run_started_at=kanban_db.current_run_started_ats(conn, [task_id]).get(task_id)+ ) if updated else None}@router.delete("/tasks/{task_id}")diff --git a/tests/plugins/test_kanban_dashboard_plugin.py b/tests/plugins/test_kanban_dashboard_plugin.pyindex 02fdba063f4..221772d38b2 100644--- a/tests/plugins/test_kanban_dashboard_plugin.py+++ b/tests/plugins/test_kanban_dashboard_plugin.py@@ -1065,6 +1065,51 @@ def test_touch_card_tap_opens_instead_of_dragging():assert result.returncode == 0, f"stdout={result.stdout!r} stderr={result.stderr!r}"assert "PASS" in result.stdout++# Run clock: current run start, not first-ever start# ----------------------------------------------------------------------------# Diagnostic severity colours follow the dashboard theme-# ---------------------------------------------------------------------------+++def test_board_card_exposes_current_run_start(client):+ """#99819: after a review timeout + retry, the card must expose the fresh+ run's start (not the task's first-ever start) so the run clock ticks from+ the current attempt."""+ now = int(time.time())+ first_start = now - 7200 # task first started 2h ago+ retry_start = now - 90 # retry run started 90s ago+ conn = kbc.connect()+ try:+ t = kb.create_task(conn, title="retried", assignee="x")+ lock = "lock-runclock"+ future = now + 3600+ conn.execute(+ "UPDATE tasks SET status='running', started_at=?, claim_lock=?, "+ "claim_expires=?, worker_pid=? WHERE id=?",+ (first_start, lock, future, 99999, t),+ )+ conn.execute(+ "INSERT INTO task_runs (task_id, status, claim_lock, claim_expires, "+ "worker_pid, started_at) VALUES (?, 'running', ?, ?, ?, ?)",+ (t, lock, future, 99999, retry_start),+ )+ run_id = conn.execute("SELECT last_insert_rowid()").fetchone()[0]+ conn.execute("UPDATE tasks SET current_run_id=? WHERE id=?", (run_id, t))+ # A sibling task with no run at all: key present, null.+ u = kb.create_task(conn, title="unclaimed", assignee="x")+ conn.commit()+ finally:+ conn.close()++ r = client.get("/api/plugins/kanban/board")+ assert r.status_code == 200, r.text+ columns = {c["name"]: c for c in r.json()["columns"]}+ card = next(c for c in columns["running"]["tasks"] if c["id"] == t)+ assert card["started_at"] == first_start+ # Red on base: this key did not exist at all.+ assert card["current_run_started_at"] == retry_start+ todo = next(c for c in columns["ready"]["tasks"] if c["id"] == u)+ assert todo["current_run_started_at"] is None++ # The detail endpoint carries the same contract.+ detail = client.get(f"/api/plugins/kanban/tasks/{t}").json()["task"]+ assert detail["current_run_started_at"] == retry_start