diff --git a/CHANGELOG.md b/CHANGELOG.md
index d069d84..42799c7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -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:
` or
+ `Your bug report: — not taken forward`; "Hi ,", the note (URLs made links), signed with
+ the closer's name, "You reported this on from ", 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 ` or `email to … failed: `. 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/` 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`
diff --git a/e2e/conftest.py b/e2e/conftest.py
index e89cce7..1f720d0 100644
--- a/e2e/conftest.py
+++ b/e2e/conftest.py
@@ -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
# ---------------------------------------------------------------------------
diff --git a/e2e/test_contract.py b/e2e/test_contract.py
index b9ea921..e589bbe 100644
--- a/e2e/test_contract.py
+++ b/e2e/test_contract.py
@@ -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
diff --git a/e2e/test_notify_http.py b/e2e/test_notify_http.py
new file mode 100644
index 0000000..8d1e744
--- /dev/null
+++ b/e2e/test_notify_http.py
@@ -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 "
+
+
+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 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
diff --git a/packages/backend-node/src/index.js b/packages/backend-node/src/index.js
index 5b49112..2804b66 100644
--- a/packages/backend-node/src/index.js
+++ b/packages/backend-node/src/index.js
@@ -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");
@@ -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);
@@ -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),
@@ -108,6 +113,7 @@ export function createBugsRouter(opts = {}) {
toStatus: "open",
fromStatus: null,
changedBy: actorEmail || addedBy,
+ changedByName: actorName,
note: "filed",
});
@@ -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);
});
@@ -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);
}
@@ -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);
});
diff --git a/packages/backend-node/src/store.js b/packages/backend-node/src/store.js
index 167961d..07d99de 100644
--- a/packages/backend-node/src/store.js
+++ b/packages/backend-node/src/store.js
@@ -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 || "",
@@ -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,
};
diff --git a/packages/backend-node/src/stores/azure-tables.js b/packages/backend-node/src/stores/azure-tables.js
index b84381a..1a76585 100644
--- a/packages/backend-node/src/stores/azure-tables.js
+++ b/packages/backend-node/src/stores/azure-tables.js
@@ -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 || "",
@@ -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 || "",
@@ -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",
@@ -263,6 +266,7 @@ export class AzureTablesStore {
fromStatus: e.FromStatus || null,
toStatus: e.ToStatus || "",
changedBy: e.ChangedBy || "",
+ changedByName: e.ChangedByName || "",
note: e.Note || "",
});
}
diff --git a/packages/backend-node/tests/router.test.js b/packages/backend-node/tests/router.test.js
index 5486473..0bb8d37 100644
--- a/packages/backend-node/tests/router.test.js
+++ b/packages/backend-node/tests/router.test.js
@@ -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
// ---------------------------------------------------------------------
diff --git a/packages/backend-python/README.md b/packages/backend-python/README.md
index 7f9ea26..e87ecda 100644
--- a/packages/backend-python/README.md
+++ b/packages/backend-python/README.md
@@ -38,6 +38,27 @@ Routes mounted (under the prefix you pass):
| PATCH | /bugs/{id} | `is_admin` |
| GET | /bugs/{id}/screenshot | open |
+## Emailing the reporter on close (2.2.0)
+
+```python
+# pip install "bug-report-py[email]" # azure-communication-email, azure-identity
+from bug_report import create_blueprint, AcsNotifier
+
+create_blueprint(
+ store=store,
+ actor_identity=lambda req: {"email": signed_in_address(req), "name": signed_in_name(req)},
+ notifier=AcsNotifier.from_env(), # None when not configured: no emails, no tick box
+ app_url="https://sv.example.com", # linked when the report has no page URL
+)
+```
+
+`PATCH {status, note, notify: true}` on a change to `resolved`/`declined` writes the change and its audit row, then
+emails the reporter and writes a second audit row with the outcome. A failed send never undoes the change; the
+response carries `notified: {ok, to, error?}`. Environment for `AcsNotifier.from_env()`: `ACS_ENDPOINT` (managed
+identity; `BUG_NOTIFY_CLIENT_ID` for a user-assigned one) or `ACS_CONNECTION_STRING`, `BUG_NOTIFY_SENDER`,
+`BUG_NOTIFY_DOMAINS` (comma list; an address outside it is refused). Any `notifier(notice) -> message id` that
+raises on failure works in its place.
+
Open-by-default for POST and single-bug GET is deliberate: any user (or agent) can file, and the user who filed should be able to read back their own report. Tighten in your own auth wrapper if your threat model needs it.
## Stores
diff --git a/packages/backend-python/bug_report/__init__.py b/packages/backend-python/bug_report/__init__.py
index dd9629d..ccd0cf0 100644
--- a/packages/backend-python/bug_report/__init__.py
+++ b/packages/backend-python/bug_report/__init__.py
@@ -16,6 +16,7 @@
"""
from .blueprint import create_blueprint
+from .email import AcsNotifier, Notice, render
from .store import (
Store,
StoreError,
@@ -28,6 +29,8 @@
BUG_SCREENSHOT_MAX,
BUG_STATUSES,
new_bug_id,
+ person_name,
+ first_name,
valid_bug_id,
)
@@ -48,6 +51,9 @@
__all__ = [
"create_blueprint",
+ "AcsNotifier",
+ "Notice",
+ "render",
"contract",
"KINDS",
"TRANSITIONS",
@@ -68,4 +74,6 @@
"BUG_STATUSES",
"new_bug_id",
"valid_bug_id",
+ "person_name",
+ "first_name",
]
diff --git a/packages/backend-python/bug_report/blueprint.py b/packages/backend-python/bug_report/blueprint.py
index 451d7ca..de343e2 100644
--- a/packages/backend-python/bug_report/blueprint.py
+++ b/packages/backend-python/bug_report/blueprint.py
@@ -7,17 +7,20 @@
import base64
import io
+import logging
import time
from typing import Callable
from flask import Blueprint, abort, jsonify, request, send_file
from . import contract
+from .email import Notice
from .models import (
BUG_DETAILS_MAX,
BUG_SCREENSHOT_MAX,
BUG_STATUSES,
new_bug_id,
+ person_name,
screenshot_content_type,
valid_bug_id,
)
@@ -28,6 +31,7 @@
Store,
)
+log = logging.getLogger(__name__)
_last_now_ns = 0
@@ -63,6 +67,8 @@ def create_blueprint(
actor_identity: Callable | None = None,
build_sha: str | Callable[[], str] = "",
url_prefix: str = "/bugs",
+ notifier: Callable | None = None,
+ app_url: str = "",
) -> Blueprint:
"""Build a Flask blueprint that serves the bug-report API.
@@ -71,17 +77,25 @@ def create_blueprint(
is_admin: ``(request) -> bool`` gate for ``GET /bugs`` and ``PATCH``.
Default: allow everything (suitable for single-user apps).
default_actor_email: Email stamped on reports filed without one.
- actor_identity: ``(request) -> str`` returning the CHECKED identity of
- the person filing (e.g. from EasyAuth's principal). When
+ actor_identity: ``(request) -> str | dict`` returning the CHECKED identity
+ of the person filing (e.g. from EasyAuth's principal): an
+ address, or ``{"email": ..., "name": ...}`` (2.2.0). When
given, it alone decides the report's ``actorEmail``: the
payload's ``actorEmail`` is ignored, because a page can
claim any address, and an empty answer files the report
with no actor rather than with the claim. Without it the
- payload's value is used, as before. Added in 2.1.0.
+ payload's value is used, as before. Added in 2.1.0. The
+ same identity stamps ``changedBy``/``changedByName`` on a
+ status change (2.2.0), replacing the request body's claim.
build_sha: String or zero-arg callable returning the current build SHA.
Stamped on each report. Empty string means "unknown".
url_prefix: Mount path within the blueprint. Outer app typically
mounts the whole blueprint under ``/api``.
+ notifier: ``(Notice) -> str`` that emails the reporter when a PATCH
+ closes their report with ``notify: true``; returns a message
+ id, raises on failure (2.2.0). See ``bug_report.email``.
+ ``None``: no email is ever sent.
+ app_url: Link used in the email when the report has no page URL.
"""
if is_admin is None:
is_admin = lambda req: True # noqa: E731 — single-user default
@@ -96,6 +110,18 @@ def _resolve_build_sha() -> str:
return ""
return build_sha or ""
+ def _identity(req) -> tuple[str, str]:
+ """(email, name) from the identity hook; a str answer is an address
+ only. An unreadable identity is no identity, never a 500."""
+ try:
+ who = actor_identity(req)
+ except Exception:
+ return "", ""
+ if isinstance(who, dict):
+ return (str(who.get("email") or "").strip()[:200],
+ str(who.get("name") or "").strip()[:200])
+ return (who or "").strip()[:200], ""
+
# ----- POST /bugs ---------------------------------------------------
@bp.route(url_prefix, methods=["POST"])
@@ -114,14 +140,12 @@ def api_create():
title = (payload.get("title") or details.splitlines()[0])[:100].strip()
added_by = (payload.get("addedBy") or payload.get("added_by") or "web").strip()[:32] or "web"
if actor_identity is not None:
- try:
- actor_email = (actor_identity(request) or "").strip()[:200]
- except Exception: # an identity that cannot be read is no identity, never a 500
- actor_email = ""
+ actor_email, actor_name = _identity(request)
else:
actor_email = (
payload.get("actorEmail") or payload.get("actor_email") or default_actor_email
).strip()[:200]
+ actor_name = str(payload.get("actorName") or payload.get("actor_name") or "").strip()[:200]
tags = payload.get("tags") or ["bug"]
if isinstance(tags, str):
@@ -157,6 +181,7 @@ def api_create():
status="open",
added_by=added_by,
actor_email=actor_email,
+ actor_name=actor_name,
added_at=_now_iso(),
meta_url=(payload.get("metaUrl") or payload.get("meta_url") or "")[:500],
meta_user_agent=(payload.get("metaUserAgent") or payload.get("meta_user_agent") or "")[:300],
@@ -169,6 +194,7 @@ def api_create():
to_status="open",
from_status=None,
changed_by=actor_email or added_by,
+ changed_by_name=actor_name,
note="filed",
))
return jsonify({"id": bug.id}), 201
@@ -202,6 +228,7 @@ def api_get(bug_id: str):
except NotFound:
return jsonify({"error": "not found"}), 404
full = bug.to_full()
+ full["canNotify"] = bool(notifier is not None and bug.actor_email)
full["audit"] = [a.to_dict() for a in store.list_audit(bug_id)]
return jsonify(full)
@@ -234,9 +261,22 @@ def api_patch(bug_id: str):
if (new_status in contract.REASON_REQUIRED_FOR and new_status != old
and not note.strip()):
return jsonify({"error": f"a reason is required to mark a report {new_status}"}), 400
- changed_by = (
- payload.get("changedBy") or payload.get("changed_by") or default_actor_email or "admin"
- )[:200]
+ will_notify = (payload.get("notify") is True and new_status != old
+ and new_status in ("resolved", "declined"))
+ if will_notify and not note.strip():
+ return jsonify({"error": "a note for the reporter is required to email them"}), 400
+ if actor_identity is not None:
+ # the checked identity, not the body's claim
+ closer_email, changed_by_name = _identity(request)
+ changed_by = (closer_email or default_actor_email or "admin")[:200]
+ else:
+ changed_by = (
+ payload.get("changedBy") or payload.get("changed_by") or default_actor_email or "admin"
+ )[:200]
+ changed_by_name = str(
+ payload.get("changedByName") or payload.get("changed_by_name") or ""
+ ).strip()[:200]
+ closer_email = changed_by if "@" in changed_by else ""
old_status = old
if new_status == old_status:
@@ -251,12 +291,54 @@ def api_patch(bug_id: str):
to_status=new_status,
from_status=old_status,
changed_by=changed_by,
+ changed_by_name=changed_by_name,
note=note,
))
+ notified = None
+ if will_notify:
+ notified = _notify(bug, new_status, note, closer_email, changed_by, changed_by_name)
full = contract.with_kind(bug.to_full())
full["audit"] = [a.to_dict() for a in store.list_audit(bug_id)]
+ if notified is not None:
+ full["notified"] = notified
return jsonify(full)
+ def _notify(bug, new_status, note, closer_email, changed_by, changed_by_name) -> dict:
+ """Email the reporter after the change is safely written. Never raises
+ and never undoes the change; the outcome is its own audit row."""
+ to = bug.actor_email
+ who = person_name(bug.actor_name, to) or "the reporter"
+ error = ""
+ if notifier is None:
+ error = "email is not set up on this server"
+ elif not to:
+ error = "this report has no address to email"
+ else:
+ try:
+ notifier(Notice(
+ to_email=to, to_name=person_name(bug.actor_name, to),
+ title=bug.title, note=note.strip(), status=new_status,
+ bug_id=bug.id, filed_at=bug.added_at, page_url=bug.meta_url,
+ app_url=app_url, closer_email=closer_email,
+ closer_name=person_name(changed_by_name, closer_email),
+ ))
+ except Exception as e:
+ log.warning("bug notify: %s: %s", bug.id, e)
+ error = (str(e) or type(e).__name__)[:200]
+ label = f"{who} <{to}>" if to else who
+ store.append_audit(bug.id, AuditEntry(
+ changed_at=_now_iso(),
+ to_status=new_status,
+ from_status=new_status,
+ changed_by=changed_by,
+ changed_by_name=changed_by_name,
+ note=(f"email to {label} failed: {error}" if error else f"emailed {label}")[:500],
+ ))
+ out = {"ok": not error, "to": to}
+ if error:
+ out["error"] = error
+ return out
+
# ----- GET /bugs//screenshot -----------------------------------
@bp.route(f"{url_prefix}//screenshot", methods=["GET"])
diff --git a/packages/backend-python/bug_report/email.py b/packages/backend-python/bug_report/email.py
new file mode 100644
index 0000000..10bf314
--- /dev/null
+++ b/packages/backend-python/bug_report/email.py
@@ -0,0 +1,230 @@
+"""Telling the reporter their report was closed, by email.
+
+``create_blueprint(notifier=...)`` takes any ``notifier(notice) -> str`` that
+returns a message id and raises on failure. This module ships the pieces a
+Leap app needs: :class:`Notice` (what the blueprint hands over), :func:`render`
+(subject + HTML, pure), and :class:`AcsNotifier` (Azure Communication Services
+Email, behind the ``[email]`` extra, modelled on leap-daily-report's
+``report_email.py``).
+
+Nothing here imports Azure at import time, so ``import bug_report`` works
+without the extra; an app that passes no notifier never emails.
+
+Environment read by :meth:`AcsNotifier.from_env`:
+
+``ACS_ENDPOINT`` managed identity (``DefaultAzureCredential``)
+``BUG_NOTIFY_CLIENT_ID`` the user-assigned identity to send as; its own name,
+ not ``AZURE_CLIENT_ID``, so it cannot change which
+ identity the rest of the app signs in as
+``ACS_CONNECTION_STRING`` fallback when there is no endpoint
+``BUG_NOTIFY_SENDER`` the From address, e.g. ``bugs@helloleap.ai``
+``BUG_NOTIFY_DOMAINS`` comma list of domains it may write to; an address
+ outside it is refused (fail closed)
+"""
+
+from __future__ import annotations
+
+import html as _html
+import logging
+import os
+import re
+from dataclasses import dataclass
+from datetime import date
+
+from .models import first_name, person_name
+
+log = logging.getLogger(__name__)
+
+FROM_NAME = "Leap bug reports"
+SEND_TIMEOUT = 30 # seconds the poller may be waited on: bounded, and short enough for a click in the Bugs panel
+
+
+@dataclass
+class Notice:
+ """One closed report, as the blueprint hands it to a notifier."""
+ to_email: str
+ to_name: str
+ title: str
+ note: str
+ status: str # "resolved" | "declined"
+ bug_id: str
+ filed_at: str = "" # ISO timestamp
+ page_url: str = "" # the report's metaUrl
+ app_url: str = ""
+ closer_email: str = ""
+ closer_name: str = ""
+
+
+# ---------------------------------------------------------------------------
+# Rendering (pure)
+# ---------------------------------------------------------------------------
+
+_URL_RE = re.compile(r"https?://[^\s<>\"']+")
+_TRAILING = ".,;:!?)]}"
+
+
+def _one_line(s: str) -> str:
+ return " ".join((s or "").split())
+
+
+def _subject(n: Notice) -> str:
+ title = _one_line(n.title)
+ if n.status == "resolved":
+ return f"Fixed: {title}"
+ if n.status == "declined":
+ return f"Your bug report: {title} — not taken forward"
+ raise ValueError(f"no email for status {n.status!r}")
+
+
+def _note_html(note: str) -> str:
+ """Escape the note, make http(s) URLs links, keep its line breaks."""
+ out = []
+ pos = 0
+ for m in _URL_RE.finditer(note):
+ url = m.group(0)
+ tail = ""
+ while url and url[-1] in _TRAILING:
+ tail = url[-1] + tail
+ url = url[:-1]
+ out.append(_html.escape(note[pos:m.start()]))
+ if url:
+ u = _html.escape(url, quote=True)
+ out.append(f'{u}')
+ out.append(_html.escape(tail))
+ pos = m.end()
+ out.append(_html.escape(note[pos:]))
+ return "".join(out).replace("\r\n", "\n").replace("\n", "
\n")
+
+
+def _pretty_date(iso: str) -> str:
+ try:
+ d = date.fromisoformat((iso or "")[:10])
+ except ValueError:
+ return ""
+ return f"{d.day} {d:%B} {d.year}"
+
+
+def render(notice: Notice) -> tuple[str, str]:
+ """``(subject, html)`` for a closed report. Everything from the report is
+ HTML-escaped; only http(s) URLs become links."""
+ subject = _subject(notice)
+ hi = first_name(notice.to_name, notice.to_email)
+ closer = person_name(notice.closer_name, notice.closer_email)
+ when = _pretty_date(notice.filed_at)
+ link = next((u for u in (notice.page_url, notice.app_url)
+ if (u or "").startswith(("http://", "https://"))), "")
+
+ parts = [f"Hi {_html.escape(hi)},
" if hi else "Hello,
"]
+ parts.append(f"{_note_html(notice.note.strip())}
")
+ parts.append(f"— {_html.escape(closer or FROM_NAME)}
")
+
+ said = "You reported this"
+ if when:
+ said += f" on {when}"
+ if link:
+ u = _html.escape(link, quote=True)
+ said += f' from {u}'
+ parts.append(f'{said}.
'
+ f"Report {_html.escape(notice.bug_id)}
")
+ body = "\n".join(parts)
+ return subject, f'\n{body}\n
'
+
+
+# ---------------------------------------------------------------------------
+# Sending (Azure Communication Services Email)
+# ---------------------------------------------------------------------------
+
+def _domain(address: str) -> str:
+ return address.rsplit("@", 1)[-1].strip().lower() if "@" in address else ""
+
+
+class AcsNotifier:
+ """``notifier(notice) -> message id`` over ACS Email.
+
+ Fails closed: no sender, or an address outside ``domains``, raises before
+ anything is sent. ``retry_total=0`` because the SDK's own retry re-sends a
+ throttled request immediately, and each attempt counts against the quota
+ that refused it (the daily report's lesson, 2026-09-15). The wait on the
+ poller is bounded by ``timeout``.
+ """
+
+ def __init__(self, *, sender: str, domains, endpoint: str = "",
+ connection_string: str = "", client_id: str = "",
+ client=None, timeout: float = SEND_TIMEOUT) -> None:
+ self.sender = (sender or "").strip()
+ if isinstance(domains, str):
+ domains = domains.split(",")
+ self.domains = tuple(d.strip().lstrip("@").lower() for d in (domains or ()) if d.strip())
+ self.endpoint = (endpoint or "").strip()
+ self.connection_string = (connection_string or "").strip()
+ self.client_id = (client_id or "").strip()
+ self.timeout = timeout
+ self._client = client
+
+ @classmethod
+ def from_env(cls, env=None):
+ """The notifier the environment describes, or ``None`` when it does not
+ (no credential, no sender, or no allowed domains), so an app can write
+ ``notifier=AcsNotifier.from_env()`` and simply not email when unset."""
+ env = os.environ if env is None else env
+ endpoint = env.get("ACS_ENDPOINT", "").strip()
+ conn = env.get("ACS_CONNECTION_STRING", "").strip()
+ sender = env.get("BUG_NOTIFY_SENDER", "").strip()
+ domains = env.get("BUG_NOTIFY_DOMAINS", "").strip()
+ if not (endpoint or conn) or not sender:
+ return None
+ if not domains:
+ log.warning("bug notify: BUG_NOTIFY_DOMAINS not set; emailing reporters is off (fail closed)")
+ return None
+ return cls(sender=sender, domains=domains, endpoint=endpoint,
+ connection_string=conn, client_id=env.get("BUG_NOTIFY_CLIENT_ID", ""))
+
+ def _get_client(self):
+ if self._client is None:
+ from azure.communication.email import EmailClient # lazy: the [email] extra
+ if self.endpoint:
+ from azure.identity import DefaultAzureCredential
+ kw = {"managed_identity_client_id": self.client_id} if self.client_id else {}
+ self._client = EmailClient(self.endpoint, DefaultAzureCredential(**kw), retry_total=0)
+ elif self.connection_string:
+ self._client = EmailClient.from_connection_string(self.connection_string, retry_total=0)
+ else:
+ raise RuntimeError("neither ACS_ENDPOINT nor ACS_CONNECTION_STRING set (fail closed)")
+ return self._client
+
+ def __call__(self, notice: Notice) -> str:
+ if not self.sender:
+ raise RuntimeError("BUG_NOTIFY_SENDER not set (fail closed)")
+ to = (notice.to_email or "").strip()
+ if not to:
+ raise RuntimeError("no address to send to")
+ if not self.domains:
+ raise RuntimeError("BUG_NOTIFY_DOMAINS not set (fail closed)")
+ if _domain(to) not in self.domains:
+ raise RuntimeError(f"{_domain(to) or to} is not an allowed domain; not sent")
+ subject, body = render(notice)
+ recipient = {"address": to}
+ if notice.to_name:
+ recipient["displayName"] = notice.to_name
+ message = {
+ "senderAddress": self.sender,
+ "content": {"subject": subject, "html": body},
+ "recipients": {"to": [recipient]},
+ }
+ if notice.closer_email:
+ reply = {"address": notice.closer_email}
+ name = person_name(notice.closer_name, notice.closer_email)
+ if name:
+ reply["displayName"] = name
+ message["replyTo"] = [reply]
+ poller = self._get_client().begin_send(message)
+ result = poller.result(timeout=self.timeout)
+ # A wait that runs out returns whatever the poller last saw (None, or
+ # a "Running" status), not an error: never audit that as "emailed".
+ if not poller.done():
+ raise RuntimeError(f"ACS had not confirmed the send after {self.timeout:g} s; it may still arrive")
+ get = result.get if isinstance(result, dict) else (lambda k, d=None: getattr(result, k, d))
+ status = getattr(get("status"), "value", get("status"))
+ if status is not None and str(status).lower() != "succeeded":
+ raise RuntimeError(f"ACS reported {status}")
+ return str(get("id") or "")
diff --git a/packages/backend-python/bug_report/models.py b/packages/backend-python/bug_report/models.py
index d21373a..ad7d594 100644
--- a/packages/backend-python/bug_report/models.py
+++ b/packages/backend-python/bug_report/models.py
@@ -53,3 +53,21 @@ def new_bug_id() -> str:
def valid_bug_id(bug_id: str) -> bool:
return bool(_BUG_ID_RE.match(bug_id or ""))
+
+
+def person_name(name: str | None, email: str | None) -> str:
+ """The display name of a person: the stored ``name``, else one derived from
+ the address's local part (``chris.hamblin@x`` -> ``Chris Hamblin``, ``ken@x``
+ -> ``Ken``), else "". The same rule the UI uses; the two must agree."""
+ name = (name or "").strip()
+ if name:
+ return name
+ local = (email or "").strip().split("@", 1)[0]
+ parts = [p for p in re.split(r"[._-]+", local) if p]
+ return " ".join(p[:1].upper() + p[1:] for p in parts)
+
+
+def first_name(name: str | None, email: str | None = "") -> str:
+ """First word of :func:`person_name`."""
+ full = person_name(name, email)
+ return full.split(None, 1)[0] if full else ""
diff --git a/packages/backend-python/bug_report/store.py b/packages/backend-python/bug_report/store.py
index ba6cb4e..038166a 100644
--- a/packages/backend-python/bug_report/store.py
+++ b/packages/backend-python/bug_report/store.py
@@ -55,6 +55,9 @@ class BugRecord:
meta_build_sha: str = ""
screenshot: bool = False
transcript: list[dict] | None = None
+ # Display name of whoever filed it ("" when unknown). Added in 2.2.0; a
+ # record on disk from before has no such key and loads with the default.
+ actor_name: str = ""
def to_summary(self) -> dict:
return {
@@ -64,6 +67,7 @@ def to_summary(self) -> dict:
"status": self.status,
"addedBy": self.added_by,
"actorEmail": self.actor_email,
+ "actorName": self.actor_name,
"addedAt": self.added_at,
"screenshot": bool(self.screenshot),
}
@@ -87,11 +91,13 @@ class AuditEntry:
from_status: str | None = None
changed_by: str = ""
note: str = ""
+ changed_by_name: str = "" # display name of changed_by; added in 2.2.0
def to_dict(self) -> dict:
return {
"changedAt": self.changed_at,
"changedBy": self.changed_by,
+ "changedByName": self.changed_by_name,
"fromStatus": self.from_status,
"toStatus": self.to_status,
"note": self.note,
@@ -332,6 +338,7 @@ def list_audit(self, bug_id):
from_status=d.get("fromStatus") if "fromStatus" in d else d.get("from_status"),
changed_by=d.get("changedBy") or d.get("changed_by", ""),
note=d.get("note", ""),
+ changed_by_name=d.get("changedByName") or d.get("changed_by_name", ""),
))
return out
diff --git a/packages/backend-python/pyproject.toml b/packages/backend-python/pyproject.toml
index 97d8f47..daf7bb2 100644
--- a/packages/backend-python/pyproject.toml
+++ b/packages/backend-python/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "bug-report-py"
-version = "2.1.1"
+version = "2.2.0"
description = "Flask blueprint + storage interface implementing the bug-report-widget API spec."
readme = "README.md"
license = { text = "MIT" }
@@ -11,6 +11,7 @@ dependencies = [
]
[project.optional-dependencies]
+email = ["azure-communication-email>=1.0", "azure-identity>=1.15"]
test = [
"pytest>=7.0",
]
diff --git a/packages/backend-python/tests/test_email.py b/packages/backend-python/tests/test_email.py
new file mode 100644
index 0000000..398364b
--- /dev/null
+++ b/packages/backend-python/tests/test_email.py
@@ -0,0 +1,281 @@
+"""bug_report.email: render() and AcsNotifier, with the Azure SDK stubbed. No network."""
+
+from __future__ import annotations
+
+import sys
+import types
+
+import pytest
+
+from bug_report.email import AcsNotifier, Notice, render
+from bug_report.models import first_name, person_name
+
+
+def notice(**kw):
+ base = dict(to_email="ana.reporter@example.com", to_name="Ana Reporter", title="Jam light stays on",
+ note="Fixed in build 41.", status="resolved", bug_id="bug-20261112-124952-abcdef",
+ filed_at="2026-11-12T12:49:52.000000Z", page_url="https://sv.example/day?x=1&y=2",
+ app_url="https://app.example/", closer_email="sam.closer@example.com",
+ closer_name="Sam Closer")
+ base.update(kw)
+ return Notice(**base)
+
+
+# ----- names -----------------------------------------------------------------
+
+@pytest.mark.parametrize("name,email,full,first", [
+ ("Ana Reporter", "x@y", "Ana Reporter", "Ana"),
+ ("", "ana.reporter@x.com", "Ana Reporter", "Ana"),
+ ("", "sam@x.com", "Sam", "Sam"),
+ (None, "a_b-c.d@x.com", "A B C D", "A"),
+ ("", "", "", ""),
+])
+def test_name_fallback_rule(name, email, full, first):
+ assert person_name(name, email) == full
+ assert first_name(name, email) == first
+
+
+# ----- render ----------------------------------------------------------------
+
+def test_subject_per_status():
+ assert render(notice())[0] == "Fixed: Jam light stays on"
+ assert render(notice(status="declined"))[0] == \
+ "Your bug report: Jam light stays on — not taken forward"
+
+
+def test_other_statuses_have_no_email():
+ with pytest.raises(ValueError):
+ render(notice(status="triaged"))
+
+
+def test_body_has_first_name_note_signature_date_link_and_id():
+ _, html = render(notice())
+ assert "Hi Ana," in html
+ assert "Fixed in build 41." in html
+ assert "— Sam Closer" in html
+ assert "12 November 2026" in html
+ assert 'href="https://sv.example/day?x=1&y=2"' in html # the page they filed from
+ assert "bug-20261112-124952-abcdef" in html
+
+
+def test_link_falls_back_to_the_app_when_there_is_no_page_url():
+ _, html = render(notice(page_url=""))
+ assert 'href="https://app.example/"' in html
+
+
+def test_no_link_when_neither_is_http():
+ _, html = render(notice(page_url="javascript:alert(1)", app_url=""))
+ assert "href" not in html and "javascript" not in html
+
+
+def test_everything_from_the_report_is_escaped():
+ evil = ""
+ sub, html = render(notice(to_name=evil + " Q", title=evil, note=evil, closer_name=evil,
+ bug_id=evil, page_url='https://x/">
'))
+ assert "