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 the claimed text, surface stuck sends anywhere, never relabel sent mail
Ethan4f07648c6cb1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 618c322..0bf60dd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,7 +16,9 @@ minor versions can still change behaviour.longer send the same email twice. An email cut off mid-send (Harvey stopped,or the provider raised an error) is marked failed and never retried, sinceit may have gone out; it shows under "Didn't send" with a note to check your- Sent folder.+ Sent folder, and the dashboard won't offer to email that person by hand.+ Rejecting an email that is already sending or sent is refused instead of+ relabelling it.- Keep local website requests out of private networks, including redirects andDNS rebinding. Preserve the original hostname for TLS verification. Websitefetching (search, company sites, profiling, the training crawler) now ignoresdiff --git a/harvey/agents/sender.py b/harvey/agents/sender.pyindex 133fc36..7ced9f2 100644--- a/harvey/agents/sender.py+++ b/harvey/agents/sender.py@@ -22,7 +22,9 @@ 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 HAND_SENT_REASON, MANUAL_SEND_KEY, StateManager+from harvey.state import (+ HAND_SENT_REASON, MANUAL_SEND_KEY, MAYBE_SENT_PREFIX, StateManager,+)logger = logging.getLogger("harvey.sender")@@ -30,10 +32,6 @@ logger = logging.getLogger("harvey.sender")# instead of bursting the daily cap in one minute.MAX_SENDS_PER_CYCLE = 8SEND_JITTER_SECONDS = (4, 15)-# A claimed email still not finished after this long was cut off mid-send (a-# send itself takes seconds). Long enough never to catch another sender's-# email in flight.-STALE_SENDING_AFTER = timedelta(minutes=15)# Prospect pipeline statuses that mean "stop emailing this person".STOP_STATUSES = {"replied", "opted_out", "lost", "meeting", "closed"}@@ -334,6 +332,14 @@ class Sender:async def _run_native(self):"""Stage new campaigns into the outbox, then drain what's due."""+ # Before any early return: a send cut off mid-way must show up as+ # failed even while sending is paused or no mailbox is connected.+ stale = await self.state.fail_stale_sending_outbox()+ if stale:+ logger.warning(+ f"Sender: {stale} email(s) were interrupted mid-send and won't be "+ "retried. Check your Sent folder; they're under Didn't send."+ )paused = await self.state.get_setting(KILL_SWITCH_KEY)if paused:logger.warning(@@ -475,13 +481,6 @@ class Sender:)return- stale = await self.state.fail_stale_sending_outbox(STALE_SENDING_AFTER)- if stale:- logger.warning(- f"Sender: {stale} email(s) were interrupted mid-send and won't be "- "retried. Check your Sent folder; they're under Didn't send."- )-max_daily = self.config.channels.email.max_daily_sendssent_today = await self.state.count_outbox_sent_today()budget = min(MAX_SENDS_PER_CYCLE, max_daily - sent_today)@@ -559,6 +558,9 @@ class Sender:# cancelled it since the queue was read; then it stays cancelled.if not await self.state.claim_outbox_item(item["id"]):continue+ # Send the email as it is now, not as the queue read it: it may+ # have been edited and approved again since.+ item = await self.state.get_outbox_item(item["id"]) or item# Whatever landed between the checks above and the claim (a reply# sets the status before it cancels) is caught here, with fresh# data. From now on nothing else can cancel this email.@@ -579,7 +581,7 @@ class Sender:# It may have gone out before the error: never retry it.await self.state.update_outbox_item(item["id"], status="failed",- error=f"send error, may have gone out: {e}"[:300],+ error=f"{MAYBE_SENT_PREFIX}send error: {e}"[:300],)logger.warning(f"Sender: send to {item['to_email']} raised: {e}")continuediff --git a/harvey/cli.py b/harvey/cli.pyindex 06a56ee..a79d7f8 100644--- a/harvey/cli.py+++ b/harvey/cli.py@@ -464,8 +464,8 @@ def cmd_outbox(args):print(f"\n {'Approved.' if n else 'No pending item with that id.'}\n")returnif args.reject:- await state.update_outbox_item(args.reject, status="rejected")- print("\n Rejected.\n")+ n = await state.reject_outbox_item(args.reject)+ print(f"\n {'Rejected.' if n else 'Nothing waiting to send with that id (already sending or sent?).'}\n")returnpaused = await state.get_setting("sending_paused")diff --git a/harvey/dashboard.py b/harvey/dashboard.pyindex 74190f7..239d158 100644--- a/harvey/dashboard.py+++ b/harvey/dashboard.py@@ -846,11 +846,16 @@ async def get_outbox_api():try:state = _state()await state.init_db()+ # A send cut off mid-way shows up under Didn't send even when Harvey+ # isn't running.+ await state.fail_stale_sending_outbox()return {"paused": await state.get_setting("sending_paused"),"pending": await _with_context(await state.get_outbox(status="pending_review", limit=100)),- "approved": await state.get_outbox(status="approved", limit=50),+ # Mail going out right now leads the list.+ "approved": (await state.get_outbox(status="sending", limit=10)+ + await state.get_outbox(status="approved", limit=50)),"sent": (await query_db("SELECT * FROM outbox WHERE status = 'sent' ""ORDER BY sent_at DESC LIMIT 25")),@@ -978,11 +983,15 @@ async def _harvey_committed_ids() -> set[str]:"""Everyone Harvey has approved or sent mail for (Outbox or Instantly).Approved mail can be going out at this moment, so these people are past- the point where a hand send can be recorded safely. A draft that only+ the point where a hand send can be recorded safely. So is anyone whose+ send was cut off mid-way: it may have reached them. A draft that onlyawaits review isn't: marking the person sent cancels it."""+ from harvey.state import MAYBE_SENT_PREFIXids = {r["prospect_id"] for r in await query_db(- "SELECT DISTINCT prospect_id FROM outbox WHERE status IN ('approved', 'sending', 'sent')")}+ "SELECT DISTINCT prospect_id FROM outbox WHERE status IN ('approved', 'sending', 'sent') "+ "OR (status = 'failed' AND substr(error, 1, ?) = ?)",+ (len(MAYBE_SENT_PREFIX), MAYBE_SENT_PREFIX))}for row in await query_db("SELECT prospect_ids_json FROM campaigns WHERE COALESCE(instantly_campaign_id, '') != ''"):try:@@ -1001,9 +1010,15 @@ async def _hand_sent_ids() -> set[str]: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 IN ('sending', 'sent') LIMIT 1",- (prospect_id,)):+ """Did Harvey itself email this person (native send, or an Instantly campaign)?++ A send in flight, or cut off mid-way, counts: it may have reached them.+ """+ from harvey.state import MAYBE_SENT_PREFIX+ if await query_db(+ "SELECT 1 FROM outbox WHERE prospect_id = ? AND (status IN ('sending', 'sent') "+ "OR (status = 'failed' AND substr(error, 1, ?) = ?)) LIMIT 1",+ (prospect_id, len(MAYBE_SENT_PREFIX), MAYBE_SENT_PREFIX)):return Truefor row in await query_db("SELECT prospect_ids_json FROM campaigns WHERE COALESCE(instantly_campaign_id, '') != ''"):@@ -1097,7 +1112,8 @@ async def outbox_reject(item_id: str):try:state = _state()await state.init_db()- await state.update_outbox_item(item_id, status="rejected")+ if not await state.reject_outbox_item(item_id):+ return _refuse("That email is already sending or sent, so it can't be rejected.")return {"success": True}except Exception as e:return JSONResponse({"success": False, "message": str(e)}, status_code=500)diff --git a/harvey/state.py b/harvey/state.pyindex ec310d9..aad4439 100644--- a/harvey/state.py+++ b/harvey/state.py@@ -38,11 +38,18 @@ WRITABLE_EMAIL_STATUSES = ("verified", "risky")MANUAL_SEND_KEY = "manual_send:"# Outbox cancel reason for mail the user sent by hand instead; undo restores it.HAND_SENT_REASON = "sent_by_hand"-# Outbox error for an email Harvey stopped in the middle of sending.+# Outbox errors starting with this: the send was cut off and the email may+# have reached them. Never retried, and counted as Harvey's mail, so the+# dashboard never offers a second one by hand.+MAYBE_SENT_PREFIX = "may have gone out: "STALE_SENDING_ERROR = (- "interrupted while sending; it may have gone out, so check your Sent "- "folder before sending it again"+ MAYBE_SENT_PREFIX + "Harvey stopped in the middle of sending it; check "+ "your Sent folder before emailing them again")+# A claimed email still not finished after this long was cut off mid-send (a+# send itself takes seconds, and a whole cycle is stopped after 10 minutes).+# Long enough never to catch another sender's email in flight.+STALE_SENDING_AFTER = timedelta(minutes=15)def _new_id() -> str:@@ -947,7 +954,9 @@ class StateManager:await db.commit()return cursor.rowcount == 1- async def fail_stale_sending_outbox(self, older_than: timedelta) -> int:+ async def fail_stale_sending_outbox(+ self, older_than: timedelta = STALE_SENDING_AFTER+ ) -> int:"""Items claimed long ago and never finished (Harvey stopped mid-send).Whether they went out is unknown, so they are never retried: they@@ -1015,6 +1024,18 @@ class StateManager:await db.commit()return len(rows)+ async def reject_outbox_item(self, item_id: str) -> int:+ """Reject an item still waiting to go out. Mail already on its way+ or sent is never relabelled. Returns rows changed (0/1)."""+ async with self._connect() as db:+ cursor = await db.execute(+ "UPDATE outbox SET status = 'rejected', updated_at = ? "+ "WHERE id = ? AND status IN ('pending_review', 'approved')",+ (_utcnow().isoformat(), item_id),+ )+ 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/tests/test_dashboard_manual_send.py b/tests/test_dashboard_manual_send.pyindex 4ed26c0..51b393f 100644--- a/tests/test_dashboard_manual_send.py+++ b/tests/test_dashboard_manual_send.py@@ -7,6 +7,7 @@ the "Mark as sent" toggle (never erases a reply, refuses unknown prospects).import asyncioimport jsonimport sqlite3+from datetime import datetime, timezoneimport pytestfrom fastapi.testclient import TestClient@@ -211,6 +212,48 @@ def test_someone_whose_mail_is_being_sent_cant_be_marked_sent(client, env):assert _status(env, "outbox", "o1") == "sending"+def test_mail_that_may_have_gone_out_counts_as_sent_by_harvey(client, env):+ # A send cut off mid-way may have reached them: never offer a second one.+ from harvey.state import MAYBE_SENT_PREFIX+ _prospect(env, "p1", "[email protected]", status="queued")+ _campaign(env, "c1", ["p1"])+ _outbox(env, "o1", "p1", "failed")+ _sql(env, "UPDATE outbox SET error = ? WHERE id = 'o1'", (MAYBE_SENT_PREFIX + "timeout",))+ recipient = client.get("/api/campaigns").json()[0]["recipients"][0]+ assert recipient["can_mark_sent"] is False and recipient["can_send_by_hand"] is False+ assert client.post("/api/prospects/p1/sent", json={"sent": True}).status_code == 409+++def test_mail_that_plainly_failed_doesnt_block_a_hand_send(client, env):+ _prospect(env, "p1", "[email protected]", status="queued")+ _campaign(env, "c1", ["p1"])+ _outbox(env, "o1", "p1", "failed")+ _sql(env, "UPDATE outbox SET error = 'gate: unrendered merge tag' WHERE id = 'o1'")+ assert client.get("/api/campaigns").json()[0]["recipients"][0]["can_send_by_hand"] is True+++def test_the_outbox_tab_shows_mail_being_sent_and_surfaces_stuck_mail(client, env):+ _prospect(env, "p1", "[email protected]", status="contacted")+ _outbox(env, "o1", "p1", "sending")+ _sql(env, "UPDATE outbox SET updated_at = ? WHERE id = 'o1'",+ (datetime.now(timezone.utc).replace(tzinfo=None).isoformat(),))+ _outbox(env, "o2", "p1", "sending", step=2)+ _sql(env, "UPDATE outbox SET updated_at = '2026-01-01T00:00:00' WHERE id = 'o2'")+ data = client.get("/api/outbox").json()+ assert [i["id"] for i in data["approved"]] == ["o1"]+ assert [i["id"] for i in data["failed"]] == ["o2"]+++def test_rejecting_mail_already_on_its_way_is_refused(client, env):+ _prospect(env, "p1", "[email protected]", status="contacted")+ _outbox(env, "o1", "p1", "sending")+ _outbox(env, "o2", "p1", "sent", step=2)+ assert client.post("/api/outbox/o1/reject").status_code == 409+ assert client.post("/api/outbox/o2/reject").status_code == 409+ assert _status(env, "outbox", "o1") == "sending"+ assert _status(env, "outbox", "o2") == "sent"++def test_drafts_awaiting_review_dont_hide_the_gmail_button_when_harvey_cant_send(client, env):_prospect(env, "p1", "[email protected]", status="queued")_campaign(env, "c1", ["p1"])diff --git a/tests/test_outbox_claim.py b/tests/test_outbox_claim.pyindex af9bd38..c97064a 100644--- a/tests/test_outbox_claim.py+++ b/tests/test_outbox_claim.py@@ -170,10 +170,80 @@ async def test_an_email_stuck_sending_is_failed_after_a_while_never_resent(stateawait db.commit()provider = FakeProvider()- await make_sender(state, provider)._drain_due()+ await make_sender(state, provider)._run_native()assert provider.sent == []stuck_item = await state.get_outbox_item(stuck)assert stuck_item["status"] == "failed"assert "Sent folder" in stuck_item["error"]# A claim this recent may be another sender's email in flight.assert (await state.get_outbox_item(fresh))["status"] == "sending"+++async def test_the_send_uses_the_text_as_it_is_when_claimed(state, monkeypatch):+ # The queue is read once per cycle; the draft can be edited and+ # re-approved during the pacing pauses before its turn comes.+ pid = await seed_prospect(state, status="contacted")+ item_id = await _approved(state, pid)+ real_claim = state.claim_outbox_item++ async def edited_before_its_turn(item_id):+ await state.update_outbox_item(+ item_id, subject="edited subject", body="Edited, plain note. Question?")+ return await real_claim(item_id)+ monkeypatch.setattr(state, "claim_outbox_item", edited_before_its_turn)++ provider = FakeProvider()+ await make_sender(state, provider)._drain_due()+ assert [(m["subject"], m["body"]) for m in provider.sent] == [+ ("edited subject", "Edited, plain note. Question?")]+++async def _stuck_since(state, item_id, hours=1):+ await state.claim_outbox_item(item_id)+ long_ago = (datetime.now(timezone.utc).replace(tzinfo=None)+ - timedelta(hours=hours)).isoformat()+ async with state._connect() as db:+ await db.execute("UPDATE outbox SET updated_at = ? WHERE id = ?", (long_ago, item_id))+ await db.commit()+++async def test_a_stuck_email_is_surfaced_even_while_sending_is_paused(state):+ pid = await seed_prospect(state, status="contacted")+ stuck = await _approved(state, pid)+ await _stuck_since(state, stuck)+ await state.set_setting("sending_paused", "bounce rate")+ await make_sender(state, FakeProvider())._run_native()+ assert (await state.get_outbox_item(stuck))["status"] == "failed"+++async def test_a_stuck_email_is_surfaced_even_with_no_mailbox_connected(state):+ pid = await seed_prospect(state, status="contacted")+ stuck = await _approved(state, pid)+ await _stuck_since(state, stuck)++ class Unconfigured(FakeProvider):+ def is_configured(self):+ return False+ await make_sender(state, Unconfigured())._run_native()+ assert (await state.get_outbox_item(stuck))["status"] == "failed"+++async def test_reject_never_touches_mail_already_sending_or_sent(state):+ pid = await seed_prospect(state, status="contacted")+ sending = await _approved(state, pid)+ await state.claim_outbox_item(sending)+ sent = await _approved(state, pid, step=3)+ await state.update_outbox_item(sent, status="sent")+ pending = await state.add_outbox_item(+ prospect_id=pid, to_email="[email protected]", subject="s", body="b",+ send_at=_now_iso(), campaign_id="c1", step=4)+ assert await state.reject_outbox_item(sending) == 0+ assert await state.reject_outbox_item(sent) == 0+ assert await state.reject_outbox_item(pending) == 1+ assert (await state.get_outbox_item(sending))["status"] == "sending"+ assert (await state.get_outbox_item(sent))["status"] == "sent"+ assert (await state.get_outbox_item(pending))["status"] == "rejected"