Calio/README.md
Elijah 8f6981c8a2
All checks were successful
Verify and publish Calio container / build-and-push (push) Successful in 29s
Apply app updates automatically and survive proxy caching
- Check for a new service worker on every return to the foreground and
  every 30 minutes; apply it in the background or just after launch,
  never with unsynced edits or an open sheet. The Update prompt remains.
- Register the worker at extension-less /sw (no-cache), so proxies that
  cache *.js regardless of headers cannot hide updates
- Return 404 for missing files instead of the HTML shell
- Tests for the static routes; smoke test covers /sw; document the Nginx
  Proxy Manager "Cache Assets" pitfall

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 11:19:30 -07:00

118 lines
18 KiB
Markdown
Raw 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.

# Calio
A single-user, self-hosted nutrition journal. PWA first, with a responsive desktop layout, light/dark/system themes, configurable accent colors, and no third-party analytics, fonts, or nutrition services. Dark mode uses neutral near-black and charcoal surfaces; choose a preset or custom accent under Settings → Look & feel; it applies immediately. Accent preferences sync between devices and remain available offline.
## Included
- Daily calorie vessel with colliding physics bubbles, week navigation, meal journal, editable entries, fractional servings. New bubbles drop from the top as calories increase.
- Food names are optional: unnamed daily entries use the meal name and next available number, such as `Dinner 1`. The main Add food action suggests breakfast from 5–11am, lunch from 11am–4pm, dinner from 4–10pm and snacks overnight, using the device's local time. Meal-specific add buttons preserve their category; the selection remains editable.
- Food entries include an editable local clock time, shown in the journal and all export formats. Existing entries without a time remain valid and show “Time not recorded” until you add one. Entries sort by time within each meal.
- Saved foods and reusable plates; **Log** on a library card opens the food sheet pre-filled. Logging a plate creates an atomic batch of independent food entries. Logs retain a nutrition snapshot when library foods change.
- Independently enabled calorie, protein, carbohydrate, fat, fiber, sugar and sodium goals.
- Weight journal in lb or kg; internally stored in kg. Multiple weigh-ins are retained, with the latest measurement per day used in charts.
- Dedicated Weight tab on desktop and mobile, with its own logging, graph and journal. Nutrition trends live under Library → Trends. Both support 7 / 30 / 90 / 365 day periods. Nutrition averages exclude empty and likely incomplete days: the initial cutoff is half the calorie target, adjustable under Settings → Nutrition averages (0 includes all logged days). Every nutrient uses the same qualifying days; faded bars and exports retain actual totals. This is a logging heuristic, so adjust it for your own routine. Any settings change stores the cutoff in kcal, independently of later goal changes.
- Settings save automatically as you change them: theme and accent switch instantly, and number fields commit after a short pause, on Return, or when you leave the field.
- On phones, swipe left/right through Today → Library → Weight → Settings. Neighboring screens are already rendered and move together under your finger; settling uses a composited slide with no fade-to-blank delay. Every tab retains its own scroll position. Vertical scrolling, form controls, horizontal macro scrolling, and browser edge gestures remain independent. The calorie simulation pauses on other tabs. Pull down from a sheet header to dismiss it. System Reduce Motion disables these transitions.
- Markdown, CSV and JSON export with date range, nutrient and weight selections. Markdown is designed for LLM analysis. Data is downloaded locally, never submitted to an LLM. Each download remembers the export format, range preset and selections for next time.
- Password authentication, IndexedDB offline journal/outbox, a precached app shell, automatic foreground/reconnect sync, and automatic app updates: each return to the foreground checks for a new version, which applies in the background or right after launch (never with unsynced edits or an open sheet), with an Update prompt to switch immediately.
### Phone layout
On phones, Today fills the available screen, including iPhone safe areas, with the calorie circle, readout, macros and navigation visible together. **Food journal** opens the selected day's meals in a separate scrollable sheet; adding, editing and removing entries open on top of it, and you return to the journal afterwards. Desktop retains the side-by-side dashboard and meals. Compact screens use the date picker instead of the full week strip, and landscape arranges the circle beside the totals. If more than three nutrient goals are enabled, swipe the macro row horizontally to see the rest.
Phone controls use larger type, 44–56 px tap targets, and 51×31 px switches. Food entry uses full-width day/time/meal rows, explicitly constrained native input widths, and a sticky sheet header. Library, Weight and Settings scroll normally.
The iPhone Home Screen icon uses a dark background and high-contrast mark so automatic tinting has a dark base instead of a bright colored square. The versioned Apple touch-icon URL lets new installations request the revised asset; Android keeps its existing regular and maskable icons. iOS owns the final tinted/clear rendering, so a PWA cannot guarantee the native Icon Composer appearance. If an existing Home Screen shortcut retains its old cached icon, first sync all pending entries, then add Calio to the Home Screen again. The server's database is unchanged.
Barcode lookup and nutrition-label OCR are deferred. This release uses manual nutrition entry and saved foods. It does not include Apple Watch integration, HealthKit, fasting, reminders or water tracking; those screenshot features were not part of the requested core.
## Deploy on Unraid
Forgejo builds and publishes the image; Unraid runs it through **Docker → Add Container**. Compose is optional and is not required for deployment. Follow [the Unraid setup guide](docs/UNRAID.md), or import [the Docker template](unraid/calio.xml).
Use repository `git.elijahkuntz.com/elijah/calio:latest`, container port `3000` (suggested host port `3080`), and a persistent mapping from `/mnt/user/appdata/calio` to `/data`. Set `APP_ORIGIN` to the exact **HTTPS origin, without a trailing slash**, `CALIO_USERNAME` to your username, and `CALIO_PASSWORD` to a unique password of at least 12 characters. There is no registration screen or default password. The template runs as Unraid's `99:100`; the mapped directory must be writable by that user. The image's standalone default is UID 1000.
Forward your HTTPS reverse proxy to `http://<Unraid-IP>:3080`, or to `calio:3000` on a shared Docker network. All paths, including `/api`, must reach Calio. Open the public HTTPS address and sign in once while online. On iPhone, use Safari → Share → **Add to Home Screen**. On Android, use Chrome's **Install app** / **Add to home screen**. Desktop browsers work too.
The registry image becomes available after the source is pushed and the first publishing workflow succeeds. See the Forgejo setup below for the required registry secret.
HTTPS is required for installed-device service workers and secure authentication cookies. `COOKIE_SECURE=false` is accepted only when `APP_ORIGIN` uses `localhost` or `127.0.0.1`; use it solely for local tests. Production defaults to Secure, HttpOnly, SameSite=Strict cookies.
For an optional local source trial, copy `.env.example` to `.env`, set a password, `APP_ORIGIN=http://localhost:3000` and `COOKIE_SECURE=false`, then run `docker compose up -d --build` and visit `http://localhost:3000`. These local settings cannot be used to install from a phone over a LAN IP.
### Credentials and secrets
The server supports `CALIO_PASSWORD`, `CALIO_PASSWORD_FILE`, `CALIO_PASSWORD_HASH`, or `CALIO_PASSWORD_HASH_FILE`. File variants accept Docker secrets. A hash avoids retaining a plaintext password in container configuration. Generate a salted scrypt hash by piping a password into `npm run --silent password` (stdin only). Do not put real passwords in shell history.
When using a hash, replace the `CALIO_PASSWORD` container variable with `CALIO_PASSWORD_HASH`. For a file, mount it read-only and set the appropriate `_FILE` variable to its container path. `.env` and runtime data are ignored by Git.
Sessions expire after 30 days and persist in SQLite. Changing credentials does not revoke existing sessions automatically. To invalidate all sessions, stop the app and delete the rows from the `sessions` table using a SQLite tool, then restart. The public login is rate limited to 10 requests per 15 minutes per connection IP; behind a proxy this conservatively shares the limit across clients. The app does not trust arbitrary forwarded-IP headers.
## Persistent data, updates and backups
SQLite lives at `/data/calio.sqlite`, mapped to `/mnt/user/appdata/calio` on Unraid. Keep this directory and mapping when replacing the image. The optional Compose setup uses a named `calio-data` volume instead. Schema migrations are versioned and transactional; an older app refuses to open a newer schema.
Before updating, make a consistent backup while Calio is running:
```sh
docker exec calio node server/backup.js /data/backups/before-update.sqlite
docker cp calio:/data/backups/before-update.sqlite ./calio-backup.sqlite
```
Choose a new filename for each backup. `VACUUM INTO` captures a consistent SQLite snapshot, including committed writes in WAL; copying only the live main database file is not a safe backup. Keep a copy off the server. Nutrition exports are useful for analysis but are **not** full database backups (they omit library data, tombstones and sessions).
Use Unraid's **Check for Updates → Update** to pull the new `latest` image and recreate the container with its saved settings. Forgejo publishes images; it does not automatically update or restart Unraid. You can pin the repository field to a full commit SHA or a published `v*` version tag for repeatable deployment. The PWA will offer **Update** after loading online; accepting it changes app code without clearing IndexedDB. Pending local changes must sync before applying an update.
To restore a database backup: stop Calio, preserve the current data directory, replace `calio.sqlite` with the backup, and remove the old `calio.sqlite-wal` and `calio.sqlite-shm` sidecars **while stopped**. Preserve ownership for the configured container user (`99:100` with the Unraid template; `1000:1000` by default), then restart. A server-only restore does not remove newer records already cached on devices: those may sync back. For a deliberate rollback, export pending device changes first, clear this site's device storage on each device, then sign in and fetch the restored journal. Do not clear device storage before saving unsynced entries.
### Offline and conflict behavior
- After the first authenticated sync, the complete journal, settings, food library and plates are held in IndexedDB. The complete current day can be reopened, edited, logged and exported offline.
- An IndexedDB transaction saves each local mutation and its outbox entry together. A plate's entries are saved as one transaction. Requests acknowledge only the exact versions sent, so a local edit made during a sync remains queued.
- Sync runs on app start, reconnect, return to the foreground, and once a minute while visible. It does not depend on iOS background sync support. If a server is unavailable, entries remain on-device and a retry status is shown.
- Independent record additions merge. Edits to the same record use the latest device edit timestamp; exact ties use an ordinal payload comparison for the same result on all devices. Settings are one record, so the latest complete settings edit wins. Deletions are retained as tombstones so stale devices cannot resurrect records. Requests are retried idempotently.
- Keep device clocks accurate. Edits over five minutes ahead of the server are rejected with a visible sync error; they remain on-device and can be exported. Once the server clock catches up they can sync. This avoids a bad device clock permanently outranking normal edits.
- An expired session preserves the local journal and asks for sign-in to resume server sync. Explicit sign-out requires pending changes to sync, then removes this device's journal. The offline cache is accessible to someone with access to this unlocked browser/device; it is not an encrypted vault.
- Browser storage can be cleared or evicted by the OS. Calio requests persistent storage, but the browser decides whether to grant it. Sync and backups remain the durable record. Check the sync status before clearing browser data or leaving a device.
- Each sync currently exchanges the complete record set. This keeps the single-user implementation auditable and caches all history; very large multi-year journals may eventually benefit from incremental pagination.
### Bubble motion
Enable **Settings → Look & feel → Tilt calorie bubbles** to allow device orientation. On iPhone, Safari asks for motion/orientation permission from that gesture; the public site must use HTTPS. The preference stays saved on this device across reopening, independently of browser permission. If iOS needs motion access again, Calio resumes it on your first normal interaction; Settings also provides **Allow motion** if needed. A denied request keeps the preference on and explains why tilt is unavailable. Sensor readings are never transmitted. Portrait, landscape and upside-down positions are mapped to the screen's gravity direction. Devices without sensors, or with permission denied, retain downward gravity.
The circle uses a bounded Matter.js simulation: bubbles collide with each other and the circular wall, new calorie bubbles drop from the top at 30 per second (50% faster than the original pace), and removing calories removes the corresponding particles. Bubbles draw smaller than their collision boundaries, creating a small visible gap between them. A full hexagonal packing defines the 100% capacity. The numeric readout always sits below the circle, leaving every dot visible. The particle count caps at the daily goal; over-goal calories still show the exact excess and a red ring. With the calorie goal disabled, the display uses a fixed 2,500 kcal visual scale. Macro bars animate when totals change, and rows with one or two tracked macros are centered. Motion honors the device's reduced-motion preference. The physics animation sleeps when settled and pauses in hidden tabs. The graphic is an approximate visual; the numeric calorie total is authoritative.
## Forgejo CI and container registry
`.forgejo/workflows/build.yml` runs on every branch/tag push, pull request and manual dispatch. It installs locked dependencies, runs tests and a production build, builds the Docker image, and runs `scripts/container-smoke.js` with both the image default user and Unraid's `99:100`. The smoke test uses temporary containers/volumes, verifies auth and static assets, and recreates the container to verify journal/session persistence. Probes run inside the container, so socket-mounted runners do not depend on host port forwarding.
The workflow matches the existing Docker-capable `unraid-runner` label, `ubuntu-latest`, and uses the same secret name as the Study pipeline:
- In Forgejo account **Settings → Applications**, create a token with `write:package` permission. In Calio **Settings → Actions → Secrets**, save it as `FORGEJO_PAT`. A secret configured only on Study is not automatically available to Calio. Keep the token out of source files and chat.
- Optionally set repository variable `REGISTRY_USERNAME` if the token owner differs from the repository owner.
- Ensure the registry is enabled at `git.elijahkuntz.com` and the runner can reach Docker Hub/GitHub actions and npm.
- Every successful push publishes `git.elijahkuntz.com/elijah/calio:<full-commit-SHA>`.
- Successful default-branch (`main`) builds also update `:latest`. Before promotion, the workflow checks the remote branch head to avoid promoting an already superseded build.
- Valid `v*` tags also publish a version alias, such as `:v0.1.0`. Other branches and release tags do not overwrite `:latest`.
- Pull requests verify without publishing or requiring registry credentials. Deleted refs are skipped. Manual dispatch uses the same publication rules as a push.
- Each workflow run uses a unique local image tag, keeping concurrent builds separate. The workflow does not deploy to or restart your server.
The repository configuration is ready, but a successful live publish still requires `FORGEJO_PAT` and the initial source push. No token, registry publication or server deployment has been performed locally.
## Develop and verify
Node 24+ is required for built-in SQLite. `npm ci` installs the lockfile. `npm test` covers authentication, validation, deterministic merges, tombstones, persistence, and client outbox handling.
For a production preview, run `npm run build`, configure the same environment variables above, then `npm start`. For live UI editing, run `npm run dev:server` on port 3000 and `npm run dev` on port 5173, with `APP_ORIGIN=http://localhost:5173` and `COOKIE_SECURE=false`. Vite proxies `/api`; the service worker is registered only in production builds.
```sh
npm test
npm run build
docker build -t calio:local .
node scripts/container-smoke.js calio:local
node scripts/container-smoke.js calio:local --unraid
```
App code is in `src/`, shared schemas/merge rules in `shared/`, and the Express/SQLite server in `server/`. The handwritten service worker is generated from production asset hashes by `scripts/build-sw.js`. Icons are committed PNGs; `scripts/generate-icons.ps1` regenerates them on Windows without external assets.
The read-only browser regression expression in `tests/browser/mobile-layout.check.js` checks Today height, visible macros/readout, navigation type and tap targets, Settings switches, and food-editor input bounds. Load its text into the browser tool's `playwright.evaluate` at phone sizes, on Today, Settings, and an open food editor; `pass` must be true. Verify small/tall portrait screens, landscape, safe-area insets, all enabled macros, and journal-to-editor actions. It runs against rendered DOM rather than asserting stylesheet strings; it is separate from the Node-only unit suite.