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.
Send by hand only when Harvey can't send, and never send to someone emailed by hand
Ethanea716014a492
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 30e4acd..f856615 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -34,6 +34,15 @@ minor versions can still change behaviour.### Added+- **Send by hand from the dashboard, and a live status panel.** With no+ mailbox connected (or email turned off), each campaign's first email has an+ **Open in Gmail** button that fills in a compose window in the account+ Harvey sends as, and a **Mark as sent** box. Harvey never sends to someone+ marked sent by hand, even if a mailbox is connected later, and only offers+ it for people it could still email (not opted out, replied, bounced, or+ already queued by Harvey). The Today tab gains a panel showing each pipeline+ step, what's running, and what to do next.+- **Outbox review: see what a draft is based on, and edit it.** Each pendingdraft now shows its campaign, the company (name, clickable website,description), the contact and how they were found, email status and score,diff --git a/harvey/agents/sender.py b/harvey/agents/sender.pyindex d556014..de06c25 100644--- a/harvey/agents/sender.py+++ b/harvey/agents/sender.py@@ -22,7 +22,7 @@ from harvey.gate import pre_send_checkfrom harvey.integrations.instantly import InstantlyClientfrom harvey.integrations.mail_provider import NATIVE_PROVIDERS, get_mail_providerfrom harvey.integrations.precleared import PreclearedClient-from harvey.state import StateManager+from harvey.state import MANUAL_SEND_KEY, StateManagerlogger = logging.getLogger("harvey.sender")@@ -207,6 +207,8 @@ class Sender:f"Sender: Skipping {email} (status '{prospect.status}' is not sendable).")continue+ if await self.state.get_setting(MANUAL_SEND_KEY + prospect.id):+ continue # the user emailed them by hand# Deliverability gate: never send to unverified/guessed addresses —# bounces are the fastest way to torch a sending domain.if (prospect.email_status or "guess") not in sendable_email:@@ -411,7 +413,9 @@ class Sender:)if item_id:staged += 1- await self.state.update_prospect_status(prospect.id, "queued")+ # Conditional: never overwrite a status set while staging+ # (marked sent by hand, a reply).+ await self.state.queue_prospect_if_unsent(prospect.id)await self.state.update_campaign(campaign.id, status="active")if skipped:@@ -496,6 +500,18 @@ class Sender:error=f"prospect status '{prospect.status}'",)continue+ # The user already emailed them by hand: whatever Harvey staged+ # (before, during or after that) would be a second email.+ if item["kind"] == "sequence" and await self.state.get_setting(+ MANUAL_SEND_KEY + prospect.id):+ await self.state.update_outbox_item(+ item["id"], status="cancelled", error="sent by hand")+ continue+ # A first email to someone already contacted is always a duplicate.+ if item["kind"] == "sequence" and item["step"] == 1 and prospect.status == "contacted":+ await self.state.update_outbox_item(+ item["id"], status="cancelled", error="already contacted")+ continuegate = pre_send_check(item["to_email"], item["subject"], item["body"],diff --git a/harvey/agents/writer.py b/harvey/agents/writer.pyindex 05b6efa..e4f34e6 100644--- a/harvey/agents/writer.py+++ b/harvey/agents/writer.py@@ -122,7 +122,7 @@ class Writer:# Mark prospects so they aren't picked up againfor p in prospects:- await self.state.update_prospect_status(p.id, "queued")+ await self.state.queue_prospect_if_unsent(p.id)await self.state.delete_setting(WRITE_ATTEMPTS_KEY + p.id)# Native providers: replace the shared template for email 1 withdiff --git a/harvey/dashboard.py b/harvey/dashboard.pyindex 133b8a4..014fa86 100644--- a/harvey/dashboard.py+++ b/harvey/dashboard.py@@ -936,10 +936,64 @@ async def outbox_edit(item_id: str, request: Request):return JSONResponse({"success": False, "message": str(e)}, status_code=500)-# Remembers what a prospect was before it was marked sent by hand, so undo-# puts it back exactly (a 'queued' prospect set to 'new' would be redrafted).-MANUAL_SEND_PREV_KEY = "manual_send_prev:"HAND_SENT_REASON = "sent_by_hand"+# A hand send is only offered to someone Harvey could still email: never to+# someone who replied, opted out, bounced or was already contacted.+HAND_SENDABLE_STATUSES = ("new", "queued")+HAND_SENDABLE_EMAIL = ("verified", "risky")+++def _harvey_can_send() -> bool:+ """Can Harvey send email itself (a connected mailbox, or Instantly)?++ Sending by hand from the dashboard is only offered when it can't: with+ two senders, any timing gap between them emails someone twice. If the+ config can't be read, the answer is yes (the safe side: no hand sends).+ """+ try:+ from harvey.config import load_config, load_env+ from harvey.integrations.mail_provider import NATIVE_PROVIDERS, get_mail_provider+ config, env = load_config(), load_env()+ email = config.channels.email+ if not email.enabled:+ return False+ if (email.provider or "").strip().lower() in NATIVE_PROVIDERS:+ provider = get_mail_provider(config, env)+ return bool(provider and provider.is_configured())+ return bool(env.instantly_api_key)+ except Exception:+ return True+++def _send_as() -> str:+ """The address Harvey sends as, so Gmail opens the right account."""+ try:+ from harvey.config import load_config+ return load_config().persona.email or ""+ except Exception:+ return ""+++async def _harvey_sending_ids() -> set[str]:+ """Everyone Harvey has queued, approved or sent mail for (Outbox or Instantly)."""+ ids = {r["prospect_id"] for r in await query_db(+ "SELECT DISTINCT prospect_id FROM outbox "+ "WHERE status IN ('pending_review', 'approved', 'sent')")}+ for row in await query_db(+ "SELECT prospect_ids_json FROM campaigns WHERE COALESCE(instantly_campaign_id, '') != ''"):+ try:+ found = json.loads(row.get("prospect_ids_json") or "[]")+ except (json.JSONDecodeError, TypeError):+ continue+ if isinstance(found, list):+ ids.update(i for i in found if isinstance(i, str))+ return ids+++async def _hand_sent_ids() -> set[str]:+ from harvey.state import MANUAL_SEND_KEY+ rows = await query_db("SELECT key FROM settings WHERE key LIKE ?", (MANUAL_SEND_KEY + "%",))+ return {r["key"][len(MANUAL_SEND_KEY):] for r in rows}async def _harvey_sent_to(prospect_id: str) -> bool:@@ -957,9 +1011,14 @@ async def _harvey_sent_to(prospect_id: str) -> bool:return False+def _refuse(message: str, code: int = 409):+ return JSONResponse({"success": False, "message": message}, status_code=code)++@app.post("/api/prospects/{prospect_id}/sent")async def mark_prospect_sent(prospect_id: str, request: Request):"""The user sent this email by hand (e.g. from Gmail): record it, or undo it."""+ from harvey.state import MANUAL_SEND_KEYtry:try:body = await request.json()@@ -967,48 +1026,57 @@ async def mark_prospect_sent(prospect_id: str, request: Request):body = {}if body is None:body = {}- if not isinstance(body, dict):- return JSONResponse({"success": False, "message": "expected {\"sent\": true|false}"},- status_code=400)- sent = bool(body.get("sent", True))+ if not isinstance(body, dict) or not isinstance(body.get("sent", True), bool):+ return _refuse('expected {"sent": true|false}', 400)+ sent = body.get("sent", True)rows = await query_db("SELECT status FROM prospects WHERE id = ?", (prospect_id,))if not rows:- return JSONResponse({"success": False, "message": "unknown prospect"},- status_code=404)+ return _refuse("unknown prospect", 404)current = rows[0].get("status") or "new"- # Only toggle between "not sent" and "sent". A prospect who already- # replied, booked or closed keeps that status — unticking a box must- # never erase a reply.- if current not in ("new", "queued", "contacted"):- return {"success": True, "sent": True, "status": current}state = _state()await state.init_db()- key = MANUAL_SEND_PREV_KEY + prospect_id+ key = MANUAL_SEND_KEY + prospect_id+ marked = bool(await state.get_setting(key))+if sent:- if current != "contacted":- await state.set_setting(key, current)+ if marked:+ return {"success": True, "sent": True}+ if current not in HAND_SENDABLE_STATUSES:+ # A reply, opt-out or close is never touched; neither is+ # someone Harvey already emailed.+ return {"success": True, "sent": True, "status": current}+ if _harvey_can_send():+ return _refuse("Harvey sends email for you here, so there's nothing to send by "+ "hand. Review it in the Outbox.")+ if await _harvey_sent_to(prospect_id):+ return _refuse("Harvey already emailed this person.")+ await state.set_setting(key, current)await state.update_prospect_status(prospect_id, "contacted")- # They've had this email from the user's own mailbox: whatever- # Harvey had queued for them must not go out as well.- cancelled = await state.cancel_pending_outbox_for_prospect(+ # Anything Harvey had queued for them must not go out as well.+ changed = await state.cancel_pending_outbox_for_prospect(prospect_id, reason=HAND_SENT_REASON)else:- if current == "contacted" and await _harvey_sent_to(prospect_id):- # Setting them back would make Harvey write and send again.- return JSONResponse({"success": False,- "message": "Harvey already emailed this person, so it "- "stays marked as sent."},- status_code=409)- previous = await state.get_setting(key) or "new"- await state.update_prospect_status(prospect_id, previous)+ if not marked:+ if current in HAND_SENDABLE_STATUSES:+ return {"success": True, "sent": False}+ if current == "contacted":+ # Setting them back would make Harvey write and send again.+ return _refuse("This wasn't marked as sent by hand here, so it stays sent.")+ return {"success": True, "sent": True, "status": current}+ if current != "contacted":+ # They replied, opted out or bounced since: that stands.+ return {"success": True, "sent": True, "status": current}+ previous = await state.get_setting(key) or "queued"+ await state.update_prospect_status(+ prospect_id, previous if previous in HAND_SENDABLE_STATUSES else "queued")await state.delete_setting(key)# What marking sent cancelled comes back for review, never straight out.- cancelled = await state.restore_hand_cancelled_outbox(+ changed = await state.restore_hand_cancelled_outbox(prospect_id, reason=HAND_SENT_REASON)await state.log_action(action_type="manual_send" if sent else "manual_send_undone",agent="user",- details={"prospect_id": prospect_id, "outbox_items": cancelled},+ details={"prospect_id": prospect_id, "outbox_items": changed},)return {"success": True, "sent": sent}except Exception as e:@@ -1069,6 +1137,10 @@ async def export_prospects(all: bool = False, min_score: int = 0, email_status:@app.get("/api/campaigns")async def get_campaigns():rows = await query_db("SELECT * FROM campaigns ORDER BY created_at DESC LIMIT 100")+ harvey_sends = _harvey_can_send()+ send_as = "" if harvey_sends else _send_as()+ harvey = await _harvey_sending_ids()+ hand_sent = await _hand_sent_ids()for row in rows:try:row["sequence"] = json.loads(row.get("sequence_json", "[]"))@@ -1081,19 +1153,20 @@ async def get_campaigns():# Who each draft goes to, so the UI can open it in the user's own mail client.ids = row["prospect_ids"]row["recipients"] = await query_db(- f"SELECT id, email, first_name, last_name, company, title, status FROM prospects "+ f"SELECT id, email, first_name, last_name, company, title, status, email_status, "+ f"source, personalization_notes FROM prospects "f"WHERE id IN ({','.join('?' * len(ids))}) AND email != ''",tuple(ids),) if ids else []- # Harvey is sending to them itself (Outbox or Instantly): the UI must- # not offer a second copy from the user's own mailbox.- harvey = {r["prospect_id"] for r in (await query_db(- f"SELECT DISTINCT prospect_id FROM outbox WHERE prospect_id IN "- f"({','.join('?' * len(ids))}) AND status IN ('pending_review', 'approved', 'sent')",- tuple(ids)) if ids else [])}- deployed = bool(row.get("instantly_campaign_id"))+ row["send_as"] = send_asfor r in row["recipients"]:- r["harvey_sending"] = deployed or r["id"] in harvey+ r["sent_by_hand"] = r["id"] in hand_sent+ r["can_send_by_hand"] = (+ not harvey_sends+ and r["id"] not in hand_sent and r["id"] not in harvey+ and (r.get("status") or "new") in HAND_SENDABLE_STATUSES+ and (r.get("email_status") or "guess") in HAND_SENDABLE_EMAIL+ )return rows@@ -1328,7 +1401,8 @@ async def _first(sql: str, params: tuple = (), key: str = "t"):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")+# Moved on from "waiting to be emailed" (opted_out too: never offered again).+SENT_STATUSES = ("contacted", "replied", "meeting", "closed", "lost", "opted_out")REPLY_STATUSES = ("replied", "meeting", "closed")@@ -1380,17 +1454,17 @@ async def get_live_status():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}- # People Harvey is emailing itself: never the user's job to send by hand.- harvey_sending = {r["prospect_id"] for r in await query_db(- "SELECT DISTINCT prospect_id FROM outbox "- "WHERE status IN ('pending_review', 'approved', 'sent')")}- for row in await query_db(- "SELECT prospect_ids_json FROM campaigns WHERE COALESCE(instantly_campaign_id, '') != ''"):- try:- harvey_sending.update(json.loads(row.get("prospect_ids_json") or "[]"))- except (json.JSONDecodeError, TypeError):- pass+ # Who is left for the user to send by hand: only when Harvey can't send+ # itself, and never someone Harvey has queued, sent to, or can't reach.+ harvey_sends = _harvey_can_send()awaiting_review = await _scalar("SELECT COUNT(*) FROM outbox WHERE status = 'pending_review'")+ by_hand: set[str] = set()+ if not harvey_sends:+ skip = await _harvey_sending_ids() | await _hand_sent_ids()+ by_hand = {p["id"] for p in prospects+ if p["id"] in drafted and p["id"] not in skip+ and (p.get("status") or "new") in HAND_SENDABLE_STATUSES+ and (p.get("email_status") or "guess") in HAND_SENDABLE_EMAIL}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)@@ -1469,10 +1543,10 @@ async def get_live_status():next_up = "Wait — emails are being found."elif stopped:next_up = "A job stopped before finishing. Run it again."- elif awaiting_review:+ elif harvey_sends and awaiting_review:next_up = f"Review the {awaiting_review} draft(s) waiting in the Outbox."- elif drafted - sent - harvey_sending:- next_up = f"Open Campaigns and send the {len(drafted - sent - harvey_sending)} unsent email(s)."+ elif by_hand:+ next_up = f"Open Campaigns and send the {len(by_hand)} unsent email(s)."elif profiled > checked:next_up = f"Find emails for the {profiled - checked} businesses not checked yet."elif deliverable - drafted:@@ -1482,14 +1556,11 @@ async def get_live_status():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",}diff --git a/harvey/state.py b/harvey/state.pyindex e513931..63c92c9 100644--- a/harvey/state.py+++ b/harvey/state.py@@ -32,6 +32,10 @@ BUSY_TIMEOUT_SECONDS = 30.0# Email statuses the Writer drafts for. Shared with the heartbeat so it only# chooses write_campaign when there is something the Writer will act on.WRITABLE_EMAIL_STATUSES = ("verified", "risky")+# Settings key, per prospect: the user emailed them by hand from the+# dashboard. Its value is the status they had before, so undo is exact; its+# presence tells the Sender never to email them as well.+MANUAL_SEND_KEY = "manual_send:"def _new_id() -> str:@@ -730,6 +734,21 @@ class StateManager:)await db.commit()+ async def queue_prospect_if_unsent(self, prospect_id: str) -> bool:+ """Mark a prospect 'queued' unless something moved them on meanwhile.++ Conditional, so a status set while a campaign was being staged (the+ user marking them sent by hand, a reply) is never overwritten.+ """+ async with self._connect() as db:+ cursor = await db.execute(+ "UPDATE prospects SET status = 'queued', updated_at = ? "+ "WHERE id = ? AND status IN ('new', 'queued')",+ (_utcnow().isoformat(), prospect_id),+ )+ await db.commit()+ return cursor.rowcount > 0+async def get_prospect_by_email(self, email: str) -> Prospect | None:"""Look up a prospect by email address (indexed, case-insensitive)."""email = _norm(email)@@ -925,16 +944,37 @@ class StateManager:"""Undo a cancel made with `reason`: those items go back for review.Always to pending_review, even if they were approved before: a human- decides again. Items cancelled for any other reason stay cancelled.+ decides again. They're rescheduled from now with their original gaps,+ so a late undo never releases a whole sequence at once. Items+ cancelled for any other reason stay cancelled."""async with self._connect() as db:- cursor = await db.execute(- "UPDATE outbox SET status = 'pending_review', error = '', updated_at = ? "- "WHERE prospect_id = ? AND status = 'cancelled' AND error = ?",- (_utcnow().isoformat(), prospect_id, reason),- )+ db.row_factory = aiosqlite.Row+ async with db.execute(+ "SELECT id, send_at FROM outbox WHERE prospect_id = ? "+ "AND status = 'cancelled' AND error = ? ORDER BY send_at",+ (prospect_id, reason),+ ) as cursor:+ rows = [dict(r) for r in await cursor.fetchall()]+ if not rows:+ return 0+ now = _utcnow()++ def _at(value):+ try:+ return datetime.fromisoformat(str(value))+ except (TypeError, ValueError):+ return now+ first = _at(rows[0]["send_at"])+ for r in rows:+ send_at = now + max(timedelta(0), _at(r["send_at"]) - first)+ await db.execute(+ "UPDATE outbox SET status = 'pending_review', error = '', send_at = ?, "+ "updated_at = ? WHERE id = ?",+ (send_at.isoformat(), now.isoformat(), r["id"]),+ )await db.commit()- return cursor.rowcount+ return len(rows)async def approve_outbox(self, item_id: str | None = None) -> int:"""Approve one pending item, or ALL pending when item_id is None."""diff --git a/harvey/web/app.js b/harvey/web/app.jsindex f9a543c..6fc02e3 100644--- a/harvey/web/app.js+++ b/harvey/web/app.js@@ -343,13 +343,9 @@ async function loadLiveStatus() {(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">💬 ' + 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="font-size:13px;margin:6px 0 4px">' + runningHtml + '</div>' + stoppedHtml +'<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: $' +@@ -1592,13 +1588,18 @@ async function loadProspects() {// Opens a filled-in compose window in whatever Gmail account the browser is// logged into. Nothing is sent from here — the user reads it and presses Send.+// Same values as the Sender's _render, so a hand-sent email reads the same.function fillMergeVars(text, r) {+ const inbox = r.source === 'company_inbox';const vals = {- first_name: r.first_name || 'there', last_name: r.last_name || '',+ first_name: r.first_name || (inbox ? 'there' : ''), last_name: r.last_name || '',company: r.company || '', title: r.title || '',+ personalization: r.personalization_notes || '',};- return String(text || '').replace(/\{\{\s*(\w+)\s*\}\}/g,- (m, k) => (k.toLowerCase() in vals ? vals[k.toLowerCase()] : m));+ return String(text || '').replace(/\{\{\s*(\w+)\s*\}\}/g, (m, k) => {+ k = k.toLowerCase();+ return Object.prototype.hasOwnProperty.call(vals, k) ? vals[k] : m;+ });}function openInGmail(ci, si, ri) {@@ -1606,7 +1607,10 @@ function openInGmail(ci, si, ri) {const step = c && (c.sequence || [])[si];const r = c && (c.recipients || [])[ri];if (!step || !r) return;+ // authuser picks the Google account Harvey sends as, not just whichever+ // one the browser happens to be signed into.const url = 'https://mail.google.com/mail/?view=cm&fs=1' ++ (c.send_as ? '&authuser=' + encodeURIComponent(c.send_as) : '') +'&to=' + encodeURIComponent(r.email) +'&su=' + encodeURIComponent(fillMergeVars(step.subject, r)) +'&body=' + encodeURIComponent(fillMergeVars(step.body, r));@@ -1654,20 +1658,26 @@ async function loadCampaigns() {let stepsHtml = '';(c.sequence || []).forEach((step, s) => {const sendBtns = (c.recipients || []).map((r, ri) => {- // Harvey is sending to them itself: a copy from Gmail would be a second email.- if (r.harvey_sending) {- return '<span class="muted" style="font-size:13px">' + escHtml(r.email) +- ' · Harvey is sending this one (see Outbox)</span>';+ // Only offered when Harvey can't send itself and this person can+ // still be emailed (the server decides: can_send_by_hand).+ if (r.sent_by_hand) {+ const tick = '<label style="display:inline-flex;align-items:center;gap:4px;font-size:13px;cursor:pointer">' ++ '<input type="checkbox" checked onchange="markSent(' + i + ',' + ri + ',this.checked)"> ' ++ '✓ Sent by you</label>';+ if (s === 0) return escHtml(r.email) + ' ' + tick;+ // Follow-ups are the user's too: Harvey never emails someone they emailed.+ return '<button class="btn btn-secondary btn-sm" onclick="openInGmail(' + i + ',' + s + ',' + ri + ')">' ++ 'Open in Gmail → ' + escHtml(r.email) + '</button>' ++ '<span class="muted" style="font-size:12px">Harvey won\'t send follow-ups to people you emailed yourself.</span>';}- // 'queued' only means Harvey wrote a draft — it is not a send.- const sent = ['contacted', 'replied', 'meeting', 'closed', 'lost'].includes(r.status);+ if (!r.can_send_by_hand || s !== 0) return '';+ const risky = r.email_status === 'risky'+ ? ' <span class="muted" style="font-size:12px">(catch-all address, may bounce)</span>' : '';return '<button class="btn btn-primary btn-sm" onclick="openInGmail(' + i + ',' + s + ',' + ri + ')">' +- 'Open in Gmail → ' + escHtml(r.email) + '</button>' ++ 'Open in Gmail → ' + escHtml(r.email) + '</button>' + risky +'<label style="display:inline-flex;align-items:center;gap:4px;font-size:13px;cursor:pointer">' +- '<input type="checkbox"' + (sent ? ' checked' : '') +- ' onchange="markSent(' + i + ',' + ri + ',this.checked)"> ' +- (sent ? '✓ Sent' : 'Mark as sent') + '</label>';- }).join(' ');+ '<input type="checkbox" onchange="markSent(' + i + ',' + ri + ',this.checked)"> Mark as sent</label>'+ }).filter(Boolean).join(' ');stepsHtml += '<div class="email-step"><div class="step-num">Email ' + escHtml(String(step.step || '?')) +(step.delay_days ? ' · send after ' + escHtml(String(step.delay_days)) + ' days' : '') + '</div>' +'<div class="subject">' + escHtml(step.subject) + '</div>' +@@ -1743,7 +1753,7 @@ 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.+// Live status panel: refreshed while the Today tab is open and visible.setInterval(() => {if (!document.hidden && !_locked && currentTab === 'today') loadLiveStatus();}, 10000);diff --git a/tests/test_dashboard_live_status.py b/tests/test_dashboard_live_status.pyindex 9dbba91..835d6d3 100644--- a/tests/test_dashboard_live_status.py+++ b/tests/test_dashboard_live_status.py@@ -30,6 +30,9 @@ def env(tmp_path, monkeypatch):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")+ # No mailbox connected: the user sends by hand. Tests that need Harvey+ # to be able to send set this back.+ monkeypatch.setattr(dash, "_harvey_can_send", lambda: False)async def _init():state = StateManager(db_path=str(db))await state.init_db()@@ -150,7 +153,8 @@ def _outbox(env, oid, pid, status):"'2026-01-01T00:00:00', ?)", (oid, pid, status))-def test_drafts_waiting_in_the_outbox_point_there_not_at_gmail(client, env):+def test_drafts_waiting_in_the_outbox_point_there_not_at_gmail(client, env, monkeypatch):+ monkeypatch.setattr(dash, "_harvey_can_send", lambda: True)# Harvey is sending these itself: telling the user to send them from# Campaigns by hand would email the same person twice._prospect(env, "p1", "[email protected]", status="queued")@@ -161,7 +165,15 @@ def test_drafts_waiting_in_the_outbox_point_there_not_at_gmail(client, env):def test_approved_mail_harvey_will_send_is_not_a_job_for_the_user(client, env):+ # Even with no mailbox connected now, mail Harvey queued is not the user's to send._prospect(env, "p1", "[email protected]", status="queued")_campaign(env, "c1", ["p1"])_outbox(env, "o1", "p1", "approved")assert "Open Campaigns" not in client.get("/api/live-status").json()["next"]+++def test_opted_out_and_unreachable_people_are_never_asked_to_be_sent(client, env):+ _prospect(env, "p1", "[email protected]", status="opted_out")+ _prospect(env, "p2", "[email protected]", email_status="guess", status="queued")+ _campaign(env, "c1", ["p1", "p2"])+ assert "Open Campaigns" not in client.get("/api/live-status").json()["next"]diff --git a/tests/test_dashboard_manual_send.py b/tests/test_dashboard_manual_send.pyindex 79e3de3..5b8e922 100644--- a/tests/test_dashboard_manual_send.py+++ b/tests/test_dashboard_manual_send.py@@ -26,6 +26,9 @@ def env(tmp_path, monkeypatch):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")+ # No mailbox connected: the user sends by hand. Tests that need Harvey+ # to be able to send set this back.+ monkeypatch.setattr(dash, "_harvey_can_send", lambda: False)asyncio.run(StateManager(db_path=str(db)).init_db())return {"db": db, "token": dash.token_store.get()}@@ -160,18 +163,111 @@ def test_unticking_someone_sent_through_instantly_is_refused(client, env):assert _status(env, "prospects", "p1") == "contacted"-def test_recipients_say_when_harvey_is_sending_to_them(client, env):+def test_recipients_say_who_can_be_sent_by_hand(client, env):_prospect(env, "p1", "[email protected]", status="queued")- _prospect(env, "p2", "[email protected]", status="queued")- _campaign(env, "c1", ["p1", "p2"])- _outbox(env, "o1", "p1", "pending_review")+ _prospect(env, "p2", "[email protected]", status="queued") # Harvey queued mail+ _prospect(env, "p3", "[email protected]", status="opted_out") # asked to be removed+ _prospect(env, "p4", "[email protected]", email_status="guess") # undeliverable+ _prospect(env, "p5", "[email protected]", email_status="invalid")+ _prospect(env, "p6", "[email protected]", email_status="risky") # catch-all: allowed+ _campaign(env, "c1", ["p1", "p2", "p3", "p4", "p5", "p6"])+ _outbox(env, "o1", "p2", "pending_review")recips = {r["id"]: r for r in client.get("/api/campaigns").json()[0]["recipients"]}- assert recips["p1"]["harvey_sending"] is True- assert recips["p2"]["harvey_sending"] is False+ assert {k for k, r in recips.items() if r["can_send_by_hand"]} == {"p1", "p6"}+++def test_nothing_is_sent_by_hand_while_harvey_can_send(client, env, monkeypatch):+ monkeypatch.setattr(dash, "_harvey_can_send", lambda: True)+ _prospect(env, "p1", "[email protected]", status="queued")+ _campaign(env, "c1", ["p1"])+ assert client.get("/api/campaigns").json()[0]["recipients"][0]["can_send_by_hand"] is False+ assert client.post("/api/prospects/p1/sent", json={"sent": True}).status_code == 409+ assert _status(env, "prospects", "p1") == "queued"+++def test_a_hand_sent_prospect_is_marked_for_the_sender(client, env):+ _prospect(env, "p1", "[email protected]", status="queued")+ _campaign(env, "c1", ["p1"])+ client.post("/api/prospects/p1/sent", json={"sent": True})+ r = client.get("/api/campaigns").json()[0]["recipients"][0]+ assert r["sent_by_hand"] is True and r["can_send_by_hand"] is False+ with sqlite3.connect(env["db"]) as db:+ assert db.execute("SELECT value FROM settings WHERE key = 'manual_send:p1'").fetchone()[0] == "queued"+ client.post("/api/prospects/p1/sent", json={"sent": False})+ with sqlite3.connect(env["db"]) as db:+ assert db.execute("SELECT 1 FROM settings WHERE key = 'manual_send:p1'").fetchone() is None+++def test_ticking_someone_harvey_emailed_changes_nothing(client, env):+ _prospect(env, "p1", "[email protected]", status="contacted")+ _outbox(env, "o1", "p1", "sent", step=1)+ _outbox(env, "o2", "p1", "approved", step=2) # Harvey's follow-up+ client.post("/api/prospects/p1/sent", json={"sent": True})+ assert _status(env, "outbox", "o2") == "approved"+++def test_undo_after_a_reply_keeps_the_reply(client, env):+ _prospect(env, "p1", "[email protected]", status="queued")+ client.post("/api/prospects/p1/sent", json={"sent": True})+ _sql(env, "UPDATE prospects SET status = 'replied'")+ client.post("/api/prospects/p1/sent", json={"sent": False})+ assert _status(env, "prospects", "p1") == "replied"[email protected]("payload", [[], "x"])[email protected]("payload", [[], "x", {"sent": "false"}])def test_a_body_that_is_not_an_object_is_refused(client, env, payload):_prospect(env, "p1", "[email protected]")assert client.post("/api/prospects/p1/sent", json=payload).status_code == 400assert _status(env, "prospects", "p1") == "new"+++# ── When is sending by hand offered at all? ──+++class _Email:+ def __init__(self, enabled=True, provider="smtp"):+ self.enabled, self.provider = enabled, provider+++class _Cfg:+ def __init__(self, **kw):+ self.channels = type("C", (), {"email": _Email(**kw)})()+++class _Env:+ def __init__(self, instantly=""):+ self.instantly_api_key = instantly+++class _Provider:+ def __init__(self, ok):+ self.ok = ok++ def is_configured(self):+ return self.ok++[email protected]("cfg, env, provider_ok, expected", [+ (_Cfg(enabled=False), _Env(), True, False), # email off: hand sends only+ (_Cfg(provider="smtp"), _Env(), False, False), # mailbox not connected+ (_Cfg(provider="gmail"), _Env(), True, True), # connected: Harvey sends+ (_Cfg(provider="instantly"), _Env(instantly="k"), True, True),+ (_Cfg(provider="instantly"), _Env(), True, False),+])+def test_harvey_can_send(monkeypatch, cfg, env, provider_ok, expected):+ import harvey.config+ import harvey.integrations.mail_provider as mp+ monkeypatch.setattr(harvey.config, "load_config", lambda: cfg)+ monkeypatch.setattr(harvey.config, "load_env", lambda: env)+ monkeypatch.setattr(mp, "get_mail_provider", lambda c, e: _Provider(provider_ok))+ # These tests don't use the env fixture, so this is the real check.+ assert dash._harvey_can_send() is expected+++def test_an_unreadable_config_means_harvey_might_send(monkeypatch):+ import harvey.config++ def boom():+ raise ValueError("bad yaml")+ monkeypatch.setattr(harvey.config, "load_config", boom)+ assert dash._harvey_can_send() is Truediff --git a/tests/test_hand_sent_guard.py b/tests/test_hand_sent_guard.pynew file mode 100644index 0000000..54756dc--- /dev/null+++ b/tests/test_hand_sent_guard.py@@ -0,0 +1,91 @@+"""Harvey never emails someone the user already emailed by hand.++Marking a prospect sent from the dashboard leaves a durable marker. Whatever+Harvey staged before, during or after that (the Writer's personal draft, the+Sender's template staging, a mailbox connected later) must not go out.+"""++from datetime import datetime, timedelta, timezone++import pytest++from harvey.state import MANUAL_SEND_KEY+from tests.test_outbox_native import ( # noqa: F401 (state is a fixture)+ FakeProvider, make_sender, seed_campaign, seed_prospect, state,+)+++def _now_iso():+ return datetime.now(timezone.utc).replace(tzinfo=None).isoformat()+++async def _approved(state, pid, step, campaign_id="c1"):+ await state.add_outbox_item(+ prospect_id=pid, to_email="[email protected]", subject="hello there",+ body="A short, plain note. Question?", send_at=_now_iso(),+ status="approved", campaign_id=campaign_id, step=step,+ )+++async def test_drain_never_sends_to_someone_emailed_by_hand(state):+ pid = await seed_prospect(state, status="contacted")+ await state.set_setting(MANUAL_SEND_KEY + pid, "queued")+ await _approved(state, pid, step=1)+ await _approved(state, pid, step=2)+ provider = FakeProvider()+ await make_sender(state, provider)._drain_due()+ assert provider.sent == []+ assert {i["error"] for i in await state.get_outbox(status="cancelled")} == {"sent by hand"}+++async def test_drain_never_sends_a_first_email_to_someone_already_contacted(state):+ pid = await seed_prospect(state, status="contacted")+ await _approved(state, pid, step=1)+ provider = FakeProvider()+ await make_sender(state, provider)._drain_due()+ assert provider.sent == []+ assert (await state.get_outbox(status="cancelled"))[0]["error"] == "already contacted"+++async def test_follow_ups_to_someone_harvey_contacted_still_go(state):+ pid = await seed_prospect(state, status="contacted")+ await _approved(state, pid, step=2)+ provider = FakeProvider()+ await make_sender(state, provider)._drain_due()+ assert len(provider.sent) == 1+++async def test_staging_never_overwrites_contacted_with_queued(state, monkeypatch):+ pid = await seed_prospect(state, status="queued")+ await seed_campaign(state, [pid])+ sender = make_sender(state, FakeProvider())+ real_add = state.add_outbox_item++ async def add_then_user_marks_sent(**kw):+ item = await real_add(**kw)+ await state.update_prospect_status(pid, "contacted") # mid-staging+ return item+ monkeypatch.setattr(state, "add_outbox_item", add_then_user_marks_sent)+ await sender._run_native()+ assert (await state.get_prospect(pid)).status == "contacted"+++async def test_restore_reschedules_from_now_keeping_the_gaps(state):+ pid = await seed_prospect(state, status="queued")+ old = datetime(2026, 1, 1)+ for step, days in ((1, 0), (2, 3)):+ await state.add_outbox_item(+ prospect_id=pid, to_email="[email protected]", subject="s", body="b",+ send_at=(old + timedelta(days=days)).isoformat(), status="approved",+ campaign_id="c1", step=step)+ await state.cancel_pending_outbox_for_prospect(pid, reason="sent_by_hand")+ assert await state.restore_hand_cancelled_outbox(pid, reason="sent_by_hand") == 2+ items = sorted(await state.get_outbox(status="pending_review"), key=lambda i: i["step"])+ first, second = (datetime.fromisoformat(i["send_at"]) for i in items)+ assert first >= datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(minutes=1)+ assert second - first == timedelta(days=3)