Compare commits
60
Commits
1489d4e7da
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1e760c51b2 | ||
|
|
a0f798d702 | ||
|
|
128752b71e | ||
|
|
93a572cbb5 | ||
|
|
09618bef3d | ||
|
|
120d3ecf32 | ||
|
|
84ae8b283d | ||
|
|
0d67615817 | ||
|
|
aac00356a1 | ||
|
|
85a5acad35 | ||
|
|
2af3c99e4c | ||
|
|
42bd4edf09 | ||
|
|
5a8ebffad2 | ||
|
|
9195d91d7d | ||
|
|
52ec28f278 | ||
|
|
0bf2923edb | ||
|
|
b2738c0d48 | ||
|
|
ea0c1d9774 | ||
|
|
4af32b993d | ||
|
|
edc9a58cbf | ||
|
|
bf13d3914b | ||
|
|
3aa198a787 | ||
|
|
80dc58ea4a | ||
|
|
b41a721086 | ||
|
|
c7e261880a | ||
|
|
61d231523e | ||
|
|
260a792e0b | ||
|
|
227bf6aa21 | ||
|
|
699c46fafb | ||
|
|
4e3543900b | ||
|
|
b416d63735 | ||
|
|
7002721e9b | ||
|
|
1d3e40126d | ||
|
|
f7db5ff686 | ||
|
|
1ab5246fbf | ||
|
|
7f47b64995 | ||
|
|
b215a26d05 | ||
|
|
d13610b410 | ||
|
|
b4d630a66d | ||
|
|
a9421c30f7 | ||
|
|
cff176f3aa | ||
|
|
a6d33ae9e3 | ||
|
|
4912257f64 | ||
|
|
6e216787cf | ||
|
|
9958477cb3 | ||
|
|
7893255fff | ||
|
|
32fde571e6 | ||
|
|
d9f3a63d78 | ||
|
|
8574132baf | ||
|
|
f579ac37bf | ||
|
|
e146ab12a8 | ||
|
|
3f02236f60 | ||
|
|
3b8938c5fb | ||
|
|
5c493362b2 | ||
|
|
c4abbfcc3c | ||
|
|
41d197ee59 | ||
|
|
372235e9d5 | ||
|
|
7250944cc3 | ||
|
|
72745b85d4 | ||
|
|
712aff354b |
No files matched your search
@@ -11,3 +11,5 @@ ALLOWED_HOSTS=
|
|||||||
MCP_BEARER_TOKEN=<GENERATE_TOKEN>
|
MCP_BEARER_TOKEN=<GENERATE_TOKEN>
|
||||||
MAX_VOLUME=40
|
MAX_VOLUME=40
|
||||||
ENABLE_RAW_SSAP=false
|
ENABLE_RAW_SSAP=false
|
||||||
|
CAPTURE_MAX_WIDTH=480
|
||||||
|
CAPTURE_JPEG_QUALITY=55
|
||||||
@@ -13,3 +13,4 @@ webos_rsa
|
|||||||
*.key
|
*.key
|
||||||
id_rsa*
|
id_rsa*
|
||||||
id_ed25519*
|
id_ed25519*
|
||||||
|
.vscode/
|
||||||
@@ -14,7 +14,7 @@ The working tree represents the user's active work.
|
|||||||
3. **Never Overwrite Blindly:** Use available file-reading tools. Preserve user comments, links, and conventions. Prefer surgical edits over wholesale overwrites.
|
3. **Never Overwrite Blindly:** Use available file-reading tools. Preserve user comments, links, and conventions. Prefer surgical edits over wholesale overwrites.
|
||||||
4. **No Destructive Git Commands:** Never run `reset --hard`, `clean -fd`, `restore`, `checkout`, `stash`, `rebase`, or `amend` without explicit permission.
|
4. **No Destructive Git Commands:** Never run `reset --hard`, `clean -fd`, `restore`, `checkout`, `stash`, `rebase`, or `amend` without explicit permission.
|
||||||
5. **Incremental Retrospective Commits:** Commit each coherent, verified micro-step on a working branch rather than accumulating an entire feature into one large commit. Commits on `main` are allowed for documentation changes (not affecting functionality or architecture). Multi-file commits must include structured `-` bullets explaining *what* changed and *why* per area so the Git history tells a retrospective of the design decisions.
|
5. **Incremental Retrospective Commits:** Commit each coherent, verified micro-step on a working branch rather than accumulating an entire feature into one large commit. Commits on `main` are allowed for documentation changes (not affecting functionality or architecture). Multi-file commits must include structured `-` bullets explaining *what* changed and *why* per area so the Git history tells a retrospective of the design decisions.
|
||||||
6. **Live Planning & Task Synchronization:** Authoritative tracker is `kiskaadee/lg-smtv-mcp` on `gitea.roadtotech.me` (Project Board ID `6`: `Project Pipeline`), synchronized against `docs/designs/lg-smtv-mcp.md`. Keep Gitea issues, milestones, and board cards aligned with code reality as slices complete; re-run `gitea-plan` on scope shifts or when reaching a milestone Readiness Gate (such as decomposing `M2` after the `M1` MVP E2E gate).
|
6. **Live Planning & Task Synchronization:** Authoritative tracker is `kiskaadee/lg-smtv-mcp` on `gitea.roadtotech.me` (Project Board ID `6`: `Project Pipeline`, columns `Backlog: 25`, `Ready: 28`, `Work in Progress: 26`, `Review: 29`, `Completed: 27`), synchronized against `ROADMAP.md` and `docs/designs/lg-smtv-mcp.md`. Keep Gitea issues, milestones, and board cards aligned with code reality as slices complete; re-run `gitea-plan` on scope shifts or when reaching a milestone Readiness Gate.
|
||||||
7. **Final Diff Verification:** Before completing work, run `git status` and `git diff` to verify that no unrelated user changes were modified or discarded. Distinguish user changes from agent changes in completion reports.
|
7. **Final Diff Verification:** Before completing work, run `git status` and `git diff` to verify that no unrelated user changes were modified or discarded. Distinguish user changes from agent changes in completion reports.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
# Architecture
|
||||||
|
|
||||||
|
`lg-smtv-mcp` is a stateful, LLM-free Model Context Protocol (MCP) server for local-network control of a single pre-paired LG webOS Smart TV. This document describes the canonical present-state architecture implemented on `main` (Milestone M1 control plane, Milestone M2 Developer Mode capture & `systemd` packaging, and M2.1 host-side JPEG downscaling).
|
||||||
|
|
||||||
|
## System Overview
|
||||||
|
|
||||||
|
The server runs primarily as a persistent `streamable-http` ASGI daemon (via `uvicorn` and FastMCP's `MCPServer`), with `stdio` supported for local test harnesses. A single-owner connection loop inside [`TvManager`](src/lg_smtv_mcp/tv_core/manager.py) maintains warm SSAP WebSocket and `subscribe` state, acquires ephemeral pointer sockets on demand, and exposes bounded control tools over [`server.py`](src/lg_smtv_mcp/server.py).
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
Host["MCP Host / Agent"] -->|"HTTPS / HTTP + Bearer Token"| Auth["BearerAuthMiddleware + TransportSecuritySettings"]
|
||||||
|
Auth --> Server["MCPServer (server.py)"]
|
||||||
|
Server --> Manager["TvManager (tv_core/manager.py)"]
|
||||||
|
Manager --> SSAP["SsapClient (wss://:3001)"]
|
||||||
|
Manager --> Pointer["PointerClient (pointer socket)"]
|
||||||
|
Manager --> WoL["send_wol (UDP :9)"]
|
||||||
|
Manager --> Capturer["CaptureClient (tv_core/capture.py)"]
|
||||||
|
Capturer --> Transport["AsyncSshCaptureTransport (asyncssh/SFTP :9922)"]
|
||||||
|
```
|
||||||
|
|
||||||
|
## Architectural Principles
|
||||||
|
|
||||||
|
- **LLM-free control plane:** No model SDKs, API keys, or internal vision loops exist in the server; decision loops live in the MCP host.
|
||||||
|
- **Boundary validation vs. internal state:** Operator inputs and environment config are validated at startup via frozen Pydantic v2 [`TvConfig`](src/lg_smtv_mcp/config.py) (`extra="forbid"`), raising [`ConfigError`](src/lg_smtv_mcp/errors.py). Runtime TV and protocol failures raise [`TvError(ErrorCode, message)`](src/lg_smtv_mcp/errors.py), mapped to FastMCP `ToolError`.
|
||||||
|
- **Fail-fast standby (`1008`):** WebSocket close code `1008` transitions [`TvManager`](src/lg_smtv_mcp/tv_core/manager.py) to `STANDBY_OFFLINE`. Mutating tools fail fast with `TV_OFFLINE_STANDBY` without implicitly sending Wake-on-LAN; read-only `get_state` bypasses `ui_lock` and returns cached fields with `connected: false, stale: true`.
|
||||||
|
- **Single-owner connection loop:** One background loop owns `wss://<TV_IP>:3001` transitions (`CONNECTING`, `CONNECTED`, `STANDBY_OFFLINE`, `WAKING`, `PAIRING_REQUIRED`), preventing races between stepped reconnect backoff (`2s -> 5s -> 15s -> 30s`) and coalesced `wake()` calls (`45s` `WAKE_TIMEOUT`).
|
||||||
|
- **Protocol-injected testability:** External I/O boundaries (`WebSocketConnectFn`, `WebSocketTransport`, `CaptureTransport`, `FrameCapturer`, `wol_fn`, `wait_fn`) are injected into `tv_core` so all automated tests run offline without touching physical hardware.
|
||||||
|
|
||||||
|
## Components & Responsibilities
|
||||||
|
|
||||||
|
| Component | Location | Responsibility |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| Config & Errors | [`config.py`](src/lg_smtv_mcp/config.py), [`errors.py`](src/lg_smtv_mcp/errors.py) | Stdlib `.env` fallback loader, frozen Pydantic `TvConfig`, `ConfigError` vs. `TvError(ErrorCode, message)`. |
|
||||||
|
| Transport Protocols | [`tv_core/protocols.py`](src/lg_smtv_mcp/tv_core/protocols.py) | `WebSocketTransport`, `WebSocketConnectFn`, `WebSocketClosedError`, `CaptureTransport`, `FrameCapturer`, and frozen result dataclasses (`TvStatus`, `TvStateSnapshot`, `CaptureResult`, `KeysResult`, `TextResult`). |
|
||||||
|
| SSAP Client | [`tv_core/ssap.py`](src/lg_smtv_mcp/tv_core/ssap.py) | `SsapClient` single-reader `_reader_loop()` multiplexing `msg["id"]` responses and `subscribe` callbacks; 16-permission `register` payload; `1008` and `401` mapping; pending `Future` failure on disconnect. |
|
||||||
|
| Pointer Client | [`tv_core/pointer.py`](src/lg_smtv_mcp/tv_core/pointer.py) | `PointerClient` button allowlist normalization/validation (rejecting `\r`/`\n` and unknown keys), `type:button` framing, pacing, and single mid-batch socket re-acquire. |
|
||||||
|
| TV Manager | [`tv_core/manager.py`](src/lg_smtv_mcp/tv_core/manager.py) | `TvManager` state machine, `send_wol`, `subscribe` state cache (`audio/getStatus`, `getForegroundAppInfo`), `ui_lock` (`25s` timeout), `CLIENT_KEY_PATH` reload on backoff/`SIGHUP`, and tool-backing operations. |
|
||||||
|
| Developer Mode Capture | [`tv_core/capture.py`](src/lg_smtv_mcp/tv_core/capture.py) | `CaptureClient` (`FrameCapturer`) triggers `executeOneShot`, pulls the JPEG, and optionally downscales/recompresses via Pillow (`CAPTURE_MAX_WIDTH`, `CAPTURE_JPEG_QUALITY`) before hashing; `AsyncSshCaptureTransport` (`CaptureTransport`) lazily opens/reuses the `asyncssh` SFTP session, maps `KeyImportError` to `SCREENSHOT_UNAVAILABLE`, sweeps stale `/tmp/lg_smtv_cap_*` files while excluding the in-flight capture, and enforces the `6.0s` read deadline plus `1.5s` shielded remove grace. |
|
||||||
|
| HTTP Auth & Security | [`auth.py`](src/lg_smtv_mcp/auth.py) | `BearerAuthMiddleware` (`hmac.compare_digest` on `Authorization: Bearer <token>`) and `build_transport_security_settings` for DNS-rebinding protection. |
|
||||||
|
| MCP Server | [`server.py`](src/lg_smtv_mcp/server.py) | `create_mcp_server` / `create_http_app`, ASGI `lifespan` (`TvManager.start()`/`close()` + `SIGHUP`), `ToolError` mapping, 12 default tools + opt-in `raw_ssap`, `TextContent`/`ImageContent` formatting. |
|
||||||
|
| CLI Entrypoint | [`cli.py`](src/lg_smtv_mcp/cli.py), [`__main__.py`](src/lg_smtv_mcp/__main__.py) | `lg-smtv-mcp serve` (`streamable-http` with fail-closed token check, or `stdio`) and `lg-smtv-mcp pair` (atomic `0600` `.client_key.json` write + optional `--fetch-ssh-key`). |
|
||||||
|
|
||||||
|
## Data Flow & Lifecycle
|
||||||
|
|
||||||
|
1. **Startup:** `cli.py serve` loads [`TvConfig`](src/lg_smtv_mcp/config.py), requires `MCP_BEARER_TOKEN` for `streamable-http`, builds the ASGI app via [`create_http_app`](src/lg_smtv_mcp/server.py), and starts `uvicorn`. The ASGI `lifespan` starts [`TvManager`](src/lg_smtv_mcp/tv_core/manager.py) and registers `SIGHUP` for `.client_key.json` reload.
|
||||||
|
2. **Steady-state & Subscriptions:** When connected, `SsapClient._reader_loop()` routes incoming frames by `msg["id"]` to either awaiting request `Future`s or `subscribe` handlers updating `TvState` (`volume`, `muted`, `sound_output`, `foreground_app`, `last_updated`).
|
||||||
|
3. **Serialized UI Control:** `send_keys`, `type_text`, and `screenshot` acquire `ui_lock` with a `25s` timeout (`LOCK_TIMEOUT`). `create_mcp_server` default-wires `TvManager(..., capture_client=CaptureClient(AsyncSshCaptureTransport(config), max_width=config.capture_max_width, jpeg_quality=config.capture_jpeg_quality))`, so `capture=True` captures over SFTP and optionally downscales/recompresses the JPEG in memory; when the capture transport is unavailable (Developer Mode SSH off or expired), `send_keys` and `type_text` return partial success with `capture_error="SCREENSHOT_UNAVAILABLE: ..."` while `screenshot` fails with `SCREENSHOT_UNAVAILABLE`. `TvManager` closes the SFTP session on standby and transport transitions.
|
||||||
|
4. **Shutdown:** ASGI `lifespan` exit removes the `SIGHUP` handler and awaits `TvManager.close()`, tearing down background tasks and open transports cleanly.
|
||||||
|
|
||||||
|
## Boundaries
|
||||||
|
|
||||||
|
- **Network & Auth:** HTTP requests pass through `TransportSecuritySettings` (DNS-rebinding allowlist from `HOST`/`PORT`/`ALLOWED_HOSTS`) and `BearerAuthMiddleware` (`401` on missing/invalid token).
|
||||||
|
- **Device Boundary:** SSAP (`wss://<TV_IP>:3001`, `ssl.CERT_NONE`), pointer socket (`ws://` / `wss://` returned by `getPointerInputSocket`), WoL (`UDP` broadcast to `WOL_BROADCAST:9`), and Developer Mode SSH/SFTP (`prisoner@<TV_IP>:9922` with `config=[]` and explicit `ssh-rsa` host-key/signature algorithms). Host-key verification is disabled by default on a trusted LAN (`known_hosts=None`) and can be pinned with `SSH_KNOWN_HOSTS_PATH`.
|
||||||
|
- **Persistence:** Client pairing keys are stored as `{ip: client_key}` JSON at `CLIENT_KEY_PATH` (written atomically via `os.replace` with `0600` permissions); optional SSH key retrieval in `pair --fetch-ssh-key` writes with `0600` permissions.
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
- **Runtime (`pyproject.toml` / `flake.nix`):** Python `>=3.14`, `websockets`, `mcp`, `pydantic`, `asyncssh`, `uvicorn`, `pillow`.
|
||||||
|
- **Development / Verification:** `pytest`, `pytest-asyncio`, `httpx`, `ruff`, `pyright` (strict mode).
|
||||||
|
|
||||||
|
## Architectural Constraints
|
||||||
|
|
||||||
|
- Python `>=3.14` (PEP 649 lazy annotations; `from __future__ import annotations` is banned via Ruff `TID251`).
|
||||||
|
- `pyright` runs in `strict` mode across `src/` and `tests/`.
|
||||||
|
- Screenshot capture shares a `6.0s` deadline over `executeOneShot` + SFTP read, plus a `1.5s` shielded cleanup grace, inside the `25s` `ui_lock` budget.
|
||||||
|
- All automated tests run offline against injected `Protocol` doubles; physical TV hardware is never contacted during automated runs.
|
||||||
|
|
||||||
|
## Decision Log Index
|
||||||
|
|
||||||
|
- [ADR-0001: Streamable HTTP Daemon with Stdio Fallback](docs/adr/0001-streamable-http-daemon-with-stdio-fallback.md)
|
||||||
|
- [ADR-0002: LLM-Free MCP Server with Composite Tools](docs/adr/0002-llm-free-mcp-server-with-composite-tools.md)
|
||||||
|
- [ADR-0003: Asyncssh Protocol Boundary for Dev Mode Capture](docs/adr/0003-asyncssh-protocol-boundary-for-dev-mode-capture.md)
|
||||||
|
- [ADR-0004: Sequenced Temp Captures with Cleanup and Sweep](docs/adr/0004-sequenced-temp-captures-with-cleanup-and-sweep.md)
|
||||||
|
- [ADR-0005: Opt-In Raw SSAP Tool Gating](docs/adr/0005-opt-in-raw-ssap-tool-gating.md)
|
||||||
@@ -1,24 +1,312 @@
|
|||||||
# lg-smtv-mcp
|
# lg-smtv-mcp
|
||||||
|
|
||||||
Model Context Protocol (MCP) server for local network control of LG Smart TVs (webOS) over SSAP WebSockets, Wake-on-LAN, and optional Developer Mode SSH screenshot capture.
|
[](https://m8ven.ai/mcp/kiskaadee-lg-smtv-mcp-1hkv9o?s=readme)
|
||||||
|
|
||||||
## Setup
|
A Python Model Context Protocol (MCP) server for persistent, local-network control of LG webOS Smart TVs.
|
||||||
|
|
||||||
|
`lg-smtv-mcp` provides an agent-friendly control plane over LG's Simple Service Access Protocol (SSAP), combining persistent WebSocket connections, remote pointer button input, subscription-based device state tracking, Wake-on-LAN recovery, and optional Developer Mode screenshot capture.
|
||||||
|
|
||||||
|
The server is deliberately **LLM-free**: it exposes bounded, deterministic operations so external AI agents (such as Antigravity, Claude, or a vision-guided decision loop) can reason over UI state and control the television without embedding model APIs into the daemon.
|
||||||
|
|
||||||
|
> **Status: M2 delivered — M2.1 live-TV polish in progress.**
|
||||||
|
> Configuration validation, error taxonomy, [`tv_core`](src/lg_smtv_mcp/tv_core/) (SSAP multiplexer, `PointerClient`, `TvManager`), FastMCP server & Bearer auth ([`server.py`](src/lg_smtv_mcp/server.py), [`auth.py`](src/lg_smtv_mcp/auth.py)), `pair` / `serve` CLI ([`cli.py`](src/lg_smtv_mcp/cli.py)), full-stack offline E2E verification ([`test_e2e_mvp.py`](tests/test_e2e_mvp.py)), Developer Mode SFTP screenshot capture with optional host-side JPEG downscaling ([`capture.py`](src/lg_smtv_mcp/tv_core/capture.py)), and `systemd` unit sandboxing hardening ([#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17)) are implemented on `main`. Ongoing M2.1 polish is tracked in [ROADMAP.md](ROADMAP.md).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Why a Persistent Control Plane?
|
||||||
|
|
||||||
|
Controlling a webOS TV through one-shot scripts introduces avoidable latency and reliability issues: every command has to re-open a TLS WebSocket, re-run the SSAP `register` handshake, re-acquire a pointer input socket, and (for vision workflows) open a fresh SSH/SFTP session.
|
||||||
|
|
||||||
|
`lg-smtv-mcp` addresses this by separating two responsibilities:
|
||||||
|
|
||||||
|
- **MCP Host (Client / Agent):** Owns reasoning, planning, and vision-guided UI navigation.
|
||||||
|
- **MCP Server (`lg-smtv-mcp`):** Owns persistent device connections, protocol multiplexing, cached device state, and bounded command execution.
|
||||||
|
|
||||||
|
Keeping those boundaries separate keeps the server deterministic, fast, and independent of any specific LLM provider or orchestration framework.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Architecture Overview
|
||||||
|
|
||||||
|
The codebase centers on [`tv_core`](src/lg_smtv_mcp/tv_core/), which owns the TV's communication channels and connection state machine:
|
||||||
|
|
||||||
|
| Component | Status | Responsibility |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| [`config.py`](src/lg_smtv_mcp/config.py) & [`errors.py`](src/lg_smtv_mcp/errors.py) | Implemented | Pydantic v2 `TvConfig` validation, `.env` loader, decoupled `ConfigError` vs. `TvError` taxonomy |
|
||||||
|
| [`SsapClient`](src/lg_smtv_mcp/tv_core/ssap.py) | Implemented | Persistent TLS SSAP WebSocket, `msg["id"]` request/subscribe multiplexing, `1008` standby mapping |
|
||||||
|
| [`PointerClient`](src/lg_smtv_mcp/tv_core/pointer.py) | Implemented | Ephemeral webOS pointer socket for allowlisted remote button frames and mid-batch reconnect |
|
||||||
|
| [`TvManager`](src/lg_smtv_mcp/tv_core/manager.py) | Implemented | Single-owner connection loop, stepped backoff, `wake()` coalescing, `subscribe` cache, `ui_lock`, control surface |
|
||||||
|
| [`server.py`](src/lg_smtv_mcp/server.py), [`auth.py`](src/lg_smtv_mcp/auth.py), [`cli.py`](src/lg_smtv_mcp/cli.py) | Implemented | FastMCP tools, `streamable-http` Bearer auth & host validation, `pair` / `serve` CLI, `SIGHUP` key reload |
|
||||||
|
| Developer Mode Capture ([`capture.py`](src/lg_smtv_mcp/tv_core/capture.py)) | Implemented | `CaptureClient` + `AsyncSshCaptureTransport`: `asyncssh` SFTP screenshot retrieval behind the [`FrameCapturer`](src/lg_smtv_mcp/tv_core/protocols.py) / `CaptureTransport` protocols, with a shared `6s` deadline and `/tmp` sweep |
|
||||||
|
|
||||||
|
### Communication Channels
|
||||||
|
|
||||||
|
- **SSAP (`wss://<TV_IP>:3001`):** JSON-over-WebSocket for device control, app launching, IME text input, external input switching, and `subscribe` state streams (`audio/getStatus`, `getForegroundAppInfo`).
|
||||||
|
- **Pointer Input Socket (`wss://...`):** Line-oriented socket obtained via SSAP for remote D-pad and navigation button events (`UP`, `DOWN`, `ENTER`, `HOME`, `BACK`, etc.).
|
||||||
|
- **Wake-on-LAN (UDP):** Explicit device wake-up via magic packets, separated from normal control requests so standby detection fails fast instead of silently waking the TV.
|
||||||
|
- **Developer Mode SSH/SFTP (`prisoner@<TV_IP>:9922`):** Optional remote screenshot capture over a reusable `asyncssh` session (`CaptureClient` behind the `FrameCapturer` protocol, default-wired in [`server.py`](src/lg_smtv_mcp/server.py)). When Developer Mode SSH is unavailable, `keys`/`type_text` still return partial success with `capture_error`, and `screenshot` fails with `SCREENSHOT_UNAVAILABLE`.
|
||||||
|
|
||||||
|
### Design Principles
|
||||||
|
|
||||||
|
- **Persistent connections:** Keep SSAP WebSocket, pointer socket, and subscription state warm across tool calls.
|
||||||
|
- **Explicit state & recovery:** Track `CONNECTING`, `CONNECTED`, `STANDBY_OFFLINE`, `WAKING`, and `PAIRING_REQUIRED` explicitly; mutating calls fail fast on standby (`1008`), while read-only state queries return cached values marked `stale: true`.
|
||||||
|
- **Deterministic & bounded operations:** Enforce allowlisted button keys, batch size/delay limits, `MAX_VOLUME` guardrails, and opt-in `ENABLE_RAW_SSAP`.
|
||||||
|
- **Graceful degradation:** Missing or expired Developer Mode SSH returns `capture_error` alongside `keys_sent: true` / `text_sent: true` without breaking SSAP control.
|
||||||
|
- **LLM independence:** Zero model SDKs, API keys, or internal agent loops in the server.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Current Capabilities & Roadmap
|
||||||
|
|
||||||
|
Implementation is tracked on the [Project Pipeline](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/projects/6):
|
||||||
|
|
||||||
|
| Milestone | Scope | Status |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **M1** | Core config, `tv_core` engine, FastMCP tools, Bearer auth, `pair`/`serve` CLI, E2E verification | Complete (`#1`–`#4` merged on `main`) |
|
||||||
|
| **M2** | Developer Mode SFTP screenshot capture (`asyncssh`), systemd unit, E2E test hardening, sandboxing | Complete (`#11`–`#13`, `#17` merged on `main`) |
|
||||||
|
| **M2.1** | Host-side JPEG downscaling (`#20`), immediate `turn_off` standby (`#21`), Nix sandbox tests (`#22`), settle retry (`#23`) | In progress (`#20` merged; `#21`–`#23` open) |
|
||||||
|
|
||||||
|
Implemented in [`TvManager`](src/lg_smtv_mcp/tv_core/manager.py) and exposed via [`server.py`](src/lg_smtv_mcp/server.py):
|
||||||
|
- Persistent SSAP multiplexing and `subscribe`-backed state snapshots (`get_state`: `volume`, `muted`, `sound_output`, `foreground_app`)
|
||||||
|
- Stepped reconnect backoff and explicit Wake-on-LAN coalescing (`tv_wake`, bounded by `WAKE_TIMEOUT`)
|
||||||
|
- Allowlisted pointer button sequences (`keys`) and IME text entry (`type_text`) with optional `capture` hook (`screenshot`)
|
||||||
|
- App discovery/launching (`list_apps`, `launch`), volume/mute guardrails (`set_volume`, `set_mute`), input discovery/switching (`list_inputs`, `switch_input`), `turn_off`, and opt-in `raw_ssap` (`ENABLE_RAW_SSAP=true`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Prerequisites & Tested Hardware
|
||||||
|
|
||||||
|
Before running the server, make sure you have:
|
||||||
|
|
||||||
|
- **Host Runtime:** Nix with Flakes enabled (recommended) or Python `3.14+`
|
||||||
|
- **Network:** Host and LG webOS Smart TV on the **same local network** (Wake-on-LAN uses UDP broadcast; SSAP uses `wss://<TV_IP>:3001`)
|
||||||
|
- **LG webOS TV Settings:**
|
||||||
|
- **LG Connect Apps** enabled (*Settings -> General -> Devices -> External Devices -> LG Connect Apps*, or *Network -> LG Connect Apps* depending on webOS version)
|
||||||
|
- **Wake-on-LAN / Mobile TV On** enabled (*Turn On via Wi-Fi / Network*) if you want `tv_wake` to power on the TV from standby
|
||||||
|
- **Static IP / DHCP reservation** (recommended) and the TV's **MAC address**
|
||||||
|
- **Optional (for Screenshots):** An LG Developer account and the **Developer Mode** app installed on the TV with **Dev Mode Status** and **Key Server** enabled (SSH/SFTP on port `9922`)
|
||||||
|
|
||||||
|
Initial protocol exploration and live-TV verification were performed against:
|
||||||
|
- **Device:** `65UR8750PSA`
|
||||||
|
- **Platform:** `WebOS/4.1.0`
|
||||||
|
|
||||||
|
Compatibility with other LG webOS models and firmware versions has not yet been established.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Getting Started (Step-by-Step)
|
||||||
|
|
||||||
|
### Step 1: Prepare the Host Environment
|
||||||
|
|
||||||
|
Clone the repository and enter the Nix devShell ([`flake.nix`](flake.nix)):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
git clone https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp.git
|
||||||
|
cd lg-smtv-mcp
|
||||||
nix develop
|
nix develop
|
||||||
```
|
```
|
||||||
|
|
||||||
Provisions Python 3.14, `websockets`, `mcp`, `pydantic`, `asyncssh`, `uvicorn`, `httpx`, `pytest`, `ruff`, and `pyright` via [flake.nix](flake.nix), and configures `.githooks/` (`ruff check`, `ruff format --check`, `pyright`, `pytest`).
|
If you use `direnv`, run `direnv allow` to activate [`.envrc`](.envrc) automatically.
|
||||||
|
|
||||||
## Historical PoC & Empirical Notes
|
The shell provisions Python 3.14, `websockets`, `mcp`, `pydantic`, `asyncssh`, `uvicorn`, `pillow`, `httpx`, `pytest`, `pytest-asyncio`, `ruff`, and `pyright`, and configures `.githooks/` as the Git hooks path.
|
||||||
|
|
||||||
Initial feasibility probes and verified device findings (`65UR8750PSA` / `WebOS/4.1.0`) are archived in [`docs/poc/`](docs/poc/):
|
> **Note:** Inside `nix develop`, run commands using `python -m lg_smtv_mcp <subcommand>` (or `nix run . -- <subcommand>`), as the devShell provisions the Python environment directly rather than installing package console scripts to `PATH`.
|
||||||
|
|
||||||
- [docs/poc/capabilities.md](docs/poc/capabilities.md) — Verified SSAP/DIAL endpoints, deep-link formats, `401` boundaries, and Developer Mode SSH screenshot pipeline.
|
### Step 2: Create and Configure `.env`
|
||||||
- [docs/poc/crunchyroll-e2e-experiment.md](docs/poc/crunchyroll-e2e-experiment.md) — Timed end-to-end vision-loop experiment (Crunchyroll → *Attack on Titan* Ep 1) and latency findings.
|
|
||||||
- [docs/poc/discover.py](docs/poc/discover.py) — SSDP multicast probe (`--all` to list DIAL/DLNA/SSAP services and MAC address).
|
|
||||||
- [docs/poc/tv_test.py](docs/poc/tv_test.py) — One-shot SSAP pairing + command runner.
|
|
||||||
|
|
||||||
## Design & RFC
|
Copy [`.env.example`](.env.example) to `.env` and fill in your TV's IP, MAC address, and a freshly generated Bearer token (never commit `.env`, `.client_key.json`, or SSH keys):
|
||||||
|
|
||||||
- [docs/designs/lg-smtv-mcp.md](docs/designs/lg-smtv-mcp.md) — Architecture RFC for the `lg-smtv-mcp` server.
|
```bash
|
||||||
|
cp .env.example .env
|
||||||
|
openssl rand -hex 32 # use output as MCP_BEARER_TOKEN
|
||||||
|
```
|
||||||
|
|
||||||
|
Minimal `.env` for local use:
|
||||||
|
|
||||||
|
```dotenv
|
||||||
|
TV_IP=<TV_IP>
|
||||||
|
TV_MAC=<TV_MAC>
|
||||||
|
MCP_BEARER_TOKEN=<GENERATED_TOKEN>
|
||||||
|
HOST=127.0.0.1
|
||||||
|
PORT=8765
|
||||||
|
MAX_VOLUME=40
|
||||||
|
```
|
||||||
|
|
||||||
|
If you enable Developer Mode screenshots, also consider setting `CAPTURE_MAX_WIDTH=480` and `CAPTURE_JPEG_QUALITY=55` (as in [`.env.example`](.env.example)) so screenshots stay compact enough for inline MCP delivery without disk offloading.
|
||||||
|
|
||||||
|
### Step 3: Pair with the TV (One-Time)
|
||||||
|
|
||||||
|
Power **on** the TV and ensure *LG Connect Apps* is enabled. Then run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m lg_smtv_mcp pair
|
||||||
|
# Or override TV_IP:
|
||||||
|
python -m lg_smtv_mcp pair --ip <TV_IP>
|
||||||
|
```
|
||||||
|
|
||||||
|
If you also want **Developer Mode screenshot capture**, enable *Developer Mode* and *Key Server* in the TV's Developer Mode app first, then run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m lg_smtv_mcp pair --fetch-ssh-key
|
||||||
|
```
|
||||||
|
|
||||||
|
Accept the pairing prompt on the TV screen using your physical remote:
|
||||||
|
- The SSAP client key is saved atomically with `0600` permissions to `CLIENT_KEY_PATH` (default `.client_key.json`).
|
||||||
|
- `--fetch-ssh-key` downloads the Developer Mode private key from `http://<TV_IP>:9991/webos_rsa` and saves it with `0600` permissions (default `.webos_rsa`). Set `SSH_KEY_PATH=.webos_rsa` (and `WEBOS_SSH_PASSPHRASE` if configured) in `.env`.
|
||||||
|
|
||||||
|
### Step 4: Start the MCP Server
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Default: persistent Streamable HTTP daemon at http://<HOST>:<PORT>/mcp
|
||||||
|
# Requires Authorization: Bearer <MCP_BEARER_TOKEN>
|
||||||
|
python -m lg_smtv_mcp serve
|
||||||
|
|
||||||
|
# Local testing over stdio (no HTTP Bearer token required)
|
||||||
|
python -m lg_smtv_mcp serve --transport stdio
|
||||||
|
```
|
||||||
|
|
||||||
|
If you re-pair while `serve` is running, send `SIGHUP` to reload `.client_key.json` without restarting the daemon.
|
||||||
|
|
||||||
|
### Step 5: Connect Your MCP Client
|
||||||
|
|
||||||
|
Point your MCP host/client at the Streamable HTTP endpoint:
|
||||||
|
|
||||||
|
- **URL:** `http://<HOST>:<PORT>/mcp` (default `http://127.0.0.1:8765/mcp`)
|
||||||
|
- **Header:** `Authorization: Bearer <MCP_BEARER_TOKEN>`
|
||||||
|
|
||||||
|
If your MCP client runs on a different machine than the server, set **both** `HOST=0.0.0.0` (or the server's LAN IP) **and** `ALLOWED_HOSTS=<server-lan-ip-or-hostname>` in `.env`, and place the server behind an HTTPS reverse proxy or encrypted tunnel (e.g., WireGuard/Tailscale) if crossing untrusted networks.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Configuration Reference
|
||||||
|
|
||||||
|
Runtime configuration is loaded by [`load_config()`](src/lg_smtv_mcp/config.py) from process environment variables with `.env` fallback (existing process environment variables always take precedence).
|
||||||
|
|
||||||
|
| Variable | Purpose | Default / Requirement |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| `TV_IP` | Target TV IPv4 address | Required |
|
||||||
|
| `TV_MAC` | Target TV MAC address for Wake-on-LAN | Required for `tv_wake` |
|
||||||
|
| `WOL_BROADCAST` | Wake-on-LAN UDP broadcast IPv4 address | `255.255.255.255` |
|
||||||
|
| `CLIENT_KEY_PATH` | SSAP pairing client-key JSON path | `.client_key.json` |
|
||||||
|
| `SSH_KEY_PATH` | Optional Developer Mode SSH private key path | Unset |
|
||||||
|
| `WEBOS_SSH_PASSPHRASE` | Optional SSH key passphrase | Unset |
|
||||||
|
| `SSH_KNOWN_HOSTS_PATH` | Optional SSH `known_hosts` path | Unset |
|
||||||
|
| `HOST` | HTTP server bind address | `127.0.0.1` |
|
||||||
|
| `PORT` | HTTP server port (`1..65535`) | `8765` |
|
||||||
|
| `ALLOWED_HOSTS` | Comma-separated permitted HTTP `Host` headers | Empty |
|
||||||
|
| `MCP_BEARER_TOKEN` | Bearer token for `streamable-http` transport | Required for HTTP |
|
||||||
|
| `MAX_VOLUME` | Upper bound guardrail (`0..100`) for `set_volume` | `40` |
|
||||||
|
| `ENABLE_RAW_SSAP` | Enables optional `raw_ssap` pass-through (`true`/`false`) | `false` |
|
||||||
|
| `CAPTURE_MAX_WIDTH` | Optional max width (`64..3840`) for host-side JPEG downscaling | Unset (raw passthrough) |
|
||||||
|
| `CAPTURE_JPEG_QUALITY` | Optional JPEG quality (`1..95`; defaults to `75` if only `CAPTURE_MAX_WIDTH` is set) | Unset (raw passthrough) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## systemd Deployment
|
||||||
|
|
||||||
|
The repository includes a unit template at [`deploy/lg-smtv-mcp.service`](deploy/lg-smtv-mcp.service). It runs the server from the project checkout so `nix develop` can use the repository flake.
|
||||||
|
|
||||||
|
1. Prepare the host on the same trusted network as the TV. Install Nix with Flakes enabled, clone this repository to a stable directory, copy `.env.example` to `.env`, and set the required TV coordinates and `MCP_BEARER_TOKEN`. Keep `.env` readable by the service user and private (for example, mode `0600`).
|
||||||
|
2. Copy the template into systemd's unit directory, then replace `<User>` with the account that will run the server and `<WorkingDirectory>` with the absolute repository checkout path. Set `EnvironmentFile` to the `.env` file used for that checkout:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo cp deploy/lg-smtv-mcp.service /etc/systemd/system/lg-smtv-mcp.service
|
||||||
|
sudoedit /etc/systemd/system/lg-smtv-mcp.service
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Check where Nix is installed with `command -v nix`. Replace `<NixBinDir>` in the unit's `PATH` with the directory containing that `nix` executable, keeping the standard system binary directories in the value. The unit starts `/usr/bin/env` by its absolute path; `env` then finds `nix` using the service's configured `PATH`.
|
||||||
|
4. Reload systemd and start the service:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo systemctl daemon-reload
|
||||||
|
sudo systemctl enable --now lg-smtv-mcp.service
|
||||||
|
sudo systemctl status lg-smtv-mcp.service
|
||||||
|
sudo journalctl -u lg-smtv-mcp.service
|
||||||
|
```
|
||||||
|
|
||||||
|
The HTTP server binds to `127.0.0.1` by default and requires `MCP_BEARER_TOKEN`. Use a trusted reverse proxy or VPN if clients need remote access. When exposing the server remotely, set **both** `HOST=0.0.0.0` (or the LAN bind address) **and** `ALLOWED_HOSTS=<proxy-or-vpn-hostname>` in `.env`; the DNS-rebinding check in `auth.py` rejects any request whose `Host` header is not in the allowlist.
|
||||||
|
|
||||||
|
### Sandboxing & Security Profile
|
||||||
|
|
||||||
|
The unit template includes a tested systemd sandboxing baseline (Issue [#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17)), reducing the `systemd-analyze --offline=yes security` exposure score from **9.0 UNSAFE** to **4.9 OK**:
|
||||||
|
|
||||||
|
- **Adopted Directives:**
|
||||||
|
- `StartLimitIntervalSec=60s` / `StartLimitBurst=5`: Bounded restart budget prevents runaway restart loops on persistent environment errors (e.g. missing `.env`).
|
||||||
|
- `NoNewPrivileges=yes`: Prevents process escalation or setuid execution.
|
||||||
|
- `PrivateTmp=yes`: Restricts `/tmp` visibility to an isolated per-service namespace.
|
||||||
|
- `UMask=0077`: Ensures files created by the service are private to the service user.
|
||||||
|
- `ProtectSystem=full`: Mounts `/usr`, `/boot`, and `/etc` read-only.
|
||||||
|
- `ProtectControlGroups=yes`, `ProtectKernelModules=yes`, `ProtectKernelTunables=yes`, `ProtectKernelLogs=yes`, `ProtectClock=yes`, `ProtectHostname=yes`: Prevents tampering with kernel and OS interfaces.
|
||||||
|
- `RestrictRealtime=yes`, `RestrictSUIDSGID=yes`, `LockPersonality=yes`: Restricts privilege escalation vectors.
|
||||||
|
- `CapabilityBoundingSet=`: Drops all Linux kernel capabilities.
|
||||||
|
|
||||||
|
- **Rejected Directives (Compatibility Constraints):**
|
||||||
|
- `ProtectHome=yes` / `ProtectHome=read-only`: Ruled out because `nix develop` requires read-write access to `~/.cache/nix/fetcher-locks` for flake evaluation, and the repository checkout resides under the operator's user directory.
|
||||||
|
- `ProtectSystem=strict`: Ruled out because it mounts the entire filesystem read-only, including the operator's home directory and the repository checkout; `nix develop` needs write access to `~/.cache/nix/fetcher-locks` for flake evaluation (the same constraint that rules out `ProtectHome`). Writable `/tmp` is not the blocker: with `PrivateTmp=yes`, systemd keeps `/tmp` and `/var/tmp` writable even under `strict`.
|
||||||
|
- `PrivateNetwork=yes`: Ruled out because the MCP daemon must communicate over the local network to the TV via SSAP (`wss://:3001`), Developer Mode SSH/SFTP (`:9922`), and Wake-on-LAN UDP broadcasts.
|
||||||
|
|
||||||
|
### Developer Mode SSH Capture Setup
|
||||||
|
|
||||||
|
Enable Developer Mode and the TV's Key Server in the Developer Mode app. Run pairing from the configured checkout as the same service user so the client key and SSH key are saved where the service can read them:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m lg_smtv_mcp pair --fetch-ssh-key
|
||||||
|
```
|
||||||
|
|
||||||
|
Accept the on-screen pairing prompt. The command fetches the SSH key from the TV and saves it with mode `0600` (default path `.webos_rsa`); set `SSH_KEY_PATH` in `.env` to that path. Developer Mode provides SSH/SFTP on port `9922`. Its on-TV countdown timer eventually expires and disables Developer Mode, so screenshot capture then returns `SCREENSHOT_UNAVAILABLE` until Developer Mode is enabled again. Other SSAP tools remain available.
|
||||||
|
|
||||||
|
On a trusted home LAN, SSH host-key checking is disabled by default because the TV regenerates its SSH host key when Developer Mode is reinitialized. To pin the host key instead, set `SSH_KNOWN_HOSTS_PATH` to a `known_hosts` file and update it after Developer Mode renewals.
|
||||||
|
|
||||||
|
## Operator Live-TV E2E Smoke Test Checklist
|
||||||
|
|
||||||
|
Automated tests run strictly offline. After deploying or updating on a host on the same LAN as the TV, run this manual smoke checklist from an MCP client connected to `python -m lg_smtv_mcp serve`:
|
||||||
|
|
||||||
|
- [ ] **`pair`**: Run `python -m lg_smtv_mcp pair`, accept the on-screen TV prompt, and confirm `CLIENT_KEY_PATH` (`.client_key.json`) exists with `0600` permissions and an entry for `<TV_IP>`.
|
||||||
|
- [ ] **`tv_wake`**: With the TV in standby, verify a mutating tool (`launch`) fails fast with `TV_OFFLINE_STANDBY` (no implicit WoL), then call `tv_wake` and confirm the TV powers on and returns `status: "connected"`.
|
||||||
|
- [ ] **`get_state`**: Call `get_state` and confirm `connected: true`, `stale: false`, and live `volume`, `muted`, `sound_output`, and `foreground_app` values.
|
||||||
|
- [ ] **`launch`**: Call `launch` (e.g., `app_id="youtube.leanback.v4"` with an optional `content_target`) and confirm the app opens on screen.
|
||||||
|
- [ ] **`keys`**: Call `keys` with a small batch (e.g., `["DOWN", "ENTER"]`) and confirm D-pad navigation registers on the TV.
|
||||||
|
- [ ] **`screenshot`**: With Developer Mode active and SSH configured, call `screenshot` and confirm the response includes JPEG image content and capture metadata.
|
||||||
|
- [ ] **`keys(..., capture=True)`**: Send a small key batch with capture enabled; confirm the response reports successful key delivery and includes the screenshot. If the Developer Mode timer has expired, confirm the response reports the capture failure while preserving `keys_sent: true`.
|
||||||
|
- [ ] **`set_volume`**: Call `set_volume` with a safe level within `MAX_VOLUME` (e.g., `15`) and confirm the TV volume updates.
|
||||||
|
- [ ] **`turn_off`**: Call `turn_off` and confirm the TV enters standby and subsequent `get_state` reports `connected: false, stale: true`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
All automated tests run offline against mocked transport boundaries (`FakeWebSocketTransport` / `FrameCapturer`) and never contact physical hardware.
|
||||||
|
|
||||||
|
Inside `nix develop`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ruff check .
|
||||||
|
ruff format --check .
|
||||||
|
pyright
|
||||||
|
pytest
|
||||||
|
```
|
||||||
|
|
||||||
|
Or run the full clean-room Nix sandbox verification (matching Gitea Actions CI in [`.gitea/workflows/ci.yaml`](.gitea/workflows/ci.yaml)):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
nix flake check
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
- [Architecture](ARCHITECTURE.md) — Canonical present-state system topology, components, and boundaries
|
||||||
|
- [Roadmap](ROADMAP.md) — Completed M1/M2 milestones and active M2.1 delivery trajectory
|
||||||
|
- [Decision Records](docs/adr/) — MADR records for core architectural choices (`0001`–`0005`)
|
||||||
|
- [Architecture & Design RFC](docs/designs/lg-smtv-mcp.md) — Component contracts, state machine, error taxonomy, and implementation plan
|
||||||
|
- [E2E Benchmarks](docs/experiments/crunchyroll-e2e-comparison.md) — Standardized live-TV Crunchyroll navigation telemetry (baseline vs. post-`#20`)
|
||||||
|
- [Verified Capabilities](docs/poc/capabilities.md) — Empirical SSAP, DIAL, deep-link, and Developer Mode findings
|
||||||
|
- [Crunchyroll E2E Experiment](docs/poc/crunchyroll-e2e-experiment.md) — Initial vision-guided navigation experiment and latency measurements
|
||||||
|
- [Agent & Engineering Guidelines](AGENTS.md) — Coding standards, validation boundaries, protocol invariants, and CI rules
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Released into the public domain under the [Unlicense](LICENSE).
|
||||||
+31
@@ -0,0 +1,31 @@
|
|||||||
|
# Roadmap
|
||||||
|
|
||||||
|
## Current Direction
|
||||||
|
|
||||||
|
`lg-smtv-mcp` has completed Milestone M2 (capture, E2E hardening, and systemd deployment packaging) and `#17` (`systemd` sandboxing hardening). Active work is **Milestone M2.1: Live-TV Polish & Latency Optimizations** (1/4 complete), focused on reducing screenshot payload size/round-trips, fixing immediate `turn_off()` standby transitions, and unblocking `systemd-analyze` checks in the Nix sandbox.
|
||||||
|
|
||||||
|
## Near Term
|
||||||
|
|
||||||
|
- **#21 (`M2.1`):** `fix(manager): transition to STANDBY_OFFLINE immediately on turn_off()` so immediate `tv_wake()` calls do not return `already_connected` before the TV drops `1008`.
|
||||||
|
- **#22 (`M2.1`):** `fix(test): unblock systemd-analyze tests inside Nix build sandbox` (investigate `--root=<tmp_path>` or narrow sandbox-only skip while keeping `nix develop` enforcement strict).
|
||||||
|
- **#23 (`M2.1`):** `feat(capture): add optional wait_for_change settle retry on keys/type_text capture` (500ms bounded retry within the shared 6.0s capture budget when `changed_since_last=false`).
|
||||||
|
|
||||||
|
## Completed
|
||||||
|
|
||||||
|
### M2.1: Live-TV Polish & Latency Optimizations (In Progress — Completed Items)
|
||||||
|
- **#20 (PR [#24](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/24), Completed 2026-11-19):** Added optional `CAPTURE_MAX_WIDTH` (`64..3840`) and `CAPTURE_JPEG_QUALITY` (`1..95`) settings in [`config.py`](src/lg_smtv_mcp/config.py), added `pillow` runtime dependency, and implemented host-side JPEG downscaling/recompression in [`capture.py`](src/lg_smtv_mcp/tv_core/capture.py) (reducing median live-TV capture size by 69.1% and disk-only offloads from 60% to 7%).
|
||||||
|
- **Live-TV E2E Benchmarks (`0d67615`, `84ae8b2`, `128752b`):** Executed standardized Crunchyroll E2E navigation benchmarks against `65UR8750PSA` (`WebOS/4.1.0`) and recorded baseline vs. post-`#20` telemetry in [`docs/experiments/`](docs/experiments/).
|
||||||
|
|
||||||
|
### Post-M2 Hardening (Completed 2026-11-18)
|
||||||
|
- **#17 (PR [#18](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/18)):** Hardened [`deploy/lg-smtv-mcp.service`](deploy/lg-smtv-mcp.service) with bounded restart throttling (`StartLimitIntervalSec=60s`, `StartLimitBurst=5`) and a 14-directive sandboxing baseline (`9.0 UNSAFE` → `4.9 OK`), added automated `systemd-analyze` tests in [`tests/test_deploy.py`](tests/test_deploy.py), documented adopted/rejected directives in [`README.md`](README.md#sandboxing--security-profile), and fixed `asyncssh` SFTP capture reads (`sftp.open()`) in [`src/lg_smtv_mcp/tv_core/capture.py`](src/lg_smtv_mcp/tv_core/capture.py).
|
||||||
|
|
||||||
|
### M2: Capture, E2E Hardening & Systemd Deployment (Completed 2026-11-17)
|
||||||
|
- **#11 (PR [#14](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/14)):** E2E harness hardening in [`tests/test_e2e_mvp.py`](tests/test_e2e_mvp.py) — fast-fail ASGI lifespan startup, `elapsed_ms` contract check, and post-`turn_off()` `1008` -> `get_state` stale parity.
|
||||||
|
- **#12 (PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/15)):** `tv_core/capture.py` (`CaptureClient` + `AsyncSshCaptureTransport`), default `server.py` wiring, and offline capture contract tests; review remediation CR-01..CR-11 landed in `61d2315`.
|
||||||
|
- **#13 (PR [#16](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/16)):** `deploy/lg-smtv-mcp.service` systemd template, deployment + Developer Mode SSH setup docs in `README.md`, and DNS-rebinding / PATH env guidance.
|
||||||
|
|
||||||
|
### M1: MVP Core & End-to-End Verification (Completed 2026-11-16)
|
||||||
|
- **#1 (PR [#6](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/6)):** Nix flake packaging, `pyproject.toml`, Pydantic v2 `TvConfig`, and `ConfigError` / `TvError` taxonomy.
|
||||||
|
- **#2 (PR [#7](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/7)):** `tv_core` (`SsapClient` multiplexer, `PointerClient`, `TvManager` state machine, `FrameCapturer` seam).
|
||||||
|
- **#3 (PR [#9](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/9)):** `MCPServer` tools, `BearerAuthMiddleware` + `TransportSecuritySettings`, ASGI `lifespan`, and `pair` / `serve` CLI.
|
||||||
|
- **#4 (PR [#10](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/10)):** Full-stack offline MVP E2E test (`tests/test_e2e_mvp.py`) and live-TV operator smoke checklist (`README.md`).
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=LG webOS Smart TV MCP server
|
||||||
|
Wants=network-online.target
|
||||||
|
After=network-online.target
|
||||||
|
StartLimitIntervalSec=60s
|
||||||
|
StartLimitBurst=5
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=<User>
|
||||||
|
WorkingDirectory=<WorkingDirectory>
|
||||||
|
EnvironmentFile=<WorkingDirectory>/.env
|
||||||
|
Environment="PATH=<NixBinDir>:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
|
||||||
|
ExecStart=/usr/bin/env nix develop --command python -m lg_smtv_mcp serve
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=5s
|
||||||
|
|
||||||
|
# Sandboxing baseline (Issue #17)
|
||||||
|
NoNewPrivileges=yes
|
||||||
|
PrivateTmp=yes
|
||||||
|
UMask=0077
|
||||||
|
ProtectSystem=full
|
||||||
|
ProtectControlGroups=yes
|
||||||
|
ProtectKernelModules=yes
|
||||||
|
ProtectKernelTunables=yes
|
||||||
|
ProtectKernelLogs=yes
|
||||||
|
ProtectClock=yes
|
||||||
|
ProtectHostname=yes
|
||||||
|
RestrictRealtime=yes
|
||||||
|
RestrictSUIDSGID=yes
|
||||||
|
LockPersonality=yes
|
||||||
|
CapabilityBoundingSet=
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# ADR-0001: Streamable HTTP Daemon with Stdio Fallback
|
||||||
|
|
||||||
|
- Status: Accepted
|
||||||
|
- Date: 2026-11-15
|
||||||
|
- Deciders: kiskaadee
|
||||||
|
|
||||||
|
## Context and Problem Statement
|
||||||
|
One-shot CLI scripts against an LG webOS TV incur ~8–10s per step in repeated `wss://:3001` TLS + `register` handshakes, `getPointerInputSocket` acquisition, and SSH setup, and cannot maintain `subscribe` state streams across tool calls.
|
||||||
|
|
||||||
|
## Decision Outcome
|
||||||
|
Chosen option: "Run `lg-smtv-mcp` primarily as a persistent `streamable-http` ASGI daemon (with `stdio` supported for local test harnesses)", because a long-lived daemon keeps SSAP, `subscribe` state, and pointer/capture sessions warm while `BearerAuthMiddleware` and `TransportSecuritySettings` secure LAN access.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
- Positive: Eliminates per-step TLS/SSAP handshake overhead, preserves `subscribe` cache (`volume`, `muted`, `sound_output`, `foreground_app`), and serializes `ui_lock` across concurrent calls.
|
||||||
|
- Negative: Requires `MCP_BEARER_TOKEN` configuration and daemon lifecycle management (`serve` / `SIGHUP`) when deployed over HTTP.
|
||||||
|
|
||||||
|
## Alternatives Considered
|
||||||
|
- Single-process `stdio` per client only: Rejected because each client session spawns a fresh process, repeating handshakes and contending for the TV's single pointer socket.
|
||||||
|
|
||||||
|
## Related Decisions
|
||||||
|
- Documented in [docs/designs/lg-smtv-mcp.md](../designs/lg-smtv-mcp.md) (Alternative A).
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# ADR-0002: LLM-Free MCP Server with Composite Tools
|
||||||
|
|
||||||
|
- Status: Accepted
|
||||||
|
- Date: 2026-11-15
|
||||||
|
- Deciders: kiskaadee
|
||||||
|
|
||||||
|
## Context and Problem Statement
|
||||||
|
Vision-guided TV UI navigation requires multi-step button presses and screen inspection, which could either be orchestrated inside the MCP server via an embedded VLM loop or delegated to the calling MCP host.
|
||||||
|
|
||||||
|
## Decision Outcome
|
||||||
|
Chosen option: "Keep `lg-smtv-mcp` strictly LLM-free and expose decision-model-friendly composite tools (`keys(..., capture=True)`, `type_text(..., capture=True)`, `frame_sha256` / `changed_since_last`)", because it decouples a local hardware driver from external LLM/VLM SDKs, API keys, and prompt logic while still minimizing round-trips.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
- Positive: Zero model dependencies or outbound API keys in the daemon; deterministic tool behavior; host can skip redundant vision turns when `changed_since_last` is `false`.
|
||||||
|
- Negative: Multi-step navigation loops must be driven by the MCP host/agent rather than a single natural-language tool call.
|
||||||
|
|
||||||
|
## Alternatives Considered
|
||||||
|
- In-server vision navigation sub-loop: Rejected because it couples the hardware control plane to external LLM/VLM providers, model selection, and prompt engineering.
|
||||||
|
|
||||||
|
## Related Decisions
|
||||||
|
- Documented in [docs/designs/lg-smtv-mcp.md](../designs/lg-smtv-mcp.md) (Alternative B).
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# ADR-0003: Asyncssh Protocol Boundary for Dev Mode Capture
|
||||||
|
|
||||||
|
- Status: Accepted (implemented in M2 `#12` / PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/15))
|
||||||
|
- Date: 2026-11-15
|
||||||
|
- Deciders: kiskaadee
|
||||||
|
|
||||||
|
## Context and Problem Statement
|
||||||
|
Retail LG webOS TVs do not serve `/tmp` screenshots over HTTPS (`:3001`), requiring SFTP retrieval from the Developer Mode SSH server (`prisoner@<TV_IP>:9922`) using legacy `ssh-rsa` algorithms.
|
||||||
|
|
||||||
|
## Decision Outcome
|
||||||
|
Chosen option: "Use `asyncssh` (`config=[]`, explicit `ssh-rsa` host-key and signature algorithms) wrapped behind `CaptureTransport` / `FrameCapturer` `Protocol` interfaces", because it keeps SFTP sessions persistent in-process and enables deterministic offline contract testing via protocol doubles.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
- Positive: Eliminates per-capture SSH subprocess startup and `ControlMaster` socket management; cleanly mockable in `pytest`; degrades gracefully to `SCREENSHOT_UNAVAILABLE` when Developer Mode expires.
|
||||||
|
- Negative: Requires explicit legacy `ssh-rsa` algorithm configuration in `asyncssh` and `known_hosts=None` default on LAN (overridable via `SSH_KNOWN_HOSTS_PATH`).
|
||||||
|
|
||||||
|
## Alternatives Considered
|
||||||
|
- OpenSSH `ControlMaster` subprocesses: Rejected because managing background control sockets, parsing subprocess output/exit codes, and writing offline unit tests is more brittle.
|
||||||
|
|
||||||
|
## Related Decisions
|
||||||
|
- Documented in [docs/designs/lg-smtv-mcp.md](../designs/lg-smtv-mcp.md) (Alternative C) and [ADR-0004](0004-sequenced-temp-captures-with-cleanup-and-sweep.md).
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# ADR-0004: Sequenced Temp Captures with Cleanup and Sweep
|
||||||
|
|
||||||
|
- Status: Accepted (implemented in M2 `#12` / PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/15); amended 2026-11-16)
|
||||||
|
- Date: 2026-11-15
|
||||||
|
- Deciders: kiskaadee
|
||||||
|
|
||||||
|
## Context and Problem Statement
|
||||||
|
`ssap://com.webos.service.capture/executeOneShot` writes screenshots to a path on the TV's `/tmp` filesystem (~1.2 GB RAM). Writing to a fixed path risks reading stale frames on silent failure, while uncleaned unique paths can exhaust TV RAM.
|
||||||
|
|
||||||
|
## Decision Outcome
|
||||||
|
Chosen option: "Capture to `/tmp/lg_smtv_cap_<seq>.jpg`, pull bytes into memory only on `returnValue: true`, delete via `finally: sftp.remove()` under a `1–2s` grace period, and sweep `/tmp/lg_smtv_cap_*.jpg` on SFTP connect/reconnect", because it prevents both stale-frame reads and `/tmp` memory exhaustion.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
- Positive: Guarantees fresh frame reads per sequence number and bounds `/tmp` usage even when captures fail or time out.
|
||||||
|
- Negative: Requires a `6s` shared capture deadline plus `1–2s` cleanup grace inside the `25s` `ui_lock` budget.
|
||||||
|
|
||||||
|
## Alternatives Considered
|
||||||
|
- Fixed `/tmp/test.jpg` overwrite path: Rejected because if `executeOneShot` fails silently or races, SFTP pull can read a stale screenshot from an earlier step.
|
||||||
|
|
||||||
|
## Amendment (2026-11-16)
|
||||||
|
|
||||||
|
PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/15) review (CR-01) found that sweeping unconditionally on a new SFTP session deletes the screenshot `executeOneShot` has just written, because the transport connects lazily **after** the capture request. The decision above stands, with one refinement: `sweep_temp_files` accepts `exclude: str | None`, and `_ensure_sftp` passes the in-flight `remote_path`, so a session sweep removes only stale captures left by earlier sessions or crashes. Guarded by `test_async_ssh_capture_transport_sweep_preserves_in_flight_remote_path`.
|
||||||
|
|
||||||
|
## Related Decisions
|
||||||
|
- Documented in [docs/designs/lg-smtv-mcp.md](../designs/lg-smtv-mcp.md) (Alternative D) and [ADR-0003](0003-asyncssh-protocol-boundary-for-dev-mode-capture.md).
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# ADR-0005: Opt-In Raw SSAP Tool Gating
|
||||||
|
|
||||||
|
- Status: Accepted
|
||||||
|
- Date: 2026-11-15
|
||||||
|
- Deciders: kiskaadee
|
||||||
|
|
||||||
|
## Context and Problem Statement
|
||||||
|
Exposing an unrestricted SSAP pass-through tool allows calling arbitrary TV URIs, which expands the MCP tool schema and can bypass safety guardrails such as `MAX_VOLUME` and explicit `turn_off`.
|
||||||
|
|
||||||
|
## Decision Outcome
|
||||||
|
Chosen option: "Omit `raw_ssap` by default and register it only when `ENABLE_RAW_SSAP=true` is explicitly configured", because closed-set decision models stay within safe, bounded tools in normal operation while operators retain an escape hatch for debugging.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
- Positive: Preserves `MAX_VOLUME` and input/power guardrails by default and keeps the MCP tool schema compact.
|
||||||
|
- Negative: Ad-hoc SSAP experiments require restarting the server with `ENABLE_RAW_SSAP=true`.
|
||||||
|
|
||||||
|
## Alternatives Considered
|
||||||
|
- Unconditional `raw_ssap` tool: Rejected because it weakens guardrails and enlarges the tool surface for decision-model callers.
|
||||||
|
|
||||||
|
## Related Decisions
|
||||||
|
- Documented in [docs/designs/lg-smtv-mcp.md](../designs/lg-smtv-mcp.md) (Alternative E).
|
||||||
+105
-130
@@ -3,32 +3,33 @@
|
|||||||
* **Author:** kiskaadee
|
* **Author:** kiskaadee
|
||||||
* **Status:** Approved
|
* **Status:** Approved
|
||||||
* **Date:** 2026-11-15
|
* **Date:** 2026-11-15
|
||||||
|
* **Last reconciled:** 2026-11-21 (M2.1 `#20` / PR [#24](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/24) merged on `main`)
|
||||||
|
|
||||||
--------------------------------------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
`lg-smtv-mcp` is a Python Model Context Protocol (MCP) server for local-network control of a single pre-paired LG webOS Smart TV. It runs primarily as a long-lived `streamable-http` daemon on a homelab server on the same LAN (with `stdio` supported for local testing), keeping the Simple Service Access Protocol (`SSAP`, LG webOS's local JSON-over-WebSocket control protocol on `wss://<TV_IP>:3001`), pointer input socket, `subscribe` state cache, and optional [LG Developer Mode](https://webostv.developer.lg.com/develop/getting-started/developer-mode-app) `asyncssh`/SFTP session (`prisoner@<TV_IP>:9922`) warm. The server contains no LLM or vision-model calls: UI navigation loops live in the MCP host (such as Antigravity, Claude, or a closed-set action-router model like `gemini-decision-1`), while `lg-smtv-mcp` exposes deterministic, decision-model-friendly tools and composite actions (such as batched key sequences with optional inline `ImageContent` screenshots).
|
`lg-smtv-mcp` is a Python Model Context Protocol (MCP) server for local-network control of a single pre-paired LG webOS Smart TV. It runs primarily as a long-lived `streamable-http` daemon on a homelab server on the same LAN (with `stdio` supported for local testing), keeping the Simple Service Access Protocol (`SSAP`, LG webOS's local JSON-over-WebSocket control protocol on `wss://<TV_IP>:3001`), pointer input socket, and `subscribe` state cache warm, and lazily opening a reusable [LG Developer Mode](https://webostv.developer.lge.com/develop/getting-started/developer-mode-app) `asyncssh`/SFTP session (`prisoner@<TV_IP>:9922`) across captures while the TV is awake. The server contains no LLM or vision-model calls: UI navigation loops live in the MCP host (such as Antigravity, Claude, or a closed-set action-router model like `gemini-decision-1`), while `lg-smtv-mcp` exposes bounded, deterministic tools and composite actions (such as batched key sequences with optional inline `ImageContent` screenshots, frame-hash change flags, and gated raw SSAP access).
|
||||||
|
|
||||||
## The Problem
|
## The Problem
|
||||||
|
|
||||||
Controlling an LG webOS TV from an AI agent or automation host using one-shot CLI scripts introduces high per-step latency and reliability gaps (documented in [docs/poc/capabilities.md](../poc/capabilities.md) and [docs/poc/crunchyroll-e2e-experiment.md](../poc/crunchyroll-e2e-experiment.md) against `WebOS/4.1.0`):
|
Controlling an LG webOS TV from an AI agent or automation host using one-shot CLI scripts introduces measurable per-step connection overhead and protocol hazards (documented in [docs/poc/capabilities.md](../poc/capabilities.md) and [docs/poc/crunchyroll-e2e-experiment.md](../poc/crunchyroll-e2e-experiment.md) against `WebOS/4.1.0`):
|
||||||
|
|
||||||
1. **Per-step handshake overhead:** In the Crunchyroll PoC ([docs/poc/crunchyroll-e2e-experiment.md](../poc/crunchyroll-e2e-experiment.md)), navigating from app launch to episode playback took 13 steps and ~7 minutes (`427s`), largely because each step spawned a fresh process, `wss://:3001` TLS + `register` handshake, `getPointerInputSocket` connection, and `scp` session.
|
1. **Per-step handshake overhead:** In the Crunchyroll PoC ([docs/poc/crunchyroll-e2e-experiment.md](../poc/crunchyroll-e2e-experiment.md)), navigating from app launch to episode playback took 13 steps and `427s` (~7 minutes), largely because each step spawned a fresh process, `wss://:3001` TLS + `register` handshake, `getPointerInputSocket` connection, and `scp` session (~8–10s per step).
|
||||||
2. **Protocol hazards on persistent connections:** Running `subscribe` streams (`audio/getStatus`, `getForegroundAppInfo`) concurrently with tool calls breaks one-shot `ws.recv()` patterns. Additionally, when the TV is in standby, `wss://:3001` accepts the WebSocket upgrade and closes immediately with `1008 (Try Again Later (EWS))`, and `ime/insertText` silently returns `returnValue: true` even when the native keyboard is closed.
|
2. **Protocol hazards on persistent connections:** Running `subscribe` streams (`audio/getStatus`, `getForegroundAppInfo`) concurrently with tool calls breaks one-shot `ws.recv()` patterns. Additionally, when the TV is in standby, `wss://:3001` accepts the WebSocket upgrade and closes immediately with `1008 (Try Again Later (EWS))`, and `ime/insertText` silently returns `returnValue: true` even when the native keyboard is closed.
|
||||||
3. **Unbounded token and `/tmp` costs:** Without batched key execution, inline image return, and deterministic frame-change detection (`frame_sha256`), the host pays an extra round-trip and vision-model turn on unchanged frames. Without per-call `/tmp` cleanup, repeated captures can exhaust the TV's ~1.2 GB RAM.
|
3. **Redundant host round-trips and `/tmp` accumulation risk:** Without batched key execution, inline image return, and deterministic frame-change detection (`frame_sha256`), the host must issue separate key and capture calls and cannot detect unchanged frames without inspecting image bytes. Without per-call `/tmp` cleanup, repeated screenshot files accumulate in the TV's `/tmp` filesystem (~1.2 GB system RAM).
|
||||||
|
|
||||||
`lg-smtv-mcp` solves this by keeping persistent, serialized connections inside a homelab `streamable-http` daemon, failing fast on `1008` standby, degrading only capture operations when the TV's Developer Mode SSH session timer expires, and returning compact state/image payloads.
|
`lg-smtv-mcp` addresses this by maintaining persistent, serialized SSAP and pointer connections inside a homelab `streamable-http` daemon (implemented in M1), failing fast on `1008` standby, and implementing optional Developer Mode SFTP capture (M2 `#12`, merged in PR `#15`) so SSH expiration degrades only screenshot capture while returning compact state and image payloads.
|
||||||
|
|
||||||
## Goals
|
## Goals
|
||||||
|
|
||||||
* Run a continuous `streamable-http` MCP daemon bound to a configurable `HOST` address (defaulting to `127.0.0.1` locally, or the homelab LAN interface when deployed) with constant-time `Authorization: Bearer <token>` authentication, plus `stdio` transport for local test harnesses.
|
* Run a continuous `streamable-http` MCP daemon bound to a configurable `HOST` address (defaulting to `127.0.0.1` locally, or a trusted homelab LAN interface when deployed) with `Authorization: Bearer <token>` verification via `hmac.compare_digest`, plus `stdio` transport for local test harnesses.
|
||||||
* Maintain persistent SSAP (`wss://:3001`), pointer input socket, `subscribe` state cache, and optional `asyncssh`/SFTP (`:9922`) connections inside a unified `tv_core` package.
|
* Maintain persistent SSAP (`wss://:3001`), pointer input socket, and `subscribe` state cache connections inside `tv_core`, plus an on-demand `asyncssh`/SFTP (`:9922`) session that stays open across captures while the TV is online and closes on standby.
|
||||||
* Serialize stateful UI and capture operations (`keys`, `type_text`, `screenshot`) with bounded contention while keeping read-only state queries non-blocking.
|
* Serialize stateful UI and capture operations (`keys`, `type_text`, `screenshot`) with bounded contention while keeping read-only state queries non-blocking.
|
||||||
* Fail fast on WebSocket close code `1008` (`TV_OFFLINE_STANDBY`) for mutating tools, return cached flat fields with `connected: false, stale: true` for read-only queries, and provide an explicit `tv_wake` tool using configurable Wake-on-LAN broadcast.
|
* Fail fast on WebSocket close code `1008` (`TV_OFFLINE_STANDBY`) for mutating tools, return cached flat fields with `connected: false, stale: true` for read-only queries, and provide an explicit `tv_wake` tool using configurable Wake-on-LAN broadcast.
|
||||||
* Expose decision-model-friendly composite tools (`keys` with delays and optional inline `ImageContent`, `type_text`, `launch` with deep-link helpers, `screenshot` with `frame_sha256` and `changed_since_last`, `set_volume` with configurable `max_volume=40` cap, explicit `turn_off` / `switch_input`, and opt-in `ENABLE_RAW_SSAP=true`).
|
* Expose bounded composite tools (`keys` with allowlisted buttons, delays, and optional inline `ImageContent`; `type_text`; `launch` with deep-link helpers; `screenshot` with `frame_sha256` and `changed_since_last`; `set_volume` with configurable `max_volume=40` cap; explicit `turn_off` / `switch_input`; and opt-in `ENABLE_RAW_SSAP=true`).
|
||||||
* Provide a one-time CLI `pair` command for interactive on-screen `PROMPT` registration, `client-key` persistence, and optional `--fetch-ssh-key` Developer Mode key retrieval.
|
* Provide a one-time CLI `pair` command for interactive on-screen `PROMPT` registration, `client-key` persistence, and optional `--fetch-ssh-key` Developer Mode key retrieval.
|
||||||
* Verify all behavior offline via `pytest` contract tests over `Protocol` mocks, passing `ruff` and `pyright` inside `nix develop`.
|
* Verify M1 and M2 behavior offline via `pytest` contract tests over `Protocol` mocks, passing `ruff` and `pyright` inside `nix develop`.
|
||||||
|
|
||||||
## Non-Goals
|
## Non-Goals
|
||||||
|
|
||||||
@@ -40,7 +41,7 @@ Controlling an LG webOS TV from an AI agent or automation host using one-shot CL
|
|||||||
|
|
||||||
## Open Questions
|
## Open Questions
|
||||||
|
|
||||||
None. All architectural questions from the initial RFC have been resolved.
|
None.
|
||||||
|
|
||||||
## Critical User Journeys (CUJs)
|
## Critical User Journeys (CUJs)
|
||||||
|
|
||||||
@@ -72,20 +73,20 @@ None. All architectural questions from the initial RFC have been resolved.
|
|||||||
|
|
||||||
### 1. Package & Module Layout
|
### 1. Package & Module Layout
|
||||||
|
|
||||||
All runtime code lives under `src/lg_smtv_mcp/`, separating the transport/protocol boundaries and state machine (`tv_core`) from the MCP tool surface (`server.py`), HTTP Bearer auth (`auth.py`), and CLI entrypoints (`cli.py`).
|
All runtime code lives under `src/lg_smtv_mcp/`, separating the transport/protocol boundaries and state machine (`tv_core`) from the MCP tool surface (`server.py`, built on FastMCP—the high-level `MCPServer` API in the official Python `mcp` SDK), HTTP Bearer auth (`auth.py`), and CLI entrypoints (`cli.py`).
|
||||||
|
|
||||||
| Module | Responsibility |
|
| Module | Responsibility |
|
||||||
| :--- | :--- |
|
| :--- | :--- |
|
||||||
| [`src/lg_smtv_mcp/config.py`](../../src/lg_smtv_mcp/config.py) | Frozen Pydantic v2 `TvConfig` (`extra="forbid"`) loaded from env vars / `.env` (`TV_IP`, `TV_MAC`, `WOL_BROADCAST`, `CLIENT_KEY_PATH`, `SSH_KEY_PATH`, `WEBOS_SSH_PASSPHRASE`, `SSH_KNOWN_HOSTS_PATH`, `HOST`, `PORT`, `ALLOWED_HOSTS`, `MCP_BEARER_TOKEN`, `MAX_VOLUME`, `ENABLE_RAW_SSAP`), raising `ConfigError` on invalid operator config. |
|
| [`src/lg_smtv_mcp/config.py`](../../src/lg_smtv_mcp/config.py) | Frozen Pydantic v2 `TvConfig` (`extra="forbid"`) loaded from env vars / `.env` (`TV_IP`, `TV_MAC`, `WOL_BROADCAST`, `CLIENT_KEY_PATH`, `SSH_KEY_PATH`, `WEBOS_SSH_PASSPHRASE`, `SSH_KNOWN_HOSTS_PATH`, `HOST`, `PORT`, `ALLOWED_HOSTS`, `MCP_BEARER_TOKEN`, `MAX_VOLUME`, `ENABLE_RAW_SSAP`, `CAPTURE_MAX_WIDTH`, `CAPTURE_JPEG_QUALITY`), raising `ConfigError` on invalid operator config. |
|
||||||
| [`src/lg_smtv_mcp/errors.py`](../../src/lg_smtv_mcp/errors.py) | `ConfigError` for startup/config failures and `TvError(ErrorCode, message)` for runtime TV/tool errors (`TV_OFFLINE_STANDBY`, `PAIRING_REQUIRED`, `SCREENSHOT_UNAVAILABLE`, `LOCK_TIMEOUT`, `WAKE_TIMEOUT`, `COMMAND_FAILED`, `INVALID_ARGUMENT`). |
|
| [`src/lg_smtv_mcp/errors.py`](../../src/lg_smtv_mcp/errors.py) | `ConfigError` for startup/config failures and `TvError(ErrorCode, message)` for runtime TV/tool errors (`TV_OFFLINE_STANDBY`, `PAIRING_REQUIRED`, `SCREENSHOT_UNAVAILABLE`, `LOCK_TIMEOUT`, `WAKE_TIMEOUT`, `COMMAND_FAILED`, `INVALID_ARGUMENT`). |
|
||||||
| `src/lg_smtv_mcp/tv_core/protocols.py` *(planned)* | Thin Python `Protocol` interfaces (`WebSocketTransport`, `WebSocketConnectFn`, `WebSocketClosedError`, `CaptureTransport`) enabling offline contract tests. |
|
| [`src/lg_smtv_mcp/tv_core/protocols.py`](../../src/lg_smtv_mcp/tv_core/protocols.py) | Python `Protocol` interfaces (`WebSocketTransport`, `WebSocketConnectFn`, `WebSocketClosedError`, `CaptureTransport`, `FrameCapturer`) and frozen result dataclasses enabling offline contract tests. |
|
||||||
| `src/lg_smtv_mcp/tv_core/ssap.py` *(planned)* | `SsapClient`: single background reader task routing frames by `msg["id"]` to `asyncio.Future`s and `subscribe` callbacks; `PERMISSIONS` constant; `register` + `1008` detection; WebSocket keepalive and pending-`Future` cleanup on disconnect. |
|
| [`src/lg_smtv_mcp/tv_core/ssap.py`](../../src/lg_smtv_mcp/tv_core/ssap.py) | `SsapClient`: single background reader task routing frames by `msg["id"]` to `asyncio.Future`s and `subscribe` callbacks; `PERMISSIONS` constant; `register` + `1008` detection; WebSocket keepalive and pending-`Future` cleanup on disconnect. |
|
||||||
| `src/lg_smtv_mcp/tv_core/pointer.py` *(planned)* | `PointerClient`: acquires `getPointerInputSocket`, normalizes/validates keys, sends plain-text `type:button` frames, and automatically re-acquires the socket if dropped. |
|
| [`src/lg_smtv_mcp/tv_core/pointer.py`](../../src/lg_smtv_mcp/tv_core/pointer.py) | `PointerClient`: acquires `getPointerInputSocket`, normalizes/validates keys, sends plain-text `type:button` frames, and automatically re-acquires the socket if dropped. |
|
||||||
| `src/lg_smtv_mcp/tv_core/capture.py` *(planned)* | `CaptureClient`: calls `executeOneShot` via `ssap_request_fn` and delegates SFTP I/O (`read_and_remove`, `sweep_temp_files`, `close`) to `CaptureTransport` (persistent `asyncssh` session), tracking `frame_sha256` / `changed_since_last`. |
|
| [`src/lg_smtv_mcp/tv_core/capture.py`](../../src/lg_smtv_mcp/tv_core/capture.py) | `CaptureClient` (implementing `FrameCapturer`) and `AsyncSshCaptureTransport` (implementing `CaptureTransport`): calls `executeOneShot` via `ssap_request_fn`, lazily opens/reuses the `asyncssh` SFTP session (`read_and_remove`, `sweep_temp_files`, `close`), maps `KeyImportError` to `SCREENSHOT_UNAVAILABLE`, excludes the in-flight capture from each session sweep, enforces the shared deadline and shielded cleanup, optionally downscales/recompresses JPEGs (`max_width`, `jpeg_quality`) via Pillow, and tracks `frame_sha256` / `changed_since_last`. |
|
||||||
| `src/lg_smtv_mcp/tv_core/manager.py` *(planned)* | `TvManager`: single-owner connection loop + state machine, `send_wol` helper, `subscribe` state cache, stepped reconnect backoff, `CaptureClient` teardown on `STANDBY_OFFLINE`, `.client_key.json` reload on `PAIRING_REQUIRED` backoff/`SIGHUP`, and `ui_lock` (`25s` acquire timeout) serializing UI/capture operations. |
|
| [`src/lg_smtv_mcp/tv_core/manager.py`](../../src/lg_smtv_mcp/tv_core/manager.py) | `TvManager`: single-owner connection loop + state machine, `send_wol` helper, `subscribe` state cache, stepped reconnect backoff, `FrameCapturer` teardown on `STANDBY_OFFLINE`, `.client_key.json` reload on `PAIRING_REQUIRED` backoff/`SIGHUP`, and `ui_lock` (`25s` acquire timeout) serializing UI/capture operations. |
|
||||||
| `src/lg_smtv_mcp/auth.py` *(planned)* | Minimal ASGI Bearer token middleware (`hmac.compare_digest` on `Authorization: Bearer <token>`) wrapping FastMCP's `streamable_http_app()` and `TransportSecuritySettings`. |
|
| [`src/lg_smtv_mcp/auth.py`](../../src/lg_smtv_mcp/auth.py) | ASGI Bearer token middleware (`hmac.compare_digest` on `Authorization: Bearer <token>`) wrapping FastMCP's `streamable_http_app()` and `TransportSecuritySettings`. |
|
||||||
| `src/lg_smtv_mcp/server.py` *(planned)* | FastMCP tool definitions, `ImageContent` formatting, partial-success shaping, `max_volume` enforcement, `ENABLE_RAW_SSAP` gating, and ASGI `lifespan` wiring for `TvManager` + `SIGHUP`. |
|
| [`src/lg_smtv_mcp/server.py`](../../src/lg_smtv_mcp/server.py) | FastMCP (`MCPServer`) tool definitions, `ImageContent` formatting, partial-success shaping, `max_volume` enforcement, `ENABLE_RAW_SSAP` gating, and ASGI `lifespan` wiring for `TvManager` + `SIGHUP`. |
|
||||||
| `src/lg_smtv_mcp/cli.py` *(planned)* | CLI entrypoint supporting `serve` (`streamable-http` with fail-closed `MCP_BEARER_TOKEN` check, or `stdio`) and one-time interactive `pair` (`.client_key.json` + optional `--fetch-ssh-key`). |
|
| [`src/lg_smtv_mcp/cli.py`](../../src/lg_smtv_mcp/cli.py) | CLI entrypoint supporting `serve` (`streamable-http` with fail-closed `MCP_BEARER_TOKEN` check, or `stdio`) and one-time interactive `pair` (`.client_key.json` + optional `--fetch-ssh-key`). |
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
classDiagram
|
classDiagram
|
||||||
@@ -115,6 +116,11 @@ classDiagram
|
|||||||
+send_buttons(keys, delay_ms) int
|
+send_buttons(keys, delay_ms) int
|
||||||
+close() void
|
+close() void
|
||||||
}
|
}
|
||||||
|
class FrameCapturer {
|
||||||
|
<<interface>>
|
||||||
|
+capture_frame(ssap_request_fn) CaptureResult
|
||||||
|
+close() void
|
||||||
|
}
|
||||||
class CaptureClient {
|
class CaptureClient {
|
||||||
+capture_frame(ssap_request_fn) CaptureResult
|
+capture_frame(ssap_request_fn) CaptureResult
|
||||||
+close() void
|
+close() void
|
||||||
@@ -128,12 +134,13 @@ classDiagram
|
|||||||
class CaptureTransport {
|
class CaptureTransport {
|
||||||
<<interface>>
|
<<interface>>
|
||||||
+read_and_remove(remote_path, timeout, cleanup_grace) bytes
|
+read_and_remove(remote_path, timeout, cleanup_grace) bytes
|
||||||
+sweep_temp_files(prefix) void
|
+sweep_temp_files(prefix, exclude) void
|
||||||
+close() void
|
+close() void
|
||||||
}
|
}
|
||||||
TvManager --> SsapClient
|
TvManager --> SsapClient
|
||||||
TvManager --> PointerClient
|
TvManager --> PointerClient
|
||||||
TvManager --> CaptureClient
|
TvManager --> FrameCapturer
|
||||||
|
CaptureClient ..|> FrameCapturer
|
||||||
SsapClient --> WebSocketTransport
|
SsapClient --> WebSocketTransport
|
||||||
PointerClient --> WebSocketTransport
|
PointerClient --> WebSocketTransport
|
||||||
CaptureClient --> CaptureTransport
|
CaptureClient --> CaptureTransport
|
||||||
@@ -144,9 +151,10 @@ classDiagram
|
|||||||
| `TvManager` | `wake() -> TvStatus`, `get_state() -> TvStateSnapshot`, `send_keys(keys, delay_ms, settle_ms, capture) -> KeysResult`, `type_text(text, send_enter, capture) -> TextResult`, `screenshot() -> CaptureResult`, `launch_app(app_id, content_target, params) -> dict`, `list_apps() -> list[dict]`, `set_volume(level) -> dict`, `set_mute(muted) -> dict`, `list_inputs() -> list[dict]`, `switch_input(input_id) -> dict`, `turn_off() -> dict`, `raw_ssap(uri, payload) -> dict` |
|
| `TvManager` | `wake() -> TvStatus`, `get_state() -> TvStateSnapshot`, `send_keys(keys, delay_ms, settle_ms, capture) -> KeysResult`, `type_text(text, send_enter, capture) -> TextResult`, `screenshot() -> CaptureResult`, `launch_app(app_id, content_target, params) -> dict`, `list_apps() -> list[dict]`, `set_volume(level) -> dict`, `set_mute(muted) -> dict`, `list_inputs() -> list[dict]`, `switch_input(input_id) -> dict`, `turn_off() -> dict`, `raw_ssap(uri, payload) -> dict` |
|
||||||
| `SsapClient` | `async connect_and_register(client_key: str \| None) -> str`, `async request(uri: str, payload: dict \| None) -> dict`, `async subscribe(uri: str, callback: Callable[[dict], None]) -> None`, `async close() -> None` |
|
| `SsapClient` | `async connect_and_register(client_key: str \| None) -> str`, `async request(uri: str, payload: dict \| None) -> dict`, `async subscribe(uri: str, callback: Callable[[dict], None]) -> None`, `async close() -> None` |
|
||||||
| `PointerClient` | `async send_buttons(keys: list[str], delay_ms: int) -> int`, `async close() -> None` |
|
| `PointerClient` | `async send_buttons(keys: list[str], delay_ms: int) -> int`, `async close() -> None` |
|
||||||
| `CaptureClient` | `async capture_frame(ssap_request_fn: Callable[[str, dict], Awaitable[dict]]) -> CaptureResult`, `async close() -> None` |
|
| `FrameCapturer` | `async capture_frame(ssap_request_fn: Callable[[str, dict], Awaitable[dict]]) -> CaptureResult`, `async close() -> None` |
|
||||||
|
| `CaptureClient` | `__init__(transport: CaptureTransport)`, implements `FrameCapturer` |
|
||||||
| `WebSocketTransport` | `async send(data: str) -> None`, `async recv() -> str`, `async close() -> None` (raises `WebSocketClosedError(code, reason)` on close); `WebSocketConnectFn = Callable[[str], Awaitable[WebSocketTransport]]` |
|
| `WebSocketTransport` | `async send(data: str) -> None`, `async recv() -> str`, `async close() -> None` (raises `WebSocketClosedError(code, reason)` on close); `WebSocketConnectFn = Callable[[str], Awaitable[WebSocketTransport]]` |
|
||||||
| `CaptureTransport` | `async read_and_remove(remote_path: str, timeout: float, cleanup_grace: float) -> bytes`, `async sweep_temp_files(prefix: str) -> None`, `async close() -> None` |
|
| `CaptureTransport` | `async read_and_remove(remote_path: str, timeout: float, cleanup_grace: float) -> bytes`, `async sweep_temp_files(prefix: str, exclude: str \| None = None) -> None`, `async close() -> None`; implemented by `AsyncSshCaptureTransport(config: TvConfig, connect_fn: ...)` |
|
||||||
|
|
||||||
### 2. Connection State Machine, Frame Dispatch & Concurrency
|
### 2. Connection State Machine, Frame Dispatch & Concurrency
|
||||||
|
|
||||||
@@ -159,7 +167,7 @@ stateDiagram-v2
|
|||||||
CONNECTED --> STANDBY_OFFLINE: Socket closed / 1008 / ping timeout
|
CONNECTED --> STANDBY_OFFLINE: Socket closed / 1008 / ping timeout
|
||||||
CONNECTED --> PAIRING_REQUIRED: Pairing revoked
|
CONNECTED --> PAIRING_REQUIRED: Pairing revoked
|
||||||
STANDBY_OFFLINE --> WAKING: Explicit tv_wake tool called
|
STANDBY_OFFLINE --> WAKING: Explicit tv_wake tool called
|
||||||
STANDBY_OFFLINE --> CONNECTING: Asymmetric backoff
|
STANDBY_OFFLINE --> CONNECTING: Stepped backoff
|
||||||
WAKING --> CONNECTED: Poll succeeds and register active
|
WAKING --> CONNECTED: Poll succeeds and register active
|
||||||
WAKING --> PAIRING_REQUIRED: Wake register returns PROMPT
|
WAKING --> PAIRING_REQUIRED: Wake register returns PROMPT
|
||||||
WAKING --> STANDBY_OFFLINE: Wake poll timeout (45s)
|
WAKING --> STANDBY_OFFLINE: Wake poll timeout (45s)
|
||||||
@@ -168,8 +176,8 @@ stateDiagram-v2
|
|||||||
|
|
||||||
* **SSAP `msg["id"]` Multiplexer:** `SsapClient` runs one background `_reader_loop()` task that owns `ws.recv()`. Responses to one-shot `request()` calls resolve matching `asyncio.Future`s by `msg["id"]`. Live-verified `subscribe` streams on `WebOS/4.1.0` (`ssap://audio/getStatus`—where `volume` and `mute` are top-level and `soundOutput` is nested under `payload["volumeStatus"]["soundOutput"]`—and `ssap://com.webos.applicationManager/getForegroundAppInfo`) update the in-memory `TvStateSnapshot` in `TvManager`. Mutating requests push subscription update frames before their own request response frame, which `msg["id"]` routing demultiplexes. On disconnect, `_reader_loop()`'s `finally:` block fails all pending `Future`s with `TV_OFFLINE_STANDBY`.
|
* **SSAP `msg["id"]` Multiplexer:** `SsapClient` runs one background `_reader_loop()` task that owns `ws.recv()`. Responses to one-shot `request()` calls resolve matching `asyncio.Future`s by `msg["id"]`. Live-verified `subscribe` streams on `WebOS/4.1.0` (`ssap://audio/getStatus`—where `volume` and `mute` are top-level and `soundOutput` is nested under `payload["volumeStatus"]["soundOutput"]`—and `ssap://com.webos.applicationManager/getForegroundAppInfo`) update the in-memory `TvStateSnapshot` in `TvManager`. Mutating requests push subscription update frames before their own request response frame, which `msg["id"]` routing demultiplexes. On disconnect, `_reader_loop()`'s `finally:` block fails all pending `Future`s with `TV_OFFLINE_STANDBY`.
|
||||||
* **Standby & Fail-Fast:** WebSocket close code `1008` (`Try Again Later (EWS)`), ping timeout (`ping_interval=10, ping_timeout=5`), or `open_timeout` (`3.0–4.0s`) transitions `TvManager` to `STANDBY_OFFLINE` and tears down any open `CaptureClient` SSH/SFTP session (which reconnects lazily on the next capture). Mutating tools fail fast with `TV_OFFLINE_STANDBY` without triggering WoL. Read-only queries (`get_state`) bypass `ui_lock` and return the flat state dict (`connected: false, stale: true` with cached values retained from the last online update).
|
* **Standby & Fail-Fast:** WebSocket close code `1008` (`Try Again Later (EWS)`), ping timeout (`ping_interval=10, ping_timeout=5`), or `open_timeout` (`3.0–4.0s`) transitions `TvManager` to `STANDBY_OFFLINE` and tears down any open `CaptureClient` SSH/SFTP session (which reconnects lazily on the next capture). Mutating tools fail fast with `TV_OFFLINE_STANDBY` without triggering WoL. Read-only queries (`get_state`) bypass `ui_lock` and return the flat state dict (`connected: false, stale: true` with cached values retained from the last online update).
|
||||||
* **Single-Owner Reconnect, Wake & Key Reload:** A single connection loop owns `wss://:3001` transitions so `tv_wake` and background reconnect (`2s -> 5s -> 15s -> 30s`) never race. Calling `tv_wake` in `STANDBY_OFFLINE` sends the WoL magic packet, signals the connection loop into `WAKING` (`~1s` polling up to a `45s` `WAKE_TIMEOUT` budget, covering `~30–35s` empirical cold standby boot), and awaits a shared connection event. Concurrent `tv_wake` calls in `WAKING` coalesce onto the in-flight attempt; `tv_wake` in `CONNECTED` returns `{status: "already_connected", elapsed_ms: 0}`; `tv_wake` in `PAIRING_REQUIRED` fails fast with `PAIRING_REQUIRED`. In `PAIRING_REQUIRED`, `TvManager` re-checks `CLIENT_KEY_PATH` (`{ip: client_key}` JSON, written atomically via `os.replace` by `cli.py pair`) on its backoff tick or `SIGHUP` (logging and remaining in `PAIRING_REQUIRED` if the file is missing or malformed).
|
* **Single-Owner Reconnect, Wake & Key Reload:** A single connection loop owns `wss://:3001` transitions so `tv_wake` and stepped background reconnect (`2s -> 5s -> 15s -> 30s`) never race. Calling `tv_wake` in `STANDBY_OFFLINE` sends the WoL magic packet, signals the connection loop into `WAKING` (`~1s` polling up to a `45s` `WAKE_TIMEOUT` budget, covering `~30–35s` empirical cold standby boot), and awaits a shared connection event. Concurrent `tv_wake` calls in `WAKING` coalesce onto the in-flight attempt; `tv_wake` in `CONNECTED` returns `{status: "already_connected", elapsed_ms: 0}`; `tv_wake` in `PAIRING_REQUIRED` fails fast with `PAIRING_REQUIRED`. In `PAIRING_REQUIRED`, `TvManager` re-checks `CLIENT_KEY_PATH` (`{ip: client_key}` JSON, written atomically via `os.replace` by `cli.py pair`) on its backoff tick or `SIGHUP` (logging and remaining in `PAIRING_REQUIRED` if the file is missing or malformed).
|
||||||
* **UI/Capture Serialization & Timeout Budget:** `send_keys`, `type_text`, and `screenshot` acquire `ui_lock` (`asyncio.Lock`) with a `25s` acquire timeout (`LOCK_TIMEOUT` if exceeded). `keys` validates key names against a strict webOS button allowlist (`UP`, `DOWN`, `LEFT`, `RIGHT`, `ENTER`, `BACK`, `HOME`, `EXIT`, `PLAY`, `PAUSE`, `STOP`, `REWIND`, `FASTFORWARD`, `RED`, `GREEN`, `YELLOW`, `BLUE`, `VOLUMEUP`, `VOLUMEDOWN`, `MUTE`, `CHANNELUP`, `CHANNELDOWN`, `INFO`, `GUIDE`, `MENU`, `CC`, `0`–`9`), rejecting unknown names or control characters (`\r`, `\n`) with `INVALID_ARGUMENT`, and bounds `1 <= len(keys) <= 20`, `0 <= delay_ms <= 500`, and `0 <= settle_ms <= 2000`. `CaptureClient.capture_frame()` wraps SSH connect + `executeOneShot` + SFTP read in a shared `6s` deadline (`asyncio.timeout(6.0)`) plus a `1–2s` `finally: sftp.remove()` grace period (`<= 8s` capture phase), keeping worst-case `keys` + `capture` hold time within the `25s` `ui_lock` budget.
|
* **UI/Capture Serialization & Timeout Budget:** `send_keys`, `type_text`, and `screenshot` acquire `ui_lock` (`asyncio.Lock`) with a `25s` acquire timeout (`LOCK_TIMEOUT` if exceeded). `keys` validates key names against a strict webOS button allowlist (`UP`, `DOWN`, `LEFT`, `RIGHT`, `ENTER`, `BACK`, `HOME`, `EXIT`, `PLAY`, `PAUSE`, `STOP`, `REWIND`, `FASTFORWARD`, `RED`, `GREEN`, `YELLOW`, `BLUE`, `VOLUMEUP`, `VOLUMEDOWN`, `MUTE`, `CHANNELUP`, `CHANNELDOWN`, `INFO`, `GUIDE`, `MENU`, `CC`, `0`–`9`), rejecting unknown names or control characters (`\r`, `\n`) with `INVALID_ARGUMENT`, and bounds `1 <= len(keys) <= 20`, `0 <= delay_ms <= 500`, and `0 <= settle_ms <= 2000`. `CaptureClient.capture_frame()` wraps `executeOneShot` + SFTP read in a shared `6.0s` operation deadline (`asyncio.timeout(6.0)`), while `AsyncSshCaptureTransport.read_and_remove()` enforces its own `timeout` budget and shields its `finally: sftp.remove(remote_path)` under a separate `1.5s` cleanup grace (`asyncio.shield` + `asyncio.wait_for(..., timeout=cleanup_grace)`) so outer timeout cancellation cannot abort remote `/tmp` file deletion (`<= 7.5s` worst-case capture phase within the `25s` `ui_lock` budget). Any new SFTP session runs `sweep_temp_files("/tmp/lg_smtv_cap_", exclude=remote_path)`, so stale captures from earlier sessions or crashes are removed while the frame about to be read survives.
|
||||||
|
|
||||||
### 3. MCP Tool Surface
|
### 3. MCP Tool Surface
|
||||||
|
|
||||||
@@ -193,15 +201,15 @@ All tools return structured JSON payloads (plus inline MCP `ImageContent` when `
|
|||||||
|
|
||||||
### 4. Runtime Configuration, Security & Daemon Deployment
|
### 4. Runtime Configuration, Security & Daemon Deployment
|
||||||
|
|
||||||
* **Network & Auth:** `streamable-http` binds to `HOST` (default `127.0.0.1` for local dev; `<SERVER_IP>` on the LAN when deployed) and `PORT` (default `8765`). Startup fails closed if `MCP_BEARER_TOKEN` is unset or whitespace-only. Requests require `Authorization: Bearer <token>` verified via `hmac.compare_digest`. `TransportSecuritySettings` derives `allowed_hosts` / `allowed_origins` from `HOST`/`PORT`, `127.0.0.1`/`localhost`, and optional `ALLOWED_HOSTS`.
|
* **Network, Transport Security & Trust Policy:** `streamable-http` binds to `HOST` (default `127.0.0.1` for local dev; `<SERVER_IP>` on a trusted home LAN when deployed) and `PORT` (default `8765`). Startup fails closed if `MCP_BEARER_TOKEN` is unset or whitespace-only, and every HTTP request requires `Authorization: Bearer <token>` verified via `hmac.compare_digest`. `TransportSecuritySettings` derives `allowed_hosts` / `allowed_origins` from `HOST`/`PORT`, `127.0.0.1`/`localhost`, and optional `ALLOWED_HOSTS`. Because `uvicorn` serves plain HTTP by default, direct LAN binding assumes a trusted home network segment; if accessed across untrusted networks, operators must place the daemon behind an HTTPS reverse proxy / TLS terminator or an encrypted overlay tunnel (e.g., WireGuard or Tailscale). On the TV link (`wss://<TV_IP>:3001`), `SsapClient` uses `ssl.CERT_NONE` because retail LG webOS TVs present a device-generated self-signed certificate without CA chain provisioning; session authorization relies on the paired `client-key` on the local LAN.
|
||||||
* **ASGI `lifespan` Ownership:** FastMCP/Starlette's ASGI `lifespan` context manager starts `TvManager` on Uvicorn's active event loop, registers `SIGHUP` via `loop.add_signal_handler`, and closes `SsapClient`, `PointerClient`, and `CaptureClient` on shutdown.
|
* **ASGI `lifespan` Ownership:** FastMCP (`MCPServer`) / Starlette's ASGI `lifespan` context manager starts `TvManager` on Uvicorn's active event loop, registers `SIGHUP` via `loop.add_signal_handler`, and closes `SsapClient`, `PointerClient`, and `FrameCapturer` on shutdown.
|
||||||
* **Developer Mode SSH Lifecycle & Headless `asyncssh` Keying:** Retail LG webOS TVs do not serve `/tmp` screenshots over HTTPS (`:3001`), so `CaptureClient` pulls captures over SFTP from the unprivileged SSH server (`prisoner@<TV_IP>:9922`) provided by LG's official [Developer Mode app](https://webostv.developer.lg.com/develop/getting-started/developer-mode-app) (see [docs/poc/capabilities.md](../poc/capabilities.md)). Port `:9922` is available only while "Dev Mode Status" and "Key Server" are enabled on the TV, and LG automatically disables Developer Mode when its countdown timer expires (at which point `CaptureClient` raises `SCREENSHOT_UNAVAILABLE` while all SSAP and WoL tools continue operating). On a headless `systemd` service, `CaptureClient` connects with `config=[]`, `known_hosts=None` (overridable via `SSH_KNOWN_HOSTS_PATH`), legacy `server_host_key_algs=["ssh-rsa", ...]`, `signature_algs=["ssh-rsa", ...]`, and either a dedicated passwordless service key (`SSH_KEY_PATH`) or `WEBOS_SSH_PASSPHRASE` passed to `asyncssh.connect(..., passphrase=...)`. `lg-smtv-mcp pair --fetch-ssh-key` retrieves `http://<TV_IP>:9991/webos_rsa` and saves it with `0600` permissions.
|
* **Developer Mode SSH Lifecycle & Host-Key Trust (`#12`):** Retail LG webOS TVs do not serve `/tmp` screenshots over HTTPS (`:3001`), so `CaptureClient` pulls captures over SFTP from the unprivileged SSH server (`prisoner@<TV_IP>:9922`) provided by LG's official [Developer Mode app](https://webostv.developer.lge.com/develop/getting-started/developer-mode-app) (see [docs/poc/capabilities.md](../poc/capabilities.md)). Port `:9922` is available only while "Dev Mode Status" and "Key Server" are enabled on the TV, and LG automatically disables Developer Mode when its countdown timer expires (at which point `CaptureClient` raises `SCREENSHOT_UNAVAILABLE` while all SSAP and WoL tools continue operating). `AsyncSshCaptureTransport` opens its `asyncssh` SFTP connection lazily on the first capture request, reuses it across subsequent captures while the TV stays online, sweeps stale `/tmp/lg_smtv_cap_*` files on each new SFTP session while excluding the in-flight capture path, and closes the session when `TvManager` transitions to `STANDBY_OFFLINE` or on transport errors. On a headless `systemd` service, `AsyncSshCaptureTransport` connects with `config=[]`, legacy `server_host_key_algs=["ssh-rsa"]`, `signature_algs=["ssh-rsa"]`, and either a key path (`SSH_KEY_PATH`) or `WEBOS_SSH_PASSPHRASE`. Because the TV's Developer Mode container regenerates its SSH host key across Developer Mode renewals, `known_hosts=None` is the default on a trusted home LAN (accepting the LAN peer's host key to prevent unattended daemon breakage); operators requiring strict SSH host authentication can set `SSH_KNOWN_HOSTS_PATH` to pin the TV's host key and update that file whenever Developer Mode is re-initialized. `lg-smtv-mcp pair --fetch-ssh-key` retrieves `http://<TV_IP>:9991/webos_rsa` and saves it with `0600` permissions.
|
||||||
* **WoL Broadcast:** `WOL_BROADCAST` defaults to `255.255.255.255` and can be set to the LAN subnet broadcast (e.g., `<LAN_SUBNET_BROADCAST>`) on multi-homed hosts so magic packets exit on the TV's Ethernet/Wi-Fi segment.
|
* **WoL Broadcast:** `WOL_BROADCAST` defaults to `255.255.255.255` and can be set to the LAN subnet broadcast (e.g., `<LAN_SUBNET_BROADCAST>`) on multi-homed hosts so magic packets exit on the TV's Ethernet/Wi-Fi segment.
|
||||||
|
|
||||||
### 5. Offline Testing & Nix Environment
|
### 5. Offline Testing & Nix Environment
|
||||||
|
|
||||||
* **Offline Contract Tests:** Tests inject fake `WebSocketTransport` and `CaptureTransport` implementations (plus a fake `send_wol` callback) into `TvManager` to test: `1008` fail-fast vs. `tv_wake` recovery and coalescing, `CaptureClient` teardown on `STANDBY_OFFLINE` and `/tmp/lg_smtv_cap_*.jpg` sweep on reconnect, `msg["id"]` interleaving between `request()` and `subscribe` (`audio/getStatus` nested `soundOutput`), pending `Future` failure on disconnect, pointer socket drop + auto-reacquire, `keys` allowlist/bounds (`INVALID_ARGUMENT`), `ui_lock` `25s` timeout and `CaptureClient` `6s` deadline + `1–2s` cleanup isolation, `keys(..., capture=True)` and `type_text(..., capture=True)` partial success when SSH fails, `finally: sftp.remove()` cleanup on failure, `frame_sha256` / `changed_since_last`, `PAIRING_REQUIRED` key reload (including malformed JSON handling), `MAX_VOLUME` guardrail, `ENABLE_RAW_SSAP` gating, and fail-closed Bearer auth.
|
* **Offline Contract Tests:** All automated tests run offline against injected `WebSocketTransport`, `CaptureTransport`, and `FrameCapturer` implementations (plus fake `wol_fn` and `wait_fn` callbacks). M1 offline coverage (`tests/test_config.py`, `tests/test_protocols.py`, `tests/test_ssap.py`, `tests/test_pointer.py`, `tests/test_manager.py`, `tests/test_auth.py`, `tests/test_server.py`, `tests/test_cli.py`, `tests/test_e2e_mvp.py`) is implemented and passing on `main`. M2 adds `tests/test_capture.py` and hardens `tests/test_e2e_mvp.py`; both are implemented and passing on `main` (PR `#15` and PR `#14`).
|
||||||
* **`flake.nix` Updates:** Expose `packages.${system}.default` via `buildPythonApplication` (`pyproject = true`, `setuptools`, `websockets`, `mcp`, `asyncssh`, `uvicorn`) and expand `devShells.${system}.default` (`mcp = "2.3.0"`, `asyncssh = "2.24.0"`, `uvicorn`, `httpx`, `pytest = "9.1.1"`, `pytest-asyncio = "1.4.1"`, `websockets`, `pyright`, `ruff`) with a `PYTHONPATH="$PWD/src:${PYTHONPATH:-}"` `shellHook`.
|
* **`flake.nix` Packaging:** Exposes `packages.${system}.default` via `buildPythonApplication` (`pyproject = true`, `setuptools`, single-sourced `runtimeDeps` and `testDeps`, `preCheck` running `ruff check .`, `ruff format --check .`, `pyright`, and `pytestCheckHook`) and `devShells.${system}.default` with `.githooks` pre-commit enforcement.
|
||||||
|
|
||||||
## Alternatives Considered
|
## Alternatives Considered
|
||||||
|
|
||||||
@@ -215,7 +223,7 @@ All tools return structured JSON payloads (plus inline MCP `ImageContent` when `
|
|||||||
|
|
||||||
* **Pros:** Could encapsulate multi-step UI navigation behind a single high-level natural-language tool call.
|
* **Pros:** Could encapsulate multi-step UI navigation behind a single high-level natural-language tool call.
|
||||||
* **Cons:** Couples a local hardware driver to external LLM/VLM API keys, provider SDKs, model selection, and prompt engineering.
|
* **Cons:** Couples a local hardware driver to external LLM/VLM API keys, provider SDKs, model selection, and prompt engineering.
|
||||||
* **Reason for Rejection:** `lg-smtv-mcp` stays LLM-free; latency and token overhead are addressed instead via composite tools (`keys(..., capture=True)`) and deterministic `frame_sha256` / `changed_since_last` metadata.
|
* **Reason for Rejection:** `lg-smtv-mcp` stays LLM-free; host round-trips and vision-turn overhead are reduced instead via composite tools (`keys(..., capture=True)`) and deterministic `frame_sha256` / `changed_since_last` metadata.
|
||||||
|
|
||||||
### Alternative C: OpenSSH `ControlMaster` Subprocess for Screenshots
|
### Alternative C: OpenSSH `ControlMaster` Subprocess for Screenshots
|
||||||
|
|
||||||
@@ -227,7 +235,7 @@ All tools return structured JSON payloads (plus inline MCP `ImageContent` when `
|
|||||||
|
|
||||||
* **Pros:** Bounded to a single file on `/tmp` without explicit delete calls.
|
* **Pros:** Bounded to a single file on `/tmp` without explicit delete calls.
|
||||||
* **Cons:** If `executeOneShot` fails silently or races, SFTP pull can read a stale screenshot from an earlier step.
|
* **Cons:** If `executeOneShot` fails silently or races, SFTP pull can read a stale screenshot from an earlier step.
|
||||||
* **Reason for Rejection:** Capturing to `/tmp/lg_smtv_cap_<seq>.jpg`, pulling only when `returnValue: true`, calling `sftp.remove()` in `finally:`, and sweeping stale files on reconnect prevents both stale reads and `/tmp` exhaustion on the TV's ~1.2 GB RAM.
|
* **Reason for Rejection:** Capturing to `/tmp/lg_smtv_cap_<seq>.jpg`, pulling only when `returnValue: true`, calling `sftp.remove()` in a shielded `finally:` block, and sweeping stale files on SFTP connect/reconnect is designed to prevent stale reads and bound `/tmp` file accumulation on the TV's ~1.2 GB RAM.
|
||||||
|
|
||||||
### Alternative E: Unconditional `raw_ssap` Tool
|
### Alternative E: Unconditional `raw_ssap` Tool
|
||||||
|
|
||||||
@@ -242,132 +250,99 @@ All tools return structured JSON payloads (plus inline MCP `ImageContent` when `
|
|||||||
| Risk | Impact | Mitigation |
|
| Risk | Impact | Mitigation |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
| Developer Mode SSH timer expires on TV | Screenshot capture fails (`SCREENSHOT_UNAVAILABLE`) | Degrade only `screenshot` / `capture=True` (returning partial success on `keys` / `type_text`); keep all SSAP and WoL tools active. |
|
| Developer Mode SSH timer expires on TV | Screenshot capture fails (`SCREENSHOT_UNAVAILABLE`) | Degrade only `screenshot` / `capture=True` (returning partial success on `keys` / `type_text`); keep all SSAP and WoL tools active. |
|
||||||
| Orphaned `/tmp/lg_smtv_cap_*.jpg` on SSH stall | Gradual `/tmp` RAM growth on TV (~1.2 GB RAM) | Per-call `finally: sftp.remove()` under `1–2s` grace + sweep of `/tmp/lg_smtv_cap_*.jpg` on SFTP connect/reconnect. |
|
| Orphaned `/tmp/lg_smtv_cap_*.jpg` on SSH stall | Gradual `/tmp` RAM growth on TV (~1.2 GB RAM) | Per-call shielded `finally: sftp.remove()` under `1.5s` grace + sweep of `/tmp/lg_smtv_cap_*.jpg` on SFTP connect/reconnect, excluding the in-flight capture path. |
|
||||||
| Concurrent `tv_wake` / reconnect race or cold wake delay | Duplicate sockets or premature `WAKE_TIMEOUT` | Single-owner connection loop coalescing `tv_wake` + `45s` budget (`~30–35s` empirical cold boot). |
|
| Concurrent `tv_wake` / reconnect race or cold wake delay | Duplicate sockets or premature `WAKE_TIMEOUT` | Single-owner connection loop coalescing `tv_wake` + `45s` budget (`~30–35s` empirical cold boot). |
|
||||||
| Dev Mode host-key regeneration or headless `known_hosts` failure | SSH connection rejected on `:9922` | Default `known_hosts=None` on LAN with optional `SSH_KNOWN_HOSTS_PATH` override. |
|
| Dev Mode host-key regeneration or LAN peer spoofing on `:9922` | Unattended SSH failure on key rotation, or unauthenticated SFTP peer when `known_hosts=None` | Default `known_hosts=None` on trusted home LAN; support `SSH_KNOWN_HOSTS_PATH` for explicit host-key pinning (updated by operator when Developer Mode regenerates keys). |
|
||||||
|
| Plain-HTTP bearer token exposure on untrusted networks | Token interception on non-private network segments | Bind to `127.0.0.1` by default; restrict direct LAN binding to trusted home networks or terminate HTTPS via reverse proxy / WireGuard / Tailscale tunnel. |
|
||||||
|
| Single-TV-per-daemon scalability limit | One `lg-smtv-mcp` process manages a single `TV_IP` and `ui_lock` | Run one isolated daemon instance per TV (distinct `TV_IP`, `CLIENT_KEY_PATH`, and `PORT`) if multiple TVs require control. |
|
||||||
| Pointer frame newline injection or oversized `keys` batch | Unintended pointer commands or `ui_lock` starvation | Strict button allowlist (rejecting `\r`/`\n`), batch/delay caps, and `25s` `ui_lock` timeout. |
|
| Pointer frame newline injection or oversized `keys` batch | Unintended pointer commands or `ui_lock` starvation | Strict button allowlist (rejecting `\r`/`\n`), batch/delay caps, and `25s` `ui_lock` timeout. |
|
||||||
|
|
||||||
--------------------------------------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
## Non-Functional Requirements
|
## Non-Functional Requirements
|
||||||
|
|
||||||
* **Security & Privacy:** `streamable-http` binds to configurable `HOST` (default `127.0.0.1`, or `<SERVER_IP>` on private LAN), fails closed if `MCP_BEARER_TOKEN` is unset, enforces `Authorization: Bearer <token>` via `hmac.compare_digest`, and configures MCP `TransportSecuritySettings`. Arbitrary SSH command execution is never exposed. `.client_key.json`, `.env`, SSH keys, and `*.jpg` captures are excluded from version control.
|
* **Security & Privacy:** `streamable-http` binds to configurable `HOST` (default `127.0.0.1`, or `<SERVER_IP>` on a trusted home LAN; HTTPS reverse proxy or VPN tunnel required across untrusted networks), fails closed if `MCP_BEARER_TOKEN` is unset, enforces `Authorization: Bearer <token>` via `hmac.compare_digest`, and configures MCP `TransportSecuritySettings`. Arbitrary SSH command execution is never exposed. `.client_key.json`, `.env`, SSH keys, and `*.jpg` captures are excluded from version control.
|
||||||
* **Performance & Latency:** Persistent SSAP, pointer, and `asyncssh` SFTP connections eliminate per-step TLS/SSH handshakes (~8–10s/step in PoC); batched `keys(..., capture=True)` and `frame_sha256` / `changed_since_last` allow the host to skip redundant vision turns.
|
* **Performance & Latency:** Persistent SSAP and pointer connections (plus the reusable on-demand `asyncssh` SFTP session) avoid repeating per-step TLS/SSH handshakes (~8–10s/step in the one-shot PoC); batched `keys(..., capture=True)` and `frame_sha256` / `changed_since_last` are designed to let the host skip redundant vision turns.
|
||||||
* **Operational Resilience:** WebSocket `1008` fails fast (`TV_OFFLINE_STANDBY`), `ui_lock` times out at `25s` with `LOCK_TIMEOUT`, and Developer Mode SSH expiration degrades only `screenshot` / `capture=True` without disrupting SSAP or WoL tools.
|
* **Operational Resilience:** WebSocket `1008` fails fast (`TV_OFFLINE_STANDBY`), `ui_lock` times out at `25s` with `LOCK_TIMEOUT`, and Developer Mode SSH unavailability degrades only `screenshot` / `capture=True` without disrupting SSAP or WoL tools.
|
||||||
|
|
||||||
## Detailed Implementation Plan
|
## Detailed Implementation Plan
|
||||||
|
|
||||||
Implementation proceeds in three incremental phases, each ending with its listed verification checkpoint (`pytest` starts in Phase 2).
|
Milestone M1 foundations (`#1`–`#4`), all Milestone M2 slices (`#11`, `#12`, `#13`), and the post-M2 `systemd` unit sandboxing hardening follow-up ([#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17), PR [#18](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/18)) are implemented, verified, and merged on `main`. The completed baselines are summarized for reference below.
|
||||||
|
|
||||||
### Phase 1: Environment, Packaging, Config & Error Taxonomy
|
### Completed Milestone M1 Baseline (`#1`–`#4`, Merged on `main`)
|
||||||
|
|
||||||
#### 1. `flake.nix` (Modify)
|
* **Environment, Config & Errors (`#1` / PR `#6`):** [`flake.nix`](../../flake.nix), [`pyproject.toml`](../../pyproject.toml), [`.gitignore`](../../.gitignore), [`.env.example`](../../.env.example), [`src/lg_smtv_mcp/errors.py`](../../src/lg_smtv_mcp/errors.py) (`ConfigError`, `ErrorCode`, `TvError`), [`src/lg_smtv_mcp/config.py`](../../src/lg_smtv_mcp/config.py) (`TvConfig`, `load_config`), and [`tests/test_config.py`](../../tests/test_config.py).
|
||||||
|
* **`tv_core` Engine & Protocol Seams (`#2` / PR `#7`):** [`src/lg_smtv_mcp/tv_core/protocols.py`](../../src/lg_smtv_mcp/tv_core/protocols.py) (`WebSocketTransport`, `WebSocketConnectFn`, `WebSocketClosedError`, `CaptureTransport`, `FrameCapturer`, `TvStatus`, `TvStateSnapshot`, `CaptureResult`, `KeysResult`, `TextResult`), [`src/lg_smtv_mcp/tv_core/ssap.py`](../../src/lg_smtv_mcp/tv_core/ssap.py) (`SsapClient`, `PERMISSIONS`), [`src/lg_smtv_mcp/tv_core/pointer.py`](../../src/lg_smtv_mcp/tv_core/pointer.py) (`PointerClient`, `ALLOWED_BUTTONS`), [`src/lg_smtv_mcp/tv_core/manager.py`](../../src/lg_smtv_mcp/tv_core/manager.py) (`TvManager`, `send_wol`, `ConnectionState`), and offline unit suites [`tests/conftest.py`](../../tests/conftest.py), [`tests/test_protocols.py`](../../tests/test_protocols.py), [`tests/test_ssap.py`](../../tests/test_ssap.py), [`tests/test_pointer.py`](../../tests/test_pointer.py), and [`tests/test_manager.py`](../../tests/test_manager.py).
|
||||||
* **Type / Scope:** Nix package and development shell configuration.
|
* **FastMCP Server, Bearer Auth & CLI (`#3` / PR `#9`):** [`src/lg_smtv_mcp/auth.py`](../../src/lg_smtv_mcp/auth.py) (`BearerAuthMiddleware`, `build_transport_security_settings`), [`src/lg_smtv_mcp/server.py`](../../src/lg_smtv_mcp/server.py) (`create_mcp_server`, `create_http_app`, 12 default tools + opt-in `raw_ssap`, `ImageContent(type="image", data=encoded, mime_type="image/jpeg")` formatting), [`src/lg_smtv_mcp/cli.py`](../../src/lg_smtv_mcp/cli.py) (`serve` and `pair`), and offline contract suites [`tests/test_auth.py`](../../tests/test_auth.py), [`tests/test_server.py`](../../tests/test_server.py), and [`tests/test_cli.py`](../../tests/test_cli.py).
|
||||||
* **Proposed Changes:** Expose `packages.${system}.default` via `pkgs.python3Packages.buildPythonApplication` (`pyproject = true`, `build-system = [ ps.setuptools ]`, single-sourced `runtimeDeps` `[ ps.websockets ps.mcp ps.pydantic ps.asyncssh ps.uvicorn ]`, `testDeps` `[ ps.httpx ps.pytest ps.pytest-asyncio ]`, and `preCheck` running `ruff check .`, `ruff format --check .`, `pyright`, plus `pytestCheckHook`). Update `devShells.${system}.default` to include `pythonEnv` (`runtimeDeps ++ testDeps`), `pkgs.pyright`, and `pkgs.ruff`, with `shellHook` exporting `PYTHONPATH="$PWD/src:${PYTHONPATH:-}"` and configuring `git config core.hooksPath .githooks`.
|
* **MVP Full-Stack Offline E2E & Operator Checklist (`#4` / PR `#10`):** [`tests/test_e2e_mvp.py`](../../tests/test_e2e_mvp.py) and live-TV smoke checklist in [`README.md`](../../README.md).
|
||||||
|
|
||||||
#### 2. `pyproject.toml` (Create)
|
|
||||||
|
|
||||||
* **Type / Scope:** Python package metadata, build, and tool configuration.
|
|
||||||
* **Proposed Changes:** Set `[build-system]` to `setuptools.build_meta`, define `lg-smtv-mcp` (`requires-python = ">=3.14"`) under `src/` with `[project].dependencies = ["websockets", "mcp", "pydantic", "asyncssh", "uvicorn"]`, console script `lg-smtv-mcp = "lg_smtv_mcp.cli:main"`, `[tool.pytest.ini_options]` (`asyncio_mode = "auto"`, `pythonpath = ["src"]`), `[tool.ruff]` (including `TID251` banning `from __future__ import annotations` in `src/` and `tests/`), and `[tool.pyright]` (`include = ["src", "tests"]`, `typeCheckingMode = "strict"`, `pythonVersion = "3.14"`).
|
|
||||||
|
|
||||||
#### 3. `.gitignore` and `.env.example` (Modify / Create)
|
|
||||||
|
|
||||||
* **Type / Scope:** Secret hygiene and runtime configuration template.
|
|
||||||
* **Proposed Changes:** Ensure `.gitignore` excludes `.client_key.json`, `.env`, `*.jpg`, and SSH keys per [AGENTS.md](../../AGENTS.md) Section 4. Create `.env.example` with placeholders (`TV_IP=<TV_IP>`, `TV_MAC=<TV_MAC>`, `WOL_BROADCAST=255.255.255.255`, `CLIENT_KEY_PATH=.client_key.json`, `SSH_KEY_PATH=`, `WEBOS_SSH_PASSPHRASE=`, `SSH_KNOWN_HOSTS_PATH=`, `HOST=127.0.0.1`, `PORT=8765`, `ALLOWED_HOSTS=`, `MCP_BEARER_TOKEN=<GENERATE_TOKEN>`, `MAX_VOLUME=40`, `ENABLE_RAW_SSAP=false`).
|
|
||||||
|
|
||||||
#### 4. `src/lg_smtv_mcp/__init__.py`, `src/lg_smtv_mcp/__main__.py`, and `src/lg_smtv_mcp/errors.py` (Create)
|
|
||||||
|
|
||||||
* **Type / Scope:** Package root, `python -m lg_smtv_mcp` entrypoint, and typed domain error taxonomy.
|
|
||||||
* **Proposed Changes:** Add `__main__.py` delegating to `cli.main()`. In `errors.py`, define `ConfigError(Exception)` for startup/operator configuration failures, `ErrorCode(StrEnum)` (`TV_OFFLINE_STANDBY`, `PAIRING_REQUIRED`, `SCREENSHOT_UNAVAILABLE`, `LOCK_TIMEOUT`, `WAKE_TIMEOUT`, `COMMAND_FAILED`, `INVALID_ARGUMENT`), and `TvError(Exception)` carrying `code: ErrorCode` and `message: str` for uniform MCP error mapping.
|
|
||||||
|
|
||||||
#### 5. `src/lg_smtv_mcp/config.py` (Create)
|
|
||||||
|
|
||||||
* **Type / Scope:** Runtime configuration loader and stdlib `.env` parser.
|
|
||||||
* **Proposed Changes:** Implement a minimal stdlib `.env` parser in `load_config()` that populates unset `os.environ` keys from `.env` (if present). Define frozen Pydantic v2 `TvConfig` (`BaseModel`, `ConfigDict(frozen=True, extra="forbid")`, remapping `ValidationError` to `ConfigError`) validating `TV_IP` (required IPv4), `0 <= MAX_VOLUME <= 100` (default `40`), `1 <= PORT <= 65535` (default `8765`), comma-separated `ALLOWED_HOSTS`, `WOL_BROADCAST` (IPv4, default `255.255.255.255`), `SSH_KNOWN_HOSTS_PATH`, `ENABLE_RAW_SSAP` (default `False`), and command-specific requirements (`require_bearer_token()` for `serve --transport streamable-http`; `require_mac()` for `tv_wake`), all raising `ConfigError` on invalid configuration.
|
|
||||||
|
|
||||||
* **Phase 1 Checkpoint:** `nix develop --command python -c "import lg_smtv_mcp"`, `nix develop --command bash -c "ruff check . && ruff format --check . && pyright && pytest"`, and `nix flake check`.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Phase 2: `tv_core` Transports, State Machine & Offline Contract Tests
|
### Completed Milestone M2 Slices (`#11`, `#12`, `#13` — Merged on `main`)
|
||||||
|
|
||||||
#### 6. `src/lg_smtv_mcp/tv_core/protocols.py` (Create)
|
Delivered by `#12` (PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/15)) and `#11` (PR [#14](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/14)). The contracts below match `main` as merged, including the PR `#15` review remediation (CR-01..CR-11).
|
||||||
|
|
||||||
* **Type / Scope:** Transport abstraction boundaries (`Protocol`s) and result schemas.
|
#### 1. `src/lg_smtv_mcp/tv_core/capture.py` and `src/lg_smtv_mcp/tv_core/__init__.py` (Completed — Issue `#12`)
|
||||||
* **Proposed Changes:** Define `WebSocketClosedError(code: int, reason: str)`, `WebSocketTransport` (`send`, `recv`, `close`), `WebSocketConnectFn = Callable[[str], Awaitable[WebSocketTransport]]`, and `CaptureTransport` (`read_and_remove`, `sweep_temp_files`, `close`). Define frozen result dataclasses/TypedDicts: `TvStatus(status: Literal["connected", "already_connected"], elapsed_ms: int)`, `TvStateSnapshot(connected: bool, stale: bool, volume: int | None, muted: bool | None, sound_output: str | None, foreground_app: str | None, last_updated: float | None)`, `KeysResult(keys_sent: bool, count: int, frame_sha256: str | None, changed_since_last: bool | None, size_bytes: int | None, capture_error: str | None)`, `TextResult(text_sent: bool, enter_sent: bool, frame_sha256: str | None, changed_since_last: bool | None, size_bytes: int | None, capture_error: str | None)`, and `CaptureResult(image_bytes: bytes, frame_sha256: str, changed_since_last: bool, size_bytes: int)`.
|
|
||||||
|
|
||||||
#### 7. `src/lg_smtv_mcp/tv_core/ssap.py` (Create)
|
* **Type / Scope:** Developer Mode `asyncssh`/SFTP screenshot client (`CaptureClient`) and transport adapter (`AsyncSshCaptureTransport`).
|
||||||
|
* **Delivered Contract:**
|
||||||
|
* Implemented `AsyncSshCaptureTransport(config: TvConfig, connect_fn: Callable[..., Awaitable[ Any ]] | None = None)` satisfying [`CaptureTransport`](../../src/lg_smtv_mcp/tv_core/protocols.py):
|
||||||
|
* Defaults `connect_fn` to `asyncssh.connect`. Connects to `host=config.tv_ip`, `port=9922`, `username="prisoner"`, `config=[]`, `known_hosts=str(config.ssh_known_hosts_path) if config.ssh_known_hosts_path is not None else None`, `server_host_key_algs=["ssh-rsa"]`, `signature_algs=["ssh-rsa"]`, `client_keys=[str(config.ssh_key_path)] if config.ssh_key_path is not None else None`, and `passphrase=config.webos_ssh_passphrase`.
|
||||||
|
* Lazily opens (or reconnects) the SSH connection and SFTP client (`await conn.start_sftp_client()`) on demand inside `read_and_remove()`. Whenever a new SFTP session is established, runs best-effort `await self.sweep_temp_files("/tmp/lg_smtv_cap_", exclude=remote_path)` (listing `/tmp`, removing matching `lg_smtv_cap_*` entries except the in-flight capture, and ignoring individual file removal errors). `start_sftp_client()` failures and cancellation close the connection deterministically before re-raising.
|
||||||
|
* In `read_and_remove(remote_path: str, timeout: float = 6.0, cleanup_grace: float = 1.5) -> bytes`, enforces the caller budget with `async with asyncio.timeout(timeout)`, reads the remote file bytes via SFTP, and guarantees remote deletion in `finally:` using `await asyncio.wait_for(asyncio.shield(sftp.remove(remote_path)), timeout=cleanup_grace)` (suppressing cleanup exceptions so the primary result or error propagates, while ensuring outer cancellation does not abort `sftp.remove`; the detached task's exception is consumed by a done-callback). On SSH/SFTP transport errors, closes and clears cached connection/SFTP handles so the next capture reconnects cleanly.
|
||||||
|
* In `close()`, closes the cached SFTP and SSH connections and clears cached handles.
|
||||||
|
* Implemented `CaptureClient(transport: CaptureTransport)` satisfying [`FrameCapturer`](../../src/lg_smtv_mcp/tv_core/protocols.py):
|
||||||
|
* Maintains an instance sequence counter `_seq: int = 0` (incremented per `capture_frame` call to form `/tmp/lg_smtv_cap_{self._seq}.jpg`) and `_last_sha256: str | None = None`.
|
||||||
|
* In `capture_frame(ssap_request_fn)`, wraps both `await ssap_request_fn("ssap://com.webos.service.capture/executeOneShot", {"path": remote_path, "method": "DISPLAY", "format": "JPG"})` and `await self._transport.read_and_remove(remote_path, timeout=6.0, cleanup_grace=1.5)` inside a shared `async with asyncio.timeout(6.0):` block.
|
||||||
|
* Requires `response.get("returnValue") is True` (exactly `true`; `false`, missing, or `null` all fail). If `executeOneShot` raises a `TvError` other than `TV_OFFLINE_STANDBY`/`PAIRING_REQUIRED`, returns a non-true `returnValue`, times out, or `read_and_remove` raises an SSH/SFTP/`OSError`, raises `TvError(ErrorCode.SCREENSHOT_UNAVAILABLE, ...)` without calling `read_and_remove` when `executeOneShot` itself failed. Propagates `TvError` with `TV_OFFLINE_STANDBY` or `PAIRING_REQUIRED` unchanged.
|
||||||
|
* Computes `frame_sha256 = hashlib.sha256(image_bytes).hexdigest()`, sets `changed_since_last = (self._last_sha256 != frame_sha256)` (`True` on the first capture after init or `close()`), updates `self._last_sha256 = frame_sha256`, and returns `CaptureResult(image_bytes=image_bytes, frame_sha256=frame_sha256, changed_since_last=changed_since_last, size_bytes=len(image_bytes))`.
|
||||||
|
* In `close()`, resets `self._last_sha256 = None` and awaits `self._transport.close()`.
|
||||||
|
* Exported `AsyncSshCaptureTransport` and `CaptureClient` in `src/lg_smtv_mcp/tv_core/__init__.py`.
|
||||||
|
|
||||||
* **Type / Scope:** SSAP WebSocket client and frame multiplexer.
|
#### 2. `src/lg_smtv_mcp/server.py` (Completed — Issue `#12`)
|
||||||
* **Proposed Changes:** Implement `SsapClient` taking `WebSocketConnectFn` with `open_timeout = 3.5`, `ping_interval = 10`, `ping_timeout = 5`, and `ssl.CERT_NONE` / `check_hostname = False`. Pin the 16 `PERMISSIONS` (`LAUNCH`, `CONTROL_AUDIO`, `CONTROL_DISPLAY`, `CONTROL_POWER`, `CONTROL_INPUT_TEXT`, `CONTROL_INPUT_MEDIA_PLAYBACK`, `CONTROL_INPUT_JOYSTICK`, `CONTROL_INPUT_TV`, `CONTROL_TV_MEDIA`, `CONTROL_MOUSE_AND_KEYBOARD`, `READ_INSTALLED_APPS`, `READ_RUNNING_APPS`, `READ_INPUT_DEVICE_LIST`, `READ_TV_CHANNEL_LIST`, `READ_POWER_STATE`, `WRITE_NOTIFICATION_TOAST`) and always send them in `register` (matching `docs/poc/tv_test.py` `PERMISSIONS` / `build_register_payload()`). Map `WebSocketClosedError(code=1008)` / connect timeout to `TV_OFFLINE_STANDBY`, and `PROMPT` in daemon mode to `PAIRING_REQUIRED`. `request(uri, payload)` returns `msg["payload"]` (`dict[str, Any]`) and raises `TvError` (`COMMAND_FAILED`, `PAIRING_REQUIRED` on `401 insufficient permissions`, or `TV_OFFLINE_STANDBY`) if `msg["type"] == "error"` or `payload.get("returnValue") is False`. In `_reader_loop()`'s `finally:`, fail all pending `asyncio.Future`s with `TV_OFFLINE_STANDBY`.
|
|
||||||
|
|
||||||
#### 8. `src/lg_smtv_mcp/tv_core/pointer.py` (Create)
|
* **Type / Scope:** Default `CaptureClient` wiring in `create_mcp_server`.
|
||||||
|
* **Delivered Changes:**
|
||||||
|
* When `create_mcp_server(config: TvConfig, manager: TvManager | None = None)` constructs its default `TvManager` (`manager is None`), it passes `capture_client=CaptureClient(AsyncSshCaptureTransport(config))`.
|
||||||
|
* `TvManager.__init__`'s `capture_client: FrameCapturer | None = None` default is unchanged so existing offline `TvManager` unit tests remain isolated without touching SSH.
|
||||||
|
|
||||||
* **Type / Scope:** Pointer input WebSocket client.
|
#### 3. `tests/test_capture.py` and `tests/test_server.py` (Completed — Issue `#12`)
|
||||||
* **Proposed Changes:** Implement `PointerClient` calling `ssap://com.webos.service.networkinput/getPointerInputSocket` and opening the pointer socket via `WebSocketConnectFn`. Normalize key names to uppercase, validate against the strict button allowlist (rejecting unknown names or `\r`/`\n` with `INVALID_ARGUMENT`), format `type:button\nname:<KEY>\n\n`, pace by `delay_ms`, and retry once by re-acquiring the pointer socket if a mid-batch send fails due to socket drop.
|
|
||||||
|
|
||||||
#### 9. `src/lg_smtv_mcp/tv_core/capture.py` (Create)
|
* **Type / Scope:** Offline contract tests for `CaptureClient`, `AsyncSshCaptureTransport`, and `server.py` default wiring.
|
||||||
|
* **Delivered Changes:**
|
||||||
|
* Created `tests/test_capture.py` covering:
|
||||||
|
* `AsyncSshCaptureTransport` passes `host`, `port=9922`, `username="prisoner"`, `config=[]`, `server_host_key_algs=["ssh-rsa"]`, `signature_algs=["ssh-rsa"]`, optional `known_hosts`, `client_keys`, and `passphrase` to `connect_fn`.
|
||||||
|
* `AsyncSshCaptureTransport` runs `sweep_temp_files("/tmp/lg_smtv_cap_", exclude=...)` on initial SFTP connect and after reconnecting following a transport failure, removing only matching `lg_smtv_cap_*` files and preserving the in-flight capture path.
|
||||||
|
* `AsyncSshCaptureTransport` closes the SSH connection when `start_sftp_client()` fails, and enforces `read_and_remove`'s `timeout` budget.
|
||||||
|
* `AsyncSshCaptureTransport.read_and_remove` shields `sftp.remove(remote_path)` under `cleanup_grace=1.5` even when `read` fails or the outer task is cancelled.
|
||||||
|
* `CaptureClient.capture_frame` sends `ssap://com.webos.service.capture/executeOneShot` with `{"path": "/tmp/lg_smtv_cap_1.jpg", "method": "DISPLAY", "format": "JPG"}`, skips SFTP read if `returnValue` is not exactly `true` or `COMMAND_FAILED`, maps non-true `returnValue` / `COMMAND_FAILED` / SSH errors / `6.0s` timeout to `ErrorCode.SCREENSHOT_UNAVAILABLE`, and preserves `TV_OFFLINE_STANDBY` / `PAIRING_REQUIRED`.
|
||||||
|
* `CaptureClient.capture_frame` computes `frame_sha256`, sets `changed_since_last=True` on first frame, `False` on identical consecutive frame, `True` after `close()` resets `_last_sha256`, and reports `size_bytes=len(image_bytes)`.
|
||||||
|
* Extended `tests/test_server.py` to verify `create_mcp_server(config)` wires a `CaptureClient` into the default `TvManager`.
|
||||||
|
|
||||||
* **Type / Scope:** Developer Mode `asyncssh`/SFTP screenshot client and `CaptureTransport` adapter.
|
#### 4. `tests/test_e2e_mvp.py` (Completed — Issue `#11`, PR [#14](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/14))
|
||||||
* **Proposed Changes:** Implement `AsyncSshCaptureTransport` (`prisoner@<TV_IP>:9922`, `config=[]`, `known_hosts=None` default or `SSH_KNOWN_HOSTS_PATH`, `server_host_key_algs=["ssh-rsa"]`, `signature_algs=["ssh-rsa"]`, optional `WEBOS_SSH_PASSPHRASE`), lazily connecting/reconnecting its `asyncssh` SFTP session inside `read_and_remove()` and running `sweep_temp_files("/tmp/lg_smtv_cap_")` on each new SFTP connection. In `CaptureClient.capture_frame(ssap_request_fn)`, wrap `ssap://com.webos.service.capture/executeOneShot` (`{"path": "/tmp/lg_smtv_cap_<seq>.jpg", "method": "DISPLAY", "format": "JPG"}`) and `CaptureTransport.read_and_remove(remote_path, timeout=6.0, cleanup_grace=1.5)` under `asyncio.timeout(6.0)`. Raise `SCREENSHOT_UNAVAILABLE` if `executeOneShot` returns `returnValue: false` or SSH fails, and compute `frame_sha256` and `changed_since_last`.
|
|
||||||
|
|
||||||
#### 10. `src/lg_smtv_mcp/tv_core/manager.py` and `src/lg_smtv_mcp/tv_core/__init__.py` (Create)
|
* **Type / Scope:** E2E test harness and standby parity hardening (PR `#10` follow-up).
|
||||||
|
* **Delivered Changes:**
|
||||||
|
* Extracted `_build_online_ssap` to a module-level helper in `tests/test_e2e_mvp.py`.
|
||||||
|
* Handled `lifespan.startup.failed` (or raced `startup_done.wait()` against `lifespan_task`) in the ASGI lifespan helper so startup failures surface immediately without waiting for the `2.0s` timeout.
|
||||||
|
* Asserted `isinstance(wake_payload["elapsed_ms"], int) and wake_payload["elapsed_ms"] >= 0` on `tv_wake`.
|
||||||
|
* After `turn_off()`, simulated the TV closing the SSAP WebSocket with `1008` and re-queried `get_state` to verify `connected: false, stale: true` with cached state retained.
|
||||||
|
|
||||||
* **Type / Scope:** Single-owner connection state machine, `subscribe` cache, and WoL helper.
|
#### 5. `deploy/lg-smtv-mcp.service` and `README.md` (Completed — Issue `#13`, PR [#16](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/16))
|
||||||
* **Proposed Changes:**
|
|
||||||
* Implement `send_wol(mac, broadcast_addr, port=9)` UDP magic packet helper.
|
|
||||||
* Implement `TvManager` owning a single connection loop (`CONNECTING`, `CONNECTED`, `STANDBY_OFFLINE`, `WAKING`, `PAIRING_REQUIRED`), stepped reconnect backoff (`2s -> 5s -> 15s -> 30s`), `CaptureClient.close()` teardown on `STANDBY_OFFLINE`, and `CLIENT_KEY_PATH` (`{ip: client_key}`) reload on `PAIRING_REQUIRED` backoff ticks or `SIGHUP` (logging and staying in `PAIRING_REQUIRED` on malformed JSON).
|
|
||||||
* Coalesce `wake()` via the connection loop (`45s` `WAKE_TIMEOUT` budget; `{status: "already_connected", elapsed_ms: 0}` in `CONNECTED`; fast-fail in `PAIRING_REQUIRED`).
|
|
||||||
* Subscribe to `ssap://audio/getStatus` (reading top-level `volume`/`mute` and nested `volumeStatus.soundOutput`) and `ssap://com.webos.applicationManager/getForegroundAppInfo`, transitioning `CONNECTED -> PAIRING_REQUIRED` on `401 insufficient permissions`.
|
|
||||||
* Expose lock-free `get_state()` (`last_updated` via `time.time()`, `connected: false, stale: true` when offline), `ui_lock` (`asyncio.Lock` with `25s` acquire timeout), and exact SSAP payloads: `setVolume` (`{"volume": level}`), `switchInput` (`{"inputId": input_id}`), `insertText` (`{"text": text, "replace": 0}`), `listLaunchPoints` (`payload["launchPoints"]` -> `[{id, title}]`), and `getExternalInputList` (`payload["devices"]` -> `[{id, label, connected}]`).
|
|
||||||
|
|
||||||
#### 11. `tests/conftest.py`, `tests/test_ssap.py`, `tests/test_capture.py`, and `tests/test_manager.py` (Create)
|
* **Type / Scope:** Systemd unit template and operator deployment documentation.
|
||||||
|
* **Delivered Changes:**
|
||||||
|
* Created `deploy/lg-smtv-mcp.service` template invoking `nix develop --command python -m lg_smtv_mcp serve` with `<User>`, `<WorkingDirectory>`, `EnvironmentFile`, `Restart=on-failure`, and `PATH` containing `<NixBinDir>`.
|
||||||
|
* Updated `README.md` with `systemd` setup instructions, Developer Mode pairing workflow (`python -m lg_smtv_mcp pair --fetch-ssh-key`), DNS-rebinding host configuration (`HOST` + `ALLOWED_HOSTS`), and live-TV operator smoke checklist items.
|
||||||
|
* Follow-up unit sandboxing hardening was delivered in issue [#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17) (PR [#18](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/18)), adding bounded restart limits, a 14-directive sandboxing baseline (`9.0 UNSAFE` → `4.9 OK`), automated `systemd-analyze` verification in `tests/test_deploy.py`, and the `asyncssh` SFTP `open()` capture fix.
|
||||||
|
|
||||||
* **Type / Scope:** Offline `tv_core` contract tests.
|
* **M2 Delivery Checkpoint:** All checks (`ruff`, `pyright`, `pytest`, `nix flake check`) passed; PR #16 merged on `main`.
|
||||||
* **Proposed Changes:**
|
|
||||||
* `tests/test_ssap.py`: Verify `msg["id"]` multiplexing with interleaved `subscribe` updates, `1008` -> `TV_OFFLINE_STANDBY`, `COMMAND_FAILED` on `returnValue: false`, and pending `Future` failure in `_reader_loop()` `finally:`.
|
|
||||||
* `tests/test_capture.py`: Verify `executeOneShot` `returnValue: false` -> `SCREENSHOT_UNAVAILABLE`, `finally: sftp.remove()` under `1.5s` grace, `sweep_temp_files` on reconnect, `6.0s` shared deadline, and `frame_sha256` / `changed_since_last`.
|
|
||||||
* `tests/test_manager.py`: Verify `tv_wake` coalescing, `CONNECTED` no-op, and `45s` `WAKE_TIMEOUT`; `CaptureClient` teardown on `STANDBY_OFFLINE`; `audio/getStatus` nested `soundOutput`; offline `get_state` flat dict; `keys` allowlist/newline/bounds rejection and mid-batch pointer re-acquire; `ui_lock` `25s` timeout; `keys`/`type_text(..., capture=True)` partial success when SSH fails; `PAIRING_REQUIRED` reload on backoff/`SIGHUP` (including malformed JSON); and `MAX_VOLUME` guardrail.
|
|
||||||
|
|
||||||
* **Phase 2 Checkpoint:** `nix develop --command ruff check . && nix develop --command pyright && nix develop --command pytest tests/test_ssap.py tests/test_capture.py tests/test_manager.py`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Phase 3: FastMCP Server, Bearer Auth, CLI & Deployment
|
|
||||||
|
|
||||||
#### 12. `src/lg_smtv_mcp/auth.py` (Create)
|
|
||||||
|
|
||||||
* **Type / Scope:** HTTP Bearer token ASGI middleware and transport security.
|
|
||||||
* **Proposed Changes:** Implement an ASGI middleware verifying `Authorization: Bearer <token>` via `hmac.compare_digest` (returning `401` on missing/invalid token) around FastMCP's built-in `streamable_http_app()`, and configure MCP `TransportSecuritySettings` (`allowed_hosts` / `allowed_origins` from `HOST`/`PORT`, `127.0.0.1`/`localhost`, and `ALLOWED_HOSTS`).
|
|
||||||
|
|
||||||
#### 13. `src/lg_smtv_mcp/server.py` (Create)
|
|
||||||
|
|
||||||
* **Type / Scope:** FastMCP server, ASGI `lifespan`, and tool definitions.
|
|
||||||
* **Proposed Changes:** Bind `TvManager` startup, `SIGHUP` `loop.add_signal_handler`, and connection/task teardown on shutdown to FastMCP's ASGI `lifespan` context manager. Register all 12 default tools (`tv_wake`, `get_state`, `keys`, `type_text`, `screenshot`, `launch`, `list_apps`, `set_volume`, `set_mute`, `list_inputs`, `switch_input`, `turn_off`) and conditionally register `raw_ssap` only when `ENABLE_RAW_SSAP=true`. Map `TvError` to FastMCP `ToolError(f"{err.code.value}: {err.message}")`; return `list[TextContent | ImageContent]` (`TextContent` JSON metadata + `ImageContent(type="image", data=base64_jpeg, mimeType="image/jpeg")`) when an image is captured. In `launch`, build `params = dict(params or {})`, set `params["contentTarget"] = content_target` if provided, and include `"params": params` in the SSAP payload only when non-empty. Validate `1 <= len(text) <= 500` in `type_text` (`INVALID_ARGUMENT`) and document the native-keyboard requirement in its tool description.
|
|
||||||
|
|
||||||
#### 14. `src/lg_smtv_mcp/cli.py` (Create)
|
|
||||||
|
|
||||||
* **Type / Scope:** CLI entrypoint (`serve`, `pair`).
|
|
||||||
* **Proposed Changes:** Implement `serve --transport [streamable-http|stdio]` (failing closed if `MCP_BEARER_TOKEN` is unset/whitespace for `streamable-http`; delegating to FastMCP's `streamable_http_app()` wrapped with `auth.py`, or `FastMCP.run(transport="stdio")`). Implement `pair [--ip <TV_IP>] [--fetch-ssh-key] [--ssh-key-path <PATH>]` (defaulting `--ip` to `TV_IP` from `TvConfig`), merging existing `.client_key.json` entries before atomic `os.replace`, and optionally fetching `http://<TV_IP>:9991/webos_rsa` via stdlib `urllib.request` to `--ssh-key-path` (defaulting to `SSH_KEY_PATH` or `.webos_rsa`) with `0600` permissions (keeping any saved client key and exiting non-zero if key fetch fails).
|
|
||||||
|
|
||||||
#### 15. `tests/test_server_auth.py` (Create)
|
|
||||||
|
|
||||||
* **Type / Scope:** Offline MCP server and HTTP auth contract tests.
|
|
||||||
* **Proposed Changes:** Use `httpx` ASGI test client against FastMCP + `auth.py` to verify Bearer auth `401` / `200` constant-time checks, `TransportSecuritySettings` host validation, `ENABLE_RAW_SSAP` gating, `ToolError` formatting, `launch` `params` construction, `type_text` length bounds, and `list[TextContent | ImageContent]` image responses.
|
|
||||||
|
|
||||||
#### 16. `deploy/lg-smtv-mcp.service` and `README.md` (Create / Modify)
|
|
||||||
|
|
||||||
* **Type / Scope:** Deployment template and repository documentation.
|
|
||||||
* **Proposed Changes:** Add `deploy/lg-smtv-mcp.service` using `<User>`, `<WorkingDirectory>`, and `EnvironmentFile` placeholders invoking `nix develop --command python -m lg_smtv_mcp serve`, and update `README.md` with setup, `pair --fetch-ssh-key` / Developer Mode SSH setup, `.env`, and verification instructions.
|
|
||||||
|
|
||||||
* **Phase 3 Checkpoint:** `nix develop --command ruff check . && nix develop --command pyright && nix develop --command pytest`
|
|
||||||
|
|
||||||
### Verification Plan
|
### Verification Plan
|
||||||
|
|
||||||
* **Environment & Build:** `nix develop --command python -c "import lg_smtv_mcp"` and `nix build`
|
* **Environment & Build:** `nix develop --command python -c "import lg_smtv_mcp"` and `nix flake check`
|
||||||
* **Static Analysis & Linting:** `nix develop --command ruff check .` and `nix develop --command pyright`
|
* **Static Analysis & Linting:** `nix develop --command ruff check .`, `nix develop --command ruff format --check .`, and `nix develop --command pyright`
|
||||||
* **Offline Unit & Contract Tests:** `nix develop --command pytest` (offline against `Protocol` mocks; zero packets sent to physical hardware)
|
* **Offline Unit, Contract & E2E Tests:** `nix develop --command pytest` (offline against `Protocol` mocks; zero packets sent to physical hardware)
|
||||||
* **Manual Live-TV Integration Checks:** Explicit operator-run verification of `pair --fetch-ssh-key`, `tv_wake` from `1008` standby, `keys(..., capture=True)` with `asyncssh`, and `set_volume` cap against `<TV_IP>`.
|
* **Manual Live-TV Integration Checks:** Explicit operator-run verification of `pair --fetch-ssh-key`, `tv_wake` from `1008` standby, `keys(..., capture=True)` with `asyncssh`, and `set_volume` cap against `<TV_IP>`.
|
||||||
|
|
||||||
--------------------------------------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
# Standardized E2E Benchmark Baseline (`main` @ `0d67615`)
|
||||||
|
|
||||||
|
Standardized pre-#20/#23 baseline executed using [`e2e-benchmark-template.md`](e2e-benchmark-template.md) by subagent `281cc834-58db-4ed5-9d9c-21b1dfd34d67` against `65UR8750PSA` (`WebOS/4.1.0`).
|
||||||
|
|
||||||
|
## Preconditions
|
||||||
|
|
||||||
|
- **Commit / Branch:** `0d67615` (`main`)
|
||||||
|
- **Server Config:** `CAPTURE_MAX_WIDTH=unset`, `CAPTURE_JPEG_QUALITY=unset`
|
||||||
|
- **TV Starting State:** Powered ON at Live TV (`com.webos.app.livetv`), Crunchyroll closed.
|
||||||
|
- **Timer Boundary:** `T0 = 10:15:27.472`, `T_end = 10:17:55.874` (`-05:00`, excluding initial schema `read_file` setup).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Normalized Scorecard
|
||||||
|
|
||||||
|
| Metric | Unstandardized Run (`aac0035`) | Standardized Baseline (`0d67615`) | Notes |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **Total Timed Span (`T0 -> T_end`)** | `4m 38s` (`278s`, incl. `tv_wake`) | `2m 28s` (`148.40s`) | Zero-waste path via fixed runbook |
|
||||||
|
| **Total Steps / Captures** | `21` / `15` | `13` / `10` | `3` non-capture + `10` capture calls |
|
||||||
|
| **Median Capture Size (B)** | `22,824 B` | `19,045 B` | Range: `8,787 B` – `92,524 B` |
|
||||||
|
| **Disk-Only Offloads (`read_file` turns)** | `11` / `15` | `6` / `10` | All `>= 15,744 B` offloaded; all `<= 9,652 B` stayed inline |
|
||||||
|
| **Wasted / Retry Steps** | `4` | `0` | — |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step-by-Step Telemetry Table
|
||||||
|
|
||||||
|
| Step # | `T+elapsed` | Tool + Arguments | Tool Duration | Inline / Offload | `size_bytes` | `changed_since_last` | Observed Screen / Result |
|
||||||
|
|---:|---:|---|---:|:---:|---:|:---:|---|
|
||||||
|
| 1 | `+6.5s` | `get_state()` | ~3s | N | — | — | TV connected (`com.webos.app.livetv`) |
|
||||||
|
| 2 | `+9.5s` | `list_apps()` | ~6s | N | — | — | Found `com.crunchyroll.webapp` ("Crunchyroll") |
|
||||||
|
| 3 | `+18.5s` | `launch(app_id="com.crunchyroll.webapp")` | ~3s | N | — | — | App launched (`returnValue: true`) |
|
||||||
|
| 4 | `+29.5s` | `screenshot()` | ~4s | Y (inline + disk) | `9,650 B` | `true` | Black screen with orange loading spinner |
|
||||||
|
| 5 | `+38.5s` | `screenshot()` *(+ `read_file` ~1s)* | ~2s | Y (disk only) | `65,872 B` | `true` | Profile picker (`"¿Quién está viendo esto?"`, `Andres` focused) |
|
||||||
|
| 6 | `+54.5s` | `keys(keys=["ENTER"], settle_ms=2000, capture=True)` *(+ `read_file` ~1s)* | ~6s | Y (disk only) | `28,663 B` | `true` | Welcome loading screen (`"¡Te damos la bienvenida, Andres!"`) |
|
||||||
|
| 7 | `+69.5s` | `screenshot()` *(+ `read_file` ~1s)* | ~3s | Y (disk only) | `92,524 B` | `true` | Crunchyroll Home screen (`"Comenzar a Ver"` focused) |
|
||||||
|
| 8 | `+82.5s` | `keys(keys=["LEFT", "UP", "ENTER"], delay_ms=250, settle_ms=1500, capture=True)` *(+ `read_file` ~1s)* | ~4s | Y (disk only) | `22,346 B` | `true` | Search screen; `"Ataque a los Titanes"` under `"Búsquedas recientes"` |
|
||||||
|
| 9 | `+97.5s` | `keys(keys=["DOWN", "ENTER"], delay_ms=250, settle_ms=1500, capture=True)` *(+ `read_file` ~1s)* | ~4s | Y (disk only) | `15,744 B` | `true` | `"Ataque a los Titanes"` series page; `"Continuar E1"` focused |
|
||||||
|
| 10 | `+113.5s` | `keys(keys=["ENTER"], settle_ms=2000, capture=True)` | ~5s | Y (inline + disk) | `9,563 B` | `true` | Black screen with bottom-left orange buffering spinner |
|
||||||
|
| 11 | `+124.5s` | `screenshot()` | ~7s | Y (inline + disk) | `9,652 B` | `true` | Still buffering (bottom-left orange spinner) |
|
||||||
|
| 12 | `+130.5s` | `screenshot()` | ~2s | Y (inline + disk) | `8,787 B` | `true` | Solid black DRM frame (playback started) |
|
||||||
|
| 13 | `+137.5s` | `keys(keys=["DOWN"], settle_ms=800, capture=True)` *(+ `read_file` <1s)* | ~3s | Y (disk only) | `26,617 B` | `true` | Player HUD: `Ataque a los Titanes / E1 - Para ti, en 2000 años -- La caída de Shiganshina, parte 1` (`01:31 / 24:08`) |
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
# Crunchyroll E2E Comparative Report (PoC vs. `lg-smtv-mcp`)
|
||||||
|
|
||||||
|
Comparison between the initial PoC run ([`crunchyroll-e2e-experiment.md`](../poc/crunchyroll-e2e-experiment.md)) and the first live `lg-smtv-mcp` (`main` @ `aac0035`) subagent run (`b050beec-fc4c-4240-a54c-4613b8364893`) against `65UR8750PSA` (`WebOS/4.1.0`).
|
||||||
|
|
||||||
|
**Goal:** Launch Crunchyroll, select profile (`Andres`), open *Attack on Titan* (*Ataque a los Titanes*), and start Episode 1.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Executive Summary
|
||||||
|
|
||||||
|
| Metric | PoC Baseline | `lg-smtv-mcp` (`aac0035`) | Notes |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **Total Elapsed Time** | `7m 07s` (`427s`) | `4m 56s` (`296s`) | `lg-smtv-mcp` run also included `tv_wake` (`5.57s`), `T17 -> T1` (`UP x16`), and HUD verification |
|
||||||
|
| **Timed TV Control Span** | `~7m 05s` | `4m 38s` (`09:37:29 -> 09:42:07`) | Excludes initial schema `read_file` setup |
|
||||||
|
| **Steps / Captures** | `13` steps / `12` captures | `21` steps / `15` captures | Different reasoning paths; not 1-to-1 comparable |
|
||||||
|
| **Per-Step Tool Duration** | `~8–10s` (fresh `nix develop` + TLS + `register` + `scp`) | `2–5s` (persistent SSAP + `asyncssh` SFTP) | Transport overhead eliminated by `TvManager` |
|
||||||
|
| **Capture Size Range** | `9,606 B` – `101,992 B` | `8,787 B` – `103,192 B` | 11/15 captures exceeded ~10–15 KB and offloaded to disk |
|
||||||
|
|
||||||
|
### What MCP Bought vs. What It Didn't
|
||||||
|
|
||||||
|
- **What `TvManager` (not MCP itself) bought:** Persistent SSAP/pointer sockets and warm `asyncssh` SFTP cut per-step transport latency from `~8–10s` to `~2–5s`. A persistent REST API backed by `TvManager` would yield the same transport speedup.
|
||||||
|
- **What MCP bought:** Zero-glue host integration (typed schemas, `ImageContent` multimodal blocks, and `stdio` / `streamable-http` lifecycle) across Antigravity and other MCP clients without writing custom client wrappers.
|
||||||
|
- **What MCP did *not* buy:** Fewer UI discovery steps or faster LLM turns. Because 11 of 15 captures (`11 KB – 103 KB`) exceeded Antigravity's inline image threshold, Antigravity offloaded them to disk and spent an extra `read_file` LLM turn (`~10–15s` gap between steps) on almost every UI screen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Three-Bucket Latency Breakdown (`lg-smtv-mcp` Run)
|
||||||
|
|
||||||
|
1. **Transport & Process Overhead (`~45–60s` total across 21 steps):**
|
||||||
|
Persistent SSAP + `asyncssh` SFTP took `2–5s` per capture call (including `settle_ms`).
|
||||||
|
2. **Host / LLM Turn Overhead (`~3m 30s`):**
|
||||||
|
- Full coding-agent turn latency (`~8–12s` per turn).
|
||||||
|
- **11 extra `read_file` turns** caused by disk-offloaded `ImageContent` (`> ~10–15 KB`), directly motivating Issue **#20** (host-side JPEG downscaling/recompression).
|
||||||
|
- **Retry / loading turns:** Skeleton/loading captures (Steps 5, 7, 13, 18, 19) and `type_text` without native IME (Steps 10–11), motivating Issue **#23** (`wait_for_change`).
|
||||||
|
3. **TV / App Hardware Settling (`~20s`):**
|
||||||
|
`tv_wake` (`5.57s`), Crunchyroll splash/profile load, `UP x16` list scroll, and video buffering.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Detailed Step Log (`lg-smtv-mcp` @ `aac0035`)
|
||||||
|
|
||||||
|
| Step | Time (`-05:00`) | Action / Tool + Arguments | Observed Screen / Result | Capture Size | `changed_since_last` / Hash |
|
||||||
|
| :--- | :--- | :--- | :--- | :--- | :--- |
|
||||||
|
| 0 | `09:37:17 -> 09:37:25` | `date` + `read_file` on 7 `lg-smtv` schemas | Start `09:37:19.214`; schemas loaded | — | — |
|
||||||
|
| 1 | `09:37:29 -> 09:37:30` | `get_state({})` | `connected: false, stale: true` (TV in standby) | — | — |
|
||||||
|
| 2 | `09:37:34 -> 09:37:42` | `tv_wake({})` | `status: "connected"`, `elapsed_ms: 5572` | — | — |
|
||||||
|
| 3 | `09:37:45 -> 09:37:48` | `list_apps({})` | Found `com.crunchyroll.webapp` | — | — |
|
||||||
|
| 4 | `09:37:53 -> 09:37:57` | `launch({"app_id": "com.crunchyroll.webapp"})` | `returnValue: true` | — | — |
|
||||||
|
| 5 | `09:38:01 -> 09:38:05` | `screenshot({})` + `read_file` | Crunchyroll splash screen | `94,613 B` | `true` / `548af733` |
|
||||||
|
| 6 | `09:38:16 -> 09:38:19` | `screenshot({})` + `read_file` | Profile picker (`"¿Quién está viendo esto?"`, `Andres` focused) | `65,872 B` | `true` / `4cf77ce7` |
|
||||||
|
| 7 | `09:38:31 -> 09:38:36` | `keys(["ENTER"], settle_ms=2000, capture=True)` + `read_file` | Profile selected; home sidebar rendered, content loading | `11,050 B` | `true` / `7f544a6e` |
|
||||||
|
| 8 | `09:38:48 -> 09:38:50` | `screenshot({})` + `read_file` | Home screen loaded; focus on `"Comenzar a Ver"` | `92,524 B` | `true` / `08d99efe` |
|
||||||
|
| 9 | `09:39:00 -> 09:39:04` | `keys(["LEFT", "UP", "ENTER"], delay_ms=250, settle_ms=800, capture=True)` + `read_file` | Search opened; `"Ataque a los Titanes"` in recent searches | `22,346 B` | `true` / `ac885345` |
|
||||||
|
| 10 | `09:39:15 -> 09:39:17` | `keys(["ENTER"], settle_ms=800, capture=True)` | No screen change (Crunchyroll search input did not open native IME) | `22,346 B` | `false` / `ac885345` |
|
||||||
|
| 11 | `09:39:23 -> 09:39:26` | `type_text("Attack on Titan", send_enter=True, capture=True)` | `text_sent: true`, screen unchanged (IME not open) | `22,346 B` | `false` / `ac885345` |
|
||||||
|
| 12 | `09:39:32 -> 09:39:35` | `keys(["DOWN"], settle_ms=800, capture=True)` + `read_file` | Focused `"Ataque a los Titanes"` under `"Búsquedas recientes"` | `22,824 B` | `true` / `bce1361e` |
|
||||||
|
| 13 | `09:39:49 -> 09:39:53` | `keys(["ENTER"], settle_ms=1500, capture=True)` + `read_file` | Series page loading (skeleton placeholders) | `16,665 B` | `true` / `463499ed` |
|
||||||
|
| 14 | `09:40:05 -> 09:40:08` | `screenshot({})` + `read_file` | Series page loaded (`"Continuar E17"`) | `89,709 B` | `true` / `bc2357f7` |
|
||||||
|
| 15 | `09:40:20 -> 09:40:23` | `keys(["DOWN"], settle_ms=800, capture=True)` + `read_file` | Focused `"EPISODIOS"` tab; Season 1 listed with `T17` | `96,025 B` | `true` / `e91c7353` |
|
||||||
|
| 16 | `09:40:38 -> 09:40:41` | `keys(["DOWN", "RIGHT"], delay_ms=250, settle_ms=800, capture=True)` + `read_file` | Focused `T17 - La titán hembra...` | `102,035 B` | `true` / `59a5942b` |
|
||||||
|
| 17 | `09:40:56 -> 09:41:01` | `keys(["UP"] * 16, delay_ms=150, settle_ms=800, capture=True)` + `read_file` | Focused `T1 - Para ti, en 2000 años -- La caída de S...` | `103,192 B` | `true` / `1f611a48` |
|
||||||
|
| 18 | `09:41:28 -> 09:41:37` | `keys(["ENTER"], settle_ms=2000, capture=True)` *(after `settle_ms=2500` failed `INVALID_ARGUMENT`)* | Player buffering (orange spinner) | `9,608 B` | `true` / `1cf098ba` |
|
||||||
|
| 19 | `09:41:45 -> 09:41:48` | `screenshot({})` | Still buffering (spinner rotated) | `9,565 B` | `true` / `66e7dae3` |
|
||||||
|
| 20 | `09:41:55 -> 09:41:57` | `screenshot({})` | Spinner gone, black frame (DRM video layer) | `8,787 B` | `true` / `f6ed2d39` |
|
||||||
|
| 21 | `09:42:05 -> 09:42:07` | `keys(["DOWN"], settle_ms=500, capture=True)` + `read_file` (`09:42:15`) | Player HUD: `E1 - Para ti, en 2000 años -- La caída de Shiganshina, parte 1` at `00:19 / 25:20` | `17,889 B` | `true` / `02654704` |
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# Post-#20 Standardized E2E Benchmark (`main` @ `09618be`)
|
||||||
|
|
||||||
|
Post-**#20** benchmark executed using [`e2e-benchmark-template.md`](e2e-benchmark-template.md) by subagent `9d82e846-0c13-4c82-8f8f-2780d34ad173` against `65UR8750PSA` (`WebOS/4.1.0`), compared against [`crunchyroll-e2e-baseline-0d67615.md`](crunchyroll-e2e-baseline-0d67615.md).
|
||||||
|
|
||||||
|
## Preconditions
|
||||||
|
|
||||||
|
- **Commit / Branch:** `09618be` (`main`, PR `#24`)
|
||||||
|
- **Server Config:** `CAPTURE_MAX_WIDTH=480`, `CAPTURE_JPEG_QUALITY=55`
|
||||||
|
- **TV Starting State:** Powered ON at Live TV (`com.webos.app.livetv`), Crunchyroll closed.
|
||||||
|
- **Timer Boundary:** `T0 = 11:16:18.965`, `T_end = 11:19:06.423` (`-05:00`, excluding initial schema `read_file` setup).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Normalized Scorecard
|
||||||
|
|
||||||
|
| Metric | Baseline (`0d67615`, raw `960x540`) | Post-**#20** (`09618be`, `480px`, `q=55`) | Delta |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **Total Timed Span (`T0 -> T_end`)** | `148.40s` (`13` steps) | `167.46s` (`17` steps) | `+19.06s` *(4 extra steps: Crunchyroll auto-resumed previous show + 1 `ENTER` retry)* |
|
||||||
|
| **Average Time per Step** | `11.42s / step` | `9.85s / step` | `-1.57s / step` |
|
||||||
|
| **Total Steps / Captures** | `13` / `10` | `17` / `14` | `+4` / `+4` |
|
||||||
|
| **Median Capture Size (B)** | `19,045 B` | `5,893 B` | `-69.1%` |
|
||||||
|
| **Disk-Only Offloads (`read_file` turns)** | `6 / 10` (`60%`) | `1 / 14` (`7%`) | `-53 pp` *(only `10,951 B` splash offloaded; all `<= 8,421 B` stayed inline)* |
|
||||||
|
| **Wasted / Retry Steps** | `0` | `1` | `+1` *(Step 6 `ENTER` on profile screen)* |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step-by-Step Telemetry Table
|
||||||
|
|
||||||
|
| Step # | `T+elapsed` | Tool + Arguments | Tool Duration | Inline / Offload | `size_bytes` | `changed_since_last` | Observed Screen / Result |
|
||||||
|
|---:|---:|---|---:|:---:|---:|:---:|---|
|
||||||
|
| 1 | `~8s` | `get_state()` | ~2s | N | — | — | `connected: true`, `foreground_app: com.webos.app.livetv` |
|
||||||
|
| 2 | `~11s` | `list_apps()` | ~5s | N | — | — | Found `com.crunchyroll.webapp` ("Crunchyroll") |
|
||||||
|
| 3 | `~19s` | `launch(app_id="com.crunchyroll.webapp")` | ~4s | N | — | — | `returnValue: true` |
|
||||||
|
| 4 | `~29s` | `screenshot()` *(+ `read_file`)* | ~4s | Y (disk only) | `10,951 B` | `true` | Crunchyroll splash screen |
|
||||||
|
| 5 | `~44s` | `screenshot()` | ~3s | Y (inline + disk) | `8,421 B` | `true` | Profile picker (`Andres` focused) |
|
||||||
|
| 6 | `~53s` | `keys(["ENTER"], settle_ms=1800, capture=True)` | ~4s | Y (inline + disk) | `8,421 B` | `false` | Still on profile picker (`Andres` focused) |
|
||||||
|
| 7 | `~64s` | `keys(["ENTER"], settle_ms=2000, capture=True)` | ~5s | Y (inline + disk) | `2,782 B` | `true` | Black loading spinner |
|
||||||
|
| 8 | `~73s` | `screenshot()` | ~4s | Y (inline + disk) | `2,812 B` | `true` | Black loading spinner |
|
||||||
|
| 9 | `~80s` | `screenshot()` | ~2s | Y (inline + disk) | `3,548 B` | `true` | Black DRM frame (auto-resumed previous show) |
|
||||||
|
| 10 | `~89s` | `keys(["DOWN"], settle_ms=1000, capture=True)` | ~4s | Y (inline + disk) | `6,454 B` | `true` | Player HUD: `Hello, I am a Witch... E1` |
|
||||||
|
| 11 | `~98s` | `keys(["BACK"], settle_ms=1500, capture=True)` | ~5s | Y (inline + disk) | `3,118 B` | `true` | Home screen loading with left sidebar |
|
||||||
|
| 12 | `~105s` | `keys(["LEFT"], settle_ms=800, capture=True)` | ~3s | Y (inline + disk) | `7,469 B` | `true` | Left sidebar open, `Inicio` focused |
|
||||||
|
| 13 | `~114s` | `keys(["UP", "ENTER"], settle_ms=1000, capture=True)` | ~4s | Y (inline + disk) | `5,499 B` | `true` | Search screen, `Ataque a los Titanes` under `Búsquedas recientes` |
|
||||||
|
| 14 | `~123s` | `keys(["DOWN", "ENTER"], settle_ms=1500, capture=True)` | ~4s | Y (inline + disk) | `7,545 B` | `true` | Series page `Ataque a los Titanes`, `Continuar E1` focused |
|
||||||
|
| 15 | `~139s` | `keys(["ENTER"], settle_ms=2000, capture=True)` | ~4s | Y (inline + disk) | `2,809 B` | `true` | Black loading spinner |
|
||||||
|
| 16 | `~146s` | `screenshot()` | ~2s | Y (inline + disk) | `3,540 B` | `true` | Black DRM frame (`16+` rating overlay) |
|
||||||
|
| 17 | `~155s` | `keys(["DOWN"], settle_ms=800, capture=True)` | ~4s | Y (inline + disk) | `6,287 B` | `true` | Player HUD: `Ataque a los Titanes` / `E1 - Para ti, en 2000 años -- La caída de Shiganshina, parte 1` (`08:02 / 17:37`) |
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# Standardized E2E Benchmark Template (`lg-smtv-mcp`)
|
||||||
|
|
||||||
|
Use this template to benchmark changes (such as **#20** JPEG downscaling or **#23** `wait_for_change`) without agent reasoning variance skewing the comparison.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Preconditions (Pin Before Starting)
|
||||||
|
|
||||||
|
- **Commit / Branch:** `<git rev-parse --short HEAD>` (`<branch>`)
|
||||||
|
- **Server Config:** `CAPTURE_MAX_WIDTH=<value|unset>`, `CAPTURE_JPEG_QUALITY=<value|unset>`
|
||||||
|
- **TV Starting State:** Powered ON at Live TV (or Standby — record which), Crunchyroll closed.
|
||||||
|
- **Timer Boundary:** Start `T=0` at the first TV-control tool call (`launch` or `tv_wake`), **excluding** one-time MCP schema `read_file` setup. End `T_end` when the playback HUD is verified.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Standardized Subagent Prompt
|
||||||
|
|
||||||
|
```text
|
||||||
|
Goal: Launch Crunchyroll, select profile "Andres", open Attack on Titan ("Ataque a los Titanes"), and start Episode 1.
|
||||||
|
|
||||||
|
Execution Rules (fixed policy for benchmark parity):
|
||||||
|
1. Load any needed lg-smtv schemas first, then record `T0` (`date +"%H:%M:%S.%3N"`).
|
||||||
|
2. Always prefer `keys(..., capture=True)` over separate `keys` + `screenshot` calls.
|
||||||
|
3. Keep `settle_ms <= 2000` (use `1500–2000` on app launch, profile select, and series page open).
|
||||||
|
4. On Crunchyroll Search, select "Ataque a los Titanes" from Recent Searches if visible instead of calling `type_text`.
|
||||||
|
5. Once playback starts (black DRM frame), press `DOWN` once with `capture=True` to verify Episode 1 on the player HUD.
|
||||||
|
6. Do NOT write or edit any repository files.
|
||||||
|
|
||||||
|
For every step, record:
|
||||||
|
- Step #, T+elapsed (s), Tool + arguments, Tool duration (ms/s), Offloaded to disk? (Y/N), Capture size_bytes, changed_since_last, Observed screen.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Normalized Scorecard
|
||||||
|
|
||||||
|
| Metric | Baseline (`aac0035`) | Candidate (`<sha>`) | Delta |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **Total Timed Span (`T0 -> T_end`)** | `4m 38s` (`278s`) | | |
|
||||||
|
| **Total Steps / Captures** | `21` / `15` | | |
|
||||||
|
| **Median Capture Size (B)** | `22,824 B` | | |
|
||||||
|
| **Offloaded Captures (`read_file` turns)** | `11` / `15` | | |
|
||||||
|
| **Wasted / Retry Steps** | `4` (steps 10, 11, 13→14, 18→19) | | |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Step-by-Step Telemetry Table
|
||||||
|
|
||||||
|
| Step | `T+s` | Tool + Arguments | Tool Duration | Offloaded? (`Y/N`) | `size_bytes` | `changed_since_last` | Observed Screen / Result |
|
||||||
|
| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- |
|
||||||
|
| 1 | | | | | | | |
|
||||||
@@ -17,6 +17,7 @@
|
|||||||
ps.pydantic
|
ps.pydantic
|
||||||
ps.asyncssh
|
ps.asyncssh
|
||||||
ps.uvicorn
|
ps.uvicorn
|
||||||
|
ps.pillow
|
||||||
];
|
];
|
||||||
|
|
||||||
testDeps = [
|
testDeps = [
|
||||||
@@ -25,6 +26,10 @@
|
|||||||
ps.pytest-asyncio
|
ps.pytest-asyncio
|
||||||
];
|
];
|
||||||
|
|
||||||
|
testTools = [
|
||||||
|
pkgs.systemd
|
||||||
|
];
|
||||||
|
|
||||||
pythonEnv = pkgs.python3.withPackages (_: runtimeDeps ++ testDeps);
|
pythonEnv = pkgs.python3.withPackages (_: runtimeDeps ++ testDeps);
|
||||||
in
|
in
|
||||||
{
|
{
|
||||||
@@ -39,7 +44,7 @@
|
|||||||
ps.pytestCheckHook
|
ps.pytestCheckHook
|
||||||
pkgs.ruff
|
pkgs.ruff
|
||||||
pkgs.pyright
|
pkgs.pyright
|
||||||
] ++ testDeps;
|
] ++ testDeps ++ testTools;
|
||||||
preCheck = ''
|
preCheck = ''
|
||||||
ruff check .
|
ruff check .
|
||||||
ruff format --check .
|
ruff format --check .
|
||||||
@@ -52,7 +57,7 @@
|
|||||||
pythonEnv
|
pythonEnv
|
||||||
pkgs.pyright
|
pkgs.pyright
|
||||||
pkgs.ruff
|
pkgs.ruff
|
||||||
];
|
] ++ testTools;
|
||||||
shellHook = ''
|
shellHook = ''
|
||||||
export PYTHONPATH="$PWD/src:${PYTHONPATH:-}"
|
export PYTHONPATH="$PWD/src:${PYTHONPATH:-}"
|
||||||
if [ -d .git ] && [ -d .githooks ]; then
|
if [ -d .git ] && [ -d .githooks ]; then
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ dependencies = [
|
|||||||
"pydantic",
|
"pydantic",
|
||||||
"asyncssh",
|
"asyncssh",
|
||||||
"uvicorn",
|
"uvicorn",
|
||||||
|
"pillow",
|
||||||
]
|
]
|
||||||
|
|
||||||
[project.scripts]
|
[project.scripts]
|
||||||
|
|||||||
@@ -0,0 +1,122 @@
|
|||||||
|
"""HTTP Bearer authentication ASGI middleware and MCP transport security settings."""
|
||||||
|
|
||||||
|
import hmac
|
||||||
|
import json
|
||||||
|
from collections.abc import Awaitable, Callable, Iterable, MutableMapping
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from mcp.server.transport_security import TransportSecuritySettings
|
||||||
|
|
||||||
|
from lg_smtv_mcp.config import TvConfig
|
||||||
|
from lg_smtv_mcp.errors import ConfigError
|
||||||
|
|
||||||
|
type Scope = MutableMapping[str, Any]
|
||||||
|
type Receive = Callable[[], Awaitable[MutableMapping[str, Any]]]
|
||||||
|
type Send = Callable[[MutableMapping[str, Any]], Awaitable[None]]
|
||||||
|
type ASGIApp = Callable[[Scope, Receive, Send], Awaitable[None]]
|
||||||
|
|
||||||
|
_UNAUTHORIZED_BODY = json.dumps({"error": "unauthorized"}).encode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def _dedupe(items: Iterable[str]) -> list[str]:
|
||||||
|
return list(dict.fromkeys(items))
|
||||||
|
|
||||||
|
|
||||||
|
def _add_host_variants(hosts: list[str], origins: list[str], raw_host: str, port: int) -> None:
|
||||||
|
entry = raw_host.strip()
|
||||||
|
if not entry:
|
||||||
|
return
|
||||||
|
if entry.startswith(("http://", "https://")):
|
||||||
|
origins.append(entry)
|
||||||
|
return
|
||||||
|
hosts.append(entry)
|
||||||
|
if ":" not in entry:
|
||||||
|
hosts.append(f"{entry}:{port}")
|
||||||
|
for scheme in ("http", "https"):
|
||||||
|
origins.append(f"{scheme}://{entry}")
|
||||||
|
origins.append(f"{scheme}://{entry}:{port}")
|
||||||
|
else:
|
||||||
|
for scheme in ("http", "https"):
|
||||||
|
origins.append(f"{scheme}://{entry}")
|
||||||
|
|
||||||
|
|
||||||
|
def build_transport_security_settings(config: TvConfig) -> TransportSecuritySettings:
|
||||||
|
"""Derive DNS-rebinding TransportSecuritySettings from TvConfig."""
|
||||||
|
hosts: list[str] = []
|
||||||
|
origins: list[str] = []
|
||||||
|
|
||||||
|
for local_host in ("127.0.0.1", "localhost"):
|
||||||
|
hosts.extend([f"{local_host}:{config.port}", f"{local_host}:*", local_host])
|
||||||
|
for scheme in ("http", "https"):
|
||||||
|
origins.extend([f"{scheme}://{local_host}:{config.port}", f"{scheme}://{local_host}:*"])
|
||||||
|
|
||||||
|
if config.host and config.host not in {"0.0.0.0", "::"}:
|
||||||
|
_add_host_variants(hosts, origins, config.host, config.port)
|
||||||
|
|
||||||
|
for extra_host in config.allowed_hosts:
|
||||||
|
_add_host_variants(hosts, origins, extra_host, config.port)
|
||||||
|
|
||||||
|
return TransportSecuritySettings(
|
||||||
|
enable_dns_rebinding_protection=True,
|
||||||
|
allowed_hosts=_dedupe(hosts),
|
||||||
|
allowed_origins=_dedupe(origins),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class BearerAuthMiddleware:
|
||||||
|
"""ASGI middleware enforcing constant-time Authorization: Bearer <token>."""
|
||||||
|
|
||||||
|
def __init__(self, app: ASGIApp, token: str) -> None:
|
||||||
|
cleaned = token.strip()
|
||||||
|
if not cleaned:
|
||||||
|
raise ConfigError("MCP_BEARER_TOKEN must be a non-empty string")
|
||||||
|
self._app = app
|
||||||
|
self._token_bytes = cleaned.encode("utf-8")
|
||||||
|
|
||||||
|
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||||
|
if scope.get("type") != "http":
|
||||||
|
await self._app(scope, receive, send)
|
||||||
|
return
|
||||||
|
|
||||||
|
if not self._is_authorized(scope):
|
||||||
|
await send(
|
||||||
|
{
|
||||||
|
"type": "http.response.start",
|
||||||
|
"status": 401,
|
||||||
|
"headers": [
|
||||||
|
(b"content-type", b"application/json"),
|
||||||
|
(b"www-authenticate", b"Bearer"),
|
||||||
|
],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
await send(
|
||||||
|
{
|
||||||
|
"type": "http.response.body",
|
||||||
|
"body": _UNAUTHORIZED_BODY,
|
||||||
|
"more_body": False,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
await self._app(scope, receive, send)
|
||||||
|
|
||||||
|
def _is_authorized(self, scope: Scope) -> bool:
|
||||||
|
headers: Iterable[tuple[bytes, bytes]] = scope.get("headers", ())
|
||||||
|
auth_value: str | None = None
|
||||||
|
for name, value in headers:
|
||||||
|
if name.lower() == b"authorization":
|
||||||
|
auth_value = value.decode("latin-1")
|
||||||
|
break
|
||||||
|
if auth_value is None:
|
||||||
|
return False
|
||||||
|
|
||||||
|
parts = auth_value.split(" ", 1)
|
||||||
|
if len(parts) != 2 or parts[0].lower() != "bearer" or not parts[1]:
|
||||||
|
return False
|
||||||
|
|
||||||
|
return hmac.compare_digest(parts[1].encode("utf-8"), self._token_bytes)
|
||||||
|
|
||||||
|
|
||||||
|
def wrap_bearer_auth(app: ASGIApp, token: str) -> ASGIApp:
|
||||||
|
"""Wrap an ASGI application with BearerAuthMiddleware."""
|
||||||
|
return BearerAuthMiddleware(app, token)
|
||||||
+199
-5
@@ -1,9 +1,203 @@
|
|||||||
"""CLI entrypoint stub for lg-smtv-mcp (expanded in Issue #3)."""
|
"""CLI entrypoint for lg-smtv-mcp (serve and pair subcommands)."""
|
||||||
|
|
||||||
from collections.abc import Sequence
|
import argparse
|
||||||
|
import asyncio
|
||||||
|
import ipaddress
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from collections.abc import Callable, Sequence
|
||||||
|
from contextlib import suppress
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, cast
|
||||||
|
|
||||||
|
from mcp.server.mcpserver import MCPServer
|
||||||
|
from websockets.exceptions import WebSocketException
|
||||||
|
|
||||||
|
from lg_smtv_mcp.auth import ASGIApp
|
||||||
|
from lg_smtv_mcp.config import TvConfig, load_config
|
||||||
|
from lg_smtv_mcp.errors import ConfigError, ErrorCode, TvError
|
||||||
|
from lg_smtv_mcp.server import create_http_app, create_mcp_server
|
||||||
|
from lg_smtv_mcp.tv_core.protocols import WebSocketConnectFn
|
||||||
|
from lg_smtv_mcp.tv_core.ssap import build_register_payload, websockets_connect
|
||||||
|
|
||||||
|
|
||||||
def main(argv: Sequence[str] | None = None) -> int:
|
def _default_uvicorn_run(app: ASGIApp, host: str, port: int) -> None:
|
||||||
"""CLI entrypoint stub."""
|
import uvicorn
|
||||||
_ = argv
|
|
||||||
|
uvicorn.run(app, host=host, port=port)
|
||||||
|
|
||||||
|
|
||||||
|
def _default_stdio_run(server: MCPServer[Any]) -> None:
|
||||||
|
server.run(transport="stdio")
|
||||||
|
|
||||||
|
|
||||||
|
def _default_fetch_url(url: str) -> bytes:
|
||||||
|
from urllib.request import urlopen
|
||||||
|
|
||||||
|
with urlopen(url, timeout=10.0) as resp: # noqa: S310
|
||||||
|
return bytes(resp.read())
|
||||||
|
|
||||||
|
|
||||||
|
def _atomic_write_0600(path: Path, data: bytes) -> None:
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=str(path.parent))
|
||||||
|
tmp_path = Path(tmp_name)
|
||||||
|
try:
|
||||||
|
os.chmod(fd, 0o600)
|
||||||
|
with os.fdopen(fd, "wb") as handle:
|
||||||
|
handle.write(data)
|
||||||
|
os.chmod(tmp_path, 0o600)
|
||||||
|
os.replace(tmp_path, path)
|
||||||
|
except BaseException:
|
||||||
|
with suppress(OSError):
|
||||||
|
tmp_path.unlink()
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def _load_existing_keys(key_path: Path) -> dict[str, str]:
|
||||||
|
if not key_path.is_file():
|
||||||
|
return {}
|
||||||
|
try:
|
||||||
|
raw = json.loads(key_path.read_text(encoding="utf-8"))
|
||||||
|
except OSError, json.JSONDecodeError:
|
||||||
|
return {}
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
return {}
|
||||||
|
raw_dict = cast(dict[Any, Any], raw)
|
||||||
|
return {str(k): str(v) for k, v in raw_dict.items() if isinstance(v, str) and v}
|
||||||
|
|
||||||
|
|
||||||
|
async def _pair_tv(
|
||||||
|
ip: str,
|
||||||
|
existing_key: str | None,
|
||||||
|
connect_fn: WebSocketConnectFn,
|
||||||
|
) -> str:
|
||||||
|
ws = await connect_fn(f"wss://{ip}:3001")
|
||||||
|
try:
|
||||||
|
reg_payload = build_register_payload(existing_key)
|
||||||
|
await ws.send(json.dumps(reg_payload))
|
||||||
|
while True:
|
||||||
|
raw = await ws.recv()
|
||||||
|
frame: dict[str, Any] = json.loads(raw)
|
||||||
|
msg_type = frame.get("type")
|
||||||
|
if msg_type == "registered":
|
||||||
|
payload = frame.get("payload")
|
||||||
|
if isinstance(payload, dict):
|
||||||
|
payload_dict = cast(dict[str, Any], payload)
|
||||||
|
client_key = payload_dict.get("client-key")
|
||||||
|
if isinstance(client_key, str) and client_key:
|
||||||
|
return client_key
|
||||||
|
raise TvError(ErrorCode.PAIRING_REQUIRED, "TV registration returned no client-key")
|
||||||
|
if msg_type == "error":
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.PAIRING_REQUIRED,
|
||||||
|
f"TV pairing rejected: {frame.get('error', 'unknown error')}",
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
await ws.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _build_parser() -> argparse.ArgumentParser:
|
||||||
|
parser = argparse.ArgumentParser(prog="lg-smtv-mcp")
|
||||||
|
subparsers = parser.add_subparsers(dest="command", required=True)
|
||||||
|
|
||||||
|
serve_parser = subparsers.add_parser("serve", help="Run the MCP server.")
|
||||||
|
serve_parser.add_argument(
|
||||||
|
"--transport",
|
||||||
|
choices=["streamable-http", "stdio"],
|
||||||
|
default="streamable-http",
|
||||||
|
help="MCP transport to serve.",
|
||||||
|
)
|
||||||
|
|
||||||
|
pair_parser = subparsers.add_parser("pair", help="Pair with an LG webOS TV.")
|
||||||
|
pair_parser.add_argument("--ip", default=None, help="TV IPv4 address (defaults to TV_IP).")
|
||||||
|
pair_parser.add_argument(
|
||||||
|
"--fetch-ssh-key",
|
||||||
|
action="store_true",
|
||||||
|
help="Also fetch Developer Mode SSH private key from http://<TV_IP>:9991/webos_rsa.",
|
||||||
|
)
|
||||||
|
pair_parser.add_argument(
|
||||||
|
"--ssh-key-path",
|
||||||
|
type=Path,
|
||||||
|
default=None,
|
||||||
|
help="Destination path for fetched Developer Mode SSH key.",
|
||||||
|
)
|
||||||
|
return parser
|
||||||
|
|
||||||
|
|
||||||
|
def _handle_serve(
|
||||||
|
args: argparse.Namespace,
|
||||||
|
config: TvConfig,
|
||||||
|
*,
|
||||||
|
uvicorn_run: Callable[[ASGIApp, str, int], None],
|
||||||
|
stdio_run: Callable[[MCPServer[Any]], None],
|
||||||
|
) -> int:
|
||||||
|
if args.transport == "stdio":
|
||||||
|
server = create_mcp_server(config)
|
||||||
|
stdio_run(server)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
app = create_http_app(config)
|
||||||
|
uvicorn_run(app, config.host, config.port)
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def _handle_pair(
|
||||||
|
args: argparse.Namespace,
|
||||||
|
config: TvConfig,
|
||||||
|
*,
|
||||||
|
connect_fn: WebSocketConnectFn,
|
||||||
|
fetch_url: Callable[[str], bytes],
|
||||||
|
) -> int:
|
||||||
|
raw_ip: str = args.ip if args.ip is not None else config.tv_ip
|
||||||
|
try:
|
||||||
|
tv_ip = str(ipaddress.IPv4Address(raw_ip.strip()))
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ConfigError(f"Invalid TV IPv4 address: {raw_ip!r}") from exc
|
||||||
|
|
||||||
|
existing_keys = _load_existing_keys(config.client_key_path)
|
||||||
|
client_key = asyncio.run(_pair_tv(tv_ip, existing_keys.get(tv_ip), connect_fn))
|
||||||
|
existing_keys[tv_ip] = client_key
|
||||||
|
_atomic_write_0600(
|
||||||
|
config.client_key_path,
|
||||||
|
(json.dumps(existing_keys, indent=2) + "\n").encode("utf-8"),
|
||||||
|
)
|
||||||
|
|
||||||
|
if args.fetch_ssh_key:
|
||||||
|
ssh_dest: Path = args.ssh_key_path or config.ssh_key_path or Path(".webos_rsa")
|
||||||
|
key_bytes = fetch_url(f"http://{tv_ip}:9991/webos_rsa")
|
||||||
|
if not key_bytes.strip():
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.SCREENSHOT_UNAVAILABLE,
|
||||||
|
"Fetched Developer Mode SSH key was empty",
|
||||||
|
)
|
||||||
|
_atomic_write_0600(ssh_dest, key_bytes)
|
||||||
|
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def main(
|
||||||
|
argv: Sequence[str] | None = None,
|
||||||
|
*,
|
||||||
|
config_loader: Callable[[], TvConfig] = load_config,
|
||||||
|
uvicorn_run: Callable[[ASGIApp, str, int], None] = _default_uvicorn_run,
|
||||||
|
stdio_run: Callable[[MCPServer[Any]], None] = _default_stdio_run,
|
||||||
|
connect_fn: WebSocketConnectFn = websockets_connect,
|
||||||
|
fetch_url: Callable[[str], bytes] = _default_fetch_url,
|
||||||
|
env_path: Path | None = None,
|
||||||
|
) -> int:
|
||||||
|
"""CLI entrypoint for `lg-smtv-mcp serve` and `lg-smtv-mcp pair`."""
|
||||||
|
_ = env_path
|
||||||
|
parser = _build_parser()
|
||||||
|
args = parser.parse_args(list(argv) if argv is not None else None)
|
||||||
|
|
||||||
|
try:
|
||||||
|
config = config_loader()
|
||||||
|
if args.command == "serve":
|
||||||
|
return _handle_serve(args, config, uvicorn_run=uvicorn_run, stdio_run=stdio_run)
|
||||||
|
return _handle_pair(args, config, connect_fn=connect_fn, fetch_url=fetch_url)
|
||||||
|
except (ConfigError, TvError, WebSocketException, OSError, ValueError) as exc:
|
||||||
|
print(f"error: {exc}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
@@ -72,6 +72,8 @@ class TvConfig(BaseModel):
|
|||||||
mcp_bearer_token: str | None = None
|
mcp_bearer_token: str | None = None
|
||||||
max_volume: int = 40
|
max_volume: int = 40
|
||||||
enable_raw_ssap: bool = False
|
enable_raw_ssap: bool = False
|
||||||
|
capture_max_width: int | None = None
|
||||||
|
capture_jpeg_quality: int | None = None
|
||||||
|
|
||||||
def __init__(self, **data: Any) -> None:
|
def __init__(self, **data: Any) -> None:
|
||||||
try:
|
try:
|
||||||
@@ -100,6 +102,20 @@ class TvConfig(BaseModel):
|
|||||||
def _validate_max_volume(cls, value: Any) -> int:
|
def _validate_max_volume(cls, value: Any) -> int:
|
||||||
return _parse_bounded_int("MAX_VOLUME", value, min_val=0, max_val=100)
|
return _parse_bounded_int("MAX_VOLUME", value, min_val=0, max_val=100)
|
||||||
|
|
||||||
|
@field_validator("capture_max_width", mode="before")
|
||||||
|
@classmethod
|
||||||
|
def _validate_capture_max_width(cls, value: Any) -> int | None:
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
return _parse_bounded_int("CAPTURE_MAX_WIDTH", value, min_val=64, max_val=3840)
|
||||||
|
|
||||||
|
@field_validator("capture_jpeg_quality", mode="before")
|
||||||
|
@classmethod
|
||||||
|
def _validate_capture_jpeg_quality(cls, value: Any) -> int | None:
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
return _parse_bounded_int("CAPTURE_JPEG_QUALITY", value, min_val=1, max_val=95)
|
||||||
|
|
||||||
|
|
||||||
def _load_dotenv(env_path: Path) -> None:
|
def _load_dotenv(env_path: Path) -> None:
|
||||||
"""Populate unset os.environ keys from a .env file using stdlib only."""
|
"""Populate unset os.environ keys from a .env file using stdlib only."""
|
||||||
@@ -149,6 +165,8 @@ def load_config(env_path: Path | None = Path(".env")) -> TvConfig:
|
|||||||
tv_ip = _optional_str("TV_IP") or ""
|
tv_ip = _optional_str("TV_IP") or ""
|
||||||
port_raw = _optional_str("PORT")
|
port_raw = _optional_str("PORT")
|
||||||
max_volume_raw = _optional_str("MAX_VOLUME")
|
max_volume_raw = _optional_str("MAX_VOLUME")
|
||||||
|
capture_max_width_raw = _optional_str("CAPTURE_MAX_WIDTH")
|
||||||
|
capture_jpeg_quality_raw = _optional_str("CAPTURE_JPEG_QUALITY")
|
||||||
|
|
||||||
host = _optional_str("HOST") or "127.0.0.1"
|
host = _optional_str("HOST") or "127.0.0.1"
|
||||||
wol_broadcast = _optional_str("WOL_BROADCAST") or "255.255.255.255"
|
wol_broadcast = _optional_str("WOL_BROADCAST") or "255.255.255.255"
|
||||||
@@ -177,6 +195,10 @@ def load_config(env_path: Path | None = Path(".env")) -> TvConfig:
|
|||||||
kwargs["port"] = port_raw
|
kwargs["port"] = port_raw
|
||||||
if max_volume_raw is not None:
|
if max_volume_raw is not None:
|
||||||
kwargs["max_volume"] = max_volume_raw
|
kwargs["max_volume"] = max_volume_raw
|
||||||
|
if capture_max_width_raw is not None:
|
||||||
|
kwargs["capture_max_width"] = capture_max_width_raw
|
||||||
|
if capture_jpeg_quality_raw is not None:
|
||||||
|
kwargs["capture_jpeg_quality"] = capture_jpeg_quality_raw
|
||||||
|
|
||||||
return TvConfig(**kwargs)
|
return TvConfig(**kwargs)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,203 @@
|
|||||||
|
"""MCP server, ASGI lifespan management, and LG webOS TV tool definitions."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import signal
|
||||||
|
from collections.abc import AsyncGenerator, Awaitable, Callable
|
||||||
|
from contextlib import asynccontextmanager, suppress
|
||||||
|
from dataclasses import asdict
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from mcp.server.mcpserver import MCPServer
|
||||||
|
from mcp.server.mcpserver.exceptions import ToolError
|
||||||
|
from mcp.types import ImageContent, TextContent
|
||||||
|
|
||||||
|
from lg_smtv_mcp.auth import ASGIApp, build_transport_security_settings, wrap_bearer_auth
|
||||||
|
from lg_smtv_mcp.config import TvConfig, require_bearer_token
|
||||||
|
from lg_smtv_mcp.errors import ConfigError, TvError
|
||||||
|
from lg_smtv_mcp.tv_core import AsyncSshCaptureTransport, CaptureClient, TvManager
|
||||||
|
|
||||||
|
|
||||||
|
async def _run_tv_call[T](fn: Callable[[], Awaitable[T]]) -> T:
|
||||||
|
try:
|
||||||
|
return await fn()
|
||||||
|
except TvError as exc:
|
||||||
|
raise ToolError(f"{exc.code.value}: {exc.message}") from exc
|
||||||
|
except ConfigError as exc:
|
||||||
|
raise ToolError(exc.message) from exc
|
||||||
|
|
||||||
|
|
||||||
|
def _build_capture_content(
|
||||||
|
metadata: dict[str, Any],
|
||||||
|
image_bytes: bytes | None,
|
||||||
|
) -> list[TextContent | ImageContent]:
|
||||||
|
items: list[TextContent | ImageContent] = [
|
||||||
|
TextContent(type="text", text=json.dumps(metadata)),
|
||||||
|
]
|
||||||
|
if image_bytes is not None:
|
||||||
|
encoded = base64.b64encode(image_bytes).decode("ascii")
|
||||||
|
items.append(ImageContent(type="image", data=encoded, mime_type="image/jpeg"))
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def _register_tools(server: MCPServer, tv_manager: TvManager, config: TvConfig) -> None:
|
||||||
|
@server.tool(description="Wake the TV via Wake-on-LAN and wait until SSAP is connected.")
|
||||||
|
async def tv_wake() -> dict[str, Any]:
|
||||||
|
status = await _run_tv_call(tv_manager.wake)
|
||||||
|
return asdict(status)
|
||||||
|
|
||||||
|
@server.tool(description="Return cached TV state without blocking on standby or UI locks.")
|
||||||
|
async def get_state() -> dict[str, Any]:
|
||||||
|
return asdict(tv_manager.get_state())
|
||||||
|
|
||||||
|
@server.tool(description="Send a batch of remote control button keys with optional screenshot.")
|
||||||
|
async def keys(
|
||||||
|
keys: list[str],
|
||||||
|
delay_ms: int = 250,
|
||||||
|
settle_ms: int = 800,
|
||||||
|
capture: bool = False,
|
||||||
|
) -> list[TextContent | ImageContent]:
|
||||||
|
res = await _run_tv_call(
|
||||||
|
lambda: tv_manager.send_keys(
|
||||||
|
keys, delay_ms=delay_ms, settle_ms=settle_ms, capture=capture
|
||||||
|
)
|
||||||
|
)
|
||||||
|
metadata: dict[str, Any] = {"keys_sent": res.keys_sent, "count": res.count}
|
||||||
|
if res.frame_sha256 is not None:
|
||||||
|
metadata["frame_sha256"] = res.frame_sha256
|
||||||
|
if res.changed_since_last is not None:
|
||||||
|
metadata["changed_since_last"] = res.changed_since_last
|
||||||
|
if res.size_bytes is not None:
|
||||||
|
metadata["size_bytes"] = res.size_bytes
|
||||||
|
if res.capture_error is not None:
|
||||||
|
metadata["capture_error"] = res.capture_error
|
||||||
|
return _build_capture_content(metadata, res.image_bytes)
|
||||||
|
|
||||||
|
@server.tool(
|
||||||
|
description=(
|
||||||
|
"Insert text via webOS IME (requires the TV's native on-screen keyboard to be open), "
|
||||||
|
"optionally pressing Enter and capturing a screenshot."
|
||||||
|
)
|
||||||
|
)
|
||||||
|
async def type_text(
|
||||||
|
text: str,
|
||||||
|
send_enter: bool = True,
|
||||||
|
capture: bool = False,
|
||||||
|
) -> list[TextContent | ImageContent]:
|
||||||
|
res = await _run_tv_call(
|
||||||
|
lambda: tv_manager.type_text(text, send_enter=send_enter, capture=capture)
|
||||||
|
)
|
||||||
|
metadata: dict[str, Any] = {
|
||||||
|
"text_sent": res.text_sent,
|
||||||
|
"enter_sent": res.enter_sent,
|
||||||
|
}
|
||||||
|
if res.frame_sha256 is not None:
|
||||||
|
metadata["frame_sha256"] = res.frame_sha256
|
||||||
|
if res.changed_since_last is not None:
|
||||||
|
metadata["changed_since_last"] = res.changed_since_last
|
||||||
|
if res.size_bytes is not None:
|
||||||
|
metadata["size_bytes"] = res.size_bytes
|
||||||
|
if res.capture_error is not None:
|
||||||
|
metadata["capture_error"] = res.capture_error
|
||||||
|
return _build_capture_content(metadata, res.image_bytes)
|
||||||
|
|
||||||
|
@server.tool(description="Capture a TV screenshot and return JPEG image content plus metadata.")
|
||||||
|
async def screenshot() -> list[TextContent | ImageContent]:
|
||||||
|
res = await _run_tv_call(tv_manager.screenshot)
|
||||||
|
metadata: dict[str, Any] = {
|
||||||
|
"frame_sha256": res.frame_sha256,
|
||||||
|
"changed_since_last": res.changed_since_last,
|
||||||
|
"size_bytes": res.size_bytes,
|
||||||
|
}
|
||||||
|
return _build_capture_content(metadata, res.image_bytes)
|
||||||
|
|
||||||
|
@server.tool(description="Launch a webOS app by ID with optional contentTarget and params.")
|
||||||
|
async def launch(
|
||||||
|
app_id: str,
|
||||||
|
content_target: str | None = None,
|
||||||
|
params: dict[str, Any] | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
return await _run_tv_call(
|
||||||
|
lambda: tv_manager.launch_app(app_id, content_target=content_target, params=params)
|
||||||
|
)
|
||||||
|
|
||||||
|
@server.tool(description="List installed TV apps as [{id, title}].")
|
||||||
|
async def list_apps() -> list[dict[str, str]]:
|
||||||
|
return await _run_tv_call(tv_manager.list_apps)
|
||||||
|
|
||||||
|
@server.tool(description="Set TV volume within [0, MAX_VOLUME].")
|
||||||
|
async def set_volume(level: int) -> dict[str, Any]:
|
||||||
|
return await _run_tv_call(lambda: tv_manager.set_volume(level))
|
||||||
|
|
||||||
|
@server.tool(description="Set TV audio mute state.")
|
||||||
|
async def set_mute(muted: bool) -> dict[str, Any]:
|
||||||
|
return await _run_tv_call(lambda: tv_manager.set_mute(muted))
|
||||||
|
|
||||||
|
@server.tool(description="List external TV inputs as [{id, label, connected}].")
|
||||||
|
async def list_inputs() -> list[dict[str, Any]]:
|
||||||
|
return await _run_tv_call(tv_manager.list_inputs)
|
||||||
|
|
||||||
|
@server.tool(description="Switch active external TV input by input_id.")
|
||||||
|
async def switch_input(input_id: str) -> dict[str, Any]:
|
||||||
|
return await _run_tv_call(lambda: tv_manager.switch_input(input_id))
|
||||||
|
|
||||||
|
@server.tool(description="Power off the TV into standby.")
|
||||||
|
async def turn_off() -> dict[str, Any]:
|
||||||
|
return await _run_tv_call(tv_manager.turn_off)
|
||||||
|
|
||||||
|
if config.enable_raw_ssap:
|
||||||
|
|
||||||
|
@server.tool(
|
||||||
|
description="Send a raw SSAP request (enabled only when ENABLE_RAW_SSAP=true)."
|
||||||
|
)
|
||||||
|
async def raw_ssap(uri: str, payload: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||||
|
return await _run_tv_call(lambda: tv_manager.raw_ssap(uri, payload))
|
||||||
|
|
||||||
|
|
||||||
|
def create_mcp_server(config: TvConfig, manager: TvManager | None = None) -> MCPServer:
|
||||||
|
"""Create and configure the MCPServer instance with TV tools and lifespan."""
|
||||||
|
tv_manager = (
|
||||||
|
manager
|
||||||
|
if manager is not None
|
||||||
|
else TvManager(
|
||||||
|
config,
|
||||||
|
capture_client=CaptureClient(
|
||||||
|
AsyncSshCaptureTransport(config),
|
||||||
|
max_width=config.capture_max_width,
|
||||||
|
jpeg_quality=config.capture_jpeg_quality,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def _lifespan(_server: MCPServer[None]) -> AsyncGenerator[None]:
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
await tv_manager.start()
|
||||||
|
sighup_registered = False
|
||||||
|
if hasattr(signal, "SIGHUP"):
|
||||||
|
with suppress(NotImplementedError, AttributeError, ValueError):
|
||||||
|
loop.add_signal_handler(signal.SIGHUP, tv_manager.reload_client_key)
|
||||||
|
sighup_registered = True
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
if sighup_registered and hasattr(signal, "SIGHUP"):
|
||||||
|
with suppress(NotImplementedError, AttributeError, ValueError):
|
||||||
|
loop.remove_signal_handler(signal.SIGHUP)
|
||||||
|
await tv_manager.close()
|
||||||
|
|
||||||
|
server = MCPServer(name="lg-smtv-mcp", lifespan=_lifespan)
|
||||||
|
_register_tools(server, tv_manager, config)
|
||||||
|
return server
|
||||||
|
|
||||||
|
|
||||||
|
def create_http_app(config: TvConfig, manager: TvManager | None = None) -> ASGIApp:
|
||||||
|
"""Create the Bearer-authenticated Streamable HTTP ASGI application."""
|
||||||
|
token = require_bearer_token(config)
|
||||||
|
server = create_mcp_server(config, manager=manager)
|
||||||
|
app = server.streamable_http_app(
|
||||||
|
transport_security=build_transport_security_settings(config),
|
||||||
|
host=config.host,
|
||||||
|
)
|
||||||
|
return wrap_bearer_auth(app, token)
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
"""Core LG webOS TV transport, protocol, and state machine package."""
|
||||||
|
|
||||||
|
from lg_smtv_mcp.tv_core.capture import AsyncSshCaptureTransport, CaptureClient
|
||||||
|
from lg_smtv_mcp.tv_core.manager import ConnectionState, TvManager, TvState, send_wol
|
||||||
|
from lg_smtv_mcp.tv_core.pointer import BUTTON_ALLOWLIST, PointerClient, normalize_button_keys
|
||||||
|
from lg_smtv_mcp.tv_core.protocols import (
|
||||||
|
CaptureResult,
|
||||||
|
CaptureTransport,
|
||||||
|
FrameCapturer,
|
||||||
|
KeysResult,
|
||||||
|
TextResult,
|
||||||
|
TvStateSnapshot,
|
||||||
|
TvStatus,
|
||||||
|
WebSocketClosedError,
|
||||||
|
WebSocketConnectFn,
|
||||||
|
WebSocketTransport,
|
||||||
|
)
|
||||||
|
from lg_smtv_mcp.tv_core.ssap import (
|
||||||
|
PERMISSIONS,
|
||||||
|
SsapClient,
|
||||||
|
build_register_payload,
|
||||||
|
websockets_connect,
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"AsyncSshCaptureTransport",
|
||||||
|
"BUTTON_ALLOWLIST",
|
||||||
|
"CaptureClient",
|
||||||
|
"CaptureResult",
|
||||||
|
"CaptureTransport",
|
||||||
|
"ConnectionState",
|
||||||
|
"FrameCapturer",
|
||||||
|
"KeysResult",
|
||||||
|
"PERMISSIONS",
|
||||||
|
"PointerClient",
|
||||||
|
"SsapClient",
|
||||||
|
"TextResult",
|
||||||
|
"TvManager",
|
||||||
|
"TvState",
|
||||||
|
"TvStateSnapshot",
|
||||||
|
"TvStatus",
|
||||||
|
"WebSocketClosedError",
|
||||||
|
"WebSocketConnectFn",
|
||||||
|
"WebSocketTransport",
|
||||||
|
"build_register_payload",
|
||||||
|
"normalize_button_keys",
|
||||||
|
"send_wol",
|
||||||
|
"websockets_connect",
|
||||||
|
]
|
||||||
@@ -0,0 +1,274 @@
|
|||||||
|
"""AsyncSSH-backed capture transport and CaptureClient for LG webOS screenshots."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import hashlib
|
||||||
|
import os
|
||||||
|
from collections.abc import Awaitable, Callable
|
||||||
|
from contextlib import suppress
|
||||||
|
from io import BytesIO
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import asyncssh
|
||||||
|
from PIL import Image, UnidentifiedImageError
|
||||||
|
|
||||||
|
from lg_smtv_mcp.config import TvConfig
|
||||||
|
from lg_smtv_mcp.errors import ErrorCode, TvError
|
||||||
|
from lg_smtv_mcp.tv_core.protocols import CaptureResult, CaptureTransport
|
||||||
|
|
||||||
|
_DEFAULT_JPEG_QUALITY = 75
|
||||||
|
|
||||||
|
|
||||||
|
def _recompress_jpeg(
|
||||||
|
raw_bytes: bytes,
|
||||||
|
*,
|
||||||
|
max_width: int | None,
|
||||||
|
jpeg_quality: int | None,
|
||||||
|
) -> bytes:
|
||||||
|
"""Optionally downscale and/or recompress JPEG bytes for inline MCP delivery."""
|
||||||
|
if max_width is None and jpeg_quality is None:
|
||||||
|
return raw_bytes
|
||||||
|
|
||||||
|
quality = jpeg_quality if jpeg_quality is not None else _DEFAULT_JPEG_QUALITY
|
||||||
|
try:
|
||||||
|
with Image.open(BytesIO(raw_bytes)) as opened:
|
||||||
|
img: Image.Image = opened
|
||||||
|
width, height = img.size
|
||||||
|
if max_width is not None and width > max_width:
|
||||||
|
target_height = max(1, round(height * (max_width / width)))
|
||||||
|
img = img.resize( # pyright: ignore[reportUnknownMemberType]
|
||||||
|
(max_width, target_height),
|
||||||
|
Image.Resampling.LANCZOS,
|
||||||
|
)
|
||||||
|
if img.mode != "RGB":
|
||||||
|
img = img.convert("RGB")
|
||||||
|
out = BytesIO()
|
||||||
|
img.save(out, format="JPEG", quality=quality)
|
||||||
|
return out.getvalue()
|
||||||
|
except (
|
||||||
|
UnidentifiedImageError,
|
||||||
|
Image.DecompressionBombError,
|
||||||
|
OSError,
|
||||||
|
ValueError,
|
||||||
|
EOFError,
|
||||||
|
) as exc:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.SCREENSHOT_UNAVAILABLE,
|
||||||
|
f"Failed to process screenshot image: {exc}",
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
|
||||||
|
class AsyncSshCaptureTransport:
|
||||||
|
"""SFTP transport for reading and removing Developer Mode screenshot captures."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
config: TvConfig,
|
||||||
|
connect_fn: Callable[..., Awaitable[Any]] | None = None,
|
||||||
|
) -> None:
|
||||||
|
self._config = config
|
||||||
|
self._connect_fn = connect_fn or asyncssh.connect
|
||||||
|
self._conn: Any = None
|
||||||
|
self._sftp: Any = None
|
||||||
|
|
||||||
|
async def _close_handles(self) -> None:
|
||||||
|
sftp = self._sftp
|
||||||
|
conn = self._conn
|
||||||
|
self._sftp = None
|
||||||
|
self._conn = None
|
||||||
|
if sftp is not None:
|
||||||
|
with suppress(Exception):
|
||||||
|
exit_fn = getattr(sftp, "exit", None)
|
||||||
|
if callable(exit_fn):
|
||||||
|
res = exit_fn()
|
||||||
|
if asyncio.iscoroutine(res):
|
||||||
|
await res
|
||||||
|
else:
|
||||||
|
close_fn = getattr(sftp, "close", None)
|
||||||
|
if callable(close_fn):
|
||||||
|
res = close_fn()
|
||||||
|
if asyncio.iscoroutine(res):
|
||||||
|
await res
|
||||||
|
if conn is not None:
|
||||||
|
with suppress(Exception):
|
||||||
|
conn.close()
|
||||||
|
wait_closed = getattr(conn, "wait_closed", None)
|
||||||
|
if callable(wait_closed):
|
||||||
|
res = wait_closed()
|
||||||
|
if asyncio.iscoroutine(res):
|
||||||
|
await res
|
||||||
|
|
||||||
|
async def _ensure_sftp(self, exclude: str | None = None) -> Any:
|
||||||
|
if self._sftp is not None:
|
||||||
|
return self._sftp
|
||||||
|
|
||||||
|
config = self._config
|
||||||
|
conn = await self._connect_fn(
|
||||||
|
host=config.tv_ip,
|
||||||
|
port=9922,
|
||||||
|
username="prisoner",
|
||||||
|
config=[],
|
||||||
|
known_hosts=(
|
||||||
|
str(config.ssh_known_hosts_path)
|
||||||
|
if config.ssh_known_hosts_path is not None
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
server_host_key_algs=["ssh-rsa"],
|
||||||
|
signature_algs=["ssh-rsa"],
|
||||||
|
client_keys=[str(config.ssh_key_path)] if config.ssh_key_path is not None else None,
|
||||||
|
passphrase=config.webos_ssh_passphrase,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
sftp = await conn.start_sftp_client()
|
||||||
|
except BaseException:
|
||||||
|
conn.close()
|
||||||
|
with suppress(Exception):
|
||||||
|
wait_closed = getattr(conn, "wait_closed", None)
|
||||||
|
if callable(wait_closed):
|
||||||
|
res = wait_closed()
|
||||||
|
if asyncio.iscoroutine(res):
|
||||||
|
await res
|
||||||
|
raise
|
||||||
|
|
||||||
|
self._conn = conn
|
||||||
|
self._sftp = sftp
|
||||||
|
with suppress(Exception):
|
||||||
|
await self.sweep_temp_files("/tmp/lg_smtv_cap_", exclude=exclude)
|
||||||
|
return self._sftp
|
||||||
|
|
||||||
|
async def read_and_remove(
|
||||||
|
self,
|
||||||
|
remote_path: str,
|
||||||
|
timeout: float = 6.0,
|
||||||
|
cleanup_grace: float = 1.5,
|
||||||
|
) -> bytes:
|
||||||
|
sftp = None
|
||||||
|
try:
|
||||||
|
async with asyncio.timeout(timeout):
|
||||||
|
sftp = await self._ensure_sftp(exclude=remote_path)
|
||||||
|
async with sftp.open(remote_path, "rb") as handle:
|
||||||
|
data = await handle.read()
|
||||||
|
return bytes(data)
|
||||||
|
except asyncssh.Error, asyncssh.KeyImportError, OSError:
|
||||||
|
await self._close_handles()
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
if sftp is not None:
|
||||||
|
remove_task = asyncio.create_task(sftp.remove(remote_path))
|
||||||
|
|
||||||
|
def _consume_exception(task: asyncio.Task[Any]) -> None:
|
||||||
|
with suppress(Exception):
|
||||||
|
_ = task.exception()
|
||||||
|
|
||||||
|
remove_task.add_done_callback(_consume_exception)
|
||||||
|
with suppress(Exception):
|
||||||
|
await asyncio.wait_for(
|
||||||
|
asyncio.shield(remove_task),
|
||||||
|
timeout=cleanup_grace,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def sweep_temp_files(
|
||||||
|
self,
|
||||||
|
prefix: str = "/tmp/lg_smtv_cap_",
|
||||||
|
exclude: str | None = None,
|
||||||
|
) -> None:
|
||||||
|
sftp = self._sftp
|
||||||
|
if sftp is None:
|
||||||
|
return
|
||||||
|
directory = os.path.dirname(prefix) or "/tmp"
|
||||||
|
name_prefix = os.path.basename(prefix)
|
||||||
|
exclude_name = os.path.basename(exclude) if exclude else None
|
||||||
|
try:
|
||||||
|
entries = await sftp.listdir(directory)
|
||||||
|
except Exception:
|
||||||
|
return
|
||||||
|
for entry in entries:
|
||||||
|
if not isinstance(entry, str) or not entry.startswith(name_prefix):
|
||||||
|
continue
|
||||||
|
if exclude_name is not None and entry == exclude_name:
|
||||||
|
continue
|
||||||
|
remote_path = f"{directory.rstrip('/')}/{entry}"
|
||||||
|
with suppress(Exception):
|
||||||
|
await sftp.remove(remote_path)
|
||||||
|
|
||||||
|
async def close(self) -> None:
|
||||||
|
await self._close_handles()
|
||||||
|
|
||||||
|
|
||||||
|
class CaptureClient:
|
||||||
|
"""FrameCapturer that triggers executeOneShot and fetches JPEG via SFTP."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
transport: CaptureTransport,
|
||||||
|
*,
|
||||||
|
max_width: int | None = None,
|
||||||
|
jpeg_quality: int | None = None,
|
||||||
|
) -> None:
|
||||||
|
self._transport = transport
|
||||||
|
self._max_width = max_width
|
||||||
|
self._jpeg_quality = jpeg_quality
|
||||||
|
self._seq = 0
|
||||||
|
self._last_sha256: str | None = None
|
||||||
|
|
||||||
|
async def capture_frame(
|
||||||
|
self,
|
||||||
|
ssap_request_fn: Callable[[str, dict[str, Any]], Awaitable[dict[str, Any]]],
|
||||||
|
) -> CaptureResult:
|
||||||
|
self._seq += 1
|
||||||
|
remote_path = f"/tmp/lg_smtv_cap_{self._seq}.jpg"
|
||||||
|
try:
|
||||||
|
async with asyncio.timeout(6.0):
|
||||||
|
try:
|
||||||
|
response = await ssap_request_fn(
|
||||||
|
"ssap://com.webos.service.capture/executeOneShot",
|
||||||
|
{"path": remote_path, "method": "DISPLAY", "format": "JPG"},
|
||||||
|
)
|
||||||
|
except TvError as exc:
|
||||||
|
if exc.code in (ErrorCode.TV_OFFLINE_STANDBY, ErrorCode.PAIRING_REQUIRED):
|
||||||
|
raise
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.SCREENSHOT_UNAVAILABLE,
|
||||||
|
f"executeOneShot failed: {exc.message}",
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
if response.get("returnValue") is not True:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.SCREENSHOT_UNAVAILABLE,
|
||||||
|
"executeOneShot did not return returnValue true",
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
image_bytes = await self._transport.read_and_remove(
|
||||||
|
remote_path, timeout=6.0, cleanup_grace=1.5
|
||||||
|
)
|
||||||
|
except TvError:
|
||||||
|
raise
|
||||||
|
except (asyncssh.Error, asyncssh.KeyImportError, OSError) as exc:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.SCREENSHOT_UNAVAILABLE,
|
||||||
|
f"Failed to retrieve screenshot over SSH/SFTP: {exc}",
|
||||||
|
) from exc
|
||||||
|
except TimeoutError as exc:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.SCREENSHOT_UNAVAILABLE,
|
||||||
|
"Screenshot capture timed out after 6.0s",
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
image_bytes = _recompress_jpeg(
|
||||||
|
image_bytes,
|
||||||
|
max_width=self._max_width,
|
||||||
|
jpeg_quality=self._jpeg_quality,
|
||||||
|
)
|
||||||
|
frame_sha256 = hashlib.sha256(image_bytes).hexdigest()
|
||||||
|
changed_since_last = self._last_sha256 != frame_sha256
|
||||||
|
self._last_sha256 = frame_sha256
|
||||||
|
return CaptureResult(
|
||||||
|
image_bytes=image_bytes,
|
||||||
|
frame_sha256=frame_sha256,
|
||||||
|
changed_since_last=changed_since_last,
|
||||||
|
size_bytes=len(image_bytes),
|
||||||
|
)
|
||||||
|
|
||||||
|
async def close(self) -> None:
|
||||||
|
self._last_sha256 = None
|
||||||
|
await self._transport.close()
|
||||||
@@ -0,0 +1,606 @@
|
|||||||
|
"""Single-owner TV connection state machine, subscribe cache, and control surface."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import socket
|
||||||
|
import time
|
||||||
|
from collections.abc import AsyncGenerator, Awaitable, Callable
|
||||||
|
from contextlib import asynccontextmanager, suppress
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from enum import StrEnum
|
||||||
|
from typing import Any, cast
|
||||||
|
|
||||||
|
from lg_smtv_mcp.config import TvConfig, require_mac
|
||||||
|
from lg_smtv_mcp.errors import ConfigError, ErrorCode, TvError
|
||||||
|
from lg_smtv_mcp.tv_core.pointer import PointerClient, normalize_button_keys
|
||||||
|
from lg_smtv_mcp.tv_core.protocols import (
|
||||||
|
CaptureResult,
|
||||||
|
FrameCapturer,
|
||||||
|
KeysResult,
|
||||||
|
TextResult,
|
||||||
|
TvStateSnapshot,
|
||||||
|
TvStatus,
|
||||||
|
WebSocketConnectFn,
|
||||||
|
)
|
||||||
|
from lg_smtv_mcp.tv_core.ssap import SsapClient, websockets_connect
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
type EventWaitFn = Callable[[asyncio.Event, float], Awaitable[None]]
|
||||||
|
|
||||||
|
|
||||||
|
async def wait_event_or_timeout(event: asyncio.Event, timeout: float) -> None:
|
||||||
|
"""Wait until event is set or timeout seconds elapse, whichever comes first."""
|
||||||
|
with suppress(TimeoutError):
|
||||||
|
await asyncio.wait_for(event.wait(), timeout=timeout)
|
||||||
|
|
||||||
|
|
||||||
|
class ConnectionState(StrEnum):
|
||||||
|
"""Lifecycle states of the single-owner TvManager connection loop."""
|
||||||
|
|
||||||
|
CONNECTING = "CONNECTING"
|
||||||
|
CONNECTED = "CONNECTED"
|
||||||
|
STANDBY_OFFLINE = "STANDBY_OFFLINE"
|
||||||
|
WAKING = "WAKING"
|
||||||
|
PAIRING_REQUIRED = "PAIRING_REQUIRED"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(slots=True)
|
||||||
|
class TvState:
|
||||||
|
"""Mutable internal cache of TV state populated by SSAP subscribe streams."""
|
||||||
|
|
||||||
|
volume: int | None = None
|
||||||
|
muted: bool | None = None
|
||||||
|
sound_output: str | None = None
|
||||||
|
foreground_app: str | None = None
|
||||||
|
last_updated: float | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def send_wol(mac: str, broadcast_addr: str = "255.255.255.255", port: int = 9) -> None:
|
||||||
|
"""Broadcast a Wake-on-LAN magic packet for the given MAC address."""
|
||||||
|
clean_hex = mac.replace(":", "").replace("-", "").strip()
|
||||||
|
if len(clean_hex) != 12:
|
||||||
|
raise ConfigError(f"Invalid MAC address for Wake-on-LAN: {mac!r}")
|
||||||
|
try:
|
||||||
|
mac_bytes = bytes.fromhex(clean_hex)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ConfigError(f"Invalid MAC address for Wake-on-LAN: {mac!r}") from exc
|
||||||
|
|
||||||
|
magic = b"\xff" * 6 + mac_bytes * 16
|
||||||
|
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
|
||||||
|
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
||||||
|
sock.sendto(magic, (broadcast_addr, port))
|
||||||
|
|
||||||
|
|
||||||
|
class TvManager:
|
||||||
|
"""Single-owner connection state machine and serialized control surface."""
|
||||||
|
|
||||||
|
state: ConnectionState
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
config: TvConfig,
|
||||||
|
*,
|
||||||
|
connect_fn: WebSocketConnectFn = websockets_connect,
|
||||||
|
capture_client: FrameCapturer | None = None,
|
||||||
|
wol_fn: Callable[[str, str, int], None] = send_wol,
|
||||||
|
backoff_steps: tuple[float, ...] = (2.0, 5.0, 15.0, 30.0),
|
||||||
|
wake_poll_interval: float = 1.0,
|
||||||
|
wake_timeout: float = 45.0,
|
||||||
|
ui_lock_timeout: float = 25.0,
|
||||||
|
wait_fn: EventWaitFn = wait_event_or_timeout,
|
||||||
|
) -> None:
|
||||||
|
self._config = config
|
||||||
|
self._connect_fn = connect_fn
|
||||||
|
self._capture_client = capture_client
|
||||||
|
self._wol_fn = wol_fn
|
||||||
|
self._wait_fn = wait_fn
|
||||||
|
self._backoff_steps = backoff_steps
|
||||||
|
self._wake_poll_interval = wake_poll_interval
|
||||||
|
self._wake_timeout = wake_timeout
|
||||||
|
self._ui_lock_timeout = ui_lock_timeout
|
||||||
|
|
||||||
|
self.state = ConnectionState.CONNECTING
|
||||||
|
self._tv_state = TvState()
|
||||||
|
self._ui_lock = asyncio.Lock()
|
||||||
|
self._client_key: str | None = None
|
||||||
|
|
||||||
|
self._ssap: SsapClient | None = None
|
||||||
|
self._pointer: PointerClient | None = None
|
||||||
|
self._loop_task: asyncio.Task[None] | None = None
|
||||||
|
self._wake_task: asyncio.Task[TvStatus] | None = None
|
||||||
|
self._stopping = False
|
||||||
|
|
||||||
|
self._wake_or_reload_event = asyncio.Event()
|
||||||
|
self._disconnected_event = asyncio.Event()
|
||||||
|
self._connected_event = asyncio.Event()
|
||||||
|
self._wake_done_event = asyncio.Event()
|
||||||
|
self._disconnect_code = ErrorCode.TV_OFFLINE_STANDBY
|
||||||
|
self._wake_requested = False
|
||||||
|
self._reload_requested = False
|
||||||
|
self._wake_failure: TvError | None = None
|
||||||
|
|
||||||
|
async def start(self) -> None:
|
||||||
|
"""Start the background connection state machine loop."""
|
||||||
|
if self._loop_task is None or self._loop_task.done():
|
||||||
|
self._stopping = False
|
||||||
|
self._loop_task = asyncio.create_task(self._connection_loop())
|
||||||
|
|
||||||
|
async def close(self) -> None:
|
||||||
|
"""Stop the connection loop and close all underlying transports."""
|
||||||
|
self._stopping = True
|
||||||
|
self._wake_or_reload_event.set()
|
||||||
|
self._disconnected_event.set()
|
||||||
|
|
||||||
|
if self._wake_task is not None and not self._wake_task.done():
|
||||||
|
self._wake_task.cancel()
|
||||||
|
with suppress(asyncio.CancelledError):
|
||||||
|
await self._wake_task
|
||||||
|
|
||||||
|
if self._loop_task is not None and not self._loop_task.done():
|
||||||
|
self._loop_task.cancel()
|
||||||
|
with suppress(asyncio.CancelledError):
|
||||||
|
await self._loop_task
|
||||||
|
self._loop_task = None
|
||||||
|
|
||||||
|
await self._teardown_transports(close_capture=True)
|
||||||
|
|
||||||
|
def reload_client_key(self) -> None:
|
||||||
|
"""Reload the saved client key from disk (e.g. on SIGHUP)."""
|
||||||
|
loaded = self._try_load_client_key()
|
||||||
|
if loaded is not None:
|
||||||
|
self._client_key = loaded
|
||||||
|
self._reload_requested = True
|
||||||
|
if self.state is ConnectionState.PAIRING_REQUIRED:
|
||||||
|
self._wake_or_reload_event.set()
|
||||||
|
|
||||||
|
async def wake(self) -> TvStatus:
|
||||||
|
"""Send a Wake-on-LAN packet and wait for the TV to register."""
|
||||||
|
if self.state is ConnectionState.CONNECTED:
|
||||||
|
return TvStatus(status="already_connected", elapsed_ms=0)
|
||||||
|
if self.state is ConnectionState.PAIRING_REQUIRED:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.PAIRING_REQUIRED,
|
||||||
|
"TV requires pairing before wake; run pair CLI first",
|
||||||
|
)
|
||||||
|
|
||||||
|
if self._wake_task is None or self._wake_task.done():
|
||||||
|
self._wake_task = asyncio.create_task(self._run_wake())
|
||||||
|
return await asyncio.shield(self._wake_task)
|
||||||
|
|
||||||
|
def get_state(self) -> TvStateSnapshot:
|
||||||
|
"""Return a lock-free snapshot of the cached TV state."""
|
||||||
|
connected = self.state is ConnectionState.CONNECTED
|
||||||
|
return TvStateSnapshot(
|
||||||
|
connected=connected,
|
||||||
|
stale=not connected,
|
||||||
|
volume=self._tv_state.volume,
|
||||||
|
muted=self._tv_state.muted,
|
||||||
|
sound_output=self._tv_state.sound_output,
|
||||||
|
foreground_app=self._tv_state.foreground_app,
|
||||||
|
last_updated=self._tv_state.last_updated,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def _run_wake(self) -> TvStatus:
|
||||||
|
mac = require_mac(self._config)
|
||||||
|
start = time.monotonic()
|
||||||
|
self._wol_fn(mac, self._config.wol_broadcast, 9)
|
||||||
|
|
||||||
|
self._wake_failure = None
|
||||||
|
self._connected_event.clear()
|
||||||
|
self._wake_done_event.clear()
|
||||||
|
self._wake_requested = True
|
||||||
|
self._wake_or_reload_event.set()
|
||||||
|
|
||||||
|
if self.state is ConnectionState.CONNECTED:
|
||||||
|
self._wake_requested = False
|
||||||
|
return TvStatus(status="already_connected", elapsed_ms=0)
|
||||||
|
|
||||||
|
wait_connected = asyncio.create_task(self._connected_event.wait())
|
||||||
|
wait_failed = asyncio.create_task(self._wake_done_event.wait())
|
||||||
|
try:
|
||||||
|
async with asyncio.timeout(self._wake_timeout):
|
||||||
|
done, _ = await asyncio.wait(
|
||||||
|
{wait_connected, wait_failed},
|
||||||
|
return_when=asyncio.FIRST_COMPLETED,
|
||||||
|
)
|
||||||
|
if wait_failed in done and self._wake_failure is not None:
|
||||||
|
raise self._wake_failure
|
||||||
|
except TimeoutError as exc:
|
||||||
|
if self.state is ConnectionState.WAKING:
|
||||||
|
self.state = ConnectionState.STANDBY_OFFLINE
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.WAKE_TIMEOUT,
|
||||||
|
f"TV did not become ready within {self._wake_timeout:.0f}s",
|
||||||
|
) from exc
|
||||||
|
finally:
|
||||||
|
self._wake_requested = False
|
||||||
|
for task in (wait_connected, wait_failed):
|
||||||
|
if not task.done():
|
||||||
|
task.cancel()
|
||||||
|
with suppress(asyncio.CancelledError):
|
||||||
|
await task
|
||||||
|
|
||||||
|
elapsed_ms = int((time.monotonic() - start) * 1000)
|
||||||
|
return TvStatus(status="connected", elapsed_ms=elapsed_ms)
|
||||||
|
|
||||||
|
async def _connection_loop(self) -> None:
|
||||||
|
backoff_idx = 0
|
||||||
|
while not self._stopping:
|
||||||
|
if self._wake_requested:
|
||||||
|
self.state = ConnectionState.WAKING
|
||||||
|
elif self.state not in (ConnectionState.CONNECTING, ConnectionState.WAKING):
|
||||||
|
self.state = ConnectionState.CONNECTING
|
||||||
|
|
||||||
|
try:
|
||||||
|
await self._connect_and_subscribe()
|
||||||
|
except TvError as exc:
|
||||||
|
await self._teardown_transports(
|
||||||
|
close_capture=exc.code is not ErrorCode.PAIRING_REQUIRED
|
||||||
|
)
|
||||||
|
if exc.code is ErrorCode.PAIRING_REQUIRED:
|
||||||
|
self.state = ConnectionState.PAIRING_REQUIRED
|
||||||
|
self._wake_requested = False
|
||||||
|
self._wake_failure = exc
|
||||||
|
self._wake_done_event.set()
|
||||||
|
backoff_idx = await self._wait_backoff(backoff_idx)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if self._wake_requested:
|
||||||
|
self.state = ConnectionState.WAKING
|
||||||
|
await asyncio.sleep(self._wake_poll_interval)
|
||||||
|
continue
|
||||||
|
|
||||||
|
self.state = ConnectionState.STANDBY_OFFLINE
|
||||||
|
backoff_idx = await self._wait_backoff(backoff_idx)
|
||||||
|
continue
|
||||||
|
|
||||||
|
backoff_idx = 0
|
||||||
|
self.state = ConnectionState.CONNECTED
|
||||||
|
self._disconnected_event.clear()
|
||||||
|
self._connected_event.set()
|
||||||
|
|
||||||
|
await self._disconnected_event.wait()
|
||||||
|
if self._stopping:
|
||||||
|
break
|
||||||
|
|
||||||
|
is_pairing = self._disconnect_code is ErrorCode.PAIRING_REQUIRED
|
||||||
|
await self._teardown_transports(close_capture=not is_pairing)
|
||||||
|
if is_pairing:
|
||||||
|
self._wake_requested = False
|
||||||
|
self.state = (
|
||||||
|
ConnectionState.PAIRING_REQUIRED if is_pairing else ConnectionState.STANDBY_OFFLINE
|
||||||
|
)
|
||||||
|
backoff_idx = await self._wait_backoff(backoff_idx)
|
||||||
|
|
||||||
|
async def _wait_backoff(self, backoff_idx: int) -> int:
|
||||||
|
current_idx = backoff_idx
|
||||||
|
while not self._stopping:
|
||||||
|
if self._wake_requested:
|
||||||
|
return 0
|
||||||
|
if self.state is ConnectionState.PAIRING_REQUIRED and self._reload_requested:
|
||||||
|
self._reload_requested = False
|
||||||
|
return current_idx
|
||||||
|
|
||||||
|
delay = self._backoff_steps[min(current_idx, len(self._backoff_steps) - 1)]
|
||||||
|
next_idx = min(current_idx + 1, len(self._backoff_steps) - 1)
|
||||||
|
self._wake_or_reload_event.clear()
|
||||||
|
|
||||||
|
# Re-check after clearing the event so concurrent wake/reload signals are not lost.
|
||||||
|
if self._wake_requested:
|
||||||
|
return 0
|
||||||
|
if self.state is ConnectionState.PAIRING_REQUIRED and self._reload_requested:
|
||||||
|
self._reload_requested = False
|
||||||
|
return current_idx
|
||||||
|
|
||||||
|
await self._wait_fn(self._wake_or_reload_event, delay)
|
||||||
|
|
||||||
|
if self.state is ConnectionState.PAIRING_REQUIRED and not self._wake_requested:
|
||||||
|
self._reload_requested = False
|
||||||
|
reloaded = self._try_load_client_key()
|
||||||
|
if reloaded is not None:
|
||||||
|
self._client_key = reloaded
|
||||||
|
return next_idx
|
||||||
|
current_idx = next_idx
|
||||||
|
continue
|
||||||
|
return next_idx
|
||||||
|
return current_idx
|
||||||
|
|
||||||
|
async def _connect_and_subscribe(self) -> None:
|
||||||
|
if self._client_key is None:
|
||||||
|
self._client_key = self._try_load_client_key()
|
||||||
|
|
||||||
|
ssap = SsapClient(
|
||||||
|
f"wss://{self._config.tv_ip}:3001",
|
||||||
|
connect_fn=self._connect_fn,
|
||||||
|
on_disconnect=self._on_ssap_disconnect,
|
||||||
|
)
|
||||||
|
self._ssap = ssap
|
||||||
|
resolved_key = await ssap.connect_and_register(self._client_key)
|
||||||
|
if resolved_key:
|
||||||
|
self._client_key = resolved_key
|
||||||
|
|
||||||
|
await ssap.subscribe("ssap://audio/getStatus", self._handle_audio_status)
|
||||||
|
await ssap.subscribe(
|
||||||
|
"ssap://com.webos.applicationManager/getForegroundAppInfo",
|
||||||
|
self._handle_foreground_app,
|
||||||
|
)
|
||||||
|
self._pointer = PointerClient(ssap.request, connect_fn=self._connect_fn)
|
||||||
|
|
||||||
|
async def _teardown_transports(self, *, close_capture: bool) -> None:
|
||||||
|
pointer = self._pointer
|
||||||
|
self._pointer = None
|
||||||
|
if pointer is not None:
|
||||||
|
await pointer.close()
|
||||||
|
|
||||||
|
ssap = self._ssap
|
||||||
|
self._ssap = None
|
||||||
|
if ssap is not None:
|
||||||
|
await ssap.close()
|
||||||
|
|
||||||
|
if close_capture and self._capture_client is not None:
|
||||||
|
with suppress(Exception):
|
||||||
|
await self._capture_client.close()
|
||||||
|
|
||||||
|
def _on_ssap_disconnect(self, code: ErrorCode) -> None:
|
||||||
|
self._disconnect_code = code
|
||||||
|
self._disconnected_event.set()
|
||||||
|
|
||||||
|
def _try_load_client_key(self) -> str | None:
|
||||||
|
key_path = self._config.client_key_path
|
||||||
|
if not key_path.is_file():
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
raw: Any = json.loads(key_path.read_text(encoding="utf-8"))
|
||||||
|
except (OSError, json.JSONDecodeError) as exc:
|
||||||
|
logger.warning("Failed to read client key file %s: %s", key_path, exc)
|
||||||
|
return None
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
logger.warning("Client key file %s does not contain a JSON object", key_path)
|
||||||
|
return None
|
||||||
|
mapping = cast(dict[str, Any], raw)
|
||||||
|
val = mapping.get(self._config.tv_ip)
|
||||||
|
if isinstance(val, str) and val.strip():
|
||||||
|
return val.strip()
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _handle_audio_status(self, payload: dict[str, Any]) -> None:
|
||||||
|
volume = payload.get("volume")
|
||||||
|
if isinstance(volume, int) and not isinstance(volume, bool):
|
||||||
|
self._tv_state.volume = volume
|
||||||
|
|
||||||
|
mute = payload.get("mute")
|
||||||
|
if isinstance(mute, bool):
|
||||||
|
self._tv_state.muted = mute
|
||||||
|
|
||||||
|
volume_status = payload.get("volumeStatus")
|
||||||
|
if isinstance(volume_status, dict):
|
||||||
|
vs_dict = cast(dict[str, Any], volume_status)
|
||||||
|
sound_output = vs_dict.get("soundOutput")
|
||||||
|
if isinstance(sound_output, str):
|
||||||
|
self._tv_state.sound_output = sound_output
|
||||||
|
elif isinstance(payload.get("soundOutput"), str):
|
||||||
|
self._tv_state.sound_output = str(payload["soundOutput"])
|
||||||
|
|
||||||
|
self._tv_state.last_updated = time.time()
|
||||||
|
|
||||||
|
def _handle_foreground_app(self, payload: dict[str, Any]) -> None:
|
||||||
|
app_id = payload.get("appId")
|
||||||
|
if isinstance(app_id, str):
|
||||||
|
self._tv_state.foreground_app = app_id
|
||||||
|
self._tv_state.last_updated = time.time()
|
||||||
|
|
||||||
|
def _require_ssap(self) -> SsapClient:
|
||||||
|
if self.state is ConnectionState.PAIRING_REQUIRED:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.PAIRING_REQUIRED,
|
||||||
|
"TV requires pairing; run pair CLI and reload client key",
|
||||||
|
)
|
||||||
|
if self.state is not ConnectionState.CONNECTED or self._ssap is None:
|
||||||
|
raise TvError(ErrorCode.TV_OFFLINE_STANDBY, "TV is offline or in standby")
|
||||||
|
return self._ssap
|
||||||
|
|
||||||
|
def _require_pointer(self) -> PointerClient:
|
||||||
|
self._require_ssap()
|
||||||
|
if self._pointer is None:
|
||||||
|
raise TvError(ErrorCode.TV_OFFLINE_STANDBY, "Pointer client is not connected")
|
||||||
|
return self._pointer
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def _acquire_ui_lock(self) -> AsyncGenerator[None]:
|
||||||
|
try:
|
||||||
|
await asyncio.wait_for(self._ui_lock.acquire(), timeout=self._ui_lock_timeout)
|
||||||
|
except TimeoutError as exc:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.LOCK_TIMEOUT,
|
||||||
|
f"Timed out waiting {self._ui_lock_timeout:.0f}s for UI lock",
|
||||||
|
) from exc
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
self._ui_lock.release()
|
||||||
|
|
||||||
|
async def _capture_optional(self, ssap: SsapClient) -> tuple[CaptureResult | None, str | None]:
|
||||||
|
if self._capture_client is None:
|
||||||
|
return None, "SCREENSHOT_UNAVAILABLE: Developer Mode SSH is not configured"
|
||||||
|
try:
|
||||||
|
return await self._capture_client.capture_frame(ssap.request), None
|
||||||
|
except TvError as exc:
|
||||||
|
if exc.code is ErrorCode.SCREENSHOT_UNAVAILABLE:
|
||||||
|
return None, str(exc)
|
||||||
|
raise
|
||||||
|
|
||||||
|
async def send_keys(
|
||||||
|
self,
|
||||||
|
keys: list[str],
|
||||||
|
delay_ms: int = 250,
|
||||||
|
settle_ms: int = 800,
|
||||||
|
capture: bool = False,
|
||||||
|
) -> KeysResult:
|
||||||
|
"""Validate, serialize, and send pointer button keys with optional capture."""
|
||||||
|
if not (1 <= len(keys) <= 20):
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.INVALID_ARGUMENT,
|
||||||
|
f"keys must contain between 1 and 20 items, got {len(keys)}",
|
||||||
|
)
|
||||||
|
if not (0 <= delay_ms <= 500):
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.INVALID_ARGUMENT,
|
||||||
|
f"delay_ms must be between 0 and 500, got {delay_ms}",
|
||||||
|
)
|
||||||
|
if not (0 <= settle_ms <= 2000):
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.INVALID_ARGUMENT,
|
||||||
|
f"settle_ms must be between 0 and 2000, got {settle_ms}",
|
||||||
|
)
|
||||||
|
normalize_button_keys(keys)
|
||||||
|
|
||||||
|
ssap = self._require_ssap()
|
||||||
|
pointer = self._require_pointer()
|
||||||
|
|
||||||
|
async with self._acquire_ui_lock():
|
||||||
|
count = await pointer.send_buttons(keys, delay_ms=delay_ms)
|
||||||
|
if not capture:
|
||||||
|
return KeysResult(keys_sent=True, count=count)
|
||||||
|
if settle_ms > 0:
|
||||||
|
await asyncio.sleep(settle_ms / 1000.0)
|
||||||
|
cap, cap_err = await self._capture_optional(ssap)
|
||||||
|
return KeysResult(
|
||||||
|
keys_sent=True,
|
||||||
|
count=count,
|
||||||
|
frame_sha256=cap.frame_sha256 if cap is not None else None,
|
||||||
|
changed_since_last=cap.changed_since_last if cap is not None else None,
|
||||||
|
size_bytes=cap.size_bytes if cap is not None else None,
|
||||||
|
capture_error=cap_err,
|
||||||
|
image_bytes=cap.image_bytes if cap is not None else None,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def type_text(
|
||||||
|
self,
|
||||||
|
text: str,
|
||||||
|
send_enter: bool = True,
|
||||||
|
capture: bool = False,
|
||||||
|
) -> TextResult:
|
||||||
|
"""Send IME text input with optional enter key and screenshot capture."""
|
||||||
|
if not (1 <= len(text) <= 500):
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.INVALID_ARGUMENT,
|
||||||
|
f"text length must be between 1 and 500 characters, got {len(text)}",
|
||||||
|
)
|
||||||
|
ssap = self._require_ssap()
|
||||||
|
async with self._acquire_ui_lock():
|
||||||
|
await ssap.request(
|
||||||
|
"ssap://com.webos.service.ime/insertText",
|
||||||
|
{"text": text, "replace": 0},
|
||||||
|
)
|
||||||
|
if send_enter:
|
||||||
|
await ssap.request("ssap://com.webos.service.ime/sendEnterKey", {})
|
||||||
|
if not capture:
|
||||||
|
return TextResult(text_sent=True, enter_sent=send_enter)
|
||||||
|
cap, cap_err = await self._capture_optional(ssap)
|
||||||
|
return TextResult(
|
||||||
|
text_sent=True,
|
||||||
|
enter_sent=send_enter,
|
||||||
|
frame_sha256=cap.frame_sha256 if cap is not None else None,
|
||||||
|
changed_since_last=cap.changed_since_last if cap is not None else None,
|
||||||
|
size_bytes=cap.size_bytes if cap is not None else None,
|
||||||
|
capture_error=cap_err,
|
||||||
|
image_bytes=cap.image_bytes if cap is not None else None,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def screenshot(self) -> CaptureResult:
|
||||||
|
"""Acquire ui_lock and capture a screenshot via Developer Mode SFTP."""
|
||||||
|
ssap = self._require_ssap()
|
||||||
|
async with self._acquire_ui_lock():
|
||||||
|
if self._capture_client is None:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.SCREENSHOT_UNAVAILABLE,
|
||||||
|
"Developer Mode SSH is not configured",
|
||||||
|
)
|
||||||
|
return await self._capture_client.capture_frame(ssap.request)
|
||||||
|
|
||||||
|
async def launch_app(
|
||||||
|
self,
|
||||||
|
app_id: str,
|
||||||
|
content_target: str | None = None,
|
||||||
|
params: dict[str, Any] | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Launch an installed webOS app with optional deep-link parameters."""
|
||||||
|
ssap = self._require_ssap()
|
||||||
|
merged_params = dict(params or {})
|
||||||
|
if content_target is not None:
|
||||||
|
merged_params["contentTarget"] = content_target
|
||||||
|
payload: dict[str, Any] = {"id": app_id}
|
||||||
|
if merged_params:
|
||||||
|
payload["params"] = merged_params
|
||||||
|
return await ssap.request("ssap://system.launcher/launch", payload)
|
||||||
|
|
||||||
|
async def list_apps(self) -> list[dict[str, str]]:
|
||||||
|
"""Return installed launch points as [{id, title}]."""
|
||||||
|
ssap = self._require_ssap()
|
||||||
|
resp = await ssap.request("ssap://com.webos.applicationManager/listLaunchPoints", {})
|
||||||
|
raw_points = resp.get("launchPoints", [])
|
||||||
|
if not isinstance(raw_points, list):
|
||||||
|
return []
|
||||||
|
apps: list[dict[str, str]] = []
|
||||||
|
for item_raw in cast(list[Any], raw_points):
|
||||||
|
if isinstance(item_raw, dict):
|
||||||
|
item = cast(dict[str, Any], item_raw)
|
||||||
|
apps.append({"id": str(item.get("id", "")), "title": str(item.get("title", ""))})
|
||||||
|
return apps
|
||||||
|
|
||||||
|
async def set_volume(self, level: int) -> dict[str, Any]:
|
||||||
|
"""Set TV volume within [0, config.max_volume]."""
|
||||||
|
if level < 0 or level > self._config.max_volume:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.INVALID_ARGUMENT,
|
||||||
|
f"Volume {level} must be between 0 and {self._config.max_volume}",
|
||||||
|
)
|
||||||
|
ssap = self._require_ssap()
|
||||||
|
return await ssap.request("ssap://audio/setVolume", {"volume": level})
|
||||||
|
|
||||||
|
async def set_mute(self, muted: bool) -> dict[str, Any]:
|
||||||
|
"""Set TV mute state."""
|
||||||
|
ssap = self._require_ssap()
|
||||||
|
return await ssap.request("ssap://audio/setMute", {"mute": muted})
|
||||||
|
|
||||||
|
async def list_inputs(self) -> list[dict[str, Any]]:
|
||||||
|
"""Return external inputs as [{id, label, connected}]."""
|
||||||
|
ssap = self._require_ssap()
|
||||||
|
resp = await ssap.request("ssap://tv/getExternalInputList", {})
|
||||||
|
raw_devices = resp.get("devices", [])
|
||||||
|
if not isinstance(raw_devices, list):
|
||||||
|
return []
|
||||||
|
inputs: list[dict[str, Any]] = []
|
||||||
|
for item_raw in cast(list[Any], raw_devices):
|
||||||
|
if isinstance(item_raw, dict):
|
||||||
|
item = cast(dict[str, Any], item_raw)
|
||||||
|
inputs.append(
|
||||||
|
{
|
||||||
|
"id": str(item.get("id", "")),
|
||||||
|
"label": str(item.get("label", "")),
|
||||||
|
"connected": bool(item.get("connected", False)),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return inputs
|
||||||
|
|
||||||
|
async def switch_input(self, input_id: str) -> dict[str, Any]:
|
||||||
|
"""Switch active external input."""
|
||||||
|
ssap = self._require_ssap()
|
||||||
|
return await ssap.request("ssap://tv/switchInput", {"inputId": input_id})
|
||||||
|
|
||||||
|
async def turn_off(self) -> dict[str, Any]:
|
||||||
|
"""Power off the TV into standby."""
|
||||||
|
ssap = self._require_ssap()
|
||||||
|
return await ssap.request("ssap://system/turnOff", {})
|
||||||
|
|
||||||
|
async def raw_ssap(self, uri: str, payload: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||||
|
"""Forward a raw SSAP request when enabled by configuration."""
|
||||||
|
if not self._config.enable_raw_ssap:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.INVALID_ARGUMENT,
|
||||||
|
"raw_ssap is disabled (ENABLE_RAW_SSAP=false)",
|
||||||
|
)
|
||||||
|
ssap = self._require_ssap()
|
||||||
|
return await ssap.request(uri, payload)
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
"""Pointer input WebSocket client for LG webOS D-pad and remote buttons."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
from collections.abc import Awaitable, Callable
|
||||||
|
from contextlib import suppress
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from lg_smtv_mcp.errors import ErrorCode, TvError
|
||||||
|
from lg_smtv_mcp.tv_core.protocols import (
|
||||||
|
WebSocketClosedError,
|
||||||
|
WebSocketConnectFn,
|
||||||
|
WebSocketTransport,
|
||||||
|
)
|
||||||
|
from lg_smtv_mcp.tv_core.ssap import websockets_connect
|
||||||
|
|
||||||
|
BUTTON_ALLOWLIST: frozenset[str] = frozenset(
|
||||||
|
{
|
||||||
|
"UP",
|
||||||
|
"DOWN",
|
||||||
|
"LEFT",
|
||||||
|
"RIGHT",
|
||||||
|
"ENTER",
|
||||||
|
"BACK",
|
||||||
|
"HOME",
|
||||||
|
"EXIT",
|
||||||
|
"PLAY",
|
||||||
|
"PAUSE",
|
||||||
|
"STOP",
|
||||||
|
"REWIND",
|
||||||
|
"FASTFORWARD",
|
||||||
|
"RED",
|
||||||
|
"GREEN",
|
||||||
|
"YELLOW",
|
||||||
|
"BLUE",
|
||||||
|
"VOLUMEUP",
|
||||||
|
"VOLUMEDOWN",
|
||||||
|
"MUTE",
|
||||||
|
"CHANNELUP",
|
||||||
|
"CHANNELDOWN",
|
||||||
|
"INFO",
|
||||||
|
"GUIDE",
|
||||||
|
"MENU",
|
||||||
|
"CC",
|
||||||
|
"0",
|
||||||
|
"1",
|
||||||
|
"2",
|
||||||
|
"3",
|
||||||
|
"4",
|
||||||
|
"5",
|
||||||
|
"6",
|
||||||
|
"7",
|
||||||
|
"8",
|
||||||
|
"9",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_button_keys(keys: list[str]) -> list[str]:
|
||||||
|
"""Validate and normalize a sequence of webOS button names."""
|
||||||
|
normalized: list[str] = []
|
||||||
|
for raw_key in keys:
|
||||||
|
if "\r" in raw_key or "\n" in raw_key:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.INVALID_ARGUMENT,
|
||||||
|
f"Button name must not contain newline characters: {raw_key!r}",
|
||||||
|
)
|
||||||
|
candidate = raw_key.strip().upper()
|
||||||
|
if candidate not in BUTTON_ALLOWLIST:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.INVALID_ARGUMENT,
|
||||||
|
f"Unsupported webOS button name: {raw_key!r}",
|
||||||
|
)
|
||||||
|
normalized.append(candidate)
|
||||||
|
return normalized
|
||||||
|
|
||||||
|
|
||||||
|
class PointerClient:
|
||||||
|
"""Manages the persistent webOS pointer input socket and button frame formatting."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
ssap_request_fn: Callable[[str, dict[str, Any]], Awaitable[dict[str, Any]]],
|
||||||
|
connect_fn: WebSocketConnectFn = websockets_connect,
|
||||||
|
sleep_fn: Callable[[float], Awaitable[None]] = asyncio.sleep,
|
||||||
|
) -> None:
|
||||||
|
self._ssap_request_fn = ssap_request_fn
|
||||||
|
self._connect_fn = connect_fn
|
||||||
|
self._sleep_fn = sleep_fn
|
||||||
|
self._ws: WebSocketTransport | None = None
|
||||||
|
|
||||||
|
async def _ensure_socket(self) -> WebSocketTransport:
|
||||||
|
if self._ws is not None:
|
||||||
|
return self._ws
|
||||||
|
resp = await self._ssap_request_fn(
|
||||||
|
"ssap://com.webos.service.networkinput/getPointerInputSocket",
|
||||||
|
{},
|
||||||
|
)
|
||||||
|
socket_path = resp.get("socketPath")
|
||||||
|
if not isinstance(socket_path, str) or not socket_path:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.COMMAND_FAILED,
|
||||||
|
"getPointerInputSocket did not return a valid socketPath",
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
self._ws = await self._connect_fn(socket_path)
|
||||||
|
except (TimeoutError, OSError, WebSocketClosedError) as exc:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.TV_OFFLINE_STANDBY,
|
||||||
|
f"Failed to connect pointer input socket: {exc}",
|
||||||
|
) from exc
|
||||||
|
return self._ws
|
||||||
|
|
||||||
|
async def send_buttons(self, keys: list[str], delay_ms: int = 250) -> int:
|
||||||
|
"""Validate, normalize, and send a sequence of button frames."""
|
||||||
|
normalized = normalize_button_keys(keys)
|
||||||
|
for index, key in enumerate(normalized):
|
||||||
|
frame = f"type:button\nname:{key}\n\n"
|
||||||
|
await self._send_frame_with_retry(frame)
|
||||||
|
if delay_ms > 0 and index < len(normalized) - 1:
|
||||||
|
await self._sleep_fn(delay_ms / 1000.0)
|
||||||
|
return len(normalized)
|
||||||
|
|
||||||
|
async def _send_frame_with_retry(self, frame: str) -> None:
|
||||||
|
ws = await self._ensure_socket()
|
||||||
|
try:
|
||||||
|
await ws.send(frame)
|
||||||
|
return
|
||||||
|
except WebSocketClosedError, OSError:
|
||||||
|
await self.close()
|
||||||
|
|
||||||
|
ws = await self._ensure_socket()
|
||||||
|
try:
|
||||||
|
await ws.send(frame)
|
||||||
|
except (WebSocketClosedError, OSError) as exc:
|
||||||
|
await self.close()
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.TV_OFFLINE_STANDBY,
|
||||||
|
f"Pointer input socket failed after retry: {exc}",
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
async def close(self) -> None:
|
||||||
|
"""Close the pointer WebSocket transport if open."""
|
||||||
|
ws = self._ws
|
||||||
|
self._ws = None
|
||||||
|
if ws is not None:
|
||||||
|
with suppress(Exception):
|
||||||
|
await ws.close()
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
"""Transport protocols, connection exceptions, and frozen result containers."""
|
||||||
|
|
||||||
|
from collections.abc import Awaitable, Callable
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Any, Literal, Protocol
|
||||||
|
|
||||||
|
|
||||||
|
class WebSocketClosedError(Exception):
|
||||||
|
"""Raised when a WebSocket transport closes unexpectedly or is already closed."""
|
||||||
|
|
||||||
|
def __init__(self, code: int, reason: str = "") -> None:
|
||||||
|
message = f"WebSocket closed ({code}): {reason}" if reason else f"WebSocket closed ({code})"
|
||||||
|
super().__init__(message)
|
||||||
|
self.code = code
|
||||||
|
self.reason = reason
|
||||||
|
|
||||||
|
|
||||||
|
class WebSocketTransport(Protocol):
|
||||||
|
"""Minimal async WebSocket transport boundary for SSAP and pointer sockets."""
|
||||||
|
|
||||||
|
async def send(self, data: str) -> None: ...
|
||||||
|
|
||||||
|
async def recv(self) -> str: ...
|
||||||
|
|
||||||
|
async def close(self) -> None: ...
|
||||||
|
|
||||||
|
|
||||||
|
type WebSocketConnectFn = Callable[[str], Awaitable[WebSocketTransport]]
|
||||||
|
|
||||||
|
|
||||||
|
class CaptureTransport(Protocol):
|
||||||
|
"""Minimal async SFTP transport boundary for Developer Mode screenshot retrieval."""
|
||||||
|
|
||||||
|
async def read_and_remove(
|
||||||
|
self,
|
||||||
|
remote_path: str,
|
||||||
|
timeout: float = 6.0,
|
||||||
|
cleanup_grace: float = 1.5,
|
||||||
|
) -> bytes: ...
|
||||||
|
|
||||||
|
async def sweep_temp_files(
|
||||||
|
self,
|
||||||
|
prefix: str = "/tmp/lg_smtv_cap_",
|
||||||
|
exclude: str | None = None,
|
||||||
|
) -> None: ...
|
||||||
|
|
||||||
|
async def close(self) -> None: ...
|
||||||
|
|
||||||
|
|
||||||
|
class FrameCapturer(Protocol):
|
||||||
|
"""Protocol for capturing screenshots via SSAP + SFTP."""
|
||||||
|
|
||||||
|
async def capture_frame(
|
||||||
|
self,
|
||||||
|
ssap_request_fn: Callable[[str, dict[str, Any]], Awaitable[dict[str, Any]]],
|
||||||
|
) -> CaptureResult: ...
|
||||||
|
|
||||||
|
async def close(self) -> None: ...
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class TvStatus:
|
||||||
|
"""Result of a tv_wake operation."""
|
||||||
|
|
||||||
|
status: Literal["connected", "already_connected"]
|
||||||
|
elapsed_ms: int
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class TvStateSnapshot:
|
||||||
|
"""Point-in-time read-only snapshot of cached TV state."""
|
||||||
|
|
||||||
|
connected: bool
|
||||||
|
stale: bool
|
||||||
|
volume: int | None
|
||||||
|
muted: bool | None
|
||||||
|
sound_output: str | None
|
||||||
|
foreground_app: str | None
|
||||||
|
last_updated: float | None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class CaptureResult:
|
||||||
|
"""Result of a screenshot capture operation."""
|
||||||
|
|
||||||
|
image_bytes: bytes
|
||||||
|
frame_sha256: str
|
||||||
|
changed_since_last: bool
|
||||||
|
size_bytes: int
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class KeysResult:
|
||||||
|
"""Result of a batched pointer key sequence."""
|
||||||
|
|
||||||
|
keys_sent: bool
|
||||||
|
count: int
|
||||||
|
frame_sha256: str | None = None
|
||||||
|
changed_since_last: bool | None = None
|
||||||
|
size_bytes: int | None = None
|
||||||
|
capture_error: str | None = None
|
||||||
|
image_bytes: bytes | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class TextResult:
|
||||||
|
"""Result of an IME text-entry operation."""
|
||||||
|
|
||||||
|
text_sent: bool
|
||||||
|
enter_sent: bool
|
||||||
|
frame_sha256: str | None = None
|
||||||
|
changed_since_last: bool | None = None
|
||||||
|
size_bytes: int | None = None
|
||||||
|
capture_error: str | None = None
|
||||||
|
image_bytes: bytes | None = None
|
||||||
@@ -0,0 +1,369 @@
|
|||||||
|
"""SSAP WebSocket client and msg['id'] frame multiplexer."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import inspect
|
||||||
|
import json
|
||||||
|
import ssl
|
||||||
|
from collections.abc import Awaitable, Callable
|
||||||
|
from contextlib import suppress
|
||||||
|
from typing import Any, cast
|
||||||
|
|
||||||
|
import websockets
|
||||||
|
from websockets.asyncio.client import ClientConnection
|
||||||
|
from websockets.exceptions import ConnectionClosed
|
||||||
|
|
||||||
|
from lg_smtv_mcp.errors import ErrorCode, TvError
|
||||||
|
from lg_smtv_mcp.tv_core.protocols import (
|
||||||
|
WebSocketClosedError,
|
||||||
|
WebSocketConnectFn,
|
||||||
|
WebSocketTransport,
|
||||||
|
)
|
||||||
|
|
||||||
|
PERMISSIONS: tuple[str, ...] = (
|
||||||
|
"LAUNCH",
|
||||||
|
"CONTROL_AUDIO",
|
||||||
|
"CONTROL_DISPLAY",
|
||||||
|
"CONTROL_POWER",
|
||||||
|
"CONTROL_INPUT_TEXT",
|
||||||
|
"CONTROL_INPUT_MEDIA_PLAYBACK",
|
||||||
|
"CONTROL_INPUT_JOYSTICK",
|
||||||
|
"CONTROL_INPUT_TV",
|
||||||
|
"CONTROL_TV_MEDIA",
|
||||||
|
"CONTROL_MOUSE_AND_KEYBOARD",
|
||||||
|
"READ_INSTALLED_APPS",
|
||||||
|
"READ_RUNNING_APPS",
|
||||||
|
"READ_INPUT_DEVICE_LIST",
|
||||||
|
"READ_TV_CHANNEL_LIST",
|
||||||
|
"READ_POWER_STATE",
|
||||||
|
"WRITE_NOTIFICATION_TOAST",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def build_ssl_context() -> ssl.SSLContext:
|
||||||
|
"""Create an SSL context accepting the TV's self-signed WSS certificate."""
|
||||||
|
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||||
|
ctx.check_hostname = False
|
||||||
|
ctx.verify_mode = ssl.CERT_NONE
|
||||||
|
return ctx
|
||||||
|
|
||||||
|
|
||||||
|
def build_register_payload(
|
||||||
|
client_key: str | None,
|
||||||
|
*,
|
||||||
|
force_pairing: bool = False,
|
||||||
|
msg_id: str = "register_0",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Build the SSAP register handshake payload with all required permissions."""
|
||||||
|
payload: dict[str, Any] = {
|
||||||
|
"forcePairing": force_pairing,
|
||||||
|
"pairingType": "PROMPT",
|
||||||
|
"manifest": {
|
||||||
|
"manifestVersion": 1,
|
||||||
|
"appVersion": "0.1.0",
|
||||||
|
"permissions": list(PERMISSIONS),
|
||||||
|
"localizedAppNames": {"": "lg-smtv-mcp"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if client_key and not force_pairing:
|
||||||
|
payload["client-key"] = client_key
|
||||||
|
return {"type": "register", "id": msg_id, "payload": payload}
|
||||||
|
|
||||||
|
|
||||||
|
def _to_closed_error(exc: ConnectionClosed) -> WebSocketClosedError:
|
||||||
|
if exc.rcvd is not None:
|
||||||
|
return WebSocketClosedError(exc.rcvd.code, exc.rcvd.reason)
|
||||||
|
return WebSocketClosedError(1006, str(exc))
|
||||||
|
|
||||||
|
|
||||||
|
class _WebsocketsAdapter:
|
||||||
|
"""Adapt websockets.asyncio.client.ClientConnection to WebSocketTransport."""
|
||||||
|
|
||||||
|
def __init__(self, conn: ClientConnection) -> None:
|
||||||
|
self._conn = conn
|
||||||
|
|
||||||
|
async def send(self, data: str) -> None:
|
||||||
|
try:
|
||||||
|
await self._conn.send(data)
|
||||||
|
except ConnectionClosed as exc:
|
||||||
|
raise _to_closed_error(exc) from exc
|
||||||
|
|
||||||
|
async def recv(self) -> str:
|
||||||
|
try:
|
||||||
|
frame = await self._conn.recv()
|
||||||
|
except ConnectionClosed as exc:
|
||||||
|
raise _to_closed_error(exc) from exc
|
||||||
|
if isinstance(frame, bytes):
|
||||||
|
return frame.decode("utf-8", errors="replace")
|
||||||
|
return frame
|
||||||
|
|
||||||
|
async def close(self) -> None:
|
||||||
|
await self._conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def websockets_connect(url: str) -> WebSocketTransport:
|
||||||
|
"""Connect to an LG webOS SSAP or pointer WebSocket endpoint."""
|
||||||
|
ssl_ctx = build_ssl_context() if url.startswith("wss://") else None
|
||||||
|
conn = await websockets.connect(
|
||||||
|
url,
|
||||||
|
ssl=ssl_ctx,
|
||||||
|
open_timeout=3.5,
|
||||||
|
ping_interval=10,
|
||||||
|
ping_timeout=5,
|
||||||
|
)
|
||||||
|
return _WebsocketsAdapter(conn)
|
||||||
|
|
||||||
|
|
||||||
|
def _is_permission_error(text: str) -> bool:
|
||||||
|
lowered = text.lower()
|
||||||
|
return "401" in lowered or "insufficient permissions" in lowered
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_error_text(msg: dict[str, Any]) -> str:
|
||||||
|
payload = msg.get("payload")
|
||||||
|
if isinstance(payload, dict):
|
||||||
|
payload_dict = cast(dict[str, Any], payload)
|
||||||
|
err_text = payload_dict.get("errorText") or payload_dict.get("errorCode")
|
||||||
|
if err_text:
|
||||||
|
return str(err_text)
|
||||||
|
if msg.get("error"):
|
||||||
|
return str(msg["error"])
|
||||||
|
return "SSAP request failed"
|
||||||
|
|
||||||
|
|
||||||
|
class SsapClient:
|
||||||
|
"""Persistent SSAP WebSocket client with msg['id'] request/subscribe demultiplexing."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
url: str,
|
||||||
|
connect_fn: WebSocketConnectFn = websockets_connect,
|
||||||
|
*,
|
||||||
|
on_disconnect: Callable[[ErrorCode], None] | None = None,
|
||||||
|
) -> None:
|
||||||
|
self._url = url
|
||||||
|
self._connect_fn = connect_fn
|
||||||
|
self._on_disconnect = on_disconnect
|
||||||
|
self._ws: WebSocketTransport | None = None
|
||||||
|
self._reader_task: asyncio.Task[None] | None = None
|
||||||
|
self._pending: dict[str, asyncio.Future[dict[str, Any]]] = {}
|
||||||
|
self._subscriptions: dict[str, Callable[[dict[str, Any]], Awaitable[None] | None]] = {}
|
||||||
|
self._next_id = 1
|
||||||
|
self._closing = False
|
||||||
|
|
||||||
|
async def connect_and_register(self, client_key: str | None) -> str:
|
||||||
|
"""Connect, perform SSAP register handshake, and start the reader loop."""
|
||||||
|
await self.close()
|
||||||
|
self._closing = False
|
||||||
|
|
||||||
|
try:
|
||||||
|
ws = await self._connect_fn(self._url)
|
||||||
|
except (TimeoutError, OSError, WebSocketClosedError) as exc:
|
||||||
|
raise TvError(ErrorCode.TV_OFFLINE_STANDBY, f"Failed to connect to TV: {exc}") from exc
|
||||||
|
|
||||||
|
self._ws = ws
|
||||||
|
try:
|
||||||
|
await ws.send(json.dumps(build_register_payload(client_key)))
|
||||||
|
while True:
|
||||||
|
raw = await ws.recv()
|
||||||
|
msg_raw: Any = json.loads(raw)
|
||||||
|
if not isinstance(msg_raw, dict):
|
||||||
|
continue
|
||||||
|
msg = cast(dict[str, Any], msg_raw)
|
||||||
|
msg_type = msg.get("type")
|
||||||
|
payload_raw = msg.get("payload")
|
||||||
|
payload = cast(dict[str, Any], payload_raw) if isinstance(payload_raw, dict) else {}
|
||||||
|
|
||||||
|
if msg_type == "registered":
|
||||||
|
resolved_key = str(payload.get("client-key") or client_key or "")
|
||||||
|
self._reader_task = asyncio.create_task(self._reader_loop())
|
||||||
|
return resolved_key
|
||||||
|
|
||||||
|
if msg_type == "response" and payload.get("pairingType") == "PROMPT":
|
||||||
|
await self._safe_close_ws(ws)
|
||||||
|
self._ws = None
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.PAIRING_REQUIRED,
|
||||||
|
"TV requested interactive pairing prompt",
|
||||||
|
)
|
||||||
|
|
||||||
|
if msg_type == "error":
|
||||||
|
await self._safe_close_ws(ws)
|
||||||
|
self._ws = None
|
||||||
|
err_text = _extract_error_text(msg)
|
||||||
|
code = (
|
||||||
|
ErrorCode.PAIRING_REQUIRED
|
||||||
|
if _is_permission_error(err_text) or "pairing" in err_text.lower()
|
||||||
|
else ErrorCode.COMMAND_FAILED
|
||||||
|
)
|
||||||
|
raise TvError(code, err_text)
|
||||||
|
except TvError:
|
||||||
|
raise
|
||||||
|
except (TimeoutError, OSError, WebSocketClosedError, json.JSONDecodeError) as exc:
|
||||||
|
await self._safe_close_ws(ws)
|
||||||
|
self._ws = None
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.TV_OFFLINE_STANDBY,
|
||||||
|
f"SSAP handshake interrupted: {exc}",
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
async def request(self, uri: str, payload: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||||
|
"""Send a one-shot SSAP request and await its matched response payload."""
|
||||||
|
ws = self._ws
|
||||||
|
if ws is None:
|
||||||
|
raise TvError(ErrorCode.TV_OFFLINE_STANDBY, "SSAP socket is not connected")
|
||||||
|
|
||||||
|
msg_id = f"req_{self._next_id}"
|
||||||
|
self._next_id += 1
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
fut: asyncio.Future[dict[str, Any]] = loop.create_future()
|
||||||
|
self._pending[msg_id] = fut
|
||||||
|
|
||||||
|
frame = json.dumps(
|
||||||
|
{
|
||||||
|
"type": "request",
|
||||||
|
"id": msg_id,
|
||||||
|
"uri": uri,
|
||||||
|
"payload": payload or {},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
await ws.send(frame)
|
||||||
|
except (WebSocketClosedError, OSError) as exc:
|
||||||
|
self._pending.pop(msg_id, None)
|
||||||
|
if not fut.done():
|
||||||
|
fut.cancel()
|
||||||
|
raise TvError(ErrorCode.TV_OFFLINE_STANDBY, f"SSAP send failed: {exc}") from exc
|
||||||
|
|
||||||
|
msg = await fut
|
||||||
|
return self._unwrap_response(msg)
|
||||||
|
|
||||||
|
async def subscribe(
|
||||||
|
self,
|
||||||
|
uri: str,
|
||||||
|
callback: Callable[[dict[str, Any]], Awaitable[None] | None],
|
||||||
|
) -> None:
|
||||||
|
"""Subscribe to an SSAP endpoint and route push updates to callback."""
|
||||||
|
ws = self._ws
|
||||||
|
if ws is None:
|
||||||
|
raise TvError(ErrorCode.TV_OFFLINE_STANDBY, "SSAP socket is not connected")
|
||||||
|
|
||||||
|
msg_id = f"sub_{self._next_id}"
|
||||||
|
self._next_id += 1
|
||||||
|
self._subscriptions[msg_id] = callback
|
||||||
|
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
fut: asyncio.Future[dict[str, Any]] = loop.create_future()
|
||||||
|
self._pending[msg_id] = fut
|
||||||
|
|
||||||
|
frame = json.dumps({"type": "subscribe", "id": msg_id, "uri": uri, "payload": {}})
|
||||||
|
try:
|
||||||
|
await ws.send(frame)
|
||||||
|
except (WebSocketClosedError, OSError) as exc:
|
||||||
|
self._pending.pop(msg_id, None)
|
||||||
|
self._subscriptions.pop(msg_id, None)
|
||||||
|
if not fut.done():
|
||||||
|
fut.cancel()
|
||||||
|
raise TvError(ErrorCode.TV_OFFLINE_STANDBY, f"SSAP subscribe failed: {exc}") from exc
|
||||||
|
|
||||||
|
msg = await fut
|
||||||
|
payload = self._unwrap_response(msg)
|
||||||
|
await self._invoke_callback(callback, payload)
|
||||||
|
|
||||||
|
async def close(self) -> None:
|
||||||
|
"""Close the SSAP transport and cancel the background reader loop."""
|
||||||
|
self._closing = True
|
||||||
|
ws = self._ws
|
||||||
|
self._ws = None
|
||||||
|
if ws is not None:
|
||||||
|
await self._safe_close_ws(ws)
|
||||||
|
|
||||||
|
task = self._reader_task
|
||||||
|
self._reader_task = None
|
||||||
|
if task is not None and not task.done():
|
||||||
|
task.cancel()
|
||||||
|
with suppress(asyncio.CancelledError):
|
||||||
|
await task
|
||||||
|
|
||||||
|
self._subscriptions.clear()
|
||||||
|
|
||||||
|
async def _reader_loop(self) -> None:
|
||||||
|
ws = self._ws
|
||||||
|
disconnect_code = ErrorCode.TV_OFFLINE_STANDBY
|
||||||
|
try:
|
||||||
|
while ws is not None:
|
||||||
|
raw = await ws.recv()
|
||||||
|
msg_raw: Any = json.loads(raw)
|
||||||
|
if not isinstance(msg_raw, dict):
|
||||||
|
continue
|
||||||
|
msg = cast(dict[str, Any], msg_raw)
|
||||||
|
msg_id = msg.get("id")
|
||||||
|
if not isinstance(msg_id, str):
|
||||||
|
continue
|
||||||
|
|
||||||
|
if msg_id in self._pending:
|
||||||
|
fut = self._pending.pop(msg_id)
|
||||||
|
if not fut.done():
|
||||||
|
fut.set_result(msg)
|
||||||
|
elif msg_id in self._subscriptions:
|
||||||
|
if msg.get("type") == "error":
|
||||||
|
err_text = _extract_error_text(msg)
|
||||||
|
if _is_permission_error(err_text):
|
||||||
|
disconnect_code = ErrorCode.PAIRING_REQUIRED
|
||||||
|
break
|
||||||
|
continue
|
||||||
|
payload = msg.get("payload")
|
||||||
|
if isinstance(payload, dict):
|
||||||
|
payload_dict = cast(dict[str, Any], payload)
|
||||||
|
await self._invoke_callback(self._subscriptions[msg_id], payload_dict)
|
||||||
|
except WebSocketClosedError, OSError, json.JSONDecodeError, asyncio.CancelledError:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
for fut in list(self._pending.values()):
|
||||||
|
if not fut.done():
|
||||||
|
fut.set_exception(
|
||||||
|
TvError(ErrorCode.TV_OFFLINE_STANDBY, "SSAP connection closed")
|
||||||
|
)
|
||||||
|
self._pending.clear()
|
||||||
|
if ws is not None:
|
||||||
|
await self._safe_close_ws(ws)
|
||||||
|
if self._ws is ws:
|
||||||
|
self._ws = None
|
||||||
|
if not self._closing and self._on_disconnect is not None:
|
||||||
|
self._on_disconnect(disconnect_code)
|
||||||
|
|
||||||
|
def _unwrap_response(self, msg: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
if msg.get("type") == "error":
|
||||||
|
err_text = _extract_error_text(msg)
|
||||||
|
code = (
|
||||||
|
ErrorCode.PAIRING_REQUIRED
|
||||||
|
if _is_permission_error(err_text)
|
||||||
|
else ErrorCode.COMMAND_FAILED
|
||||||
|
)
|
||||||
|
raise TvError(code, err_text)
|
||||||
|
|
||||||
|
payload_raw = msg.get("payload")
|
||||||
|
if not isinstance(payload_raw, dict):
|
||||||
|
return {}
|
||||||
|
payload = cast(dict[str, Any], payload_raw)
|
||||||
|
if payload.get("returnValue") is False:
|
||||||
|
err_text = _extract_error_text(msg)
|
||||||
|
code = (
|
||||||
|
ErrorCode.PAIRING_REQUIRED
|
||||||
|
if _is_permission_error(err_text)
|
||||||
|
else ErrorCode.COMMAND_FAILED
|
||||||
|
)
|
||||||
|
raise TvError(code, err_text)
|
||||||
|
return payload
|
||||||
|
|
||||||
|
async def _invoke_callback(
|
||||||
|
self,
|
||||||
|
callback: Callable[[dict[str, Any]], Awaitable[None] | None],
|
||||||
|
payload: dict[str, Any],
|
||||||
|
) -> None:
|
||||||
|
result = callback(payload)
|
||||||
|
if inspect.isawaitable(result):
|
||||||
|
await result
|
||||||
|
|
||||||
|
async def _safe_close_ws(self, ws: WebSocketTransport) -> None:
|
||||||
|
with suppress(Exception):
|
||||||
|
await ws.close()
|
||||||
Whitespace-only changes.
@@ -0,0 +1,61 @@
|
|||||||
|
"""Shared offline test fakes and fixtures for lg-smtv-mcp contract tests."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
from collections.abc import Callable
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from lg_smtv_mcp.tv_core.protocols import WebSocketClosedError
|
||||||
|
|
||||||
|
|
||||||
|
class FakeWebSocketTransport:
|
||||||
|
"""In-memory WebSocketTransport double for offline SSAP and pointer tests."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
on_send: Callable[[str, FakeWebSocketTransport], None] | None = None,
|
||||||
|
) -> None:
|
||||||
|
self.sent: list[str] = []
|
||||||
|
self.closed = False
|
||||||
|
self._on_send = on_send
|
||||||
|
self._incoming: asyncio.Queue[str | Exception] = asyncio.Queue()
|
||||||
|
|
||||||
|
def push_text(self, data: str) -> None:
|
||||||
|
"""Enqueue a raw text frame to be returned by recv()."""
|
||||||
|
self._incoming.put_nowait(data)
|
||||||
|
|
||||||
|
def push_json(self, payload: dict[str, Any]) -> None:
|
||||||
|
"""Enqueue a JSON-serialized frame to be returned by recv()."""
|
||||||
|
self._incoming.put_nowait(json.dumps(payload))
|
||||||
|
|
||||||
|
def push_error(self, exc: Exception) -> None:
|
||||||
|
"""Enqueue an exception to be raised by the next recv()."""
|
||||||
|
self._incoming.put_nowait(exc)
|
||||||
|
|
||||||
|
def push_close(self, code: int = 1000, reason: str = "") -> None:
|
||||||
|
"""Enqueue a WebSocketClosedError to simulate remote socket close."""
|
||||||
|
self._incoming.put_nowait(WebSocketClosedError(code, reason))
|
||||||
|
|
||||||
|
async def send(self, data: str) -> None:
|
||||||
|
"""Record an outgoing frame or raise WebSocketClosedError if closed."""
|
||||||
|
if self.closed:
|
||||||
|
raise WebSocketClosedError(1006, "transport closed")
|
||||||
|
self.sent.append(data)
|
||||||
|
if self._on_send is not None:
|
||||||
|
self._on_send(data, self)
|
||||||
|
|
||||||
|
async def recv(self) -> str:
|
||||||
|
"""Return the next queued frame or raise a queued exception."""
|
||||||
|
if self.closed and self._incoming.empty():
|
||||||
|
raise WebSocketClosedError(1006, "transport closed")
|
||||||
|
item = await self._incoming.get()
|
||||||
|
if isinstance(item, Exception):
|
||||||
|
raise item
|
||||||
|
return item
|
||||||
|
|
||||||
|
async def close(self) -> None:
|
||||||
|
"""Mark the transport closed and wake any blocked recv()."""
|
||||||
|
if not self.closed:
|
||||||
|
self.closed = True
|
||||||
|
self._incoming.put_nowait(WebSocketClosedError(1000, "closed"))
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
"""Offline contract tests for BearerAuthMiddleware and TransportSecuritySettings."""
|
||||||
|
|
||||||
|
from collections.abc import MutableMapping
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from lg_smtv_mcp.auth import (
|
||||||
|
Receive,
|
||||||
|
Scope,
|
||||||
|
Send,
|
||||||
|
build_transport_security_settings,
|
||||||
|
wrap_bearer_auth,
|
||||||
|
)
|
||||||
|
from lg_smtv_mcp.config import TvConfig
|
||||||
|
from lg_smtv_mcp.errors import ConfigError
|
||||||
|
|
||||||
|
|
||||||
|
async def _ok_app(scope: Scope, receive: Receive, send: Send) -> None:
|
||||||
|
_ = (scope, receive)
|
||||||
|
await send(
|
||||||
|
{
|
||||||
|
"type": "http.response.start",
|
||||||
|
"status": 200,
|
||||||
|
"headers": [(b"content-type", b"application/json")],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
await send({"type": "http.response.body", "body": b'{"ok":true}', "more_body": False})
|
||||||
|
|
||||||
|
|
||||||
|
async def test_bearer_auth_allows_valid_token_and_forwards_to_app() -> None:
|
||||||
|
app = wrap_bearer_auth(_ok_app, "secret-token-123")
|
||||||
|
transport = httpx.ASGITransport(app=app)
|
||||||
|
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
|
||||||
|
resp = await client.get("/mcp", headers={"Authorization": "Bearer secret-token-123"})
|
||||||
|
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.json() == {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"headers",
|
||||||
|
[
|
||||||
|
{},
|
||||||
|
{"Authorization": ""},
|
||||||
|
{"Authorization": "Basic dXNlcjpwYXNz"},
|
||||||
|
{"Authorization": "Bearer"},
|
||||||
|
{"Authorization": "Bearer "},
|
||||||
|
{"Authorization": "Bearer wrong-token"},
|
||||||
|
{"Authorization": "Bearer secret-token-1234"},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
async def test_bearer_auth_rejects_missing_malformed_or_invalid_token_with_401(
|
||||||
|
headers: dict[str, str],
|
||||||
|
) -> None:
|
||||||
|
app = wrap_bearer_auth(_ok_app, "secret-token-123")
|
||||||
|
transport = httpx.ASGITransport(app=app)
|
||||||
|
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
|
||||||
|
resp = await client.get("/mcp", headers=headers)
|
||||||
|
|
||||||
|
assert resp.status_code == 401
|
||||||
|
assert resp.headers.get("www-authenticate") == "Bearer"
|
||||||
|
assert resp.json() == {"error": "unauthorized"}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_bearer_auth_passes_through_non_http_lifespan_scope() -> None:
|
||||||
|
seen_scopes: list[str] = []
|
||||||
|
|
||||||
|
async def lifespan_app(scope: Scope, receive: Receive, send: Send) -> None:
|
||||||
|
_ = (receive, send)
|
||||||
|
seen_scopes.append(str(scope["type"]))
|
||||||
|
|
||||||
|
app = wrap_bearer_auth(lifespan_app, "secret-token-123")
|
||||||
|
|
||||||
|
async def dummy_receive() -> MutableMapping[str, Any]:
|
||||||
|
return {"type": "lifespan.startup"}
|
||||||
|
|
||||||
|
async def dummy_send(message: MutableMapping[str, Any]) -> None:
|
||||||
|
_ = message
|
||||||
|
|
||||||
|
await app({"type": "lifespan"}, dummy_receive, dummy_send)
|
||||||
|
assert seen_scopes == ["lifespan"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("bad_token", ["", " "])
|
||||||
|
def test_bearer_auth_rejects_blank_server_token_with_config_error(bad_token: str) -> None:
|
||||||
|
with pytest.raises(ConfigError):
|
||||||
|
wrap_bearer_auth(_ok_app, bad_token)
|
||||||
|
|
||||||
|
|
||||||
|
def test_transport_security_settings_includes_local_bound_host_and_allowed_hosts() -> None:
|
||||||
|
config = TvConfig(
|
||||||
|
tv_ip="192.0.2.10",
|
||||||
|
host="192.0.2.50",
|
||||||
|
port=9000,
|
||||||
|
allowed_hosts=("tv-mcp.local", "198.51.100.5:9000"),
|
||||||
|
)
|
||||||
|
settings = build_transport_security_settings(config)
|
||||||
|
|
||||||
|
assert settings.enable_dns_rebinding_protection is True
|
||||||
|
assert "127.0.0.1:9000" in settings.allowed_hosts
|
||||||
|
assert "localhost:9000" in settings.allowed_hosts
|
||||||
|
assert "192.0.2.50:9000" in settings.allowed_hosts
|
||||||
|
assert "tv-mcp.local" in settings.allowed_hosts
|
||||||
|
assert "tv-mcp.local:9000" in settings.allowed_hosts
|
||||||
|
assert "198.51.100.5:9000" in settings.allowed_hosts
|
||||||
|
assert "http://192.0.2.50:9000" in settings.allowed_origins
|
||||||
|
assert "http://tv-mcp.local:9000" in settings.allowed_origins
|
||||||
|
|
||||||
|
|
||||||
|
def test_transport_security_settings_excludes_wildcard_bind_host_from_allowed_hosts() -> None:
|
||||||
|
config = TvConfig(tv_ip="192.0.2.10", host="0.0.0.0", port=8765)
|
||||||
|
settings = build_transport_security_settings(config)
|
||||||
|
|
||||||
|
assert "0.0.0.0" not in settings.allowed_hosts
|
||||||
|
assert "0.0.0.0:8765" not in settings.allowed_hosts
|
||||||
|
assert "127.0.0.1:8765" in settings.allowed_hosts
|
||||||
|
assert "localhost:8765" in settings.allowed_hosts
|
||||||
@@ -0,0 +1,672 @@
|
|||||||
|
"""Offline contract tests for AsyncSshCaptureTransport and CaptureClient."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import hashlib
|
||||||
|
import inspect
|
||||||
|
from io import BytesIO
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import asyncssh
|
||||||
|
import pytest
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from lg_smtv_mcp.config import TvConfig
|
||||||
|
from lg_smtv_mcp.errors import ErrorCode, TvError
|
||||||
|
from lg_smtv_mcp.tv_core.capture import AsyncSshCaptureTransport, CaptureClient
|
||||||
|
|
||||||
|
|
||||||
|
class FakeSftpFile:
|
||||||
|
"""Mirror asyncssh.SFTPClientFile: sync open(), async read(), async context manager."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
data: bytes,
|
||||||
|
*,
|
||||||
|
error: Exception | None = None,
|
||||||
|
read_delay: float = 0.0,
|
||||||
|
) -> None:
|
||||||
|
self._data = data
|
||||||
|
self._error = error
|
||||||
|
self._read_delay = read_delay
|
||||||
|
self.closed = False
|
||||||
|
|
||||||
|
async def __aenter__(self) -> FakeSftpFile:
|
||||||
|
return self
|
||||||
|
|
||||||
|
async def __aexit__(self, *_exc: object) -> None:
|
||||||
|
self.closed = True
|
||||||
|
|
||||||
|
async def read(self) -> bytes:
|
||||||
|
if self._read_delay > 0:
|
||||||
|
await asyncio.sleep(self._read_delay)
|
||||||
|
if self._error is not None:
|
||||||
|
raise self._error
|
||||||
|
return self._data
|
||||||
|
|
||||||
|
|
||||||
|
class FakeSftpClient:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
files: dict[str, bytes] | None = None,
|
||||||
|
extra_names: list[str] | None = None,
|
||||||
|
read_error: Exception | None = None,
|
||||||
|
read_delay: float = 0.0,
|
||||||
|
remove_delay: float = 0.0,
|
||||||
|
remove_error: Exception | None = None,
|
||||||
|
) -> None:
|
||||||
|
self.files = dict(files or {})
|
||||||
|
self.extra_names = list(extra_names or [])
|
||||||
|
self.read_error = read_error
|
||||||
|
self.read_delay = read_delay
|
||||||
|
self.remove_delay = remove_delay
|
||||||
|
self.remove_error = remove_error
|
||||||
|
self.open_calls: list[tuple[str, str]] = []
|
||||||
|
self.handles: list[FakeSftpFile] = []
|
||||||
|
self.remove_calls: list[str] = []
|
||||||
|
self.closed = False
|
||||||
|
|
||||||
|
def open(self, path: str, mode: str = "r") -> FakeSftpFile:
|
||||||
|
"""Mirror asyncssh.SFTPClient.open: regular function returning an async file."""
|
||||||
|
self.open_calls.append((path, mode))
|
||||||
|
error = self.read_error
|
||||||
|
if error is None and path not in self.files:
|
||||||
|
error = FileNotFoundError(path)
|
||||||
|
handle = FakeSftpFile(
|
||||||
|
self.files.get(path, b""),
|
||||||
|
error=error,
|
||||||
|
read_delay=self.read_delay,
|
||||||
|
)
|
||||||
|
self.handles.append(handle)
|
||||||
|
return handle
|
||||||
|
|
||||||
|
async def remove(self, path: str) -> None:
|
||||||
|
if self.remove_delay > 0:
|
||||||
|
await asyncio.sleep(self.remove_delay)
|
||||||
|
self.remove_calls.append(path)
|
||||||
|
if self.remove_error is not None:
|
||||||
|
raise self.remove_error
|
||||||
|
self.files.pop(path, None)
|
||||||
|
|
||||||
|
async def listdir(self, path: str) -> list[str]:
|
||||||
|
_ = path
|
||||||
|
names = {Path(p).name for p in self.files} | set(self.extra_names)
|
||||||
|
return sorted(names)
|
||||||
|
|
||||||
|
async def exit(self) -> None:
|
||||||
|
self.closed = True
|
||||||
|
|
||||||
|
|
||||||
|
class FakeSshConnection:
|
||||||
|
def __init__(self, sftp: FakeSftpClient) -> None:
|
||||||
|
self.sftp = sftp
|
||||||
|
self.sftp_calls = 0
|
||||||
|
self.closed = False
|
||||||
|
|
||||||
|
async def start_sftp_client(self) -> FakeSftpClient:
|
||||||
|
self.sftp_calls += 1
|
||||||
|
return self.sftp
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
self.closed = True
|
||||||
|
|
||||||
|
async def wait_closed(self) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class FakeCaptureTransport:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
image_bytes: bytes = b"default-image",
|
||||||
|
read_error: Exception | None = None,
|
||||||
|
block_read: bool = False,
|
||||||
|
) -> None:
|
||||||
|
self.image_bytes = image_bytes
|
||||||
|
self.read_error = read_error
|
||||||
|
self.block_read = block_read
|
||||||
|
self.read_calls: list[tuple[str, float, float]] = []
|
||||||
|
self.read_cancelled = asyncio.Event()
|
||||||
|
self.closed = False
|
||||||
|
|
||||||
|
async def read_and_remove(
|
||||||
|
self,
|
||||||
|
remote_path: str,
|
||||||
|
timeout: float = 6.0,
|
||||||
|
cleanup_grace: float = 1.5,
|
||||||
|
) -> bytes:
|
||||||
|
self.read_calls.append((remote_path, timeout, cleanup_grace))
|
||||||
|
if self.block_read:
|
||||||
|
try:
|
||||||
|
await asyncio.Event().wait()
|
||||||
|
finally:
|
||||||
|
self.read_cancelled.set()
|
||||||
|
if self.read_error is not None:
|
||||||
|
raise self.read_error
|
||||||
|
return self.image_bytes
|
||||||
|
|
||||||
|
async def sweep_temp_files(
|
||||||
|
self,
|
||||||
|
prefix: str = "/tmp/lg_smtv_cap_",
|
||||||
|
exclude: str | None = None,
|
||||||
|
) -> None:
|
||||||
|
_ = (prefix, exclude)
|
||||||
|
|
||||||
|
async def close(self) -> None:
|
||||||
|
self.closed = True
|
||||||
|
|
||||||
|
|
||||||
|
def _make_config(tmp_path: Path, *, with_ssh: bool = False) -> TvConfig:
|
||||||
|
ssh_key = tmp_path / "id_rsa"
|
||||||
|
known_hosts = tmp_path / "known_hosts"
|
||||||
|
if with_ssh:
|
||||||
|
ssh_key.write_text("dummy", encoding="utf-8")
|
||||||
|
known_hosts.write_text("dummy", encoding="utf-8")
|
||||||
|
kwargs: dict[str, Any] = {"tv_ip": "192.0.2.10"}
|
||||||
|
if with_ssh:
|
||||||
|
kwargs["ssh_key_path"] = ssh_key
|
||||||
|
kwargs["ssh_known_hosts_path"] = known_hosts
|
||||||
|
kwargs["webos_ssh_passphrase"] = "secret"
|
||||||
|
return TvConfig(**kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_async_ssh_capture_transport_connect_uses_required_args(tmp_path: Path) -> None:
|
||||||
|
sftp = FakeSftpClient(files={"/tmp/lg_smtv_cap_1.jpg": b"jpeg"})
|
||||||
|
conn = FakeSshConnection(sftp)
|
||||||
|
calls: list[dict[str, Any]] = []
|
||||||
|
|
||||||
|
async def fake_connect(**kwargs: Any) -> FakeSshConnection:
|
||||||
|
calls.append(kwargs)
|
||||||
|
return conn
|
||||||
|
|
||||||
|
cfg = _make_config(tmp_path, with_ssh=True)
|
||||||
|
transport = AsyncSshCaptureTransport(cfg, connect_fn=fake_connect)
|
||||||
|
data = await transport.read_and_remove("/tmp/lg_smtv_cap_1.jpg")
|
||||||
|
|
||||||
|
assert data == b"jpeg"
|
||||||
|
assert len(calls) == 1
|
||||||
|
assert calls[0]["host"] == "192.0.2.10"
|
||||||
|
assert calls[0]["port"] == 9922
|
||||||
|
assert calls[0]["username"] == "prisoner"
|
||||||
|
assert calls[0]["config"] == []
|
||||||
|
assert calls[0]["server_host_key_algs"] == ["ssh-rsa"]
|
||||||
|
assert calls[0]["signature_algs"] == ["ssh-rsa"]
|
||||||
|
assert calls[0]["client_keys"] == [str(cfg.ssh_key_path)]
|
||||||
|
assert calls[0]["known_hosts"] == str(cfg.ssh_known_hosts_path)
|
||||||
|
assert calls[0]["passphrase"] == "secret"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_async_ssh_capture_transport_reads_via_real_sftp_open_api(tmp_path: Path) -> None:
|
||||||
|
"""Guard against reintroducing sftp.read(), which asyncssh 2.24 does not expose."""
|
||||||
|
assert not hasattr(asyncssh.SFTPClient, "read")
|
||||||
|
assert hasattr(asyncssh.SFTPClient, "open")
|
||||||
|
assert hasattr(asyncssh.SFTPClientFile, "__aenter__")
|
||||||
|
assert inspect.iscoroutinefunction(asyncssh.SFTPClientFile.read)
|
||||||
|
|
||||||
|
remote_path = "/tmp/lg_smtv_cap_1.jpg"
|
||||||
|
sftp = FakeSftpClient(files={remote_path: b"jpeg"})
|
||||||
|
conn = FakeSshConnection(sftp)
|
||||||
|
|
||||||
|
async def fake_connect(**kwargs: Any) -> FakeSshConnection:
|
||||||
|
_ = kwargs
|
||||||
|
return conn
|
||||||
|
|
||||||
|
transport = AsyncSshCaptureTransport(_make_config(tmp_path), connect_fn=fake_connect)
|
||||||
|
data = await transport.read_and_remove(remote_path)
|
||||||
|
|
||||||
|
assert data == b"jpeg"
|
||||||
|
assert sftp.open_calls == [(remote_path, "rb")]
|
||||||
|
assert len(sftp.handles) == 1
|
||||||
|
assert sftp.handles[0].closed is True
|
||||||
|
|
||||||
|
|
||||||
|
async def test_async_ssh_capture_transport_sweeps_on_initial_connect_and_reconnect(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
sftp1 = FakeSftpClient(
|
||||||
|
files={"/tmp/lg_smtv_cap_1.jpg": b"one"},
|
||||||
|
extra_names=["lg_smtv_cap_old.jpg", "other.txt"],
|
||||||
|
)
|
||||||
|
conn1 = FakeSshConnection(sftp1)
|
||||||
|
sftp2 = FakeSftpClient(
|
||||||
|
files={"/tmp/lg_smtv_cap_2.jpg": b"two"},
|
||||||
|
extra_names=["lg_smtv_cap_stale.jpg", "keep.txt"],
|
||||||
|
)
|
||||||
|
conn2 = FakeSshConnection(sftp2)
|
||||||
|
conns = [conn1, conn2]
|
||||||
|
|
||||||
|
async def fake_connect(**kwargs: Any) -> FakeSshConnection:
|
||||||
|
_ = kwargs
|
||||||
|
return conns.pop(0)
|
||||||
|
|
||||||
|
transport = AsyncSshCaptureTransport(_make_config(tmp_path), connect_fn=fake_connect)
|
||||||
|
await transport.read_and_remove("/tmp/lg_smtv_cap_1.jpg")
|
||||||
|
assert "/tmp/lg_smtv_cap_old.jpg" in sftp1.remove_calls
|
||||||
|
assert "/tmp/other.txt" not in sftp1.remove_calls
|
||||||
|
|
||||||
|
# Force transport error on next read to trigger reconnect and sweep on new SFTP.
|
||||||
|
sftp1.read_error = OSError("boom")
|
||||||
|
with pytest.raises(OSError):
|
||||||
|
await transport.read_and_remove("/tmp/lg_smtv_cap_1.jpg")
|
||||||
|
|
||||||
|
data = await transport.read_and_remove("/tmp/lg_smtv_cap_2.jpg")
|
||||||
|
assert data == b"two"
|
||||||
|
assert "/tmp/lg_smtv_cap_stale.jpg" in sftp2.remove_calls
|
||||||
|
assert "/tmp/keep.txt" not in sftp2.remove_calls
|
||||||
|
|
||||||
|
|
||||||
|
async def test_async_ssh_capture_transport_sweep_preserves_in_flight_remote_path(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
remote_path = "/tmp/lg_smtv_cap_1.jpg"
|
||||||
|
sftp = FakeSftpClient(
|
||||||
|
files={
|
||||||
|
remote_path: b"fresh-frame",
|
||||||
|
"/tmp/lg_smtv_cap_stale.jpg": b"stale-frame",
|
||||||
|
},
|
||||||
|
extra_names=["other_file.txt"],
|
||||||
|
)
|
||||||
|
conn = FakeSshConnection(sftp)
|
||||||
|
|
||||||
|
async def fake_connect(**kwargs: Any) -> FakeSshConnection:
|
||||||
|
_ = kwargs
|
||||||
|
return conn
|
||||||
|
|
||||||
|
transport = AsyncSshCaptureTransport(_make_config(tmp_path), connect_fn=fake_connect)
|
||||||
|
data = await transport.read_and_remove(remote_path)
|
||||||
|
|
||||||
|
assert data == b"fresh-frame"
|
||||||
|
assert "/tmp/lg_smtv_cap_stale.jpg" in sftp.remove_calls
|
||||||
|
assert remote_path in sftp.remove_calls
|
||||||
|
assert "/tmp/other_file.txt" not in sftp.remove_calls
|
||||||
|
|
||||||
|
|
||||||
|
async def test_async_ssh_capture_transport_closes_connection_when_start_sftp_client_fails(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
class FailingSshConnection:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.closed = False
|
||||||
|
|
||||||
|
async def start_sftp_client(self) -> Any:
|
||||||
|
raise OSError("sftp start failed")
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
self.closed = True
|
||||||
|
|
||||||
|
async def wait_closed(self) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
conn = FailingSshConnection()
|
||||||
|
|
||||||
|
async def fake_connect(**kwargs: Any) -> FailingSshConnection:
|
||||||
|
_ = kwargs
|
||||||
|
return conn
|
||||||
|
|
||||||
|
transport = AsyncSshCaptureTransport(_make_config(tmp_path), connect_fn=fake_connect)
|
||||||
|
with pytest.raises(OSError):
|
||||||
|
await transport.read_and_remove("/tmp/lg_smtv_cap_1.jpg")
|
||||||
|
|
||||||
|
assert conn.closed is True
|
||||||
|
|
||||||
|
|
||||||
|
async def test_async_ssh_capture_transport_enforces_read_timeout(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
sftp = FakeSftpClient(files={"/tmp/lg_smtv_cap_1.jpg": b"bytes"}, read_delay=10.0)
|
||||||
|
conn = FakeSshConnection(sftp)
|
||||||
|
|
||||||
|
async def fake_connect(**kwargs: Any) -> FakeSshConnection:
|
||||||
|
_ = kwargs
|
||||||
|
return conn
|
||||||
|
|
||||||
|
transport = AsyncSshCaptureTransport(_make_config(tmp_path), connect_fn=fake_connect)
|
||||||
|
with pytest.raises(TimeoutError):
|
||||||
|
await transport.read_and_remove("/tmp/lg_smtv_cap_1.jpg", timeout=0.05)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_async_ssh_capture_transport_finishes_remove_after_cancellation(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
remote_path = "/tmp/lg_smtv_cap_1.jpg"
|
||||||
|
|
||||||
|
class BlockingRemoveSftp(FakeSftpClient):
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__(files={remote_path: b"jpeg"})
|
||||||
|
self.remove_started = asyncio.Event()
|
||||||
|
self.allow_remove = asyncio.Event()
|
||||||
|
self.remove_finished = asyncio.Event()
|
||||||
|
|
||||||
|
async def remove(self, path: str) -> None:
|
||||||
|
self.remove_started.set()
|
||||||
|
await self.allow_remove.wait()
|
||||||
|
await super().remove(path)
|
||||||
|
self.remove_finished.set()
|
||||||
|
|
||||||
|
sftp = BlockingRemoveSftp()
|
||||||
|
conn = FakeSshConnection(sftp)
|
||||||
|
|
||||||
|
async def fake_connect(**kwargs: Any) -> FakeSshConnection:
|
||||||
|
_ = kwargs
|
||||||
|
return conn
|
||||||
|
|
||||||
|
transport = AsyncSshCaptureTransport(_make_config(tmp_path), connect_fn=fake_connect)
|
||||||
|
read_task = asyncio.create_task(transport.read_and_remove(remote_path, cleanup_grace=0.05))
|
||||||
|
try:
|
||||||
|
await asyncio.wait_for(sftp.remove_started.wait(), timeout=1.0)
|
||||||
|
read_task.cancel()
|
||||||
|
with pytest.raises(asyncio.CancelledError):
|
||||||
|
await read_task
|
||||||
|
finally:
|
||||||
|
sftp.allow_remove.set()
|
||||||
|
if not read_task.done():
|
||||||
|
read_task.cancel()
|
||||||
|
await asyncio.gather(read_task, return_exceptions=True)
|
||||||
|
|
||||||
|
await asyncio.wait_for(sftp.remove_finished.wait(), timeout=1.0)
|
||||||
|
assert remote_path in sftp.remove_calls
|
||||||
|
|
||||||
|
|
||||||
|
async def test_capture_client_sends_execute_one_shot_and_returns_metadata() -> None:
|
||||||
|
image = b"frame-bytes"
|
||||||
|
expected_sha = hashlib.sha256(image).hexdigest()
|
||||||
|
|
||||||
|
transport = FakeCaptureTransport(image_bytes=image)
|
||||||
|
client = CaptureClient(transport)
|
||||||
|
calls: list[tuple[str, dict[str, Any]]] = []
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
calls.append((uri, payload))
|
||||||
|
return {"returnValue": True}
|
||||||
|
|
||||||
|
result = await client.capture_frame(ssap_request)
|
||||||
|
|
||||||
|
assert calls == [
|
||||||
|
(
|
||||||
|
"ssap://com.webos.service.capture/executeOneShot",
|
||||||
|
{"path": "/tmp/lg_smtv_cap_1.jpg", "method": "DISPLAY", "format": "JPG"},
|
||||||
|
)
|
||||||
|
]
|
||||||
|
assert transport.read_calls == [("/tmp/lg_smtv_cap_1.jpg", 6.0, 1.5)]
|
||||||
|
assert result.image_bytes == image
|
||||||
|
assert result.frame_sha256 == expected_sha
|
||||||
|
assert result.changed_since_last is True
|
||||||
|
assert result.size_bytes == len(image)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_capture_client_changed_since_last_and_close_resets() -> None:
|
||||||
|
client = CaptureClient(FakeCaptureTransport(image_bytes=b"same"))
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = (uri, payload)
|
||||||
|
return {"returnValue": True}
|
||||||
|
|
||||||
|
first = await client.capture_frame(ssap_request)
|
||||||
|
second = await client.capture_frame(ssap_request)
|
||||||
|
await client.close()
|
||||||
|
third = await client.capture_frame(ssap_request)
|
||||||
|
|
||||||
|
assert first.changed_since_last is True
|
||||||
|
assert second.changed_since_last is False
|
||||||
|
assert third.changed_since_last is True
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"response",
|
||||||
|
[{"returnValue": False}, {}, {"returnValue": None}],
|
||||||
|
ids=["false", "missing", "null"],
|
||||||
|
)
|
||||||
|
async def test_capture_client_rejects_non_true_return_value_without_sftp_read(
|
||||||
|
response: dict[str, Any],
|
||||||
|
) -> None:
|
||||||
|
transport = FakeCaptureTransport()
|
||||||
|
client = CaptureClient(transport)
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = (uri, payload)
|
||||||
|
return response
|
||||||
|
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await client.capture_frame(ssap_request)
|
||||||
|
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
||||||
|
assert len(transport.read_calls) == 0
|
||||||
|
|
||||||
|
|
||||||
|
async def test_capture_client_preserves_standby_and_pairing_errors() -> None:
|
||||||
|
client = CaptureClient(FakeCaptureTransport())
|
||||||
|
|
||||||
|
async def standby_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = (uri, payload)
|
||||||
|
raise TvError(ErrorCode.TV_OFFLINE_STANDBY, "standby")
|
||||||
|
|
||||||
|
with pytest.raises(TvError) as standby_exc:
|
||||||
|
await client.capture_frame(standby_request)
|
||||||
|
assert standby_exc.value.code is ErrorCode.TV_OFFLINE_STANDBY
|
||||||
|
|
||||||
|
async def pairing_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = (uri, payload)
|
||||||
|
raise TvError(ErrorCode.PAIRING_REQUIRED, "pairing")
|
||||||
|
|
||||||
|
with pytest.raises(TvError) as pairing_exc:
|
||||||
|
await client.capture_frame(pairing_request)
|
||||||
|
assert pairing_exc.value.code is ErrorCode.PAIRING_REQUIRED
|
||||||
|
|
||||||
|
|
||||||
|
async def test_capture_client_maps_command_failed_without_sftp_read() -> None:
|
||||||
|
transport = FakeCaptureTransport()
|
||||||
|
client = CaptureClient(transport)
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = (uri, payload)
|
||||||
|
raise TvError(ErrorCode.COMMAND_FAILED, "executeOneShot failed")
|
||||||
|
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await client.capture_frame(ssap_request)
|
||||||
|
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
||||||
|
assert len(transport.read_calls) == 0
|
||||||
|
|
||||||
|
|
||||||
|
async def test_capture_client_maps_sftp_os_error_to_screenshot_unavailable() -> None:
|
||||||
|
transport = FakeCaptureTransport(read_error=OSError("sftp read failed"))
|
||||||
|
client = CaptureClient(transport)
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = (uri, payload)
|
||||||
|
return {"returnValue": True}
|
||||||
|
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await client.capture_frame(ssap_request)
|
||||||
|
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
||||||
|
|
||||||
|
|
||||||
|
async def test_capture_client_maps_timeout_to_screenshot_unavailable() -> None:
|
||||||
|
client = CaptureClient(FakeCaptureTransport())
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = (uri, payload)
|
||||||
|
await asyncio.sleep(10)
|
||||||
|
return {"returnValue": True}
|
||||||
|
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await client.capture_frame(ssap_request)
|
||||||
|
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
||||||
|
|
||||||
|
|
||||||
|
async def test_capture_client_maps_sftp_timeout_and_cancels_read() -> None:
|
||||||
|
transport = FakeCaptureTransport(block_read=True)
|
||||||
|
client = CaptureClient(transport)
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = (uri, payload)
|
||||||
|
return {"returnValue": True}
|
||||||
|
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await asyncio.wait_for(client.capture_frame(ssap_request), timeout=7.0)
|
||||||
|
|
||||||
|
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
||||||
|
assert transport.read_cancelled.is_set()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_capture_client_maps_key_import_error_to_screenshot_unavailable() -> None:
|
||||||
|
transport = FakeCaptureTransport(
|
||||||
|
read_error=asyncssh.KeyImportError(
|
||||||
|
"Passphrase must be specified to import encrypted private keys"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
client = CaptureClient(transport)
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = (uri, payload)
|
||||||
|
return {"returnValue": True}
|
||||||
|
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await client.capture_frame(ssap_request)
|
||||||
|
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
||||||
|
assert "Passphrase must be specified" in exc_info.value.message
|
||||||
|
|
||||||
|
|
||||||
|
def _make_jpeg(
|
||||||
|
width: int,
|
||||||
|
height: int,
|
||||||
|
*,
|
||||||
|
color: tuple[int, int, int] = (25, 80, 160),
|
||||||
|
quality: int = 95,
|
||||||
|
) -> bytes:
|
||||||
|
buf = BytesIO()
|
||||||
|
img = Image.new("RGB", (width, height), color=color)
|
||||||
|
# Draw varied pixels so JPEG recompression has realistic entropy differences.
|
||||||
|
for x in range(0, width, 8):
|
||||||
|
img.putpixel((x, x % height), ((x * 7) % 255, (x * 13) % 255, 200))
|
||||||
|
img.save(buf, format="JPEG", quality=quality)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_capture_client_passes_raw_bytes_unchanged_when_no_resize_or_quality() -> None:
|
||||||
|
raw = b"raw-unprocessed-bytes"
|
||||||
|
client = CaptureClient(FakeCaptureTransport(image_bytes=raw))
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = (uri, payload)
|
||||||
|
return {"returnValue": True}
|
||||||
|
|
||||||
|
result = await client.capture_frame(ssap_request)
|
||||||
|
|
||||||
|
assert result.image_bytes == raw
|
||||||
|
assert result.size_bytes == len(raw)
|
||||||
|
assert result.frame_sha256 == hashlib.sha256(raw).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_capture_client_downscales_preserving_aspect_ratio_with_default_quality_75() -> None:
|
||||||
|
raw = _make_jpeg(1920, 1080, quality=95)
|
||||||
|
client = CaptureClient(FakeCaptureTransport(image_bytes=raw), max_width=640)
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = (uri, payload)
|
||||||
|
return {"returnValue": True}
|
||||||
|
|
||||||
|
result = await client.capture_frame(ssap_request)
|
||||||
|
|
||||||
|
with Image.open(BytesIO(result.image_bytes)) as img:
|
||||||
|
assert img.format == "JPEG"
|
||||||
|
assert img.size == (640, 360)
|
||||||
|
assert result.size_bytes == len(result.image_bytes)
|
||||||
|
assert result.frame_sha256 == hashlib.sha256(result.image_bytes).hexdigest()
|
||||||
|
assert result.image_bytes != raw
|
||||||
|
|
||||||
|
|
||||||
|
async def test_capture_client_never_upscales_when_width_at_or_below_max_width() -> None:
|
||||||
|
raw = _make_jpeg(800, 600, quality=95)
|
||||||
|
client = CaptureClient(
|
||||||
|
FakeCaptureTransport(image_bytes=raw),
|
||||||
|
max_width=1280,
|
||||||
|
jpeg_quality=80,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = (uri, payload)
|
||||||
|
return {"returnValue": True}
|
||||||
|
|
||||||
|
result = await client.capture_frame(ssap_request)
|
||||||
|
|
||||||
|
with Image.open(BytesIO(result.image_bytes)) as img:
|
||||||
|
assert img.format == "JPEG"
|
||||||
|
assert img.size == (800, 600)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_capture_client_recompresses_at_native_resolution_when_only_quality_set() -> None:
|
||||||
|
raw = _make_jpeg(1280, 720, quality=95)
|
||||||
|
client = CaptureClient(FakeCaptureTransport(image_bytes=raw), jpeg_quality=30)
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = (uri, payload)
|
||||||
|
return {"returnValue": True}
|
||||||
|
|
||||||
|
result = await client.capture_frame(ssap_request)
|
||||||
|
|
||||||
|
with Image.open(BytesIO(result.image_bytes)) as img:
|
||||||
|
assert img.format == "JPEG"
|
||||||
|
assert img.size == (1280, 720)
|
||||||
|
assert result.size_bytes < len(raw)
|
||||||
|
assert result.frame_sha256 == hashlib.sha256(result.image_bytes).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_capture_client_hashes_and_tracks_changes_on_final_delivered_bytes() -> None:
|
||||||
|
raw = _make_jpeg(1280, 720, quality=95)
|
||||||
|
client = CaptureClient(
|
||||||
|
FakeCaptureTransport(image_bytes=raw),
|
||||||
|
max_width=640,
|
||||||
|
jpeg_quality=75,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = (uri, payload)
|
||||||
|
return {"returnValue": True}
|
||||||
|
|
||||||
|
first = await client.capture_frame(ssap_request)
|
||||||
|
second = await client.capture_frame(ssap_request)
|
||||||
|
|
||||||
|
assert first.frame_sha256 != hashlib.sha256(raw).hexdigest()
|
||||||
|
assert first.frame_sha256 == hashlib.sha256(first.image_bytes).hexdigest()
|
||||||
|
assert first.changed_since_last is True
|
||||||
|
assert second.changed_since_last is False
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"kwargs",
|
||||||
|
[
|
||||||
|
{"max_width": 640},
|
||||||
|
{"jpeg_quality": 75},
|
||||||
|
{"max_width": 640, "jpeg_quality": 75},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
async def test_capture_client_raises_screenshot_unavailable_on_corrupt_image_bytes(
|
||||||
|
kwargs: dict[str, int],
|
||||||
|
) -> None:
|
||||||
|
client = CaptureClient(FakeCaptureTransport(image_bytes=b"not-a-valid-jpeg"), **kwargs)
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = (uri, payload)
|
||||||
|
return {"returnValue": True}
|
||||||
|
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await client.capture_frame(ssap_request)
|
||||||
|
|
||||||
|
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
||||||
|
|
||||||
|
|
||||||
|
async def test_capture_client_maps_decompression_bomb_error_to_screenshot_unavailable(
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
) -> None:
|
||||||
|
raw = _make_jpeg(32, 32, quality=95)
|
||||||
|
monkeypatch.setattr(Image, "MAX_IMAGE_PIXELS", 100)
|
||||||
|
client = CaptureClient(FakeCaptureTransport(image_bytes=raw), max_width=16)
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = (uri, payload)
|
||||||
|
return {"returnValue": True}
|
||||||
|
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await client.capture_frame(ssap_request)
|
||||||
|
|
||||||
|
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
"""Offline contract tests for lg-smtv-mcp CLI (serve and pair)."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import stat
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
from mcp.server.mcpserver import MCPServer
|
||||||
|
from websockets.exceptions import InvalidMessage
|
||||||
|
|
||||||
|
from lg_smtv_mcp.auth import ASGIApp
|
||||||
|
from lg_smtv_mcp.cli import main
|
||||||
|
from lg_smtv_mcp.config import TvConfig
|
||||||
|
from tests.conftest import FakeWebSocketTransport
|
||||||
|
|
||||||
|
|
||||||
|
def _make_config(
|
||||||
|
tmp_path: Path,
|
||||||
|
*,
|
||||||
|
token: str | None = "test-token",
|
||||||
|
ssh_key_path: Path | None = None,
|
||||||
|
) -> TvConfig:
|
||||||
|
return TvConfig(
|
||||||
|
tv_ip="192.0.2.10",
|
||||||
|
tv_mac="AA:BB:CC:DD:EE:FF",
|
||||||
|
client_key_path=tmp_path / ".client_key.json",
|
||||||
|
ssh_key_path=ssh_key_path,
|
||||||
|
mcp_bearer_token=token,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("bad_token", [None, "", " "])
|
||||||
|
def test_cli_serve_http_fails_closed_when_bearer_token_missing_or_blank(
|
||||||
|
tmp_path: Path,
|
||||||
|
bad_token: str | None,
|
||||||
|
) -> None:
|
||||||
|
called = False
|
||||||
|
|
||||||
|
def fake_uvicorn(app: ASGIApp, host: str, port: int) -> None:
|
||||||
|
nonlocal called
|
||||||
|
_ = (app, host, port)
|
||||||
|
called = True
|
||||||
|
|
||||||
|
rc = main(
|
||||||
|
["serve", "--transport", "streamable-http"],
|
||||||
|
config_loader=lambda: _make_config(tmp_path, token=bad_token),
|
||||||
|
uvicorn_run=fake_uvicorn,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert rc == 1
|
||||||
|
assert called is False
|
||||||
|
|
||||||
|
|
||||||
|
async def test_cli_serve_http_runs_uvicorn_with_configured_host_and_port(tmp_path: Path) -> None:
|
||||||
|
captured: list[tuple[ASGIApp, str, int]] = []
|
||||||
|
|
||||||
|
def fake_uvicorn(app: ASGIApp, host: str, port: int) -> None:
|
||||||
|
captured.append((app, host, port))
|
||||||
|
|
||||||
|
rc = main(
|
||||||
|
["serve", "--transport", "streamable-http"],
|
||||||
|
config_loader=lambda: _make_config(tmp_path, token="valid-secret"),
|
||||||
|
uvicorn_run=fake_uvicorn,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert rc == 0
|
||||||
|
assert len(captured) == 1
|
||||||
|
app, host, port = captured[0]
|
||||||
|
assert host == "127.0.0.1"
|
||||||
|
assert port == 8765
|
||||||
|
|
||||||
|
transport = httpx.ASGITransport(app=app)
|
||||||
|
async with httpx.AsyncClient(transport=transport, base_url="http://127.0.0.1:8765") as client:
|
||||||
|
unauth = await client.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "initialize"})
|
||||||
|
assert unauth.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_cli_serve_stdio_delegates_to_stdio_runner_without_bearer_token(tmp_path: Path) -> None:
|
||||||
|
ran: list[MCPServer[Any]] = []
|
||||||
|
|
||||||
|
def fake_stdio(server: MCPServer[Any]) -> None:
|
||||||
|
ran.append(server)
|
||||||
|
|
||||||
|
rc = main(
|
||||||
|
["serve", "--transport", "stdio"],
|
||||||
|
config_loader=lambda: _make_config(tmp_path, token=None),
|
||||||
|
stdio_run=fake_stdio,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert rc == 0
|
||||||
|
assert len(ran) == 1
|
||||||
|
assert isinstance(ran[0], MCPServer)
|
||||||
|
|
||||||
|
|
||||||
|
def test_cli_pair_merges_existing_client_keys_and_writes_0600(tmp_path: Path) -> None:
|
||||||
|
key_file = tmp_path / ".client_key.json"
|
||||||
|
key_file.write_text(json.dumps({"192.0.2.10": "old-key"}), encoding="utf-8")
|
||||||
|
|
||||||
|
def on_send(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg: dict[str, Any] = json.loads(raw)
|
||||||
|
if msg.get("type") == "register":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "registered",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {"client-key": "new-key-20"},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
ws = FakeWebSocketTransport(on_send=on_send)
|
||||||
|
connected_urls: list[str] = []
|
||||||
|
|
||||||
|
async def fake_connect(url: str) -> FakeWebSocketTransport:
|
||||||
|
connected_urls.append(url)
|
||||||
|
return ws
|
||||||
|
|
||||||
|
rc = main(
|
||||||
|
["pair", "--ip", "192.0.2.20"],
|
||||||
|
config_loader=lambda: _make_config(tmp_path),
|
||||||
|
connect_fn=fake_connect,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert rc == 0
|
||||||
|
assert connected_urls == ["wss://192.0.2.20:3001"]
|
||||||
|
saved = json.loads(key_file.read_text(encoding="utf-8"))
|
||||||
|
assert saved == {"192.0.2.10": "old-key", "192.0.2.20": "new-key-20"}
|
||||||
|
assert stat.S_IMODE(key_file.stat().st_mode) == 0o600
|
||||||
|
|
||||||
|
|
||||||
|
def test_cli_pair_fetch_ssh_key_saves_key_with_0600_permissions(tmp_path: Path) -> None:
|
||||||
|
ssh_dest = tmp_path / "webos_rsa"
|
||||||
|
fetched_urls: list[str] = []
|
||||||
|
|
||||||
|
def on_send(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg: dict[str, Any] = json.loads(raw)
|
||||||
|
if msg.get("type") == "register":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "registered",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {"client-key": "tv-key-10"},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
async def fake_connect(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return FakeWebSocketTransport(on_send=on_send)
|
||||||
|
|
||||||
|
def fake_fetch(url: str) -> bytes:
|
||||||
|
fetched_urls.append(url)
|
||||||
|
return b"-----BEGIN RSA PRIVATE KEY-----\nTEST\n-----END RSA PRIVATE KEY-----\n"
|
||||||
|
|
||||||
|
rc = main(
|
||||||
|
["pair", "--fetch-ssh-key", "--ssh-key-path", str(ssh_dest)],
|
||||||
|
config_loader=lambda: _make_config(tmp_path),
|
||||||
|
connect_fn=fake_connect,
|
||||||
|
fetch_url=fake_fetch,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert rc == 0
|
||||||
|
assert fetched_urls == ["http://192.0.2.10:9991/webos_rsa"]
|
||||||
|
assert ssh_dest.read_bytes().startswith(b"-----BEGIN RSA PRIVATE KEY-----")
|
||||||
|
assert stat.S_IMODE(ssh_dest.stat().st_mode) == 0o600
|
||||||
|
|
||||||
|
|
||||||
|
def test_cli_pair_fetch_ssh_key_failure_preserves_client_key_and_exits_nonzero(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
key_file = tmp_path / ".client_key.json"
|
||||||
|
ssh_dest = tmp_path / "webos_rsa"
|
||||||
|
|
||||||
|
def on_send(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg: dict[str, Any] = json.loads(raw)
|
||||||
|
if msg.get("type") == "register":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "registered",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {"client-key": "tv-key-10"},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
async def fake_connect(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return FakeWebSocketTransport(on_send=on_send)
|
||||||
|
|
||||||
|
def failing_fetch(_url: str) -> bytes:
|
||||||
|
raise OSError("connection refused")
|
||||||
|
|
||||||
|
rc = main(
|
||||||
|
["pair", "--fetch-ssh-key", "--ssh-key-path", str(ssh_dest)],
|
||||||
|
config_loader=lambda: _make_config(tmp_path),
|
||||||
|
connect_fn=fake_connect,
|
||||||
|
fetch_url=failing_fetch,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert rc == 1
|
||||||
|
assert json.loads(key_file.read_text(encoding="utf-8")) == {"192.0.2.10": "tv-key-10"}
|
||||||
|
assert not ssh_dest.exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_cli_pair_returns_nonzero_on_websocket_handshake_error(
|
||||||
|
tmp_path: Path,
|
||||||
|
capsys: pytest.CaptureFixture[str],
|
||||||
|
) -> None:
|
||||||
|
async def failing_connect(_url: str) -> FakeWebSocketTransport:
|
||||||
|
raise InvalidMessage("did not receive a valid HTTP response")
|
||||||
|
|
||||||
|
rc = main(
|
||||||
|
["pair"],
|
||||||
|
config_loader=lambda: _make_config(tmp_path),
|
||||||
|
connect_fn=failing_connect,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert rc == 1
|
||||||
|
captured = capsys.readouterr()
|
||||||
|
assert "error: did not receive a valid HTTP response" in captured.err
|
||||||
@@ -22,6 +22,8 @@ def _clear_tv_env(monkeypatch: pytest.MonkeyPatch) -> None:
|
|||||||
"MCP_BEARER_TOKEN",
|
"MCP_BEARER_TOKEN",
|
||||||
"MAX_VOLUME",
|
"MAX_VOLUME",
|
||||||
"ENABLE_RAW_SSAP",
|
"ENABLE_RAW_SSAP",
|
||||||
|
"CAPTURE_MAX_WIDTH",
|
||||||
|
"CAPTURE_JPEG_QUALITY",
|
||||||
):
|
):
|
||||||
monkeypatch.delenv(key, raising=False)
|
monkeypatch.delenv(key, raising=False)
|
||||||
|
|
||||||
@@ -74,6 +76,8 @@ def test_load_config_uses_expected_defaults_when_optional_vars_unset(
|
|||||||
assert cfg.allowed_hosts == ()
|
assert cfg.allowed_hosts == ()
|
||||||
assert cfg.tv_mac is None
|
assert cfg.tv_mac is None
|
||||||
assert cfg.mcp_bearer_token is None
|
assert cfg.mcp_bearer_token is None
|
||||||
|
assert cfg.capture_max_width is None
|
||||||
|
assert cfg.capture_jpeg_quality is None
|
||||||
|
|
||||||
|
|
||||||
def test_dotenv_fallback_does_not_overwrite_existing_env(
|
def test_dotenv_fallback_does_not_overwrite_existing_env(
|
||||||
@@ -108,6 +112,12 @@ def test_dotenv_fallback_does_not_overwrite_existing_env(
|
|||||||
({"TV_IP": "192.0.2.10", "PORT": "0"}, "PORT"),
|
({"TV_IP": "192.0.2.10", "PORT": "0"}, "PORT"),
|
||||||
({"TV_IP": "192.0.2.10", "PORT": "65536"}, "PORT"),
|
({"TV_IP": "192.0.2.10", "PORT": "65536"}, "PORT"),
|
||||||
({"TV_IP": "192.0.2.10", "PORT": "abc"}, "PORT"),
|
({"TV_IP": "192.0.2.10", "PORT": "abc"}, "PORT"),
|
||||||
|
({"TV_IP": "192.0.2.10", "CAPTURE_MAX_WIDTH": "63"}, "CAPTURE_MAX_WIDTH"),
|
||||||
|
({"TV_IP": "192.0.2.10", "CAPTURE_MAX_WIDTH": "3841"}, "CAPTURE_MAX_WIDTH"),
|
||||||
|
({"TV_IP": "192.0.2.10", "CAPTURE_MAX_WIDTH": "wide"}, "CAPTURE_MAX_WIDTH"),
|
||||||
|
({"TV_IP": "192.0.2.10", "CAPTURE_JPEG_QUALITY": "0"}, "CAPTURE_JPEG_QUALITY"),
|
||||||
|
({"TV_IP": "192.0.2.10", "CAPTURE_JPEG_QUALITY": "96"}, "CAPTURE_JPEG_QUALITY"),
|
||||||
|
({"TV_IP": "192.0.2.10", "CAPTURE_JPEG_QUALITY": "high"}, "CAPTURE_JPEG_QUALITY"),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
def test_load_config_rejects_invalid_env_values_with_config_error(
|
def test_load_config_rejects_invalid_env_values_with_config_error(
|
||||||
@@ -136,6 +146,14 @@ def test_load_config_rejects_invalid_env_values_with_config_error(
|
|||||||
({"tv_ip": "192.0.2.10", "max_volume": 150}, "MAX_VOLUME"),
|
({"tv_ip": "192.0.2.10", "max_volume": 150}, "MAX_VOLUME"),
|
||||||
({"tv_ip": "192.0.2.10", "max_volume": 12.5}, "MAX_VOLUME"),
|
({"tv_ip": "192.0.2.10", "max_volume": 12.5}, "MAX_VOLUME"),
|
||||||
({"tv_ip": "192.0.2.10", "wol_broadcast": "bad-ip"}, "WOL_BROADCAST"),
|
({"tv_ip": "192.0.2.10", "wol_broadcast": "bad-ip"}, "WOL_BROADCAST"),
|
||||||
|
({"tv_ip": "192.0.2.10", "capture_max_width": 63}, "CAPTURE_MAX_WIDTH"),
|
||||||
|
({"tv_ip": "192.0.2.10", "capture_max_width": 3841}, "CAPTURE_MAX_WIDTH"),
|
||||||
|
({"tv_ip": "192.0.2.10", "capture_max_width": 1280.5}, "CAPTURE_MAX_WIDTH"),
|
||||||
|
({"tv_ip": "192.0.2.10", "capture_max_width": True}, "CAPTURE_MAX_WIDTH"),
|
||||||
|
({"tv_ip": "192.0.2.10", "capture_jpeg_quality": 0}, "CAPTURE_JPEG_QUALITY"),
|
||||||
|
({"tv_ip": "192.0.2.10", "capture_jpeg_quality": 96}, "CAPTURE_JPEG_QUALITY"),
|
||||||
|
({"tv_ip": "192.0.2.10", "capture_jpeg_quality": 75.5}, "CAPTURE_JPEG_QUALITY"),
|
||||||
|
({"tv_ip": "192.0.2.10", "capture_jpeg_quality": False}, "CAPTURE_JPEG_QUALITY"),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
def test_tv_config_rejects_invalid_direct_arguments_with_config_error(
|
def test_tv_config_rejects_invalid_direct_arguments_with_config_error(
|
||||||
@@ -210,3 +228,41 @@ def test_require_mac_returns_trimmed_value(monkeypatch: pytest.MonkeyPatch, tmp_
|
|||||||
|
|
||||||
cfg = load_config(env_path=tmp_path / "missing.env")
|
cfg = load_config(env_path=tmp_path / "missing.env")
|
||||||
assert require_mac(cfg) == "AA:BB:CC:DD:EE:FF"
|
assert require_mac(cfg) == "AA:BB:CC:DD:EE:FF"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("width_env", "quality_env", "expected_width", "expected_quality"),
|
||||||
|
[
|
||||||
|
("64", "1", 64, 1),
|
||||||
|
("3840", "95", 3840, 95),
|
||||||
|
(" 1280 ", " 75 ", 1280, 75),
|
||||||
|
("", " ", None, None),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_load_config_parses_capture_max_width_and_jpeg_quality(
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
tmp_path: Path,
|
||||||
|
width_env: str,
|
||||||
|
quality_env: str,
|
||||||
|
expected_width: int | None,
|
||||||
|
expected_quality: int | None,
|
||||||
|
) -> None:
|
||||||
|
_clear_tv_env(monkeypatch)
|
||||||
|
monkeypatch.setenv("TV_IP", "192.0.2.10")
|
||||||
|
monkeypatch.setenv("CAPTURE_MAX_WIDTH", width_env)
|
||||||
|
monkeypatch.setenv("CAPTURE_JPEG_QUALITY", quality_env)
|
||||||
|
|
||||||
|
cfg = load_config(env_path=tmp_path / "missing.env")
|
||||||
|
|
||||||
|
assert cfg.capture_max_width == expected_width
|
||||||
|
assert cfg.capture_jpeg_quality == expected_quality
|
||||||
|
|
||||||
|
|
||||||
|
def test_tv_config_accepts_explicit_none_and_valid_capture_bounds() -> None:
|
||||||
|
cfg_none = TvConfig(tv_ip="192.0.2.10", capture_max_width=None, capture_jpeg_quality=None)
|
||||||
|
assert cfg_none.capture_max_width is None
|
||||||
|
assert cfg_none.capture_jpeg_quality is None
|
||||||
|
|
||||||
|
cfg_bounds = TvConfig(tv_ip="192.0.2.10", capture_max_width=1280, capture_jpeg_quality=80)
|
||||||
|
assert cfg_bounds.capture_max_width == 1280
|
||||||
|
assert cfg_bounds.capture_jpeg_quality == 80
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
"""Unit tests verifying deploy/lg-smtv-mcp.service template and sandboxing directives."""
|
||||||
|
|
||||||
|
import configparser
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
SERVICE_TEMPLATE_PATH = Path(__file__).resolve().parent.parent / "deploy" / "lg-smtv-mcp.service"
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_service_template(content: str) -> configparser.ConfigParser:
|
||||||
|
"""Parse a systemd unit file while stripping comments and preserving empty values."""
|
||||||
|
parser = configparser.ConfigParser(
|
||||||
|
comment_prefixes=("#", ";"),
|
||||||
|
inline_comment_prefixes=None,
|
||||||
|
strict=False,
|
||||||
|
allow_no_value=True,
|
||||||
|
)
|
||||||
|
parser.read_string(content)
|
||||||
|
return parser
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def systemd_analyze_bin() -> str:
|
||||||
|
binary = shutil.which("systemd-analyze")
|
||||||
|
if not binary:
|
||||||
|
pytest.fail("systemd-analyze not found in PATH; ensure pkgs.systemd is in testTools")
|
||||||
|
return binary
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def substituted_service_file(tmp_path: Path, systemd_analyze_bin: str) -> Path:
|
||||||
|
content = SERVICE_TEMPLATE_PATH.read_text(encoding="utf-8")
|
||||||
|
workdir = tmp_path / "workdir"
|
||||||
|
workdir.mkdir()
|
||||||
|
# Use neutral non-personal values derived from tmp_path (CR-02)
|
||||||
|
substituted = (
|
||||||
|
content.replace("<User>", "testuser")
|
||||||
|
.replace("<WorkingDirectory>", str(workdir))
|
||||||
|
.replace("<NixBinDir>", str(Path(systemd_analyze_bin).parent))
|
||||||
|
)
|
||||||
|
test_unit_file = tmp_path / "lg-smtv-mcp.service"
|
||||||
|
test_unit_file.write_text(substituted, encoding="utf-8")
|
||||||
|
return test_unit_file
|
||||||
|
|
||||||
|
|
||||||
|
def test_service_template_exists():
|
||||||
|
assert SERVICE_TEMPLATE_PATH.is_file(), f"Template missing at {SERVICE_TEMPLATE_PATH}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_service_template_declares_deployment_placeholders():
|
||||||
|
content = SERVICE_TEMPLATE_PATH.read_text(encoding="utf-8")
|
||||||
|
assert "<User>" in content
|
||||||
|
assert "<WorkingDirectory>" in content
|
||||||
|
assert "<NixBinDir>" in content
|
||||||
|
|
||||||
|
|
||||||
|
def test_service_template_bounds_restart_limit_in_unit_section():
|
||||||
|
content = SERVICE_TEMPLATE_PATH.read_text(encoding="utf-8")
|
||||||
|
parser = _parse_service_template(content)
|
||||||
|
|
||||||
|
assert "Unit" in parser, "Missing [Unit] section in service template"
|
||||||
|
unit_section = parser["Unit"]
|
||||||
|
# CR-01: Assert exact keys and values in [Unit], not substring matches
|
||||||
|
assert unit_section.get("startlimitintervalsec") == "60s"
|
||||||
|
assert unit_section.get("startlimitburst") == "5"
|
||||||
|
|
||||||
|
|
||||||
|
def test_service_template_enables_sandboxing_baseline_in_service_section():
|
||||||
|
content = SERVICE_TEMPLATE_PATH.read_text(encoding="utf-8")
|
||||||
|
parser = _parse_service_template(content)
|
||||||
|
|
||||||
|
assert "Service" in parser, "Missing [Service] section in service template"
|
||||||
|
service_section = parser["Service"]
|
||||||
|
|
||||||
|
# CR-01: Section-aware exact-value checks; comments stripped, CapabilityBoundingSet="" enforced
|
||||||
|
assert service_section.get("nonewprivileges") == "yes"
|
||||||
|
assert service_section.get("privatetmp") == "yes"
|
||||||
|
assert service_section.get("umask") == "0077"
|
||||||
|
assert service_section.get("protectsystem") == "full"
|
||||||
|
assert service_section.get("capabilityboundingset") == ""
|
||||||
|
assert service_section.get("protectcontrolgroups") == "yes"
|
||||||
|
assert service_section.get("protectkernelmodules") == "yes"
|
||||||
|
assert service_section.get("protectkerneltunables") == "yes"
|
||||||
|
assert service_section.get("protectkernellogs") == "yes"
|
||||||
|
assert service_section.get("protectclock") == "yes"
|
||||||
|
assert service_section.get("protecthostname") == "yes"
|
||||||
|
assert service_section.get("restrictrealtime") == "yes"
|
||||||
|
assert service_section.get("restrictsuidsgid") == "yes"
|
||||||
|
assert service_section.get("lockpersonality") == "yes"
|
||||||
|
|
||||||
|
|
||||||
|
def test_systemd_analyze_verify_succeeds_on_substituted_template(
|
||||||
|
systemd_analyze_bin: str, substituted_service_file: Path
|
||||||
|
):
|
||||||
|
cmd = [systemd_analyze_bin, "verify", str(substituted_service_file)]
|
||||||
|
# CR-04: Subprocess timeout prevents CI hang
|
||||||
|
res = subprocess.run(cmd, capture_output=True, text=True, timeout=30.0)
|
||||||
|
|
||||||
|
# CR-01: Fail on warnings such as 'Unknown key' or 'Unknown lvalue' that exit 0
|
||||||
|
assert "Unknown key" not in res.stderr, f"Unknown key in template: {res.stderr}"
|
||||||
|
assert "Unknown lvalue" not in res.stderr, f"Unknown lvalue in template: {res.stderr}"
|
||||||
|
assert res.returncode == 0, f"systemd-analyze verify failed: {res.stderr}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_systemd_analyze_security_reports_ok_exposure_bracket(
|
||||||
|
systemd_analyze_bin: str, substituted_service_file: Path
|
||||||
|
):
|
||||||
|
cmd = [systemd_analyze_bin, "--offline=yes", "security", str(substituted_service_file)]
|
||||||
|
# CR-04: Subprocess timeout prevents CI hang
|
||||||
|
res = subprocess.run(cmd, capture_output=True, text=True, timeout=30.0)
|
||||||
|
assert res.returncode == 0, f"systemd-analyze security failed: {res.stderr}"
|
||||||
|
|
||||||
|
# CR-05: Regex-parse the numeric exposure score and assert it satisfies the OK bracket (<= 5.0)
|
||||||
|
lines = [line for line in res.stdout.splitlines() if "Overall exposure level" in line]
|
||||||
|
assert lines, "No exposure level reported by systemd-analyze security"
|
||||||
|
score_line = lines[0]
|
||||||
|
|
||||||
|
match = re.search(r"Overall exposure level.*:\s*([0-9]+\.[0-9]+)\s+OK", score_line)
|
||||||
|
assert match is not None, f"Could not parse numeric score and OK status from: {score_line}"
|
||||||
|
|
||||||
|
score = float(match.group(1))
|
||||||
|
assert score <= 5.0, f"Exposure score {score} exceeds OK bracket threshold 5.0"
|
||||||
@@ -0,0 +1,314 @@
|
|||||||
|
"""End-to-end MVP lifecycle test over in-process Streamable HTTP MCP ClientSession."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
from collections.abc import MutableMapping
|
||||||
|
from contextlib import suppress
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, cast
|
||||||
|
|
||||||
|
import httpx2
|
||||||
|
from mcp import ClientSession
|
||||||
|
from mcp.client.streamable_http import streamable_http_client
|
||||||
|
from mcp.types import TextContent
|
||||||
|
|
||||||
|
from lg_smtv_mcp.config import TvConfig
|
||||||
|
from lg_smtv_mcp.server import create_http_app
|
||||||
|
from lg_smtv_mcp.tv_core import TvManager
|
||||||
|
from tests.conftest import FakeWebSocketTransport
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_json_text(content: list[Any]) -> dict[str, Any]:
|
||||||
|
assert content, "Expected non-empty tool content"
|
||||||
|
first = content[0]
|
||||||
|
assert isinstance(first, TextContent)
|
||||||
|
parsed: Any = json.loads(first.text)
|
||||||
|
assert isinstance(parsed, dict)
|
||||||
|
return cast(dict[str, Any], parsed)
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_error_text(content: list[Any]) -> str:
|
||||||
|
return " ".join(item.text for item in content if isinstance(item, TextContent))
|
||||||
|
|
||||||
|
|
||||||
|
def _build_online_ssap(
|
||||||
|
tv_ip: str,
|
||||||
|
sent_requests: list[tuple[str, dict[str, Any]]],
|
||||||
|
) -> FakeWebSocketTransport:
|
||||||
|
def on_send(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg: dict[str, Any] = json.loads(raw)
|
||||||
|
msg_type = msg.get("type")
|
||||||
|
msg_id = msg.get("id")
|
||||||
|
if msg_type == "register":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "registered",
|
||||||
|
"id": msg_id,
|
||||||
|
"payload": {"client-key": "e2e-saved-key"},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return
|
||||||
|
if msg_type == "subscribe":
|
||||||
|
uri = str(msg.get("uri", ""))
|
||||||
|
if uri == "ssap://audio/getStatus":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg_id,
|
||||||
|
"payload": {
|
||||||
|
"subscribed": True,
|
||||||
|
"volume": 10,
|
||||||
|
"mute": False,
|
||||||
|
"volumeStatus": {"soundOutput": "tv_speaker"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return
|
||||||
|
if uri == "ssap://com.webos.applicationManager/getForegroundAppInfo":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg_id,
|
||||||
|
"payload": {
|
||||||
|
"subscribed": True,
|
||||||
|
"appId": "com.webos.app.home",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return
|
||||||
|
ws.push_json({"type": "response", "id": msg_id, "payload": {"subscribed": True}})
|
||||||
|
return
|
||||||
|
if msg_type == "request":
|
||||||
|
uri = str(msg.get("uri", ""))
|
||||||
|
if uri == "ssap://com.webos.service.networkinput/getPointerInputSocket":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg_id,
|
||||||
|
"payload": {
|
||||||
|
"returnValue": True,
|
||||||
|
"socketPath": f"ws://{tv_ip}:3000/pointer",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return
|
||||||
|
payload_in = dict(msg.get("payload") or {})
|
||||||
|
sent_requests.append((uri, payload_in))
|
||||||
|
ws.push_json({"type": "response", "id": msg_id, "payload": {"returnValue": True}})
|
||||||
|
|
||||||
|
return FakeWebSocketTransport(on_send=on_send)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_e2e_mvp_lifecycle_from_standby_through_clean_shutdown(tmp_path: Path) -> None:
|
||||||
|
tasks_before = set(asyncio.all_tasks())
|
||||||
|
|
||||||
|
tv_ip = "192.0.2.42"
|
||||||
|
tv_mac = "AA:BB:CC:DD:EE:FF"
|
||||||
|
bearer_token = "e2e-test-bearer-token"
|
||||||
|
key_file = tmp_path / ".client_key.json"
|
||||||
|
key_file.write_text(json.dumps({tv_ip: "e2e-saved-key"}), encoding="utf-8")
|
||||||
|
|
||||||
|
config = TvConfig(
|
||||||
|
tv_ip=tv_ip,
|
||||||
|
tv_mac=tv_mac,
|
||||||
|
client_key_path=key_file,
|
||||||
|
mcp_bearer_token=bearer_token,
|
||||||
|
max_volume=40,
|
||||||
|
)
|
||||||
|
|
||||||
|
tv_awake = False
|
||||||
|
wol_calls: list[tuple[str, str, int]] = []
|
||||||
|
sent_requests: list[tuple[str, dict[str, Any]]] = []
|
||||||
|
standby_backoff_entered = asyncio.Event()
|
||||||
|
turn_off_completed = asyncio.Event()
|
||||||
|
post_turn_off_standby_entered = asyncio.Event()
|
||||||
|
pointer_ws = FakeWebSocketTransport()
|
||||||
|
online_ssap_connections: list[FakeWebSocketTransport] = []
|
||||||
|
|
||||||
|
def fake_send_wol(mac: str, broadcast_addr: str, port: int) -> None:
|
||||||
|
nonlocal tv_awake
|
||||||
|
wol_calls.append((mac, broadcast_addr, port))
|
||||||
|
tv_awake = True
|
||||||
|
|
||||||
|
async def fake_wait_fn(event: asyncio.Event, timeout: float) -> None:
|
||||||
|
if turn_off_completed.is_set():
|
||||||
|
post_turn_off_standby_entered.set()
|
||||||
|
else:
|
||||||
|
standby_backoff_entered.set()
|
||||||
|
with suppress(TimeoutError):
|
||||||
|
await asyncio.wait_for(event.wait(), timeout=timeout)
|
||||||
|
|
||||||
|
async def connect_fn(url: str) -> FakeWebSocketTransport:
|
||||||
|
if url.endswith("/pointer"):
|
||||||
|
return pointer_ws
|
||||||
|
if not tv_awake:
|
||||||
|
standby_ws = FakeWebSocketTransport()
|
||||||
|
standby_ws.push_close(1008, "Try Again Later (EWS)")
|
||||||
|
return standby_ws
|
||||||
|
online_ws = _build_online_ssap(tv_ip, sent_requests)
|
||||||
|
online_ssap_connections.append(online_ws)
|
||||||
|
return online_ws
|
||||||
|
|
||||||
|
manager = TvManager(
|
||||||
|
config,
|
||||||
|
connect_fn=connect_fn,
|
||||||
|
wol_fn=fake_send_wol,
|
||||||
|
backoff_steps=(10.0,),
|
||||||
|
wake_poll_interval=0.01,
|
||||||
|
wait_fn=fake_wait_fn,
|
||||||
|
)
|
||||||
|
app = create_http_app(config, manager=manager)
|
||||||
|
|
||||||
|
incoming: list[MutableMapping[str, Any]] = [
|
||||||
|
{"type": "lifespan.startup"},
|
||||||
|
{"type": "lifespan.shutdown"},
|
||||||
|
]
|
||||||
|
startup_done = asyncio.Event()
|
||||||
|
allow_shutdown = asyncio.Event()
|
||||||
|
|
||||||
|
async def receive() -> MutableMapping[str, Any]:
|
||||||
|
if incoming[0]["type"] == "lifespan.shutdown":
|
||||||
|
await allow_shutdown.wait()
|
||||||
|
return incoming.pop(0)
|
||||||
|
|
||||||
|
startup_error: list[str] = []
|
||||||
|
|
||||||
|
async def send(msg: MutableMapping[str, Any]) -> None:
|
||||||
|
if msg["type"] == "lifespan.startup.complete":
|
||||||
|
startup_done.set()
|
||||||
|
elif msg["type"] == "lifespan.startup.failed":
|
||||||
|
startup_error.append(str(msg.get("message", "ASGI startup failed")))
|
||||||
|
startup_done.set()
|
||||||
|
|
||||||
|
async def _run_lifespan() -> None:
|
||||||
|
await app({"type": "lifespan"}, receive, send)
|
||||||
|
|
||||||
|
lifespan_task: asyncio.Task[None] = asyncio.create_task(_run_lifespan())
|
||||||
|
try:
|
||||||
|
startup_wait_task = asyncio.create_task(startup_done.wait())
|
||||||
|
try:
|
||||||
|
done, _ = await asyncio.wait(
|
||||||
|
{startup_wait_task, lifespan_task},
|
||||||
|
timeout=2.0,
|
||||||
|
return_when=asyncio.FIRST_COMPLETED,
|
||||||
|
)
|
||||||
|
assert done, "ASGI lifespan startup did not finish within 2.0s"
|
||||||
|
if lifespan_task in done:
|
||||||
|
await lifespan_task
|
||||||
|
raise AssertionError("ASGI lifespan exited before startup completed")
|
||||||
|
assert not startup_error, f"ASGI startup failed: {startup_error[0]}"
|
||||||
|
finally:
|
||||||
|
if not startup_wait_task.done():
|
||||||
|
startup_wait_task.cancel()
|
||||||
|
with suppress(asyncio.CancelledError):
|
||||||
|
await startup_wait_task
|
||||||
|
await asyncio.wait_for(standby_backoff_entered.wait(), timeout=2.0)
|
||||||
|
|
||||||
|
transport = httpx2.ASGITransport(app=app)
|
||||||
|
async with (
|
||||||
|
httpx2.AsyncClient(
|
||||||
|
transport=transport,
|
||||||
|
base_url="http://127.0.0.1:8765",
|
||||||
|
headers={"Authorization": f"Bearer {bearer_token}"},
|
||||||
|
) as http_client,
|
||||||
|
streamable_http_client(
|
||||||
|
"http://127.0.0.1:8765/mcp",
|
||||||
|
http_client=http_client,
|
||||||
|
) as (read_stream, write_stream),
|
||||||
|
ClientSession(read_stream, write_stream) as session,
|
||||||
|
):
|
||||||
|
await session.initialize()
|
||||||
|
|
||||||
|
# 1. Standby (1008): launch fails fast with TV_OFFLINE_STANDBY and no implicit WoL.
|
||||||
|
standby_launch = await session.call_tool(
|
||||||
|
"launch",
|
||||||
|
{"app_id": "youtube.leanback.v4"},
|
||||||
|
)
|
||||||
|
assert standby_launch.is_error is True
|
||||||
|
assert "TV_OFFLINE_STANDBY" in _extract_error_text(standby_launch.content)
|
||||||
|
assert wol_calls == []
|
||||||
|
|
||||||
|
# 2. tv_wake: sends WoL magic packet, connects, and subscribes.
|
||||||
|
wake_res = await session.call_tool("tv_wake", {})
|
||||||
|
assert wake_res.is_error is False
|
||||||
|
wake_payload = _extract_json_text(wake_res.content)
|
||||||
|
assert wake_payload["status"] == "connected"
|
||||||
|
assert isinstance(wake_payload["elapsed_ms"], int) and wake_payload["elapsed_ms"] >= 0
|
||||||
|
assert wol_calls == [(tv_mac, "255.255.255.255", 9)]
|
||||||
|
|
||||||
|
# 3. get_state: returns connected, fresh subscribed state.
|
||||||
|
state_res = await session.call_tool("get_state", {})
|
||||||
|
assert state_res.is_error is False
|
||||||
|
state_payload = _extract_json_text(state_res.content)
|
||||||
|
assert state_payload["connected"] is True
|
||||||
|
assert state_payload["stale"] is False
|
||||||
|
assert state_payload["volume"] == 10
|
||||||
|
assert state_payload["muted"] is False
|
||||||
|
assert state_payload["sound_output"] == "tv_speaker"
|
||||||
|
assert state_payload["foreground_app"] == "com.webos.app.home"
|
||||||
|
|
||||||
|
# 4. launch with content_target: forwards params.contentTarget.
|
||||||
|
launch_res = await session.call_tool(
|
||||||
|
"launch",
|
||||||
|
{
|
||||||
|
"app_id": "youtube.leanback.v4",
|
||||||
|
"content_target": "v=dQw4w9WgXcQ",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert launch_res.is_error is False
|
||||||
|
assert (
|
||||||
|
"ssap://system.launcher/launch",
|
||||||
|
{
|
||||||
|
"id": "youtube.leanback.v4",
|
||||||
|
"params": {"contentTarget": "v=dQw4w9WgXcQ"},
|
||||||
|
},
|
||||||
|
) in sent_requests
|
||||||
|
|
||||||
|
# 5. Batched keys: acquires pointer socket and sends both button frames.
|
||||||
|
keys_res = await session.call_tool(
|
||||||
|
"keys",
|
||||||
|
{"keys": ["DOWN", "ENTER"], "delay_ms": 0, "settle_ms": 0},
|
||||||
|
)
|
||||||
|
assert keys_res.is_error is False
|
||||||
|
keys_payload = _extract_json_text(keys_res.content)
|
||||||
|
assert keys_payload == {"keys_sent": True, "count": 2}
|
||||||
|
assert pointer_ws.sent == [
|
||||||
|
"type:button\nname:DOWN\n\n",
|
||||||
|
"type:button\nname:ENTER\n\n",
|
||||||
|
]
|
||||||
|
|
||||||
|
# 6. set_volume(15): sends {"volume": 15}.
|
||||||
|
vol_res = await session.call_tool("set_volume", {"level": 15})
|
||||||
|
assert vol_res.is_error is False
|
||||||
|
assert ("ssap://audio/setVolume", {"volume": 15}) in sent_requests
|
||||||
|
|
||||||
|
# 7. turn_off(): sends ssap://system/turnOff.
|
||||||
|
off_res = await session.call_tool("turn_off", {})
|
||||||
|
assert off_res.is_error is False
|
||||||
|
assert ("ssap://system/turnOff", {}) in sent_requests
|
||||||
|
turn_off_completed.set()
|
||||||
|
online_ssap_connections[-1].push_close(1008, "Try Again Later (EWS)")
|
||||||
|
await asyncio.wait_for(post_turn_off_standby_entered.wait(), timeout=2.0)
|
||||||
|
|
||||||
|
# 8. Standby (1008) after turn_off: get_state returns cached stale values.
|
||||||
|
stale_state_res = await session.call_tool("get_state", {})
|
||||||
|
assert stale_state_res.is_error is False
|
||||||
|
stale_state_payload = _extract_json_text(stale_state_res.content)
|
||||||
|
assert stale_state_payload["connected"] is False
|
||||||
|
assert stale_state_payload["stale"] is True
|
||||||
|
assert stale_state_payload["volume"] == 10
|
||||||
|
assert stale_state_payload["muted"] is False
|
||||||
|
assert stale_state_payload["sound_output"] == "tv_speaker"
|
||||||
|
assert stale_state_payload["foreground_app"] == "com.webos.app.home"
|
||||||
|
finally:
|
||||||
|
# 9. Clean ASGI lifespan shutdown with zero orphaned asyncio tasks.
|
||||||
|
allow_shutdown.set()
|
||||||
|
await asyncio.wait_for(lifespan_task, timeout=2.0)
|
||||||
|
|
||||||
|
# sse_starlette spawns one per-loop _shutdown_watcher() singleton polling AppStatus.should_exit.
|
||||||
|
orphaned_tasks = [
|
||||||
|
task
|
||||||
|
for task in (asyncio.all_tasks() - tasks_before)
|
||||||
|
if getattr(task.get_coro(), "__qualname__", None) != "_shutdown_watcher"
|
||||||
|
]
|
||||||
|
assert orphaned_tasks == []
|
||||||
@@ -0,0 +1,810 @@
|
|||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
from collections.abc import AsyncGenerator, Awaitable, Callable
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from lg_smtv_mcp.config import TvConfig
|
||||||
|
from lg_smtv_mcp.errors import ErrorCode, TvError
|
||||||
|
from lg_smtv_mcp.tv_core.manager import ConnectionState, TvManager
|
||||||
|
from lg_smtv_mcp.tv_core.protocols import CaptureResult, WebSocketClosedError
|
||||||
|
from tests.conftest import FakeWebSocketTransport
|
||||||
|
|
||||||
|
POINTER_URL = "wss://192.0.2.10:3001/ptr"
|
||||||
|
|
||||||
|
|
||||||
|
def _make_config(tmp_path: Path, **overrides: Any) -> TvConfig:
|
||||||
|
key_path = tmp_path / ".client_key.json"
|
||||||
|
if "client_key_path" not in overrides:
|
||||||
|
key_path.write_text(json.dumps({"192.0.2.10": "saved-key"}), encoding="utf-8")
|
||||||
|
defaults: dict[str, Any] = {
|
||||||
|
"tv_ip": "192.0.2.10",
|
||||||
|
"tv_mac": "00:11:22:33:44:55",
|
||||||
|
"client_key_path": key_path,
|
||||||
|
"max_volume": 40,
|
||||||
|
}
|
||||||
|
defaults.update(overrides)
|
||||||
|
return TvConfig(**defaults)
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeCapturer:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
error: TvError | None = None,
|
||||||
|
gate: asyncio.Event | None = None,
|
||||||
|
) -> None:
|
||||||
|
self.closed_count = 0
|
||||||
|
self.error = error
|
||||||
|
self.gate = gate
|
||||||
|
self.calls = 0
|
||||||
|
|
||||||
|
async def capture_frame(
|
||||||
|
self,
|
||||||
|
ssap_request_fn: Callable[[str, dict[str, Any]], Awaitable[dict[str, Any]]],
|
||||||
|
) -> CaptureResult:
|
||||||
|
_ = ssap_request_fn
|
||||||
|
self.calls += 1
|
||||||
|
if self.gate is not None:
|
||||||
|
await self.gate.wait()
|
||||||
|
if self.error is not None:
|
||||||
|
raise self.error
|
||||||
|
return CaptureResult(
|
||||||
|
image_bytes=b"\xff\xd8\xff\xe0",
|
||||||
|
frame_sha256="deadbeef",
|
||||||
|
changed_since_last=True,
|
||||||
|
size_bytes=4,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def close(self) -> None:
|
||||||
|
self.closed_count += 1
|
||||||
|
|
||||||
|
|
||||||
|
def _make_online_transport(
|
||||||
|
*,
|
||||||
|
volume: int = 22,
|
||||||
|
mute: bool = False,
|
||||||
|
sound_output: str = "tv_speaker",
|
||||||
|
app_id: str = "com.webos.app.livetv",
|
||||||
|
on_request: Callable[[dict[str, Any], FakeWebSocketTransport], None] | None = None,
|
||||||
|
) -> FakeWebSocketTransport:
|
||||||
|
def on_send(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg = json.loads(raw)
|
||||||
|
msg_type = msg.get("type")
|
||||||
|
if msg_type == "register":
|
||||||
|
ws.push_json({"type": "registered", "id": msg["id"], "payload": {"client-key": "k"}})
|
||||||
|
elif msg_type == "subscribe":
|
||||||
|
uri = msg["uri"]
|
||||||
|
if uri == "ssap://audio/getStatus":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {
|
||||||
|
"returnValue": True,
|
||||||
|
"subscribed": True,
|
||||||
|
"volume": volume,
|
||||||
|
"mute": mute,
|
||||||
|
"volumeStatus": {"soundOutput": sound_output},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
elif uri == "ssap://com.webos.applicationManager/getForegroundAppInfo":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {
|
||||||
|
"returnValue": True,
|
||||||
|
"subscribed": True,
|
||||||
|
"appId": app_id,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
elif msg_type == "request" and on_request is not None:
|
||||||
|
on_request(msg, ws)
|
||||||
|
|
||||||
|
return FakeWebSocketTransport(on_send=on_send)
|
||||||
|
|
||||||
|
|
||||||
|
def _standby_transport() -> FakeWebSocketTransport:
|
||||||
|
ws = FakeWebSocketTransport()
|
||||||
|
ws.push_close(1008, "Try Again Later (EWS)")
|
||||||
|
return ws
|
||||||
|
|
||||||
|
|
||||||
|
def _pointer_socket_reply(msg: dict[str, Any], ws: FakeWebSocketTransport) -> None:
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {"returnValue": True, "socketPath": POINTER_URL},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _noop_wol(_mac: str, _broadcast: str, _port: int) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
async def _wait_for(predicate: Callable[[], bool], what: str, timeout: float = 2.0) -> None:
|
||||||
|
"""Poll predicate until true; fail loudly (instead of silently continuing) on timeout."""
|
||||||
|
try:
|
||||||
|
async with asyncio.timeout(timeout):
|
||||||
|
while not predicate():
|
||||||
|
await asyncio.sleep(0.005)
|
||||||
|
except TimeoutError:
|
||||||
|
pytest.fail(f"timed out after {timeout}s waiting for {what}")
|
||||||
|
|
||||||
|
|
||||||
|
async def _wait_for_state(mgr: TvManager, state: ConnectionState) -> None:
|
||||||
|
await _wait_for(lambda: mgr.state is state, f"ConnectionState.{state.value}")
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def _started(
|
||||||
|
mgr: TvManager,
|
||||||
|
*,
|
||||||
|
until: ConnectionState | None = ConnectionState.CONNECTED,
|
||||||
|
) -> AsyncGenerator[TvManager]:
|
||||||
|
"""Start mgr, optionally wait for a state, and always close it (even if a test fails)."""
|
||||||
|
await mgr.start()
|
||||||
|
try:
|
||||||
|
if until is not None:
|
||||||
|
await _wait_for_state(mgr, until)
|
||||||
|
yield mgr
|
||||||
|
finally:
|
||||||
|
await mgr.close()
|
||||||
|
|
||||||
|
|
||||||
|
# --- Connection lifecycle ---------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_uses_stepped_reconnect_backoff_and_tears_down_capture_on_standby(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
capturer = _FakeCapturer()
|
||||||
|
waits: list[float] = []
|
||||||
|
|
||||||
|
async def fake_wait(_event: asyncio.Event, timeout: float) -> None:
|
||||||
|
waits.append(timeout)
|
||||||
|
await asyncio.sleep(0)
|
||||||
|
|
||||||
|
async def connect_standby(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return _standby_transport()
|
||||||
|
|
||||||
|
mgr = TvManager(
|
||||||
|
_make_config(tmp_path),
|
||||||
|
connect_fn=connect_standby,
|
||||||
|
capture_client=capturer,
|
||||||
|
backoff_steps=(2.0, 5.0, 15.0, 30.0),
|
||||||
|
wait_fn=fake_wait,
|
||||||
|
)
|
||||||
|
async with _started(mgr, until=None):
|
||||||
|
await _wait_for(lambda: len(waits) >= 5, "5 backoff waits")
|
||||||
|
|
||||||
|
assert mgr.state is ConnectionState.STANDBY_OFFLINE
|
||||||
|
assert waits[:5] == [2.0, 5.0, 15.0, 30.0, 30.0]
|
||||||
|
assert capturer.closed_count >= 1
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_wake_coalesces_concurrent_calls_into_single_wol_packet(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
wol_calls: list[tuple[str, str, int]] = []
|
||||||
|
online = False
|
||||||
|
|
||||||
|
def fake_wol(mac: str, broadcast: str, port: int) -> None:
|
||||||
|
wol_calls.append((mac, broadcast, port))
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return _make_online_transport() if online else _standby_transport()
|
||||||
|
|
||||||
|
mgr = TvManager(
|
||||||
|
_make_config(tmp_path),
|
||||||
|
connect_fn=connect_fn,
|
||||||
|
wol_fn=fake_wol,
|
||||||
|
backoff_steps=(10.0,),
|
||||||
|
wake_poll_interval=0.01,
|
||||||
|
wake_timeout=2.0,
|
||||||
|
)
|
||||||
|
async with _started(mgr, until=ConnectionState.STANDBY_OFFLINE):
|
||||||
|
|
||||||
|
async def flip_online() -> None:
|
||||||
|
nonlocal online
|
||||||
|
await asyncio.sleep(0.03)
|
||||||
|
online = True
|
||||||
|
|
||||||
|
flipper = asyncio.create_task(flip_online())
|
||||||
|
res1, res2 = await asyncio.gather(mgr.wake(), mgr.wake())
|
||||||
|
await flipper
|
||||||
|
|
||||||
|
assert len(wol_calls) == 1
|
||||||
|
assert res1.status == "connected"
|
||||||
|
assert res2.status == "connected"
|
||||||
|
assert mgr.state is ConnectionState.CONNECTED
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_wake_returns_already_connected_without_sending_wol(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
wol_calls: list[tuple[str, str, int]] = []
|
||||||
|
|
||||||
|
def fake_wol(mac: str, broadcast: str, port: int) -> None:
|
||||||
|
wol_calls.append((mac, broadcast, port))
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return _make_online_transport()
|
||||||
|
|
||||||
|
mgr = TvManager(
|
||||||
|
_make_config(tmp_path), connect_fn=connect_fn, wol_fn=fake_wol, backoff_steps=(10.0,)
|
||||||
|
)
|
||||||
|
async with _started(mgr):
|
||||||
|
already = await mgr.wake()
|
||||||
|
|
||||||
|
assert already.status == "already_connected"
|
||||||
|
assert already.elapsed_ms == 0
|
||||||
|
assert wol_calls == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_wake_fails_fast_with_pairing_required_when_unpaired(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
def on_send_prompt(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg = json.loads(raw)
|
||||||
|
if msg["type"] == "register":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {"pairingType": "PROMPT", "returnValue": True},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
async def connect_prompt(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return FakeWebSocketTransport(on_send=on_send_prompt)
|
||||||
|
|
||||||
|
mgr = TvManager(
|
||||||
|
_make_config(tmp_path), connect_fn=connect_prompt, wol_fn=_noop_wol, backoff_steps=(10.0,)
|
||||||
|
)
|
||||||
|
async with _started(mgr, until=ConnectionState.PAIRING_REQUIRED):
|
||||||
|
with pytest.raises(TvError) as exc_pair:
|
||||||
|
await mgr.wake()
|
||||||
|
|
||||||
|
assert exc_pair.value.code is ErrorCode.PAIRING_REQUIRED
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_wake_raises_wake_timeout_when_tv_never_comes_online(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
async def connect_standby(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return _standby_transport()
|
||||||
|
|
||||||
|
mgr = TvManager(
|
||||||
|
_make_config(tmp_path),
|
||||||
|
connect_fn=connect_standby,
|
||||||
|
wol_fn=_noop_wol,
|
||||||
|
backoff_steps=(10.0,),
|
||||||
|
wake_poll_interval=0.01,
|
||||||
|
wake_timeout=0.05,
|
||||||
|
)
|
||||||
|
async with _started(mgr, until=ConnectionState.STANDBY_OFFLINE):
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await mgr.wake()
|
||||||
|
assert exc_info.value.code is ErrorCode.WAKE_TIMEOUT
|
||||||
|
assert mgr.state is ConnectionState.STANDBY_OFFLINE
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_reloads_client_key_on_sighup_and_stays_in_pairing_on_bad_json(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
key_path = tmp_path / ".client_key.json"
|
||||||
|
key_path.write_text("{not valid json", encoding="utf-8")
|
||||||
|
cfg = _make_config(tmp_path, client_key_path=key_path)
|
||||||
|
|
||||||
|
def on_send_check_key(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg = json.loads(raw)
|
||||||
|
if msg["type"] == "register":
|
||||||
|
if msg["payload"].get("client-key") == "fresh-key":
|
||||||
|
ws.push_json(
|
||||||
|
{"type": "registered", "id": msg["id"], "payload": {"client-key": "fresh-key"}}
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {"pairingType": "PROMPT", "returnValue": True},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
elif msg["type"] == "subscribe":
|
||||||
|
ws.push_json(
|
||||||
|
{"type": "response", "id": msg["id"], "payload": {"returnValue": True, "volume": 1}}
|
||||||
|
)
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return FakeWebSocketTransport(on_send=on_send_check_key)
|
||||||
|
|
||||||
|
mgr = TvManager(cfg, connect_fn=connect_fn, backoff_steps=(10.0,))
|
||||||
|
async with _started(mgr, until=ConnectionState.PAIRING_REQUIRED):
|
||||||
|
# Reload with malformed JSON stays in PAIRING_REQUIRED (absence check: short grace period).
|
||||||
|
mgr.reload_client_key()
|
||||||
|
await asyncio.sleep(0.02)
|
||||||
|
assert mgr.state is ConnectionState.PAIRING_REQUIRED
|
||||||
|
|
||||||
|
# Write valid JSON and reload -> transitions to CONNECTED.
|
||||||
|
key_path.write_text(json.dumps({"192.0.2.10": "fresh-key"}), encoding="utf-8")
|
||||||
|
mgr.reload_client_key()
|
||||||
|
await _wait_for(lambda: mgr.get_state().connected, "connected after key reload")
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_caches_subscribe_state_and_returns_lock_free_offline_snapshot(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
transport = _make_online_transport(
|
||||||
|
volume=27,
|
||||||
|
mute=True,
|
||||||
|
sound_output="external_arc",
|
||||||
|
app_id="netflix",
|
||||||
|
)
|
||||||
|
connects = 0
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
nonlocal connects
|
||||||
|
connects += 1
|
||||||
|
return transport if connects == 1 else _standby_transport()
|
||||||
|
|
||||||
|
mgr = TvManager(_make_config(tmp_path), connect_fn=connect_fn, backoff_steps=(10.0,))
|
||||||
|
async with _started(mgr):
|
||||||
|
snap_online = mgr.get_state()
|
||||||
|
assert snap_online.connected is True
|
||||||
|
assert snap_online.stale is False
|
||||||
|
assert snap_online.volume == 27
|
||||||
|
assert snap_online.muted is True
|
||||||
|
assert snap_online.sound_output == "external_arc"
|
||||||
|
assert snap_online.foreground_app == "netflix"
|
||||||
|
assert snap_online.last_updated is not None
|
||||||
|
|
||||||
|
# Drop connection and verify cached values remain available offline.
|
||||||
|
transport.push_error(WebSocketClosedError(1008, "Try Again Later (EWS)"))
|
||||||
|
await _wait_for_state(mgr, ConnectionState.STANDBY_OFFLINE)
|
||||||
|
|
||||||
|
snap_offline = mgr.get_state()
|
||||||
|
assert snap_offline.connected is False
|
||||||
|
assert snap_offline.stale is True
|
||||||
|
assert snap_offline.volume == 27
|
||||||
|
assert snap_offline.sound_output == "external_arc"
|
||||||
|
assert snap_offline.foreground_app == "netflix"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_transitions_to_pairing_required_on_subscription_401(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
def on_send_401(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg = json.loads(raw)
|
||||||
|
if msg["type"] == "register":
|
||||||
|
ws.push_json({"type": "registered", "id": msg["id"], "payload": {"client-key": "k"}})
|
||||||
|
elif msg["type"] == "subscribe":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "error",
|
||||||
|
"id": msg["id"],
|
||||||
|
"error": "401 insufficient permissions",
|
||||||
|
"payload": {"returnValue": False},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return FakeWebSocketTransport(on_send=on_send_401)
|
||||||
|
|
||||||
|
mgr = TvManager(_make_config(tmp_path), connect_fn=connect_fn, backoff_steps=(10.0,))
|
||||||
|
async with _started(mgr, until=ConnectionState.PAIRING_REQUIRED):
|
||||||
|
assert mgr.state is ConnectionState.PAIRING_REQUIRED
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_wake_pairing_failure_clears_wake_requested_and_respects_backoff(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
connect_attempts = 0
|
||||||
|
return_prompt = False
|
||||||
|
|
||||||
|
def on_send(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg = json.loads(raw)
|
||||||
|
if msg["type"] == "register":
|
||||||
|
if return_prompt:
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {"pairingType": "PROMPT", "returnValue": True},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
ws.push_close(1008, "Try Again Later (EWS)")
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
nonlocal connect_attempts
|
||||||
|
connect_attempts += 1
|
||||||
|
return FakeWebSocketTransport(on_send=on_send)
|
||||||
|
|
||||||
|
mgr = TvManager(
|
||||||
|
_make_config(tmp_path),
|
||||||
|
connect_fn=connect_fn,
|
||||||
|
wol_fn=_noop_wol,
|
||||||
|
backoff_steps=(1.0,),
|
||||||
|
wake_poll_interval=0.01,
|
||||||
|
wake_timeout=1.0,
|
||||||
|
)
|
||||||
|
async with _started(mgr, until=ConnectionState.STANDBY_OFFLINE):
|
||||||
|
return_prompt = True
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await mgr.wake()
|
||||||
|
assert exc_info.value.code is ErrorCode.PAIRING_REQUIRED
|
||||||
|
|
||||||
|
# Absence check: no busy-loop reconnects within the 1.0s backoff window.
|
||||||
|
attempts_after_wake = connect_attempts
|
||||||
|
await asyncio.sleep(0.05)
|
||||||
|
assert connect_attempts == attempts_after_wake
|
||||||
|
|
||||||
|
|
||||||
|
# --- UI lock & capture ------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_ui_lock_times_out_with_lock_timeout(tmp_path: Path) -> None:
|
||||||
|
gate = asyncio.Event()
|
||||||
|
capturer = _FakeCapturer(gate=gate)
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return _make_online_transport()
|
||||||
|
|
||||||
|
mgr = TvManager(
|
||||||
|
_make_config(tmp_path),
|
||||||
|
connect_fn=connect_fn,
|
||||||
|
capture_client=capturer,
|
||||||
|
backoff_steps=(10.0,),
|
||||||
|
ui_lock_timeout=0.02,
|
||||||
|
)
|
||||||
|
async with _started(mgr):
|
||||||
|
holder = asyncio.create_task(mgr.screenshot())
|
||||||
|
try:
|
||||||
|
# Deterministic: wait until the holder is inside the capture (holding the lock).
|
||||||
|
await _wait_for(lambda: capturer.calls == 1, "first screenshot to hold the UI lock")
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await mgr.screenshot()
|
||||||
|
assert exc_info.value.code is ErrorCode.LOCK_TIMEOUT
|
||||||
|
finally:
|
||||||
|
gate.set()
|
||||||
|
await holder
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_screenshot_raises_unavailable_when_capture_client_is_none(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return _make_online_transport()
|
||||||
|
|
||||||
|
mgr = TvManager(
|
||||||
|
_make_config(tmp_path), connect_fn=connect_fn, capture_client=None, backoff_steps=(10.0,)
|
||||||
|
)
|
||||||
|
async with _started(mgr):
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await mgr.screenshot()
|
||||||
|
|
||||||
|
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
||||||
|
|
||||||
|
|
||||||
|
# --- send_keys ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("keys", "delay_ms", "settle_ms"),
|
||||||
|
[
|
||||||
|
([], 250, 0),
|
||||||
|
(["UP"] * 21, 250, 0),
|
||||||
|
(["UP"], -1, 0),
|
||||||
|
(["UP"], 501, 0),
|
||||||
|
(["UP"], 0, -1),
|
||||||
|
(["UP"], 0, 2001),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
async def test_manager_send_keys_rejects_out_of_bounds_args_without_sending(
|
||||||
|
tmp_path: Path,
|
||||||
|
keys: list[str],
|
||||||
|
delay_ms: int,
|
||||||
|
settle_ms: int,
|
||||||
|
) -> None:
|
||||||
|
pointer_ws = FakeWebSocketTransport()
|
||||||
|
ssap_ws = _make_online_transport(on_request=_pointer_socket_reply)
|
||||||
|
|
||||||
|
async def connect_fn(url: str) -> FakeWebSocketTransport:
|
||||||
|
return pointer_ws if url == POINTER_URL else ssap_ws
|
||||||
|
|
||||||
|
mgr = TvManager(_make_config(tmp_path), connect_fn=connect_fn, backoff_steps=(10.0,))
|
||||||
|
async with _started(mgr):
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await mgr.send_keys(keys, delay_ms=delay_ms, settle_ms=settle_ms)
|
||||||
|
|
||||||
|
assert exc_info.value.code is ErrorCode.INVALID_ARGUMENT
|
||||||
|
assert pointer_ws.sent == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("keys", "delay_ms", "settle_ms"),
|
||||||
|
[
|
||||||
|
(["UP"] * 20, 0, 0),
|
||||||
|
(["UP"], 0, 0),
|
||||||
|
(["UP"], 500, 0),
|
||||||
|
(["UP"], 0, 2000),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
async def test_manager_send_keys_accepts_inclusive_boundary_values(
|
||||||
|
tmp_path: Path,
|
||||||
|
keys: list[str],
|
||||||
|
delay_ms: int,
|
||||||
|
settle_ms: int,
|
||||||
|
) -> None:
|
||||||
|
pointer_ws = FakeWebSocketTransport()
|
||||||
|
ssap_ws = _make_online_transport(on_request=_pointer_socket_reply)
|
||||||
|
|
||||||
|
async def connect_fn(url: str) -> FakeWebSocketTransport:
|
||||||
|
return pointer_ws if url == POINTER_URL else ssap_ws
|
||||||
|
|
||||||
|
mgr = TvManager(_make_config(tmp_path), connect_fn=connect_fn, backoff_steps=(10.0,))
|
||||||
|
async with _started(mgr):
|
||||||
|
res = await mgr.send_keys(keys, delay_ms=delay_ms, settle_ms=settle_ms)
|
||||||
|
|
||||||
|
assert res.keys_sent is True
|
||||||
|
assert res.count == len(keys)
|
||||||
|
assert len(pointer_ws.sent) == len(keys)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("capturer", "expected_error"),
|
||||||
|
[
|
||||||
|
(None, "SCREENSHOT_UNAVAILABLE"),
|
||||||
|
(
|
||||||
|
_FakeCapturer(error=TvError(ErrorCode.SCREENSHOT_UNAVAILABLE, "Dev Mode expired")),
|
||||||
|
"SCREENSHOT_UNAVAILABLE: Dev Mode expired",
|
||||||
|
),
|
||||||
|
],
|
||||||
|
ids=["no_capture_client", "capture_client_raises"],
|
||||||
|
)
|
||||||
|
async def test_manager_send_keys_capture_returns_partial_success_when_capture_unavailable(
|
||||||
|
tmp_path: Path,
|
||||||
|
capturer: _FakeCapturer | None,
|
||||||
|
expected_error: str,
|
||||||
|
) -> None:
|
||||||
|
pointer_ws = FakeWebSocketTransport()
|
||||||
|
ssap_ws = _make_online_transport(on_request=_pointer_socket_reply)
|
||||||
|
|
||||||
|
async def connect_fn(url: str) -> FakeWebSocketTransport:
|
||||||
|
return pointer_ws if url == POINTER_URL else ssap_ws
|
||||||
|
|
||||||
|
mgr = TvManager(
|
||||||
|
_make_config(tmp_path),
|
||||||
|
connect_fn=connect_fn,
|
||||||
|
capture_client=capturer,
|
||||||
|
backoff_steps=(10.0,),
|
||||||
|
)
|
||||||
|
async with _started(mgr):
|
||||||
|
res = await mgr.send_keys(["UP", "ENTER"], delay_ms=0, settle_ms=0, capture=True)
|
||||||
|
|
||||||
|
assert res.keys_sent is True
|
||||||
|
assert res.count == 2
|
||||||
|
assert res.capture_error is not None
|
||||||
|
assert expected_error in res.capture_error
|
||||||
|
assert pointer_ws.sent == ["type:button\nname:UP\n\n", "type:button\nname:ENTER\n\n"]
|
||||||
|
|
||||||
|
|
||||||
|
# --- SSAP controls -----------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _recording_transport(
|
||||||
|
sent_requests: list[tuple[str, dict[str, Any]]],
|
||||||
|
replies: dict[str, dict[str, Any]] | None = None,
|
||||||
|
) -> FakeWebSocketTransport:
|
||||||
|
"""Online transport that records requests and answers per-URI (default returnValue=True)."""
|
||||||
|
replies = replies or {}
|
||||||
|
|
||||||
|
def on_request(msg: dict[str, Any], ws: FakeWebSocketTransport) -> None:
|
||||||
|
uri = msg["uri"]
|
||||||
|
sent_requests.append((uri, msg["payload"]))
|
||||||
|
payload = {"returnValue": True, **replies.get(uri, {})}
|
||||||
|
ws.push_json({"type": "response", "id": msg["id"], "payload": payload})
|
||||||
|
|
||||||
|
return _make_online_transport(on_request=on_request)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("level", [0, 20, 35])
|
||||||
|
async def test_manager_set_volume_accepts_levels_within_inclusive_max_volume(
|
||||||
|
tmp_path: Path, level: int
|
||||||
|
) -> None:
|
||||||
|
sent_requests: list[tuple[str, dict[str, Any]]] = []
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return _recording_transport(sent_requests)
|
||||||
|
|
||||||
|
mgr = TvManager(
|
||||||
|
_make_config(tmp_path, max_volume=35), connect_fn=connect_fn, backoff_steps=(10.0,)
|
||||||
|
)
|
||||||
|
async with _started(mgr):
|
||||||
|
await mgr.set_volume(level)
|
||||||
|
|
||||||
|
assert sent_requests == [("ssap://audio/setVolume", {"volume": level})]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("level", [-1, 36])
|
||||||
|
async def test_manager_set_volume_rejects_levels_outside_max_volume_without_sending(
|
||||||
|
tmp_path: Path, level: int
|
||||||
|
) -> None:
|
||||||
|
sent_requests: list[tuple[str, dict[str, Any]]] = []
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return _recording_transport(sent_requests)
|
||||||
|
|
||||||
|
mgr = TvManager(
|
||||||
|
_make_config(tmp_path, max_volume=35), connect_fn=connect_fn, backoff_steps=(10.0,)
|
||||||
|
)
|
||||||
|
async with _started(mgr):
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await mgr.set_volume(level)
|
||||||
|
|
||||||
|
assert exc_info.value.code is ErrorCode.INVALID_ARGUMENT
|
||||||
|
assert sent_requests == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_mvp_ssap_controls_send_expected_uris_and_payloads(tmp_path: Path) -> None:
|
||||||
|
sent_requests: list[tuple[str, dict[str, Any]]] = []
|
||||||
|
replies = {
|
||||||
|
"ssap://com.webos.applicationManager/listLaunchPoints": {
|
||||||
|
"launchPoints": [{"id": "netflix", "title": "Netflix"}]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return _recording_transport(sent_requests, replies)
|
||||||
|
|
||||||
|
mgr = TvManager(_make_config(tmp_path), connect_fn=connect_fn, backoff_steps=(10.0,))
|
||||||
|
async with _started(mgr):
|
||||||
|
await mgr.launch_app("youtube.leanback.v4", content_target="v=abc&t=10s")
|
||||||
|
apps = await mgr.list_apps()
|
||||||
|
await mgr.set_mute(True)
|
||||||
|
await mgr.turn_off()
|
||||||
|
|
||||||
|
assert apps == [{"id": "netflix", "title": "Netflix"}]
|
||||||
|
assert sent_requests == [
|
||||||
|
(
|
||||||
|
"ssap://system.launcher/launch",
|
||||||
|
{"id": "youtube.leanback.v4", "params": {"contentTarget": "v=abc&t=10s"}},
|
||||||
|
),
|
||||||
|
("ssap://com.webos.applicationManager/listLaunchPoints", {}),
|
||||||
|
("ssap://audio/setMute", {"mute": True}),
|
||||||
|
("ssap://system/turnOff", {}),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("bad_text", ["", "x" * 501])
|
||||||
|
async def test_manager_type_text_rejects_out_of_bounds_length_without_sending(
|
||||||
|
tmp_path: Path, bad_text: str
|
||||||
|
) -> None:
|
||||||
|
sent_requests: list[tuple[str, dict[str, Any]]] = []
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return _recording_transport(sent_requests)
|
||||||
|
|
||||||
|
mgr = TvManager(_make_config(tmp_path), connect_fn=connect_fn, backoff_steps=(10.0,))
|
||||||
|
async with _started(mgr):
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await mgr.type_text(bad_text)
|
||||||
|
|
||||||
|
assert exc_info.value.code is ErrorCode.INVALID_ARGUMENT
|
||||||
|
assert sent_requests == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("text", ["a", "x" * 500])
|
||||||
|
async def test_manager_type_text_accepts_inclusive_boundary_lengths(
|
||||||
|
tmp_path: Path, text: str
|
||||||
|
) -> None:
|
||||||
|
sent_requests: list[tuple[str, dict[str, Any]]] = []
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return _recording_transport(sent_requests)
|
||||||
|
|
||||||
|
mgr = TvManager(_make_config(tmp_path), connect_fn=connect_fn, backoff_steps=(10.0,))
|
||||||
|
async with _started(mgr):
|
||||||
|
res = await mgr.type_text(text, send_enter=False)
|
||||||
|
|
||||||
|
assert res.text_sent is True
|
||||||
|
assert res.enter_sent is False
|
||||||
|
assert sent_requests == [
|
||||||
|
("ssap://com.webos.service.ime/insertText", {"text": text, "replace": 0})
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_type_text_capture_returns_partial_success_when_capture_fails(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
sent_requests: list[tuple[str, dict[str, Any]]] = []
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return _recording_transport(sent_requests)
|
||||||
|
|
||||||
|
failing_capturer = _FakeCapturer(
|
||||||
|
error=TvError(ErrorCode.SCREENSHOT_UNAVAILABLE, "Dev Mode expired")
|
||||||
|
)
|
||||||
|
mgr = TvManager(
|
||||||
|
_make_config(tmp_path),
|
||||||
|
connect_fn=connect_fn,
|
||||||
|
capture_client=failing_capturer,
|
||||||
|
backoff_steps=(10.0,),
|
||||||
|
)
|
||||||
|
async with _started(mgr):
|
||||||
|
res = await mgr.type_text("anime", send_enter=True, capture=True)
|
||||||
|
|
||||||
|
assert res.text_sent is True
|
||||||
|
assert res.enter_sent is True
|
||||||
|
assert res.capture_error == "SCREENSHOT_UNAVAILABLE: Dev Mode expired"
|
||||||
|
assert sent_requests == [
|
||||||
|
("ssap://com.webos.service.ime/insertText", {"text": "anime", "replace": 0}),
|
||||||
|
("ssap://com.webos.service.ime/sendEnterKey", {}),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_list_inputs_and_switch_input_send_expected_uris(tmp_path: Path) -> None:
|
||||||
|
sent_requests: list[tuple[str, dict[str, Any]]] = []
|
||||||
|
replies = {
|
||||||
|
"ssap://tv/getExternalInputList": {
|
||||||
|
"devices": [{"id": "HDMI_1", "label": "HDMI 1", "connected": True}]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return _recording_transport(sent_requests, replies)
|
||||||
|
|
||||||
|
mgr = TvManager(_make_config(tmp_path), connect_fn=connect_fn, backoff_steps=(10.0,))
|
||||||
|
async with _started(mgr):
|
||||||
|
inputs = await mgr.list_inputs()
|
||||||
|
await mgr.switch_input("HDMI_1")
|
||||||
|
|
||||||
|
assert inputs == [{"id": "HDMI_1", "label": "HDMI 1", "connected": True}]
|
||||||
|
assert sent_requests == [
|
||||||
|
("ssap://tv/getExternalInputList", {}),
|
||||||
|
("ssap://tv/switchInput", {"inputId": "HDMI_1"}),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_raw_ssap_rejects_when_disabled_without_sending(tmp_path: Path) -> None:
|
||||||
|
sent_requests: list[tuple[str, dict[str, Any]]] = []
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return _recording_transport(sent_requests)
|
||||||
|
|
||||||
|
mgr = TvManager(
|
||||||
|
_make_config(tmp_path, enable_raw_ssap=False), connect_fn=connect_fn, backoff_steps=(10.0,)
|
||||||
|
)
|
||||||
|
async with _started(mgr):
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await mgr.raw_ssap("ssap://system/getSystemInfo")
|
||||||
|
|
||||||
|
assert exc_info.value.code is ErrorCode.INVALID_ARGUMENT
|
||||||
|
assert sent_requests == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_manager_raw_ssap_forwards_request_when_enabled(tmp_path: Path) -> None:
|
||||||
|
sent_requests: list[tuple[str, dict[str, Any]]] = []
|
||||||
|
replies = {"ssap://system/getSystemInfo": {"ok": 1}}
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return _recording_transport(sent_requests, replies)
|
||||||
|
|
||||||
|
mgr = TvManager(
|
||||||
|
_make_config(tmp_path, enable_raw_ssap=True), connect_fn=connect_fn, backoff_steps=(10.0,)
|
||||||
|
)
|
||||||
|
async with _started(mgr):
|
||||||
|
resp = await mgr.raw_ssap("ssap://system/getSystemInfo", {"x": 1})
|
||||||
|
|
||||||
|
assert resp == {"returnValue": True, "ok": 1}
|
||||||
|
assert sent_requests == [("ssap://system/getSystemInfo", {"x": 1})]
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from lg_smtv_mcp.errors import ErrorCode, TvError
|
||||||
|
from lg_smtv_mcp.tv_core.pointer import BUTTON_ALLOWLIST, PointerClient
|
||||||
|
from tests.conftest import FakeWebSocketTransport
|
||||||
|
|
||||||
|
|
||||||
|
async def test_pointer_normalizes_keys_to_uppercase_and_formats_frames() -> None:
|
||||||
|
ws = FakeWebSocketTransport()
|
||||||
|
ssap_calls: list[str] = []
|
||||||
|
|
||||||
|
async def fake_ssap(uri: str, _payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
ssap_calls.append(uri)
|
||||||
|
return {"socketPath": "wss://192.0.2.10:3001/pointer/1"}
|
||||||
|
|
||||||
|
async def fake_connect(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return ws
|
||||||
|
|
||||||
|
client = PointerClient(fake_ssap, connect_fn=fake_connect)
|
||||||
|
count = await client.send_buttons(["up", "Enter", "home"], delay_ms=0)
|
||||||
|
await client.close()
|
||||||
|
|
||||||
|
assert count == 3
|
||||||
|
assert ssap_calls == ["ssap://com.webos.service.networkinput/getPointerInputSocket"]
|
||||||
|
assert ws.sent == [
|
||||||
|
"type:button\nname:UP\n\n",
|
||||||
|
"type:button\nname:ENTER\n\n",
|
||||||
|
"type:button\nname:HOME\n\n",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("bad_key", ["INVALID_KEY", "UP\nname:HOME", "ENTER\r", ""])
|
||||||
|
async def test_pointer_rejects_unknown_keys_and_newlines_with_invalid_argument(
|
||||||
|
bad_key: str,
|
||||||
|
) -> None:
|
||||||
|
assert "UP" in BUTTON_ALLOWLIST
|
||||||
|
ws = FakeWebSocketTransport()
|
||||||
|
|
||||||
|
async def fake_ssap(_uri: str, _payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return {"socketPath": "wss://192.0.2.10:3001/pointer/1"}
|
||||||
|
|
||||||
|
async def fake_connect(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return ws
|
||||||
|
|
||||||
|
client = PointerClient(fake_ssap, connect_fn=fake_connect)
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await client.send_buttons(["UP", bad_key], delay_ms=0)
|
||||||
|
|
||||||
|
assert exc_info.value.code is ErrorCode.INVALID_ARGUMENT
|
||||||
|
assert ws.sent == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_pointer_paces_buttons_by_delay_ms() -> None:
|
||||||
|
ws = FakeWebSocketTransport()
|
||||||
|
sleeps: list[float] = []
|
||||||
|
|
||||||
|
async def fake_sleep(seconds: float) -> None:
|
||||||
|
sleeps.append(seconds)
|
||||||
|
|
||||||
|
async def fake_ssap(_uri: str, _payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return {"socketPath": "wss://192.0.2.10:3001/pointer/1"}
|
||||||
|
|
||||||
|
async def fake_connect(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return ws
|
||||||
|
|
||||||
|
client = PointerClient(fake_ssap, connect_fn=fake_connect, sleep_fn=fake_sleep)
|
||||||
|
await client.send_buttons(["LEFT", "RIGHT", "ENTER"], delay_ms=150)
|
||||||
|
await client.close()
|
||||||
|
|
||||||
|
assert sleeps == [pytest.approx(0.15), pytest.approx(0.15)]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_pointer_retries_once_on_mid_batch_socket_drop() -> None:
|
||||||
|
ws1 = FakeWebSocketTransport()
|
||||||
|
ws2 = FakeWebSocketTransport()
|
||||||
|
connects = 0
|
||||||
|
|
||||||
|
def drop_after_first(data: str, transport: FakeWebSocketTransport) -> None:
|
||||||
|
if "LEFT" in data:
|
||||||
|
transport.closed = True
|
||||||
|
|
||||||
|
ws1._on_send = drop_after_first # pyright: ignore[reportPrivateUsage]
|
||||||
|
|
||||||
|
async def fake_ssap(_uri: str, _payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return {"socketPath": f"wss://192.0.2.10:3001/pointer/{connects + 1}"}
|
||||||
|
|
||||||
|
async def fake_connect(_url: str) -> FakeWebSocketTransport:
|
||||||
|
nonlocal connects
|
||||||
|
connects += 1
|
||||||
|
return ws1 if connects == 1 else ws2
|
||||||
|
|
||||||
|
client = PointerClient(fake_ssap, connect_fn=fake_connect)
|
||||||
|
count = await client.send_buttons(["LEFT", "ENTER"], delay_ms=0)
|
||||||
|
await client.close()
|
||||||
|
|
||||||
|
assert count == 2
|
||||||
|
assert connects == 2
|
||||||
|
assert ws1.sent == ["type:button\nname:LEFT\n\n"]
|
||||||
|
assert ws2.sent == ["type:button\nname:ENTER\n\n"]
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
from dataclasses import FrozenInstanceError
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from lg_smtv_mcp.tv_core.protocols import (
|
||||||
|
CaptureResult,
|
||||||
|
KeysResult,
|
||||||
|
TextResult,
|
||||||
|
TvStateSnapshot,
|
||||||
|
TvStatus,
|
||||||
|
WebSocketClosedError,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_websocket_closed_error_preserves_args_and_str_representation() -> None:
|
||||||
|
err = WebSocketClosedError(1008, "Try Again Later (EWS)")
|
||||||
|
|
||||||
|
assert isinstance(err, Exception)
|
||||||
|
assert err.code == 1008
|
||||||
|
assert err.reason == "Try Again Later (EWS)"
|
||||||
|
assert err.args
|
||||||
|
assert "1008" in str(err)
|
||||||
|
assert "Try Again Later (EWS)" in str(err)
|
||||||
|
|
||||||
|
err_no_reason = WebSocketClosedError(1000)
|
||||||
|
assert err_no_reason.code == 1000
|
||||||
|
assert err_no_reason.reason == ""
|
||||||
|
assert "1000" in str(err_no_reason)
|
||||||
|
|
||||||
|
|
||||||
|
def test_result_dataclasses_are_frozen_and_expose_expected_fields() -> None:
|
||||||
|
status = TvStatus(status="connected", elapsed_ms=120)
|
||||||
|
snapshot = TvStateSnapshot(
|
||||||
|
connected=True,
|
||||||
|
stale=False,
|
||||||
|
volume=15,
|
||||||
|
muted=False,
|
||||||
|
sound_output="tv_speaker",
|
||||||
|
foreground_app="youtube.leanback.v4",
|
||||||
|
last_updated=1234.5,
|
||||||
|
)
|
||||||
|
capture = CaptureResult(
|
||||||
|
image_bytes=b"\xff\xd8\xff",
|
||||||
|
frame_sha256="abc123",
|
||||||
|
changed_since_last=True,
|
||||||
|
size_bytes=3,
|
||||||
|
)
|
||||||
|
keys_res = KeysResult(keys_sent=True, count=2, capture_error="SCREENSHOT_UNAVAILABLE: off")
|
||||||
|
text_res = TextResult(text_sent=True, enter_sent=False)
|
||||||
|
|
||||||
|
assert status.status == "connected"
|
||||||
|
assert snapshot.foreground_app == "youtube.leanback.v4"
|
||||||
|
assert capture.size_bytes == 3
|
||||||
|
assert keys_res.count == 2
|
||||||
|
assert keys_res.capture_error == "SCREENSHOT_UNAVAILABLE: off"
|
||||||
|
assert text_res.enter_sent is False
|
||||||
|
|
||||||
|
with pytest.raises(FrozenInstanceError):
|
||||||
|
status.elapsed_ms = 0 # type: ignore[misc]
|
||||||
|
with pytest.raises(FrozenInstanceError):
|
||||||
|
snapshot.volume = 99 # type: ignore[misc]
|
||||||
|
with pytest.raises(FrozenInstanceError):
|
||||||
|
capture.size_bytes = 0 # type: ignore[misc]
|
||||||
|
with pytest.raises(FrozenInstanceError):
|
||||||
|
keys_res.count = 0 # type: ignore[misc]
|
||||||
|
with pytest.raises(FrozenInstanceError):
|
||||||
|
text_res.text_sent = False # type: ignore[misc]
|
||||||
@@ -0,0 +1,611 @@
|
|||||||
|
"""Offline contract tests for MCPServer tools, error mapping, and ASGI lifespan."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import signal
|
||||||
|
from collections.abc import AsyncGenerator, Awaitable, Callable, MutableMapping
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import asyncssh
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
from mcp.server.mcpserver.exceptions import ToolError
|
||||||
|
from mcp.types import CallToolResult, ImageContent, TextContent
|
||||||
|
|
||||||
|
from lg_smtv_mcp.config import TvConfig
|
||||||
|
from lg_smtv_mcp.errors import ErrorCode, TvError
|
||||||
|
from lg_smtv_mcp.server import create_http_app, create_mcp_server
|
||||||
|
from lg_smtv_mcp.tv_core import CaptureResult, ConnectionState, TvManager
|
||||||
|
from tests.conftest import FakeWebSocketTransport
|
||||||
|
|
||||||
|
_TEST_JPEG = b"\xff\xd8\xff\xe0test-jpeg"
|
||||||
|
_TEST_SHA256 = hashlib.sha256(_TEST_JPEG).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeCapturer:
|
||||||
|
def __init__(self, *, error: TvError | None = None) -> None:
|
||||||
|
self._error = error
|
||||||
|
self.closed = False
|
||||||
|
|
||||||
|
async def capture_frame(
|
||||||
|
self,
|
||||||
|
ssap_request_fn: Callable[[str, dict[str, Any]], Awaitable[dict[str, Any]]],
|
||||||
|
) -> CaptureResult:
|
||||||
|
_ = ssap_request_fn
|
||||||
|
if self._error is not None:
|
||||||
|
raise self._error
|
||||||
|
return CaptureResult(
|
||||||
|
image_bytes=_TEST_JPEG,
|
||||||
|
frame_sha256=_TEST_SHA256,
|
||||||
|
changed_since_last=True,
|
||||||
|
size_bytes=len(_TEST_JPEG),
|
||||||
|
)
|
||||||
|
|
||||||
|
async def close(self) -> None:
|
||||||
|
self.closed = True
|
||||||
|
|
||||||
|
|
||||||
|
def _make_config(
|
||||||
|
tmp_path: Path,
|
||||||
|
*,
|
||||||
|
enable_raw_ssap: bool = False,
|
||||||
|
max_volume: int = 30,
|
||||||
|
) -> TvConfig:
|
||||||
|
key_file = tmp_path / ".client_key.json"
|
||||||
|
key_file.write_text(json.dumps({"192.0.2.10": "saved-key"}), encoding="utf-8")
|
||||||
|
return TvConfig(
|
||||||
|
tv_ip="192.0.2.10",
|
||||||
|
tv_mac="AA:BB:CC:DD:EE:FF",
|
||||||
|
client_key_path=key_file,
|
||||||
|
mcp_bearer_token="test-bearer-token",
|
||||||
|
enable_raw_ssap=enable_raw_ssap,
|
||||||
|
max_volume=max_volume,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _online_transport(
|
||||||
|
sent_requests: list[tuple[str, dict[str, Any]]],
|
||||||
|
replies: dict[str, dict[str, Any]] | None = None,
|
||||||
|
) -> FakeWebSocketTransport:
|
||||||
|
replies = replies or {}
|
||||||
|
|
||||||
|
def on_send(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg: dict[str, Any] = json.loads(raw)
|
||||||
|
msg_type = msg.get("type")
|
||||||
|
msg_id = msg.get("id")
|
||||||
|
if msg_type == "register":
|
||||||
|
ws.push_json(
|
||||||
|
{"type": "registered", "id": msg_id, "payload": {"client-key": "saved-key"}}
|
||||||
|
)
|
||||||
|
return
|
||||||
|
if msg_type == "subscribe":
|
||||||
|
ws.push_json({"type": "response", "id": msg_id, "payload": {"subscribed": True}})
|
||||||
|
return
|
||||||
|
if msg_type == "request":
|
||||||
|
uri = str(msg.get("uri", ""))
|
||||||
|
if uri == "ssap://com.webos.service.networkinput/getPointerInputSocket":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg_id,
|
||||||
|
"payload": {
|
||||||
|
"returnValue": True,
|
||||||
|
"socketPath": "ws://192.0.2.10:3000/pointer",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return
|
||||||
|
payload_in = dict(msg.get("payload") or {})
|
||||||
|
sent_requests.append((uri, payload_in))
|
||||||
|
reply_payload = {"returnValue": True, **replies.get(uri, {})}
|
||||||
|
ws.push_json({"type": "response", "id": msg_id, "payload": reply_payload})
|
||||||
|
|
||||||
|
return FakeWebSocketTransport(on_send=on_send)
|
||||||
|
|
||||||
|
|
||||||
|
async def _wait_connected(mgr: TvManager) -> None:
|
||||||
|
async def _poll() -> None:
|
||||||
|
while mgr.state != ConnectionState.CONNECTED:
|
||||||
|
await asyncio.sleep(0)
|
||||||
|
|
||||||
|
await asyncio.wait_for(_poll(), timeout=2.0)
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def _started_manager(
|
||||||
|
tmp_path: Path,
|
||||||
|
*,
|
||||||
|
enable_raw_ssap: bool = False,
|
||||||
|
max_volume: int = 30,
|
||||||
|
capturer: _FakeCapturer | None = None,
|
||||||
|
replies: dict[str, dict[str, Any]] | None = None,
|
||||||
|
) -> AsyncGenerator[tuple[TvConfig, TvManager, list[tuple[str, dict[str, Any]]]]]:
|
||||||
|
sent_requests: list[tuple[str, dict[str, Any]]] = []
|
||||||
|
pointer_ws = FakeWebSocketTransport()
|
||||||
|
|
||||||
|
async def connect_fn(url: str) -> FakeWebSocketTransport:
|
||||||
|
if url.endswith("/pointer"):
|
||||||
|
return pointer_ws
|
||||||
|
return _online_transport(sent_requests, replies)
|
||||||
|
|
||||||
|
config = _make_config(
|
||||||
|
tmp_path,
|
||||||
|
enable_raw_ssap=enable_raw_ssap,
|
||||||
|
max_volume=max_volume,
|
||||||
|
)
|
||||||
|
mgr = TvManager(
|
||||||
|
config,
|
||||||
|
connect_fn=connect_fn,
|
||||||
|
capture_client=capturer,
|
||||||
|
backoff_steps=(10.0,),
|
||||||
|
)
|
||||||
|
await mgr.start()
|
||||||
|
try:
|
||||||
|
await _wait_connected(mgr)
|
||||||
|
yield config, mgr, sent_requests
|
||||||
|
finally:
|
||||||
|
await mgr.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_server_registers_12_default_tools_and_gates_raw_ssap(tmp_path: Path) -> None:
|
||||||
|
expected_default = {
|
||||||
|
"tv_wake",
|
||||||
|
"get_state",
|
||||||
|
"keys",
|
||||||
|
"type_text",
|
||||||
|
"screenshot",
|
||||||
|
"launch",
|
||||||
|
"list_apps",
|
||||||
|
"set_volume",
|
||||||
|
"set_mute",
|
||||||
|
"list_inputs",
|
||||||
|
"switch_input",
|
||||||
|
"turn_off",
|
||||||
|
}
|
||||||
|
|
||||||
|
server_off = create_mcp_server(_make_config(tmp_path, enable_raw_ssap=False))
|
||||||
|
names_off = {tool.name for tool in await server_off.list_tools()}
|
||||||
|
assert names_off == expected_default
|
||||||
|
assert "raw_ssap" not in names_off
|
||||||
|
|
||||||
|
server_on = create_mcp_server(_make_config(tmp_path, enable_raw_ssap=True))
|
||||||
|
names_on = {tool.name for tool in await server_on.list_tools()}
|
||||||
|
assert names_on == expected_default | {"raw_ssap"}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_server_maps_tv_error_to_tool_error_code_and_message(tmp_path: Path) -> None:
|
||||||
|
async def standby_connect(_url: str) -> FakeWebSocketTransport:
|
||||||
|
raise TvError(ErrorCode.TV_OFFLINE_STANDBY, "TV is in standby")
|
||||||
|
|
||||||
|
config = _make_config(tmp_path)
|
||||||
|
mgr = TvManager(config, connect_fn=standby_connect, backoff_steps=(10.0,))
|
||||||
|
await mgr.start()
|
||||||
|
try:
|
||||||
|
server = create_mcp_server(config, manager=mgr)
|
||||||
|
with pytest.raises(ToolError, match=r"TV_OFFLINE_STANDBY: "):
|
||||||
|
await server.call_tool("turn_off", {})
|
||||||
|
finally:
|
||||||
|
await mgr.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_server_launch_merges_content_target_and_omits_empty_params(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
async with _started_manager(tmp_path) as (config, mgr, sent_requests):
|
||||||
|
server = create_mcp_server(config, manager=mgr)
|
||||||
|
await server.call_tool("launch", {"app_id": "youtube.leanback.v4"})
|
||||||
|
await server.call_tool(
|
||||||
|
"launch",
|
||||||
|
{
|
||||||
|
"app_id": "youtube.leanback.v4",
|
||||||
|
"content_target": "v=abc123",
|
||||||
|
"params": {"contentTarget": "old", "extra": 1},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
launch_calls = [
|
||||||
|
payload for uri, payload in sent_requests if uri == "ssap://system.launcher/launch"
|
||||||
|
]
|
||||||
|
assert launch_calls == [
|
||||||
|
{"id": "youtube.leanback.v4"},
|
||||||
|
{"id": "youtube.leanback.v4", "params": {"contentTarget": "v=abc123", "extra": 1}},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("level", "should_succeed"),
|
||||||
|
[(-1, False), (0, True), (30, True), (31, False)],
|
||||||
|
)
|
||||||
|
async def test_server_set_volume_enforces_max_volume_bounds(
|
||||||
|
tmp_path: Path,
|
||||||
|
level: int,
|
||||||
|
should_succeed: bool,
|
||||||
|
) -> None:
|
||||||
|
async with _started_manager(tmp_path, max_volume=30) as (config, mgr, sent_requests):
|
||||||
|
server = create_mcp_server(config, manager=mgr)
|
||||||
|
if should_succeed:
|
||||||
|
await server.call_tool("set_volume", {"level": level})
|
||||||
|
assert ("ssap://audio/setVolume", {"volume": level}) in sent_requests
|
||||||
|
else:
|
||||||
|
with pytest.raises(ToolError, match=r"INVALID_ARGUMENT: "):
|
||||||
|
await server.call_tool("set_volume", {"level": level})
|
||||||
|
assert not any(uri == "ssap://audio/setVolume" for uri, _ in sent_requests)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("text", "should_succeed"),
|
||||||
|
[("", False), ("a", True), ("x" * 500, True), ("x" * 501, False)],
|
||||||
|
)
|
||||||
|
async def test_server_type_text_validates_length_bounds(
|
||||||
|
tmp_path: Path,
|
||||||
|
text: str,
|
||||||
|
should_succeed: bool,
|
||||||
|
) -> None:
|
||||||
|
async with _started_manager(tmp_path) as (config, mgr, sent_requests):
|
||||||
|
server = create_mcp_server(config, manager=mgr)
|
||||||
|
if should_succeed:
|
||||||
|
await server.call_tool("type_text", {"text": text, "send_enter": False})
|
||||||
|
assert (
|
||||||
|
"ssap://com.webos.service.ime/insertText",
|
||||||
|
{"text": text, "replace": 0},
|
||||||
|
) in sent_requests
|
||||||
|
else:
|
||||||
|
with pytest.raises(ToolError, match=r"INVALID_ARGUMENT: "):
|
||||||
|
await server.call_tool("type_text", {"text": text, "send_enter": False})
|
||||||
|
|
||||||
|
|
||||||
|
async def test_server_screenshot_returns_text_and_image_content(tmp_path: Path) -> None:
|
||||||
|
capturer = _FakeCapturer()
|
||||||
|
async with _started_manager(tmp_path, capturer=capturer) as (config, mgr, _):
|
||||||
|
server = create_mcp_server(config, manager=mgr)
|
||||||
|
shot_res = await server.call_tool("screenshot", {})
|
||||||
|
|
||||||
|
assert isinstance(shot_res, CallToolResult)
|
||||||
|
assert len(shot_res.content) == 2
|
||||||
|
text_block, image_block = shot_res.content[0], shot_res.content[1]
|
||||||
|
assert isinstance(text_block, TextContent)
|
||||||
|
assert isinstance(image_block, ImageContent)
|
||||||
|
shot_meta = json.loads(text_block.text)
|
||||||
|
assert shot_meta["frame_sha256"] == _TEST_SHA256
|
||||||
|
assert shot_meta["size_bytes"] == len(_TEST_JPEG)
|
||||||
|
assert image_block.mime_type == "image/jpeg"
|
||||||
|
assert base64.b64decode(image_block.data) == _TEST_JPEG
|
||||||
|
|
||||||
|
|
||||||
|
async def test_server_keys_capture_returns_text_and_image_content(tmp_path: Path) -> None:
|
||||||
|
capturer = _FakeCapturer()
|
||||||
|
async with _started_manager(tmp_path, capturer=capturer) as (config, mgr, _):
|
||||||
|
server = create_mcp_server(config, manager=mgr)
|
||||||
|
keys_res = await server.call_tool(
|
||||||
|
"keys",
|
||||||
|
{"keys": ["UP"], "delay_ms": 0, "settle_ms": 0, "capture": True},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert isinstance(keys_res, CallToolResult)
|
||||||
|
assert len(keys_res.content) == 2
|
||||||
|
text_block, image_block = keys_res.content[0], keys_res.content[1]
|
||||||
|
assert isinstance(text_block, TextContent)
|
||||||
|
assert isinstance(image_block, ImageContent)
|
||||||
|
keys_meta = json.loads(text_block.text)
|
||||||
|
assert keys_meta["keys_sent"] is True
|
||||||
|
assert keys_meta["count"] == 1
|
||||||
|
assert base64.b64decode(image_block.data) == _TEST_JPEG
|
||||||
|
|
||||||
|
|
||||||
|
async def test_server_type_text_capture_returns_text_and_image_content(tmp_path: Path) -> None:
|
||||||
|
capturer = _FakeCapturer()
|
||||||
|
async with _started_manager(tmp_path, capturer=capturer) as (config, mgr, _):
|
||||||
|
server = create_mcp_server(config, manager=mgr)
|
||||||
|
text_res = await server.call_tool(
|
||||||
|
"type_text",
|
||||||
|
{"text": "hi", "send_enter": False, "capture": True},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert isinstance(text_res, CallToolResult)
|
||||||
|
assert len(text_res.content) == 2
|
||||||
|
text_block, image_block = text_res.content[0], text_res.content[1]
|
||||||
|
assert isinstance(text_block, TextContent)
|
||||||
|
assert isinstance(image_block, ImageContent)
|
||||||
|
assert base64.b64decode(image_block.data) == _TEST_JPEG
|
||||||
|
|
||||||
|
|
||||||
|
async def test_server_keys_capture_returns_text_only_on_capture_error(tmp_path: Path) -> None:
|
||||||
|
capturer = _FakeCapturer(error=TvError(ErrorCode.SCREENSHOT_UNAVAILABLE, "Dev Mode expired"))
|
||||||
|
async with _started_manager(tmp_path, capturer=capturer) as (config, mgr, _):
|
||||||
|
server = create_mcp_server(config, manager=mgr)
|
||||||
|
res = await server.call_tool(
|
||||||
|
"keys",
|
||||||
|
{"keys": ["ENTER"], "delay_ms": 0, "settle_ms": 0, "capture": True},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert isinstance(res, CallToolResult)
|
||||||
|
assert len(res.content) == 1
|
||||||
|
text_block = res.content[0]
|
||||||
|
assert isinstance(text_block, TextContent)
|
||||||
|
meta = json.loads(text_block.text)
|
||||||
|
assert meta["keys_sent"] is True
|
||||||
|
assert meta["capture_error"] == "SCREENSHOT_UNAVAILABLE: Dev Mode expired"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_server_http_app_rejects_unauthenticated_mcp_request_with_401(tmp_path: Path) -> None:
|
||||||
|
config = _make_config(tmp_path)
|
||||||
|
mgr = TvManager(config, backoff_steps=(10.0,))
|
||||||
|
app = create_http_app(config, manager=mgr)
|
||||||
|
|
||||||
|
transport = httpx.ASGITransport(app=app)
|
||||||
|
async with httpx.AsyncClient(transport=transport, base_url="http://127.0.0.1:8765") as client:
|
||||||
|
unauth = await client.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "initialize"})
|
||||||
|
|
||||||
|
assert unauth.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
async def test_server_http_app_lifespan_starts_and_closes_manager_with_sighup(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
sent_requests: list[tuple[str, dict[str, Any]]] = []
|
||||||
|
pointer_ws = FakeWebSocketTransport()
|
||||||
|
ssap_ws = _online_transport(sent_requests)
|
||||||
|
|
||||||
|
async def connect_fn(url: str) -> FakeWebSocketTransport:
|
||||||
|
if url.endswith("/pointer"):
|
||||||
|
return pointer_ws
|
||||||
|
return ssap_ws
|
||||||
|
|
||||||
|
config = _make_config(tmp_path)
|
||||||
|
mgr = TvManager(config, connect_fn=connect_fn, backoff_steps=(10.0,))
|
||||||
|
app = create_http_app(config, manager=mgr)
|
||||||
|
|
||||||
|
incoming: list[MutableMapping[str, Any]] = [
|
||||||
|
{"type": "lifespan.startup"},
|
||||||
|
{"type": "lifespan.shutdown"},
|
||||||
|
]
|
||||||
|
outgoing: list[MutableMapping[str, Any]] = []
|
||||||
|
startup_done = asyncio.Event()
|
||||||
|
allow_shutdown = asyncio.Event()
|
||||||
|
|
||||||
|
async def receive() -> MutableMapping[str, Any]:
|
||||||
|
if incoming[0]["type"] == "lifespan.shutdown":
|
||||||
|
await allow_shutdown.wait()
|
||||||
|
return incoming.pop(0)
|
||||||
|
|
||||||
|
async def send(msg: MutableMapping[str, Any]) -> None:
|
||||||
|
outgoing.append(msg)
|
||||||
|
if msg["type"] == "lifespan.startup.complete":
|
||||||
|
startup_done.set()
|
||||||
|
|
||||||
|
async def _run_lifespan() -> None:
|
||||||
|
await app({"type": "lifespan"}, receive, send)
|
||||||
|
|
||||||
|
lifespan_task: asyncio.Task[None] = asyncio.create_task(_run_lifespan())
|
||||||
|
try:
|
||||||
|
await asyncio.wait_for(startup_done.wait(), timeout=2.0)
|
||||||
|
await _wait_connected(mgr)
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
assert loop.remove_signal_handler(signal.SIGHUP) is True
|
||||||
|
finally:
|
||||||
|
allow_shutdown.set()
|
||||||
|
await asyncio.wait_for(lifespan_task, timeout=2.0)
|
||||||
|
|
||||||
|
assert [m["type"] for m in outgoing] == [
|
||||||
|
"lifespan.startup.complete",
|
||||||
|
"lifespan.shutdown.complete",
|
||||||
|
]
|
||||||
|
assert ssap_ws.closed is True
|
||||||
|
|
||||||
|
|
||||||
|
async def test_server_http_app_allows_authenticated_mcp_initialize_request(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
sent_requests: list[tuple[str, dict[str, Any]]] = []
|
||||||
|
ssap_ws = _online_transport(sent_requests)
|
||||||
|
|
||||||
|
async def connect_fn(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return ssap_ws
|
||||||
|
|
||||||
|
config = _make_config(tmp_path)
|
||||||
|
mgr = TvManager(config, connect_fn=connect_fn, backoff_steps=(10.0,))
|
||||||
|
app = create_http_app(config, manager=mgr)
|
||||||
|
|
||||||
|
incoming: list[MutableMapping[str, Any]] = [
|
||||||
|
{"type": "lifespan.startup"},
|
||||||
|
{"type": "lifespan.shutdown"},
|
||||||
|
]
|
||||||
|
startup_done = asyncio.Event()
|
||||||
|
allow_shutdown = asyncio.Event()
|
||||||
|
|
||||||
|
async def receive() -> MutableMapping[str, Any]:
|
||||||
|
if incoming[0]["type"] == "lifespan.shutdown":
|
||||||
|
await allow_shutdown.wait()
|
||||||
|
return incoming.pop(0)
|
||||||
|
|
||||||
|
async def send(msg: MutableMapping[str, Any]) -> None:
|
||||||
|
if msg["type"] == "lifespan.startup.complete":
|
||||||
|
startup_done.set()
|
||||||
|
|
||||||
|
async def _run_lifespan() -> None:
|
||||||
|
await app({"type": "lifespan"}, receive, send)
|
||||||
|
|
||||||
|
lifespan_task: asyncio.Task[None] = asyncio.create_task(_run_lifespan())
|
||||||
|
try:
|
||||||
|
await asyncio.wait_for(startup_done.wait(), timeout=2.0)
|
||||||
|
transport = httpx.ASGITransport(app=app)
|
||||||
|
async with httpx.AsyncClient(
|
||||||
|
transport=transport, base_url="http://127.0.0.1:8765"
|
||||||
|
) as client:
|
||||||
|
resp = await client.post(
|
||||||
|
"/mcp",
|
||||||
|
headers={
|
||||||
|
"Authorization": "Bearer test-bearer-token",
|
||||||
|
"Accept": "application/json, text/event-stream",
|
||||||
|
},
|
||||||
|
json={
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"id": 1,
|
||||||
|
"method": "initialize",
|
||||||
|
"params": {
|
||||||
|
"protocolVersion": "2025-03-26",
|
||||||
|
"capabilities": {},
|
||||||
|
"clientInfo": {"name": "test-client", "version": "0.1.0"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert "lg-smtv-mcp" in resp.text
|
||||||
|
finally:
|
||||||
|
allow_shutdown.set()
|
||||||
|
await asyncio.wait_for(lifespan_task, timeout=2.0)
|
||||||
|
|
||||||
|
|
||||||
|
def _wire_capture_client_with_fake_ssh(
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
config: TvConfig,
|
||||||
|
) -> tuple[dict[str, Any], dict[str, bytes], list[str], list[dict[str, Any]], list[Any]]:
|
||||||
|
import lg_smtv_mcp.server as server_mod
|
||||||
|
|
||||||
|
captured: dict[str, Any] = {}
|
||||||
|
remote_files: dict[str, bytes] = {}
|
||||||
|
removed_paths: list[str] = []
|
||||||
|
connect_calls: list[dict[str, Any]] = []
|
||||||
|
sftp_sessions: list[Any] = []
|
||||||
|
|
||||||
|
class DummyManager:
|
||||||
|
async def start(self) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def close(self) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
class FakeSftp:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.closed = False
|
||||||
|
|
||||||
|
async def listdir(self, path: str) -> list[str]:
|
||||||
|
_ = path
|
||||||
|
return []
|
||||||
|
|
||||||
|
def open(self, path: str, mode: str = "r") -> Any:
|
||||||
|
_ = mode
|
||||||
|
|
||||||
|
class FakeFile:
|
||||||
|
async def __aenter__(self) -> FakeFile:
|
||||||
|
return self
|
||||||
|
|
||||||
|
async def __aexit__(self, *_exc: object) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def read(self) -> bytes:
|
||||||
|
return remote_files[path]
|
||||||
|
|
||||||
|
return FakeFile()
|
||||||
|
|
||||||
|
async def remove(self, path: str) -> None:
|
||||||
|
removed_paths.append(path)
|
||||||
|
remote_files.pop(path, None)
|
||||||
|
|
||||||
|
async def exit(self) -> None:
|
||||||
|
self.closed = True
|
||||||
|
|
||||||
|
class FakeSshConnection:
|
||||||
|
async def start_sftp_client(self) -> FakeSftp:
|
||||||
|
sftp = FakeSftp()
|
||||||
|
sftp_sessions.append(sftp)
|
||||||
|
return sftp
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def wait_closed(self) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def fake_tv_manager(cfg: Any, **kwargs: Any) -> DummyManager:
|
||||||
|
captured["config"] = cfg
|
||||||
|
captured["kwargs"] = kwargs
|
||||||
|
return DummyManager()
|
||||||
|
|
||||||
|
async def fake_connect(**kwargs: Any) -> FakeSshConnection:
|
||||||
|
connect_calls.append(kwargs)
|
||||||
|
return FakeSshConnection()
|
||||||
|
|
||||||
|
monkeypatch.setattr(server_mod, "TvManager", fake_tv_manager)
|
||||||
|
monkeypatch.setattr(asyncssh, "connect", fake_connect)
|
||||||
|
server_mod.create_mcp_server(config)
|
||||||
|
return captured, remote_files, removed_paths, connect_calls, sftp_sessions
|
||||||
|
|
||||||
|
|
||||||
|
async def test_server_create_mcp_server_wires_default_capture_client(
|
||||||
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||||
|
) -> None:
|
||||||
|
from lg_smtv_mcp.tv_core.capture import CaptureClient
|
||||||
|
|
||||||
|
config = _make_config(tmp_path)
|
||||||
|
captured, remote_files, removed_paths, connect_calls, sftp_sessions = (
|
||||||
|
_wire_capture_client_with_fake_ssh(monkeypatch, config)
|
||||||
|
)
|
||||||
|
|
||||||
|
assert captured["config"] is config
|
||||||
|
assert "capture_client" in captured["kwargs"]
|
||||||
|
capture_client = captured["kwargs"]["capture_client"]
|
||||||
|
assert isinstance(capture_client, CaptureClient)
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
assert uri == "ssap://com.webos.service.capture/executeOneShot"
|
||||||
|
remote_files[payload["path"]] = _TEST_JPEG
|
||||||
|
return {"returnValue": True}
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = await capture_client.capture_frame(ssap_request)
|
||||||
|
finally:
|
||||||
|
await capture_client.close()
|
||||||
|
|
||||||
|
assert result.image_bytes == _TEST_JPEG
|
||||||
|
assert len(connect_calls) == 1
|
||||||
|
assert connect_calls[0]["host"] == config.tv_ip
|
||||||
|
assert connect_calls[0]["port"] == 9922
|
||||||
|
assert removed_paths == ["/tmp/lg_smtv_cap_1.jpg"]
|
||||||
|
assert len(sftp_sessions) == 1
|
||||||
|
assert sftp_sessions[0].closed is True
|
||||||
|
|
||||||
|
|
||||||
|
async def test_server_create_mcp_server_wires_capture_downscaling_config(
|
||||||
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||||
|
) -> None:
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from lg_smtv_mcp.tv_core.capture import CaptureClient
|
||||||
|
|
||||||
|
config = TvConfig(
|
||||||
|
tv_ip="192.0.2.10",
|
||||||
|
client_key_path=tmp_path / ".client_key.json",
|
||||||
|
capture_max_width=640,
|
||||||
|
capture_jpeg_quality=60,
|
||||||
|
)
|
||||||
|
captured, remote_files, _removed_paths, _connect_calls, _sftp_sessions = (
|
||||||
|
_wire_capture_client_with_fake_ssh(monkeypatch, config)
|
||||||
|
)
|
||||||
|
|
||||||
|
capture_client = captured["kwargs"]["capture_client"]
|
||||||
|
assert isinstance(capture_client, CaptureClient)
|
||||||
|
|
||||||
|
buf = BytesIO()
|
||||||
|
Image.new("RGB", (1920, 1080), color=(30, 60, 90)).save(buf, format="JPEG", quality=95)
|
||||||
|
large_jpeg = buf.getvalue()
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = uri
|
||||||
|
remote_files[payload["path"]] = large_jpeg
|
||||||
|
return {"returnValue": True}
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = await capture_client.capture_frame(ssap_request)
|
||||||
|
finally:
|
||||||
|
await capture_client.close()
|
||||||
|
|
||||||
|
with Image.open(BytesIO(result.image_bytes)) as img:
|
||||||
|
assert img.format == "JPEG"
|
||||||
|
assert img.size == (640, 360)
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from lg_smtv_mcp.errors import ErrorCode, TvError
|
||||||
|
from lg_smtv_mcp.tv_core.protocols import WebSocketClosedError
|
||||||
|
from lg_smtv_mcp.tv_core.ssap import SsapClient
|
||||||
|
from tests.conftest import FakeWebSocketTransport
|
||||||
|
|
||||||
|
|
||||||
|
async def test_ssap_register_sends_all_permissions_even_with_saved_client_key() -> None:
|
||||||
|
def on_send(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg = json.loads(raw)
|
||||||
|
if msg["type"] == "register":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "registered",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {"client-key": "saved-key-123"},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
transport = FakeWebSocketTransport(on_send=on_send)
|
||||||
|
|
||||||
|
async def connect(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return transport
|
||||||
|
|
||||||
|
client = SsapClient("wss://192.0.2.10:3001", connect_fn=connect)
|
||||||
|
key = await client.connect_and_register("saved-key-123")
|
||||||
|
await client.close()
|
||||||
|
|
||||||
|
assert key == "saved-key-123"
|
||||||
|
reg_msg = json.loads(transport.sent[0])
|
||||||
|
assert reg_msg["type"] == "register"
|
||||||
|
assert reg_msg["payload"]["client-key"] == "saved-key-123"
|
||||||
|
expected_permissions = [
|
||||||
|
"LAUNCH",
|
||||||
|
"CONTROL_AUDIO",
|
||||||
|
"CONTROL_DISPLAY",
|
||||||
|
"CONTROL_POWER",
|
||||||
|
"CONTROL_INPUT_TEXT",
|
||||||
|
"CONTROL_INPUT_MEDIA_PLAYBACK",
|
||||||
|
"CONTROL_INPUT_JOYSTICK",
|
||||||
|
"CONTROL_INPUT_TV",
|
||||||
|
"CONTROL_TV_MEDIA",
|
||||||
|
"CONTROL_MOUSE_AND_KEYBOARD",
|
||||||
|
"READ_INSTALLED_APPS",
|
||||||
|
"READ_RUNNING_APPS",
|
||||||
|
"READ_INPUT_DEVICE_LIST",
|
||||||
|
"READ_TV_CHANNEL_LIST",
|
||||||
|
"READ_POWER_STATE",
|
||||||
|
"WRITE_NOTIFICATION_TOAST",
|
||||||
|
]
|
||||||
|
assert reg_msg["payload"]["manifest"]["permissions"] == expected_permissions
|
||||||
|
|
||||||
|
|
||||||
|
async def test_ssap_request_demuxes_interleaved_subscribe_push_frame() -> None:
|
||||||
|
sub_id_holder: list[str] = []
|
||||||
|
|
||||||
|
def on_send(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg = json.loads(raw)
|
||||||
|
if msg["type"] == "register":
|
||||||
|
ws.push_json({"type": "registered", "id": msg["id"], "payload": {"client-key": "k"}})
|
||||||
|
elif msg["type"] == "subscribe":
|
||||||
|
sub_id_holder.append(msg["id"])
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {"subscribed": True, "returnValue": True, "volume": 10},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
elif msg["type"] == "request":
|
||||||
|
# Push a subscribe update frame BEFORE the request response frame.
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": sub_id_holder[0],
|
||||||
|
"payload": {"returnValue": True, "volume": 10, "mute": True},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {"returnValue": True, "muteApplied": True},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
transport = FakeWebSocketTransport(on_send=on_send)
|
||||||
|
|
||||||
|
async def connect(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return transport
|
||||||
|
|
||||||
|
client = SsapClient("wss://192.0.2.10:3001", connect_fn=connect)
|
||||||
|
await client.connect_and_register("k")
|
||||||
|
|
||||||
|
updates: list[dict[str, Any]] = []
|
||||||
|
await client.subscribe("ssap://audio/getStatus", updates.append)
|
||||||
|
resp = await client.request("ssap://audio/setMute", {"mute": True})
|
||||||
|
await asyncio.sleep(0)
|
||||||
|
await client.close()
|
||||||
|
|
||||||
|
assert resp == {"returnValue": True, "muteApplied": True}
|
||||||
|
assert updates[-1]["mute"] is True
|
||||||
|
|
||||||
|
|
||||||
|
async def test_ssap_connect_maps_1008_and_timeout_to_tv_offline_standby() -> None:
|
||||||
|
transport_1008 = FakeWebSocketTransport()
|
||||||
|
transport_1008.push_close(1008, "Try Again Later (EWS)")
|
||||||
|
|
||||||
|
async def connect_1008(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return transport_1008
|
||||||
|
|
||||||
|
client_1008 = SsapClient("wss://192.0.2.10:3001", connect_fn=connect_1008)
|
||||||
|
with pytest.raises(TvError) as exc_1008:
|
||||||
|
await client_1008.connect_and_register("k")
|
||||||
|
assert exc_1008.value.code is ErrorCode.TV_OFFLINE_STANDBY
|
||||||
|
|
||||||
|
async def connect_timeout(_url: str) -> FakeWebSocketTransport:
|
||||||
|
raise TimeoutError("handshake timed out")
|
||||||
|
|
||||||
|
client_timeout = SsapClient("wss://192.0.2.10:3001", connect_fn=connect_timeout)
|
||||||
|
with pytest.raises(TvError) as exc_timeout:
|
||||||
|
await client_timeout.connect_and_register("k")
|
||||||
|
assert exc_timeout.value.code is ErrorCode.TV_OFFLINE_STANDBY
|
||||||
|
|
||||||
|
|
||||||
|
async def test_ssap_register_maps_prompt_to_pairing_required() -> None:
|
||||||
|
def on_send(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg = json.loads(raw)
|
||||||
|
if msg["type"] == "register":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {"pairingType": "PROMPT", "returnValue": True},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
transport = FakeWebSocketTransport(on_send=on_send)
|
||||||
|
|
||||||
|
async def connect(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return transport
|
||||||
|
|
||||||
|
client = SsapClient("wss://192.0.2.10:3001", connect_fn=connect)
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await client.connect_and_register(None)
|
||||||
|
assert exc_info.value.code is ErrorCode.PAIRING_REQUIRED
|
||||||
|
assert transport.closed is True
|
||||||
|
|
||||||
|
|
||||||
|
async def test_ssap_request_maps_return_value_false_and_401_to_domain_errors() -> None:
|
||||||
|
def on_send(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg = json.loads(raw)
|
||||||
|
if msg["type"] == "register":
|
||||||
|
ws.push_json({"type": "registered", "id": msg["id"], "payload": {"client-key": "k"}})
|
||||||
|
elif msg["type"] == "request":
|
||||||
|
if msg["uri"] == "ssap://fail/cmd":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "response",
|
||||||
|
"id": msg["id"],
|
||||||
|
"payload": {"returnValue": False, "errorText": "bad target"},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
elif msg["uri"] == "ssap://settings/getSystemSettings":
|
||||||
|
ws.push_json(
|
||||||
|
{
|
||||||
|
"type": "error",
|
||||||
|
"id": msg["id"],
|
||||||
|
"error": "401 insufficient permissions",
|
||||||
|
"payload": {"returnValue": False},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
transport = FakeWebSocketTransport(on_send=on_send)
|
||||||
|
|
||||||
|
async def connect(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return transport
|
||||||
|
|
||||||
|
client = SsapClient("wss://192.0.2.10:3001", connect_fn=connect)
|
||||||
|
await client.connect_and_register("k")
|
||||||
|
|
||||||
|
with pytest.raises(TvError) as exc_cmd:
|
||||||
|
await client.request("ssap://fail/cmd")
|
||||||
|
assert exc_cmd.value.code is ErrorCode.COMMAND_FAILED
|
||||||
|
|
||||||
|
with pytest.raises(TvError) as exc_perm:
|
||||||
|
await client.request("ssap://settings/getSystemSettings")
|
||||||
|
assert exc_perm.value.code is ErrorCode.PAIRING_REQUIRED
|
||||||
|
|
||||||
|
await client.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_ssap_reader_loop_finally_fails_pending_futures_with_standby_error() -> None:
|
||||||
|
def on_send(raw: str, ws: FakeWebSocketTransport) -> None:
|
||||||
|
msg = json.loads(raw)
|
||||||
|
if msg["type"] == "register":
|
||||||
|
ws.push_json({"type": "registered", "id": msg["id"], "payload": {"client-key": "k"}})
|
||||||
|
elif msg["type"] == "request":
|
||||||
|
# Drop the socket instead of answering the request.
|
||||||
|
ws.push_error(WebSocketClosedError(1008, "Try Again Later (EWS)"))
|
||||||
|
|
||||||
|
transport = FakeWebSocketTransport(on_send=on_send)
|
||||||
|
|
||||||
|
async def connect(_url: str) -> FakeWebSocketTransport:
|
||||||
|
return transport
|
||||||
|
|
||||||
|
disconnected: list[ErrorCode] = []
|
||||||
|
client = SsapClient(
|
||||||
|
"wss://192.0.2.10:3001",
|
||||||
|
connect_fn=connect,
|
||||||
|
on_disconnect=disconnected.append,
|
||||||
|
)
|
||||||
|
await client.connect_and_register("k")
|
||||||
|
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await client.request("ssap://audio/getStatus")
|
||||||
|
assert exc_info.value.code is ErrorCode.TV_OFFLINE_STANDBY
|
||||||
|
await asyncio.sleep(0)
|
||||||
|
assert disconnected == [ErrorCode.TV_OFFLINE_STANDBY]
|
||||||
|
await client.close()
|
||||||
Reference in new issue
Block a user