14 Commits
Author SHA1 Message Date
rickandCursor 913490389f openspec(fix-reauth-flow): verification follow-up tasks + spec update
Records section 8 (the already_in_progress finding and its fix) and
renames the translation requirement to cover every abort reason, with
scenarios for the concurrent-flow path and source-derived enumeration.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 15:39:27 +02:00
rick 5c357859d6 Merge agent/fix-reauth-flow: translate already_in_progress, derive abort reasons 2026-09-06 15:39:18 +02:00
rickandCursor 5d049c5529 fix: translate the already_in_progress abort, derive the reason set
Verification caught this change violating its own requirement that every
abort reason the flow can emit has a translation. async_set_unique_id()
defaults to raise_on_progress=True and raises already_in_progress when
another flow holds the same unique ID. That is reachable, and reachable
by exactly the users this change is for: park a reauth flow, give up,
try Add Integration for the same account, and the raw key surfaces.

The coverage test was hardcoded to three reasons, so it checked a "for
every" requirement against a list written by hand and passed anyway.
Replace it with an AST scan of config_flow.py that resolves each
aborting helper call to the reason it raises, honouring explicit reason=
and the raise_on_progress=False opt-out, plus a sanity test so a scanner
that goes blind fails instead of silently passing. Confirmed the new
check fails against the pre-fix translation files.

Also adds a regression test for the concurrent-flow path, which is the
evidence that this abort is real rather than theoretical.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 15:39:13 +02:00
rickandCursor f124b46f0a openspec(fix-reauth-flow): apply tasks complete + sync config-flow spec
Marks sections 1-5 and the automated verification in 6 done, syncs the
config-flow delta into the main specs, and records the deferred
Cognito-token-persistence item in PROJECT_HYGIENE.md.

Archive (7.5/7.6) is deliberately held until on-device verification
(6.4-6.7) confirms the fix against the live machine.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 15:27:36 +02:00
rick 710b6be045 Merge agent/fix-reauth-flow: reauth updates the entry instead of aborting 2026-09-06 15:27:22 +02:00
rickandCursor 0f3b4c20af fix: make reauth update the existing entry instead of aborting
async_step_token is shared by the user and reauth sources but was written
only for the former. It called _abort_if_unique_id_configured() on every
path, and during reauth the unique ID belongs to the entry being repaired,
so the duplicate guard fired by design: authentication succeeded, the flow
aborted with already_configured, the new tokens were discarded, and the
coordinator's next poll re-raised the reauth repair. The integration was
unrecoverable through the UI short of delete-and-re-add, which costs entity
history and the restored keg-freshness baseline.

Branch on self.source at the terminal step, per HA's documented pattern for
flows shared between setup and reauth: reauth now guards with
_abort_if_unique_id_mismatch() and persists through
async_update_reload_and_abort(), which merges the new tokens into the
existing entry, keeps email and machine ID, reloads, and aborts with
reauth_successful. The user path keeps _abort_if_unique_id_configured()
unchanged.

Reauth also stops re-fetching /api/me when the entry already records a
machine ID, removing a round trip from a flow the user waits on and a
failure mode where a transient /api/me error turned a successful sign-in
into cannot_connect.

The helpers require core 2024.11, so declare that floor in hacs.json —
otherwise older cores would AttributeError mid-flow, which is worse than
the bug being fixed.

Adds the repo's first HA test harness (requirements-test.txt, opt-in) with
regression tests covering token persistence, entry reload, account
mismatch, case-insensitive email, and the explicit assertion that reauth
never aborts as already_configured. tests/test_keg_detection.py still runs
standalone under python3 -m unittest.

Version set to 0.3.1 rather than the 0.4.0 that PR #2 introduced; no
v0.4.0 tag was ever cut, so nothing was released under that number.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 15:26:48 +02:00
rickandCursor 4ff26f6e7b openspec(fix-reauth-flow): propose artifacts
Reauth aborts with already_configured because async_step_token calls
_abort_if_unique_id_configured() on every source, including reauth where
a matching unique ID is the expected condition. Fresh tokens are discarded
and the entry stays broken.

Artifacts cover the source-aware fix, the 2024.11 core floor the reauth
helpers require, and the pytest-homeassistant-custom-component harness
needed to regression-test a config flow.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 15:13:18 +02:00
rick 3b69942542 Merge GitHub PR #2 (brettjenkins): active-keg detection + keg name sensor 2026-09-06 14:39:51 +02:00
Rick FalkvingeandGitHub c39d906c99 Merge pull request #2 from brettjenkins/keg-name-sensor
Merged! Thanks for the contrib!

