- F# 58.4%
- JavaScript 32.4%
- Nix 9.2%
| Migrations | ||
| nix | ||
| scriptable | ||
| .gitignore | ||
| Domain.fs | ||
| flake.lock | ||
| flake.nix | ||
| Frontend.fs | ||
| global.json | ||
| HabitTracker.Api.fsproj | ||
| packages.lock.json | ||
| Program.fs | ||
| README.md | ||
| Storage.fs | ||
Habit Tracker API
F# / .NET 11 API and management frontend, PostgreSQL archive, Evolve migrations, and Scriptable heatmap widgets. Habits are created and configured through the authenticated frontend or API. The database starts empty. Screen Time, Apple Reminders, Home Assistant, and Immich are not used.
Build
nix build
Or use the installed .NET 11 SDK:
dotnet restore --locked-mode
dotnet build --no-restore
There is no test suite. JavaScript syntax can be checked with:
node --input-type=module --check < 'scriptable/Habit Tracker.js'
After changing NuGet dependencies, update both lock files:
dotnet restore --force-evaluate
nix build .#default.fetch-deps --out-link /tmp/htapi-fetch-deps
/tmp/htapi-fetch-deps nix/deps.json
NixOS deployment
Import this flake's module and enable the service:
{
inputs.habit-tracker-api = {
url = "git+ssh://forgejo@git.steenblik.ch:2222/jblik/habit-tracker-api.git?ref=master&rev=<published-commit>";
inputs.nixpkgs.follows = "nixpkgs";
};
# In the NixOS configuration:
# imports = [ inputs.habit-tracker-api.nixosModules.default ];
# services.habit-tracker-api.enable = true;
}
The module runs as the Linux user htapi, listens on 127.0.0.1:5182, and connects
to the local PostgreSQL database htapi over /run/postgresql using peer authentication.
It does not create database roles or databases. The existing PostgreSQL service must be enabled.
The port and package service options can be overridden.
The companion nixos-server configuration adds the module and HTTPS proxy at
https://habits.steenblik.ch. Its input uses this repository's remote SSH URL,
with a pinned revision on master. Give the server's GitOps
deploy key read access to this repository, as with server-dashboard.
For future updates, publish the new API revision, update its rev in the server's
flake.nix, run nix flake update habit-tracker-api, and commit both flake files
before deployment.
1. Create the PostgreSQL role and database on the server
Run these once, before deploying the enabled API service:
sudo -u postgres createuser --no-superuser --no-createdb --no-createrole htapi
sudo -u postgres createdb --owner=htapi htapi
No database password is needed. PostgreSQL must allow local htapi htapi peer;
NixOS's normal local all all peer rule also covers this. If the database already
exists, inspect its owner rather than rerunning the creation commands.
2. Deploy the server configuration
From ~/projects/nixos-server, use the repository's documented deployment command:
nix run nixpkgs#nixos-rebuild -- switch --flake .#nixos-server --target-host nixos-server --build-host nixos-server --use-substitutes --sudo --ask-sudo-password
On the server, check:
sudo systemctl status habit-tracker-api
sudo journalctl -u habit-tracker-api -n 50
sudo -u htapi psql -h /run/postgresql -d htapi -c '\conninfo'
curl --fail https://habits.steenblik.ch/health
The existing proxy setup requests the certificate and adds the hostname to dynamic DNS.
On startup Evolve applies Migrations/V*.sql and records its migration history.
Schema changes belong in new migrations; do not edit a migration after deployment.
Evolve erase is disabled. A failed migration prevents API startup.
3. Obtain the API token
The service creates a random token on its first start and preserves it across restarts:
sudo cat /var/lib/habit-tracker-api/api-token
Keep this value for Scriptable setup. API requests require Authorization: Bearer <token>.
/health, /widget.js, and the sign-in page are unauthenticated and contain no private habit data.
The token lives outside the Nix store and repository. Back up the service's
/var/lib/habit-tracker-api directory separately from the database. It also
contains the frontend's form-security keys; systemd restricts this directory to htapi.
4. Create and edit habits
Connect the iPhone or computer to Tailscale and open
https://habits.internal.steenblik.ch. Sign in with the API token above.
This frontend is restricted to VPN addresses (including direct LAN access being denied).
The public hostname only exposes the API, health check, and Scriptable download;
it does not expose the frontend or its login and management routes.
Use Add a habit to choose its name, color, type, target, units, and direction. Leave the widget ID blank to generate one from the name, or enter your own. The ID stays fixed after creation. Existing habits have Save changes forms, and each habit has a form to record or correct daily totals. Under Edit daily values, choose an Entry date and press Load values to see the saved entries for that day. Change a value and press Save value; the chosen date stays selected. Dates older than the heatmap are supported; future dates are rejected. Boolean input writes 0 or 1; choose numeric input for arbitrary units such as pages, minutes, or repetitions. No habits are preinstalled.
For example, create Work out and Stretch as boolean habits with target 1, and
Read as a numeric habit with unit pages and target 20. Choose Good for all
three. A future Screen Time habit can use numeric input, unit minutes, target
120, and Bad. Screen Time collection is still not implemented.
Good habits get brighter as the value approaches the target. Bad habits start fully colored at a recorded zero and fade to gray at the target or above. Missing days stay gray in both directions. The target is a full-scale value, not an automatic daily entry or an alert threshold. Values can exceed the target and are preserved in full; only displayed color intensity is capped.
Scriptable still uses the public https://habits.steenblik.ch API address.
Its token-authenticated API updates remain available without the VPN so widget
interactions work while away; the VPN restriction applies to the management frontend.
You can also create a habit through the API:
htapi_token=$(sudo cat /var/lib/habit-tracker-api/api-token)
curl --fail-with-body --silent --show-error https://habits.steenblik.ch/api/habits \
-H "Authorization: Bearer $htapi_token" -H 'Content-Type: application/json' \
--data '{"id":"read","name":"Read","color":"#4bb8f5","target":20,"type":"count","unit":"pages","inverted":false}'
unset htapi_token
iPhone: Scriptable setup
- In Safari on the iPhone, open
https://habits.steenblik.ch/widget.jsand copy the entire script. Alternatively transferscriptable/Habit Tracker.jsto the phone. - Open Scriptable, tap +, and paste the script. Name it Habit Tracker.
- Run it using the play button. Enter
https://habits.steenblik.chand the token obtained above. Both values are saved in Scriptable's iPhone Keychain, not the script. - Choose a habit, then choose a Home Screen or Lock Screen preview. Running the script manually again lets you change the API address or token.
- Return to the Home Screen, press and hold an empty area, then choose Edit → Add Widget → Scriptable. Add a small or medium widget.
- Press and hold the widget and choose Edit Widget. Set Script to
Habit Tracker, When Interacting to Run Script, and Parameter to
the exact Widget ID shown in the frontend (for example,
work-out). - Repeat for two more widgets, using each habit's ID (
stretchandreadif you used those names with automatically generated IDs). Both sizes use the same script; it detects the size automatically. Small widgets show 8 week columns; medium widgets show 18 week columns. Both have seven rows, a compact centered name/current-value header, and no buttons or hint text. The grid is centered horizontally and vertically in the space below the header. The leftmost week always starts on Monday with all seven days; the current week on the right ends at today. The shorter display does not remove older history. - On supported iOS 17+ Scriptable versions, tap the workout or stretching title or heatmap to switch today's value inline without opening the app. No or an unrecorded day becomes Yes; tap again after the redraw to switch Yes back to No. The content is the control, with no visible button or app-launch link. Versions without stack actions fall back to editing inside Scriptable.
- For every numeric habit (
count), tap the title/value to cycle inline through 25%, 50%, 75%, 100%, then 0 of its configured target. A target of 100 pages gives 25 → 50 → 75 → 100 → 0. Steps round to whole units; duplicate rounded steps are skipped. An unrecorded day starts at the first positive step. A manually entered value advances to the next higher step; values at or above target wrap to zero. Tap anywhere else on the widget to open Scriptable's number-entry popup, enter today's total, and save. Entering 20 twice still means 20. Newly created numeric habits use this automatically.
Widget edits always use the server's current day. Historical editing is only
available in the frontend or the daily-value API. Missing entries remain null,
not an automatically saved zero. Both missing and explicit No (0) appear gray
for a good habit, but the widget labels missing entries Not recorded. For bad
habits the distinction matters: a recorded zero is fully colored, while a missing
entry stays gray.
When the server's script changes, replace the code inside Scriptable using the
new /widget.js download; installed iPhone scripts do not update automatically.
Your existing Keychain settings and widget parameters can be reused.
For a Lock Screen widget, hold the Lock Screen, choose Customize → Lock Screen, tap the widget area, and add Scriptable's circular (tiny) or rectangular (double-width) widget. Tap its configuration, select Habit Tracker, set the parameter to the habit's Widget ID, and choose Run Script for interaction if shown. The same script detects the Lock Screen size automatically: circular shows 7 week columns (up to 49 squares) and rectangular shows 22 (up to 154), both with seven Monday-first rows. Lock Screen widgets show a small centered habit name above the centered heatmap, without the current value. The heatmap keeps every square inside the circular mask on tiny widgets and fills the width below the title on rectangular widgets. Cells stay square; the current week ends at today. You can preview both sizes by running the script manually.
On supported iOS 17+ Scriptable versions, tapping anywhere on either Lock Screen widget updates today's value inline: Yes/No habits toggle, and numeric habits cycle through the same 25%, 50%, 75%, 100%, then 0 steps. There is no number-entry popup on the Lock Screen. Versions without stack actions fall back to editing inside Scriptable. iOS may require unlocking for an action and controls the widget's monochrome tint and background. It cannot preserve the Home Screen's full colors and black background.
Widgets request a refresh every 30 minutes; iOS decides when to actually run them. Inline widget actions save and redraw the widget, updating both the value and heatmap. Each action applies the displayed next value for today's server date; a stale action from yesterday only refreshes the display. Edits made in Scriptable may take until the next widget refresh to appear on the Home Screen. Saving or cancelling a widget edit finishes without opening a preview; previews are only shown when running the script manually for setup. Cached history can be shown offline, with Offline in the header; updates require connectivity. Reading's free-form number popup requires opening Scriptable; it cannot be entered inline in a widget. Input popups run inside Scriptable, not inside the widget itself.
API
All /api endpoints require the bearer token. JSON uses camelCase.
| Method | Path | Purpose |
|---|---|---|
| GET | /api/habits |
List habit configurations |
| POST | /api/habits |
Create a habit; duplicate IDs return 409 |
| PUT | /api/habits/{id} |
Replace settings, including name, color, and target |
| GET | /api/habits/{id}/history |
Configuration and latest 372 daily values |
| PUT | /api/habits/{id}/days/{yyyy-MM-dd} |
Save {"value":23} for a calendar day |
Habit settings use the same body as the creation examples. IDs are immutable.
Settings include type (boolean or count), unit (possibly empty), and
inverted (true for bad habits). All values are nonnegative integers; there is no binary field or
type-specific storage constraint. Type only selects a boolean or numeric input
control. The boolean control writes 0 or 1; target 1 is a useful choice for it,
but is not enforced. Changing type preserves history, even values above 1.
Target and inverted alone determine heatmap intensity. The initial Evolve
migration creates this schema directly.
Future dates are rejected; older dates remain editable. Repeated daily writes
replace the value rather than adding to it.
History includes habit, today, start, and days:[{"date":"2026-12-01","value":null}].
The API returns the latest 372 days. Home Screen widgets show a Monday-first
window of 8 or 18 weeks, with seven rows; future dates in the current week are blank. Dates are calculated on the server in Europe/Zurich, regardless
of the phone's timezone. Missing days have null values and appear dark gray. Recorded zero-value days
are gray for good habits and fully colored for bad habits; no past history is invented. Values are kept indefinitely in
PostgreSQL, including days outside the visible window. Daily totals remain unchanged
when the calendar rolls over; the next day starts with no entry.
Back up the htapi PostgreSQL database using the server's database backup policy.
The existing server configuration already places PostgreSQL on the snapshotted ZFS
dataset; snapshots are separate from an off-server backup.