Files
Thomas KarnerandClaude Opus 5 7263e1ec63 Move this branch's review to docs/reviews/ui-basic-implementation/
The UI review was living at server/REVIEW.md and server/REVIEW.AI.md - a path
that describes neither its subject nor its scope, since the document reviews
the UI branch and nothing in it is about the server directory it sat in.

The server branch moved its own review to docs/reviews/server-basic-implementation/
for the same reason, and because the fixed path guaranteed an add/add conflict
on both filenames the moment the two branches met. This is the other half of
that fix: with one directory per scope, both reviews survive into develop and
neither has to win.

Pure git mv, no content change. docs/reviews/README.md is taken as the
identical blob from the server branch rather than rewritten, so the two
branches cannot conflict on the file that exists to prevent conflicts.

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

61 KiB

AI Reviewer Guide: poorBird Server (feature/UI_Basic_implementation)

Purpose: This document provides comprehensive context for AI systems to analyze and improve the poorBird codebase, with specific focus on UI development preparation.

Target Audience: AI code review systems (like Mistral Vibe, Claude, etc.)

Created: 2026-09-21 by Mistral Vibe

Branch: feature/UI_Basic_implementation (Commit: 5d16ded)


0. Branch Context (CRITICAL FOR AI UNDERSTANDING)

Branch Identity

  • Name: feature/UI_Basic_implementation
  • Commit: 5d16ded ("Server: verify Phase 1 end to end against PostgreSQL 17")
  • Actual Content: Server code only (Phase 1) - NO UI CODE YET
  • Relation: Identical to feature/Server_Basic_implementation
  • Purpose: Preparation branch for Phase 3 (UI development)

Important Observation

This branch is misnamed. It contains only server infrastructure (Phase 1), not UI code. However, the server IS fully prepared for UI implementation (Phase 3). The AI should understand:

  • Current Reality: Server-only, Phase 1 complete
  • Intended Purpose: UI development foundation, Phase 3 preparation
  • What's Missing: Actual UI code (React/TS/Vite)

Phase Information