I see you have made several code mods in a fork -- mind if I merge those in too?
2026-08-25 16:11:53 +02:00
Brett Jenkins 9b3852b9fd Add active-keg detection and a keg name sensor
Resolves the tapped keg's product id to a beer name via a bundled
catalog (keg_catalog.json), exposing it as a new Keg sensor alongside
the existing Keg Remaining/Freshness sensors.
2026-07-05 00:49:29 +01:00
rickandCursor 8fbc7c830e docs: confirm keg remaining (kegVolume) is stable across power cycle
Corroborating observation: on a power cycle / integration reload, Keg
Remaining did not change while pours reset to 0. Confirms volume-jump
detection (b/c) and the manual button are power-cycle-safe.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-01 06:59:49 +02:00
rickandCursor 4b9c5ec647 docs: record that pour count resets on power cycle (drop pour-based keg detection)
Empirically confirmed numberOfPoursSinceStartup resets to 0 on a machine
power cycle, so it cannot reliably signal a keg change. Logs the finding
and a TODO to remove the pour-count-based detection (trigger a + last_pours
tracking) in a future OpenSpec change; volume jumps + the manual button
already cover keg changes and are power-cycle-safe.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-01 05:51:01 +02:00
rickandCursor d3d5bffb13 openspec(improve-keg-change-detection): archive completed change
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-31 21:22:46 +02:00
rickandCursor 43d9a3e818 openspec(improve-keg-change-detection): on-device verified + sync specs
Task 5.3 confirmed on-device (Mark Keg Changed button and volume-jump
detection both work). Applied the entities delta to the main spec: the
keg freshness sensor now documents the volume-jump triggers and
last_volume restore, plus the new Manual keg-change button requirement.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-31 21:22:36 +02:00
28 changed files with 1344 additions and 53 deletions
+2
View File
@@ -4,6 +4,8 @@
__pycache__/
*.pyc
.venv/
.venv-test/
.pytest_cache/
.credentials.json
*.swp
custom_components/perfectdraft.zip
+208
View File
@@ -0,0 +1,208 @@
# PROJECT_HYGIENE.md - Provenance, Project Context, Development/QA Hygiene, and Learnings
Drop-in operating instructions for coding agents. Read this file before every task.
**Working code only. Finish the job. Plausibility is not correctness.**
This file follows the [AGENTS.md](https://agents.md) open standard (Linux Foundation / Agentic AI Foundation). Claude Code, Codex, Cursor, Windsurf, Copilot, Aider, Devin, Amp read it natively. For tools that look elsewhere, symlink:
```bash
ln -s AGENTS.md CLAUDE.md
ln -s AGENTS.md GEMINI.md
```
---
## 0. Non-negotiables
These rules override everything else in this file when in conflict:
1. **No flattery, no filler.** Skip openers like "Great question", "You're absolutely right", "Excellent idea", "I'd be happy to". Start with the answer or the action.
2. **Disagree when you disagree.** If the user's premise is wrong, say so before doing the work. Agreeing with false premises to be polite is the single worst failure mode in coding agents.
3. **Never fabricate.** Not file paths, not commit hashes, not API names, not test results, not library functions. If you don't know, read the file, run the command, or say "I don't know, let me check."
4. **Stop when confused.** If the task has two plausible interpretations, ask. Do not pick silently and proceed.
5. **Touch only what you must.** Every changed line must trace directly to the user's request. No drive-by refactors, reformatting, or "while I was in there" cleanups.
---
## 1. Before writing code
**Goal: understand the problem and the codebase before producing a diff.**
- State your plan in one or two sentences before editing. For anything non-trivial, produce a numbered list of steps with a verification check for each.
- Read the files you will touch. Read the files that call the files you will touch. Claude Code: use subagents for exploration so the main context stays clean.
- Match existing patterns in the codebase. If the project uses pattern X, use pattern X, even if you'd do it differently in a greenfield repo.
- Surface assumptions out loud: "I'm assuming you want X, Y, Z. If that's wrong, say so." Do not bury assumptions inside the implementation.
- If two approaches exist, present both with tradeoffs. Do not pick one silently. Exception: trivial tasks (typo, rename, log line) where the diff fits in one sentence.
---
## 2. Writing code: simplicity first
**Goal: the minimum code that solves the stated problem. Nothing speculative.**
- No features beyond what was asked.
- No abstractions for single-use code. No configurability, flexibility, or hooks that were not requested.
- No error handling for impossible scenarios. Handle the failures that can actually happen.
- If the solution runs 200 lines and could be 50, rewrite it before showing it.
- If you find yourself adding "for future extensibility", stop. Future extensibility is a future decision.
- Bias toward deleting code over adding code. Shipping less is almost always better.
The test: would a senior engineer reading the diff call this overcomplicated? If yes, simplify.
---
## 3. Surgical changes
**Goal: clean, reviewable diffs. Change only what the request requires.**
- Do not "improve" adjacent code, comments, formatting, or imports that are not part of the task.
- Do not refactor code that works just because you are in the file.
- Do not delete pre-existing dead code unless asked. If you notice it, mention it in the summary.
- Do clean up orphans created by your own changes (unused imports, variables, functions your edit made obsolete).
- Match the project's existing style exactly: indentation, quotes, naming, file layout.
The test: every changed line traces directly to the user's request. If a line fails that test, revert it.
---
## 4. Goal-driven execution
**Goal: define success as something you can verify, then loop until verified.**
Rewrite vague asks into verifiable goals before starting:
- "Add validation" becomes "Write tests for invalid inputs (empty, malformed, oversized), then make them pass."
- "Fix the bug" becomes "Write a failing test that reproduces the reported symptom, then make it pass."
- "Refactor X" becomes "Ensure the existing test suite passes before and after, and no public API changes."
- "Make it faster" becomes "Benchmark the current hot path, identify the bottleneck with profiling, change it, show the benchmark is faster."
For every task:
1. State the success criteria before writing code.
2. Write the verification (test, script, benchmark, screenshot diff) where practical.
3. Run the verification. Read the output. Do not claim success without checking.
4. If the verification fails, fix the cause, not the test.
---
## 5. Tool use and verification
- Prefer running the code to guessing about the code. If a test suite exists, run it. If a linter exists, run it. If a type checker exists, run it.
- Never report "done" based on a plausible-looking diff alone. Plausibility is not correctness.
- When debugging, address root causes, not symptoms. Suppressing the error is not fixing the error.
- For UI changes, verify visually: screenshot before, screenshot after, describe the diff.
- Use CLI tools (gh, aws, gcloud, kubectl) when they exist. They are more context-efficient than reading docs or hitting APIs unauthenticated.
- When reading logs, errors, or stack traces, read the whole thing. Half-read traces produce wrong fixes.
---
## 6. Session hygiene
- Context is the constraint. Long sessions with accumulated failed attempts perform worse than fresh sessions with a better prompt.
- After two failed corrections on the same issue, stop. Summarize what you learned and ask the user to reset the session with a sharper prompt.
- Use subagents (Claude Code: "use subagents to investigate X") for exploration tasks that would otherwise pollute the main context with dozens of file reads.
- When committing, write descriptive commit messages (subject under 72 chars, body explains the why). No "update file" or "fix bug" commits. No "Co-Authored-By: Claude" attribution unless the project explicitly wants it.
---
## 7. Communication style
- Direct, not diplomatic. "This won't scale because X" beats "That's an interesting approach, but have you considered...".
- Concise by default. Two or three short paragraphs unless the user asks for depth. No padding, no restating the question, no ceremonial closings.
- When a question has a clear answer, give it. When it does not, say so and give your best read on the tradeoffs.
- Celebrate only what matters: shipping, solving genuinely hard problems, metrics that moved. Not feature ideas, not scope creep, not "wouldn't it be cool if".
- No excessive bullet points, no unprompted headers, no emoji. Prose is usually clearer than structure for short answers.
---
## 8. When to ask, when to proceed
**Ask before proceeding when:**
- The request has two plausible interpretations and the choice materially affects the output.
- The change touches something you've been told is load-bearing, versioned, or has a migration path.
- You need a credential, a secret, or a production resource you don't have access to.
- The user's stated goal and the literal request appear to conflict.
**Proceed without asking when:**
- The task is trivial and reversible (typo, rename a local variable, add a log line).
- The ambiguity can be resolved by reading the code or running a command.
- The user has already answered the question once in this session.
---
## 9. Self-improvement loop
**This file is living. Keep it short by keeping it honest.**
After every session where the agent did something wrong:
1. Ask: was the mistake because this file lacks a rule, or because the agent ignored a rule?
2. If lacking: add the rule under "Project Learnings" below, written as concretely as possible ("Always use X for Y" not "be careful with Y").
3. If ignored: the rule may be too long, too vague, or buried. Tighten it or move it up.
4. Every few weeks, prune. For each line, ask: "Would removing this cause the agent to make a mistake?" If no, delete. Bloated AGENTS.md files get ignored wholesale.
Boris Cherny (creator of Claude Code) keeps his team's file around 100 lines. Under 300 is a good ceiling. Over 500 and you are fighting your own config.
---
## 10. Project context
**Fill this in per project. Keep it specific. Delete sections that don't apply.**
### Stack
- Language and version:
- Framework(s):
- Package manager:
- Runtime / deployment target:
### Commands
- Install: `TODO`
- Build: `TODO`
- Test (all): `TODO`
- Test (single file): `TODO`
- Lint: `TODO`
- Typecheck: `TODO`
- Run locally: `TODO`
Prefer single-file or single-test runs during iteration. Full suites are for the final verification pass.
### Layout
- Source lives in: `TODO`
- Tests live in: `TODO`
- Do not modify: `TODO` (generated code, vendored deps, legacy areas)
### Conventions specific to this repo
- Naming: `TODO`
- Import style: `TODO`
- Error handling pattern: `TODO`
- Testing pattern and framework: `TODO`
### Forbidden
- `TODO`: things that look reasonable but will break this project.
---
## 11. Project Learnings
**Accumulated corrections. This section is for the agent to maintain, not just the human.**
When the user corrects your approach, append a one-line rule here before ending the session. Write it concretely ("Always use X for Y"), never abstractly ("be careful with Y"). If an existing line already covers the correction, tighten it instead of adding a new one. Remove lines when the underlying issue goes away (model upgrades, refactors, process changes).
- **`numberOfPoursSinceStartup` resets to 0 on a machine power cycle** (confirmed 2026-06-01: power-cycled the machine at pours=16, reloaded the integration, Pours read 0). It counts since machine startup, NOT since keg insertion. Do not base keg-change detection on the pour counter — a power cycle (outage, unplug, firmware update) would false-trigger it. `kegVolume` (Keg Remaining) was confirmed unchanged across the same power cycle/reload, so a power cycle produces no spurious volume jump — volume-jump signals (b/c) and the manual button are the power-cycle-safe detectors; prefer them.
- **TODO — own OpenSpec change: persist Cognito-refreshed tokens back to the config entry.** `PerfectDraftApiClient.refresh_access_token()` updates `_access_token`/`_id_token` in memory only, so every HA restart reloads the stale access token and burns a wasted 401-plus-refresh round trip before the first successful poll. Harmless today because the refresh token is what actually gates reauth and Cognito's `REFRESH_TOKEN_AUTH` never issues a new one, so nothing is lost — just wasteful. Deferred out of `fix-reauth-flow` to keep that diff surgical.
- **TODO — own OpenSpec change + release: remove pour-count-based keg detection** from `PerfectDraftKegFreshnessSensor` in `sensor.py`: trigger (a) `pours == 0 && kegVolume > 5.5 && last_pours != 0`, plus the `_last_pours` field and its restore/exposure/rebaseline. It can false-fire on a power cycle while the keg is above ~92% full, and adds nothing the volume triggers (b/c) and the Mark Keg Changed button don't already cover.
---
## 12. How this file was built
This boilerplate synthesizes:
- Sean Donahoe's IJFW ("It Just F\*cking Works") principles: one install, working code, no ceremony.
- Andrej Karpathy's observations on LLM coding pitfalls (the four principles: think-first, simplicity, surgical changes, goal-driven execution).
- Boris Cherny's public Claude Code workflow (reactive pruning, keep it ~100 lines, only rules that fix real mistakes).
- Anthropic's official Claude Code best practices (explore-plan-code-commit, verification loops, context as the scarce resource).
- Community anti-sycophancy patterns (explicit banned phrases, direct-not-diplomatic).
- The AGENTS.md open standard (cross-tool portability via symlinks).
Read once. Edit sections 10 and 11 for your project. Prune the rest over time. This file gets better the more you use it.
+1
View File
@@ -7,6 +7,7 @@ A Home Assistant custom integration for the [PerfectDraft Pro](https://www.perfe
| Sensor | Description | Unit |
|--------|-------------|------|
| Temperature | Current beer temperature | °C |
| Keg | Name of the tapped beer, resolved from a bundled catalog | — |
| Keg Remaining | Beer left in the keg | % |
| Keg Freshness | Days remaining until 30-day freshness expires | days |
| Connection | Machine connectivity status | — |
+14
View File
@@ -187,3 +187,17 @@ class PerfectDraftApiClient:
return await self._request(
"GET", f"/api/perfectdraft_machines/{machine_id}"
)
async def get_machine_active_keg(self, machine_id: str) -> dict[str, Any]:
"""GET the machine serialized with the active-keg group.
Returns the machine with a ``kegActive`` object holding the currently
tapped keg's product reference and its insertion date. This group is
mutually exclusive with the default status fields, so it needs its own
request alongside get_machine_details.
"""
return await self._request(
"GET",
f"/api/perfectdraft_machines/{machine_id}",
params={"groups[]": "perfectdraft_keg_active_read"},
)
+51 -14
View File
@@ -89,25 +89,27 @@ class PerfectDraftConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
_LOGGER.error("API error during auth: %s", err)
errors["base"] = "unknown"
else:
reauth_entry = (
self._get_reauth_entry()
if self.source == config_entries.SOURCE_REAUTH
else None
)
machine_id = (
reauth_entry.data.get(CONF_MACHINE_ID) if reauth_entry else None
)
if machine_id:
return await self._async_persist(
client, reauth_entry, machine_id
)
try:
profile = await client.get_user_profile()
except (PerfectDraftApiError, PerfectDraftConnectionError):
errors["base"] = "cannot_connect"
else:
machine_id = _extract_machine_id(profile)
await self.async_set_unique_id(self._email.lower())
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=f"PerfectDraft ({self._email})",
data={
CONF_EMAIL: self._email,
CONF_ACCESS_TOKEN: client.access_token,
CONF_ID_TOKEN: client.id_token,
CONF_REFRESH_TOKEN: client.refresh_token,
CONF_MACHINE_ID: machine_id,
},
return await self._async_persist(
client, reauth_entry, _extract_machine_id(profile)
)
return self.async_show_form(
@@ -120,6 +122,41 @@ class PerfectDraftConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
errors=errors,
)
async def _async_persist(
self,
client: PerfectDraftApiClient,
reauth_entry: config_entries.ConfigEntry | None,
machine_id: str | None,
) -> config_entries.ConfigFlowResult:
"""Store the freshly issued tokens.
Reauth must update the entry it was started for. Creating a new one
would change the entry_id and orphan every entity's unique_id, and
`_abort_if_unique_id_configured` cannot be used here at all: during
reauth the unique ID belongs to that very entry, so the duplicate
guard would abort the flow and discard the new tokens.
"""
data = {
CONF_ACCESS_TOKEN: client.access_token,
CONF_ID_TOKEN: client.id_token,
CONF_REFRESH_TOKEN: client.refresh_token,
CONF_MACHINE_ID: machine_id,
}
await self.async_set_unique_id(self._email.lower())
if reauth_entry is not None:
self._abort_if_unique_id_mismatch(reason="reauth_account_mismatch")
return self.async_update_reload_and_abort(
reauth_entry, data_updates=data
)
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=f"PerfectDraft ({self._email})",
data={CONF_EMAIL: self._email, **data},
)
async def async_step_reauth(
self, entry_data: dict[str, Any]
) -> config_entries.ConfigFlowResult:
@@ -82,4 +82,13 @@ class PerfectDraftDataUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]):
raise UpdateFailed(str(err)) from err
details["_machine_id"] = machine_id
# The active keg lives behind a separate serialization group. Treat it
# as best-effort so a failure here doesn't take the whole device down.
try:
active = await self.client.get_machine_active_keg(machine_id)
details["kegActive"] = active.get("kegActive")
except (PerfectDraftApiError, PerfectDraftConnectionError) as err:
_LOGGER.debug("Active keg lookup failed: %s", err)
return details
@@ -0,0 +1,88 @@
{
"452": "Beck's Gold",
"453": "Beck's",
"454": "Löwenbräu",
"455": "Franziskaner Weissbier",
"456": "Diebels",
"457": "Stella Artois",
"458": "Jupiler",
"500": "Hasseroder",
"509": "Leffe Blonde",
"679": "Hoegaarden",
"759": "Diekirch Grand Cru",
"1095": "Leffe Ruby",
"2073": "Hertog Jan",
"2167": "Leffe Spring",
"2172": "Leffe Brune",
"2452": "Leffe Royal Whitbread Golding",
"2565": "Hoegaarden Rose",
"9156": "Leffe Royal Cascade",
"29745": "Lowenbrau Oktoberfestbier",
"29775": "Goose Island Midway",
"29896": "Kwak",
"29974": "Spaten",
"30955": "Franziskaner Royal",
"31718": "Leffe Summer",
"31747": "Budweiser",
"31896": "Tripel Karmeliet",
"32814": "Birra Del Borgo Lisa",
"32816": "Goose Island IPA",
"32864": "Leffe Amber",
"33642": "Ginette Bio Refreshing Blonde",
"33917": "Tiny Rebel Clwb Tropica",
"33918": "Spaten Oktoberfestbier",
"34327": "Thornbridge Jaipur",
"34493": "Corona Extra",
"34944": "Leffe La Légère",
"35344": "Ginette Bio White",
"36302": "Tennent's Lager",
"41588": "Schneider's Bayrisch Hell",
"41830": "BrewDog Punk IPA",
"42223": "Victoria",
"42352": "St Feuillien Blonde",
"42377": "Bud Light",
"42526": "Vocation Life & Death",
"42640": "Kwak Blonde",
"42756": "Innis & Gunn Lager Beer",
"42778": "Mikkeller Game of Thrones",
"42863": "1L Stein",
"42876": "Orchard Pig Reveller Cider",
"43006": "Camden Hells Lager",
"43009": "Stella Artois Unfiltered",
"43019": "Hawkstone Lager",
"43033": "Hertog Jan Bockbier",
"43235": "Corona Cero (0.0% abv) 6L Keg",
"43805": "Camden Pale Ale",
"43806": "Magic Rock Magic Orange",
"44059": "San Miguel Especial",
"44090": "Kopparberg Strawberry and Lime Cider",
"44171": "Leffe Blanche",
"44238": "BrewDog Hopped in Harmony",
"44331": "Short Date Ninkasi Flower Lager 6L Keg BBE June 2024",
"44387": "Mont Blanc La Rousse",
"44452": "Franziskaner Kellerbier",
"44474": "Camden Marzen",
"44526": "Mahou",
"44536": "Short Date Tiny Rebel Stay Puft 6L Keg BBE August 2024",
"47144": "Haake Beck",
"47285": "Theakston Old Peculier",
"47384": "Peroni Nastro Azzurro",
"47418": "Singha",
"47440": "Ninkasi French IPA",
"47486": "Meteor White IPA",
"47629": "Camden Eazy IPA",
"47943": "Fuller's London Pride",
"47962": "Bass Pale Ale",
"47972": "Stella Artois 0.0%",
"47973": "Trooper Original",
"47974": "Ch'ti Blonde",
"47977": "Früh Kölsch",
"47978": "Saison Dupont Dry Hop",
"47979": "Modelo Especial",
"47984": "Samson 11",
"47986": "La Chouffe Blonde",
"47999": "Thatchers Gold Cider",
"48019": "Leffe Blonde 0.0%",
"48024": "Siren Lumina IPA",
"48061": "Northern Monk Faith"
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"domain": "perfectdraft",
"name": "PerfectDraft",
"version": "0.3.0",
"version": "0.3.1",
"documentation": "https://github.com/Falkvinge/hassio-integration-perfectdraft-pro",
"issue_tracker": "https://github.com/Falkvinge/hassio-integration-perfectdraft-pro/issues",
"codeowners": ["@Falkvinge"],
+91 -23
View File
@@ -1,8 +1,11 @@
"""Sensor entities for PerfectDraft."""
from __future__ import annotations
import json
import logging
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable
from homeassistant.components.sensor import (
@@ -24,9 +27,23 @@ from .const import DOMAIN, keg_changed_signal
from .coordinator import PerfectDraftDataUpdateCoordinator
from .keg_detection import KEG_TOTAL_VOLUME, detect_keg_change
_LOGGER = logging.getLogger(__name__)
KEG_FRESHNESS_DAYS = 30
def _load_keg_catalog() -> dict[int, str]:
try:
raw = json.loads((Path(__file__).parent / "keg_catalog.json").read_text())
return {int(k): v for k, v in raw.items()}
except (OSError, ValueError) as err:
_LOGGER.debug("Could not load keg catalog: %s", err)
return {}
_KEG_CATALOG: dict[int, str] = _load_keg_catalog()
@dataclass(frozen=True, kw_only=True)
class PerfectDraftSensorDescription(SensorEntityDescription):
"""Extended description with a value extractor."""
@@ -88,6 +105,33 @@ def _get_mode(data: dict) -> str | None:
return setting.get("mode")
def _get_keg_product_id(data: dict) -> int | None:
ref = (data.get("kegActive") or {}).get("keg")
if not ref:
return None
try:
return int(str(ref).rstrip("/").rsplit("/", 1)[-1])
except ValueError:
return None
def _get_keg_name(data: dict) -> str | None:
product_id = _get_keg_product_id(data)
if product_id is None:
return None
return _KEG_CATALOG.get(product_id)
def _keg_inserted_at(data: dict) -> datetime | None:
iso = (data.get("kegActive") or {}).get("insertedAt")
if not iso:
return None
try:
return datetime.fromisoformat(iso)
except (ValueError, TypeError):
return None
SENSOR_DESCRIPTIONS: tuple[PerfectDraftSensorDescription, ...] = (
PerfectDraftSensorDescription(
key="temperature",
@@ -107,6 +151,18 @@ SENSOR_DESCRIPTIONS: tuple[PerfectDraftSensorDescription, ...] = (
suggested_display_precision=0,
value_fn=_get_volume_remaining,
),
PerfectDraftSensorDescription(
key="keg_product_id",
translation_key="keg_product_id",
icon="mdi:barcode",
value_fn=_get_keg_product_id,
),
PerfectDraftSensorDescription(
key="keg_name",
translation_key="keg_name",
icon="mdi:beer",
value_fn=_get_keg_name,
),
PerfectDraftSensorDescription(
key="connection",
translation_key="connection",
@@ -200,9 +256,10 @@ class PerfectDraftKegFreshnessSensor(
):
"""Tracks keg freshness as a 30-day countdown from insertion.
Detects new keg insertion when numberOfPoursSinceStartup resets to 0
and kegVolume is near full. Persists the insertion timestamp across
HA restarts via RestoreEntity.
Prefers the insertion date reported by the API's active keg. When that is
unavailable it falls back to detecting insertion locally (pour count reset
with a near-full keg). The date is persisted across HA restarts via
RestoreEntity.
"""
_attr_has_entity_name = True
@@ -261,27 +318,30 @@ class PerfectDraftKegFreshnessSensor(
@callback
def _handle_coordinator_update(self) -> None:
"""Detect new keg insertion on each data update."""
"""Update the insertion date on each poll."""
data = self.coordinator.data
if not data:
super()._handle_coordinator_update()
return
details = data.get("details") or {}
pours = details.get("numberOfPoursSinceStartup")
volume = details.get("kegVolume")
reported = _keg_inserted_at(data)
if reported is not None:
self._keg_inserted_at = reported
else:
details = data.get("details") or {}
pours = details.get("numberOfPoursSinceStartup")
volume = details.get("kegVolume")
if pours is not None and volume is not None:
if detect_keg_change(
last_pours=self._last_pours,
last_volume=self._last_volume,
pours=int(pours),
volume=float(volume),
):
self._keg_inserted_at = datetime.now(timezone.utc)
if pours is not None and volume is not None:
if detect_keg_change(
last_pours=self._last_pours,
last_volume=self._last_volume,
pours=int(pours),
volume=float(volume),
):
self._keg_inserted_at = datetime.now(timezone.utc)
self._last_pours = int(pours)
self._last_volume = float(volume)
self._last_pours = int(pours)
self._last_volume = float(volume)
super()._handle_coordinator_update()
@@ -304,17 +364,25 @@ class PerfectDraftKegFreshnessSensor(
self.async_write_ha_state()
def _inserted_at(self) -> datetime | None:
"""The current insertion date, preferring the live API value."""
if self.coordinator.data:
reported = _keg_inserted_at(self.coordinator.data)
if reported is not None:
return reported
return self._keg_inserted_at
@property
def native_value(self) -> int | None:
if self._keg_inserted_at is None:
inserted = self._inserted_at()
if inserted is None:
return None
elapsed = (datetime.now(timezone.utc) - self._keg_inserted_at).days
remaining = KEG_FRESHNESS_DAYS - elapsed
return max(remaining, 0)
elapsed = (datetime.now(timezone.utc) - inserted).days
return max(KEG_FRESHNESS_DAYS - elapsed, 0)
@property
def available(self) -> bool:
return super().available and self._keg_inserted_at is not None
return super().available and self._inserted_at() is not None
def _device_info(
+5 -1
View File
@@ -32,13 +32,17 @@
},
"abort": {
"already_configured": "This PerfectDraft account is already configured.",
"reauth_successful": "Re-authentication successful."
"reauth_successful": "Re-authentication successful.",
"reauth_account_mismatch": "Those credentials are for a different PerfectDraft account. Re-authenticate with the account this integration was set up with, or delete the integration and add the other account separately.",
"already_in_progress": "Setup for this PerfectDraft account is already under way. Finish or cancel the pending flow first — look for it under Settings > Devices & Services."
}
},
"entity": {
"sensor": {
"temperature": { "name": "Temperature" },
"keg_remaining": { "name": "Keg Remaining" },
"keg_product_id": { "name": "Keg Product" },
"keg_name": { "name": "Keg" },
"connection": { "name": "Connection" },
"door": { "name": "Door" },
"pours": { "name": "Pours" },
@@ -32,13 +32,17 @@
},
"abort": {
"already_configured": "This PerfectDraft account is already configured.",
"reauth_successful": "Re-authentication successful."
"reauth_successful": "Re-authentication successful.",
"reauth_account_mismatch": "Those credentials are for a different PerfectDraft account. Re-authenticate with the account this integration was set up with, or delete the integration and add the other account separately.",
"already_in_progress": "Setup for this PerfectDraft account is already under way. Finish or cancel the pending flow first — look for it under Settings > Devices & Services."
}
},
"entity": {
"sensor": {
"temperature": { "name": "Temperature" },
"keg_remaining": { "name": "Keg Remaining" },
"keg_product_id": { "name": "Keg Product" },
"keg_name": { "name": "Keg" },
"connection": { "name": "Connection" },
"door": { "name": "Door" },
"pours": { "name": "Pours" },
+2 -1
View File
@@ -1,4 +1,5 @@
{
"name": "PerfectDraft",
"render_readme": true
"render_readme": true,
"homeassistant": "2024.11.0"
}
@@ -27,5 +27,5 @@
- [x] 5.1 Syntax-check all modified/new files (`py_compile` + JSON validation — passed)
- [x] 5.2 Unit-test the three detection triggers and the no-baseline guard against representative `(last_pours, last_volume) → (pours, volume)` transitions (incl. the "swap then immediate pour" case: pours 1, volume jump) — `tests/test_keg_detection.py`, 11 tests pass
- [ ] 5.3 Build zip, deploy to HA: verify the button appears on the device, pressing it resets the freshness countdown to 30, and a simulated volume jump sets the insertion date (manual — user; do after installing the v0.3.0 release via HACS)
- [x] 5.3 Build zip, deploy to HA: verify the button appears on the device, pressing it resets the freshness countdown to 30, and a simulated volume jump sets the insertion date (manual — verified on-device after installing the v0.3.0 release via HACS)
- [x] 5.4 Bump `manifest.json` version (0.3.0) and commit
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-09-06
+126
View File
@@ -0,0 +1,126 @@
## Context
The config flow has three entry points that converge on one terminal step:
```
async_step_user ──────────────┐
├──> async_step_token ──> async_create_entry
async_step_reauth ──> async_step_reauth_confirm ──┘
```
`async_step_token` is the only place that talks to the API and the only place that persists tokens. It was written for the initial-setup path and never made aware that reauth also lands there:
```100:111:custom_components/perfectdraft/config_flow.py
await self.async_set_unique_id(self._email.lower())
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=f"PerfectDraft ({self._email})",
data={
CONF_EMAIL: self._email,
CONF_ACCESS_TOKEN: client.access_token,
CONF_ID_TOKEN: client.id_token,
CONF_REFRESH_TOKEN: client.refresh_token,
CONF_MACHINE_ID: machine_id,
},
)
```
During reauth the unique ID resolves to the entry being repaired, so `_abort_if_unique_id_configured()` fires and the flow terminates with `already_configured` before reaching `async_create_entry`. This is the documented behaviour of that helper — it is simply the wrong helper for this source. The observed symptom chain follows directly: authentication succeeds (the "churning"), the abort surfaces "already configured", the entry retains its dead tokens, and the coordinator's next `ConfigEntryAuthFailed` re-raises the reauth repair.
Constraints on the fix:
- The reauth path must reach the *same* API calls as setup. PerfectDraft's `/authentication/sign-in` requires a fresh reCAPTCHA token with a two-minute lifetime, so reauth genuinely needs the full email/password/token sequence — there is no silent re-auth to fall back on. Sharing `async_step_token` between sources is correct; only its terminal branch is wrong.
- The entry must be preserved, not recreated. Recreating would change `entry_id`, orphan every entity's `unique_id`, and discard the keg-freshness baseline that `PerfectDraftKegFreshnessSensor` restores via `RestoreEntity`.
- `CONF_MACHINE_ID` already lives in the entry. Reauth should not depend on rediscovering it.
## Goals / Non-Goals
**Goals:**
- Reauth completes: fresh tokens land in the existing config entry, the entry reloads, the repair clears.
- Reauth can never abort with `already_configured`.
- Signing in as a different account during reauth is rejected with a clear message, not silently rebound onto the existing entry.
- The initial-setup path behaves exactly as it does today, including duplicate prevention.
- Automated regression coverage for all of the above.
**Non-Goals:**
- Persisting Cognito-refreshed access/ID tokens back to the config entry during normal polling. Noted in the proposal, tracked separately.
- Eliminating the reCAPTCHA token requirement from reauth. The upstream API mandates it.
- A `reconfigure` step. Nothing in the entry data is user-editable outside of credentials.
- Any change to token refresh, coordinator, or entity behaviour.
## Decisions
### Decision 1: Branch inside `async_step_token` on `self.source`, using HA's reauth helpers
The terminal branch becomes:
```python
await self.async_set_unique_id(self._email.lower())
if self.source == SOURCE_REAUTH:
self._abort_if_unique_id_mismatch(reason="reauth_account_mismatch")
return self.async_update_reload_and_abort(
self._get_reauth_entry(),
data_updates={
CONF_ACCESS_TOKEN: client.access_token,
CONF_ID_TOKEN: client.id_token,
CONF_REFRESH_TOKEN: client.refresh_token,
},
)
self._abort_if_unique_id_configured()
return self.async_create_entry(...)
```
This is verbatim the pattern Home Assistant's developer documentation prescribes for flows whose steps are shared between `user` and `reauth` sources. `data_updates` merges into the existing entry data, so `CONF_EMAIL` and `CONF_MACHINE_ID` survive untouched. `async_update_reload_and_abort` reloads the entry and aborts with `reauth_successful` by default, which is exactly the desired terminal state and is already translated in `strings.json`.
*Alternative considered — a separate reauth-specific token step.* Duplicating the authenticate/profile/error-handling block into `async_step_reauth_token` would avoid the source check, but it clones roughly forty lines of error handling that must then stay in sync across two paths. The bug being fixed here is precisely a divergence between setup and reauth expectations; duplicating the code invites the next one.
*Alternative considered — hand-rolled entry update for pre-2024.11 compatibility.* `self.hass.config_entries.async_get_entry(self.context["entry_id"])`, a manual unique-ID comparison, `async_update_entry`, `async_reload`, and `self.async_abort(reason="reauth_successful")` reproduce the helpers' behaviour on older cores. Rejected: it is more code, it is the pattern HA explicitly deprecated in favour of the helpers, and 2024.11 shipped in November 2024 — a floor that is nearly two years old.
### Decision 2: Declare `"homeassistant": "2024.11.0"` in `hacs.json`
`_get_reauth_entry`, `_abort_if_unique_id_mismatch`, and the `data_updates` parameter of `async_update_reload_and_abort` all landed in Home Assistant Core 2024.11. The repo currently declares no minimum core version anywhere, so on an older core the fix would fail with an `AttributeError` mid-flow — a worse failure than the bug it replaces. HACS reads the `homeassistant` key and blocks installation below that floor, turning a runtime crash into an install-time message.
Note this belongs in `hacs.json`, not `manifest.json`: integration manifests have no minimum-core-version field.
### Decision 3: Custom abort reason `reauth_account_mismatch` over the default
`_abort_if_unique_id_mismatch()` defaults to reason `unique_id_mismatch`. Either reason needs a corresponding entry under `config.abort` in `strings.json` and `translations/en.json`, since custom components cannot use core's `[%key:common::...]` translation references. Given a string must be written regardless, the specific reason carries the actionable message — the user re-entered a different account's email and needs to use the original one, or delete the entry and add the new account fresh.
### Decision 4: Test with `pytest-homeassistant-custom-component`
Config-flow behaviour cannot be verified without instantiating Home Assistant: the failure is in `ConfigFlow` helper interaction, not in any extractable pure function. `pytest-homeassistant-custom-component` is the standard harness for custom integrations and provides `hass`, `MockConfigEntry`, and the flow-driving helpers needed to assert on abort reasons and post-flow entry data.
This adds the repo's first dev dependency. It goes in a new `requirements-test.txt` so the runtime component stays dependency-free (`manifest.json` keeps `"requirements": []`), and the existing stdlib-only `test_keg_detection.py` continues to run under plain `python3 -m unittest` for anyone who does not install the harness.
The harness version must be pinned to match a core version at or above the 2024.11 floor; `pytest-homeassistant-custom-component` releases track core releases one-to-one.
*Alternative considered — stubbing HA modules with `unittest.mock`.* Cheap, no dependency, and worthless here: the bug lives in the real behaviour of `_abort_if_unique_id_configured` against a real config entry registry. A stub would encode our assumption about that helper rather than test it, and would have passed against the broken code.
### Decision 5: Keep the profile lookup conditional on a missing machine ID
Reauth currently re-fetches `/api/me` to extract the machine ID, then discards it in the abort. Since `data_updates` preserves the stored `CONF_MACHINE_ID`, the call is redundant on the reauth path whenever the entry already has one. Skipping it removes a network round trip from a flow the user is actively waiting on, and removes a failure mode where a transient `/api/me` error turns a successful authentication into `cannot_connect`. The lookup is retained when the entry has no machine ID recorded, which keeps the reauth path capable of healing an entry that was created before a machine was registered.
## Risks / Trade-offs
**The 2024.11 floor excludes users on older cores.** → Two years of core releases is a generous floor for an integration whose current release is 0.3.0, and HACS surfaces the requirement at install time rather than as a runtime crash. Users below it are already missing security fixes.
**`self.source` is unreliable if a step is reached by an unanticipated route.** → The flow has exactly three entry points, all enumerated above, and `SOURCE_REAUTH` is set by Home Assistant itself when it starts the repair. The `else` branch retains `_abort_if_unique_id_configured()`, so any unforeseen source keeps today's conservative duplicate-prevention behaviour rather than silently overwriting an entry.
**Email case sensitivity determines whether the mismatch guard fires correctly.** → `async_set_unique_id(self._email.lower())` already normalises, and the stored unique ID was written by the same expression at setup time. The reauth form pre-fills the stored email, so the common path compares identical strings. A test asserting that a differently-cased re-entry of the *same* address is accepted pins this down.
**Adding a test dependency risks breaking the existing lightweight test run.** → `requirements-test.txt` is opt-in and `test_keg_detection.py` keeps its stdlib-only imports, so `python3 -m unittest discover -s tests` continues to work standalone. Verification during implementation must confirm both runners pass.
## Migration Plan
No data migration. The config entry schema is unchanged — `VERSION` stays 1 and `async_migrate_entry` is untouched — because only the *values* of the token fields are refreshed.
Deployment is a normal integration update. Users currently stuck in the reauth loop recover by re-running reauth after updating; no delete-and-re-add is required, and entity history plus the keg-freshness baseline are preserved. Rollback is reverting the commit: it restores the bug but corrupts nothing, since entries written by the fixed code are schema-identical to entries written by the broken code.
## Open Questions
None blocking. The one deferred item — persisting Cognito-refreshed tokens back to the config entry — is recorded in the proposal's Impact section for a separate change.
@@ -0,0 +1,33 @@
## Why
Re-authentication is broken. When the coordinator raises `ConfigEntryAuthFailed`, Home Assistant starts a reauth flow; the user re-enters credentials and a fresh verification token, authentication against the PerfectDraft API succeeds — and then the flow aborts with `already_configured`. The freshly minted tokens are thrown away, the config entry keeps its expired tokens, and HA immediately re-raises the "please re-authenticate" repair. The integration is unrecoverable through the UI: the only way back is to delete and re-add the entry, losing entity history and the restored keg-freshness baseline.
Root cause: `async_step_reauth_confirm` delegates to `async_step_token`, which is written exclusively for the initial-setup path. It unconditionally calls `async_set_unique_id(email)` followed by `_abort_if_unique_id_configured()` and then `async_create_entry()`. During reauth the unique ID *is* already configured — by the very entry being repaired — so the duplicate guard fires by design and the flow dies before it can persist anything.
## What Changes
- `async_step_token` becomes reauth-aware: on a successful authentication it either creates a new entry (initial setup, unchanged behaviour) or updates the existing entry and reloads it (reauth).
- On the reauth path, the duplicate-prevention guard `_abort_if_unique_id_configured()` is replaced by an identity guard that verifies the re-entered email still resolves to the entry under repair, so signing in with a *different* account during reauth is rejected rather than silently rebinding the entry.
- Successful reauth writes the new access, ID, and refresh tokens into the existing entry's data, preserves the already-discovered machine ID, reloads the entry, and aborts with `reauth_successful`.
- Reauth no longer re-derives the machine ID unnecessarily; the profile lookup is only needed when the entry has no machine ID recorded.
- One new abort string (`reauth_account_mismatch`) is added to `strings.json` and `translations/en.json` to explain the account-mismatch rejection. `reauth_successful` and `already_configured` already exist.
- Regression tests cover the reauth path so the `already_configured` abort cannot silently return.
## Capabilities
### New Capabilities
None. This change fixes behaviour already specified.
### Modified Capabilities
- `config-flow`: the existing "Reauth flow" requirement asserts that "on success, the config entry SHALL be updated with new tokens" — behaviour the implementation never had. The requirement is tightened into testable scenarios covering token persistence, entry reload, account-mismatch rejection, and the explicit prohibition on aborting with `already_configured` during reauth. The "Unique ID prevents duplicates" requirement is scoped to the user-initiated setup path so it no longer reads as applying to reauth.
## Impact
- `custom_components/perfectdraft/config_flow.py` — `async_step_token`, `async_step_reauth`, `async_step_reauth_confirm`.
- `custom_components/perfectdraft/strings.json` and `translations/en.json` — one new abort string.
- `hacs.json` — the fix uses config-flow helpers (`_get_reauth_entry`, `_abort_if_unique_id_mismatch`, `async_update_reload_and_abort` with `data_updates`) introduced in Home Assistant Core 2024.11, so a minimum core version is declared rather than left implicit.
- `tests/` — new test module for the config flow. Existing tests are stdlib-only (`test_keg_detection.py` imports the HA-free `keg_detection` module); config-flow tests need Home Assistant plus `pytest-homeassistant-custom-component`, so the test approach is a design decision, not a given.
- No API client, coordinator, or entity changes. No config entry version bump: the data schema is unchanged, only its contents are refreshed.
- Out of scope, noted while investigating: `PerfectDraftApiClient.refresh_access_token()` updates tokens in memory only and never writes them back to the config entry, so every HA restart burns one wasted 401-plus-refresh round trip. Harmless today because the Cognito refresh token is what actually gates reauth, and it is unchanged by a refresh. Tracked separately rather than bundled here.
@@ -0,0 +1,87 @@
## MODIFIED Requirements
### Requirement: Unique ID prevents duplicates
The config flow SHALL set a unique ID based on the lowercased user email. On the user-initiated setup path the flow SHALL abort when that unique ID already belongs to a configured entry. This duplicate guard SHALL NOT be applied on the reauth path, where a matching unique ID is the expected condition rather than a conflict.
#### Scenario: Duplicate prevention on user setup
- **WHEN** a user attempts to add the integration with an email that is already configured
- **THEN** the config flow SHALL abort with reason `already_configured`
#### Scenario: Unique ID normalisation
- **WHEN** the unique ID is set from a submitted email
- **THEN** it SHALL be the lowercased email, so that the same account entered with different capitalisation resolves to the same unique ID
#### Scenario: Duplicate guard not applied during reauth
- **WHEN** the flow reaches the token step with source `reauth`
- **THEN** the flow SHALL NOT abort with reason `already_configured`
### Requirement: Reauth flow
The integration SHALL support Home Assistant's reauth mechanism when the refresh token expires. A successful reauth SHALL update the existing config entry in place, reload it, and abort with `reauth_successful`. It SHALL NOT create a second config entry, and it SHALL NOT abort with `already_configured`.
#### Scenario: Reauth triggered
- **WHEN** the coordinator raises `ConfigEntryAuthFailed` because token refresh has failed
- **THEN** Home Assistant SHALL start a reauth flow for the affected entry
- **THEN** the flow SHALL show the `reauth_confirm` form pre-filled with the stored email
- **THEN** submitting credentials SHALL advance to the token step
#### Scenario: Reauth succeeds and persists new tokens
- **WHEN** the user submits a valid verification token during reauth and authentication succeeds
- **THEN** the existing config entry's access token, ID token, and refresh token SHALL be replaced with the newly issued values
- **THEN** the entry's stored email and machine ID SHALL be preserved unchanged
- **THEN** the entry SHALL be reloaded
- **THEN** the flow SHALL abort with reason `reauth_successful`
- **THEN** no additional config entry SHALL be created
#### Scenario: Reauth does not abort as already configured
- **WHEN** reauth authentication succeeds for the same account as the entry under repair
- **THEN** the flow SHALL NOT abort with reason `already_configured`
- **THEN** the "authentication failed, please re-authenticate" condition SHALL clear once the reloaded entry polls successfully
#### Scenario: Reauth with a different account is rejected
- **WHEN** the user submits credentials during reauth for an email whose lowercased value differs from the entry's unique ID, and authentication succeeds
- **THEN** the flow SHALL abort with reason `reauth_account_mismatch`
- **THEN** the existing config entry's tokens SHALL be left unchanged
#### Scenario: Reauth accepts the same account in different letter case
- **WHEN** the user re-enters the entry's email with different capitalisation during reauth
- **THEN** the flow SHALL treat it as the same account and complete successfully
#### Scenario: Reauth authentication fails
- **WHEN** the verification token is expired or the credentials are wrong during reauth
- **THEN** the flow SHALL show the `invalid_auth` error on the token form and allow retry with a fresh token
- **THEN** the existing config entry's tokens SHALL be left unchanged
#### Scenario: Machine ID lookup is skipped when already known
- **WHEN** reauth authentication succeeds and the existing entry already records a machine ID
- **THEN** the flow SHALL NOT call the user profile endpoint
- **THEN** the entry SHALL retain its recorded machine ID
#### Scenario: Machine ID recovered when absent
- **WHEN** reauth authentication succeeds and the existing entry has no machine ID recorded
- **THEN** the flow SHALL fetch the user profile and store the discovered machine ID on the entry
## ADDED Requirements
### Requirement: Minimum Home Assistant core version is declared
The integration SHALL declare a minimum supported Home Assistant core version of 2024.11.0 in `hacs.json`, because the config flow depends on reauth helpers introduced in that release.
#### Scenario: Installation on an unsupported core
- **WHEN** a user attempts to install the integration through HACS on a core older than 2024.11.0
- **THEN** HACS SHALL refuse the installation and report the minimum version, rather than allowing an install that fails at runtime
### Requirement: All abort reasons are translated
Every abort reason the config flow can emit SHALL have a corresponding entry under `config.abort` in `strings.json` and `translations/en.json`, so no user ever sees an untranslated reason key. The set of reasons SHALL be derived from the flow's source rather than maintained by hand, so that a newly reachable abort cannot ship untranslated.
#### Scenario: Mismatch message is rendered
- **WHEN** the reauth flow aborts with reason `reauth_account_mismatch`
- **THEN** the dialog SHALL render a translated message explaining that the credentials belong to a different account than the one being re-authenticated
#### Scenario: Concurrent flow for the same account is rejected
- **WHEN** a reauth flow is pending for an entry and the user starts a user-initiated setup for the same email
- **THEN** the second flow SHALL abort with reason `already_in_progress`
- **THEN** that reason SHALL render a translated message telling the user to finish or cancel the pending flow
#### Scenario: Abort reasons are enumerated from the source
- **WHEN** the translation coverage check runs
- **THEN** it SHALL enumerate abort reasons by inspecting the calls `config_flow.py` makes to aborting flow helpers, including reasons those helpers raise by default
- **THEN** it SHALL fail if any enumerated reason is absent from either translation file
+81
View File
@@ -0,0 +1,81 @@
## 1. Isolate the work
- [x] 1.1 Create the agent worktree and branch: `scripts/agent-worktree.sh create fix-reauth-flow master`
- [x] 1.2 Confirm `.agent-lock` exists in `.worktree/fix-reauth-flow` and records this task
- [x] 1.3 Confirm the worktree base includes merge commit `3b69942` (PR #2 mirrored to both remotes)
## 2. Test harness
- [x] 2.1 Add `requirements-test.txt` pinning `pytest-homeassistant-custom-component==0.13.205` (newest release still supporting Python 3.12; pins core 2025.1.4, above the 2024.11 floor). Also pins `pycares==4.5.0` — core pins `aiodns==3.2.0` but leaves pycares floating, and pycares 4.6+ starts a daemon shutdown thread that the harness's `verify_cleanup` fixture flags as a leak, erroring every test at teardown.
- [x] 2.2 Add `tests/conftest.py` enabling custom integrations (the `auto_enable_custom_integrations` fixture) so `custom_components/perfectdraft` is loadable by the `hass` fixture
- [x] 2.3 Add `pytest.ini` with `asyncio_mode = auto` and `pythonpath = .` so `custom_components` is importable; confirm `pytest tests/` collects
- [x] 2.4 Confirm `python3 -m unittest discover -s tests` still passes standalone. Required guarding the Home Assistant imports in `test_config_flow.py` with a `unittest.SkipTest` raised on `ImportError` — unittest converts that into a skip rather than a collection error. Result: 11 passed, 1 skipped.
## 3. Failing regression tests
Write these against the current broken code first and watch them fail for the right reason — an `already_configured` abort, not an import or fixture error.
- [x] 3.1 `tests/test_config_flow.py`: reauth with a valid token updates the existing entry's access, ID, and refresh tokens
- [x] 3.2 Same test asserts the entry's email and machine ID are unchanged and that `hass.config_entries.async_entries(DOMAIN)` still has length 1
- [x] 3.3 Assert the reauth flow's result type is `ABORT` with reason `reauth_successful`, and explicitly assert the reason is not `already_configured`
- [x] 3.4 Reauth with a different account's email aborts with `reauth_account_mismatch` and leaves the stored tokens untouched
- [x] 3.5 Reauth re-entering the same email in different capitalisation succeeds
- [x] 3.6 Reauth with a rejected token shows the `invalid_auth` error on the token form and leaves the stored tokens untouched
- [x] 3.7 Reauth does not call the user profile endpoint when the entry already records a machine ID
- [x] 3.8 Reauth fetches the profile and stores the machine ID when the entry has none
- [x] 3.9 Initial user setup still creates an entry, and a second setup with an already-configured email still aborts with `already_configured`
Confirmed failing against unfixed code: 8 failed, 7 passed. The headline assertion failed as `assert 'already_configured' != 'already_configured'` — the reported bug, reproduced exactly.
## 4. Implement the fix
- [x] 4.1 Reference `SOURCE_REAUTH` as `config_entries.SOURCE_REAUTH` rather than adding a bare import — the module already qualifies every other `config_entries` symbol, so this matches existing style and adds no import line
- [x] 4.2 In `async_step_token`, replace the unconditional `_abort_if_unique_id_configured()` + `async_create_entry()` terminal block with the source-aware branch from design Decision 1
- [x] 4.3 On the reauth branch, call `_abort_if_unique_id_mismatch(reason="reauth_account_mismatch")` then `async_update_reload_and_abort(reauth_entry, data_updates={...})`. Extracted into `_async_persist()` because both the machine-ID-known and machine-ID-recovered paths terminate through it.
- [x] 4.4 Make the machine ID lookup conditional: skip `get_user_profile()` when the source is reauth and the entry already has `CONF_MACHINE_ID`; otherwise fetch as today and include it in the data written
- [x] 4.5 Confirm the non-reauth branch is behaviourally identical to today's setup path (guarded by tasks 3.9 and the connection-error test)
## 5. Strings and packaging
- [x] 5.1 Add `reauth_account_mismatch` under `config.abort` in `custom_components/perfectdraft/strings.json`
- [x] 5.2 Mirror the same key and message into `custom_components/perfectdraft/translations/en.json`
- [x] 5.3 Cross-check that every abort reason reachable from `config_flow.py` (`already_configured`, `reauth_successful`, `reauth_account_mismatch`) is present in both files — enforced by a parametrised test, not just inspection
- [x] 5.4 Add `"homeassistant": "2024.11.0"` to `hacs.json`
- [x] 5.5 Set `version` in `manifest.json` to `0.3.1`. Note the merged PR #2 had bumped it to `0.4.0`; no `v0.4.0` tag exists on either remote, so nothing was ever released under that number and stepping down to `0.3.1` breaks no HACS update path.
- [x] 5.6 Verify `strings.json`, `translations/en.json`, `hacs.json`, and `manifest.json` all still parse as JSON
- [x] 5.7 Add `.venv-test/` and `.pytest_cache/` to `.gitignore`
## 6. Verify
- [x] 6.1 All tests from section 3 pass: 26 passed (15 config flow + 11 keg detection)
- [x] 6.2 `python3 -m unittest discover -s tests` still passes: 11 passed, 1 skipped
- [x] 6.3 `python3 -m compileall -q custom_components/perfectdraft/` is clean
- [ ] 6.4 On-device: install the branch on the live HA instance, forge an expired session by editing `access_token`/`refresh_token` in `config/.storage/core.config_entries`, restart, and confirm the reauth repair appears
- [ ] 6.5 On-device: complete the reauth flow with a fresh verification token and confirm it ends on "Re-authentication successful" — not "already configured"
- [ ] 6.6 On-device: confirm the integration polls successfully afterwards, entity history is continuous, and the keg-freshness baseline survived (no reset to unknown)
- [ ] 6.7 On-device: confirm entering a different account's email during reauth is rejected with the mismatch message
## 7. Close out
- [x] 7.1 Commit on `agent/fix-reauth-flow` with a message explaining why `_abort_if_unique_id_configured` was the wrong helper for the reauth source
- [x] 7.2 Merge into `master` from the main checkout
- [x] 7.3 Push `master` to `origin` (git.falkvinge.net) and to `github` so both remotes stay at parity
- [x] 7.4 Sync the delta spec into `openspec/specs/config-flow/spec.md` to reflect what was actually built
- [ ] 7.5 Archive: `mv openspec/changes/fix-reauth-flow openspec/changes/archive/<YYYY-MM-DD>-fix-reauth-flow` — held until on-device verification (6.4–6.7) confirms the fix on the live machine
- [ ] 7.6 Remove the worktree and branch: `git worktree remove .worktree/fix-reauth-flow --force && git branch -d agent/fix-reauth-flow` — held with 7.5
- [x] 7.7 Record the deferred item (persisting Cognito-refreshed tokens back to the config entry) as a TODO in `PROJECT_HYGIENE.md` section 11
## 8. Verification follow-up (found by `openspec-verify-change`)
Verification found the change violating its own "every abort reason is translated" requirement. `async_set_unique_id()` defaults to `raise_on_progress=True` and raises `already_in_progress` when another flow holds the same unique ID — reachable when a user parks a reauth flow and then tries Add Integration for the same account. Task 5.3's test hardcoded three reasons, so it asserted a "for every" requirement against a hand-written list and passed regardless.
- [x] 8.1 Confirm reachability empirically rather than by reading HA source: park a reauth flow, start a user flow for the same email, observe the abort reason
- [x] 8.2 Add `already_in_progress` to `strings.json` and `translations/en.json`
- [x] 8.3 Replace the hardcoded reason list with an AST scan of `config_flow.py` that resolves each aborting helper call to the reason it raises, honouring explicit `reason=` and the `raise_on_progress=False` opt-out
- [x] 8.4 Add a scanner sanity test, so a scanner that silently stops finding reasons fails instead of passing
- [x] 8.5 Add a regression test for the concurrent-flow abort path itself
- [x] 8.6 Confirm the new check fails against the pre-fix translation files and passes after
- [x] 8.7 Update the delta spec and main spec: rename the requirement to "All abort reasons are translated" and add the two new scenarios
- [ ] 8.8 On-device: confirm the `already_in_progress` dialog renders the message rather than the raw key
Still open from verification, not blocking archive: the `reauth_confirm` email pre-fill and unique-ID lowercasing at setup are implemented and manually confirmed but unasserted; a mismatched-account reauth on an entry with no recorded machine ID makes one wasted `/api/me` call before aborting.
+76 -8
View File
@@ -32,20 +32,88 @@ The config flow SHALL present a form requesting a reCAPTCHA verification token a
- **THEN** the flow SHALL show a connection error
### Requirement: Unique ID prevents duplicates
The config flow SHALL set a unique ID based on the user's email to prevent duplicate integrations.
The config flow SHALL set a unique ID based on the lowercased user email. On the user-initiated setup path the flow SHALL abort when that unique ID already belongs to a configured entry. This duplicate guard SHALL NOT be applied on the reauth path, where a matching unique ID is the expected condition rather than a conflict.
#### Scenario: Duplicate prevention
#### Scenario: Duplicate prevention on user setup
- **WHEN** a user attempts to add the integration with an email that is already configured
- **THEN** the config flow SHALL abort
- **THEN** the config flow SHALL abort with reason `already_configured`
#### Scenario: Unique ID normalisation
- **WHEN** the unique ID is set from a submitted email
- **THEN** it SHALL be the lowercased email, so that the same account entered with different capitalisation resolves to the same unique ID
#### Scenario: Duplicate guard not applied during reauth
- **WHEN** the flow reaches the token step with source `reauth`
- **THEN** the flow SHALL NOT abort with reason `already_configured`
### Requirement: Reauth flow
The integration SHALL support HA's reauth mechanism when the refresh token expires.
The integration SHALL support Home Assistant's reauth mechanism when the refresh token expires. A successful reauth SHALL update the existing config entry in place, reload it, and abort with `reauth_successful`. It SHALL NOT create a second config entry, and it SHALL NOT abort with `already_configured`.
#### Scenario: Reauth triggered
- **WHEN** the coordinator detects that token refresh has failed
- **THEN** HA SHALL prompt the user to re-authenticate
- **THEN** the reauth flow SHALL collect email, password, and a fresh token
- **THEN** on success, the config entry SHALL be updated with new tokens
- **WHEN** the coordinator raises `ConfigEntryAuthFailed` because token refresh has failed
- **THEN** Home Assistant SHALL start a reauth flow for the affected entry
- **THEN** the flow SHALL show the `reauth_confirm` form pre-filled with the stored email
- **THEN** submitting credentials SHALL advance to the token step
#### Scenario: Reauth succeeds and persists new tokens
- **WHEN** the user submits a valid verification token during reauth and authentication succeeds
- **THEN** the existing config entry's access token, ID token, and refresh token SHALL be replaced with the newly issued values
- **THEN** the entry's stored email and machine ID SHALL be preserved unchanged
- **THEN** the entry SHALL be reloaded
- **THEN** the flow SHALL abort with reason `reauth_successful`
- **THEN** no additional config entry SHALL be created
#### Scenario: Reauth does not abort as already configured
- **WHEN** reauth authentication succeeds for the same account as the entry under repair
- **THEN** the flow SHALL NOT abort with reason `already_configured`
- **THEN** the "authentication failed, please re-authenticate" condition SHALL clear once the reloaded entry polls successfully
#### Scenario: Reauth with a different account is rejected
- **WHEN** the user submits credentials during reauth for an email whose lowercased value differs from the entry's unique ID, and authentication succeeds
- **THEN** the flow SHALL abort with reason `reauth_account_mismatch`
- **THEN** the existing config entry's tokens SHALL be left unchanged
#### Scenario: Reauth accepts the same account in different letter case
- **WHEN** the user re-enters the entry's email with different capitalisation during reauth
- **THEN** the flow SHALL treat it as the same account and complete successfully
#### Scenario: Reauth authentication fails
- **WHEN** the verification token is expired or the credentials are wrong during reauth
- **THEN** the flow SHALL show the `invalid_auth` error on the token form and allow retry with a fresh token
- **THEN** the existing config entry's tokens SHALL be left unchanged
#### Scenario: Machine ID lookup is skipped when already known
- **WHEN** reauth authentication succeeds and the existing entry already records a machine ID
- **THEN** the flow SHALL NOT call the user profile endpoint
- **THEN** the entry SHALL retain its recorded machine ID
#### Scenario: Machine ID recovered when absent
- **WHEN** reauth authentication succeeds and the existing entry has no machine ID recorded
- **THEN** the flow SHALL fetch the user profile and store the discovered machine ID on the entry
### Requirement: Minimum Home Assistant core version is declared
The integration SHALL declare a minimum supported Home Assistant core version of 2024.11.0 in `hacs.json`, because the config flow depends on reauth helpers introduced in that release.
#### Scenario: Installation on an unsupported core
- **WHEN** a user attempts to install the integration through HACS on a core older than 2024.11.0
- **THEN** HACS SHALL refuse the installation and report the minimum version, rather than allowing an install that fails at runtime
### Requirement: All abort reasons are translated
Every abort reason the config flow can emit SHALL have a corresponding entry under `config.abort` in `strings.json` and `translations/en.json`, so no user ever sees an untranslated reason key. The set of reasons SHALL be derived from the flow's source rather than maintained by hand, so that a newly reachable abort cannot ship untranslated.
#### Scenario: Mismatch message is rendered
- **WHEN** the reauth flow aborts with reason `reauth_account_mismatch`
- **THEN** the dialog SHALL render a translated message explaining that the credentials belong to a different account than the one being re-authenticated
#### Scenario: Concurrent flow for the same account is rejected
- **WHEN** a reauth flow is pending for an entry and the user starts a user-initiated setup for the same email
- **THEN** the second flow SHALL abort with reason `already_in_progress`
- **THEN** that reason SHALL render a translated message telling the user to finish or cancel the pending flow
#### Scenario: Abort reasons are enumerated from the source
- **WHEN** the translation coverage check runs
- **THEN** it SHALL enumerate abort reasons by inspecting the calls `config_flow.py` makes to aborting flow helpers, including reasons those helpers raise by default
- **THEN** it SHALL fail if any enumerated reason is absent from either translation file
### Requirement: Options flow for polling interval
The integration SHALL provide an OptionsFlow to change the polling interval.
+38 -3
View File
@@ -78,12 +78,29 @@ The integration SHALL expose the firmware version, disabled by default.
- **THEN** the entity SHALL be disabled by default in the entity registry
### Requirement: Keg freshness sensor
The integration SHALL track keg freshness as a 30-day countdown from insertion, detected client-side and persisted across restarts.
The integration SHALL track keg freshness as a 30-day countdown from insertion, detected client-side and persisted across restarts. A keg change SHALL be detected by monitoring the coordinator data for a pour-count reset OR an upward jump in keg volume between consecutive readings, so that a swap is recognized even when the pour count never reads 0 (e.g. the user pours immediately after swapping).
#### Scenario: New keg detected
#### Scenario: New keg detected via pour reset
- **WHEN** `details.numberOfPoursSinceStartup` is 0 AND `details.kegVolume` is greater than 5.5L AND the previous pour count was not 0
- **THEN** the sensor SHALL record the current UTC timestamp as the keg insertion date
#### Scenario: New keg detected via refill to near-full
- **WHEN** a previous volume reading exists AND the previous remaining volume was below 80% of capacity AND the current remaining volume is at least 95% of capacity
- **THEN** the sensor SHALL record the current UTC timestamp as the keg insertion date
#### Scenario: New keg detected via large volume jump
- **WHEN** a previous volume reading exists AND the current remaining volume exceeds the previous remaining volume by at least 50 percentage points of capacity (a gain of at least 3.0L)
- **THEN** the sensor SHALL record the current UTC timestamp as the keg insertion date
#### Scenario: No false trigger on first reading
- **WHEN** the integration produces its first volume reading after install or restart and no previous volume reading is available
- **THEN** the volume-jump triggers SHALL NOT fire
#### Scenario: Detection never moves the date backward
- **WHEN** any detection trigger fires
- **THEN** the sensor SHALL set the insertion date to the current time only
- **THEN** the sensor SHALL update its tracked previous pour count and previous volume to the current readings so the same event does not re-trigger on the next update
#### Scenario: Freshness countdown
- **WHEN** a keg insertion date is known
- **THEN** the sensor SHALL report `30 - days_since_insertion`, minimum 0
@@ -95,7 +112,25 @@ The integration SHALL track keg freshness as a 30-day countdown from insertion,
#### Scenario: HA restart
- **WHEN** Home Assistant restarts
- **THEN** the sensor SHALL restore the keg insertion date and last pour count from the previous session's state attributes
- **THEN** the sensor SHALL restore the keg insertion date, last pour count, and last volume from the previous session's state attributes
### Requirement: Manual keg-change button
The integration SHALL expose a button entity that, when pressed, records the current time as the keg insertion date, providing a deterministic manual override for keg-change detection.
#### Scenario: Button press records insertion
- **WHEN** the user presses the "Mark Keg Changed" button
- **THEN** the keg freshness sensor SHALL set the keg insertion date to the current UTC timestamp
- **THEN** the freshness countdown SHALL report 30 days
#### Scenario: Override rebaselines detection
- **WHEN** the button is pressed
- **THEN** the sensor SHALL update its tracked previous pour count and previous volume to the latest readings so automatic detection does not immediately re-fire
#### Scenario: Button entity presentation
- **WHEN** entities are created
- **THEN** the integration SHALL register the `button` platform
- **THEN** the button SHALL belong to the same device as the machine's sensors
- **THEN** the button SHALL have a stable unique ID following the `{machine_id}_{entity_key}` pattern and a translated name "Mark Keg Changed"
### Requirement: Entity unique IDs
All entities SHALL have stable unique IDs derived from the machine ID and entity type.
+5
View File
@@ -0,0 +1,5 @@
[pytest]
testpaths = tests
pythonpath = .
asyncio_mode = auto
asyncio_default_fixture_loop_scope = function
+18
View File
@@ -0,0 +1,18 @@
# Test-only dependencies. The integration itself stays dependency-free
# (manifest.json keeps "requirements": []); this harness exists because
# config-flow behaviour cannot be exercised without a real Home Assistant.
#
# pytest-homeassistant-custom-component releases track core one-to-one.
# 0.13.205 is the newest release that still supports Python 3.12 and it
# pins core 2025.1.4 — above the 2024.11 floor the reauth helpers need.
#
# python3 -m venv .venv-test
# .venv-test/bin/pip install -r requirements-test.txt
# .venv-test/bin/pytest tests/
pytest-homeassistant-custom-component==0.13.205
# Core pins aiodns==3.2.0 but leaves pycares floating. pycares 4.6+ starts a
# daemon shutdown thread that the harness's verify_cleanup fixture flags as a
# leak, failing every test at teardown. 4.5.0 is contemporaneous with core
# 2025.1.4 and has no such thread.
pycares==4.5.0
+15
View File
@@ -0,0 +1,15 @@
"""Fixtures for the Home Assistant test harness.
Only the pytest suite uses this. ``test_keg_detection.py`` imports the
Home-Assistant-free ``keg_detection`` module and still runs standalone under
``python3 -m unittest discover -s tests``.
"""
import pytest
pytest_plugins = "pytest_homeassistant_custom_component"
@pytest.fixture(autouse=True)
def auto_enable_custom_integrations(enable_custom_integrations):
"""Make custom_components/perfectdraft loadable in every test."""
yield
+385
View File
@@ -0,0 +1,385 @@
"""Config flow tests, focused on the reauth path.
The bug these guard against: ``async_step_token`` is shared by the user and
reauth sources, and used to call ``_abort_if_unique_id_configured()``
unconditionally. During reauth the unique ID belongs to the entry being
repaired, so the duplicate guard aborted the flow with ``already_configured``
and the freshly issued tokens were discarded.
"""
import ast
import json
import unittest
from pathlib import Path
from unittest.mock import AsyncMock, patch
try:
import pytest
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_EMAIL, CONF_PASSWORD
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from pytest_homeassistant_custom_component.common import MockConfigEntry
from custom_components.perfectdraft.const import (
CONF_ACCESS_TOKEN,
CONF_ID_TOKEN,
CONF_MACHINE_ID,
CONF_REFRESH_TOKEN,
DOMAIN,
)
from custom_components.perfectdraft.exceptions import (
AuthenticationError,
PerfectDraftConnectionError,
)
except ImportError as err:
# Keeps `python3 -m unittest discover -s tests` working for anyone who
# only wants the stdlib-only keg-detection tests: unittest turns a
# SkipTest raised during import into a skip rather than an error.
raise unittest.SkipTest(
"Home Assistant test harness missing "
"(pip install -r requirements-test.txt)"
) from err
EMAIL = "drinker@example.com"
PASSWORD = "hunter2"
TOKEN = "recaptcha-token"
MACHINE_ID = "machine-1"
CLIENT_PATH = "custom_components.perfectdraft.config_flow.PerfectDraftApiClient"
SETUP_PATH = "custom_components.perfectdraft.async_setup_entry"
STORED_DATA = {
CONF_EMAIL: EMAIL,
CONF_ACCESS_TOKEN: "old-access",
CONF_ID_TOKEN: "old-id",
CONF_REFRESH_TOKEN: "old-refresh",
CONF_MACHINE_ID: MACHINE_ID,
}
def _mock_client(*, authenticate_error=None, machines=((MACHINE_ID,))):
"""An API client that hands back recognisably new tokens."""
client = AsyncMock()
client.access_token = "new-access"
client.id_token = "new-id"
client.refresh_token = "new-refresh"
if authenticate_error is not None:
client.authenticate.side_effect = authenticate_error
client.get_user_profile.return_value = {
"perfectdraftMachines": [{"id": m} for m in machines]
}
return client
def _entry(hass: HomeAssistant, data=None, unique_id=EMAIL) -> MockConfigEntry:
entry = MockConfigEntry(
domain=DOMAIN,
unique_id=unique_id,
data=dict(STORED_DATA if data is None else data),
title=f"PerfectDraft ({EMAIL})",
)
entry.add_to_hass(hass)
return entry
async def _run_reauth(hass, entry, client, *, email=EMAIL, token=TOKEN):
"""Drive reauth_confirm then token, returning the final flow result."""
with (
patch(CLIENT_PATH, return_value=client),
patch(SETUP_PATH, return_value=True),
):
result = await entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_EMAIL: email, CONF_PASSWORD: PASSWORD}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "token"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"recaptcha_token": token}
)
await hass.async_block_till_done()
return result
# --- Reauth: the regression this change fixes ---
async def test_reauth_persists_new_tokens(hass: HomeAssistant) -> None:
entry = _entry(hass)
result = await _run_reauth(hass, entry, _mock_client())
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert entry.data[CONF_ACCESS_TOKEN] == "new-access"
assert entry.data[CONF_ID_TOKEN] == "new-id"
assert entry.data[CONF_REFRESH_TOKEN] == "new-refresh"
async def test_reauth_preserves_email_and_machine_id(hass: HomeAssistant) -> None:
entry = _entry(hass)
await _run_reauth(hass, entry, _mock_client())
assert entry.data[CONF_EMAIL] == EMAIL
assert entry.data[CONF_MACHINE_ID] == MACHINE_ID
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
async def test_reauth_never_aborts_as_already_configured(hass: HomeAssistant) -> None:
"""The exact failure reported: auth succeeds, then the flow dies here."""
entry = _entry(hass)
result = await _run_reauth(hass, entry, _mock_client())
assert result["reason"] != "already_configured"
assert result["reason"] == "reauth_successful"
async def test_reauth_reloads_the_entry(hass: HomeAssistant) -> None:
entry = _entry(hass)
client = _mock_client()
with (
patch(CLIENT_PATH, return_value=client),
patch(SETUP_PATH, return_value=True) as mock_setup,
):
result = await entry.start_reauth_flow(hass)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_EMAIL: EMAIL, CONF_PASSWORD: PASSWORD}
)
await hass.config_entries.flow.async_configure(
result["flow_id"], {"recaptcha_token": TOKEN}
)
await hass.async_block_till_done()
assert mock_setup.call_count == 1
async def test_reauth_rejects_a_different_account(hass: HomeAssistant) -> None:
entry = _entry(hass)
result = await _run_reauth(
hass, entry, _mock_client(), email="someone.else@example.com"
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_account_mismatch"
assert entry.data[CONF_ACCESS_TOKEN] == "old-access"
assert entry.data[CONF_REFRESH_TOKEN] == "old-refresh"
async def test_reauth_accepts_same_account_different_case(
hass: HomeAssistant,
) -> None:
entry = _entry(hass)
result = await _run_reauth(hass, entry, _mock_client(), email="Drinker@Example.COM")
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert entry.data[CONF_ACCESS_TOKEN] == "new-access"
async def test_reauth_bad_token_keeps_old_tokens(hass: HomeAssistant) -> None:
entry = _entry(hass)
client = _mock_client(authenticate_error=AuthenticationError("token expired"))
result = await _run_reauth(hass, entry, client)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "token"
assert result["errors"] == {"base": "invalid_auth"}
assert entry.data[CONF_ACCESS_TOKEN] == "old-access"
assert entry.data[CONF_REFRESH_TOKEN] == "old-refresh"
async def test_reauth_skips_profile_when_machine_id_known(
hass: HomeAssistant,
) -> None:
entry = _entry(hass)
client = _mock_client()
await _run_reauth(hass, entry, client)
client.get_user_profile.assert_not_called()
assert entry.data[CONF_MACHINE_ID] == MACHINE_ID
async def test_reauth_recovers_missing_machine_id(hass: HomeAssistant) -> None:
data = {k: v for k, v in STORED_DATA.items() if k != CONF_MACHINE_ID}
entry = _entry(hass, data=data)
client = _mock_client()
await _run_reauth(hass, entry, client)
client.get_user_profile.assert_called_once()
assert entry.data[CONF_MACHINE_ID] == MACHINE_ID
async def test_add_integration_while_reauth_pending(hass: HomeAssistant) -> None:
"""The path a stuck user takes: give up on reauth, try Add Integration.
`async_set_unique_id` raises `already_in_progress` because the parked
reauth flow holds the same unique ID. This is what makes that abort
reason reachable, and therefore something that needs a translation.
"""
entry = _entry(hass)
client = _mock_client()
with (
patch(CLIENT_PATH, return_value=client),
patch(SETUP_PATH, return_value=True),
):
await entry.start_reauth_flow(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_EMAIL: EMAIL, CONF_PASSWORD: PASSWORD}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"recaptcha_token": TOKEN}
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_in_progress"
# --- User setup: must be unchanged by this fix ---
async def test_user_setup_creates_entry(hass: HomeAssistant) -> None:
client = _mock_client()
with (
patch(CLIENT_PATH, return_value=client),
patch(SETUP_PATH, return_value=True),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_EMAIL: EMAIL, CONF_PASSWORD: PASSWORD}
)
assert result["step_id"] == "token"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"recaptcha_token": TOKEN}
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"][CONF_ACCESS_TOKEN] == "new-access"
assert result["data"][CONF_MACHINE_ID] == MACHINE_ID
assert result["result"].unique_id == EMAIL
async def test_user_setup_still_blocks_duplicates(hass: HomeAssistant) -> None:
_entry(hass)
client = _mock_client()
with (
patch(CLIENT_PATH, return_value=client),
patch(SETUP_PATH, return_value=True),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_EMAIL: EMAIL, CONF_PASSWORD: PASSWORD}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"recaptcha_token": TOKEN}
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_user_setup_connection_error(hass: HomeAssistant) -> None:
client = _mock_client(
authenticate_error=PerfectDraftConnectionError("no route to host")
)
with patch(CLIENT_PATH, return_value=client):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_EMAIL: EMAIL, CONF_PASSWORD: PASSWORD}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"recaptcha_token": TOKEN}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "cannot_connect"}
# --- Translations must cover every reachable abort reason ---
COMPONENT_DIR = Path(__file__).parent.parent / "custom_components" / "perfectdraft"
# Flow helpers that can abort, and the reason each raises when the call site
# passes no explicit reason=.
ABORT_HELPERS = {
"_abort_if_unique_id_configured": "already_configured",
"_abort_if_unique_id_mismatch": "unique_id_mismatch",
"async_update_reload_and_abort": "reauth_successful",
"async_set_unique_id": "already_in_progress",
"async_abort": None,
}
def _abort_reasons_in_source() -> set[str]:
"""Every abort reason config_flow.py can emit, read out of the source.
Deriving this beats listing it by hand: a hand-written list is exactly
what let `already_in_progress` ship without a translation, because the
test only ever checked the reasons its author already knew about.
"""
tree = ast.parse((COMPONENT_DIR / "config_flow.py").read_text(encoding="utf-8"))
reasons: set[str] = set()
for node in ast.walk(tree):
if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute):
continue
if node.func.attr not in ABORT_HELPERS:
continue
keywords = {kw.arg: kw.value for kw in node.keywords}
# async_set_unique_id only races when it is allowed to.
if node.func.attr == "async_set_unique_id":
opt_out = keywords.get("raise_on_progress")
if isinstance(opt_out, ast.Constant) and opt_out.value is False:
continue
explicit = keywords.get("reason")
if isinstance(explicit, ast.Constant):
reasons.add(explicit.value)
elif ABORT_HELPERS[node.func.attr] is not None:
reasons.add(ABORT_HELPERS[node.func.attr])
return reasons
def test_abort_reason_scanner_sees_the_known_reasons() -> None:
"""Guards the scanner itself: a blind scanner would pass silently."""
assert {
"already_configured",
"already_in_progress",
"reauth_account_mismatch",
"reauth_successful",
} <= _abort_reasons_in_source()
@pytest.mark.parametrize("filename", ["strings.json", "translations/en.json"])
def test_every_abort_reason_is_translated(filename: str) -> None:
declared = json.loads(
(COMPONENT_DIR / filename).read_text(encoding="utf-8")
)["config"]["abort"]
missing = sorted(_abort_reasons_in_source() - set(declared))
assert not missing, f"{filename} is missing abort reasons: {missing}"