Skip to content

Autonomous AI sales agent powered by Claude Code or Codex. Finds prospects, writes cold emails, sends campaigns, handles replies, books meetings. No API keys needed — runs on your Claude or Codex subscriptions.

Today: live status panel answering "what's happening right now?"

YooshaMirza74dae81959dc
diff --git a/harvey/dashboard.py b/harvey/dashboard.py
index 5455588..51398ca 100644
--- a/harvey/dashboard.py
+++ b/harvey/dashboard.py
@@ -11,7 +11,7 @@ import subprocess
import sys
import tempfile
import uuid
-from datetime import datetime
+from datetime import datetime, timezone
from pathlib import Path
import aiosqlite
@@ -1112,6 +1112,186 @@ async def stop_discovery():
return JSONResponse({"success": False, "message": str(e)}, status_code=500)
+def _parse_ts(value) -> datetime | None:
+ """SQLite CURRENT_TIMESTAMP / isoformat strings -> naive UTC datetime."""
+ if not value:
+ return None
+ try:
+ return datetime.fromisoformat(str(value).replace("Z", "").split("+")[0])
+ except ValueError:
+ return None
+
+
+async def _scalar(sql: str, params: tuple = ()) -> int:
+ rows = await query_db(sql, params)
+ return int(next(iter(rows[0].values())) or 0) if rows else 0
+
+
+async def _first(sql: str, params: tuple = (), key: str = "t"):
+ """First row's `key`, or None — query_db returns [] on any DB problem."""
+ rows = await query_db(sql, params)
+ return rows[0].get(key) if rows else None
+
+
+# A run row still says 'running' after its process was killed (closed window,
+# reboot). No new facts for this long means it is not coming back.
+STALE_RUN_SECONDS = 900
+# Contact-finding has no run row; a recent prospects_checked_at means it is active.
+CONTACT_ACTIVE_SECONDS = 180
+SENT_STATUSES = ("contacted", "replied", "meeting", "closed", "lost")
+REPLY_STATUSES = ("replied", "meeting", "closed")
+
+
+def _eta_text(minutes) -> str:
+ if minutes is None:
+ return ""
+ return "less than a minute left" if minutes < 1 else f"about {round(minutes)} min left"
+
+
[email protected]("/api/live-status")
+async def get_live_status():
+ """Plain-language progress: each pipeline step, what is running, how long is left.
+
+ Built for someone who would otherwise keep asking "what's the status?".
+ Everything is derived from the database, so it is true whatever started
+ the work — `harvey run`, a CLI command, or a one-off script. Every total
+ counts only what the step can act on (a business with no website is never
+ read), so a finished step always reaches 100% instead of sticking.
+ """
+ now = datetime.now(timezone.utc).replace(tzinfo=None) # DB stores naive UTC
+ has_site = "COALESCE(domain, '') != ''"
+ companies = await _scalar("SELECT COUNT(*) FROM companies")
+ with_site = await _scalar(f"SELECT COUNT(*) FROM companies WHERE {has_site}")
+ no_site = companies - with_site
+ profiled = await _scalar(
+ f"SELECT COUNT(*) FROM companies WHERE {has_site} AND profile_checked_at IS NOT NULL")
+ checked = await _scalar(
+ f"SELECT COUNT(*) FROM companies WHERE {has_site} "
+ "AND profile_checked_at IS NOT NULL AND prospects_checked_at IS NOT NULL")
+
+ prospects = await query_db("SELECT id, email, email_status, status FROM prospects")
+ with_email = [p for p in prospects if p.get("email")]
+ by_status: dict[str, int] = {}
+ for p in with_email:
+ k = (p.get("email_status") or "guess").lower()
+ by_status[k] = by_status.get(k, 0) + 1
+ deliverable = {p["id"] for p in with_email
+ if (p.get("email_status") or "") in ("verified", "risky")}
+ unconfirmed = sum(n for k, n in by_status.items()
+ if k not in ("verified", "risky", "invalid"))
+
+ # Drafts are counted per person, not per campaign: one campaign can cover many.
+ drafted: set[str] = set()
+ for row in await query_db("SELECT prospect_ids_json FROM campaigns"):
+ try:
+ ids = json.loads(row.get("prospect_ids_json") or "[]")
+ except (json.JSONDecodeError, TypeError):
+ ids = []
+ if isinstance(ids, list):
+ drafted.update(i for i in ids if isinstance(i, str))
+ sent = {p["id"] for p in prospects if p.get("status") in SENT_STATUSES}
+ replies = sum(1 for p in prospects if p.get("status") in REPLY_STATUSES)
+ cost = float(await _first(
+ "SELECT COALESCE(SUM(cost_usd), 0) AS c FROM runs", key="c") or 0)
+
+ running, stopped = [], []
+ for run in await query_db(
+ "SELECT * FROM runs WHERE status = 'running' ORDER BY started_at"):
+ started = _parse_ts(run.get("started_at"))
+ elapsed = max(0.0, (now - started).total_seconds()) if started else 0.0
+ last = _parse_ts(await _first(
+ "SELECT MAX(observed_at) AS t FROM observations WHERE run_id = ?",
+ (run["id"],))) or started
+ item = {"stage": run.get("stage"), "provider": run.get("provider"),
+ "elapsed_min": round(elapsed / 60, 1), "eta_min": None}
+ if last and (now - last).total_seconds() > STALE_RUN_SECONDS:
+ stopped.append(item)
+ continue
+ if run.get("stage") == "profile" and started:
+ done_in_run = await _scalar(
+ f"SELECT COUNT(*) FROM companies WHERE {has_site} AND profile_checked_at >= ?",
+ (run["started_at"],))
+ left = max(0, with_site - profiled)
+ if left and done_in_run and elapsed > 0:
+ item["eta_min"] = left / (done_in_run / elapsed) / 60
+ running.append(item)
+
+ last_contact = _parse_ts(await _first(
+ "SELECT MAX(prospects_checked_at) AS t FROM companies"))
+ finding_emails = bool(
+ last_contact and (now - last_contact).total_seconds() < CONTACT_ACTIVE_SECONDS)
+ reading = any(r["stage"] == "profile" for r in running)
+ finding = any(r["stage"] == "discover" for r in running)
+
+ def step(label, done, total, active, detail, info=False):
+ if active:
+ state_ = "running"
+ elif info:
+ state_ = "done" if done else "waiting"
+ elif total and done >= total:
+ state_ = "done"
+ elif done:
+ state_ = "partial"
+ else:
+ state_ = "waiting"
+ return {"label": label, "done": done, "total": total,
+ "state": state_, "detail": detail}
+
+ profile_eta = next((r["eta_min"] for r in running if r["stage"] == "profile"), None)
+ read_detail = f"{profiled} of {with_site} read"
+ if reading and profile_eta is not None:
+ read_detail += " · " + _eta_text(profile_eta)
+ if no_site:
+ read_detail += f" · {no_site} have no website (skipped)"
+
+ steps = [
+ step("Find businesses", companies, 0, finding,
+ f"{companies} businesses found", info=True),
+ step("Read their websites", profiled, with_site, reading, read_detail),
+ step("Find emails", checked, profiled, finding_emails,
+ f"{checked} of {profiled} checked · {len(with_email)} emails found"),
+ step("Check emails are real", len(with_email) - unconfirmed, len(with_email), False,
+ f"{by_status.get('verified', 0)} verified · {by_status.get('risky', 0)} risky · "
+ f"{unconfirmed} not confirmed"
+ + (f" · {by_status['invalid']} bad" if by_status.get("invalid") else "")),
+ step("Write first emails", len(drafted), len(deliverable | drafted), False,
+ f"{len(drafted)} written · see Campaigns"),
+ step("Sent by you", len(sent & drafted), len(drafted), False,
+ f"{len(sent & drafted)} of {len(drafted)} sent"),
+ step("Replies", replies, 0, False,
+ f"{replies} replies" if replies else "No replies yet", info=True),
+ ]
+
+ if reading or finding:
+ next_up = "Wait — Harvey is working. This page updates by itself."
+ elif finding_emails:
+ next_up = "Wait — emails are being found."
+ elif stopped:
+ next_up = "A job stopped before finishing. Run it again."
+ elif drafted - sent:
+ next_up = f"Open Campaigns and send the {len(drafted - sent)} unsent email(s)."
+ elif profiled > checked:
+ next_up = f"Find emails for the {profiled - checked} businesses not checked yet."
+ elif deliverable - drafted:
+ next_up = f"Write first emails for {len(deliverable - drafted)} more contact(s)."
+ elif not companies:
+ next_up = "Search for businesses to get started."
+ else:
+ next_up = "Search more cities or industries to get more leads."
+
+ note_rows = await query_db(
+ "SELECT value, updated_at FROM settings WHERE key = 'status_note'")
+ return {
+ "steps": steps,
+ "running": [dict(r, eta_text=_eta_text(r["eta_min"])) for r in running],
+ "stopped": stopped,
+ "next": next_up,
+ "note": note_rows[0] if note_rows else None,
+ "cost_usd": round(cost, 4),
+ "updated_at": now.isoformat() + "Z",
+ }
+
+
@app.get("/api/today")
async def get_today():
"""What needs a human, right now.
diff --git a/harvey/web/app.js b/harvey/web/app.js
index f36d4a1..0324155 100644
--- a/harvey/web/app.js
+++ b/harvey/web/app.js
@@ -247,7 +247,7 @@ function showTab(id, btn) {
function loadCurrentTab() {
switch (currentTab) {
- case 'today': loadToday(); loadSetupStatus(); loadRuns(); loadTodayActivity(); break;
+ case 'today': loadLiveStatus(); loadToday(); loadSetupStatus(); loadRuns(); loadTodayActivity(); break;
case 'signals': loadSignals(); break;
case 'discover': loadDiscoverProviders(); break;
case 'companies': if (!companyDrill) loadCompanies(); break;
@@ -296,6 +296,66 @@ async function loadToday() {
).join('') + '</div>';
}
+// ── Live status: the "what's happening?" answer, kept on screen ──
+
+async function loadLiveStatus() {
+ const el = document.getElementById('live-status');
+ if (!el) return;
+ const d = await api('/api/live-status');
+ if (!d || !Array.isArray(d.steps)) {
+ // Keep the last good numbers on screen, but never let them pass for live.
+ const flag = el.querySelector('.live-flag');
+ if (flag) flag.textContent = "Can't reach Harvey right now — numbers below may be old.";
+ else el.innerHTML = '<div class="rail-block"><div class="subhead">Status — live</div>' +
+ '<p class="muted live-flag" style="font-size:13px">Can\'t reach Harvey right now. ' +
+ 'Is the dashboard window still open?</p></div>';
+ return;
+ }
+ const icon = {done: '&#10003;', running: '&#9203;', partial: '&#9679;', waiting: '&#9675;'};
+ const color = {done: '#2e7d32', running: '#b26a00',
+ partial: 'var(--text-2, #666)', waiting: 'var(--text-3, #999)'};
+ const rows = d.steps.map(s => {
+ const st = icon[s.state] ? s.state : 'waiting';
+ const pct = s.total ? Math.min(100, Math.round(100 * s.done / s.total)) : 0;
+ const bar = s.total
+ ? '<div style="height:5px;background:var(--border, #e5e5e5);border-radius:3px;margin-top:5px">' +
+ '<div style="height:5px;width:' + pct + '%;background:' + color[st] +
+ ';border-radius:3px;transition:width .4s"></div></div>'
+ : '';
+ return '<div style="display:flex;gap:10px;padding:8px 0;border-bottom:1px solid var(--border, #eee)">' +
+ '<span style="width:20px;text-align:center;color:' + color[st] + '">' + icon[st] + '</span>' +
+ '<div style="flex:1;min-width:0"><div style="display:flex;justify-content:space-between;gap:8px;flex-wrap:wrap">' +
+ '<strong style="font-size:13.5px">' + escHtml(s.label) + '</strong>' +
+ '<span class="muted" style="font-size:12.5px">' + escHtml(s.detail) + '</span></div>' + bar +
+ '</div></div>';
+ }).join('');
+ const jobName = r => r.stage === 'profile' ? 'Reading websites'
+ : r.stage === 'discover' ? 'Searching for businesses (' + (r.provider || '') + ')'
+ : String(r.stage || 'Job');
+ const running = d.running || [];
+ const runningHtml = running.length
+ ? running.map(r => '&#9203; ' + escHtml(jobName(r)) + ' · running ' + r.elapsed_min + ' min' +
+ (r.eta_text ? ' · ' + escHtml(r.eta_text) : '')).join('<br>')
+ : 'Nothing running right now.';
+ const stoppedHtml = (d.stopped || []).length
+ ? '<div style="margin-top:6px;font-size:13px;color:#b3261e">&#9888; ' +
+ (d.stopped || []).map(r => escHtml(jobName(r))).join(', ') +
+ ' stopped before finishing.</div>'
+ : '';
+ const note = d.note && d.note.value
+ ? '<div style="margin-top:8px;font-size:13px">&#128172; ' + escHtml(d.note.value) +
+ ' <span class="muted">(' + formatDate(d.note.updated_at) + ')</span></div>'
+ : '';
+ el.innerHTML = '<div class="rail-block">' +
+ '<div class="subhead">Status — live</div>' +
+ '<div style="font-size:13px;margin:6px 0 4px">' + runningHtml + '</div>' + stoppedHtml + note +
+ '<div style="margin-top:10px">' + rows + '</div>' +
+ '<div style="margin-top:10px;font-size:13px"><strong>Next:</strong> ' + escHtml(d.next || '') + '</div>' +
+ '<div class="muted live-flag" style="margin-top:4px;font-size:12px">Cost so far: $' +
+ Number(d.cost_usd || 0).toFixed(2) + ' · updated ' + new Date().toLocaleTimeString() +
+ ' · refreshes every 10 seconds</div></div>';
+}
+
function renderFigures(stats) {
const el = document.getElementById('today-figures');
if (!el) return;
@@ -1546,9 +1606,16 @@ loadRuns();
loadTodayActivity();
loadHarveyStatus();
+loadLiveStatus();
+
// Agent status: quick poll (not while locked: it would only be refused)
setInterval(() => { if (!_locked) loadHarveyStatus(); }, 8000);
+// Live status panel: the cheapest query on the page, so it refreshes fastest.
+setInterval(() => {
+ if (!document.hidden && !_locked && currentTab === 'today') loadLiveStatus();
+}, 10000);
+
// Nav counts stay live wherever you are, so "something needs me" is visible
// from any tab without polling that tab's contents.
setInterval(async () => {
diff --git a/harvey/web/index.html b/harvey/web/index.html
index 9443452..8dc67bf 100644
--- a/harvey/web/index.html
+++ b/harvey/web/index.html
@@ -76,6 +76,7 @@
</div>
<div class="today-grid">
<div class="today-main">
+ <div id="live-status" style="margin-bottom:28px"></div>
<div id="today-queue"></div>
<div class="rail-block" style="margin-top:34px">
<div class="subhead">Recent activity</div>
diff --git a/tests/test_dashboard_live_status.py b/tests/test_dashboard_live_status.py
new file mode 100644
index 0000000..03be391
--- /dev/null
+++ b/tests/test_dashboard_live_status.py
@@ -0,0 +1,144 @@
+"""The Today tab's live status panel (/api/live-status).
+
+Totals only count what a step can act on, so a finished step reaches 100%
+instead of sticking (a business with no website is never read); a run killed
+mid-way is reported as stopped rather than "running" forever; drafts and
+sends are counted per person; an empty or missing database never errors.
+"""
+
+import asyncio
+import json
+import sqlite3
+from datetime import datetime, timedelta, timezone
+
+import pytest
+from fastapi.testclient import TestClient
+
+import harvey.dashboard as dash
+from harvey.signals import seed_signal_catalog
+from harvey.state import StateManager
+
+ORIGIN = "http://127.0.0.1:5555"
+
+
+def env(tmp_path, monkeypatch):
+ (tmp_path / "data").mkdir()
+ db = tmp_path / "data" / "harvey.db"
+ monkeypatch.setattr(dash, "ENV_FILE", tmp_path / ".env")
+ monkeypatch.setattr(dash, "DB_PATH", db)
+ monkeypatch.setattr(dash, "PID_FILE", tmp_path / "data" / "harvey.pid")
+ monkeypatch.setattr(dash, "LOG_FILE", tmp_path / "data" / "harvey.log")
+ dash.token_store.configure(tmp_path / "data" / "dashboard-token")
+ async def _init():
+ state = StateManager(db_path=str(db))
+ await state.init_db()
+ await seed_signal_catalog(state) # observations only accept known codes
+ asyncio.run(_init())
+ return {"db": db, "token": dash.token_store.get()}
+
+
+def client(env):
+ with TestClient(dash.app, base_url=ORIGIN,
+ headers={"Authorization": f"Bearer {env['token']}"}) as c:
+ yield c
+
+
+def _sql(env, query, params=()):
+ with sqlite3.connect(env["db"]) as db:
+ db.execute(query, params)
+
+
+def _ts(minutes_ago=0):
+ now = datetime.now(timezone.utc).replace(tzinfo=None) # the DB stores naive UTC
+ return (now - timedelta(minutes=minutes_ago)).strftime("%Y-%m-%d %H:%M:%S")
+
+
+def _company(env, cid, domain="", profiled=False, checked=False):
+ _sql(env, "INSERT INTO companies (id, name, domain, profile_checked_at, "
+ "prospects_checked_at) VALUES (?, ?, ?, ?, ?)",
+ (cid, cid, domain, _ts(30) if profiled else None, _ts(30) if checked else None))
+
+
+def _prospect(env, pid, email, email_status="verified", status="new"):
+ _sql(env, "INSERT INTO prospects (id, first_name, last_name, email, email_status, "
+ "status, company) VALUES (?, '', '', ?, ?, ?, 'Acme')",
+ (pid, email, email_status, status))
+
+
+def _campaign(env, cid, prospect_ids):
+ _sql(env, "INSERT INTO campaigns (id, name, channel, sequence_json, prospect_ids_json, "
+ "status) VALUES (?, ?, 'email', ?, ?, 'draft')",
+ (cid, cid, json.dumps([{"step": 1, "subject": "hi", "body": "Hi {{company}}",
+ "delay_days": 0}]), json.dumps(prospect_ids)))
+
+
+def _step(data, label):
+ return next(s for s in data["steps"] if s["label"] == label)
+
+
+def test_live_status_on_an_empty_database(client):
+ data = client.get("/api/live-status").json()
+ assert data["running"] == [] and data["stopped"] == []
+ assert _step(data, "Read their websites")["state"] == "waiting"
+ assert data["next"] == "Search for businesses to get started."
+
+
+def test_live_status_without_a_database_file(client, env):
+ env["db"].unlink()
+ assert client.get("/api/live-status").status_code == 200
+
+
+def test_businesses_without_a_website_do_not_stall_reading(client, env):
+ _company(env, "a", "a.test", profiled=True, checked=True)
+ _company(env, "b", "b.test", profiled=True, checked=True)
+ _company(env, "c") # no website: never read, so never counted as pending
+ step = _step(client.get("/api/live-status").json(), "Read their websites")
+ assert (step["done"], step["total"], step["state"]) == (2, 2, "done")
+ assert "1 have no website (skipped)" in step["detail"]
+
+
+def test_queued_drafts_are_not_counted_as_sent(client, env):
+ _prospect(env, "p1", "[email protected]", status="queued")
+ _prospect(env, "p2", "[email protected]", status="contacted")
+ _campaign(env, "c1", ["p1", "p2"])
+ data = client.get("/api/live-status").json()
+ sent = _step(data, "Sent by you")
+ assert (sent["done"], sent["total"]) == (1, 2)
+ assert _step(data, "Write first emails")["done"] == 2 # per person, not per campaign
+ assert data["next"] == "Open Campaigns and send the 1 unsent email(s)."
+
+
+def test_unconfirmed_emails_are_reported_not_hidden(client, env):
+ _prospect(env, "p1", "[email protected]", email_status="verified")
+ _prospect(env, "p2", "[email protected]", email_status="guess")
+ step = _step(client.get("/api/live-status").json(), "Check emails are real")
+ assert (step["done"], step["total"]) == (1, 2)
+ assert "1 not confirmed" in step["detail"]
+
+
+def test_a_live_run_shows_progress_and_time_left(client, env):
+ _sql(env, "INSERT INTO runs (id, stage, status, provider, started_at) "
+ "VALUES ('r1', 'profile', 'running', 'http', ?)", (_ts(10),))
+ _sql(env, "INSERT INTO companies (id, name, domain, profile_checked_at) "
+ "VALUES ('a', 'a', 'a.test', ?)", (_ts(1),))
+ _company(env, "b", "b.test")
+ _sql(env, "INSERT INTO observations (company_id, signal_code, collector, observed_at, "
+ "run_id) VALUES ('a', 'TECH_STACK', 'profile', ?, 'r1')", (_ts(1),))
+ data = client.get("/api/live-status").json()
+ assert [r["stage"] for r in data["running"]] == ["profile"]
+ assert data["running"][0]["eta_text"].endswith("min left")
+ assert _step(data, "Read their websites")["state"] == "running"
+ assert data["next"].startswith("Wait")
+
+
+def test_a_killed_run_is_reported_as_stopped_not_running(client, env):
+ _sql(env, "INSERT INTO runs (id, stage, status, provider, started_at) "
+ "VALUES ('r1', 'profile', 'running', 'http', ?)", (_ts(120),))
+ _company(env, "a", "a.test")
+ data = client.get("/api/live-status").json()
+ assert data["running"] == []
+ assert [r["stage"] for r in data["stopped"]] == ["profile"]
+ assert _step(data, "Read their websites")["state"] != "running"
+ assert "stopped before finishing" in data["next"]