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
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,16 @@

All notable changes to this monorepo.

## backends v3.3.0 - 2026-11-15 (`bug-report-py` 3.3.0)

A UI can show the vote button's state. Additive; the report contract gains one field.

- **`myVote`** (true/false) on every list summary and on the detail: whether the caller has voted, as the vote routes see the caller (`actor_identity`, else the request's `actorEmail`). A caller with no identity gets false.
- **Votes answer with the caller's state.** `POST /bugs/{id}/vote` by someone who already voted is a 200 with `{voted: true, votes: <count>}` and the count unchanged; `DELETE` answers `{voted: false, votes: <count>}` whether or not there was a vote. `voted` is read from the store after the change.
- **`Store.voted_among(bug_ids, voter) -> set[str]`** on `InMemoryStore`, `FilesystemStore` and `PostgresStore`. The Postgres list stays at a fixed number of queries however long it is (a test counts them).
- **`canTriage`** (true/false): the app's own `is_admin` answer for the caller, a top-level field of the `GET /bugs` body and on the detail. Since 3.2.0 a non-admin's list is a 200, so "the list worked" no longer means "admin"; apps use this instead. False with no identity (as the app's `is_admin` decides). The proxy passes it through unchanged (tested).
- `report-contract.json` (a `callerFields` entry, not `summaryFields`/`detailFields`: they describe the caller, like `canNotify`; and the example), `types.py`, `types.ts` and `openapi.yaml` carry `myVote`. The Node backend does not send it: its list is admin-only, so it is documented as not ported, as 3.2.0 did for visibility. `report-contract.json` is mirrored byte-identically elsewhere, so its copies need re-mirroring.

## backends v3.2.0 - 2026-11-15 (`bug-report-py` 3.2.0)

What LeapHQ's move needs from the library (Ken's decisions 1 and 3). The report contract is unchanged.
Expand Down
2 changes: 1 addition & 1 deletion packages/backend-node/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,4 +113,4 @@ The router stores and echoes the v3 fields (`kind`, `app`, `product`, `area`, `p
`duplicate of <id>`), filters the list by `app`, `kind`, `area` and `priority`, and serves `POST`/`DELETE /:id/vote`.
Options: `appStamp(req)` (the app a report is filed under; the body's `app` is never read) and `actorIdentity(req)`
(the signed-in email, who votes). `FilesystemStore` and `InMemoryStore` keep them; the Azure Tables store does not yet
and the router answers 501 for triage fields and votes on it. The Python library is the reference for the central store.
and the router answers 501 for triage fields and votes on it. The Python library is the reference for the central store. `myVote` and `canTriage` (3.3.0) are Python only, not ported.
10 changes: 9 additions & 1 deletion packages/backend-python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,15 @@ what changed (`area: none -> Cutter; priority: none -> now`); a value equal to t
`POST /bugs/{id}/vote` and `DELETE /bugs/{id}/vote` need only a signed-in caller (the `actor_identity` email; without
that hook, the body's `actorEmail`), one vote per person, case-insensitively. `GET /bugs` filters by `app`, `kind`,
`area` and `priority` as well as `status` and `days`. Every summary carries `kind`, `app`, `product`, `area`,
`priority`, `owner`, `parentId`, `duplicateOf` and `votes`; a record written before v3 has them null and `votes` 0.
`priority`, `owner`, `parentId`, `duplicateOf` and `votes`, and (3.3.0) `myVote`, whether the caller has voted (false with no
identity; a store with `voted_among` is asked once per list). A repeat POST is a 200 with `voted: true`; DELETE with nothing to take
back answers `voted: false`; both carry the current `votes`. `GET /bugs` also carries a top-level `canTriage` and the detail carries one: the `is_admin` answer for the caller (3.3.0), the signal for showing triage controls. The Node backend sends neither `myVote` nor `canTriage`.

**Claims mode and `canTriage`.** `myVote` is asked for the same person `_caller_email` gives (the checked identity, or without
`actor_identity` the request's own `actorEmail`), never `default_actor_email`: an anonymous caller reads `false` even after the
default actor has voted, and a caller who claims that address reads `true` (claims are unchecked in that mode, as for filing).
`canTriage` is only as good as the `is_admin` you pass: the default is `lambda req: True`, so an app that does not pass `is_admin`
tells everyone `canTriage: true`. A store with `add_vote` but no `voted_among` still votes; `voted` then reports what was asked. A record written before v3 has them null and `votes` 0.
`create_blueprint(app_stamp=lambda req: "placements")` stamps the app a report is filed under (the body's `app` is
never read); `guard=` refuses a request before any route runs.

Expand Down
26 changes: 22 additions & 4 deletions packages/backend-python/bug_report/blueprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,10 +277,13 @@ def api_list():
if not admin:
me = _caller_email(request)
bugs = [b for b in bugs if _visible(b, me)]
counts = _vote_counts([b.id for b in bugs])
rows = [contract.with_kind({**b.to_summary(), "votes": counts.get(b.id, 0)}) for b in bugs]
ids = [b.id for b in bugs]
counts = _vote_counts(ids)
mine = _my_votes(ids)
rows = [contract.with_kind({**b.to_summary(), "votes": counts.get(b.id, 0), "myVote": b.id in mine})
for b in bugs]
rows.sort(key=lambda r: r["addedAt"], reverse=True)
return jsonify({"bugs": rows})
return jsonify({"bugs": rows, "canTriage": bool(admin)})

def _caller_email(req) -> str:
"""The caller's address, for what a non-admin may see: the checked identity when the app
Expand Down Expand Up @@ -310,9 +313,20 @@ def _vote_counts(ids):
counter = getattr(store, "vote_counts", None)
return counter(ids) if counter and ids else {}

def _my_votes(ids, who=None) -> set:
"""Which of ``ids`` the caller has voted on. A READ asks as ``_caller_email`` does, never as
the app's default actor; the vote routes pass the voter they used. Nobody signed in, or a
store that predates votes, means none. One store call per list."""
finder = getattr(store, "voted_among", None)
if who is None:
who = _caller_email(request)
return set(finder(ids, who)) if finder and ids and who else set()

def _detail(bug) -> dict:
full = contract.with_kind(bug.to_full())
full["votes"] = _vote_counts([bug.id]).get(bug.id, 0)
full["myVote"] = bug.id in _my_votes([bug.id])
full["canTriage"] = bool(is_admin(request))
full["audit"] = [a.to_dict() for a in store.list_audit(bug.id)]
return full

Expand Down Expand Up @@ -537,7 +551,11 @@ def _vote(bug_id: str, adding: bool):
(store.add_vote if adding else store.remove_vote)(bug_id, voter)
except NotFound:
return jsonify({"error": "not found"}), 404
return jsonify({"votes": store.vote_counts([bug_id]).get(bug_id, 0), "voted": adding})
# `voted` is whether the caller's vote stands now: a repeat POST is a 200 that says true,
# a DELETE with nothing to take back says false.
# (a store without `voted_among` cannot say, so `adding` stands)
voted = bug_id in _my_votes([bug_id], voter) if hasattr(store, "voted_among") else adding
return jsonify({"votes": store.vote_counts([bug_id]).get(bug_id, 0), "voted": voted})

@bp.route(f"{url_prefix}/<bug_id>/vote", methods=["POST"])
def api_vote(bug_id: str):
Expand Down
10 changes: 10 additions & 0 deletions packages/backend-python/bug_report/pg.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,16 @@ def go(cur):
got = self._run(go)
return {i: int(got.get(i, 0)) for i in bug_ids}

def voted_among(self, bug_ids: list[str], voter: str) -> set[str]:
v = normal_voter(voter)
if not bug_ids or not v:
return set()

def go(cur):
cur.execute("SELECT id FROM report_votes WHERE voter=%s AND id = ANY(%s)", (v, list(bug_ids)))
return {r[0] for r in cur.fetchall()}
return self._run(go)

def list_votes(self, bug_id: str) -> list[dict]:
def go(cur):
cur.execute("SELECT voter, at FROM report_votes WHERE id=%s ORDER BY at, voter", (bug_id,))
Expand Down
11 changes: 11 additions & 0 deletions packages/backend-python/bug_report/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,9 @@ def add_vote(self, bug_id: str, voter: str, at: str | None = None) -> bool:
...
def remove_vote(self, bug_id: str, voter: str) -> bool: ...
def vote_counts(self, bug_ids: list[str]) -> dict[str, int]: ...
def voted_among(self, bug_ids: list[str], voter: str) -> set[str]:
"""The ids in ``bug_ids`` that ``voter`` has voted on (one lookup for the whole list)."""
...
def list_votes(self, bug_id: str) -> list[dict]:
"""``[{"voter", "at"}]``, oldest first."""
...
Expand Down Expand Up @@ -275,6 +278,10 @@ def remove_vote(self, bug_id, voter):
def vote_counts(self, bug_ids):
return {i: len(self._votes.get(i, {})) for i in bug_ids}

def voted_among(self, bug_ids, voter):
v = normal_voter(voter)
return {i for i in bug_ids if v and v in self._votes.get(i, {})}

def list_votes(self, bug_id):
return [{"voter": v, "at": at} for v, at in self._votes.get(bug_id, {}).items()]

Expand Down Expand Up @@ -488,6 +495,10 @@ def remove_vote(self, bug_id, voter):
def vote_counts(self, bug_ids):
return {i: len(self._read_votes(i)) for i in bug_ids}

def voted_among(self, bug_ids, voter):
v = normal_voter(voter)
return {i for i in bug_ids if v and v in self._read_votes(i)}

def list_votes(self, bug_id):
return [{"voter": v, "at": at} for v, at in self._read_votes(bug_id).items()]

Expand Down
2 changes: 1 addition & 1 deletion packages/backend-python/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "bug-report-py"
version = "3.2.0"
version = "3.3.0"
description = "Flask blueprint + storage interface implementing the bug-report-widget API spec."
readme = "README.md"
license = { text = "MIT" }
Expand Down
4 changes: 2 additions & 2 deletions packages/backend-python/tests/test_blueprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ def test_screenshot_type_is_sniffed_not_taken_from_the_data_url(client):
# ---------------------------------------------------------------------------

def test_list_empty(client):
assert client.get("/bugs").get_json() == {"bugs": []}
assert client.get("/bugs").get_json()["bugs"] == []


def test_list_sorted_newest_first(client):
Expand Down Expand Up @@ -245,7 +245,7 @@ def test_admin_gate_blocks_patch_and_filters_list(store, admin_deny):
app.register_blueprint(create_blueprint(store=store, is_admin=admin_deny))
c = app.test_client()
bid = c.post("/bugs", json={"details": "anyone can file"}).get_json()["id"]
assert c.get("/bugs").get_json() == {"bugs": []} # a bug filed by nobody is no one's to see
assert c.get("/bugs").get_json()["bugs"] == [] # a bug filed by nobody is no one's to see
assert c.get(f"/bugs/{bid}").status_code == 404
assert c.patch(f"/bugs/{bid}", json={"status": "triaged"}).status_code == 403

Expand Down
5 changes: 5 additions & 0 deletions packages/backend-python/tests/test_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,8 @@ def test_a_stored_kind_beats_the_tags_and_an_undeclared_kind_does_not():
assert contract.effective_kind("capability", ["feature"]) == "feature" # not a kind: fall back to the tags
assert contract.effective_kind(None, []) == "bug"
assert contract.with_kind({"kind": "feature", "tags": ["bug"]})["kind"] == "feature"


def test_caller_fields_describe_the_caller_and_are_in_neither_field_list():
assert SPEC["callerFields"] == ["myVote", "canTriage"]
assert not set(SPEC["callerFields"]) & (set(SPEC["summaryFields"]) | set(SPEC["detailFields"]))
25 changes: 25 additions & 0 deletions packages/backend-python/tests/test_pg_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,3 +141,28 @@ def test_a_database_that_is_down_is_a_store_error_not_a_driver_exception(pg_dsn)
st = PostgresStore(lambda: psycopg.connect("postgresql://postgres@127.0.0.1:1/x", connect_timeout=1))
with pytest.raises(StoreError):
st.get_bug("bug-20200101-000000-aaaaaa")


def test_the_list_costs_a_bounded_number_of_queries_however_many_reports(pg_store):
"""myVote is one `voted_among` query for the whole list, not one per report."""
from flask import Flask
from bug_report import create_blueprint
app = Flask(__name__)
app.register_blueprint(create_blueprint(
store=pg_store, is_admin=lambda r: True, actor_identity=lambda r: {"email": "me@example.com", "name": ""}))
c = app.test_client()
runs = []
real = pg_store._run
pg_store._run = lambda fn: (runs.append(fn), real(fn))[1]

def list_cost():
runs.clear()
assert c.get("/bugs?days=365").status_code == 200
return len(runs)

ids = [c.post("/bugs", json={"details": f"d{i}"}).get_json()["id"] for i in range(3)]
small = list_cost()
ids += [c.post("/bugs", json={"details": f"d{i}"}).get_json()["id"] for i in range(3, 15)]
for i in ids:
c.post(f"/bugs/{i}/vote")
assert list_cost() == small <= 3
20 changes: 20 additions & 0 deletions packages/backend-python/tests/test_proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,3 +328,23 @@ def serve_short():
t.join(3)
lsock.close()
assert r.status_code == 502 and "incomplete" in r.get_json()["error"]


def test_can_triage_and_my_vote_pass_through_the_proxy_unchanged(front):
feat = file(front, tags=["feature"])
front.c.post(f"/api/bugs/{feat}/vote")
listed = front.c.get("/api/bugs?days=1").get_json()
assert listed["canTriage"] is True and listed["bugs"][0]["myVote"] is True
front.person[0] = {"email": "someone@example.com", "name": ""}
listed = front.c.get("/api/bugs?days=1").get_json()
assert listed["canTriage"] is False and listed["bugs"][0]["myVote"] is False
assert front.c.get(f"/api/bugs/{feat}").get_json()["canTriage"] is False


def test_no_identity_through_the_proxy_is_not_triage_and_not_a_vote(front):
feat = file(front, tags=["feature"])
front.c.post(f"/api/bugs/{feat}/vote")
front.person[0] = {"email": "", "name": ""}
listed = front.c.get("/api/bugs?days=1").get_json()
assert listed["canTriage"] is False
assert all(b["myVote"] is False for b in listed["bugs"])
23 changes: 23 additions & 0 deletions packages/backend-python/tests/test_spec_drift.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,29 @@ def test_every_field_the_server_sends_is_in_the_spec(tmp_path):
assert set(created) <= _schema_properties_of_created()


def _list_body_properties() -> set[str]:
"""The listBugs 200 body's top-level properties, from the inline schema."""
text = SPEC.read_text()
block = text[text.index("operationId: listBugs"):text.index(" /bugs/{id}:")]
after = block[block.index("properties:", block.index('"200":')):]
return set(re.findall(r"^ {18}(\w+):\s*$", after, re.M))


def test_the_list_body_is_the_same_in_the_server_the_spec_and_both_types(tmp_path):
body = _client(tmp_path).get("/api/bugs?days=1").get_json()
spec_keys = _list_body_properties()
assert spec_keys == {"bugs", "canTriage"}
assert set(body) == spec_keys
from importlib import util
py = pathlib.Path(__file__).resolve().parents[2] / "spec"
mod = util.spec_from_file_location("spec_types", py / "types.py")
m = util.module_from_spec(mod); mod.loader.exec_module(m)
assert set(m.BugList.__annotations__) == spec_keys
ts = (py / "types.ts").read_text()
block = ts[ts.index("export interface BugList"):]
assert set(re.findall(r"^ (\w+)\??:", block[:block.index("}")], re.M)) == spec_keys


def _schema_properties_of_created() -> set[str]:
"""The 201 body's properties, read from the createBug response (an inline schema)."""
text = SPEC.read_text()
Expand Down
Loading
Loading