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): enrich task/watch detail (session, agent, local time, next run) (#431)

Call White83002f7eca1b
diff --git a/storage/background.py b/storage/background.py
index 33da5431c..63713ec46 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -5,13 +5,16 @@ import logging
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Optional
+from zoneinfo import ZoneInfo
+from apscheduler.triggers.cron import CronTrigger
+from apscheduler.triggers.date import DateTrigger
from sqlalchemy import insert, or_, select, update
from config import paths
from storage.db import SqliteInvalidationProbe, create_sqlite_engine
from storage.migrations import background_tables_ready, initialize_background_tables
-from storage.models import agent_runs, run_definitions
+from storage.models import agent_runs, agent_sessions, run_definitions, scopes
from storage.pagination import PageRequest, PageResult, page_result_from_limit_plus_one
logger = logging.getLogger(__name__)
@@ -34,6 +37,46 @@ def _utc_now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
+def compute_next_run_at(
+ *,
+ enabled: bool,
+ schedule_type: Optional[str],
+ cron: Optional[str],
+ run_at: Optional[str],
+ timezone_name: Optional[str],
+) -> Optional[str]:
+ """Next fire time (tz-aware ISO) for a scheduled task, or None.
+
+ Shared by the harness API payload and the CLI so the two never drift. A
+ disabled task, an unparseable schedule, or an ``at`` task whose time has
+ already passed all yield ``None``.
+ """
+ if not enabled:
+ return None
+ try:
+ tz = ZoneInfo(timezone_name or "UTC")
+ now = datetime.now(tz)
+ if schedule_type == "cron":
+ if not cron:
+ return None
+ trigger = CronTrigger.from_crontab(cron, timezone=tz)
+ 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)
+ if instant <= now:
+ # A one-shot whose time has already passed has no next run.
+ return None
+ trigger = DateTrigger(run_date=instant)
+ else:
+ return None
+ next_fire = trigger.get_next_fire_time(None, now)
+ return next_fire.isoformat() if next_fire else None
+ except Exception:
+ return None
+
+
RUN_STATUS_ALIASES: dict[str, str] = {
"pending": "queued",
"queued": "queued",
@@ -88,13 +131,15 @@ class SQLiteBackgroundTaskStore:
def list_scheduled_tasks(self) -> list[dict[str, Any]]:
with self.engine.connect() as conn:
- rows = 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._scheduled_task_from_row(row) for row in rows]
+ 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]
def get_scheduled_task(self, definition_id: str) -> Optional[dict[str, Any]]:
with self.engine.connect() as conn:
@@ -105,7 +150,7 @@ class SQLiteBackgroundTaskStore:
.where(run_definitions.c.deleted_at.is_(None))
.limit(1)
).mappings().first()
- return self._scheduled_task_from_row(row) if row else None
+ return self._enrich_task(self._scheduled_task_from_row(row), conn) if row else None
def upsert_scheduled_task(self, payload: dict[str, Any]) -> None:
values = self._scheduled_task_values(payload)
@@ -149,13 +194,15 @@ class SQLiteBackgroundTaskStore:
def list_watches(self) -> list[dict[str, Any]]:
with self.engine.connect() as conn:
- rows = 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._watch_from_row(row) for row in rows]
+ 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]
def get_watch(self, watch_id: str) -> Optional[dict[str, Any]]:
with self.engine.connect() as conn:
@@ -166,7 +213,7 @@ class SQLiteBackgroundTaskStore:
.where(run_definitions.c.deleted_at.is_(None))
.limit(1)
).mappings().first()
- return self._watch_from_row(row) if row else None
+ return self._enrich_watch(self._watch_from_row(row), conn) if row else None
def upsert_watch(self, payload: dict[str, Any]) -> None:
values = self._watch_values(payload)
@@ -711,6 +758,120 @@ 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")
+ )
+ )
+ 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"),
+ )
+ 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")
+ )
+ )
+ return watch
+
+ @staticmethod
+ def _session_summary(
+ conn: Any,
+ session_id: Optional[str],
+ session_key: Optional[str],
+ deliver_key: Optional[str] = None,
+ ) -> dict[str, Any]:
+ """Resolve a task/watch's bound session into UI-facing display fields.
+
+ A workbench binding (avibe ``project`` scope) carries a concrete
+ ``session_id`` and a human ``title`` and is linkable to its chat. A
+ legacy IM binding lives in ``session_key``. A ``create_per_run``
+ definition has neither — it mints a fresh session each run and stores
+ only its target scope in ``deliver_key`` — so that is used as a final
+ fallback for the platform + channel label. Key-based targets are never
+ linkable (no concrete session to open). Best-effort: never raises into
+ the harness list.
+ """
+ summary: dict[str, Any] = {
+ "session_title": None,
+ "session_platform": None,
+ "session_scope_kind": None,
+ "session_label": None,
+ "session_is_workbench": False,
+ }
+ try:
+ if session_id:
+ row = conn.execute(
+ select(
+ agent_sessions.c.title,
+ scopes.c.platform,
+ scopes.c.scope_type,
+ scopes.c.native_id,
+ scopes.c.display_name,
+ )
+ .select_from(
+ agent_sessions.join(scopes, scopes.c.id == agent_sessions.c.scope_id, isouter=True)
+ )
+ .where(agent_sessions.c.id == session_id)
+ .limit(1)
+ ).mappings().first()
+ if row is not None:
+ platform = (row["platform"] or "").strip()
+ scope_type = (row["scope_type"] or "").strip()
+ is_workbench = platform == "avibe" or scope_type == "project"
+ summary["session_platform"] = platform or None
+ summary["session_scope_kind"] = scope_type or None
+ summary["session_is_workbench"] = is_workbench
+ summary["session_title"] = row["title"]
+ summary["session_label"] = (
+ row["title"] if is_workbench else (row["display_name"] or row["native_id"])
+ )
+ return summary
+ for key in (session_key, deliver_key):
+ resolved = SQLiteBackgroundTaskStore._summary_from_session_key(conn, key)
+ if resolved is not None:
+ return resolved
+ except Exception:
+ logger.debug("harness session summary resolution failed", exc_info=True)
+ return summary
+
+ @staticmethod
+ def _summary_from_session_key(conn: Any, key: Optional[str]) -> Optional[dict[str, Any]]:
+ """Parse a "<platform>::<channel|user>::<native_id>[::thread::<id>]" key
+ into a non-linkable session summary, resolving the channel display name.
+ Shared by the legacy ``session_key`` and the ``create_per_run``
+ ``deliver_key`` paths. Returns None when ``key`` is empty/malformed."""
+ if not key:
+ return None
+ parts = key.split("::")
+ if len(parts) < 3 or not parts[0] or not parts[2]:
+ return None
+ platform, scope_type, native_id = parts[0], parts[1], parts[2]
+ label = native_id
+ drow = conn.execute(
+ select(scopes.c.display_name)
+ .where(scopes.c.platform == platform)
+ .where(scopes.c.scope_type == scope_type)
+ .where(scopes.c.native_id == native_id)
+ .limit(1)
+ ).mappings().first()
+ if drow is not None and drow["display_name"]:
+ label = drow["display_name"]
+ return {
+ "session_title": None,
+ "session_platform": platform,
+ "session_scope_kind": scope_type,
+ "session_label": label,
+ "session_is_workbench": False,
+ }
+
@staticmethod
def _message_payload_json(payload: dict[str, Any]) -> Optional[str]:
return SQLiteBackgroundTaskStore._payload_json(payload, "message_payload", "message_payload_json")
diff --git a/tests/test_harness_payload_enrichment.py b/tests/test_harness_payload_enrichment.py
new file mode 100644
index 000000000..2d06f16ac
--- /dev/null
+++ b/tests/test_harness_payload_enrichment.py
@@ -0,0 +1,233 @@
+"""Harness API payload enrichment: resolved session summary + next run.
+
+The web Harness cards show a bound session by title (workbench → linkable to
+chat) or by platform + channel name (IM → not linkable), plus a cron task's
+next fire time. These are derived server-side in the background store so every
+client inherits them. See ``storage/background.py``.
+"""
+
+from __future__ import annotations
+
+import sys
+from datetime import datetime, timezone
+from pathlib import Path
+
+from sqlalchemy import update
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from storage import workbench_sessions_service
+from storage.background import SQLiteBackgroundTaskStore, compute_next_run_at
+from storage.db import create_sqlite_engine
+from storage.models import agent_sessions
+from storage.sessions_service import SQLiteSessionsService
+from storage.settings_service import upsert_scope
+
+NOW = "2026-05-31T00:00:00Z"
+
+
+def _build_schema(db_path: Path) -> None:
+ # SQLiteSessionsService builds + migrates the core schema (scopes,
+ # agent_sessions, ...); the background store later adds run_definitions.
+ SQLiteSessionsService(db_path).close()
+
+
+def test_compute_next_run_at_handles_cron_disabled_and_past() -> None:
+ nxt = compute_next_run_at(
+ enabled=True, schedule_type="cron", cron="0 9 * * *", run_at=None, timezone_name="Asia/Shanghai"
+ )
+ assert nxt is not None
+ parsed = datetime.fromisoformat(nxt)
+ assert parsed.tzinfo is not None # tz-aware so the client can localize it
+ assert parsed > datetime.now(timezone.utc)
+
+ # Disabled tasks and already-fired one-shots have no next run.
+ assert compute_next_run_at(
+ enabled=False, schedule_type="cron", cron="0 9 * * *", run_at=None, timezone_name="UTC"
+ ) is None
+ assert compute_next_run_at(
+ enabled=True, schedule_type="at", cron=None, run_at="2020-01-01T00:00:00+00:00", timezone_name="UTC"
+ ) is None
+
+
+def test_scheduled_task_payload_resolves_workbench_session(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ _build_schema(db_path)
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn, platform="avibe", scope_type="project", native_id="proj_test", now=NOW
+ )
+ session = workbench_sessions_service.create_session(
+ conn, scope_id=scope_id, agent_backend="claude", agent_name="default"
+ )
+ conn.execute(
+ update(agent_sessions).where(agent_sessions.c.id == session["id"]).values(title="重构鉴权模块")
+ )
+ finally:
+ engine.dispose()
+
+ store = SQLiteBackgroundTaskStore(db_path)
+ try:
+ store.upsert_scheduled_task(
+ {
+ "id": "task_wb",
+ "name": "每日构建巡检",
+ "session_id": session["id"],
+ "prompt": "hello",
+ "schedule_type": "cron",
+ "cron": "0 9 * * *",
+ "timezone": "Asia/Shanghai",
+ "enabled": True,
+ "created_at": NOW,
+ "updated_at": NOW,
+ }
+ )
+ task = next(t for t in store.list_scheduled_tasks() if t["id"] == "task_wb")
+ finally:
+ store.close()
+
+ assert task["session_is_workbench"] is True
+ assert task["session_platform"] == "avibe"
+ assert task["session_scope_kind"] == "project"
+ assert task["session_title"] == "重构鉴权模块"
+ assert task["session_label"] == "重构鉴权模块"
+ assert task["next_run_at"] is not None
+ # get_scheduled_task enriches identically to the list path.
+ store2 = SQLiteBackgroundTaskStore(db_path)
+ try:
+ assert store2.get_scheduled_task("task_wb")["session_title"] == "重构鉴权模块"
+ finally:
+ store2.close()
+
+
+def test_scheduled_task_payload_resolves_im_channel_name(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ _build_schema(db_path)
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ upsert_scope(
+ conn,
+ platform="slack",
+ scope_type="channel",
+ native_id="C0123",
+ now=NOW,
+ display_name="#dev-ops",
+ )
+ finally:
+ engine.dispose()
+
+ store = SQLiteBackgroundTaskStore(db_path)
+ try:
+ store.upsert_scheduled_task(
+ {
+ "id": "task_im",
+ "name": "周报推送",
+ "session_key": "slack::channel::C0123",
+ "prompt": "hello",
+ "schedule_type": "cron",
+ "cron": "0 18 * * 5",
+ "timezone": "UTC",
+ "enabled": True,
+ "created_at": NOW,
+ "updated_at": NOW,
+ }
+ )
+ task = next(t for t in store.list_scheduled_tasks() if t["id"] == "task_im")
+ finally:
+ store.close()
+
+ assert task["session_is_workbench"] is False
+ assert task["session_platform"] == "slack"
+ assert task["session_scope_kind"] == "channel"
+ assert task["session_label"] == "#dev-ops" # channel display name, not the raw id
+
+
+def test_watch_payload_resolves_im_channel_name(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ _build_schema(db_path)
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ upsert_scope(
+ conn,
+ platform="slack",
+ scope_type="channel",
+ native_id="C0999",
+ now=NOW,
+ display_name="#ops",
+ )
+ finally:
+ engine.dispose()
+
+ store = SQLiteBackgroundTaskStore(db_path)
+ try:
+ store.upsert_watch(
+ {
+ "id": "watch_im",
+ "name": "部署监控",
+ "session_key": "slack::channel::C0999",
+ "shell_command": "tail -f /var/log/x.log",
+ "mode": "forever",
+ "enabled": True,
+ "created_at": NOW,
+ "updated_at": NOW,
+ }
+ )
+ watch = next(w for w in store.list_watches() if w["id"] == "watch_im")
+ finally:
+ store.close()
+
+ assert watch["session_is_workbench"] is False
+ assert watch["session_platform"] == "slack"
+ assert watch["session_label"] == "#ops"
+
+
+def test_scheduled_task_payload_resolves_deliver_key_for_create_per_run(tmp_path: Path) -> None:
+ # A create_per_run task mints a new session each run, so session_id /
+ # session_key are empty and the target scope lives in deliver_key. The card
+ # should still show the platform + channel from that delivery target.
+ db_path = tmp_path / "vibe.sqlite"
+ _build_schema(db_path)
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ upsert_scope(
+ conn,
+ platform="slack",
+ scope_type="channel",
+ native_id="Cdeploy",
+ now=NOW,
+ display_name="#deploys",
+ )
+ finally:
+ engine.dispose()
+
+ store = SQLiteBackgroundTaskStore(db_path)
+ try:
+ store.upsert_scheduled_task(
+ {
+ "id": "task_per_run",
+ "name": "夜间巡检",
+ "session_policy": "create_per_run",
+ "deliver_key": "slack::channel::Cdeploy",
+ "prompt": "hello",
+ "schedule_type": "cron",
+ "cron": "0 2 * * *",
+ "timezone": "UTC",
+ "enabled": True,
+ "created_at": NOW,
+ "updated_at": NOW,
+ }
+ )
+ task = next(t for t in store.list_scheduled_tasks() if t["id"] == "task_per_run")
+ finally:
+ store.close()
+
+ assert task["session_id"] is None
+ assert task["session_key"] == ""
+ assert task["session_is_workbench"] is False
+ assert task["session_platform"] == "slack"
+ assert task["session_label"] == "#deploys"
diff --git a/ui/src/components/workbench/HarnessPage.tsx b/ui/src/components/workbench/HarnessPage.tsx
index 46d9325b9..dde264923 100644
--- a/ui/src/components/workbench/HarnessPage.tsx
+++ b/ui/src/components/workbench/HarnessPage.tsx
@@ -19,17 +19,25 @@ import {
Clock,
PauseCircle,
Search,
+ Bot,
+ MessageSquare,
+ ArrowUpRight,
} from 'lucide-react';
import clsx from 'clsx';
+import { Link } from 'react-router-dom';
import { useApi } from '../../context/ApiContext';
import type {
HarnessRun,
HarnessRunStatus,
+ HarnessSessionSummary,
HarnessTask,
HarnessWatch,
+ VibeAgentBrief,
} from '../../context/ApiContext';
import { formatRelativeTime } from '../../lib/relativeTime';
+import { formatLocalDateTime } from '../../lib/datetime';
+import { PlatformIcon } from '../visual/PlatformIcon';
import { CreateViaChatDialog } from './CreateViaChatDialog';
import type { CreateViaChatKind } from './CreateViaChatDialog';
import { CapabilityTabs } from './CapabilityTabs';
@@ -127,6 +135,25 @@ export const HarnessPage: React.FC = () => {
refresh();
}, [refresh]);
+ // Resolve agent_name → backend/model/effort for the detail panels: the
+ // task/watch payload stores only the name. Fetched once on mount.
+ const [agentsByName, setAgentsByName] = useState<Record<string, VibeAgentBrief>>({});
+ useEffect(() => {
+ let cancelled = false;
+ api
+ .listVibeAgents({ includeDisabled: true })
+ .then((res) => {
+ if (cancelled) return;
+ const map: Record<string, VibeAgentBrief> = {};
+ for (const a of res.agents) map[a.name] = a;
+ setAgentsByName(map);
+ })
+ .catch(() => {});
+ return () => {
+ cancelled = true;
+ };
+ }, [api]);
+
const markPending = useCallback((id: string, value: boolean) => {
setPendingMutation((prev) => {
const next = { ...prev };
@@ -143,7 +170,13 @@ export const HarnessPage: React.FC = () => {
const next = !task.enabled;
setTasks((prev) => prev.map((t) => (t.id === task.id ? { ...t, enabled: next } : t)));
try {
- await api.setHarnessTaskEnabled(task.id, next);
+ const result = await api.setHarnessTaskEnabled(task.id, next);
+ // Reconcile with the server's recomputed fields — next_run_at depends on
+ // `enabled`, so the optimistic flip alone would leave it stale.
+ if (result.task) {
+ const updated = result.task;
+ setTasks((prev) => prev.map((t) => (t.id === task.id ? updated : t)));
+ }
} catch (err: any) {
setError(err?.message ?? String(err));
setTasks((prev) => prev.map((t) => (t.id === task.id ? { ...t, enabled: task.enabled } : t)));
@@ -180,7 +213,12 @@ export const HarnessPage: React.FC = () => {
const next = !watch.enabled;
setWatches((prev) => prev.map((w) => (w.id === watch.id ? { ...w, enabled: next } : w)));
try {
- await api.setHarnessWatchEnabled(watch.id, next);
+ const result = await api.setHarnessWatchEnabled(watch.id, next);
+ // Reconcile with the server payload (refreshed runtime + session summary).
+ if (result.watch) {
+ const updated = result.watch;
+ setWatches((prev) => prev.map((w) => (w.id === watch.id ? updated : w)));
+ }
} catch (err: any) {
setError(err?.message ?? String(err));
setWatches((prev) => prev.map((w) => (w.id === watch.id ? { ...w, enabled: watch.enabled } : w)));
@@ -476,12 +514,14 @@ export const HarnessPage: React.FC = () => {
{selectedTask ? (
<TaskDetail
task={selectedTask}
+ agent={agentsByName[selectedTask.agent_name ?? '']}
onToggleEnabled={() => toggleTaskEnabled(selectedTask)}
pending={!!pendingMutation[selectedTask.id]}
/>
) : selectedWatch ? (
<WatchDetail
watch={selectedWatch}
+ agent={agentsByName[selectedWatch.agent_name ?? '']}
onToggleEnabled={() => toggleWatchEnabled(selectedWatch)}
pending={!!pendingMutation[selectedWatch.id]}
/>
@@ -656,11 +696,12 @@ const RowActions: React.FC<RowActionsProps> = ({ enabled, pending, onToggle, onD
interface TaskDetailProps {
task: HarnessTask;
+ agent?: VibeAgentBrief;
onToggleEnabled: () => void;
pending: boolean;
}
-const TaskDetail: React.FC<TaskDetailProps> = ({ task, onToggleEnabled, pending }) => {
+const TaskDetail: React.FC<TaskDetailProps> = ({ task, agent, onToggleEnabled, pending }) => {
const { t } = useTranslation();
const title = displayTitle(task.name, task.id);
return (
@@ -684,9 +725,25 @@ const TaskDetail: React.FC<TaskDetailProps> = ({ task, onToggleEnabled, pending
</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>
+ </DetailField>
+ )}
<DetailField label={t('harness.detail.agent')}>
- <span className="text-[12px] text-foreground">{task.agent_name || '—'}</span>
+ <DetailAgent agentName={task.agent_name} agent={agent} />
+ </DetailField>
+ <DetailField label={t('harness.detail.session')}>
+ <DetailSession summary={task} sessionId={task.session_id} />
</DetailField>
+ <div className="grid grid-cols-2 gap-4">
+ <DetailField label={t('harness.detail.sessionPolicy')}>
+ <span className="text-[12px] text-foreground">{sessionPolicyLabel(task.session_policy, t)}</span>
+ </DetailField>
+ <DetailField label={t('harness.detail.delivery')}>
+ <span className="text-[12px] text-foreground">{deliveryLabel(task.post_to, t)}</span>
+ </DetailField>
+ </div>
<DetailField label={t('harness.detail.message')}>
<pre className="max-h-44 overflow-auto whitespace-pre-wrap rounded-md border border-border bg-surface-3 p-2 font-mono text-[11px] text-foreground">
{task.message || task.prompt || '—'}
@@ -694,7 +751,7 @@ const TaskDetail: React.FC<TaskDetailProps> = ({ task, onToggleEnabled, pending
</DetailField>
{task.last_run_at && (
<DetailField label={t('harness.detail.lastRun')}>
- <span className="font-mono text-[11px] text-muted">{task.last_run_at}</span>
+ <span className="font-mono text-[11px] text-muted">{formatLocalDateTime(task.last_run_at)}</span>
{task.last_error && (
<div className="mt-1 rounded-md border border-destructive/40 bg-destructive/[0.06] px-2 py-1 text-[11px] text-destructive">
{task.last_error}
@@ -799,11 +856,12 @@ const WatchesList: React.FC<WatchesListProps> = ({
interface WatchDetailProps {
watch: HarnessWatch;
+ agent?: VibeAgentBrief;
onToggleEnabled: () => void;
pending: boolean;
}
-const WatchDetail: React.FC<WatchDetailProps> = ({ watch, onToggleEnabled, pending }) => {
+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);
@@ -828,8 +886,19 @@ const WatchDetail: React.FC<WatchDetailProps> = ({ watch, onToggleEnabled, pendi
</pre>
</DetailField>
<DetailField label={t('harness.detail.agent')}>
- <span className="text-[12px] text-foreground">{watch.agent_name || '—'}</span>
+ <DetailAgent agentName={watch.agent_name} agent={agent} />
</DetailField>
+ <DetailField label={t('harness.detail.session')}>
+ <DetailSession summary={watch} sessionId={watch.session_id} />
+ </DetailField>
+ <div className="grid grid-cols-2 gap-4">
+ <DetailField label={t('harness.detail.sessionPolicy')}>
+ <span className="text-[12px] text-foreground">{sessionPolicyLabel(watch.session_policy, t)}</span>
+ </DetailField>
+ <DetailField label={t('harness.detail.delivery')}>
+ <span className="text-[12px] text-foreground">{deliveryLabel(watch.post_to, t)}</span>
+ </DetailField>
+ </div>
<DetailField label={t('harness.detail.cwd')}>
<code className="font-mono text-[11px] text-muted">{watch.cwd || '—'}</code>
</DetailField>
@@ -844,7 +913,7 @@ const WatchDetail: React.FC<WatchDetailProps> = ({ watch, onToggleEnabled, pendi
{watch.runtime.running && watch.runtime.pid != null && (
<DetailField label={t('harness.detail.runtime')}>
<span className="font-mono text-[11px] text-muted">
- pid {watch.runtime.pid} · started {watch.runtime.started_at}
+ pid {watch.runtime.pid} · {formatLocalDateTime(watch.runtime.started_at)}
</span>
</DetailField>
)}
@@ -1019,9 +1088,9 @@ const RunDetail: React.FC<RunDetailProps> = ({ run }) => {
)}
<DetailField label={t('harness.detail.timing')}>
<div className="flex flex-col gap-0.5 font-mono text-[10px] text-muted">
- <span>created {run.created_at ?? '—'}</span>
- {run.started_at && <span>started {run.started_at}</span>}
- {run.completed_at && <span>completed {run.completed_at}</span>}
+ <span>created {formatLocalDateTime(run.created_at)}</span>
+ {run.started_at && <span>started {formatLocalDateTime(run.started_at)}</span>}
+ {run.completed_at && <span>completed {formatLocalDateTime(run.completed_at)}</span>}
{run.exit_code != null && <span>exit_code {run.exit_code}</span>}
{run.pid != null && <span>pid {run.pid}</span>}
</div>
@@ -1074,6 +1143,93 @@ const StatusPill: React.FC<StatusPillProps> = ({ enabled, runtimeRunning }) => {
);
};
+function sessionPolicyLabel(policy: string | null | undefined, t: (k: string) => string): string {
+ if (policy === 'create_per_run') return t('harness.sessionPolicy.createPerRun');
+ if (policy === 'create_once') return t('harness.sessionPolicy.createOnce');
+ return t('harness.sessionPolicy.existing');
+}
+
+function deliveryLabel(postTo: string | null | undefined, t: (k: string) => string): string {
+ if (postTo === 'channel') return t('harness.delivery.channel');
+ if (postTo === 'thread') return t('harness.delivery.thread');
+ return t('harness.delivery.session');
+}
+
+// Agent executor: name + resolved backend·model·effort, with a jump to the
+// Agents page. agent_name can be null (the definition inherits the scope /
+// global default); model/effort can be null (backend default).
+const DetailAgent: React.FC<{ agentName: string | null; agent?: VibeAgentBrief }> = ({ agentName, agent }) => {
+ const { t } = useTranslation();
+ if (!agentName) {
+ return <span className="text-[12px] text-muted">{t('harness.detail.agentInherit')}</span>;
+ }
+ const meta = agent
+ ? [
+ agent.backend,
+ agent.model,
+ agent.reasoning_effort ? t('harness.detail.effort', { value: agent.reasoning_effort }) : null,
+ ]
+ .filter(Boolean)
+ .join(' · ')
+ : '';
+ return (
+ <div className="flex min-w-0 items-center gap-2">
+ <Bot className="size-3.5 shrink-0 text-violet" />
+ <span className="shrink-0 text-[12px] font-medium text-foreground">{agentName}</span>
+ {meta && <span className="min-w-0 flex-1 truncate font-mono text-[10px] text-muted">{meta}</span>}
+ <Link
+ to="/agents"
+ className="ml-auto inline-flex shrink-0 items-center gap-0.5 text-[11px] font-medium text-violet hover:underline"
+ >
+ {t('harness.detail.openInAgents')}
+ <ArrowUpRight className="size-3" />
+ </Link>
+ </div>
+ );
+};
+
+// Bound session. Workbench sessions show their title and link to the chat; IM
+// sessions show platform + channel and are intentionally not linkable.
+const DetailSession: React.FC<{ summary: HarnessSessionSummary; sessionId: string | null }> = ({
+ summary,
+ sessionId,
+}) => {
+ const { t } = useTranslation();
+ if (!summary.session_is_workbench && !summary.session_platform && !sessionId) {
+ return <span className="text-[12px] text-muted">{t('harness.detail.sessionNone')}</span>;
+ }
+ if (summary.session_is_workbench) {
+ const label = summary.session_title || sessionId || '—';
+ const body = (
+ <>
+ <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" />}
+ </>
+ );
+ 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>
+ );
+ }
+ 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>
+ );
+};
+
interface DetailFieldProps {
label: string;
children: React.ReactNode;
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 4d746ef9c..639290ca0 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -497,7 +497,18 @@ export type InboxFeedResult = {
// Harness (scheduled tasks / watches / runs)
// =============================================================================
-export type HarnessTask = {
+// 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.
+export type HarnessSessionSummary = {
+ session_title: string | null;
+ session_platform: string | null;
+ session_scope_kind: string | null;
+ session_label: string | null;
+ session_is_workbench: boolean;
+};
+
+export type HarnessTask = HarnessSessionSummary & {
id: string;
name: string | null;
agent_name: string | null;
@@ -519,6 +530,7 @@ export type HarnessTask = {
last_run_at: string | null;
last_run_id: string | null;
last_error: string | null;
+ next_run_at: string | null;
};
export type HarnessWatchRuntime = {
@@ -528,7 +540,7 @@ export type HarnessWatchRuntime = {
updated_at?: string | null;
};
-export type HarnessWatch = {
+export type HarnessWatch = HarnessSessionSummary & {
id: string;
name: string | null;
agent_name: string | null;
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index e3306ac30..cfc91305b 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1615,7 +1615,25 @@
"definition": "Definition",
"result": "Result",
"error": "Error",
- "timing": "Timing"
+ "timing": "Timing",
+ "nextRun": "Next run",
+ "session": "Session",
+ "sessionPolicy": "Session mode",
+ "delivery": "Delivery",
+ "openInAgents": "Open in Agents",
+ "agentInherit": "Inherits default agent",
+ "sessionNone": "No bound session",
+ "effort": "effort {{value}}"
+ },
+ "sessionPolicy": {
+ "createPerRun": "New session each run",
+ "createOnce": "Create once, then reuse",
+ "existing": "Reuse the same session"
+ },
+ "delivery": {
+ "channel": "Channel",
+ "thread": "Thread",
+ "session": "Default · session location"
},
"row": {
"enable": "Enable",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index fbe278c3a..e6d20c720 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1614,7 +1614,25 @@
"definition": "定义",
"result": "结果",
"error": "错误",
- "timing": "时间线"
+ "timing": "时间线",
+ "nextRun": "下次运行",
+ "session": "关联会话",
+ "sessionPolicy": "会话模式",
+ "delivery": "投递目标",
+ "openInAgents": "在 Agents 打开",
+ "agentInherit": "继承默认 Agent",
+ "sessionNone": "未绑定会话",
+ "effort": "推理 {{value}}"
+ },
+ "sessionPolicy": {
+ "createPerRun": "每次运行新建会话",
+ "createOnce": "建一次后复用",
+ "existing": "复用同一会话"
+ },
+ "delivery": {
+ "channel": "频道",
+ "thread": "线程",
+ "session": "默认 · 会话所在位置"
},
"row": {
"enable": "启用",
diff --git a/ui/src/lib/datetime.ts b/ui/src/lib/datetime.ts
new file mode 100644
index 000000000..77f56e4a2
--- /dev/null
+++ b/ui/src/lib/datetime.ts
@@ -0,0 +1,26 @@
+// Format an ISO timestamp in the viewer's local timezone as
+// "YYYY-MM-DD HH:MM:SS GMT+8" — no "T" separator, no "+00:00" offset chain,
+// just a single tz label. Harness stores times in UTC/ISO; the cards localize
+// them so the user reads schedules on their own clock. Returns "—" for empty
+// input and the raw string for unparseable input (never throws).
+export function formatLocalDateTime(iso: string | null | undefined): string {
+ if (!iso) return '—';
+ const d = new Date(iso);
+ if (Number.isNaN(d.getTime())) return iso;
+ const p = (n: number) => String(n).padStart(2, '0');
+ const date = `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
+ const time = `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
+ return `${date} ${time} ${localTzLabel(d)}`;
+}
+
+// "GMT+8" / "GMT+5:30" / "GMT-7" / "GMT" — one human tz label for the date's
+// local offset. Derived from the Date itself, so it stays DST-correct.
+export function localTzLabel(d: Date = new Date()): string {
+ const offsetMin = -d.getTimezoneOffset(); // minutes east of UTC
+ if (offsetMin === 0) return 'GMT';
+ const sign = offsetMin > 0 ? '+' : '-';
+ const abs = Math.abs(offsetMin);
+ const h = Math.floor(abs / 60);
+ const m = abs % 60;
+ return `GMT${sign}${h}${m ? ':' + String(m).padStart(2, '0') : ''}`;
+}
diff --git a/vibe/cli.py b/vibe/cli.py
index af34372c3..cca98b71a 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -21,7 +21,6 @@ from uuid import uuid4
from zoneinfo import ZoneInfo
from apscheduler.triggers.cron import CronTrigger
-from apscheduler.triggers.date import DateTrigger
from tzlocal import get_localzone_name
from sqlalchemy import select
@@ -59,7 +58,7 @@ from vibe.upgrade import (
get_safe_cwd,
)
from storage.db import create_sqlite_engine
-from storage.background import normalize_run_status
+from storage.background import compute_next_run_at, normalize_run_status
from storage.models import scope_settings
from storage.pagination import DEFAULT_PAGE_LIMIT, PageRequest, make_page_request, pagination_payload
from storage.read_only_query import ReadOnlyQueryError, run_read_only_query
@@ -1033,30 +1032,13 @@ def _task_last_status(task) -> str:
def _task_next_run_at(task) -> Optional[str]:
- if not task.enabled:
- return None
- try:
- timezone = ZoneInfo(task.timezone)
- now = datetime.now(timezone)
- if task.schedule_type == "cron":
- if not task.cron:
- return None
- trigger = CronTrigger.from_crontab(task.cron, timezone=timezone)
- elif task.schedule_type == "at":
- if not task.run_at:
- return None
- run_at = datetime.fromisoformat(task.run_at)
- if run_at.tzinfo is None:
- run_at = run_at.replace(tzinfo=timezone)
- else:
- run_at = run_at.astimezone(timezone)
- trigger = DateTrigger(run_date=run_at)
- else:
- return None
- next_fire = trigger.get_next_fire_time(None, now)
- return next_fire.isoformat() if next_fire else None
- except Exception:
- return None
+ return compute_next_run_at(
+ enabled=task.enabled,
+ schedule_type=task.schedule_type,
+ cron=task.cron,
+ run_at=task.run_at,
+ timezone_name=task.timezone,
+ )
def _task_schedule_summary(task) -> str: