Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,43 @@ Simulator first.
- No option and no wire change. The button is inert while the form is open (it was already under the
backdrop).

## backends v2.2.0 — 2026-11-13

From Chris Hamblin's report bug-20261112-124952: it was fixed, and Ken had to tell Chris by hand. Closing
a report can now carry a note and email the person who filed it, and people are named throughout
(bug-report-py 2.2.0; bug-report-node passes the new fields through). All additive.

- **New: `create_blueprint(notifier=…, app_url=…)`.** `PATCH` takes `notify: true` (default false). On a
change to `resolved` or `declined` the server emails the reporter once: subject `Fixed: <title>` or
`Your bug report: <title> — not taken forward`; "Hi <first name>,", the note (URLs made links), signed with
the closer's name, "You reported this on <date> from <page>", the report id. Reply-To is the closer.
Reopening never emails. `notify` needs a non-empty `note` (400 otherwise, nothing changed). The status
change and its audit row are written first and a failed send never undoes them; a second audit row
(from = to = the new status) says `emailed Chris Hamblin <address>` or `email to … failed: <reason>`. The
response gains `notified: {ok, to, error?}`; no notifier configured, or a report with no address, is
`ok: false` with the reason (and the audit row). `GET /bugs/<id>` gains `canNotify` (a notifier is
configured and the report has an address). An app that passes no notifier never emails.
- **New: `bug_report.email`** — `Notice`, `render(notice) -> (subject, html)` (everything escaped) and
`AcsNotifier`, an Azure Communication Services Email sender modelled on leap-daily-report's, behind
the `[email]` extra (`azure-communication-email`, `azure-identity`). `AcsNotifier.from_env()` reads
`ACS_ENDPOINT` (managed identity; `BUG_NOTIFY_CLIENT_ID` picks a user-assigned one, its own name so it never changes the identity the rest of the app uses) or `ACS_CONNECTION_STRING`,
`BUG_NOTIFY_SENDER` and `BUG_NOTIFY_DOMAINS`, and returns `None` when any is missing, so
`notifier=AcsNotifier.from_env()` just does not email when unset. Fails closed: an address outside
`BUG_NOTIFY_DOMAINS` is refused before anything is sent. SDK retries are off (`retry_total=0`) and the
wait on the send is bounded (30 s); a send ACS has not confirmed by then is audited as failed, not
sent.
- **New: people are named.** Reports gain `actorName` and audit rows `changedByName` (`""` when unknown;
the UI derives "Chris Hamblin" from `chris.hamblin@…` the same way `bug_report.person_name` does).
`actor_identity` may return `{"email": …, "name": …}` as well as a bare address, and now also stamps
`changedBy`/`changedByName` on a status change, replacing the request body's claim, which read "admin"
on every close. Without the hook the body's `actorName`/`changedBy`/`changedByName` are used, as before.
`BugRecord.actor_name` and `AuditEntry.changed_by_name` default to `""`, so existing constructors and
files on disk work unchanged.
- **Node:** accepts and stores `actorName`/`changedByName` (Azure Tables: `ActorName`, `ChangedByName`),
serves `canNotify: false`, and ignores `notify` (no `notified`).
- Spec: `openapi.yaml`, `types.ts`, `types.py`, and `report-contract.json` (`optionalSummaryFields`,
`optionalAuditFields`) updated; e2e contract tests cover the names on both backends.

## backends — bug-report-py 2.1.1, bug-report-node 1.1.1 — 2026-10-20

- **Fix: `FilesystemStore` wrote a report in place, so a concurrent read saw half of it.** `put_bug`
Expand Down
54 changes: 54 additions & 0 deletions e2e/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,60 @@ def python_server(tmp_path_factory):
except subprocess.TimeoutExpired: proc.kill()


# ---------------------------------------------------------------------------
# Python backend with a mailer — the notify path over real HTTP (2.2.0)
# ---------------------------------------------------------------------------

PY_MAILER_SCRIPT = """
import json, sys
sys.path.insert(0, r"{pkg}")
from flask import Flask, request
from bug_report import create_blueprint, FilesystemStore

def notifier(n):
# A stand-in for AcsNotifier: records what it was asked to send, and fails
# on cue so the failure path is driven over HTTP too.
if "FAIL" in n.note:
raise RuntimeError("mail server said no")
with open(r"{outbox}", "a") as f:
f.write(json.dumps(n.__dict__) + "\\n")
return "msg-1"

def who(req):
return {{"email": req.headers.get("X-Test-User", ""), "name": req.headers.get("X-Test-Name", "")}}

app = Flask(__name__)
app.register_blueprint(create_blueprint(
store=FilesystemStore(r"{state}"), is_admin=lambda req: True,
actor_identity=who, notifier=notifier, app_url="https://app.example/",
))
app.run(host="127.0.0.1", port={port}, use_reloader=False)
"""


@pytest.fixture(scope="session")
def python_mailer_server(tmp_path_factory):
port = _free_port()
state = tmp_path_factory.mktemp("py-mail-state")
outbox = tmp_path_factory.mktemp("py-mail-out") / "outbox.jsonl"
script = PY_MAILER_SCRIPT.format(pkg=str(PY_PKG), state=str(state), port=port, outbox=str(outbox))
log = tmp_path_factory.mktemp("py-mail-log") / "out.log"
with open(log, "w") as logf:
proc = subprocess.Popen([sys.executable, "-c", script], stdout=logf, stderr=subprocess.STDOUT)
base = f"http://127.0.0.1:{port}/bugs"
try:
try:
_wait_alive(base)
except RuntimeError:
tail = log.read_text()[-2000:] if log.exists() else "(no log)"
raise RuntimeError(f"python mailer backend failed to start. log tail:\n{tail}")
yield base, outbox
finally:
proc.terminate()
try: proc.wait(timeout=3)
except subprocess.TimeoutExpired: proc.kill()


# ---------------------------------------------------------------------------
# Node backend — Express subprocess
# ---------------------------------------------------------------------------
Expand Down
36 changes: 36 additions & 0 deletions e2e/test_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,39 @@ def test_screenshot_type_is_sniffed_not_trusted(backend_url):
def test_screenshot_404_when_missing(backend_url):
bid = requests.post(backend_url, json={"details": "no shot"}).json()["id"]
assert requests.get(f"{backend_url}/{bid}/screenshot").status_code == 404


# ----- names (backends 2.2.0) ----------------------------------------
# Both backends keep and serve the display names; neither has a mailer in this
# harness, so `notify` must not produce a `notified` block and canNotify is false.

def test_names_are_stored_and_served(backend_url):
bid = requests.post(backend_url, json={
"details": "names", "actorEmail": "ana.reporter@example.com", "actorName": "Ana Reporter",
}).json()["id"]
requests.patch(f"{backend_url}/{bid}", json={
"status": "triaged", "changedBy": "sam.closer@example.com", "changedByName": "Sam Closer",
})
rec = requests.get(f"{backend_url}/{bid}").json()
assert rec["actorName"] == "Ana Reporter"
assert rec["audit"][0]["changedByName"] == "Ana Reporter"
assert (rec["audit"][1]["changedBy"], rec["audit"][1]["changedByName"]) == (
"sam.closer@example.com", "Sam Closer")
row = next(r for r in requests.get(backend_url).json()["bugs"] if r["id"] == bid)
assert row["actorName"] == "Ana Reporter"


def test_unknown_names_are_empty_strings_not_missing(backend_url):
bid = requests.post(backend_url, json={"details": "no names"}).json()["id"]
rec = requests.get(f"{backend_url}/{bid}").json()
assert rec["actorName"] == ""
assert rec["audit"][0]["changedByName"] == ""


