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.

Claim each email before sending it, so a cancel is never overridden

Ethandac08b3f271d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f856615..618c322 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,14 @@ minor versions can still change behaviour.
### Fixed
+- The Sender claims each email right before sending it. A reply, bounce, hand
+ send or rejection that cancels an approved email while the Sender is working
+ through its queue now stops it, instead of the Sender sending its earlier
+ copy and recording it as sent. Two Harvey processes running at once can no
+ 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, since
+ it may have gone out; it shows under "Didn't send" with a note to check your
+ Sent folder.
- Keep local website requests out of private networks, including redirects and
DNS rebinding. Preserve the original hostname for TLS verification. Website
fetching (search, company sites, profiling, the training crawler) now ignores
diff --git a/harvey/agents/sender.py b/harvey/agents/sender.py
index 0824536..133fc36 100644
--- a/harvey/agents/sender.py
+++ b/harvey/agents/sender.py
@@ -30,6 +30,10 @@ logger = logging.getLogger("harvey.sender")
# instead of bursting the daily cap in one minute.
MAX_SENDS_PER_CYCLE = 8
SEND_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"}
@@ -435,6 +439,33 @@ class Sender:
details={"campaign": campaign.name, "staged": staged, "mode": mode},
)
+ async def _blocked(self, item: dict, prospect, allow_risky: bool) -> tuple[str, str] | None:
+ """Why this email must not go out, as (status, error), or None."""
+ if prospect is None:
+ return "failed", "prospect missing"
+ if item["kind"] == "sequence":
+ # Stop-on-reply / opt-out: never continue a sequence after contact.
+ if prospect.status in STOP_STATUSES:
+ return "cancelled", f"prospect status '{prospect.status}'"
+ # The user already emailed them by hand: whatever Harvey staged
+ # (before, during or after that) would be a second email.
+ if await self.state.get_setting(MANUAL_SEND_KEY + prospect.id):
+ return "cancelled", HAND_SENT_REASON
+ # A first email to someone already contacted is always a duplicate.
+ if item["step"] == 1 and prospect.status == "contacted":
+ return "cancelled", "already contacted"
+ gate = pre_send_check(
+ item["to_email"], item["subject"], item["body"],
+ prospect=prospect, allow_risky=allow_risky, kind=item["kind"],
+ )
+ if not gate:
+ logger.warning(
+ f"Sender: gate blocked email to {item['to_email']}: "
+ f"{gate.reasons}"
+ )
+ return "failed", "gate: " + "; ".join(gate.reasons)[:300]
+ return None
+
async def _drain_due(self):
"""Send due, approved outbox items through the provider."""
if not self.provider.is_configured():
@@ -444,6 +475,13 @@ 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_sends
sent_today = await self.state.count_outbox_sent_today()
budget = min(MAX_SENDS_PER_CYCLE, max_daily - sent_today)
@@ -487,45 +525,10 @@ class Sender:
continue
prospect = await self.state.get_prospect(item["prospect_id"])
- if prospect is None:
+ blocked = await self._blocked(item, prospect, allow_risky)
+ if blocked:
await self.state.update_outbox_item(
- item["id"], status="failed", error="prospect missing"
- )
- continue
-
- # Stop-on-reply / opt-out: never continue a sequence after contact.
- if item["kind"] == "sequence" and prospect.status in STOP_STATUSES:
- await self.state.update_outbox_item(
- item["id"], status="cancelled",
- 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=HAND_SENT_REASON)
- 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")
- continue
-
- gate = pre_send_check(
- item["to_email"], item["subject"], item["body"],
- prospect=prospect, allow_risky=allow_risky, kind=item["kind"],
- )
- if not gate:
- await self.state.update_outbox_item(
- item["id"], status="failed",
- error="gate: " + "; ".join(gate.reasons)[:300],
- )
- logger.warning(
- f"Sender: gate blocked email to {item['to_email']}: "
- f"{gate.reasons}"
- )
+ item["id"], status=blocked[0], error=blocked[1])
continue
# Optional compliance check (compliance.precleared): one per
@@ -552,11 +555,34 @@ class Sender:
continue
receipt_id = clearance.receipt_id
- result = await self.provider.send_email(
- item["to_email"], item["subject"], item["body"],
- thread_ref=item.get("thread_ref", ""),
- in_reply_to=item.get("in_reply_to", ""),
- )
+ # Claim it. A reply, bounce, hand send or rejection may have
+ # cancelled it since the queue was read; then it stays cancelled.
+ if not await self.state.claim_outbox_item(item["id"]):
+ continue
+ # 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.
+ prospect = await self.state.get_prospect(item["prospect_id"])
+ blocked = await self._blocked(item, prospect, allow_risky)
+ if blocked:
+ await self.state.update_outbox_item(
+ item["id"], status=blocked[0], error=blocked[1])
+ continue
+
+ try:
+ result = await self.provider.send_email(
+ item["to_email"], item["subject"], item["body"],
+ thread_ref=item.get("thread_ref", ""),
+ in_reply_to=item.get("in_reply_to", ""),
+ )
+ except Exception as e:
+ # 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],
+ )
+ logger.warning(f"Sender: send to {item['to_email']} raised: {e}")
+ continue
if not result.ok:
await self.state.update_outbox_item(
item["id"], status="failed", error=result.error[:300]
diff --git a/harvey/dashboard.py b/harvey/dashboard.py
index 7b348f5..74190f7 100644
--- a/harvey/dashboard.py
+++ b/harvey/dashboard.py
@@ -982,7 +982,7 @@ async def _harvey_committed_ids() -> set[str]:
awaits review isn't: marking the person sent cancels it.
"""
ids = {r["prospect_id"] for r in await query_db(
- "SELECT DISTINCT prospect_id FROM outbox WHERE status IN ('approved', 'sent')")}
+ "SELECT DISTINCT prospect_id FROM outbox WHERE status IN ('approved', 'sending', 'sent')")}
for row in await query_db(
"SELECT prospect_ids_json FROM campaigns WHERE COALESCE(instantly_campaign_id, '') != ''"):
try:
@@ -1002,7 +1002,7 @@ 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 = 'sent' LIMIT 1",
+ if await query_db("SELECT 1 FROM outbox WHERE prospect_id = ? AND status IN ('sending', 'sent') LIMIT 1",
(prospect_id,)):
return True
for row in await query_db(
diff --git a/harvey/state.py b/harvey/state.py
index 868ccff..ec310d9 100644
--- a/harvey/state.py
+++ b/harvey/state.py
@@ -38,6 +38,11 @@ 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.
+STALE_SENDING_ERROR = (
+ "interrupted while sending; it may have gone out, so check your Sent "
+ "folder before sending it again"
+)
def _new_id() -> str:
@@ -926,6 +931,38 @@ class StateManager:
)
await db.commit()
+ async def claim_outbox_item(self, item_id: str) -> bool:
+ """Take an approved item for sending: approved → sending, atomically.
+
+ False when it is no longer approved (cancelled by a reply, bounce or
+ hand send, rejected, or taken by another sender), so it must not go
+ out. Cancels never touch a claimed item: it is already on its way.
+ """
+ async with self._connect() as db:
+ cursor = await db.execute(
+ "UPDATE outbox SET status = 'sending', updated_at = ? "
+ "WHERE id = ? AND status = 'approved'",
+ (_utcnow().isoformat(), item_id),
+ )
+ await db.commit()
+ return cursor.rowcount == 1
+
+ async def fail_stale_sending_outbox(self, older_than: timedelta) -> int:
+ """Items claimed long ago and never finished (Harvey stopped mid-send).
+
+ Whether they went out is unknown, so they are never retried: they
+ become failed with a note to check the Sent folder.
+ """
+ cutoff = (_utcnow() - older_than).isoformat()
+ async with self._connect() as db:
+ cursor = await db.execute(
+ "UPDATE outbox SET status = 'failed', error = ?, updated_at = ? "
+ "WHERE status = 'sending' AND updated_at < ?",
+ (STALE_SENDING_ERROR, _utcnow().isoformat(), cutoff),
+ )
+ await db.commit()
+ return cursor.rowcount
+
async def edit_outbox_draft(self, item_id: str, subject: str, body: str) -> int:
"""Rewrite a draft's subject and body — only while it awaits review.
diff --git a/tests/test_dashboard_manual_send.py b/tests/test_dashboard_manual_send.py
index 1b84230..4ed26c0 100644
--- a/tests/test_dashboard_manual_send.py
+++ b/tests/test_dashboard_manual_send.py
@@ -202,6 +202,15 @@ def test_someone_with_approved_mail_cant_be_marked_sent(client, env):
assert _status(env, "outbox", "o1") == "approved"
+def test_someone_whose_mail_is_being_sent_cant_be_marked_sent(client, env):
+ _prospect(env, "p1", "[email protected]", status="queued")
+ _campaign(env, "c1", ["p1"])
+ _outbox(env, "o1", "p1", "sending")
+ assert client.get("/api/campaigns").json()[0]["recipients"][0]["can_mark_sent"] is False
+ assert client.post("/api/prospects/p1/sent", json={"sent": True}).status_code == 409
+ assert _status(env, "outbox", "o1") == "sending"
+
+
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.py
new file mode 100644
index 0000000..af9bd38
--- /dev/null
+++ b/tests/test_outbox_claim.py
@@ -0,0 +1,179 @@
+"""The Sender claims each email before sending it.
+
+A reply, bounce, hand send or rejection can cancel an approved email while the
+Sender is working through its queue. Without a claim the Sender sends from the
+copy it read earlier and then overwrites the cancel with 'sent'. With one,
+an email goes out only if it was still approved the moment the Sender took it,
+and only once, however many senders run.
+"""
+
+import asyncio
+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_prospect, state,
+)
+
+
+def _now_iso():
+ return datetime.now(timezone.utc).replace(tzinfo=None).isoformat()
+
+
+async def _approved(state, pid, step=2):
+ return 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="c1", step=step,
+ )
+
+
+async def _reply_lands(state, pid):
+ # What the Handler does when a reply arrives: status first, then cancel.
+ await state.update_prospect_status(pid, "replied")
+ await state.cancel_pending_outbox_for_prospect(pid)
+
+
+async def test_a_cancel_after_the_checks_is_never_overwritten_by_a_send(state, monkeypatch):
+ pid = await seed_prospect(state, status="contacted")
+ item_id = await _approved(state, pid)
+ real_claim = state.claim_outbox_item
+
+ async def claim_after_reply(item_id):
+ # The reply is processed after the Sender's checks, before its claim.
+ await _reply_lands(state, pid)
+ return await real_claim(item_id)
+ monkeypatch.setattr(state, "claim_outbox_item", claim_after_reply)
+
+ provider = FakeProvider()
+ await make_sender(state, provider)._drain_due()
+ assert provider.sent == []
+ item = await state.get_outbox_item(item_id)
+ assert item["status"] == "cancelled" and item["error"] == "stop_on_reply"
+
+
+async def test_a_reply_recorded_just_after_the_claim_still_stops_the_send(state, monkeypatch):
+ pid = await seed_prospect(state, status="contacted")
+ item_id = await _approved(state, pid)
+ real_claim = state.claim_outbox_item
+
+ async def claim_then_reply(item_id):
+ claimed = await real_claim(item_id)
+ await _reply_lands(state, pid) # the cancel can't touch a claimed row
+ return claimed
+ monkeypatch.setattr(state, "claim_outbox_item", claim_then_reply)
+
+ provider = FakeProvider()
+ await make_sender(state, provider)._drain_due()
+ assert provider.sent == []
+ item = await state.get_outbox_item(item_id)
+ assert item["status"] == "cancelled"
+ assert "replied" in item["error"]
+
+
+async def test_a_hand_send_recorded_just_after_the_claim_still_stops_the_send(state, monkeypatch):
+ pid = await seed_prospect(state, status="queued")
+ item_id = await _approved(state, pid, step=1)
+ real_claim = state.claim_outbox_item
+
+ async def claim_then_hand_send(item_id):
+ claimed = await real_claim(item_id)
+ await state.set_setting(MANUAL_SEND_KEY + pid, "queued")
+ return claimed
+ monkeypatch.setattr(state, "claim_outbox_item", claim_then_hand_send)
+
+ provider = FakeProvider()
+ await make_sender(state, provider)._drain_due()
+ assert provider.sent == []
+ assert (await state.get_outbox_item(item_id))["error"] == "sent_by_hand"
+
+
+async def test_a_bounce_recorded_just_after_the_claim_still_stops_the_send(state, monkeypatch):
+ pid = await seed_prospect(state, status="contacted")
+ item_id = await _approved(state, pid)
+ real_claim = state.claim_outbox_item
+
+ async def claim_then_bounce(item_id):
+ claimed = await real_claim(item_id)
+ prospect = await state.get_prospect(pid)
+ await state.update_prospect_email(pid, prospect.email, "invalid")
+ return claimed
+ monkeypatch.setattr(state, "claim_outbox_item", claim_then_bounce)
+
+ provider = FakeProvider()
+ await make_sender(state, provider)._drain_due()
+ assert provider.sent == []
+ assert (await state.get_outbox_item(item_id))["status"] == "failed"
+
+
+async def test_two_senders_at_once_send_each_email_once(state):
+ pid = await seed_prospect(state, status="contacted")
+ await _approved(state, pid)
+
+ class SlowProvider(FakeProvider):
+ async def send_email(self, *a, **kw):
+ await asyncio.sleep(0.05) # both drains are inside the loop now
+ return await super().send_email(*a, **kw)
+ provider = SlowProvider()
+ await asyncio.gather(
+ make_sender(state, provider)._drain_due(),
+ make_sender(state, provider)._drain_due(),
+ )
+ assert len(provider.sent) == 1
+ assert len(await state.get_outbox(status="sent")) == 1
+
+
+async def test_claim_takes_only_approved_items(state):
+ pid = await seed_prospect(state, status="contacted")
+ item_id = await _approved(state, pid)
+ assert await state.claim_outbox_item(item_id) is True
+ assert await state.claim_outbox_item(item_id) is False # already taken
+ assert (await state.get_outbox_item(item_id))["status"] == "sending"
+ # Nothing cancels an email that is already on its way.
+ assert await state.cancel_pending_outbox_for_prospect(pid) == 0
+
+
+async def test_a_send_that_raises_is_failed_not_retried(state):
+ pid = await seed_prospect(state, status="contacted")
+ item_id = await _approved(state, pid)
+
+ class BrokenProvider(FakeProvider):
+ async def send_email(self, *a, **kw):
+ raise RuntimeError("connection reset")
+ await make_sender(state, BrokenProvider())._drain_due()
+ item = await state.get_outbox_item(item_id)
+ # It may have gone out before the error, so it is never sent again.
+ assert item["status"] == "failed"
+ assert "connection reset" in item["error"]
+
+
+async def test_an_email_stuck_sending_is_failed_after_a_while_never_resent(state):
+ pid = await seed_prospect(state, status="contacted")
+ stuck = await _approved(state, pid)
+ fresh = await _approved(state, pid, step=3)
+ await state.claim_outbox_item(stuck)
+ await state.claim_outbox_item(fresh)
+ long_ago = (datetime.now(timezone.utc).replace(tzinfo=None)
+ - timedelta(hours=1)).isoformat()
+ async with state._connect() as db: # backdate the claim (Harvey crashed)
+ await db.execute("UPDATE outbox SET updated_at = ? WHERE id = ?", (long_ago, stuck))
+ await db.commit()
+
+ provider = FakeProvider()
+ await make_sender(state, provider)._drain_due()
+ 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"