Files
Thomas KarnerandClaude Opus 5 f9d0b09d2f Correct the docs the gallery work made wrong
Housekeeping, not new behaviour. The status table still said the WebUI was
"nothing beyond the Vite scaffold" and the server was "Phases 1 and 2" at 194
tests, all of which stopped being true three commits ago. A status table that
is wrong is worse than no status table: it is the first thing read and the last
thing checked.

Endpoint lists in server/README.md were taken from the app's own OpenAPI
schema rather than from memory, which is how the last round of this found that
/ingest was documented as multipart when it is a raw body. The operator half is
now listed separately from the device half, because the two authenticate in
ways that must not be mixed up -- bearer token and no cookies on one side,
session cookie plus CSRF on the other.

Ticked auth-checked image serving, which shipped in 735cbcc, and recorded why
there are two delivery paths and only one authorization path.

The test count is 308 because the suite was run, not because 308 was the number
I remembered.

Two comments in api/app.py contradicted the code beside them. One said the
enroll-secret warning was "not fatal at Phase 1 -- no device endpoint exists
yet", six lines above the device endpoints being mounted; it now says the real
reason the API starts anyway, which is that an enrolled camera keeps working
and refusing to start would take the gallery down too. The other said the
Phase 3 UI endpoints were still to come, directly below the two lines that
mount them.

