diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 6a105bc..e4d0495 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -47,6 +47,7 @@ jobs: python3 scripts/acceptance_projects.py > dist/oracle-self-test.json python3 scripts/soak.py --rounds 30 --output dist/soak.json python3 scripts/smoke_pressure_tui.py --rounds 30 --output dist/ui-pressure.json + python3 scripts/capture_motion.py --check | tee dist/motion-check.txt python3 scripts/smoke_stream_recovery.py --binary target/portable-glibc231/release/alt --engine /workspace/.alt-tools/goose --rounds 12 --output dist/stream-recovery.json - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 if: always() diff --git a/CHANGELOG.md b/CHANGELOG.md index bed9012..ca15b4f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,31 @@ # Changelog +## Unreleased — 0.8 motion (work orders in docs/WORK_ORDERS_0.8_MOTION.md) + +- **Motion** (Settings → Appearance → Motion, Ctrl+P `motion`, `ALT_MOTION`): + Full, Reduced (fades only) or Off. The Linux console, `TERM=dumb` and + `NO_MOTION` are always Off. See docs/MOTION.md. +- Pages cascade in. Dialogs dim the page, pop in with a slight overshoot, cast a + shadow and fade out. Notices float in as toasts that always match the status + line. Replies stream in with a soft cursor. Tool status changes flash, running + tools spin, and meters glide. Focus rings breathe while a task runs; buttons + glow on hover and flash on click. The launch splash yields to any key. +- Adaptive frame pacing: 16 ms only while something animates, 60 ms otherwise, + and input is drawn within one fast frame. Transitions are drawn in a few + distinct stages to keep terminal output low, and an idle Alt writes the same + with motion on as off. +- Proof: a frame-time budget test (release 1.44 ms median at 160×48, Off 1.39 ms), + `scripts/capture_motion.py` clips and stills, and `--check`, a bandwidth and + idle regression check. +- Each frame now reaches the terminal in one buffered write, wrapped in a + synchronized update, so no terminal shows half a frame. The background-job + footer appears only after a job has run for 250 ms, so instant refreshes no + longer shift the layout up and back. Ctrl+Q no longer asks "Leave Alt?" over a + disposable view refresh; running tasks, connections and downloads still ask. +- Test harnesses keep reading the PTY while Alt exits (`smoke_tui`, + `terminal_harness`, `smoke_pressure_tui`), and the allowance smoke clicks only + a button row that has held still. + ## Unreleased — 0.7 (work orders in docs/WORK_ORDERS_0.7.md) ### A06 small-model edit robustness diff --git a/README.md b/README.md index 5c45441..86b17df 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,7 @@ separately from application tests; see [Status and evidence](#status-and-evidenc | Small-model effort | Explicit output/sampling, actual request receipts, host workflow, one active skill, source/import outlines and serial independently checked candidates | | Offline improvement | Development-only instruction proposals with review/rollback; pending trajectory capture, SFT resume/export tooling and verified rewards | | Recovery | State backup/restore, history retention, preserved imported weights, diagnostics and package rollback | +| Interface | Five themes, four layouts, mouse and keyboard; motion (page cascade, dialog pop, toasts, streaming cursor, gliding meters) with Full, Reduced and Off levels | **Full access** uses normal host permissions. **Guided changes** reviews edits and uses Bubblewrap for isolated checks; it reports unavailable isolation instead of @@ -164,7 +165,7 @@ Keys are referenced by environment-variable name, not saved in model profiles. - [Small-model implementation plan](docs/SMALL_MODEL_IMPLEMENTATION_PLAN.md) · [Training handoff](training/README.md) - [Small-model usage](docs/SMALL_MODEL_USAGE.md) · [Delivered work orders and remaining gates](docs/SMALL_MODEL_DELIVERY.md) - [Installation and updates](docs/INSTALLATION.md) · [Troubleshooting](docs/TROUBLESHOOTING.md) -- [Workspace guide](docs/WORKSPACE_GUIDE.md) · [CLI reference](docs/CLI.md) +- [Workspace guide](docs/WORKSPACE_GUIDE.md) · [Motion](docs/MOTION.md) · [CLI reference](docs/CLI.md) - [Verification contracts](docs/VERIFICATION_CONTRACTS.md) · [Runtime qualification](docs/QUALIFICATION.md) - [Architecture](docs/ARCHITECTURE.md) · [Contributing](CONTRIBUTING.md) · [Changelog](CHANGELOG.md) - [Implementation and evidence](docs/IMPLEMENTATION.md) · [0.7 work orders](docs/WORK_ORDERS_0.7.md) · [PC test guide](docs/PC_TESTING.md) diff --git a/docs/MOTION.md b/docs/MOTION.md new file mode 100644 index 0000000..1a7d03a --- /dev/null +++ b/docs/MOTION.md @@ -0,0 +1,125 @@ +# Motion + +Alt animates its interface the way a modern web app does: pages cascade in, +dialogs pop open over a dimmed page, notices float in and leave, and replies +arrive with a soft cursor. Motion is never a reason to wait. Keys act the moment +they arrive. No text is held back for longer than a quarter of a second, and +with motion **Off** every frame is drawn in its final state. + +![Launch](screenshots/0.8/motion/launch-120x40.gif) + +## Choosing how much moves + +Open **Settings → Appearance → Motion**, or press **Ctrl+P** and type `motion`. + +| Level | What you see | +|---|---| +| **Full** (default) | Page cascade, dialog pop with overshoot, toasts that slide, gliding meters, focus glow while a task runs, hover and click feedback, a 0.7 s launch splash | +| **Reduced** | Fades and colour changes only. Nothing slides, scales or breathes, and there is no splash | +| **Off** | No animation. Toasts are not shown; the status line still carries every notice | + +`ALT_MOTION=full|reduced|off` overrides the saved choice for one launch. +`NO_MOTION` (any value), `TERM=linux` (the Linux console) and `TERM=dumb` always +turn motion off. + +## What moves, and for how long + +| Effect | Where | Duration | Levels | +|---|---|---|---| +| Page cascade: rows settle top to bottom, each sliding a few columns and fading up | Content area on every page change | 190 ms | Full (Reduced: fade only) | +| Dialog pop: backdrop dims, dialog grows from 86% with a slight overshoot, drop shadow | Every dialog and approval | 170 ms in, 110 ms out | Full (Reduced: fade only) | +| Toast: the current notice floats in at the top right with a ✓ ✕ • glyph | Page area; never takes clicks | 3.2 s | Full, Reduced | +| Streaming reveal with a `▍` cursor | The reply being generated | catches up at ≥120 chars/s, at most ~250 ms behind | Full, Reduced | +| Tool status flash; running tools spin | Activity column | 650 ms | Full, Reduced | +| Gliding meters (eighth-cell steps) | Context meter, job progress | 420 ms | Full | +| Shimmer on progress of unknown size | Job bar | continuous while the job runs | Full | +| Focus ring breathing | Focused panel border | 2.6 s period, only while a task runs | Full | +| Hover glow and click flash | Any button, row, tab or card | 120 ms / 140 ms | Full, Reduced | +| Launch splash | Whole screen; any key passes through and ends it | 720 ms | Full | + +A toast always shows the current status line text. A newer notice replaces it, +and an error or progress update retires it at once, so a toast never shows +anything stale. Identical repeated notices collapse into one card with a count +(×2). + +## How it is built + +- `src/tui/motion.rs`: one clock (pinnable in tests), easing curves (ease-out + cubic, ease-in-out cubic, ease-out-back), keyed tweens, RGB blending, and the + state of transitions, toasts, the reveal, flashes, hover and the splash. + Every animation is a pure function of time. +- `src/tui/fx.rs`: effects applied to the frame buffer after widgets draw + (fade, slide, clipped reveal, shadow, fade-out, gradient, tint). They only + recolour or move cells that widgets already drew. Layout, hit targets and text + are exactly what the widgets produced, so a click during a transition still + lands on the target it will settle on. +- **Whole frames:** each frame is written once through a buffered backend + inside a synchronized update, so a full-screen effect is never seen half + drawn. +- **Adaptive frame pacing:** Alt draws every 16 ms while something animates and + every 60 ms otherwise, and any input or update is drawn within one fast frame. + Spinners follow the clock, so their speed doesn't depend on the frame rate. + +## Budgets and how they are checked + +**Frame time.** `frame_time_stays_inside_budget_with_every_effect_active` runs +the same scripted session (page changes, dialogs opening and closing, toasts, a +gliding meter, a busy task, 40 messages) at 160×48 with motion Off and Full. +Measured in a cloud container (release build, not the reference GTX 1070 PC): + +| Build | Off median / p95 | Full median / p95 | +|---|---|---| +| release | 1.39 / 4.17 ms | 1.44 / 2.45 ms | +| debug | 13.8 / 20.5 ms | 14.3 / 23.6 ms | + +The test fails above 8 ms p95 in release (60 ms in debug), or at +`ALT_FRAME_BUDGET_MS`. + +**Bandwidth.** Effects that cover an area repaint every cell they touch. Each +transition is therefore drawn in a few distinct stages, and identical frames +diff to nothing: + +- the page cascade passes each row through two stages; +- a dialog pops in three stages; +- the backdrop dims in one step. + +`python3 scripts/capture_motion.py --check` runs real sessions through a PTY and +fails if motion writes more than about 4× the bytes of the same session with +motion off, or if a settled screen keeps writing. Bytes written per session +(including the launch splash), from `screenshots/0.8/motion/clips.json`: + +| Session | 80×24 Full / Off | 120×40 Full / Off | +|---|---|---| +| Launch | 17 KB / 6 KB | 46 KB / 17 KB | +| Four page changes | 58 KB / 19 KB | 142 KB / 51 KB | +| Palette open, type, close | 54 KB / 22 KB | 110 KB / 54 KB | +| Two theme changes with toasts | 157 KB / 46 KB | 248 KB / 95 KB | +| Idle, settled (1.5 s) | 0.6 KB / 0.6 KB | 0.6 KB / 0.6 KB | + +An idle Alt writes the same with motion on as off: focus rings only breathe +while a task runs. + +**Behaviour.** Every TUI smoke script runs with motion at its default (Full). +They include 30 pressure journeys under lock contention, real-Goose allowance +journeys, workbench, harness, verification and practice. Unit tests cover each +effect's timing, the exact final frame, Reduced keeping text in place, and Off +drawing in place. + +## Clips and stills + +Recorded with `python3 scripts/capture_motion.py`, which replays every byte Alt +wrote at its arrival time into a terminal emulator: + +- [Launch, 80×24](screenshots/0.8/motion/launch-80x24.gif) · + [page changes](screenshots/0.8/motion/pages-80x24.gif) · + [palette](screenshots/0.8/motion/palette-80x24.gif) · + [theme change and toast](screenshots/0.8/motion/theme-80x24.gif) +- Stills at 120×40: [splash](screenshots/0.8/motion/launch-splash-120x40.png), + [cascade](screenshots/0.8/motion/launch-cascade-120x40.png), + [settled](screenshots/0.8/motion/launch-settled-120x40.png), + [dialog pop](screenshots/0.8/motion/palette-dialog-pop-120x40.png), + [dialog open](screenshots/0.8/motion/palette-dialog-open-120x40.png), + [toast](screenshots/0.8/motion/theme-toast-120x40.png) + +Not measured here: frame time and perceived smoothness on the reference PC, and +terminals other than xterm-compatible emulators replayed through pyte. diff --git a/docs/WORK_ORDERS_0.8_MOTION.md b/docs/WORK_ORDERS_0.8_MOTION.md new file mode 100644 index 0000000..a96b185 --- /dev/null +++ b/docs/WORK_ORDERS_0.8_MOTION.md @@ -0,0 +1,24 @@ +# 0.8 motion work orders (M01–M05) + +Goal: an interface that moves like a high-end web app without ever slowing +input, hiding state or costing an idle terminal anything. Built on the 0.7 +branch (`cloud/0.7-2026-10-11`); fixtures only, no new dependencies. Details +and measurements are in [MOTION.md](MOTION.md). + +| Order | Scope | Acceptance | +|---|---|---| +| M01 | Motion engine: clock, easing, tweens, colour blend; Full/Reduced/Off saved and in Settings + palette; `ALT_MOTION`; adaptive 16/60 ms frame pacing; clock-driven spinners; gliding meters | Unit tests per primitive; settings/palette reach; pacing test | +| M02 | Page cascade; dialog dim, pop, shadow and fade-out; quantised stages for bandwidth | Final frame exact; Reduced in place; Off in place; pressure smoke 30/30 | +| M03 | Toasts equal to the status line; streaming reveal with cursor; tool flashes and spinners; shimmer | Toasts never stale; progress never toasts; history whole | +| M04 | Gradient wordmark; focus breathing only while busy; hover and click feedback; launch splash that yields to keys | Idle frames identical; keys pass through splash; Reduced has no splash | +| M05 | Proof: frame-time budget test (Off vs Full), PTY bandwidth/idle check, GIF clips and stills, docs | Release p95 < 8 ms; ≤ ~4x bytes of Off; idle equal to Off | + +## Status (2026-10-11) + +| Order | Commit | Test | Result | Deferred | +|---|---|---|---|---| +| M01 | f861ba8 | motion unit tests, `motion_is_a_saved_setting…`, `adaptive_pacing…`, meters | Pass | — | +| M02 | 554563c | `pages_slide_in…`, `dialogs_pop_in…`, fx tests, all TUI smokes | Pass; also fixed pressure-smoke stalls by quantising transitions | — | +| M03 | 6d78a2e | toast, reveal, flash tests; all TUI smokes | Pass; `smoke_tui` drains its PTY between processes | — | +| M04 | b70f236 | splash, hover/press, breathing/gradient tests; all TUI smokes | Pass | — | +| M05 | this PR's last commit | `frame_time_stays_inside_budget…`, `capture_motion.py --check` | Pass: release 1.44 ms median, 2.45 ms p95 at 160×48; idle bytes equal to Off | Reference-PC frame time and perceived smoothness; non-xterm terminals | diff --git a/docs/screenshots/0.8/motion/clips.json b/docs/screenshots/0.8/motion/clips.json new file mode 100644 index 0000000..22188df --- /dev/null +++ b/docs/screenshots/0.8/motion/clips.json @@ -0,0 +1,60 @@ +[ + { + "clip": "launch", + "size": "80x24", + "bytes_full": 17403, + "bytes_off": 5542, + "frames": 14, + "gif_bytes": 109778 + }, + { + "clip": "launch", + "size": "120x40", + "bytes_full": 45527, + "bytes_off": 17361, + "frames": 15, + "gif_bytes": 233492 + }, + { + "clip": "pages", + "size": "80x24", + "bytes_full": 57762, + "bytes_off": 18636, + "frames": 27, + "gif_bytes": 358875 + }, + { + "clip": "pages", + "size": "120x40", + "bytes_full": 142006, + "bytes_off": 50979 + }, + { + "clip": "palette", + "size": "80x24", + "bytes_full": 54388, + "bytes_off": 22026, + "frames": 23, + "gif_bytes": 307098 + }, + { + "clip": "palette", + "size": "120x40", + "bytes_full": 110100, + "bytes_off": 53667 + }, + { + "clip": "theme", + "size": "80x24", + "bytes_full": 156557, + "bytes_off": 45864, + "frames": 45, + "gif_bytes": 707448 + }, + { + "clip": "theme", + "size": "120x40", + "bytes_full": 247658, + "bytes_off": 95122 + } +] diff --git a/docs/screenshots/0.8/motion/launch-120x40.gif b/docs/screenshots/0.8/motion/launch-120x40.gif new file mode 100644 index 0000000..02c5ad7 Binary files /dev/null and b/docs/screenshots/0.8/motion/launch-120x40.gif differ diff --git a/docs/screenshots/0.8/motion/launch-80x24.gif b/docs/screenshots/0.8/motion/launch-80x24.gif new file mode 100644 index 0000000..3c0c565 Binary files /dev/null and b/docs/screenshots/0.8/motion/launch-80x24.gif differ diff --git a/docs/screenshots/0.8/motion/launch-cascade-120x40.png b/docs/screenshots/0.8/motion/launch-cascade-120x40.png new file mode 100644 index 0000000..1188845 Binary files /dev/null and b/docs/screenshots/0.8/motion/launch-cascade-120x40.png differ diff --git a/docs/screenshots/0.8/motion/launch-settled-120x40.png b/docs/screenshots/0.8/motion/launch-settled-120x40.png new file mode 100644 index 0000000..c690587 Binary files /dev/null and b/docs/screenshots/0.8/motion/launch-settled-120x40.png differ diff --git a/docs/screenshots/0.8/motion/launch-splash-120x40.png b/docs/screenshots/0.8/motion/launch-splash-120x40.png new file mode 100644 index 0000000..d93a725 Binary files /dev/null and b/docs/screenshots/0.8/motion/launch-splash-120x40.png differ diff --git a/docs/screenshots/0.8/motion/pages-80x24.gif b/docs/screenshots/0.8/motion/pages-80x24.gif new file mode 100644 index 0000000..367b9bb Binary files /dev/null and b/docs/screenshots/0.8/motion/pages-80x24.gif differ diff --git a/docs/screenshots/0.8/motion/palette-80x24.gif b/docs/screenshots/0.8/motion/palette-80x24.gif new file mode 100644 index 0000000..c9cf7d0 Binary files /dev/null and b/docs/screenshots/0.8/motion/palette-80x24.gif differ diff --git a/docs/screenshots/0.8/motion/palette-dialog-open-120x40.png b/docs/screenshots/0.8/motion/palette-dialog-open-120x40.png new file mode 100644 index 0000000..fee2a33 Binary files /dev/null and b/docs/screenshots/0.8/motion/palette-dialog-open-120x40.png differ diff --git a/docs/screenshots/0.8/motion/palette-dialog-pop-120x40.png b/docs/screenshots/0.8/motion/palette-dialog-pop-120x40.png new file mode 100644 index 0000000..27933dc Binary files /dev/null and b/docs/screenshots/0.8/motion/palette-dialog-pop-120x40.png differ diff --git a/docs/screenshots/0.8/motion/theme-80x24.gif b/docs/screenshots/0.8/motion/theme-80x24.gif new file mode 100644 index 0000000..5bcc1b6 Binary files /dev/null and b/docs/screenshots/0.8/motion/theme-80x24.gif differ diff --git a/docs/screenshots/0.8/motion/theme-toast-120x40.png b/docs/screenshots/0.8/motion/theme-toast-120x40.png new file mode 100644 index 0000000..32af5d2 Binary files /dev/null and b/docs/screenshots/0.8/motion/theme-toast-120x40.png differ diff --git a/scripts/capture_motion.py b/scripts/capture_motion.py new file mode 100644 index 0000000..a5830ce --- /dev/null +++ b/scripts/capture_motion.py @@ -0,0 +1,206 @@ +#!/usr/bin/env python3 +"""Record Alt's motion as GIF clips through a real PTY (M05). + +Usage: capture_motion.py [CLIP ...] [--out DIR] [--sizes 80x24,120x40] [--fps 20] + capture_motion.py --check # bandwidth and idle regression check, no GIFs + +Runs the deterministic fixture engine (no weights, no network). Every byte Alt +writes is recorded with its arrival time, then replayed into a terminal emulator +and sampled at a fixed frame rate, so a clip shows exactly what a terminal would +have shown. It also reports bytes written per clip, the bandwidth cost of +motion, alongside a motion-off baseline. Needs pyte and Pillow with DejaVu fonts. +""" +import argparse, fcntl, json, os, pty, select, struct, subprocess, sys, tempfile, termios, time +from pathlib import Path + +import pyte + +repo = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(repo / "scripts")) +from capture_screens import FIXTURE_CONFIG # noqa: E402 + +binary = Path(os.environ.get("ALT_TEST_BINARY", repo / "target/debug/alt")).resolve() +fixture = repo / "tests/fixtures/acp_engine.py" + +# (seconds after the previous step, keys); the clip ends `tail` seconds after the last key. +CLIPS = { + "launch": {"steps": [], "tail": 1.6}, + "pages": {"steps": [(1.2, b"\x1b2"), (0.7, b"\x1b7"), (0.7, b"\x1b3"), (0.7, b"\x1b1")], "tail": 0.6}, + "palette": {"steps": [(1.2, b"\x10"), (0.6, b"the"), (0.5, b"me"), (0.7, b"\x1b")], "tail": 0.6}, + "theme": {"steps": [(1.2, b"\x10"), (0.4, b"setting: theme"), (0.6, b"\r"), (0.8, b"\x1b[B"), + (0.3, b"\x1b[B"), (0.3, b"\r"), (0.6, b"\x10"), (0.4, b"setting: theme"), + (0.6, b"\r"), (0.6, b"\r")], "tail": 1.4}, +} + + +# Stills (seconds into the clip) saved as PNG at the wide size: the key moments. +STILLS = { + "launch": {"splash": 0.45, "cascade": 0.8, "settled": 1.5}, + "palette": {"dialog-pop": 1.26, "dialog-open": 1.9}, + "theme": {"toast": 4.0}, +} +# GIFs kept in git (each under the 1 MiB repository limit); others are stills. +GIF_SIZES = {"launch": ("80x24", "120x40"), "pages": ("80x24",), "palette": ("80x24",), "theme": ("80x24",)} + + +def record(clip, columns, lines, motion="full"): + """Run one clip and return [(seconds, bytes)] of everything Alt wrote.""" + plan = CLIPS[clip] + with tempfile.TemporaryDirectory(prefix="alt-motion-") as directory: + root = Path(directory) + project = root / "project" + project.mkdir() + (project / "README.md").write_text("Fixture project for motion clips.\n") + state = root / "state" + state.mkdir(mode=0o700) + (state / "config.toml").write_text(FIXTURE_CONFIG) + (state / "preferences.toml").write_text(f'project = "{project}"\nmouse = false\n') + master, slave = pty.openpty() + fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", lines, columns, 0, 0)) + env = {**os.environ, "TERM": "xterm-256color", "COLORTERM": "truecolor", "ALT_MOTION": motion} + started = time.monotonic() + process = subprocess.Popen([str(binary), "--data-dir", str(state), "--engine", str(fixture), "tui"], + stdin=slave, stdout=slave, stderr=slave, cwd=project, env=env) + chunks = [] + + def pump(until): + while (left := until - time.monotonic()) > 0: + if select.select([master], [], [], min(left, 0.01))[0]: + chunks.append((time.monotonic() - started, os.read(master, 1 << 20))) + + try: + for delay, keys in plan["steps"]: + pump(time.monotonic() + delay) + os.write(master, keys) + pump(time.monotonic() + plan["tail"]) + finally: + process.terminate() + try: + process.wait(timeout=8) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + os.close(master) + os.close(slave) + return chunks + + +def frames(chunks, columns, lines, fps): + """Replay recorded output and yield (seconds, screen) at a fixed rate.""" + screen = pyte.Screen(columns, lines) + stream = pyte.ByteStream(screen) + end = chunks[-1][0] if chunks else 0 + index = 0 + step = 1 / fps + t = 0.0 + while t <= end + step: + while index < len(chunks) and chunks[index][0] <= t: + stream.feed(chunks[index][1]) + index += 1 + yield t, screen + t += step + + +def image(screen, cell=(7, 15), size=12): + from PIL import Image, ImageDraw, ImageFont + fonts = Path("/usr/share/fonts/truetype/dejavu") + normal = ImageFont.truetype(str(fonts / "DejaVuSansMono.ttf"), size) + bold = ImageFont.truetype(str(fonts / "DejaVuSansMono-Bold.ttf"), size) + w, h = cell + picture = Image.new("RGB", (screen.columns * w, screen.lines * h), "#0f141d") + draw = ImageDraw.Draw(picture) + named = {"default": "0f141d", "black": "000000", "white": "e0e7ef"} + for y in range(screen.lines): + row = screen.buffer[y] + for x in range(screen.columns): + c = row[x] + bg = named.get(c.bg, c.bg) + fg = "e0e7ef" if c.fg == "default" else named.get(c.fg, c.fg) + if len(bg) == 6: + draw.rectangle((x * w, y * h, x * w + w, y * h + h), fill="#" + bg) + if c.data.strip() and len(fg) == 6: + draw.text((x * w, y * h), c.data, font=bold if c.bold else normal, fill="#" + fg) + return picture + + +def gif(chunks, columns, lines, fps, destination): + """Write a GIF; identical consecutive frames merge into one longer frame.""" + pictures, durations, last = [], [], None + for _, screen in frames(chunks, columns, lines, fps): + key = "\n".join(screen.display) + repr([[(c.fg, c.bg) for c in screen.buffer[y].values()] for y in range(lines)]) + if key == last: + durations[-1] += round(1000 / fps) + continue + last = key + pictures.append(image(screen).convert("P", palette=1, colors=128)) # 1 = Image.ADAPTIVE + durations.append(round(1000 / fps)) + destination.parent.mkdir(parents=True, exist_ok=True) + pictures[0].save(destination, save_all=True, append_images=pictures[1:], duration=durations, + loop=0, optimize=True, disposal=1) + return len(pictures) + + +def idle_bytes(chunks, after): + return sum(len(c) for t, c in chunks if t >= after) + + +def check(sizes): + """Fail when motion costs more than ~4x the bytes of the same session with + motion off, or when a settled, idle screen keeps writing.""" + failures = [] + for size in sizes: + columns, lines = (int(n) for n in size.split("x")) + for clip in ("pages", "palette", "theme"): + full = sum(len(c) for _, c in record(clip, columns, lines)) + off = sum(len(c) for _, c in record(clip, columns, lines, motion="off")) + ok = full <= 4 * off + 20_000 + print(f"{'PASS' if ok else 'FAIL'} {clip} {size}: {full} bytes with motion, {off} without") + ok or failures.append(clip) + CLIPS["idle"] = {"steps": [], "tail": 4.0} + full = idle_bytes(record("idle", columns, lines), 2.5) + off = idle_bytes(record("idle", columns, lines, motion="off"), 2.5) + ok = full <= off + 600 + print(f"{'PASS' if ok else 'FAIL'} idle {size}: {full} bytes in the settled 1.5 s with motion, {off} without") + ok or failures.append("idle") + return 1 if failures else 0 + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("clips", nargs="*", default=sorted(CLIPS)) + parser.add_argument("--out", type=Path, default=repo / "docs/screenshots/0.8/motion") + parser.add_argument("--sizes", default="80x24,120x40") + parser.add_argument("--fps", type=int, default=20) + parser.add_argument("--no-gif", action="store_true", help="measure bytes only") + parser.add_argument("--check", action="store_true", help="bandwidth/idle regression check") + args = parser.parse_args() + if args.check: + raise SystemExit(check(args.sizes.split(","))) + report = [] + for clip in args.clips: + for size in args.sizes.split(","): + columns, lines = (int(n) for n in size.split("x")) + chunks = record(clip, columns, lines) + baseline = record(clip, columns, lines, motion="off") + row = {"clip": clip, "size": size, "bytes_full": sum(len(c) for _, c in chunks), + "bytes_off": sum(len(c) for _, c in baseline)} + if not args.no_gif and size in GIF_SIZES.get(clip, ()): + destination = args.out / f"{clip}-{size}.gif" + row["frames"] = gif(chunks, columns, lines, args.fps, destination) + row["gif_bytes"] = destination.stat().st_size + if not args.no_gif and columns >= 120: + wanted = sorted(STILLS.get(clip, {}).items(), key=lambda kv: kv[1]) + for t, screen in frames(chunks, columns, lines, 100): + while wanted and t >= wanted[0][1]: + name, _ = wanted.pop(0) + image(screen, cell=(10, 21), size=16).save(args.out / f"{clip}-{name}-{size}.png") + if not wanted: + break + report.append(row) + print(json.dumps(row), flush=True) + if not args.no_gif: + (args.out / "clips.json").write_text(json.dumps(report, indent=2) + "\n") + + +if __name__ == "__main__": + main() diff --git a/scripts/setup-cloud.sh b/scripts/setup-cloud.sh index ee59999..fb4db30 100644 --- a/scripts/setup-cloud.sh +++ b/scripts/setup-cloud.sh @@ -61,6 +61,7 @@ python3 scripts/smoke_task_tui.py python3 scripts/smoke_workbench_tui.py python3 scripts/smoke_verification_tui.py python3 scripts/smoke_practice_tui.py +python3 scripts/capture_motion.py --check python3 scripts/smoke_harness_tui.py python3 scripts/smoke_allowance_tui.py --engine /workspace/.alt-tools/goose python3 scripts/smoke_pc_recorder.py --engine /workspace/.alt-tools/goose diff --git a/scripts/smoke_allowance_tui.py b/scripts/smoke_allowance_tui.py index 1eee248..275ac83 100644 --- a/scripts/smoke_allowance_tui.py +++ b/scripts/smoke_allowance_tui.py @@ -60,8 +60,20 @@ def main(): offset = len(REQUESTS) def click(label): term.wait(label) - for _ in range(3): term.pump(.03) - y, text = next((y, line) for y, line in enumerate(term.screen.display) if label in line and 'Reconnect' in line and 'Send' in line) + # Poll like wait(): the composer's button row must be on + # screen (not a dialog or a frame still being received). + # The row must also hold still across two looks, so a + # transient layout is never the click target. + deadline = time.monotonic() + 10 + previous = None + while True: + term.pump(.1) + found = [(y, line) for y, line in enumerate(term.screen.display) if label in line and 'Reconnect' in line and 'Send' in line] + if (found and found == previous) or time.monotonic() > deadline: + break + previous = found + assert found, f'Missing the {label} button row\n' + '\n'.join(term.screen.display) + y, text = found[0] x = text.index(label) + 1 term.send(('\x1b[<0;{};{}M\x1b[<0;{};{}m'.format(x, y + 1, x, y + 1)).encode()) def choose(index): term.send(b'\x1b[B' * index + b'\r') diff --git a/scripts/smoke_pressure_tui.py b/scripts/smoke_pressure_tui.py index b930a38..01c7dde 100644 --- a/scripts/smoke_pressure_tui.py +++ b/scripts/smoke_pressure_tui.py @@ -22,6 +22,12 @@ def wait(text,timeout=5): if text in '\n'.join(screen.display):return (time.monotonic()-started)*1000 raise AssertionError('Missing '+text+'\n'+'\n'.join(screen.display)) def send(value):os.write(master,value) + def exit_wait(timeout=10): + # Keep reading while Alt exits, as a terminal does; an unread PTY blocks its last frame. + end=time.monotonic()+timeout + while proc.poll() is None and time.monotonic(), + /// Interface motion: full | reduced | off. `ALT_MOTION` overrides it. + #[serde(default = "default_motion")] + pub motion: String, } impl Default for Preferences { @@ -217,6 +220,7 @@ impl Default for Preferences { theme: crate::tui::theme::DEFAULT.to_owned(), layout: default_layout(), skills_disabled: Vec::new(), + motion: default_motion(), } } } @@ -279,6 +283,10 @@ fn default_theme() -> String { crate::tui::theme::DEFAULT.to_owned() } +fn default_motion() -> String { + "full".to_owned() +} + fn default_layout() -> String { "sidebar".to_owned() } diff --git a/src/tui/app.rs b/src/tui/app.rs index d48314d..f642415 100644 --- a/src/tui/app.rs +++ b/src/tui/app.rs @@ -361,8 +361,10 @@ pub struct App { pub recovery_dialog: Option>, pub project_missing: bool, pub theme: &'static crate::tui::theme::Theme, - /// Monotonic render counter; drives spinner animation. + /// Monotonic render counter. pub frame: u64, + /// Animation clock and transition state (M01). + pub motion: super::motion::Motion, pub layout: LayoutMode, pub home_selected: usize, pub connection_selected: usize, @@ -468,6 +470,7 @@ impl App { }; let (tx, rx) = mpsc::channel(32); let theme = crate::tui::theme::by_name(preferences.theme.as_str()); + let motion = super::motion::Motion::new(super::motion::Level::resolve(&preferences.motion)); let layout = LayoutMode::from_saved(&preferences.layout); let mut app = Self { workbench: Default::default(), @@ -488,6 +491,7 @@ impl App { project_missing: false, theme, frame: 0, + motion, layout, home_selected: 0, connection_selected: 0, @@ -575,7 +579,7 @@ impl App { /// `setting_action` and `settings_all_items` exactly. pub fn settings_tab_indexes(tab: usize) -> &'static [usize] { const TABS: [&[usize]; 5] = [ - &[2, 3, 4], + &[2, 3, 4, 23], &[0, 19, 21, 20, 10, 11, 16], &[8, 17, 12], &[1, 5, 6, 22, 9, 15, 18], @@ -729,6 +733,11 @@ impl App { "Detect an NVIDIA GPU and install or select a CUDA 12 llama-server; CPU stays default." .into(), ), + ( + format!("Motion: {}", self.motion.level.label()), + "Full, Reduced (fades only) or Off. ALT_MOTION overrides; the Linux console is always Off." + .into(), + ), ] } @@ -966,6 +975,35 @@ impl App { pub fn notify(&mut self, text: impl Into) { self.status = text.into(); self.status_error = false; + let lowered = self.status.to_lowercase(); + let tone = if ["fail", "could not", "cannot", "error", "denied"] + .iter() + .any(|word| lowered.contains(word)) + { + super::motion::Tone::Bad + } else if [ + "saved", + "connected", + "changed", + "applied", + "completed", + "passed", + "ready", + ] + .iter() + .any(|word| lowered.contains(word)) + { + super::motion::Tone::Good + } else { + super::motion::Tone::Info + }; + let text = self.status.clone(); + self.motion.toast(&text, tone); + } + /// Status-line progress without a floating notice (frequent stage updates). + pub fn progress_status(&mut self, text: impl Into) { + self.status = text.into(); + self.status_error = false; } /// N08: Ctrl+L cycles Sidebar → Top tabs → Bottom tabs → Split and back. pub fn cycle_layout(&mut self) -> Result<()> { @@ -1414,7 +1452,7 @@ impl App { self.add_message("Notice", &error); self.error(error); } - workspace::Update::Progress(progress) => self.notify(progress.stage), + workspace::Update::Progress(progress) => self.progress_status(progress.stage), workspace::Update::Inference(status) => { let seen = self .inference_status @@ -2791,14 +2829,25 @@ pub async fn run( "Open Alt in a terminal, or use `alt run` in a script" ); let mut app = App::load(root, engine, profile)?; - let mut terminal = ratatui::try_init()?; + // try_init enters raw mode and the alternate screen and installs the panic + // hook; drawing goes through a buffered backend so each frame reaches the + // terminal in one write, wrapped in a synchronized update. Terminals never + // show half a frame, even when motion repaints the whole screen. + let _ = ratatui::try_init()?; + let mut terminal = ratatui::Terminal::new(ratatui::backend::CrosstermBackend::new( + std::io::BufWriter::with_capacity(1 << 20, std::io::stdout()), + ))?; let _restore = Restore; execute!(std::io::stdout(), EnableBracketedPaste)?; if app.preferences.mouse { execute!(std::io::stdout(), EnableMouseCapture)?; } let mut events = EventStream::new(); - let mut tick = tokio::time::interval(Duration::from_millis(60)); + // M01: adaptive frame pacing. 16 ms while something animates, 60 ms when + // idle; any input or update redraws on the next 16 ms boundary at most. + let frame_timer = tokio::time::sleep(Duration::ZERO); + tokio::pin!(frame_timer); + let mut last_draw = tokio::time::Instant::now(); let mut hardware = tokio::spawn(runtime::hardware()); let mut hardware_pending = true; let shutdown = crate::process::shutdown_signal(); @@ -2809,7 +2858,14 @@ pub async fn run( while !app.quit { tokio::select! { _=&mut shutdown=>{app.quit=true;}, - _=tick.tick()=>{terminal.draw(|frame|view::draw(frame,&mut app))?;}, + _=&mut frame_timer=>{ + crossterm::queue!(terminal.backend_mut(),crossterm::terminal::BeginSynchronizedUpdate)?; + terminal.draw(|frame|view::draw(frame,&mut app))?; + execute!(terminal.backend_mut(),crossterm::terminal::EndSynchronizedUpdate)?; + last_draw=tokio::time::Instant::now(); + frame_timer.as_mut().reset(last_draw+app.motion.frame_period()); + continue; + }, result=&mut hardware,if hardware_pending=>{hardware_pending=false;if let Ok(info)=result{app.hardware=info;}}, update=async{app.workspace.as_mut().expect("guarded workspace").updates.recv().await},if app.workspace.is_some()=>{ let result=if let Some(update)=update{app.workspace_update(update)}else{app.workspace=None;app.connected=false;app.connecting=false;app.busy=false;Ok(())}; @@ -2830,6 +2886,13 @@ pub async fn run( if let Err(error)=result{app.error(error);} } } + // Something changed: show it within one fast frame. + let soon = last_draw + super::motion::ACTIVE_FRAME; + if frame_timer.deadline() > soon { + frame_timer + .as_mut() + .reset(soon.max(tokio::time::Instant::now())); + } } if let Some(job) = app.job.take() { job.cancel.store(true, Ordering::Relaxed); diff --git a/src/tui/fx.rs b/src/tui/fx.rs new file mode 100644 index 0000000..26da915 --- /dev/null +++ b/src/tui/fx.rs @@ -0,0 +1,231 @@ +//! Buffer effects applied after widgets render: fades, slides, dims, shadows and +//! clipped reveals. They only recolour or move cells that were already drawn, +//! so layout, hit targets and text content are exactly what the widgets made. +use super::motion::blend; +use ratatui::buffer::{Buffer, Cell}; +use ratatui::layout::Rect; +use ratatui::style::Color; + +fn rgb(color: Color, fallback: Color) -> Color { + match color { + Color::Reset => fallback, + other => other, + } +} + +/// Blend every cell's colours in `area` toward `toward` by `amount` (0..1). +pub fn fade(buf: &mut Buffer, area: Rect, toward: Color, amount: f64, text: Color) { + if amount <= 0.0 { + return; + } + let area = area.intersection(buf.area); + for y in area.top()..area.bottom() { + for x in area.left()..area.right() { + let cell = &mut buf[(x, y)]; + cell.fg = blend(rgb(cell.fg, text), toward, amount); + cell.bg = blend(rgb(cell.bg, toward), toward, amount); + } + } +} + +/// Shift the cells of `area` right by `dx`, filling the gap with `bg`. +pub fn slide_right(buf: &mut Buffer, area: Rect, dx: u16, bg: Color) { + let area = area.intersection(buf.area); + if dx == 0 || area.width == 0 { + return; + } + for y in area.top()..area.bottom() { + let row: Vec = (area.left()..area.right()) + .map(|x| buf[(x, y)].clone()) + .collect(); + for (i, x) in (area.left()..area.right()).enumerate() { + let cell = &mut buf[(x, y)]; + if (i as u16) < dx { + cell.reset(); + cell.bg = bg; + } else { + *cell = row[i - dx as usize].clone(); + } + } + // A wide glyph cut by the shift would leave half a character behind. + let edge = area.left() + dx.min(area.width - 1); + if buf[(edge, y)].symbol().is_empty() { + buf[(edge, y)].set_symbol(" "); + } + } +} + +pub fn snapshot(buf: &Buffer, area: Rect) -> Vec { + let area = area.intersection(buf.area); + let mut cells = Vec::with_capacity(area.area() as usize); + for y in area.top()..area.bottom() { + for x in area.left()..area.right() { + cells.push(buf[(x, y)].clone()); + } + } + cells +} + +/// Grow `rect` from `scale` of its size about its centre. +pub fn scaled(rect: Rect, scale: f64) -> Rect { + let scale = scale.clamp(0.0, 1.2); + let w = ((rect.width as f64 * scale).round() as u16).clamp(1, rect.width); + let h = ((rect.height as f64 * scale).round() as u16).clamp(1, rect.height); + Rect::new( + rect.x + (rect.width - w) / 2, + rect.y + (rect.height - h) / 2, + w, + h, + ) +} + +/// Keep only the part of a freshly drawn dialog inside `visible`; cells outside +/// return to what was beneath (`before`, captured over `area`). +pub fn clip_to(buf: &mut Buffer, area: Rect, before: &[Cell], dialog: Rect, visible: Rect) { + let area = area.intersection(buf.area); + let width = area.width as usize; + for y in dialog.top()..dialog.bottom() { + for x in dialog.left()..dialog.right() { + if !area.contains((x, y).into()) || visible.contains((x, y).into()) { + continue; + } + let index = (y - area.y) as usize * width + (x - area.x) as usize; + if let Some(cell) = before.get(index) { + buf[(x, y)] = cell.clone(); + } + } + } +} + +/// A soft drop shadow one row below and two columns right of `rect`. +pub fn shadow(buf: &mut Buffer, rect: Rect, color: Color, amount: f64) { + let bounds = buf.area; + let right = Rect::new(rect.right(), rect.y + 1, 2, rect.height.saturating_sub(1)); + let below = Rect::new(rect.x + 2, rect.bottom(), rect.width, 1); + for part in [right, below] { + let part = part.intersection(bounds); + for y in part.top()..part.bottom() { + for x in part.left()..part.right() { + let cell = &mut buf[(x, y)]; + cell.bg = blend(rgb(cell.bg, color), color, amount); + cell.fg = blend(rgb(cell.fg, color), color, amount * 0.8); + } + } + } +} + +/// Fade a closed dialog's colours out over what is now beneath it. The new +/// screen's text is shown from the first frame; only the dialog's colours +/// linger, so nothing stale can be read or clicked. +pub fn fade_out(buf: &mut Buffer, rect: Rect, cells: &[Cell], t: f64, text: Color, bg: Color) { + let area = rect.intersection(buf.area); + if area != rect { + return; + } + let mut iter = cells.iter(); + for y in rect.top()..rect.bottom() { + for x in rect.left()..rect.right() { + let Some(old) = iter.next() else { return }; + let cell = &mut buf[(x, y)]; + let (new_fg, new_bg) = (rgb(cell.fg, text), rgb(cell.bg, bg)); + cell.fg = blend(rgb(old.fg, text), new_fg, t); + cell.bg = blend(rgb(old.bg, bg), new_bg, t); + } + } +} + +/// Horizontal gradient across the foreground of `area`. +pub fn gradient(buf: &mut Buffer, area: Rect, from: Color, to: Color) { + let area = area.intersection(buf.area); + let span = area.width.saturating_sub(1).max(1) as f64; + for y in area.top()..area.bottom() { + for x in area.left()..area.right() { + let cell = &mut buf[(x, y)]; + if cell.symbol() != " " { + cell.fg = blend(from, to, (x - area.x) as f64 / span); + } + } + } +} + +/// Tint the background of `area` toward `color`. +pub fn tint(buf: &mut Buffer, area: Rect, color: Color, amount: f64, bg: Color) { + let area = area.intersection(buf.area); + for y in area.top()..area.bottom() { + for x in area.left()..area.right() { + let cell = &mut buf[(x, y)]; + cell.bg = blend(rgb(cell.bg, bg), color, amount); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn buffer(text: &str) -> Buffer { + let mut buf = Buffer::empty(Rect::new(0, 0, text.chars().count() as u16, 1)); + buf.set_string( + 0, + 0, + text, + ratatui::style::Style::default().bg(Color::Rgb(0, 0, 0)), + ); + buf + } + fn row(buf: &Buffer) -> String { + (0..buf.area.width).map(|x| buf[(x, 0)].symbol()).collect() + } + + #[test] + fn slide_moves_cells_and_clears_the_gap() { + let mut buf = buffer("abcdef"); + let area = buf.area; + slide_right(&mut buf, area, 2, Color::Rgb(1, 2, 3)); + assert_eq!(row(&buf), " abcd"); + assert_eq!(buf[(0, 0)].bg, Color::Rgb(1, 2, 3)); + } + + #[test] + fn fade_keeps_text_and_moves_colour() { + let mut buf = buffer("hi"); + buf[(0, 0)].fg = Color::Rgb(200, 200, 200); + let area = buf.area; + fade(&mut buf, area, Color::Rgb(0, 0, 0), 0.5, Color::White); + assert_eq!(row(&buf), "hi"); + assert_eq!(buf[(0, 0)].fg, Color::Rgb(100, 100, 100)); + } + + #[test] + fn clipped_reveal_restores_the_backdrop_outside_the_visible_box() { + let mut buf = Buffer::empty(Rect::new(0, 0, 10, 5)); + let before = snapshot(&buf, buf.area); + buf.set_string(2, 1, "xxxxx", ratatui::style::Style::default()); + buf.set_string(2, 3, "yyyyy", ratatui::style::Style::default()); + let dialog = Rect::new(2, 1, 5, 3); + let visible = scaled(dialog, 0.5); + assert!(dialog.contains(visible.as_position())); + let area = buf.area; + clip_to(&mut buf, area, &before, dialog, visible); + assert_eq!( + buf[(2, 1)].symbol(), + " ", + "outside the reveal returns to the backdrop" + ); + assert_eq!(scaled(dialog, 1.0), dialog); + } + + #[test] + fn fade_out_shows_the_new_text_at_once_and_fades_colours() { + let mut buf = buffer("new"); + let mut old = buffer("old"); + for x in 0..3 { + old[(x, 0)].bg = Color::Rgb(200, 200, 200); + } + let cells = snapshot(&old, old.area); + let area = buf.area; + fade_out(&mut buf, area, &cells, 0.25, Color::White, Color::Black); + assert_eq!(row(&buf), "new", "no stale text, even early"); + assert_eq!(buf[(0, 0)].bg, Color::Rgb(150, 150, 150)); + } +} diff --git a/src/tui/keys.rs b/src/tui/keys.rs index 71c775a..6642660 100644 --- a/src/tui/keys.rs +++ b/src/tui/keys.rs @@ -6,6 +6,7 @@ use std::sync::atomic::Ordering; impl App { pub fn key(&mut self, key: KeyEvent) -> Result<()> { + self.motion.dismiss_splash(); let ctrl = key.modifiers.contains(KeyModifiers::CONTROL); let alt = key.modifiers.contains(KeyModifiers::ALT); if key.code == KeyCode::Esc @@ -385,7 +386,11 @@ impl App { } match action { "quit" => { - if self.busy || self.connecting || self.job.is_some() { + // A disposable view refresh yields to quitting; real work asks. + if self.busy + || self.connecting + || self.job.as_ref().is_some_and(|job| !job.replaceable) + { self.dialog=Some(Dialog::Confirm{title:"Leave Alt?".into(),body:"Your conversation is saved. The active task and any download will stop; partial downloads can be resumed later.".into(),action:ConfirmAction::Quit,selected:0}); } else { self.quit = true; @@ -676,6 +681,7 @@ impl App { 20 => return self.manager_action("params-menu", serde_json::json!({})), 21 => return self.manager_action("probe-run", serde_json::json!({})), 22 => return self.manager_action("cuda-runtime", serde_json::json!({})), + 23 => return self.manager_action("motion", serde_json::json!({})), 12 => return self.manager_action("manage-tools", serde_json::json!({})), 13 => return self.manager_action("manage-storage", serde_json::json!({})), 14 => return self.manager_action("manage-models", serde_json::json!({})), @@ -1004,6 +1010,17 @@ impl App { } pub fn mouse(&mut self, kind: MouseEventKind, x: u16, y: u16) -> Result<()> { + if matches!(kind, MouseEventKind::Moved | MouseEventKind::Drag(_)) { + self.motion.hover = Some((x, y)); + return Ok(()); + } + if self.motion.splash().is_some() { + // A click cannot aim at a hidden screen: it only ends the splash. + if matches!(kind, MouseEventKind::Down(_)) { + self.motion.dismiss_splash(); + } + return Ok(()); + } if matches!(kind, MouseEventKind::ScrollUp | MouseEventKind::ScrollDown) { return self.key(KeyEvent::new( if kind == MouseEventKind::ScrollUp { @@ -1017,12 +1034,17 @@ impl App { if kind != MouseEventKind::Down(MouseButton::Left) { return Ok(()); } - let hit = self + self.motion.hover = Some((x, y)); + let found = self .hits .iter() .rev() .find(|(rect, _)| rect.contains((x, y).into())) - .map(|(_, hit)| hit.clone()); + .cloned(); + if let Some((rect, _)) = &found { + self.motion.pressed(*rect); + } + let hit = found.map(|(_, hit)| hit); match hit { Some(Hit::Nav(page)) => self.set_page(page), Some(Hit::Home(index)) => { diff --git a/src/tui/management.rs b/src/tui/management.rs index ec1d722..92e5ebb 100644 --- a/src/tui/management.rs +++ b/src/tui/management.rs @@ -206,6 +206,43 @@ impl App { ); return Ok(()); } + if action == "motion" { + let current = self.motion.level; + let items = crate::tui::motion::Level::ALL + .iter() + .map(|level| { + ( + format!( + "{}{}", + level.label(), + if *level == current { + " · current" + } else { + "" + } + ), + level.describe().to_string(), + "motion-select".into(), + json!({"level":level.saved_name()}), + ) + }) + .collect(); + self.manager_menu( + "Motion", + "How much the interface animates. Input is never delayed; Off draws every frame in its final state.", + items, + ); + return Ok(()); + } + if action == "motion-select" { + let name = state["level"].as_str().context("Motion level")?; + let level = crate::tui::motion::Level::from_name(name); + self.preferences.motion = level.saved_name().to_owned(); + self.preferences.save(&self.root)?; + self.motion.set_level(level); + self.notify(format!("Motion: {}. {}", level.label(), level.describe())); + return Ok(()); + } if action == "theme-select" { let name = state["name"].as_str().context("Theme")?; self.theme = crate::tui::theme::by_name(name); diff --git a/src/tui/mod.rs b/src/tui/mod.rs index 8a6dfbf..c46c5f0 100644 --- a/src/tui/mod.rs +++ b/src/tui/mod.rs @@ -1,6 +1,8 @@ mod app; +mod fx; mod input; mod keys; +pub(crate) mod motion; mod task; pub(crate) mod theme; mod view; diff --git a/src/tui/motion.rs b/src/tui/motion.rs new file mode 100644 index 0000000..f5f914d --- /dev/null +++ b/src/tui/motion.rs @@ -0,0 +1,693 @@ +//! Motion: one clock, easing curves, keyed tweens and the transition state the +//! renderer reads each frame. Every animation is a pure function of time, so a +//! frame drawn twice at the same instant is identical and tests can pin the +//! clock. Motion never delays input or hides state: transitions are short, +//! text is never withheld, and `Off` renders every frame in its final state. +use ratatui::layout::Rect; +use ratatui::style::Color; +use std::cell::Cell; +use std::collections::HashMap; +use std::time::{Duration, Instant}; + +/// How much the interface moves. Saved as `preferences.motion`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Level { + /// Slides, pops, glides, glow and the startup splash. + #[default] + Full, + /// Fades and colour changes only; nothing slides, scales or breathes. + Reduced, + /// Every frame is drawn in its final state. + Off, +} + +impl Level { + pub const ALL: [Level; 3] = [Level::Full, Level::Reduced, Level::Off]; + pub fn saved_name(self) -> &'static str { + match self { + Level::Full => "full", + Level::Reduced => "reduced", + Level::Off => "off", + } + } + pub fn label(self) -> &'static str { + match self { + Level::Full => "Full", + Level::Reduced => "Reduced", + Level::Off => "Off", + } + } + pub fn describe(self) -> &'static str { + match self { + Level::Full => "Slides, pops, gliding meters, focus glow and a short splash.", + Level::Reduced => "Fades and colour changes only; nothing slides or scales.", + Level::Off => "No animation. Every frame is drawn in its final state.", + } + } + pub fn from_name(name: &str) -> Self { + match name.trim().to_ascii_lowercase().as_str() { + "reduced" | "reduce" | "minimal" => Level::Reduced, + "off" | "none" | "0" | "false" => Level::Off, + _ => Level::Full, + } + } + /// The saved preference, overridden by `ALT_MOTION`. Terminals that cannot + /// show colour blends (the Linux console, `dumb`) and `NO_MOTION` turn it off. + /// Unit tests render in the final state unless they opt in. + pub fn resolve(saved: &str) -> Self { + Self::resolve_with( + saved, + std::env::var("ALT_MOTION").ok().as_deref(), + std::env::var("TERM").ok().as_deref(), + std::env::var_os("NO_MOTION").is_some(), + ) + } + pub fn resolve_with( + saved: &str, + env: Option<&str>, + term: Option<&str>, + no_motion: bool, + ) -> Self { + if let Some(value) = env.filter(|v| !v.trim().is_empty()) { + return Self::from_name(value); + } + if no_motion || matches!(term, Some("linux" | "dumb")) || cfg!(test) { + return Level::Off; + } + Self::from_name(saved) + } + pub fn moves(self) -> bool { + self == Level::Full + } + pub fn fades(self) -> bool { + self != Level::Off + } +} + +pub fn ease_out_cubic(t: f64) -> f64 { + let t = t.clamp(0.0, 1.0); + 1.0 - (1.0 - t).powi(3) +} +pub fn ease_in_out_cubic(t: f64) -> f64 { + let t = t.clamp(0.0, 1.0); + if t < 0.5 { + 4.0 * t * t * t + } else { + 1.0 - (-2.0 * t + 2.0).powi(3) / 2.0 + } +} +/// Overshoots slightly before settling: the "pop" used for dialogs. +pub fn ease_out_back(t: f64) -> f64 { + let t = t.clamp(0.0, 1.0); + let c1 = 1.70158; + let c3 = c1 + 1.0; + 1.0 + c3 * (t - 1.0).powi(3) + c1 * (t - 1.0).powi(2) +} + +/// Quantise progress into `steps` equal stages. Whole-area effects repaint +/// every cell they touch, so a transition drawn in a few distinct stages costs +/// a few repaints (identical frames diff to nothing) instead of one per 16 ms +/// frame — kind to slow SSH links and terminals that read output lazily. +pub fn stepped(t: f64, steps: u32) -> f64 { + let steps = steps.max(1) as f64; + ((t.clamp(0.0, 1.0) * steps).floor() / steps).min(1.0) +} + +/// Linear blend of two colours; `t = 0` is `a`, `t = 1` is `b`. Named and +/// indexed colours cannot be mixed, so they switch at the midpoint. +pub fn blend(a: Color, b: Color, t: f64) -> Color { + let t = t.clamp(0.0, 1.0); + match (a, b) { + (Color::Rgb(r1, g1, b1), Color::Rgb(r2, g2, b2)) => { + let mix = |x: u8, y: u8| (x as f64 + (y as f64 - x as f64) * t).round() as u8; + Color::Rgb(mix(r1, r2), mix(g1, g2), mix(b1, b2)) + } + _ if t < 0.5 => a, + _ => b, + } +} + +/// Durations, in milliseconds, shared by the renderer and the docs. +pub const PAGE_MS: f64 = 190.0; +pub const MODAL_IN_MS: f64 = 170.0; +pub const MODAL_OUT_MS: f64 = 110.0; +pub const GLIDE_MS: f64 = 420.0; +pub const TOAST_MS: f64 = 3200.0; +pub const TOAST_EDGE_MS: f64 = 220.0; +pub const FLASH_MS: f64 = 650.0; +pub const PRESS_MS: f64 = 140.0; +pub const HOVER_MS: f64 = 120.0; +pub const SPLASH_MS: f64 = 720.0; +/// Frame period while something is animating, and while idle. +pub const ACTIVE_FRAME: Duration = Duration::from_millis(16); +pub const IDLE_FRAME: Duration = Duration::from_millis(60); + +#[derive(Debug, Clone, Copy)] +struct Tween { + from: f64, + to: f64, + start: f64, + duration: f64, +} + +impl Tween { + fn value(&self, now: f64) -> f64 { + let t = ((now - self.start) / self.duration).clamp(0.0, 1.0); + self.from + (self.to - self.from) * ease_out_cubic(t) + } + fn done(&self, now: f64) -> bool { + now >= self.start + self.duration + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Tone { + Info, + Good, + Bad, +} + +#[derive(Debug, Clone)] +pub struct Toast { + pub text: String, + pub tone: Tone, + pub born: f64, + /// Identical consecutive notices collapse into one card with a count. + pub count: u32, +} + +/// Cells of the last dialog drawn, kept so a closing dialog can fade out. +#[derive(Debug, Clone)] +pub struct Retained { + pub rect: Rect, + pub cells: Vec, +} + +#[derive(Debug)] +pub struct Motion { + pub level: Level, + epoch: Instant, + /// Pinned clock for tests and frame-by-frame captures (milliseconds). + pinned: Option, + now: f64, + tweens: HashMap<&'static str, Tween>, + pub page_since: Option, + pub last_page: Option, + pub modal_since: Option, + pub modal_key: Option, + pub modal_closing: Option<(f64, Retained)>, + pub modal_retained: Option, + /// Where the dialog drawn this frame sits; set by the dialog renderer. + pub dialog_rect: Option, + pub toasts: Vec, + /// Characters shown of a streaming reply: (message index, shown, last frame ms). + reveal: Option<(usize, f64, f64)>, + /// Tool id → (last seen status, flash start). + flashes: HashMap)>, + pub hover: Option<(u16, u16)>, + hover_rect: Option<(Rect, f64)>, + pub press: Option<(Rect, f64)>, + pub splash_until: Option, +} + +impl Default for Motion { + fn default() -> Self { + Self::new(Level::Off) + } +} + +impl Motion { + pub fn new(level: Level) -> Self { + Self { + level, + epoch: Instant::now(), + pinned: None, + now: 0.0, + tweens: HashMap::new(), + page_since: None, + last_page: None, + modal_since: None, + modal_key: None, + modal_closing: None, + modal_retained: None, + dialog_rect: None, + toasts: Vec::new(), + reveal: None, + flashes: HashMap::new(), + hover: None, + hover_rect: None, + press: None, + splash_until: level.moves().then_some(SPLASH_MS), + } + } + /// Pin the clock (milliseconds since start); `None` returns to real time. + #[cfg(test)] + pub fn pin(&mut self, ms: Option) { + self.pinned = ms; + self.tick(false); + } + pub fn set_level(&mut self, level: Level) { + self.level = level; + if !level.moves() { + self.splash_until = None; + } + if !level.fades() { + self.page_since = None; + self.modal_since = None; + self.modal_closing = None; + self.tweens.clear(); + self.reveal = None; + self.press = None; + self.hover_rect = None; + } + } + /// Advance the clock; called once at the start of every frame. `busy` + /// lets focus rings breathe while a task runs (and stay still otherwise). + pub fn tick(&mut self, busy: bool) -> f64 { + self.now = self + .pinned + .unwrap_or_else(|| self.epoch.elapsed().as_secs_f64() * 1000.0); + self.toasts.retain(|t| self.now - t.born < TOAST_MS); + // When the splash ends the interface cascades in like a page change. + if self.splash_until.is_some_and(|until| self.now >= until) { + self.splash_until = None; + self.page_since = Some(self.now); + } + FRAME.with(|f| { + f.set(Shared { + now: self.now, + level: self.level, + busy, + }) + }); + self.now + } + pub fn now(&self) -> f64 { + self.now + } + /// Progress `0..=1` of an animation that began at `since` and lasts `ms`. + pub fn progress(&self, since: Option, ms: f64) -> Option { + let since = since?; + let t = (self.now - since) / ms; + (t < 1.0).then(|| t.max(0.0)) + } + /// Glide a value toward `target`; returns the value to draw this frame. + pub fn glide(&mut self, key: &'static str, target: f64) -> f64 { + if !self.level.moves() { + self.tweens.remove(key); + return target; + } + let now = self.now; + match self.tweens.get(key).copied() { + Some(tween) if (tween.to - target).abs() < f64::EPSILON => tween.value(now), + Some(tween) => { + let from = tween.value(now); + self.tweens.insert( + key, + Tween { + from, + to: target, + start: now, + duration: GLIDE_MS, + }, + ); + from + } + None => { + // The first value is shown as is; only changes glide. + self.tweens.insert( + key, + Tween { + from: target, + to: target, + start: now - GLIDE_MS, + duration: GLIDE_MS, + }, + ); + target + } + } + } + /// Note the page drawn this frame; a change starts the page transition. + pub fn page(&mut self, page: u8) { + if self.last_page.is_some_and(|p| p != page) && self.level.fades() { + self.page_since = Some(self.now); + } + self.last_page = Some(page); + } + /// Note the dialog drawn this frame (`None` when none). Returns the progress + /// of its entrance, if still running. + pub fn modal(&mut self, key: Option) -> Option { + if key != self.modal_key { + if key.is_some() && self.level.fades() { + self.modal_since = Some(self.now); + self.modal_closing = None; + } else if key.is_none() { + self.modal_since = None; + if let Some(retained) = self.modal_retained.take() + && self.level.fades() + { + self.modal_closing = Some((self.now, retained)); + } + } + self.modal_key = key; + } + if self.modal_key.is_none() { + self.modal_retained = None; + } + self.progress(self.modal_since, MODAL_IN_MS) + } + pub fn closing(&mut self) -> Option<(f64, Retained)> { + let (since, retained) = self.modal_closing.clone()?; + match self.progress(Some(since), MODAL_OUT_MS) { + Some(t) => Some((t, retained)), + None => { + self.modal_closing = None; + None + } + } + } + pub fn toast(&mut self, text: &str, tone: Tone) { + let text = text.trim(); + if text.is_empty() || !self.level.fades() { + return; + } + if let Some(last) = self.toasts.last_mut() + && last.text == text + { + last.count += 1; + last.born = self.now; + return; + } + // One notice at a time, like the status line it echoes: a new notice + // replaces the old one at once, so nothing stale lingers on screen. + self.toasts.clear(); + self.toasts.push(Toast { + text: text.to_owned(), + tone, + born: self.now, + count: 1, + }); + } + /// How many characters of message `index` (of `len`) to show. Only replies + /// that grow while visible are revealed; history appears at once. + pub fn reveal(&mut self, index: usize, len: usize, streaming: bool) -> usize { + if !self.level.fades() { + self.reveal = None; + return len; + } + let now = self.now; + let (shown, last) = match self.reveal { + Some((i, shown, last)) if i == index => (shown, last), + _ if streaming => (0.0, now), + _ => { + self.reveal = Some((index, len as f64, now)); + return len; + } + }; + let behind = len as f64 - shown; + // Never fall more than ~a quarter second behind the model. + let rate = (behind * 4.0).max(120.0) / 1000.0; + let next = (shown + rate * (now - last).max(0.0)).min(len as f64); + self.reveal = Some((index, next, now)); + next.floor() as usize + } + /// Colour flash for a tool whose status just changed: progress `0..1`. + pub fn flash(&mut self, id: &str, status: &str) -> Option { + let now = self.now; + let fades = self.level.fades(); + let entry = self + .flashes + .entry(id.to_owned()) + .or_insert_with(|| (status.to_owned(), None)); + if entry.0 != status { + entry.0 = status.to_owned(); + entry.1 = fades.then_some(now); + } + let since = entry.1; + self.progress(since, FLASH_MS) + } + /// Hover highlight strength `0..=1` for the target under the pointer. + pub fn hover(&mut self, rect: Option) -> Option<(Rect, f64)> { + if !self.level.fades() { + return rect.map(|r| (r, 1.0)); + } + let rect = rect?; + let since = match self.hover_rect { + Some((r, since)) if r == rect => since, + _ => self.now, + }; + self.hover_rect = Some((rect, since)); + Some((rect, ((self.now - since) / HOVER_MS).clamp(0.0, 1.0))) + } + pub fn pressed(&mut self, rect: Rect) { + if self.level.fades() { + self.press = Some((rect, self.now)); + } + } + pub fn press(&self) -> Option<(Rect, f64)> { + let (rect, since) = self.press?; + self.progress(Some(since), PRESS_MS).map(|t| (rect, t)) + } + pub fn splash(&self) -> Option { + let until = self.splash_until?; + (self.now < until).then(|| self.now / until) + } + /// Any key or click ends the splash at once; it never holds input. + pub fn dismiss_splash(&mut self) { + if self.splash_until.take().is_some() && self.level.moves() { + self.page_since = Some(self.now); + } + } + /// True while something moves fast enough to need the 16 ms frame. + pub fn active(&self) -> bool { + let now = self.now; + let running = |since: Option, ms: f64| since.is_some_and(|s| now - s < ms); + running(self.page_since, PAGE_MS) + || running(self.modal_since, MODAL_IN_MS) + || self.modal_closing.is_some() + || self.splash().is_some() + || self.press().is_some() + || self.tweens.values().any(|t| !t.done(now)) + || self + .toasts + .iter() + .any(|t| now - t.born < TOAST_EDGE_MS || now - t.born > TOAST_MS - TOAST_EDGE_MS) + || self + .flashes + .values() + .any(|(_, since)| running(*since, FLASH_MS)) + || self.reveal.is_some_and(|(_, shown, _)| shown.fract() > 0.0) + || self + .hover_rect + .is_some_and(|(_, since)| now - since < HOVER_MS) + } + pub fn frame_period(&self) -> Duration { + if self.active() { + ACTIVE_FRAME + } else { + IDLE_FRAME + } + } +} + +#[derive(Debug, Clone, Copy)] +struct Shared { + now: f64, + level: Level, + busy: bool, +} + +thread_local! { + static FRAME: Cell = const { + Cell::new(Shared { + now: 0.0, + level: Level::Off, + busy: false, + }) + }; +} + +/// Milliseconds on the motion clock for the frame being drawn. +pub fn now() -> f64 { + FRAME.with(|f| f.get().now) +} +/// Slow 0..1 "breath" for focus rings while a task runs; flat when idle or +/// when motion is reduced or off, so an idle Alt writes nothing to the +/// terminal. Eight levels keep the ring to a few small repaints a second. +pub fn breath() -> f64 { + let shared = FRAME.with(|f| f.get()); + if !shared.level.moves() || !shared.busy { + return 0.0; + } + let phase = shared.now / 2600.0 * std::f64::consts::TAU; + stepped((1.0 - phase.cos()) / 2.0, 8) +} +/// Spinner frame from the clock, so speed does not depend on frame rate. +pub fn spin(frames: usize) -> usize { + ((now() / 90.0) as usize) % frames.max(1) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn easing_curves_start_at_zero_and_settle_at_one() { + for curve in [ease_out_cubic, ease_in_out_cubic, ease_out_back] { + assert!(curve(0.0).abs() < 1e-9); + assert!((curve(1.0) - 1.0).abs() < 1e-9); + } + assert!(ease_out_back(0.7) > 1.0, "the pop overshoots"); + assert!(ease_out_cubic(0.5) > 0.5, "ease-out leads"); + } + + #[test] + fn stepping_limits_distinct_frames() { + let stages: std::collections::BTreeSet = (0..=100) + .map(|i| (stepped(ease_out_cubic(i as f64 / 100.0), 5) * 1000.0) as u64) + .collect(); + assert_eq!(stages.len(), 6); + assert_eq!(stepped(0.0, 5), 0.0); + assert_eq!(stepped(1.0, 5), 1.0); + } + + #[test] + fn blending_mixes_rgb_and_switches_named_colours() { + let a = Color::Rgb(0, 0, 0); + let b = Color::Rgb(200, 100, 50); + assert_eq!(blend(a, b, 0.5), Color::Rgb(100, 50, 25)); + assert_eq!(blend(a, b, 2.0), b); + assert_eq!(blend(Color::Red, Color::Blue, 0.4), Color::Red); + assert_eq!(blend(Color::Red, Color::Blue, 0.6), Color::Blue); + } + + #[test] + fn level_resolution_respects_env_terminal_and_saved_choice() { + assert_eq!( + Level::resolve_with("full", Some("reduced"), None, false), + Level::Reduced + ); + assert_eq!( + Level::resolve_with("full", None, Some("linux"), false), + Level::Off + ); + assert_eq!(Level::resolve_with("full", None, None, true), Level::Off); + assert_eq!( + Level::resolve_with("reduced", Some("full"), Some("dumb"), false), + Level::Full + ); + for level in Level::ALL { + assert_eq!(Level::from_name(level.saved_name()), level); + } + } + + #[test] + fn glides_ease_toward_new_targets_and_skip_when_off() { + let mut m = Motion::new(Level::Full); + m.pin(Some(1000.0)); + assert_eq!(m.glide("ctx", 0.2), 0.2, "first value is not animated"); + assert_eq!( + m.glide("ctx", 0.8), + 0.2, + "a change starts from the shown value" + ); + assert!(m.active()); + m.pin(Some(1000.0 + GLIDE_MS / 2.0)); + let mid = m.glide("ctx", 0.8); + assert!(mid > 0.5 && mid < 0.8, "{mid}"); + m.pin(Some(1000.0 + GLIDE_MS + 1.0)); + assert_eq!(m.glide("ctx", 0.8), 0.8); + let mut off = Motion::new(Level::Off); + off.glide("ctx", 0.1); + assert_eq!(off.glide("ctx", 0.9), 0.9); + assert!(!off.active()); + } + + #[test] + fn page_and_modal_transitions_run_once_and_finish() { + let mut m = Motion::new(Level::Full); + m.splash_until = None; + m.pin(Some(0.0)); + m.page(1); + assert!(m.page_since.is_none(), "the first page does not animate"); + m.page(2); + assert_eq!(m.progress(m.page_since, PAGE_MS), Some(0.0)); + m.pin(Some(PAGE_MS + 1.0)); + assert_eq!(m.progress(m.page_since, PAGE_MS), None); + assert_eq!(m.modal(Some("menu".into())), Some(0.0)); + m.pin(Some(PAGE_MS + 50.0)); + assert!(m.modal(Some("menu".into())).is_some_and(|t| t > 0.2)); + m.modal_retained = Some(Retained { + rect: Rect::new(0, 0, 1, 1), + cells: vec![Default::default()], + }); + m.pin(Some(1000.0)); + assert_eq!(m.modal(None), None); + assert!(m.closing().is_some(), "closing dialogs fade out"); + m.pin(Some(1000.0 + MODAL_OUT_MS + 1.0)); + assert!(m.closing().is_none()); + assert!(!m.active()); + } + + #[test] + fn toasts_collapse_replace_and_expire() { + let mut m = Motion::new(Level::Reduced); + m.pin(Some(0.0)); + m.toast("Saved", Tone::Good); + m.toast("Saved", Tone::Good); + assert_eq!(m.toasts.len(), 1); + assert_eq!(m.toasts[0].count, 2); + for text in ["a", "b", "c", "d"] { + m.toast(text, Tone::Info); + } + assert_eq!(m.toasts.len(), 1, "a new notice replaces the old one"); + assert_eq!(m.toasts[0].text, "d"); + m.pin(Some(TOAST_MS + 1.0)); + assert!(m.toasts.is_empty()); + let mut off = Motion::new(Level::Off); + off.toast("Saved", Tone::Good); + assert!(off.toasts.is_empty(), "no toasts when motion is off"); + } + + #[test] + fn streaming_replies_catch_up_and_history_is_immediate() { + let mut m = Motion::new(Level::Full); + m.pin(Some(0.0)); + assert_eq!(m.reveal(0, 500, false), 500, "history shows at once"); + assert_eq!( + m.reveal(1, 400, true), + 0, + "a new streaming reply starts hidden" + ); + m.pin(Some(100.0)); + let shown = m.reveal(1, 400, true); + assert!((120..400).contains(&shown), "{shown}"); + m.pin(Some(400.0)); + assert_eq!(m.reveal(1, 400, true), 400, "never far behind"); + } + + #[test] + fn tool_status_changes_flash_once() { + let mut m = Motion::new(Level::Full); + m.pin(Some(0.0)); + assert_eq!(m.flash("t1", "pending"), None, "first sight does not flash"); + m.pin(Some(10.0)); + assert_eq!(m.flash("t1", "completed"), Some(0.0)); + m.pin(Some(10.0 + FLASH_MS)); + assert_eq!(m.flash("t1", "completed"), None); + } + + #[test] + fn splash_never_outlives_its_budget_and_can_be_dismissed() { + let mut m = Motion::new(Level::Full); + m.pin(Some(10.0)); + assert!(m.splash().is_some()); + m.dismiss_splash(); + assert!(m.splash().is_none()); + let mut m = Motion::new(Level::Full); + m.pin(Some(SPLASH_MS)); + assert!(m.splash().is_none()); + assert!(Motion::new(Level::Reduced).splash_until.is_none()); + } +} diff --git a/src/tui/view.rs b/src/tui/view.rs index 3aae90e..f834d76 100644 --- a/src/tui/view.rs +++ b/src/tui/view.rs @@ -2,7 +2,7 @@ // the per-frame theme instead of hard-coded values. #![allow(non_snake_case)] -use super::{app::*, input::Editor, theme}; +use super::{app::*, fx, input::Editor, motion, theme}; use crate::{display_text, models::human_bytes}; use ratatui::{ Frame, @@ -10,7 +10,8 @@ use ratatui::{ style::{Color, Modifier, Style}, text::{Line, Span, Text}, widgets::{ - Block, BorderType, Borders, Clear, Gauge, List, ListItem, ListState, Paragraph, Wrap, + Block, BorderType, Borders, Clear, Gauge, List, ListItem, ListState, Paragraph, Widget, + Wrap, }, }; @@ -62,7 +63,12 @@ fn block(title: impl Into>, focused: bool) -> Block<'static> { .border_type(BorderType::Rounded) .title(title) .title_style(style(ACCENT())) - .border_style(style(if focused { BORDER_FOCUSED() } else { BORDER() })) + .border_style(style(if focused { + // The focus ring breathes toward the second accent while a task runs. + motion::blend(BORDER_FOCUSED(), ACCENT2(), motion::breath() * 0.6) + } else { + BORDER() + })) .style(Style::default().bg(PANEL()).fg(TEXT())) } fn line(text: impl Into, color: Color) -> Line<'static> { @@ -114,10 +120,34 @@ fn buttons(frame: &mut Frame, app: &mut App, area: Rect, items: &[(&str, &'stati } } +/// Background jobs get the progress footer only once they have run for a +/// moment, so an instant refresh never shifts the whole layout up and back. +pub(crate) const JOB_FOOTER_DELAY: std::time::Duration = std::time::Duration::from_millis(250); +fn shown_job(app: &App) -> Option<&Job> { + app.job + .as_ref() + .filter(|job| job.started.elapsed() >= JOB_FOOTER_DELAY) +} + +/// A smooth horizontal bar: whole cells plus one eighth-block partial cell. +pub(crate) fn meter_bar(fill: f64, width: usize) -> String { + const PARTS: [char; 8] = [' ', '▏', '▎', '▍', '▌', '▋', '▊', '▉']; + let eighths = (fill.clamp(0.0, 1.0) * width as f64 * 8.0).round() as usize; + let full = (eighths / 8).min(width); + let mut bar = "█".repeat(full); + if full < width { + let part = eighths % 8; + bar.push(if part == 0 { '·' } else { PARTS[part] }); + bar.push_str(&"·".repeat(width - full - 1)); + } + bar +} + pub fn draw(frame: &mut Frame, app: &mut App) { let area = frame.area(); theme::set(*app.theme); app.frame = app.frame.wrapping_add(1); + app.motion.tick(app.busy); app.hits.clear(); frame.render_widget( Block::default().style(Style::default().bg(BG()).fg(TEXT())), @@ -138,7 +168,7 @@ pub fn draw(frame: &mut Frame, app: &mut App) { let root = Layout::vertical([ Constraint::Length(3), Constraint::Min(10), - Constraint::Length(if app.job.is_some() { 6 } else { 3 }), + Constraint::Length(if shown_job(app).is_some() { 6 } else { 3 }), ]) .split(area); let header = Layout::horizontal([Constraint::Length(27), Constraint::Min(10)]) @@ -157,6 +187,13 @@ pub fn draw(frame: &mut Frame, app: &mut App) { line(crate::BUILD_LABEL, MUTED()), ], ); + // M04: the wordmark is a two-accent gradient. + fx::gradient( + frame.buffer_mut(), + Rect::new(header[0].x, header[0].y, 7.min(header[0].width), 1), + ACCENT(), + ACCENT2(), + ); let model = app .session .as_ref() @@ -168,12 +205,11 @@ pub fn draw(frame: &mut Frame, app: &mut App) { // second line animates while a task runs so the state is visible at a glance. let meter = match (app.context_used, app.context_size) { (Some(used), Some(size)) if size > 0 => { - let width = 10usize; - let filled = ((used.min(size) as f64 / size as f64) * width as f64).round() as usize; + // The bar glides to each new reading in eighth-cell steps. + let fill = app.motion.glide("ctx", used.min(size) as f64 / size as f64); format!( - " ctx ▕{}{}▏ {}K/{}K", - "▮".repeat(filled.min(width)), - "·".repeat(width.saturating_sub(filled.min(width))), + " ctx ▕{}▏ {}K/{}K", + meter_bar(fill, 10), used / 1024, size / 1024 ) @@ -188,13 +224,13 @@ pub fn draw(frame: &mut Frame, app: &mut App) { "Waiting for your approval" }, WARN(), - th.spinner[(app.frame as usize) % th.spinner.len()], + th.spinner[motion::spin(th.spinner.len())], ) } else if app.connecting { ( "Connecting…", WARN(), - th.spinner[(app.frame as usize) % th.spinner.len()], + th.spinner[motion::spin(th.spinner.len())], ) } else if app.connected { ("Connected · saved locally", GOOD(), "") @@ -269,13 +305,320 @@ pub fn draw(frame: &mut Frame, app: &mut App) { Page::Jobs => jobs(frame, app, content), Page::Context => context(frame, app, content), } + page_transition(frame, app, content); + toasts(frame, app, content); footer(frame, app, root[2]); - if app.dialog.is_some() || !app.permissions.is_empty() { - app.hits.clear(); - modal(frame, app, area); + dialog_layer(frame, app, area); + pointer_feedback(frame, app); + splash(frame, app, area); +} + +/// M04: the target under the mouse glows softly; a click flashes it. +fn pointer_feedback(frame: &mut Frame, app: &mut App) { + let target = app.motion.hover.and_then(|(x, y)| { + app.hits + .iter() + .rev() + .find(|(rect, hit)| rect.contains((x, y).into()) && !matches!(hit, Hit::Composer)) + .map(|(rect, _)| *rect) + }); + let buf = frame.buffer_mut(); + if let Some((rect, strength)) = app.motion.hover(target) { + fx::tint( + buf, + rect, + ACCENT(), + 0.16 * motion::stepped(strength, 3), + PANEL(), + ); + } + if let Some((rect, t)) = app.motion.press() { + fx::tint( + buf, + rect, + ACCENT(), + 0.45 * (1.0 - motion::stepped(t, 3)), + PANEL(), + ); + } +} + +/// M04: a short wordmark splash on launch (Full motion only, 720 ms). Any key +/// passes straight through and ends it; the interface then cascades in. +fn splash(frame: &mut Frame, app: &mut App, area: Rect) { + let Some(t) = app.motion.splash() else { + return; + }; + let buf = frame.buffer_mut(); + for y in area.top()..area.bottom() { + for x in area.left()..area.right() { + let cell = &mut buf[(x, y)]; + cell.reset(); + cell.bg = BG(); + } + } + const LOGO: [&str; 2] = ["▄▀█ █ ▀█▀", "█▀█ █▄▄ █ "]; + const TAGLINE: &str = "L O C A L W O R K S P A C E"; + let reveal = motion::stepped(motion::ease_out_cubic(t / 0.45), 4); + let top = area.y + area.height.saturating_sub(6) / 2; + let logo_x = area.x + area.width.saturating_sub(11) / 2; + for (row, text) in LOGO.iter().enumerate() { + for (i, ch) in text.chars().enumerate() { + let color = motion::blend(ACCENT(), ACCENT2(), i as f64 / 10.0); + buf[(logo_x + i as u16, top + row as u16)] + .set_char(ch) + .set_fg(motion::blend(BG(), color, reveal)) + .set_bg(BG()); + } + } + let tag_x = area.x + area.width.saturating_sub(TAGLINE.len() as u16) / 2; + buf.set_string( + tag_x, + top + 3, + TAGLINE, + Style::default() + .fg(motion::blend(BG(), MUTED(), reveal)) + .bg(BG()), + ); + let bar = meter_bar(motion::stepped(motion::ease_in_out_cubic(t), 12), 24); + let bar_x = area.x + area.width.saturating_sub(24) / 2; + buf.set_string( + bar_x, + top + 5, + bar, + Style::default() + .fg(motion::blend(BG(), ACCENT(), reveal)) + .bg(BG()), + ); +} + +/// M02: a new page cascades in: rows settle top to bottom, each sliding a few +/// columns from the right and fading up from the background (a staggered +/// entrance). Each row passes through two stages, so the whole transition +/// costs about three repaints of the page. Reduced keeps the fade; Off draws +/// in place. +fn page_transition(frame: &mut Frame, app: &mut App, content: Rect) { + let index = Page::ALL.iter().position(|p| *p == app.page).unwrap_or(0) as u8; + app.motion.page(index); + let Some(t) = app.motion.progress(app.motion.page_since, motion::PAGE_MS) else { + return; + }; + let moves = app.motion.level.moves(); + let height = content.height.max(1) as f64; + let buf = frame.buffer_mut(); + for y in content.top()..content.bottom() { + // Rows start 0–45% into the transition and take 55% of it to settle. + let delay = (y - content.y) as f64 / height * 0.45; + let local = ((t - delay) / 0.55).clamp(0.0, 1.0); + let (fade, dx) = match motion::stepped(motion::ease_out_cubic(local), 3) { + s if s < 0.33 => (0.8, 4), + s if s < 0.66 => (0.35, 1), + _ => continue, + }; + let row = Rect::new(content.x, y, content.width, 1); + if moves { + fx::slide_right(buf, row, dx.min(content.width / 10), BG()); + } + fx::fade(buf, row, BG(), fade, TEXT()); } } +/// M03: notices float in at the top right of the page and fade away. They +/// echo the status line (which stays put) and never take clicks. +fn toasts(frame: &mut Frame, app: &mut App, content: Rect) { + // A toast only ever shows the current status; any later status (an + // error, progress, a direct update) retires it at once. + if app + .motion + .toasts + .last() + .is_some_and(|t| t.text != app.status.trim() || app.status_error) + { + app.motion.toasts.clear(); + } + if app.motion.toasts.is_empty() || content.width < 30 || content.height < 8 { + return; + } + let width = content.width.saturating_sub(2).min(46); + let now = app.motion.now(); + let moves = app.motion.level.moves(); + let mut y = content.y; + for toast in app.motion.toasts.clone().iter().rev() { + let glyph = match toast.tone { + motion::Tone::Good => "✓ ", + motion::Tone::Bad => "✕ ", + motion::Tone::Info => "• ", + }; + let mut text = format!("{glyph}{}", toast.text); + if toast.count > 1 { + text.push_str(&format!(" ×{}", toast.count)); + } + let lines = textwrap_lines(&text, width.saturating_sub(4) as usize, 2); + let height = lines.len() as u16 + 2; + if y + height > content.bottom() { + break; + } + let age = now - toast.born; + // Four stages in and out keep a toast to a few small repaints. + let enter = motion::stepped(motion::ease_out_cubic(age / motion::TOAST_EDGE_MS), 4); + let leave = motion::stepped((motion::TOAST_MS - age) / motion::TOAST_EDGE_MS, 4); + let shift = if moves { + ((1.0 - enter) * (width as f64 * 0.5)).round() as u16 + } else { + 0 + }; + let x = content.right().saturating_sub(width + 1) + shift; + let rect = Rect::new(x, y, width.min(content.right().saturating_sub(x)), height); + let tone = match toast.tone { + motion::Tone::Good => GOOD(), + motion::Tone::Bad => BAD(), + motion::Tone::Info => ACCENT(), + }; + frame.render_widget(Clear, rect); + frame.render_widget( + Paragraph::new( + lines + .into_iter() + .enumerate() + .map(|(i, l)| match l.strip_prefix(glyph).filter(|_| i == 0) { + Some(rest) => Line::from(vec![ + Span::styled(glyph, style(tone).add_modifier(Modifier::BOLD)), + Span::styled(rest.to_owned(), style(TEXT())), + ]), + None => line(l, TEXT()), + }) + .collect::>(), + ) + .block( + Block::default() + .borders(Borders::LEFT | Borders::TOP | Borders::BOTTOM | Borders::RIGHT) + .border_type(BorderType::Rounded) + .border_style(style(tone)) + .style(Style::default().bg(PANEL()).fg(TEXT())), + ), + rect, + ); + let buf = frame.buffer_mut(); + let fade = 1.0 - enter.min(leave); + if fade > 0.0 { + fx::fade(buf, rect, BG(), fade, TEXT()); + } + fx::shadow( + buf, + rect, + motion::blend(BG(), Color::Rgb(0, 0, 0), 0.55), + 0.5 * (1.0 - fade), + ); + y += height + 1; + } +} + +/// Greedy word wrap into at most `max` lines; the last line ends in "…" when cut. +fn textwrap_lines(text: &str, width: usize, max: usize) -> Vec { + let width = width.max(8); + let mut lines: Vec = Vec::new(); + let mut current = String::new(); + for word in display_text(text).split_whitespace() { + let fits = + current.chars().count() + word.chars().count() + usize::from(!current.is_empty()) + <= width; + if !fits && !current.is_empty() { + lines.push(std::mem::take(&mut current)); + } + if !current.is_empty() { + current.push(' '); + } + current.push_str(&word.chars().take(width).collect::()); + } + if !current.is_empty() { + lines.push(current); + } + if lines.len() > max { + lines.truncate(max); + let last = &mut lines[max - 1]; + let keep: String = last.chars().take(width.saturating_sub(1)).collect(); + *last = format!("{keep}…"); + } + lines +} + +/// Identity of the dialog on screen; a new identity replays the entrance. +fn dialog_key(app: &App) -> Option { + if let Some((id, _)) = app.permissions.front() { + return Some(format!("permission:{id}")); + } + app.dialog.as_ref().map(|dialog| match dialog { + Dialog::Menu { title, .. } => format!("menu:{title}"), + other => format!("{:?}", std::mem::discriminant(other)), + }) +} + +/// M02: dialogs dim the page behind them, cast a shadow and pop in (scale +/// 86% → 100% with a slight overshoot); closing fades them back out. +fn dialog_layer(frame: &mut Frame, app: &mut App, area: Rect) { + let key = dialog_key(app); + let entrance = app.motion.modal(key.clone()); + if key.is_none() { + if let Some((t, retained)) = app.motion.closing() { + fx::fade_out( + frame.buffer_mut(), + retained.rect, + &retained.cells, + motion::stepped(motion::ease_out_cubic(t), 2), + TEXT(), + BG(), + ); + } + return; + } + app.hits.clear(); + let shade = motion::blend(BG(), Color::Rgb(0, 0, 0), 0.55); + // The backdrop dims in one step; only the dialog itself animates. + fx::fade(frame.buffer_mut(), area, shade, 0.5, TEXT()); + let entrance = entrance.map(|t| motion::stepped(t, 3)); + // Only the entrance needs what lay beneath; a settled dialog costs no + // full-screen snapshot. + let moves = app.motion.level.moves(); + let before = (entrance.is_some() && moves).then(|| fx::snapshot(frame.buffer_mut(), area)); + app.motion.dialog_rect = None; + modal(frame, app, area); + let buf = frame.buffer_mut(); + let Some(rect) = app.motion.dialog_rect.map(|r| r.intersection(area)) else { + return; + }; + let visible = match (entrance, &before) { + (Some(t), Some(before)) => { + let visible = fx::scaled(rect, 0.86 + 0.14 * motion::ease_out_back(t)); + fx::clip_to(buf, area, before, rect, visible); + // A ring on the growing edge keeps the reveal a clean box. + if visible != rect { + Block::default() + .borders(Borders::ALL) + .border_type(BorderType::Rounded) + .border_style(style(BORDER_FOCUSED())) + .render(visible, buf); + } + visible + } + _ => rect, + }; + if let Some(t) = entrance { + fx::fade( + buf, + visible, + BG(), + (1.0 - motion::ease_out_cubic(t)) * 0.7, + TEXT(), + ); + } else { + app.motion.modal_retained = Some(motion::Retained { + rect, + cells: fx::snapshot(buf, rect), + }); + } + fx::shadow(buf, visible, shade, 0.7); +} + /// Live activity/context column; rendered beside Chat and in Split layout. fn activity_column(frame: &mut Frame, app: &mut App, area: Rect) { let th = theme::cur(); @@ -325,14 +668,21 @@ fn activity_column(frame: &mut Frame, app: &mut App, area: Rect) { ), ], ); + let flashes: Vec> = app + .tools + .iter() + .map(|tool| app.motion.flash(&tool.id, &tool.status)) + .collect(); + let spinner = th.spinner[motion::spin(th.spinner.len())]; let items = app .tools .iter() .map(|tool| { let (led, status_color) = match tool.status.as_str() { - "completed" => (th.led_on, GOOD()), - "failed" => (th.led_on, BAD()), - _ => (th.led_off, WARN()), + "completed" => (th.led_on.to_string(), GOOD()), + "failed" => (th.led_on.to_string(), BAD()), + _ if app.busy && app.motion.level.fades() => (spinner.to_string(), WARN()), + _ => (th.led_off.to_string(), WARN()), }; ListItem::new(vec![ Line::from(vec![ @@ -368,10 +718,17 @@ fn activity_column(frame: &mut Frame, app: &mut App, area: Rect) { if y >= inner.bottom() { break; } - app.hits.push(( - Rect::new(inner.x, y, inner.width, 2.min(inner.bottom() - y)), - Hit::Row(i), - )); + let row = Rect::new(inner.x, y, inner.width, 2.min(inner.bottom() - y)); + if let Some(t) = flashes.get(i).copied().flatten() { + let color = match app.tools[i].status.as_str() { + "completed" => GOOD(), + "failed" => BAD(), + _ => WARN(), + }; + let fade = 1.0 - motion::stepped(motion::ease_out_cubic(t), 4); + fx::tint(frame.buffer_mut(), row, color, 0.42 * fade, PANEL()); + } + app.hits.push((row, Hit::Row(i))); } } buttons( @@ -513,7 +870,9 @@ fn nav(frame: &mut Frame, app: &mut App, area: Rect) { fn footer(frame: &mut Frame, app: &mut App, area: Rect) { let inner = inset(area, 2, 0); - let status_y = if let Some(job) = &app.job { + let status_y = if shown_job(app).is_some() + && let Some(job) = &app.job + { let ratio = if job.progress.total > 0 { job.progress.received as f64 / job.progress.total as f64 } else { @@ -535,6 +894,13 @@ fn footer(frame: &mut Frame, app: &mut App, area: Rect) { job.started.elapsed().as_secs() ) }; + // Progress glides between reports; a fresh job starts from empty. + let ratio = if ratio <= 0.0 { + app.motion.glide("job", 0.0); + 0.0 + } else { + app.motion.glide("job", ratio) + }; let progress = Rect::new(inner.x, inner.y, inner.width.saturating_sub(10), 1); frame.render_widget( Gauge::default() @@ -543,6 +909,9 @@ fn footer(frame: &mut Frame, app: &mut App, area: Rect) { .gauge_style(Style::default().fg(ACCENT()).bg(SELECT())), progress, ); + if job.progress.total == 0 && app.motion.level.moves() { + shimmer(frame.buffer_mut(), progress, app.motion.now()); + } let stage = job.progress.stage.clone(); button( frame, @@ -607,6 +976,25 @@ fn footer(frame: &mut Frame, app: &mut App, area: Rect) { ); } +/// A soft band of light sweeping across a bar whose length is unknown. +fn shimmer(buf: &mut ratatui::buffer::Buffer, area: Rect, now: f64) { + let span = area.width as f64 + 16.0; + let centre = (now / 1500.0).fract() * span - 8.0; + for x in area.left()..area.right() { + let distance = ((x - area.x) as f64 - centre).abs(); + if distance < 8.0 { + let strength = 0.55 * (1.0 - distance / 8.0).powi(2); + fx::tint( + buf, + Rect::new(x, area.y, 1, 1), + ACCENT(), + strength, + SELECT(), + ); + } + } +} + /// Status cards plus a two-column grid of action cards (H01, harvested from the /// final-pass branch and drawn through the active theme). Indexes match the /// Start-here list, so keyboard, mouse and actions are unchanged. @@ -980,7 +1368,20 @@ fn chat(frame: &mut Frame, app: &mut App, area: Rect) { line("No model selected? Open Connections first.", MUTED()), ]); } - for message in &app.messages { + let newest = app.messages.len().saturating_sub(1); + let reveal = app + .messages + .back() + .filter(|m| m.role != "You" && m.role != "Notice") + .map(|m| { + let len = m.text.chars().count(); + (len, app.motion.reveal(newest, len, app.busy)) + }); + for (index, message) in app.messages.iter().enumerate() { + let partial = reveal + .filter(|(len, shown)| index == newest && shown < len) + .map(|(_, shown)| message.text.chars().take(shown).collect::()); + let body = partial.as_deref().unwrap_or(&message.text); lines.push(line("", TEXT())); let (badge_color, led) = if message.role == "You" { (ACCENT2(), th.led_on) @@ -997,7 +1398,7 @@ fn chat(frame: &mut Frame, app: &mut App, area: Rect) { ), ])); let mut code = false; - for text in message.text.lines() { + for text in body.lines() { if text.starts_with("```") { code = !code; lines.push(line(text, MUTED())); @@ -1014,9 +1415,18 @@ fn chat(frame: &mut Frame, app: &mut App, area: Rect) { }, )); } + if partial.is_some() { + // A soft cursor rides the end of a reply that is still arriving. + match lines.last_mut() { + Some(last) if !body.ends_with('\n') => { + last.spans.push(Span::styled("▍", style(ACCENT()))) + } + _ => lines.push(line("▍", ACCENT())), + } + } } if app.busy { - let frame_index = (app.frame as usize) % th.spinner.len(); + let frame_index = motion::spin(th.spinner.len()); lines.push(Line::from(vec![ Span::styled(format!("{} ", th.spinner[frame_index]), style(WARN())), Span::styled( @@ -1727,6 +2137,7 @@ fn modal(frame: &mut Frame, app: &mut App, area: Rect) { _ => 24, }, ); + app.motion.dialog_rect = Some(rect); frame.render_widget(Clear, rect); match dialog { Dialog::Menu { @@ -2155,6 +2566,7 @@ fn permission_modal(frame: &mut Frame, app: &mut App, area: Rect) { }; let tool = ¶ms["toolCall"]; let rect = centered(area, 94, area.height.saturating_sub(2)); + app.motion.dialog_rect = Some(rect); frame.render_widget(Clear, rect); frame.render_widget( block(" Review this action ", true).border_style(style(WARN())), @@ -2573,6 +2985,361 @@ mod tests { .collect::>() .join("\n") } + #[test] + fn meters_fill_in_eighth_cell_steps() { + assert_eq!(meter_bar(0.0, 4), "····"); + assert_eq!(meter_bar(1.0, 4), "████"); + assert_eq!(meter_bar(0.5, 4), "██··"); + assert_eq!(meter_bar(0.5625, 4), "██▎·"); + assert_eq!(meter_bar(0.59375, 4), "██▍·"); + for step in 0..=80 { + assert_eq!(meter_bar(step as f64 / 80.0, 10).chars().count(), 10); + } + } + #[tokio::test] + async fn motion_is_a_saved_setting_reachable_from_settings_and_palette() { + let (dir, mut app) = setup(); + assert!(App::settings_tab_indexes(0).contains(&23)); + assert!( + app.palette_items() + .iter() + .any(|(label, _, _)| label.starts_with("Setting: Motion:")) + ); + app.manager_action("motion", serde_json::json!({})).unwrap(); + assert!(render(&mut app, 80, 24).contains("Reduced")); + app.manager_action("motion-select", serde_json::json!({"level":"reduced"})) + .unwrap(); + assert_eq!(app.motion.level, motion::Level::Reduced); + let saved = std::fs::read_to_string(dir.path().join("preferences.toml")).unwrap(); + assert!(saved.contains("motion = \"reduced\""), "{saved}"); + } + #[tokio::test] + async fn adaptive_pacing_runs_fast_only_while_animating() { + let (_dir, mut app) = setup(); + app.motion = motion::Motion::new(motion::Level::Full); + app.motion.splash_until = None; + app.motion.pin(Some(0.0)); + assert_eq!(app.motion.frame_period(), motion::IDLE_FRAME); + app.context_used = Some(1024); + app.context_size = Some(8192); + render(&mut app, 100, 30); + app.context_used = Some(6144); + render(&mut app, 100, 30); + assert_eq!(app.motion.frame_period(), motion::ACTIVE_FRAME); + app.motion.pin(Some(motion::GLIDE_MS + 1.0)); + let text = render(&mut app, 100, 30); + assert!(text.contains("6K/8K"), "{text}"); + assert_eq!(app.motion.frame_period(), motion::IDLE_FRAME); + } + fn animated(app: &mut App) { + app.motion = motion::Motion::new(motion::Level::Full); + app.motion.splash_until = None; + app.motion.pin(Some(0.0)); + } + #[tokio::test] + async fn pages_slide_in_and_settle_on_the_exact_final_frame() { + let (_dir, mut app) = setup(); + app.set_page(Page::Help); + let still = render(&mut app, 100, 30); + animated(&mut app); + render(&mut app, 100, 30); + app.set_page(Page::Sessions); + app.motion.pin(Some(1000.0)); + let first = render(&mut app, 100, 30); + app.motion.pin(Some(1000.0 + motion::PAGE_MS + 1.0)); + let settled = render(&mut app, 100, 30); + assert_ne!(first, settled, "the first frame is mid-slide"); + assert!(!app.motion.active()); + app.motion.set_level(motion::Level::Off); + assert_eq!(settled, render(&mut app, 100, 30)); + app.set_page(Page::Help); + assert_eq!(still, render(&mut app, 100, 30), "Off draws in place"); + // Reduced fades without moving: text is in place on the first frame. + app.motion.set_level(motion::Level::Reduced); + app.set_page(Page::Sessions); + assert_eq!(settled, render(&mut app, 100, 30)); + assert!(app.motion.active()); + } + #[tokio::test] + async fn dialogs_pop_in_cast_a_shadow_and_fade_out() { + let (_dir, mut app) = setup(); + animated(&mut app); + render(&mut app, 100, 30); + app.connection_wizard(); + let opening = render(&mut app, 100, 30); + app.motion.pin(Some(motion::MODAL_IN_MS + 1.0)); + let open = render(&mut app, 100, 30); + assert_ne!(opening, open, "the first frame is a smaller reveal"); + assert!(open.contains("Where will your model run?")); + let hits = app.hits.len(); + assert!(hits > 0, "dialog targets are live from the first frame"); + app.dialog = None; + app.motion.pin(Some(motion::MODAL_IN_MS + 2.0)); + let closing = render(&mut app, 100, 30); + assert!( + !closing.contains("Where will your model run?"), + "a closing dialog's text is gone at once" + ); + assert!(app.motion.active(), "its colours fade out"); + app.motion + .pin(Some(motion::MODAL_IN_MS + motion::MODAL_OUT_MS + 3.0)); + let closed = render(&mut app, 100, 30); + assert!(!closed.contains("Where will your model run?")); + assert!(!app.motion.active()); + } + #[tokio::test] + async fn notices_float_in_as_toasts_and_progress_stays_in_the_status_line() { + let (_dir, mut app) = setup(); + animated(&mut app); + app.set_page(Page::Help); + render(&mut app, 100, 30); + app.notify("Theme changed to IRIS. Everything else is unchanged."); + app.notify("Theme changed to IRIS. Everything else is unchanged."); + app.motion.pin(Some(motion::TOAST_EDGE_MS + 1.0)); + let text = render(&mut app, 100, 30); + assert!(text.contains("×2"), "identical notices collapse\n{text}"); + assert_eq!(app.motion.toasts[0].tone, motion::Tone::Good); + app.progress_status("Reading project files"); + assert_eq!(app.motion.toasts.len(), 1, "progress never toasts"); + assert_eq!(app.status, "Reading project files"); + let text = render(&mut app, 100, 30); + assert!( + app.motion.toasts.is_empty(), + "a newer status retires the toast" + ); + assert!(!text.contains("×2")); + app.notify("Theme changed to IRIS. Everything else is unchanged."); + app.motion + .pin(Some(motion::TOAST_MS + motion::TOAST_EDGE_MS + 1.0)); + let text = render(&mut app, 100, 30); + assert!(!text.contains("×2"), "toasts expire"); + assert!(app.motion.toasts.is_empty()); + } + #[tokio::test] + async fn streaming_replies_reveal_with_a_cursor_and_history_is_whole() { + let (_dir, mut app) = setup(); + animated(&mut app); + app.set_page(Page::Chat); + let reply = "Here is the plan. ".repeat(12); + app.messages.push_back(Message { + role: "Alt", + text: reply.clone(), + }); + let history = render(&mut app, 120, 40); + assert!( + !history.contains('▍'), + "a reply that is not streaming shows at once" + ); + app.busy = true; + app.messages.push_back(Message { + role: "Alt", + text: reply.clone(), + }); + app.motion.pin(Some(1000.0)); + render(&mut app, 120, 40); + app.motion.pin(Some(1100.0)); + let partial = render(&mut app, 120, 40); + assert!(partial.contains('▍'), "{partial}"); + app.motion.pin(Some(2000.0)); + app.busy = false; + let done = render(&mut app, 120, 40); + assert!(!done.contains('▍'), "{done}"); + } + #[tokio::test] + async fn tool_status_changes_flash_and_running_tools_spin() { + let (_dir, mut app) = setup(); + animated(&mut app); + app.layout = LayoutMode::Split; + app.set_page(Page::Help); + app.busy = true; + app.tools.push(Tool { + id: "t1".into(), + title: "Read README.md".into(), + status: "pending".into(), + input: serde_json::Value::Null, + content: String::new(), + }); + render(&mut app, 140, 40); + app.tools[0].status = "completed".into(); + app.motion.pin(Some(10.0)); + render(&mut app, 140, 40); + assert!(app.motion.active(), "the change flashes"); + app.motion.pin(Some(10.0 + motion::FLASH_MS + 1.0)); + render(&mut app, 140, 40); + assert!(!app.motion.active()); + } + fn render_buffer(app: &mut App, width: u16, height: u16) -> ratatui::buffer::Buffer { + let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); + terminal.draw(|f| draw(f, app)).unwrap(); + terminal.backend().buffer().clone() + } + #[tokio::test] + async fn splash_shows_the_wordmark_briefly_and_keys_pass_straight_through() { + let (_dir, mut app) = setup(); + app.motion = motion::Motion::new(motion::Level::Full); + app.motion.pin(Some(100.0)); + let text = render(&mut app, 80, 24); + assert!(text.contains("▄▀█ █ ▀█▀"), "{text}"); + assert!(!text.contains("Start here"), "the splash covers the screen"); + app.key(KeyEvent::new(KeyCode::Char('2'), KeyModifiers::ALT)) + .unwrap(); + assert_eq!(app.page, Page::Chat, "the key still acted"); + let text = render(&mut app, 80, 24); + assert!(!text.contains("▄▀█ █ ▀█▀")); + assert!(app.motion.active(), "the interface cascades in"); + // Left alone, it ends by itself within its budget. + let (_dir, mut app) = setup(); + app.motion = motion::Motion::new(motion::Level::Full); + app.motion.pin(Some(motion::SPLASH_MS + 1.0)); + assert!(!render(&mut app, 80, 24).contains("▄▀█")); + let (_dir, mut app) = setup(); + app.motion = motion::Motion::new(motion::Level::Reduced); + assert!( + !render(&mut app, 80, 24).contains("▄▀█"), + "Reduced has no splash" + ); + } + #[tokio::test] + async fn hover_glows_and_clicks_flash_the_target() { + use crossterm::event::{MouseButton, MouseEventKind}; + let (_dir, mut app) = setup(); + animated(&mut app); + app.set_page(Page::Help); + render_buffer(&mut app, 100, 30); + let (rect, _) = app + .hits + .iter() + .find(|(_, hit)| matches!(hit, Hit::Nav(Page::Models))) + .cloned() + .unwrap(); + let plain = render_buffer(&mut app, 100, 30)[(rect.x + 2, rect.y)].bg; + app.mouse(MouseEventKind::Moved, rect.x + 2, rect.y) + .unwrap(); + app.motion.pin(Some(motion::HOVER_MS + 1.0)); + render_buffer(&mut app, 100, 30); + app.motion.pin(Some(2.0 * motion::HOVER_MS + 2.0)); + let hovered = render_buffer(&mut app, 100, 30)[(rect.x + 2, rect.y)].bg; + assert_ne!(plain, hovered, "hover tints the target"); + app.mouse(MouseEventKind::Down(MouseButton::Left), rect.x + 2, rect.y) + .unwrap(); + assert_eq!(app.page, Page::Models); + assert!(app.motion.press().is_some(), "the click flashes"); + } + #[tokio::test] + async fn focus_rings_breathe_only_while_a_task_runs_and_the_wordmark_is_a_gradient() { + let (_dir, mut app) = setup(); + animated(&mut app); + app.set_page(Page::Settings); + let colors = |app: &mut App| { + let buffer = render_buffer(app, 100, 30); + (0..30) + .flat_map(|y| (0..100).map(move |x| (x, y))) + .map(|(x, y)| buffer[(x, y)].fg) + .collect::>() + }; + app.motion.pin(Some(1000.0)); + let idle_a = colors(&mut app); + app.motion.pin(Some(2300.0)); + let idle_b = colors(&mut app); + assert_eq!(idle_a, idle_b, "an idle screen does not change"); + app.busy = true; + app.motion.pin(Some(1300.0)); + let busy_a = colors(&mut app); + app.motion.pin(Some(2600.0)); + let busy_b = colors(&mut app); + assert_ne!(busy_a, busy_b, "the focus ring breathes while working"); + let buffer = render_buffer(&mut app, 100, 30); + assert_ne!( + buffer[(2, 0)].fg, + buffer[(4, 0)].fg, + "A and T differ in hue" + ); + } + /// Frame-time budget (M05): drawing with every effect active must stay far + /// inside the 16 ms animation frame. The same scripted session (page + /// changes, dialogs opening and closing, toasts, a gliding meter, a busy + /// task) runs with motion Off and Full; Full is reported against Off. + /// Debug builds are several times slower than release, so the default + /// debug budget is generous; `ALT_FRAME_BUDGET_MS` sets an exact one. + fn scripted_frames(level: motion::Level) -> Vec { + let dir = tempfile::tempdir().unwrap(); + let mut app = App::load(dir.path().to_path_buf(), "goose".into(), None).unwrap(); + app.preferences.project = dir.path().to_path_buf(); + app.motion = motion::Motion::new(level); + app.motion.splash_until = None; + app.layout = LayoutMode::Split; + app.busy = true; + app.context_size = Some(8192); + for i in 0..40 { + app.messages.push_back(Message { + role: if i % 2 == 0 { "You" } else { "Alt" }, + text: "A line of conversation with some length to wrap. ".repeat(4), + }); + } + let mut terminal = Terminal::new(TestBackend::new(160, 48)).unwrap(); + let mut times = Vec::new(); + for frame in 0..300u32 { + app.motion.pin(Some(frame as f64 * 16.0)); + if frame % 40 == 0 { + app.set_page(if frame % 80 == 0 { + Page::Chat + } else { + Page::Home + }); + app.notify(format!("Notice {frame}")); + app.context_used = Some(1024 + frame as u64 * 20); + } + match frame % 60 { + 20 => app.connection_wizard(), + 40 => app.dialog = None, + _ => {} + } + let started = std::time::Instant::now(); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + times.push(started.elapsed().as_secs_f64() * 1000.0); + } + times.sort_by(|a, b| a.partial_cmp(b).unwrap()); + times + } + #[test] + fn frame_time_stays_inside_budget_with_every_effect_active() { + let runtime = tokio::runtime::Runtime::new().unwrap(); + let _guard = runtime.enter(); + let off = scripted_frames(motion::Level::Off); + let full = scripted_frames(motion::Level::Full); + let pick = |t: &[f64], q: usize| t[t.len() * q / 100]; + eprintln!( + "frame time at 160x48 (median / p95 ms): off {:.2} / {:.2}, full {:.2} / {:.2}", + pick(&off, 50), + pick(&off, 95), + pick(&full, 50), + pick(&full, 95) + ); + let budget: f64 = std::env::var("ALT_FRAME_BUDGET_MS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(if cfg!(debug_assertions) { 60.0 } else { 8.0 }); + assert!( + pick(&full, 95) < budget, + "p95 {:.2} ms over the {budget} ms budget", + pick(&full, 95) + ); + } + #[tokio::test] + async fn quitting_skips_the_prompt_for_view_refreshes_but_not_real_work() { + let (_dir, mut app) = setup(); + app.set_page(Page::Files); + if let Some(job) = &app.job { + assert!(job.replaceable, "a page refresh is disposable"); + } + app.action("quit").unwrap(); + assert!(app.quit && app.dialog.is_none(), "a refresh never asks"); + let (_dir, mut app) = setup(); + app.busy = true; + app.action("quit").unwrap(); + assert!(!app.quit, "a running task asks first"); + assert!(matches!(app.dialog, Some(Dialog::Confirm { .. }))); + } #[tokio::test] async fn every_page_and_dialog_renders_at_supported_sizes() { let (_dir, mut app) = setup();