def test_without_a_mailer_can_notify_is_false_and_notify_is_inert(backend_url):
bid = requests.post(backend_url, json={"details": "no mailer", "actorEmail": "ana@example.com"}).json()["id"]
assert requests.get(f"{backend_url}/{bid}").json()["canNotify"] is False
assert "canNotify" not in requests.get(backend_url).json()["bugs"][0]
r = requests.patch(f"{backend_url}/{bid}", json={"status": "triaged", "note": "x", "notify": True})
assert r.status_code == 200 and "notified" not in r.json()
assert len(r.json()["audit"]) == 2 # filed, triaged: no emailed row
81 changes: 81 additions & 0 deletions e2e/test_notify_http.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
"""Closing a report emails the person who filed it — over real HTTP (2.2.0).

Python only: the Node backend has no notifier (it answers ``canNotify: false``
and ignores ``notify``; test_contract.py pins that on both stacks). This drives
the ``notifier=`` wiring through a running server with a stand-in mailer, so a
break between the blueprint and the notifier fails here, not in production.
"""
from __future__ import annotations

import json

import requests

CHRIS = {"X-Test-User": "chris.hamblin@helloleap.ai", "X-Test-Name": "Chris Hamblin"}
KEN = {"X-Test-User": "ken.moynihan@helloleap.ai", "X-Test-Name": "Ken Moynihan"}


def _file_and_triage(base: str, title: str) -> str:
r = requests.post(base, json={"title": title, "details": "d", "metaUrl": "https://app.example/day"},
headers=CHRIS, timeout=5)
assert r.status_code == 201, r.text
bid = r.json()["id"]
assert requests.patch(f"{base}/{bid}", json={"status": "triaged", "note": ""}, headers=KEN,
timeout=5).status_code == 200
return bid


def _sent(outbox) -> list[dict]:
return [json.loads(line) for line in outbox.read_text().splitlines()] if outbox.exists() else []


def test_resolving_with_notify_emails_the_filer_and_audits_it(python_mailer_server):
base, outbox = python_mailer_server
bid = _file_and_triage(base, "Time of issue not set")
assert requests.get(f"{base}/{bid}", headers=KEN, timeout=5).json()["canNotify"] is True
before = len(_sent(outbox))

r = requests.patch(f"{base}/{bid}", json={"status": "resolved", "note": "Fixed — it asks first now.",
"notify": True}, headers=KEN, timeout=5)
assert r.status_code == 200, r.text
body = r.json()
assert body["status"] == "resolved"
assert body["notified"] == {"ok": True, "to": "chris.hamblin@helloleap.ai"}

sent = _sent(outbox)[before:]
assert len(sent) == 1
n = sent[0]
assert (n["to_email"], n["to_name"], n["closer_email"], n["closer_name"]) == (
"chris.hamblin@helloleap.ai", "Chris Hamblin", "ken.moynihan@helloleap.ai", "Ken Moynihan")
assert (n["status"], n["note"], n["page_url"], n["app_url"]) == (
"resolved", "Fixed — it asks first now.", "https://app.example/day", "https://app.example/")

change, outcome = body["audit"][-2:]
assert (change["fromStatus"], change["toStatus"], change["changedByName"]) == ("triaged", "resolved", "Ken Moynihan")
assert outcome["note"] == "emailed Chris Hamblin <chris.hamblin@helloleap.ai>"


def test_a_failed_send_still_resolves_and_says_so(python_mailer_server):
base, outbox = python_mailer_server
bid = _file_and_triage(base, "Send fails")
before = len(_sent(outbox))

r = requests.patch(f"{base}/{bid}", json={"status": "resolved", "note": "FAIL on purpose", "notify": True},
headers=KEN, timeout=5)
assert r.status_code == 200, r.text
body = r.json()
assert body["status"] == "resolved"
assert body["notified"]["ok"] is False and "mail server said no" in body["notified"]["error"]
assert body["audit"][-1]["note"].startswith("email to Chris Hamblin <chris.hamblin@helloleap.ai> failed:")
assert len(_sent(outbox)) == before
# the change stuck: a fresh read agrees
assert requests.get(f"{base}/{bid}", headers=KEN, timeout=5).json()["status"] == "resolved"


