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.

A hand send can always be recorded, and Open in Gmail records it first

Ethan6c188710a883
diff --git a/harvey/agents/sender.py b/harvey/agents/sender.py
index de06c25..0824536 100644
--- a/harvey/agents/sender.py
+++ b/harvey/agents/sender.py
@@ -22,7 +22,7 @@ from harvey.gate import pre_send_check
from harvey.integrations.instantly import InstantlyClient
from harvey.integrations.mail_provider import NATIVE_PROVIDERS, get_mail_provider
from harvey.integrations.precleared import PreclearedClient
-from harvey.state import MANUAL_SEND_KEY, StateManager
+from harvey.state import HAND_SENT_REASON, MANUAL_SEND_KEY, StateManager
logger = logging.getLogger("harvey.sender")
@@ -505,7 +505,7 @@ class Sender:
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")
+ 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":
diff --git a/harvey/dashboard.py b/harvey/dashboard.py
index 014fa86..326b798 100644
--- a/harvey/dashboard.py
+++ b/harvey/dashboard.py
@@ -936,7 +936,6 @@ async def outbox_edit(item_id: str, request: Request):
return JSONResponse({"success": False, "message": str(e)}, status_code=500)
-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")
@@ -954,8 +953,9 @@ def _harvey_can_send() -> bool:
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()
+ from harvey.config import legacy_sending_held
email = config.channels.email
- if not email.enabled:
+ if not email.enabled or legacy_sending_held(config):
return False
if (email.provider or "").strip().lower() in NATIVE_PROVIDERS:
provider = get_mail_provider(config, env)
@@ -974,11 +974,15 @@ def _send_as() -> str:
return ""
-async def _harvey_sending_ids() -> set[str]:
- """Everyone Harvey has queued, approved or sent mail for (Outbox or Instantly)."""
+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
+ 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 ('pending_review', 'approved', 'sent')")}
+ "SELECT DISTINCT prospect_id FROM outbox WHERE status IN ('approved', 'sent')")}
for row in await query_db(
"SELECT prospect_ids_json FROM campaigns WHERE COALESCE(instantly_campaign_id, '') != ''"):
try:
@@ -1018,7 +1022,7 @@ def _refuse(message: str, code: int = 409):
@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_KEY
+ from harvey.state import HAND_SENT_REASON, MANUAL_SEND_KEY
try:
try:
body = await request.json()
@@ -1045,11 +1049,12 @@ async def mark_prospect_sent(prospect_id: str, request: Request):
# 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.")
+ # Allowed even when Harvey can send: recording "I already emailed
+ # them" can only ever stop Harvey sending. Not once Harvey has
+ # approved or sent mail to them, though: that may be going out now.
+ if prospect_id in await _harvey_committed_ids():
+ return _refuse("Harvey has already approved or sent an email to this person. "
+ "Check the Outbox.")
await state.set_setting(key, current)
await state.update_prospect_status(prospect_id, "contacted")
# Anything Harvey had queued for them must not go out as well.
@@ -1139,7 +1144,7 @@ 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()
+ committed = await _harvey_committed_ids()
hand_sent = await _hand_sent_ids()
for row in rows:
try:
@@ -1161,10 +1166,14 @@ async def get_campaigns():
row["send_as"] = send_as
for r in row["recipients"]:
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
+ # "I already emailed them": always recordable before Harvey commits.
+ r["can_mark_sent"] = (
+ r["id"] not in hand_sent and r["id"] not in committed
and (r.get("status") or "new") in HAND_SENDABLE_STATUSES
+ )
+ # The Gmail button: only when Harvey can't send itself.
+ r["can_send_by_hand"] = (
+ r["can_mark_sent"] and not harvey_sends
and (r.get("email_status") or "guess") in HAND_SENDABLE_EMAIL
)
return rows
@@ -1460,7 +1469,7 @@ async def get_live_status():
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()
+ skip = await _harvey_committed_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
diff --git a/harvey/state.py b/harvey/state.py
index 63c92c9..868ccff 100644
--- a/harvey/state.py
+++ b/harvey/state.py
@@ -36,6 +36,8 @@ WRITABLE_EMAIL_STATUSES = ("verified", "risky")
# 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:"
+# Outbox cancel reason for mail the user sent by hand instead; undo restores it.
+HAND_SENT_REASON = "sent_by_hand"
def _new_id() -> str:
diff --git a/harvey/web/app.js b/harvey/web/app.js
index 6fc02e3..abdfd3d 100644
--- a/harvey/web/app.js
+++ b/harvey/web/app.js
@@ -1602,7 +1602,7 @@ function fillMergeVars(text, r) {
});
}
-function openInGmail(ci, si, ri) {
+async function openInGmail(ci, si, ri) {
const c = _campaigns[ci];
const step = c && (c.sequence || [])[si];
const r = c && (c.recipients || [])[ri];
@@ -1616,13 +1616,19 @@ function openInGmail(ci, si, ri) {
'&body=' + encodeURIComponent(fillMergeVars(step.body, r));
const left = /\{\{\s*\w+\s*\}\}/.test(fillMergeVars(step.subject, r) + fillMergeVars(step.body, r));
// No 'noopener' feature string: with it window.open always returns null,
- // so a blocked pop-up could not be told apart from a successful one.
- const w = window.open(url, '_blank');
+ // so a blocked pop-up could not be told apart from a successful one. The
+ // tab opens blank right away (inside the click, so it isn't blocked) and
+ // only gets the draft once the send is recorded.
+ const w = window.open('', '_blank');
if (!w) {
showToast('Your browser blocked the Gmail tab. Allow pop-ups for this page and click again.', 'error');
return;
}
w.opener = null;
+ // Record the send BEFORE the user can press Send in Gmail, so Harvey can
+ // never email them as well — not even if they forget to tick the box.
+ if (!r.sent_by_hand && !(await markSent(ci, ri, true))) { w.close(); return; }
+ w.location.href = url;
if (left) showToast('This draft still has a {{placeholder}} in it. Fix it in Gmail before sending.', 'error');
}
@@ -1638,9 +1644,12 @@ async function markSent(ci, ri, 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');
+ 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.');
loadCampaigns();
+ // True only when this call changed it; a status in the reply means they replied or opted out.
+ return ok && sent === !!res.sent && !res.status;
}
async function loadCampaigns() {
@@ -1670,7 +1679,15 @@ async function loadCampaigns() {
'Open in Gmail &rarr; ' + escHtml(r.email) + '</button>' +
'<span class="muted" style="font-size:12px">Harvey won\'t send follow-ups to people you emailed yourself.</span>';
}
- if (!r.can_send_by_hand || s !== 0) return '';
+ if (s !== 0) return '';
+ if (!r.can_send_by_hand) {
+ // Harvey sends here; this only records an email the user already sent.
+ return r.can_mark_sent
+ ? '<label class="muted" style="display:inline-flex;align-items:center;gap:4px;font-size:12px;cursor:pointer">' +
+ '<input type="checkbox" onchange="markSent(' + i + ',' + ri + ',this.checked)"> ' +
+ 'I already emailed ' + escHtml(r.email) + ' myself</label>'
+ : '';
+ }
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 + ')">' +
diff --git a/tests/test_dashboard_live_status.py b/tests/test_dashboard_live_status.py
index 835d6d3..30e6291 100644
--- a/tests/test_dashboard_live_status.py
+++ b/tests/test_dashboard_live_status.py
@@ -165,7 +165,7 @@ def test_drafts_waiting_in_the_outbox_point_there_not_at_gmail(client, env, monk
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.
+ # Even with no mailbox connected now, mail already approved is not the user's to send.
_prospect(env, "p1", "[email protected]", status="queued")
_campaign(env, "c1", ["p1"])
_outbox(env, "o1", "p1", "approved")
diff --git a/tests/test_dashboard_manual_send.py b/tests/test_dashboard_manual_send.py
index 5b8e922..63d34d0 100644
--- a/tests/test_dashboard_manual_send.py
+++ b/tests/test_dashboard_manual_send.py
@@ -123,7 +123,7 @@ def _status(env, table, row_id):
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, "o1", "p1", "pending_review", 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"
@@ -132,11 +132,12 @@ def test_sending_by_hand_cancels_what_harvey_had_queued(client, env):
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")
+ _outbox(env, "o1", "p1", "pending_review")
client.post("/api/prospects/p1/sent", json={"sent": True})
+ assert _status(env, "outbox", "o1") == "cancelled"
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
+ assert _status(env, "outbox", "o1") == "pending_review" # back for review
def test_undo_never_cancels_an_unrelated_cancellation(client, env):
@@ -165,24 +166,47 @@ def test_unticking_someone_sent_through_instantly_is_refused(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") # Harvey queued mail
+ _prospect(env, "p2", "[email protected]", status="queued") # Harvey approved 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")
+ _outbox(env, "o1", "p2", "approved")
recips = {r["id"]: r for r in client.get("/api/campaigns").json()[0]["recipients"]}
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):
+def test_no_gmail_button_while_harvey_can_send_but_a_hand_send_can_still_be_recorded(
+ client, env, monkeypatch):
+ # Recording "I already emailed them" can only stop Harvey sending, so it
+ # is never refused just because a mailbox is connected now.
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
+ _outbox(env, "o1", "p1", "pending_review")
+ r = client.get("/api/campaigns").json()[0]["recipients"][0]
+ assert r["can_send_by_hand"] is False and r["can_mark_sent"] is True
+ assert client.post("/api/prospects/p1/sent", json={"sent": True}).json()["sent"] is True
+ assert _status(env, "prospects", "p1") == "contacted"
+ assert _status(env, "outbox", "o1") == "cancelled"
+
+
+def test_someone_with_approved_mail_cant_be_marked_sent(client, env):
+ # Approved mail may be mid-send right now: the Outbox is where to stop it.
+ _prospect(env, "p1", "[email protected]", status="queued")
+ _campaign(env, "c1", ["p1"])
+ _outbox(env, "o1", "p1", "approved")
+ 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, "prospects", "p1") == "queued"
+ assert _status(env, "outbox", "o1") == "approved"
+
+
+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"])
+ _outbox(env, "o1", "p1", "pending_review") # staged, but no mailbox to send it
+ assert client.get("/api/campaigns").json()[0]["recipients"][0]["can_send_by_hand"] is True
def test_a_hand_sent_prospect_is_marked_for_the_sender(client, env):
@@ -225,8 +249,8 @@ def test_a_body_that_is_not_an_object_is_refused(client, env, payload):
class _Email:
- def __init__(self, enabled=True, provider="smtp"):
- self.enabled, self.provider = enabled, provider
+ def __init__(self, enabled=True, provider="smtp", approval=False):
+ self.enabled, self.provider, self.require_approval = enabled, provider, approval
class _Cfg:
@@ -253,6 +277,7 @@ class _Provider:
(_Cfg(provider="gmail"), _Env(), True, True), # connected: Harvey sends
(_Cfg(provider="instantly"), _Env(instantly="k"), True, True),
(_Cfg(provider="instantly"), _Env(), True, False),
+ (_Cfg(provider="instantly", approval=True), _Env(instantly="k"), True, False), # held
])
def test_harvey_can_send(monkeypatch, cfg, env, provider_ok, expected):
import harvey.config
diff --git a/tests/test_hand_sent_guard.py b/tests/test_hand_sent_guard.py
index 54756dc..bf3b68c 100644
--- a/tests/test_hand_sent_guard.py
+++ b/tests/test_hand_sent_guard.py
@@ -36,7 +36,8 @@ async def test_drain_never_sends_to_someone_emailed_by_hand(state):
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"}
+ # The same reason undo restores, so an undo brings these back too.
+ assert {i["error"] for i in await state.get_outbox(status="cancelled")} == {"sent_by_hand"}
@pytest.mark.asyncio