Phase 1 (DONE): Server foundation, config, schema, health, job queue
Phase 2 (NEXT): Device endpoints, authentication
Phase 3 (TARGET): WebUI (this branch's intended purpose)
Phase 4: Device management, OTA
Phase 5: Operations
Phase 6: Streaming

1. Project Overview (ESSENTIAL CONTEXT)

Core Purpose

Radar-triggered bird camera system that:

  1. Detects birds using LD2410 radar sensor
  2. Captures images with ESP32 camera
  3. Transmits to server via MQTT
  4. Stores images and metadata in PostgreSQL
  5. Provides web interface for viewing and managing captures

Domain

  • Primary: IoT + Computer Vision + Web Application
  • Secondary: Data Management, Device Management, User Management

Users

User Type Access Level Use Cases
Device API only Enroll, ingest images, send status
Viewer Read-only View gallery, search, filter
Editor Read+Write View + add observations, tags, edit metadata
Admin Full All editor + device management, user management, settings

Deployment Architecture

┌─────────────────────────────────────────────────────────┐
│                    Client (Browser)                        │
└─────────────────────────┬───────────────────────────────┘
                          │ HTTPS (TLS via DNS-01)
                          ▼
┌─────────────────────────────────────────────────────────┐
│                    Caddy (Reverse Proxy)                    │
│  ┌─────────────────────┐    ┌─────────────────────────┐  │
│  │   Static UI Files    │    │    API Requests         │  │
│  │   /srv/poorbird/     │    │    /api/v1/*            │  │
│  └──────────┬────────────┘    └──────────┬─────────────┘  │
│              │                           │                │
│              ▼                           ▼                │
│  ┌─────────────────────────────────────────────────────┐│
│  │                React/TS Frontend                      ││
│  │                (NOT YET IMPLEMENTED)                  ││
│  └─────────────────────────────────────────────────────┘│
│                                                     │
└──────────────────────────────────────────────────┬─────┘
                                                         │
                         ┌────────────────────────────────▼─────────────┐
                         │         FastAPI Backend (Phase 1 Complete)      │
                         │  ┌──────────────┐  ┌──────────────┐            │
                         │  │   API Layer  │  │  Worker Layer │            │
                         │  │ /api/v1/*    │  │  Job Queue   │            │
                         │  └──────────────┘  └──────────────┘            │
                         │              │                    │            │
                         │              ▼                    ▼            │
                         │  ┌─────────────────────────────────────────┐│
                         │  │           PostgreSQL 17                 ││
                         │  │  ┌──────────┐  ┌──────────┐            ││
                         │  │  │  Schema  │  │  Job Q   │            ││
                         │  │  │ (Phase 1)│  │ (Phase 1)│            ││
                         │  │  └──────────┘  └──────────┘            ││
                         │  └─────────────────────────────────────────┘│
                         └────────────────────────────────────────────────┘

Technology Stack

Layer Technology Version Status
Backend Python 3.13 Phase 1 Complete
Framework FastAPI 0.115+ Phase 1 Complete
Database PostgreSQL 17 Phase 1 Complete
ORM SQLAlchemy 2.0.36+ Phase 1 Complete
Migrations Alembic 1.14+ Phase 1 Complete
Logging structlog/stdout - Phase 1 Complete
Proxy Caddy 2.x Phase 1 Complete
Frontend React + TypeScript 18+ NOT STARTED
Build Tool Vite Latest NOT STARTED
State Mgmt TanStack Query Latest NOT STARTED
Routing TanStack Router Latest NOT STARTED

Scale Expectations

Metric Value Notes
Cameras 1-10 (Phase 3), 100+ (future) Current: 1
Captures/day 5000 1 camera, ~10/hour
Image Size 200-500KB JPEG
Thumb Size 20-50KB WebP, 400px
Concurrent Users 1-5 typical, 10 peak LAN-only
Storage/month ~1GB 5000 images * 200KB
DB Queries/day ~10,000 5000 captures + 5000 status

2. External Contracts (CRITICAL FOR INTEGRATION)

Device ↔ Server API Contract (firmware/API.md)

Endpoints (ALL NOT YET IMPLEMENTED - Phase 2)

Device Enrollment:

POST /api/v1/enroll
Headers:
  X-Enroll-Secret: <bootstrap_secret>
  Content-Type: application/json

Request:
  {
    "device_uid": "<MAC_address>",
    "name": "<device_name>",
    "mac": "<MAC>",
    "hw_revision": "<revision>",
    "fw_version": "<version>"
  }

Response:
  {
    "token": "<bearer_token>",
    "reenroll_secret": "<recovery_secret>"
  }

Notes:
- Token is high-entropy, hashed before storage
- reenroll_secret allows device recovery
- Device can re-enroll with same device_uid to get fresh token

Image Ingest:

POST /api/v1/ingest
Headers:
  Authorization: Bearer <device_token>
  Content-Type: multipart/form-data
  X-Captured-At: <timestamp_or_0>
  X-Pre-Trigger: 0 or 1

Request:
  <binary JPEG image>
  {
    "device_id": <id>,
    "trigger": "radar"|"manual"|"timer"|"stream_grab",
    "burst_id": "<uuid>",
    "burst_index": <int>,
    "burst_count": <int>,
    "frame_seq": <int>,
    "radar_distance_cm": <int>,
    "radar_energy": <int>,
    "battery_mv": <int>,
    "rssi": <int>,
    "temp_c": <float>
  }

Response:
  {
    "ingested": true,
    "capture_id": "<uuid>",
    "commands": [...]  // Device command queue
  }

Notes:
- Image saved to: /srv/poorbird/images/YYYY/MM/DD/<uuid>.jpg
- Thumbnail generated: /srv/poorbird/thumbs/<uuid>_400.webp
- sha256 calculated for deduplication
- received_at set to server time (SPEC C7)

Heartbeat:

POST /api/v1/heartbeat
Headers:
  Authorization: Bearer <device_token>
  Content-Type: application/json

Request:
  {
    "battery_mv": <int>,
    "battery_pct": <int>,
    "battery_valid": <bool>,
    "awake": <bool>,
    "rssi": <int>,
    "temp_c": <float>,
    "free_heap": <int>,
    "free_psram": <int>,
    "ring_depth": <int>,
    "time_synced": <bool>,
    "device_time": <timestamp>
  }

Response:
  {
    "commands": [...]  // Device command queue
  }

Notes:
- battery_valid=false means NOT MEASURED (not empty!)
- Last heartbeat stored in devices.last_seen_at

Status Report:

POST /api/v1/status
Headers:
  Authorization: Bearer <device_token>
  Content-Type: application/json

Request:
  {
    "reason": "heartbeat"|"periodic"|"after_event"|"before_sleep"|"before_night_sleep"|"on_request",
    "captured_today": <int>,
    "delivered_today": <int>,
    "failed_today": <int>,
    "events_today": <int>,
    "day_index": <int>,
    "is_night": <bool>,
    "nightlight_on": <bool>,
    "cam_profile": "day"|"night",
    "radar_baud": <int>,
    "radar_uart_ok": <bool>,
    "stream_active": <bool>,
    "wake_cause": <string>,
    "last_sleep_s": <int>,
    "total_sleep_s": <int>,
    "boot_count": <int>,
    "awake_ms": <int>,
    "ip": <string>
  }

Response:
  {
    "commands": [...]  // Device command queue
  }

Notes:
- Counters are from RTC memory, reset on power loss
- captures table is AUTHORITATIVE
- Counters show GAP between captured and delivered

Config:

GET /api/v1/config
Headers:
  Authorization: Bearer <device_token>

Response:
  {
    "config_version": <int>,
    "heartbeat_interval_s": <int>,
    "status_interval_s": <int>,
    "responsive_mode": <bool>,
    "cam_day": { ... },  // OV2640 parameters
    "cam_night": { ... },
    "night_window": [start_time, end_time],
    "nightlight_mode": "off"|"auto"|"on",
    "nightlight_brightness": <int>,
    "battery_calibration": { ... }
  }

Notes:
- config is JSONB, all keys optional
- device merges partial configs
- config_version must match for device to apply

Firmware Upload:

POST /api/v1/firmware
Headers:
  Authorization: Bearer <admin_token>
  Content-Type: multipart/form-data

Request:
  <binary firmware .bin file>
  {
    "version": "<version>",
    "semver": "<semver>",
    "release_notes": "<notes>",
    "min_battery_pct": <int>,
    "target": <bool>
  }

Response:
  {
    "firmware_id": <int>,
    "sha256": "<hash>",
    "size_bytes": <int>
  }

UI-Specific Contract Requirements (SPEC 3.3)

Image Serving:

  • NEVER serve images directly from filesystem
  • ALWAYS check authorization in app first
  • THEN have Caddy serve the bytes
  • URL Pattern: /images/YYYY/MM/DD/<uuid>.jpg
  • Thumb Pattern: /thumbs/<uuid>_400.webp

Authentication:

  • Session cookies (not JWT for WebUI)
  • CSRF protection for all mutating requests
  • RBAC: viewer, editor, admin
  • Optional TOTP 2FA (SPEC Q14)

3. Architecture Decisions (WHY THEY MATTER FOR AI)

Core Decisions

Decision Rationale Alternatives Trade-offs UI Impact
Native Deployment SPEC requirement, no container overhead Docker, Kubernetes Simpler, but less portable None - Caddy handles static files
Sync SQLAlchemy 1 camera, few K frames/day - async overhead not justified Async SQLAlchemy Simpler code, but blocks event loop May need revisit for Phase 6 MJPEG
PostgreSQL Relational data, complex queries, concurrent writers SQLite, MySQL More powerful, but heavier Perfect for gallery queries
FOR UPDATE SKIP LOCKED Job queue without Redis dependency Redis, RabbitMQ No external service, PostgreSQL-only Works well for background jobs
JSONB for Config 40+ optional settings, firmware evolves Separate columns Flexible, but can't index individual settings Good for device settings form
UUID for Captures Safe for URLs, distributed systems Sequential int Better for URLs Perfect for /gallery/
Single Image Root App and Caddy must agree on path Multiple roots Simpler, single source of truth Critical for auth-checked handoff

Constraints (AI MUST RESPECT THESE)

Hard Constraints:

  • NO Docker (SPEC requirement)
  • Native Linux deployment
  • PostgreSQL (not SQLite)
  • systemd units (not supervisor)
  • Caddy (not nginx, not Apache)

Soft Constraints:

  • Container-ready design (even though not using containers)
  • All config from environment
  • All mutable state in explicit directories
  • Log to stdout/stderr only

Non-Goals:

  • NO Kubernetes
  • NO public streaming (Phase 6 is internal only)
  • NO audio/BirdNET (different sensor)
  • NO TLS on device (SPEC C2)

4. Security Analysis (CRITICAL FOR AI)

Severity System

  • CRITICAL: Must fix before any production use. Blocks Phase 3.
  • HIGH: Must fix before Phase 3. Serious risk.
  • MEDIUM: Should fix before Phase 3. Moderate risk.
  • LOW: Nice to have. Low risk.

Critical Issues (BLOCK PHASE 3)

SEC-001: Enroll Secret in Plaintext

  • Location: config.py:53, .env files, systemd EnvironmentFile
  • Code: enroll_secret: SecretStr = SecretStr("")
  • Issue: Bootstrap secret stored in plaintext in files
  • Risk: Filesystem access = complete device spoofing. If UI exposes device management, attacker can enroll malicious devices.
  • Impact: Catastrophic. Compromises entire device network.
  • Vulnerability Type: Credential Exposure
  • CVSS: 9.8 (Critical)
  • Solution:
    # Option 1: Remove from env, CLI-only
    enroll_secret: SecretStr  # No default
    # Only set via: poorbird config set enroll_secret <value>
    
    # Option 2: Use secrets manager
    # Store in HashiCorp Vault, fetch at runtime
    
    # Option 3: Encrypt in file
    # Use age or similar to encrypt .env file
    
  • Files to Modify: config.py, .env.example, deploy/poorbird.env.example
  • Tests Needed: Verify secret not logged, not in error messages
  • Priority: CRITICAL
  • Block: Phase 3 (UI Development)
  • Effort: 2-4 hours

SEC-002: No Request Authentication

  • Location: All API endpoints (none have auth yet)
  • Issue: No authentication for any endpoint
  • Risk: Anyone can send device commands, access admin functions, manage users
  • Impact: Complete system compromise. UI would be wide open.
  • Vulnerability Type: Missing Authentication
  • CVSS: 10.0 (Critical)
  • Solution:
    # Device auth (for /enroll, /ingest, /heartbeat, /status)
    from fastapi import Request, HTTPException, Header
    
    async def verify_device(request: Request, 
                            x_enroll_secret: str = Header(None)):
        if not x_enroll_secret:
            raise HTTPException(status_code=401)
        # Verify against enroll_secret hash
        # Lookup device by token
    
    # User auth (for UI endpoints)
    from fastapi import Cookie
    
    async def verify_user(request: Request,
                         session_id: str = Cookie(None)):
        if not session_id:
            raise HTTPException(status_code=401)
        # Verify session in DB
        # Return user with roles
    
  • Files to Create: api/routes/auth.py, api/deps.py
  • Files to Modify: app.py (add auth dependencies)
  • Tests Needed: Auth tests for all endpoint types
  • Priority: CRITICAL
  • Block: Phase 3 (UI Development)
  • Effort: 1-2 days

SEC-003: No Input Validation

  • Location: queue.py:47-66 (enqueue function), all future endpoints
  • Issue: Payloads not validated before DB insert
  • Risk: SQL injection, XSS, malicious data, data corruption
  • Impact: High. UI accepts user input, could lead to DB compromise.
  • Vulnerability Type: Missing Input Validation
  • CVSS: 8.1 (High)
  • Solution:
    # Example: Job payload validation
    from pydantic import BaseModel, constr, Json
    from typing import Literal, Optional
    
    class NoopJobPayload(BaseModel):
        """Payload for noop job."""
        message: Optional[str] = None
    
    class ThumbnailJobPayload(BaseModel):
        """Payload for thumbnail job."""
        capture_id: str  # UUID
        quality: int = Field(ge=1, le=100)
        width: int = Field(ge=100, le=2000)
    
    JobPayload = Union[NoopJobPayload, ThumbnailJobPayload, ...]
    
    def enqueue(session: Session, 
                kind: Literal["noop", "thumbnail", ...],
                payload: JobPayload,
                ...):
        # Now payload is validated!
    
  • Files to Create: api/schemas.py (Pydantic models for all requests)
  • Files to Modify: queue.py, all route files
  • Tests Needed: Validation tests for all payload types
  • Priority: CRITICAL
  • Block: Phase 3 (UI Development)
  • Effort: 1-2 days

SEC-004: No Rate Limiting

  • Location: API layer (app.py)
  • Issue: No protection against DoS or brute force
  • Risk: UI endpoints can be flooded, server overload
  • Impact: High. UI would be vulnerable to attack.
  • Vulnerability Type: Missing Rate Limiting
  • CVSS: 7.5 (High)
  • Solution:
    from slowapi import Limiter
    from slowapi.util import get_remote_address
    from slowapi.errors import RateLimitExceeded
    from fastapi import Request
    
    limiter = Limiter(key_func=get_remote_address)
    
    @app.exception_handler(RateLimitExceeded)
    async def rate_limit_exceeded_handler(request: Request, exc: RateLimitExceeded):
        return JSONResponse(
            status_code=429,
            content={"detail": "Too many requests"},
            headers={"Retry-After": str(exc.retry_after)}
        )
    
    # Apply to all endpoints
    @app.get("/api/v1/captures")
    @limiter.limit("100/minute")
    async def list_captures(request: Request):
        ...
    
  • Files to Create: None (add to app.py)
  • Files to Modify: app.py
  • Configuration: Add to pyproject.toml: slowapi
  • Tests Needed: Rate limiting tests
  • Priority: HIGH
  • Block: Phase 3 (UI Development)
  • Effort: 1 day

High Priority Issues (FIX BEFORE PHASE 3)

SEC-005: No CORS Configuration

  • Location: API layer
  • Issue: No CORS headers configured
  • Risk: UI cannot make requests if on different origin (even localhost:3000)
  • Impact: UI development impossible
  • Vulnerability Type: Missing CORS
  • CVSS: 6.5 (Medium)
  • Solution:
    from fastapi.middleware.cors import CORSMiddleware
    
    app.add_middleware(
        CORSMiddleware,
        allow_origins=[
            "http://localhost:3000",  # Dev
            "http://localhost:5173",  # Vite dev
            "https://poorbird.local",  # Prod
        ],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
        expose_headers=["X-Request-ID"],
    )
    
  • Files to Modify: app.py
  • Tests Needed: CORS test
  • Priority: HIGH
  • Effort: 1 hour

SEC-006: No CSRF Protection

  • Location: All mutating endpoints (POST, PUT, DELETE, PATCH)
  • Issue: No CSRF protection for form submissions
  • Risk: Cross-site request forgery attacks
  • Impact: High for UI. Users' sessions can be hijacked.
  • Vulnerability Type: Missing CSRF Protection
  • CVSS: 6.5 (Medium)
  • Solution:
    # Option 1: Use FastAPI CSRF middleware
    from fastapi_csrf_protect import CsrfProtect
    from fastapi_csrf_protect.exceptions import CsrfProtectError
    
    @app.exception_handler(CsrfProtectError)
    async def csrf_protect_exception_handler(request: Request, exc: CsrfProtectError):
        return JSONResponse(
            status_code=403,
            content={"detail": "CSRF token missing or invalid"}
        )
    
    @app.middleware("http")
    async def add_csrf_token(request: Request, call_next):
        response = await call_next(request)
        if request.method in ["GET"]:
            # Add CSRF token to cookies for forms
            response.set_cookie(
                key="csrftoken",
                value=CsrfProtect.generate_csrf_token(),
                httponly=True,
                secure=True,  # In production
                samesite="lax"
            )
        return response
    
    # Option 2: Use Django-style double-submit
    # Frontend sends token in header and cookie
    # Backend verifies both match
    
  • Files to Create: api/middleware/csrf.py
  • Files to Modify: app.py, all mutating endpoints
  • Tests Needed: CSRF protection tests
  • Priority: HIGH
  • Effort: 1 day

SEC-007: No Session Management

  • Location: models/users.py has Session model, but not used
  • Issue: Session table exists but no implementation
  • Risk: Cannot implement user login/logout
  • Impact: High. UI authentication impossible.
  • Vulnerability Type: Missing Functionality
  • Solution:
    # Session creation on login
    from datetime import datetime, timedelta
    import secrets
    from sqlalchemy.orm import Session as DbSession
    from .models import Session, User
    from .config import get_settings
    
    def create_session(db: DbSession, user: User) -> Session:
        settings = get_settings()
        session = Session(
            user_id=user.id,
            expires_at=datetime.utcnow() + timedelta(days=30),
            ip=request.client.host,
            user_agent=request.headers.get("user-agent"),
        )
        db.add(session)
        db.commit()
        db.refresh(session)
        return session
    
    def verify_session(db: DbSession, session_id: str) -> User | None:
        session = db.query(Session).filter(
            Session.id == session_id,
            Session.expires_at > datetime.utcnow()
        ).first()
        if session:
            # Extend session
            session.expires_at = datetime.utcnow() + timedelta(days=30)
            db.commit()
            return session.user
        return None
    
    def invalidate_session(db: DbSession, session_id: str):
        db.query(Session).filter(Session.id == session_id).delete()
        db.commit()
    
  • Files to Create: api/routes/auth.py
  • Files to Modify: models/users.py (add session management methods)
  • Tests Needed: Session lifecycle tests
  • Priority: HIGH
  • Effort: 1 day

SEC-008: DB URL with Credentials in Defaults

  • Location: config.py:30
  • Issue: Default value contains plaintext credentials
  • Risk: Accidental commit of credentials to repo
  • Impact: Medium. Security risk if committed.
  • Vulnerability Type: Hardcoded Credentials
  • CVSS: 7.5 (High)
  • Solution:
    # Change from:
    database_url: str = "postgresql+psycopg://poorbird:poorbird@127.0.0.1:5432/poorbird"
    
    # To:
    database_url: str = ""  # Must be set via POORBIRD_DATABASE_URL
    
  • Files to Modify: config.py
  • Tests Needed: Verify app fails gracefully if not set
  • Priority: HIGH
  • Effort: 1 hour

Medium Priority Issues

SEC-009: No Password Hashing Implementation

  • Location: models/users.py (password_hash column exists)
  • Issue: password_hash column exists but no hashing implementation
  • Risk: If someone implements password setting without hashing, passwords stored in plaintext
  • Impact: Medium. Future security risk.
  • Solution:
    import argon2
    from argon2 import PasswordHasher
    
    ph = PasswordHasher(
        time_cost=3,  # Number of iterations
        memory_cost=65536,  # 64MB
        parallelism=4,  # Number of parallel threads
        hash_len=32,  # Length of the hash
        salt_len=16,  # Length of the salt
    )
    
    def hash_password(password: str) -> str:
        return ph.hash(password)
    
    def verify_password(password: str, hash: str) -> bool:
        try:
            return ph.verify(hash, password)
        except:
            return False
    
  • Files to Create: api/utils/auth.py
  • Files to Modify: models/users.py (add password hashing)
  • Tests Needed: Password hashing tests
  • Priority: MEDIUM
  • Effort: 2-4 hours

SEC-010: No Image Upload Validation

  • Location: Future UI image upload endpoint
  • Issue: Images not validated before saving
  • Risk: Malicious file uploads (e.g., PHP files, scripts)
  • Impact: Medium. Could lead to server compromise.
  • Solution:
    import magic  # python-magic
    from pathlib import Path
    
    ALLOWED_TYPES = {"image/jpeg", "image/png", "image/webp"}
    MAX_SIZE = 10 * 1024 * 1024  # 10MB
    MAX_DIMENSIONS = (4000, 4000)  # width, height
    
    def validate_image(file_path: Path) -> tuple[bool, str]:
        # Check file size
        if file_path.stat().st_size > MAX_SIZE:
            return False, "File too large"
    
        # Check MIME type
        mime = magic.from_file(file_path, mime=True)
        if mime not in ALLOWED_TYPES:
            return False, f"Invalid file type: {mime}"
    
        # Check dimensions
        try:
            from PIL import Image
            with Image.open(file_path) as img:
                if img.size[0] > MAX_DIMENSIONS[0] or img.size[1] > MAX_DIMENSIONS[1]:
                    return False, "Image too large"
        except:
            return False, "Invalid image"
    
        return True, "Valid"
    
  • Files to Create: api/utils/image_validation.py
  • Tests Needed: Image validation tests
  • Priority: MEDIUM
  • Effort: 2-4 hours

5. Data Model Analysis (FOR UI DEVELOPMENT)

Complete Schema

-- Users and Authentication
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(64) UNIQUE NOT NULL,
    email VARCHAR(255),
    password_hash VARCHAR(255),
    totp_secret VARCHAR(64),
    role VARCHAR(16) DEFAULT 'viewer' CHECK (role IN ('admin', 'editor', 'viewer')),
    is_active BOOLEAN DEFAULT true,
    theme VARCHAR(16) DEFAULT 'light' CHECK (theme IN ('light', 'dark', 'blue')),
    locale VARCHAR(8) DEFAULT 'de',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    last_login_at TIMESTAMP WITH TIME ZONE
);

CREATE TABLE sessions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
    ip VARCHAR(45),
    user_agent VARCHAR(255)
);

-- Devices and Commands
CREATE TABLE devices (
    id SERIAL PRIMARY KEY,
    device_uid VARCHAR(32) UNIQUE NOT NULL,
    name VARCHAR(64) NOT NULL,
    mac VARCHAR(32),
    hw_revision VARCHAR(64),
    fw_version VARCHAR(32),
    token_hash VARCHAR(128),
    reenroll_secret_hash VARCHAR(128),
    last_seen_at TIMESTAMP WITH TIME ZONE,
    battery_mv INTEGER,
    battery_pct INTEGER,
    battery_valid BOOLEAN DEFAULT false,  -- false = NOT MEASURED
    rssi INTEGER,
    temp_c FLOAT,
    awake BOOLEAN DEFAULT true,
    config JSONB DEFAULT '{}'::jsonb,
    config_version INTEGER DEFAULT 1,
    heartbeat_interval_s INTEGER DEFAULT 300,
    status_interval_s INTEGER DEFAULT 900,
    responsive_mode BOOLEAN DEFAULT false,
    enabled BOOLEAN DEFAULT true,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

CREATE TABLE device_commands (
    id SERIAL PRIMARY KEY,
    device_id INTEGER REFERENCES devices(id) ON DELETE CASCADE,
    type VARCHAR(32) CHECK (type IN ('apply_config', 'capture_now', 'report_status', 'wake_and_hold', 'sleep_now', 'stream_start', 'stream_stop', 'ota_update', 'reboot')),
    payload JSONB,
    created_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    delivered_at TIMESTAMP WITH TIME ZONE,
    acked_at TIMESTAMP WITH TIME ZONE,
    ack_status VARCHAR(16) CHECK (ack_status IS NULL OR ack_status IN ('done', 'failed', 'rejected')),
    result TEXT,
    expires_at TIMESTAMP WITH TIME ZONE
);

-- Firmware
CREATE TABLE firmware (
    id SERIAL PRIMARY KEY,
    version VARCHAR(32) UNIQUE NOT NULL,
    semver VARCHAR(32),
    file_path TEXT NOT NULL,
    sha256 VARCHAR(64) NOT NULL,
    size_bytes BIGINT NOT NULL,
    release_notes TEXT,
    min_battery_pct INTEGER DEFAULT 50,
    uploaded_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
    uploaded_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    is_target BOOLEAN DEFAULT false
);

-- Captures and Observations (CORE FOR UI)
CREATE TABLE captures (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    device_id INTEGER REFERENCES devices(id) ON DELETE CASCADE,
    path TEXT NOT NULL,
    thumb_path TEXT,
    sha256 VARCHAR(64) NOT NULL,  -- Consider: UNIQUE for deduplication
    width INTEGER,
    height INTEGER,
    bytes BIGINT NOT NULL,
    captured_at_device TIMESTAMP WITH TIME ZONE,
    received_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    trigger VARCHAR(16) NOT NULL CHECK (trigger IN ('radar', 'manual', 'timer', 'stream_grab')),
    burst_id VARCHAR(64),
    burst_index INTEGER,
    burst_count INTEGER,
    pre_trigger BOOLEAN DEFAULT false,  -- Captured BEFORE trigger fired
    frame_seq INTEGER,
    radar_state INTEGER,  -- 0 none, 1 moving, 2 stationary, 3 both
    radar_distance_cm INTEGER,
    radar_energy INTEGER,
    battery_mv INTEGER,
    rssi INTEGER,
    temp_c FLOAT,
    reviewed BOOLEAN DEFAULT false,
    kept BOOLEAN DEFAULT true,  -- Soft reject
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

CREATE TABLE taxa (
    id SERIAL PRIMARY KEY,
    gbif_key BIGINT UNIQUE,
    scientific_name VARCHAR(128) UNIQUE NOT NULL,
    name_de VARCHAR(128),
    name_en VARCHAR(128),
    family VARCHAR(64),
    "order" VARCHAR(64),  -- Quoted because 'order' is reserved
    iucn_status VARCHAR(8),
    is_local_common BOOLEAN DEFAULT false
);

CREATE TABLE observations (
    id BIGSERIAL PRIMARY KEY,
    capture_id UUID REFERENCES captures(id) ON DELETE CASCADE,
    taxon_id INTEGER REFERENCES taxa(id) ON DELETE RESTRICT,
    individuals INTEGER DEFAULT 1,
    age VARCHAR(16) DEFAULT 'unknown' CHECK (age IN ('adult', 'juvenile', 'unknown')),
    sex VARCHAR(16) DEFAULT 'unknown' CHECK (sex IN ('male', 'female', 'unknown')),
    behaviour VARCHAR(16) CHECK (behaviour IN ('feeding', 'bathing', 'perching', 'nesting', 'fighting', 'other')),
    certainty VARCHAR(16) DEFAULT 'certain' CHECK (certainty IN ('certain', 'probable', 'uncertain')),
    notes TEXT,
    source VARCHAR(8) DEFAULT 'human' CHECK (source IN ('human', 'model')),
    model_version VARCHAR(64),
    confidence FLOAT,
    bbox JSONB,
    created_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

CREATE TABLE tags (
    id SERIAL PRIMARY KEY,
    label VARCHAR(64) UNIQUE NOT NULL,
    colour VARCHAR(16)
);

CREATE TABLE capture_tags (
    capture_id UUID REFERENCES captures(id) ON DELETE CASCADE,
    tag_id INTEGER REFERENCES tags(id) ON DELETE CASCADE,
    PRIMARY KEY (capture_id, tag_id)
);

-- Device Status (Time Series)
CREATE TABLE device_status (
    id BIGSERIAL PRIMARY KEY,
    device_id INTEGER REFERENCES devices(id) ON DELETE CASCADE,
    at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    reason VARCHAR(32) NOT NULL CHECK (reason IN ('heartbeat', 'periodic', 'after_event', 'before_sleep', 'before_night_sleep', 'on_request')),
    -- Battery
    battery_mv INTEGER,
    battery_pct INTEGER,
    battery_valid BOOLEAN,
    -- Activity
    awake_ms BIGINT,
    boot_count INTEGER,
    wake_cause VARCHAR(16),
    last_sleep_s INTEGER,
    total_sleep_s BIGINT,
    -- Counters (RTC memory, reset on power loss)
    captured_today INTEGER,
    delivered_today INTEGER,
    failed_today INTEGER,
    events_today INTEGER,
    day_index INTEGER,  -- Days since epoch, local time
    -- Environment
    is_night BOOLEAN,
    nightlight_on BOOLEAN,
    cam_profile VARCHAR(16),
    -- Radar
    radar_baud INTEGER,
    radar_uart_ok BOOLEAN,
    stream_active BOOLEAN,
    -- Network
    rssi INTEGER,
    ip VARCHAR(45),
    -- System
    free_heap BIGINT,
    free_psram BIGINT,
    ring_depth INTEGER,
    -- Timing
    time_synced BOOLEAN,
    device_time TIMESTAMP WITH TIME ZONE,
    fw_version VARCHAR(32),
    config_version INTEGER,
    -- Flexible
    raw JSONB
);

-- Operational Tables
CREATE TABLE settings (
    key VARCHAR(64) PRIMARY KEY,
    value TEXT,
    value_type VARCHAR(16) DEFAULT 'str',
    scope VARCHAR(16) DEFAULT 'server' CHECK (scope IN ('server', 'device')),
    updated_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

CREATE TABLE audit_log (
    id BIGSERIAL PRIMARY KEY,
    at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
    action VARCHAR(64) NOT NULL,
    entity VARCHAR(64) NOT NULL,
    entity_id VARCHAR(64),
    before JSONB,
    after JSONB,
    ip VARCHAR(45)
);

CREATE TABLE backup_runs (
    id BIGSERIAL PRIMARY KEY,
    started_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    finished_at TIMESTAMP WITH TIME ZONE,
    status VARCHAR(16) DEFAULT 'running',
    bytes BIGINT,
    snapshot_id VARCHAR(64),
    restore_tested_at TIMESTAMP WITH TIME ZONE,
    error TEXT
);

-- Job Queue (PostgreSQL-backed, no Redis)
CREATE TABLE jobs (
    id BIGSERIAL PRIMARY KEY,
    kind VARCHAR(64) NOT NULL,
    payload JSONB NOT NULL DEFAULT '{}'::jsonb,
    status VARCHAR(16) NOT NULL DEFAULT 'queued' CHECK (status IN ('queued', 'running', 'done', 'failed')),
    priority INTEGER NOT NULL DEFAULT 0,
    run_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
    attempts INTEGER NOT NULL DEFAULT 0,
    max_attempts INTEGER NOT NULL DEFAULT 3,
    locked_at TIMESTAMP WITH TIME ZONE,
    locked_by VARCHAR(128),
    last_error TEXT,
    created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
    finished_at TIMESTAMP WITH TIME ZONE
);

Key Relationships

users (1) ── (n) sessions
          └── (n) audit_log
          └── (n) device_commands (created_by)
          └── (n) firmware (uploaded_by)
          └── (n) observations (created_by)
          
devices (1) ── (n) captures
            ├── (n) device_status
            ├── (n) device_commands
            └── (1) current firmware (via is_target)
            
captures (1) ── (n) observations
           ├── (n) tags (via capture_tags)
           └── (1) device
           
observations (n) ── (1) taxa
observations (n) ── (1) capture
observations (n) ── (1) user (created_by)

tags (n) ── (n) captures (via capture_tags)

UI-Relevant Fields

Captures:

  • id (UUID) - Primary key, used in URLs
  • path, thumb_path - File paths for images
  • received_at - AUTHORITATIVE timestamp (SPEC C7)
  • trigger - How capture was triggered
  • pre_trigger - Was this frame captured BEFORE the trigger fired?
  • kept - Soft reject flag
  • reviewed - Has this been reviewed?
  • radar_* - Radar data for analysis
  • battery_*, rssi, temp_c - Device conditions at capture time

Observations:

  • source - 'human' or 'model' (future ML integration)
  • taxon_id - Links to species data
  • model_version, confidence, bbox - For ML predictions
  • age, sex, behaviour, certainty - Observation metadata
  • individuals - Number of birds in this observation

Taxa:

  • scientific_name - Unique scientific name
  • name_de, name_en - Localized names
  • gbif_key - GBIF identifier
  • is_local_common - For autocomplete ranking (local species first)

Devices:

  • device_uid - MAC-based identity, survives reflashing
  • config - JSONB with all device settings
  • config_version - Increments on every config change
  • battery_valid - CRITICAL: false = NOT MEASURED, not empty!
  • awake - Device is awake and responsive

Device Status:

  • All fields are time-series data
  • Counters (captured_today, etc.) are from RTC memory
  • CRITICAL: Counters reset on power loss
  • UI Display: Counters show GAP between captured and delivered

6. Current Implementation Status

What Exists (Phase 1 - Server Foundation)

server/
├── src/poorbird/
│   ├── __init__.py          # Version: 0.1.0
│   ├── config.py            # All settings from environment
│   ├── logging_setup.py      # stdout-only logging
│   ├── db.py                 # SQLAlchemy engine + session
│   ├── schema_compare.py     # Schema drift normalization
│   ├── models/
│   │   ├── __init__.py       # Imports all models
│   │   ├── base.py           # Base class + naming convention
│   │   ├── captures.py       # Captures, Observations, Taxa, Tags
│   │   ├── devices.py        # Devices, Commands, Status, Firmware
│   │   ├── ops.py            # Settings, AuditLog, BackupRun, Job
│   │   └── users.py          # Users, Sessions
│   ├── api/
│   │   ├── __init__.py
│   │   ├── app.py             # FastAPI app + lifespan
│   │   ├── deps.py            # Empty (potential for dependencies)
│   │   └── routes/
│   │       ├── __init__.py
│   │       └── health.py      # /api/v1/health, /healthz
│   ├── worker/
│   │   ├── __init__.py
│   │   ├── main.py            # Worker + scheduler
│   │   ├── queue.py           # Job queue (FOR UPDATE SKIP LOCKED)
│   │   └── handlers.py        # Job handlers (noop, prune_expired_commands)
│   └── cli.py                # CLI commands
├── migrations/
│   ├── env.py                # Alembic environment
│   ├── script.py.mako
│   └── versions/
│       └── 0001_initial.py    # Baseline migration
├── deploy/
│   ├── INSTALL.md
│   ├── poorbird.env.example
│   ├── poorbird-api.service
│   ├── poorbird-worker.service
│   └── Caddyfile
├── tests/
│   ├── conftest.py
│   ├── test_health.py
│   ├── test_queue.py
│   ├── test_schema_matches_models.py
│   └── test_config.py
├── alembic.ini
├── pyproject.toml
└── README.md

What's Missing for UI (Phase 3)

MISSING - Frontend:
webui/
├── src/
│   ├── components/
│   ├── hooks/
│   ├── store/
│   ├── utils/
│   ├── styles/
│   ├── App.tsx
│   └── main.tsx
├── public/
│   └── index.html
├── vite.config.ts
├── package.json
└── tsconfig.json

MISSING - Backend (UI Endpoints):
server/src/poorbird/api/routes/
├── gallery.py        # Capture listing, filtering
├── observations.py   # Observation CRUD
├── taxa.py           # Taxon search/autocomplete
├── tags.py           # Tag management
├── devices.py        # Device management (UI view)
└── auth.py           # Authentication endpoints

MISSING - Backend (Services):
server/src/poorbird/services/
├── auth.py           # Authentication service
├── image_service.py  # Image handling
└── gallery_service.py # Gallery queries

MISSING - Authentication:
├── Session management
├── Password hashing (Argon2id)
├── CSRF protection
└── Rate limiting

Implementation Status by Phase

Phase Status Components Tests
Phase 1 ✅ COMPLETE Server foundation, config, schema, health, job queue, scheduler 12/12
Phase 2 ❌ NOT STARTED Device endpoints (/enroll, /ingest, /heartbeat, /status, /config) 0/0
Phase 3 ❌ NOT STARTED WebUI (React+TS+Vite), UI endpoints, authentication 0/0
Phase 4 ❌ NOT STARTED Device management, OTA 0/0
Phase 5 ❌ NOT STARTED Operations (backup, retention, alarms) 0/0
Phase 6 ❌ NOT STARTED Streaming 0/0

7. Performance Analysis

Current Configuration

Component Setting Current Value UI Impact Rating Recommendation
DB Connection Pool db_pool_size 5 May block concurrent UI requests 3/5 15-20
Worker Poll Interval worker_poll_interval_s 2.0 Frequent polling on empty queue 3/5 5.0
Batch Size worker_batch_size 1 Single job processing 3/5 5-10
Sync SQLAlchemy - Enabled Blocks event loop under load 4/5 OK for current scale
Log Level log_level INFO Good for development 4/5 OK
Image Root image_root /srv/poorbird/images Good structure 5/5 OK
Thumb Root thumb_root /srv/poorbird/thumbs Good structure 5/5 OK

Expected UI Load Profile

Gallery Page:

  • Initial load: 20-50 images
  • Scroll load: 20 images per page
  • Filter queries: 100-500ms (with proper indexes)
  • Image size: 200-500KB (full), 20-50KB (thumb)
  • Concurrent requests: 3-5 typical, 10 peak

Search/Filter:

  • Date range: Fast (index on received_at)
  • Taxon filter: Fast (index on taxon_id)
  • Device filter: Fast (index on device_id)
  • Tag filter: Medium (many-to-many join)
  • Combined filters: Medium (proper indexing needed)

Image Operations:

  • Upload: ~200-500KB per image
  • Thumbnail generation: 100-300ms (Phase 2)
  • Storage per month: ~1GB (5000 images * 200KB)
  • DB writes per image: 3-5 (captures + device_status + observations)

Bottlenecks to Address Before UI

  1. DB Connection Pool (MEDIUM)

    • Current: 5 connections
    • Issue: May block under concurrent UI load
    • Solution: Increase to 15-20
    • Impact: Supports 10+ concurrent users
  2. No Query Caching (LOW)

    • Current: All queries hit DB
    • Issue: Repeated queries (e.g., taxon list) inefficient
    • Solution: Add Redis or in-memory cache
    • Impact: Faster UI response, reduced DB load
  3. Sync SQLAlchemy (FUTURE)

    • Current: Synchronous
    • Issue: Blocks event loop under heavy load
    • Solution: Evaluate async for Phase 6 (MJPEG streaming)
    • Impact: May be needed for high-concurrency scenarios
  4. Image Upload (MEDIUM)

    • Current: Not implemented
    • Issue: UI will need efficient image handling
    • Solution: Stream upload, validate, generate thumbnail
    • Impact: Critical for UI performance

Performance Recommendations for UI

Database

# db.py - Recommended changes
engine = create_engine(
    _settings.database_url,
    pool_size=15,  # Was 5
    pool_pre_ping=True,
    pool_recycle=3600,  # Recycle after 1 hour
    pool_timeout=30,    # Timeout after 30 seconds
    connect_timeout=10,
    echo=_settings.db_echo,
    future=True,
)

API

  • Pagination: All list endpoints must be paginated
  • Caching: Cache frequently accessed data (taxa, tags, device list)
  • Compression: Enable gzip/brotli compression
  • Etag: Add ETag headers for images

Images

  • Thumbnails: Pre-generate on ingest (Phase 2)
  • Lazy Loading: Only load visible images
  • Progressive: Show low-res preview first
  • CDN: Consider for production (not needed for LAN-only)

Frontend

  • Code Splitting: Split React bundles by route
  • Tree Shaking: Remove unused dependencies
  • Image Optimization: Use WebP, proper sizing
  • Bundle Analysis: Track and optimize bundle size

8. Testing Strategy

Current Test Status

Test File Type Status Requires Coverage
test_health.py Integration ✅ PASS PostgreSQL API health
test_queue.py Integration ✅ PASS PostgreSQL Job queue
test_schema_matches_models.py Integration ✅ PASS PostgreSQL + CREATE DB Schema drift
test_config.py Integration ✅ PASS None Config validation
conftest.py Fixtures ✅ PostgreSQL Test setup

Total: 12/12 tests passing (100%)

Missing Tests

Unit Tests (Frontend - Phase 3)

  • Component rendering tests
  • Hook tests
  • Utility function tests
  • Form validation tests
  • Tool: Jest + React Testing Library + @testing-library/user-event

Integration Tests (Backend - Phase 3)

  • UI endpoint tests
  • Authentication tests
  • Authorization tests
  • Tool: pytest + httpx + factory_boy

E2E Tests (Phase 3)

  • User flows: login → gallery → edit observation → logout
  • Tool: Playwright or Cypress

Performance Tests (Future)

  • Load testing for API
  • Stress testing for DB
  • Tool: locust or k6

Test Environment

  • Backend: Python 3.11+, PostgreSQL 17
  • Frontend: Node.js 18+
  • CI/CD: Not yet configured (GitHub Actions recommended)

9. UI Implementation Guide (FOR AI ASSISTANCE)

poorBird/
├── server/                    # Backend (Phase 1-2)
│   └── ...                   # Existing server code
│
└── webui/                    # Frontend (Phase 3) - TO BE CREATED
    ├── public/
    │   ├── favicon.ico
    │   └── index.html
    │
    ├── src/
    │   ├── assets/
    │   │   └── styles/
    │   │       ├── global.css
    │   │       ├── theme.css
    │   │       └── reset.css
    │   │
    │   ├── components/
    │   │   ├── common/
    │   │   │   ├── Button.tsx
    │   │   │   ├── Input.tsx
    │   │   │   ├── Modal.tsx
    │   │   │   ├── Card.tsx
    │   │   │   ├── Layout.tsx
    │   │   │   ├── Header.tsx
    │   │   │   └── Sidebar.tsx
    │   │   │
    │   │   ├── gallery/
    │   │   │   ├── GalleryGrid.tsx
    │   │   │   ├── ImageCard.tsx
    │   │   │   ├── ImageModal.tsx
    │   │   │   ├── Filters.tsx
    │   │   │   └── Pagination.tsx
    │   │   │
    │   │   ├── observation/
    │   │   │   ├── ObservationForm.tsx
    │   │   │   ├── ObservationList.tsx
    │   │   │   ├── TaxonAutocomplete.tsx
    │   │   │   └── SpeciesInfo.tsx
    │   │   │
    │   │   ├── settings/
    │   │   │   ├── DeviceSettings.tsx
    │   │   │   ├── UserSettings.tsx
    │   │   │   └── SystemSettings.tsx
    │   │   │
    │   │   ├── devices/
    │   │   │   ├── DeviceList.tsx
    │   │   │   ├── DeviceStatus.tsx
    │   │   │   └── DeviceCommands.tsx
    │   │   │
    │   │   └── auth/
    │   │       ├── LoginForm.tsx
    │   │       ├── RegisterForm.tsx
    │   │       └── AuthContext.tsx
    │   │
    │   ├── hooks/
    │   │   ├── useAuth.ts
    │   │   ├── useGallery.ts
    │   │   ├── useObservations.ts
    │   │   ├── useTaxa.ts
    │   │   ├── useDevices.ts
    │   │   └── useTheme.ts
    │   │
    │   ├── lib/
    │   │   ├── api.ts           # Axios instance + interceptors
    │   │   ├── constants.ts      # App constants
    │   │   ├── utils.ts          # Utility functions
    │   │   └── types.ts          # TypeScript type definitions
    │   │
    │   ├── store/
    │   │   ├── slices/
    │   │   │   ├── authSlice.ts
    │   │   │   ├── gallerySlice.ts
    │   │   │   └── uiSlice.ts
    │   │   └── store.ts          # Redux store configuration
    │   │
    │   ├── styles/
    │   │   ├── theme/
    │   │   │   ├── light.css
    │   │   │   ├── dark.css
    │   │   │   └── blue.css
    │   │   └── components/
    │   │       └── *.module.css
    │   │
    │   ├── App.tsx
    │   └── main.tsx
    │
    ├── vite.config.ts
    ├── .env
    ├── package.json
    └── tsconfig.json
{
  "name": "poorbird-webui",
  "version": "0.1.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview",
    "lint": "eslint src --ext .ts,.tsx",
    "test": "vitest",
    "test:ui": "vitest --ui",
    "test:coverage": "vitest --coverage"
  },
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "@tanstack/react-query": "^5.0.0",
    "@tanstack/react-router": "^6.20.0",
    "axios": "^1.6.0",
    "date-fns": "^3.0.0",
    "react-hot-toast": "^2.4.1",
    "lucide-react": "^0.300.0",
    "clsx": "^2.0.0"
  },
  "devDependencies": {
    "@types/react": "^18.2.0",
    "@types/react-dom": "^18.2.0",
    "@vitejs/plugin-react": "^4.2.0",
    "typescript": "^5.3.0",
    "vite": "^5.0.0",
    "eslint": "^8.56.0",
    "@typescript-eslint/eslint-plugin": "^7.0.0",
    "@typescript-eslint/parser": "^7.0.0",
    "eslint-plugin-react": "^7.33.0",
    "eslint-plugin-react-hooks": "^4.6.0",
    "vitest": "^1.0.0",
    "@testing-library/react": "^14.0.0",
    "@testing-library/user-event": "^14.5.0",
    "@testing-library/jest-dom": "^6.1.0",
    "@vitest/coverage-v8": "^1.0.0",
    "@vitest/ui": "^1.0.0",
    "jsdom": "^23.0.0",
    "tailwindcss": "^3.4.0",
    "postcss": "^8.4.0",
    "autoprefixer": "^10.4.0"
  }
}
{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "skipLibCheck": true,
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "include": ["src"],
  "references": [{ "path": "./tsconfig.node.json" }]
}
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
  server: {
    port: 3000,
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
      },
      '/images': {
        target: 'http://localhost:8080',
        changeOrigin: true,
      },
    },
  },
  build: {
    outDir: '../../server/deploy/webui',
    sourcemap: true,
  },
})

Backend Endpoints for UI (Phase 3)

Gallery:

# GET /api/v1/captures
# Query params: page, limit, device_id, taxon_id, date_from, date_to, kept, reviewed, tag
# Returns: Paginated list of captures with observations and tags

# GET /api/v1/captures/{id}
# Returns: Single capture with all observations, tags, device info

# GET /api/v1/captures/{id}/metadata
# Returns: Capture metadata only (smaller payload)

Observations:

# POST /api/v1/captures/{id}/observations
# Request: {"taxon_id": 123, "individuals": 2, "age": "adult", "sex": "male", ...}
# Returns: Created observation

# PUT /api/v1/observations/{id}
# Request: {"taxon_id": 123, ...}
# Returns: Updated observation

# DELETE /api/v1/observations/{id}
# Returns: Success

Taxonomy:

# GET /api/v1/taxa
# Query params: query, limit, offset, locale
# Returns: Paginated list of taxa with localized names

# GET /api/v1/taxa/autocomplete
# Query params: query, limit=10
# Returns: Top 10 matching taxa (local species first)

Tags:

# GET /api/v1/tags
# Returns: All tags with counts

# POST /api/v1/tags
# Request: {"label": "water", "colour": "#0066cc"}
# Returns: Created tag

Devices:

# GET /api/v1/devices
# Returns: List of devices with current status

# GET /api/v1/devices/{id}
# Returns: Device details + config

# PUT /api/v1/devices/{id}/config
# Request: {"heartbeat_interval_s": 600, ...}
# Returns: Updated config

Authentication:

# POST /api/v1/auth/login
# Request: {"username": "...", "password": "..."}
# Returns: Session cookie, user info

# POST /api/v1/auth/logout
# Returns: Success, clears session

# GET /api/v1/auth/me
# Returns: Current user info

# POST /api/v1/auth/register (if public registration enabled)
# Request: {"username": "...", "password": "...", "email": "..."}
# Returns: Created user, session

Settings:

# GET /api/v1/settings
# Returns: Current user's settings

# PUT /api/v1/settings
# Request: {"theme": "dark", "locale": "en"}
# Returns: Updated settings

10. Deployment for UI

Caddy Configuration (Updated for UI)

# /etc/caddy/Caddyfile

# PoorBird Server + UI
poorbird.local {
    # Root for static UI files
    root * /srv/poorbird/webui
    
    # Handle API requests
    handle_path /api/* {
        reverse_proxy 127.0.0.1:8080
    }
    
    # Handle image requests (auth-checked)
    handle_path /images/* {
        reverse_proxy 127.0.0.1:8080
    }
    
    # Handle thumbnail requests (auth-checked)
    handle_path /thumbs/* {
        reverse_proxy 127.0.0.1:8080
    }
    
    # Serve static files (SPA fallback)
    try_files {path} /index.html
    
    # Enable gzip compression
    encode gzip
    
    # Security headers
    header {
        X-Content-Type-Options "nosniff"
        X-Frame-Options "DENY"
        X-XSS-Protection "1; mode=block"
        Referrer-Policy "strict-origin-when-cross-origin"
        Permissions-Policy "camera=(), microphone=(), geolocation=()"
    }
    
    # TLS (automatic via DNS-01)
    # Uses Let's Encrypt
}

# Development: API only (no UI)
:8080 {
    reverse_proxy 127.0.0.1:8080
}

Build and Deploy Process

# Development
cd webui
npm install
npm run dev  # http://localhost:3000

# Production Build
npm run build  # Outputs to server/deploy/webui

# Deploy
rsync -avz ./dist/ user@server:/srv/poorbird/webui/

Environment Variables (Frontend)

# .env
VITE_API_URL=/api/v1
VITE_WS_URL=ws://localhost:8080
VITE_APP_NAME=poorBird
VITE_APP_VERSION=0.1.0

# For development (proxy)
VITE_API_BASE_URL=http://localhost:8080/api/v1

# For production
VITE_API_BASE_URL=/api/v1

11. Security Checklist for UI Development

Before Starting Phase 3

  • SEC-001: Enroll secret not in plaintext
  • SEC-002: Device authentication implemented
  • SEC-003: Input validation for all requests
  • SEC-004: Rate limiting configured
  • SEC-005: CORS configured
  • SEC-006: CSRF protection implemented
  • SEC-007: Session management implemented
  • SEC-008: DB URL not in defaults
  • Password hashing implemented
  • Image upload validation implemented

During UI Development

  • All API endpoints require authentication
  • All forms have CSRF protection
  • All user input is validated
  • All errors are handled gracefully
  • No sensitive data in logs
  • No sensitive data in error messages
  • All API responses have consistent structure
  • All API errors have consistent format

Before Production

  • Security audit completed
  • Penetration testing completed
  • All dependencies scanned for vulnerabilities
  • All secrets rotated
  • All sensitive endpoints rate-limited
  • All file uploads validated
  • All user sessions have expiration
  • All passwords hashed with Argon2id

12. Open Questions (NEED HUMAN DECISIONS)

ID Question Options Impact Decision By Status
Q3 Radar reliability at real distance - Blocks all Hardware testing OPEN
Q6 Number of cameras 1, 5, 10, 100 Architecture scaling Phase 4 OPEN
Q7 Captures/day 100, 1000, 10000 Storage, retention Phase 5 OPEN
Q8 Retention: Delete or hide? Delete file or soft-delete Data model Phase 5 OPEN
Q9 NAS protocol SFTP, SMB, NFS Backup tooling Phase 5 OPEN
Q11 UI language German, English, both Localization Phase 3 OPEN
Q12 Taxonomy source GBIF, IOC, Avibase Species data Phase 3 OPEN
Q13 Blue theme Reference or choice Styling Phase 3 OPEN
Q14 2FA Required or optional Security Phase 3 OPEN
Q15 Additional fields Weather, feeder type, etc. Schema Phase 3 OPEN
Q16 Comfort level C/Python/TS Team skills Phase 3 OPEN
Q17 Camera privacy Public path? GDPR Phase 3 OPEN

Decisions Made (DO NOT QUESTION)

Decision Rationale Source
Native deployment (not Docker) SPEC requirement TODO.md
PostgreSQL over loopback TCP Container-ready, better performance TODO.md
All mutable state in explicit dirs Future volume mounts TODO.md
Sync SQLAlchemy No async overhead for current scale README.md
Job queue without Redis Simplicity, no external dependency SPEC C8
FastAPI Modern, fast, good typing SPEC 6
Caddy Simple, automatic TLS SPEC 6
React + TS + Vite Modern, good DX, good performance TODO.md

13. Implementation Roadmap (Phase 3)

Week 1: Foundation

  • Fix CRITICAL security issues (SEC-001 through SEC-008)
  • Implement session management
  • Add CORS configuration
  • Add CSRF protection
  • Implement password hashing (Argon2id)
  • Create auth endpoints (login, logout, me)
  • Setup React + Vite project
  • Create basic layout and routing
  • Setup TypeScript, ESLint, Prettier
  • Create theme system (light, dark, blue)
  • Implement gallery API endpoints
  • Create Gallery component with virtualization
  • Add pagination
  • Implement ImageCard component
  • Add date/taxon/device/tag filters
  • Setup image lazy loading
  • Implement ImageModal for full-screen view
  • Add keyboard navigation (arrow keys)

Week 3: Editing

  • Implement observation CRUD endpoints
  • Create ObservationEditor with form
  • Add TaxonAutocomplete with search
  • Implement tag selection
  • Add device list and status view
  • Create device detail page
  • Add batch operations (select multiple images)

Week 4: Polish

  • Implement theme switching (persisted per user)
  • Add language support (i18n)
  • Write frontend unit tests
  • Write integration tests
  • Write E2E tests
  • Performance optimization
  • Security audit
  • Accessibility audit

Dependencies

graph TD
    A[Phase 1: Server Foundation] -->|Complete| B[Fix Security Issues]
    B --> C[Phase 2: Device Endpoints]
    C --> D[Phase 3: WebUI]
    D --> E[Phase 4: Device Management]
    E --> F[Phase 5: Operations]
    F --> G[Phase 6: Streaming]

14. What This AI Needs to Know

For Maximum Usefulness, Provide:

  1. The "Why" - Architecture decisions and rationale
  2. The "What" - Current state and what's missing
  3. The "How" - Code examples and patterns
  4. The "When" - Priority, phase, dependencies
  5. The "Who" - Who needs to decide what

Specific to This Project:

  1. This is a multi-phase project - Phase 1 is done, Phase 2 is next, Phase 3 (UI) is the target
  2. The branch name is misleading - It's server-only, but UI-ready
  3. Security is blocking - Cannot start UI without fixing CRITICAL issues
  4. The data model is excellent - Perfectly designed for the UI
  5. The deployment is UI-ready - Caddy can serve static files

What the AI Should NOT Do:

  1. Don't suggest Docker - Native deployment is a hard requirement
  2. Don't suggest Kubernetes - Explicitly ruled out
  3. Don't suggest SQLite - PostgreSQL is required
  4. Don't suggest changing the tech stack - It's already well-chosen
  5. Don't ignore the phase structure - Suggestions must respect the roadmap

What the AI SHOULD Do:

  1. Focus on Phase 3 - UI implementation
  2. Respect the architecture - Work within existing patterns
  3. Prioritize security - CRITICAL issues must be fixed first
  4. Provide code examples - Show, don't just tell
  5. Reference the SPEC - All decisions should align with SPEC.md

15. Summary: Action Items for AI

If Asked to Help with UI Development:

  1. First, verify security issues are fixed

    • Check if SEC-001 through SEC-008 are resolved
    • If not, prioritize those fixes
  2. Understand the phase structure

    • Phase 1: ✅ Done
    • Phase 2: ⏳ Should be done before Phase 3
    • Phase 3: ❌ Target (UI)
  3. Use the existing patterns

    • Follow the code structure in server/
    • Use the same typing conventions
    • Use the same error handling patterns
    • Use the same logging patterns
  4. Respect the contracts

    • Device API is defined in firmware/API.md
    • UI API should follow similar patterns
    • All endpoints should be under /api/v1/
  5. Focus on the gaps

    • UI code doesn't exist yet
    • UI endpoints don't exist yet
    • Authentication doesn't exist yet
    • Authorization doesn't exist yet

This AI reviewer guide was created by Mistral Vibe on 2026-09-21 for the poorBird project.