initial: hermes-dashboard snapshot (post overview + git integration)

This commit is contained in:
hermes-dashboard
2026-08-17 19:51:51 +08:00
commit 1e5e30ffcb
22 changed files with 2333 additions and 0 deletions

1
services/__init__.py Normal file
View File

@@ -0,0 +1 @@
"""Services package."""

29
services/gitea.py Normal file
View File

@@ -0,0 +1,29 @@
"""Gitea API service — read-only queries against local Gitea instance."""
import logging
from typing import Any
import requests
import config
from extensions import get_gitea_session
logger = logging.getLogger(__name__)
def get_repos() -> dict[str, Any]:
"""Fetch all repos from Gitea. Returns {repos: [...], available: bool}."""
try:
session = get_gitea_session()
resp = session.get(
f"{config.GITEA_API_URL}/repos/search",
params={"limit": 50, "uid": 0},
timeout=3,
)
resp.raise_for_status()
data = resp.json()
repos = data.get("data", [])
return {"repos": repos, "available": True}
except (requests.RequestException, ValueError, KeyError) as exc:
logger.debug("Gitea repos fetch failed: %s", exc)
return {"repos": [], "available": False, "error": str(exc)}

139
services/kanban.py Normal file
View File

@@ -0,0 +1,139 @@
"""Kanban database service — read-only queries against kanban.db."""
import logging
import sqlite3
from typing import Any
from extensions import get_db
logger = logging.getLogger(__name__)
STATUSES = ("ready", "running", "done", "blocked", "failed")
def _row_to_dict(row: sqlite3.Row) -> dict[str, Any]:
"""Convert sqlite3.Row to plain dict."""
return dict(row)
def get_tasks(status: str | None = None) -> dict[str, Any]:
"""Return tasks list and status counts."""
try:
db = get_db()
# Get counts per status
counts: dict[str, int] = {}
for s in STATUSES:
row = db.execute(
"SELECT COUNT(*) as cnt FROM tasks WHERE status = ?", (s,)
).fetchone()
counts[s] = row["cnt"] if row else 0
# Get filtered or all tasks
if status and status in STATUSES:
rows = db.execute(
"SELECT * FROM tasks WHERE status = ? ORDER BY created_at DESC",
(status,),
).fetchall()
else:
rows = db.execute(
"SELECT * FROM tasks ORDER BY created_at DESC"
).fetchall()
tasks = [_row_to_dict(r) for r in rows]
return {"tasks": tasks, "counts": counts}
except sqlite3.Error as exc:
logger.exception("get_tasks failed")
return {"tasks": [], "counts": {s: 0 for s in STATUSES}, "error": str(exc)}
def get_recent_tasks(limit: int = 5) -> list[dict]:
"""Return the most recent tasks with outcome summary."""
try:
db = get_db()
rows = db.execute(
"SELECT id, title, status, created_at, result FROM tasks "
"ORDER BY created_at DESC LIMIT ?",
(limit,),
).fetchall()
return [
{
"id": r["id"],
"title": r["title"],
"status": r["status"],
"created_at": r["created_at"],
"outcome_summary": (r["result"] or "")[:200],
}
for r in rows
]
except sqlite3.Error as exc:
logger.exception("get_recent_tasks failed")
return []
def get_task_detail(task_id: str) -> dict[str, Any]:
"""Return full task detail with events, comments, runs, attachments."""
try:
db = get_db()
task_row = db.execute("SELECT * FROM tasks WHERE id = ?", (task_id,)).fetchone()
if not task_row:
return {"error": "task not found"}
task = _row_to_dict(task_row)
events_rows = db.execute(
"SELECT * FROM task_events WHERE task_id = ? ORDER BY created_at",
(task_id,),
).fetchall()
events = [_row_to_dict(r) for r in events_rows]
comments_rows = db.execute(
"SELECT * FROM task_comments WHERE task_id = ? ORDER BY created_at",
(task_id,),
).fetchall()
comments = [_row_to_dict(r) for r in comments_rows]
runs_rows = db.execute(
"SELECT * FROM task_runs WHERE task_id = ? ORDER BY started_at DESC",
(task_id,),
).fetchall()
runs = [_row_to_dict(r) for r in runs_rows]
attachments_rows = db.execute(
"SELECT * FROM task_attachments WHERE task_id = ? ORDER BY created_at",
(task_id,),
).fetchall()
attachments = [_row_to_dict(r) for r in attachments_rows]
return {
"task": task,
"events": events,
"comments": comments,
"runs": runs,
"attachments": attachments,
}
except sqlite3.Error as exc:
logger.exception("get_task_detail failed")
return {"error": str(exc)}
def get_kanban_board() -> dict[str, Any]:
"""Return tasks grouped by status for kanban board view."""
try:
db = get_db()
board: dict[str, list[dict[str, Any]]] = {s: [] for s in STATUSES}
rows = db.execute(
"SELECT * FROM tasks ORDER BY created_at DESC"
).fetchall()
for row in rows:
d = _row_to_dict(row)
status = d.get("status", "ready")
if status in board:
board[status].append(d)
return {"board": board}
except sqlite3.Error as exc:
logger.exception("get_kanban_board failed")
return {"board": {s: [] for s in STATUSES}, "error": str(exc)}

