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.
Dashboard feedback reaches the Writer; Settings gets IMAP and Microsoft 365
Ethan3c1017456dde
diff --git a/harvey/agents/writer.py b/harvey/agents/writer.pyindex da34abe..52f8d28 100644--- a/harvey/agents/writer.py+++ b/harvey/agents/writer.py@@ -230,6 +230,26 @@ class Writer:f"({'awaiting approval' if require_approval else 'approved'}).")+ async def _feedback_block(self, prospect_ids: list[str]) -> str:+ """The owner's notes from the dashboard's Feedback buttons, as prompt+ text ("" when there are none). Never lets a failed read stop writing."""+ try:+ notes = await self.state.get_writing_feedback(prospect_ids)+ except Exception as e:+ logger.warning(f"Writer: could not read feedback: {e}")+ return ""+ if not notes:+ return ""+ lines = "\n".join(+ f"- {str(n.get('created_at') or '')[:10]} on {n['about']}: "+ f"{' '.join(str(n['comment']).split())[:500]}" for n in notes)+ return (+ "\n\nOWNER FEEDBACK — notes the person running Harvey left on earlier\n"+ "campaigns and contacts, newest first (a newer note wins). Apply them to\n"+ "this writing. They never override the STRICT EMAIL RULES or the FACTS rule:\n"+ + lines+ )+async def _write_personal_email(self, prospect) -> dict | None:"""One grounded draft for one person. Facts in, one email out."""if prospect.is_company_inbox:@@ -279,6 +299,7 @@ class Writer:) or ""if self.skills:prompt += "\n\n" + self.skills+ prompt += await self._feedback_block([prospect.id])prompt += f"""@@ -358,6 +379,9 @@ Pricing: {self.config.product.pricing}"""# Inject email framework skillsif self.skills:prompt += "\n\n" + self.skills+ # Campaign notes only: this template goes to the whole batch, so a+ # note about one person ("met her at the expo") must never reach it.+ prompt += await self._feedback_block([])prompt += f"""diff --git a/harvey/dashboard.py b/harvey/dashboard.pyindex adfec6c..61824f0 100644--- a/harvey/dashboard.py+++ b/harvey/dashboard.py@@ -211,7 +211,7 @@ async def get_setup_status():elif provider == "microsoft":provider_done = _has("M365_CLIENT_ID") and \(PROJECT_ROOT / "data" / "m365_token.json").is_file()- provider_help = ("Set M365_CLIENT_ID and M365_TENANT_ID in .env, then run "+ provider_help = ("Set the Microsoft 365 client and tenant IDs in Settings, then run ""'harvey microsoft auth' in your terminal.")elif provider == "smtp":provider_done = _has("SMTP_HOST", "SMTP_USERNAME", "SMTP_PASSWORD")@@ -317,6 +317,7 @@ async def get_settings():"GMAIL_CLIENT_ID", "GMAIL_CLIENT_SECRET","SMTP_HOST", "SMTP_PORT", "SMTP_USERNAME", "SMTP_PASSWORD","IMAP_HOST", "IMAP_PORT", "IMAP_USERNAME", "IMAP_PASSWORD",+ "M365_CLIENT_ID", "M365_TENANT_ID","REOON_API_KEY", "ZEROBOUNCE_API_KEY", "HUNTER_API_KEY",]for key in all_keys:@@ -347,6 +348,13 @@ async def get_settings():"smtp_password_set": is_set("SMTP_PASSWORD"),"imap_host": env_vars.get("IMAP_HOST", ""),"imap_port": env_vars.get("IMAP_PORT", ""),+ "imap_username": env_vars.get("IMAP_USERNAME", ""),+ "imap_password_set": is_set("IMAP_PASSWORD"),+ # Microsoft 365: ids aren't secret (no client secret: Harvey signs+ # in as a public client with PKCE); the token file means signed in.+ "m365_client_id": env_vars.get("M365_CLIENT_ID", ""),+ "m365_tenant_id": env_vars.get("M365_TENANT_ID", ""),+ "m365_authorized": (PROJECT_ROOT / "data" / "m365_token.json").is_file(),"reoon_api_key_set": is_set("REOON_API_KEY"),"zerobounce_api_key_set": is_set("ZEROBOUNCE_API_KEY"),"hunter_api_key_set": is_set("HUNTER_API_KEY"),@@ -369,6 +377,7 @@ async def save_env_settings(request: Request):"GMAIL_CLIENT_ID", "GMAIL_CLIENT_SECRET","SMTP_HOST", "SMTP_PORT", "SMTP_USERNAME", "SMTP_PASSWORD","IMAP_HOST", "IMAP_PORT", "IMAP_USERNAME", "IMAP_PASSWORD",+ "M365_CLIENT_ID", "M365_TENANT_ID","REOON_API_KEY", "ZEROBOUNCE_API_KEY", "HUNTER_API_KEY"]:if key in data and data[key] is not None:value = data[key]@@ -376,6 +385,10 @@ async def save_env_settings(request: Request):return JSONResponse({"success": False, "message": f"{key} must be text."},status_code=400)value = str(value)+ # A port Harvey can't parse would stop it starting at all.+ if key.endswith("_PORT") and value.strip() and not value.strip().isdigit():+ return JSONResponse({"success": False, "message": f"{key} must be a number."},+ status_code=400)if len(value) > 4096 or "\x00" in value:return JSONResponse({"success": False, "message": f"{key} is invalid."},status_code=400)diff --git a/harvey/state.py b/harvey/state.pyindex c440acf..f592fc8 100644--- a/harvey/state.py+++ b/harvey/state.py@@ -1786,6 +1786,46 @@ class StateManager:rows = await cursor.fetchall()return [dict(r) for r in rows]+ async def get_writing_feedback(+ self, prospect_ids: list[str] | tuple = (), limit: int = 10+ ) -> list[dict]:+ """What the owner said about past campaigns (newest first), plus+ anything said about these contacts: the Writer follows it.++ Each row: {"about": "campaign 'Denver roofers'" | "Dana Ruiz",+ "comment": ...}."""+ out: list[dict] = []+ async with self._connect() as db:+ db.row_factory = aiosqlite.Row+ async with db.execute(+ """SELECT f.comment, f.created_at, c.name FROM feedback f+ LEFT JOIN campaigns c ON c.id = f.entity_id+ WHERE f.entity_type = 'campaign' AND TRIM(f.comment) != ''+ ORDER BY f.created_at DESC LIMIT ?""",+ (int(limit),),+ ) as cursor:+ for r in await cursor.fetchall():+ about = f"campaign '{r['name']}'" if r["name"] else "a past campaign"+ out.append({"about": about, "comment": r["comment"],+ "created_at": r["created_at"]})+ ids = [i for i in prospect_ids if i][:50]+ if ids:+ marks = ",".join("?" * len(ids))+ async with db.execute(+ f"""SELECT f.comment, f.created_at, p.first_name, p.last_name FROM feedback f+ JOIN prospects p ON p.id = f.entity_id+ WHERE f.entity_type = 'contact' AND f.entity_id IN ({marks})+ AND TRIM(f.comment) != ''+ ORDER BY f.created_at DESC LIMIT ?""",+ (*ids, int(limit)),+ ) as cursor:+ for r in await cursor.fetchall():+ name = " ".join(x for x in (r["first_name"], r["last_name"]) if x)+ out.append({"about": name or "this contact", "comment": r["comment"],+ "created_at": r["created_at"]})+ out.sort(key=lambda n: str(n.get("created_at") or ""), reverse=True) # newest first+ return out+# ── Reply Deduplication ──async def is_reply_processed(self, reply_id: str) -> bool:diff --git a/harvey/web/app.js b/harvey/web/app.jsindex a8df742..9c43613 100644--- a/harvey/web/app.js+++ b/harvey/web/app.js@@ -892,11 +892,18 @@ async function loadSettings() {document.getElementById('smtp-host').value = data.smtp_host || '';document.getElementById('smtp-port').value = data.smtp_port || '';document.getElementById('smtp-user').value = data.smtp_username || '';+ document.getElementById('imap-host').value = data.imap_host || '';+ document.getElementById('imap-port').value = data.imap_port || '';+ document.getElementById('imap-user').value = data.imap_username || '';+ document.getElementById('m365-client').value = data.m365_client_id || '';+ document.getElementById('m365-tenant').value = data.m365_tenant_id || '';document.getElementById('linkedin-email').value = data.linkedin_email || '';document.getElementById('cf-account-id').value = data.cloudflare_account_id || '';savedPh('gmail-secret', data.gmail_client_secret_set, 'Enter client secret');savedPh('smtp-pass', data.smtp_password_set, 'Enter password / app password');+ savedPh('imap-pass', data.imap_password_set, 'Same as SMTP password');+ document.getElementById('imap-same-pass').checked = !data.imap_password_set;savedPh('instantly-key', data.instantly_api_key_set, 'Enter your Instantly API key');savedPh('reoon-key', data.reoon_api_key_set, '600 free/mo — reoon.com/email-verifier');savedPh('zerobounce-key', data.zerobounce_api_key_set, '100 free/mo — best for M365/Workspace catch-alls');@@ -911,6 +918,12 @@ async function loadSettings() {else if (data.gmail_client_secret_set) { g.className = 'email-tag risky'; g.textContent = 'run: harvey gmail auth'; }else { g.className = 'email-tag guess'; g.textContent = 'not set up'; }}+ const m = document.getElementById('m365-status');+ if (m) {+ if (data.m365_authorized) { m.className = 'email-tag verified'; m.textContent = 'authorized'; }+ else if (data.m365_client_id) { m.className = 'email-tag risky'; m.textContent = 'run: harvey microsoft auth'; }+ else { m.className = 'email-tag guess'; m.textContent = 'not set up'; }+ }tag('reoon-status', data.reoon_api_key_set, 'set');tag('zerobounce-status', data.zerobounce_api_key_set, 'set');tag('hunter-status', data.hunter_api_key_set, 'set');@@ -931,9 +944,25 @@ function saveSmtp() {};const pass = document.getElementById('smtp-pass').value;if (pass) payload.SMTP_PASSWORD = pass;+ // Blank IMAP fields fall back to the SMTP ones. A typed IMAP password wins;+ // otherwise the checkbox clears it back to the SMTP one, and an unticked+ // empty box keeps whatever IMAP password is saved.+ payload.IMAP_HOST = document.getElementById('imap-host').value.trim();+ payload.IMAP_PORT = document.getElementById('imap-port').value.trim();+ payload.IMAP_USERNAME = document.getElementById('imap-user').value.trim();+ const imapPass = document.getElementById('imap-pass').value;+ if (imapPass) payload.IMAP_PASSWORD = imapPass;+ else if (document.getElementById('imap-same-pass').checked) payload.IMAP_PASSWORD = '';saveEnv(payload, 'SMTP settings saved.').then(loadSettings);}+function saveMicrosoft() {+ const client = document.getElementById('m365-client').value.trim();+ if (!client) { showToast('Paste the Application (client) ID first.', 'error'); return; }+ saveEnv({M365_CLIENT_ID: client, M365_TENANT_ID: document.getElementById('m365-tenant').value.trim()},+ 'Saved. Now run "harvey microsoft auth" in your terminal.').then(loadSettings);+}+function saveVerifiers() {const payload = {};const r = document.getElementById('reoon-key').value;@@ -1564,18 +1593,20 @@ async function submitFeedback(entityType, entityId, promptText) {method: 'POST', headers: {'Content-Type': 'application/json'},body: JSON.stringify({entity_type: entityType, entity_id: entityId, comment: comment})});- if (data && data.success) showToast('Feedback saved. Harvey will take it into account.', 'success');+ if (data && data.success) showToast(entityType === 'campaign'+ ? 'Saved. Harvey follows it in the emails it writes from now on.'+ : 'Saved. Harvey uses it if it writes this person\'s first email (Gmail, SMTP or Microsoft 365).', 'success');else showToast((data && data.message) || 'Could not save feedback.', 'error');}function fbProspect(i) {const p = _prospects[i];- if (p) submitFeedback('contact', p.id, 'Feedback on this contact:');+ if (p) submitFeedback('contact', p.id, 'Anything Harvey should know before writing to this person?');}function fbCampaign(i) {const c = _campaigns[i];- if (c) submitFeedback('campaign', c.id, 'Leave feedback on this campaign:');+ if (c) submitFeedback('campaign', c.id, 'What should Harvey do differently in the emails it writes next? (e.g. "shorter; don\'t mention reviews")');}async function loadProspects() {diff --git a/harvey/web/index.html b/harvey/web/index.htmlindex 8dc67bf..5684ea1 100644--- a/harvey/web/index.html+++ b/harvey/web/index.html@@ -224,7 +224,7 @@<div class="section-head"><h2>Settings</h2><p>Credentials are stored locally in <span style="font-family:var(--mono);font-size:12px">.env</span> — never sent anywhere except the services themselves.</p></div><div class="card"><h2>Email Provider</h2>- <p class="lede">How Harvey sends and reads replies. Active provider: <b id="active-provider">…</b> — change it by setting <span style="font-family:var(--mono);font-size:12px">channels.email.provider</span> in <span style="font-family:var(--mono);font-size:12px">harvey.yaml</span> to <span style="font-family:var(--mono);font-size:12px">gmail</span>, <span style="font-family:var(--mono);font-size:12px">smtp</span>, or <span style="font-family:var(--mono);font-size:12px">instantly</span>.</p>+ <p class="lede">How Harvey sends and reads replies. Active provider: <b id="active-provider">…</b> — change it by setting <span style="font-family:var(--mono);font-size:12px">channels.email.provider</span> in <span style="font-family:var(--mono);font-size:12px">harvey.yaml</span> to <span style="font-family:var(--mono);font-size:12px">gmail</span>, <span style="font-family:var(--mono);font-size:12px">microsoft</span>, <span style="font-family:var(--mono);font-size:12px">smtp</span>, or <span style="font-family:var(--mono);font-size:12px">instantly</span>.</p><div style="border:1px solid var(--border);border-radius:10px;padding:16px;margin-bottom:12px"><div style="font-weight:650;margin-bottom:4px">Gmail / Google Workspace <span class="optional-tag">recommended</span> <span id="gmail-status" class="email-tag"></span></div>@@ -253,9 +253,38 @@<div class="form-row"><div class="form-group" style="margin-bottom:0"><input type="password" class="form-input" id="smtp-pass" placeholder="Enter password / app password" autocomplete="off"></div><button class="btn btn-secondary btn-sm" onclick="toggleVisibility('smtp-pass')">Show</button></div></div>+ <details style="margin-bottom:12px">+ <summary style="cursor:pointer;font-size:13px;color:var(--text-2)">Reading replies from a different IMAP server or login</summary>+ <div class="form-row" style="margin-top:10px">+ <div class="form-group"><label class="form-label" for="imap-host">IMAP host</label>+ <input type="text" class="form-input" id="imap-host" placeholder="Same as SMTP host" autocomplete="off"></div>+ <div class="form-group" style="max-width:120px"><label class="form-label" for="imap-port">Port</label>+ <input type="text" class="form-input" id="imap-port" placeholder="993" autocomplete="off"></div>+ </div>+ <div class="form-group"><label class="form-label" for="imap-user">IMAP username</label>+ <input type="text" class="form-input" id="imap-user" placeholder="Same as SMTP username" autocomplete="off"></div>+ <div class="form-group"><label class="form-label" for="imap-pass">IMAP password</label>+ <div class="form-row"><div class="form-group" style="margin-bottom:0">+ <input type="password" class="form-input" id="imap-pass" placeholder="Same as SMTP password" autocomplete="off" oninput="if (this.value) document.getElementById('imap-same-pass').checked = false"></div>+ <button class="btn btn-secondary btn-sm" onclick="toggleVisibility('imap-pass')">Show</button></div></div>+ <label style="display:inline-flex;align-items:center;gap:6px;font-size:13px;cursor:pointer">+ <input type="checkbox" id="imap-same-pass"> Use the SMTP password for IMAP</label>+ </details><button class="btn btn-primary btn-sm" onclick="saveSmtp()">Save SMTP</button></div>+ <div style="border:1px solid var(--border);border-radius:10px;padding:16px;margin-bottom:12px">+ <div style="font-weight:650;margin-bottom:4px">Microsoft 365 / Outlook <span id="m365-status" class="email-tag"></span></div>+ <p class="lede" style="margin-top:4px">Microsoft turned off password sign-in for IMAP, so Outlook mailboxes connect with OAuth. In <a href="https://entra.microsoft.com" target="_blank" rel="noopener noreferrer">Entra</a> → App registrations, register an app for your organization only, add the redirect URI <span style="font-family:var(--mono);font-size:12px">http://localhost:8766</span> as "Public client/native", paste both IDs here, save, then run <span style="font-family:var(--mono);font-size:12px">harvey microsoft auth</span> in your terminal. No client secret is needed.</p>+ <div class="form-row">+ <div class="form-group"><label class="form-label" for="m365-client">Application (client) ID</label>+ <input type="text" class="form-input" id="m365-client" placeholder="00000000-0000-0000-0000-000000000000" autocomplete="off"></div>+ <div class="form-group"><label class="form-label" for="m365-tenant">Directory (tenant) ID</label>+ <input type="text" class="form-input" id="m365-tenant" placeholder="00000000-0000-0000-0000-000000000000" autocomplete="off"></div>+ </div>+ <button class="btn btn-primary btn-sm" onclick="saveMicrosoft()">Save Microsoft 365</button>+ </div>+<div style="border:1px solid var(--border);border-radius:10px;padding:16px"><div style="font-weight:650;margin-bottom:4px">Instantly <span class="optional-tag">legacy</span></div><p class="lede" style="margin-top:4px">Get your API key from <a href="https://app.instantly.ai/app/settings/integrations" target="_blank" rel="noopener">Instantly Settings → Integrations</a> (Growth plan+ for API).</p>diff --git a/tests/test_dashboard_auth.py b/tests/test_dashboard_auth.pyindex f683e64..d0c99f4 100644--- a/tests/test_dashboard_auth.py+++ b/tests/test_dashboard_auth.py@@ -355,6 +355,25 @@ def test_authorised_settings_round_trip(authed):assert "NOT_ALLOWED" not in dash.ENV_FILE.read_text()+def test_imap_and_microsoft_settings_round_trip(authed):+ r = authed.post("/api/settings/env", json={+ "IMAP_HOST": "imap.example.test", "IMAP_USERNAME": "[email protected]",+ "IMAP_PASSWORD": "imap-pw-9", "M365_CLIENT_ID": "client-1", "M365_TENANT_ID": "tenant-2"})+ assert r.json()["success"]+ data = authed.get("/api/settings").json()+ assert data["imap_host"] == "imap.example.test" and data["imap_username"] == "[email protected]"+ assert data["imap_password_set"] is True and "imap-pw-9" not in json.dumps(data)+ assert (data["m365_client_id"], data["m365_tenant_id"]) == ("client-1", "tenant-2")+ assert data["m365_authorized"] in (True, False)+++def test_a_port_harvey_cannot_parse_is_refused(authed):+ r = authed.post("/api/settings/env", json={"IMAP_PORT": "993 SSL"})+ assert r.status_code == 400 and not dash.ENV_FILE.exists()+ assert authed.post("/api/settings/env", json={"IMAP_PORT": ""}).json()["success"] # blank = default+ assert authed.post("/api/settings/env", json={"SMTP_PORT": " 587 "}).json()["success"]++@pytest.mark.parametrize("value", [{"a": 1}, ["x"], True, "x" * 5000, "a\x00b"])def test_settings_values_are_validated(authed, value):r = authed.post("/api/settings/env", json={"SMTP_HOST": value})diff --git a/tests/test_writer_feedback.py b/tests/test_writer_feedback.pynew file mode 100644index 0000000..b8d0ec5--- /dev/null+++ b/tests/test_writer_feedback.py@@ -0,0 +1,107 @@+"""The dashboard's Feedback buttons reach the Writer.++Campaign feedback is guidance for every email written next; feedback on a+contact is used when Harvey writes to that contact. Before this, the notes+were stored and nothing read them.+"""++from types import SimpleNamespace++import pytest+import pytest_asyncio++from harvey.agents.writer import Writer+from harvey.models.campaign import Campaign+from harvey.models.prospect import Prospect+from harvey.state import StateManager++SEQ = [{"step": 1, "subject": "quick one", "body": "Hi {{first_name}}, who answers at {{company}}?",+ "delay_days": 0}]+++class RecordingBrain:+ def __init__(self, reply):+ self.reply, self.prompts = reply, []++ def load_skills_for_agent(self, name):+ return ""++ def load_prompt(self, name, **kw):+ return "prompt"++ async def think_json(self, prompt, **kw):+ self.prompts.append(prompt)+ return self.reply+++def config(provider):+ return SimpleNamespace(+ channels=SimpleNamespace(email=SimpleNamespace(provider=provider, require_approval=True)),+ product=SimpleNamespace(name="P", description="D", key_benefits=[], pricing=""),+ persona=SimpleNamespace(name="S", company="C", role="R", tone="t"),+ humanizer=SimpleNamespace(enabled=False),+ )+++def writer(brain, state, provider):+ w = Writer(brain, state, config(provider))+ w.skills = "" # run() loads these; the tests call the prompt builders directly+ return w+++@pytest_asyncio.fixture+async def state(tmp_path):+ s = StateManager(str(tmp_path / "w.db"))+ await s.init_db()+ return s+++async def prospect(state, first):+ return await state.add_prospect(Prospect(+ first_name=first, last_name="Doe", title="Owner", company=f"{first} Co",+ industry="Roofing", email=f"{first.lower()}@x.test", email_status="verified"))+++async def test_sequence_prompt_gets_campaign_notes_but_never_one_contacts(state):+ pid = await prospect(state, "Ana")+ other = await prospect(state, "Ben")+ cid = await state.add_campaign(Campaign(id="", name="Denver roofers"))+ await state.add_feedback("campaign", cid, "Too long.\nDrop the question about reviews.")+ await state.add_feedback("contact", pid, "She is the owner's daughter; keep it warm.")+ await state.add_feedback("contact", other, "Not relevant to Ana.")++ brain = RecordingBrain(SEQ)+ await writer(brain, state, "instantly")._write_sequence([await state.get_prospect(pid)])+ [prompt] = brain.prompts+ assert "OWNER FEEDBACK" in prompt+ assert "on campaign 'Denver roofers': Too long. Drop the question about reviews." in prompt+ # The template goes to the whole batch: a note about Ana must not reach it.+ assert "owner's daughter" not in prompt and "on Ana Doe" not in prompt+++async def test_personal_email_prompt_carries_that_contacts_feedback(state):+ pid = await prospect(state, "Cara")+ await state.add_feedback("contact", pid, "Met her at the expo in May.")+ brain = RecordingBrain({"subject": "hi", "body": "Hi Cara"})+ await writer(brain, state, "gmail")._write_personal_email(await state.get_prospect(pid))+ assert "on Cara Doe: Met her at the expo in May." in brain.prompts[0]+++async def test_no_feedback_adds_nothing(state):+ pid = await prospect(state, "Dee")+ brain = RecordingBrain({"subject": "hi", "body": "Hi Dee"})+ await writer(brain, state, "gmail")._write_personal_email(await state.get_prospect(pid))+ assert "OWNER FEEDBACK" not in brain.prompts[0]+++async def test_personal_prompt_skips_other_contacts_notes(state):+ pid = await prospect(state, "Eve")+ other = await prospect(state, "Fay")+ await state.add_feedback("contact", other, "Fay only.")+ brain = RecordingBrain({"subject": "hi", "body": "Hi Eve"})+ await writer(brain, state, "gmail")._write_personal_email(await state.get_prospect(pid))+ assert "Fay only" not in brain.prompts[0]