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.

Outbox edit: no stale approvals mid-edit, replies keep their subject

Ethan01492a2ca06d
diff --git a/harvey/dashboard.py b/harvey/dashboard.py
index b02b8bb..c8dfe6c 100644
--- a/harvey/dashboard.py
+++ b/harvey/dashboard.py
@@ -791,21 +791,35 @@ async def _with_context(items: list[dict]) -> list[dict]:
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 "
+ "o.observed_at, o.run_id, "
+ "COALESCE(NULLIF(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",
+ "ORDER BY o.observed_at, o.id",
(*company_ids, *OUTBOX_CONTEXT_SIGNALS),
)
- for r in rows: # oldest first, so the latest observation wins
+ # Oldest first, so the latest observation wins. A signal can be seen
+ # several times at once (one HIRING_ROLE row per open role): every
+ # value from the latest sighting shows, not just one of them.
+ latest: dict[tuple, tuple] = {}
+ for r in rows:
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
+ key = (r["company_id"], r["label"])
+ seen = (r["run_id"] or r["observed_at"])
+ prev_seen, values = latest.get(key, (None, []))
+ if seen != prev_seen:
+ values = []
+ if value not in values:
+ values = values + [value]
+ latest[key] = (seen, values)
+ for (company_id, label), (_, values) in latest.items():
+ signals.setdefault(company_id, {})[label] = ", ".join(v for v in values if v)
for item in items:
p = people.get(item.get("prospect_id")) or {}
@@ -877,8 +891,10 @@ async def outbox_edit(item_id: str, request: Request):
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 isinstance(body, dict):
+ body = {}
+ subject = str(body.get("subject") or "").strip()
+ text = str(body.get("body") or "").strip()
if not subject or not text:
return JSONResponse({"success": False, "message": "Subject and body are both required."},
status_code=400)
@@ -896,10 +912,22 @@ async def outbox_edit(item_id: str, request: Request):
try:
state = _state()
await state.init_db()
- if not await state.edit_outbox_draft(item_id, subject, text):
+ item = await state.get_outbox_item(item_id)
+ if item and item.get("kind") == "reply" and subject != (item.get("subject") or "").strip():
+ # Gmail threads a reply by its subject: a new one would land as a
+ # fresh, unthreaded email to someone who wrote in.
+ return JSONResponse({"success": False,
+ "message": "A reply keeps its subject so it stays in the "
+ "thread. Edit the body only."},
+ status_code=400)
+ if not item or 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)
+ await state.log_action("outbox_edited", "dashboard", {
+ "outbox_id": item_id, "to_email": item.get("to_email", ""),
+ "old_subject": item.get("subject", ""), "old_body": item.get("body", ""),
+ })
return {"success": True}
except Exception as e:
return JSONResponse({"success": False, "message": str(e)}, status_code=500)
diff --git a/harvey/web/app.js b/harvey/web/app.js
index a7943e0..5665754 100644
--- a/harvey/web/app.js
+++ b/harvey/web/app.js
@@ -1193,6 +1193,10 @@ async function loadOutbox() {
const pending = data.pending || [];
_desk.items = pending;
+ if (_desk.editing && !pending.some(p => p.id === _desk.editing)) {
+ _desk.editing = null;
+ _desk.unsaved = null;
+ }
if (_desk.i >= pending.length) _desk.i = Math.max(0, pending.length - 1);
navCount('nav-outbox', pending.length);
@@ -1275,11 +1279,12 @@ function renderDeskContext(ctx) {
row('Website', site) +
row('About', escHtml(ctx.description)) +
row('Contact', who) +
- row('Found via', escHtml(CONTACT_SOURCES[ctx.contact_source] || ctx.contact_source)) +
+ row('Found via', escHtml(Object.prototype.hasOwnProperty.call(CONTACT_SOURCES, ctx.contact_source)
+ ? 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('Campaign', ctx.campaign ? escHtml(ctx.campaign) +
+ ' <span class="muted">(how they were found, not a fact about them)</span>' : '') +
row('Writer notes', escHtml(ctx.notes)) +
'</div>';
}
@@ -1293,9 +1298,15 @@ function renderDesk(items, i) {
'</div>').join('');
const editing = _desk.editing === cur.id;
+ const unsaved = (editing && _desk.unsaved) || {subject: cur.subject || '', body: cur.body || ''};
+ // A reply keeps its subject: Gmail threads by it.
+ const fixedSubject = cur.kind === 'reply'
+ ? ' readonly title="A reply keeps its subject so it stays in the thread"' : '';
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>'
+ ? '<input id="desk-subject" class="desk-edit-subject" value="' + escHtml(unsaved.subject) + '"' +
+ fixedSubject + ' oninput="deskKeep()">' +
+ '<textarea id="desk-body" class="desk-edit-body" rows="14" oninput="deskKeep()">' +
+ escHtml(unsaved.body) + '</textarea>'
: '<div class="subject">' + escHtml(cur.subject || '(no subject)') + '</div>' +
'<div class="body">' + escHtml(cur.body) + '</div>';
const actions = editing
@@ -1325,10 +1336,27 @@ function renderDesk(items, i) {
function deskEdit(id) {
_desk.editing = id;
+ _desk.unsaved = null;
document.getElementById('outbox-desk').innerHTML = renderDesk(_desk.items, _desk.i);
if (id) document.getElementById('desk-body').focus();
}
+// What's typed survives a re-render (switching tabs and back reloads the desk).
+function deskKeep() {
+ _desk.unsaved = {
+ subject: document.getElementById('desk-subject').value,
+ body: document.getElementById('desk-body').value,
+ };
+}
+
+// While a draft is being edited, nothing else on the desk may act on the
+// stored version of it: Save or Cancel first.
+function deskBusy() {
+ if (!_desk.editing) return false;
+ showToast('Save or cancel your edit first.', 'error');
+ return true;
+}
+
async function deskSave(id) {
const subject = document.getElementById('desk-subject').value.trim();
const body = document.getElementById('desk-body').value.trim();
@@ -1344,6 +1372,7 @@ async function deskSave(id) {
} catch {}
if (data && data.success) {
_desk.editing = null;
+ _desk.unsaved = null;
showToast('Saved. Still waiting for your approval.', 'success');
loadOutbox();
} else {
@@ -1352,15 +1381,22 @@ async function deskSave(id) {
}
function deskGo(n) {
- if (n < 0 || n >= _desk.items.length) return;
+ if (n < 0 || n >= _desk.items.length || deskBusy()) return;
_desk.i = n;
- _desk.editing = null; // moving to another draft drops unsaved edits
document.getElementById('outbox-desk').innerHTML = renderDesk(_desk.items, n);
}
// Keyboard review. Ignored while typing into a field, so Settings still works.
document.addEventListener('keydown', e => {
if (currentTab !== 'outbox' || e.metaKey || e.ctrlKey || e.altKey) return;
+ // Mid-edit, A would approve the stored draft, not what's typed. Only
+ // Escape (cancel) works until the edit is saved or cancelled.
+ if (_desk.editing) {
+ const typing = /^(input|textarea)$/i.test(e.target.tagName || '');
+ if (e.key === 'Escape') { e.preventDefault(); deskEdit(null); }
+ else if (!typing && 'jkare'.includes(e.key.toLowerCase())) { e.preventDefault(); deskBusy(); }
+ return;
+ }
const tag = (e.target.tagName || '').toLowerCase();
if (tag === 'input' || tag === 'textarea' || e.target.isContentEditable) return;
const cur = _desk.items[_desk.i];
@@ -1373,6 +1409,7 @@ document.addEventListener('keydown', e => {
});
async function outboxAct(id, action) {
+ if (deskBusy()) return;
const data = await api('/api/outbox/' + encodeURIComponent(id) + '/' + action, {method: 'POST'});
if (data && data.success) showToast(action === 'approve' ? 'Approved — will send on schedule.' : 'Rejected.', 'success');
else showToast('Action failed.', 'error');
@@ -1380,6 +1417,7 @@ async function outboxAct(id, action) {
}
async function outboxApproveAll() {
+ if (deskBusy()) return;
const data = await api('/api/outbox/approve-all', {method: 'POST'});
if (data && data.success) showToast('Approved ' + data.approved + ' email(s).', 'success');
else showToast('Approve-all failed.', 'error');
diff --git a/tests/test_outbox_review.py b/tests/test_outbox_review.py
index b74449e..ebed84c 100644
--- a/tests/test_outbox_review.py
+++ b/tests/test_outbox_review.py
@@ -6,9 +6,11 @@ that is nearly right instead of throwing the lead away.
"""
import asyncio
+import json
import tempfile
from pathlib import Path
+import aiosqlite
import pytest
from fastapi.testclient import TestClient
@@ -34,7 +36,7 @@ def client(monkeypatch):
yield c
-async def _seed(db_path, status="pending_review"):
+async def _seed(db_path, status="pending_review", kind="sequence"):
state = StateManager(str(db_path))
await state.init_db()
await seed_signal_catalog(state)
@@ -56,7 +58,7 @@ async def _seed(db_path, status="pending_review"):
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)
+ send_at="2026-01-01T00:00:00", status=status, campaign_id=campaign_id, kind=kind)
return state, item_id
@@ -119,3 +121,82 @@ def test_editing_needs_the_dashboard_token(client):
r = client.post(f"/api/outbox/{item_id}/edit", headers={"Authorization": ""},
json={"subject": "s", "body": "b"})
assert r.status_code in (401, 403)
+
+
+def test_a_reply_keeps_its_subject_so_it_stays_in_the_thread(client):
+ state, item_id = asyncio.run(_seed(client.db_path, kind="reply"))
+ r = client.post(f"/api/outbox/{item_id}/edit",
+ json={"subject": "something new", "body": "Thanks, Tuesday works."})
+ assert r.status_code == 400
+ assert "thread" in r.json()["message"]
+ r = client.post(f"/api/outbox/{item_id}/edit",
+ json={"subject": "your client portal", "body": "Thanks, Tuesday works."})
+ assert r.json() == {"success": True}
+ assert asyncio.run(state.get_outbox_item(item_id))["body"] == "Thanks, Tuesday works."
+
+
[email protected]("payload", [[], "text", 5])
+def test_a_body_that_is_not_an_object_is_a_400_not_a_crash(client, payload):
+ _, item_id = asyncio.run(_seed(client.db_path))
+ assert client.post(f"/api/outbox/{item_id}/edit", json=payload).status_code == 400
+
+
+def test_an_edit_is_logged_with_what_it_replaced(client):
+ _, item_id = asyncio.run(_seed(client.db_path))
+ client.post(f"/api/outbox/{item_id}/edit", json={"subject": "your portal", "body": "New text"})
+ rows = asyncio.run(dash.query_db(
+ "SELECT details_json FROM actions WHERE action_type = 'outbox_edited'"))
+ assert len(rows) == 1
+ details = json.loads(rows[0]["details_json"])
+ assert details["outbox_id"] == item_id
+ assert details["old_subject"] == "your client portal"
+ assert details["old_body"] == "Hello welcome team,\n\nHaris"
+
+
+def test_editing_is_refused_cross_site(client):
+ _, item_id = asyncio.run(_seed(client.db_path))
+ r = client.post(f"/api/outbox/{item_id}/edit", json={"subject": "s", "body": "b"},
+ headers={"Origin": "https://evil.example", "Sec-Fetch-Site": "cross-site"})
+ assert r.status_code in (401, 403)
+
+
+def test_every_open_role_shows_and_unlabelled_signals_keep_their_code(client):
+ state, _ = asyncio.run(_seed(client.db_path))
+
+ async def more():
+ cid = (await dash.query_db("SELECT id FROM companies"))[0]["id"]
+ await state.add_observations([
+ {"company_id": cid, "signal_code": "HIRING_ROLE", "value_text": "Roofing estimator",
+ "run_id": "r1"},
+ {"company_id": cid, "signal_code": "HIRING_ROLE", "value_text": "Crew foreman",
+ "run_id": "r1"},
+ ])
+ async with aiosqlite.connect(client.db_path) as db:
+ await db.execute("UPDATE signal_codes SET label = '' WHERE code = 'TECH_STACK'")
+ await db.commit()
+ asyncio.run(more())
+ signals = client.get("/api/outbox").json()["pending"][0]["context"]["signals"]
+ assert signals["TECH_STACK"] == "Lovable, Stripe"
+ assert "" not in signals
+ hiring = [v for k, v in signals.items() if "hiring" in k.lower() or k == "HIRING_ROLE"]
+ assert len(hiring) == 1
+ assert "Roofing estimator" in hiring[0] and "Crew foreman" in hiring[0]
+
+
+def test_an_approved_edit_is_what_gets_sent(client):
+ from tests.test_outbox_native import FakeProvider, make_sender
+ state, item_id = asyncio.run(_seed(client.db_path))
+ client.post(f"/api/outbox/{item_id}/edit",
+ json={"subject": "your portal", "body": "Hello Proven Resource team,\n\nHaris"})
+ assert client.post(f"/api/outbox/{item_id}/approve").json()["success"]
+
+ async def send():
+ async with aiosqlite.connect(client.db_path) as db:
+ await db.execute("UPDATE prospects SET email_status = 'verified'")
+ await db.commit()
+ provider = FakeProvider()
+ await make_sender(state, provider)._drain_due()
+ return provider.sent
+ sent = asyncio.run(send())
+ assert [(m["subject"], m["body"]) for m in sent] == [
+ ("your portal", "Hello Proven Resource team,\n\nHaris")]