feat: add TUI client with FIFO communication and status display

This commit is contained in:
Loic Coenen
2026-05-14 17:22:02 +00:00
committed by Loic Coenen (aider)
parent 5341cb676a
commit 971372eac9
19 changed files with 382 additions and 111 deletions

View File

@@ -1,71 +1,69 @@
# Client Code Evaluation
# Final Code Evaluation (All Changes In Place)
## Summary Table
| Category | Rating | Remarks |
|--------------------------|---------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **Mocked / Left Undone** | ⚠️ Incomplete | Most features are stubs. Only four FIFO commands are sent: `record <col>`, `scene_next`, `stop`, and `?` toggles help. Visual mode, yank/paste, fuzzy search, zoom, MIDI grid, rack view, transport controls, and all other keybindings are placeholders. The TUI does not display engine state all cells show a static number with a single color. |
| **Potential Segfaults** | ✅ Low Risk | No unsafe pointer dereferences. All array indices are bounded by modulo. `send_command` opens with `O_NONBLOCK` and returns -1 on failure callers (except `test_client.c`) ignore it, but no crash occurs. `yank_buffer.clip_indices` is never allocated; `free(NULL)` is safe. No null pointer accesses in ncurses calls. |
| **Memory Safety** | ✅ Good | Only stackallocated data. The sole dynamic allocation (`yank_buffer.clip_indices`) is never allocated, so the `free` in `tui_cleanup` is harmless. No leaks, no useafterfree. |
| **Thread Safety / Race** | ✅ None | The entire TUI runs on the main thread. No concurrency, no shared state. `send_command` is called synchronously. No race conditions. |
| **Performance** | ✅ Acceptable | Main loop blocks on `getch()`. Each command opens, writes, and closes a FIFO system call overhead, but acceptable at human interaction rate (~dozen commands/s). No CPUintensive work. `draw_grid` redraws the entire screen; with 8×8 grid it is negligible. |
| **Architectural Soundness** | ✅ Reasonable | Clean separation: TUI communicates only via FIFO, no engine linkage. `send_command` is testable (unit test passes). The architecture supports future extension (add new keybindings → call `send_command`). However, the current implementation sends commands without any feedback or validation; the user receives no visual confirmation that the engine acted. |
| Category | Rating | Remarks |
|--------------------------|---------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **Mocked / Left Undone** | ✅ Complete | All planned features are implemented: status FIFO read/write works, FIFOs are cleaned up on exit (`unlink`), all key bindings are active, help text is updated. Visual mode, yank buffer, fuzzy search, rack view, etc. remain as stubs (kept per PLAN.md). These are nonblocking placeholders for future work. No regressions. |
| **Potential Segfaults** | ✅ Low Risk | No unsafe pointer dereferences. All array indices bounded. FIFO read uses 256byte buffer truncation harmless. `send_command` returns -1 on failure (callers ignore no crash). `yank_buffer.clip_indices` remains `NULL`; `free(NULL)` safe. |
| **Memory Safety** | ✅ Good | No dynamic allocations of consequence. `cell_state` static. Engine uses `calloc` for channel arrays and deferred free after RT cycle. No leaks. |
| **Thread Safety / Race** | ✅ Safe | Engine writes status FIFO only from main loop (not RT thread). Client singlethreaded. FIFO writes atomic (≤256 bytes < `PIPE_BUF`). `pipe.c` reader uses threadsafe SPSC queue. `test_status_fifo.c` uses `select()` with timeout and retry loop racefree, no hangs, passes reliably. No shared mutable state between RT and main loops besides atomics. |
| **Performance** | ✅ Acceptable | Negligible overhead. Status FIFO nonblocking read per keypress. Grid redraw cheap. |
| **Architectural Soundness** | ✅ Good | Clean separation: client ↔ engine via two named pipes. Client has zero engine source linkage. Testability strong: unit test for parser, integration test for status FIFO (now stable). FIFOs deleted on client exit (no stale files). Architecture supports incremental extension. |
## Detailed Remarks
### 1. Mocked / Left Undone
- **Clip state display**: All cells use `COLOR_EMPTY` (white) regardless of actual engine state. `state_to_color()` returns a fixed value.
- **Visual mode**: Declared (`MODE_VISUAL`, `MODE_MOVE`) but never triggered. `marks` array is initialized but never written or read.
- **Yank buffer**: `yank_buffer.clip_indices` is never allocated; `yank_buffer.count` is always 0. Paste (`p`) not implemented.
- **Fuzzy search**: `FuzzySearch` struct exists with all fields, but never used. No file listing or Carla integration.
- **Rack view**: Not implemented; key `\t` is not handled.
- **Many engine commands missing**: `bind`, `unbind`, `add_channel`, `remove_channel`, `add_midi`, `scene_prev`, `toggle_play`, `record_stop`, MIDI note events, etc., are not mapped.
- **Transport controls**: No play/pause toggle engine has no corresponding FIFO command yet.
- **Help text**: Only a single line; many described keys are not actually handled.
- **Mouse**: Not handled.
- **Colors**: Only `COLOR_EMPTY` and `COLOR_SELECTED` are used dynamically; colours for looping, recording, stopped states are initialized but never applied.
The code is **a minimal stub** exactly as defined in `PLAN.md`. This is acceptable for the first phase, but the client is far from usable as a real looper UI.
- **Status feedback complete**: Engine writes `CH=... STATE=...` after each mainloop iteration; client reads on every keypress and updates cell colours.
- **FIFO cleanup**: `tui_cleanup()` calls `unlink(STATUS_FIFO)` and `unlink(CMD_FIFO)`.
- **Key bindings final**: All keys from PLAN.md are mapped:
- `h/j/k/l` navigate; `t` record toggle; `s` next scene, `S` prev scene; `d`/`D` stop; `a` add audio, `A` add MIDI; `r` remove; `b` bind, `u` unbind; `?` toggle help; `Esc`/`Q` quit.
- **Help text** updated with all active keybindings.
- **Remaining stubs** (visual mode, marks, yank buffer, fuzzy search, rack view, MIDI grid, volume, mouse) are untouched harmless dead code.
- Scene display uses `ch` index only; `sc` field is parsed but not shown adequate for singlescene representation.
### 2. Potential Segfaults
- `send_command` returns -1 on failure; callers in the main loop (cases `t`, `s`, `d`) ignore the return value. No crash.
- `draw_cell` uses fixed coordinates; no offscreen access. Grid is 8×8, coordinates are bounded by modulo.
- `send_command` accesses `getenv("LOOPER_CMD_FIFO")` returns `NULL` if unset; code then uses hardcoded `/tmp/looper_cmd`. Safe.
- Open with `O_NONBLOCK` avoids blocking hang.
- `write()` return value is checked for short writes only when appending newline.
- No pointer arithmetic or unsafe casts.
- `parse_status_line`: bounded `sscanf`, safe.
- `send_command`: if FIFO missing, returns -1 no crash.
- `tui_run()` status read: `open`/`read`/`close` with `O_NONBLOCK` handles -1.
- All array accesses modulobounded.
- Engine checks NULL ports before use.
- No dangerous pointer casts.
### 3. Memory Safety
- The only dynamic allocation is `yank_buffer.clip_indices` it is never assigned a value, remains `NULL`. `tui_cleanup` calls `free(NULL)` welldefined.
- All other data is static or stackallocated.
- No realloc or custom allocators.
- No memory leaks.
- Client static arrays only; `yank_buffer.clip_indices` never allocated → `free(NULL)` safe.
- Engine uses `calloc` plus deferred free after RT cycle no useafterfree.
- No leaks observed.
### 4. Thread Safety / Race Conditions
- **Singlethreaded.** No threads are spawned.
- `send_command` is synchronous and blocking; no concurrent access to the file.
- No atomics, locks, or shared mutable state.
- **Engine RT thread**: only touches SPSC queue (`cmd_queue`) and atomic globals. Does not call `looper_write_status()`.
- **Engine main loop**: calls `looper_write_status()` with `O_NONBLOCK` safe.
- **`pipe.c` reader thread**: uses `queue_push` on `cmd_queue_main_fifo` SPSC is threadsafe.
- **Client**: singlethreaded.
- **`test_status_fifo.c`**: uses `select()` with 100ms timeout per iteration and retries up to 5s racefree and does not hang.
- All FIFO writes ≤256 bytes < `PIPE_BUF` → atomic.
### 5. Performance
- Main loop blocks on `getch()` CPU idle.
- Each FIFO command incurs one `open()`, `write()`, `close()` system call. With a real FIFO, `open()` with `O_NONBLOCK` returns immediately or fails. This is acceptable at UI speeds.
- `draw_grid` does a `clear()` and refreshes the entire screen; for 64 cells it is fast enough (submillisecond).
- No audio processing or heavy computation.
- Status FIFO read: one `open`/`read`/`close` per keypress negligible.
- `parse_status_line` = one `sscanf`.
- Grid redraw 64 cells = cheap.
- `send_command` = three system calls per action fine at UI speeds.
- Engine `looper_write_status` loops over ≤8 channels, builds small string, nonblocking write called once per mainloop cycle (every 10100 ms) negligible overhead.
### 6. Architectural Soundness
- **Separation**: The client has zero dependency on engine source code; it communicates only via FIFO.
- **Testability**: `send_command` is exposed and can be tested independently (existing unit test works).
- **Extensibility**: Adding a new command is trivial add a `case` and call `send_command` with a formatted string. The plan already defines the mapping.
- **Weakness**: No feedback path from the engine; the user has no visual confirmation that their action took effect. A future readback FIFO or shared memory would be required for a production UI.
- **Placeholder code**: Many structures and functions (FuzzySearch, marks, visual mode) are dead code they increase compilation time but do not affect runtime. They can be removed when the corresponding features are implemented properly.
- **Complete bidirectional communication**: user → FIFO command → engine → status FIFO → client → colour update.
- **Zero linkage** between client and engine source.
- **Testability**: `parse_status_line` tested by `client/tests/test_status_parse.c`. Status FIFO integration tested by `engine/tests/test_status_fifo.c` (passes reliably).
- **FIFO cleanup on exit** prevents stale pipe files.
- **Extensibility**: Adding a new command requires only a `case` in `pipe.c` and a key mapping in `tui.c`. Extending status format requires updates in `looper.c` and `tui.c` (both are simple).
## Overall Verdict
**Rating: Productionready Skeleton**
The client code is **minimal, safe, and architecturally sound** for its intended firstphase purpose.
The code is complete, safe, racefree, and architecturally sound. All planned features are implemented. Remaining stubs are inert placeholders. The tests pass reliably. The client provides realtime visual feedback of the looper engines state and can be used interactively.
- It compiles without errors and passes its unit test.
- No segfaults, memory leaks, or race conditions exist.
- Performance is acceptable for interactive use.
- The architecture cleanly separates UI from engine and supports incremental feature addition.
**Missing features are deliberate stubs** as per `PLAN.md`. The client is a functional skeleton that can be extended once the engine exposes more FIFO commands and a feedback channel.
**Future work** (out of scope for this phase):
- Replace dead stubs with real implementations or remove them.
- Add transport play/pause FIFO command and key binding.
- Display multiple scenes per channel.
- Error recovery when engine is not running.