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.

Dashboard audit fixes: every control does something, honest numbers

Ethan187b03abd851
diff --git a/harvey/dashboard.py b/harvey/dashboard.py
index cd3bee8..b5ac3d8 100644
--- a/harvey/dashboard.py
+++ b/harvey/dashboard.py
@@ -595,6 +595,26 @@ async def get_harvey_logs():
# ── Pipeline Data (existing endpoints) ──
+def _pipeline_bucket(status: str | None, stage: str | None, intent: str | None,
+ email_status: str | None = None) -> str:
+ """One funnel stage per contact, from its status and latest conversation."""
+ status = status or "new"
+ if status in ("new", "queued"):
+ return "to_write"
+ if status == "contacted":
+ # A bounce leaves the status alone and marks the address invalid.
+ return "closed_out" if email_status == "invalid" else "contacted"
+ if status == "meeting":
+ return "ready_to_meet"
+ if status == "replied" and stage != "closed_lost":
+ if stage == "closing":
+ return "ready_to_meet"
+ if intent == "interested" or stage in ("presenting", "negotiating"):
+ return "interested"
+ return "replied"
+ return "closed_out" # lost, opted out, bounced, unwritable
+
+
@app.get("/api/stats")
async def get_stats():
"""Pipeline overview stats."""
@@ -615,6 +635,21 @@ async def get_stats():
)
convo_map = {r["status"]: r["count"] for r in conversations}
+ # Where each contact stands. Prospect status alone stops at
+ # "replied"; how a reply went lives on its latest conversation.
+ rows = await query_db("""
+ SELECT p.status, p.email_status, l.stage, l.intent, COUNT(*) AS count FROM prospects p
+ LEFT JOIN (SELECT prospect_id, stage, intent, ROW_NUMBER() OVER (
+ PARTITION BY prospect_id ORDER BY updated_at DESC, created_at DESC) AS rn
+ FROM conversations) l ON l.prospect_id = p.id AND l.rn = 1
+ GROUP BY p.status, p.email_status, l.stage, l.intent
+ """)
+ pipeline = dict.fromkeys(
+ ("to_write", "contacted", "replied", "interested", "ready_to_meet", "closed_out"), 0)
+ for r in rows:
+ pipeline[_pipeline_bucket(r["status"], r["stage"], r["intent"],
+ r["email_status"])] += r["count"]
+
actions = await query_db("SELECT COUNT(*) as count FROM actions")
action_count = actions[0]["count"] if actions else 0
@@ -628,6 +663,7 @@ async def get_stats():
"prospects": {"total": prospect_total, "by_status": prospect_map},
"campaigns": {"total": sum(campaign_map.values()), "by_status": campaign_map},
"conversations": {"total": sum(convo_map.values()), "by_status": convo_map},
+ "pipeline": pipeline,
"actions_total": action_count,
"claude_calls_today": usage_today,
"codex_calls_today": codex_today,
@@ -1237,7 +1273,7 @@ async def get_conversations():
emails: dict[str, list] = {}
if pids:
for e in await query_db(
- "SELECT prospect_id, step, subject, body, sent_at FROM outbox "
+ "SELECT prospect_id, campaign_id, step, subject, body, sent_at FROM outbox "
f"WHERE kind = 'sequence' AND status = 'sent' AND prospect_id IN ({_in(pids)}) "
"ORDER BY sent_at", tuple(pids)):
emails.setdefault(e.pop("prospect_id"), []).append(e)
@@ -1251,24 +1287,56 @@ async def get_conversations():
row["thread"] = json.loads(row.get("thread_json", "[]"))
except (json.JSONDecodeError, TypeError):
row["thread"] = []
- row["emails"] = emails.get(row.get("prospect_id"), [])
+ # A prospect in two campaigns: show the sequence this reply answers.
+ camp = row.get("campaign_id") or ""
+ row["emails"] = [{k: v for k, v in e.items() if k != "campaign_id"}
+ for e in emails.get(row.get("prospect_id"), [])
+ if not camp or e.get("campaign_id") == camp]
row["draft"] = drafts.get(row["id"])
return rows
[email protected]("/api/conversations/{convo_id}/status")
+async def set_conversation_status(convo_id: str, request: Request):
+ """Close a conversation, or hand one Harvey escalated back to it.
+
+ Harvey answers new replies only on open conversations, so "open" means
+ "Harvey, carry on" and "closed" means it's done."""
+ try:
+ data = await request.json()
+ except Exception:
+ data = {}
+ status = data.get("status") if isinstance(data, dict) else None
+ if status not in ("open", "closed"):
+ return JSONResponse({"success": False, "message": "status must be open or closed"},
+ status_code=400)
+ rows = await query_db("SELECT status FROM conversations WHERE id = ?", (convo_id,))
+ if not rows:
+ return JSONResponse({"success": False, "message": "No such conversation."},
+ status_code=404)
+ state = _state()
+ await state.update_conversation(convo_id, status=status)
+ await state.log_action("conversation_status", "dashboard",
+ {"conversation_id": convo_id, "from": rows[0]["status"], "to": status})
+ return {"success": True, "status": status}
+
+
@app.get("/api/trend")
-async def get_trend(days: int = 14):
- """Daily counts for the last `days` UTC days (stored times are UTC):
- contacts found, emails sent, first replies. Days with nothing are 0."""
+async def get_trend(days: int = 14, tz: int = 0):
+ """Daily counts for the last `days` days in the viewer's time zone
+ (`tz`: minutes east of UTC; stored times are UTC): contacts found,
+ emails sent, first replies. Days with nothing are 0."""
from datetime import datetime, timedelta, timezone
days = max(1, min(90, days))
- today = datetime.now(timezone.utc).date()
+ tz = max(-840, min(840, tz))
+ shift = f"{tz:+d} minutes"
+ today = (datetime.now(timezone.utc) + timedelta(minutes=tz)).date()
labels = [(today - timedelta(days=n)).isoformat() for n in range(days - 1, -1, -1)]
async def per_day(table: str, column: str, where: str = "") -> list[int]:
rows = await query_db(
- f"SELECT date({column}) AS d, COUNT(*) AS n FROM {table} "
- f"WHERE date({column}) >= ? {where} GROUP BY d", (labels[0],))
+ f"SELECT date({column}, ?) AS d, COUNT(*) AS n FROM {table} "
+ f"WHERE date({column}, ?) >= ? {where} GROUP BY d", (shift, shift, labels[0]))
counts = {r["d"]: r["n"] for r in rows}
return [counts.get(day, 0) for day in labels]
@@ -1301,6 +1369,7 @@ async def get_activity():
_discovery_task: asyncio.Task | None = None
_discovery_report: dict | None = None
+_discovery_kind = "discover" # or "profile": reading sites has no stop switch
def _discovery_queries(body: dict, config):
@@ -1329,6 +1398,8 @@ async def get_discovery_providers():
"selected": await state.get_setting("discovery_provider") or DEFAULT_PROVIDER,
"paused": await state.get_setting("discovery_paused"),
"running": bool(_discovery_task and not _discovery_task.done()),
+ "running_kind": _discovery_kind,
+ "unprofiled": await state.count_companies_needing_profile(),
"last_report": _discovery_report,
}
except Exception as e:
@@ -1394,6 +1465,9 @@ async def start_discovery(request: Request):
await state.set_setting("discovery_provider", provider)
await state.set_setting("discovery_paused", "")
+ global _discovery_kind
+ _discovery_kind = "discover"
+
async def _go():
global _discovery_report
try:
@@ -1450,6 +1524,8 @@ async def start_profile():
logger.exception("profile run failed")
_discovery_report = {"errors": [str(exc)], "stopped": "failed"}
+ global _discovery_kind
+ _discovery_kind = "profile"
_discovery_report = None
_discovery_task = asyncio.create_task(_go())
return {"success": True, "pending": pending}
@@ -1631,30 +1707,32 @@ async def get_live_status():
f"{replies} replies" if replies else "No replies yet", info=True),
]
+ next_tab = "" # where the next step is done, when it's done in the dashboard
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."
+ next_up, next_tab = "A job stopped before finishing. Run it again.", "discover"
elif harvey_sends and awaiting_review:
- next_up = f"Review the {awaiting_review} draft(s) waiting in the Outbox."
+ next_up, next_tab = f"Review the {awaiting_review} draft(s) waiting in the Outbox.", "outbox"
elif by_hand:
- next_up = f"Open Campaigns and send the {len(by_hand)} unsent email(s)."
+ next_up, next_tab = f"Open Campaigns and send the {len(by_hand)} unsent email(s).", "campaigns"
elif profiled > checked:
- next_up = f"Find emails for the {profiled - checked} businesses not checked yet."
+ next_up, next_tab = f"Find emails for the {profiled - checked} businesses not checked yet.", "controls"
elif deliverable - drafted:
- next_up = f"Write first emails for {len(deliverable - drafted)} more contact(s)."
+ next_up, next_tab = f"Write first emails for {len(deliverable - drafted)} more contact(s).", "controls"
elif not companies:
- next_up = "Search for businesses to get started."
+ next_up, next_tab = "Search for businesses to get started.", "discover"
else:
- next_up = "Search more cities or industries to get more leads."
+ next_up, next_tab = "Search more cities or industries to get more leads.", "discover"
return {
"steps": steps,
"running": [dict(r, eta_text=_eta_text(r["eta_min"])) for r in running],
"stopped": stopped,
"next": next_up,
+ "next_tab": next_tab,
"cost_usd": round(cost, 4),
"updated_at": now.isoformat() + "Z",
}
@@ -1689,6 +1767,10 @@ async def get_today():
"SELECT COUNT(*) AS n FROM conversations WHERE status = 'open'"
)
open_convos = convos[0]["n"] if convos else 0
+ handed = await query_db(
+ "SELECT COUNT(*) AS n FROM conversations WHERE status = 'needs_human'"
+ )
+ needs_human = handed[0]["n"] if handed else 0
companies = await query_db("SELECT COUNT(*) AS n FROM companies")
n_companies = companies[0]["n"] if companies else 0
@@ -1700,10 +1782,25 @@ async def get_today():
"outbox_pending": len(pending),
"outbox_approved": len(approved),
"open_conversations": open_convos,
+ "needs_human": needs_human,
+ "signals_proposed": len(proposed),
+ "email_provider": _current_provider(),
"unprofiled": unprofiled_count,
}
# Ordered by how much it blocks Harvey from doing anything at all.
+ brain = await _brain_status()
+ if brain.get("status") == "paused":
+ who = "Codex" if brain.get("provider") == "codex" else "Harvey's model"
+ items.append({
+ "key": "brain-paused", "tone": "bad",
+ "title": f"{who} is paused, so Harvey is waiting",
+ "detail": (str(brain.get("reason") or "It can't be used right now.")[:300] +
+ " Replies and queued emails are untouched; Harvey resumes "
+ "once it's fixed. harvey status --check says what's wrong."),
+ "action": "Open the log", "tab": "controls",
+ })
+
if paused:
items.append({
"key": "paused", "tone": "bad",
@@ -1761,6 +1858,17 @@ async def get_today():
"action": "Read their sites", "tab": "discover",
})
+ if needs_human:
+ items.append({
+ "key": "needs-human", "tone": "bad",
+ "title": (f"{needs_human} conversation needs you" if needs_human == 1
+ else f"{needs_human} conversations need you"),
+ "detail": ("Harvey stopped and handed these over: an escalation, or a "
+ "reply it had no safe answer for. Reply yourself, then close "
+ "it or hand it back."),
+ "action": "Read them", "tab": "conversations",
+ })
+
if pending:
items.append({
"key": "outbox", "tone": "warn",
@@ -2012,7 +2120,19 @@ async def get_runs_api():
state = _state()
await state.init_db()
await state.sweep_stale_runs()
- return await state.get_runs(limit=25)
+ runs = await state.get_runs(limit=25)
+ # Same rule as the live panel: a "running" run that has recorded
+ # nothing for STALE_RUN_SECONDS has stopped, whatever its row says.
+ now = datetime.now(timezone.utc).replace(tzinfo=None)
+ for run in runs:
+ if run.get("status") != "running":
+ continue
+ last = _parse_ts(await _first(
+ "SELECT MAX(observed_at) AS t FROM observations WHERE run_id = ?",
+ (run["id"],))) or _parse_ts(run.get("started_at"))
+ if last and (now - last).total_seconds() > STALE_RUN_SECONDS:
+ run["status"] = "stalled"
+ return runs
except Exception as e:
return {"error": str(e)}
diff --git a/harvey/web/app.css b/harvey/web/app.css
index d441888..d5b0621 100644
--- a/harvey/web/app.css
+++ b/harvey/web/app.css
@@ -192,7 +192,7 @@ svg.icon { width: 16px; height: 16px; flex: none; stroke: currentColor; fill: no
/* ── App shell: sidebar + content ────────────────────────────── */
-.app { display: grid; grid-template-columns: var(--sidebar-w) minmax(0, 1fr); min-height: 100dvh; }
+.app { display: grid; grid-template-columns: var(--sidebar-w) minmax(0, 1fr); align-items: start; min-height: 100dvh; }
.sidebar {
position: sticky; top: 0; height: 100dvh;
@@ -202,15 +202,8 @@ svg.icon { width: 16px; height: 16px; flex: none; stroke: currentColor; fill: no
background: var(--bg);
overflow-y: auto; overscroll-behavior: contain;
}
-.brand { display: flex; align-items: center; gap: 10px; padding: 4px 6px; }
-.brand .mark {
- width: 28px; height: 28px; flex: none; border-radius: 8px;
- display: flex; align-items: center; justify-content: center;
- background: var(--accent); color: var(--accent-text);
- font-size: 15px; font-weight: 600; letter-spacing: -0.02em;
- box-shadow: var(--btn-primary-shadow);
-}
-.brand h1 { font-size: var(--fs-body); font-weight: 600; letter-spacing: -0.01em; line-height: 1.2; }
+.brand { display: flex; flex-direction: column; gap: 2px; padding: 4px 8px; }
+.brand h1 { font-size: 17px; font-weight: 650; letter-spacing: -0.025em; line-height: 1.15; }
.brand .tagline { font-size: var(--fs-caption); color: var(--text-3); line-height: 1.2; }
nav { display: flex; flex-direction: column; gap: var(--sp-4); }
@@ -602,7 +595,7 @@ tr:focus-within .row-action { opacity: 1; }
background: var(--surface-2); color: var(--text-2);
}
.tl-icon .icon { width: 13px; height: 13px; }
-.tl-text { font-size: var(--fs-ui); color: var(--text); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.tl-text { font-size: var(--fs-ui); color: var(--text); min-width: 0; overflow-wrap: anywhere; }
.tl-text::first-letter { text-transform: uppercase; }
.tl-agent { font-size: var(--fs-caption); color: var(--text-3); }
.tl-item.quiet .tl-text { color: var(--text-3); }
@@ -859,6 +852,8 @@ textarea.form-input { height: auto; padding: 8px 12px; }
}
.convo-head { display: flex; align-items: center; gap: var(--sp-3); margin-bottom: var(--sp-4); flex-wrap: wrap; }
.convo-head h3 { font-size: var(--fs-body); font-weight: 600; }
+.convo-head > div:nth-child(2) { min-width: 0; flex: 1 1 200px; }
+.convo-head h3, .convo-head .sub { overflow-wrap: anywhere; }
.convo-head .sub { font-size: var(--fs-caption); color: var(--text-3); }
.convo-head .tags { margin-left: auto; display: flex; gap: 6px; flex-wrap: wrap; }
.thread { display: flex; flex-direction: column; gap: var(--sp-2); }
@@ -953,7 +948,7 @@ textarea.form-input { height: auto; padding: 8px 12px; }
/* ── Small screens: the sidebar becomes a top bar ────────────── */
@media (max-width: 900px) {
- .app { grid-template-columns: minmax(0, 1fr); }
+ .app { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto 1fr; }
.sidebar {
position: sticky; top: 0; z-index: 20; height: auto; flex-direction: row; flex-wrap: wrap;
align-items: center; gap: var(--sp-2) var(--sp-3); padding: var(--sp-2) var(--sp-4);
@@ -978,3 +973,17 @@ textarea.form-input { height: auto; padding: 8px 12px; }
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { transition-duration: 0.01ms !important; animation-duration: 0.01ms !important; }
}
+
+/* Replies and scraped text are written by outsiders: a 3,000-character URL
+ must wrap inside its box, never push the page sideways. */
+.desk-pane .body, .thread-msg, .te-body, .td-body, .te-head span, .cell-main, .cell-sub { overflow-wrap: anywhere; }
+
+.convo-actions { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-top: var(--sp-4); padding-top: var(--sp-3); border-top: 1px solid var(--line); }
+.convo-actions .muted { display: inline-flex; align-items: center; gap: 6px; font-size: var(--fs-caption); margin-right: auto; }
+.convo-actions .btn-ghost { margin-left: auto; }
+.facts { display: flex; flex-wrap: wrap; gap: 4px 14px; padding: 10px 4px 0; margin-bottom: var(--sp-5); font-size: var(--fs-caption); color: var(--text-3); }
+.facts b { color: var(--text-2); font-weight: 600; font-variant-numeric: tabular-nums; }
+.cell-sub .verified { color: var(--good); font-weight: 600; }
+/* Long subjects end in an ellipsis; the card scrolls sideways if it must. */
+table.clip td { max-width: 320px; overflow: hidden; text-overflow: ellipsis; }
+.live-next .btn { margin-left: auto; }
diff --git a/harvey/web/app.js b/harvey/web/app.js
index 0ad7048..08513f9 100644
--- a/harvey/web/app.js
+++ b/harvey/web/app.js
@@ -42,6 +42,22 @@ function escHtml(s) {
));
}
+// A value placed inside an onclick handler as a JS string: JSON-quote it,
+// then escape for the attribute (escHtml alone is undone before the JS runs).
+function jsq(v) {
+ return escHtml(JSON.stringify(String(v ?? '')));
+}
+
+// The reason a failed action gave, or a fallback when it gave none.
+function failMsg(data, fallback) {
+ return (data && (data.message || data.error || data.detail)) || fallback;
+}
+
+// Lookup tables keyed by stored strings: "constructor" must not hit Object's.
+function own(table, key) {
+ return Object.prototype.hasOwnProperty.call(table, key) ? table[key] : undefined;
+}
+
// Links built from collected data (websites, profiles) open only as http(s):
// a javascript: URL from a scraped page must never run in the dashboard.
function safeHref(u) {
@@ -107,11 +123,12 @@ const STATUS = {
// runs
running: ['Running', 'active'],
stale: ['Stale', 'bad'],
+ stalled: ['Stopped', 'bad'],
};
function statusMeta(status) {
const key = String(status || '').toLowerCase().replace(/[^a-z0-9]+/g, '_');
- const hit = STATUS[key];
+ const hit = own(STATUS, key);
if (hit) return { label: hit[0], tone: hit[1] };
const label = String(status || 'unknown').replace(/_/g, ' ');
return { label: label.charAt(0).toUpperCase() + label.slice(1), tone: 'idle' };
@@ -125,7 +142,9 @@ function badge(status) {
function formatDate(d) {
if (!d) return '';
try {
- const dt = new Date(d);
+ let t = String(d).trim().replace(' ', 'T');
+ if (/^\d{4}-\d\d-\d\dT/.test(t) && !/[zZ]$|[+-]\d\d:?\d\d$/.test(t)) t += 'Z'; // stored UTC
+ const dt = new Date(t);
if (isNaN(dt)) return escHtml(d);
return dt.toLocaleString('en-US', {month:'short',day:'numeric',hour:'numeric',minute:'2-digit'});
} catch { return escHtml(d); }
@@ -140,7 +159,8 @@ function icon(name, cls) {
function initials(first, last) {
const a = String(first || '').trim(), b = String(last || '').trim();
- const s = (a.charAt(0) + b.charAt(0)) || a.slice(0, 2) || '?';
+ const ch = x => Array.from(x)[0] || ''; // whole characters, not UTF-16 halves
+ const s = (ch(a) + ch(b)) || '?';
return escHtml(s.toUpperCase());
}
@@ -157,11 +177,15 @@ function relTime(d) {
const dt = parseTs(d);
if (isNaN(dt)) return escHtml(d);
const mins = Math.round((Date.now() - dt) / 60000);
- if (mins < 1) return 'just now';
- if (mins < 60) return mins + 'm ago';
- if (mins < 60 * 24) return Math.round(mins / 60) + 'h ago';
- if (mins < 60 * 48) return 'Yesterday';
- return dt.toLocaleDateString('en-US', {month: 'short', day: 'numeric'});
+ if (mins < -1 && mins > -60) return 'in ' + -mins + 'm';
+ if (mins < -1 && mins > -60 * 24) return 'in ' + Math.round(-mins / 60) + 'h';
+ if (mins >= -1 && mins < 1) return 'just now';
+ if (mins >= 1 && mins < 60) return mins + 'm ago';
+ if (mins >= 60 && mins < 60 * 24) return Math.round(mins / 60) + 'h ago';
+ if (mins >= 60 * 24 && mins < 60 * 48) return 'Yesterday';
+ const opts = {month: 'short', day: 'numeric'};
+ if (dt.getFullYear() !== new Date().getFullYear()) opts.year = 'numeric';
+ return dt.toLocaleDateString('en-US', opts);
}
function dayLabel(d) {
@@ -240,6 +264,9 @@ function actionText(a) {
case 'manual_send': return 'You marked a contact as emailed by hand';
case 'manual_send_undone': return 'You undid a hand-sent mark';
case 'outbox_edited': return 'You edited a draft';
+ case 'conversation_status':
+ return d.to === 'closed' ? 'You closed a conversation'
+ : d.from === 'needs_human' ? 'You handed a conversation back to Harvey' : 'You reopened a conversation';
}
const text = escHtml(String(a.action_type || '').replace(/_/g, ' '));
return a.agent === 'main' ? 'Heartbeat: ' + text : text;
@@ -260,7 +287,13 @@ async function api(path, opts) {
try {
const r = await authFetch(path, opts);
if (await lockIfRefused(r)) return null;
- if (!r.ok) return null;
+ if (!r.ok) {
+ // An action the server refused says why ("a run is already going");
+ // pass that body on so the toast can show it. Reads stay null.
+ if (!opts || !opts.method || opts.method === 'GET') return null;
+ const body = await r.json().catch(() => null);
+ return body && typeof body === 'object' ? {success: false, ...body} : null;
+ }
return await r.json();
} catch {
return null;
@@ -392,9 +425,17 @@ async function loadToday() {
const data = await api('/api/today');
const el = document.getElementById('today-queue');
if (!data) { el.innerHTML = offlineState(); return; }
+ if (data.error) {
+ // A failed check must never read as "Nothing needs you".
+ el.innerHTML = emptyState(icon('alert'), 'Couldn\'t check what needs you',
+ 'The dashboard hit an error reading Harvey\'s data: ' + escHtml(data.error));
+ return;
+ }
navCount('nav-today', (data.items || []).filter(i => i.tone !== 'good').length);
navCount('nav-outbox', (data.stats || {}).outbox_pending || 0);
+ navCount('nav-signals', (data.stats || {}).signals_proposed || 0);
+ navCount('nav-conversations', (data.stats || {}).needs_human || 0);
_todayStats = data.stats || {};
renderFigures(_todayStats);
@@ -418,7 +459,7 @@ async function loadToday() {
'<div class="qtitle">' + escHtml(it.title) + '</div>' +
'<div class="qdetail">' + escHtml(it.detail) + '</div>' +
'</div>' +
- '<button class="btn btn-secondary btn-sm" onclick="goTab(\'' + escHtml(it.tab) + '\')">' +
+ '<button class="btn btn-secondary btn-sm" onclick="goTab(' + jsq(it.tab) + ')">' +
escHtml(it.action) + icon('arrow') + '</button>' +
'</div>';
}).join('') + '</div>';
@@ -469,7 +510,9 @@ async function loadLiveStatus() {
'<span class="setup-pct">Cost so far $' + Number(d.cost_usd || 0).toFixed(2) + '</span></div>' +
stoppedHtml +
'<div class="steps">' + rows + '</div>' +
- (d.next ? '<div class="live-next">' + icon('arrow') + '<span><b>Next</b> · ' + escHtml(d.next) + '</span></div>' : '') +
+ (d.next ? '<div class="live-next">' + icon('arrow') + '<span><b>Next</b> · ' + escHtml(d.next) + '</span>' +
+ (d.next_tab ? '<button class="btn btn-secondary btn-sm" onclick="goTab(' + jsq(d.next_tab) + ')">Go</button>' : '') +
+ '</div>' : '') +
'<div class="live-flag">Updated ' + new Date().toLocaleTimeString() + ' · refreshes every 10 seconds</div>';
}
@@ -485,15 +528,29 @@ function renderFigures(stats) {
'<div class="kpi-main"><span class="kpi-value' + (value ? '' : ' zero') + '">' + value + '</span>' + spark + '</div>' +
'<span class="kpi-note">' + note + '</span></div>';
+ // Instantly sends from its own servers, so the Outbox never sees them.
+ const sent = stats.email_provider === 'instantly'
+ ? card('Emails sent', '&mdash;', '', 'Instantly tracks sends')
+ : card('Emails sent', sum(t.sent), sparkBars(t.sent, 'Emails sent per day, last 14 days'),
+ 'last 14 days · <b>' + (stats.outbox_approved || 0) + '</b> scheduled');
+ const waiting = (stats.outbox_pending || 0) + (stats.needs_human || 0);
+ const waitNote = [
+ stats.outbox_pending ? stats.outbox_pending + ' to approve' : '',
+ stats.needs_human ? stats.needs_human + ' handed to you' : '',
+ ].filter(Boolean).join(' · ') || 'nothing to approve';
+ const facts = document.getElementById('today-facts');
+ if (facts) facts.innerHTML =
+ '<span><b>' + (stats.companies || 0) + '</b> companies</span>' +
+ '<span><b>' + (stats.unprofiled || 0) + '</b> sites not read yet</span>' +
+ '<span><b>' + (stats.signals_confirmed || 0) + '</b> signals on</span>';
+
el.innerHTML = '<div class="kpis">' +
card('Contacts found', stats.prospects || 0, sparkBars(t.found, 'Contacts found per day, last 14 days'),
'<b>+' + last7(t.found) + '</b> this week') +
- card('Emails sent', sum(t.sent), sparkBars(t.sent, 'Emails sent per day, last 14 days'),
- 'last 14 days · <b>' + (stats.outbox_approved || 0) + '</b> scheduled') +
+ sent +
card('Conversations', stats.open_conversations || 0, sparkBars(t.replies, 'New replies per day, last 14 days'),
'<b>' + sum(t.replies) + '</b> new in 14 days') +
- card('Waiting on you', stats.outbox_pending || 0, '',
- stats.outbox_pending ? 'drafts in the Outbox' : 'nothing to approve') +
+ card('Waiting on you', waiting, '', waitNote) +
'</div>';
}
@@ -501,7 +558,7 @@ let _todayStats = {};
let _trend = null;
async function loadTrend() {
- const t = await api('/api/trend?days=14');
+ const t = await api('/api/trend?days=14&tz=' + -new Date().getTimezoneOffset());
if (t && Array.isArray(t.days)) { _trend = t; renderFigures(_todayStats); }
}
@@ -510,18 +567,17 @@ async function loadFunnel() {
const el = document.getElementById('today-figures');
if (!el) return;
const data = await api('/api/stats');
- if (!data || data.error) { el.innerHTML = '<p class="muted" style="font-size:13px">No contacts yet.</p>'; return; }
- const by = (data.prospects || {}).by_status || {};
+ if (!data) return; // offline: keep the last numbers; Today's queue says so
+ if (data.error) { el.innerHTML = '<p class="muted" style="font-size:13px">Couldn\'t read the pipeline.</p>'; return; }
const total = (data.prospects || {}).total || 0;
- const n = keys => keys.reduce((x, k) => x + (by[k] || 0), 0);
- const known = ['new', 'queued', 'contacted', 'replied', 'interested', 'meeting'];
+ const pipe = data.pipeline || {};
const stages = [
- ['To write', n(['new', 'queued']), 'c-accent-soft'],
- ['Contacted', n(['contacted']), 'c-accent'],
- ['Replied', n(['replied']), 'c-active'],
- ['Interested', n(['interested']), 'c-good'],
- ['Meeting booked', n(['meeting']), 'c-note'],
- ['Closed out', total - n(known), 'c-idle'],
+ ['To write', pipe.to_write || 0, 'c-accent-soft'],
+ ['Contacted', pipe.contacted || 0, 'c-accent'],
+ ['Replied', pipe.replied || 0, 'c-active'],
+ ['Interested', pipe.interested || 0, 'c-good'],
+ ['Ready to meet', pipe.ready_to_meet || 0, 'c-note'],
+ ['Closed out', pipe.closed_out || 0, 'c-idle'],
];
if (!total) {
el.innerHTML = '<p class="muted" style="font-size:13px">No contacts yet. Scout adds them as it finds people.</p>';
@@ -543,15 +599,18 @@ async function loadTodayActivity() {
const el = document.getElementById('today-activity');
if (!el) return;
const data = await api('/api/activity');
- if (!Array.isArray(data) || !data.length) {
+ if (!Array.isArray(data)) return; // offline: Today's queue says so
+ // Heartbeats are noise here; the Activity tab keeps them.
+ const shown = data.filter(a => a.agent !== 'main').slice(0, 8);
+ if (!shown.length) {
el.innerHTML = '<p class="muted" style="font-size:13px">' +
'Nothing yet. Every action Harvey takes shows up here.</p>';
return;
}
- el.innerHTML = '<div class="timeline">' + data.filter(a => a.agent !== 'main').slice(0, 8).map(a =>
+ el.innerHTML = '<div class="timeline">' + shown.map(a =>
'<div class="tl-item">' +
'<span class="tl-time">' + relTime(a.created_at) + '</span>' +
- '<span class="tl-icon">' + icon(AGENT_ICONS[a.agent] || 'activity') + '</span>' +
+ '<span class="tl-icon">' + icon(own(AGENT_ICONS, a.agent) || 'activity') + '</span>' +
'<span class="tl-text">' + actionText(a) + '</span>' +
'<span class="tl-agent">' + escHtml(a.agent) + '</span>' +
'</div>').join('') + '</div>';
@@ -653,7 +712,9 @@ async function loadSignals() {
).join('') + '</div></div>';
grpEl.innerHTML = (data.groups || []).map(g => {
- const codes = g.signals.map(x => x.code);
+ // Only the undecided ones: "Confirm all" must never re-enable a signal
+ // you turned off (or "Skip all" turn off one you confirmed).
+ const pending = escHtml(JSON.stringify(g.signals.filter(x => x.status === 'proposed').map(x => x.code)));
const undecided = g.signals.filter(x => x.status === 'proposed').length;
return '<div class="sig-group">' +
'<div class="sig-group-head"><div>' +
@@ -661,10 +722,10 @@ async function loadSignals() {
'</div>' +
(undecided
? '<div style="display:flex;gap:6px;flex-shrink:0">' +
- '<button class="btn btn-primary btn-sm" onclick=\'setSignals(' +
- JSON.stringify(codes) + ", \"confirmed\")'>Confirm all " + undecided + '</button>' +
- '<button class="btn btn-secondary btn-sm" onclick=\'setSignals(' +
- JSON.stringify(codes) + ", \"rejected\")'>Skip all</button>" +
+ '<button class="btn btn-primary btn-sm" onclick="setSignals(' + pending +
+ ', \'confirmed\')">Confirm all ' + undecided + '</button>' +
+ '<button class="btn btn-secondary btn-sm" onclick="setSignals(' + pending +
+ ', \'rejected\')">Skip all ' + undecided + '</button>' +
'</div>'
: '') +
'</div>' +
@@ -686,15 +747,15 @@ function sigRow(sig) {
Math.round(sig.confidence_floor * 100) + '% confidence</span>' : '';
const decide = sig.status === 'confirmed'
- ? '<button class="btn btn-secondary btn-sm" onclick="setSignals([\'' + sig.code +
- '\'],\'rejected\')">Turn off</button>'
+ ? '<button class="btn btn-secondary btn-sm" onclick="setSignals([' + jsq(sig.code) +
+ '],\'rejected\')">Turn off</button>'
: sig.status === 'rejected'
- ? '<button class="btn btn-secondary btn-sm" onclick="setSignals([\'' + sig.code +
- '\'],\'confirmed\')">Turn on</button>'
- : '<button class="btn btn-primary btn-sm" onclick="setSignals([\'' + sig.code +
- '\'],\'confirmed\')">Confirm</button>' +
- '<button class="btn btn-secondary btn-sm" onclick="setSignals([\'' + sig.code +
- '\'],\'rejected\')">Skip</button>';
+ ? '<button class="btn btn-secondary btn-sm" onclick="setSignals([' + jsq(sig.code) +
+ '],\'confirmed\')">Turn on</button>'
+ : '<button class="btn btn-primary btn-sm" onclick="setSignals([' + jsq(sig.code) +
+ '],\'confirmed\')">Confirm</button>' +
+ '<button class="btn btn-secondary btn-sm" onclick="setSignals([' + jsq(sig.code) +
+ '],\'rejected\')">Skip</button>';
return '<div class="sig-row ' + (sig.status === 'rejected' ? 'rejected' : '') + '">' +
'<div class="sig-main">' +
@@ -724,7 +785,7 @@ async function setSignals(codes, status) {
: data.changed + ' signal' + (data.changed === 1 ? '' : 's') + ' turned off.',
'success');
} else {
- showToast('Could not update that signal.', 'error');
+ showToast(failMsg(data, 'Could not update that signal.'), 'error');
}
loadSignals();
}
@@ -745,7 +806,7 @@ async function loadDiscoverProviders() {
? '<span class="badge t-good">ready</span>'
: '<span class="badge t-waiting">needs a key</span>';
return '<div class="prov-card ' + (p.key === _provider ? 'selected' : '') +
- '" onclick="pickProvider(\'' + p.key + '\')">' +
+ '" onclick="pickProvider(' + jsq(p.key) + ')">' +
'<div class="prov-head"><h3>' + escHtml(p.label) + '</h3>' + ready + '</div>' +
'<div class="blurb">' + escHtml(p.blurb) + '</div>' +
'<div class="row"><span class="k">Cost</span><span class="v">' +
@@ -763,7 +824,9 @@ async function loadDiscoverProviders() {
}).join('') + '</div>';
const running = data.running;
- document.getElementById('disc-stop').style.display = running ? '' : 'none';
+ // Reading sites can't be stopped part-way; only a discovery run can.
+ document.getElementById('disc-stop').style.display = running && data.running_kind !== 'profile' ? '' : 'none';
+ renderProfileCard(data.unprofiled || 0, running);
if (running && !_discoverPoll) {
_discoverPoll = setInterval(loadDiscoverProviders, 4000);
} else if (!running && _discoverPoll) {
@@ -773,7 +836,7 @@ async function loadDiscoverProviders() {
const btn = document.getElementById('disc-run');
btn.disabled = true;
btn.textContent = 'Estimate first';
- showToast('Discovery finished.', 'success');
+ showToast(data.running_kind === 'profile' ? 'Finished reading websites.' : 'Discovery finished.', 'success');
}
renderDiscoverResult(data.last_report, running);
}
@@ -852,7 +915,34 @@ async function runDiscovery() {
async function stopDiscovery() {
const data = await api('/api/discover/stop', {method: 'POST'});
showToast(data && data.success ? 'Stopping after the current query.'
- : 'Could not stop.', data ? 'success' : 'error');
+ : failMsg(data, 'Could not stop.'), data && data.success ? 'success' : 'error');
+ loadDiscoverProviders();
+}
+
+// Companies found but not looked at: reading their sites is free and
+// model-free, and it is what makes an email specific.
+function renderProfileCard(pending, running) {
+ const el = document.getElementById('discover-profile');
+ if (!el) return;
+ if (!pending) { el.innerHTML = ''; return; }
+ el.innerHTML = '<div class="subhead">Read websites</div><div class="card"><div class="queue-item good" style="padding:0;border:0;box-shadow:none">' +
+ '<div class="qtext"><div class="qtitle">' + pending + ' compan' + (pending === 1 ? 'y' : 'ies') +
+ ' not looked at yet</div><div class="qdetail">Free, no account needed. Harvey reads each site for ' +
+ 'who their agency is, what they are missing, and whether they run ads. Up to 200 per run.</div></div>' +
+ '<button class="btn btn-primary btn-sm" onclick="runProfile(this)"' + (running ? ' disabled' : '') + '>' +
+ (running ? 'Busy…' : 'Read their sites') + '</button></div></div>';
+}
+
+async function runProfile(btn) {
+ btn.disabled = true;
+ btn.textContent = 'Starting…';
+ const data = await api('/api/profile/run', {method: 'POST'});
+ if (data && data.success) {
+ showToast(data.pending ? 'Reading ' + Math.min(data.pending, 200) + ' websites.' : 'Every site is already read.', 'success');
+ if (data.pending && !_discoverPoll) _discoverPoll = setInterval(loadDiscoverProviders, 4000);
+ } else {
+ showToast(failMsg(data, 'Could not start.'), 'error');
+ }
loadDiscoverProviders();
}
@@ -871,12 +961,21 @@ function renderDiscoverResult(report, running) {
'<div class="value"' + (tone ? ' style="color:var(--' + tone + ')"' : '') + '>' +
value + '</div></div>';
+ if (report.profiled_companies !== undefined && report.new_companies === undefined) {
+ el.innerHTML = '<div class="subhead">Last run</div><div class="stats-grid">' +
+ stat('Websites read', report.profiled_companies || 0, 'accent') +
+ stat('Facts recorded', report.profile_observations || 0) +
+ stat('Cost', 'free') + '</div>' +
+ (report.stopped ? '<div class="test-result error" style="margin-top:14px">Stopped early: ' + escHtml(report.stopped) + '</div>' : '');
+ return;
+ }
el.innerHTML = '<div class="subhead">Last run</div>' +
'<div class="stats-grid">' +
stat('New companies', report.new_companies || 0, 'accent') +
stat('Already known', report.known_companies || 0) +
stat('Observations', report.observations || 0) +
stat('Filtered as junk', report.junk || 0) +
+ (report.profiled_companies ? stat('Websites read', report.profiled_companies) : '') +
stat('Actual cost', report.actual_cost ? '$' + report.actual_cost.toFixed(4) : 'free') +
'</div>' +
(report.stopped ? '<div class="test-result error" style="margin-top:14px">' +
@@ -917,7 +1016,7 @@ function renderCohortBuilder() {
confirmed.map(s =>
'<label class="cohort-pick"><input type="checkbox" ' +
(_cohort[key].has(s.code) ? 'checked ' : '') +
- 'onchange="toggleCohort(\'' + key + '\',\'' + s.code + '\',this.checked)">' +
+ 'onchange="toggleCohort(\'' + key + '\',' + jsq(s.code) + ',this.checked)">' +
'<span>' + escHtml(s.label || s.code) + '</span>' +
'<span class="n">' + (s.companies || 0) + '</span></label>'
).join('') + '</div></div>';
@@ -954,7 +1053,10 @@ async function runCohort() {
offset: offset, limit: COHORT_PAGE}),
});
if (generation !== _cohortGeneration) return;
- if (!data) { el.innerHTML = ''; return; }
+ if (!data || data.error) {
+ el.innerHTML = data ? '<div class="test-result error">' + escHtml(data.error) + '</div>' : '';
+ return;
+ }
let html = '<div style="border-top:1px solid var(--border);margin-top:20px;padding-top:20px">' +
'<div class="cohort-size">' + data.size + '</div>' +
@@ -1121,8 +1223,11 @@ async function saveEnv(payload, okMsg) {
else showToast((data && data.message) || 'Save failed — is the dashboard still running?', 'error');
}
+// Secrets are only sent when typed: an empty box means "keep the saved one".
function saveInstantly() {
- saveEnv({INSTANTLY_API_KEY: document.getElementById('instantly-key').value.trim()}, 'Instantly API key saved.');
+ const key = document.getElementById('instantly-key').value.trim();
+ if (!key) { showToast('Enter a new key first. The saved one is kept.', 'error'); return; }
+ saveEnv({INSTANTLY_API_KEY: key}, 'Instantly API key saved.');
}
function saveLinkedIn() {
@@ -1133,10 +1238,10 @@ function saveLinkedIn() {
}
function saveCloudflare() {
- saveEnv({
- CLOUDFLARE_ACCOUNT_ID: document.getElementById('cf-account-id').value.trim(),
- CLOUDFLARE_API_TOKEN: document.getElementById('cf-api-token').value.trim()
- }, 'Cloudflare credentials saved.');
+ const payload = {CLOUDFLARE_ACCOUNT_ID: document.getElementById('cf-account-id').value.trim()};
+ const token = document.getElementById('cf-api-token').value.trim();
+ if (token) payload.CLOUDFLARE_API_TOKEN = token;
+ saveEnv(payload, 'Cloudflare credentials saved.');
}
async function testInstantly() {
@@ -1151,7 +1256,7 @@ async function testInstantly() {
el.innerHTML = '<div class="test-result error">Could not reach the dashboard server.</div>';
return;
}
- el.innerHTML = '<div class="test-result ' + (data.success ? 'success' : 'error') + '">' + escHtml(data.message) + '</div>';
+ el.innerHTML = '<div class="test-result ' + (data.success ? 'success' : 'error') + '">' + escHtml(failMsg(data, '')) + '</div>';
}
// ── Controls ──
@@ -1223,35 +1328,6 @@ async function loadLogs() {
// ── Pipeline data ──
-async function loadStats() {
- const grid = document.getElementById('stats-grid');
- const data = await api('/api/stats');
- if (!data) { grid.innerHTML = offlineState(); return; }
- if (data.error) {
- grid.innerHTML = emptyState('&#9670;', 'No pipeline data yet',
- 'Start Harvey from the <b>Controls</b> tab and it will begin prospecting, writing, and sending on its own.');
- return;
- }
- const p = data.prospects || {}, c = data.campaigns || {}, v = data.conversations || {};
- const chips = (map) => {
- const entries = Object.entries(map || {});
- if (!entries.length) return '<span class="chip muted">none yet</span>';
- return entries.map(([k, n]) =>
- '<span class="chip">' + escHtml(k) + ' <b>' + escHtml(String(n)) + '</b></span>'
- ).join('');
- };
- const card = (label, value, breakdown) =>
- '<div class="stat-card"><div class="label">' + label + '</div>' +
- '<div class="value">' + value + '</div>' +
- '<div class="breakdown">' + breakdown + '</div></div>';
-
- grid.innerHTML =
- card('Prospects', p.total || 0, chips(p.by_status)) +
- card('Campaigns', c.total || 0, chips(c.by_status)) +
- card('Conversations', v.total || 0, chips(v.by_status)) +
- card('Actions Logged', data.actions_total || 0, brainCallChips(data));
-}
-
// Calls today per subscription — each labelled with the provider it ran on.
function brainCallChips(data) {
const chip = (label, n) => '<span class="chip">' + label + ' calls today <b>' + escHtml(String(n || 0)) + '</b></span>';
@@ -1282,7 +1358,7 @@ function emailTag(p) {
if (!p.email) return '';
// Fall back to the legacy boolean for rows predating email_status.
const status = p.email_status || (p.email_verified ? 'verified' : 'guess');
- if (!STATUS[status]) return '';
+ if (!own(STATUS, status)) return '';
const m = statusMeta(status);
return ' <span class="mini t-' + m.tone + '" title="Email ' + escHtml(m.label.toLowerCase()) + '">' +
escHtml(m.label) + '</span>';
@@ -1411,6 +1487,12 @@ async function loadOutbox() {
const list = document.getElementById('outbox-list');
const actions = document.getElementById('outbox-actions');
if (!data) { desk.innerHTML = offlineState(); list.innerHTML = ''; return; }
+ if (data.error) {
+ // Never let a failed read pass for "Nothing to review".
+ desk.innerHTML = emptyState(icon('alert'), 'Couldn\'t read the Outbox', escHtml(data.error));
+ list.innerHTML = '';
+ return;
+ }
const pending = data.pending || [];
_desk.items = pending;
@@ -1441,7 +1523,9 @@ async function loadOutbox() {
? '<div class="banner bad">' + icon('alert') + '<div><b>Sending is paused</b>' +
'<p>' + escHtml(data.paused) + '. Approved mail stays queued until you resume.</p></div></div>'
: '';
- if (data.compliance_notice) {
+ // Only once there is mail to warn about: a fresh install sends nothing.
+ const anyMail = pending.length || (data.approved || []).length || (data.sent || []).length;
+ if (data.compliance_notice && anyMail) {
banner.innerHTML +=
'<div class="banner wait">' + icon('alert') + '<div><b>Add your postal address</b>' +
'<p>' + escHtml(data.compliance_notice) + '</p></div></div>';
@@ -1455,7 +1539,7 @@ async function loadOutbox() {
const table = (title, rows, cols) => {
if (!rows || !rows.length) return '';
let h = '<div class="subhead">' + title + ' <span class="hint">' + rows.length + '</span></div>' +
- '<div class="table-card"><table><thead><tr>' +
+ '<div class="table-card"><table class="nowrap clip"><thead><tr>' +
cols.map(c => '<th>' + c[0] + '</th>').join('') + '</tr></thead><tbody>';
for (const r of rows) {
h += '<tr>' + cols.map(c => '<td' + (c[2] ? ' class="muted"' : '') + '>' +
@@ -1550,13 +1634,13 @@ function renderDesk(items, i) {
? '<div class="desk-footer" title="Added when it sends (compliance in harvey.yaml)">' +
escHtml(added) + '</div>' : '';
const actions = editing
- ? '<button class="btn btn-primary" onclick="deskSave(\'' + cur.id + '\')">Save</button>' +
+ ? '<button class="btn btn-primary" onclick="deskSave(' + jsq(cur.id) + ')">Save</button>' +
'<button class="btn btn-secondary" onclick="deskEdit(null)">Cancel</button>'
- : '<button class="btn btn-primary" onclick="outboxAct(\'' + cur.id + '\',\'approve\')">' +
+ : '<button class="btn btn-primary" onclick="outboxAct(' + jsq(cur.id) + ',\'approve\')">' +
'Approve <kbd>A</kbd></button>' +
- '<button class="btn btn-secondary" onclick="deskEdit(\'' + cur.id + '\')">' +
+ '<button class="btn btn-secondary" onclick="deskEdit(' + jsq(cur.id) + ')">' +
'Edit <kbd>E</kbd></button>' +
- '<button class="btn btn-secondary" onclick="outboxAct(\'' + cur.id + '\',\'reject\')">' +
+ '<button class="btn btn-secondary" onclick="outboxAct(' + jsq(cur.id) + ',\'reject\')">' +
'Reject <kbd>R</kbd></button>';
return '<div class="desk">' +
@@ -1652,7 +1736,7 @@ async function outboxAct(id, action) {
if (deskBusy()) return;
const data = await api('/api/outbox/' + encodeURIComponent(id) + '/' + action, {method: 'POST'});
if (data && data.success) showToast(action === 'approve' ? 'Approved — will send on schedule.' : 'Rejected.', 'success');
- else showToast('Action failed.', 'error');
+ else showToast(failMsg(data, 'Action failed.'), 'error');
loadOutbox();
}
@@ -1660,14 +1744,14 @@ async function outboxApproveAll() {
if (deskBusy()) return;
const data = await api('/api/outbox/approve-all', {method: 'POST'});
if (data && data.success) showToast('Approved ' + data.approved + ' email(s).', 'success');
- else showToast('Approve-all failed.', 'error');
+ else showToast(failMsg(data, 'Approve-all failed.'), 'error');
loadOutbox();
}
async function sendingToggle(action) {
const data = await api('/api/sending/' + action, {method: 'POST'});
if (data && data.success) showToast(action === 'pause' ? 'Sending paused.' : 'Sending resumed.', 'success');
- else showToast('Failed.', 'error');
+ else showToast(failMsg(data, action === 'pause' ? 'Could not pause sending.' : 'Could not resume sending.'), 'error');
loadOutbox();
}
@@ -1679,7 +1763,8 @@ async function loadCompanies() {
_companies = data;
if (!data.length) {
el.innerHTML = emptyState(icon('companies'), 'No companies yet',
- 'Harvey\'s Scout agent hasn\'t researched any companies. Finish <b>Setup</b>, then start Harvey from the <b>Controls</b> tab.');
+ 'Confirm your <b>Signals</b>, then find businesses on the <b>Discover</b> tab. ' +
+ 'OpenStreetMap is free and needs no account.');
return;
}
let html = '<div class="table-card"><table class="nowrap"><thead><tr><th>Company</th><th>Industry</th>' +
@@ -1740,7 +1825,7 @@ async function submitFeedback(entityType, entityId, promptText) {
method: 'POST', headers: {'Content-Type': 'application/json'},
body: JSON.stringify({entity_type: entityType, entity_id: entityId, comment: comment})
});
- if (data && data.success) showToast('Feedback saved. Harvey will take it into account.', 'success');
+ if (data && data.success) showToast('Feedback saved.', 'success');
else showToast((data && data.message) || 'Could not save feedback.', 'error');
}
@@ -1782,6 +1867,8 @@ async function loadProspects() {
'aria-label="Search contacts" oninput="_contactQuery=this.value;renderContacts()"></label>' +
'<div class="segmented" id="contact-filters" role="group" aria-label="Filter by status"></div>' +
'</div><div id="contact-rows"></div>';
+ // A rebuild after an offline blip must show the search still applied.
+ document.getElementById('contact-search').value = _contactQuery;
}
renderContacts();
}
@@ -1800,14 +1887,14 @@ function renderContacts() {
const rowsEl = document.getElementById('contact-rows');
const filtersEl = document.getElementById('contact-filters');
if (!rowsEl) return;
+ const q = _contactQuery.trim().toLowerCase();
+ const found = p => !q || [p.first_name, p.last_name, p.company, p.email, p.title].join(' ').toLowerCase().includes(q);
filtersEl.innerHTML = CONTACT_FILTERS.map(f =>
- '<button class="' + (f[0] === _contactFilter ? 'on' : '') + '" onclick="setContactFilter(\'' + f[0] + '\')">' +
- f[1] + ' <span class="n">' + _prospects.filter(p => contactMatches(p, f[0])).length + '</span></button>'
+ '<button class="' + (f[0] === _contactFilter ? 'on' : '') + '" aria-pressed="' + (f[0] === _contactFilter) + '" onclick="setContactFilter(\'' + f[0] + '\')">' +
+ f[1] + ' <span class="n">' + _prospects.filter(p => contactMatches(p, f[0]) && found(p)).length + '</span></button>'
).join('');
- const q = _contactQuery.trim().toLowerCase();
- const rows = _prospects.map((p, i) => [p, i]).filter(([p]) => contactMatches(p, _contactFilter) &&
- (!q || [p.first_name, p.last_name, p.company, p.email, p.title].join(' ').toLowerCase().includes(q)));
+ const rows = _prospects.map((p, i) => [p, i]).filter(([p]) => contactMatches(p, _contactFilter) && found(p));
if (!rows.length) {
rowsEl.innerHTML = '<div class="table-card">' + emptyState(icon('discover'), 'No matches',
'Nothing matches that search and filter.') + '</div>';
@@ -1821,7 +1908,9 @@ function renderContacts() {
'<span class="cell-sub">' + escHtml(p.title) + '</span></div></div></td>' +
'<td>' + escHtml(p.company) + '</td>' +
'<td><div class="cell-stack"><span>' + escHtml(p.email) + '</span>' +
- '<span class="cell-sub">' + emailTag(p) + (p.phone ? ' · ' + escHtml(p.phone) : '') + '</span>' +
+ '<span class="cell-sub">' + [emailTag(p).trim(), p.phone ? escHtml(p.phone) +
+ (p.phone_verified ? ' <span class="verified" title="Phone verified">&#10003;</span>' : '') : '']
+ .filter(Boolean).join(' · ') + '</span>' +
'</div></td>' +
'<td>' + (p.score || p.score === 0 ? meterHtml(p.score) : '') + '</td>' +
'<td>' + badge(p.status) + '</td>' +
@@ -1904,6 +1993,7 @@ async function markSent(ci, ri, sent) {
const ok = !!(res && res.success);
if (!ok) showToast((res && res.message) || 'Could not save that. Try again.', 'error');
else if (!sent && res.sent) showToast('They already replied, so this stays marked as sent.');
+ else showToast(sent ? 'Marked as sent by you.' : 'Unmarked.', 'success');
loadCampaigns();
// True only when this call changed it: a status means they replied or
// opted out, 'already' means another click or tab got there first.
@@ -1968,7 +2058,7 @@ async function loadCampaigns() {
: '';
}
const risky = r.email_status === 'risky'
- ? ' <span class="mini t-waiting" title="Catch-all address: it may bounce">Catch-all</span>' : '';
+ ? ' <span class="mini t-waiting">Catch-all, may bounce</span>' : '';
return '<span class="rcpt-who">' + escHtml(r.email) + risky + '</span>' +
'<button class="btn btn-secondary btn-sm" onclick="openInGmail(' + i + ',' + s + ',' + ri + ')">' +
'Open in Gmail</button>' +
@@ -2030,10 +2120,13 @@ function renderConversations() {
const el = document.getElementById('conversations-list');
const filter = CONVO_FILTERS.find(f => f[0] === _convoFilter) || CONVO_FILTERS[3];
const bar = '<div class="toolbar"><div class="segmented" role="group" aria-label="Filter conversations">' +
- CONVO_FILTERS.map(f => '<button class="' + (f[0] === filter[0] ? 'on' : '') +
+ CONVO_FILTERS.map(f => '<button class="' + (f[0] === filter[0] ? 'on' : '') + '" aria-pressed="' + (f[0] === filter[0]) +
'" onclick="setConvoFilter(\'' + f[0] + '\')">' + f[1] + ' <span class="n">' +
_convos.filter(f[2]).length + '</span></button>').join('') + '</div></div>';
- const shown = _convos.filter(filter[2]);
+ // Handed-to-you first, then drafts waiting; otherwise newest first (as served).
+ const rank = c => c.status === 'needs_human' ? 0 : c.draft ? 1 : 2;
+ const shown = _convos.filter(filter[2]).map((c, i) => [c, i])
+ .sort((a, b) => rank(a[0]) - rank(b[0]) || a[1] - b[1]).map(x => x[0]);
if (!shown.length) {
el.innerHTML = bar + '<div class="card">' + emptyState(icon('check'), 'Nothing here',
'No conversation matches this filter.') + '</div>';
@@ -2045,7 +2138,9 @@ function renderConversations() {
function convoCard(c) {
const items = (c.emails || []).map(e => ({ts: e.sent_at, email: e}))
.concat((c.thread || []).map(m => ({ts: m.timestamp, msg: m})))
- .sort((a, b) => parseTs(a.ts) - parseTs(b.ts));
+ .map(it => ({...it, key: +parseTs(it.ts)}))
+ // An item with no time goes last instead of scrambling the order.
+ .sort((a, b) => (isNaN(a.key) ? Infinity : a.key) - (isNaN(b.key) ? Infinity : b.key) || 0);
const first = c.first_name || 'Them';
const thread = items.map(it => {
if (it.email) {
@@ -2065,14 +2160,47 @@ function convoCard(c) {
'<button class="btn btn-primary btn-sm" onclick="goTab(\'outbox\')">Review in Outbox' + icon('arrow') + '</button></div>'
: '';
const name = [c.first_name, c.last_name].filter(Boolean).join(' ') || 'Unknown';
- const stage = STAGE_LABELS[c.stage] ? '<span class="tag">' + STAGE_LABELS[c.stage] + '</span>' : '';
+ const stage = own(STAGE_LABELS, c.stage) ? '<span class="tag">' + STAGE_LABELS[c.stage] + '</span>' : '';
return '<div class="convo-card"><div class="convo-head">' +
'<span class="avatar">' + initials(c.first_name, c.last_name) + '</span>' +
'<div><h3>' + escHtml(name) + '</h3><div class="sub">' +
escHtml([c.company, c.prospect_email].filter(Boolean).join(' · ')) + ' · ' + relTime(c.updated_at) + '</div></div>' +
- '<div class="tags">' + (c.intent ? badge(c.intent) : '') + stage + badge(c.status) + '</div></div>' +
+ // An escalation's intent badge says the same as its status: show one.
+ '<div class="tags">' + (c.intent && !(c.status === 'needs_human' && c.intent === 'escalate') ? badge(c.intent) : '') +
+ stage + badge(c.status) + '</div></div>' +
'<div class="thread">' + (thread || '<p class="muted" style="font-size:13px">No messages in this thread yet.</p>') +
- draft + '</div></div>';
+ draft + '</div>' + convoActions(c) + '</div>';
+}
+
+// Harvey answers new replies only on open conversations: an escalated one
+// waits for you to reply yourself, then close it or hand it back.
+function convoActions(c) {
+ if (c.status === 'needs_human') {
+ return '<div class="convo-actions"><span class="muted">' + icon('alert') +
+ 'Harvey handed this to you. Reply from your inbox, then:</span>' +
+ '<button class="btn btn-secondary btn-sm" onclick="setConvoStatus(' + jsq(c.id) + ',\'open\')">Hand back to Harvey</button>' +
+ '<button class="btn btn-secondary btn-sm" onclick="setConvoStatus(' + jsq(c.id) + ',\'closed\')">Close</button></div>';
+ }
+ if (c.status === 'open') {
+ return '<div class="convo-actions"><button class="btn btn-ghost btn-sm" onclick="setConvoStatus(' +
+ jsq(c.id) + ',\'closed\')">Close conversation</button></div>';
+ }
+ if (c.status === 'closed') {
+ return '<div class="convo-actions"><button class="btn btn-ghost btn-sm" onclick="setConvoStatus(' +
+ jsq(c.id) + ',\'open\')">Reopen</button></div>';
+ }
+ return '';
+}
+
+async function setConvoStatus(id, status) {
+ const data = await api('/api/conversations/' + encodeURIComponent(id) + '/status', {
+ method: 'POST', headers: {'Content-Type': 'application/json'},
+ body: JSON.stringify({status: status}),
+ });
+ if (data && data.success) showToast(status === 'open' ? 'Open again. Harvey will answer the next reply.' : 'Closed. A new reply starts a new conversation.', 'success');
+ else showToast(failMsg(data, 'Could not update that conversation.'), 'error');
+ loadConversations();
+ loadToday();
}
async function loadActivity() {
@@ -2090,7 +2218,7 @@ async function loadActivity() {
const label = dayLabel(a.created_at);
if (label !== day) { day = label; html += '<div class="tl-day">' + escHtml(label) + '</div>'; }
html += '<div class="tl-item' + (a.agent === 'main' ? ' quiet' : '') + '"><span class="tl-time">' + timeOfDay(a.created_at) + '</span>' +
- '<span class="tl-icon">' + icon(AGENT_ICONS[a.agent] || 'activity') + '</span>' +
+ '<span class="tl-icon">' + icon(own(AGENT_ICONS, a.agent) || 'activity') + '</span>' +
'<span class="tl-text">' + actionText(a) + '</span>' +
'<span class="tl-agent">' + escHtml(a.agent) + '</span></div>';
}
diff --git a/harvey/web/index.html b/harvey/web/index.html
index 4698515..24ab37d 100644
--- a/harvey/web/index.html
+++ b/harvey/web/index.html
@@ -63,35 +63,32 @@
<aside class="sidebar">
<div class="brand">
- <div class="mark">H</div>
- <div>
- <h1>Harvey</h1>
- <div class="tagline">Always Be Closing</div>
- </div>
+ <h1>Harvey</h1>
+ <div class="tagline">Always Be Closing</div>
</div>
<nav aria-label="Sections">
<div class="nav-group">
<div class="nav-label">Work</div>
- <button class="active" onclick="showTab('today', this)"><svg class="icon"><use href="#i-today"/></svg><span class="label">Today</span><span class="nav-count" id="nav-today"></span></button>
- <button onclick="showTab('outbox', this)"><svg class="icon"><use href="#i-outbox"/></svg><span class="label">Outbox</span><span class="nav-count" id="nav-outbox"></span></button>
- <button onclick="showTab('conversations', this)"><svg class="icon"><use href="#i-conversations"/></svg><span class="label">Conversations</span></button>
+ <button class="active" onclick="showTab('today', this)"><svg class="icon" aria-hidden="true"><use href="#i-today"/></svg><span class="label">Today</span><span class="nav-count" id="nav-today"></span></button>
+ <button onclick="showTab('outbox', this)"><svg class="icon" aria-hidden="true"><use href="#i-outbox"/></svg><span class="label">Outbox</span><span class="nav-count" id="nav-outbox"></span></button>
+ <button onclick="showTab('conversations', this)"><svg class="icon" aria-hidden="true"><use href="#i-conversations"/></svg><span class="label">Conversations</span><span class="nav-count" id="nav-conversations"></span></button>
</div>
<div class="nav-group">
<div class="nav-label">Pipeline</div>
- <button onclick="showTab('signals', this)"><svg class="icon"><use href="#i-signals"/></svg><span class="label">Signals</span><span class="nav-count" id="nav-signals"></span></button>
- <button onclick="showTab('discover', this)"><svg class="icon"><use href="#i-discover"/></svg><span class="label">Discover</span></button>
- <button onclick="showTab('companies', this)"><svg class="icon"><use href="#i-companies"/></svg><span class="label">Companies</span></button>
- <button onclick="showTab('prospects', this)"><svg class="icon"><use href="#i-contacts"/></svg><span class="label">Contacts</span></button>
- <button onclick="showTab('campaigns', this)"><svg class="icon"><use href="#i-campaigns"/></svg><span class="label">Campaigns</span></button>
+ <button onclick="showTab('signals', this)"><svg class="icon" aria-hidden="true"><use href="#i-signals"/></svg><span class="label">Signals</span><span class="nav-count" id="nav-signals"></span></button>
+ <button onclick="showTab('discover', this)"><svg class="icon" aria-hidden="true"><use href="#i-discover"/></svg><span class="label">Discover</span></button>
+ <button onclick="showTab('companies', this)"><svg class="icon" aria-hidden="true"><use href="#i-companies"/></svg><span class="label">Companies</span></button>
+ <button onclick="showTab('prospects', this)"><svg class="icon" aria-hidden="true"><use href="#i-contacts"/></svg><span class="label">Contacts</span></button>
+ <button onclick="showTab('campaigns', this)"><svg class="icon" aria-hidden="true"><use href="#i-campaigns"/></svg><span class="label">Campaigns</span></button>
</div>
<div class="nav-group">
<div class="nav-label">System</div>
- <button onclick="showTab('activity', this)"><svg class="icon"><use href="#i-activity"/></svg><span class="label">Activity</span></button>
- <button onclick="showTab('usage', this)"><svg class="icon"><use href="#i-usage"/></svg><span class="label">Usage</span></button>
- <button onclick="showTab('controls', this)"><svg class="icon"><use href="#i-controls"/></svg><span class="label">Controls</span></button>
- <button onclick="showTab('settings', this)"><svg class="icon"><use href="#i-settings"/></svg><span class="label">Settings</span></button>
- <button onclick="showTab('help', this)"><svg class="icon"><use href="#i-help"/></svg><span class="label">Help</span></button>
+ <button onclick="showTab('activity', this)"><svg class="icon" aria-hidden="true"><use href="#i-activity"/></svg><span class="label">Activity</span></button>
+ <button onclick="showTab('usage', this)"><svg class="icon" aria-hidden="true"><use href="#i-usage"/></svg><span class="label">Usage</span></button>
+ <button onclick="showTab('controls', this)"><svg class="icon" aria-hidden="true"><use href="#i-controls"/></svg><span class="label">Controls</span></button>
+ <button onclick="showTab('settings', this)"><svg class="icon" aria-hidden="true"><use href="#i-settings"/></svg><span class="label">Settings</span></button>
+ <button onclick="showTab('help', this)"><svg class="icon" aria-hidden="true"><use href="#i-help"/></svg><span class="label">Help</span></button>
</div>
</nav>
@@ -138,6 +135,7 @@
<aside>
<div class="subhead">Contacts by stage</div>
<div class="card" id="today-figures"></div>
+ <div class="facts" id="today-facts"></div>
<div id="today-runs-block">
<div class="subhead">Collector runs</div>
<div class="card" id="today-runs" style="padding-top:8px;padding-bottom:8px"></div>
@@ -178,6 +176,8 @@
then run it &mdash; nothing is called until you press the button.</p>
</div>
</div>
+ <div id="discover-profile"></div>
+
<div class="subhead">Source</div>
<div id="discover-providers"></div>
@@ -224,7 +224,7 @@
<div class="section-head">
<div><h2>Contacts</h2><p>People Harvey has found, how sure it is of their address, and where each one stands.</p></div>
<div class="page-actions">
- <button class="btn btn-secondary btn-sm" onclick="downloadCsv('/api/export/prospects.csv', 'prospects.csv', this)"><svg class="icon"><use href="#i-download"/></svg>Export deliverable</button>
+ <button class="btn btn-secondary btn-sm" onclick="downloadCsv('/api/export/prospects.csv', 'prospects.csv', this)"><svg class="icon" aria-hidden="true"><use href="#i-download"/></svg>Export deliverable</button>
<button class="btn btn-ghost btn-sm" onclick="downloadCsv('/api/export/prospects.csv?all=true', 'prospects-all.csv', this)">Export all</button>
</div>
</div>
@@ -407,7 +407,7 @@
</div>
</div>
<div class="card">
- <h2>Recent logs <button class="btn btn-ghost btn-sm" onclick="loadLogs()" style="margin-left:auto"><svg class="icon"><use href="#i-refresh"/></svg>Refresh</button></h2>
+ <h2>Recent logs <button class="btn btn-ghost btn-sm" onclick="loadLogs()" style="margin-left:auto"><svg class="icon" aria-hidden="true"><use href="#i-refresh"/></svg>Refresh</button></h2>
<div class="log-viewer" id="log-viewer">No logs yet. Start Harvey to see activity.</div>
</div>
</div>
@@ -503,7 +503,7 @@
<details>
<summary>Codex calls fail</summary>
- <div class="faq-body">With <code>brain.provider: codex</code>, set <code>brain.model</code> to an available model ID, including Luna, Sol, or Terra (for example <code>gpt-6.1-sol</code>), or leave it blank to select a listed model. Harvey runs these models without tools; <code>gpt-5.5</code> also remains supported when present in your account's catalog. Run <code>codex login</code> and choose "Sign in with ChatGPT" (API-key logins are refused). Harvey never renews your Codex login: if the log says it has expired or is due for renewal, use Codex once or run <code>codex login</code>. Harvey needs Codex CLI 0.159.3 on macOS or Linux (Codex isn't supported on Windows; use Claude there) and refuses other versions. While Codex can't be used, Harvey pauses (the Actions card shows "Codex paused" and why), leaves replies and queued emails untouched, and resumes once it's fixed; <code>harvey status --check</code> checks on demand. If the log says isolation could not be verified, a Codex config layer is forcing a tool, hook, MCP server or custom endpoint back on — Harvey refuses to send prompts until it is removed. Harvey never falls back to Claude on its own.</div>
+ <div class="faq-body">With <code>brain.provider: codex</code>, set <code>brain.model</code> to an available model ID, including Luna, Sol, or Terra (for example <code>gpt-6.1-sol</code>), or leave it blank to select a listed model. Harvey runs these models without tools; <code>gpt-5.5</code> also remains supported when present in your account's catalog. Run <code>codex login</code> and choose "Sign in with ChatGPT" (API-key logins are refused). Harvey never renews your Codex login: if the log says it has expired or is due for renewal, use Codex once or run <code>codex login</code>. Harvey needs Codex CLI 0.159.3 on macOS or Linux (Codex isn't supported on Windows; use Claude there) and refuses other versions. While Codex can't be used, Harvey pauses (Today shows "Codex is paused" and why), leaves replies and queued emails untouched, and resumes once it's fixed; <code>harvey status --check</code> checks on demand. If the log says isolation could not be verified, a Codex config layer is forcing a tool, hook, MCP server or custom endpoint back on — Harvey refuses to send prompts until it is removed. Harvey never falls back to Claude on its own.</div>
</details>
<details>
diff --git a/tests/test_dashboard_conversations.py b/tests/test_dashboard_conversations.py
index 6adf5af..d52058c 100644
--- a/tests/test_dashboard_conversations.py
+++ b/tests/test_dashboard_conversations.py
@@ -52,3 +52,39 @@ def test_a_conversation_without_emails_or_draft(client):
_sql(client.db_path, "INSERT INTO conversations (id, prospect_id, thread_json, status) VALUES ('c9', 'p9', '[]', 'open')")
[convo] = client.get("/api/conversations").json()
assert convo["emails"] == [] and convo["draft"] is None
+
+
+def test_a_prospect_in_two_campaigns_sees_only_the_sequence_the_reply_answers(client):
+ _seed(client.db_path)
+ _sql(client.db_path, "INSERT INTO outbox (id, prospect_id, campaign_id, kind, step, to_email, subject, body, "
+ "status, sent_at, send_at) VALUES ('o7', 'p1', 'k2', 'sequence', 1, '[email protected]', 'other campaign', "
+ "'Hi again.', 'sent', '2026-09-01T09:00:00', '2026-09-01T09:00:00')")
+ [convo] = client.get("/api/conversations").json()
+ assert [e["subject"] for e in convo["emails"]] == ["quick question", "re: booking"]
+ assert all("campaign_id" not in e for e in convo["emails"])
+
+
+def test_an_escalated_conversation_shows_on_today_and_can_be_handed_back(client):
+ db = client.db_path
+ asyncio.run(StateManager(str(db)).init_db())
+ _sql(db, "INSERT INTO prospects (id, first_name, email, status) VALUES ('p1', 'Iris', '[email protected]', 'replied')")
+ _sql(db, "INSERT INTO conversations (id, prospect_id, status) VALUES ('c1', 'p1', 'needs_human')")
+ today = client.get("/api/today").json()
+ assert today["stats"]["needs_human"] == 1
+ assert any(i["key"] == "needs-human" and i["tab"] == "conversations" for i in today["items"])
+
+ assert client.post("/api/conversations/c1/status", json={"status": "open"}).json()["success"]
+ with sqlite3.connect(db) as conn:
+ assert conn.execute("SELECT status FROM conversations WHERE id='c1'").fetchone()[0] == "open"
+ logged = conn.execute("SELECT details_json FROM actions WHERE action_type='conversation_status'").fetchone()
+ conn.close()
+ assert json.loads(logged[0]) == {"conversation_id": "c1", "from": "needs_human", "to": "open"}
+ assert not any(i["key"] == "needs-human" for i in client.get("/api/today").json()["items"])
+
+
+def test_conversation_status_rejects_bad_input(client):
+ asyncio.run(StateManager(str(client.db_path)).init_db())
+ _sql(client.db_path, "INSERT INTO conversations (id, status) VALUES ('c1', 'open')")
+ assert client.post("/api/conversations/c1/status", json={"status": "needs_human"}).status_code == 400
+ assert client.post("/api/conversations/c1/status", json=["closed"]).status_code == 400
+ assert client.post("/api/conversations/nope/status", json={"status": "closed"}).status_code == 404
diff --git a/tests/test_dashboard_live_status.py b/tests/test_dashboard_live_status.py
index 30e6291..6e3c3e4 100644
--- a/tests/test_dashboard_live_status.py
+++ b/tests/test_dashboard_live_status.py
@@ -86,6 +86,7 @@ def test_live_status_on_an_empty_database(client):
assert data["running"] == [] and data["stopped"] == []
assert _step(data, "Read their websites")["state"] == "waiting"
assert data["next"] == "Search for businesses to get started."
+ assert data["next_tab"] == "discover"
def test_live_status_without_a_database_file(client, env):
@@ -111,6 +112,7 @@ def test_queued_drafts_are_not_counted_as_sent(client, env):
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)."
+ assert data["next_tab"] == "campaigns"
def test_unconfirmed_emails_are_reported_not_hidden(client, env):
@@ -133,7 +135,7 @@ def test_a_live_run_shows_progress_and_time_left(client, env):
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")
+ assert data["next"].startswith("Wait") and data["next_tab"] == ""
def test_a_killed_run_is_reported_as_stopped_not_running(client, env):
diff --git a/tests/test_dashboard_pipeline.py b/tests/test_dashboard_pipeline.py
new file mode 100644
index 0000000..b1401b6
--- /dev/null
+++ b/tests/test_dashboard_pipeline.py
@@ -0,0 +1,71 @@
+"""/api/stats pipeline: one funnel stage per contact. Prospect status stops at
+"replied"; how the reply went comes from the latest conversation."""
+
+import asyncio
+import sqlite3
+
+from tests.test_dashboard_signals import client # noqa: F401 (fixture)
+from harvey.state import StateManager
+
+
+def _sql(db, query, params=()):
+ with sqlite3.connect(db) as conn:
+ conn.execute(query, params)
+ conn.close()
+
+
+def test_pipeline_buckets_each_contact_once(client):
+ db = client.db_path
+ asyncio.run(StateManager(str(db)).init_db())
+ people = [("a", "new"), ("b", "queued"), ("c", "contacted"), ("d", "replied"), ("e", "replied"),
+ ("f", "replied"), ("g", "replied"), ("h", "lost"), ("i", "opted_out"), ("j", "replied"), ("k", "contacted")]
+ for pid, status in people:
+ _sql(db, "INSERT INTO prospects (id, first_name, status) VALUES (?, 'X', ?)", (pid, status))
+ _sql(db, "UPDATE prospects SET email_status = 'invalid' WHERE id = 'k'") # bounced
+ convos = [
+ ("c1", "d", "question", "engaged", "2026-10-01"),
+ ("c2", "e", "interested", "engaged", "2026-10-01"),
+ ("c3", "f", "question", "closing", "2026-10-01"),
+ ("c4", "g", "objection", "presenting", "2026-10-01"),
+ # j: an old interested thread, then a not-interested one: the latest wins.
+ ("c5", "j", "interested", "closing", "2026-10-01"),
+ ("c6", "j", "not_interested", "closed_lost", "2026-10-05"),
+ ]
+ for cid, pid, intent, stage, at in convos:
+ _sql(db, "INSERT INTO conversations (id, prospect_id, intent, stage, updated_at) VALUES (?,?,?,?,?)",
+ (cid, pid, intent, stage, at))
+ pipe = client.get("/api/stats").json()["pipeline"]
+ assert pipe == {"to_write": 2, "contacted": 1, "replied": 1, "interested": 2,
+ "ready_to_meet": 1, "closed_out": 4}
+ assert sum(pipe.values()) == len(people)
+
+
+def test_discover_tab_knows_how_many_sites_are_unread(client):
+ asyncio.run(StateManager(str(client.db_path)).init_db())
+ data = client.get("/api/discover/providers").json()
+ assert data["unprofiled"] == 0 and data["running_kind"] in ("discover", "profile")
+
+
+def test_a_paused_brain_is_on_today_not_hidden(client, monkeypatch):
+ import json as _json
+ import harvey.dashboard as dash
+ asyncio.run(StateManager(str(client.db_path)).init_db())
+ monkeypatch.setattr(dash, "_active_provider", lambda: "codex")
+ _sql(client.db_path, "INSERT INTO settings (key, value) VALUES (?, ?)",
+ (__import__("harvey.brain", fromlist=["x"]).BRAIN_STATUS_KEY,
+ _json.dumps({"provider": "codex", "status": "paused", "reason": "codex login expired"})))
+ items = client.get("/api/today").json()["items"]
+ [item] = [i for i in items if i["key"] == "brain-paused"]
+ assert "codex login expired" in item["detail"] and item["tone"] == "bad"
+
+
+def test_a_run_that_went_quiet_is_not_shown_as_running(client):
+ from datetime import datetime, timedelta, timezone
+ asyncio.run(StateManager(str(client.db_path)).init_db())
+ now = datetime.now(timezone.utc).replace(tzinfo=None)
+ _sql(client.db_path, "INSERT INTO runs (id, stage, status, started_at) VALUES ('old', 'profile', 'running', ?)",
+ ((now - timedelta(hours=2)).isoformat(),))
+ _sql(client.db_path, "INSERT INTO runs (id, stage, status, started_at) VALUES ('new', 'profile', 'running', ?)",
+ ((now - timedelta(minutes=2)).isoformat(),))
+ runs = {r["id"]: r["status"] for r in client.get("/api/runs").json()}
+ assert runs == {"old": "stalled", "new": "running"}
diff --git a/tests/test_dashboard_trend.py b/tests/test_dashboard_trend.py
index 8a81e2e..33ee7b0 100644
--- a/tests/test_dashboard_trend.py
+++ b/tests/test_dashboard_trend.py
@@ -40,3 +40,17 @@ def test_trend_days_are_bounded(client):
assert len(client.get("/api/trend?days=500").json()["days"]) == 90
assert len(client.get("/api/trend?days=0").json()["days"]) == 1
assert client.get("/api/trend?days=x").status_code == 422
+
+
+def test_trend_counts_days_in_the_viewers_time_zone(client):
+ asyncio.run(StateManager(str(client.db_path)).init_db())
+ now = datetime.now(timezone.utc)
+ # 3 hours ago UTC is "today" in UTC but, 10 hours west, belongs to whatever
+ # local day it was then; compute the expected local day the same way.
+ stamp = (now - timedelta(hours=3)).strftime("%Y-%m-%dT%H:%M:%S")
+ _sql(client.db_path, "INSERT INTO prospects (id, first_name, status, created_at) VALUES ('p1', 'A', 'new', ?)", (stamp,))
+ local = (now - timedelta(hours=3) - timedelta(minutes=600)).date().isoformat()
+ data = client.get("/api/trend?days=7&tz=-600").json()
+ assert data["days"][-1] == (now - timedelta(minutes=600)).date().isoformat()
+ assert data["found"][data["days"].index(local)] == 1
+ assert len(client.get("/api/trend?days=3&tz=99999").json()["days"]) == 3 # clamped, no crash