def test_without_notify_nothing_is_sent(python_mailer_server):
base, outbox = python_mailer_server
bid = _file_and_triage(base, "Quiet close")
before = len(_sent(outbox))
r = requests.patch(f"{base}/{bid}", json={"status": "resolved", "note": "done"}, headers=KEN, timeout=5)
assert r.status_code == 200 and "notified" not in r.json()
assert len(_sent(outbox)) == before
16 changes: 13 additions & 3 deletions packages/backend-node/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ export { BUG_DETAILS_MAX, BUG_SCREENSHOT_MAX, BUG_STATUSES, newBugId, validBugId

const DEFAULT_ALLOW = () => true;

// A row written before backends 2.2.0 has no name; the wire says "" then.
const withChangedByName = (a) => ({ ...a, changedByName: a.changedByName || "" });

export function createBugsRouter(opts = {}) {
const store = opts.store;
if (!store) throw new Error("createBugsRouter: opts.store is required");
Expand Down Expand Up @@ -63,6 +66,7 @@ export function createBugsRouter(opts = {}) {
let title = (payload.title || details.split("\n")[0]).slice(0, 100).trim();
let addedBy = String(payload.addedBy || "web").trim().slice(0, 32) || "web";
const actorEmail = String(payload.actorEmail || defaultActorEmail || "").trim().slice(0, 200);
const actorName = String(payload.actorName || "").trim().slice(0, 200);

let tags = payload.tags || ["bug"];
if (typeof tags === "string") tags = tags.split(",").map(s => s.trim()).filter(Boolean);
Expand Down Expand Up @@ -95,6 +99,7 @@ export function createBugsRouter(opts = {}) {
status: "open",
addedBy,
actorEmail,
actorName,
addedAt: nowIso(),
metaUrl: String(payload.metaUrl || "").slice(0, 500),
metaUserAgent: String(payload.metaUserAgent || "").slice(0, 300),
Expand All @@ -108,6 +113,7 @@ export function createBugsRouter(opts = {}) {
toStatus: "open",
fromStatus: null,
changedBy: actorEmail || addedBy,
changedByName: actorName,
note: "filed",
});

Expand Down Expand Up @@ -143,7 +149,8 @@ export function createBugsRouter(opts = {}) {
throw e;
}
const full = toBugFull(rec);
full.audit = await store.listAudit(rec.id);
full.canNotify = false; // this backend has no mailer
full.audit = (await store.listAudit(rec.id)).map(withChangedByName);
res.json(full);
});

Expand All @@ -165,12 +172,14 @@ export function createBugsRouter(opts = {}) {
}
const note = String(payload.note || "").slice(0, 500);
const changedBy = String(payload.changedBy || defaultActorEmail || "admin").slice(0, 200);
const changedByName = String(payload.changedByName || "").trim().slice(0, 200);
// `notify` is accepted and ignored: no mailer here, so no `notified` either.

const oldStatus = rec.status;
if (newStatus === oldStatus) {
// No-op: skip audit.
const full = toBugFull(rec);
full.audit = await store.listAudit(rec.id);
full.audit = (await store.listAudit(rec.id)).map(withChangedByName);
return res.json(full);
}

Expand All @@ -180,11 +189,12 @@ export function createBugsRouter(opts = {}) {
toStatus: newStatus,
fromStatus: oldStatus,
changedBy,
changedByName,
note,
});

const full = toBugFull(updated);
full.audit = await store.listAudit(rec.id);
full.audit = (await store.listAudit(rec.id)).map(withChangedByName);
res.json(full);
});

