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.
Sending by hand never doubles up with what Harvey sends
Ethan3e5be3bc8c5f
diff --git a/harvey/dashboard.py b/harvey/dashboard.pyindex 7ddee94..133b8a4 100644--- a/harvey/dashboard.py+++ b/harvey/dashboard.py@@ -936,6 +936,27 @@ 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"+++async def _harvey_sent_to(prospect_id: str) -> bool:+ """Did Harvey itself email this person (native send, or an Instantly campaign)?"""+ if await query_db("SELECT 1 FROM outbox WHERE prospect_id = ? AND status = 'sent' LIMIT 1",+ (prospect_id,)):+ return True+ for row in await query_db(+ "SELECT prospect_ids_json FROM campaigns WHERE COALESCE(instantly_campaign_id, '') != ''"):+ try:+ if prospect_id in json.loads(row.get("prospect_ids_json") or "[]"):+ return True+ except (json.JSONDecodeError, TypeError):+ continue+ return False++@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."""@@ -944,7 +965,12 @@ async def mark_prospect_sent(prospect_id: str, request: Request):body = await request.json()except ValueError:body = {}- sent = bool((body or {}).get("sent", True))+ 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))rows = await query_db("SELECT status FROM prospects WHERE id = ?", (prospect_id,))if not rows:return JSONResponse({"success": False, "message": "unknown prospect"},@@ -957,11 +983,32 @@ async def mark_prospect_sent(prospect_id: str, request: Request):return {"success": True, "sent": True, "status": current}state = _state()await state.init_db()- await state.update_prospect_status(prospect_id, "contacted" if sent else "new")+ key = MANUAL_SEND_PREV_KEY + prospect_id+ if sent:+ if current != "contacted":+ 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(+ 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)+ await state.delete_setting(key)+ # What marking sent cancelled comes back for review, never straight out.+ cancelled = 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},+ details={"prospect_id": prospect_id, "outbox_items": cancelled},)return {"success": True, "sent": sent}except Exception as e:@@ -1038,6 +1085,15 @@ async def get_campaigns():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"))+ for r in row["recipients"]:+ r["harvey_sending"] = deployed or r["id"] in harveyreturn rows@@ -1324,6 +1380,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+ awaiting_review = await _scalar("SELECT COUNT(*) FROM outbox WHERE status = 'pending_review'")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)@@ -1390,7 +1457,7 @@ async def get_live_status():+ (f" · {by_status['invalid']} bad" if by_status.get("invalid") else "")),step("Write first emails", len(drafted), len(deliverable | drafted), False,f"{len(drafted)} written · see Campaigns"),- step("Sent by you", len(sent & drafted), len(drafted), False,+ step("Sent", len(sent & drafted), len(drafted), False,f"{len(sent & drafted)} of {len(drafted)} sent"),step("Replies", replies, 0, False,f"{replies} replies" if replies else "No replies yet", info=True),@@ -1402,8 +1469,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 drafted - sent:- next_up = f"Open Campaigns and send the {len(drafted - sent)} unsent email(s)."+ elif 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 profiled > checked:next_up = f"Find emails for the {profiled - checked} businesses not checked yet."elif deliverable - drafted:diff --git a/harvey/state.py b/harvey/state.pyindex 03988ba..e513931 100644--- a/harvey/state.py+++ b/harvey/state.py@@ -921,6 +921,21 @@ class StateManager:await db.commit()return cursor.rowcount+ async def restore_hand_cancelled_outbox(self, prospect_id: str, reason: str) -> int:+ """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.+ """+ 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),+ )+ await db.commit()+ return cursor.rowcount+async def approve_outbox(self, item_id: str | None = None) -> int:"""Approve one pending item, or ALL pending when item_id is None."""async with self._connect() as db:diff --git a/harvey/web/app.js b/harvey/web/app.jsindex f974eaf..f9a543c 100644--- a/harvey/web/app.js+++ b/harvey/web/app.js@@ -1625,11 +1625,16 @@ function openInGmail(ci, si, ri) {async function markSent(ci, ri, sent) {const r = (_campaigns[ci] && _campaigns[ci].recipients || [])[ri];if (!r) return;- const res = await api('/api/prospects/' + encodeURIComponent(r.id) + '/sent', {- method: 'POST', headers: {'Content-Type': 'application/json'},- body: JSON.stringify({sent}),- });- if (!res || !res.success) showToast('Could not save that. Try again.', 'error');+ let res = null;+ try {+ const resp = await authFetch('/api/prospects/' + encodeURIComponent(r.id) + '/sent', {+ method: 'POST', headers: {'Content-Type': 'application/json'},+ body: JSON.stringify({sent}),+ });+ if (await lockIfRefused(resp)) return;+ res = await resp.json();+ } catch {}+ if (!res || !res.success) 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.');loadCampaigns();}@@ -1649,6 +1654,11 @@ 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>';+ }// 'queued' only means Harvey wrote a draft — it is not a send.const sent = ['contacted', 'replied', 'meeting', 'closed', 'lost'].includes(r.status);return '<button class="btn btn-primary btn-sm" onclick="openInGmail(' + i + ',' + s + ',' + ri + ')">' +diff --git a/tests/test_dashboard_live_status.py b/tests/test_dashboard_live_status.pyindex 03be391..9dbba91 100644--- a/tests/test_dashboard_live_status.py+++ b/tests/test_dashboard_live_status.py@@ -104,7 +104,7 @@ def test_queued_drafts_are_not_counted_as_sent(client, env):_prospect(env, "p2", "[email protected]", status="contacted")_campaign(env, "c1", ["p1", "p2"])data = client.get("/api/live-status").json()- sent = _step(data, "Sent by you")+ sent = _step(data, "Sent")assert (sent["done"], sent["total"]) == (1, 2)assert _step(data, "Write first emails")["done"] == 2 # per person, not per campaignassert data["next"] == "Open Campaigns and send the 1 unsent email(s)."@@ -142,3 +142,26 @@ def test_a_killed_run_is_reported_as_stopped_not_running(client, env):assert [r["stage"] for r in data["stopped"]] == ["profile"]assert _step(data, "Read their websites")["state"] != "running"assert "stopped before finishing" in data["next"]+++def _outbox(env, oid, pid, status):+ _sql(env, "INSERT INTO outbox (id, prospect_id, campaign_id, step, to_email, subject, body, "+ "send_at, status) VALUES (?, ?, 'c1', 1, '[email protected]', 's', 'b', "+ "'2026-01-01T00:00:00', ?)", (oid, pid, status))+++def test_drafts_waiting_in_the_outbox_point_there_not_at_gmail(client, env):+ # 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")+ _campaign(env, "c1", ["p1"])+ _outbox(env, "o1", "p1", "pending_review")+ assert client.get("/api/live-status").json()["next"] == \+ "Review the 1 draft(s) waiting in the Outbox."+++def test_approved_mail_harvey_will_send_is_not_a_job_for_the_user(client, env):+ _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"]diff --git a/tests/test_dashboard_manual_send.py b/tests/test_dashboard_manual_send.pyindex 4350fab..79e3de3 100644--- a/tests/test_dashboard_manual_send.py+++ b/tests/test_dashboard_manual_send.py@@ -102,3 +102,76 @@ def test_unknown_prospect_is_refused(client):def test_missing_body_means_sent(client, env):_prospect(env, "p1", "[email protected]")assert client.post("/api/prospects/p1/sent").json()["sent"] is True+++# ── Never email someone twice ──+++def _outbox(env, oid, pid, status, step=1, campaign="c1"):+ _sql(env, "INSERT INTO outbox (id, prospect_id, campaign_id, step, to_email, subject, body, "+ "send_at, status) VALUES (?, ?, ?, ?, '[email protected]', 's', 'b', "+ "'2026-01-01T00:00:00', ?)", (oid, pid, campaign, step, status))+++def _status(env, table, row_id):+ with sqlite3.connect(env["db"]) as db:+ return db.execute(f"SELECT status FROM {table} WHERE id = ?", (row_id,)).fetchone()[0]+++def test_sending_by_hand_cancels_what_harvey_had_queued(client, env):+ _prospect(env, "p1", "[email protected]", status="queued")+ _outbox(env, "o1", "p1", "approved", step=1)+ _outbox(env, "o2", "p1", "pending_review", step=2)+ client.post("/api/prospects/p1/sent", json={"sent": True})+ assert _status(env, "outbox", "o1") == "cancelled"+ assert _status(env, "outbox", "o2") == "cancelled"+++def test_undo_puts_the_prospect_and_their_drafts_back_for_review(client, env):+ _prospect(env, "p1", "[email protected]", status="queued")+ _outbox(env, "o1", "p1", "approved")+ client.post("/api/prospects/p1/sent", json={"sent": True})+ assert client.post("/api/prospects/p1/sent", json={"sent": False}).json()["sent"] is False+ assert _status(env, "prospects", "p1") == "queued" # not 'new': the Writer won't redraft+ assert _status(env, "outbox", "o1") == "pending_review" # back to you, never straight out+++def test_undo_never_cancels_an_unrelated_cancellation(client, env):+ _prospect(env, "p1", "[email protected]", status="queued")+ _outbox(env, "o1", "p1", "cancelled")+ client.post("/api/prospects/p1/sent", json={"sent": True})+ client.post("/api/prospects/p1/sent", json={"sent": False})+ assert _status(env, "outbox", "o1") == "cancelled"+++def test_unticking_someone_harvey_emailed_is_refused(client, env):+ _prospect(env, "p1", "[email protected]", status="contacted")+ _outbox(env, "o1", "p1", "sent")+ r = client.post("/api/prospects/p1/sent", json={"sent": False})+ assert r.status_code == 409+ assert _status(env, "prospects", "p1") == "contacted"+++def test_unticking_someone_sent_through_instantly_is_refused(client, env):+ _prospect(env, "p1", "[email protected]", status="contacted")+ _campaign(env, "c1", ["p1"])+ _sql(env, "UPDATE campaigns SET instantly_campaign_id = 'inst-1', status = 'active'")+ assert client.post("/api/prospects/p1/sent", json={"sent": False}).status_code == 409+ assert _status(env, "prospects", "p1") == "contacted"+++def test_recipients_say_when_harvey_is_sending_to_them(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")+ 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++[email protected]("payload", [[], "x"])+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 == 400+ assert _status(env, "prospects", "p1") == "new"