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.
Campaigns: open a draft in Gmail and mark it sent by hand
YooshaMirzab1dae4b914d7
diff --git a/harvey/dashboard.py b/harvey/dashboard.pyindex 816c31d..5455588 100644--- a/harvey/dashboard.py+++ b/harvey/dashboard.py@@ -802,6 +802,38 @@ async def outbox_approve(item_id: str):return JSONResponse({"success": False, "message": str(e)}, status_code=500)[email protected]("/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."""+ try:+ try:+ body = await request.json()+ except ValueError:+ body = {}+ sent = bool((body or {}).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)+ 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()+ await state.update_prospect_status(prospect_id, "contacted" if sent else "new")+ await state.log_action(+ action_type="manual_send" if sent else "manual_send_undone",+ agent="user",+ details={"prospect_id": prospect_id},+ )+ return {"success": True, "sent": sent}+ except Exception as e:+ return JSONResponse({"success": False, "message": str(e)}, status_code=500)++@app.post("/api/outbox/{item_id}/reject")async def outbox_reject(item_id: str):try:@@ -865,6 +897,13 @@ async def get_campaigns():row["prospect_ids"] = json.loads(row.get("prospect_ids_json", "[]"))except (json.JSONDecodeError, TypeError):row["prospect_ids"] = []+ # 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"WHERE id IN ({','.join('?' * len(ids))}) AND email != ''",+ tuple(ids),+ ) if ids else []return rowsdiff --git a/harvey/web/app.js b/harvey/web/app.jsindex 591914a..f36d4a1 100644--- a/harvey/web/app.js+++ b/harvey/web/app.js@@ -1408,6 +1408,50 @@ async function loadProspects() {el.innerHTML = html + '</tbody></table></div>';}+// 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.+function fillMergeVars(text, r) {+ const vals = {+ first_name: r.first_name || 'there', last_name: r.last_name || '',+ company: r.company || '', title: r.title || '',+ };+ return String(text || '').replace(/\{\{\s*(\w+)\s*\}\}/g,+ (m, k) => (k.toLowerCase() in vals ? vals[k.toLowerCase()] : m));+}++function openInGmail(ci, si, ri) {+ const c = _campaigns[ci];+ const step = c && (c.sequence || [])[si];+ const r = c && (c.recipients || [])[ri];+ if (!step || !r) return;+ const url = 'https://mail.google.com/mail/?view=cm&fs=1' ++ '&to=' + encodeURIComponent(r.email) ++ '&su=' + encodeURIComponent(fillMergeVars(step.subject, r)) ++ '&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');+ if (!w) {+ showToast('Your browser blocked the Gmail tab. Allow pop-ups for this page and click again.', 'error');+ return;+ }+ w.opener = null;+ if (left) showToast('This draft still has a {{placeholder}} in it. Fix it in Gmail before sending.', 'error');+}++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');+ else if (!sent && res.sent) showToast('They already replied, so this stays marked as sent.');+ loadCampaigns();+}+async function loadCampaigns() {const el = document.getElementById('campaigns-list');const data = await api('/api/campaigns');@@ -1421,12 +1465,24 @@ async function loadCampaigns() {let html = '';data.forEach((c, i) => {let stepsHtml = '';- for (const step of (c.sequence || [])) {+ (c.sequence || []).forEach((step, s) => {+ const sendBtns = (c.recipients || []).map((r, ri) => {+ // '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 + ')">' ++ 'Open in Gmail → ' + escHtml(r.email) + '</button>' ++ '<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(' ');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>' +- '<div class="body">' + escHtml(step.body) + '</div></div>';- }+ '<div class="body">' + escHtml(step.body) + '</div>' ++ (sendBtns ? '<div style="margin-top:8px;display:flex;gap:6px;flex-wrap:wrap">' + sendBtns + '</div>' : '') ++ '</div>';+ });const pc = (c.prospect_ids || []).length;html += '<div class="campaign-card"><h3>' + escHtml(c.name || 'Untitled Campaign') + '</h3>' +'<div class="meta">' + badge(c.status) + '<span>' + escHtml(c.channel || 'email') + '</span>' +diff --git a/tests/test_dashboard_manual_send.py b/tests/test_dashboard_manual_send.pynew file mode 100644index 0000000..4350fab--- /dev/null+++ b/tests/test_dashboard_manual_send.py@@ -0,0 +1,104 @@+"""Sending by hand from the dashboard.++Covers the Campaigns tab's "Open in Gmail" data (recipients per campaign) and+the "Mark as sent" toggle (never erases a reply, refuses unknown prospects).+"""++import asyncio+import json+import sqlite3++import pytest+from fastapi.testclient import TestClient++import harvey.dashboard as dash+from harvey.state import StateManager++ORIGIN = "http://127.0.0.1:5555"+++def env(tmp_path, monkeypatch):+ (tmp_path / "data").mkdir()+ db = tmp_path / "data" / "harvey.db"+ monkeypatch.setattr(dash, "ENV_FILE", tmp_path / ".env")+ monkeypatch.setattr(dash, "DB_PATH", db)+ 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")+ asyncio.run(StateManager(db_path=str(db)).init_db())+ return {"db": db, "token": dash.token_store.get()}+++def client(env):+ with TestClient(dash.app, base_url=ORIGIN,+ headers={"Authorization": f"Bearer {env['token']}"}) as c:+ yield c+++def _sql(env, query, params=()):+ with sqlite3.connect(env["db"]) as db:+ db.execute(query, params)+++def _prospect(env, pid, email, email_status="verified", status="new"):+ _sql(env, "INSERT INTO prospects (id, first_name, last_name, email, email_status, "+ "status, company) VALUES (?, '', '', ?, ?, ?, 'Acme')",+ (pid, email, email_status, status))+++def _campaign(env, cid, prospect_ids):+ _sql(env, "INSERT INTO campaigns (id, name, channel, sequence_json, prospect_ids_json, "+ "status) VALUES (?, ?, 'email', ?, ?, 'draft')",+ (cid, cid, json.dumps([{"step": 1, "subject": "hi", "body": "Hi {{company}}",+ "delay_days": 0}]), json.dumps(prospect_ids)))+++# ── Campaign recipients ──+++def test_campaigns_list_their_recipients(client, env):+ _prospect(env, "p1", "[email protected]")+ _prospect(env, "p2", "") # no address: nothing to open in Gmail+ _campaign(env, "c1", ["p1", "p2"])+ rows = client.get("/api/campaigns").json()+ assert [r["email"] for r in rows[0]["recipients"]] == ["[email protected]"]+ assert rows[0]["recipients"][0]["status"] == "new"+++def test_campaign_with_no_prospects_has_no_recipients(client, env):+ _campaign(env, "c1", [])+ assert client.get("/api/campaigns").json()[0]["recipients"] == []+++# ── Mark as sent ──+++def test_mark_sent_and_undo(client, env):+ _prospect(env, "p1", "[email protected]")+ assert client.post("/api/prospects/p1/sent", json={"sent": True}).json()["sent"] is True+ assert client.get("/api/campaigns").json() == [] # no campaign needed to toggle+ with sqlite3.connect(env["db"]) as db:+ assert db.execute("SELECT status FROM prospects").fetchone()[0] == "contacted"+ assert db.execute("SELECT action_type FROM actions").fetchone()[0] == "manual_send"+ client.post("/api/prospects/p1/sent", json={"sent": False})+ with sqlite3.connect(env["db"]) as db:+ assert db.execute("SELECT status FROM prospects").fetchone()[0] == "new"+++def test_unticking_never_erases_a_reply(client, env):+ _prospect(env, "p1", "[email protected]", status="replied")+ r = client.post("/api/prospects/p1/sent", json={"sent": False}).json()+ assert r == {"success": True, "sent": True, "status": "replied"}+ with sqlite3.connect(env["db"]) as db:+ assert db.execute("SELECT status FROM prospects").fetchone()[0] == "replied"+++def test_unknown_prospect_is_refused(client):+ assert client.post("/api/prospects/nope/sent", json={"sent": True}).status_code == 404+++def test_missing_body_means_sent(client, env):+ _prospect(env, "p1", "[email protected]")+ assert client.post("/api/prospects/p1/sent").json()["sent"] is True