From da59c2ce54d281c8c544417701a4d7e245903b6b Mon Sep 17 00:00:00 2001 From: kmoy007 Date: Sun, 15 Nov 2026 10:46:38 -0800 Subject: [PATCH 1/2] Votes: myVote and canTriage on list and detail, idempotent vote answers, Store.voted_among (bug-report-py 3.3.0) Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 10 +++ packages/backend-node/README.md | 2 +- packages/backend-python/README.md | 4 +- .../backend-python/bug_report/blueprint.py | 22 +++++- packages/backend-python/bug_report/pg.py | 10 +++ packages/backend-python/bug_report/store.py | 11 +++ packages/backend-python/pyproject.toml | 2 +- .../backend-python/tests/test_blueprint.py | 4 +- .../backend-python/tests/test_pg_store.py | 25 ++++++ packages/backend-python/tests/test_proxy.py | 11 +++ .../backend-python/tests/test_v3_triage.py | 79 +++++++++++++++++++ .../backend-python/tests/test_visibility.py | 2 +- packages/spec/openapi.yaml | 11 ++- packages/spec/report-contract.json | 12 ++- packages/spec/types.py | 7 ++ packages/spec/types.ts | 10 +++ 16 files changed, 208 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 82ca369..52c5956 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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: }` and the count unchanged; `DELETE` answers `{voted: false, votes: }` 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` (`summaryFields`, 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. diff --git a/packages/backend-node/README.md b/packages/backend-node/README.md index 75d5cc6..20be81b 100644 --- a/packages/backend-node/README.md +++ b/packages/backend-node/README.md @@ -113,4 +113,4 @@ The router stores and echoes the v3 fields (`kind`, `app`, `product`, `area`, `p `duplicate of `), 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. diff --git a/packages/backend-python/README.md b/packages/backend-python/README.md index 4c24f3b..96b5fed 100644 --- a/packages/backend-python/README.md +++ b/packages/backend-python/README.md @@ -58,7 +58,9 @@ 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`. 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. diff --git a/packages/backend-python/bug_report/blueprint.py b/packages/backend-python/bug_report/blueprint.py index 0bec388..9807508 100644 --- a/packages/backend-python/bug_report/blueprint.py +++ b/packages/backend-python/bug_report/blueprint.py @@ -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 @@ -310,9 +313,18 @@ def _vote_counts(ids): counter = getattr(store, "vote_counts", None) return counter(ids) if counter and ids else {} + def _my_votes(ids) -> set: + """Which of ``ids`` the caller (the same person the vote routes use) has voted on; + nobody signed in, or a store that predates votes, means none. One store call per list.""" + finder = getattr(store, "voted_among", None) + who = _voter(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 @@ -537,7 +549,9 @@ 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. + return jsonify({"votes": store.vote_counts([bug_id]).get(bug_id, 0), "voted": bug_id in _my_votes([bug_id])}) @bp.route(f"{url_prefix}//vote", methods=["POST"]) def api_vote(bug_id: str): diff --git a/packages/backend-python/bug_report/pg.py b/packages/backend-python/bug_report/pg.py index 87464a6..c2ddc41 100644 --- a/packages/backend-python/bug_report/pg.py +++ b/packages/backend-python/bug_report/pg.py @@ -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,)) diff --git a/packages/backend-python/bug_report/store.py b/packages/backend-python/bug_report/store.py index aff0e50..0138be0 100644 --- a/packages/backend-python/bug_report/store.py +++ b/packages/backend-python/bug_report/store.py @@ -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.""" ... @@ -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()] @@ -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()] diff --git a/packages/backend-python/pyproject.toml b/packages/backend-python/pyproject.toml index 9c432d6..ab1d2c2 100644 --- a/packages/backend-python/pyproject.toml +++ b/packages/backend-python/pyproject.toml @@ -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" } diff --git a/packages/backend-python/tests/test_blueprint.py b/packages/backend-python/tests/test_blueprint.py index c0fd2b2..545b879 100644 --- a/packages/backend-python/tests/test_blueprint.py +++ b/packages/backend-python/tests/test_blueprint.py @@ -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): @@ -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 diff --git a/packages/backend-python/tests/test_pg_store.py b/packages/backend-python/tests/test_pg_store.py index 5a77120..87cd404 100644 --- a/packages/backend-python/tests/test_pg_store.py +++ b/packages/backend-python/tests/test_pg_store.py @@ -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 diff --git a/packages/backend-python/tests/test_proxy.py b/packages/backend-python/tests/test_proxy.py index c366845..bf82e52 100644 --- a/packages/backend-python/tests/test_proxy.py +++ b/packages/backend-python/tests/test_proxy.py @@ -328,3 +328,14 @@ 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 diff --git a/packages/backend-python/tests/test_v3_triage.py b/packages/backend-python/tests/test_v3_triage.py index 43f2ad5..99c16fe 100644 --- a/packages/backend-python/tests/test_v3_triage.py +++ b/packages/backend-python/tests/test_v3_triage.py @@ -303,3 +303,82 @@ def test_the_store_protocol_takes_exactly_the_contracts_filters(): for cls in (InMemoryStore, FilesystemStore): params = set(inspect.signature(cls.list_bugs).parameters) - {"self", "status", "since_iso"} assert params == want, cls + + +# ---- myVote (3.3.0) -------------------------------------------------------- + +def _my_vote(c, bid): + detail = c.get(f"/api/bugs/{bid}").get_json()["myVote"] + listed = next(b for b in c.get("/api/bugs?days=1").get_json()["bugs"] if b["id"] == bid)["myVote"] + assert detail == listed + return detail + + +def test_my_vote_follows_voting_and_unvoting(client): + bid = file_bug(client) + assert _my_vote(client, bid) is False + client.post(f"/api/bugs/{bid}/vote") + assert _my_vote(client, bid) is True + client.delete(f"/api/bugs/{bid}/vote") + assert _my_vote(client, bid) is False + + +def test_my_vote_is_the_callers_own_and_case_insensitive(client): + bid = file_bug(client) + other = file_bug(client) + client.post(f"/api/bugs/{bid}/vote") + client.person[0] = "someone.else@example.com" + assert _my_vote(client, bid) is False # a different caller + assert client.get(f"/api/bugs/{bid}").get_json()["votes"] == 1 + client.person[0] = ADMIN.upper() + assert _my_vote(client, bid) is True and _my_vote(client, other) is False + client.person[0] = "" # nobody signed in + assert _my_vote(client, bid) is False + + +def test_voting_twice_is_a_200_that_still_says_voted(client): + bid = file_bug(client) + first = client.post(f"/api/bugs/{bid}/vote") + again = client.post(f"/api/bugs/{bid}/vote") + assert again.status_code == 200 + assert first.get_json() == again.get_json() == {"votes": 1, "voted": True} + + +def test_delete_with_no_vote_says_voted_false_and_keeps_the_count(client): + bid = file_bug(client) + assert client.delete(f"/api/bugs/{bid}/vote").get_json() == {"votes": 0, "voted": False} + client.person[0] = "b@example.com" + client.post(f"/api/bugs/{bid}/vote") + client.person[0] = ADMIN + assert client.delete(f"/api/bugs/{bid}/vote").get_json() == {"votes": 1, "voted": False} + + +def test_voted_among_is_the_callers_ids_in_the_list(any_store): + a, b = file_bug(make_client(any_store)), file_bug(make_client(any_store)) + any_store.add_vote(a, "Me@Example.com") + any_store.add_vote(b, "you@example.com") + assert any_store.voted_among([a, b, "nope"], "me@example.com") == {a} + assert any_store.voted_among([], "me@example.com") == set() + assert any_store.voted_among([a, b], "") == set() + + +# ---- canTriage (3.3.0) ----------------------------------------------------- + +def _triage_client(store, email, admin_email=ADMIN): + app = Flask(__name__) + app.register_blueprint(create_blueprint( + store=store, is_admin=lambda r: bool(email) and email == admin_email, + actor_identity=lambda r: {"email": email, "name": ""} if email else ""), url_prefix="/api") + return app.test_client() + + +@pytest.mark.parametrize("email,expected", [(ADMIN, True), ("pat@example.com", False), ("", False)]) +def test_can_triage_is_the_apps_is_admin_on_list_and_detail(any_store, email, expected): + bid = file_bug(make_client(any_store)) + feature = file_bug(make_client(any_store), tags=["feature"]) + c = _triage_client(any_store, email) + listed = c.get("/api/bugs?days=1").get_json() + assert listed["canTriage"] is expected + assert c.get(f"/api/bugs/{feature}").get_json()["canTriage"] is expected + if expected: + assert c.get(f"/api/bugs/{bid}").get_json()["canTriage"] is True diff --git a/packages/backend-python/tests/test_visibility.py b/packages/backend-python/tests/test_visibility.py index 85897bb..c2d73fa 100644 --- a/packages/backend-python/tests/test_visibility.py +++ b/packages/backend-python/tests/test_visibility.py @@ -144,7 +144,7 @@ def test_the_app_default_actor_is_not_a_caller_nobody_sees_its_reports(any_store c = app.test_client() bid = c.post("/bugs", json={"details": "filed with no one signed in"}).get_json()["id"] assert any_store.get_bug(bid).actor_email == "owner@example.com" - assert c.get("/bugs").get_json() == {"bugs": []} + assert c.get("/bugs").get_json()["bugs"] == [] assert c.get(f"/bugs/{bid}").status_code == 404 diff --git a/packages/spec/openapi.yaml b/packages/spec/openapi.yaml index 8f4430b..1ebb572 100644 --- a/packages/spec/openapi.yaml +++ b/packages/spec/openapi.yaml @@ -116,6 +116,9 @@ paths: type: array items: $ref: "#/components/schemas/BugSummary" + canTriage: + type: boolean + description: Whether the caller may triage (the app's `is_admin` answer; 3.3.0, the Python backend only). /bugs/{id}: parameters: @@ -219,7 +222,7 @@ paths: - $ref: "#/components/parameters/BugId" post: summary: Vote for a report (any signed-in caller; backends 3.0.0) - description: One vote per person; voting twice is a no-op. 401 when nobody is signed in. + description: One vote per person; voting twice is a no-op that still answers 200 with `voted` true. 401 when nobody is signed in. operationId: voteBug responses: "200": @@ -463,6 +466,9 @@ components: type: integer minimum: 0 description: Count of people who voted (3.0.0); 0 on a v2 record. + myVote: + type: boolean + description: Whether the caller has voted (3.3.0; the Python backend only, the Node backend does not send it). False when nobody is signed in. Bug: allOf: @@ -474,6 +480,9 @@ components: metaUrl: { type: string } metaUserAgent: { type: string } metaBuildSha: { type: string } + canTriage: + type: boolean + description: Whether the caller may triage (the app's `is_admin` answer; 3.3.0, the Python backend only). canNotify: type: boolean description: | diff --git a/packages/spec/report-contract.json b/packages/spec/report-contract.json index 93a8992..6f7e6b8 100644 --- a/packages/spec/report-contract.json +++ b/packages/spec/report-contract.json @@ -156,7 +156,8 @@ "owner", "parentId", "duplicateOf", - "votes" + "votes", + "myVote" ], "_v3": [ @@ -167,7 +168,10 @@ "`owner`, `parentId` and `duplicateOf` are TRIAGE fields (null until set);", "setting `duplicateOf` declines the report with the note", "'duplicate of '. `votes` is a count; one vote per signed-in person.", - "A v2 record carries none of these: they read back null, `votes` 0." + "A v2 record carries none of these: they read back null, `votes` 0.", + "`myVote` (3.3.0) is whether the CALLER has voted, false for nobody signed in;", + "the Python backend sends it on list and detail, the Node backend does not yet.", + "`canTriage` (3.3.0) is the app's own is_admin answer for the caller: a top-level field of the list body and on the detail." ], "products": ["PikPak", "Seal", "Placement", "Internal"], "appProducts": { @@ -200,7 +204,8 @@ "metaUrl", "metaUserAgent", "metaBuildSha", - "audit" + "audit", + "canTriage" ], "optionalDetailFields": ["transcript"], @@ -246,6 +251,7 @@ "parentId": null, "duplicateOf": null, "votes": 2, + "myVote": true, "details": "Tapping 7.5 twice leaves the picker open and the value unset.", "metaUrl": "https://hq.helloleap.ai/index.html?tab=entry", "metaUserAgent": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X)", diff --git a/packages/spec/types.py b/packages/spec/types.py index af08279..fed0e7e 100644 --- a/packages/spec/types.py +++ b/packages/spec/types.py @@ -60,6 +60,7 @@ class BugSummary(TypedDict): parentId: NotRequired[str | None] duplicateOf: NotRequired[str | None] votes: NotRequired[int] + myVote: NotRequired[bool] # whether the caller has voted (backends 3.3.0; Python backend only) class AuditEntry(TypedDict): @@ -78,6 +79,7 @@ class Bug(BugSummary): metaBuildSha: NotRequired[str] transcript: NotRequired[list[TranscriptTurn] | None] canNotify: NotRequired[bool] # GET /bugs/ only (backends 2.2.0) + canTriage: NotRequired[bool] # whether the caller may triage: the app's is_admin (backends 3.3.0; Python only) notified: NotRequired["Notified"] # PATCH response only, when notify was requested (backends 2.2.0) audit: list[AuditEntry] @@ -88,6 +90,11 @@ class Notified(TypedDict): error: NotRequired[str] +class BugList(TypedDict): + bugs: list[BugSummary] + canTriage: NotRequired[bool] # backends 3.3.0; Python only + + class Voted(TypedDict): votes: int voted: bool diff --git a/packages/spec/types.ts b/packages/spec/types.ts index 7cd3c92..1a75cce 100644 --- a/packages/spec/types.ts +++ b/packages/spec/types.ts @@ -64,6 +64,8 @@ export interface BugSummary { parentId?: string | null; duplicateOf?: string | null; votes?: number; + /** Whether the caller has voted (backends 3.3.0; the Python backend only). */ + myVote?: boolean; } export interface AuditEntry { @@ -84,6 +86,8 @@ export interface Bug extends BugSummary { transcript?: TranscriptTurn[] | null; /** GET /bugs/{id} only: the server can email the reporter and the report has an address (backends 2.2.0). */ canNotify?: boolean; + /** Whether the caller may triage: the app's `is_admin` answer (backends 3.3.0; the Python backend only). */ + canTriage?: boolean; /** PATCH response only, when `notify` was requested (backends 2.2.0). */ notified?: Notified; audit: AuditEntry[]; @@ -95,6 +99,12 @@ export interface Notified { error?: string; } +/** GET /bugs response body. `canTriage` is the app's `is_admin` answer for the caller (backends 3.3.0; Python only). */ +export interface BugList { + bugs: BugSummary[]; + canTriage?: boolean; +} + /** POST/DELETE /bugs/{id}/vote response (backends 3.0.0). */ export interface Voted { votes: number; From 61dea3567cd962ed88e5ced3cc4dd1d596cbbff0 Mon Sep 17 00:00:00 2001 From: kmoy007 Date: Sun, 15 Nov 2026 10:51:18 -0800 Subject: [PATCH 2/2] myVote never asks as the default actor; caller fields leave the field lists; list-body drift test; README notes Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 2 +- packages/backend-python/README.md | 8 ++++- .../backend-python/bug_report/blueprint.py | 14 +++++--- .../backend-python/tests/test_contract.py | 5 +++ packages/backend-python/tests/test_proxy.py | 9 +++++ .../backend-python/tests/test_spec_drift.py | 23 ++++++++++++ .../backend-python/tests/test_v3_triage.py | 35 +++++++++++++++++++ packages/spec/README.md | 1 + packages/spec/openapi.yaml | 6 ++-- packages/spec/report-contract.json | 20 +++++++---- 10 files changed, 106 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 52c5956..dce9bd4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ A UI can show the vote button's state. Additive; the report contract gains one f - **Votes answer with the caller's state.** `POST /bugs/{id}/vote` by someone who already voted is a 200 with `{voted: true, votes: }` and the count unchanged; `DELETE` answers `{voted: false, votes: }` 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` (`summaryFields`, 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. +- `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) diff --git a/packages/backend-python/README.md b/packages/backend-python/README.md index 96b5fed..9e84820 100644 --- a/packages/backend-python/README.md +++ b/packages/backend-python/README.md @@ -60,7 +60,13 @@ that hook, the body's `actorEmail`), one vote per person, case-insensitively. `G `area` and `priority` as well as `status` and `days`. Every summary carries `kind`, `app`, `product`, `area`, `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`. A record written before v3 has them null and `votes` 0. +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. diff --git a/packages/backend-python/bug_report/blueprint.py b/packages/backend-python/bug_report/blueprint.py index 9807508..90f1d82 100644 --- a/packages/backend-python/bug_report/blueprint.py +++ b/packages/backend-python/bug_report/blueprint.py @@ -313,11 +313,13 @@ def _vote_counts(ids): counter = getattr(store, "vote_counts", None) return counter(ids) if counter and ids else {} - def _my_votes(ids) -> set: - """Which of ``ids`` the caller (the same person the vote routes use) has voted on; - nobody signed in, or a store that predates votes, means none. One store call per list.""" + 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) - who = _voter(request) + 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: @@ -551,7 +553,9 @@ def _vote(bug_id: str, adding: bool): return jsonify({"error": "not found"}), 404 # `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. - return jsonify({"votes": store.vote_counts([bug_id]).get(bug_id, 0), "voted": bug_id in _my_votes([bug_id])}) + # (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}//vote", methods=["POST"]) def api_vote(bug_id: str): diff --git a/packages/backend-python/tests/test_contract.py b/packages/backend-python/tests/test_contract.py index 4f93acf..921cfec 100644 --- a/packages/backend-python/tests/test_contract.py +++ b/packages/backend-python/tests/test_contract.py @@ -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"])) diff --git a/packages/backend-python/tests/test_proxy.py b/packages/backend-python/tests/test_proxy.py index bf82e52..f9e86b3 100644 --- a/packages/backend-python/tests/test_proxy.py +++ b/packages/backend-python/tests/test_proxy.py @@ -339,3 +339,12 @@ def test_can_triage_and_my_vote_pass_through_the_proxy_unchanged(front): 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"]) diff --git a/packages/backend-python/tests/test_spec_drift.py b/packages/backend-python/tests/test_spec_drift.py index f237080..63ee10f 100644 --- a/packages/backend-python/tests/test_spec_drift.py +++ b/packages/backend-python/tests/test_spec_drift.py @@ -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() diff --git a/packages/backend-python/tests/test_v3_triage.py b/packages/backend-python/tests/test_v3_triage.py index 99c16fe..5d91c9e 100644 --- a/packages/backend-python/tests/test_v3_triage.py +++ b/packages/backend-python/tests/test_v3_triage.py @@ -382,3 +382,38 @@ def test_can_triage_is_the_apps_is_admin_on_list_and_detail(any_store, email, ex assert c.get(f"/api/bugs/{feature}").get_json()["canTriage"] is expected if expected: assert c.get(f"/api/bugs/{bid}").get_json()["canTriage"] is True + + +# ---- round 2: who myVote is asked for -------------------------------------- + +def _claims_client(store, **kw): + app = Flask(__name__) + app.register_blueprint(create_blueprint(store=store, **kw)) + return app.test_client() + + +def test_my_vote_is_never_the_default_actors(any_store): + c = _claims_client(any_store, default_actor_email="app@example.com") + bid = c.post("/bugs", json={"details": "x"}).get_json()["id"] + r = c.post(f"/bugs/{bid}/vote") # no claim: the default votes + assert r.get_json() == {"votes": 1, "voted": True} + assert c.get(f"/bugs/{bid}").get_json()["myVote"] is False # an anonymous caller is not that person + assert c.get("/bugs?days=1").get_json()["bugs"][0]["myVote"] is False + assert c.get(f"/bugs/{bid}?actorEmail=app@example.com").get_json()["myVote"] is True # a claim of it is + + +def test_a_store_without_voted_among_answers_with_what_was_asked(any_store): + class Old: + def __init__(self, inner): + self._i = inner + def __getattr__(self, n): + if n == "voted_among": + raise AttributeError(n) + return getattr(self._i, n) + c = _claims_client(Old(any_store)) + bid = c.post("/bugs", json={"details": "x"}).get_json()["id"] + body = {"actorEmail": "a@example.com"} + assert c.post(f"/bugs/{bid}/vote", json=body).get_json() == {"votes": 1, "voted": True} + assert c.post(f"/bugs/{bid}/vote", json=body).get_json() == {"votes": 1, "voted": True} + assert c.delete(f"/bugs/{bid}/vote?actorEmail=a@example.com").get_json() == {"votes": 0, "voted": False} + assert "myVote" in c.get(f"/bugs/{bid}").get_json() and c.get(f"/bugs/{bid}").get_json()["myVote"] is False diff --git a/packages/spec/README.md b/packages/spec/README.md index cd97f2f..6ab2699 100644 --- a/packages/spec/README.md +++ b/packages/spec/README.md @@ -65,5 +65,6 @@ Additive; a v2 record and a v2 client work unchanged. See `report-contract.json` All additive and optional, so older data and older clients keep working: - `actorName` on a report and `changedByName` on an audit row: the display name beside the address. `""` when unknown. A reader derives a name from the address when it is empty (split the local part on `.` `_` `-`, capitalise each part: `chris.hamblin@x` is "Chris Hamblin", `ken@x` is "Ken"); the first name is the first word. +- `myVote` (every list row and the detail) and `canTriage` (the list body and the detail), 3.3.0, Python backend only: caller fields, like `canNotify`, not part of the report. `myVote` is whether the caller has voted; `canTriage` is the app's `is_admin` answer. - `canNotify` on `GET /bugs/{id}` only: this server can email the reporter and the report has an `actorEmail`. - `PATCH` takes `notify: true` (default false). It is acted on only when the status actually changes to `resolved` or `declined` (reopening never emails), needs a non-empty `note`, and writes the change and its audit row before the send. The response gains `notified: {ok, to, error?}`; a second audit row (from = to = the new status) records `emailed
` or `email to
failed: `. The Node backend has no mailer: it ignores `notify` and returns no `notified`. diff --git a/packages/spec/openapi.yaml b/packages/spec/openapi.yaml index 1ebb572..f7da3ad 100644 --- a/packages/spec/openapi.yaml +++ b/packages/spec/openapi.yaml @@ -118,7 +118,7 @@ paths: $ref: "#/components/schemas/BugSummary" canTriage: type: boolean - description: Whether the caller may triage (the app's `is_admin` answer; 3.3.0, the Python backend only). + description: A caller field, like `canNotify`. Whether the caller may triage (the app's `is_admin` answer; 3.3.0, the Python backend only). /bugs/{id}: parameters: @@ -468,7 +468,7 @@ components: description: Count of people who voted (3.0.0); 0 on a v2 record. myVote: type: boolean - description: Whether the caller has voted (3.3.0; the Python backend only, the Node backend does not send it). False when nobody is signed in. + description: A caller field, like `canNotify`, not a property of the report. Whether the caller has voted (3.3.0; the Python backend only). False when nobody is signed in; never answered for the app's default actor. Bug: allOf: @@ -482,7 +482,7 @@ components: metaBuildSha: { type: string } canTriage: type: boolean - description: Whether the caller may triage (the app's `is_admin` answer; 3.3.0, the Python backend only). + description: A caller field, like `canNotify`. Whether the caller may triage (the app's `is_admin` answer; 3.3.0, the Python backend only). canNotify: type: boolean description: | diff --git a/packages/spec/report-contract.json b/packages/spec/report-contract.json index 6f7e6b8..d8184b0 100644 --- a/packages/spec/report-contract.json +++ b/packages/spec/report-contract.json @@ -156,8 +156,7 @@ "owner", "parentId", "duplicateOf", - "votes", - "myVote" + "votes" ], "_v3": [ @@ -169,9 +168,7 @@ "setting `duplicateOf` declines the report with the note", "'duplicate of '. `votes` is a count; one vote per signed-in person.", "A v2 record carries none of these: they read back null, `votes` 0.", - "`myVote` (3.3.0) is whether the CALLER has voted, false for nobody signed in;", - "the Python backend sends it on list and detail, the Node backend does not yet.", - "`canTriage` (3.3.0) is the app's own is_admin answer for the caller: a top-level field of the list body and on the detail." + "Caller fields (3.3.0) are listed in `callerFields`, not in the two lists above." ], "products": ["PikPak", "Seal", "Placement", "Internal"], "appProducts": { @@ -183,6 +180,16 @@ "leaphq": "Internal" }, "priorities": ["now", "next", "later"], + "_callerFields": [ + "Fields that describe the CALLER, not the report, like `canNotify` (which", + "this contract has never listed either). The Python backend sends them,", + "the Node backend does not yet. `myVote` is on every list row and the", + "detail: whether the caller has voted (false for nobody signed in; the", + "caller is the checked identity, or in claims mode the request's own", + "`actorEmail`, never the app's default actor). `canTriage` is the app's own", + "is_admin answer, a top-level field of the list body and on the detail." + ], + "callerFields": ["myVote", "canTriage"], "triageFields": ["area", "priority", "owner", "parentId", "duplicateOf"], "listFilters": ["status", "days", "app", "kind", "area", "priority"], @@ -204,8 +211,7 @@ "metaUrl", "metaUserAgent", "metaBuildSha", - "audit", - "canTriage" + "audit" ], "optionalDetailFields": ["transcript"],