diff --git a/.github/workflows/wearos.yml b/.github/workflows/wearos.yml new file mode 100644 index 0000000..c73e06d --- /dev/null +++ b/.github/workflows/wearos.yml @@ -0,0 +1,44 @@ +name: Wear OS watch client +on: + pull_request: + paths: + - 'clients/wearos/**' + - '.github/workflows/wearos.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + watch: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - name: Check out source + uses: actions/checkout@v4 + - name: Set up Java 17 + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + - name: Use runner Android SDK + shell: bash + run: | + echo "Android SDK: $ANDROID_HOME" + SDKMANAGER="$(find "$ANDROID_HOME/cmdline-tools" -type f -name sdkmanager | head -n 1)" + test -x "$SDKMANAGER" + "$SDKMANAGER" --version + "$SDKMANAGER" "platforms;android-35" "build-tools;35.0.0" + - name: Set up Gradle 8.13 + uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '8.13' + - name: Check unit protocol and compile debug APK + run: gradle -p clients/wearos :app:testDebugUnitTest :app:assembleDebug --stacktrace --no-daemon + - name: Upload debug APK for watch testing + if: success() + uses: actions/upload-artifact@v4 + with: + name: patchbay-watch-debug + path: clients/wearos/app/build/outputs/apk/debug/app-debug.apk + if-no-files-found: error diff --git a/clients/wearos/DEVICE_TEST_HANDOFF.md b/clients/wearos/DEVICE_TEST_HANDOFF.md new file mode 100644 index 0000000..5d78609 --- /dev/null +++ b/clients/wearos/DEVICE_TEST_HANDOFF.md @@ -0,0 +1,152 @@ +# PatchBay Wear — Watch6 Classic field validation & Claude Code handoff + +**Recorded:** 2026-11-01 +**Repository:** `Platano78/patchbay` +**Active implementation branch:** `feat/wearos-charm-client` — [draft PR #3](https://github.com/Platano78/patchbay/pull/3) +**Documentation delivery:** separate `handoff/wearos-device-validation-20261101` branch to avoid moving the watch implementation branch while device-tested fixes are still local. + +> **Evidence provenance:** The observations in this document were reported by the owner from a hands-on Claude Code/ADB session on the Samsung Galaxy Watch6 Classic. The author of this handoff has **not** independently inspected the unpushed local code or physical watch. Treat the session report as a verified-by-operator baseline, and reverify critical assertions before modifying the working client. + +## 0. Mission and architectural boundary + +Bring the *already working* PatchBay Wear client into a safe, reviewable state, solve the remaining usability problems, and validate on the physical device. **Do not redesign PatchBay.** + +The watch is a thin, native Wear OS expression of **one existing, self-hosted PatchBay**. The same core owns the model, persona, STT, tools, conversation state, and TTS. The watch owns microphone, speaker, animation and UI. EchoBay, desktop cockpit and future ESP32 endpoints are other expressions of the same core. Muse is only possible **hardware-driver reference material** for future ESP32 endpoints; neither Muse firmware nor Muse services belong in this watch task. + +Do not introduce a watch AI runtime, alternate voice backend, new agent framework, second assistant session, phone bridge, or cloud dependency. Do not edit or restart the production PatchBay server unless a measured defect actually requires it and the owner approves. + +## 1. Git state: do this first + +**The device-tested fixes are on the owner's local checkout, not yet pushed. Preserve them.** + +At the time this handoff was authored: +- The GitHub PR #3 feature head was `e98aee01f06a4b73fd7102a11d2f1d2952dee06d` (remote evidence). +- The owner reports the *local* watch fixes are committed on the same feature branch as `f2fa4a4`. +- The owner has explicitly approved **pushing the validated fixes**, but **not merging PR #3**. +- The separate handoff branch contains only this markdown file based on the older remote feature head. + +From the owner's local repository: + +```sh +git status --short --branch +git branch --show-current +git log --oneline -8 +git fetch origin +git rev-parse origin/feat/wearos-charm-client +git show --stat --oneline f2fa4a4 +git diff --stat origin/feat/wearos-charm-client...HEAD +``` + +**Do not run `reset --hard`, `clean -fdx`, rebase a dirty tree, or force-push.** If `f2fa4a4` is not found, the working tree isn't the expected one, or the branch has unexpected changes, stop and present the observed Git state for owner approval. Do not reproduce or overwrite the device-tested code from memory. + +Bring this documentation commit into the local feature branch *without altering the remote feature branch first*. On a clean local feature branch, after checking that the handoff branch is based on the expected remote head: + +```sh +git fetch origin handoff/wearos-device-validation-20261101 +git log --oneline -2 origin/handoff/wearos-device-validation-20261101 +git cherry-pick origin/handoff/wearos-device-validation-20261101 +``` + +The cherry-pick should add only `clients/wearos/DEVICE_TEST_HANDOFF.md`. If it is already present or history has changed, avoid duplicating it and explain what you found. + +### Pre-push safety inspection + +Inspect **every changed path** relative to the remote feature branch, and confirm the five fixes and their tests are present. Review for accidentally committed secrets, private audio, `brains.json`, signing keys, local configuration, ADB serials, watch identifiers, exact home IP addresses, raw debug logs, or recordings. In particular, never publish scratch recordings or keystore material. + +Then, when the branch is clean and the expected files are present, push to the **existing feature branch only**: + +```sh +git push origin feat/wearos-charm-client +``` + +Never force-push or merge PR #3. Verify the remote HEAD matches the pushed commit and record the CI run result. If GitHub has advanced meanwhile, fetch and reconcile before pushing. + +## 2. Field results (owner-reported, 2026-11-01) + +| Test | Outcome and limits | +| --- | --- | +| Device / ADB | Samsung Galaxy Watch6 Classic, model SM-R960; Android 16; Linux ADB 34.0.5; wireless pairing/connection succeeded. The ADB connection port changes after Wi-Fi toggles; pairing persists. | +| Install | `com.patchbay.wear` 0.1.0 installed. The current working APK is a **locally built debug APK** using the Linux machine's signing key. The GitHub CI APK uses a different key. | +| Launch | App launches, no observed crash. | +| Server | Existing PatchBay WebSocket on trusted home LAN; no new public port or network exposure. | +| Screens | Ready, Listening, Working, Speaking observed; mouth reacts during TTS. Last Reply and bezel scrolling **not tested**. | +| Voice | 12 consecutive complete turns: watch mic → PatchBay transcription/brain → existing TTS → watch speaker → Ready. | +| Long TTS | 17–20 second answers played to final audio frame after playback-drain fix; no reported echo or dropped connections. | +| Web search | Tool-bearing replies survived 3–6 second pauses after handling search-in-progress correctly. | +| Background | Mic/speaker released about **one second after app exit**, not immediately. Needs lifecycle investigation only if reproducible/important. | +| Wi-Fi failure | Mic released immediately; no stale uplink audio replay after reconnect. | +| UX faults | Settings Back/Save buttons partly cut off by round display; entering URL with `adb input text` loses characters on Samsung keyboard; operator temporarily wrote app setting through ADB. | +| Short phrases | Very short quiet questions sometimes fail speech recognition. | +| Tests | Owner reports **6/6 unit tests passing** on local changes; a prior assertion concerning search-turn behavior was intentionally updated. Confirm in code. | + +Five reported **code** fixes on `f2fa4a4`: +1. Switch mic capture source to speech recognition and apply a bounded/fixed capture boost, after separate **physical cleaning of the watch mic port**. Samsung Voice Recorder was also near-silent before cleaning. Keep physical and software causes distinct. +2. End speech only after the speaker **actually drains playback**, not merely after the last incoming network frame. +3. Increase effective playback queue budget to approximately **60 seconds** to tolerate network audio arriving faster than speaker output. +4. Respect web-search/tool pauses rather than prematurely closing the response. +5. Return from the Working state after approximately **40 seconds** without a reply. + +A voice stream of 16 kHz, mono, signed 16-bit PCM consumes **32,000 bytes per second**; a 60-second queue budget is about **1.92 MB** of raw PCM. Inspect actual queue implementation, error handling and peak device memory rather than assuming this is free. + +## 3. Current work order (keep scope deliberately small) + +### Gate A — Preserve the known-good working build + +- Verify branch and commit provenance, review the actual five fixes and the changed search test, and retain operator evidence. +- Cherry-pick this documentation only if appropriate, safety-check the diff, then push the tested local branch to PR #3. +- Verify a fresh GitHub Actions run compiles and passes `testDebugUnitTest`, and emits the expected debug APK. +- Do **not** replace the working local debug APK on the watch with GitHub's differently signed APK merely to prove the artifact exists. An uninstall would discard app data and needs owner approval. + +### Gate B — Fix the genuine watch UI defects + +1. **Round-screen clipping:** make Settings Back and Save reachable and fully inside circular safe bounds on the real Watch6 Classic. Use scroll, responsive spacing, and IME-aware focus. Do not simply shrink controls below accessible touch sizes. Confirm with a physical screenshot and taps. +2. **Usable endpoint entry:** validate entry and persistence from the actual watch UI without editing SharedPreferences through ADB. First distinguish a limitation of `adb input text` from Samsung's real on-watch keyboard. Do not invent a phone companion if on-watch typing works. If manual entry fails, propose and implement the smallest self-contained reliable method; keep no hard-coded address or public token in the APK. +3. **Last Reply:** display the actual last reply and prove bezel scrolling on the physical watch. +4. Retest Ready/Listening/Working/Speaking visuals after layout changes. + +### Gate C — Natural short-speech reliability + +- Reproduce failures with at least five short/quiet utterances and log evidence, without storing raw audio unnecessarily. +- Distinguish hardware mic-port obstruction, capture-source effects, playback echo, clipping and server VAD/STT sensitivity. +- Check actual sample levels and clipping after the fixed boost. Do not increase gain blindly; prefer bounded gain and tests. +- Keep voice capture half-duplex, foreground-only, and correct at 16 kHz mono PCM16. +- Fix only a demonstrated app-side defect; server global VAD changes need explicit scope/approval. + +### Gate D — Measurements and remaining checks + +- Repeat at least ten end-to-end watch turns after any code changes; include a 20-second TTS and a web-search answer. +- Capture empirical end-to-end latency and approximate watch battery impact over **20 interactions** plus an idle baseline; label small samples as preliminary, not laboratory measurements. +- Test background release latency, screen off, Wi-Fi loss/recovery and stale-audio discard. +- Test TalkBack at least once; note untested font-scale/43mm behavior if only the 47mm watch is available. +- Test simultaneous desktop cockpit and watch interaction. **Important:** current PatchBay broadcasts TTS to every client and shares a conversation; listening gating is not proven client isolation. Record this behavior; **do not** redesign server routing during this work. +- Measure playback queue memory and verify that correct network-frame arrival does not imply playback completion. + +### Gate E — Cleanup and report + +- The owner reported a temporary Voice Recorder entry (named `Voice 001`) and scratch test recordings on the Linux host. **Ask owner approval before deleting recordings** and confirm exact paths/filenames before any removal. Never commit them. +- Keep changes on `feat/wearos-charm-client`; use small, descriptive commits and push only after tests. +- Update `clients/wearos/README.md` and `SPEC.md` with what is **actually** verified, correcting stale remote statements. +- Keep draft PR #3 **draft and unmerged**. +- Final report must separate: **observed pass / observed fail / untested**, commits and CI URL, installed APK signing status, fixes made, remaining risks, and whether daily home use remains viable. + +## 4. Non-goals / operating constraints + +- No Muse firmware/service; no new cloud account; no other brain, memory, tools or TTS on watch. +- No full Embodiment Android application on Wear OS. +- No Tailscale/mobile relay or remote access in this acceptance cycle; don't assume the watch inherits a paired phone VPN. +- No public forwarding of PatchBay's unauthenticated WebSocket. +- No new protocol / turn isolation project unless the existing shared-session behavior is demonstrated to break watch use and the owner approves a separate scope. +- No wholesale refactor or enterprise control framework. +- No reset, uninstall, or signing-key replacement without the owner's explicit approval. +- Follow repository `AGENTS.md` and `docs/contracts/ws-client-protocol.md`. + +## 5. Stop conditions + +Stop and ask the owner if any of the following occurs: +- The expected local `f2fa4a4` commit, branch, or device-tested fixes cannot be found. +- A dirty or diverged Git history cannot be reconciled by a safe fast-forward/cherry-pick. +- A fix requires restarting production PatchBay, modifying server-global voice VAD, adding a companion app or changing its WebSocket protocol. +- Debug APK signing mismatch would require uninstall and loss of device settings. +- A proposed cleanup includes files not created by this session or whose origin is unclear. + +Everything else: perform focused investigation, implement minimal verified fixes, test them on device and CI, and document the result. diff --git a/clients/wearos/README.md b/clients/wearos/README.md new file mode 100644 index 0000000..d9db723 --- /dev/null +++ b/clients/wearos/README.md @@ -0,0 +1,100 @@ +# PatchBay Wear — native Samsung Galaxy Watch6 Classic client + +A small Wear OS application that turns the watch into **another physical expression of your existing PatchBay**, not a new assistant. It captures 16kHz mono PCM, streams it to PatchBay, plays the existing TTS, and animates an original 2D face. + +**Status:** prototype, usable for everyday experimentation on a home network. Verified on a physical Galaxy Watch6 Classic (47 mm, SM-R960, Android 16 / SDK 36) on 2026-11-01; see [Verified on a Watch6 Classic](#verified-on-a-watch6-classic). Gates still open are in SPEC.md section 8. + +## Prerequisites + +- Samsung Galaxy Watch6 Classic with Wear OS and wireless debugging enabled +- Android Studio with SDK Platform 35, Android build-tools and JDK 17 +- Gradle 8.13 (the independent prototype deliberately does not contain a binary wrapper) +- Existing PatchBay pipeline running on a trusted home network +- The LAN IPv4 address of the PatchBay server and port (default 8765) + +The implementation lives entirely under `clients/wearos/`; no other PatchBay code is modified. Open **clients/wearos** as its own Android Studio project. + +## Build + +```bash +gradle -p clients/wearos :app:testDebugUnitTest :app:assembleDebug +``` + +The unsigned debug APK will be at `clients/wearos/app/build/outputs/apk/debug/app-debug.apk` **only after a successful build**. + +In Galaxy Watch settings, enable Developer options and Wireless debugging, then connect with ADB (including its current IP:port and any pairing step required by the watch): + +```bash +adb pair WATCH_IP:PAIRING_PORT +adb connect WATCH_IP:DEBUG_PORT +adb install -r clients/wearos/app/build/outputs/apk/debug/app-debug.apk +``` + +On the watch, launch PatchBay from Apps. You may optionally assign the watch's Home-key double-press shortcut to this app in Samsung's settings. No root, firmware replacement or new watch face required. + +## Configure and use + +1. In the watch app, turn the bezel (or swipe up) to reach **Settings**. Type your PatchBay server's LAN IP address on the on-screen keypad, for example `192.168.x.x`; port 8765 is added for you (type `ip:port` for another port). For a `wss://` address, tap **Full URL** to use the system keyboard instead. +2. Save; the app connects and requests `config_get`. +3. Tap the central character to start talking. Grant microphone permission if prompted. +4. Tap again to finish. The app drains the capture and sends VAD silence. +5. Hear the existing PatchBay answer from the watch speaker; view the latest response via **Reply**. +6. If offline, tap the face to retry. Leaving the app disconnects and releases the mic/speaker. + +## Networking / security + +PatchBay's current WebSocket is unauthenticated and shared by all clients. **Never port-forward it**. For this proof-of-use, `ws://` is limited by the client to RFC1918 IPv4 destinations on trusted home Wi-Fi. `wss://` is also supported without certificate bypass, but the network perimeter must still be authenticated. Phone-based or VPN remote connectivity has **not been implemented**; a paired phone does not magically forward its VPN. + +No local AI model, agent, speech model, or independent memory is shipped in this APK. No conversation data is saved to storage. The watch only plays audio when its own PTT initiated a turn. Because the server broadcasts all speech, simultaneous multi-client use needs a later protocol improvement for guaranteed isolation. + +## Repo map + +- `SPEC.md` — product contract, limitations and acceptance gates +- `app/src/main/java/com/patchbay/wear/WatchScreen.kt` — circular Compose UI + vector character +- `WatchController.kt` — foreground session, PTT, UI phases +- `WatchAudio.kt` — microphone and speaker streams +- `PatchbaySocket.kt` — WebSocket to existing server +- `PatchbayProtocol.kt` — URL restriction, event parser, PCM helpers +- `app/src/test/` — focused unit tests: protocol, endpoint entry, uplink gain, capture statistics +- `.github/workflows/wearos.yml` in repository root — Android CI build + +## Verified on a Watch6 Classic + +Observed on one 47 mm SM-R960 (Android 16) against a live PatchBay on 2026-11-01. Small samples: read the numbers as preliminary, not benchmarks. + +| Area | Result | +|---|---| +| Install, launch, connect | Pass. Debug APK installs and launches; the socket connects and `config_state` arrives. | +| Voice turns | 30+ turns over the evening; 6/6 short, quiet phrases ("Thanks.", "Stop.") on the final build. | +| Long replies | Replies of 17-20 s played to the last frame. | +| Web-search turns | The answer survives the 3-6 s silent gap while the tool runs. | +| Round-screen layout | Every control on Home, Settings and Last Reply scrolls fully inside the circle (screenshots and taps on the device). | +| Server address entry | The in-app keypad cleared and retyped the IP, saved it as `ws://:8765` and reconnected, driven by taps over adb. Owner hand test still pending; the system keyboards it replaces failed by hand. | +| Last Reply | Shows the latest answer (owner check). | +| Leaving the app | Mic and speaker released ~1 s after exit. | +| Wi-Fi off and on | Mic released at once; no stale audio replayed after reconnecting. | +| Latency | Second tap to first reply audio: median 1.31 s (0.87-1.62 s, 6 short turns, no tools). | +| Memory | 86 MB PSS, 7.8 MB Java heap at idle. | +| Mic levels | Final build, 7 turns: speech peaks of 25-101 RMS (int16) per 200 ms before gain; 0 clipped samples, 0% post-gain saturation. | + +Every turn writes one `PatchBayWear` logcat line with capture levels (numbers, never audio), so a "no answer" report can be split into "the mic heard nothing" and "the server ignored it". + +## Known limitations + +- **Shared session.** PatchBay broadcasts TTS to every connected client. The watch only plays audio for a turn it started, but a desktop cockpit that is open at the same time will also speak the answers to watch questions. Interleaved desktop + watch use is untested. +- **No TTS-done event.** A reply ends when no audio has arrived for 1.6 s, the speaker has played everything it was given, and no tool call is pending (the server's empty-text `assistant_text` with `tools`). +- **Server TTS cap.** PatchBay's remote TTS stops a reply that takes longer than 15 s to synthesize (`remote_speech_max_duration_s`). When the TTS host is busy and synthesizes at about real time, long answers are cut near 15 s on every client, not only the watch. +- **Very short, quiet phrases** can fall under the server VAD's 384 ms active-speech floor. During testing, 4 turns were lost this way, all within one 8-minute stretch that ended after the owner checked the watch's mic again; none were lost in the 20+ turns after it. Capture uses `VOICE_RECOGNITION` plus a fixed +15.6 dB soft-clipped gain; `VOICE_COMMUNICATION` delivered near-silence on the SM-R960. +- **Check the mic hardware first** if no turn is ever transcribed: record in Samsung Voice Recorder and play it back. A partly blocked mic port caused exactly this during testing (blow it out gently or use a soft brush; no pins). +- **Leaving the app** releases mic and speaker about 1 s later: teardown runs in `onStop`, after the exit animation. Moving it to `onPause` would also tear down the session whenever the microphone permission dialog appears. +- **Home network only.** Away from home the watch reaches the internet through the phone's Bluetooth proxy, which reportedly does not carry the phone's VPN (not tested here). Tailscale has no official Wear OS app, and plain `ws://` is restricted to RFC1918 addresses by design. +- **Not measured yet:** battery over a 20-turn session, TalkBack, font scaling, the 43 mm model, and explicit owner confirmation of bezel scrolling on Last Reply. +- No Gradle wrapper binary bundled; use Gradle 8.13 via Android Studio or CLI. +- Signing: a locally built debug APK and the CI artifact use different debug keys. Switching between them needs an uninstall, which clears the saved server address. + +## Future enhancements (not started) + +- An explicit end-of-speech event from the server, replacing the quiet-interval rule. +- Per-client audio routing or turn identifiers, so a watch turn is not spoken by other open clients. +- Remote use: an authenticated private path (for example a `wss://` endpoint on a tailnet) plus a vetted way for the watch itself to join it. Needs its own experiment and a server-side change. +- A watch complication or tile to launch PatchBay from the watch face. diff --git a/clients/wearos/SPEC.md b/clients/wearos/SPEC.md new file mode 100644 index 0000000..9f91c55 --- /dev/null +++ b/clients/wearos/SPEC.md @@ -0,0 +1,126 @@ +# PatchBay Wear: Watch6 Classic expression + +**Status:** draft branch; built in CI and verified on a physical Watch6 Classic (47 mm) for gates A0-A6 and most of A7 (see section 8, updated 2026-11-01) +**Target:** Samsung Galaxy Watch6 Classic, 43 mm or 47 mm, Wear OS +**Date:** 2026-10-31 + +## 1. Product promise + +PatchBay exists already. The watch is a **physical expression of the same PatchBay agent**, not an agent of its own. No distinct model, persona, memory, tools, speech recognition, or speech synthesizer may be introduced to the watch. The voice on the watch is the voice configured in the existing PatchBay. + +> Double-press the watch Home key (after the user configures the shortcut), tap the character, speak a question, tap to finish, and hear PatchBay's answer from the watch speaker. The watch displays a reactive 2D character. + +No new hardware purchase is needed for the first acceptance program. + +## 2. Design and behavior + +- Keep the normal Samsung watch face. This is a foreground Wear OS application, not a replacement watch face. +- Original simple 2D avatar occupies the center of a circular OLED-first design; oversized hit area serves as the only main command. +- Ready: blue ring, relaxed face, "Tap to talk". +- Listening: teal ring, mouth/reactive level, "Tap again when finished". +- Waiting: violet ring, three dots; describes server activity without pretending to visualize internal reasoning. +- Speaking: blue ring, mouth openness from decoded PCM amplitude. No claim of viseme accuracy. +- Offline/error: warm red status and explicit retry. +- Latest answer: separate readable, bezel-scrollable view. No full conversation browser. +- Settings: one server address, typed on an in-app 0-9 / . / delete keypad as a bare private IPv4 (optionally `:port`; saved as `ws://:8765`). "Full URL" switches to the system keyboard for `wss://`. No brain chooser, no model tuning, no local agent configuration. (The system keyboards could not enter an IP on the Watch6 Classic: QWERTY needs page switches for every symbol, the decimal pad allows one dot, the phone pad has no dot.) +- Round screen: Home, Settings and Last Reply scroll with touch and the rotating bezel, with padding scaled to the display, so no control is left at the narrow bottom of the circle. +- Accessibility: descriptive click labels, readable text, large touch target; animation respects system-wide animator disable where practical. +- Layout must be evaluated on both watch sizes (432x432 and 480x480 physical pixel variants), font scaling, and TalkBack. + +Palette: near-black #05070D; navy #13243B; text #E8F7FF; ready #77CFFF; listening #50E5C2; waiting #C29BFF; speaking #6DB7FF; error #FF9D94. + +## 3. Reuse boundary + +**Existing server:** `patches/websocket_streamer.py` and the published `docs/contracts/ws-client-protocol.md` are the protocol source of truth. + +**Existing phone research:** `Platano78/phonelinux` contains `LifelineSocket.kt` and `LifelineSession.kt`. Their websocket, turn-end silence, and audio playback ideas inform this implementation. The full Embodiment APK, local models, native libraries, and its local decision making are **not** embedded in Wear. + +**New client:** `clients/wearos/` is the entire build boundary. No modifications to PatchBay server semantics or production configuration are required for this first experiment. + +## 4. Protocol and voice turn + +One WebSocket connection to the existing server on port 8765 (unless a private gateway gives it another URL). + +- Binary frames carry signed little-endian 16-bit mono PCM at exactly 16000 Hz, in both directions. +- Text frames contain JSON with `type` discriminator, not `event_type`. +- On open, send `{"type":"config_get"}`. +- Observe `transcription_completed`, `partial_transcription`, and non-empty `assistant_text`. Ignore unknown server events. +- On PTT release, stop/drain the microphone and send 2 seconds of PCM zeroes to close the server VAD turn; this mirrors Lifeline. +- Do not capture through spoken playback; no continuous wake word in v0.1. +- Handle arbitrary TTS frame boundaries in a continuous AudioTrack stream. +- There is no server-emitted explicit completion-of-TTS event for this audio path. A reply ends only when (a) no audio arrived for 1.6 s, (b) the AudioTrack has played out every frame written (the server streams ~2x faster than real time, so arrival-quiet alone cut replies short), and (c) no tool call is pending (empty-text `assistant_text` carrying `tools`, until the answer frame). The playback queue is bounded at 60 s of audio, not by chunk count. An explicit server event would still be cleaner, in a separate protocol PR. +- UI only plays audio after the wearer initiated a PTT turn, while the app is foreground. This is a mitigation, **not** true per-client routing; simultaneous clients remain a known limitation. + +## 5. Network and confidentiality + +- The current PatchBay raw WebSocket has **no application-level login**. It also shares the same conversation and broadcasts TTS to all connected clients. +- **Do not** expose port 8765 to the public internet. +- Development uses `ws://` only with a manually specified RFC1918 IPv4 address on a trusted home Wi-Fi network. +- `wss://` endpoints must validate their TLS certificates normally. Encryption is **not authentication**; remote access still requires a real authenticated private path. +- The Android watch's network connection via a paired phone does not imply access to the phone's private VPN. That requires its own on-device test. +- Store only the user-specified URL in app preferences. No GPS, voice recordings, tokens or transcript history are persisted. The most recent speech text remains in RAM only. +- On background, the socket, playback, and microphone are torn down. Stale uplink audio may not be replayed on reconnect. + +## 6. Architecture + +``` +Watch6 Classic (Wear OS, foreground) + MainActivity + WatchScreen (Compose + Canvas original avatar) + WatchController (phase + state) + WatchMicrophone (AudioRecord PCM16/16k) + WatchSpeaker (AudioTrack PCM16/16k) + PatchbaySocket (OkHttp WebSocket) + | binary audio, text control/events | + v + Existing PatchBay speech-to-speech pipeline :8765 + ASR -> currently selected brain/persona/tools -> existing TTS +``` + +## 7. Explicitly deferred + +- A phone companion: only add Android Wear Data Layer ChannelClient or another phone relay **after** local Wi-Fi proves the interaction is worthwhile. +- True per-client session audio isolation or request/turn identifiers (server protocol change). +- Background/always listening, AI on the watch, watch-face replacements, voice cloning, local notifications, or floating agent surfaces. +- New cloud services and new hardware. + +## 8. Test and acceptance program + +| Gate | Evidence required | +|---|---| +| A0 | Gradle resolves dependencies; `testDebugUnitTest` and `assembleDebug` pass in CI | +| A1 | Debug APK installs and launches on actual Galaxy Watch6 Classic | +| A2 | A real home Wi-Fi socket connects; configuration event arrives | +| A3 | Ten PTT turns: correct start, final-silence VAD completion, correct transcript | +| A4 | Ten returned TTS answers: intelligible, uninterrupted, no self-feedback | +| A5 | Watch screen off/background: mic, socket, speaker stop; nothing spoken unsolicited | +| A6 | Connection drop mid-turn: no buffered audio is replayed after retry | +| A7 | Circular layout and TalkBack verified on actual watch; rotary reply scrolling works | +| A8 | Interleaved desktop use explored; warn of shared-audio limitations rather than fake session privacy | +| A9 | Battery and latency measured over 20 interactions plus idle period; thresholds set from actual baseline | + +**Gate status (2026-11-01, one 47 mm SM-R960, Android 16; small samples, preliminary):** + +| Gate | Result | Evidence | +|---|---|---| +| A0 | Pass | CI green on every pushed head; 10 unit tests (protocol, endpoint entry, gain, capture stats). | +| A1 | Pass | Debug APK installed and launched; no crash seen. | +| A2 | Pass | Socket connects on home Wi-Fi; `config_state` arrives. | +| A3 | Pass, with a known edge | 30+ turns over the session; 6/6 short, quiet phrases on the final build. 4 turns were lost to the server VAD's 384 ms active-speech floor, all within one 8-minute stretch that ended after the owner checked the watch's mic again; none in the 20+ turns after. | +| A4 | Pass, with a server-side limit | Replies of 17-20 s played to the last frame; web-search answers survive 3-6 s tool gaps; no self-feedback. One reply was cut at 15 s by PatchBay's own remote-TTS synthesis cap while the TTS host was busy; that affects every client. | +| A5 | Pass | Mic and speaker released ~1 s after leaving the app (teardown in `onStop`). | +| A6 | Pass | Wi-Fi off mid-listen released the mic at once; nothing replayed after reconnect. | +| A7 | Partly | Circular layout: every control reachable inside the circle (device screenshots, taps). Address entry works through the in-app keypad (adb-driven taps; owner hand test pending). Last Reply shows the latest answer. Not done: TalkBack, font scaling, 43 mm model, owner confirmation of bezel scrolling. | +| A8 | Not done | Expected from the code: an idle watch stays silent during desktop turns, but the desktop cockpit speaks the answers to watch turns (server broadcast). Needs a hands-on check. | +| A9 | Partly | Latency, second tap to first reply audio: median 1.31 s (0.87-1.62 s, n=6, no tools). Memory at idle: 86 MB PSS. Battery over 20 turns + idle: not measured yet. Playback-queue peak memory: bounded by design at 60 s of PCM (1.92 MB), not measured on device. | + +## 9. Backlog only after acceptance + +1. Explicit audio-done and turn-origin metadata if multi-client use makes the current heuristic unsafe. +2. Outside-home use through an authenticated private path. Findings so far: the watch's Bluetooth proxy through the phone reportedly does not carry the phone's VPN (other users' reports, not tested here); Tailscale has no official Wear OS app; a `wss://` URL with a valid certificate already passes the client's validation, so the work is mostly server-side plus a vetted way for the watch to join the network. +3. Better 2D animation assets, more expressive mouth shapes, avatar/persona identity from existing PatchBay. +4. Optional watch complication to launch the app while retaining Samsung's watch face. + +## 10. Product success test + +The best metric isn't feature count. It is whether the owner naturally uses the watch for short conversations, without taking out the phone or touching the computer, and without disrupting current watch functionality. diff --git a/clients/wearos/app/build.gradle.kts b/clients/wearos/app/build.gradle.kts new file mode 100644 index 0000000..3881032 --- /dev/null +++ b/clients/wearos/app/build.gradle.kts @@ -0,0 +1,45 @@ +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.android") + id("org.jetbrains.kotlin.plugin.compose") +} + +android { + namespace = "com.patchbay.wear" + compileSdk = 35 + + defaultConfig { + applicationId = "com.patchbay.wear" + minSdk = 30 + targetSdk = 35 + versionCode = 1 + versionName = "0.1.0" + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + buildTypes { + release { isMinifyEnabled = false } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + kotlinOptions { jvmTarget = "17" } + buildFeatures { compose = true } +} + +dependencies { + implementation(platform("androidx.compose:compose-bom:2025.05.01")) + implementation("androidx.compose.ui:ui") + implementation("androidx.compose.ui:ui-graphics") + implementation("androidx.compose.foundation:foundation") + implementation("androidx.compose.animation:animation") + implementation("androidx.activity:activity-compose:1.10.1") + implementation("androidx.core:core-ktx:1.16.0") + implementation("androidx.wear.compose:compose-foundation:1.5.3") + implementation("androidx.wear.compose:compose-material3:1.5.3") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2") + implementation("com.squareup.okhttp3:okhttp:4.12.0") + + testImplementation("junit:junit:4.13.2") + testImplementation("org.json:json:20240303") +} diff --git a/clients/wearos/app/src/main/AndroidManifest.xml b/clients/wearos/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..a69bec4 --- /dev/null +++ b/clients/wearos/app/src/main/AndroidManifest.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + diff --git a/clients/wearos/app/src/main/java/com/patchbay/wear/MainActivity.kt b/clients/wearos/app/src/main/java/com/patchbay/wear/MainActivity.kt new file mode 100644 index 0000000..9f729d8 --- /dev/null +++ b/clients/wearos/app/src/main/java/com/patchbay/wear/MainActivity.kt @@ -0,0 +1,78 @@ +package com.patchbay.wear + +import android.Manifest +import android.content.pm.PackageManager +import android.os.Bundle +import android.view.WindowManager +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.core.content.ContextCompat + +/** Wear OS app, not a phone app. PatchBay remains the one and only agent. */ +class MainActivity : ComponentActivity() { + private val controller by lazy { WatchController(applicationContext) } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContent { Root() } + } + + override fun onStart() { + super.onStart() + controller.onForeground() + } + + override fun onStop() { + controller.onBackground() // no background microphone, socket, or playback + super.onStop() + } + + override fun onDestroy() { + controller.dispose() + super.onDestroy() + } + + @Composable + private fun Root() { + val state by controller.ui.collectAsState() + val permission = rememberLauncherForActivityResult( + ActivityResultContracts.RequestPermission() + ) { granted -> + if (granted) controller.toggleTalk() + else controller.permissionDenied() + } + + // A user-initiated voice turn should not be silently cut off by wrist-screen timeout. + // No always-on wakelock or service after the activity is hidden. + DisposableEffect(state.phase) { + if (state.phase in setOf( + WatchPhase.LISTENING, WatchPhase.WAITING, WatchPhase.SPEAKING + )) { + window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + } else { + window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + } + onDispose { window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } + } + + WatchScreen( + state = state, + onTalk = { + if (state.phase == WatchPhase.LISTENING || + ContextCompat.checkSelfPermission( + this, Manifest.permission.RECORD_AUDIO + ) == PackageManager.PERMISSION_GRANTED + ) controller.toggleTalk() + else permission.launch(Manifest.permission.RECORD_AUDIO) + }, + onConfigure = controller::configure, + onRetry = controller::retry + ) + } +} diff --git a/clients/wearos/app/src/main/java/com/patchbay/wear/PatchbayProtocol.kt b/clients/wearos/app/src/main/java/com/patchbay/wear/PatchbayProtocol.kt new file mode 100644 index 0000000..5398cb9 --- /dev/null +++ b/clients/wearos/app/src/main/java/com/patchbay/wear/PatchbayProtocol.kt @@ -0,0 +1,190 @@ +package com.patchbay.wear + +import org.json.JSONObject +import java.net.URI +import kotlin.math.abs +import kotlin.math.max + +/** + * PatchBay's existing contract, not a new assistant protocol. + * See ../../../../../../../../docs/contracts/ws-client-protocol.md in the main repository. + */ +object PatchbayProtocol { + const val SAMPLE_RATE = 16_000 + const val CHANNELS = 1 + const val BYTES_PER_SAMPLE = 2 + const val TURN_END_SILENCE_MS = 2_000 + + /** + * VOICE_RECOGNITION has no AGC (CDD 5.4.2), and at wrist distance quiet speech reached the + * server's VAD below its 384 ms active-speech floor and was discarded. Apply a fixed +15.6 dB + * with a tanh soft clip so loud speech (raw peaks ~8500 seen) is rounded, not chopped. + */ + const val UPLINK_GAIN = 6.0 + + fun uplinkGain(sample: Short): Short = + (32767.0 * kotlin.math.tanh(UPLINK_GAIN * sample / 32767.0)).toInt().toShort() + + fun finishTurnSilence(): ByteArray = + ByteArray(SAMPLE_RATE * BYTES_PER_SAMPLE * TURN_END_SILENCE_MS / 1_000) + + fun packPcm(samples: ShortArray, count: Int): ByteArray { + require(count in 0..samples.size) + val bytes = ByteArray(count * BYTES_PER_SAMPLE) + for (i in 0 until count) { + val value = samples[i].toInt() + bytes[i * 2] = (value and 0xff).toByte() + bytes[i * 2 + 1] = ((value ushr 8) and 0xff).toByte() + } + return bytes + } + + /** Cheap amplitude approximation for the reactive character; not a speech/affect classifier. */ + fun amplitude(pcm: ByteArray): Float { + if (pcm.size < 2) return 0f + var peak = 0 + for (i in 0 until pcm.size - 1 step 2) { + val sample = (pcm[i].toInt() and 0xff) or (pcm[i + 1].toInt() shl 8) + peak = max(peak, abs(sample.toShort().toInt()).coerceAtMost(32767)) + } + return (peak / 16000f).coerceIn(0f, 1f) + } + + const val DEFAULT_PORT = 8765 + private val BARE_IPV4 = Regex("""^\d{1,3}(\.\d{1,3}){3}(:\d{1,5})?$""") + + /** + * Accepts a full ws:// or wss:// URL, or -- because typing "ws://" and ":" on a watch + * keyboard proved impractical on a Galaxy Watch6 Classic -- a bare private IPv4 address + * with an optional port, which becomes ws://:. + */ + fun validateEndpoint(input: String): String? { + val trimmed = input.trim() + val url = if (BARE_IPV4.matches(trimmed)) { + if (':' in trimmed) "ws://$trimmed" else "ws://$trimmed:$DEFAULT_PORT" + } else trimmed + val uri = try { URI(url) } catch (_: Exception) { return null } + val scheme = uri.scheme?.lowercase() + if (scheme != "ws" && scheme != "wss") return null + val host = uri.host ?: return null + if (host.isBlank() || uri.rawUserInfo != null || uri.rawQuery != null || uri.rawFragment != null) return null + if (uri.port != -1 && uri.port !in 1..65535) return null + if (scheme == "ws" && !isPrivateIpv4(host)) return null + return url + } + + /** What the number-pad entry field shows for a saved endpoint: just the address. */ + fun editableAddress(endpoint: String): String { + val uri = try { URI(endpoint) } catch (_: Exception) { return endpoint } + if (uri.scheme?.lowercase() != "ws" || uri.host == null || !isPrivateIpv4(uri.host)) return endpoint + if (uri.rawPath?.let { it.isNotEmpty() && it != "/" } == true) return endpoint + return if (uri.port == -1 || uri.port == DEFAULT_PORT) uri.host else "${uri.host}:${uri.port}" + } + + /** True when a saved endpoint cannot be shown as a bare IP (e.g. wss://), so the + * entry page must open in full-URL mode. Blank means first setup: IP mode. */ + fun needsFullUrl(endpoint: String): Boolean = + endpoint.isNotBlank() && editableAddress(endpoint) == endpoint + + private fun isPrivateIpv4(host: String): Boolean { + val parts = host.split(".") + if (parts.size != 4) return false + if (parts.any { it.isEmpty() || it.length > 3 || !it.all(Char::isDigit) }) return false + val octets = parts.map { it.toIntOrNull() ?: return false } + if (octets.any { it !in 0..255 }) return false + return octets[0] == 10 || + (octets[0] == 172 && octets[1] in 16..31) || + (octets[0] == 192 && octets[1] == 168) + } + + sealed interface Event { + data class Transcript(val text: String) : Event + data class Partial(val delta: String) : Event + data class Reply(val text: String) : Event + /** Empty-text assistant_text carrying `tools`: the real answer comes later. */ + data object ToolCall : Event + data object Configured : Event + data object Unknown : Event + } + + /** Unknown and tool-progress messages are harmless, never user-facing as invented replies. */ + fun parseEvent(text: String): Event = try { + val json = JSONObject(text) + when (json.optString("type")) { + "transcription_completed" -> Event.Transcript(json.optString("transcript")) + "partial_transcription" -> Event.Partial(json.optString("delta")) + "assistant_text" -> { + val reply = json.optString("text") + val tools = json.optJSONArray("tools") + when { + reply.isNotBlank() -> Event.Reply(reply) + tools != null && tools.length() > 0 -> Event.ToolCall + else -> Event.Unknown + } + } + "config_state", "config_ack" -> Event.Configured + else -> Event.Unknown + } + } catch (_: Exception) { + Event.Unknown + } +} + +enum class WatchPhase { + UNCONFIGURED, CONNECTING, READY, LISTENING, WAITING, SPEAKING, OFFLINE, ERROR +} + +data class WatchUiState( + val phase: WatchPhase = WatchPhase.UNCONFIGURED, + val endpoint: String = "", + val connected: Boolean = false, + val transcript: String = "", + val partialTranscript: String = "", + val lastReply: String = "", + val audioLevel: Float = 0f, + val detail: String = "Set the PatchBay address in Settings" +) + +/** + * Per-turn capture levels for field diagnosis: numbers only, never audio. Separates a quiet + * speaker from a clipping one, and keeps the stop tap (which lands in the last few hundred ms + * and can reach full scale on its own) out of the speech figures. + */ +class CaptureStats { + private val windows = ArrayList() // pre-gain RMS per 200 ms window + private var winSq = 0.0 + private var winN = 0 + private var samples = 0L + private var rawClipped = 0L // pre-gain samples at the int16 rail + private var postSaturated = 0L // post-gain samples at >= 97.7% of full scale + + fun add(raw: Short, sent: Short) { + val v = raw.toInt() + samples++ + if (v >= 32_760 || v <= -32_760) rawClipped++ + if (sent >= 32_000 || sent <= -32_000) postSaturated++ + winSq += v.toDouble() * v + if (++winN == WINDOW) { + windows.add(kotlin.math.sqrt(winSq / WINDOW).toInt()) + winSq = 0.0; winN = 0 + } + } + + /** Windows that can contain speech: all but the last [TAP_WINDOWS] (the stop tap). */ + fun speechWindows(): List = windows.dropLast(TAP_WINDOWS) + + fun summary(): String { + val speech = speechWindows() + val peakWin = speech.maxOrNull() ?: 0 + val median = speech.sorted().let { if (it.isEmpty()) 0 else it[it.size / 2] } + val satPct = if (samples > 0) 100.0 * postSaturated / samples else 0.0 + return "capture: secs=%.2f speechPeakWinRms=%d speechMedianWinRms=%d rawClipped=%d postSaturated=%.2f%% env200ms=%s" + .format(samples / PatchbayProtocol.SAMPLE_RATE.toFloat(), peakWin, median, rawClipped, satPct, + windows.joinToString(",")) + } + + companion object { + const val WINDOW = 3_200 // 200 ms at 16 kHz + const val TAP_WINDOWS = 2 // last 400 ms + } +} diff --git a/clients/wearos/app/src/main/java/com/patchbay/wear/PatchbaySocket.kt b/clients/wearos/app/src/main/java/com/patchbay/wear/PatchbaySocket.kt new file mode 100644 index 0000000..f84b5fe --- /dev/null +++ b/clients/wearos/app/src/main/java/com/patchbay/wear/PatchbaySocket.kt @@ -0,0 +1,98 @@ +package com.patchbay.wear + +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.Response +import okhttp3.WebSocket +import okhttp3.WebSocketListener +import okio.ByteString +import okio.ByteString.Companion.toByteString +import java.util.concurrent.TimeUnit + +/** + * Wire-only transport. No LLM, persona state, speech synthesis, or local memory. + * Connections are explicitly scoped to the visible watch activity. + */ +class PatchbaySocket(private val callbacks: Callbacks) { + interface Callbacks { + fun connected() + fun receivedAudio(pcm: ByteArray) + fun receivedEvent(event: PatchbayProtocol.Event) + fun disconnected(reason: String) + } + + private val client = OkHttpClient.Builder() + .pingInterval(25, TimeUnit.SECONDS) + .build() + + private var generation = 0L + private var socket: WebSocket? = null + private var open = false + + @Synchronized + fun connect(url: String) { + close() + val session = generation + val request = Request.Builder().url(url).build() + socket = client.newWebSocket(request, object : WebSocketListener() { + override fun onOpen(webSocket: WebSocket, response: Response) { + synchronized(this@PatchbaySocket) { + if (session != generation) { webSocket.cancel(); return } + open = true + webSocket.send("""{"type":"config_get"}""") + } + callbacks.connected() + } + + override fun onMessage(webSocket: WebSocket, bytes: ByteString) { + if (isLive(session)) callbacks.receivedAudio(bytes.toByteArray()) + } + + override fun onMessage(webSocket: WebSocket, text: String) { + if (isLive(session)) callbacks.receivedEvent(PatchbayProtocol.parseEvent(text)) + } + + override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { + if (markClosed(session)) callbacks.disconnected(t.message ?: "Connection failed") + } + + override fun onClosed(webSocket: WebSocket, code: Int, reason: String) { + if (markClosed(session)) callbacks.disconnected("Socket closed ($code)") + } + + override fun onClosing(webSocket: WebSocket, code: Int, reason: String) { + webSocket.close(code, reason) + } + }) + } + + @Synchronized + private fun isLive(session: Long): Boolean = session == generation && open + + @Synchronized + private fun markClosed(session: Long): Boolean { + if (session != generation) return false + open = false + socket = null + return true + } + + /** + * Drop instead of queueing unbounded microphone data across an outage. + * OkHttp queueSize includes pending outgoing traffic. + */ + @Synchronized + fun sendPcm(pcm: ByteArray): Boolean { + val ws = socket ?: return false + if (!open || ws.queueSize() > 1024 * 1024L) return false + return ws.send(pcm.toByteString()) + } + + @Synchronized + fun close() { + generation++ + open = false + socket?.cancel() + socket = null + } +} diff --git a/clients/wearos/app/src/main/java/com/patchbay/wear/WatchAudio.kt b/clients/wearos/app/src/main/java/com/patchbay/wear/WatchAudio.kt new file mode 100644 index 0000000..3a41812 --- /dev/null +++ b/clients/wearos/app/src/main/java/com/patchbay/wear/WatchAudio.kt @@ -0,0 +1,249 @@ +package com.patchbay.wear + +import android.media.AudioAttributes +import android.media.AudioFormat +import android.media.AudioRecord +import android.media.AudioTrack +import android.media.MediaRecorder +import android.util.Log +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlin.math.max +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicLong + +/** + * Hardware I/O only. This watch does not transcribe, reason, or synthesize. + * Foreground push-to-talk mic capture and continuous 16kHz PCM speaker output. + */ +class WatchMicrophone(private val scope: CoroutineScope) { + private var recorder: AudioRecord? = null + private var captureJob: Job? = null + private val running = AtomicBoolean(false) + + fun start(onPcm: (ByteArray) -> Unit, onLevel: (Float) -> Unit, onError: (String) -> Unit): Boolean { + if (running.get()) return false + val format = AudioFormat.Builder() + .setSampleRate(PatchbayProtocol.SAMPLE_RATE) + .setEncoding(AudioFormat.ENCODING_PCM_16BIT) + .setChannelMask(AudioFormat.CHANNEL_IN_MONO) + .build() + try { + val min = AudioRecord.getMinBufferSize( + PatchbayProtocol.SAMPLE_RATE, + AudioFormat.CHANNEL_IN_MONO, + AudioFormat.ENCODING_PCM_16BIT + ) + if (min <= 0) throw IllegalStateException("Watch microphone does not accept 16kHz PCM") + // VOICE_RECOGNITION, not VOICE_COMMUNICATION: on a Galaxy Watch6 Classic (SM-R960, + // Android 16) VOICE_COMMUNICATION delivered speech at RMS ~1-30 (the server VAD never + // fired), while VOICE_RECOGNITION -- CDD 5.4.2: no AGC, no noise suppression, + // calibrated level -- was transcribed on most turns; its misses were quiet speech, + // which PatchbayProtocol.uplinkGain addresses. Push-to-talk keeps the mic closed + // during playback, so the echo canceller VOICE_COMMUNICATION would bring is not needed. + val source = AudioRecord.Builder() + .setAudioSource(MediaRecorder.AudioSource.VOICE_RECOGNITION) + .setAudioFormat(format) + .setBufferSizeInBytes(max(min * 2, 6400)) + .build() + if (source.state != AudioRecord.STATE_INITIALIZED) { + source.release() + throw IllegalStateException("Watch microphone could not initialize") + } + source.startRecording() + if (source.recordingState != AudioRecord.RECORDSTATE_RECORDING) { + source.release() + throw IllegalStateException("Watch microphone did not start") + } + recorder = source + running.set(true) + captureJob = scope.launch(Dispatchers.IO) { + val buf = ShortArray(640) // 40 ms + val stats = CaptureStats() + try { + while (isActive && running.get()) { + val count = source.read(buf, 0, buf.size, AudioRecord.READ_BLOCKING) + if (count < 0) { + if (running.get()) onError("Microphone read failed: $count") + break + } + for (i in 0 until count) { + val raw = buf[i] + buf[i] = PatchbayProtocol.uplinkGain(raw) + stats.add(raw, buf[i]) + } + if (count > 0 && running.get()) { + val pcm = PatchbayProtocol.packPcm(buf, count) + onPcm(pcm) + onLevel(PatchbayProtocol.amplitude(pcm)) + } + } + } catch (t: Exception) { + if (running.get()) onError("Microphone error: ${t.message}") + } finally { + // One line per turn, levels only: tells "mic heard nothing" apart from + // "server ignored it", and quiet speech from clipping, recording nothing. + Log.i(TAG, stats.summary()) + } + } + return true + } catch (t: Exception) { + running.set(false) + releaseNow() + onError(t.message ?: "Microphone unavailable") + return false + } + } + + /** Stop capture, wait for final sent audio, THEN let the controller send VAD silence. */ + suspend fun stopAndDrain() { + running.set(false) + val source = recorder + try { source?.stop() } catch (_: Exception) {} + captureJob?.join() + try { source?.release() } catch (_: Exception) {} + captureJob = null + recorder = null + } + + /** No waiting for UI lifecycle: immediately stop the microphone when leaving foreground. */ + fun stopImmediately() { + running.set(false) + val source = recorder + recorder = null + try { source?.stop() } catch (_: Exception) {} + captureJob?.cancel() + captureJob = null + try { source?.release() } catch (_: Exception) {} + } + + private fun releaseNow() { + try { recorder?.release() } catch (_: Exception) {} + recorder = null + } +} + +/** + * Buffered gapless playback across arbitrary WebSocket frame boundaries. + * The bounded queue fails rather than storing many seconds of unexpected audio. + */ +class WatchSpeaker( + private val scope: CoroutineScope, + private val onLevel: (Float) -> Unit, + private val onError: (String) -> Unit +) { + // Bounded by seconds of audio, not chunk count: the server streams TTS ~2x faster than + // real time, so a 40-chunk cap (~5 s of backlog) failed mid-reply on every answer longer + // than ~8 s and tore the session down. + private val queue = Channel(capacity = Channel.UNLIMITED) + private val running = AtomicBoolean(true) + @Volatile private var track: AudioTrack? = null + /** Bytes offered but not yet handed to the AudioTrack. */ + private val pendingBytes = AtomicLong(0) + /** Frames handed to the AudioTrack so far. */ + @Volatile private var framesWritten = 0L + + private val worker: Job = scope.launch(Dispatchers.IO) { + try { + for (pcm in queue) { + if (!running.get()) break + if (track == null) track = createTrack() + val out = track ?: break + onLevel(PatchbayProtocol.amplitude(pcm)) + var offset = 0 + while (offset < pcm.size && running.get()) { + val written = out.write( + pcm, offset, pcm.size - offset, AudioTrack.WRITE_BLOCKING + ) + if (written <= 0) throw IllegalStateException("Speaker write error: $written") + offset += written + framesWritten += written / PatchbayProtocol.BYTES_PER_SAMPLE + pendingBytes.addAndGet(-written.toLong()) + } + } + } catch (t: Exception) { + if (running.get()) onError("Speaker error: ${t.message}") + } finally { + releaseTrack() + } + } + + fun offer(pcm: ByteArray): Boolean { + if (!running.get()) return false + if (pendingBytes.get() + pcm.size > MAX_PENDING_BYTES) return false + pendingBytes.addAndGet(pcm.size.toLong()) + if (queue.trySend(pcm).isSuccess) return true + pendingBytes.addAndGet(-pcm.size.toLong()) + return false + } + + /** + * True once every offered byte has been written AND played out by the hardware. + * The server streams TTS faster than real time, so "no new audio arrived" is not + * "finished speaking" -- stopping then flushes the unplayed tail of the reply. + */ + fun isDrained(): Boolean { + if (pendingBytes.get() > 0) return false + val out = track ?: return true + val played = out.playbackHeadPosition.toLong() and 0xffffffffL + return played >= framesWritten + } + + fun stop() { + if (!running.getAndSet(false)) return + queue.close() + try { track?.pause() } catch (_: Exception) {} + try { track?.flush() } catch (_: Exception) {} + worker.cancel() + } + + private fun createTrack(): AudioTrack { + val min = AudioTrack.getMinBufferSize( + PatchbayProtocol.SAMPLE_RATE, + AudioFormat.CHANNEL_OUT_MONO, + AudioFormat.ENCODING_PCM_16BIT + ) + if (min <= 0) throw IllegalStateException("Watch speaker does not support 16kHz PCM") + val created = AudioTrack.Builder() + .setAudioAttributes( + AudioAttributes.Builder() + .setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION) + .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH) + .build() + ) + .setAudioFormat( + AudioFormat.Builder() + .setSampleRate(PatchbayProtocol.SAMPLE_RATE) + .setEncoding(AudioFormat.ENCODING_PCM_16BIT) + .setChannelMask(AudioFormat.CHANNEL_OUT_MONO) + .build() + ) + .setBufferSizeInBytes(max(min, 6400)) + .setTransferMode(AudioTrack.MODE_STREAM) + .build() + if (created.state != AudioTrack.STATE_INITIALIZED) { + created.release() + throw IllegalStateException("Watch speaker could not initialize") + } + created.play() + return created + } + + private fun releaseTrack() { + val old = track + track = null + try { old?.stop() } catch (_: Exception) {} + try { old?.release() } catch (_: Exception) {} + onLevel(0f) + } +} + +private const val TAG = "PatchBayWear" + +/** 60 s of 16 kHz mono int16 not yet played: far beyond any real reply, still a hard bound. */ +private const val MAX_PENDING_BYTES = + 60L * PatchbayProtocol.SAMPLE_RATE * PatchbayProtocol.BYTES_PER_SAMPLE diff --git a/clients/wearos/app/src/main/java/com/patchbay/wear/WatchController.kt b/clients/wearos/app/src/main/java/com/patchbay/wear/WatchController.kt new file mode 100644 index 0000000..e2cc17d --- /dev/null +++ b/clients/wearos/app/src/main/java/com/patchbay/wear/WatchController.kt @@ -0,0 +1,333 @@ +package com.patchbay.wear + +import android.content.Context +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update + +/** + * One view into one existing PatchBay conversation. No separate assistant state. + * + * Lifecycle rule: only while the watch activity is visibly foregrounded may we hold + * the socket, microphone or speaker. On background, tear everything down. + */ +class WatchController(context: Context) { + private val preferences = context.applicationContext.getSharedPreferences( + "patchbay_wear_config", Context.MODE_PRIVATE + ) + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + private val _ui = MutableStateFlow( + WatchUiState(endpoint = preferences.getString("endpoint", "") ?: "") + ) + val ui: StateFlow = _ui.asStateFlow() + + private var visible = false + private var expectingReply = false + private var heardSpeech = false + private var socket: PatchbaySocket? = null + private var microphone: WatchMicrophone? = null + private var speaker: WatchSpeaker? = null + private var idleJob: Job? = null + private var waitingJob: Job? = null + private var stoppingCapture = false + private var toolPending = false + + fun onForeground() { + if (visible) return + visible = true + connect() + } + + fun onBackground() { + if (!visible) return + visible = false + tearDown() + _ui.update { + it.copy( + connected = false, audioLevel = 0f, + phase = if (it.endpoint.isBlank()) WatchPhase.UNCONFIGURED else WatchPhase.OFFLINE, + detail = "Paused while watch app is closed" + ) + } + } + + fun dispose() { + onBackground() + scope.cancel() + } + + fun configure(raw: String) { + val endpoint = PatchbayProtocol.validateEndpoint(raw) + if (endpoint == null) { + _ui.update { + it.copy( + phase = WatchPhase.ERROR, + detail = "Enter a wss:// URL or ws:// private LAN IPv4 address" + ) + } + return + } + preferences.edit().putString("endpoint", endpoint).apply() + _ui.update { it.copy(endpoint = endpoint) } + if (visible) connect() + } + + fun permissionDenied() { + if (!visible) return + _ui.update { + it.copy(detail = "Microphone permission is needed for voice input") + } + } + + fun retry() { + if (visible) connect() + } + + private fun connect() { + tearDown() + val endpoint = PatchbayProtocol.validateEndpoint(_ui.value.endpoint) + if (endpoint == null) { + _ui.update { + it.copy(phase = WatchPhase.UNCONFIGURED, connected = false, + detail = WatchUiState().detail) + } + return + } + _ui.update { + it.copy(phase = WatchPhase.CONNECTING, connected = false, + detail = "Connecting to PatchBay…", audioLevel = 0f) + } + lateinit var fresh: PatchbaySocket + fresh = PatchbaySocket(object : PatchbaySocket.Callbacks { + override fun connected() { + scope.launch { + if (!visible || socket !== fresh) return@launch + _ui.update { + it.copy(phase = WatchPhase.READY, connected = true, + detail = "Tap to talk") + } + } + } + + override fun receivedAudio(pcm: ByteArray) { + scope.launch { + if (!visible || socket !== fresh || !expectingReply) return@launch + if (speaker == null) { + speaker = WatchSpeaker(scope, + onLevel = { level -> + scope.launch { + if (visible) _ui.update { it.copy(audioLevel = level) } + } + }, + onError = { problem -> scope.launch { fail(problem) } } + ) + } + if (speaker?.offer(pcm) != true) { + fail("Audio playback queue is full") + return@launch + } + heardSpeech = true + _ui.update { + it.copy(phase = WatchPhase.SPEAKING, detail = "PatchBay is speaking") + } + scheduleReplyEnd(fresh) + } + } + + override fun receivedEvent(event: PatchbayProtocol.Event) { + scope.launch { + if (!visible || socket !== fresh) return@launch + when (event) { + is PatchbayProtocol.Event.Transcript -> + if (expectingReply || _ui.value.phase == WatchPhase.LISTENING) { + _ui.update { + it.copy(transcript = event.text, partialTranscript = "") + } + } + is PatchbayProtocol.Event.Partial -> + if (expectingReply || _ui.value.phase == WatchPhase.LISTENING) { + _ui.update { + it.copy(partialTranscript = + (it.partialTranscript + event.delta).takeLast(240)) + } + } + is PatchbayProtocol.Event.Reply -> if (expectingReply) { + toolPending = false + _ui.update { it.copy(lastReply = event.text) } + // The answer's audio follows this frame; restart the quiet window + // so a turn already past its filler cannot end in that gap. + if (heardSpeech) scheduleReplyEnd(fresh) + } + is PatchbayProtocol.Event.ToolCall -> if (expectingReply) { + // Contract: a tool turn sends an empty-text frame with `tools`, then + // the real answer once the tool returns. A web search left a 2.9 s + // silent gap after the filler and the watch dropped the answer. + toolPending = true + } + else -> Unit + } + } + } + + override fun disconnected(reason: String) { + scope.launch { + if (visible && socket === fresh) fail(reason) + } + } + }) + socket = fresh + try { fresh.connect(endpoint) } catch (t: Exception) { + fail(t.message ?: "Could not open socket") + } + } + + /** The character is a single large button; no background wakeword mode. */ + fun toggleTalk() { + when (_ui.value.phase) { + WatchPhase.READY -> beginTalk() + WatchPhase.LISTENING -> endTalk() + else -> Unit + } + } + + private fun beginTalk() { + if (!visible || _ui.value.phase != WatchPhase.READY || socket == null) return + idleJob?.cancel() + waitingJob?.cancel() + expectingReply = false + heardSpeech = false + toolPending = false + speaker?.stop() + speaker = null + stoppingCapture = false + + val mic = WatchMicrophone(scope) + microphone = mic + val started = mic.start( + onPcm = { pcm -> + if (socket?.sendPcm(pcm) != true) { + scope.launch { fail("Microphone uplink interrupted") } + } + }, + onLevel = { level -> + scope.launch { + if (visible && _ui.value.phase == WatchPhase.LISTENING) { + _ui.update { it.copy(audioLevel = level) } + } + } + }, + onError = { problem -> scope.launch { fail(problem) } } + ) + if (started) { + _ui.update { + it.copy(phase = WatchPhase.LISTENING, + transcript = "", partialTranscript = "", + audioLevel = 0f, detail = "Tap again when finished") + } + } else { + fail("Microphone could not start") + } + } + + private fun endTalk() { + if (!visible || _ui.value.phase != WatchPhase.LISTENING || stoppingCapture) return + stoppingCapture = true + _ui.update { + it.copy(phase = WatchPhase.WAITING, audioLevel = 0f, + detail = "Sending your question…") + } + scope.launch { + microphone?.stopAndDrain() + microphone = null + stoppingCapture = false + if (!visible || !_ui.value.connected || _ui.value.phase != WatchPhase.WAITING) return@launch + // Server-side VAD needs actual zero samples to close the user turn. + // See the same technique in Embodiment's LifelineSession. + val sent = socket?.sendPcm(PatchbayProtocol.finishTurnSilence()) == true + if (!sent) { + fail("Could not finish the voice turn") + return@launch + } + expectingReply = true + _ui.update { it.copy(detail = "PatchBay is working…") } + waitingJob?.cancel() + waitingJob = launch { + delay(40_000L) + if (expectingReply && !heardSpeech && visible && + _ui.value.phase == WatchPhase.WAITING) { + // No reply ever arrives when the server's VAD heard no speech in the turn. + // Without this the watch sat on "Working" until the app was closed. + expectingReply = false + _ui.update { + it.copy(phase = WatchPhase.READY, + detail = "No reply from PatchBay. Tap to try again") + } + } + } + } + } + + /** + * End the reply only when: no new audio for a quiet interval, the speaker has played out + * everything it holds, and no tool call is still running. The server sends no end-of-TTS + * event and streams faster than real time, so the quiet interval alone cut replies short + * (a 5.0 s reply delivered in 2.3 s stopped at 3.8 s on a Watch6 Classic). + */ + private fun scheduleReplyEnd(fresh: PatchbaySocket) { + idleJob?.cancel() + idleJob = scope.launch { + delay(1_600L) + val deadline = System.currentTimeMillis() + 30_000L + while ((speaker?.isDrained() == false || toolPending) && + System.currentTimeMillis() < deadline) { + delay(100L) + } + if (visible && socket === fresh && expectingReply && heardSpeech) { + expectingReply = false + toolPending = false + speaker?.stop() + speaker = null + _ui.update { + it.copy(phase = WatchPhase.READY, audioLevel = 0f, detail = "Tap to talk") + } + } + } + } + + private fun fail(reason: String) { + if (!visible) return + android.util.Log.w("PatchBayWear", "session failed: $reason") + tearDown() + _ui.update { + it.copy( + phase = WatchPhase.ERROR, connected = false, + audioLevel = 0f, detail = reason.take(120) + ) + } + } + + private fun tearDown() { + expectingReply = false + heardSpeech = false + toolPending = false + idleJob?.cancel() + waitingJob?.cancel() + idleJob = null + waitingJob = null + microphone?.stopImmediately() + microphone = null + speaker?.stop() + speaker = null + socket?.close() + socket = null + stoppingCapture = false + } +} diff --git a/clients/wearos/app/src/main/java/com/patchbay/wear/WatchScreen.kt b/clients/wearos/app/src/main/java/com/patchbay/wear/WatchScreen.kt new file mode 100644 index 0000000..27a4e32 --- /dev/null +++ b/clients/wearos/app/src/main/java/com/patchbay/wear/WatchScreen.kt @@ -0,0 +1,445 @@ +package com.patchbay.wear + +import android.animation.ValueAnimator +import androidx.activity.compose.BackHandler +import androidx.compose.animation.core.RepeatMode +import androidx.compose.animation.core.animateFloat +import androidx.compose.animation.core.infiniteRepeatable +import androidx.compose.animation.core.keyframes +import androidx.compose.animation.core.rememberInfiniteTransition +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.focusable +import androidx.compose.foundation.gestures.scrollBy +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.defaultMinSize +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.BasicText +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.input.rotary.onRotaryScrollEvent +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import kotlinx.coroutines.launch + +private val BACK = Color(0xFF05070D) +private val FACE = Color(0xFF13243B) +private val ICE = Color(0xFFE8F7FF) +private val MUTED = Color(0xFFAFC5DB) +private val NAVY = Color(0xFF23364D) +private val READY = Color(0xFF77CFFF) +private val LISTENING = Color(0xFF50E5C2) +private val WAITING = Color(0xFFC29BFF) +private val SPEAKING = Color(0xFF6DB7FF) +private val ERROR = Color(0xFFFF9D94) + +private enum class Page { HOME, REPLY, SETTINGS } + +/** + * Vertical scrolling driven by touch AND the Watch6 Classic's rotating bezel. Content that does + * not fit a round screen must scroll into its wide middle: a fixed bottom row sits where the + * circle is narrowest and gets clipped (the Reply/Settings and Back/Save rows both were). + */ +@Composable +private fun Modifier.roundScroll(): Modifier { + val scroll = rememberScrollState() + val focusRequester = remember { FocusRequester() } + val scope = rememberCoroutineScope() + LaunchedEffect(Unit) { focusRequester.requestFocus() } + return this + .onRotaryScrollEvent { + scope.launch { scroll.scrollBy(it.verticalScrollPixels) } + true + } + .focusRequester(focusRequester) + .focusable() + .verticalScroll(scroll) +} + +private fun accent(phase: WatchPhase): Color = when (phase) { + WatchPhase.LISTENING -> LISTENING + WatchPhase.WAITING, WatchPhase.CONNECTING -> WAITING + WatchPhase.SPEAKING -> SPEAKING + WatchPhase.ERROR, WatchPhase.OFFLINE -> ERROR + else -> READY +} + +private fun headline(phase: WatchPhase): String = when (phase) { + WatchPhase.UNCONFIGURED -> "Not configured" + WatchPhase.CONNECTING -> "Connecting" + WatchPhase.READY -> "Ready to talk" + WatchPhase.LISTENING -> "Listening" + WatchPhase.WAITING -> "Working" + WatchPhase.SPEAKING -> "Speaking" + WatchPhase.OFFLINE -> "Offline" + WatchPhase.ERROR -> "Connection error" +} + +/** Three views, not a scaled-down desktop cockpit. */ +@Composable +fun WatchScreen( + state: WatchUiState, + onTalk: () -> Unit, + onConfigure: (String) -> Unit, + onRetry: () -> Unit +) { + var page by rememberSaveable { mutableStateOf(Page.HOME) } + BackHandler(enabled = page != Page.HOME) { page = Page.HOME } + when (page) { + Page.HOME -> HomeFace( + state, + onFaceTap = { + when (state.phase) { + WatchPhase.READY, WatchPhase.LISTENING -> onTalk() + WatchPhase.ERROR, WatchPhase.OFFLINE -> onRetry() + WatchPhase.UNCONFIGURED -> page = Page.SETTINGS + else -> Unit + } + }, + onReply = { page = Page.REPLY }, + onSettings = { page = Page.SETTINGS } + ) + Page.REPLY -> ReplyPage(state, onBack = { page = Page.HOME }) + Page.SETTINGS -> SettingsPage( + state.endpoint, + onSave = { entered -> onConfigure(entered); page = Page.HOME }, + onBack = { page = Page.HOME } + ) + } +} + +@Composable +private fun HomeFace( + state: WatchUiState, + onFaceTap: () -> Unit, + onReply: () -> Unit, + onSettings: () -> Unit +) { + BoxWithConstraints(Modifier.fillMaxSize().background(BACK)) { + val diameter = minOf(maxWidth, maxHeight) + Column( + modifier = Modifier + .fillMaxSize() + .roundScroll() + .padding( + start = diameter * 0.12f, end = diameter * 0.12f, + top = diameter * 0.08f, bottom = diameter * 0.26f + ), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(6.dp) + ) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + SmallText("PATCHBAY", 13, ICE, FontWeight.Bold) + SmallText(if (state.connected) "CONNECTED" else "NOT CONNECTED", + 10, if (state.connected) LISTENING else MUTED) + } + + Face( + phase = state.phase, + amplitude = state.audioLevel, + modifier = Modifier.size(diameter * 0.56f), + onTap = onFaceTap + ) + Column(horizontalAlignment = Alignment.CenterHorizontally) { + SmallText(headline(state.phase), 15, ICE, FontWeight.SemiBold) + SmallText(state.detail, 11, MUTED, maxLines = 2) + } + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Action("Reply", enabled = state.lastReply.isNotBlank(), onClick = onReply) + Action("Settings", onClick = onSettings) + } + } + } +} + +@Composable +private fun Face( + phase: WatchPhase, + amplitude: Float, + modifier: Modifier = Modifier, + onTap: () -> Unit +) { + val animated = ValueAnimator.areAnimatorsEnabled() + val blinkTransition = rememberInfiniteTransition(label = "face blink") + val eyesOpen by blinkTransition.animateFloat( + initialValue = 1f, targetValue = 1f, + animationSpec = infiniteRepeatable( + animation = keyframes { + durationMillis = 4200 + 1f at 0 + 1f at 3490 + 0.06f at 3590 + 1f at 3700 + 1f at 4200 + }, + repeatMode = RepeatMode.Restart + ), label = "eyes" + ) + + val ringColor = accent(phase) + val clickLabel = when (phase) { + WatchPhase.READY -> "Start talking to PatchBay" + WatchPhase.LISTENING -> "Finish speaking and send to PatchBay" + WatchPhase.OFFLINE, WatchPhase.ERROR -> "Reconnect to PatchBay" + WatchPhase.UNCONFIGURED -> "Configure PatchBay connection" + else -> headline(phase) + } + val tappable = phase in setOf( + WatchPhase.READY, WatchPhase.LISTENING, + WatchPhase.OFFLINE, WatchPhase.ERROR, WatchPhase.UNCONFIGURED + ) + + Canvas( + modifier + .clip(CircleShape) + .clickable(enabled = tappable, role = Role.Button, onClick = onTap) + .semantics { contentDescription = clickLabel } + ) { + val d = size.minDimension + val cx = size.width / 2 + val cy = size.height / 2 + val eyeHeight = d * 0.083f * if (animated) eyesOpen else 1f + drawCircle(FACE, radius = d * 0.485f) + drawCircle(ringColor, radius = d * 0.472f, + style = Stroke(width = d * 0.023f)) + drawCircle(Color(0xFF193149), radius = d * 0.395f) + val eyeWidth = d * 0.115f + for (dx in listOf(-0.15f, 0.15f)) { + drawRoundRect(ICE, + topLeft = Offset(cx + d * dx - eyeWidth / 2, cy - d * 0.105f), + size = Size(eyeWidth, eyeHeight.coerceAtLeast(d * 0.009f)), + cornerRadius = CornerRadius(d * 0.055f, d * 0.055f)) + if (eyeHeight > d * 0.05f) { + drawCircle(Color(0xFF183553), radius = d * 0.023f, + center = Offset(cx + d * dx, cy - d * 0.065f)) + } + } + if (phase == WatchPhase.SPEAKING || phase == WatchPhase.LISTENING) { + val mouthHeight = d * (0.045f + amplitude * 0.15f) + drawOval( + Color(0xFF07101C), + topLeft = Offset(cx - d * 0.065f, cy + d * 0.065f), + size = Size(d * 0.13f, mouthHeight) + ) + drawOval( + ICE, + topLeft = Offset(cx - d * 0.065f, cy + d * 0.065f), + size = Size(d * 0.13f, mouthHeight), + style = Stroke(width = d * 0.012f) + ) + } else if (phase == WatchPhase.WAITING || phase == WatchPhase.CONNECTING) { + for (i in -1..1) { + drawCircle(WAITING, radius = d * 0.017f, + center = Offset(cx + i * d * 0.07f, cy + d * 0.15f)) + } + } else { + drawArc( + color = ICE, startAngle = 10f, sweepAngle = 160f, + useCenter = false, + topLeft = Offset(cx - d * 0.12f, cy + d * 0.045f), + size = Size(d * 0.24f, d * 0.17f), + style = Stroke(width = d * 0.018f) + ) + } + drawCircle(ringColor, radius = d * 0.019f, + center = Offset(cx, cy - d * 0.435f)) + } +} + +@Composable +private fun ReplyPage(state: WatchUiState, onBack: () -> Unit) { + Column( + modifier = Modifier + .fillMaxSize() + .background(BACK) + .roundScroll() + .padding(start = 39.dp, end = 39.dp, top = 24.dp, bottom = 56.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + SmallText("LAST REPLY", 12, READY, FontWeight.Bold) + Spacer(Modifier.height(12.dp)) + SmallText(state.lastReply.ifBlank { "No reply yet" }, + 14, ICE, textAlign = TextAlign.Start) + Spacer(Modifier.height(18.dp)) + Action("Back", onClick = onBack) + } +} + +@Composable +private fun SettingsPage( + current: String, + onSave: (String) -> Unit, + onBack: () -> Unit +) { + // IP mode uses an in-app keypad. On a Galaxy Watch6 Classic the system keyboards all failed + // for an IP: QWERTY needs page switches for "ws://" and ":", the decimal pad allows only one + // dot (it rewrote 192.168.0.20 to 1921680.20), and the phone pad has no dot key. + // "Full URL" keeps the system keyboard for wss:// setups. + val simple = PatchbayProtocol.editableAddress(current) + var fullUrl by rememberSaveable(current) { mutableStateOf(PatchbayProtocol.needsFullUrl(current)) } + var input by rememberSaveable(current, fullUrl) { mutableStateOf(if (fullUrl) current else simple) } + Column( + modifier = Modifier + .fillMaxSize() + .background(BACK) + .roundScroll() + .padding(start = 30.dp, end = 30.dp, top = 24.dp, bottom = 56.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(10.dp) + ) { + SmallText("PATCHBAY SERVER", 13, ICE, FontWeight.Bold) + SmallText( + if (fullUrl) "Enter your trusted home WebSocket URL" + else "Your PatchBay server's home IP address. Port 8765 is added for you.", + 11, MUTED + ) + if (fullUrl) { + BasicTextField( + value = input, + onValueChange = { input = it.take(180) }, + singleLine = true, + textStyle = TextStyle(color = ICE, fontSize = 13.sp), + keyboardOptions = KeyboardOptions( + keyboardType = KeyboardType.Uri, + imeAction = ImeAction.Done + ), + keyboardActions = KeyboardActions(onDone = { onSave(input) }), + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .background(NAVY) + .defaultMinSize(minHeight = 48.dp) + .padding(9.dp) + .semantics { contentDescription = "PatchBay WebSocket URL" }, + decorationBox = { inner -> + Box { + if (input.isEmpty()) SmallText("ws://192.168.x.x:8765", 11, MUTED) + inner() + } + } + ) + } else { + Box( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .background(NAVY) + .defaultMinSize(minHeight = 44.dp) + .padding(9.dp) + .semantics { contentDescription = "PatchBay server IP address: ${input.ifEmpty { "empty" }}" }, + contentAlignment = Alignment.Center + ) { + if (input.isEmpty()) SmallText("192.168.x.x", 14, MUTED) + else SmallText(input, 15, ICE, FontWeight.Medium) + } + for (row in listOf("123", "456", "789", ".0<")) { + Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + for (key in row) { + Key(if (key == '<') "⌫" else key.toString(), + description = if (key == '<') "Delete" else key.toString()) { + input = if (key == '<') input.dropLast(1) + else (input + key).take(21) // a.b.c.d:port + } + } + } + } + } + SmallText("Unencrypted ws:// is limited to private LAN IPs. Use wss:// only through a protected private connection.", 10, MUTED) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Action("Back", onClick = onBack) + Action("Save", onClick = { onSave(input) }) + } + Action(if (fullUrl) "IP only" else "Full URL", onClick = { fullUrl = !fullUrl }) + } +} + +/** One keypad key: 48 dp square, the Wear minimum touch target. */ +@Composable +private fun Key(label: String, description: String, onClick: () -> Unit) { + Box( + modifier = Modifier + .size(48.dp) + .clip(CircleShape) + .background(NAVY) + .clickable(role = Role.Button, onClick = onClick) + .semantics { contentDescription = description }, + contentAlignment = Alignment.Center + ) { + SmallText(label, 16, ICE, FontWeight.Medium) + } +} + +@Composable +private fun Action(label: String, enabled: Boolean = true, onClick: () -> Unit) { + Box( + modifier = Modifier + .defaultMinSize(minWidth = 74.dp, minHeight = 44.dp) + .clip(RoundedCornerShape(28.dp)) + .background(if (enabled) NAVY else Color(0xFF161E29)) + .clickable(enabled = enabled, role = Role.Button, onClick = onClick) + .semantics { contentDescription = label }, + contentAlignment = Alignment.Center + ) { + SmallText(label, 12, if (enabled) ICE else MUTED, FontWeight.Medium) + } +} + +@Composable +private fun SmallText( + text: String, + size: Int, + color: Color, + weight: FontWeight = FontWeight.Normal, + maxLines: Int = Int.MAX_VALUE, + textAlign: TextAlign = TextAlign.Center +) { + BasicText( + text, + style = TextStyle( + color = color, fontSize = size.sp, + fontWeight = weight, textAlign = textAlign + ), + maxLines = maxLines + ) +} diff --git a/clients/wearos/app/src/main/res/drawable/ic_launcher.xml b/clients/wearos/app/src/main/res/drawable/ic_launcher.xml new file mode 100644 index 0000000..6d17880 --- /dev/null +++ b/clients/wearos/app/src/main/res/drawable/ic_launcher.xml @@ -0,0 +1,15 @@ + + + + + + + diff --git a/clients/wearos/app/src/test/java/com/patchbay/wear/PatchbayProtocolTest.kt b/clients/wearos/app/src/test/java/com/patchbay/wear/PatchbayProtocolTest.kt new file mode 100644 index 0000000..8787a6f --- /dev/null +++ b/clients/wearos/app/src/test/java/com/patchbay/wear/PatchbayProtocolTest.kt @@ -0,0 +1,119 @@ +package com.patchbay.wear + +import org.junit.Assert.* +import org.junit.Test + +class PatchbayProtocolTest { + @Test fun matchesServerPcmFormat() { + assertEquals(16_000, PatchbayProtocol.SAMPLE_RATE) + assertArrayEquals( + byteArrayOf(0x00, 0x80.toByte(), 0xff.toByte(), 0x7f), + PatchbayProtocol.packPcm(shortArrayOf(Short.MIN_VALUE, Short.MAX_VALUE), 2) + ) + assertEquals(64_000, PatchbayProtocol.finishTurnSilence().size) + assertTrue(PatchbayProtocol.finishTurnSilence().all { it == 0.toByte() }) + } + + @Test fun acceptsOnlyPrivatePlaintextEndpoints() { + assertNotNull(PatchbayProtocol.validateEndpoint("ws://192.168.77.79:8765")) + assertNotNull(PatchbayProtocol.validateEndpoint("ws://10.0.0.1:8765")) + assertNotNull(PatchbayProtocol.validateEndpoint("ws://172.31.1.4:8765")) + assertNotNull(PatchbayProtocol.validateEndpoint("wss://patchbay.example.test:8443/voice")) + for (bad in listOf( + "http://192.168.77.79", "ws://8.8.8.8:8765", "ws://172.32.0.1", + "ws://192.168.77.999", "ws://localhost:8765", "ws://example.org:8765", + "wss://user:password@x.example", "wss://x.example/path?token=secret", + "ws://192.168.77.79:8765/#fragment", "" + )) assertNull(bad, PatchbayProtocol.validateEndpoint(bad)) + } + + @Test fun handlesKnownEventsAndIgnoresEmptyAssistantFrame() { + val user = PatchbayProtocol.parseEvent( + """{"type":"transcription_completed","transcript":"Where is my phone?"}""" + ) + assertEquals(PatchbayProtocol.Event.Transcript("Where is my phone?"), user) + // The empty tool frame is never a Reply (nothing to render); it signals a pending tool. + assertEquals(PatchbayProtocol.Event.ToolCall, + PatchbayProtocol.parseEvent("""{"type":"assistant_text","text":"","tools":["tool"]}""")) + assertEquals(PatchbayProtocol.Event.Reply("Found it."), + PatchbayProtocol.parseEvent("""{"type":"assistant_text","text":"Found it."}""")) + assertEquals(PatchbayProtocol.Event.Unknown, PatchbayProtocol.parseEvent("{invalid")) + assertEquals(PatchbayProtocol.Event.Unknown, PatchbayProtocol.parseEvent("""{"type":"future_event"}""")) + } + + @Test fun amplitudeIsBounded() { + assertEquals(0f, PatchbayProtocol.amplitude(byteArrayOf()), 0.001f) + assertEquals(0f, PatchbayProtocol.amplitude(byteArrayOf(0, 0)), 0.001f) + assertEquals(1f, PatchbayProtocol.amplitude( + PatchbayProtocol.packPcm(shortArrayOf(Short.MIN_VALUE), 1) + ), 0.001f) + } + + @Test fun uplinkGainLiftsQuietSpeechAndSoftClipsLoud() { + fun g(v: Int) = PatchbayProtocol.uplinkGain(v.toShort()).toInt() + assertEquals(0, g(0)) + // Quiet wrist-distance speech (RMS ~30-100 measured) gets ~6x. + assertEquals(600.0, g(100).toDouble(), 6.0) + // Loud peaks are rounded into range, never wrapped. + assertTrue(g(8_500) in 28_000..32_767) // tanh: 29_976 + assertTrue(g(Short.MAX_VALUE.toInt()) <= 32_767) + assertTrue(g(Short.MIN_VALUE.toInt()) >= -32_768) + assertEquals(-g(4_000), g(-4_000)) + // Monotonic: louder in never gives quieter out. + var last = Int.MIN_VALUE + for (v in -32_768..32_767 step 97) { val o = g(v); assertTrue(o >= last); last = o } + } + + @Test fun toolCallFrameIsNotAReplyButIsRecognised() { + // Shape observed live: empty text + tools, then the real answer in a second frame. + assertEquals(PatchbayProtocol.Event.ToolCall, PatchbayProtocol.parseEvent( + """{"type":"assistant_text","text":"","tools":[{"name":"web_search","arguments":"{}"}]}""")) + assertEquals(PatchbayProtocol.Event.Reply("No games today."), PatchbayProtocol.parseEvent( + """{"type":"assistant_text","text":"No games today.","tools":[]}""")) + assertEquals(PatchbayProtocol.Event.Unknown, PatchbayProtocol.parseEvent( + """{"type":"assistant_text","text":""}""")) + } + + @Test fun bareIpEntryBecomesALanWebSocketUrl() { + assertEquals("ws://10.0.0.5:8765", PatchbayProtocol.validateEndpoint("10.0.0.5")) + assertEquals("ws://10.0.0.5:9000", PatchbayProtocol.validateEndpoint(" 10.0.0.5:9000 ")) + // The private-LAN rule still applies to the shorthand. + assertNull(PatchbayProtocol.validateEndpoint("8.8.8.8")) + assertNull(PatchbayProtocol.validateEndpoint("10.0.0")) + assertNull(PatchbayProtocol.validateEndpoint("10.0.0.5:99999")) + assertNull(PatchbayProtocol.validateEndpoint("10.0.0.256")) + // Full URLs keep working unchanged. + assertEquals("ws://10.0.0.5:8765", PatchbayProtocol.validateEndpoint("ws://10.0.0.5:8765")) + } + + @Test fun editableAddressShowsOnlyTheIpForNumberPadEditing() { + assertEquals("10.0.0.5", PatchbayProtocol.editableAddress("ws://10.0.0.5:8765")) + assertEquals("10.0.0.5:9000", PatchbayProtocol.editableAddress("ws://10.0.0.5:9000")) + // Anything a bare IP cannot express stays a full URL. + assertEquals("wss://voice.example:443", PatchbayProtocol.editableAddress("wss://voice.example:443")) + assertEquals("ws://10.0.0.5:8765/x", PatchbayProtocol.editableAddress("ws://10.0.0.5:8765/x")) + assertEquals("", PatchbayProtocol.editableAddress("")) + } + + @Test fun entryPageOpensInIpModeUnlessTheUrlNeedsMore() { + // Regression: the page compared the other way round and always opened in full-URL mode. + assertFalse(PatchbayProtocol.needsFullUrl("ws://10.0.0.5:8765")) + assertFalse(PatchbayProtocol.needsFullUrl("ws://10.0.0.5:9000")) + assertFalse(PatchbayProtocol.needsFullUrl("")) + assertTrue(PatchbayProtocol.needsFullUrl("wss://voice.example:443")) + } + + @Test fun captureStatsKeepTheStopTapOutOfSpeechLevelsAndCountClipping() { + val st = CaptureStats() + fun feed(level: Int, windows: Int) = repeat(windows * CaptureStats.WINDOW) { i -> + val raw = (if (i % 2 == 0) level else -level).toShort() + st.add(raw, PatchbayProtocol.uplinkGain(raw)) + } + feed(100, 3) // quiet speech, RMS 100 + feed(32_767, 2) // stop tap at the rail, last 400 ms + assertEquals(listOf(100, 100, 100), st.speechWindows()) + assertTrue(st.summary().contains("speechPeakWinRms=100")) + assertTrue(st.summary().contains("rawClipped=6400")) // the tap's 2 windows + assertTrue(st.summary().contains("postSaturated=40.00%")) + } +} diff --git a/clients/wearos/build.gradle.kts b/clients/wearos/build.gradle.kts new file mode 100644 index 0000000..5617141 --- /dev/null +++ b/clients/wearos/build.gradle.kts @@ -0,0 +1,5 @@ +plugins { + id("com.android.application") version "8.11.1" apply false + id("org.jetbrains.kotlin.android") version "2.2.21" apply false + id("org.jetbrains.kotlin.plugin.compose") version "2.2.21" apply false +} diff --git a/clients/wearos/gradle.properties b/clients/wearos/gradle.properties new file mode 100644 index 0000000..2430f7a --- /dev/null +++ b/clients/wearos/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx3g -Dfile.encoding=UTF-8 +android.useAndroidX=true +kotlin.code.style=official diff --git a/clients/wearos/settings.gradle.kts b/clients/wearos/settings.gradle.kts new file mode 100644 index 0000000..ffa0cf2 --- /dev/null +++ b/clients/wearos/settings.gradle.kts @@ -0,0 +1,16 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} +rootProject.name = "patchbay-wear" +include(":app")