diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 235f165..26313ef 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -34,6 +34,9 @@ jobs: version: "0.12.10" enable-cache: false - name: Run device-free native and portable contracts + env: + CI_PLATFORM: Windows + CI_ARCH: x64 run: | $scratch = Join-Path $env:RUNNER_TEMP ("gs-native-" + [guid]::NewGuid()) New-Item -ItemType Directory -Force $scratch | Out-Null @@ -52,12 +55,18 @@ jobs: uv sync --python 3.13 --frozen --no-install-project --no-build if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } $python = "$scratch/venv/Scripts/python.exe" + & $python scripts/check_ci_platform.py verify $env:CI_PLATFORM $env:CI_ARCH + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } & $python -c 'import sys; from importlib.metadata import version; assert sys.platform == "win32"; assert sys.version_info[:2] == (3, 13); print(sys.version); print({name: version(name) for name in ("sounddevice", "pyfluidsynth", "pytest")}); assert not any(name in sys.modules for name in ("sounddevice", "_sounddevice", "fluidsynth"))' if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + # Native uses frozen dependencies without installing/building the project; this is source-only. & $python -m gentle_stream --help if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } & $python -m pytest -q tests/test_native_windows.py tests/test_daemon.py tests/test_bridge.py tests/test_voice_free_delivery.py tests/test_music_panic.py tests/test_ui_toolbar_contracts.py tests/test_ui_save_contracts.py tests/test_ui_picker_contracts.py tests/test_ui_transport_contracts.py tests/test_genres_contract.py tests/test_performance_selection.py -o "cache_dir=$scratch/pytest-cache" --basetemp="$scratch/pytest-temp" if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + # Keep this source CLI lane to the machine contract (no sample installs or daemon fixtures). + & $python -m pytest -q tests/test_main.py -k 'test_ctl_ and (json or test_ctl_status_still_never_starts_a_player)' -o "cache_dir=$scratch/pytest-cache" --basetemp="$scratch/cli-temp" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } # Only this mocked host regression is portable; the real-pipe module is POSIX. & $python -m pytest -q tests/test_pause_output.py::test_host_pause_delivers_stop_with_full_pending_queue -o "cache_dir=$scratch/pytest-cache" --basetemp="$scratch/queue-temp" if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } @@ -72,14 +81,18 @@ jobs: fail-fast: false max-parallel: 3 matrix: + # Other OS/architecture combinations are unverified; keep the proven runner labels. include: - platform: Linux + arch: x64 runner: ubuntu-24.04 shell: bash - platform: macOS + arch: arm64 runner: macos-15 shell: bash - platform: WSL + arch: x64 runner: windows-latest shell: wsl-bash {0} defaults: @@ -100,7 +113,13 @@ jobs: set-as-default: "true" use-cache: "false" update: "true" - additional-packages: libportaudio2 python3-venv ca-certificates + additional-packages: libportaudio2 python3-venv ca-certificates git + - name: Log Windows host WSL distributions and versions + if: matrix.platform == 'WSL' + shell: pwsh + run: | + wsl.exe --list --verbose + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Install Linux PortAudio library if: matrix.platform == 'Linux' run: | @@ -115,9 +134,14 @@ jobs: with: version: "0.11.14" enable-cache: false - - name: Install frozen dependencies and run correctness tests + - name: Verify the runner and checkout, smoke the installed CLI, and run correctness tests + env: + CI_PLATFORM: ${{ matrix.platform }} + CI_ARCH: ${{ matrix.arch }} + # Pass only these declared values and the GitHub-provided SHA from Windows to WSL. + WSLENV: CI_PLATFORM:CI_ARCH:GITHUB_SHA run: | - platform='${{ matrix.platform }}' + set -euo pipefail # Short system-temp roots keep macOS AF_UNIX socket paths within limits. scratch="$(mktemp -d /tmp/gs-ci-XXXXXX)" export PYTHONDONTWRITEBYTECODE=1 @@ -134,14 +158,10 @@ jobs: export PYTEST_ADDOPTS="-o cache_dir=$scratch/pytest-cache --basetemp=$scratch/pytest-temp" mkdir -p "$HOME" "$XDG_CONFIG_HOME" "$XDG_CACHE_HOME" "$XDG_RUNTIME_DIR" "$TMPDIR" chmod 700 "$XDG_RUNTIME_DIR" - if [[ "$platform" == WSL ]]; then + if [[ "$CI_PLATFORM" == WSL ]]; then # Move off DrvFS: sockets, executable fake scripts and mode bits need POSIX paths. cp -R . "$scratch/repo" cd "$scratch/repo" - test "$(uname -s)" = Linux - grep -qi microsoft /proc/sys/kernel/osrelease - . /etc/os-release - test "$ID:$VERSION_ID" = ubuntu:24.04 python3 -m venv "$scratch/bootstrap" "$scratch/bootstrap/bin/python" -m pip install --only-binary=:all: uv==0.11.14 export PATH="$scratch/bootstrap/bin:$PATH" @@ -150,6 +170,9 @@ jobs: uv --version uv python install 3.13 uv sync --frozen --python 3.13 + # WSL checks the copied checkout that supplies the actual source and tests. + "$scratch/venv/bin/python" scripts/check_ci_platform.py verify "$CI_PLATFORM" "$CI_ARCH" + "$scratch/venv/bin/python" scripts/check_ci_platform.py smoke "$scratch/venv/bin/gentle-stream" "$scratch/smoke" uv run --frozen --no-sync python -c 'import sys, sounddevice; assert sys.version_info[:2] == (3, 13); print(sys.version); print(sys.platform); print(sounddevice.get_portaudio_version())' # Full default correctness includes the COMPLETE real-pipe pause module on Linux. uv run --frozen --no-sync pytest diff --git a/README.md b/README.md index 47c0708..1871e67 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,8 @@ Only describing a mood calls a model. The status line shows what that call used, ## Get started +See [platform setup and audio verification](docs/platform-support.md) for the Linux, macOS, WSL2, and native Windows paths. + **Requirements** | You need | Why | @@ -218,7 +220,7 @@ not a guaranteed fix for every cause of stutter, and it does not restart Gentle | `--mood TEXT` | Mood to interpret as soon as the app starts | | `--gentle-shell PATH` | `gentle-shell` executable to run (default: `gentle-shell`) | | `setup-samples` | Subcommand: download the FluidR3_GM soundfont once (see below) | -| `ctl ACTION` | Subcommand: control the music playing in the background (see below) | +| `ctl ACTION` | Subcommand: control the music playing in the background (see Background playback) |
Back to top
@@ -230,18 +232,26 @@ The music plays in a background player, one per user, that `gentle-stream` start ```bash gentle-stream ctl status # playback details and audio diagnostics as one JSON line +gentle-stream ctl start # start or attach to the music (may open the audio device, never calls a model) gentle-stream ctl pause # also: play, toggle, next gentle-stream ctl stop # ends the background player +gentle-stream ctl volume 60 --json +gentle-stream ctl mood "rainy night in a small café" --json ``` +### Legacy text output (backward compatible) + | Command | Output | Exit code | | :--- | :--- | :--- | | `ctl status` | One JSON line; just `{"running": false}` when nothing plays | `0` | +| `ctl start` | One JSON line with playback details; starts or attaches to the player | `0`, or `1` when it cannot start | | `ctl play`, `pause`, `toggle`, `next`, `stop` | Nothing, or `gentle-stream: nothing is playing` on stderr | `0`, or `1` when nothing plays | +`ctl volume 60` and `ctl mood "text"` without `--json` also print nothing on success, and the usual `gentle-stream: …` error on stderr when they fail. + ### Audio diagnostics -If audio cuts out, run `gentle-stream ctl status` again and compare the readings: +If audio cuts out, run `gentle-stream ctl status` without `--json` and compare the readings: ```json {"running": true, "playing": true, "name": "Midnight Rain", "genre": "lofi", "mood": "", "underruns": 0, "output_underflows": 0, "buffered_seconds": 1.2} @@ -259,6 +269,41 @@ An older running daemon cannot supply these fields: the updated client reports t On native Windows, the player uses an authenticated JSON named pipe, a current-user-only ACL-protected runtime directory and a Windows file lock; see [Native Windows](docs/windows-native.md#runtime-and-security). On POSIX, the player listens on a Unix socket in a private directory (`$XDG_RUNTIME_DIR/gentle-stream`, default `~/.cache/gentle-stream/run`, mode `0700`), authenticated with a random key in a `0600` file. A player that crashed is detected and replaced on the next start. If the audio output cannot be opened, `gentle-stream` prints the error and exits with `1`. +### Machine interface (`--json`) + +Add `--json` to any `ctl` command and it prints one stable envelope per call on stdout — the interface Gentle Desktop consumes: + +| Command | Meaning | +| :--- | :--- | +| `ctl status --json` | Current snapshot | +| `ctl start --json` | Start or attach to the player, then the snapshot | +| `ctl play` · `pause` · `toggle` · `next --json` | The action, then the resulting snapshot | +| `ctl volume N --json` | Set the volume to `N`, a whole percent `0`–`100` | +| `ctl mood "text" --json` | Interpret `text` into a style and queue it | +| `ctl stop --json` | Stop the music and end the player | + +**Success** prints one line whose shape is the snapshot plus `ok`: + +```json +{"ok": true, "running": true, "playing": true, "volume": 60, "name": "Café Night", "genre": "jazz", "mood": "rainy night in a small café"} +``` + +Fields, in order: `ok` (always `true` on success), `running`, `playing`, `volume` (whole percent 0–100), then `name`/`genre`/`mood` when a player is running. `ctl status --json` with no player returns just `{"ok": true, "running": false}` (exit `0`). `ctl start --json` behaves like `ctl status --json` but starts or attaches first, so on success `running` is `true`. `ctl stop --json` returns `{"ok": true, "running": false}` when it stopped a player, and the `nothing_playing` failure below (exit `1`) when there was none. `name`/`genre`/`mood` report the current parameters — the style being rendered; for `mood` they are the style that was just queued, which becomes audible at the next bar. Every action response is the actual resulting snapshot, never an assumed success. + +**Failure** exits non-zero and prints one safe envelope: + +```json +{"ok": false, "error": {"code": "nothing_playing", "message": "nothing is playing"}} +``` + +The error codes are `nothing_playing`, `invalid_request` and `unavailable`; messages are fixed text with no keys, socket paths, tokens or tracebacks. + +**Volume** is a whole percentage `0`–`100` (mapped to the player's 0.0–1.0 gain). Non-numeric, out-of-range or extra arguments are rejected as `invalid_request` before the player is ever contacted. + +**Mood** takes the rest of the line as text (spaces and Unicode preserved); it must be non-empty and at most 200 characters. It is synchronous: `ctl mood` waits for Gentle Shell to interpret the text with the chosen model (one model call — the only thing that spends tokens — using the same interpretation as the TUI's mood prompt), then queues the resulting style at the next bar. The response reflects the queued style immediately, before it is audible. A failed interpretation returns `unavailable` and leaves the music untouched. + +**Start** starts the background player when none is running, or attaches to the one already playing, through the same owner the TUI uses (`client.ensure`). It may open the audio device, but it makes **no model call** — mood interpretation stays a separate `ctl mood` call. If the player cannot be started (for example, the audio output cannot be opened), it exits `1` with the safe `unavailable` envelope. `start` is the only `ctl` action that spawns: `status`, `play`, `pause`, `toggle`, `next`, `stop` and `volume` keep attaching only and never start a player. +
Back to top
@@ -274,8 +319,8 @@ model: claude-bridge/claude-haiku-5-5 · session: 35.4k tokens · $0.0015 | Action | Calls a model? | | :--- | :--- | -| Describing a mood (`/` or `--mood`) | **Yes** — the only thing that does | -| Playback, `space`, `n`, Panic (`F4`), volume | No | +| Describing a mood (`/`, `--mood`, or `ctl mood`) | **Yes** — the only thing that does | +| Playback, `space`, `n`, Panic (`F4`), volume, `ctl status`/`start`/`play`/`pause`/`toggle`/`next`/`stop`/`volume` | No | | Saving (`s`) or applying (`p`) a prompt | No | | Failed or cancelled requests | Add nothing to the total | diff --git a/docs/ci.md b/docs/ci.md index 7f47bb1..f029757 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -29,6 +29,19 @@ POSIX preflight imports sounddevice and reports PortAudio's version; this can initialize the host backend, but the tests use fake streams, not an output device. Native preflight uses `importlib.metadata` without importing sounddevice or fluidsynth, and asserts `sys.platform == "win32"` and Python 3.13. +Each job checks the declared OS and CPU architecture (Linux x64, macOS ARM64, +WSL2 x64 or Windows x64). `scripts/check_ci_platform.py verify` also checks that +Git's checkout root and `HEAD` match the run's `GITHUB_SHA`, including in the +WSL copy. This can be a GitHub-generated merge commit on pull-request runs. +The Windows host logs `wsl --list --verbose`; inside Linux the gate requires a +Microsoft WSL2 kernel and Ubuntu 24.04. + +The POSIX jobs use the console script installed by the frozen sync from an +isolated directory. `--help` must succeed cleanly, and `ctl --json status` +must emit the exact no-player success line with exit 0 and empty stderr. The +native Windows job uses source-based CLI checks, not an installed launcher. +These checks never establish audible output; use the +[manual audio and terminal checklist](platform-support.md#check-the-terminal-and-actual-sound). OS packages and Python patch releases can change; this is not a hermetic image. ## Correctness and performance selection diff --git a/docs/platform-support.md b/docs/platform-support.md new file mode 100644 index 0000000..4859a4d --- /dev/null +++ b/docs/platform-support.md @@ -0,0 +1,34 @@ +# Install and verify the terminal player by platform + +Gentle Stream runs in a terminal on Linux, macOS, Ubuntu on WSL2, and native Windows. The Windows desktop shell is a separate feature; the terminal support below does not install a graphical app on Linux or macOS. You can play the default instrumental without Gentle Shell or a model request. + +## Choose your setup + +| Platform | Audio prerequisite | What the test matrix covers | +| --- | --- | --- | +| Ubuntu 24.04 x64 | `sudo apt-get install libportaudio2` and a working output device | Installed console and full device-free correctness suite | +| macOS ARM64 | `brew install portaudio` and a working Core Audio output | Installed console and full device-free correctness suite on `macos-15` | +| Ubuntu 24.04 on WSL2 x64 | `sudo apt-get install libportaudio2` and configured WSLg audio; alternatively use the [Windows FFplay bridge](windows-wsl.md#optional-native-windows-audio) | Installed console and full device-free correctness suite in actual WSL2 | +| Native Windows x64 | The Windows `sounddevice` wheel includes PortAudio; follow [Native Windows setup](windows-native.md) | Focused device-free source contracts, not an installed-console job | + +These are the configured CI targets, not a claim that every revision or audio device passed. Linux ARM64, Intel macOS and WSL ARM64 are not verified by this matrix. On Linux, the distro's package name and audio stack may differ. In WSL, keep the checkout under your Linux home rather than `/mnt/c`; a POSIX runtime directory is required for Unix sockets. Use `wsl --list --verbose` from Windows to check that the distro is version 2. + +From the checkout, with `uv` available: + +```sh +uv sync --locked --python 3.13 +uv run --locked gentle-stream --help +``` + +For WSL, the optional [Windows Gentle Shell adapter](windows-wsl.md#connect-the-windows-gentle-shell-already-installed-on-your-device) is independent of the audio backend. Start with the default audio path, then test FFplay separately only if you use it. + +## Check the terminal and actual sound + +Use a test account, VM, or isolated runtime and preference directories. Do not attach to or stop an existing listening session to run this checklist. + +1. In the test environment, run `uv run --locked gentle-stream ctl --json status` before launching. It should return `{"ok": true, "running": false}`. If it reports an existing session, stop the *test* and isolate it rather than stopping that player. +2. Run `uv run --locked gentle-stream` in an interactive terminal, with no `--mood` or automatic model request. Confirm that the UI draws and you hear the default instrumental on the selected output device. The moving spectrum or a `playing` status is not a substitute for hearing it. +3. With `Space`, pause and resume. Listen for the output to stop and resume, then try the volume keys. Press `b` to detach and reopen the terminal player to check that it attaches to the same test playback. Quit the test player with `q` and check that `ctl --json status` is back to `running:false`. +4. For WSL, record WSLg/PortAudio and optional Windows FFplay as **separate** tests. An audio failure on one path does not validate or disprove the other. + +When reporting a result, include the exact checked-out Git SHA, OS/distro, architecture, Python version, audio backend, and which steps passed or failed. Do not include account details, credentials, or provider output. See [device-free CI](ci.md) for scope and limitations. diff --git a/scripts/check_ci_platform.py b/scripts/check_ci_platform.py new file mode 100644 index 0000000..9c7b1a1 --- /dev/null +++ b/scripts/check_ci_platform.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +"""Check a CI runner and its checkout, or smoke the installed console script.""" + +import argparse +import os +from pathlib import Path +import platform +import re +import subprocess +import sys + + +SYSTEMS = {"Linux": "linux", "macOS": "darwin", "Windows": "win32", "WSL": "linux"} +MACHINES = {"amd64": "x64", "x86_64": "x64", "arm64": "arm64", "aarch64": "arm64"} +NO_SESSION = '{"ok": true, "running": false}\n' + + +class CheckFailed(Exception): + pass + + +def verify(target: str, arch: str) -> None: + system, machine, kernel = sys.platform, platform.machine(), platform.release() + if system != SYSTEMS[target]: + raise CheckFailed(f"expected sys.platform={SYSTEMS[target]}, got {system}") + if MACHINES.get(machine.lower()) != arch: + raise CheckFailed(f"expected architecture {arch}, got {machine}") + + evidence = f"{target}/{arch}: sys.platform={system} machine={machine} kernel={kernel}" + if target == "Linux" and "microsoft" in kernel.lower(): + raise CheckFailed("expected native Linux, not WSL") + if target == "WSL": + # The Windows list is logged separately; its state labels are localized. + if not re.search(r"\bmicrosoft(?:-standard)?-wsl2\b", kernel, re.IGNORECASE): + raise CheckFailed("expected a Microsoft WSL2 kernel") + distro = platform.freedesktop_os_release() + if (distro.get("ID"), distro.get("VERSION_ID")) != ("ubuntu", "24.04"): + raise CheckFailed("expected distro ubuntu:24.04") + evidence += " distro=ubuntu:24.04" + + sha = os.environ.get("GITHUB_SHA", "") + if not re.fullmatch(r"[0-9a-fA-F]{40}", sha): + raise CheckFailed("GITHUB_SHA is missing or is not a full commit SHA") + source = Path.cwd() + env = os.environ.copy() + for key in ("GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_NAMESPACE"): + env.pop(key, None) + git = subprocess.run(["git", "rev-parse", "--show-toplevel", "HEAD"], cwd=source, + env=env, capture_output=True, text=True, encoding="utf-8", timeout=15) + lines = git.stdout.splitlines() + if git.returncode or len(lines) != 2: + raise CheckFailed("could not read checkout root and HEAD") + root, head = lines + if Path(root).resolve() != source.resolve(): + raise CheckFailed("run the check at the actual checkout root") + if head != sha.lower(): + raise CheckFailed("checkout HEAD does not match GITHUB_SHA") + print(evidence) + print(f"Checkout HEAD matches GITHUB_SHA: {head}") + + +def smoke(executable: Path, scratch: Path) -> None: + executable, scratch = executable.absolute(), scratch.absolute() + scratch.mkdir(mode=0o700) # Require a new directory, including a new runtime namespace. + env = {k: v for k, v in os.environ.items() if not k.startswith(("PYTHON", "GENTLE_STREAM_"))} + for key, name in {"HOME": "home", "XDG_CONFIG_HOME": "config", "XDG_CACHE_HOME": "cache", + "XDG_RUNTIME_DIR": "run", "TMPDIR": "tmp"}.items(): + directory = scratch / name + directory.mkdir(mode=0o700) + env[key] = str(directory) + # status only attaches. If it regresses to ensure(), refuse audio before any spawn. + env.update(GENTLE_STREAM_AUDIO_OUTPUT="ci-no-player-start", PYTHONDONTWRITEBYTECODE="1", LC_ALL="C") + + def run(*args: str) -> subprocess.CompletedProcess: + # Keep bytes so universal-newline conversion cannot hide a framing change. + return subprocess.run([str(executable), *args], cwd=scratch, env=env, + capture_output=True, timeout=15) + + help_result = run("--help") + if (help_result.returncode or help_result.stderr or not help_result.stdout.startswith(b"usage: gentle-stream ") + or b"ctl" not in help_result.stdout or b"setup-samples" not in help_result.stdout): + raise CheckFailed("installed gentle-stream --help did not print clean help") + status = run("ctl", "--json", "status") + if status.returncode or status.stderr or status.stdout != NO_SESSION.encode("ascii"): + raise CheckFailed("installed no-session status did not return the exact success envelope") + print(f"Installed CLI help OK; no-session status: {NO_SESSION}", end="") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + verify_parser = commands.add_parser("verify", help="check platform, architecture and GITHUB_SHA") + verify_parser.add_argument("platform", choices=SYSTEMS) + verify_parser.add_argument("architecture", choices=("x64", "arm64")) + smoke_parser = commands.add_parser("smoke", help="run the installed CLI in fresh isolation") + smoke_parser.add_argument("executable", type=Path) + smoke_parser.add_argument("scratch", type=Path, help="new directory beneath the runner scratch root") + args = parser.parse_args(argv) + try: + if args.command == "verify": + verify(args.platform, args.architecture) + else: + smoke(args.executable, args.scratch) + except (CheckFailed, OSError, subprocess.TimeoutExpired) as exc: + print(f"CI check failed: {exc}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/gentle_stream/__init__.py b/src/gentle_stream/__init__.py index dd457ff..8c65732 100644 --- a/src/gentle_stream/__init__.py +++ b/src/gentle_stream/__init__.py @@ -38,9 +38,10 @@ background playback: the music plays in a background player; gentle-stream attaches to it when it is already playing. - gentle-stream ctl play|pause|toggle|next|stop|status controls it from any terminal - (status prints one JSON line with underruns, output_underflows and buffered_seconds; - diagnostics are null with older players; the others exit 1 when nothing is playing). + gentle-stream ctl play|pause|toggle|next|stop|status|start|volume|mood controls it from any terminal. + status without --json prints one JSON line with underruns, output_underflows and buffered_seconds + (null with older players). start starts or attaches; other actions exit 1 when no player is running. + volume takes a whole percent 0-100; mood takes text. Add --json for one stable machine envelope. native Windows (no WSL): run with Python 3.13+ and the default sounddevice output; no FFplay is needed. @@ -85,39 +86,131 @@ def progress(done: int, total: int | None) -> None: return 0 -def ctl(action: str) -> int: - from .client import NoPlayer, PlayerError, PlayerGone, connect +MOOD_MAX = 200 # Style clamps mood text to 200 characters +_PLAIN_CTL_ACTIONS = ("play", "pause", "toggle", "next", "stop", "status") + +def _parse_volume(value: list[str]) -> int | None: + """The ctl volume percent (a whole number 0-100), or None when the arguments are invalid.""" + if len(value) != 1: + return None try: - player = connect() + percent = int(value[0]) + except (TypeError, ValueError): + return None + return percent if 0 <= percent <= 100 else None + + +def _snapshot(state: dict, style: dict | None = None) -> dict: + """One stable machine snapshot: the current parameters (the rendered style, overridable for a queued mood).""" + style = state["style"] if style is None else style + return {"ok": True, "running": True, "playing": bool(state["playing"]), + "volume": round(float(state["volume"]) * 100), "name": style["name"], "genre": style["genre"], + "mood": style["mood"]} + + +def _error(code: str, message: str) -> dict: + return {"ok": False, "error": {"code": code, "message": message}} + + +def ctl(action: str, as_json: bool = False, value: list[str] | None = None, + gentle_shell: str = "gentle-shell", model: str | None = None) -> int: + """Control the background player; with `--json`, print one machine envelope and exit non-zero on error.""" + value = list(value or []) + + def fail(code: str, message: str, legacy: str | None = None) -> int: + if as_json: + print(json.dumps(_error(code, message), ensure_ascii=False)) + else: + print(f"gentle-stream: {legacy or message}", file=sys.stderr) + return 1 + + def ok(snapshot: dict, legacy: dict | None = None) -> int: + if as_json: + print(json.dumps(snapshot, ensure_ascii=False)) + elif legacy is not None: + print(json.dumps(legacy, ensure_ascii=False)) + return 0 + + # Local validation: bad volume, mood or extra arguments never reach the player or the model. + mood = None + if action == "volume": + percent = _parse_volume(value) + if percent is None: + return fail("invalid_request", "volume must be a whole number from 0 to 100") + elif action == "mood": + mood = " ".join(value).strip() + if not mood: + return fail("invalid_request", "mood needs some text") + if len(mood) > MOOD_MAX: + return fail("invalid_request", f"mood is too long ({MOOD_MAX} characters max)") + elif value: + return fail("invalid_request", f"{action} takes no arguments") + + player = None + try: + from .client import NoPlayer, PlayerError, PlayerGone, connect, ensure + player = ensure() if action == "start" else connect() + if action == "status" and not as_json: + style = player.now.style + status = {"running": True, "playing": player.playing, "name": style.name, "genre": style.genre, + "mood": style.mood, "underruns": player.underruns, + "output_underflows": player.output_underflows, "buffered_seconds": player.buffered_seconds} + if getattr(player, 'audio_output', None) == 'windows': + status.update(audio_output='windows', audio_output_error=player.audio_output_error) + print(json.dumps(status, ensure_ascii=False)) + player.detach() + return 0 + if action in ("status", "start"): + state = player.request("state") + now = state["now"]["style"] + legacy = {"running": True, "playing": bool(state["playing"]), "name": now["name"], + "genre": now["genre"], "mood": now["mood"]} + player.detach() + return ok(_snapshot(state), legacy) + if action == "stop": + player.close() + return ok({"ok": True, "running": False}) + if action == "mood": + from .bridge import GentleShell, InterpretError + try: + style = GentleShell(binary=gentle_shell, model=model).interpret(mood, player.style) + except InterpretError as e: + player.detach() + return fail("unavailable", "mood interpretation is unavailable", str(e)) + wanted = style.to_dict() + state = player.request("set_style", style=wanted) + player.detach() + return ok(_snapshot(state, wanted)) + if action == "volume": + state = player.request("set_volume", volume=percent / 100) + else: + state = player.request(action) + player.detach() + return ok(_snapshot(state)) except NoPlayer: if action == "status": - print(json.dumps({"running": False})) - return 0 - print("gentle-stream: nothing is playing", file=sys.stderr) - return 1 + return ok({"ok": True, "running": False}, {"running": False}) + return fail("nothing_playing", "nothing is playing") + except PlayerGone as e: + if not as_json and action in _PLAIN_CTL_ACTIONS: + if player is None: + return fail("unavailable", "the player is unavailable", str(e)) + if action in ("status", "stop"): + raise + return fail("nothing_playing", "nothing is playing") except PlayerError as e: - print(f"gentle-stream: {e}", file=sys.stderr) - return 1 - if action == "status": - style = player.now.style - status = {"running": True, "playing": player.playing, "name": style.name, "genre": style.genre, - "mood": style.mood, "underruns": player.underruns, - "output_underflows": player.output_underflows, "buffered_seconds": player.buffered_seconds} - if getattr(player, 'audio_output', None) == 'windows': - status.update(audio_output='windows', audio_output_error=player.audio_output_error) - print(json.dumps(status, ensure_ascii=False)) - elif action == "stop": - player.close() - return 0 - else: - try: - player.request(action) - except PlayerGone: - print("gentle-stream: nothing is playing", file=sys.stderr) - return 1 - player.detach() - return 0 + if not as_json and action in _PLAIN_CTL_ACTIONS and player is not None: + raise + return fail("unavailable", "the player is unavailable", str(e)) + except Exception: + # A malformed answer, a wrong state shape, or anything else unexpected must never leak a + # traceback, path or secret into the machine envelope; legacy keeps the raw error. + if as_json: + if player is not None: + player.detach() + return fail("unavailable", "unexpected error from the player") + raise def main(argv: list[str] | None = None) -> int: @@ -142,10 +235,17 @@ def main(argv: list[str] | None = None) -> int: sub = ap.add_subparsers(dest="command", metavar="command") sub.add_parser("setup-samples", help="download the FluidR3_GM soundfont (MIT) for sampled instruments, once") ctl_parser = sub.add_parser("ctl", help="control the music playing in the background") - ctl_parser.add_argument("action", choices=("play", "pause", "toggle", "next", "stop", "status")) + ctl_parser.add_argument("action", + choices=("play", "pause", "toggle", "next", "stop", "status", "start", "volume", "mood")) + ctl_parser.add_argument("--json", action="store_true", dest="as_json", + help="print one JSON envelope (ok/error) for machines") + ctl_parser.add_argument("value", nargs="*", metavar="ARG", + help="volume: a whole percent 0-100; mood: the text to interpret") args = ap.parse_args(argv) if args.command == "ctl": - return ctl(args.action) + if not args.as_json and args.action in _PLAIN_CTL_ACTIONS and args.value: + ap.error("unrecognized arguments: " + " ".join(args.value)) + return ctl(args.action, args.as_json, args.value, args.gentle_shell, args.model) if args.command == "setup-samples": from . import samples diff --git a/tests/test_audio_diagnostics.py b/tests/test_audio_diagnostics.py index 518fddc..c928779 100644 --- a/tests/test_audio_diagnostics.py +++ b/tests/test_audio_diagnostics.py @@ -7,10 +7,11 @@ from unittest.mock import patch import numpy as np +import pytest from gentle_stream import main from gentle_stream import daemon -from gentle_stream.client import NoPlayer, PlayerClient +from gentle_stream.client import NoPlayer, PlayerClient, PlayerError from gentle_stream.player import Player from gentle_stream.style import Style @@ -64,6 +65,38 @@ def base_state(): "backend": "fake", "now": {"style": style, "piece": 1, "bar": 2}, "style": style} +def test_plain_play_propagates_wsl_output_refusal(capsys): + class FailedOutput: + def play(self): + raise ValueError("Windows output control failed: supervisor exit status 23") + + class RefusingConnection(Connection): + def recv_bytes(self): + request = self.requests[-1] + if request["cmd"] == "play": + return json.dumps(daemon.handle(FailedOutput(), request)).encode() + return super().recv_bytes() + + player = PlayerClient(RefusingConnection(base_state())) + with patch("gentle_stream.client.connect", return_value=player): + with pytest.raises(PlayerError) as caught: + main(["ctl", "play"]) + assert str(caught.value) == "bad request: Windows output control failed: supervisor exit status 23" + assert capsys.readouterr() == ("", "") + + +def test_plain_status_extra_argument_keeps_argparse_error(capsys): + with patch("gentle_stream.client.connect") as connect: + with pytest.raises(SystemExit) as caught: + main(["ctl", "status", "typo"]) + connect.assert_not_called() + assert caught.value.code == 2 + out, err = capsys.readouterr() + assert out == "" + assert err.startswith("usage: gentle-stream ") + assert err.endswith("gentle-stream: error: unrecognized arguments: typo\n") + + class AudioDiagnosticsTests(unittest.TestCase): def player(self): player = Player(FakeEngine()) diff --git a/tests/test_ci_platform.py b/tests/test_ci_platform.py new file mode 100644 index 0000000..f0221ed --- /dev/null +++ b/tests/test_ci_platform.py @@ -0,0 +1,146 @@ +"""Device-free checks of the CI gate, with no real git or CLI subprocesses.""" + +import os +from pathlib import Path +import subprocess + +import pytest + +from scripts import check_ci_platform as check + + +SHA = "a" * 40 +KERNEL = "6.6.87.2-microsoft-standard-WSL2" + + +@pytest.fixture +def host(monkeypatch): + def configure(system, machine, release="6.8.0-generic", distro=("ubuntu", "24.04"), + sha=SHA, head=SHA, root=Path.cwd(), git_exit=0): + monkeypatch.setattr(check.sys, "platform", system) + monkeypatch.setattr(check.platform, "machine", lambda: machine) + monkeypatch.setattr(check.platform, "release", lambda: release) + monkeypatch.setattr(check.platform, "freedesktop_os_release", + lambda: dict(zip(("ID", "VERSION_ID"), distro))) + if sha is None: + monkeypatch.delenv("GITHUB_SHA", raising=False) + else: + monkeypatch.setenv("GITHUB_SHA", sha) + calls = [] + + def git(argv, *, cwd, **kwargs): + calls.append(argv) + assert argv == ["git", "rev-parse", "--show-toplevel", "HEAD"] + assert cwd == Path.cwd() + return subprocess.CompletedProcess(argv, git_exit, f"{root}\n{head}\n", "") + + monkeypatch.setattr(check.subprocess, "run", git) + return calls + + return configure + + +@pytest.mark.parametrize(("target", "arch", "system", "machine", "release"), [ + ("Linux", "x64", "linux", "x86_64", "6.8.0-generic"), + ("macOS", "arm64", "darwin", "arm64", "24.6.0"), + ("Windows", "x64", "win32", "AMD64", "10"), + ("WSL", "x64", "linux", "x86_64", KERNEL), +]) +def test_verify_reports_actual_platform_and_head(host, capsys, target, arch, system, machine, release): + calls = host(system, machine, release) + assert check.main(["verify", target, arch]) == 0 + platform_line = f"{target}/{arch}: sys.platform={system} machine={machine} kernel={release}" + if target == "WSL": + platform_line += " distro=ubuntu:24.04" + assert capsys.readouterr() == (f"{platform_line}\nCheckout HEAD matches GITHUB_SHA: {SHA}\n", "") + assert len(calls) == 1 + + +@pytest.mark.parametrize(("target", "arch", "system", "machine", "release", "distro", "error"), [ + ("Windows", "x64", "linux", "x86_64", "6.8.0", ("ubuntu", "24.04"), "expected sys.platform=win32, got linux"), + ("macOS", "arm64", "darwin", "x86_64", "24.6.0", ("ubuntu", "24.04"), "expected architecture arm64, got x86_64"), + ("Linux", "x64", "linux", "i686", "6.8.0", ("ubuntu", "24.04"), "expected architecture x64, got i686"), + ("Linux", "x64", "linux", "x86_64", KERNEL, ("ubuntu", "24.04"), "expected native Linux, not WSL"), + ("WSL", "x64", "linux", "x86_64", "6.8.0-generic", ("ubuntu", "24.04"), "expected a Microsoft WSL2 kernel"), + ("WSL", "x64", "linux", "x86_64", "4.4.0-19041-Microsoft", ("ubuntu", "24.04"), "expected a Microsoft WSL2 kernel"), + ("WSL", "x64", "linux", "x86_64", "6.6.0-WSL2", ("ubuntu", "24.04"), "expected a Microsoft WSL2 kernel"), + ("WSL", "x64", "linux", "x86_64", KERNEL, ("ubuntu", "22.04"), "expected distro ubuntu:24.04"), + ("WSL", "x64", "linux", "x86_64", KERNEL, ("debian", "24.04"), "expected distro ubuntu:24.04"), +]) +def test_verify_rejects_wrong_target(host, capsys, target, arch, system, machine, release, distro, error): + calls = host(system, machine, release, distro) + assert check.main(["verify", target, arch]) == 1 + assert capsys.readouterr() == ("", f"CI check failed: {error}\n") + assert calls == [] + + +@pytest.mark.parametrize(("overrides", "error", "calls_expected"), [ + ({"sha": None}, "GITHUB_SHA is missing or is not a full commit SHA", 0), + ({"sha": "branch-name"}, "GITHUB_SHA is missing or is not a full commit SHA", 0), + ({"head": "b" * 40}, "checkout HEAD does not match GITHUB_SHA", 1), + ({"root": Path.cwd().parent}, "run the check at the actual checkout root", 1), + ({"git_exit": 128}, "could not read checkout root and HEAD", 1), +]) +def test_verify_fails_closed_on_provenance(host, capsys, overrides, error, calls_expected): + calls = host("linux", "x86_64", **overrides) + assert check.main(["verify", "Linux", "x64"]) == 1 + assert capsys.readouterr() == ("", f"CI check failed: {error}\n") + assert len(calls) == calls_expected + + +HELP = "usage: gentle-stream [-h] command ...\n\n setup-samples download the soundfont\n ctl control the music\n" +STATUS = '{"ok": true, "running": false}\n' + + +@pytest.mark.parametrize(("help_result", "status_result", "failure"), [ + ((0, HELP, ""), (0, STATUS, ""), None), + ((1, HELP, ""), None, "installed gentle-stream --help did not print clean help"), + ((0, "unrelated tool\n", ""), None, "installed gentle-stream --help did not print clean help"), + ((0, HELP, "warning\n"), None, "installed gentle-stream --help did not print clean help"), + ((0, HELP, ""), (1, STATUS, ""), "installed no-session status did not return the exact success envelope"), + ((0, HELP, ""), (0, STATUS, "warning\n"), "installed no-session status did not return the exact success envelope"), + ((0, HELP, ""), (0, STATUS + "extra\n", ""), "installed no-session status did not return the exact success envelope"), + ((0, HELP, ""), (0, STATUS.replace("\n", "\r\n"), ""), + "installed no-session status did not return the exact success envelope"), + ((0, HELP, ""), (0, STATUS.replace("\n", "\r"), ""), + "installed no-session status did not return the exact success envelope"), + ((0, HELP, ""), (0, '{"ok": true, "running": true}\n', ""), + "installed no-session status did not return the exact success envelope"), +]) +def test_installed_smoke_uses_empty_isolated_scratch(monkeypatch, capsys, help_result, status_result, failure): + scratch = Path.cwd() / "fake-smoke" + executable = Path.cwd() / "venv" / "bin" / "gentle-stream" + mkdirs = [] + monkeypatch.setattr(Path, "mkdir", lambda path, *, mode: mkdirs.append((path, mode))) + for key in ("PYTHONPATH", "PYTHONHOME", "GENTLE_STREAM_AUDIO_FACTORY", "XDG_RUNTIME_DIR"): + monkeypatch.setenv(key, "must-not-leak") + calls = [] + + def cli(argv, *, cwd, env, **kwargs): + assert cwd == scratch + assert Path(argv[0]) == executable + for key in ("HOME", "XDG_CACHE_HOME", "XDG_CONFIG_HOME", "XDG_RUNTIME_DIR", "TMPDIR"): + assert (Path(env[key]), 0o700) in mkdirs + assert Path(env[key]).parent == scratch + assert len({env[k] for k in ("HOME", "XDG_CACHE_HOME", "XDG_CONFIG_HOME", "XDG_RUNTIME_DIR", "TMPDIR")}) == 5 + assert all(k not in env for k in ("PYTHONPATH", "PYTHONHOME", "GENTLE_STREAM_AUDIO_FACTORY")) + assert env["GENTLE_STREAM_AUDIO_OUTPUT"] == "ci-no-player-start" + assert not (scratch / "run" / "gentle-stream").exists() + calls.append(argv[1:]) + code, out, err = help_result if argv[1:] == ["--help"] else status_result + if kwargs.get("text"): + # Match subprocess's universal-newline behavior in text mode. + out = out.replace("\r\n", "\n").replace("\r", "\n") + err = err.replace("\r\n", "\n").replace("\r", "\n") + else: + out, err = out.encode(), err.encode() + return subprocess.CompletedProcess(argv, code, out, err) + + monkeypatch.setattr(check.subprocess, "run", cli) + assert check.main(["smoke", os.fspath(executable), os.fspath(scratch)]) == int(failure is not None) + assert mkdirs[0] == (scratch, 0o700) + assert calls == [["--help"]] + ([["ctl", "--json", "status"]] if status_result else []) + if failure: + assert capsys.readouterr() == ("", f"CI check failed: {failure}\n") + else: + assert capsys.readouterr() == (f"Installed CLI help OK; no-session status: {STATUS}", "") diff --git a/tests/test_daemon.py b/tests/test_daemon.py index 5ad7396..be9caec 100644 --- a/tests/test_daemon.py +++ b/tests/test_daemon.py @@ -232,6 +232,13 @@ def run_ctl(capsys, action): return code, out, err +def run_ctl_json(capsys, argv): + """Run `gentle-stream ctl --json` and return (exit code, stdout, stderr).""" + code = main(["ctl", *argv, "--json"]) + out, err = capsys.readouterr() + return code, out, err + + # ------------------------------------------------------------ lifecycle def test_the_first_client_starts_the_player_and_the_next_one_attaches(runtime): from gentle_stream import client @@ -479,3 +486,87 @@ def test_ctl_controls_a_running_player(runtime, capsys): assert run_ctl(capsys, "stop") == (0, "", "") assert not alive(pid) or wait_for(lambda: not alive(pid)) is None assert run_ctl(capsys, "status") == (0, '{"running": false}\n', "") + + +# ------------------------------------------------------------ ctl --json machine interface +def test_ctl_json_status_and_volume_against_a_running_player(runtime, capsys): + from gentle_stream import client + + player = client.ensure() + code, out, err = run_ctl_json(capsys, ["status"]) + assert code == 0 and err == "" + data = json.loads(out) + assert data["ok"] is True and data["running"] is True and data["playing"] is True + assert 0 <= data["volume"] <= 100 + + code, out, err = run_ctl_json(capsys, ["volume", "40"]) + assert code == 0 and err == "" + data = json.loads(out) + assert data["ok"] is True and data["volume"] == 40 + checker = client.connect() + assert checker.volume == pytest.approx(0.4) # the real player moved, not an assumed value + checker.detach() + player.close() + + +def test_ctl_json_volume_rejects_out_of_range_without_changing_the_player(runtime, capsys): + from gentle_stream import client + + player = client.ensure() + before = player.volume + code, out, err = run_ctl_json(capsys, ["volume", "101"]) + assert code == 1 + assert json.loads(out)["error"]["code"] == "invalid_request" + checker = client.connect() + assert checker.volume == before + checker.detach() + player.close() + + +def test_ctl_json_mood_queues_the_style(runtime, capsys, monkeypatch): + from gentle_stream import client + + class FakeShell: + def __init__(self, binary=None, model=None): + self.calls = [] + + def interpret(self, mood, current): + self.calls.append((mood, current)) + return Style.from_dict({"name": "Summer Storm", "genre": "jazz", "mood": mood}, current) + + shell = FakeShell() + monkeypatch.setattr("gentle_stream.bridge.GentleShell", lambda binary=None, model=None: shell) + + player = client.ensure() + code, out, err = run_ctl_json(capsys, ["mood", "storm"]) + assert code == 0 and err == "" + data = json.loads(out) + assert data["ok"] is True and data["mood"] == "storm" + assert data["name"] == "Summer Storm" and data["genre"] == "jazz" + assert shell.calls[0][0] == "storm" + + watcher = client.connect() + wait_for(lambda: watcher.spectrum(8) is not None and watcher.style.name == "Summer Storm", timeout=20) + assert watcher.style.mood == "storm" + watcher.detach() + player.close() + + +def test_ctl_json_start_attaches_or_starts_the_player(runtime, capsys): + from gentle_stream import client + + code, out, err = run_ctl_json(capsys, ["start"]) # nothing playing: start one (fake audio, no model call) + assert code == 0 and err == "" + data = json.loads(out) + assert data["ok"] is True and data["running"] is True and data["playing"] is True + assert 0 <= data["volume"] <= 100 + pid = client.connect().pid + + code, out, err = run_ctl_json(capsys, ["start"]) # already playing: attach to the same player + assert code == 0 and err == "" + data = json.loads(out) + assert data["ok"] is True and data["running"] is True + checker = client.connect() + assert checker.pid == pid # no second player + checker.close() + wait_for(lambda: not alive(pid)) diff --git a/tests/test_main.py b/tests/test_main.py index a5d841f..96a9c5d 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -1,6 +1,10 @@ +import json + import pytest from gentle_stream import main +from gentle_stream.client import AudioError, NoPlayer, PlayerError +from gentle_stream.style import Style from tests.test_daemon import runtime # noqa: F401 (fixture: private runtime dir, fake audio, cleanup) @@ -72,3 +76,318 @@ def test_setup_samples_reports_a_checksum_mismatch(tmp_path, monkeypatch, capsys monkeypatch.setattr(samples, "DEB_SHA256", "0" * 64) assert main(["setup-samples"]) == 1 assert "checksum" in capsys.readouterr().err.lower() + + +# ------------------------------------------------------------ ctl JSON machine interface +ENVELOPE_KEYS = ["ok", "running", "playing", "volume", "name", "genre", "mood"] + + +def fake_state(style=None, playing=True, volume=0.6): + style = style or Style(name="Midnight Rain", mood="", genre="lofi") + return {"pid": 999, "playing": playing, "volume": volume, "level": 0.4, "backend": "procedural", + "now": {"style": style.to_dict(), "piece": 1, "bar": 0}, "style": style.to_dict()} + + +class FakeClient: + """A `client.PlayerClient` stand-in for the CLI tests; no socket, no audio.""" + + def __init__(self, state, apply=True): + self.state = dict(state) + self.style = Style.from_dict(state["style"]) + self.requests = [] + self.closed = self.detached = False + self._apply = apply + + def request(self, cmd, **args): + self.requests.append((cmd, args)) + if self._apply: + if cmd == "set_volume": + self.state["volume"] = float(min(1.0, max(0.0, args["volume"]))) + elif cmd == "pause": + self.state["playing"] = False + elif cmd == "play": + self.state["playing"] = True + elif cmd == "toggle": + self.state["playing"] = not self.state["playing"] + elif cmd == "set_style": + self.state["style"] = args["style"] + self.style = Style.from_dict(args["style"]) + return dict(self.state) + + def close(self): + self.closed = True + + def detach(self): + self.detached = True + + +class FakeShell: + """A `bridge.GentleShell` stand-in: interpretation is deterministic and never calls a model.""" + + def __init__(self, binary="gentle-shell", model=None): + self.binary, self.model = binary, model + self.calls = [] + self.error = None + self.answer = {"name": "Summer Storm", "genre": "jazz"} + + def interpret(self, mood, current): + from gentle_stream.bridge import InterpretError + + self.calls.append((mood, current)) + if self.error: + raise InterpretError(self.error) + return Style.from_dict({**self.answer, "mood": mood}, current) + + +def test_ctl_status_json_reports_the_snapshot_envelope(monkeypatch, capsys): + client = FakeClient(fake_state()) + monkeypatch.setattr("gentle_stream.client.connect", lambda: client) + assert main(["ctl", "status", "--json"]) == 0 + out = capsys.readouterr().out + assert out.endswith("\n") and out.count("\n") == 1 + data = json.loads(out) + assert data == {"ok": True, "running": True, "playing": True, "volume": 60, + "name": "Midnight Rain", "genre": "lofi", "mood": ""} + assert list(data) == ENVELOPE_KEYS + + +def test_ctl_status_json_without_a_player_is_ok_running_false(monkeypatch, capsys): + monkeypatch.setattr("gentle_stream.client.connect", lambda: (_ for _ in ()).throw(NoPlayer("x"))) + assert main(["ctl", "status", "--json"]) == 0 + assert json.loads(capsys.readouterr().out) == {"ok": True, "running": False} + + +@pytest.mark.parametrize("action", ["play", "pause", "toggle", "next", "stop"]) +def test_ctl_json_action_without_a_player_is_nothing_playing(monkeypatch, capsys, action): + monkeypatch.setattr("gentle_stream.client.connect", lambda: (_ for _ in ()).throw(NoPlayer("x"))) + assert main(["ctl", action, "--json"]) == 1 + assert json.loads(capsys.readouterr().out) == {"ok": False, + "error": {"code": "nothing_playing", + "message": "nothing is playing"}} + + +def test_ctl_volume_json_validates_and_applies_the_percent_scale(monkeypatch, capsys): + client = FakeClient(fake_state()) + monkeypatch.setattr("gentle_stream.client.connect", lambda: client) + assert main(["ctl", "volume", "60", "--json"]) == 0 + data = json.loads(capsys.readouterr().out) + assert data["ok"] is True and data["volume"] == 60 + assert client.requests == [("set_volume", {"volume": 0.6})] + + +@pytest.mark.parametrize("value", [["abc"], ["-1"], ["101"], ["60.5"], ["60", "70"], []]) +def test_ctl_volume_json_rejects_bad_values_without_contacting_the_player(monkeypatch, capsys, value): + called = [] + monkeypatch.setattr("gentle_stream.client.connect", lambda: called.append(True)) + assert main(["ctl", "volume", *value, "--json"]) == 1 + data = json.loads(capsys.readouterr().out) + assert data["ok"] is False and data["error"]["code"] == "invalid_request" + assert called == [] + + +def test_ctl_volume_json_reports_the_actual_snapshot_not_assumed_success(monkeypatch, capsys): + client = FakeClient(fake_state(playing=False), apply=False) # a player that reports it stayed paused + monkeypatch.setattr("gentle_stream.client.connect", lambda: client) + assert main(["ctl", "play", "--json"]) == 0 + data = json.loads(capsys.readouterr().out) + assert data["ok"] is True and data["playing"] is False + + +def test_ctl_mood_json_uses_the_model_and_reports_the_queued_style(monkeypatch, capsys): + current = Style(name="Current", mood="old mood") + client = FakeClient(fake_state(current)) + shell = FakeShell() + + def factory(binary=None, model=None): + shell.binary, shell.model = binary, model + return shell + + monkeypatch.setattr("gentle_stream.client.connect", lambda: client) + monkeypatch.setattr("gentle_stream.bridge.GentleShell", factory) + assert main(["ctl", "mood", "rainy night", "--json"]) == 0 + data = json.loads(capsys.readouterr().out) + assert data["ok"] is True and data["name"] == "Summer Storm" + assert data["genre"] == "jazz" and data["mood"] == "rainy night" + assert shell.calls == [("rainy night", current)] + assert (shell.binary, shell.model) == ("gentle-shell", None) + assert client.requests[0][0] == "set_style" + assert client.requests[0][1]["style"]["mood"] == "rainy night" + + +def test_ctl_mood_json_passes_the_model_and_binary_to_the_shell(monkeypatch, capsys): + client = FakeClient(fake_state()) + seen = {} + + def factory(binary=None, model=None): + seen["shell"] = FakeShell(binary, model) + return seen["shell"] + + monkeypatch.setattr("gentle_stream.client.connect", lambda: client) + monkeypatch.setattr("gentle_stream.bridge.GentleShell", factory) + assert main(["--model", "claude-bridge/claude-haiku-5-5", "--gentle-shell", "/custom/gentle-shell", + "ctl", "mood", "rain", "--json"]) == 0 + shell = seen["shell"] + assert (shell.binary, shell.model) == ("/custom/gentle-shell", "claude-bridge/claude-haiku-5-5") + assert shell.calls[0][0] == "rain" + + +def test_ctl_mood_json_preserves_unicode_and_spaces(monkeypatch, capsys): + shell = FakeShell() + client = FakeClient(fake_state()) + monkeypatch.setattr("gentle_stream.client.connect", lambda: client) + monkeypatch.setattr("gentle_stream.bridge.GentleShell", lambda binary=None, model=None: shell) + mood = "café ☕ 東京 night" + assert main(["ctl", "mood", mood, "--json"]) == 0 + assert shell.calls[0][0] == mood + assert json.loads(capsys.readouterr().out)["mood"] == mood + + +@pytest.mark.parametrize("value", [[], [""], [" "], ["x" * 201]]) +def test_ctl_mood_json_rejects_invalid_text_without_contacting_the_player(monkeypatch, capsys, value): + called = [] + monkeypatch.setattr("gentle_stream.client.connect", lambda: called.append(True)) + assert main(["ctl", "mood", *value, "--json"]) == 1 + data = json.loads(capsys.readouterr().out) + assert data["error"]["code"] == "invalid_request" + assert called == [] + + +def test_ctl_mood_json_reports_unavailable_when_interpretation_fails(monkeypatch, capsys): + shell = FakeShell() + shell.error = 'Model "nope" not found.' + client = FakeClient(fake_state()) + monkeypatch.setattr("gentle_stream.client.connect", lambda: client) + monkeypatch.setattr("gentle_stream.bridge.GentleShell", lambda binary=None, model=None: shell) + assert main(["ctl", "mood", "rain", "--json"]) == 1 + assert json.loads(capsys.readouterr().out) == {"ok": False, + "error": {"code": "unavailable", + "message": "mood interpretation is unavailable"}} + assert client.requests == [] + assert client.detached is True + + +def test_ctl_json_errors_never_leak_paths_or_secrets(monkeypatch, capsys): + def boom(): + raise PlayerError("cannot reach the player: /secret/authkey socket=player.sock") + + monkeypatch.setattr("gentle_stream.client.connect", boom) + assert main(["ctl", "status", "--json"]) == 1 + out = capsys.readouterr().out + assert json.loads(out) == {"ok": False, + "error": {"code": "unavailable", "message": "the player is unavailable"}} + assert "/secret" not in out and "authkey" not in out and "player.sock" not in out and "Traceback" not in out + + +def test_ctl_json_unexpected_error_is_a_safe_envelope(monkeypatch, capsys): + class Broken(FakeClient): + def request(self, cmd, **args): + raise KeyError("state missing 'now'") + + monkeypatch.setattr("gentle_stream.client.connect", lambda: Broken(fake_state())) + assert main(["ctl", "status", "--json"]) == 1 + out = capsys.readouterr().out + assert json.loads(out) == {"ok": False, + "error": {"code": "unavailable", "message": "unexpected error from the player"}} + assert "KeyError" not in out and "'now'" not in out and "Traceback" not in out + + +def test_ctl_json_malformed_player_json_is_a_safe_envelope(monkeypatch, capsys): + class Broken(FakeClient): + def request(self, cmd, **args): + raise json.JSONDecodeError("Expecting value", "", 0) + + monkeypatch.setattr("gentle_stream.client.connect", lambda: Broken(fake_state())) + assert main(["ctl", "status", "--json"]) == 1 + out = capsys.readouterr().out + assert json.loads(out) == {"ok": False, + "error": {"code": "unavailable", "message": "unexpected error from the player"}} + assert "Expecting value" not in out and "Traceback" not in out + + +def test_ctl_legacy_unexpected_error_is_raised_not_swallowed(monkeypatch, capsys): + class Broken(FakeClient): + @property + def now(self): + raise KeyError("boom") + + def request(self, cmd, **args): + raise KeyError("boom") + + monkeypatch.setattr("gentle_stream.client.connect", lambda: Broken(fake_state())) + with pytest.raises(KeyError): + main(["ctl", "status"]) + + +def test_ctl_volume_and_mood_legacy_print_nothing_on_success(monkeypatch, capsys): + client = FakeClient(fake_state()) + shell = FakeShell() + monkeypatch.setattr("gentle_stream.client.connect", lambda: client) + monkeypatch.setattr("gentle_stream.bridge.GentleShell", lambda binary=None, model=None: shell) + assert main(["ctl", "volume", "60"]) == 0 + assert capsys.readouterr().out == "" + assert main(["ctl", "mood", "rain"]) == 0 + assert capsys.readouterr().out == "" + assert client.requests[0] == ("set_volume", {"volume": 0.6}) + + +# ------------------------------------------------------------ ctl start --json (the ensure owner) +def test_ctl_start_json_uses_ensure_once_to_attach_or_start(monkeypatch, capsys): + """`start` is the one ctl action that may spawn; it delegates to client.ensure exactly once, never connect.""" + client = FakeClient(fake_state(playing=True, volume=0.55)) + calls = [] + connected = [] + monkeypatch.setattr("gentle_stream.client.ensure", lambda: calls.append("ensure") or client) + monkeypatch.setattr("gentle_stream.client.connect", lambda: connected.append("connect") or client) + assert main(["ctl", "start", "--json"]) == 0 + data = json.loads(capsys.readouterr().out) + assert data == {"ok": True, "running": True, "playing": True, "volume": 55, + "name": "Midnight Rain", "genre": "lofi", "mood": ""} + assert list(data) == ENVELOPE_KEYS + assert calls == ["ensure"] and connected == [] + assert client.detached is True + + +def test_ctl_start_json_reports_the_actual_snapshot_not_assumed_success(monkeypatch, capsys): + client = FakeClient(fake_state(playing=False, volume=0.3), apply=False) # a player that reports it stayed paused + monkeypatch.setattr("gentle_stream.client.ensure", lambda: client) + monkeypatch.setattr("gentle_stream.client.connect", + lambda: (_ for _ in ()).throw(AssertionError("start must use ensure, not connect"))) + assert main(["ctl", "start", "--json"]) == 0 + data = json.loads(capsys.readouterr().out) + assert data["ok"] is True and data["playing"] is False and data["volume"] == 30 + + +def test_ctl_start_json_audio_failure_is_a_safe_unavailable_envelope(monkeypatch, capsys): + def ensure(): + raise AudioError("Error querying device -1") + + monkeypatch.setattr("gentle_stream.client.ensure", ensure) + monkeypatch.setattr("gentle_stream.client.connect", + lambda: (_ for _ in ()).throw(AssertionError("start must use ensure, not connect"))) + assert main(["ctl", "start", "--json"]) == 1 + out = capsys.readouterr().out + assert json.loads(out) == {"ok": False, + "error": {"code": "unavailable", "message": "the player is unavailable"}} + assert "device" not in out and "-1" not in out and "Traceback" not in out + + +def test_ctl_start_json_start_failure_never_leaks_paths_or_secrets(monkeypatch, capsys): + def ensure(): + raise PlayerError("the player did not start in time (see /secret/player.log)") + + monkeypatch.setattr("gentle_stream.client.ensure", ensure) + assert main(["ctl", "start", "--json"]) == 1 + out = capsys.readouterr().out + assert json.loads(out) == {"ok": False, + "error": {"code": "unavailable", "message": "the player is unavailable"}} + assert "/secret" not in out and "player.log" not in out and "Traceback" not in out + + +def test_ctl_status_still_never_starts_a_player(monkeypatch, capsys): + """status and play keep attaching only; `start` is the only ctl action that may spawn.""" + monkeypatch.setattr("gentle_stream.client.ensure", + lambda: (_ for _ in ()).throw(AssertionError("status must never start a player"))) + monkeypatch.setattr("gentle_stream.client.connect", + lambda: (_ for _ in ()).throw(NoPlayer("nothing is playing"))) + assert main(["ctl", "status", "--json"]) == 0 + assert json.loads(capsys.readouterr().out) == {"ok": True, "running": False}