Expand Down
2 changes: 2 additions & 0 deletions packages/backend-node/src/store.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export function makeBugRecord(o) {
status: o.status || "open",
addedBy: o.addedBy || "web",
actorEmail: o.actorEmail || "",
actorName: o.actorName || "",
addedAt: o.addedAt,
metaUrl: o.metaUrl || "",
metaUserAgent: o.metaUserAgent || "",
Expand All @@ -46,6 +47,7 @@ export function toBugSummary(rec) {
status: rec.status,
addedBy: rec.addedBy,
actorEmail: rec.actorEmail,
actorName: rec.actorName || "",
addedAt: rec.addedAt,
screenshot: !!rec.screenshot,
};
Expand Down
4 changes: 4 additions & 0 deletions packages/backend-node/src/stores/azure-tables.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ function entityToBugRecord(e) {
status: e.Status || "open",
addedBy: e.AddedBy || "web",
actorEmail: e.ActorEmail || "",
actorName: e.ActorName || "",
addedAt: e.AddedAt || "",
metaUrl: e.MetaUrl || "",
metaUserAgent: e.MetaUserAgent || "",
Expand All @@ -92,6 +93,7 @@ function bugRecordToEntity(rec) {
AddedBy: rec.addedBy,
AddedAt: rec.addedAt,
ActorEmail: rec.actorEmail || "",
ActorName: rec.actorName || "",
MetaUrl: rec.metaUrl || "",
MetaUserAgent: rec.metaUserAgent || "",
MetaBuildSha: rec.metaBuildSha || "",
Expand Down Expand Up @@ -244,6 +246,7 @@ export class AzureTablesStore {
FromStatus: entry.fromStatus || "",
ToStatus: entry.toStatus || "",
ChangedBy: entry.changedBy || "",
ChangedByName: entry.changedByName || "",
ChangedAt: entry.changedAt || new Date().toISOString(),
Note: entry.note || "",
Action: entry.fromStatus === null || entry.fromStatus === "" ? "create" : "transition",
Expand All @@ -263,6 +266,7 @@ export class AzureTablesStore {
fromStatus: e.FromStatus || null,
toStatus: e.ToStatus || "",
changedBy: e.ChangedBy || "",
changedByName: e.ChangedByName || "",
note: e.Note || "",
});
}
Expand Down
39 changes: 39 additions & 0 deletions packages/backend-node/tests/router.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,45 @@ for (const [name, makeStore] of STORES) {
});
}

// ---------------------------------------------------------------------
// Names (backends 2.2.0): passed through; no mailer, so notify is ignored
// ---------------------------------------------------------------------

for (const [name, makeStore] of STORES) {
test(`[${name}] names are stored and served; notify is ignored (no notified, canNotify false)`, async () => {
await withApp(makeStore, null, async ({ server }) => {
const json = { "Content-Type": "application/json" };
const id = (await (await fetch(url(server, "/bugs"), {
method: "POST", headers: json,
body: JSON.stringify({ details: "d", actorEmail: "ana@example.com", actorName: "Ana Reporter" }),
})).json()).id;
const patched = await (await fetch(url(server, `/bugs/${id}`), {
method: "PATCH", headers: json,
body: JSON.stringify({ status: "declined", note: "no", notify: true, changedBy: "sam@example.com", changedByName: "Sam Closer" }),
})).json();
assert.equal("notified" in patched, false);
const got = await (await fetch(url(server, `/bugs/${id}`))).json();
assert.equal(got.actorName, "Ana Reporter");
assert.equal(got.canNotify, false);
assert.equal(got.audit[0].changedByName, "Ana Reporter");
assert.deepEqual([got.audit[1].changedBy, got.audit[1].changedByName], ["sam@example.com", "Sam Closer"]);
const list = await (await fetch(url(server, "/bugs"))).json();
assert.equal(list.bugs[0].actorName, "Ana Reporter");
});
});

test(`[${name}] a report filed without a name says "" and its audit rows say ""`, async () => {
await withApp(makeStore, null, async ({ server }) => {
const id = (await (await fetch(url(server, "/bugs"), {
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ details: "d" }),
})).json()).id;
const got = await (await fetch(url(server, `/bugs/${id}`))).json();
assert.equal(got.actorName, "");
assert.equal(got.audit[0].changedByName, "");
});
});
}

// ---------------------------------------------------------------------
// Single-store sanity tests
// ---------------------------------------------------------------------
Expand Down
Loading
Loading