Left alone deliberately: the "12/12 tests" in docs/reviews/**. Those are
point-in-time review snapshots, and updating them to current numbers would
destroy the only thing they are for.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 22:01:35 +02:00

342 lines
24 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# TODO: poorBird
**Baseline:** [SPEC.md](SPEC.md) · **Device contract:** [firmware/API.md](firmware/API.md) · **Hardware notes:** [firmware/README.md](firmware/README.md)
**Updated:** 2026-09-20
This file tracks *work*. It does not restate decisions — those live in SPEC §0.
Anything here that contradicts SPEC means SPEC needs an edit, not a workaround.
---
## Decisions since SPEC §0
| Decision | Consequence |
|---|---|
| **Deploy natively, not with Docker** | SPEC §6's *Deploy* row is void; the stack itself is unchanged (FastAPI + PostgreSQL 17 + React/TS). It runs as systemd units from a venv, with Caddy and Postgres as host packages. `TODO.Dockerization.md` is deleted — the content was obsolete, not the idea. |
| **Build container-ready anyway** | Containers stay a plausible future, so the design avoids anything that would make the move expensive. Constraints listed under Phase 1.2. They cost close to nothing and most are better practice natively too. |
| **Server = x86 thin client, Linux, same LAN** | Closes SPEC §10 Q5. amd64 matches the dev machine, so no cross-building. Native NVMe/SATA, no SD-card corruption failure mode. Detection (Option C) stays physically possible. |
| **The server owns everything non-device** | Database, WebUI, image store, auth, backup, OTA hosting, stream sink. The ESP side only ever needs one IP and port. |
- [ ] Fold these three rows into SPEC §0 and strike the *Deploy* row of §6 — **do this first**, so SPEC stays the single baseline
---
## Where things actually stand
| Area | State |
|---|---|
| Firmware | Written, compiles, **never run on hardware**. Known gaps below. |
| Device↔server contract | Specified in full (`firmware/API.md`). Server half of the **device** endpoints implemented (Phase 2). The operator-facing half (firmware upload, device management) no longer waits on auth — that exists now — only on Phase 4. |
| Data model | Designed (SPEC §3) + §0 additions, migration written and applied, guarded by a drift test. |
| Server | Phases 1 and 2 plus the Phase 3 server half, in [`server/`](server/) — config, schema, health, job queue, scheduler, systemd units, every device endpoint the firmware calls, and user auth with the captures API behind it. Verified on Python 3.14.7 against PostgreSQL 17: 308 tests, migrations applied, real HTTP ingest through the worker to a WebP thumbnail on disk. Not yet on the real host, and **never yet spoken to by real firmware**. |
| WebUI | Shell, themes, i18n, login and a working cursor-paged gallery on `feature/UI_Basic_implementation`. Devices and System are still honest empty states — they need Phase 4 endpoints. **The gallery's appearance has not been checked in a browser yet.** |
---
## Phase 0 — Hardware bring-up (blocks everything)
The riskiest unknowns in this project are physical, not architectural. None of the
server work is wasted if this goes badly, but all of it is pointless until it goes well.
### 0.1 Before anything is connected
- [ ] **Measure the LD2410's TX logic level on a 5 V supply.** Unverified on this hardware
(`firmware/README.md` → Wiring). A 5 V swing into the ESP32S3 RX damages the pin.
Level-shift or divide if it is not 3.3 V.
- [ ] Verify `PIN_STATUS_LED` (GPIO21) against the actual XIAO board revision — it has moved between revisions
- [ ] Bench-power the board and confirm the mains supply holds up under WiFi TX + camera peaks
### 0.2 First flash
- [ ] Fill `secrets.ini` from `secrets.ini.example`, flash with the OTA partition table (`partitions/poorbird_8mb_ota.csv`)
- [ ] Confirm PSRAM is detected and the frame ring allocates at the configured depth
- [ ] Confirm camera init + the day profile produce a sane JPEG over serial/local dump
- [ ] Confirm SNTP sync, and that the device falls back to `server_time` cleanly when SNTP fails
### 0.3 Radar — the biggest unknown in the project
SPEC §10 Q3, restated as a radar question. Everything downstream assumes this works.
- [ ] Verify `ld2410.cpp` frame offsets against real module output — they are from the datasheet, not measured
- [ ] Verify baud autodetection across all three cases: factory default (256000), reconfigured (115200), factory-reset
- [ ] Make `radarSetGateSensitivity` validate that the ACK *matches*, not merely that bytes came back
- [ ] **Tune gates for birds at the real feeder distance.** Log distance + per-gate energy for a full day, then set thresholds from the data rather than from defaults
- [ ] Decide the fallback if radar cannot be tuned acceptably: AM312 PIR on `PIN_AUX_ADC` (one function, `radarIsTrigger`), or on-device frame differencing
### 0.4 Known code defects
- [ ] `nightlight.cpp` allocates an LEDC channel after the camera has claimed channel 0 for XCLK — routes around it in theory, untested in practice
- [ ] Battery percentage curves are generic room-temperature open-circuit approximations. Fine for the low banner and the OTA gate; do not present as a runtime estimate
- [ ] Enclosure: IP65, sun shade, drainage, desiccant. Condensation ruins more photos than any software bug
---
## Phase 1 — Server foundation
Target host: the x86 Linux thin client. No containers — packages and systemd units.
Skeleton written — see [`server/README.md`](server/README.md) to run it, and
[`server/deploy/INSTALL.md`](server/deploy/INSTALL.md) to deploy it. What is
written vs. what still needs doing on the real host:
- [x] Python venv layout, FastAPI + Pydantic v2 + SQLAlchemy 2.0 + Alembic — `server/`
- [x] systemd units `poorbird-api.service` + `poorbird-worker.service`, `After=postgresql.service`, restart policies, sandboxing
- [x] Caddyfile with DNS-01 TLS, the `:8080` plain-HTTP camera listener and the auth-checked image handoff
- [x] `poorbird check` — validates config, paths and DB before anything starts
- [x] **Run it against a real PostgreSQL** — done on the dev machine (uv-managed Python 3.14.7, Podman `postgres:17`): `poorbird check`, `migrate`, `serve`, `worker` and 12/12 tests all green
- [ ] Repeat the same four commands on the actual thin client, which is the run that counts
- [ ] Base install on the thin client: static IP (or DHCP reservation) and **hardcode that address in firmware** — more reliable than mDNS
- [ ] PostgreSQL 17 from the distro or PGDG repo; dedicated role + database; **loopback TCP with `scram-sha-256`, not a Unix socket** (see 1.2)
- [ ] Caddy DNS provider plugin build (`caddy add-package …`) and a real hostname
- [ ] Tailscale for remote access
- [x] Image store at `/srv/poorbird/images/YYYY/MM/DD/<uuid>.jpg`, thumbs alongside as `_400.webp` (SPEC §3.3) — writer landed with Phase 2; writes are atomic (`.part` then `os.replace`) so a crash cannot leave a half-JPEG that a thumbnail job would then fail on
- [ ] journald log retention capped, disk usage alarmed
### 1.1 Schema — SPEC §3 plus the §0 additions
- [x] Initial Alembic migration covering SPEC §3, guarded by a schema-drift test
- [x] `captures.pre_trigger BOOL` — was this frame captured *before* the trigger fired
- [x] `devices.awake BOOL` — reported every heartbeat, so the UI can show command latency honestly
- [x] `devices.reenroll_secret_hash`
- [x] `device_status` time-series table (SPEC §0 columns, plus `raw` JSONB so nothing is lost)
- [x] `devices` settings surface — **one JSONB `config` column, not forty**: `GET /config` is ~40 optional keys the firmware merges and clamps, so a column per key means a migration per firmware tunable. Validation moves to a Pydantic model. Promote an individual key to a column only if it ever needs querying across devices.
- [x] Job queue on Postgres with `FOR UPDATE SKIP LOCKED` — **No Redis.** Handlers for thumbnails / retention / backup arrive with their phases.
- [ ] Seed `taxa` (Phase 3) and the `settings` defaults
### 1.2 Staying container-ready
Not building containers now. Just not painting into a corner. Each of these is
cheap today and most are the better native choice regardless.
- [x] **All config from environment**, via systemd `EnvironmentFile=/etc/poorbird/poorbird.env`. No paths, hosts or secrets baked into code or committed config. That file becomes a compose `.env` unchanged.
- [x] **Postgres over loopback TCP**, not a Unix socket — the one genuinely container-hostile choice, and the only real change from a purely native design
- [x] **All mutable state in a few explicit top-level directories** (`/srv/poorbird/images`, `/srv/poorbird/thumbs`, `/var/lib/poorbird`), never scattered under the app dir. These are the future volume mounts.
- [x] **Log to stdout/stderr.** journald catches it now, a log driver would catch it later. Simpler than app-managed log files either way.
- [x] **Migrations as a standalone idempotent command** (`poorbird migrate`), run from `ExecStartPre` on the API unit only — never at app import time, and never from two units at once
- [x] **One env var for the image root**, read by both the app and the Caddy config, since the auth-checked handoff needs them to agree on the path
- [x] **Scheduled jobs run in the worker, not as systemd timers** — decided. APScheduler with a SQLAlchemy jobstore on the existing Postgres. Not primarily for portability: SPEC §3.4 makes *backup schedule + target* and *retention policy* UI-editable server settings, and a UI-editable systemd timer means the app writing unit files and calling `daemon-reload` behind a polkit or sudoers rule. In-app, the schedule is just a settings row. Timers stay the better answer for anything that is **not** UI-configurable — if such a job appears, use one.
- [x] Keep API and worker as separate processes — maps 1:1 to two services later
**Deliberately not doing now:** writing Dockerfiles or a compose file speculatively. That means maintaining two deployment paths to prove a point.
---
## Phase 2 — Walking skeleton: radar → photo → gallery
The first milestone worth celebrating. Nothing below this line matters until a real
bird photo appears in a browser.
- [x] `POST /api/v1/enroll` — bootstrap secret in, per-device `reenroll_secret` + token out.
**Re-enrolling a known `device_uid` must return the existing row with a fresh token, never a duplicate.**
Accepts the shared secret *or* that device's own `reenroll_secret`; checking only the
shared one would lock out every device already enrolled. Hardware facts (`mac`,
`hw_revision`, `fw_version`) refresh on every enrollment, the operator's `name` does not.
- [x] `POST /api/v1/ingest` — **raw JPEG body with metadata in headers, not multipart.**
`firmware/API.md` and `uploader.cpp` send the bytes directly; multipart was a
misreading. Honours `X-Pre-Trigger`, dedupes on sha256 per device.
- [x] `POST /api/v1/heartbeat` and `POST /status` — full conditions report into `device_status`
- [x] `GET /api/v1/config` — enums by name not number, `config_version` bump semantics.
Column-backed keys win over stale JSONB copies, so an operator rename actually reaches
the device; the device's own `config_version` never overwrites the server's.
- [x] Response envelope + `server_time` (SPEC C7: `received_at` stays authoritative).
On `/heartbeat` and `/ingest`. **Not** on `/status`, which is 204 with no body per
`firmware/API.md` — "every response" was not compatible with the firmware contract.
- [x] Thumbnail job on ingest — 400px WebP, decode kept off the request path
- [x] Device authentication, rate limiting, `POST /commands/{id}/ack`, `GET /firmware/{v}.bin`
— not in the original list, but the firmware calls them (see `docs/reviews/`)
- [~] Minimal gallery page purely to prove the path — **superseded.** The scaffold's System page
already proves browser → proxy → FastAPI → Postgres, and SPEC §3.3 requires image serving
to be auth-checked, so "no auth yet" is not a state the gallery can legitimately pass
through. The real grid is Phase 3, behind sessions.
- [ ] **End-to-end test on real hardware:** bird walks past → burst uploads → visible in browser.
Blocked on Phase 0: the server side is proven only against synthetic uploads.
---
## Phase 3 — WebUI
Scaffolding done — see [`web/README.md`](web/README.md). Typechecks, builds,
and the System page reads live data through the Vite proxy.
- [x] React 19 + TS + Vite + TanStack Query/Router, built on the dev machine, served as static files by Caddy
- [x] Three themes as design tokens, `data-theme` on `<html>`, no flash of the wrong theme
- [x] `npm run check:contrast` — asserts WCAG AA across all three themes; caught three failing `--border-strong` values on its first run
- [x] i18n de/en with a build-time-complete catalogue
- [x] Auth shell: provider, login form with TOTP field, `RequireAuth` (no dev bypass, on purpose)
- [x] System page on live `/health` — the end-to-end proof browser → proxy → FastAPI → Postgres
- [x] Wire `RequireAuth` into `router.tsx` and delete the "not enforced" banner — gallery needs
any signed-in user, Devices and System need `admin`. Sign-out is in the header.
- [ ] ESLint (skipped during scaffolding; `tsc --noEmit` covers the important cases for now)
- [x] Virtualised gallery grid, cursor-paged, thumbnails through the auth-checked route.
Filters for date range, device, kept, reviewed and pre-trigger — the columns that have
data. **Taxon and tag filters are deliberately still missing:** both need a join, and
neither has anything to join to until `taxa` is seeded and the observation editor exists.
A filter that can only return nothing is worse than an absent one, because the UI offers it.
- [x] `poorbird seed --captures 500` — synthetic captures with real JPEGs on disk, realistic
burst structure and pre-trigger flags. `--clear` is scoped to its own device so it can
never remove a real camera's frames.
- [ ] Full-size viewer: keyboard navigation is in, but it only steps through what is already
loaded. Stepping past the last loaded page needs the viewer to be able to trigger a fetch.
- [ ] Observation editor — `captures` 1—n `observations`, so a photo can hold two species or none
- [ ] Taxon autocomplete; seed `taxa` with 60–80 Central European garden species incl. GBIF keys, `name_de` + `name_en`, `is_local_common` ranking first
- [ ] Tags, favourite/reject (`kept`), review flag
- [ ] Persist the theme choice **per user** (`users.theme`) rather than in localStorage — the
tokens and the switcher are done (above); this is the half that needs accounts to exist
- [x] Auth: session cookies, Argon2id, CSRF, RBAC per SPEC §3.1 (viewer / editor / admin),
`audit_log` on login, failed login and logout. Sessions are rows, so logout is immediate;
only the SHA-256 of the cookie is stored; CSRF is bound to the session, not just
double-submitted. Accounts come from `poorbird user add` — there is no sign-up endpoint.
- [ ] Extend `audit_log` to the *content* mutations (observations, tags, device config) as each
endpoint lands. Auth events are covered; nothing else writes to it yet.
- [x] **Auth-checked image serving** — the app authorizes, Caddy serves the bytes via `X-Accel-Redirect`.
An unguessable URL is not access control. One authorization path, two ways of finishing the
response: `serve_images_directly=true` makes the app send the file for development, where there
is no Caddy. Not a separate unauthenticated dev route — that is the kind of thing that survives
into production because it works. `poorbird check` validates the sibling `images`/`thumbs`
layout the handoff depends on, since getting it wrong yields 404s from Caddy with nothing in
the app's log.
- [x] TOTP 2FA — enforced at account creation for `admin` rather than at login, because a
login-time check can lock the only admin out of their own account. Codes required whenever
the account has a secret. Replay inside the ~90s window is documented, not closed.
- [ ] **Revisit CORS.** Deliberately not configured in Phase 2: Caddy serves the built UI and the
API from one origin, so there is no cross-origin request to permit, and adding permissive
headers "for the UI" would only weaken that. The Vite dev server proxies `/api` for the
same reason, so development matches production. Decide it properly only if the UI is ever
served from somewhere else — *then* it matters.
### 3.0 UI decisions (2026-09-21)
**Language: German and English, both, from the first component (Q11).** i18n is
nearly free on day one and miserable to retrofit. `taxa` already carries
`name_de` and `name_en`; `users.locale` already exists and defaults to `de`.
Rule: no user-facing string literal in a component, ever — every one goes
through the translation catalogue, including the first one.
**Theme "blue" is a dark navy (Q13).** Tokens below. Light and dark stay
conventional; blue is the distinctive one. Contrast targets WCAG AA (≥4.5:1 for
body text) — check it when the tokens land, do not assume it.
| Token | Blue |
|---|---|
| `--bg` | `#0B1220` |
| `--surface` | `#111C2E` |
| `--surface-raised` | `#17253B` |
| `--border` | `#22344F` |
| `--text` | `#E6EDF7` |
| `--text-muted` | `#9FB3CE` |
| `--accent` | `#4C8DFF` |
| `--accent-hover` | `#6BA1FF` |
| `--success` / `--warning` / `--danger` | `#3DD68C` / `#F0B429` / `#F2545B` |
**2FA: build TOTP now, optional per user, enforced for `admin` (Q14).** The
reasoning matters more than the setting, because "the UI does not need it" and
"I need access from outside" describe the *same* surface — whatever is reachable
from outside is the UI. What differs is the path:
- Over **Tailscale** (the SPEC §0 decision): the network layer already demands an
enrolled device, and Tailscale enforces 2FA at your identity provider. UI 2FA
is then belt-and-braces.
- Over a **public domain** (SPEC §1.2, "design for, do not build"): UI 2FA stops
being optional.
Build it now regardless, because retrofitting 2FA means reopening the login
flow, the session model, the user model and the audit log at once — the four
places you least want to revisit. `users.totp_secret` already exists. Enforce
for `admin`; leave it opt-in for `viewer`/`editor` on the LAN. A
`require_2fa` server setting flips the whole thing on the day you go public.
**Stack stays React + TypeScript (Q16), with the learning curve taken seriously.**
No TS experience, but willing to learn. The gallery is genuinely a client-side
app — a virtualised grid and the keyboard-driven labelling loop — and that is
the thing HTMX would fight later. So: plain function components, no exotic
generics, no state-management library beyond TanStack Query, and comments that
explain the TypeScript rather than assuming it. **Fallback if it stops being
fun:** SPEC §5's Jinja2 + HTMX frontend is still a valid target and the API does
not change. Deciding to switch is not a failure; discovering it three months in
would be.
**Placeholder data: generated, not downloaded.** A seed command
(`poorbird seed --captures 500`) synthesises captures with realistic burst
structure, pre-trigger flags, timestamps and species spread. Reasons: no image
licensing question at all, no binary blobs in git, and it can produce the
*volume* the virtualised grid actually needs to be tested against. Real photos
prove nothing about a gallery that a generated one does not — until Phase 2
brings real captures, which is the only test that counts.
### 3.1 Two things the UI must not get wrong
- [ ] `battery_valid = false` means **not measured** (no divider is wired by default) — render as "n/a", never as a flat-battery alarm
- [ ] Daily counters live in RTC memory and reset on power loss. The `captures` table is authoritative; the counters' value is the **gap** between captured and delivered, which is an upload-health signal
---
## Phase 4 — Device management & OTA
- [ ] Device list with live/awake state, last seen, RSSI, heap/PSRAM, ring depth
- [ ] Settings editor writing the `devices` settings surface → `apply_config` → `config_version`
- [ ] Command queue UI: `wake_and_hold`, `capture_now`, `apply_config`, `ota_update`, `stream_start`, `reboot`; commands ride along on the ingest response
- [ ] Firmware upload, SHA-256, target marking, per-device staged rollout.
`GET /firmware/{version}.bin` already serves the bytes; the upload half was left out of
Phase 2 because it needs operator auth. **Constrain `firmware.is_target` to a single row
while doing this** — nothing enforces it today, and the lookup takes the first match, so
two target rows would pick non-deterministically between them.
- [ ] Verify the full OTA path on hardware: **trial boot and automatic rollback**. The camera is unreachable once mounted — this is the one feature with no recovery if it is broken
- [ ] Document that rotating the shared bootstrap secret server-side without shipping new firmware **removes the last-resort escape hatch**
---
## Phase 5 — Operations
- [ ] restic → NAS. **Decide the NAS protocol first (open Q9)** — SFTP or a mounted path; SMB-only changes the tooling
- [ ] `pg_dump` pre-hook; retention 7 daily / 4 weekly / 12 monthly
- [ ] **Monthly automated restore test** into a scratch Postgres database on the same host (the Docker-based scratch container from SPEC §6 is replaced by a throwaway cluster/DB). A backup you have never restored is a hypothesis.
- [ ] Alarms via ntfy or Gotify + WebUI banner: low battery, device offline > N hours, disk > 80 %, backup failure, ingest stalled
- [ ] Retention policy job (open Q8 — and decide whether deleting in the UI deletes the file or only hides it)
- [ ] `GET /api/v1/health` covering device liveness, battery, disk, last backup
---
## Phase 6 — Streaming (plumbing only)
Scope is device → server, watched internally. Public relay stays out (SPEC C3).
- [ ] Chunked MJPEG sink per `firmware/API.md` → Streaming
- [ ] `record` / `watch` / `both` modes; the record writer plus the ingest writer are the two concurrent writers that justified Postgres
- [ ] Session time-box: 60 s default, firmware-capped at 600 s. Kept as policy, not as a power constraint
- [ ] Live view in the WebUI, admin-only
---
## Explicitly not now
- **Species detection** — schema is ready (`observations.source`, `model_version`, `confidence`, `bbox`), pipeline is not built. Revisit after a few thousand real captures, when you also know whether you want to label them.
- **Public stream / public gallery** — SPEC Option C.
- **Local SD buffering** of failed uploads — pins are free; add only if the WiFi link proves marginal.
- **On-device frame differencing** — the PSRAM ring makes this easy to add later.
- **TLS on the device** — deliberate, SPEC C2.
- **Containers** — not now, but the door stays open; see Phase 1.2. **Kubernetes** stays shut regardless: a control plane on a single host gains nothing here.
- **Audio / BirdNET** — different sensor, different pipeline.
---
## Still open (from SPEC §10)
Answered and closed: Q1 (Option B), Q2 (XIAO ESP32S3 Sense), Q4 (internal first),
Q5 (x86 thin client), **Q11, Q13, Q14 and Q16 — see Phase 3.0**.
Void under mains power: Q10 (battery chemistry).
| # | Question | Blocks |
|---|---|---|
| 3 | Does the radar trigger reliably on *your* birds, at *your* distance? | Phase 0.3 — the project's biggest unknown |
| 9 | NAS access protocol — SFTP, SMB, NFS? | Phase 5, backup tooling choice |
| 6 | How many cameras eventually? | Phase 4 scope (device management, OTA staging) |
| 7 | Expected captures per day? | Storage sizing, retention, inline-vs-queued thumbnailing |
| 8 | Retention policy, and does UI delete remove the file? | Phase 5 |
| 11 | UI language — German, English, or both? | Cheap on day one, annoying to retrofit. `name_de`/`name_en` exist either way |
| 12 | Taxonomy source — GBIF backbone, IOC, Avibase? Which regional seed list? | Phase 3 taxa seed |
| 13 | The "blue" theme — a reference palette, or my choice? | Phase 3 theming |
| 14 | Is 2FA required, or is a strong password on a LAN-only service enough? | Phase 3 auth |
| 15 | Anything to record beyond SPEC §3 — weather, feeder type, ring number? | Schema, cheapest to settle before the first migration |
| 16 | Comfort level in C / Python / TypeScript? | The React frontend is the largest chunk of potentially unfamiliar work |
| 17 | Can the camera see a neighbour's garden or a public path? | One GDPR paragraph in the deployment notes |