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.
Outbox: show the facts behind each draft, and let a reviewer edit it
Haris Chandiofa2c2c70af6c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b1c5a75..9b1310d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,15 @@ minor versions can still change behaviour.### Added+- **Outbox review: see what a draft is based on, and edit it.** Each pending+ draft now shows its campaign, the company (name, clickable website,+ description), the contact and how they were found, email status and score,+ tech / agency / hiring / ads / booking signals, and the Writer's notes, so+ every claim can be checked against what Harvey actually found. **Edit** (or+ `E`) turns subject and body into fields; Save rewrites the draft only while+ it is still `pending_review` and never approves it.+ `POST /api/outbox/{id}/edit` backs it.+- **Microsoft 365 mail provider.** Set `channels.email.provider: microsoft` tosend and read through a Microsoft 365 / Outlook mailbox via Microsoft Graph,for domains whose mail lives in Exchange Online (which no longer acceptsdiff --git a/harvey/dashboard.py b/harvey/dashboard.pyindex 816c31d..7bb3375 100644--- a/harvey/dashboard.py+++ b/harvey/dashboard.py@@ -759,6 +759,73 @@ def _state():return StateManager(db_path=str(DB_PATH))+# What a reviewer needs next to a draft to check its claims against the facts.+OUTBOX_CONTEXT_SIGNALS = (+ "TECH_STACK", "INCUMBENT_AGENCY", "HIRING_ROLE", "RUNNING_GOOGLE_ADS", "NO_ONLINE_BOOKING",+)+++def _in(ids) -> str:+ return ",".join("?" for _ in ids)+++async def _with_context(items: list[dict]) -> list[dict]:+ """Attach the campaign, company, contact and signals behind each draft."""+ if not items:+ return items+ pids = sorted({i["prospect_id"] for i in items if i.get("prospect_id")})+ cids = sorted({i["campaign_id"] for i in items if i.get("campaign_id")})++ people = {r["id"]: r for r in (await query_db(+ "SELECT p.id, p.first_name, p.last_name, p.title, p.source, p.email_status, "+ "p.score, p.personalization_notes, p.company_id, c.name AS company_name, "+ "c.domain, c.website, c.description, c.industry AS found_by "+ "FROM prospects p LEFT JOIN companies c ON c.id = p.company_id "+ f"WHERE p.id IN ({_in(pids)})", tuple(pids)) if pids else [])}+ campaigns = {r["id"]: r["name"] for r in (await query_db(+ f"SELECT id, name FROM campaigns WHERE id IN ({_in(cids)})",+ tuple(cids)) if cids else [])}++ company_ids = sorted({p["company_id"] for p in people.values() if p.get("company_id")})+ signals: dict[str, dict[str, str]] = {}+ if company_ids:+ rows = await query_db(+ "SELECT o.company_id, o.signal_code, o.value_num, o.value_text, "+ "COALESCE(sc.label, o.signal_code) AS label FROM observations o "+ "LEFT JOIN signal_codes sc ON sc.code = o.signal_code "+ f"WHERE o.company_id IN ({_in(company_ids)}) "+ f"AND o.signal_code IN ({_in(OUTBOX_CONTEXT_SIGNALS)}) "+ "ORDER BY o.observed_at",+ (*company_ids, *OUTBOX_CONTEXT_SIGNALS),+ )+ for r in rows: # oldest first, so the latest observation wins+ if r["value_text"]:+ value = r["value_text"]+ elif r["value_num"] is None:+ value = ""+ else:+ value = "yes" if r["value_num"] else "no"+ signals.setdefault(r["company_id"], {})[r["label"]] = value++ for item in items:+ p = people.get(item.get("prospect_id")) or {}+ item["context"] = {+ "campaign": campaigns.get(item.get("campaign_id"), ""),+ "company": p.get("company_name", ""),+ "website": p.get("website") or (f"https://{p['domain']}" if p.get("domain") else ""),+ "description": p.get("description", ""),+ "found_by": p.get("found_by", ""),+ "contact": " ".join(x for x in (p.get("first_name"), p.get("last_name")) if x),+ "contact_title": p.get("title", ""),+ "contact_source": p.get("source", ""),+ "email_status": p.get("email_status", ""),+ "score": p.get("score"),+ "notes": p.get("personalization_notes", ""),+ "signals": signals.get(p.get("company_id"), {}),+ }+ return items++@app.get("/api/outbox")async def get_outbox_api():"""Outbox queue + kill-switch state for the Outbox tab."""@@ -767,7 +834,8 @@ async def get_outbox_api():await state.init_db()return {"paused": await state.get_setting("sending_paused"),- "pending": await state.get_outbox(status="pending_review", limit=100),+ "pending": await _with_context(+ await state.get_outbox(status="pending_review", limit=100)),"approved": await state.get_outbox(status="approved", limit=50),"sent": (await query_db("SELECT * FROM outbox WHERE status = 'sent' "@@ -802,6 +870,30 @@ async def outbox_approve(item_id: str):return JSONResponse({"success": False, "message": str(e)}, status_code=500)[email protected]("/api/outbox/{item_id}/edit")+async def outbox_edit(item_id: str, request: Request):+ """Rewrite a draft awaiting review. Never approves it."""+ try:+ body = await request.json()+ except Exception:+ body = {}+ subject = str((body or {}).get("subject") or "").strip()+ text = str((body or {}).get("body") or "").strip()+ if not subject or not text:+ return JSONResponse({"success": False, "message": "Subject and body are both required."},+ status_code=400)+ try:+ state = _state()+ await state.init_db()+ if not await state.edit_outbox_draft(item_id, subject, text):+ return JSONResponse({"success": False,+ "message": "Only drafts awaiting review can be edited."},+ status_code=409)+ return {"success": True}+ 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:diff --git a/harvey/state.py b/harvey/state.pyindex 8158211..6ee441a 100644--- a/harvey/state.py+++ b/harvey/state.py@@ -901,6 +901,22 @@ class StateManager:)await db.commit()+ 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.++ Atomic on status, like approve: an item already approved, sent or+ rejected is never changed. Editing never approves; that stays a+ separate, explicit step. Returns the number of rows changed (0/1).+ """+ async with self._connect() as db:+ cursor = await db.execute(+ "UPDATE outbox SET subject = ?, body = ?, updated_at = ? "+ "WHERE id = ? AND status = 'pending_review'",+ (subject, body, _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/harvey/web/app.css b/harvey/web/app.cssindex 5469d53..2d4d3e9 100644--- a/harvey/web/app.css+++ b/harvey/web/app.css@@ -429,8 +429,24 @@ td a:hover { text-decoration: underline; }padding: 18px 0; border-top: 1px solid var(--border); border-bottom: 1px solid var(--border);}.desk-actions { display: flex; align-items: center; gap: 10px; margin-top: 18px; }--@media (max-width: 900px) { .desk { grid-template-columns: 1fr; } .desk-list { max-height: 220px; } }+.desk-context {+ display: grid; grid-template-columns: 110px minmax(0,1fr); gap: 6px 14px;+ margin: 14px 0 4px; padding: 14px 16px; font-size: 12.5px; line-height: 1.5;+ background: var(--panel-raised); border: 1px solid var(--border); border-radius: var(--r-md);+}+.desk-context .k { color: var(--text-3); }+.desk-context .v { overflow-wrap: anywhere; }+.desk-context a { color: inherit; text-decoration: underline; text-underline-offset: 2px; }+.desk-edit-subject, .desk-edit-body {+ display: block; width: 100%; box-sizing: border-box; margin: 12px 0 0;+ padding: 10px 12px; font: inherit; color: var(--text); background: var(--panel);+ border: 1px solid var(--border-strong); border-radius: var(--r-md);+}+.desk-edit-subject { font-size: 16px; }+.desk-edit-body { font-size: 14px; line-height: 1.7; resize: vertical; max-width: 64ch; }+.desk-edit-subject:focus, .desk-edit-body:focus { outline: none; border-color: var(--text-3); }++@media (max-width: 900px) { .desk { grid-template-columns: 1fr; } .desk-list { max-height: 220px; } .desk-context { grid-template-columns: 1fr; } .desk-pane { padding: 20px 16px; } }/* ── Discovery providers ─────────────────────────────────────── */diff --git a/harvey/web/app.js b/harvey/web/app.jsindex 591914a..f74434a 100644--- a/harvey/web/app.js+++ b/harvey/web/app.js@@ -1245,6 +1245,44 @@ async function loadOutbox() {]);}+const CONTACT_SOURCES = {+ known_company_backfill: 'team page on their site',+ company_website: 'team page on their site',+ scraped_mailto: 'address published on their site',+ linkedin_search: 'LinkedIn search',+ hunter_domain_search: 'Hunter domain search',+ job_board: 'job board',+ web_search: 'web search',+};++// What the draft is built on, so every claim can be checked against it.+function renderDeskContext(ctx) {+ if (!ctx) return '';+ const row = (k, v) => v ? '<div class="k">' + k + '</div><div class="v">' + v + '</div>' : '';+ const href = safeHref(ctx.website);+ const site = href+ ? '<a href="' + href + '" target="_blank" rel="noopener noreferrer">' ++ escHtml(ctx.website.replace(/^https?:\/\//i, '')) + ' ↗</a>'+ : '';+ const who = [ctx.contact, ctx.contact_title].filter(Boolean).map(escHtml).join(' · ');+ const email = [ctx.email_status, ctx.score ? 'score ' + ctx.score : '']+ .filter(Boolean).map(escHtml).join(' · ');+ const signals = Object.entries(ctx.signals || {})+ .map(([k, v]) => escHtml(k) + ': <b>' + escHtml(v) + '</b>').join('<br>');+ return '<div class="desk-context">' ++ row('Company', escHtml(ctx.company)) ++ row('Website', site) ++ row('About', escHtml(ctx.description)) ++ row('Contact', who) ++ row('Found via', escHtml(CONTACT_SOURCES[ctx.contact_source] || ctx.contact_source)) ++ row('Email', email) ++ row('Signals', signals) ++ row('Campaign', escHtml(ctx.campaign) ++ (ctx.found_by ? ' <span class="muted">(how they were found, not a fact about them)</span>' : '')) ++ row('Writer notes', escHtml(ctx.notes)) ++ '</div>';+}+function renderDesk(items, i) {const cur = items[i];const rail = items.map((it, n) =>@@ -1253,28 +1291,69 @@ function renderDesk(items, i) {'<div class="sub">' + escHtml(it.subject || '(no subject)') + '</div>' +'</div>').join('');+ const editing = _desk.editing === cur.id;+ const draft = editing+ ? '<input id="desk-subject" class="desk-edit-subject" value="' + escHtml(cur.subject || '') + '">' ++ '<textarea id="desk-body" class="desk-edit-body" rows="14">' + escHtml(cur.body) + '</textarea>'+ : '<div class="subject">' + escHtml(cur.subject || '(no subject)') + '</div>' ++ '<div class="body">' + escHtml(cur.body) + '</div>';+ const actions = editing+ ? '<button class="btn btn-primary" onclick="deskSave(\'' + cur.id + '\')">Save</button>' ++ '<button class="btn btn-secondary" onclick="deskEdit(null)">Cancel</button>'+ : '<button class="btn btn-primary" onclick="outboxAct(\'' + cur.id + '\',\'approve\')">' ++ 'Approve <kbd>A</kbd></button>' ++ '<button class="btn btn-secondary" onclick="deskEdit(\'' + cur.id + '\')">' ++ 'Edit <kbd>E</kbd></button>' ++ '<button class="btn btn-secondary" onclick="outboxAct(\'' + cur.id + '\',\'reject\')">' ++ 'Reject <kbd>R</kbd></button>';+return '<div class="desk">' +'<div class="desk-list">' + rail + '</div>' +'<div class="desk-pane">' +'<div class="to-line">To <b>' + escHtml(cur.to_email) + '</b> · step ' +cur.step + ' (' + escHtml(cur.kind) + ') · sends ' +formatDate(cur.send_at) + '</div>' +- '<div class="subject">' + escHtml(cur.subject || '(no subject)') + '</div>' +- '<div class="body">' + escHtml(cur.body) + '</div>' +- '<div class="desk-actions">' +- '<button class="btn btn-primary" onclick="outboxAct(\'' + cur.id + '\',\'approve\')">' +- 'Approve <kbd>A</kbd></button>' +- '<button class="btn btn-secondary" onclick="outboxAct(\'' + cur.id + '\',\'reject\')">' +- 'Reject <kbd>R</kbd></button>' ++ renderDeskContext(cur.context) ++ draft ++ '<div class="desk-actions">' + actions +'<span class="muted" style="font-size:12px;margin-left:auto">' +(i + 1) + ' of ' + items.length + '</span>' +'</div>' +'</div></div>';}+function deskEdit(id) {+ _desk.editing = id;+ document.getElementById('outbox-desk').innerHTML = renderDesk(_desk.items, _desk.i);+ if (id) document.getElementById('desk-body').focus();+}++async function deskSave(id) {+ const subject = document.getElementById('desk-subject').value.trim();+ const body = document.getElementById('desk-body').value.trim();+ if (!subject || !body) { showToast('Subject and body are both required.', 'error'); return; }+ let data = null;+ try {+ const r = await authFetch('/api/outbox/' + encodeURIComponent(id) + '/edit', {+ method: 'POST', headers: {'Content-Type': 'application/json'},+ body: JSON.stringify({subject: subject, body: body}),+ });+ if (await lockIfRefused(r)) return;+ data = await r.json();+ } catch {}+ if (data && data.success) {+ _desk.editing = null;+ showToast('Saved. Still waiting for your approval.', 'success');+ loadOutbox();+ } else {+ showToast((data && data.message) || 'Save failed.', 'error');+ }+}+function deskGo(n) {if (n < 0 || n >= _desk.items.length) return;_desk.i = n;+ _desk.editing = null; // moving to another draft drops unsaved editsdocument.getElementById('outbox-desk').innerHTML = renderDesk(_desk.items, n);}@@ -1289,6 +1368,7 @@ document.addEventListener('keydown', e => {else if (k === 'k') { e.preventDefault(); deskGo(_desk.i - 1); }else if (k === 'a' && cur) { e.preventDefault(); outboxAct(cur.id, 'approve'); }else if (k === 'r' && cur) { e.preventDefault(); outboxAct(cur.id, 'reject'); }+ else if (k === 'e' && cur) { e.preventDefault(); deskEdit(cur.id); }});async function outboxAct(id, action) {diff --git a/tests/test_outbox_review.py b/tests/test_outbox_review.pynew file mode 100644index 0000000..4795ee9--- /dev/null+++ b/tests/test_outbox_review.py@@ -0,0 +1,102 @@+"""The Outbox review desk: the facts behind each draft, and editing it.++Reviewing a cold email means checking its claims against what Harvey actually+found. The desk shows that next to the draft, and lets a reviewer fix a draft+that is nearly right instead of throwing the lead away.+"""++import asyncio+import tempfile+from pathlib import Path++import pytest+from fastapi.testclient import TestClient++import harvey.dashboard as dash+from harvey.models import Company+from harvey.models.campaign import Campaign+from harvey.models.prospect import Prospect+from harvey.signals import seed_signal_catalog+from harvey.state import StateManager+++def client(monkeypatch):+ with tempfile.TemporaryDirectory() as tmp:+ db = Path(tmp) / "harvey.db"+ monkeypatch.setattr(dash, "DB_PATH", db)+ monkeypatch.setattr(dash, "WEB_DIR", Path(__file__).resolve().parent.parent / "harvey" / "web")+ dash.token_store.configure(Path(tmp) / "data" / "dashboard-token")+ token = dash.token_store.get()+ with TestClient(dash.app, base_url="http://127.0.0.1:5555",+ headers={"Authorization": f"Bearer {token}"}) as c:+ c.db_path = db+ yield c+++async def _seed(db_path, status="pending_review"):+ state = StateManager(str(db_path))+ await state.init_db()+ await seed_signal_catalog(state)+ company_id = await state.add_company(Company(+ name="Proven Resource", domain="proven.lovable.app",+ website="https://proven.lovable.app", description="Client portal for law firms",+ industry='site:lovable.app "client portal"'))+ await state.add_observations([+ {"company_id": company_id, "signal_code": "TECH_STACK", "value_text": "Lovable, Stripe"},+ {"company_id": company_id, "signal_code": "RUNNING_GOOGLE_ADS", "value_num": 1},+ ])+ prospect_id = await state.add_prospect(Prospect(+ email="[email protected]", email_status="risky", title="General inbox",+ source="scraped_mailto", company="Proven Resource", company_id=company_id,+ score=45, personalization_notes="Lovable-built client portal."))+ campaign_id = await state.add_campaign(Campaign(+ id="", name='site:lovable.app "client portal"-outreach', channel="email",+ sequence=[], prospect_ids=[prospect_id], status="active"))+ item_id = await state.add_outbox_item(+ prospect_id=prospect_id, to_email="[email protected]",+ subject="your client portal", body="Hello welcome team,\n\nHaris",+ send_at="2026-01-01T00:00:00", status=status, campaign_id=campaign_id)+ return state, item_id+++def test_pending_drafts_carry_the_facts_behind_them(client):+ asyncio.run(_seed(client.db_path))+ item = client.get("/api/outbox").json()["pending"][0]+ ctx = item["context"]+ assert ctx["company"] == "Proven Resource"+ assert ctx["website"] == "https://proven.lovable.app"+ assert ctx["description"] == "Client portal for law firms"+ assert ctx["campaign"] == 'site:lovable.app "client portal"-outreach'+ assert ctx["found_by"] == 'site:lovable.app "client portal"'+ assert ctx["contact_source"] == "scraped_mailto"+ assert ctx["email_status"] == "risky"+ assert ctx["notes"] == "Lovable-built client portal."+ assert ctx["signals"] == {"Website platform / tools": "Lovable, Stripe", "Running Google Ads": "yes"}+++def test_editing_a_draft_changes_it_but_does_not_approve_it(client):+ state, item_id = asyncio.run(_seed(client.db_path))+ r = client.post(f"/api/outbox/{item_id}/edit", json={+ "subject": "your portal", "body": "Hello Proven Resource team,\n\nHaris"})+ assert r.json() == {"success": True}+ item = asyncio.run(state.get_outbox_item(item_id))+ assert item["subject"] == "your portal"+ assert item["body"] == "Hello Proven Resource team,\n\nHaris"+ assert item["status"] == "pending_review"++[email protected]("status", ["approved", "sent", "rejected"])+def test_only_drafts_awaiting_review_can_be_edited(client, status):+ state, item_id = asyncio.run(_seed(client.db_path, status=status))+ r = client.post(f"/api/outbox/{item_id}/edit", json={"subject": "x", "body": "y"})+ assert r.status_code == 409+ assert asyncio.run(state.get_outbox_item(item_id))["subject"] == "your client portal"+++def test_edit_needs_both_subject_and_body(client):+ _, item_id = asyncio.run(_seed(client.db_path))+ assert client.post(f"/api/outbox/{item_id}/edit",+ json={"subject": " ", "body": "text"}).status_code == 400+ assert client.post(f"/api/outbox/{item_id}/edit",+ json={"subject": "s"}).status_code == 400