161
services/projects.py Normal file
View File

@@ -0,0 +1,161 @@
"""Projects service — git info for managed projects."""
import logging
import os
import subprocess
from typing import Any
import config
logger = logging.getLogger(__name__)
def _run_git(cwd: str, args: list[str]) -> str:
"""Run a git command in the given directory. Returns stdout or empty string."""
try:
result = subprocess.run(
["git"] + args,
cwd=cwd,
capture_output=True,
text=True,
check=False,
timeout=5,
)
if result.returncode != 0:
return ""
return result.stdout.strip()
except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as exc:
logger.debug("git %s in %s failed: %s", args, cwd, exc)
return ""
def _is_git_repo(path: str) -> bool:
"""Check if path is a git repository."""
return os.path.isdir(os.path.join(path, ".git"))
def get_project_info(proj: config.ProjectConfig) -> dict[str, Any]:
"""Get git info for a single project."""
path = proj["path"]
name = proj["name"]
if not os.path.isdir(path):
return {
"name": name,
"path": path,
"gitea_repo": proj["gitea_repo"],
"status": "not-found",
"branch": "",
"commit_hash": "",
"commit_short": "",
"commit_msg": "",
"commit_time": "",
"commit_time_rel": "",
"dirty_count": 0,
"error": "directory not found",
}
if not _is_git_repo(path):
return {
"name": name,
"path": path,
"gitea_repo": proj["gitea_repo"],
"status": "not-git-repo",
"branch": "",
"commit_hash": "",
"commit_short": "",
"commit_msg": "",
"commit_time": "",
"commit_time_rel": "",
"dirty_count": 0,
}
branch = _run_git(path, ["rev-parse", "--abbrev-ref", "HEAD"])
commit_hash = _run_git(path, ["rev-parse", "HEAD"])
commit_short = commit_hash[:7] if commit_hash else ""
# Format: unix_epoch|subject
log_line = _run_git(path, ["log", "-1", "--format=%ct|%s"])
commit_time = ""
commit_msg = ""
if "|" in log_line:
parts = log_line.split("|", 1)
commit_time = parts[0]
commit_msg = parts[1]
# Dirty count
status_output = _run_git(path, ["status", "--porcelain"])
dirty_count = len(status_output.splitlines()) if status_output else 0
return {
"name": name,
"path": path,
"gitea_repo": proj["gitea_repo"],
"status": "ok",
"branch": branch,
"commit_hash": commit_hash,
"commit_short": commit_short,
"commit_msg": commit_msg,
"commit_time": commit_time,
"commit_time_rel": "", # computed in template via |rel filter
"dirty_count": dirty_count,
}
def get_all_projects() -> list[dict[str, Any]]:
"""Get info for all managed projects."""
results: list[dict[str, Any]] = []
for proj in config.MANAGED_PROJECTS:
try:
results.append(get_project_info(proj))
except Exception as exc:
logger.exception("get_project_info failed for %s", proj["name"])
results.append({
"name": proj["name"],
"path": proj["path"],
"gitea_repo": proj["gitea_repo"],
"status": "error",
"error": str(exc),
})
return results
def get_project_detail(name: str) -> dict[str, Any]:
"""Get detailed info for a specific project."""
proj = None
for p in config.MANAGED_PROJECTS:
if p["name"] == name:
proj = p
break
if proj is None:
return {"error": "project not found"}
info = get_project_info(proj)
path = proj["path"]
if info.get("status") != "ok":
return info
# Recent commits (last 10)
log_output = _run_git(path, ["log", "-10", "--oneline"])
recent_commits = log_output.splitlines() if log_output else []
# Diff stat HEAD~1..HEAD
diff_stat = ""
commit_count_str = _run_git(path, ["rev-list", "--count", "HEAD"])
try:
commit_count = int(commit_count_str) if commit_count_str else 0
except ValueError:
commit_count = 0
if commit_count >= 2:
diff_stat = _run_git(path, ["diff", "--stat", "HEAD~1..HEAD"])
# git status --porcelain
status_porcelain = _run_git(path, ["status", "--porcelain"])
info["recent_commits"] = recent_commits
info["diff_stat"] = diff_stat
info["status_porcelain"] = status_porcelain
return info

