diff --git a/docs/api.md b/docs/api.md index f0fa8058..f0da2e0a 100644 --- a/docs/api.md +++ b/docs/api.md @@ -6,7 +6,7 @@ Listens on **port 80** after STA Wi-Fi connects, or during setup AP mode at `htt Outbound events (device → host) use a separate WebSocket on **port 81** at path `/events` while this HTTP server is running, and the same JSON on USB serial as `Evt` frames. See [Outbound events](#outbound-events). -Optional auth: when an `access_token` is configured in settings, all JSON API routes require `Authorization: Bearer `. Empty token (default) means no auth. `GET /auth` is always public and reports whether auth is required. Missing/wrong token → **401** `{"ok":false,"error":"unauthorized"}`. HTML panel routes stay public (the UI prompts for the token). Replies are `Content-Type: application/json`. Routes that take parameters (except `POST /anim` and `/play`) read a JSON object body sent with `Content-Type: application/json`; query parameters or form fields on those routes → **400** `send a JSON body with Content-Type: application/json`, and a body that is not a JSON object → **400** `body must be a JSON object`. CORS: requests with an `Origin` header get `Access-Control-Allow-Origin: *`, `Access-Control-Allow-Headers: Authorization, Content-Type` and `Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS`; a preflight `OPTIONS` gets **200**. +Optional auth: when an `access_token` is configured in settings, all JSON API routes require `Authorization: Bearer `. Empty token (default) means no auth. `GET /auth` is always public and reports whether auth is required. Missing/wrong token → **401** `{"ok":false,"error":"unauthorized"}`. HTML panel routes stay public (the UI prompts for the token). Replies are `Content-Type: application/json`. Routes that take parameters (except `POST /anim` and `/play`) read a JSON object body sent with `Content-Type: application/json`; query parameters or form fields on those routes → **400** `send a JSON body with Content-Type: application/json`, and a body that is not a JSON object → **400** `body must be a JSON object`. CORS: requests with an `Origin` header get `Access-Control-Allow-Origin: *`, `Access-Control-Allow-Headers: Authorization, Content-Type` and `Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS`; a preflight `OPTIONS` gets **200**. When the robot is not yet provisioned (no connection mode chosen), control APIs (`/anim`, `/test/*`, `/play`) return **503** `{"ok":false,"error":"not provisioned"}`. Setup routes (`/`, `/config`, `/auth`, `/health`, `/settings`, `/setup/servo`, `/setup/led`, `/setup/audio`, `/setup/oled`, `/servos/park`) stay available on the setup AP. Connection mode is `wifi` or `usb` (`link_mode` in settings/auth/health). USB-only mode disables Wi‑Fi station and the HTTP API after reboot; control then uses the USB serial protocol ([serial.md](serial.md)). @@ -171,6 +171,12 @@ curl http://tiny-engineer.local/settings "serial_log": false, "push_button": false, "push_button_pin": 20, + "lcd1602": false, + "lcd1602_backlight_sleep": true, + "lcd1602_welcome_hello": false, + "lcd1602_boot": "none", + "lcd1602_line1": "", + "lcd1602_line2": "", "continuous_timeout": 5, "loading": "progress", "eyes_style": "classic", @@ -194,6 +200,11 @@ curl http://tiny-engineer.local/settings | `serial_log` | USB serial debug logging (default **false**). When off, diagnostic `Serial` output is suppressed | | `push_button` | Extension-port push-button reader (default **false**). When on, publishes immediate `button.down` / `button.up` plus `button.click` / `button.double_click` / `button.long_click` (see [Outbound events](#outbound-events)). Applies **immediately**. Local reactions use [Actions](#get-settingsactions) | | `push_button_pin` | GPIO on the Extension port for the push-button: **6**, **7**, **20**, or **21** (default **20**). Persists when `push_button` is off. Applies **immediately** when the extension is on | +| `lcd1602` | Waveshare LCD1602 I2C extension (default **false**). When on, serves `/extensions/lcd1602/…`. Applies **immediately**. Emits no events | +| `lcd1602_backlight_sleep` | Follow sleep: dim backlight on sleep and light to **100** on wake (default **true**). When false, enable/boot turns backlight on (including when `last` brightness is 0) and sleep/wake leave brightness alone. Persists when off. Applies **immediately** | +| `lcd1602_welcome_hello` | Show centered **HELLO** / **HUMAN** on the LCD during every `welcome` animation (default **false**). Text/clear during the overlay queues (last-wins); `GET` returns logical stash/pending, not HELLO. Persists when off. Applies **immediately** | +| `lcd1602_boot` | Boot content: `none`, `last`, or `config` (default **`none`**). Persists when off. Applies **immediately** | +| `lcd1602_line1` / `lcd1602_line2` | Configured boot lines when `lcd1602_boot` is `config` (max **64** chars each, no C0 control bytes, default empty). Persists when off. Applies **immediately** | | `continuous_timeout` | Minutes a continuous animation (`typing` / `reading` / `thinking` / `talking`) may run before the firmware switches to `attention` then idle (default **5**) | | `loading` | Boot loading screen: `progress` (bar + large IP for 3 s) or `sleep_inertia` (eyes wake; no bar/IP). Default **`progress`**. Applies on **next reboot** | | `eyes_style` | OLED eyes look: `classic` (procedural rounded eyes), `kaomoji` (animated faces), `cover` (full-half bars for an eye-hole mask), `dots` (12×12 circles), or `kawaii` (round eyes with big moving pupils, a talking mouth, and blush). Default **`classic`**. Applies **immediately**. Classic, cover, and dots sequences are described under [`POST /anim`](#post-anim); kaomoji face mapping is under [Kaomoji eyes](#kaomoji-eyes); cover drawing is under [Cover eyes](#cover-eyes); dots drawing is under [Dots eyes](#dots-eyes); kawaii moods are under [Kawaii eyes](#kawaii-eyes) | @@ -209,12 +220,15 @@ curl http://tiny-engineer.local/settings ### `POST /settings` -Update one or more settings from a JSON object body. Values are written to NVS. `sleep_timeout`, `volume`, `welcome`, `serial_log`, `push_button`, `push_button_pin`, `continuous_timeout`, `eyes_style`, and `access_token` apply immediately; a changed `hostname` or `loading` takes effect on the **next reboot**. WiFi networks are set with [`PUT /settings/wifi`](#put-settingswifi). On-device Actions are set with [`PUT /settings/actions`](#put-settingsactions). Servo ranges (`servo_mins` + `servo_maxs`), RGB LED mapping (`rgb_order`) and OLED rotation (`oled_rotate_180`) are **setup AP only** and apply immediately. Requires Bearer when auth is enabled. +Update one or more settings from a JSON object body. Values are written to NVS. `sleep_timeout`, `volume`, `welcome`, `serial_log`, `push_button`, `push_button_pin`, `lcd1602`, `lcd1602_backlight_sleep`, `lcd1602_welcome_hello`, `lcd1602_boot`, `lcd1602_line1`, `lcd1602_line2`, `continuous_timeout`, `eyes_style`, and `access_token` apply immediately; a changed `hostname` or `loading` takes effect on the **next reboot**. WiFi networks are set with [`PUT /settings/wifi`](#put-settingswifi). On-device Actions are set with [`PUT /settings/actions`](#put-settingsactions). Servo ranges (`servo_mins` + `servo_maxs`), RGB LED mapping (`rgb_order`) and OLED rotation (`oled_rotate_180`) are **setup AP only** and apply immediately. Requires Bearer when auth is enabled. ```bash curl -X POST "http://tiny-engineer.local/settings" \ -H "Content-Type: application/json" \ -d '{"volume":40,"welcome":false,"eyes_style":"kaomoji"}' +curl -X POST "http://tiny-engineer.local/settings" \ + -H "Content-Type: application/json" \ + -d '{"lcd1602":true,"lcd1602_boot":"config","lcd1602_line1":"HELLO","lcd1602_line2":"HUMAN"}' curl -X POST "http://tiny-engineer.local/settings" \ -H "Content-Type: application/json" \ -d '{"access_token":""}' @@ -233,6 +247,12 @@ curl -X POST "http://192.168.4.1/settings" \ "serial_log": false, "push_button": false, "push_button_pin": 20, + "lcd1602": false, + "lcd1602_backlight_sleep": true, + "lcd1602_welcome_hello": false, + "lcd1602_boot": "none", + "lcd1602_line1": "", + "lcd1602_line2": "", "continuous_timeout": 5, "loading": "progress", "eyes_style": "classic", @@ -257,6 +277,11 @@ curl -X POST "http://192.168.4.1/settings" \ | `serial_log` | boolean | USB serial debug logging | | `push_button` | boolean | Extension-port push-button (default **false**) | | `push_button_pin` | integer | Extension-port GPIO **6**, **7**, **20**, or **21** (default **20**); persists when off | +| `lcd1602` | boolean | Waveshare LCD1602 extension (default **false**) | +| `lcd1602_backlight_sleep` | boolean | Dim on sleep / light on wake (default **true**) | +| `lcd1602_welcome_hello` | boolean | HELLO/HUMAN on welcome (default **false**) | +| `lcd1602_boot` | string | `none` / `last` / `config` (default **`none`**) | +| `lcd1602_line1` / `lcd1602_line2` | string | Boot lines for `config` (max **64**, no C0 control bytes) | | `continuous_timeout` | integer | 1–1440 minutes (positive) | | `loading` | string | `progress` or `sleep_inertia` | | `eyes_style` | string | `classic`, `kaomoji`, `cover`, `dots`, or `kawaii` | @@ -352,6 +377,12 @@ curl -X POST "http://tiny-engineer.local/settings/reset" "serial_log": false, "push_button": false, "push_button_pin": 20, + "lcd1602": false, + "lcd1602_backlight_sleep": true, + "lcd1602_welcome_hello": false, + "lcd1602_boot": "none", + "lcd1602_line1": "", + "lcd1602_line2": "", "continuous_timeout": 5, "loading": "progress", "eyes_style": "classic", @@ -538,6 +569,39 @@ Wrong fields return **400**: Save with `POST /settings` `{"oled_rotate_180":true}` (setup AP only). The saved value applies immediately and on the next boot. +### LCD 1602 extension (`/extensions/lcd1602/…`) + +Waveshare LCD1602 I2C (AiP31068 @ `0x3E`; controllable backlight SN3193 @ `0x6B` or PCA9633 @ `0x60`, auto-detected) on the Extension I2C port. Off until `lcd1602` is true. Same access class as `POST /anim` (`Configured`). When the extension is off → **503** `extension disabled`. When on but the LCD (`0x3E`) does not ACK → text **POST**/`DELETE` **503** `lcd not found` (settings stay enabled); **GET** text still returns the cached logical state with **200**. When the LCD is up but neither backlight chip ACKs → brightness **POST** **503** `backlight not found`; **GET** brightness still returns the cached value with **200**. On PCA9633, brightness scales the base RGB color (`PWM = channel × brightness / 100`); use `/color` for base R/G/B. Color on SN3193 → **400** `rgb not supported`. When `lcd1602_backlight_sleep` is true, entering sleep (`sleep` anim or idle `sleep_timeout`) fades backlight to **0** over ~2 s; wakeup / wake-from-sleep fades to **100** over ~2 s (persists last state). When false, sleep/wake do not change backlight. When `lcd1602_welcome_hello` is true, every `welcome` animation overlays centered **HELLO** / **HUMAN**; text/clear during that overlay queues until welcome ends; `GET` text returns logical content (pending or pre-overlay), not HELLO. No outbound events. + +#### `GET` / `POST` / `DELETE /extensions/lcd1602/text` + +`GET` returns the full logical lines (not only the 16-column viewport), including when the LCD does not ACK (**200** cached state). `POST` / `DELETE` without an ACK → **503** `lcd not found`. + +```json +{ + "line1": { "text": "HELLO", "align": "left" }, + "line2": { "text": "", "align": "left" } +} +``` + +`POST` accepts a partial JSON body. Omitted `line1` / `line2` leave that line unchanged. Each present line object needs `text` (0–64 chars; empty clears the line) and optional `align` (`left` / `right` / `center`, default **`left`**). Lines longer than 16 characters ignore align and marquee LTR. + +```bash +curl -X POST "http://tiny-engineer.local/extensions/lcd1602/text" \ + -H "Content-Type: application/json" \ + -d '{"line1":{"text":"HELLO","align":"center"}}' +``` + +`DELETE` clears both lines and leaves brightness unchanged. + +#### `GET` / `POST /extensions/lcd1602/brightness` + +`GET` → `{"brightness":50}` (cached logical value; **200** even when no backlight chip ACKs). `POST` body `{"brightness":0..100}` (0 = backlight off). Neither SN3193 nor PCA9633 ACK on **POST** → **503** `backlight not found`. On PCA9633, brightness scales the stored base color (default white `255,255,255`). Successful text/clear/brightness/color updates persist **last** state for `lcd1602_boot=last`. + +#### `GET` / `POST /extensions/lcd1602/color` + +PCA9633 RGB modules only. `GET` → `{"r":255,"g":255,"b":255}`. `POST` body `{"r":0..255,"g":0..255,"b":0..255}` sets the base color (PWM scaled by current brightness). SN3193 (or other non-RGB backlight) → **400** `rgb not supported`. No backlight chip → **503** `backlight not found`. + ### `POST /servos/park` Flash-safe park: stop the current animation, smoothly move every joint to its calibrated mid, persist the pose to NVS, and keep PWM enabled until the next reboot (skips idle limp). No body. Requires Bearer when auth is enabled. Available in setup AP and after provisioning (does not require a chosen connection mode). diff --git a/docs/hardware/testing.md b/docs/hardware/testing.md index 98d8aa16..17729ebe 100644 --- a/docs/hardware/testing.md +++ b/docs/hardware/testing.md @@ -112,7 +112,10 @@ curl -X POST "http://tiny-engineer.local/test/servo" -H "Content-Type: applicati | `GET` | `/health` | Health JSON — full field list in [api.md](../api.md#get-health) | | `GET` / `POST` | `/anim` | Current animation / start one (`name`, optional `interrupt`) — full params in [api.md](../api.md#post-anim) | | `POST` | `/play` | Stream a WAV while `talking` (or `/play/{name}`) runs; answers when the clip ends — full params in [api.md](../api.md#post-play) | -| `GET` | `/settings` | Persistent settings (`sleep_timeout`, `hostname`, `volume`, `welcome`, `serial_log`, `push_button`, `push_button_pin`, `continuous_timeout`, `loading`, `eyes_style`, `access_token_set`, `wifi_configured`, `servo_mins`, `servo_maxs`, `rgb_order`, `oled_rotate_180`, `wifi_networks`) | +| `GET` | `/settings` | Persistent settings (`sleep_timeout`, `hostname`, `volume`, `welcome`, `serial_log`, `push_button`, `push_button_pin`, `lcd1602`, `lcd1602_backlight_sleep`, `lcd1602_welcome_hello`, `lcd1602_boot`, `lcd1602_line1`, `lcd1602_line2`, `continuous_timeout`, `loading`, `eyes_style`, `access_token_set`, `wifi_configured`, `servo_mins`, `servo_maxs`, `rgb_order`, `oled_rotate_180`, `wifi_networks`) | +| `GET` / `POST` / `DELETE` | `/extensions/lcd1602/text` | LCD 1602 text (extension off → 503) | +| `GET` / `POST` | `/extensions/lcd1602/brightness` | LCD 1602 backlight 0–100 | +| `GET` / `POST` | `/extensions/lcd1602/color` | LCD 1602 RGB base color (PCA9633 only) | | `GET` / `PUT` | `/settings/actions` | On-device Actions list (event patterns → sound / anim) | | `POST` | `/actions/test` | Simulate an event type for Actions (no outbound publish) | | `POST` | `/settings` | Update NVS settings from a JSON object; the reply carries `reboot_required`, true once `hostname`, `loading` or the WiFi networks differ from what the robot booted with. `servo_mins` / `servo_maxs` (integer arrays), `rgb_order` and `oled_rotate_180` (boolean) are setup-AP-only | diff --git a/docs/hooks.md b/docs/hooks.md index bc217c55..9a877d62 100644 --- a/docs/hooks.md +++ b/docs/hooks.md @@ -198,5 +198,6 @@ Config: [`.cursor/hooks.json`](../.cursor/hooks.json). Local anim hook: [`.curso - Robot offline → hook still exits 0; no agent stall. - Animation API holds each pose ≥1s and keeps only the latest pending switch — see [`api.md`](api.md). - The onboard RGB LED follows the active animation (white for typing/reading/thinking/talking/welcome/ring/wakeup, pulsing red for attention/error/dead, solid red for abort, off for `none`/`sleep`) with 1 s fades between non-pulse states — see [RGB LED](api.md#rgb-led). +- After a completed turn (`stop` → `ring`), the CLI may update an enabled LCD1602 with remaining Cursor AI budget (`AI BUDGET:` / `NN.NN%`). **Opt-in:** set `TINY_ENGINEER_AI_USAGE_LCD=1` in user config (`~/.config/tiny-engineer/env`) or enable during `tiny-engineer setup` (interactive prompt, or `--ai-usage-lcd` / `--no-ai-usage-lcd`). Uses the local Cursor web session (Keychain / IDE state DB). The LCD extension is optional: missing session, slow cursor.com, disabled LCD, or robot errors are silent and never change the hook exit code. - To change the map, edit [`packages/tiny-engineer-cli/src/integrations/cursor/map.js`](../packages/tiny-engineer-cli/src/integrations/cursor/map.js). - Custom agents or non-Cursor IDEs: call the [REST API](integration.md#2-rest-api-advanced--custom). diff --git a/docs/serial.md b/docs/serial.md index 84304a9b..cc2fc245 100644 --- a/docs/serial.md +++ b/docs/serial.md @@ -50,7 +50,11 @@ Before another program opens the USB serial device, run `tiny-engineer daemon re - **Provisioning:** while unprovisioned or in setup AP, only sync/ping and `servos_park`. Full API after a connection mode is chosen (Wi‑Fi or USB-only). Serial does **not** use Bearer auth. - **Busy:** long play holds a global busy lock; a second play (HTTP or serial) gets `busy`. -Ops (JSON `op`): `ping`/`sync`, `servos_park`, `anim`, `settings.get`/`settings.set`, `test`, `servo`, `health`, `factory_reset`, `play` / `play_end`, plus stream data/credit/error frames. +Ops (JSON `op`): `ping`/`sync`, `servos_park`, `anim`, `settings.get`/`settings.set`, `ext`, `test`, `servo`, `health`, `factory_reset`, `play` / `play_end`, plus stream data/credit/error frames. + +`settings.get` / `settings.set` over serial include a **LCD slice** (`lcd1602`, `lcd1602_backlight_sleep`, `lcd1602_welcome_hello`, `lcd1602_boot`, `lcd1602_line1`, `lcd1602_line2`) so USB-only hosts can enable the Waveshare module. Other HTTP settings fields (wifi list, actions, push_button, …) may still be missing on serial — full GET `/settings` parity is a follow-up. + +`ext` mirrors HTTP `/extensions//`: `{ "op":"ext", "id":"lcd1602", "suffix":"text"|"brightness"|"color", "method":"GET"|"POST"|"DELETE", ...body }`. Same disabled/validation/hardware errors as HTTP. CLI: `tiny-engineer ext lcd1602 text|brightness|color …`. ## PlatformIO monitor diff --git a/docs/settings.md b/docs/settings.md index f3aeac4a..af15ef3f 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -2,9 +2,9 @@ Persistent settings live in NVS (namespace `te`) under [`src/settings/`](../src/settings/). They are exposed on `GET`/`POST /settings`, the Config web UI, and must stay in sync with API docs. -**HTTP / JSON** (`POST /settings` body and `GET /settings` fields — see [api.md](api.md)): `sleep_timeout`, `hostname`, `volume`, `welcome`, `serial_log`, `push_button`, `push_button_pin`, `continuous_timeout`, `loading`, `eyes_style`, `access_token`, `servo_mins` / `servo_maxs`, `rgb_order`, `oled_rotate_180`. WiFi networks have their own endpoint, `PUT /settings/wifi`, and show as `wifi_networks`. On-device Actions use `GET`/`PUT /settings/actions`. +**HTTP / JSON** (`POST /settings` body and `GET /settings` fields — see [api.md](api.md)): `sleep_timeout`, `hostname`, `volume`, `welcome`, `serial_log`, `push_button`, `push_button_pin`, `lcd1602`, `lcd1602_backlight_sleep`, `lcd1602_welcome_hello`, `lcd1602_boot`, `lcd1602_line1`, `lcd1602_line2`, `continuous_timeout`, `loading`, `eyes_style`, `access_token`, `servo_mins` / `servo_maxs`, `rgb_order`, `oled_rotate_180`. WiFi networks have their own endpoint, `PUT /settings/wifi`, and show as `wifi_networks`. On-device Actions use `GET`/`PUT /settings/actions`. -**NVS keys** (≤15 chars; defined in [`nvs.h`](../src/settings/nvs.h)): `sleep_m`, `host`, `vol`, `welcome`, `serial_log`, `ext_btn` (`push_button`), `ext_btn_pin` (`push_button_pin`), `cont_to`, `loading`, `eyes_sty`, `access_tok`, `wifi_nets` (blob of up to 5 networks; replaces the older single-network `wifi_ssid` / `wifi_pass`, which are migrated on load), `actions` (Actions blob, up to 16 rows), `sranges`, `rgb_ord`, `oled_rot`. Last commanded servo angles live in the same namespace as key `spose` (internal; not a settings API field). Boot migrates legacy `btn_snd_*` keys into Actions then removes them, and drops leftover `srv_hold`. Add new short keys there — do not reuse HTTP names as NVS keys unless they already fit the length limit. +**NVS keys** (≤15 chars; defined in [`nvs.h`](../src/settings/nvs.h)): `sleep_m`, `host`, `vol`, `welcome`, `serial_log`, `ext_btn` (`push_button`), `ext_btn_pin` (`push_button_pin`), `ext_lcd` (`lcd1602`), `ext_lcd_bl` (`lcd1602_backlight_sleep`), `ext_lcd_hi` (`lcd1602_welcome_hello`), `ext_lcd_boot`, `ext_lcd_l1`, `ext_lcd_l2`, `ext_lcd_last` (LCD last-state blob; not a settings API field), `cont_to`, `loading`, `eyes_sty`, `access_tok`, `wifi_nets` (blob of up to 5 networks; replaces the older single-network `wifi_ssid` / `wifi_pass`, which are migrated on load), `actions` (Actions blob, up to 16 rows), `sranges`, `rgb_ord`, `oled_rot`. Last commanded servo angles live in the same namespace as key `spose` (internal; not a settings API field). Boot migrates legacy `btn_snd_*` keys into Actions then removes them, and drops leftover `srv_hold`. Add new short keys there — do not reuse HTTP names as NVS keys unless they already fit the length limit. Follow the same pattern for a new setting. @@ -45,7 +45,7 @@ Call the getter wherever the value affects behavior (e.g. `settingsVolume()` in ### 4. Web UI — [`ui/`](../ui/) 1. Add the field to `Settings` in [`ui/src/api/types.ts`](../ui/src/api/types.ts). -2. Add a control to `ConfigForm` in [`ui/src/config/ConfigForm.tsx`](../ui/src/config/ConfigForm.tsx): read it in `draftFrom()` and send it from `save()`. Use `.range-row` + range/number for 0–N scales (see volume). Exception: extension toggles/pin (`push_button` / `push_button_pin`) live on the Extensions page; event→effect bindings live on the Actions page (`/settings/actions`). +2. Add a control to `ConfigForm` in [`ui/src/config/ConfigForm.tsx`](../ui/src/config/ConfigForm.tsx): read it in `draftFrom()` and send it from `save()`. Use `.range-row` + range/number for 0–N scales (see volume). Exception: extension toggles/fields (`push_button` / `push_button_pin`, `lcd1602` / …) live on the Extensions page; event→effect bindings live on the Actions page (`/settings/actions`). 3. API reference table under POST `/settings` in [`ui/src/views/ApiReference.tsx`](../ui/src/views/ApiReference.tsx): param, type, range. 4. Home Config card blurb if the setting is user-facing. diff --git a/include/pins.h b/include/pins.h index 6842194e..e4ce5ae1 100644 --- a/include/pins.h +++ b/include/pins.h @@ -55,3 +55,14 @@ constexpr int SERVO_MAX_US = 2200; constexpr int OLED_WIDTH = 128; constexpr int OLED_HEIGHT = 32; constexpr uint8_t OLED_ADDRESS = 0x3C; + +// ===================================================== +// Waveshare LCD1602 I2C (AiP31068L + SN3193 or PCA9633) — LCD 1602 extension +// ===================================================== + +// Wiki lists LCD as 8-bit 0x7C → 7-bit 0x3E. +// Controllable backlight: SN3193 @ 0x6B (Blue/Gray/Green) or PCA9633 @ 0x60 +// (RGB module, wiki 8-bit 0xC0 → 7-bit 0x60). Probe which ACK; not both. +constexpr uint8_t LCD1602_ADDRESS = 0x3E; +constexpr uint8_t LCD1602_LED_ADDRESS = 0x6B; +constexpr uint8_t LCD1602_RGB_ADDRESS = 0x60; diff --git a/openspec/changes/archive/2026-11-14-cli-ext-lcd1602/.openspec.yaml b/openspec/changes/archive/2026-11-14-cli-ext-lcd1602/.openspec.yaml new file mode 100644 index 00000000..be831cee --- /dev/null +++ b/openspec/changes/archive/2026-11-14-cli-ext-lcd1602/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-14 diff --git a/openspec/changes/archive/2026-11-14-cli-ext-lcd1602/design.md b/openspec/changes/archive/2026-11-14-cli-ext-lcd1602/design.md new file mode 100644 index 00000000..4cd9d5d6 --- /dev/null +++ b/openspec/changes/archive/2026-11-14-cli-ext-lcd1602/design.md @@ -0,0 +1,63 @@ +# Design + +## Context + +HTTP already has `http_registry` (`ExtHttpRoute` table) for `/extensions//…`. LCD handlers live under `src/extensions/lcd1602/http.*`. Serial `link.cpp` dispatches JSON `op`s; `settings.get`/`settings.set` omit `lcd1602*`. CLI `ops.js` + `viaTransport` already unify HTTP/serial for settings/test/servo/park/reset; `anim`/`play` use `transport.js`. No `ext` command yet. + +## Goals / Non-Goals + +**Goals:** +- One serial `ext` dispatcher sharing the HTTP extension mount table +- LCD 1602 as first (only) registered serial/HTTP consumer in this change +- Serial settings slice for `lcd1602*` so USB-only can enable the extension +- CLI `tiny-engineer ext …` with transport parity for LCD text/brightness + +**Non-Goals:** +- Full serial `settings.get` parity with every `GET /settings` field (wifi, actions, …) +- Serial/CLI surface for push-button or other extensions beyond registering future rows +- Short `lcd` CLI alias +- Bearer auth on serial (unchanged: serial skips token) + +## Decisions + +### 1. Serial op shape: registry mirror (B) +Request fields: `op: "ext"`, `id` (e.g. `lcd1602`), `suffix` (e.g. `text` / `brightness`), `method` (`GET`|`POST`|`DELETE`), plus body fields for POST (same JSON keys as HTTP). Dispatch: look up `(path=/extensions//, method)` in the shared table; run `Refusal::check(Configured)` then `enabled()` then handler. Prefer extracting a small shared invoke helper used by HTTP `server.on` lambdas and serial, rather than duplicating LCD logic. + +**Alternatives rejected:** dedicated `lcd1602.text` ops (does not match CLI `ext`); raw HTTP path tunnel (heavier framing). + +### 2. CLI is generic `ext`; unknown id fails locally +CLI knows a small map of ids → resources (v1: only `lcd1602`). Unknown id → exit 1 before open/HTTP. Known id + resource maps to HTTP path or serial `ext` fields via `viaTransport`-style helper. + +Example UX: +``` +tiny-engineer ext lcd1602 text get +tiny-engineer ext lcd1602 text set --line1=HELLO --align=center +tiny-engineer ext lcd1602 text clear +tiny-engineer ext lcd1602 brightness get|set +``` +Enable/boot: existing `settings set --lcd1602=true` (after serial settings slice). + +### 3. Settings slice only +`settings.get` adds the five `lcd1602*` fields. `settings.set` accepts them with existing validators and calls `lcd1602ApplyFromSettings` when relevant (same as HTTP handler). Document in `docs/serial.md` that other settings gaps remain. + +### 4. Error parity +Reuse HTTP error strings where handlers already emit them (`extension disabled`, `lcd not found`, `backlight not found`, validation messages). Serial status codes mirror HTTP (`code` in JSON res). + +### 5. Docs / tests +Update `docs/serial.md` ops list; CLI help/README. CLI unit tests for arg parsing / unknown id; firmware: extend serial settings coverage if native-testable, else compile + focused serial/HTTP smoke notes in tasks. + +## Risks / Trade-offs + +- [Shared handler coupling] → Keep invoke thin; handlers stay WebServer-oriented — may need a small adapter (fake WebServer or body/response callbacks). Prefer response JSON builders already used by LCD HTTP if refactor stays small. +- [Partial settings parity vs main serial-protocol wording] → This change MODIFIES the parity requirement to admit the lcd slice + `ext` while naming the remaining gap explicitly. +- [CLI id allowlist drift] → Document that new extensions add CLI map entries + registry rows together. + +## Migration Plan + +1. Firmware: settings lcd fields on serial; then `ext` dispatcher wired to existing LCD routes. +2. CLI: `ext` command + ops; tests; docs. +3. No NVS migration. Rollback = prior firmware/CLI; unknown `ext` op → 404 as today. + +## Open Questions + +None blocking. Exact CLI flag names for line2/align can follow existing `settings set --key=value` style where practical. diff --git a/openspec/changes/archive/2026-11-14-cli-ext-lcd1602/proposal.md b/openspec/changes/archive/2026-11-14-cli-ext-lcd1602/proposal.md new file mode 100644 index 00000000..d7d76e74 --- /dev/null +++ b/openspec/changes/archive/2026-11-14-cli-ext-lcd1602/proposal.md @@ -0,0 +1,31 @@ +# Proposal + +## Why + +USB-only and serial-first hosts can drive anim/play/settings today, but LCD 1602 lives only on HTTP `/extensions/lcd1602/…`. The CLI has no extension commands, and serial `settings.get`/`settings.set` omit the `lcd1602*` fields needed to enable the module. Users need the same LCD control over `--transport serial` as over HTTP, with a CLI shape that scales to later extensions. + +## What Changes + +- Add a **serial `ext` dispatcher** that mounts the same extension route table as HTTP (`id` + `suffix` + method + JSON body), with **LCD 1602 as the only registered consumer** in this change +- Extend serial **`settings.get` / `settings.set`** to include/accept the **`lcd1602*` settings slice** (enable + boot/backlight/lines) so the extension can be turned on without Wi‑Fi +- Add CLI command **`tiny-engineer ext …`** (first id: `lcd1602`) for text get/set/clear and brightness get/set over HTTP or serial via existing transport helpers +- Document serial `ext` and CLI usage; update help/`docs/serial.md` +- **Not in this change:** full serial settings parity (wifi/actions/all HTTP fields), push-button (or other) extension APIs over serial, a short `lcd` CLI alias + +## Capabilities + +### New Capabilities +- `extension-serial`: Serial JSON `op: "ext"` that reuses the shared extension mount table (same id/suffix/method semantics and refusals as HTTP `/extensions//…`) + +### Modified Capabilities +- `serial-protocol`: Add `ext` to the control surface; narrow settings get/set to also carry the `lcd1602*` field slice (full GET `/settings` parity remains deferred) +- `cli-transport`: Add day-to-day `ext ` commands with transport parity for LCD 1602 resources +- `lcd1602`: Clarify that text/brightness APIs are reachable via the serial `ext` path with the same behavior as HTTP (disabled/503, validation, last-state) + +## Impact + +- Firmware: `src/serial/link.cpp` (and shared helpers to dispatch into `http_registry` / LCD handlers); serial settings JSON include/accept `lcd1602*` +- CLI: `packages/tiny-engineer-cli` — new `ext` command, `ops.js` (or sibling) for HTTP+serial, help/README tests +- Docs: `docs/serial.md`, CLI help; API docs cross-link if needed +- Specs: new `extension-serial`; deltas on `serial-protocol`, `cli-transport`, `lcd1602` +- Scope `integrations` for package work; firmware/serial for device side diff --git a/openspec/changes/archive/2026-11-14-cli-ext-lcd1602/specs/cli-transport/spec.md b/openspec/changes/archive/2026-11-14-cli-ext-lcd1602/specs/cli-transport/spec.md new file mode 100644 index 00000000..471bea2f --- /dev/null +++ b/openspec/changes/archive/2026-11-14-cli-ext-lcd1602/specs/cli-transport/spec.md @@ -0,0 +1,25 @@ +# Spec Delta + +## ADDED Requirements + +### Requirement: CLI ext command for registered extensions +The CLI MUST provide an `ext …` command family that targets extension APIs over the selected transport (`http` or `serial`). For id `lcd1602`, the CLI MUST support text get, text set (partial lines/align), text clear, brightness get, and brightness set. Unknown `` values that the CLI does not know how to map MUST fail locally with a clear error without contacting the robot. + +#### Scenario: LCD text over HTTP +- **WHEN** the user runs `tiny-engineer ext lcd1602 text set` with line arguments and transport `http` +- **THEN** the CLI issues `POST /extensions/lcd1602/text` and prints or confirms the resulting state + +#### Scenario: LCD brightness over serial +- **WHEN** the user runs `tiny-engineer ext lcd1602 brightness set 20` with transport `serial` +- **THEN** the CLI sends serial `ext` for brightness and does not fall back to HTTP + +#### Scenario: Unknown extension id +- **WHEN** the user runs `tiny-engineer ext nope text get` +- **THEN** the CLI exits non-zero with an unknown-extension style error and does not open a robot session solely for that id + +### Requirement: Ext uses the same transport resolution as other robot commands +`ext` MUST honor the existing transport resolution order (flag → env/config → default `http`) and the same URL/port/token rules as other day-to-day robot commands. + +#### Scenario: Serial transport flag +- **WHEN** the user passes `--transport serial` to an `ext lcd1602` command +- **THEN** the CLI uses serial and does not fall back to HTTP on failure diff --git a/openspec/changes/archive/2026-11-14-cli-ext-lcd1602/specs/extension-serial/spec.md b/openspec/changes/archive/2026-11-14-cli-ext-lcd1602/specs/extension-serial/spec.md new file mode 100644 index 00000000..8d2c289d --- /dev/null +++ b/openspec/changes/archive/2026-11-14-cli-ext-lcd1602/specs/extension-serial/spec.md @@ -0,0 +1,36 @@ +# Spec Delta + +## Purpose + +Lets hosts drive extension REST surfaces over USB serial through one `ext` op that reuses the same mount table, access, and disabled-gate rules as HTTP `/extensions//…`. + +## ADDED Requirements + +### Requirement: Serial ext op mounts extensions +The serial control API MUST accept JSON requests with `op` equal to **`ext`**. The request MUST name a kebab-case extension `id`, a resource `suffix` (path segment after `/extensions//`), and an HTTP-equivalent `method` (`GET`, `POST`, `DELETE`, …). The device MUST dispatch using the same registered extension route table as HTTP. + +#### Scenario: LCD text get over serial +- **WHEN** the host sends `ext` with `id` `lcd1602`, `suffix` `text`, and `method` `GET` while the extension is on +- **THEN** the response carries the same logical text JSON shape as `GET /extensions/lcd1602/text` + +#### Scenario: Unknown extension id +- **WHEN** the host sends `ext` with an `id` that has no registered routes +- **THEN** the device answers **404** (or equivalent serial status) without performing extension hardware I/O + +### Requirement: Ext refusals match HTTP +For a registered extension route, serial `ext` MUST apply the same access class as the HTTP route (`Configured`). When the extension’s settings toggle is false, `ext` MUST answer **503** with a clear disabled message and MUST NOT perform that extension’s hardware I/O. Unsupported method on a known suffix MUST answer **405**. + +#### Scenario: LCD off refuses text post +- **WHEN** `lcd1602` is false and the host sends `ext` POST `text` +- **THEN** the response is **503** and no LCD I2C traffic runs for that request + +#### Scenario: Wrong method +- **WHEN** the host sends `ext` with method `PUT` or `PATCH` on suffix `text` for `lcd1602` +- **THEN** the response is **405** + +### Requirement: Ext body and success semantics match HTTP handlers +When method and body are valid for a registered route, serial `ext` MUST produce the same success/error codes and JSON payloads as the corresponding HTTP handler (including LCD validation **400**, missing hardware **503** messages, and last-state updates on success). + +#### Scenario: Brightness set parity +- **WHEN** the host sends `ext` POST `brightness` with `{"brightness":50}` and the backlight is reachable +- **THEN** the response is **200** with brightness `50`, matching HTTP `POST /extensions/lcd1602/brightness` diff --git a/openspec/changes/archive/2026-11-14-cli-ext-lcd1602/specs/lcd1602/spec.md b/openspec/changes/archive/2026-11-14-cli-ext-lcd1602/specs/lcd1602/spec.md new file mode 100644 index 00000000..cdc6c0da --- /dev/null +++ b/openspec/changes/archive/2026-11-14-cli-ext-lcd1602/specs/lcd1602/spec.md @@ -0,0 +1,14 @@ +# Spec Delta + +## ADDED Requirements + +### Requirement: LCD APIs available over serial ext +The LCD 1602 text and brightness behaviors defined for HTTP `/extensions/lcd1602/…` MUST also apply when the same operations are invoked through serial `ext` with `id` `lcd1602` and the matching `suffix`/`method`. Disabled-extension, validation, missing-LCD, and missing-backlight outcomes MUST match the HTTP API (including distinct not-found style messages for LCD vs backlight where HTTP already distinguishes them). + +#### Scenario: Serial clear matches HTTP delete +- **WHEN** the host clears both lines via serial `ext` DELETE `text` while the extension is on +- **THEN** both lines are empty, brightness is unchanged, and last state is persisted as for `DELETE /extensions/lcd1602/text` + +#### Scenario: Serial backlight missing +- **WHEN** the extension is on, the LCD ACKs, the backlight chip does not, and the host sets brightness via serial `ext` +- **THEN** the response is **503** with a backlight not-found style message diff --git a/openspec/changes/archive/2026-11-14-cli-ext-lcd1602/specs/serial-protocol/spec.md b/openspec/changes/archive/2026-11-14-cli-ext-lcd1602/specs/serial-protocol/spec.md new file mode 100644 index 00000000..f77e479a --- /dev/null +++ b/openspec/changes/archive/2026-11-14-cli-ext-lcd1602/specs/serial-protocol/spec.md @@ -0,0 +1,42 @@ +# Spec Delta + +## ADDED Requirements + +### Requirement: Serial settings include LCD 1602 fields +`settings.get` over serial MUST include the `lcd1602`, `lcd1602_backlight_boot`, `lcd1602_boot`, `lcd1602_line1`, and `lcd1602_line2` fields with the same types and defaults as `GET /settings`. `settings.set` MUST accept those keys with the same validation and immediate-apply behavior as `POST /settings`. Other settings fields not already returned or accepted by serial MAY remain deferred (full GET `/settings` parity is not claimed by this change alone). + +#### Scenario: Enable LCD over serial +- **WHEN** the host sends `settings.set` with `{"lcd1602": true}` after provisioning +- **THEN** the extension becomes active without reboot and a later `settings.get` reports `lcd1602` true + +#### Scenario: Invalid boot mode rejected +- **WHEN** the host sends `settings.set` with `{"lcd1602_boot": "welcome"}` +- **THEN** the device answers **400** and does not save the value + +### Requirement: Ext op is part of the serial control surface +The serial protocol MUST document and implement `op` **`ext`** for extension APIs as specified by the `extension-serial` capability. Day-to-day control over serial MUST include `ext` for registered extensions (LCD 1602 in this change). + +#### Scenario: Ext listed among control ops +- **WHEN** a provisioned host sends a valid `ext` request for a registered LCD route +- **THEN** the device does not reject solely because `ext` is an unknown op + +## MODIFIED Requirements + +### Requirement: Feature parity with HTTP control surface +The serial API MUST expose the same day-to-day control operations as the HTTP JSON API, including animations, settings read/write, hardware tests, servo test, health, factory reset, streamed WAV play with optional animation name, servo park, and **extension APIs via `ext` for registered extensions**. Settings read/write MUST include at least the fields already supported plus the **`lcd1602*` slice** in this change; remaining HTTP settings fields remain a known gap until a later change closes full GET `/settings` parity. + +#### Scenario: Settings over serial +- **WHEN** the host requests current settings over serial +- **THEN** the device returns at least the previously supported serial settings fields plus the `lcd1602*` fields (excluding secrets) + +#### Scenario: Play with pose over serial +- **WHEN** the host streams a WAV with an allowed play animation name over serial +- **THEN** the device plays the clip while running that animation, matching `POST /play` behavior + +#### Scenario: Park over serial matches HTTP +- **WHEN** the host sends serial op `servos_park` +- **THEN** the device applies the same park semantics as `POST /servos/park` + +#### Scenario: Extension text over serial +- **WHEN** the host sends a valid `ext` POST for LCD text while the extension is on and hardware is present +- **THEN** the device updates the display with the same semantics as `POST /extensions/lcd1602/text` diff --git a/openspec/changes/archive/2026-11-14-cli-ext-lcd1602/tasks.md b/openspec/changes/archive/2026-11-14-cli-ext-lcd1602/tasks.md new file mode 100644 index 00000000..0cfd6be4 --- /dev/null +++ b/openspec/changes/archive/2026-11-14-cli-ext-lcd1602/tasks.md @@ -0,0 +1,28 @@ +# Tasks + +## 1. Serial settings lcd slice + +- [x] 1.1 Extend serial `settings.get` to include `lcd1602`, `lcd1602_backlight_boot`, `lcd1602_boot`, `lcd1602_line1`, `lcd1602_line2` with the same types/defaults as HTTP; verify with a serial/HTTP get comparison or unit/fixture assertion on the JSON keys +- [x] 1.2 Extend serial `settings.set` to accept those keys (validation + `lcd1602ApplyFromSettings` when relevant); verify enable via serial then `settings.get` shows `lcd1602` true, and invalid `lcd1602_boot` → 400 + +## 2. Serial `ext` dispatcher + +- [x] 2.1 Add shared invoke path so serial can run registered extension routes (Configured → enabled gate → handler) without duplicating LCD business logic; verify `pio run` compiles +- [x] 2.2 Implement serial `op: "ext"` (`id`, `suffix`, `method`, body) against the HTTP extension table; verify unknown id → 404, disabled LCD POST text → 503, PUT text → 405 +- [x] 2.3 Verify LCD text get/set/clear and brightness get/set over serial match HTTP status/body shapes (including `backlight not found` when LED NACK) + +## 3. CLI `ext` command + +- [x] 3.1 Add `tiny-engineer ext …` with transport resolution; v1 map only `lcd1602` (text get/set/clear, brightness get/set); verify unknown id fails locally without robot I/O +- [x] 3.2 Wire LCD resources through `viaTransport` (HTTP paths + serial `ext` fields); verify `npm test --prefix packages/tiny-engineer-cli` covers parsing/unknown id and a transport stub path +- [x] 3.3 Update CLI help/README examples for `ext lcd1602`; verify help text lists the new command + +## 4. Docs and build + +- [x] 4.1 Document serial `ext` and the `lcd1602*` settings slice in `docs/serial.md` (note remaining settings parity gap); verify ops list matches firmware +- [x] 4.2 Run `pio run` and CLI package tests; confirm both pass + +## Workflow follow-up + +- Archive after review/verify (`/opsx-verify` then `/opsx-archive`). +- Later change: full serial settings parity; register further extensions in the same `ext` table + CLI map. diff --git a/openspec/changes/archive/2026-11-14-lcd1602-extension/.openspec.yaml b/openspec/changes/archive/2026-11-14-lcd1602-extension/.openspec.yaml new file mode 100644 index 00000000..be831cee --- /dev/null +++ b/openspec/changes/archive/2026-11-14-lcd1602-extension/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-14 diff --git a/openspec/changes/archive/2026-11-14-lcd1602-extension/design.md b/openspec/changes/archive/2026-11-14-lcd1602-extension/design.md new file mode 100644 index 00000000..356ef84e --- /dev/null +++ b/openspec/changes/archive/2026-11-14-lcd1602-extension/design.md @@ -0,0 +1,96 @@ +# Design + +## Context + +See proposal.md — Why. Today: flat `kRoutes[]` in `src/http/routes.cpp`; push-button files sit flat under `src/extensions/`; temporary `initLcd1602Hello()` lives under `src/display/`. Settings checklist lives in `docs/settings.md`. I2C bus already shared (PCA9685 `0x40`, OLED `0x3C`). Waveshare LCD1602 uses AiP31068L @ `0x3E` + SN3193 @ `0x6B` (fixed). Pin-claims do not apply to LCD (no GPIO). + +## Goals / Non-Goals + +**Goals:** +- Opt-in LCD 1602 extension with Extensions UI + NVS settings + last-state restore +- Reusable `/extensions//…` mount table for future extensions +- Clear **per-extension** firmware tree: `src/extensions//…`; push-button moved into that layout in the same change +- Raw Wire driver (no new PlatformIO lib) for AiP31068 + SN3193 +- Scroll tick from `loop()` when a line is long + +**Non-Goals:** +- Configurable I2C addresses or PCF8574 backpacks +- Outbound events / Actions triggers from LCD +- Multi-LCD or I2C mux +- Per-line brightness or RGB backlight modes beyond single brightness 0–100 +- Moving NVS/settings core out of `src/settings/` into per-extension folders +- Changing push-button runtime behavior (move/includes only) + +## Decisions + +### 1. Extension HTTP registry beside `kRoutes` +Add a small table (e.g. `ExtHttpRoute`: `id`, `suffix`, method, `Access`, `enabled()` predicate, handler) in shared extension infra, registered from `registerHttpRoutes`. Paths become `/extensions/` + id + suffix. Gate: `Refusal::check(Configured)` then if `!enabled()` → **503** `extension disabled`. Extend `isKnownPath` so wrong methods on registered suffixes → **405**. + +**Alternatives:** stuff every path into `kRoutes` (works once, no shared disabled gate); single catch-all `UriBraces("/extensions/{}/{}")` dispatcher (harder 405/table docs). Prefer explicit table rows for docs sync and typed handlers. + +### 2. Keep SPA `GET /extensions` in `kRoutes` +Unchanged shell route. Extension APIs never collide with the page path (they need a second segment). + +### 3. Per-extension module layout +**Rule:** code that exists only for one optional extension lives under `src/extensions//`. Shared extension infrastructure stays at `src/extensions/` root. Stock robot face (OLED/eyes) stays in `src/display/` — LCD is not face firmware. + +``` +src/extensions/ + README.md # layout rule for agents/humans + pin_claims.* # shared GPIO claims + pin_claims_settings.* + http_registry.* # shared /extensions// mount + push_button/ + push_button.h/.cpp # apply / poll + logic.h/.cpp # pure debounce/gestures (native-tested) + sfx.h + lcd1602/ + lcd1602.h/.cpp # apply / poll / logical state / boot + hw.h/.cpp # AiP31068 + SN3193 + http.h/.cpp # REST handlers registered via registry +``` + +- **First:** delete smoke test (`initLcd1602Hello`, `src/display/lcd1602.*`, smoke-only pins). +- **Then:** move push-button into `push_button/` and fix includes + `platformio.ini` native filter + tests. +- **Then:** add `lcd1602/` (hw + runtime + http). Call `lcd1602ApplyFromSettings()` after settings/I2C ready and `lcd1602Poll()` from `loop()`. +- Optional UI: `ui/src/extensions/*Section.tsx` imported by `Extensions.tsx` — same split, not required for v1 if the page stays readable. + +**Alternatives rejected:** LCD hw under `src/display/` (blurs stock display vs optional extension); LCD handlers only under `src/http/` with no extension folder (scatters the feature); leave push-button flat (two layouts forever). + +### 4. Settings / NVS +JSON fields: `lcd1602`, `lcd1602_backlight_boot`, `lcd1602_boot`, `lcd1602_line1`, `lcd1602_line2`. Short NVS keys under 15 chars (e.g. `ext_lcd`, `ext_lcd_bl`, `ext_lcd_boot`, `ext_lcd_l1`, `ext_lcd_l2`). Last state: one `putBytes` blob (two 64-char lines + aligns + brightness) keyed e.g. `ext_lcd_last`. Follow `docs/settings.md` checklist end-to-end. Defaults: enable false, backlight_boot true, boot `none`, lines empty. + +### 5. Logical state vs viewport +RAM holds full strings (≤64) + align + brightness + scroll index per line. GET returns logical strings. Hardware shows 16-col window (aligned pad or marquee slice). Scroll step ~375 ms; ~750 ms pause when wrap returns to 0 (readable). + +### 6. Success vs hardware failure +Validate JSON first. If LCD missing (`0x3E` NACK): **503** on mutating routes that need HW; do not update last blob on failed HW apply. If HW OK: update RAM, write display, save last, **200** with state. GET may return RAM/NVS even when HW absent. + +### 7. Disable behavior +No I2C teardown writes (module may be gone). Stop poll; drop “active” flag. Last blob kept for later `boot=last`. + +### 8. Access +`Configured` for all `/extensions/lcd1602/*` APIs (same as `/anim`). + +### 9. Docs / UI sync +Per `.cursor/rules/sync-api-endpoints.mdc`: `routes` / extension table, `docs/api.md`, `ui/src/views/ApiReference.tsx`, settings tables, hardware testing / README if endpoint list changes. Document `src/extensions/` layout briefly (AGENTS.md or `src/extensions/README.md`). + +## Risks / Trade-offs + +- [Include-path churn for push-button] → Mitigation: mechanical move + `rg` for old paths; native tests must pass before LCD work. +- [SN3193 absent / different backlight] → Mitigation: LCD text still works if AiP31068 ACKs; brightness POST may 503 if LED NACK while LCD OK (document). +- [I2C bus load / slow Wire during scroll] → Mitigation: one short transaction per step; fixed modest period; never block HTTP long. +- [NVS wear from frequent text updates] → Mitigation: write last blob only when logical state actually changes. +- [Extension table vs docs drift] → Mitigation: same sync checklist as `kRoutes`. + +## Migration Plan + +1. Remove smoke-test code first (no HELLO on boot). +2. Move push-button into `src/extensions/push_button/`; fix includes/filters/tests; `pio run` + `pio test -e native`. +3. Land settings + `lcd1602/` + registry; LCD inert until `lcd1602` true. +4. No settings migration (new keys only). +5. Rollback: flash previous firmware; new NVS keys ignored by old builds. + +## Open Questions + +None that block specs/tasks. Scroll pause/step constants may be tuned on hardware during apply without changing the contract (“readable fixed pace”). diff --git a/openspec/changes/archive/2026-11-14-lcd1602-extension/proposal.md b/openspec/changes/archive/2026-11-14-lcd1602-extension/proposal.md new file mode 100644 index 00000000..434bde80 --- /dev/null +++ b/openspec/changes/archive/2026-11-14-lcd1602-extension/proposal.md @@ -0,0 +1,37 @@ +# Proposal + +## Why + +The Waveshare LCD1602 on the I2C extension port only has a temporary boot smoke test. Users need an opt-in extension (like push-button) that can show agent/status text over REST, with a reusable `/extensions//…` HTTP pattern for later extensions. Extension code must live in a clear per-extension tree so push-button and LCD (and future add-ons) do not sprawl across `display/` and flat `extensions/` files. + +## What Changes + +- **Remove** the always-on `initLcd1602Hello()` smoke test (and its files) first, then add a proper **LCD 1602** extension, **off by default**, toggled on the web UI **Extensions** page (immediate apply, no reboot). +- **Restructure** firmware extensions under `src/extensions//` (one folder per extension). Move the existing push-button sources into `src/extensions/push_button/`. Keep shared infra (`pin_claims*`, HTTP registry) at `src/extensions/` root. LCD driver and its HTTP handlers live under `src/extensions/lcd1602/` — not under `src/display/`. +- When enabled: drive Waveshare LCD1602 (AiP31068L @ `0x3E`, SN3193 backlight @ `0x6B` — addresses fixed in firmware). When disabled: perform **no** LCD I2C traffic (module may be unplugged). +- Add boot settings: backlight on start (or wait for API); boot content `none` | `last` | `config` (with configured line strings for `config`). +- Persist **last** display state (both lines + per-line align + brightness) after every successful text/clear/brightness API call; restore when `boot=last`. +- Expose REST under `/extensions/lcd1602/…`: `GET`/`POST` text, `DELETE` text (clear both lines), `GET`/`POST` brightness. Partial JSON text updates; per-line align; empty `text` clears that line; lines longer than 16 characters marquee LTR (`[i..i+16)`, `i++`). +- Introduce a small **extension HTTP route registry** so future extensions mount under `/extensions//…` the same way (access + disabled → 503). +- No events from this extension. No configurable I2C addresses in v1. No PCF8574 / generic HD44780 backpack support. + +No **BREAKING** HTTP route or settings semantics. Push-button behavior unchanged (path/include move only). New LCD settings and routes are additive; LCD defaults off. + +## Capabilities + +### New Capabilities + +- `extension-http`: Shared pattern for mounting extension REST routes under `/extensions//…`, including access checks and the disabled-extension refusal. +- `lcd1602`: Optional Waveshare LCD1602 I2C extension — settings, Extensions UI, boot/last content, text/brightness HTTP API, scroll, and fixed-address driver. + +### Modified Capabilities + +- (none) + +## Impact + +- **Firmware**: remove smoke-test boot HELLO; nest `push_button/` and add `lcd1602/` under `src/extensions/`; update includes + native `build_src_filter` paths; LCD driver + apply/poll + handlers inside `lcd1602/`; NVS settings + last-state blob; shared HTTP registry; `kRoutes` / `isKnownPath` aware of `/extensions//…`. +- **Web UI**: second Extensions section “LCD 1602” (optional split into `ui/src/extensions/` section components); settings types; API reference rows for new routes and settings fields. +- **Docs**: `docs/api.md`, `docs/settings.md`, hardware testing / README summaries if endpoint lists change; note J3 I2C wiring and Waveshare-only module; short note on `src/extensions/` layout. +- **Tests**: native settings validation; update push-button / pin-claims include paths; UI tests as needed. +- **Dependencies**: none new (raw Wire to AiP31068/SN3193). diff --git a/openspec/changes/archive/2026-11-14-lcd1602-extension/specs/extension-http/spec.md b/openspec/changes/archive/2026-11-14-lcd1602-extension/specs/extension-http/spec.md new file mode 100644 index 00000000..54ced537 --- /dev/null +++ b/openspec/changes/archive/2026-11-14-lcd1602-extension/specs/extension-http/spec.md @@ -0,0 +1,46 @@ +# Spec Delta + +## Purpose + +Defines how optional hardware extensions expose REST under `/extensions//…`, including access checks and refusals when an extension is disabled, so later extensions can reuse one mounting pattern. + +## ADDED Requirements + +### Requirement: Extension routes use a shared path prefix +The firmware MUST mount every extension-owned REST route under `/extensions//`, where `` is a stable kebab-case extension identifier. The SPA shell route `GET /extensions` MUST remain the Extensions page and MUST NOT be treated as an extension API route. + +#### Scenario: LCD text path shape +- **WHEN** a client calls the LCD 1602 text resource +- **THEN** the path is under `/extensions/lcd1602/` (not a top-level `/lcd1602` route) + +#### Scenario: SPA Extensions page unchanged +- **WHEN** a browser requests `GET /extensions` +- **THEN** the device serves the web UI shell as today + +### Requirement: Extension API access matches configured control routes +Extension API routes under `/extensions//…` MUST use the same access class as `POST /anim` (`Configured`: token when auth is on, and refused until connection mode is set). + +#### Scenario: Unconfigured connection mode +- **WHEN** connection mode is not yet set and a client calls an extension API route +- **THEN** the device refuses with the same class of refusal used for `POST /anim` + +### Requirement: Disabled extension refuses its API +When the settings toggle for extension `` is false, every API route under `/extensions//…` MUST answer **503** with a clear disabled message and MUST NOT perform that extension’s hardware I/O for the request. + +#### Scenario: Call while LCD extension off +- **WHEN** `lcd1602` is false and a client `POST`s `/extensions/lcd1602/text` +- **THEN** the response is **503** and the device does not talk to the LCD over I2C for that request + +### Requirement: Unknown method on a known extension path is 405 +For a path that belongs to a registered extension API route, an unsupported HTTP method MUST answer **405**. Paths that are not registered MUST answer **404**. + +#### Scenario: Wrong method on text +- **WHEN** a client sends `PUT /extensions/lcd1602/text` +- **THEN** the response is **405** + +### Requirement: Future extensions reuse the same mount table +New extension HTTP surfaces MUST be added by registering routes in the shared extension mount table (same prefix, access, and disabled gate), not by inventing a second top-level REST namespace for extensions. + +#### Scenario: Second extension later +- **WHEN** a later change adds another extension with REST +- **THEN** its routes are mounted under `/extensions//…` using the same registry pattern diff --git a/openspec/changes/archive/2026-11-14-lcd1602-extension/specs/lcd1602/spec.md b/openspec/changes/archive/2026-11-14-lcd1602-extension/specs/lcd1602/spec.md new file mode 100644 index 00000000..7693ee65 --- /dev/null +++ b/openspec/changes/archive/2026-11-14-lcd1602-extension/specs/lcd1602/spec.md @@ -0,0 +1,172 @@ +# Spec Delta + +## Purpose + +Optional Waveshare LCD1602 I2C extension that shows short status text over REST when enabled from the Extensions page, with boot content and brightness control. + +## ADDED Requirements + +### Requirement: LCD 1602 defaults off +The setting `lcd1602` MUST be a boolean on `GET /settings` and `POST /settings`, default **false** when unset, including after factory reset. Saving it MUST apply immediately without reboot. + +#### Scenario: Fresh device +- **WHEN** the device boots with no stored `lcd1602` value +- **THEN** `GET /settings` reports `lcd1602` false and the firmware does not initialize the LCD over I2C + +#### Scenario: Factory reset +- **WHEN** factory reset completes +- **THEN** `lcd1602` is false + +#### Scenario: Enable without reboot +- **WHEN** the client posts `{"lcd1602": true}` +- **THEN** the extension becomes active before the next reboot + +### Requirement: Disabled extension leaves LCD bus idle +When `lcd1602` is false, the firmware MUST NOT probe, initialize, write, or read the LCD or its backlight controller over I2C for this extension, and MUST NOT run LCD scroll ticks. + +#### Scenario: Module unplugged while off +- **WHEN** `lcd1602` is false and no LCD is connected +- **THEN** boot and runtime continue without LCD I2C traffic from this extension + +#### Scenario: Disable stops scroll +- **WHEN** the extension was scrolling and the client posts `{"lcd1602": false}` +- **THEN** scroll ticks stop and further LCD I2C writes for this extension do not run + +### Requirement: Fixed Waveshare I2C addresses +When enabled, the extension MUST use LCD address **0x3E** (AiP31068L) and backlight address **0x6B** (SN3193). Those addresses MUST NOT be settings. The extension MUST target the Waveshare LCD1602 I2C module family, not PCF8574 backpacks. + +#### Scenario: No address settings +- **WHEN** a client posts an unknown field intended as an LCD I2C address +- **THEN** `POST /settings` rejects it as an unknown or invalid field and does not save it + +### Requirement: Backlight on boot setting +The setting `lcd1602_backlight_boot` MUST be a boolean on `GET`/`POST /settings`, default **true** when unset, including after factory reset. It MUST persist when `lcd1602` is false. When the extension enables or boots with the extension on: if true, the firmware MUST turn the backlight on (default brightness unless last/config supplies another); if false, the backlight MUST stay off until a successful brightness API call. + +#### Scenario: Default true +- **WHEN** the device has no stored `lcd1602_backlight_boot` +- **THEN** `GET /settings` reports `lcd1602_backlight_boot` true + +#### Scenario: Wait for API +- **WHEN** `lcd1602` is true, `lcd1602_backlight_boot` is false, and boot content does not require a brightness from last +- **THEN** the backlight remains off until `POST /extensions/lcd1602/brightness` succeeds + +### Requirement: Boot content mode +The setting `lcd1602_boot` MUST be a string on `GET`/`POST /settings` allowing only `none`, `last`, and `config`, default **`none`** when unset, including after factory reset. Invalid values MUST be rejected without saving. The value MUST persist when `lcd1602` is false. On enable/boot with the extension on, the firmware MUST apply that mode. + +#### Scenario: none clears +- **WHEN** `lcd1602_boot` is `none` and the extension becomes active +- **THEN** both lines are cleared (empty) on the display when hardware is present + +#### Scenario: last restores +- **WHEN** `lcd1602_boot` is `last`, a last state is stored, and the extension becomes active with LCD present +- **THEN** the display shows the stored lines, aligns, and brightness + +#### Scenario: config shows settings lines +- **WHEN** `lcd1602_boot` is `config` and the extension becomes active with LCD present +- **THEN** the display shows `lcd1602_line1` and `lcd1602_line2` with default left align unless those strings are empty + +#### Scenario: invalid boot mode +- **WHEN** the client posts `{"lcd1602_boot": "welcome"}` +- **THEN** the device answers **400**, nothing is saved + +### Requirement: Boot config line strings +The settings `lcd1602_line1` and `lcd1602_line2` MUST be strings on `GET`/`POST /settings`, default empty when unset, including after factory reset. Each MUST accept at most **64** characters; longer values MUST be rejected without saving. They MUST persist when `lcd1602` is false and apply when `lcd1602_boot` is `config`. + +#### Scenario: Persist while off +- **WHEN** `lcd1602` is false and the client posts config lines +- **THEN** the values are saved and `GET /settings` returns them + +#### Scenario: Too long rejected +- **WHEN** the client posts a line longer than 64 characters +- **THEN** the device answers **400** and nothing is saved + +### Requirement: Extensions page owns LCD 1602 controls +The Extensions page MUST include an **LCD 1602** section for `lcd1602` and related boot settings. The Config page MUST NOT show these controls. Details and wiring MUST appear only while the draft toggle is on; the section MUST note `/extensions/lcd1602/` HTTP paths and that this extension emits no events. + +#### Scenario: Toggle from Extensions +- **WHEN** the user enables LCD 1602 and saves +- **THEN** the UI posts `lcd1602` true + +#### Scenario: Details hidden when off +- **WHEN** the draft LCD toggle is off +- **THEN** LCD boot/backlight/line controls and LCD wiring are not shown + +#### Scenario: Details shown when on +- **WHEN** the draft LCD toggle is on +- **THEN** the section shows backlight-on-boot, boot-content mode, Waveshare I2C Extension-port wiring, and (when mode is `config`) the two line fields + +#### Scenario: Config omits LCD +- **WHEN** the user opens the Config page +- **THEN** that page has no LCD 1602 controls + +### Requirement: Text API partial update +`POST /extensions/lcd1602/text` MUST accept JSON where omitted `line1`/`line2` leave that line unchanged, present line objects carry required `text` (0–64 chars) and optional `align` (default `left`), empty `text` clears the line, bad input is **400**, and success updates display when present, persists last state, and returns **200** with full text state. + +#### Scenario: Update one line +- **WHEN** only `line1` is posted with `{"text":"HI"}` +- **THEN** line1 becomes `HI` (align left) and line2 is unchanged + +#### Scenario: Clear one line +- **WHEN** the client posts `{"line1":{"text":""}}` +- **THEN** line1 is cleared and line2 is unchanged + +#### Scenario: Align center under 16 +- **WHEN** the client posts `{"line1":{"text":"OK","align":"center"}}` and the text length is ≤16 +- **THEN** the visible line is centered in 16 columns + +### Requirement: Long line marquees LTR +When a line’s `text` length is greater than 16, the firmware MUST ignore `align` for that line and scroll a 16-character window `[i .. i+16)` advancing `i` by one on each step (wrapping), at a fixed readable pace. Lines ≤16 MUST NOT marquee. + +#### Scenario: Long line scrolls +- **WHEN** line1 text has more than 16 characters and the extension is on with LCD present +- **THEN** the visible 16 columns advance through the string in a loop until the line is replaced or cleared + +#### Scenario: Short line static +- **WHEN** line1 text has 16 or fewer characters with align `right` +- **THEN** the line stays static and right-aligned + +### Requirement: GET text returns full logical state +`GET /extensions/lcd1602/text` MUST return JSON with `line1` and `line2` objects each containing `text` and `align` for the current logical content (full string, not only the 16-column viewport). + +#### Scenario: Get after partial post +- **WHEN** the client successfully set both lines then `GET`s `/extensions/lcd1602/text` +- **THEN** the body includes both lines’ full `text` and `align` values + +### Requirement: DELETE text clears both lines +`DELETE /extensions/lcd1602/text` MUST clear both lines, stop marquees, leave brightness unchanged, persist last state, and answer **200** with the cleared text state when the extension is on. + +#### Scenario: Clear both +- **WHEN** the client `DELETE`s `/extensions/lcd1602/text` while the extension is on +- **THEN** both lines are empty and brightness is unchanged + +### Requirement: Brightness API +`GET /extensions/lcd1602/brightness` MUST return JSON `{"brightness": <0-100>}`. `POST /extensions/lcd1602/brightness` MUST accept `{"brightness": <0-100>}`, apply backlight (0 = off), persist last state, and answer **200** with the new value. Out-of-range or bad types MUST answer **400** without changing brightness. + +#### Scenario: Set brightness +- **WHEN** the client posts `{"brightness": 50}` while the extension is on and LCD backlight is reachable +- **THEN** backlight is set near 50% and `GET` reports `50` + +#### Scenario: Invalid brightness +- **WHEN** the client posts `{"brightness": 101}` +- **THEN** the response is **400** and brightness is unchanged + +### Requirement: Missing LCD while enabled +When `lcd1602` is true but the LCD does not ACK at `0x3E`, write/clear/brightness requests that need hardware MUST answer **503** with a not-found style message. `GET` text/brightness MAY return the last known logical state from RAM/NVS. The enabled setting MUST remain true. + +#### Scenario: Write without hardware +- **WHEN** `lcd1602` is true, no device ACKs at `0x3E`, and the client posts text +- **THEN** the response is **503** and `GET /settings` still reports `lcd1602` true + +### Requirement: Last state persistence +After every successful text update, clear, or brightness change, the firmware MUST store last state: both lines’ text and align, plus brightness. Factory reset MUST clear last state to empty lines, align left, and a defined default brightness (implementation default, documented). + +#### Scenario: Boot last after power cycle +- **WHEN** last state was saved, `lcd1602_boot` is `last`, and the device reboots with the extension on and LCD present +- **THEN** the display restores that last text, align, and brightness + +### Requirement: No outbound events +The LCD 1602 extension MUST NOT publish outbound events on WebSocket or serial. + +#### Scenario: Text update silent on event bus +- **WHEN** a successful `POST /extensions/lcd1602/text` completes +- **THEN** no new outbound event is emitted for that update diff --git a/openspec/changes/archive/2026-11-14-lcd1602-extension/tasks.md b/openspec/changes/archive/2026-11-14-lcd1602-extension/tasks.md new file mode 100644 index 00000000..ccf3dda0 --- /dev/null +++ b/openspec/changes/archive/2026-11-14-lcd1602-extension/tasks.md @@ -0,0 +1,46 @@ +# Tasks + +## 1. Remove LCD smoke test + +- [x] 1.1 Delete the temporary LCD test path before building the extension: remove `initLcd1602Hello()` call from `main.cpp`, delete `src/display/lcd1602.cpp` / `src/display/lcd1602.h`, and drop smoke-only LCD address constants from `include/pins.h` if nothing else needs them yet; verify `rg` finds no `initLcd1602Hello` / `LCD1602: HELLO` and `pio run` still succeeds + +## 2. Extension tree layout (incl. push-button) + +- [x] 2.1 Move push-button sources into `src/extensions/push_button/` (`push_button`, `logic`, `sfx`), update all `#include` sites, `platformio.ini` native `build_src_filter`, and native tests; verify `pio test -e native` and `pio run` pass with unchanged push-button behavior +- [x] 2.2 Add `src/extensions/README.md` stating the rule (per-extension code under `src/extensions//`; shared infra at `src/extensions/` root; OLED/eyes stay in `src/display/`) and verify the README matches the on-disk layout after the move +- [x] 2.3 Keep `pin_claims*` at `src/extensions/` root (shared); verify pin-claim native tests still include the correct path + +## 3. Settings foundation + +- [x] 3.1 Add `lcd1602`, `lcd1602_backlight_boot`, `lcd1602_boot`, `lcd1602_line1`, `lcd1602_line2` through the settings checklist (defaults, NVS keys ≤15 chars, validate, getters, patch, GET/POST JSON) and verify `pio test -e native` covers validation (boot enum, line length ≤64, defaults false/true/none/empty) +- [x] 3.2 Add last-state NVS blob load/save (both lines text+align + brightness; factory reset clears to empty/left + documented default brightness) and verify reset + reload round-trip in native or focused firmware unit coverage where practical +- [x] 3.3 Update `docs/settings.md` field/NVS lists for the new keys and verify the listed key names match `nvs.h` + +## 4. LCD driver and extension runtime (`src/extensions/lcd1602/`) + +- [x] 4.1 Add AiP31068/SN3193 `hw` helpers (fixed `0x3E`/`0x6B` in `pins.h` as needed) under `src/extensions/lcd1602/` only — not `src/display/` — and verify `pio run` compiles +- [x] 4.2 Implement `lcd1602ApplyFromSettings` / disable path (no I2C when off; probe+init+boot mode when on) in `src/extensions/lcd1602/` and verify serial log shows skip when off and init/boot behavior when on (or soft 503 path when NACK) +- [x] 4.3 Implement logical state, align ≤16, LTR marquee `i++` with readable fixed step/pause, and `lcd1602Poll` from `loop()`; verify long line scrolls and short aligned lines stay static on hardware or with a deterministic scroll-index unit test +- [x] 4.4 Wire apply on settings save and boot after `Wire.begin`; verify enable/disable via `POST /settings` applies without reboot + +## 5. Extension HTTP registry and LCD API + +- [x] 5.1 Add shared `http_registry` at `src/extensions/` root (`/extensions//`, `Configured` access, disabled → 503, `isKnownPath` for 405), wired from `registerHttpRoutes`; verify a disabled LCD call returns 503 with no I2C side effects +- [x] 5.2 Implement `GET`/`POST`/`DELETE /extensions/lcd1602/text` handlers under `src/extensions/lcd1602/http.*` (partial JSON, empty text clears line, persist last on success, 400 on bad body, 503 if LCD NACK on mutate) and verify with curl or UI-less HTTP checks against the documented examples +- [x] 5.3 Implement `GET`/`POST /extensions/lcd1602/brightness` in the same `lcd1602` http module (0–100, persist last, 400/503 rules) and verify GET mirrors last successful value +- [x] 5.4 Sync `docs/api.md`, `ui/src/views/ApiReference.tsx`, and README / `docs/hardware/testing.md` endpoint summaries for the new routes; verify path/method/param text matches handlers + +## 6. Extensions UI + +- [x] 6.1 Add **LCD 1602** section on Extensions (toggle + backlight boot + boot mode + config lines when relevant + Waveshare I2C wiring hint + API note, no events); optionally extract push-button / LCD into `ui/src/extensions/*Section.tsx`; verify Config page has no LCD controls +- [x] 6.2 Extend `ui` Settings types and tests/fixtures for the new fields; verify `npm run lint --prefix ui` and `npm test --prefix ui` pass + +## 7. Integration check + +- [x] 7.1 Run `pio run` and confirm firmware builds clean after the full change + +## Workflow follow-up + +- Archive the change after review when implementation matches the specs. +- Verify the archived main specs for `extension-http` and `lcd1602` after archive. +- Hardware smoke (LCD on J3 + push-button after move) is manual — outside this task list. diff --git a/openspec/changes/archive/2026-11-17-lcd1602-follow-sleep-backlight/.openspec.yaml b/openspec/changes/archive/2026-11-17-lcd1602-follow-sleep-backlight/.openspec.yaml new file mode 100644 index 00000000..bbe8b393 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-lcd1602-follow-sleep-backlight/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-17 diff --git a/openspec/changes/archive/2026-11-17-lcd1602-follow-sleep-backlight/design.md b/openspec/changes/archive/2026-11-17-lcd1602-follow-sleep-backlight/design.md new file mode 100644 index 00000000..85b7c7b1 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-lcd1602-follow-sleep-backlight/design.md @@ -0,0 +1,64 @@ +# Design + +## Context + +See proposal.md — Why. Today `lcd1602_backlight_boot` only steers enable/boot brightness in `applyBrightnessPolicy` (`src/extensions/lcd1602/lcd1602.cpp`). Sleep/wake always call `lcd1602FadeBrightnessTo` from `src/sleep.cpp` when the extension is active. HTTP/serial/UI/docs all name the boot field. NVS short key is already `ext_lcd_bl`. + +## Goals / Non-Goals + +**Goals:** + +- One boolean meaning: gate sleep/wake backlight fades; boot/enable still turns backlight on when not restoring from `last` (and when follow sleep is off, even if restored `last` brightness is 0). +- Rename the public JSON field; keep NVS storage cell. +- Spec, UI, HTTP, serial, and docs stay in sync (settings checklist + API sync). + +**Non-Goals:** + +- Changing fade duration (keep `anim::SLEEP_NOD_OFF_MS`). +- Restoring wake to pre-sleep brightness (always 100). +- Migrating or aliasing the old JSON key. +- New HTTP routes or outbound events. +- CLI host packages beyond serial/parity key lists that already hardcode the LCD settings slice. + +## Decisions + +1. **JSON rename, NVS reuse** + Public: `lcd1602_backlight_sleep`. Internal C++: rename symbols (`lcd1602BacklightSleep`, `settingsLcd1602BacklightSleep`, default `SETTINGS_DEFAULT_LCD1602_BACKLIGHT_SLEEP`). Keep `kKeyLcd1602Bl = "ext_lcd_bl"` so existing devices keep their stored bool without a migration step. + *Alt:* new NVS key — rejected (need migration + drop old). + *Alt:* keep JSON `…_boot` — rejected (misleading forever). + +2. **Gate fades in sleep path** + Wrap `lcd1602FadeBrightnessTo(0|100, …)` call sites in `sleep.cpp` with `settingsLcd1602BacklightSleep()` (and keep existing `g_active` guard inside the fade helper). + *Alt:* gate inside `lcd1602FadeBrightnessTo` — rejected; that helper is also usable for future non-sleep fades and should stay a dumb fade. + +3. **Boot policy always on (non-last), plus last-zero override when follow sleep off** + Replace the old if/else in `applyBrightnessPolicy`: when not applying `last` brightness, always set default brightness on (both flag true and false). Flag only gates sleep/wake fades. + `lcd1602_boot=last` still restores stored brightness, except when `lcd1602_backlight_sleep` is false and that brightness is **0** — then force default brightness on (sleep may have persisted 0 into last; follow-sleep-off means the panel stays lit while awake). + +4. **Unknown old key** + Do not accept or emit `lcd1602_backlight_boot`. Never returned on GET. + - **HTTP** `POST /settings`: `readPatch()` rejects the whole body with **400** `unknown field lcd1602_backlight_boot` and saves nothing — same as any other unknown settings field. + - **Serial** `settings.set`: only reads known keys and ignores unknowns. A body that also has known fields still saves those; a body with **only** the removed key (no known fields) → **400** `send at least one setting`. + Clients must drop the old key before submitting a patch (especially over HTTP). + +5. **UI copy** + Label: **Follow sleep**. Bound to `lcd1602_backlight_sleep`. + +6. **Breaking commit** + `feat(settings)!: rename lcd1602 backlight setting` with footer `BREAKING CHANGE: lcd1602_backlight_boot removed; use lcd1602_backlight_sleep.` Scope `settings` (JSON + NVS mapping); firmware/UI/docs ride along in the same change. + +## Risks / Trade-offs + +- [Devices with `ext_lcd_bl=false`] → Semantics flip: was “off until API”, becomes “boot on, no sleep dim”. Acceptable; matches product intent and default remains true. +- [External scripts still sending old key] → HTTP: **400** `unknown field lcd1602_backlight_boot`, entire patch rejected (including sibling fields). Serial: old key ignored; known siblings still save; only-old-key body → **400** `send at least one setting`. Mitigate: API docs + BREAKING CHANGE footer; tell clients to remove the key; ApiReference update. +- [Wake always 100] → Overrides a manual dim set before sleep when follow sleep is on. Accepted (user decision). + +## Migration Plan + +- Flash new firmware: NVS bool reused; no wipe. +- Clients: use `lcd1602_backlight_sleep`; remove `lcd1602_backlight_boot` from POST/serial bodies (HTTP: unknown field → 400, nothing saved; serial: key ignored, or 400 if it was the only field). +- Rollback: old firmware again reads `ext_lcd_bl` as backlight-on-boot (false again means off until API). + +## Open Questions + +None — wake target 100, OFF = boot on + no sleep sync, rename to `lcd1602_backlight_sleep`, and UI **Follow sleep** confirmed in explore. diff --git a/openspec/changes/archive/2026-11-17-lcd1602-follow-sleep-backlight/proposal.md b/openspec/changes/archive/2026-11-17-lcd1602-follow-sleep-backlight/proposal.md new file mode 100644 index 00000000..f275908b --- /dev/null +++ b/openspec/changes/archive/2026-11-17-lcd1602-follow-sleep-backlight/proposal.md @@ -0,0 +1,34 @@ +# Proposal + +## Why + +The LCD1602 Extensions toggle is labeled **Backlight on boot**, but firmware already dims/lights the backlight on sleep and wake regardless of that flag. The label and setting name describe the wrong behavior, and the false case (“stay off until `/brightness`”) fights the sleep/wake path users actually notice. + +## What Changes + +- Replace `lcd1602_backlight_boot` with **`lcd1602_backlight_sleep`** (default **true**). +- UI label becomes **Follow sleep**. +- **When true:** backlight on at enable/boot (unless boot content `last` supplies brightness); sleep fades to **0**; wake / wake-from-sleep fades to **100**. +- **When false:** backlight on at enable/boot (unless `last` supplies a non-zero brightness); if `last` brightness is **0**, still turn on. Sleep and wake **do not** change backlight. +- **BREAKING:** HTTP and serial settings drop `lcd1602_backlight_boot`; clients must use `lcd1602_backlight_sleep`. NVS key `ext_lcd_bl` is reused (stored bool kept). +- Remove the old “false → off until brightness API” policy. +- Document sleep/wake backlight gating in the lcd1602 capability (today only mentioned in API prose). + +## Capabilities + +### New Capabilities + +- (none) + +### Modified Capabilities + +- `lcd1602`: Replace backlight-on-boot requirement with follow-sleep backlight; add sleep/wake fade behavior gated by the setting. +- `serial-protocol`: Serial settings LCD slice uses `lcd1602_backlight_sleep` instead of `lcd1602_backlight_boot`. + +## Impact + +- Firmware: settings field/getters/NVS mapping rename; `applyBrightnessPolicy`; gate fades in `src/sleep.cpp`. +- HTTP/serial settings JSON; Web UI Extensions + ApiReference + types/tests. +- Docs: `docs/api.md`, `docs/settings.md`, `docs/serial.md`, `docs/hardware/testing.md`. +- Native settings tests / fixtures that mention the old key. +- Commit as `feat(settings)!:` (or `feat(http)!:`) with `BREAKING CHANGE` footer for the dropped JSON key. diff --git a/openspec/changes/archive/2026-11-17-lcd1602-follow-sleep-backlight/specs/lcd1602/spec.md b/openspec/changes/archive/2026-11-17-lcd1602-follow-sleep-backlight/specs/lcd1602/spec.md new file mode 100644 index 00000000..5ea51714 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-lcd1602-follow-sleep-backlight/specs/lcd1602/spec.md @@ -0,0 +1,64 @@ +# Spec Delta + +## REMOVED Requirements + +### Requirement: Backlight on boot setting +**Reason**: Replaced by follow-sleep backlight; the old false case (off until brightness API) conflicted with sleep/wake dimming. +**Migration**: Use `lcd1602_backlight_sleep`. Existing NVS `ext_lcd_bl` values keep their bool; interpret true as follow sleep. + +## ADDED Requirements + +### Requirement: Follow sleep backlight setting +The setting `lcd1602_backlight_sleep` MUST be a boolean on `GET`/`POST /settings`, default **true** when unset, including after factory reset. It MUST persist when `lcd1602` is false. On enable/boot with the extension on, when boot content is not restoring brightness from `last`, the firmware MUST turn the backlight on (default brightness). When the setting is false, enable/boot MUST still turn the backlight on even if `last` brightness is 0. + +#### Scenario: Default true +- **WHEN** the device has no stored `lcd1602_backlight_sleep` +- **THEN** `GET /settings` reports `lcd1602_backlight_sleep` true + +#### Scenario: Boot on when follow sleep off +- **WHEN** `lcd1602` is true, `lcd1602_backlight_sleep` is false, and boot content does not restore brightness from `last` +- **THEN** the backlight turns on at enable/boot + +#### Scenario: Boot on when follow sleep off and last brightness is zero +- **WHEN** `lcd1602` is true, `lcd1602_backlight_sleep` is false, `lcd1602_boot` is `last`, and stored last brightness is 0 +- **THEN** the backlight turns on at enable/boot (does not stay at 0) + +#### Scenario: Old key not restored +- **WHEN** the client posts `{"lcd1602_backlight_boot": true}` +- **THEN** `GET /settings` does not include `lcd1602_backlight_boot` + +### Requirement: Sleep and wake backlight fades +When the extension is on and `lcd1602_backlight_sleep` is true, entering sleep (`sleep` anim or idle `sleep_timeout`) MUST fade backlight to **0**, and wakeup / wake-from-sleep MUST fade backlight to **100**, over the same nod-off duration used for sleep motion. When `lcd1602_backlight_sleep` is false, sleep and wake MUST NOT change backlight. Manual brightness API MUST still apply regardless of the flag. + +#### Scenario: Follow sleep dims on sleep +- **WHEN** `lcd1602` is true, `lcd1602_backlight_sleep` is true, and the device enters sleep +- **THEN** the backlight fades to 0 + +#### Scenario: Follow sleep lights on wake +- **WHEN** `lcd1602` is true, `lcd1602_backlight_sleep` is true, and the device wakes or plays `wakeup` +- **THEN** the backlight fades to 100 + +#### Scenario: Follow sleep off leaves backlight +- **WHEN** `lcd1602` is true, `lcd1602_backlight_sleep` is false, and the device sleeps then wakes +- **THEN** backlight brightness is unchanged by those transitions + +## MODIFIED Requirements + +### Requirement: Extensions page owns LCD 1602 controls +The Extensions page MUST include an **LCD 1602** section for `lcd1602` and related boot settings. The Config page MUST NOT show these controls. Details and wiring MUST appear only while the draft toggle is on; the section MUST note `/extensions/lcd1602/` HTTP paths and that this extension emits no events. + +#### Scenario: Toggle from Extensions +- **WHEN** the user enables LCD 1602 and saves +- **THEN** the UI posts `lcd1602` true + +#### Scenario: Details hidden when off +- **WHEN** the draft LCD toggle is off +- **THEN** LCD boot/backlight/line controls and LCD wiring are not shown + +#### Scenario: Details shown when on +- **WHEN** the draft LCD toggle is on +- **THEN** the section shows a **Follow sleep** backlight toggle bound to `lcd1602_backlight_sleep`, boot-content mode, Waveshare I2C Extension-port wiring, and (when mode is `config`) the two line fields + +#### Scenario: Config omits LCD +- **WHEN** the user opens the Config page +- **THEN** that page has no LCD 1602 controls diff --git a/openspec/changes/archive/2026-11-17-lcd1602-follow-sleep-backlight/specs/serial-protocol/spec.md b/openspec/changes/archive/2026-11-17-lcd1602-follow-sleep-backlight/specs/serial-protocol/spec.md new file mode 100644 index 00000000..863ab27e --- /dev/null +++ b/openspec/changes/archive/2026-11-17-lcd1602-follow-sleep-backlight/specs/serial-protocol/spec.md @@ -0,0 +1,18 @@ +# Spec Delta + +## MODIFIED Requirements + +### Requirement: Serial settings include LCD 1602 fields +`settings.get` over serial MUST include the `lcd1602`, `lcd1602_backlight_sleep`, `lcd1602_boot`, `lcd1602_line1`, and `lcd1602_line2` fields with the same types and defaults as `GET /settings`. `settings.set` MUST accept those keys with the same validation and immediate-apply behavior as `POST /settings`. Other settings fields not already returned or accepted by serial MAY remain deferred (full GET `/settings` parity is not claimed by this change alone). + +#### Scenario: Enable LCD over serial +- **WHEN** the host sends `settings.set` with `{"lcd1602": true}` after provisioning +- **THEN** the extension becomes active without reboot and a later `settings.get` reports `lcd1602` true + +#### Scenario: Invalid boot mode rejected +- **WHEN** the host sends `settings.set` with `{"lcd1602_boot": "welcome"}` +- **THEN** the device answers **400** and does not save the value + +#### Scenario: Follow sleep field over serial +- **WHEN** the host sends `settings.set` with `{"lcd1602_backlight_sleep": false}` after provisioning +- **THEN** a later `settings.get` reports `lcd1602_backlight_sleep` false and does not include `lcd1602_backlight_boot` diff --git a/openspec/changes/archive/2026-11-17-lcd1602-follow-sleep-backlight/tasks.md b/openspec/changes/archive/2026-11-17-lcd1602-follow-sleep-backlight/tasks.md new file mode 100644 index 00000000..af67ddaf --- /dev/null +++ b/openspec/changes/archive/2026-11-17-lcd1602-follow-sleep-backlight/tasks.md @@ -0,0 +1,24 @@ +# Tasks + +## 1. Settings rename + +- [x] 1.1 Rename settings symbols/defaults (`lcd1602BacklightSleep`, `SETTINGS_DEFAULT_LCD1602_BACKLIGHT_SLEEP`, getter) across `settings.h` / `values.*` / `getters.cpp` / `nvs.cpp`; keep NVS key `ext_lcd_bl`; verify `pio test -e native` still passes +- [x] 1.2 Switch HTTP and serial settings JSON to `lcd1602_backlight_sleep` (handlers, serial link, apply-immediate checks in `commands.cpp`); verify GET/POST/serial get/set no longer emit or require `lcd1602_backlight_boot` +- [x] 1.3 Update `docs/settings.md` field and NVS mapping lines for the new key; verify the listed HTTP name matches `docs/api.md` after docs sync + +## 2. Backlight behavior + +- [x] 2.1 Change `applyBrightnessPolicy` so non-`last` enable/boot always turns backlight on (default brightness); verify enable with flag false leaves backlight on without waiting for `/brightness` +- [x] 2.2 Gate `lcd1602FadeBrightnessTo` call sites in `src/sleep.cpp` with `settingsLcd1602BacklightSleep()`; verify flag true still fades sleep→0 and wake→100, flag false leaves brightness unchanged across sleep/wake +- [x] 2.3 Run `pio run` after firmware edits and verify the build succeeds + +## 3. UI and API docs sync + +- [x] 3.1 Update UI types, Extensions draft/save, ApiReference, and `ui/test/robot.tsx` to `lcd1602_backlight_sleep` with label **Follow sleep**; verify `npm run lint --prefix ui` and `npm test --prefix ui` pass +- [x] 3.2 Update `docs/api.md`, `docs/serial.md`, and `docs/hardware/testing.md` settings tables/examples for the rename and follow-sleep behavior; verify wording matches the lcd1602 delta scenarios +- [x] 3.3 Update CLI parity key list (`packages/tiny-engineer-cli/src/commands/parity.js`) and any other hardcoded `lcd1602_backlight_boot` references; verify `rg lcd1602_backlight_boot` finds none outside archives/history + +## Workflow follow-up + +- Archive the change after implementation and review (`/opsx-archive`). +- Commit as `feat(settings)!: …` with `BREAKING CHANGE:` footer for the dropped JSON key. diff --git a/openspec/changes/archive/2026-11-17-lcd1602-welcome-hello/.openspec.yaml b/openspec/changes/archive/2026-11-17-lcd1602-welcome-hello/.openspec.yaml new file mode 100644 index 00000000..bbe8b393 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-lcd1602-welcome-hello/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-17 diff --git a/openspec/changes/archive/2026-11-17-lcd1602-welcome-hello/design.md b/openspec/changes/archive/2026-11-17-lcd1602-welcome-hello/design.md new file mode 100644 index 00000000..4faa27ae --- /dev/null +++ b/openspec/changes/archive/2026-11-17-lcd1602-welcome-hello/design.md @@ -0,0 +1,61 @@ +# Design + +## Context + +See proposal.md — Why. LCD already applies boot content in `lcd1602ApplyFromSettings` before Wi‑Fi; boot then may `setAnimation(Welcome)`. Welcome also runs from `POST /anim`. Text goes through `lcd1602SetText` / `lcd1602ClearText` / GET via `lcd1602TextState()`. Welcome ends via `finishAnimation` from `updateWelcome`. Existing LCD settings use NVS keys `ext_lcd*`. + +## Goals / Non-Goals + +**Goals:** + +- Opt-in overlay tied to every `AnimationId::Welcome` start/end. +- Queue text/clear during overlay; logical GET; no HELLO in `last` NVS. +- Settings + UI + docs/serial parity for the new bool. + +**Non-Goals:** + +- Custom greeting strings or i18n. +- Overlay on setup-AP `playWelcome()` without welcome anim. +- Deferring brightness/color. +- Changing welcome audio/motion timing. + +## Decisions + +1. **Setting name** + JSON `lcd1602_welcome_hello`, UI **Hello on welcome**, default false. NVS `ext_lcd_hi` (≤15). C++ `lcd1602WelcomeHello` / `settingsLcd1602WelcomeHello()`. + +2. **Hook points** + - Start overlay when welcome animation actually starts (`startWelcome` / registry start path), if extension on + flag. + - End overlay in one place when leaving Welcome — prefer `finishAnimation` when current anim is Welcome, or an explicit `lcd1602OnWelcomeFinished()` called from welcome’s finish path so other one-shots do not touch LCD. Prefer **welcome-specific end hook** from `updateWelcome` before/with `finishAnimation` to avoid coupling every animation finish. + - Also clear overlay if Welcome is interrupted by another animation (setAnimation replaces Welcome) — same end path: restore stash or apply queue. + +3. **State machine (RAM only)** + ``` + idle --> overlay (stash g_text, show HELLO/HUMAN center, no persist) + --> optional pending logical text (last-wins merges) + --> idle (apply pending if any else restore stash; persist only on real apply) + ``` + Visible framebuffer during overlay is HELLO/HUMAN; `g_text` holds logical (stash, then pending merges). GET reads `g_text`. Render path draws overlay strings while `g_overlayActive`. + +4. **Text/clear during overlay** + Validate as today; merge into `g_text` (logical); set `g_pendingApply=true`; return **200** with logical body; do not `persistLast` until overlay ends and apply runs. DELETE = both lines empty in logical state. Brightness/color still apply and may `persistLast` immediately, but must snapshot **stash** (last-applied) lines — never queued `g_text` — until the pending apply runs. + +5. **Boot order** + Unchanged: boot content then later Welcome. Overlay stashes whatever boot already set. + +6. **Flag false / extension off** + No overlay. Mid-overlay disable: end overlay immediately (apply pending or restore) when settings turn extension or flag off. Flag-only off while the extension stays on must **not** re-run `applyBootContent()` (that would wipe logical `g_text`); end overlay + render is enough. Live `lcd1602_backlight_sleep` / `lcd1602_welcome_hello` changes must also keep runtime text (and any pending apply) intact — awake brightness force-on only if follow-sleep turns off and brightness is 0; ending the overlay then persists the accepted text, including when boot is `last`. Full boot reapply still runs for enable, boot/line changes, and boot/`changed == nullptr`. + +## Risks / Trade-offs + +- [Welcome interrupted by another anim] → Must end overlay on leave-Welcome, not only natural finish. Mitigate: end hook from animation controller when leaving Welcome. +- [Agent GET expects visible text] → Spec says logical; document in api.md. +- [NVS key budget] → `ext_lcd_hi` fits. + +## Migration Plan + +- New key absent → false. No migration. Rollback: ignore unknown JSON field. + +## Open Questions + +None — every-welcome trigger and logical GET/pending confirmed in explore. diff --git a/openspec/changes/archive/2026-11-17-lcd1602-welcome-hello/proposal.md b/openspec/changes/archive/2026-11-17-lcd1602-welcome-hello/proposal.md new file mode 100644 index 00000000..d3243f67 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-lcd1602-welcome-hello/proposal.md @@ -0,0 +1,32 @@ +# Proposal + +## Why + +Welcome already says “Hello, human” in audio and motion, but the optional LCD1602 stays on boot/agent text through that moment. A small opt-in overlay makes the desk display match the greeting without replacing normal LCD content afterward. + +## What Changes + +- Add boolean setting **`lcd1602_welcome_hello`** (default **false**), persisted when the extension is off, apply immediately; UI label **Hello on welcome** on Extensions. +- When the extension is on and the flag is true, every `welcome` animation (boot after Wi‑Fi and `POST /anim?name=welcome`) overlays centered **HELLO** / **HUMAN** on the LCD for the duration of that animation. +- When welcome ends, restore the pre-overlay logical text (or apply any text/clear updates queued during the overlay). +- Text/clear HTTP and serial `ext` updates during the overlay are accepted (**200**), last-wins queued, and do not change the visible HELLO lines until welcome finishes. +- `GET` text during overlay returns **logical** content: pending queued text if any, otherwise the stashed pre-overlay state — never the HELLO overlay itself. +- Do not persist HELLO/HUMAN as `last` state. +- Out of scope: setup-AP `playWelcome()` without the welcome animation; delaying brightness/color; custom hello strings. + +## Capabilities + +### New Capabilities + +- (none) + +### Modified Capabilities + +- `lcd1602`: Welcome-hello setting, overlay behavior, queued text/clear, logical GET during overlay. +- `serial-protocol`: Serial settings LCD slice includes `lcd1602_welcome_hello`. + +## Impact + +- Firmware: settings checklist + NVS key; LCD overlay/queue state; hooks on welcome start/finish; text/clear/GET paths. +- HTTP/serial settings JSON; Extensions UI + ApiReference; docs (`api.md`, `settings.md`, `serial.md`, testing summaries as needed). +- Non-breaking (new optional field, default off). diff --git a/openspec/changes/archive/2026-11-17-lcd1602-welcome-hello/specs/lcd1602/spec.md b/openspec/changes/archive/2026-11-17-lcd1602-welcome-hello/specs/lcd1602/spec.md new file mode 100644 index 00000000..a3de6435 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-lcd1602-welcome-hello/specs/lcd1602/spec.md @@ -0,0 +1,76 @@ +# Spec Delta + +## ADDED Requirements + +### Requirement: Welcome hello setting +The setting `lcd1602_welcome_hello` MUST be a boolean on `GET`/`POST /settings`, default **false** when unset, including after factory reset. It MUST persist when `lcd1602` is false and apply immediately. When false, welcome animations MUST NOT change LCD text for this feature. + +#### Scenario: Default false +- **WHEN** the device has no stored `lcd1602_welcome_hello` +- **THEN** `GET /settings` reports `lcd1602_welcome_hello` false + +#### Scenario: Flag off leaves LCD text alone +- **WHEN** `lcd1602` is true, `lcd1602_welcome_hello` is false, and a `welcome` animation runs +- **THEN** the LCD text is not replaced with HELLO/HUMAN by this feature + +### Requirement: Welcome hello overlay +When `lcd1602` and `lcd1602_welcome_hello` are true, every `welcome` animation (boot after Wi‑Fi and `POST /anim` `welcome`) MUST show line1 **HELLO** and line2 **HUMAN**, both center-aligned, for the animation duration. HELLO/HUMAN MUST NOT be written to last-state NVS. When welcome ends with no queued text update, the firmware MUST restore the pre-overlay logical text on the display. + +#### Scenario: Boot welcome shows hello +- **WHEN** the extension is on, the flag is true, and boot starts `welcome` after Wi‑Fi connect +- **THEN** the LCD shows centered HELLO and HUMAN until that welcome finishes + +#### Scenario: API welcome shows hello +- **WHEN** the extension is on, the flag is true, and the client posts `welcome` via `/anim` +- **THEN** the LCD shows centered HELLO and HUMAN until that welcome finishes + +#### Scenario: Restore after welcome +- **WHEN** welcome ends and no text/clear was queued during the overlay +- **THEN** the display shows the logical text from before the overlay + +### Requirement: Queue text during welcome hello +While the welcome-hello overlay is active, successful `POST`/`DELETE` text (HTTP or serial `ext`) MUST NOT change the visible HELLO/HUMAN lines, MUST NOT persist last state for those queued edits until applied, MUST answer **200**, and MUST last-wins queue the resulting logical text. When welcome ends, the firmware MUST apply the queued logical text to the display and persist last state. Brightness and color MUST still apply immediately. + +#### Scenario: Post during overlay queues +- **WHEN** the overlay is active and the client posts new line text +- **THEN** the response is **200**, HELLO/HUMAN stay visible, and after welcome ends the display shows the posted text + +#### Scenario: Last wins +- **WHEN** two successful text updates arrive during one overlay +- **THEN** after welcome ends the display matches the later update + +#### Scenario: Delete during overlay queues clear +- **WHEN** the overlay is active and the client deletes text +- **THEN** HELLO/HUMAN stay visible until welcome ends, then both lines are empty + +### Requirement: GET text is logical during welcome hello +While the welcome-hello overlay is active, `GET /extensions/lcd1602/text` (and serial `ext` GET text) MUST return the logical text: the queued result if a text/clear was accepted during the overlay, otherwise the pre-overlay stash. It MUST NOT return HELLO/HUMAN as the logical lines. + +#### Scenario: Get during overlay without queue +- **WHEN** the overlay is active, no text was queued, and the client GETs text +- **THEN** the body matches the pre-overlay logical lines, not HELLO/HUMAN + +#### Scenario: Get during overlay with queue +- **WHEN** the overlay is active, a text update was queued, and the client GETs text +- **THEN** the body matches the queued logical lines, not HELLO/HUMAN + +## MODIFIED Requirements + +### Requirement: Extensions page owns LCD 1602 controls +The Extensions page MUST include an **LCD 1602** section for `lcd1602` and related boot settings. The Config page MUST NOT show these controls. Details and wiring MUST appear only while the draft toggle is on; the section MUST note `/extensions/lcd1602/` HTTP paths and that this extension emits no events. + +#### Scenario: Toggle from Extensions +- **WHEN** the user enables LCD 1602 and saves +- **THEN** the UI posts `lcd1602` true + +#### Scenario: Details hidden when off +- **WHEN** the draft LCD toggle is off +- **THEN** LCD boot/backlight/line controls and LCD wiring are not shown + +#### Scenario: Details shown when on +- **WHEN** the draft LCD toggle is on +- **THEN** the section shows a **Follow sleep** backlight toggle bound to `lcd1602_backlight_sleep`, a **Hello on welcome** toggle bound to `lcd1602_welcome_hello`, boot-content mode, Waveshare I2C Extension-port wiring, and (when mode is `config`) the two line fields + +#### Scenario: Config omits LCD +- **WHEN** the user opens the Config page +- **THEN** that page has no LCD 1602 controls diff --git a/openspec/changes/archive/2026-11-17-lcd1602-welcome-hello/specs/serial-protocol/spec.md b/openspec/changes/archive/2026-11-17-lcd1602-welcome-hello/specs/serial-protocol/spec.md new file mode 100644 index 00000000..a102c1e1 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-lcd1602-welcome-hello/specs/serial-protocol/spec.md @@ -0,0 +1,22 @@ +# Spec Delta + +## MODIFIED Requirements + +### Requirement: Serial settings include LCD 1602 fields +`settings.get` over serial MUST include the `lcd1602`, `lcd1602_backlight_sleep`, `lcd1602_welcome_hello`, `lcd1602_boot`, `lcd1602_line1`, and `lcd1602_line2` fields with the same types and defaults as `GET /settings`. `settings.set` MUST accept those keys with the same validation and immediate-apply behavior as `POST /settings`. Other settings fields not already returned or accepted by serial MAY remain deferred (full GET `/settings` parity is not claimed by this change alone). + +#### Scenario: Enable LCD over serial +- **WHEN** the host sends `settings.set` with `{"lcd1602": true}` after provisioning +- **THEN** the extension becomes active without reboot and a later `settings.get` reports `lcd1602` true + +#### Scenario: Invalid boot mode rejected +- **WHEN** the host sends `settings.set` with `{"lcd1602_boot": "welcome"}` +- **THEN** the device answers **400** and does not save the value + +#### Scenario: Follow sleep field over serial +- **WHEN** the host sends `settings.set` with `{"lcd1602_backlight_sleep": false}` after provisioning +- **THEN** a later `settings.get` reports `lcd1602_backlight_sleep` false and does not include `lcd1602_backlight_boot` + +#### Scenario: Welcome hello field over serial +- **WHEN** the host sends `settings.set` with `{"lcd1602_welcome_hello": true}` after provisioning +- **THEN** a later `settings.get` reports `lcd1602_welcome_hello` true diff --git a/openspec/changes/archive/2026-11-17-lcd1602-welcome-hello/tasks.md b/openspec/changes/archive/2026-11-17-lcd1602-welcome-hello/tasks.md new file mode 100644 index 00000000..1f39f9e2 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-lcd1602-welcome-hello/tasks.md @@ -0,0 +1,20 @@ +# Tasks + +## 1. Settings and API surface + +- [x] 1.1 Add `lcd1602_welcome_hello` through the settings checklist (default false, NVS `ext_lcd_hi`, patch/getter/HTTP/serial JSON, immediate apply); verify `pio test -e native` passes +- [x] 1.2 Update `docs/settings.md`, `docs/api.md`, `docs/serial.md`, and hardware testing settings lists for the new field; verify names match across docs +- [x] 1.3 Add Extensions UI toggle **Hello on welcome**, ApiReference row, types + `ui/test/robot.tsx`, and CLI parity key list; verify `npm run lint --prefix ui` and `npm test --prefix ui` pass + +## 2. Overlay and queue + +- [x] 2.1 Implement welcome-hello overlay state in LCD1602 (stash, show HELLO/HUMAN center without `persistLast`, restore or apply pending on end); verify flag false leaves text unchanged through a welcome +- [x] 2.2 Hook overlay start/end for every Welcome start and leave (natural finish and interrupt by another anim); verify boot welcome and `POST /anim?name=welcome` both show then restore +- [x] 2.3 Queue text/clear during overlay (last-wins, **200**, logical GET, persist only on apply after end); verify post-during-overlay then end shows queued text, and GET during overlay never returns HELLO/HUMAN +- [x] 2.4 End overlay immediately when extension or flag turns off mid-overlay; verify display returns to logical text +- [x] 2.5 Run `pio run` after firmware edits and verify the build succeeds + +## Workflow follow-up + +- Archive after implementation and review (`/opsx-archive`). +- Commit as `feat(settings): add LCD welcome hello overlay` (non-breaking). diff --git a/openspec/specs/cli-transport/spec.md b/openspec/specs/cli-transport/spec.md index 01ce737b..8ef2fd1e 100644 --- a/openspec/specs/cli-transport/spec.md +++ b/openspec/specs/cli-transport/spec.md @@ -164,3 +164,25 @@ After a successful serial `play` open, if streaming fails before normal completi #### Scenario: Probe honors yield - **WHEN** a yield is active and the user runs `port --probe` - **THEN** the command fails, names the yield, and does not start a daemon or open the serial device in the CLI process + +### Requirement: CLI ext command for registered extensions +The CLI MUST provide an `ext …` command family that targets extension APIs over the selected transport (`http` or `serial`). For id `lcd1602`, the CLI MUST support text get, text set (partial lines/align), text clear, brightness get, and brightness set. Unknown `` values that the CLI does not know how to map MUST fail locally with a clear error without contacting the robot. + +#### Scenario: LCD text over HTTP +- **WHEN** the user runs `tiny-engineer ext lcd1602 text set` with line arguments and transport `http` +- **THEN** the CLI issues `POST /extensions/lcd1602/text` and prints or confirms the resulting state + +#### Scenario: LCD brightness over serial +- **WHEN** the user runs `tiny-engineer ext lcd1602 brightness set 20` with transport `serial` +- **THEN** the CLI sends serial `ext` for brightness and does not fall back to HTTP + +#### Scenario: Unknown extension id +- **WHEN** the user runs `tiny-engineer ext nope text get` +- **THEN** the CLI exits non-zero with an unknown-extension style error and does not open a robot session solely for that id + +### Requirement: Ext uses the same transport resolution as other robot commands +`ext` MUST honor the existing transport resolution order (flag → env/config → default `http`) and the same URL/port/token rules as other day-to-day robot commands. + +#### Scenario: Serial transport flag +- **WHEN** the user passes `--transport serial` to an `ext lcd1602` command +- **THEN** the CLI uses serial and does not fall back to HTTP on failure diff --git a/openspec/specs/extension-http/spec.md b/openspec/specs/extension-http/spec.md new file mode 100644 index 00000000..2530fbea --- /dev/null +++ b/openspec/specs/extension-http/spec.md @@ -0,0 +1,45 @@ +# extension-http Specification + +## Purpose +Defines how optional hardware extensions expose REST under `/extensions//…`, including access checks and refusals when an extension is disabled, so later extensions can reuse one mounting pattern. + +## Requirements + +### Requirement: Extension routes use a shared path prefix +The firmware MUST mount every extension-owned REST route under `/extensions//`, where `` is a stable kebab-case extension identifier. The SPA shell route `GET /extensions` MUST remain the Extensions page and MUST NOT be treated as an extension API route. + +#### Scenario: LCD text path shape +- **WHEN** a client calls the LCD 1602 text resource +- **THEN** the path is under `/extensions/lcd1602/` (not a top-level `/lcd1602` route) + +#### Scenario: SPA Extensions page unchanged +- **WHEN** a browser requests `GET /extensions` +- **THEN** the device serves the web UI shell as today + +### Requirement: Extension API access matches configured control routes +Extension API routes under `/extensions//…` MUST use the same access class as `POST /anim` (`Configured`: token when auth is on, and refused until connection mode is set). + +#### Scenario: Unconfigured connection mode +- **WHEN** connection mode is not yet set and a client calls an extension API route +- **THEN** the device refuses with the same class of refusal used for `POST /anim` + +### Requirement: Disabled extension refuses its API +When the settings toggle for extension `` is false, every API route under `/extensions//…` MUST answer **503** with a clear disabled message and MUST NOT perform that extension’s hardware I/O for the request. + +#### Scenario: Call while LCD extension off +- **WHEN** `lcd1602` is false and a client `POST`s `/extensions/lcd1602/text` +- **THEN** the response is **503** and the device does not talk to the LCD over I2C for that request + +### Requirement: Unknown method on a known extension path is 405 +For a path that belongs to a registered extension API route, an unsupported HTTP method MUST answer **405**. Paths that are not registered MUST answer **404**. + +#### Scenario: Wrong method on text +- **WHEN** a client sends `PUT /extensions/lcd1602/text` +- **THEN** the response is **405** + +### Requirement: Future extensions reuse the same mount table +New extension HTTP surfaces MUST be added by registering routes in the shared extension mount table (same prefix, access, and disabled gate), not by inventing a second top-level REST namespace for extensions. + +#### Scenario: Second extension later +- **WHEN** a later change adds another extension with REST +- **THEN** its routes are mounted under `/extensions//…` using the same registry pattern diff --git a/openspec/specs/extension-serial/spec.md b/openspec/specs/extension-serial/spec.md new file mode 100644 index 00000000..ad428ea8 --- /dev/null +++ b/openspec/specs/extension-serial/spec.md @@ -0,0 +1,36 @@ +# extension-serial Specification + +## Purpose + +Lets hosts drive extension REST surfaces over USB serial through one `ext` op that reuses the same mount table, access, and disabled-gate rules as HTTP `/extensions//…`. + +## Requirements + +### Requirement: Serial ext op mounts extensions +The serial control API MUST accept JSON requests with `op` equal to **`ext`**. The request MUST name a kebab-case extension `id`, a resource `suffix` (path segment after `/extensions//`), and an HTTP-equivalent `method` (`GET`, `POST`, `DELETE`, …). The device MUST dispatch using the same registered extension route table as HTTP. + +#### Scenario: LCD text get over serial +- **WHEN** the host sends `ext` with `id` `lcd1602`, `suffix` `text`, and `method` `GET` while the extension is on +- **THEN** the response carries the same logical text JSON shape as `GET /extensions/lcd1602/text` + +#### Scenario: Unknown extension id +- **WHEN** the host sends `ext` with an `id` that has no registered routes +- **THEN** the device answers **404** (or equivalent serial status) without performing extension hardware I/O + +### Requirement: Ext refusals match HTTP +For a registered extension route, serial `ext` MUST apply the same access class as the HTTP route (`Configured`). When the extension’s settings toggle is false, `ext` MUST answer **503** with a clear disabled message and MUST NOT perform that extension’s hardware I/O. Unsupported method on a known suffix MUST answer **405**. + +#### Scenario: LCD off refuses text post +- **WHEN** `lcd1602` is false and the host sends `ext` POST `text` +- **THEN** the response is **503** and no LCD I2C traffic runs for that request + +#### Scenario: Wrong method +- **WHEN** the host sends `ext` with method `PUT` or `PATCH` on suffix `text` for `lcd1602` +- **THEN** the response is **405** + +### Requirement: Ext body and success semantics match HTTP handlers +When method and body are valid for a registered route, serial `ext` MUST produce the same success/error codes and JSON payloads as the corresponding HTTP handler (including LCD validation **400**, missing hardware **503** messages, and last-state updates on success). + +#### Scenario: Brightness set parity +- **WHEN** the host sends `ext` POST `brightness` with `{"brightness":50}` and the backlight is reachable +- **THEN** the response is **200** with brightness `50`, matching HTTP `POST /extensions/lcd1602/brightness` diff --git a/openspec/specs/lcd1602/spec.md b/openspec/specs/lcd1602/spec.md new file mode 100644 index 00000000..3d1d8bb9 --- /dev/null +++ b/openspec/specs/lcd1602/spec.md @@ -0,0 +1,272 @@ +# lcd1602 Specification + +## Purpose +Optional Waveshare LCD1602 I2C extension that shows short status text over REST when enabled from the Extensions page, with boot content and brightness control. + +## Requirements + +### Requirement: LCD 1602 defaults off +The setting `lcd1602` MUST be a boolean on `GET /settings` and `POST /settings`, default **false** when unset, including after factory reset. Saving it MUST apply immediately without reboot. + +#### Scenario: Fresh device +- **WHEN** the device boots with no stored `lcd1602` value +- **THEN** `GET /settings` reports `lcd1602` false and the firmware does not initialize the LCD over I2C + +#### Scenario: Factory reset +- **WHEN** factory reset completes +- **THEN** `lcd1602` is false + +#### Scenario: Enable without reboot +- **WHEN** the client posts `{"lcd1602": true}` +- **THEN** the extension becomes active before the next reboot + +### Requirement: Disabled extension leaves LCD bus idle +When `lcd1602` is false, the firmware MUST NOT probe, initialize, write, or read the LCD or its backlight controller over I2C for this extension, and MUST NOT run LCD scroll ticks. + +#### Scenario: Module unplugged while off +- **WHEN** `lcd1602` is false and no LCD is connected +- **THEN** boot and runtime continue without LCD I2C traffic from this extension + +#### Scenario: Disable stops scroll +- **WHEN** the extension was scrolling and the client posts `{"lcd1602": false}` +- **THEN** scroll ticks stop and further LCD I2C writes for this extension do not run + +### Requirement: Fixed Waveshare I2C addresses +When enabled, the extension MUST use LCD address **0x3E** (AiP31068L). Controllable backlight MUST auto-detect **0x6B** (SN3193, Blue/Gray/Green) or **0x60** (PCA9633, RGB module); those addresses MUST NOT be settings. On PCA9633, brightness MUST scale the base RGB color; the color API sets that base (default white 255,255,255). The extension MUST target the Waveshare LCD1602 I2C module family, not PCF8574 backpacks. + +#### Scenario: No address settings +- **WHEN** a client posts an unknown field intended as an LCD I2C address +- **THEN** `POST /settings` rejects it as an unknown or invalid field and does not save it + +### Requirement: Follow sleep backlight setting +The setting `lcd1602_backlight_sleep` MUST be a boolean on `GET`/`POST /settings`, default **true** when unset, including after factory reset. It MUST persist when `lcd1602` is false. On enable/boot with the extension on, when boot content is not restoring brightness from `last`, the firmware MUST turn the backlight on (default brightness). When the setting is false, enable/boot MUST still turn the backlight on even if `last` brightness is 0. + +#### Scenario: Default true +- **WHEN** the device has no stored `lcd1602_backlight_sleep` +- **THEN** `GET /settings` reports `lcd1602_backlight_sleep` true + +#### Scenario: Boot on when follow sleep off +- **WHEN** `lcd1602` is true, `lcd1602_backlight_sleep` is false, and boot content does not restore brightness from `last` +- **THEN** the backlight turns on at enable/boot + +#### Scenario: Boot on when follow sleep off and last brightness is zero +- **WHEN** `lcd1602` is true, `lcd1602_backlight_sleep` is false, `lcd1602_boot` is `last`, and stored last brightness is 0 +- **THEN** the backlight turns on at enable/boot (does not stay at 0) + +#### Scenario: Old key not restored +- **WHEN** the client posts `{"lcd1602_backlight_boot": true}` +- **THEN** `GET /settings` does not include `lcd1602_backlight_boot` + +### Requirement: Sleep and wake backlight fades +When the extension is on and `lcd1602_backlight_sleep` is true, entering sleep (`sleep` anim or idle `sleep_timeout`) MUST fade backlight to **0**, and wakeup / wake-from-sleep MUST fade backlight to **100**, over the same nod-off duration used for sleep motion. When `lcd1602_backlight_sleep` is false, sleep and wake MUST NOT change backlight. Manual brightness API MUST still apply regardless of the flag. + +#### Scenario: Follow sleep dims on sleep +- **WHEN** `lcd1602` is true, `lcd1602_backlight_sleep` is true, and the device enters sleep +- **THEN** the backlight fades to 0 + +#### Scenario: Follow sleep lights on wake +- **WHEN** `lcd1602` is true, `lcd1602_backlight_sleep` is true, and the device wakes or plays `wakeup` +- **THEN** the backlight fades to 100 + +#### Scenario: Follow sleep off leaves backlight +- **WHEN** `lcd1602` is true, `lcd1602_backlight_sleep` is false, and the device sleeps then wakes +- **THEN** backlight brightness is unchanged by those transitions + +### Requirement: Boot content mode +The setting `lcd1602_boot` MUST be a string on `GET`/`POST /settings` allowing only `none`, `last`, and `config`, default **`none`** when unset, including after factory reset. Invalid values MUST be rejected without saving. The value MUST persist when `lcd1602` is false. On enable/boot with the extension on, the firmware MUST apply that mode. + +#### Scenario: none clears +- **WHEN** `lcd1602_boot` is `none` and the extension becomes active +- **THEN** both lines are cleared (empty) on the display when hardware is present + +#### Scenario: last restores +- **WHEN** `lcd1602_boot` is `last`, a last state is stored, and the extension becomes active with LCD present +- **THEN** the display shows the stored lines, aligns, and brightness + +#### Scenario: config shows settings lines +- **WHEN** `lcd1602_boot` is `config` and the extension becomes active with LCD present +- **THEN** the display shows `lcd1602_line1` and `lcd1602_line2` with default left align unless those strings are empty + +#### Scenario: invalid boot mode +- **WHEN** the client posts `{"lcd1602_boot": "welcome"}` +- **THEN** the device answers **400**, nothing is saved + +### Requirement: Boot config line strings +The settings `lcd1602_line1` and `lcd1602_line2` MUST be strings on `GET`/`POST /settings`, default empty when unset, including after factory reset. Each MUST accept at most **64** characters; longer values MUST be rejected without saving. They MUST persist when `lcd1602` is false and apply when `lcd1602_boot` is `config`. + +#### Scenario: Persist while off +- **WHEN** `lcd1602` is false and the client posts config lines +- **THEN** the values are saved and `GET /settings` returns them + +#### Scenario: Too long rejected +- **WHEN** the client posts a line longer than 64 characters +- **THEN** the device answers **400** and nothing is saved + +### Requirement: Extensions page owns LCD 1602 controls +The Extensions page MUST include an **LCD 1602** section for `lcd1602` and related boot settings. The Config page MUST NOT show these controls. Details and wiring MUST appear only while the draft toggle is on; the section MUST note `/extensions/lcd1602/` HTTP paths and that this extension emits no events. + +#### Scenario: Toggle from Extensions +- **WHEN** the user enables LCD 1602 and saves +- **THEN** the UI posts `lcd1602` true + +#### Scenario: Details hidden when off +- **WHEN** the draft LCD toggle is off +- **THEN** LCD boot/backlight/line controls and LCD wiring are not shown + +#### Scenario: Details shown when on +- **WHEN** the draft LCD toggle is on +- **THEN** the section shows a **Follow sleep** backlight toggle bound to `lcd1602_backlight_sleep`, a **Hello on welcome** toggle bound to `lcd1602_welcome_hello`, boot-content mode, Waveshare I2C Extension-port wiring, and (when mode is `config`) the two line fields + +#### Scenario: Config omits LCD +- **WHEN** the user opens the Config page +- **THEN** that page has no LCD 1602 controls + +### Requirement: Welcome hello setting +The setting `lcd1602_welcome_hello` MUST be a boolean on `GET`/`POST /settings`, default **false** when unset, including after factory reset. It MUST persist when `lcd1602` is false and apply immediately. When false, welcome animations MUST NOT change LCD text for this feature. + +#### Scenario: Default false +- **WHEN** the device has no stored `lcd1602_welcome_hello` +- **THEN** `GET /settings` reports `lcd1602_welcome_hello` false + +#### Scenario: Flag off leaves LCD text alone +- **WHEN** `lcd1602` is true, `lcd1602_welcome_hello` is false, and a `welcome` animation runs +- **THEN** the LCD text is not replaced with HELLO/HUMAN by this feature + +### Requirement: Welcome hello overlay +When `lcd1602` and `lcd1602_welcome_hello` are true, every `welcome` animation (boot after Wi‑Fi and `POST /anim` `welcome`) MUST show line1 **HELLO** and line2 **HUMAN**, both center-aligned, for the animation duration. HELLO/HUMAN MUST NOT be written to last-state NVS. When welcome ends with no queued text update, the firmware MUST restore the pre-overlay logical text on the display. + +#### Scenario: Boot welcome shows hello +- **WHEN** the extension is on, the flag is true, and boot starts `welcome` after Wi‑Fi connect +- **THEN** the LCD shows centered HELLO and HUMAN until that welcome finishes + +#### Scenario: API welcome shows hello +- **WHEN** the extension is on, the flag is true, and the client posts `welcome` via `/anim` +- **THEN** the LCD shows centered HELLO and HUMAN until that welcome finishes + +#### Scenario: Restore after welcome +- **WHEN** welcome ends and no text/clear was queued during the overlay +- **THEN** the display shows the logical text from before the overlay + +### Requirement: Queue text during welcome hello +While the welcome-hello overlay is active, successful `POST`/`DELETE` text (HTTP or serial `ext`) MUST NOT change the visible HELLO/HUMAN lines, MUST NOT persist last state for those queued edits until applied, MUST answer **200**, and MUST last-wins queue the resulting logical text. When welcome ends, the firmware MUST apply the queued logical text to the display and persist last state. Brightness and color MUST still apply immediately. + +#### Scenario: Post during overlay queues +- **WHEN** the overlay is active and the client posts new line text +- **THEN** the response is **200**, HELLO/HUMAN stay visible, and after welcome ends the display shows the posted text + +#### Scenario: Last wins +- **WHEN** two successful text updates arrive during one overlay +- **THEN** after welcome ends the display matches the later update + +#### Scenario: Delete during overlay queues clear +- **WHEN** the overlay is active and the client deletes text +- **THEN** HELLO/HUMAN stay visible until welcome ends, then both lines are empty + +### Requirement: GET text is logical during welcome hello +While the welcome-hello overlay is active, `GET /extensions/lcd1602/text` (and serial `ext` GET text) MUST return the logical text: the queued result if a text/clear was accepted during the overlay, otherwise the pre-overlay stash. It MUST NOT return HELLO/HUMAN as the logical lines. + +#### Scenario: Get during overlay without queue +- **WHEN** the overlay is active, no text was queued, and the client GETs text +- **THEN** the body matches the pre-overlay logical lines, not HELLO/HUMAN + +#### Scenario: Get during overlay with queue +- **WHEN** the overlay is active, a text update was queued, and the client GETs text +- **THEN** the body matches the queued logical lines, not HELLO/HUMAN + +### Requirement: Text API partial update +`POST /extensions/lcd1602/text` MUST accept JSON where omitted `line1`/`line2` leave that line unchanged, present line objects carry required `text` (0–64 chars) and optional `align` (default `left`), empty `text` clears the line, bad input is **400**, and success updates display when present, persists last state, and returns **200** with full text state. + +#### Scenario: Update one line +- **WHEN** only `line1` is posted with `{"text":"HI"}` +- **THEN** line1 becomes `HI` (align left) and line2 is unchanged + +#### Scenario: Clear one line +- **WHEN** the client posts `{"line1":{"text":""}}` +- **THEN** line1 is cleared and line2 is unchanged + +#### Scenario: Align center under 16 +- **WHEN** the client posts `{"line1":{"text":"OK","align":"center"}}` and the text length is ≤16 +- **THEN** the visible line is centered in 16 columns + +### Requirement: Long line marquees LTR +When a line’s `text` length is greater than 16, the firmware MUST ignore `align` for that line and scroll a 16-character window `[i .. i+16)` advancing `i` by one on each step (wrapping), at a fixed readable pace. Lines ≤16 MUST NOT marquee. + +#### Scenario: Long line scrolls +- **WHEN** line1 text has more than 16 characters and the extension is on with LCD present +- **THEN** the visible 16 columns advance through the string in a loop until the line is replaced or cleared + +#### Scenario: Short line static +- **WHEN** line1 text has 16 or fewer characters with align `right` +- **THEN** the line stays static and right-aligned + +### Requirement: GET text returns full logical state +`GET /extensions/lcd1602/text` MUST return JSON with `line1` and `line2` objects each containing `text` and `align` for the current logical content (full string, not only the 16-column viewport). + +#### Scenario: Get after partial post +- **WHEN** the client successfully set both lines then `GET`s `/extensions/lcd1602/text` +- **THEN** the body includes both lines’ full `text` and `align` values + +### Requirement: DELETE text clears both lines +`DELETE /extensions/lcd1602/text` MUST clear both lines, stop marquees, leave brightness unchanged, persist last state, and answer **200** with the cleared text state when the extension is on. + +#### Scenario: Clear both +- **WHEN** the client `DELETE`s `/extensions/lcd1602/text` while the extension is on +- **THEN** both lines are empty and brightness is unchanged + +### Requirement: Brightness API +`GET /extensions/lcd1602/brightness` MUST return JSON `{"brightness": <0-100>}`. `POST /extensions/lcd1602/brightness` MUST accept `{"brightness": <0-100>}`, apply backlight (0 = off), persist last state, and answer **200** with the new value. On PCA9633, brightness MUST scale the stored base RGB color (`PWM = channel × brightness / 100`). Out-of-range or bad types MUST answer **400** without changing brightness. + +#### Scenario: Set brightness +- **WHEN** the client posts `{"brightness": 50}` while the extension is on and LCD backlight is reachable +- **THEN** backlight is set near 50% and `GET` reports `50` + +#### Scenario: Invalid brightness +- **WHEN** the client posts `{"brightness": 101}` +- **THEN** the response is **400** and brightness is unchanged + +### Requirement: RGB color API +`GET` / `POST /extensions/lcd1602/color` MUST be available when the detected backlight is PCA9633. `GET` MUST return `{"r","g","b"}` each 0–255. `POST` MUST accept those three fields, store them as the base color, apply PWM scaled by current brightness, persist last state, and answer **200**. When the backlight is SN3193, color MUST answer **400** `rgb not supported`. When no backlight chip ACKs, color MUST answer **503** `backlight not found`. + +#### Scenario: Set color on RGB module +- **WHEN** the PCA9633 ACKs and the client posts `{"r":0,"g":128,"b":255}` while the extension is on +- **THEN** the response is **200** with that color and the backlight uses those channels scaled by brightness + +#### Scenario: Color rejected on SN3193 +- **WHEN** the SN3193 ACKs and the client posts color +- **THEN** the response is **400** with `rgb not supported` + +#### Scenario: Color without backlight +- **WHEN** neither backlight chip ACKs and the client posts color +- **THEN** the response is **503** with a backlight not-found style message + +### Requirement: Missing LCD while enabled +When `lcd1602` is true but the LCD does not ACK at `0x3E`, write/clear/brightness requests that need hardware MUST answer **503** with a not-found style message. `GET` text/brightness MAY return the last known logical state from RAM/NVS. The enabled setting MUST remain true. + +#### Scenario: Write without hardware +- **WHEN** `lcd1602` is true, no device ACKs at `0x3E`, and the client posts text +- **THEN** the response is **503** and `GET /settings` still reports `lcd1602` true + +### Requirement: Last state persistence +After every successful text update, clear, brightness, or color change, the firmware MUST store last state: both lines’ text and align, brightness, and base RGB color. Factory reset MUST clear last state to empty lines, align left, default brightness, and white color (255,255,255). + +#### Scenario: Boot last after power cycle +- **WHEN** last state was saved, `lcd1602_boot` is `last`, and the device reboots with the extension on and LCD present +- **THEN** the display restores that last text, align, brightness, and color + +### Requirement: No outbound events +The LCD 1602 extension MUST NOT publish outbound events on WebSocket or serial. + +#### Scenario: Text update silent on event bus +- **WHEN** a successful `POST /extensions/lcd1602/text` completes +- **THEN** no new outbound event is emitted for that update + +### Requirement: LCD APIs available over serial ext +The LCD 1602 text, brightness, and color behaviors defined for HTTP `/extensions/lcd1602/…` MUST also apply when the same operations are invoked through serial `ext` with `id` `lcd1602` and the matching `suffix`/`method`. Disabled-extension, validation, missing-LCD, missing-backlight, and rgb-not-supported outcomes MUST match the HTTP API (including distinct not-found style messages for LCD vs backlight where HTTP already distinguishes them). + +#### Scenario: Serial clear matches HTTP delete +- **WHEN** the host clears both lines via serial `ext` DELETE `text` while the extension is on +- **THEN** both lines are empty, brightness is unchanged, and last state is persisted as for `DELETE /extensions/lcd1602/text` + +#### Scenario: Serial backlight missing +- **WHEN** the extension is on, the LCD ACKs, the backlight chip does not, and the host sets brightness via serial `ext` +- **THEN** the response is **503** with a backlight not-found style message diff --git a/openspec/specs/serial-protocol/spec.md b/openspec/specs/serial-protocol/spec.md index e9078a48..db485717 100644 --- a/openspec/specs/serial-protocol/spec.md +++ b/openspec/specs/serial-protocol/spec.md @@ -109,12 +109,38 @@ While the device is unprovisioned or in setup AP provisioning, the serial API MU - **WHEN** the setup AP is active and the host sends serial op `servos_park` - **THEN** the device performs park and does not reject solely for provisioning state +### Requirement: Serial settings include LCD 1602 fields +`settings.get` over serial MUST include the `lcd1602`, `lcd1602_backlight_sleep`, `lcd1602_welcome_hello`, `lcd1602_boot`, `lcd1602_line1`, and `lcd1602_line2` fields with the same types and defaults as `GET /settings`. `settings.set` MUST accept those keys with the same validation and immediate-apply behavior as `POST /settings`. Other settings fields not already returned or accepted by serial MAY remain deferred (full GET `/settings` parity is not claimed by this change alone). + +#### Scenario: Enable LCD over serial +- **WHEN** the host sends `settings.set` with `{"lcd1602": true}` after provisioning +- **THEN** the extension becomes active without reboot and a later `settings.get` reports `lcd1602` true + +#### Scenario: Invalid boot mode rejected +- **WHEN** the host sends `settings.set` with `{"lcd1602_boot": "welcome"}` +- **THEN** the device answers **400** and does not save the value + +#### Scenario: Follow sleep field over serial +- **WHEN** the host sends `settings.set` with `{"lcd1602_backlight_sleep": false}` after provisioning +- **THEN** a later `settings.get` reports `lcd1602_backlight_sleep` false and does not include `lcd1602_backlight_boot` + +#### Scenario: Welcome hello field over serial +- **WHEN** the host sends `settings.set` with `{"lcd1602_welcome_hello": true}` after provisioning +- **THEN** a later `settings.get` reports `lcd1602_welcome_hello` true + +### Requirement: Ext op is part of the serial control surface +The serial protocol MUST document and implement `op` **`ext`** for extension APIs as specified by the `extension-serial` capability. Day-to-day control over serial MUST include `ext` for registered extensions (LCD 1602 in this change). + +#### Scenario: Ext listed among control ops +- **WHEN** a provisioned host sends a valid `ext` request for a registered LCD route +- **THEN** the device does not reject solely because `ext` is an unknown op + ### Requirement: Feature parity with HTTP control surface -The serial API MUST expose the same day-to-day control operations as the HTTP JSON API, including animations, settings read/write, hardware tests, servo test, health, factory reset, streamed WAV play with optional animation name, and servo park. +The serial API MUST expose the same day-to-day control operations as the HTTP JSON API, including animations, settings read/write, hardware tests, servo test, health, factory reset, streamed WAV play with optional animation name, servo park, and **extension APIs via `ext` for registered extensions**. Settings read/write MUST include at least the fields already supported plus the **`lcd1602*` slice** in this change; remaining HTTP settings fields remain a known gap until a later change closes full GET `/settings` parity. #### Scenario: Settings over serial - **WHEN** the host requests current settings over serial -- **THEN** the device returns the same settings fields exposed by `GET /settings` (excluding secrets) +- **THEN** the device returns at least the previously supported serial settings fields plus the `lcd1602*` fields (excluding secrets) #### Scenario: Play with pose over serial - **WHEN** the host streams a WAV with an allowed play animation name over serial @@ -124,6 +150,10 @@ The serial API MUST expose the same day-to-day control operations as the HTTP JS - **WHEN** the host sends serial op `servos_park` - **THEN** the device applies the same park semantics as `POST /servos/park` +#### Scenario: Extension text over serial +- **WHEN** the host sends a valid `ext` POST for LCD text while the extension is on and hardware is present +- **THEN** the device updates the display with the same semantics as `POST /extensions/lcd1602/text` + ### Requirement: Future device-initiated events The protocol MUST reserve and define an event message type so the device can later send unsolicited notifications to the host without changing the framing layer. diff --git a/packages/tiny-engineer-cli/README.md b/packages/tiny-engineer-cli/README.md index f2ce0a56..9c064ec6 100644 --- a/packages/tiny-engineer-cli/README.md +++ b/packages/tiny-engineer-cli/README.md @@ -25,7 +25,7 @@ Cold `npx` can be slow: `setup` writes hook **`timeout` ≥ 30**. Prefer registr | Area | Commands | | --- | --- | | Hooks / setup | `setup`, `uninstall`, `doctor`, `hook ` | -| Robot | `anim`, `play`, `settings`, `test`, `servo`, `park`, `health`, `reset` | +| Robot | `anim`, `play`, `settings`, `ext`, `test`, `servo`, `park`, `health`, `reset` | | Serial / events | `monitor`, `watch`, `port`, `daemon …`, `rules …` | Full flag list: `tiny-engineer --help` and `tiny-engineer daemon --help`. diff --git a/packages/tiny-engineer-cli/src/cli.js b/packages/tiny-engineer-cli/src/cli.js index 101d5c84..95d2bd16 100644 --- a/packages/tiny-engineer-cli/src/cli.js +++ b/packages/tiny-engineer-cli/src/cli.js @@ -3,6 +3,7 @@ import { basename, dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { DEFAULT_URL, loadDotEnv } from "./config/env.js"; +import { runExt } from "./commands/ext.js"; import { runHealth, runPark, @@ -50,6 +51,7 @@ Commands: anim Set animation pose play [opts] Stream WAV play (HTTP or serial credits) settings [get|set] Read or write settings + ext … Extension APIs (lcd1602 text/brightness) test Run hardware test (audio|bell|screen|movement|led) servo Move one servo (degrees) park Center servos and hold PWM (flash-safe) @@ -103,6 +105,8 @@ Examples: tiny-engineer doctor tiny-engineer anim ring tiny-engineer settings get --transport serial + tiny-engineer settings set --lcd1602=true + tiny-engineer ext lcd1602 text set --line1=HELLO --align=center tiny-engineer reset --yes echo '{"hook_event_name":"stop"}' | tiny-engineer hook cursor `); @@ -156,6 +160,14 @@ async function runHook(out, argv, quietGlobal) { await robotSetAnim(anim, { url: opts.url, transport: opts.transport, port: opts.port }); } + await integration.afterAnim?.({ + anim, + input, + url: opts.url, + transport: opts.transport, + port: opts.port, + }); + const fileLines = integration.describeFiles?.(input, localOut.style) ?? []; for (const line of fileLines) { localOut.info(line); @@ -313,6 +325,9 @@ export async function run(argv) { case "settings": await runSettings(out, rest, global.quiet); return; + case "ext": + await runExt(out, rest, global.quiet); + return; case "test": await runTest(out, rest, global.quiet); return; diff --git a/packages/tiny-engineer-cli/src/commands/ext.js b/packages/tiny-engineer-cli/src/commands/ext.js new file mode 100644 index 00000000..d8c80ebb --- /dev/null +++ b/packages/tiny-engineer-cli/src/commands/ext.js @@ -0,0 +1,292 @@ +import { robotExt } from "../robot/ops.js"; +import { formatRobotError } from "../robot/transport.js"; +import { parseCommonArgs } from "../util/args.js"; +import { createOutput } from "../util/output.js"; + +/** @type {ReadonlySet} */ +export const KNOWN_EXTENSION_IDS = new Set(["lcd1602"]); + +/** + * @param {string[]} argv + */ +function parseExtArgs(argv) { + const common = parseCommonArgs(argv, { passthroughUnknown: true }); + return { ...common, restPos: common.rest }; +} + +/** + * @param {string[]} tokens + * @returns {{ flags: Record, error?: string }} + */ +function parseFlags(tokens) { + /** @type {Record} */ + const flags = {}; + for (const token of tokens) { + if (!token.startsWith("--")) { + continue; + } + if (!token.includes("=")) { + return { flags: {}, error: `malformed option ${token} (expected --key=value)` }; + } + const eq = token.indexOf("="); + flags[token.slice(2, eq)] = token.slice(eq + 1); + } + return { flags }; +} + +/** + * @param {import("../util/output.js").Output} out + * @param {string[]} argv + * @param {boolean} quietGlobal + */ +export async function runExt(out, argv, quietGlobal) { + const opts = parseExtArgs(argv); + const quiet = quietGlobal || opts.quiet; + const localOut = quiet === out.quiet ? out : createOutput({ quiet, style: out.style }); + + if (opts.error) { + localOut.error(opts.error); + process.exitCode = 1; + return; + } + + if (opts.help) { + console.log(`Usage: tiny-engineer ext [options] + +Extensions (v1): + lcd1602 text get + lcd1602 text set --line1=TEXT [--align=left|right|center] [--line2=TEXT] [--align2=...] + lcd1602 text clear + lcd1602 brightness get + lcd1602 brightness set <0-100> + lcd1602 color get + lcd1602 color set --r=0-255 --g=0-255 --b=0-255 + +Enable the module with: tiny-engineer settings set --lcd1602=true + +Options: + --transport --url --port +`); + return; + } + + const [id, resource, action, ...rest] = opts.restPos ?? []; + if (!id) { + localOut.error("usage: tiny-engineer ext "); + process.exitCode = 1; + return; + } + + if (!KNOWN_EXTENSION_IDS.has(id)) { + localOut.error(`unknown extension: ${id}`); + process.exitCode = 1; + return; + } + + const transportOpts = { url: opts.url, transport: opts.transport, port: opts.port }; + + if (id === "lcd1602") { + await runLcd1602(localOut, resource, action, rest, transportOpts); + return; + } + + localOut.error(`unknown extension: ${id}`); + process.exitCode = 1; +} + +/** + * @param {import("../util/output.js").Output} out + * @param {string | undefined} resource + * @param {string | undefined} action + * @param {string[]} rest + * @param {{ url?: string, transport?: string, port?: string | null }} transportOpts + */ +async function runLcd1602(out, resource, action, rest, transportOpts) { + if (resource === "text") { + if (action === "get") { + const result = await robotExt( + { id: "lcd1602", suffix: "text", method: "GET" }, + transportOpts, + ); + if (!result.ok) { + out.error(formatRobotError(result)); + process.exitCode = 1; + return; + } + console.log(JSON.stringify(result.bodyJson ?? {}, null, 2)); + process.exitCode = 0; + return; + } + + if (action === "clear") { + const result = await robotExt( + { id: "lcd1602", suffix: "text", method: "DELETE" }, + transportOpts, + ); + if (!result.ok) { + out.error(formatRobotError(result)); + process.exitCode = 1; + return; + } + out.ok("lcd text cleared"); + process.exitCode = 0; + return; + } + + if (action === "set") { + const parsed = parseFlags(rest); + if (parsed.error) { + out.error(parsed.error); + process.exitCode = 1; + return; + } + const flags = parsed.flags; + /** @type {Record} */ + const body = {}; + if (flags.line1 !== undefined) { + body.line1 = { text: flags.line1, ...(flags.align ? { align: flags.align } : {}) }; + } + if (flags.line2 !== undefined) { + body.line2 = { + text: flags.line2, + ...(flags.align2 ? { align: flags.align2 } : {}), + }; + } + if (!body.line1 && !body.line2) { + out.error("text set needs --line1=... and/or --line2=..."); + process.exitCode = 1; + return; + } + const result = await robotExt( + { id: "lcd1602", suffix: "text", method: "POST", body }, + transportOpts, + ); + if (!result.ok) { + out.error(formatRobotError(result)); + process.exitCode = 1; + return; + } + console.log(JSON.stringify(result.bodyJson ?? {}, null, 2)); + process.exitCode = 0; + return; + } + + out.error("lcd1602 text actions: get | set | clear"); + process.exitCode = 1; + return; + } + + if (resource === "brightness") { + if (action === "get") { + const result = await robotExt( + { id: "lcd1602", suffix: "brightness", method: "GET" }, + transportOpts, + ); + if (!result.ok) { + out.error(formatRobotError(result)); + process.exitCode = 1; + return; + } + console.log(JSON.stringify(result.bodyJson ?? {}, null, 2)); + process.exitCode = 0; + return; + } + + if (action === "set") { + const valueToken = rest.find((t) => !t.startsWith("--")); + const trimmed = valueToken !== undefined ? valueToken.trim() : ""; + const n = trimmed !== "" ? Number(trimmed) : NaN; + if (!Number.isInteger(n) || n < 0 || n > 100) { + out.error("brightness set needs an integer 0–100"); + process.exitCode = 1; + return; + } + const result = await robotExt( + { id: "lcd1602", suffix: "brightness", method: "POST", body: { brightness: n } }, + transportOpts, + ); + if (!result.ok) { + out.error(formatRobotError(result)); + process.exitCode = 1; + return; + } + console.log(JSON.stringify(result.bodyJson ?? {}, null, 2)); + process.exitCode = 0; + return; + } + + out.error("lcd1602 brightness actions: get | set"); + process.exitCode = 1; + return; + } + + if (resource === "color") { + if (action === "get") { + const result = await robotExt( + { id: "lcd1602", suffix: "color", method: "GET" }, + transportOpts, + ); + if (!result.ok) { + out.error(formatRobotError(result)); + process.exitCode = 1; + return; + } + console.log(JSON.stringify(result.bodyJson ?? {}, null, 2)); + process.exitCode = 0; + return; + } + + if (action === "set") { + const parsed = parseFlags(rest); + if (parsed.error) { + out.error(parsed.error); + process.exitCode = 1; + return; + } + const flags = parsed.flags; + /** @param {string | undefined} raw */ + const channel = (raw) => { + if (raw === undefined) return NaN; + const trimmed = raw.trim(); + return trimmed !== "" ? Number(trimmed) : NaN; + }; + const r = channel(flags.r); + const g = channel(flags.g); + const b = channel(flags.b); + if ( + !Number.isInteger(r) || + !Number.isInteger(g) || + !Number.isInteger(b) || + r < 0 || + r > 255 || + g < 0 || + g > 255 || + b < 0 || + b > 255 + ) { + out.error("color set needs --r=0-255 --g=0-255 --b=0-255"); + process.exitCode = 1; + return; + } + const result = await robotExt( + { id: "lcd1602", suffix: "color", method: "POST", body: { r, g, b } }, + transportOpts, + ); + if (!result.ok) { + out.error(formatRobotError(result)); + process.exitCode = 1; + return; + } + console.log(JSON.stringify(result.bodyJson ?? {}, null, 2)); + process.exitCode = 0; + return; + } + + out.error("lcd1602 color actions: get | set"); + process.exitCode = 1; + return; + } + + out.error("lcd1602 resources: text | brightness | color"); + process.exitCode = 1; +} diff --git a/packages/tiny-engineer-cli/src/commands/parity.js b/packages/tiny-engineer-cli/src/commands/parity.js index 9840d1a7..fce27cc3 100644 --- a/packages/tiny-engineer-cli/src/commands/parity.js +++ b/packages/tiny-engineer-cli/src/commands/parity.js @@ -13,9 +13,10 @@ import { confirm } from "../wizard/prompt.js"; /** * @param {string[]} argv + * @param {{ passthroughUnknown?: boolean }} [options] * @returns {ReturnType & { yes?: boolean, sub?: string, restPos?: string[] }} */ -function parseParityArgs(argv) { +function parseParityArgs(argv, options = {}) { let yes = false; /** @type {string[]} */ const filtered = []; @@ -26,7 +27,9 @@ function parseParityArgs(argv) { } filtered.push(arg); } - const common = parseCommonArgs(filtered); + const common = parseCommonArgs(filtered, { + passthroughUnknown: options.passthroughUnknown === true, + }); return { ...common, yes, restPos: common.rest }; } @@ -36,7 +39,7 @@ function parseParityArgs(argv) { * @param {boolean} quietGlobal */ export async function runSettings(out, argv, quietGlobal) { - const opts = parseParityArgs(argv); + const opts = parseParityArgs(argv, { passthroughUnknown: true }); const quiet = quietGlobal || opts.quiet; const localOut = quiet === out.quiet ? out : out; @@ -49,7 +52,8 @@ export async function runSettings(out, argv, quietGlobal) { console.log(`Usage: tiny-engineer settings [get|set] [options] settings get - settings set --key=value ... (volume, welcome, serial_log, link_mode, eyes_style, hostname) + settings set --key=value ... (volume, welcome, serial_log, link_mode, eyes_style, hostname, + lcd1602, lcd1602_backlight_sleep, lcd1602_welcome_hello, lcd1602_boot, lcd1602_line1, lcd1602_line2) Options: --transport --url --port diff --git a/packages/tiny-engineer-cli/src/daemon/robot.js b/packages/tiny-engineer-cli/src/daemon/robot.js index b975bfcd..2b4992f0 100644 --- a/packages/tiny-engineer-cli/src/daemon/robot.js +++ b/packages/tiny-engineer-cli/src/daemon/robot.js @@ -5,11 +5,14 @@ import { daemonPlay, daemonProbe, daemonRobotRequest } from "./client.js"; * SerialRobotClient runs only inside that process. * @param {string} op * @param {Record} [fields] - * @param {{ port?: string | null }} [opts] + * @param {{ port?: string | null, timeoutMs?: number }} [opts] * @returns {Promise>} */ export function serialRequest(op, fields = {}, opts = {}) { - return daemonRobotRequest(op, fields, { port: opts.port ?? null }); + /** @type {{ port: string | null, timeoutMs?: number }} */ + const rpcOpts = { port: opts.port ?? null }; + if (opts.timeoutMs != null) rpcOpts.timeoutMs = opts.timeoutMs; + return daemonRobotRequest(op, fields, rpcOpts); } /** diff --git a/packages/tiny-engineer-cli/src/daemon/rpc.js b/packages/tiny-engineer-cli/src/daemon/rpc.js index 8fa421b4..f7b904e7 100644 --- a/packages/tiny-engineer-cli/src/daemon/rpc.js +++ b/packages/tiny-engineer-cli/src/daemon/rpc.js @@ -5,7 +5,7 @@ import { delay } from "./proc.js"; /** * @param {string} op * @param {Record} fields - * @param {{ port?: string | null, configDir?: string }} [opts] + * @param {{ port?: string | null, configDir?: string, timeoutMs?: number }} [opts] */ export async function daemonRobotRequest(op, fields = {}, opts = {}) { const conn = await ensureDaemon({ configDir: opts.configDir, port: opts.port ?? null }); @@ -13,7 +13,7 @@ export async function daemonRobotRequest(op, fields = {}, opts = {}) { const res = await conn.peer.request( "robot.request", { op, fields, port: opts.port ?? null }, - 15_000, + opts.timeoutMs ?? 15_000, ); if (typeof res.error === "string") throw new Error(res.error); return /** @type {Record} */ (res.result && /** @type {{ body?: Record }} */ (res.result).body) ?? {}; diff --git a/packages/tiny-engineer-cli/src/integrations/cursor/index.js b/packages/tiny-engineer-cli/src/integrations/cursor/index.js index 09005549..99f32829 100644 --- a/packages/tiny-engineer-cli/src/integrations/cursor/index.js +++ b/packages/tiny-engineer-cli/src/integrations/cursor/index.js @@ -7,6 +7,7 @@ import { planInstall, planUninstall, } from "./install.js"; +import { maybeShowCursorUsageOnLcd } from "./lcd-usage.js"; import { animationForEvent } from "./map.js"; /** @@ -76,6 +77,19 @@ export const cursor = { return formatFileModifications(/** @type {Record} */ (raw), style); }, + /** + * After a completed turn (`ring`), optionally refresh LCD1602 with remaining AI budget. + * @param {import("../types.js").AfterAnimContext} ctx + */ + async afterAnim(ctx) { + if (ctx.anim !== "ring") return; + await maybeShowCursorUsageOnLcd({ + url: ctx.url, + transport: ctx.transport, + port: ctx.port, + }); + }, + // Cursor has no stdout contract; stay silent. respond() {}, diff --git a/packages/tiny-engineer-cli/src/integrations/cursor/lcd-usage.js b/packages/tiny-engineer-cli/src/integrations/cursor/lcd-usage.js new file mode 100644 index 00000000..2283d9c0 --- /dev/null +++ b/packages/tiny-engineer-cli/src/integrations/cursor/lcd-usage.js @@ -0,0 +1,101 @@ +import { robotExt } from "../../robot/ops.js"; +import { fetchCursorLimits } from "./usage-api.js"; +import { remainingBudgetPercent } from "./usage-remaining.js"; +import { resolveCursorSessionCookie } from "./usage-session.js"; + +/** Opt-in: only `"1"` enables LCD AI budget updates after Cursor `ring`. */ +export const AI_USAGE_LCD_KEY = "TINY_ENGINEER_AI_USAGE_LCD"; + +export const OVERALL_TIMEOUT_MS = 2000; +export const STEP_TIMEOUT_MS = 1500; + +/** + * @typedef {{ + * url?: string, + * transport?: string, + * port?: string | null, + * }} TransportOpts + */ + +/** + * @typedef {{ + * resolveCookie?: (opts?: { signal?: AbortSignal }) => Promise, + * fetchLimits?: (cookie: string, opts?: { timeoutMs?: number }) => Promise | null>, + * postLcd?: (pct: number, transport: TransportOpts) => Promise, + * overallTimeoutMs?: number, + * stepTimeoutMs?: number, + * env?: NodeJS.ProcessEnv, + * }} LcdUsageDeps + */ + +/** + * @param {number} pct + * @param {TransportOpts} transport + * @param {number} timeoutMs + */ +async function defaultPostLcd(pct, transport, timeoutMs) { + await robotExt( + { + id: "lcd1602", + suffix: "text", + method: "POST", + body: { + line1: { text: "AI BUDGET:" }, + line2: { text: `${pct.toFixed(2)}%`, align: "right" }, + }, + }, + { ...transport, timeoutMs }, + ); +} + +/** + * After a completed Cursor turn (`ring`), optionally show remaining AI budget on LCD1602. + * Fail-open: never throws; capped wall time; silent on any error. + * + * @param {TransportOpts} [transport] + * @param {LcdUsageDeps} [deps] + * @returns {Promise} + */ +export async function maybeShowCursorUsageOnLcd(transport = {}, deps = {}) { + const env = deps.env ?? process.env; + if (env[AI_USAGE_LCD_KEY] !== "1") return; + + const overallTimeoutMs = deps.overallTimeoutMs ?? OVERALL_TIMEOUT_MS; + const stepTimeoutMs = deps.stepTimeoutMs ?? STEP_TIMEOUT_MS; + const resolveCookie = deps.resolveCookie ?? resolveCursorSessionCookie; + const fetchLimits = deps.fetchLimits ?? fetchCursorLimits; + const postLcd = + deps.postLcd ?? + ((pct, opts) => defaultPostLcd(pct, opts, stepTimeoutMs)); + + const ac = new AbortController(); + let cancelled = false; + const run = (async () => { + const cookie = await resolveCookie({ signal: ac.signal }); + if (cancelled || ac.signal.aborted || !cookie) return; + + const limits = await fetchLimits(cookie, { timeoutMs: stepTimeoutMs }); + if (cancelled || ac.signal.aborted || !limits) return; + + const pct = remainingBudgetPercent(limits); + if (cancelled || ac.signal.aborted || pct == null) return; + + await postLcd(pct, transport); + })(); + + /** @type {ReturnType | undefined} */ + let overallTimer; + const overallDeadline = new Promise((resolve) => { + overallTimer = setTimeout(resolve, overallTimeoutMs); + }); + + try { + await Promise.race([run.catch(() => {}), overallDeadline]); + } catch { + // fail-open + } finally { + cancelled = true; + ac.abort(); + if (overallTimer !== undefined) clearTimeout(overallTimer); + } +} diff --git a/packages/tiny-engineer-cli/src/integrations/cursor/usage-api.js b/packages/tiny-engineer-cli/src/integrations/cursor/usage-api.js new file mode 100644 index 00000000..b5ec5a93 --- /dev/null +++ b/packages/tiny-engineer-cli/src/integrations/cursor/usage-api.js @@ -0,0 +1,72 @@ +import { remainingBudgetPercent } from "./usage-remaining.js"; + +const BASE = "https://cursor.com"; +const DEFAULT_TIMEOUT_MS = 1500; + +/** + * @param {string} cookieValue `id::jwt` + * @returns {string} + */ +function cookieHeader(cookieValue) { + return `WorkosCursorSessionToken=${cookieValue.replace(/::/g, "%3A%3A")}`; +} + +/** + * @param {string} cookieValue + * @param {string} path + * @param {{ method?: string, body?: unknown, timeoutMs?: number, fetchImpl?: typeof fetch }} [opts] + * @returns {Promise | null>} + */ +async function cursorRequest(cookieValue, path, opts = {}) { + const fetchImpl = opts.fetchImpl ?? globalThis.fetch; + const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS; + /** @type {Record} */ + const headers = { + Cookie: cookieHeader(cookieValue), + Accept: "application/json", + "User-Agent": "tiny-engineer-cli", + }; + /** @type {RequestInit} */ + const init = { + method: opts.method ?? "GET", + headers, + signal: AbortSignal.timeout(timeoutMs), + }; + if (opts.body !== undefined) { + headers["Content-Type"] = "application/json"; + headers.Origin = BASE; + init.body = JSON.stringify(opts.body); + } + try { + const res = await fetchImpl(`${BASE}${path}`, init); + if (!res.ok) return null; + const json = await res.json(); + if (!json || typeof json !== "object") return null; + return /** @type {Record} */ (json); + } catch { + return null; + } +} + +/** + * Fetch current-cycle limits JSON from cursor.com (fail-open → null). + * + * @param {string} cookieValue + * @param {{ timeoutMs?: number, fetchImpl?: typeof fetch }} [opts] + * @returns {Promise | null>} + */ +export async function fetchCursorLimits(cookieValue, opts = {}) { + const primary = await cursorRequest(cookieValue, "/api/dashboard/get-current-period-usage", { + method: "POST", + body: {}, + timeoutMs: opts.timeoutMs, + fetchImpl: opts.fetchImpl, + }); + if (primary && remainingBudgetPercent(primary) != null) return primary; + + return cursorRequest(cookieValue, "/api/usage-summary", { + method: "GET", + timeoutMs: opts.timeoutMs, + fetchImpl: opts.fetchImpl, + }); +} diff --git a/packages/tiny-engineer-cli/src/integrations/cursor/usage-remaining.js b/packages/tiny-engineer-cli/src/integrations/cursor/usage-remaining.js new file mode 100644 index 00000000..8bac5e37 --- /dev/null +++ b/packages/tiny-engineer-cli/src/integrations/cursor/usage-remaining.js @@ -0,0 +1,31 @@ +/** + * Remaining plan budget percent from Cursor cycle-limits JSON. + * Mirrors cursor-usage-tiny-engineer: 100 - max(autoPercentUsed, apiPercentUsed), + * clamped to ≥0, rounded to two decimal places. + * + * @param {unknown} payload + * @returns {number | null} + */ +export function remainingBudgetPercent(payload) { + if (!payload || typeof payload !== "object") return null; + + const root = /** @type {Record} */ (payload); + const individual = + root.individualUsage && typeof root.individualUsage === "object" + ? /** @type {Record} */ (root.individualUsage) + : null; + const planRaw = + (root.planUsage && typeof root.planUsage === "object" ? root.planUsage : null) ?? + (individual?.plan && typeof individual.plan === "object" ? individual.plan : null) ?? + {}; + const plan = /** @type {Record} */ (planRaw); + + const used = [plan.autoPercentUsed, plan.apiPercentUsed] + .filter((v) => v != null && v !== "") + .map((v) => Number(v)) + .filter((n) => Number.isFinite(n)); + + if (!used.length) return null; + + return Math.round(Math.max(100 - Math.max(...used), 0) * 100) / 100; +} diff --git a/packages/tiny-engineer-cli/src/integrations/cursor/usage-session.js b/packages/tiny-engineer-cli/src/integrations/cursor/usage-session.js new file mode 100644 index 00000000..8339aeb1 --- /dev/null +++ b/packages/tiny-engineer-cli/src/integrations/cursor/usage-session.js @@ -0,0 +1,241 @@ +import { spawn } from "node:child_process"; +import { homedir } from "node:os"; +import { join } from "node:path"; + +const KEYCHAIN_SERVICE = "cursor-access-token"; +const STATE_DB_KEY = "cursorAuth/accessToken"; +const SOURCE_TIMEOUT_MS = 2000; + +/** + * @param {string} token + * @returns {Record} + */ +export function jwtClaims(token) { + try { + const parts = token.split("."); + if (parts.length < 2) return {}; + let payload = parts[1].replace(/-/g, "+").replace(/_/g, "/"); + payload += "=".repeat((4 - (payload.length % 4)) % 4); + const claims = JSON.parse(Buffer.from(payload, "base64").toString("utf8")); + // JSON.parse("null") / primitives must not throw later at claims.type — + // that would abort resolveCursorSessionCookie before Keychain/DB fallback. + if (claims === null || typeof claims !== "object" || Array.isArray(claims)) { + return {}; + } + return /** @type {Record} */ (claims); + } catch { + return {}; + } +} + +/** + * @param {Record} claims + * @returns {string | null} + */ +export function cookieIdFromClaims(claims) { + const sub = claims.sub; + if (typeof sub !== "string" || !sub) return null; + const parts = sub.split("|"); + return parts[parts.length - 1] || null; +} + +/** + * @param {string} token + * @returns {string | null} full `id::jwt` cookie value, or null if unusable + */ +export function cookieFromToken(token) { + const raw = token.trim().replace(/%3A%3A/gi, "::"); + if (!raw) return null; + if (raw.includes("::")) return raw; + + const claims = jwtClaims(raw); + if (claims.type === "api_key_token") return null; + const id = cookieIdFromClaims(claims); + if (!id) return null; + return `${id}::${raw}`; +} + +/** + * @param {AbortSignal | undefined} signal + * @returns {boolean} + */ +function isAborted(signal) { + return signal != null && signal.aborted; +} + +/** + * @param {string} command + * @param {string[]} args + * @param {number} timeoutMs + * @param {AbortSignal} [signal] + * @returns {Promise} + */ +function spawnStdout(command, args, timeoutMs, signal) { + return new Promise((resolve) => { + if (isAborted(signal)) { + resolve(null); + return; + } + + /** @type {import("node:child_process").ChildProcessWithoutNullStreams} */ + let child; + try { + child = spawn(command, args, { stdio: ["ignore", "pipe", "ignore"] }); + } catch { + resolve(null); + return; + } + + let settled = false; + let out = ""; + + /** @param {string | null} value */ + const finish = (value) => { + if (settled) return; + settled = true; + clearTimeout(timer); + signal?.removeEventListener("abort", onAbort); + resolve(value); + }; + + const onAbort = () => { + child.kill("SIGKILL"); + finish(null); + }; + + const timer = setTimeout(() => { + child.kill("SIGKILL"); + finish(null); + }, timeoutMs); + + signal?.addEventListener("abort", onAbort, { once: true }); + + child.stdout.setEncoding("utf8"); + child.stdout.on("data", (chunk) => { + out += chunk; + }); + child.on("error", () => { + finish(null); + }); + child.on("close", (code) => { + if (code !== 0) { + finish(null); + return; + } + finish(out.trim() || null); + }); + }); +} + +/** + * @param {AbortSignal} [signal] + * @returns {Promise} + */ +async function fromMacosKeychain(signal) { + if (process.platform !== "darwin") return null; + return spawnStdout( + "security", + ["find-generic-password", "-s", KEYCHAIN_SERVICE, "-w"], + SOURCE_TIMEOUT_MS, + signal, + ); +} + +/** + * @returns {string[]} + */ +export function stateDbCandidates() { + const home = homedir(); + /** @type {string} */ + let base; + if (process.platform === "darwin") { + base = join(home, "Library", "Application Support"); + } else if (process.platform === "win32") { + base = process.env.APPDATA || join(home, "AppData", "Roaming"); + } else { + base = process.env.XDG_CONFIG_HOME || join(home, ".config"); + } + return ["Cursor", "Cursor Nightly"].map((app) => + join(base, app, "User", "globalStorage", "state.vscdb"), + ); +} + +/** + * @param {string} dbPath + * @param {AbortSignal} [signal] + * @returns {Promise} + */ +async function tokenFromStateDb(dbPath, signal) { + // Escape single quotes for sqlite string literal. + const key = STATE_DB_KEY.replace(/'/g, "''"); + const sql = `SELECT value FROM ItemTable WHERE key = '${key}' LIMIT 1;`; + const out = await spawnStdout( + "sqlite3", + ["-readonly", dbPath, sql], + SOURCE_TIMEOUT_MS, + signal, + ); + if (!out) return null; + return out.replace(/^"|"$/g, "").trim() || null; +} + +/** + * First usable raw token from a candidate list (skips api_key / malformed). + * @param {string[]} tokens + * @returns {string | null} + */ +export function selectUsableStateDbToken(tokens) { + for (const token of tokens) { + if (token && cookieFromToken(token)) return token; + } + return null; +} + +/** + * @param {AbortSignal} [signal] + * @returns {Promise} + */ +async function fromStateDb(signal) { + for (const path of stateDbCandidates()) { + if (isAborted(signal)) return null; + const token = await tokenFromStateDb(path, signal); + const usable = selectUsableStateDbToken(token ? [token] : []); + if (usable) return usable; + } + return null; +} + +/** + * Resolve WorkOS session cookie value `id::jwt` for cursor.com dashboard APIs. + * Returns null when no usable web session is found (never throws). + * + * @param {{ + * signal?: AbortSignal, + * sources?: Array<(signal?: AbortSignal) => Promise>, + * }} [opts] + * @returns {Promise} + */ +export async function resolveCursorSessionCookie(opts = {}) { + const signal = opts.signal; + const sources = opts.sources ?? [fromMacosKeychain, fromStateDb]; + try { + if (isAborted(signal)) return null; + + const env = process.env.CURSOR_SESSION_TOKEN?.trim(); + if (env) { + const cookie = cookieFromToken(env); + if (cookie) return cookie; + } + + for (const source of sources) { + if (isAborted(signal)) return null; + const token = await source(signal); + if (!token) continue; + const cookie = cookieFromToken(token); + if (cookie) return cookie; + } + } catch { + // fail-open + } + return null; +} diff --git a/packages/tiny-engineer-cli/src/integrations/types.js b/packages/tiny-engineer-cli/src/integrations/types.js index 130116e8..efb8d9c4 100644 --- a/packages/tiny-engineer-cli/src/integrations/types.js +++ b/packages/tiny-engineer-cli/src/integrations/types.js @@ -13,6 +13,15 @@ * @property {HookInput} [input] */ +/** + * @typedef {object} AfterAnimContext + * @property {string | null} anim + * @property {HookInput} [input] + * @property {string} [url] + * @property {string} [transport] + * @property {string | null} [port] + */ + /** * @typedef {object} InstallContext * @property {string} projectRoot @@ -49,6 +58,7 @@ * @property {(argv: string[], stdinText: string) => HookInput | null} parseHook * @property {(input: HookInput) => string | null} mapToAnim * @property {(input: HookInput, style: import("../util/style.js").Style) => string[]} [describeFiles] + * @property {(ctx: AfterAnimContext) => void | Promise} [afterAnim] * @property {(ctx: HookRespondContext) => void} [respond] * @property {(projectRoot: string) => boolean} [detect] * @property {() => string} [configRelativePath] diff --git a/packages/tiny-engineer-cli/src/robot/ops.js b/packages/tiny-engineer-cli/src/robot/ops.js index bfef1c2b..3c2e689a 100644 --- a/packages/tiny-engineer-cli/src/robot/ops.js +++ b/packages/tiny-engineer-cli/src/robot/ops.js @@ -4,7 +4,7 @@ import { robotFetch } from "./client.js"; import { withTransport } from "./with-transport.js"; /** - * @typedef {{ transport?: string, url?: string, port?: string | null }} TransportOpts + * @typedef {{ transport?: string, url?: string, port?: string | null, timeoutMs?: number }} TransportOpts */ /** @@ -48,7 +48,10 @@ async function viaTransport(op, fields, opts, httpFn) { return withTransport(opts, { serial: async () => { try { - const body = await serialRequest(op, fields, { port: opts.port }); + /** @type {{ port?: string | null, timeoutMs?: number }} */ + const serialOpts = { port: opts.port }; + if (opts.timeoutMs != null) serialOpts.timeoutMs = opts.timeoutMs; + const body = await serialRequest(op, fields, serialOpts); if (body.ok === false) { return { ok: false, @@ -171,3 +174,38 @@ export async function robotPark(opts = {}) { return fromHttpResponse(res); }); } + +/** + * Extension API over HTTP path or serial `ext` op. + * @param {{ + * id: string, + * suffix: string, + * method: string, + * body?: Record, + * }} call + * @param {TransportOpts & { timeoutMs?: number }} [opts] + */ +export async function robotExt(call, opts = {}) { + const { id, suffix, method, body = {} } = call; + const path = `/extensions/${id}/${suffix}`; + const timeoutMs = opts.timeoutMs ?? 10_000; + return viaTransport( + "ext", + { id, suffix, method, ...body }, + opts, + async () => { + const upper = method.toUpperCase(); + /** @type {RequestInit} */ + const init = { + method: upper, + signal: AbortSignal.timeout(timeoutMs), + }; + if (upper === "POST") { + init.headers = { "Content-Type": "application/json" }; + init.body = JSON.stringify(body); + } + const res = await robotFetch(opts.url ?? getBaseUrl(), path, init, httpToken(opts)); + return fromHttpResponse(res); + }, + ); +} diff --git a/packages/tiny-engineer-cli/src/util/args.js b/packages/tiny-engineer-cli/src/util/args.js index 29787246..51c642c4 100644 --- a/packages/tiny-engineer-cli/src/util/args.js +++ b/packages/tiny-engineer-cli/src/util/args.js @@ -32,6 +32,9 @@ export function stripGlobalFlags(argv) { * Parse shared flags from argv. Flags may appear before or after positionals * (e.g. `hook cursor -q`). Non-flag tokens go to `rest` in order. * @param {string[]} argv + * @param {{ passthroughUnknown?: boolean }} [options] + * When `passthroughUnknown` is true, unrecognized `-…` tokens stay in `rest` + * (for commands that parse their own `--key=value` flags, e.g. settings/ext). * @returns {{ * help: boolean, * quiet: boolean, @@ -42,7 +45,8 @@ export function stripGlobalFlags(argv) { * error?: string, * }} */ -export function parseCommonArgs(argv) { +export function parseCommonArgs(argv, options = {}) { + const passthroughUnknown = options.passthroughUnknown === true; let help = false; let quiet = false; /** @type {string | undefined} */ @@ -102,6 +106,10 @@ export function parseCommonArgs(argv) { continue; } if (arg.startsWith("-")) { + if (passthroughUnknown) { + rest.push(arg); + continue; + } return { help, quiet, url, transport, port, rest, error: `Unknown argument: ${arg}` }; } rest.push(arg); diff --git a/packages/tiny-engineer-cli/src/wizard/setup.js b/packages/tiny-engineer-cli/src/wizard/setup.js index f3f3f012..544c2c28 100644 --- a/packages/tiny-engineer-cli/src/wizard/setup.js +++ b/packages/tiny-engineer-cli/src/wizard/setup.js @@ -12,6 +12,7 @@ import { resolveTransport, } from "../config/env.js"; import { userEnvPath } from "../config/paths.js"; +import { AI_USAGE_LCD_KEY } from "../integrations/cursor/lcd-usage.js"; import { all as allIntegrations, get as getIntegration } from "../integrations/registry.js"; import { hookCommandFor } from "./cliPath.js"; import { mergeEnvKey, readEnvKey, readJsonFile, writeJsonFile } from "./merge.js"; @@ -32,6 +33,7 @@ const DEFAULT_TIMEOUT = 30; * port?: string, * token?: string, * command?: string, + * aiUsageLcd?: boolean, * ides: string[], * error?: string, * }} @@ -51,6 +53,8 @@ export function parseSetupArgs(argv) { let token; /** @type {string | undefined} */ let command; + /** @type {boolean | undefined} */ + let aiUsageLcd; /** @type {string[]} */ const ides = []; @@ -72,6 +76,14 @@ export function parseSetupArgs(argv) { dryRun = true; continue; } + if (arg === "--ai-usage-lcd") { + aiUsageLcd = true; + continue; + } + if (arg === "--no-ai-usage-lcd") { + aiUsageLcd = false; + continue; + } if (arg === "--force-url" || arg === "--force-transport") { return { help, @@ -148,7 +160,7 @@ export function parseSetupArgs(argv) { ides.push(arg); } - return { help, yes, all, dryRun, url, transport, port, token, command, ides }; + return { help, yes, all, dryRun, url, transport, port, token, command, aiUsageLcd, ides }; } /** @@ -394,6 +406,9 @@ export async function runSetup( plans.push(integration.planInstall(ctx)); } + /** @type {boolean | undefined} */ + const aiUsageLcdPreview = args.aiUsageLcd; + if (args.dryRun) { out.ok("dry-run — no files written"); out.info("Project hooks:"); @@ -413,6 +428,9 @@ export async function runSetup( if (transport === "serial" && port) { out.info(` TINY_ENGINEER_PORT=${port}`); } + if (aiUsageLcdPreview !== undefined) { + out.info(` ${AI_USAGE_LCD_KEY}=${aiUsageLcdPreview ? "1" : "0"}`); + } process.exitCode = 0; return; } @@ -486,6 +504,25 @@ export async function runSetup( }); } + /** @type {boolean | undefined} */ + let aiUsageLcd = args.aiUsageLcd; + if (aiUsageLcd === undefined && !args.yes) { + aiUsageLcd = await confirmFn( + "Show remaining Cursor AI budget on LCD1602 after completed turns?", + false, + ); + } + if (aiUsageLcd !== undefined) { + await persistUserEnvKey(out, { + key: AI_USAGE_LCD_KEY, + value: aiUsageLcd ? "1" : "0", + yes: args.yes, + dryRun: false, + label: AI_USAGE_LCD_KEY, + confirmFn, + }); + } + out.ok("setup complete — run: tiny-engineer doctor"); process.exitCode = 0; } @@ -494,7 +531,8 @@ function printSetupHelp() { console.log(`Usage: tiny-engineer setup [ide...] [options] Merge Tiny Engineer hook commands into the current project (project-local). -Connection prefs (transport, URL, port, token) go to user config (global). +Connection prefs (transport, URL, port, token, optional LCD AI budget) go to user config (global). +Cursor LCD AI budget updates are opt-in (TINY_ENGINEER_AI_USAGE_LCD=1). Options: --all Install all integrations (cursor, claude-code, antigravity) @@ -505,6 +543,8 @@ Options: --url Robot URL when transport is http (user config) --port Optional serial port when transport is serial (user config) --token Optional HTTP access token (user config; omit to skip) + --ai-usage-lcd Enable LCD AI budget after Cursor ring (user config) + --no-ai-usage-lcd Disable LCD AI budget (user config) --command Override CLI launcher (default: npx -y tiny-engineer) -h, --help Show this help @@ -513,6 +553,7 @@ Examples: npx -y tiny-engineer setup cursor --yes npx -y tiny-engineer setup --all --yes --url http://192.168.1.10 npx -y tiny-engineer setup cursor --yes --transport serial + npx -y tiny-engineer setup cursor --yes --ai-usage-lcd tiny-engineer setup --dry-run tiny-engineer setup cursor --yes --command 'node packages/tiny-engineer-cli/bin/tiny-engineer.js' `); diff --git a/packages/tiny-engineer-cli/test/args.test.js b/packages/tiny-engineer-cli/test/args.test.js index 2416fc02..6c4ecbc1 100644 --- a/packages/tiny-engineer-cli/test/args.test.js +++ b/packages/tiny-engineer-cli/test/args.test.js @@ -42,6 +42,15 @@ test("parseCommonArgs help and missing --url value", () => { assert.equal(parseCommonArgs(["--url"]).error, "--url requires a value"); }); +test("parseCommonArgs passthroughUnknown keeps --key=value in rest", () => { + const parsed = parseCommonArgs(["lcd1602", "text", "set", "--line1=HELLO", "--transport", "serial"], { + passthroughUnknown: true, + }); + assert.equal(parsed.error, undefined); + assert.equal(parsed.transport, "serial"); + assert.deepEqual(parsed.rest, ["lcd1602", "text", "set", "--line1=HELLO"]); +}); + test("parseCommonArgs accepts quiet before or after ide id", () => { assert.equal(parseCommonArgs(["cursor", "-q"]).quiet, true); assert.deepEqual(parseCommonArgs(["cursor", "-q"]).rest, ["cursor"]); diff --git a/packages/tiny-engineer-cli/test/ext-command.test.js b/packages/tiny-engineer-cli/test/ext-command.test.js new file mode 100644 index 00000000..3046b7b0 --- /dev/null +++ b/packages/tiny-engineer-cli/test/ext-command.test.js @@ -0,0 +1,110 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +import { KNOWN_EXTENSION_IDS, runExt } from "../src/commands/ext.js"; +import { createOutput } from "../src/util/output.js"; +import { createStyle } from "../src/util/style.js"; + +test("KNOWN_EXTENSION_IDS includes lcd1602 only", () => { + assert.deepEqual([...KNOWN_EXTENSION_IDS], ["lcd1602"]); +}); + +test("runExt rejects unknown id without contacting the robot", async () => { + /** @type {string[]} */ + const errs = []; + const out = createOutput({ + quiet: false, + style: createStyle({ color: false }), + log: () => {}, + error: (m) => errs.push(String(m)), + }); + process.exitCode = 0; + await runExt(out, ["nope", "text", "get"], false); + assert.equal(process.exitCode, 1); + assert.ok(errs.some((e) => e.includes("unknown extension"))); + process.exitCode = 0; +}); + +test("runExt --help prints lcd1602 usage", async () => { + /** @type {string[]} */ + const logs = []; + const original = console.log; + console.log = (...args) => logs.push(args.join(" ")); + const out = createOutput({ + quiet: false, + style: createStyle({ color: false }), + log: () => {}, + error: () => {}, + }); + try { + await runExt(out, ["--help"], false); + assert.ok(logs.some((l) => l.includes("lcd1602 text get"))); + assert.ok(logs.some((l) => l.includes("lcd1602 color get"))); + } finally { + console.log = original; + } +}); + +test("runExt color set rejects missing channels locally", async () => { + /** @type {string[]} */ + const errs = []; + const out = createOutput({ + quiet: false, + style: createStyle({ color: false }), + log: () => {}, + error: (m) => errs.push(String(m)), + }); + process.exitCode = 0; + await runExt(out, ["lcd1602", "color", "set", "--r=10"], false); + assert.equal(process.exitCode, 1); + assert.ok(errs.some((e) => e.includes("color set needs"))); + process.exitCode = 0; +}); + +test("runExt text set rejects flag with missing operand", async () => { + /** @type {string[]} */ + const errs = []; + const out = createOutput({ + quiet: false, + style: createStyle({ color: false }), + log: () => {}, + error: (m) => errs.push(String(m)), + }); + process.exitCode = 0; + await runExt(out, ["lcd1602", "text", "set", "--line1=NEW", "--line2"], false); + assert.equal(process.exitCode, 1); + assert.ok(errs.some((e) => e.includes("malformed option --line2"))); + process.exitCode = 0; +}); + +test("runExt brightness set rejects empty operand", async () => { + /** @type {string[]} */ + const errs = []; + const out = createOutput({ + quiet: false, + style: createStyle({ color: false }), + log: () => {}, + error: (m) => errs.push(String(m)), + }); + process.exitCode = 0; + await runExt(out, ["lcd1602", "brightness", "set", ""], false); + assert.equal(process.exitCode, 1); + assert.ok(errs.some((e) => e.includes("brightness set needs"))); + process.exitCode = 0; +}); + +test("runExt color set rejects empty channel operand", async () => { + /** @type {string[]} */ + const errs = []; + const out = createOutput({ + quiet: false, + style: createStyle({ color: false }), + log: () => {}, + error: (m) => errs.push(String(m)), + }); + process.exitCode = 0; + await runExt(out, ["lcd1602", "color", "set", "--r=", "--g=10", "--b=20"], false); + assert.equal(process.exitCode, 1); + assert.ok(errs.some((e) => e.includes("color set needs"))); + process.exitCode = 0; +}); diff --git a/packages/tiny-engineer-cli/test/lcd-usage.test.js b/packages/tiny-engineer-cli/test/lcd-usage.test.js new file mode 100644 index 00000000..bc9a9f9f --- /dev/null +++ b/packages/tiny-engineer-cli/test/lcd-usage.test.js @@ -0,0 +1,262 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +import { + AI_USAGE_LCD_KEY, + maybeShowCursorUsageOnLcd, +} from "../src/integrations/cursor/lcd-usage.js"; +import { + cookieFromToken, + jwtClaims, + cookieIdFromClaims, + resolveCursorSessionCookie, + selectUsableStateDbToken, +} from "../src/integrations/cursor/usage-session.js"; + +test("maybeShowCursorUsageOnLcd skips when unset (opt-in default off)", async () => { + let posted = 0; + await maybeShowCursorUsageOnLcd( + {}, + { + env: {}, + resolveCookie: async () => "id::jwt", + fetchLimits: async () => ({ planUsage: { autoPercentUsed: 10 } }), + postLcd: async () => { + posted += 1; + }, + }, + ); + assert.equal(posted, 0); +}); + +test("maybeShowCursorUsageOnLcd skips when set to 0", async () => { + let posted = 0; + await maybeShowCursorUsageOnLcd( + {}, + { + env: { [AI_USAGE_LCD_KEY]: "0" }, + resolveCookie: async () => "id::jwt", + fetchLimits: async () => ({ planUsage: { autoPercentUsed: 10 } }), + postLcd: async () => { + posted += 1; + }, + }, + ); + assert.equal(posted, 0); +}); + +test("maybeShowCursorUsageOnLcd skips LCD when no cookie", async () => { + let posted = 0; + await maybeShowCursorUsageOnLcd( + {}, + { + env: { [AI_USAGE_LCD_KEY]: "1" }, + resolveCookie: async () => null, + fetchLimits: async () => ({ planUsage: { autoPercentUsed: 10 } }), + postLcd: async () => { + posted += 1; + }, + }, + ); + assert.equal(posted, 0); +}); + +test("maybeShowCursorUsageOnLcd skips LCD when remaining is null", async () => { + let posted = 0; + await maybeShowCursorUsageOnLcd( + {}, + { + env: { [AI_USAGE_LCD_KEY]: "1" }, + resolveCookie: async () => "id::token", + fetchLimits: async () => ({ planUsage: {} }), + postLcd: async () => { + posted += 1; + }, + }, + ); + assert.equal(posted, 0); +}); + +test("maybeShowCursorUsageOnLcd posts remaining percent when enabled", async () => { + /** @type {{ pct: number, transport: object } | null} */ + let seen = null; + await maybeShowCursorUsageOnLcd( + { url: "http://robot.local" }, + { + env: { [AI_USAGE_LCD_KEY]: "1" }, + resolveCookie: async () => "id::token", + fetchLimits: async () => ({ + planUsage: { autoPercentUsed: 40, apiPercentUsed: 25 }, + }), + postLcd: async (pct, transport) => { + seen = { pct, transport }; + }, + }, + ); + assert.deepEqual(seen, { pct: 60, transport: { url: "http://robot.local" } }); +}); + +test("maybeShowCursorUsageOnLcd swallows postLcd errors", async () => { + await maybeShowCursorUsageOnLcd( + {}, + { + env: { [AI_USAGE_LCD_KEY]: "1" }, + resolveCookie: async () => "id::token", + fetchLimits: async () => ({ planUsage: { autoPercentUsed: 5 } }), + postLcd: async () => { + throw new Error("lcd down"); + }, + overallTimeoutMs: 500, + }, + ); +}); + +test("maybeShowCursorUsageOnLcd respects overall timeout", async () => { + let posted = 0; + /** @type {AbortSignal | undefined} */ + let seenSignal; + const started = Date.now(); + await maybeShowCursorUsageOnLcd( + {}, + { + env: { [AI_USAGE_LCD_KEY]: "1" }, + resolveCookie: (opts) => + new Promise((resolve) => { + seenSignal = opts?.signal; + // Resolves after the overall cap so cancelled=true skips postLcd. + setTimeout(() => resolve("id::token"), 80); + }), + fetchLimits: async () => ({ planUsage: { autoPercentUsed: 1 } }), + postLcd: async () => { + posted += 1; + }, + overallTimeoutMs: 30, + }, + ); + assert.ok(Date.now() - started < 200); + assert.equal(seenSignal?.aborted, true); + // Let the late cookie resolve; cancel flag must still block LCD. + await new Promise((r) => setTimeout(r, 100)); + assert.equal(posted, 0); +}); + +test("resolveCursorSessionCookie returns immediately when already aborted", async () => { + const prev = process.env.CURSOR_SESSION_TOKEN; + delete process.env.CURSOR_SESSION_TOKEN; + try { + const ac = new AbortController(); + ac.abort(); + const started = Date.now(); + assert.equal(await resolveCursorSessionCookie({ signal: ac.signal }), null); + assert.ok(Date.now() - started < 100); + } finally { + if (prev === undefined) delete process.env.CURSOR_SESSION_TOKEN; + else process.env.CURSOR_SESSION_TOKEN = prev; + } +}); + +test("resolveCursorSessionCookie stops lookup when aborted mid-flight", async () => { + const prev = process.env.CURSOR_SESSION_TOKEN; + delete process.env.CURSOR_SESSION_TOKEN; + try { + const ac = new AbortController(); + let secondStarted = 0; + /** @param {AbortSignal | undefined} signal */ + const hangUntilAbort = (signal) => + new Promise((resolve) => { + const done = () => resolve(null); + if (signal?.aborted) { + done(); + return; + } + signal?.addEventListener("abort", done, { once: true }); + }); + /** @param {AbortSignal | undefined} _signal */ + const second = async (_signal) => { + secondStarted += 1; + return "should-not-run"; + }; + + const started = Date.now(); + const pending = resolveCursorSessionCookie({ + signal: ac.signal, + sources: [hangUntilAbort, second], + }); + setTimeout(() => ac.abort(), 40); + assert.equal(await pending, null); + assert.equal(secondStarted, 0); + assert.ok(Date.now() - started < 500); + } finally { + if (prev === undefined) delete process.env.CURSOR_SESSION_TOKEN; + else process.env.CURSOR_SESSION_TOKEN = prev; + } +}); + +test("resolveCursorSessionCookie uses injected source when not aborted", async () => { + const prev = process.env.CURSOR_SESSION_TOKEN; + delete process.env.CURSOR_SESSION_TOKEN; + try { + const sessionPayload = Buffer.from( + JSON.stringify({ sub: "github|user_01ABC", type: "session" }), + ).toString("base64url"); + const sessionJwt = `hdr.${sessionPayload}.sig`; + let calls = 0; + const cookie = await resolveCursorSessionCookie({ + sources: [ + async () => { + calls += 1; + return sessionJwt; + }, + async () => { + calls += 1; + return "unused"; + }, + ], + }); + assert.equal(cookie, "user_01ABC::" + sessionJwt); + assert.equal(calls, 1); + } finally { + if (prev === undefined) delete process.env.CURSOR_SESSION_TOKEN; + else process.env.CURSOR_SESSION_TOKEN = prev; + } +}); + +test("cookieFromToken builds id::jwt and skips api_key_token", () => { + // header.payload.sig — payload {"sub":"github|user_01ABC","type":"session"} + const sessionPayload = Buffer.from( + JSON.stringify({ sub: "github|user_01ABC", type: "session" }), + ).toString("base64url"); + const sessionJwt = `hdr.${sessionPayload}.sig`; + assert.equal(cookieFromToken(sessionJwt), "user_01ABC::" + sessionJwt); + + const apiPayload = Buffer.from( + JSON.stringify({ sub: "github|user_01ABC", type: "api_key_token" }), + ).toString("base64url"); + assert.equal(cookieFromToken(`hdr.${apiPayload}.sig`), null); + + assert.equal(cookieFromToken("already::full"), "already::full"); +}); + +test("selectUsableStateDbToken skips api_key then keeps session", () => { + const sessionPayload = Buffer.from( + JSON.stringify({ sub: "github|user_01ABC", type: "session" }), + ).toString("base64url"); + const sessionJwt = `hdr.${sessionPayload}.sig`; + const apiPayload = Buffer.from( + JSON.stringify({ sub: "github|user_01ABC", type: "api_key_token" }), + ).toString("base64url"); + const apiJwt = `hdr.${apiPayload}.sig`; + + assert.equal(selectUsableStateDbToken([apiJwt, sessionJwt]), sessionJwt); + assert.equal(selectUsableStateDbToken([apiJwt]), null); +}); + +test("jwtClaims and cookieIdFromClaims parse sub", () => { + const payload = Buffer.from(JSON.stringify({ sub: "auth0|user_xyz" })).toString("base64url"); + const claims = jwtClaims(`x.${payload}.y`); + assert.equal(cookieIdFromClaims(claims), "user_xyz"); + assert.deepEqual(jwtClaims("not-a-jwt"), {}); + // payload "null" — must not throw; empty claims so env token can fall through + assert.deepEqual(jwtClaims("x.bnVsbA.y"), {}); + assert.equal(cookieFromToken("x.bnVsbA.y"), null); +}); diff --git a/packages/tiny-engineer-cli/test/parity-commands.test.js b/packages/tiny-engineer-cli/test/parity-commands.test.js index 8752ba21..aa639c89 100644 --- a/packages/tiny-engineer-cli/test/parity-commands.test.js +++ b/packages/tiny-engineer-cli/test/parity-commands.test.js @@ -3,7 +3,23 @@ import assert from "node:assert/strict"; import { createOutput } from "../src/util/output.js"; import { createStyle } from "../src/util/style.js"; -import { runReset, runTest } from "../src/commands/parity.js"; +import { runReset, runServo, runTest } from "../src/commands/parity.js"; + +test("runServo rejects unknown options before contacting the robot", async () => { + /** @type {string[]} */ + const errs = []; + const out = createOutput({ + quiet: false, + style: createStyle({ color: false }), + log: () => {}, + error: (m) => errs.push(String(m)), + }); + process.exitCode = 0; + await runServo(out, ["0", "90", "--urll=http://other-device"], false); + assert.equal(process.exitCode, 1); + assert.ok(errs.some((e) => /unknown argument/i.test(e))); + process.exitCode = 0; +}); test("runTest rejects unknown test name", async () => { /** @type {string[]} */ diff --git a/packages/tiny-engineer-cli/test/setup-args.test.js b/packages/tiny-engineer-cli/test/setup-args.test.js index 0590fd6e..27bab1af 100644 --- a/packages/tiny-engineer-cli/test/setup-args.test.js +++ b/packages/tiny-engineer-cli/test/setup-args.test.js @@ -15,6 +15,7 @@ import { join } from "node:path"; import { createOutput } from "../src/util/output.js"; import { createStyle } from "../src/util/style.js"; import { mergeEnvKey, mergeEnvUrl, readEnvKey } from "../src/wizard/merge.js"; +import { AI_USAGE_LCD_KEY } from "../src/integrations/cursor/lcd-usage.js"; import { parseSetupArgs, runSetup, warnProjectOverrides } from "../src/wizard/setup.js"; test("parseSetupArgs --yes without ide fails at run time; parser ok", () => { @@ -41,6 +42,12 @@ test("parseSetupArgs reads flags without force", () => { assert.equal(args.url, "http://x"); assert.equal(args.transport, "serial"); assert.equal(args.port, "/dev/ttyUSB0"); + assert.equal(args.aiUsageLcd, undefined); +}); + +test("parseSetupArgs reads --ai-usage-lcd and --no-ai-usage-lcd", () => { + assert.equal(parseSetupArgs(["--ai-usage-lcd"]).aiUsageLcd, true); + assert.equal(parseSetupArgs(["--no-ai-usage-lcd"]).aiUsageLcd, false); }); test("parseSetupArgs rejects removed force flags", () => { @@ -94,6 +101,36 @@ test("runSetup --dry-run does not write files", async () => { } }); +test("runSetup --dry-run --ai-usage-lcd previews key without writing", async () => { + const dir = mkdtempSync(join(tmpdir(), "te-setup-")); + const cfg = mkdtempSync(join(tmpdir(), "te-ucfg-")); + const prev = process.env.TINY_ENGINEER_CONFIG_DIR; + process.env.TINY_ENGINEER_CONFIG_DIR = cfg; + /** @type {string[]} */ + const infos = []; + const out = createOutput({ + quiet: false, + style: createStyle({ color: false }), + log: () => {}, + error: (m) => infos.push(String(m)), + }); + try { + await runSetup(out, ["cursor", "--yes", "--dry-run", "--ai-usage-lcd"], { + projectRoot: dir, + }); + assert.equal(process.exitCode, 0); + assert.ok(infos.some((l) => l.includes(`${AI_USAGE_LCD_KEY}=1`))); + assert.equal(readEnvKey(join(cfg, "env"), AI_USAGE_LCD_KEY), null); + assert.equal(existsSync(join(cfg, "env")), false); + } finally { + if (prev === undefined) delete process.env.TINY_ENGINEER_CONFIG_DIR; + else process.env.TINY_ENGINEER_CONFIG_DIR = prev; + rmSync(dir, { recursive: true, force: true }); + rmSync(cfg, { recursive: true, force: true }); + process.exitCode = 0; + } +}); + test("runSetup --yes writes cursor hooks and user env not project .env", async () => { const dir = mkdtempSync(join(tmpdir(), "te-setup-")); const cfg = mkdtempSync(join(tmpdir(), "te-ucfg-")); @@ -487,3 +524,132 @@ test("setup leaves existing project .env byte-identical", async () => { process.exitCode = 0; } }); + +test("runSetup --yes alone leaves AI usage LCD key unset", async () => { + const dir = mkdtempSync(join(tmpdir(), "te-setup-")); + const cfg = mkdtempSync(join(tmpdir(), "te-ucfg-")); + const prev = process.env.TINY_ENGINEER_CONFIG_DIR; + process.env.TINY_ENGINEER_CONFIG_DIR = cfg; + mkdirSync(join(dir, ".cursor")); + const out = createOutput({ + quiet: true, + style: createStyle({ color: false }), + log: () => {}, + error: () => {}, + }); + try { + await runSetup(out, ["cursor", "--yes", "--url", "http://robot.test"], { + projectRoot: dir, + }); + assert.equal(process.exitCode, 0); + assert.equal(readEnvKey(join(cfg, "env"), AI_USAGE_LCD_KEY), null); + } finally { + if (prev === undefined) delete process.env.TINY_ENGINEER_CONFIG_DIR; + else process.env.TINY_ENGINEER_CONFIG_DIR = prev; + rmSync(dir, { recursive: true, force: true }); + rmSync(cfg, { recursive: true, force: true }); + process.exitCode = 0; + } +}); + +test("runSetup --yes --ai-usage-lcd writes 1", async () => { + const dir = mkdtempSync(join(tmpdir(), "te-setup-")); + const cfg = mkdtempSync(join(tmpdir(), "te-ucfg-")); + const prev = process.env.TINY_ENGINEER_CONFIG_DIR; + process.env.TINY_ENGINEER_CONFIG_DIR = cfg; + mkdirSync(join(dir, ".cursor")); + const out = createOutput({ + quiet: true, + style: createStyle({ color: false }), + log: () => {}, + error: () => {}, + }); + try { + await runSetup(out, ["cursor", "--yes", "--url", "http://robot.test", "--ai-usage-lcd"], { + projectRoot: dir, + }); + assert.equal(process.exitCode, 0); + assert.equal(readEnvKey(join(cfg, "env"), AI_USAGE_LCD_KEY), "1"); + } finally { + if (prev === undefined) delete process.env.TINY_ENGINEER_CONFIG_DIR; + else process.env.TINY_ENGINEER_CONFIG_DIR = prev; + rmSync(dir, { recursive: true, force: true }); + rmSync(cfg, { recursive: true, force: true }); + process.exitCode = 0; + } +}); + +test("runSetup --yes --no-ai-usage-lcd writes 0", async () => { + const dir = mkdtempSync(join(tmpdir(), "te-setup-")); + const cfg = mkdtempSync(join(tmpdir(), "te-ucfg-")); + const prev = process.env.TINY_ENGINEER_CONFIG_DIR; + process.env.TINY_ENGINEER_CONFIG_DIR = cfg; + mkdirSync(join(dir, ".cursor")); + const out = createOutput({ + quiet: true, + style: createStyle({ color: false }), + log: () => {}, + error: () => {}, + }); + try { + await runSetup(out, ["cursor", "--yes", "--url", "http://robot.test", "--no-ai-usage-lcd"], { + projectRoot: dir, + }); + assert.equal(process.exitCode, 0); + assert.equal(readEnvKey(join(cfg, "env"), AI_USAGE_LCD_KEY), "0"); + } finally { + if (prev === undefined) delete process.env.TINY_ENGINEER_CONFIG_DIR; + else process.env.TINY_ENGINEER_CONFIG_DIR = prev; + rmSync(dir, { recursive: true, force: true }); + rmSync(cfg, { recursive: true, force: true }); + process.exitCode = 0; + } +}); + +test("interactive setup AI usage confirm writes 1 or 0", async () => { + const dir = mkdtempSync(join(tmpdir(), "te-setup-")); + const cfg = mkdtempSync(join(tmpdir(), "te-ucfg-")); + const prev = process.env.TINY_ENGINEER_CONFIG_DIR; + process.env.TINY_ENGINEER_CONFIG_DIR = cfg; + mkdirSync(join(dir, ".cursor")); + const out = createOutput({ + quiet: true, + style: createStyle({ color: false }), + log: () => {}, + error: () => {}, + }); + try { + await runSetup(out, ["cursor", "--url", "http://robot.test"], { + projectRoot: dir, + ask: async (q, def = "") => { + if (String(q).includes("Access token")) return ""; + return def || "http"; + }, + confirm: async (q) => { + if (String(q).includes("AI budget")) return true; + return true; + }, + }); + assert.equal(readEnvKey(join(cfg, "env"), AI_USAGE_LCD_KEY), "1"); + + await runSetup(out, ["cursor", "--url", "http://robot.test"], { + projectRoot: dir, + ask: async (q, def = "") => { + if (String(q).includes("Access token")) return ""; + return def || "http"; + }, + confirm: async (q) => { + if (String(q).includes("AI budget")) return false; + if (String(q).includes("Replace user config")) return true; + return true; + }, + }); + assert.equal(readEnvKey(join(cfg, "env"), AI_USAGE_LCD_KEY), "0"); + } finally { + if (prev === undefined) delete process.env.TINY_ENGINEER_CONFIG_DIR; + else process.env.TINY_ENGINEER_CONFIG_DIR = prev; + rmSync(dir, { recursive: true, force: true }); + rmSync(cfg, { recursive: true, force: true }); + process.exitCode = 0; + } +}); diff --git a/packages/tiny-engineer-cli/test/usage-api.test.js b/packages/tiny-engineer-cli/test/usage-api.test.js new file mode 100644 index 00000000..87ef7964 --- /dev/null +++ b/packages/tiny-engineer-cli/test/usage-api.test.js @@ -0,0 +1,43 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +import { fetchCursorLimits } from "../src/integrations/cursor/usage-api.js"; + +test("fetchCursorLimits falls back when primary has no usable percent", async () => { + /** @type {string[]} */ + const paths = []; + const fetchImpl = async (url) => { + paths.push(new URL(String(url)).pathname); + if (paths.length === 1) { + return { + ok: true, + json: async () => ({ planUsage: {} }), + }; + } + return { + ok: true, + json: async () => ({ planUsage: { autoPercentUsed: 10 } }), + }; + }; + const result = await fetchCursorLimits("id::jwt", { fetchImpl: /** @type {typeof fetch} */ (fetchImpl) }); + assert.deepEqual(paths, [ + "/api/dashboard/get-current-period-usage", + "/api/usage-summary", + ]); + assert.deepEqual(result, { planUsage: { autoPercentUsed: 10 } }); +}); + +test("fetchCursorLimits skips fallback when primary has usable percent", async () => { + /** @type {string[]} */ + const paths = []; + const fetchImpl = async (url) => { + paths.push(new URL(String(url)).pathname); + return { + ok: true, + json: async () => ({ planUsage: { autoPercentUsed: 40 } }), + }; + }; + const result = await fetchCursorLimits("id::jwt", { fetchImpl: /** @type {typeof fetch} */ (fetchImpl) }); + assert.deepEqual(paths, ["/api/dashboard/get-current-period-usage"]); + assert.deepEqual(result, { planUsage: { autoPercentUsed: 40 } }); +}); diff --git a/packages/tiny-engineer-cli/test/usage-remaining.test.js b/packages/tiny-engineer-cli/test/usage-remaining.test.js new file mode 100644 index 00000000..afe0a5bc --- /dev/null +++ b/packages/tiny-engineer-cli/test/usage-remaining.test.js @@ -0,0 +1,66 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +import { remainingBudgetPercent } from "../src/integrations/cursor/usage-remaining.js"; + +test("remainingBudgetPercent from planUsage max of auto/api", () => { + assert.equal( + remainingBudgetPercent({ + planUsage: { autoPercentUsed: 40, apiPercentUsed: 25 }, + }), + 60, + ); +}); + +test("remainingBudgetPercent uses individualUsage.plan fallback", () => { + assert.equal( + remainingBudgetPercent({ + individualUsage: { plan: { autoPercentUsed: 12.34, apiPercentUsed: 10 } }, + }), + 87.66, + ); +}); + +test("remainingBudgetPercent prefers planUsage over individualUsage", () => { + assert.equal( + remainingBudgetPercent({ + planUsage: { autoPercentUsed: 50 }, + individualUsage: { plan: { autoPercentUsed: 90 } }, + }), + 50, + ); +}); + +test("remainingBudgetPercent clamps at 0 when over 100", () => { + assert.equal( + remainingBudgetPercent({ + planUsage: { autoPercentUsed: 110 }, + }), + 0, + ); +}); + +test("remainingBudgetPercent rounds to two decimals", () => { + assert.equal( + remainingBudgetPercent({ + planUsage: { apiPercentUsed: 33.333 }, + }), + 66.67, + ); +}); + +test("remainingBudgetPercent returns null when no usable fields", () => { + assert.equal(remainingBudgetPercent({}), null); + assert.equal(remainingBudgetPercent({ planUsage: {} }), null); + assert.equal(remainingBudgetPercent(null), null); + assert.equal(remainingBudgetPercent(undefined), null); +}); + +test("remainingBudgetPercent ignores non-finite values", () => { + assert.equal( + remainingBudgetPercent({ + planUsage: { autoPercentUsed: "nope", apiPercentUsed: 20 }, + }), + 80, + ); +}); diff --git a/platformio.ini b/platformio.ini index 728671bc..70e7d48b 100644 --- a/platformio.ini +++ b/platformio.ini @@ -87,7 +87,7 @@ build_src_filter = +