78
services/worker.py Normal file
View File

@@ -0,0 +1,78 @@
"""Worker service — process scanning and SOUL.md reading."""
import logging
import os
from typing import Any
import psutil
import config
logger = logging.getLogger(__name__)
def get_running_processes() -> list[dict[str, Any]]:
"""Scan for opencode worker processes (cmdline contains both 'opencode' and 'run')."""
processes: list[dict[str, Any]] = []
try:
for proc in psutil.process_iter(["pid", "create_time", "cmdline"]):
try:
cmdline = proc.info.get("cmdline") or []
cmdline_str = " ".join(cmdline)
if "opencode" in cmdline_str and "run" in cmdline_str:
# Truncate cmdline to 200 chars
if len(cmdline_str) > 200:
cmdline_str = cmdline_str[:200] + "..."
# Calculate elapsed time
create_time = proc.info.get("create_time", 0)
processes.append({
"pid": proc.info["pid"],
"cmdline": cmdline_str,
"create_time": create_time,
})
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
except Exception as exc:
logger.exception("get_running_processes failed")
return processes
def get_current_task() -> dict[str, Any] | None:
"""Find the currently running task (status=running) from kanban DB."""
try:
from extensions import get_db
db = get_db()
row = db.execute(
"SELECT * FROM tasks WHERE status = 'running' ORDER BY started_at DESC LIMIT 1"
).fetchone()
if row:
return dict(row)
except Exception as exc:
logger.debug("get_current_task failed: %s", exc)
return None
def get_soul_excerpt(max_chars: int = 2000) -> str:
"""Read first max_chars from SOUL.md."""
try:
with open(config.SOUL_MD_PATH, "r", encoding="utf-8") as f:
content = f.read(max_chars)
return content
except (FileNotFoundError, PermissionError, OSError) as exc:
logger.debug("SOUL.md read failed: %s", exc)
return f"(SOUL.md not available: {exc})"
def get_worker_status() -> dict[str, Any]:
"""Aggregate worker status: current task, processes, soul excerpt."""
return {
"current_task": get_current_task(),
"processes": get_running_processes(),
"soul_excerpt": get_soul_excerpt(500),
}
def get_soul_full() -> dict[str, str]:
"""Return first 2000 chars of SOUL.md."""
return {"content": get_soul_excerpt(2000)}