diff --git a/.env.example b/.env.example
new file mode 100644
index 0000000000000000000000000000000000000000..2e28b76c4701c71822ea03e9049bf38b426c9248
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,79 @@
+# =============================================================================
+# OpenWebUI connection
+# =============================================================================
+# OpenWebUI base URL. Values ending in /api are accepted.
+OPENWEBUI_URL=http://localhost:3001/api
+
+# Model/workspace id as known by OpenWebUI.
+OPENWEB_LOADED_LLM=reachy-convo
+
+# API key for OpenWebUI HTTP endpoints when API-key bearer auth is accepted.
+OPENWEBUI_API_KEY=
+
+# OpenWebUI browser/session JWT. Preferred over OPENWEBUI_API_KEY and required
+# for authenticated Socket.IO user-join behavior.
+OPENWEBUI_TOKEN=
+
+# Optional browser User-Agent sent with OpenWebUI requests.
+OPENWEBUI_USER_AGENT=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36
+
+
+# =============================================================================
+# OpenWebUI chat state
+# =============================================================================
+# Leave blank on first launch. The app saves the real OpenWebUI chat id after a
+# successful turn. Callback and daily rollover clear this value on purpose.
+OPENWEBUI_CHAT_ID=
+OPENWEBUI_CHAT_WINDOW_START=
+OPENWEBUI_CHAT_PENDING_REASON=
+OPENWEBUI_CHAT_PENDING_EVENT_ID=
+
+
+# =============================================================================
+# OpenWebUI variables and user context
+# =============================================================================
+OPENWEBUI_USER_ID=
+OPENWEBUI_USER_NAME=Reachy
+OPENWEBUI_USER_EMAIL=reachy@example.local
+OPENWEBUI_USER_LANGUAGE=en-US
+OPENWEBUI_USER_LOCATION=Unknown
+OPENWEBUI_USER_TIMEZONE=America/New_York
+
+
+# =============================================================================
+# Audio, speech, and VAD
+# =============================================================================
+# Digital gain applied to microphone input before VAD and transcription upload.
+MIC_GAIN=1.0
+
+# OpenWebUI speech read timeout in seconds.
+OPENWEBUI_TTS_READ_TIMEOUT=15.0
+
+# No-wake-word VAD tuning. ONNX Silero is preferred; audio-level fallback keeps
+# startup alive if ONNX Runtime or the model is unavailable.
+VAD_THRESHOLD=0.12
+VAD_FALLBACK_THRESHOLD=0.010
+VAD_SPEECH_ONSET_CHUNKS=2
+VAD_SILENCE_END_CHUNKS=70
+VAD_MIN_SPEECH_CHUNKS=8
+
+# Optional override for the downloaded Silero ONNX model path. Blank uses
+# ~/.cache/reachy-openwebui-vad/silero_vad.onnx.
+SILERO_VAD_ONNX_PATH=
+
+# Optional idle timeout. 0 disables idle-based conversation reset.
+OPENWEBUI_CONVERSATION_IDLE_RESET_SECONDS=0
+
+
+# =============================================================================
+# Vision and Hugging Face cache
+# =============================================================================
+# Local device vision model used only when optional local vision code is present
+# and the app is launched with --smolvlm.
+LOCAL_DEV_VISION_MODEL=HuggingFaceTB/SmolVLM2-2.2B-Instruct
+
+# Cache directory for downloaded Hugging Face assets.
+HF_HOME=./cache
+
+# Optional Hugging Face token for gated/private assets.
+HF_TOKEN=
diff --git a/.gitattributes b/.gitattributes
index a6344aac8c09253b3b630fb776ae94478aa0275b..02fab2a29569c7350ca660dde22eb2b5a5b57bbd 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1,35 +1,61 @@
-*.7z filter=lfs diff=lfs merge=lfs -text
-*.arrow filter=lfs diff=lfs merge=lfs -text
-*.bin filter=lfs diff=lfs merge=lfs -text
-*.bz2 filter=lfs diff=lfs merge=lfs -text
-*.ckpt filter=lfs diff=lfs merge=lfs -text
-*.ftz filter=lfs diff=lfs merge=lfs -text
-*.gz filter=lfs diff=lfs merge=lfs -text
-*.h5 filter=lfs diff=lfs merge=lfs -text
-*.joblib filter=lfs diff=lfs merge=lfs -text
-*.lfs.* filter=lfs diff=lfs merge=lfs -text
-*.mlmodel filter=lfs diff=lfs merge=lfs -text
-*.model filter=lfs diff=lfs merge=lfs -text
-*.msgpack filter=lfs diff=lfs merge=lfs -text
-*.npy filter=lfs diff=lfs merge=lfs -text
-*.npz filter=lfs diff=lfs merge=lfs -text
-*.onnx filter=lfs diff=lfs merge=lfs -text
-*.ot filter=lfs diff=lfs merge=lfs -text
-*.parquet filter=lfs diff=lfs merge=lfs -text
-*.pb filter=lfs diff=lfs merge=lfs -text
-*.pickle filter=lfs diff=lfs merge=lfs -text
-*.pkl filter=lfs diff=lfs merge=lfs -text
-*.pt filter=lfs diff=lfs merge=lfs -text
-*.pth filter=lfs diff=lfs merge=lfs -text
-*.rar filter=lfs diff=lfs merge=lfs -text
-*.safetensors filter=lfs diff=lfs merge=lfs -text
-saved_model/**/* filter=lfs diff=lfs merge=lfs -text
-*.tar.* filter=lfs diff=lfs merge=lfs -text
-*.tar filter=lfs diff=lfs merge=lfs -text
-*.tflite filter=lfs diff=lfs merge=lfs -text
-*.tgz filter=lfs diff=lfs merge=lfs -text
-*.wasm filter=lfs diff=lfs merge=lfs -text
-*.xz filter=lfs diff=lfs merge=lfs -text
-*.zip filter=lfs diff=lfs merge=lfs -text
-*.zst filter=lfs diff=lfs merge=lfs -text
-*tfevents* filter=lfs diff=lfs merge=lfs -text
+# Macro for all binary files that should use Git LFS.
+[attr]lfs -text filter=lfs diff=lfs merge=lfs
+
+# Image
+*.jpg lfs
+*.jpeg lfs
+*.png lfs
+*.apng lfs
+*.atsc lfs
+*.gif lfs
+*.bmp lfs
+*.exr lfs
+*.tga lfs
+*.tiff lfs
+*.tif lfs
+*.iff lfs
+*.pict lfs
+*.dds lfs
+*.xcf lfs
+*.leo lfs
+*.kra lfs
+*.kpp lfs
+*.clip lfs
+*.webm lfs
+*.webp lfs
+*.svg text eol=lf
+*.svgz text eol=lf
+*.psd lfs
+*.afphoto lfs
+*.afdesign lfs
+# Models
+*.pth lfs
+# Binaries
+*.bin lfs
+*.pkl lfs
+*.pckl lfs
+# 3D
+*.ply lfs
+*.vis lfs
+*.db lfs
+*.ply lfs
+docs/assets/reachy_mini_dance.gif filter=lfs diff=lfs merge=lfs -text
+src/reachy_mini_conversation_app/images/reachymini_avatar.png filter=lfs diff=lfs merge=lfs -text
+src/reachy_mini_conversation_app/images/user_avatar.png filter=lfs diff=lfs merge=lfs -text
+src/Reachy_OpenWebUI/images/reachymini_avatar.png filter=lfs diff=lfs merge=lfs -text
+src/Reachy_OpenWebUI/images/user_avatar.png filter=lfs diff=lfs merge=lfs -text
+src/Reachy_OpenWebUI/static/assets/reachy-conversation-app.png filter=lfs diff=lfs merge=lfs -text
+src/Reachy_OpenWebUI/__pycache__/console.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
+src/Reachy_OpenWebUI/images/astronaut.png filter=lfs diff=lfs merge=lfs -text
+src/Reachy_OpenWebUI/images/captain.png filter=lfs diff=lfs merge=lfs -text
+src/Reachy_OpenWebUI/images/cowboy.png filter=lfs diff=lfs merge=lfs -text
+src/Reachy_OpenWebUI/images/explorer.png filter=lfs diff=lfs merge=lfs -text
+src/Reachy_OpenWebUI/images/farmer-2sejRPMv.png filter=lfs diff=lfs merge=lfs -text
+src/Reachy_OpenWebUI/images/plumber.png filter=lfs diff=lfs merge=lfs -text
+src/Reachy_OpenWebUI/images/reachy-conversation-app.jpg filter=lfs diff=lfs merge=lfs -text
+src/Reachy_OpenWebUI/images/reachy-conversation-app.png filter=lfs diff=lfs merge=lfs -text
+src/Reachy_OpenWebUI/images/reachy-how-to-create-app.png filter=lfs diff=lfs merge=lfs -text
+src/Reachy_OpenWebUI/images/reachy-icon.png filter=lfs diff=lfs merge=lfs -text
+src/Reachy_OpenWebUI/images/sleeping-reachy.png filter=lfs diff=lfs merge=lfs -text
+src/Reachy_OpenWebUI/static/assets/pwa-icon-512.png filter=lfs diff=lfs merge=lfs -text
+src/Reachy_OpenWebUI/static/assets/settings-icon.png filter=lfs diff=lfs merge=lfs -text
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..b2789b94369393fcff76e662650467aa6af3a1c3
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,15 @@
+.env
+__pycache__/
+*.py[cod]
+build/
+*.egg-info/
+.tmp_wheel_test/
+dist/
+
+# Local-only developer scratch files and private bot overlays.
+dev/
+turbo/
+local_bot/
+
+# Raw OpenWebUI model exports can include user ids, emails, and access grants.
+profiles/*/*.json
diff --git a/APP_INTEGRATION_LAYER.md b/APP_INTEGRATION_LAYER.md
new file mode 100644
index 0000000000000000000000000000000000000000..3a0918be3d4f4a1ebadeb3baf7830fde4200089e
--- /dev/null
+++ b/APP_INTEGRATION_LAYER.md
@@ -0,0 +1,57 @@
+# App Integration Layer
+
+Each mini app keeps its own files inside its own app folder.
+
+For CookAIware, the app folder is:
+
+`src/Reachy_OpenWebUI/sub_apps/cookAIware/`
+
+That folder owns CookAIware-specific tools, prompts, profile files, data helpers, assets, and app behavior. If CookAIware needs to be removed, this folder should be safe to wipe after removing its integration-layer hooks.
+
+For the base conversation app, the app folder is:
+
+`src/Reachy_OpenWebUI/sub_apps/conversation_app/`
+
+That folder owns conversation-mode support code such as chat history, VAD helpers, and the OpenWebUI local handler/LLM/TTS pipeline. Keep conversation-only state and helpers there instead of spreading them through the global app package.
+
+## Integration Layer
+
+The integration layer is the only place where app-specific code is allowed to touch the shared Reachy app.
+
+Current CookAIware integration-layer files:
+
+`src/Reachy_OpenWebUI/static/index.html`
+
+`src/Reachy_OpenWebUI/static/main.js`
+
+`src/Reachy_OpenWebUI/static/style.css`
+
+`src/Reachy_OpenWebUI/console.py`
+
+`src/Reachy_OpenWebUI/local/handler.py`
+
+`src/Reachy_OpenWebUI/tools/core_tools.py`
+
+`pyproject.toml`
+
+## Rule
+
+Do not scatter app-owned files through shared folders.
+
+Shared files should only contain the wiring needed to:
+
+- show or launch the app
+- route app requests to the backend
+- load the app profile/tools
+- pass runtime context into the shared conversation spine
+- package the app folder
+
+Everything else belongs in the app folder.
+
+## Removal Checklist
+
+To remove an app:
+
+1. Delete its app folder.
+2. Remove its entries from the integration-layer files.
+3. Restart and verify the shared app still starts.
diff --git a/ATTITUDE_PLAN.md b/ATTITUDE_PLAN.md
new file mode 100644
index 0000000000000000000000000000000000000000..a350ca18b7abae8f6f041d30bf4f54927d57623d
--- /dev/null
+++ b/ATTITUDE_PLAN.md
@@ -0,0 +1,128 @@
+# Reachy Attitude Plan
+
+## Goal
+
+Make Reachy feel different per contact/model by selecting one simple user-facing `Attitude`.
+
+The app should not expose separate controls for idle, speaking, and tool moves. The chosen attitude should control those internal pieces together.
+
+## Core Idea
+
+One setting:
+
+```text
+Attitude
+```
+
+That attitude controls:
+
+```text
+idle movement
+speaking movement
+available emotion/dance tool moves
+```
+
+All robot movement stays bot-side/local. OpenWebUI models can trigger tools, but Reachy decides what moves are available and how they execute.
+
+## Movement Types
+
+`Idle movement`
+
+Runs when Reachy is waiting, listening, or between responses.
+
+`Speaking movement`
+
+Runs while TTS is playing. This should be procedural and loopable, not a big recorded emotion every sentence.
+
+`Accent moves`
+
+One-shot recorded emotion/dance moves, usually triggered by tool calls or selected from an attitude's allowed move pool.
+
+## Attitude Examples
+
+`flirty`
+
+Soft, playful, attentive. Good candidate accents: `shy1`, `loving1`, `welcoming2`, `laughing2`, `thoughtful2`.
+
+`serious`
+
+Restrained, direct, minimal. Good candidate accents: `attentive1`, `understanding2`, `inquiring1`, `thoughtful1`.
+
+`spaceshot`
+
+Distracted, wandering, odd timing. Good candidate accents: `lost1`, `curious1`, `confused1`, `inquiring3`, `indifferent1`.
+
+`depressed`
+
+Low energy, slower, downward posture. Good candidate accents: `downcast1`, `sad2`, `tired1`, `resigned1`, `lonely1`.
+
+`tough`
+
+Harder, less friendly, guarded. Good candidate accents: `impatient1`, `impatient2`, `irritated1`, `displeased2`, `contempt1`.
+
+`silly`
+
+Goofy, bouncy, reactive. Good candidate accents: `curious1`, `indifferent1`, `proud2`, `laughing2`, `dance1`.
+
+## Emotion Library Use
+
+The emotion library source is:
+
+```text
+C:\Users\jsnmd\Documents\Reachy_OpenWebUI\reachy-mini-emotions-library
+```
+
+The `.json` files are the recorded motion data. The matching `.wav` files are audio and should not be used unless we intentionally want robot-side sound.
+
+Most recorded moves are too theatrical for idle. Use them as occasional accent moves, not continuous behavior.
+
+## Tool Move Gating
+
+The app sends tool schemas with each model message turn.
+
+That means allowed `play_emotion` and `dance` choices can be changed before each model response based on the currently selected attitude.
+
+Example:
+
+```text
+Attitude = flirty
+play_emotion enum = shy1, loving1, welcoming2, laughing2
+
+Attitude = serious
+play_emotion enum = attentive1, understanding2, inquiring1, thoughtful1
+```
+
+The model only sees the allowed list for that turn. If the attitude changes, the next message can send a different list.
+
+## UI Plan
+
+Keep the settings UI simple:
+
+```text
+Attitude
+```
+
+Do not expose separate idle/speaking/accent settings in the first pass.
+
+Rename the current `Idle attitude` field to `Attitude`.
+
+## Implementation Plan
+
+1. Rename current user-facing `Idle attitude` wording to `Attitude`.
+2. Keep the existing backend setting for now unless renaming it is worth the churn.
+3. Add an attitude definition structure that includes:
+ - idle motion parameters
+ - speaking motion parameters
+ - allowed emotion moves
+ - allowed dance moves
+4. Use selected attitude to filter `play_emotion` tool enum per message.
+5. Use selected attitude to filter `dance` tool enum per message.
+6. Keep full tool enable/disable separate from move gating.
+7. Later, allow OpenWebUI model/contact metadata to select attitude automatically, with manual app setting as fallback or override.
+
+## Do Not Do Yet
+
+- Do not dump the full emotion library into the app repo.
+- Do not make separate UI controls for idle and speaking movement.
+- Do not use long theatrical moves as random idle loops.
+- Do not depend on OpenWebUI to execute robot movement.
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000000000000000000000000000000000000..77ab930e75806d59f64bc8346c64d56e0760c665
--- /dev/null
+++ b/CODE_OF_CONDUCT.md
@@ -0,0 +1,89 @@
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+We pledge to make our community welcoming, safe, and equitable for all.
+
+We are committed to fostering an environment that respects and promotes the dignity, rights, and contributions of all individuals, regardless of characteristics including race, ethnicity, caste, color, age, physical characteristics, neurodiversity, disability, sex or gender, gender identity or expression, sexual orientation, language, philosophy or religion, national or social origin, socio-economic position, level of education, or other status. The same privileges of participation are extended to everyone who participates in good faith and in accordance with this Covenant.
+
+
+## Encouraged Behaviors
+
+While acknowledging differences in social norms, we all strive to meet our community's expectations for positive behavior. We also understand that our words and actions may be interpreted differently than we intend based on culture, background, or native language.
+
+With these considerations in mind, we agree to behave mindfully toward each other and act in ways that center our shared values, including:
+
+1. Respecting the **purpose of our community**, our activities, and our ways of gathering.
+2. Engaging **kindly and honestly** with others.
+3. Respecting **different viewpoints** and experiences.
+4. **Taking responsibility** for our actions and contributions.
+5. Gracefully giving and accepting **constructive feedback**.
+6. Committing to **repairing harm** when it occurs.
+7. Behaving in other ways that promote and sustain the **well-being of our community**.
+
+
+## Restricted Behaviors
+
+We agree to restrict the following behaviors in our community. Instances, threats, and promotion of these behaviors are violations of this Code of Conduct.
+
+1. **Harassment.** Violating explicitly expressed boundaries or engaging in unnecessary personal attention after any clear request to stop.
+2. **Character attacks.** Making insulting, demeaning, or pejorative comments directed at a community member or group of people.
+3. **Stereotyping or discrimination.** Characterizing anyone’s personality or behavior on the basis of immutable identities or traits.
+4. **Sexualization.** Behaving in a way that would generally be considered inappropriately intimate in the context or purpose of the community.
+5. **Violating confidentiality**. Sharing or acting on someone's personal or private information without their permission.
+6. **Endangerment.** Causing, encouraging, or threatening violence or other harm toward any person or group.
+7. Behaving in other ways that **threaten the well-being** of our community.
+
+### Other Restrictions
+
+1. **Misleading identity.** Impersonating someone else for any reason, or pretending to be someone else to evade enforcement actions.
+2. **Failing to credit sources.** Not properly crediting the sources of content you contribute.
+3. **Promotional materials**. Sharing marketing or other commercial content in a way that is outside the norms of the community.
+4. **Irresponsible communication.** Failing to responsibly present content which includes, links or describes any other restricted behaviors.
+
+
+## Reporting an Issue
+
+Tensions can occur between community members even when they are trying their best to collaborate. Not every conflict represents a code of conduct violation, and this Code of Conduct reinforces encouraged behaviors and norms that can help avoid conflicts and minimize harm.
+
+When an incident does occur, it is important to report it promptly. To report a possible violation, please, send an email to contact@pollen-robotics.com.
+
+Community Moderators take reports of violations seriously and will make every effort to respond in a timely manner. They will investigate all reports of code of conduct violations, reviewing messages, logs, and recordings, or interviewing witnesses and other participants. Community Moderators will keep investigation and enforcement actions as transparent as possible while prioritizing safety and confidentiality. In order to honor these values, enforcement actions are carried out in private with the involved parties, but communicating to the whole community may be part of a mutually agreed upon resolution.
+
+
+## Addressing and Repairing Harm
+
+If an investigation by the Community Moderators finds that this Code of Conduct has been violated, the following enforcement ladder may be used to determine how best to repair harm, based on the incident's impact on the individuals involved and the community as a whole. Depending on the severity of a violation, lower rungs on the ladder may be skipped.
+
+1) **Warning**
+ 1) Event: A violation involving a single incident or series of incidents.
+ 2) Consequence: A private, written warning from the Community Moderators.
+ 3) Repair: Examples of repair include a private written apology, acknowledgement of responsibility, and seeking clarification on expectations.
+2) **Temporarily Limited Activities**
+ 1) Event: A repeated incidence of a violation that previously resulted in a warning, or the first incidence of a more serious violation.
+ 2) Consequence: A private, written warning with a time-limited cooldown period designed to underscore the seriousness of the situation and give the community members involved time to process the incident. The cooldown period may be limited to particular communication channels or interactions with particular community members.
+ 3) Repair: Examples of repair may include making an apology, using the cooldown period to reflect on actions and impact, and being thoughtful about re-entering community spaces after the period is over.
+3) **Temporary Suspension**
+ 1) Event: A pattern of repeated violation which the Community Moderators have tried to address with warnings, or a single serious violation.
+ 2) Consequence: A private written warning with conditions for return from suspension. In general, temporary suspensions give the person being suspended time to reflect upon their behavior and possible corrective actions.
+ 3) Repair: Examples of repair include respecting the spirit of the suspension, meeting the specified conditions for return, and being thoughtful about how to reintegrate with the community when the suspension is lifted.
+4) **Permanent Ban**
+ 1) Event: A pattern of repeated code of conduct violations that other steps on the ladder have failed to resolve, or a violation so serious that the Community Moderators determine there is no way to keep the community safe with this person as a member.
+ 2) Consequence: Access to all community spaces, tools, and communication channels is removed. In general, permanent bans should be rarely used, should have strong reasoning behind them, and should only be resorted to if working through other remedies has failed to change the behavior.
+ 3) Repair: There is no possible repair in cases of this severity.
+
+This enforcement ladder is intended as a guideline. It does not limit the ability of Community Managers to use their discretion and judgment, in keeping with the best interests of our community.
+
+
+## Scope
+
+This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public or other spaces. Examples of representing our community include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
+
+
+## Attribution
+
+This Code of Conduct is adapted from the Contributor Covenant, version 3.0, permanently available at [https://www.contributor-covenant.org/version/3/0/](https://www.contributor-covenant.org/version/3/0/).
+
+Contributor Covenant is stewarded by the Organization for Ethical Source and licensed under CC BY-SA 4.0. To view a copy of this license, visit [https://creativecommons.org/licenses/by-sa/4.0/](https://creativecommons.org/licenses/by-sa/4.0/)
+
+For answers to common questions about Contributor Covenant, see the FAQ at [https://www.contributor-covenant.org/faq](https://www.contributor-covenant.org/faq). Translations are provided at [https://www.contributor-covenant.org/translations](https://www.contributor-covenant.org/translations). Additional enforcement and community guideline resources can be found at [https://www.contributor-covenant.org/resources](https://www.contributor-covenant.org/resources). The enforcement ladder was inspired by the work of [Mozilla’s code of conduct team](https://github.com/mozilla/inclusion).
\ No newline at end of file
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000000000000000000000000000000000000..639e2af5146a66888263986b02226fec06328f37
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,93 @@
+# Contributing
+
+Thank you for helping improve Reachy OpenWebUI.
+
+This repository is an OpenWebUI-native Reachy Mini app. Keep changes aligned with the current shape of the code: OpenWebUI owns transcription, model/workspace behavior, variables, and speech; the Reachy app owns robot media, settings, tool dispatch, VAD, and motion.
+
+## Quick Start
+
+1. Fork and clone the repo.
+
+```bash
+git clone https://github.com/pollen-robotics/Reachy_OpenWebUI
+cd Reachy_OpenWebUI
+```
+
+2. Create an environment.
+
+```bash
+uv venv --python python3.12 .venv
+source .venv/bin/activate
+uv sync --group dev
+```
+
+3. Copy `.env.example` only for local development. Do not commit real `.env` files or secrets.
+
+## Current Project Shape
+
+- Python package: `Reachy_OpenWebUI`
+- Reachy Mini Apps entry point: `Reachy_OpenWebUI`
+- Console script: `reachy-mini-conversation-app-openwebui`
+- Main runtime code: `src/Reachy_OpenWebUI/`
+- Settings/call UI: `src/Reachy_OpenWebUI/static/`
+- Default tool allow-list: `src/Reachy_OpenWebUI/profiles/default/tools.txt`
+- Hugging Face Space project page: `app.py`
+
+`requirements.txt` is for the Space project page only. Use `pyproject.toml` for the robot app dependencies.
+
+## Development Workflow
+
+- Keep pull requests focused on one behavior or documentation update.
+- Prefer small, reviewable changes over broad rewrites.
+- Do not reintroduce legacy local STT, voice-provider, or old package-name docs unless the code actually supports them again.
+- Keep OpenWebUI auth wording precise: API keys may work for HTTP endpoints, but the realtime socket path needs a JWT in `OPENWEBUI_TOKEN`.
+- Update README and `.env.example` whenever settings, CLI flags, package names, or user-visible behavior change.
+- Avoid committing generated files, real settings files, downloaded models, caches, or secrets.
+
+## Checks
+
+Run the checks that are available in this checkout:
+
+```bash
+uv run ruff check .
+uv run ruff format . --check
+uv run mypy --pretty --show-error-codes
+uv run python -m compileall src app.py
+```
+
+There is no `tests/` directory in this checkout. Add focused tests when you add behavior that can be tested without robot hardware.
+
+## Documentation Checklist
+
+Before opening a PR, verify docs against the actual code:
+
+- CLI flags come from `src/Reachy_OpenWebUI/utils.py`.
+- Env keys come from `src/Reachy_OpenWebUI/settings_keys.py` and `src/Reachy_OpenWebUI/config.py`.
+- Settings UI routes come from `src/Reachy_OpenWebUI/console.py`.
+- Tool names come from `src/Reachy_OpenWebUI/profiles/default/tools.txt` and `src/Reachy_OpenWebUI/tools/`.
+- Package names and entry points come from `pyproject.toml`.
+
+## Release Notes
+
+When preparing a release:
+
+1. Update the version in `pyproject.toml`.
+2. Confirm README and `.env.example` match the release behavior.
+3. Run the checks above.
+4. Commit the version bump.
+5. Create and push a tag.
+
+```bash
+git tag vX.Y.Z
+git push origin vX.Y.Z
+```
+
+## AI-Assisted Contributions
+
+AI tools are fine for exploration and drafts, but the human author is responsible for the final patch. Keep AI-assisted changes readable, minimal, and verified against the code that is actually in the repo.
+
+## Filing Issues
+
+For bugs, include the Reachy Mini environment, Python version, OpenWebUI URL shape, auth mode, exact command or launcher path, and relevant logs. Use `--debug` when collecting local logs.
+
+For feature requests, describe the user workflow, expected robot behavior, and whether the change belongs in OpenWebUI, the Reachy settings UI, or the robot-side tool/runtime layer.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..29f81d812f3e768fa89638d1f72920dbfd1413a8
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/MANIFEST.in b/MANIFEST.in
new file mode 100644
index 0000000000000000000000000000000000000000..bc71a67f1f3fa593e90978941d860e6d3a9e1248
--- /dev/null
+++ b/MANIFEST.in
@@ -0,0 +1 @@
+recursive-include src/Reachy_OpenWebUI/profiles *.txt *.py
diff --git a/README.md b/README.md
index 98c76c3f009784ea749cb93ddabc18b8b9415da2..ef48957320d25d5397065599749d231a500931ff 100644
--- a/README.md
+++ b/README.md
@@ -1,11 +1,253 @@
----
-title: Reachy OpenWebUI
-emoji: 📊
-colorFrom: gray
-colorTo: red
-sdk: static
-pinned: false
-license: apache-2.0
----
-
-Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
+---
+title: Reachy OpenWebUI
+emoji: 🐞
+colorFrom: gray
+colorTo: blue
+sdk: gradio
+app_file: app.py
+pinned: false
+short_description: Phone-style OpenWebUI conversations for Reachy Mini.
+tags:
+- reachy_mini
+- reachy_mini_python_app
+sdk_version: 6.18.0
+license: apache-2.0
+---
+
+
+
+
+
+# Reachy OpenWebUI
+
+Reachy OpenWebUI is a phone-style conversation app for Reachy Mini. OpenWebUI owns the model, transcription, chat behavior, user context, and TTS. This app owns the robot-side runtime: settings, no-wake-word listening, camera buffering, local Reachy tools, avatars, chat state, and motion.
+
+This Hugging Face Space is a project page. The real app runs inside the Reachy Mini app environment where it can access the robot daemon, microphone, speaker, camera, and movement APIs.
+
+## Highlights
+
+- Phone-inspired settings and conversation UI served by the Reachy Mini app webserver.
+- OpenWebUI model/workspace picker shown as contacts.
+- OpenWebUI conversation list support for returning to saved chats.
+- Model and user avatar proxying from OpenWebUI profile image endpoints.
+- No-wake-word voice loop using Reachy audio, Silero VAD, OpenWebUI STT, OpenWebUI chat, and OpenWebUI TTS.
+- Sentence-by-sentence speech streaming so audio starts before the full model answer is finished.
+- Reachy-side tools for dance, recorded emotions, camera, head tracking, head movement, and speech.
+- Speech-reactive head motion blended with queued robot moves.
+- Robot attitudes that can shape idle motion, speaking motion, and which dance/emotion moves the model can choose.
+
+## Runtime Flow
+
+```text
+Reachy microphone
+ -> audio startup tuning and SDK record loop
+ -> Silero VAD and level fallback
+ -> OpenWebUI audio transcription
+ -> OpenWebUI chat stream with optional Reachy tool specs
+ -> optional Reachy-side tool execution
+ -> OpenWebUI speech
+ -> Reachy speaker output plus speech-reactive motion
+```
+
+OpenWebUI may accept requests at `/api/chat/completions` while returning either
+classic chat-completion chunks (`chat.completion.chunk`) or Responses-style
+events (`response.output_text.delta`, `response.output_text.done`,
+`response.completed`). The runtime reader must support both formats because the
+selected OpenWebUI model/contact can route through different providers even when
+the model id shown in the UI is unchanged.
+
+## Install
+
+This repo currently has no `uv.lock`, so do not use `uv sync --frozen`.
+
+```bash
+uv venv --python python3.12 .venv
+source .venv/bin/activate
+uv sync
+```
+
+Editable pip install:
+
+```bash
+python -m venv .venv
+source .venv/bin/activate
+pip install -e .
+```
+
+Optional local vision extra:
+
+```bash
+uv sync --extra local_vision
+pip install -e .[local_vision]
+```
+
+Developer tools:
+
+```bash
+uv sync --group dev
+```
+
+`requirements.txt` is only for this Hugging Face Space project page. The robot app dependencies live in `pyproject.toml`.
+
+## Configuration
+
+The app reads `~/.config/settings/.env` first, then a local `.env` if present. The settings UI writes the stable file at `~/.config/settings/.env`.
+
+Core OpenWebUI settings:
+
+| Variable | Purpose |
+| --- | --- |
+| `OPENWEBUI_URL` | OpenWebUI base URL. Values ending in `/api` are accepted. |
+| `OPENWEB_LOADED_LLM` | Selected OpenWebUI model, workspace, or contact id. |
+| `OPENWEBUI_API_KEY` | API key for HTTP requests when your OpenWebUI server accepts API-key bearer auth. |
+| `OPENWEBUI_TOKEN` | Browser/session JWT. Preferred for chat, Socket.IO, transcription, and speech. |
+| `OPENWEBUI_CHAT_ID` | Saved OpenWebUI chat id. Leave blank on first launch. |
+| `MIC_GAIN` | Digital gain applied before VAD and transcription upload. |
+| `HF_HOME` | Hugging Face cache directory. |
+| `HF_TOKEN` | Optional token for gated or private assets. |
+
+User/context variables sent to OpenWebUI:
+
+| Variable | Purpose |
+| --- | --- |
+| `OPENWEBUI_USER_ID` | Optional user id. If blank, the app tries to derive it from the JWT. |
+| `OPENWEBUI_USER_NAME` | User name supplied to OpenWebUI variables and socket context. |
+| `OPENWEBUI_USER_EMAIL` | User email supplied to OpenWebUI variables and socket context. |
+| `OPENWEBUI_USER_LANGUAGE` | User language variable. |
+| `OPENWEBUI_USER_LOCATION` | User location variable. |
+| `OPENWEBUI_USER_TIMEZONE` | User timezone variable. |
+
+Audio and timing settings:
+
+| Variable | Purpose |
+| --- | --- |
+| `OPENWEBUI_TTS_READ_TIMEOUT` | Read timeout for OpenWebUI speech responses. |
+| `OPENWEBUI_CONVERSATION_IDLE_RESET_SECONDS` | Optional idle reset. `0` disables it. |
+| `VAD_THRESHOLD` | Silero speech probability threshold. |
+| `VAD_FALLBACK_THRESHOLD` | RMS fallback threshold. |
+| `VAD_SPEECH_ONSET_CHUNKS` | Speech chunks required before a turn starts. |
+| `VAD_SILENCE_END_CHUNKS` | Silence chunks required before a turn ends. |
+| `VAD_MIN_SPEECH_CHUNKS` | Minimum speech chunks before sending audio to OpenWebUI transcription. |
+| `SILERO_VAD_ONNX_PATH` | Optional path for the Silero ONNX model. |
+
+## TTS Voices
+
+Set TTS voices in OpenWebUI. This app reads the selected model/contact voice metadata and sends that voice back to the OpenWebUI speech endpoint.
+
+If a model/contact has no voice set in OpenWebUI, the app sends no voice value and lets OpenWebUI use its default TTS behavior. There is intentionally no app-level voice picker because every OpenWebUI install can expose different TTS engines and voice names.
+
+## Running
+
+The normal runtime path is the Reachy Mini Apps launcher. It provides the FastAPI settings app and serves the phone UI declared by:
+
+```python
+custom_app_url = "http://0.0.0.0:7860/"
+```
+
+Console entry point:
+
+```bash
+reachy-mini-conversation-app-openwebui
+```
+
+CLI options:
+
+| Option | Default | Description |
+| --- | --- | --- |
+| `--no-camera` | `False` | Skip camera frame buffering. |
+| `--smolvlm` | `False` | Try to initialize the optional local SmolVLM vision manager. |
+| `--robot-name ` | `None` | Connect to a daemon started with the same robot name. |
+| `--debug` | `False` | Enable verbose app logging. |
+
+## Settings UI
+
+The phone-style UI lives in `src/Reachy_OpenWebUI/static/`.
+
+It includes:
+
+- Power-on screen while the backend is getting ready.
+- Home screen with contacts, conversations, quick connect, and settings.
+- Contacts page backed by OpenWebUI models.
+- Conversations page backed by OpenWebUI chat history.
+- Call screen with transcript bubbles, typing indicators, model avatar, user avatar, mute, end call, and back navigation.
+- Settings for OpenWebUI URL, model/contact, credentials, mic gain, vision-only contacts, attitude, and Reachy-side tools.
+
+## Tools
+
+Default Reachy-side tool allow-list:
+
+```text
+src/Reachy_OpenWebUI/profiles/default/tools.txt
+```
+
+Enabled by default:
+
+| Tool | Behavior |
+| --- | --- |
+| `dance` | Queue a named or random dance from `reachy_mini_dances_library`. |
+| `stop_dance` | Clear the dance queue. |
+| `play_emotion` | Queue a recorded emotion from `reachy-mini-emotions-library`. |
+| `stop_emotion` | Clear the emotion queue. |
+| `camera` | Read the latest buffered camera frame and pass it to an optional vision manager. |
+| `idle_do_nothing` | Explicit idle no-op for idle turns. |
+| `head_tracking` | Attempt to toggle camera-worker head tracking. |
+| `move_head` | Queue a head pose change: left, right, up, down, or front. |
+| `speak` | Send text through the same OpenWebUI speech path used by normal assistant responses. |
+
+The settings page can enable or disable Reachy-side tools. OpenWebUI tools are still managed in OpenWebUI.
+
+## Attitudes
+
+`Attitude` is one user-facing movement setting. It is designed to control:
+
+- idle motion
+- speech-reactive motion
+- which dance and emotion moves are offered to the model
+
+The goal is simple: a serious model should not move like a silly one, and a playful model should not be stuck with the same tiny idle pattern as a formal one.
+
+## Chat State
+
+OpenWebUI chat state is stored in the stable settings file and recorded in:
+
+```text
+~/.config/settings/openwebui_chat_history.json
+```
+
+The conversation window rolls over at local 7 AM. Callback and conversation selection clear or replace the saved chat id so OpenWebUI can attach the next turn to the right conversation.
+
+## Vision Status
+
+Camera frame buffering is bundled and enabled unless `--no-camera` is passed. The optional local vision manager expects `Reachy_OpenWebUI.vision.processors`, which is not present in this checkout. If that module is absent, startup logs a warning and the `camera` tool returns an unavailable-vision error.
+
+## Project Layout
+
+```text
+app.py Hugging Face Space project page
+pyproject.toml package metadata, dependencies, app entry points
+requirements.txt Space-only dependency file
+src/Reachy_OpenWebUI/main.py Reachy Mini App entry point
+src/Reachy_OpenWebUI/console.py settings routes and media loop
+src/Reachy_OpenWebUI/local/ OpenWebUI chat, speech, transcription, VAD
+src/Reachy_OpenWebUI/tools/ Reachy-side tools
+src/Reachy_OpenWebUI/static/ phone-style UI
+src/Reachy_OpenWebUI/profiles/default/ default tool allow-list
+external_content/ starter external profile/tool examples
+```
+
+## Development Checks
+
+Run the checks available in this checkout:
+
+```bash
+uv run ruff check .
+uv run ruff format . --check
+uv run mypy --pretty --show-error-codes
+uv run python -m compileall src app.py
+```
+
+There is no `tests/` directory in this checkout. Add focused tests when adding behavior that can be tested off-robot.
+
+## License
+
+Apache 2.0
\ No newline at end of file
diff --git a/app.py b/app.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f88f393d14897b8c9390800b8f73c3c4d9d9264
--- /dev/null
+++ b/app.py
@@ -0,0 +1,239 @@
+import base64
+from pathlib import Path
+
+import gradio as gr
+
+
+CSS = """
+:root {
+ color-scheme: dark;
+}
+
+.gradio-container {
+ min-height: 100vh;
+ background:
+ radial-gradient(circle at 18% 8%, rgba(0, 122, 204, 0.20), transparent 28rem),
+ radial-gradient(circle at 90% 16%, rgba(80, 180, 150, 0.12), transparent 24rem),
+ linear-gradient(145deg, #0b0f14 0%, #121821 48%, #070a0f 100%) !important;
+ color: #eef3f8;
+ font-family: Inter, Segoe UI, Arial, sans-serif;
+}
+
+.main {
+ max-width: 1120px;
+ margin: 0 auto;
+ padding: 36px 20px 44px;
+}
+
+.hero {
+ display: grid;
+ grid-template-columns: minmax(0, 1.25fr) minmax(280px, 0.75fr);
+ gap: 28px;
+ align-items: center;
+ padding: 24px 0 34px;
+}
+
+.eyebrow {
+ margin: 0 0 12px;
+ color: #7bb9e8;
+ font-size: 0.78rem;
+ font-weight: 700;
+ letter-spacing: 0.12em;
+ text-transform: uppercase;
+}
+
+.hero h1 {
+ margin: 0;
+ color: #ffffff;
+ font-size: clamp(2.5rem, 7vw, 5.4rem);
+ line-height: 0.94;
+ letter-spacing: 0;
+}
+
+.lead {
+ max-width: 680px;
+ margin: 22px 0 0;
+ color: #b8c6d5;
+ font-size: 1.08rem;
+ line-height: 1.65;
+}
+
+.hero-card,
+.panel {
+ border: 1px solid rgba(180, 198, 213, 0.16);
+ border-radius: 8px;
+ background: rgba(13, 19, 28, 0.74);
+ box-shadow: 0 22px 70px rgba(0, 0, 0, 0.36);
+}
+
+.hero-card {
+ display: grid;
+ gap: 16px;
+ padding: 22px;
+}
+
+.app-mark {
+ width: 90px;
+ height: 90px;
+ border-radius: 22px;
+ background: #0f1620;
+ box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.08);
+}
+
+.hero-card h2,
+.panel h2 {
+ margin: 0;
+ color: #ffffff;
+ font-size: 1.15rem;
+}
+
+.hero-card p,
+.panel p {
+ margin: 0;
+ color: #b8c6d5;
+ line-height: 1.55;
+}
+
+.chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin-top: 4px;
+}
+
+.chip {
+ border: 1px solid rgba(123, 185, 232, 0.28);
+ border-radius: 999px;
+ padding: 6px 10px;
+ color: #d9ecfb;
+ background: rgba(0, 122, 204, 0.14);
+ font-size: 0.86rem;
+}
+
+.grid {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 14px;
+ margin-top: 18px;
+}
+
+.panel {
+ padding: 18px;
+}
+
+.section-title {
+ margin: 36px 0 12px;
+ color: #ffffff;
+ font-size: 1.35rem;
+}
+
+.flow {
+ display: grid;
+ gap: 8px;
+ padding: 18px;
+ border: 1px solid rgba(180, 198, 213, 0.14);
+ border-radius: 8px;
+ background: rgba(255, 255, 255, 0.045);
+ color: #d5e2ec;
+ font-family: Consolas, Monaco, monospace;
+ font-size: 0.92rem;
+}
+
+.flow span {
+ display: block;
+}
+
+.footer-note {
+ margin-top: 28px;
+ color: #8393a2;
+ font-size: 0.92rem;
+}
+
+@media (max-width: 820px) {
+ .hero,
+ .grid {
+ grid-template-columns: 1fr;
+ }
+}
+"""
+
+
+def _image_data_uri(path: str) -> str:
+ image_path = Path(path)
+ if not image_path.exists():
+ return ""
+ encoded = base64.b64encode(image_path.read_bytes()).decode("ascii")
+ return f"data:image/png;base64,{encoded}"
+
+
+ICON_URI = _image_data_uri("src/Reachy_OpenWebUI/static/assets/reachy-conversation-app.png")
+
+
+HTML = f"""
+
+
+
+
Reachy Mini + OpenWebUI
+
Reachy OpenWebUI
+
+ A phone-style conversation app for Reachy Mini. OpenWebUI handles the model,
+ transcription, user context, and TTS; the Reachy app handles the robot runtime,
+ settings UI, local tools, avatars, chat state, and movement.
+
+
+
+
+
+
What It Does
+
+
+
Contacts
+
OpenWebUI models and workspaces appear as phone contacts with cached avatars.
+
+
+
Conversations
+
Saved OpenWebUI chat ids can be selected from a phone-style conversation list.
+
+
+
Motion
+
Speech-reactive head movement blends with Reachy-side dances and recorded emotions.
+
+
+
+
Runtime Flow
+
+ Reachy microphone
+ -> VAD and OpenWebUI transcription
+ -> OpenWebUI chat completion with Reachy tool specs
+ -> optional local Reachy tool execution
+ -> OpenWebUI speech
+ -> Reachy speaker output plus motion
+
+
+
+ Install from the repository and launch through Reachy Mini Apps for the full robot runtime.
+ This hosted Space intentionally does not attempt to control hardware.
+
+
+"""
+
+
+with gr.Blocks(title="Reachy OpenWebUI") as demo:
+ gr.HTML(HTML)
+
+
+if __name__ == "__main__":
+ demo.launch(css=CSS)
diff --git a/external_content/external_profiles/starter_profile/instructions.txt b/external_content/external_profiles/starter_profile/instructions.txt
new file mode 100644
index 0000000000000000000000000000000000000000..7a100fbdb9f518cb2ade91b5e10d6bb7346c087d
--- /dev/null
+++ b/external_content/external_profiles/starter_profile/instructions.txt
@@ -0,0 +1,6 @@
+You are a helpful Reachy Mini assistant running from an external profile.
+
+When asked to demonstrate your custom greeting, use the `starter_custom_tool` tool.
+You can also dance and show emotions like the built-in profiles.
+
+Be friendly and concise, and explain that you're using an external profile/tool setup when asked about yourself.
diff --git a/external_content/external_profiles/starter_profile/tools.txt b/external_content/external_profiles/starter_profile/tools.txt
new file mode 100644
index 0000000000000000000000000000000000000000..9ea3041ed386e89066fbf6f46595342ca6065d85
--- /dev/null
+++ b/external_content/external_profiles/starter_profile/tools.txt
@@ -0,0 +1,12 @@
+# This file is an explicit allow-list.
+# Every tool name listed below must be either:
+# - a built-in tool from src/Reachy_OpenWebUI/tools/
+# - or an external tool file in TOOLS_DIRECTORY (e.g. external_tools/starter_custom_tool.py)
+
+dance
+stop_dance
+play_emotion
+stop_emotion
+move_head
+starter_custom_tool
+
diff --git a/external_content/external_tools/starter_custom_tool.py b/external_content/external_tools/starter_custom_tool.py
new file mode 100644
index 0000000000000000000000000000000000000000..796c6da99a38073797b7fd6aab18a3fdecaaea68
--- /dev/null
+++ b/external_content/external_tools/starter_custom_tool.py
@@ -0,0 +1,34 @@
+"""Example external tool implementation."""
+
+import logging
+from typing import Any, Dict
+
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+
+
+logger = logging.getLogger(__name__)
+
+
+class StarterCustomTool(Tool):
+ """Placeholder custom tool - demonstrates external tool loading."""
+
+ name = "starter_custom_tool"
+ description = "A placeholder custom tool loaded from outside the library"
+ parameters_schema = {
+ "type": "object",
+ "properties": {
+ "message": {
+ "type": "string",
+ "description": "Optional message to include in the response",
+ },
+ },
+ "required": [],
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ """Execute the placeholder tool."""
+ message = kwargs.get("message", "Hello from custom tool!")
+ logger.info(f"Tool call: starter_custom_tool message={message}")
+
+ return {"status": "success", "message": message}
+
diff --git a/index.html b/index.html
index b0c4b3666032a737f3903db53e6a8a9272483e28..90d6193ecc32bd3428f39f1534c178245bf79275 100644
--- a/index.html
+++ b/index.html
@@ -1,19 +1,125 @@
-
-
-
-
-
- My static Space
-
-
-
-
-
Welcome to your static Space!
-
You can modify this app directly by editing index.html in the Files and versions tab.
OpenWebUI managed voice and personality · No wake word
+
+
+
+
Local Conversation App
+
Run Reachy Mini conversations on your own stack.
+
+ An OpenWebUI-first, camera-aware companion for Reachy Mini. Use OpenWebUI workspaces/models for personality and voice behavior, with VAD listening without a wake word.
+
+ OpenWebUI model dropdown
+ OpenWebUI-managed TTS
+ No-wake-word VAD
+ Workspace-managed personalities
+
+
+
+
+
+
Reachy Mini can move, dance, and emote while holding a natural conversation.
+
+
+
+
+
+
+
+
What’s inside
+
All-in-one conversational layer for your robot
+
+ The app blends local speech, vision, and motion so Reachy Mini feels present.
+
+
+
+
+ 🎤
+
Natural voice chat
+
Talk freely and get replies from your configured local chat-completions model.
+
+
+ 🎥
+
Vision-aware replies
+
Ask the camera tool to see what’s in front, track a face, or keep attention on whoever is speaking.
+
+
+ 💃
+
Expressive motion
+
Queue dances, play recorded emotions while Reachy listens and talks.
+
+
+ 🧠
+
Personalities on demand
+
Switch conversation styles in OpenWebUI workspaces/models while the bot exposes tools like dance, camera, and tracking.
+
+
+ 🌐
+
Ready for your setup
+
Works with wired or wireless Reachy Mini, and can run vision locally or through the default cloud model.
+
+
+
+
+
+
+
+
How it feels
+
From hello to helpful in seconds
+
+
👋 Say “Hey Reachy” and start chatting—no extra setup in the moment.
+
👀 Ask what it sees; it can peek through the camera or keep focus on your face.
+
🎭 Trigger emotions or dance breaks to keep the conversation lively.
+
📝 Follow along with live transcripts in the web UI or run audio-only from the console.
+
+
+
+
Where it shines
+
Great for demos, teaching, and playful exploration
+
+ Show off how Reachy Mini listens, responds, and moves in sync. Whether you’re guiding a class, hosting a booth, or experimenting at home, the app keeps the robot expressive without juggling scripts or joystick controls.
+
+
+ Live conversation
+ Face tracking
+ Camera tool
+ Dance library
+ Profiles & tools
+
+
+
+
+
+
+
+
+
+
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000000000000000000000000000000000000..01e12f448a04659eca091f47d701b9665346f95e
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,150 @@
+[build-system]
+requires = ["setuptools"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "Reachy_OpenWebUI"
+version = "0.6.4.86"
+authors = [{ name = "Jacid23" }]
+description = "OpenWebUI-first Reachy Mini conversation app using OpenWebUI-managed STT, chat, workspace tools, and TTS."
+readme = "README.md"
+requires-python = ">=3.10"
+dependencies = [
+ #Media
+ "av",
+ "aiortc>=1.13.0",
+ "fastrtc>=0.0.34",
+ "gradio==5.50.1.dev1",
+ "huggingface-hub==1.3.0",
+ "httpx",
+ "numpy",
+ "onnxruntime",
+ "opencv-python>=4.12.0.88",
+ "zxing-cpp>=2.3.0",
+
+ #Environment variables
+ "python-dotenv",
+
+ # Client library used for local Ollama/vLLM/OpenWebUI chat endpoints
+ "openai>=2.30.0",
+
+ #Reachy mini
+ "reachy_mini_dances_library",
+ "reachy_mini_toolbox",
+ "reachy-mini>=1.7.1",
+ "gradio_client>=1.13.3",
+
+ #Required at import/runtime by camera_worker, local audio, and local pipeline
+ "scipy",
+
+ #OpenWebUI pipeline (VAD/audio upload/chat/TTS). Torch/Silero are optional at runtime
+ # because Reachy's shared venv already owns torch, and fresh torch pulls can
+ # drag in giant CUDA/triton wheels.
+ "soundfile",
+ "setuptools<82",
+]
+
+[project.optional-dependencies]
+local_vision = [
+ "accelerate>=1.13.0; platform_machine != 'aarch64' and platform_machine != 'arm64'",
+ "torch>=2.1; platform_machine != 'aarch64' and platform_machine != 'arm64'",
+ "transformers==5.3.0; platform_machine != 'aarch64' and platform_machine != 'arm64'",
+ "num2words",
+]
+
+[dependency-groups]
+dev = [
+ "pytest",
+ "pytest-asyncio",
+ "ruff==0.12.0",
+ "mypy==1.18.2",
+ "pre-commit",
+ "types-requests",
+ "python-semantic-release>=10.5.3",
+]
+
+[project.scripts]
+reachy-mini-conversation-app-openwebui = "Reachy_OpenWebUI.main:main"
+
+[tool.uv]
+dependency-metadata = [
+ # Upstream metadata currently marks `gstreamer-msvc-runtime` as unconditional.
+ # It should only be required on Windows. Temp fix.
+ { name = "gstreamer-libs", version = "1.28.1", requires-dist = ["gstreamer-msvc-runtime; sys_platform == 'win32'", "setuptools"] },
+]
+
+[project.entry-points."reachy_mini_apps"]
+Reachy_OpenWebUI = "Reachy_OpenWebUI.main:ReachyMiniConversationOpenWebUIApp"
+
+[tool.setuptools]
+package-dir = { "" = "src" }
+include-package-data = true
+
+[tool.setuptools.packages.find]
+where = ["src"]
+
+[tool.setuptools.package-data]
+Reachy_OpenWebUI = [
+ "images/*",
+ "static/*",
+ "static/assets/*",
+ "sub_apps/cookAIware/data/*.json",
+ "sub_apps/cookAIware/profiles/**/*.txt",
+ "sub_apps/cookAIware/profiles/**/*.py",
+ ".env.example",
+ "demos/**/*.txt",
+ "profiles/**/*.txt",
+ "profiles/**/*.py",
+]
+reachy_talk_data = [
+ "profiles/**/*.txt",
+ "profiles/**/*.py",
+]
+
+[tool.ruff]
+line-length = 119
+exclude = [".venv", "dist", "build", "**/__pycache__", "*.egg-info", ".mypy_cache", ".pytest_cache"]
+
+[tool.ruff.lint]
+select = [
+ "E", # pycodestyle errors
+ "F", # pyflakes
+ "W", # pycodestyle warnings
+ "I", # isort
+ "C4", # flake8-comprehensions
+ "D", # pydocstyle
+]
+ignore = [
+ "E501", # handled by formatter
+ "D100", # ignore missing module docstrings
+ "D203", # blank line before class docstring (conflicts with D211)
+ "D213", # summary on second line (conflicts with D212)
+]
+
+[tool.ruff.lint.isort]
+length-sort = true
+lines-after-imports = 2
+no-lines-before = ["standard-library", "local-folder"]
+known-local-folder = ["Reachy_OpenWebUI"]
+known-first-party = ["reachy_mini", "reachy_mini_dances_library", "reachy_mini_toolbox"]
+split-on-trailing-comma = true
+
+[tool.ruff.format]
+quote-style = "double"
+indent-style = "space"
+skip-magic-trailing-comma = false
+line-ending = "auto"
+
+[tool.mypy]
+python_version = "3.12"
+files = ["src/"]
+ignore_missing_imports = true
+strict = true
+show_error_codes = true
+warn_unused_ignores = true
+
+
+
+
+
+
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..eb9c6b0a11edef008fb8884e0f28c3566f47f394
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1 @@
+# Hugging Face Spaces provides Gradio from the README Space SDK config.
diff --git a/setup.py b/setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..d4ef68d2c176cb6b2c271373dac68d9625a5d62d
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,28 @@
+from __future__ import annotations
+from shutil import copytree
+from pathlib import Path
+
+from setuptools import setup
+from setuptools.command.build_py import build_py
+
+
+PROJECT_ROOT = Path(__file__).parent.resolve()
+SOURCE_PROFILES_DIR = PROJECT_ROOT / "src" / "Reachy_OpenWebUI" / "profiles"
+TARGET_PACKAGE = "reachy_talk_data"
+TARGET_SUBDIR = "profiles"
+
+
+class BuildPyWithProfiles(build_py):
+ """Copy built-in profiles into the wheel data package at build time."""
+
+ def run(self) -> None:
+ """Build Python modules, then copy root-level profiles into reachy_talk_data."""
+ super().run()
+
+ target_root = Path(self.build_lib) / TARGET_PACKAGE / TARGET_SUBDIR
+ copytree(SOURCE_PROFILES_DIR, target_root, dirs_exist_ok=True)
+
+
+setup(
+ cmdclass={"build_py": BuildPyWithProfiles},
+)
diff --git a/src/Reachy_OpenWebUI/.env.example b/src/Reachy_OpenWebUI/.env.example
new file mode 100644
index 0000000000000000000000000000000000000000..1437294a511a211687f45b1b228a018486ed6aea
--- /dev/null
+++ b/src/Reachy_OpenWebUI/.env.example
@@ -0,0 +1,44 @@
+# =============================================================================
+# LLM Configuration (Judgy Reachy local OpenWebUI)
+# =============================================================================
+# OpenWebUI native API base. The client posts to /api/chat/completions.
+OPENWEBUI_URL="http://localhost:3001/api"
+
+# Model name as known by your LLM server
+OPENWEBUI_MODEL="reachy-convo"
+
+# API key for your LLM server. Leave as ollama unless OpenWebUI auth is enabled.
+OPENWEBUI_API_KEY="ollama"
+
+# =============================================================================
+# Speech-to-Text
+# =============================================================================
+# Faster-Whisper model size: tiny.en, small.en, medium.en, large-v3
+LOCAL_STT_MODEL="small.en"
+
+# Digital gain applied to microphone input (e.g., 2.0 to double volume)
+MIC_GAIN=1.0
+
+# No-wake-word VAD tuning. Each chunk is about 32 ms at 16 kHz.
+VAD_THRESHOLD=0.50
+VAD_FALLBACK_THRESHOLD=0.012
+VAD_SPEECH_ONSET_CHUNKS=4
+VAD_SILENCE_END_CHUNKS=55
+VAD_MIN_SPEECH_CHUNKS=10
+WEBRTC_VAD_AGGRESSIVENESS=2
+SILERO_VAD_ONNX_PATH=
+
+
+# =============================================================================
+# Vision
+# =============================================================================
+# Local vision model (only used with --smolvlm CLI flag)
+LOCAL_VISION_MODEL=HuggingFaceTB/SmolVLM2-2.2B-Instruct
+
+# Cache directory for downloaded models
+HF_HOME=./cache
+
+# Hugging Face token (optional, falls back to `hf auth login`)
+HF_TOKEN=
+
+
diff --git a/src/Reachy_OpenWebUI/__init__.py b/src/Reachy_OpenWebUI/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..31819a0f2cf763696b1ad2bef53e1cb706ca40bc
--- /dev/null
+++ b/src/Reachy_OpenWebUI/__init__.py
@@ -0,0 +1 @@
+"""Nothing (for ruff)."""
diff --git a/src/Reachy_OpenWebUI/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..147c27d8b1408d683db5b55b5804760a6b9fbcc0
Binary files /dev/null and b/src/Reachy_OpenWebUI/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/__pycache__/app_profiles.cpython-311.pyc b/src/Reachy_OpenWebUI/__pycache__/app_profiles.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a97d8c58cee9eaff5c61eca86bcba15d34a69e2f
Binary files /dev/null and b/src/Reachy_OpenWebUI/__pycache__/app_profiles.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/__pycache__/camera_frame_encoding.cpython-311.pyc b/src/Reachy_OpenWebUI/__pycache__/camera_frame_encoding.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c1ed2f6828932212777b9a7f584772326f9bdada
Binary files /dev/null and b/src/Reachy_OpenWebUI/__pycache__/camera_frame_encoding.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/__pycache__/camera_worker.cpython-311.pyc b/src/Reachy_OpenWebUI/__pycache__/camera_worker.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8b9d70e54b0a72ee8acb5077e77005f2bc2f4a7c
Binary files /dev/null and b/src/Reachy_OpenWebUI/__pycache__/camera_worker.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/__pycache__/chat_history.cpython-311.pyc b/src/Reachy_OpenWebUI/__pycache__/chat_history.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8eec060b2ea35ac796532dc2804899480198e33d
Binary files /dev/null and b/src/Reachy_OpenWebUI/__pycache__/chat_history.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/__pycache__/config.cpython-311.pyc b/src/Reachy_OpenWebUI/__pycache__/config.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0334f2105267e7ba35449c8a11337bc8682f08a4
Binary files /dev/null and b/src/Reachy_OpenWebUI/__pycache__/config.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/__pycache__/console.cpython-311.pyc b/src/Reachy_OpenWebUI/__pycache__/console.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..680e56ad994cec1172130ab98ba426f62a1c381c
--- /dev/null
+++ b/src/Reachy_OpenWebUI/__pycache__/console.cpython-311.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:385ef54b921814f767d47368f47749120f1eb632ecbe9929f196b06547d1a1a3
+size 149921
diff --git a/src/Reachy_OpenWebUI/__pycache__/dance_emotion_moves.cpython-311.pyc b/src/Reachy_OpenWebUI/__pycache__/dance_emotion_moves.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c5bc28d080bf357d3c8dfa18807fdd8a0bf3555f
Binary files /dev/null and b/src/Reachy_OpenWebUI/__pycache__/dance_emotion_moves.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/__pycache__/main.cpython-311.pyc b/src/Reachy_OpenWebUI/__pycache__/main.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3c8ed0f64f76cf5f5782f56da1e6d4ff02502870
Binary files /dev/null and b/src/Reachy_OpenWebUI/__pycache__/main.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/__pycache__/motion_patterns.cpython-311.pyc b/src/Reachy_OpenWebUI/__pycache__/motion_patterns.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..76392349002ccada8d7dbb637023803d190be339
Binary files /dev/null and b/src/Reachy_OpenWebUI/__pycache__/motion_patterns.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/__pycache__/moves.cpython-311.pyc b/src/Reachy_OpenWebUI/__pycache__/moves.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..295063f4dd553a3e3acdbada5b90c6b29fe3de84
Binary files /dev/null and b/src/Reachy_OpenWebUI/__pycache__/moves.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/__pycache__/settings_keys.cpython-311.pyc b/src/Reachy_OpenWebUI/__pycache__/settings_keys.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..44385bd4a9df3c248c3db336cf6600755f415c8c
Binary files /dev/null and b/src/Reachy_OpenWebUI/__pycache__/settings_keys.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/__pycache__/utils.cpython-311.pyc b/src/Reachy_OpenWebUI/__pycache__/utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..48f9f51d7c5290a5b653889c32a134a18f60a511
Binary files /dev/null and b/src/Reachy_OpenWebUI/__pycache__/utils.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/app_profiles.py b/src/Reachy_OpenWebUI/app_profiles.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5cc32f72156732692b7e59916b5741d5799e29b
--- /dev/null
+++ b/src/Reachy_OpenWebUI/app_profiles.py
@@ -0,0 +1,62 @@
+"""Profile source registry for app-owned tool and profile files.
+
+Shared loaders should ask this module where a profile lives instead of hardcoding
+mini-app package names in core runtime code.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from pathlib import Path
+
+
+DEFAULT_PROFILE = "default"
+COOKAIWARE_PROFILE = "cookaiware"
+
+
+@dataclass(frozen=True)
+class ToolProfileSource:
+ """Locations used to load a profile's tool list and tool modules."""
+
+ profile: str
+ profile_path: Path
+ profile_package: str
+ shared_tool_packages: tuple[str, ...]
+
+ @property
+ def tools_txt_path(self) -> Path:
+ return self.profile_path / "tools.txt"
+
+
+_PACKAGE_ROOT = Path(__file__).parent
+
+_PROFILE_SOURCES: dict[str, ToolProfileSource] = {
+ DEFAULT_PROFILE: ToolProfileSource(
+ profile=DEFAULT_PROFILE,
+ profile_path=_PACKAGE_ROOT / "profiles" / DEFAULT_PROFILE,
+ profile_package="Reachy_OpenWebUI.profiles.default",
+ shared_tool_packages=("Reachy_OpenWebUI.tools",),
+ ),
+ COOKAIWARE_PROFILE: ToolProfileSource(
+ profile=COOKAIWARE_PROFILE,
+ profile_path=_PACKAGE_ROOT / "sub_apps" / "cookAIware" / "profiles" / COOKAIWARE_PROFILE,
+ profile_package="Reachy_OpenWebUI.sub_apps.cookAIware.profiles.cookaiware",
+ shared_tool_packages=("Reachy_OpenWebUI.sub_apps.cookAIware.tools",),
+ ),
+}
+
+
+def resolve_tool_profile_source(profile: str | None) -> ToolProfileSource:
+ """Return the registered tool/profile source for the selected mode."""
+ selected = (profile or DEFAULT_PROFILE).strip() or DEFAULT_PROFILE
+ return _PROFILE_SOURCES.get(selected) or ToolProfileSource(
+ profile=selected,
+ profile_path=_PACKAGE_ROOT / "profiles" / selected,
+ profile_package=f"Reachy_OpenWebUI.profiles.{selected}",
+ shared_tool_packages=("Reachy_OpenWebUI.tools",),
+ )
+
+
+def registered_tool_profiles() -> tuple[str, ...]:
+ """Return known profile ids for settings/status UIs."""
+ return tuple(_PROFILE_SOURCES)
diff --git a/src/Reachy_OpenWebUI/audio/__init__.py b/src/Reachy_OpenWebUI/audio/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..31819a0f2cf763696b1ad2bef53e1cb706ca40bc
--- /dev/null
+++ b/src/Reachy_OpenWebUI/audio/__init__.py
@@ -0,0 +1 @@
+"""Nothing (for ruff)."""
diff --git a/src/Reachy_OpenWebUI/audio/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/audio/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e1d460cb1b586c0b64b02108cefcfe8f03b780eb
Binary files /dev/null and b/src/Reachy_OpenWebUI/audio/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/audio/__pycache__/attitude_wobbler.cpython-311.pyc b/src/Reachy_OpenWebUI/audio/__pycache__/attitude_wobbler.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..21bdc6fbb4dfeee3ba6595be1972303058ddc7fa
Binary files /dev/null and b/src/Reachy_OpenWebUI/audio/__pycache__/attitude_wobbler.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/audio/__pycache__/head_wobbler.cpython-311.pyc b/src/Reachy_OpenWebUI/audio/__pycache__/head_wobbler.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..adb4096412797f2cb03868bfab39b9e3c8da7f1e
Binary files /dev/null and b/src/Reachy_OpenWebUI/audio/__pycache__/head_wobbler.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/audio/__pycache__/speech_tapper.cpython-311.pyc b/src/Reachy_OpenWebUI/audio/__pycache__/speech_tapper.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..80d916b741241ce0218dc26edb24d3a5bea36c1d
Binary files /dev/null and b/src/Reachy_OpenWebUI/audio/__pycache__/speech_tapper.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/audio/__pycache__/startup_config.cpython-311.pyc b/src/Reachy_OpenWebUI/audio/__pycache__/startup_config.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6fd6f3d8635e63cc968ef4ab6df3d85bb92ea437
Binary files /dev/null and b/src/Reachy_OpenWebUI/audio/__pycache__/startup_config.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/audio/attitude_wobbler.py b/src/Reachy_OpenWebUI/audio/attitude_wobbler.py
new file mode 100644
index 0000000000000000000000000000000000000000..f94fc64a7e5e92d22259921ca3be91dab9b980a3
--- /dev/null
+++ b/src/Reachy_OpenWebUI/audio/attitude_wobbler.py
@@ -0,0 +1,243 @@
+"""Per-attitude speech wobble — extends HeadWobbler with axis-specific scaling and offsets.
+
+Originals (speech_tapper.py, head_wobbler.py) are untouched.
+"""
+
+from __future__ import annotations
+
+import math
+import time
+import queue
+import logging
+import threading
+from typing import Tuple
+from collections.abc import Callable
+
+import numpy as np
+from numpy.typing import NDArray
+
+from Reachy_OpenWebUI.audio.speech_tapper import SwayRollRT, HOP_MS
+from Reachy_OpenWebUI.sub_apps.attitudes import AttitudeProfile, resolve_attitude
+
+
+SAMPLE_RATE = 24000
+MOVEMENT_LATENCY_S = 0.2
+logger = logging.getLogger(__name__)
+
+
+class AttitudeSwayRT(SwayRollRT):
+ """SwayRollRT that also exposes the speech envelope in each hop dict."""
+
+ def feed(self, pcm, sr=None):
+ results = super().feed(pcm, sr)
+ for r in results:
+ r["env"] = self.sway_env
+ return results
+
+
+class AttitudeHeadWobbler:
+ """HeadWobbler with per-attitude axis scales and speech-time pose offsets.
+
+ Drop-in replacement: same public API as HeadWobbler.
+ """
+
+ def __init__(
+ self,
+ set_speech_offsets: Callable[[Tuple[float, float, float, float, float, float]], None],
+ attitude: str = "calm",
+ ) -> None:
+ self._apply_offsets = set_speech_offsets
+ self._base_ts: float | None = None
+ self._hops_done: int = 0
+
+ self.audio_queue: "queue.Queue[Tuple[int, int, NDArray[np.int16]]]" = queue.Queue()
+ self.sway = AttitudeSwayRT()
+
+ self._state_lock = threading.Lock()
+ self._sway_lock = threading.Lock()
+ self._generation = 0
+
+ profile = resolve_attitude(attitude)
+ self._scale = profile.speaking_motion_scale
+ self._pitch_scale = profile.speaking_pitch_scale
+ self._yaw_scale = profile.speaking_yaw_scale
+ self._roll_scale = profile.speaking_roll_scale
+ self._x_scale = profile.speaking_x_scale
+ self._y_scale = profile.speaking_y_scale
+ self._z_scale = profile.speaking_z_scale
+ self._pitch_offset = math.radians(profile.speaking_pitch_offset_deg)
+ self._z_offset = profile.speaking_z_offset_m
+
+ self._stop_event = threading.Event()
+ self._thread: threading.Thread | None = None
+
+ def feed(self, delta_b64: str) -> None:
+ import base64
+ buf = np.frombuffer(base64.b64decode(delta_b64), dtype=np.int16)
+ self.feed_pcm(buf, SAMPLE_RATE)
+
+ def feed_pcm(self, pcm: NDArray[np.int16], sample_rate: int = SAMPLE_RATE) -> None:
+ buf = np.asarray(pcm, dtype=np.int16).reshape(1, -1)
+ if buf.size == 0:
+ return
+ with self._state_lock:
+ generation = self._generation
+ self.audio_queue.put((generation, int(sample_rate or SAMPLE_RATE), buf))
+
+ def start(self) -> None:
+ self._stop_event.clear()
+ self._thread = threading.Thread(target=self.working_loop, daemon=True)
+ self._thread.start()
+ logger.debug("Attitude head wobbler started")
+
+ def set_attitude(self, attitude: str) -> None:
+ profile = resolve_attitude(attitude)
+ with self._state_lock:
+ self._scale = profile.speaking_motion_scale
+ self._pitch_scale = profile.speaking_pitch_scale
+ self._yaw_scale = profile.speaking_yaw_scale
+ self._roll_scale = profile.speaking_roll_scale
+ self._x_scale = profile.speaking_x_scale
+ self._y_scale = profile.speaking_y_scale
+ self._z_scale = profile.speaking_z_scale
+ self._pitch_offset = math.radians(profile.speaking_pitch_offset_deg)
+ self._z_offset = profile.speaking_z_offset_m
+ logger.info(
+ "Speech attitude set to %s (scale=%.2f, pitch_off=%.1f°, z_off=%.3fm)",
+ profile.name, profile.speaking_motion_scale,
+ profile.speaking_pitch_offset_deg, profile.speaking_z_offset_m,
+ )
+
+ def stop(self) -> None:
+ self._stop_event.set()
+ if self._thread is not None:
+ self._thread.join()
+ logger.debug("Attitude head wobbler stopped")
+
+ def working_loop(self) -> None:
+ hop_dt = HOP_MS / 1000.0
+
+ logger.debug("Attitude head wobbler thread started")
+ while not self._stop_event.is_set():
+ queue_ref = self.audio_queue
+ try:
+ chunk_generation, sr, chunk = queue_ref.get_nowait()
+ except queue.Empty:
+ time.sleep(MOVEMENT_LATENCY_S)
+ continue
+
+ try:
+ with self._state_lock:
+ current_generation = self._generation
+ if chunk_generation != current_generation:
+ continue
+
+ if self._base_ts is None:
+ with self._state_lock:
+ if self._base_ts is None:
+ self._base_ts = time.monotonic()
+
+ pcm = np.asarray(chunk).squeeze(0)
+ with self._sway_lock:
+ results = self.sway.feed(pcm, sr)
+
+ i = 0
+ while i < len(results):
+ with self._state_lock:
+ if self._generation != current_generation:
+ break
+ base_ts = self._base_ts
+ hops_done = self._hops_done
+
+ if base_ts is None:
+ base_ts = time.monotonic()
+ with self._state_lock:
+ if self._base_ts is None:
+ self._base_ts = base_ts
+ hops_done = self._hops_done
+
+ target = base_ts + MOVEMENT_LATENCY_S + hops_done * hop_dt
+ now = time.monotonic()
+
+ if now - target >= hop_dt:
+ lag_hops = int((now - target) / hop_dt)
+ drop = min(lag_hops, len(results) - i - 1)
+ if drop > 0:
+ with self._state_lock:
+ self._hops_done += drop
+ hops_done = self._hops_done
+ i += drop
+ continue
+
+ if target > now:
+ time.sleep(target - now)
+ with self._state_lock:
+ if self._generation != current_generation:
+ break
+
+ r = results[i]
+ with self._state_lock:
+ if self._generation != current_generation:
+ break
+ scale = self._scale
+ ps = self._pitch_scale
+ ys = self._yaw_scale
+ rs = self._roll_scale
+ xs = self._x_scale
+ y_s = self._y_scale
+ zs = self._z_scale
+ p_off = self._pitch_offset
+ z_off = self._z_offset
+
+ env = r.get("env", 1.0)
+
+ offsets = (
+ (r["x_mm"] / 1000.0) * scale * xs,
+ (r["y_mm"] / 1000.0) * scale * y_s,
+ (r["z_mm"] / 1000.0) * scale * zs + env * z_off,
+ r["roll_rad"] * scale * rs,
+ r["pitch_rad"] * scale * ps + env * p_off,
+ r["yaw_rad"] * scale * ys,
+ )
+
+ with self._state_lock:
+ if self._generation != current_generation:
+ break
+
+ self._apply_offsets(offsets)
+
+ with self._state_lock:
+ self._hops_done += 1
+ i += 1
+ finally:
+ queue_ref.task_done()
+ logger.debug("Attitude head wobbler thread exited")
+
+ def drain_audio_queue(self) -> None:
+ self._drain_audio_queue()
+
+ def _drain_audio_queue(self) -> bool:
+ drained_any = False
+ try:
+ while True:
+ self.audio_queue.get_nowait()
+ self.audio_queue.task_done()
+ drained_any = True
+ except queue.Empty:
+ return drained_any
+
+ def reset(self) -> None:
+ with self._state_lock:
+ self._generation += 1
+ self._base_ts = None
+ self._hops_done = 0
+
+ drained_any = self._drain_audio_queue()
+
+ with self._sway_lock:
+ self.sway.reset()
+
+ self._apply_offsets((0.0, 0.0, 0.0, 0.0, 0.0, 0.0))
+
+ if drained_any:
+ logger.debug("Attitude head wobbler queue drained during reset")
diff --git a/src/Reachy_OpenWebUI/audio/head_wobbler.py b/src/Reachy_OpenWebUI/audio/head_wobbler.py
new file mode 100644
index 0000000000000000000000000000000000000000..625f196a1270a82d81632370a20761be76607fe0
--- /dev/null
+++ b/src/Reachy_OpenWebUI/audio/head_wobbler.py
@@ -0,0 +1,205 @@
+"""Moves head given audio samples."""
+
+import time
+import queue
+import base64
+import logging
+import threading
+from typing import Tuple
+from collections.abc import Callable
+
+import numpy as np
+from numpy.typing import NDArray
+
+from Reachy_OpenWebUI.audio.speech_tapper import HOP_MS, SwayRollRT
+from Reachy_OpenWebUI.sub_apps.attitudes import resolve_attitude
+
+
+SAMPLE_RATE = 24000
+MOVEMENT_LATENCY_S = 0.2 # seconds between audio and robot movement
+logger = logging.getLogger(__name__)
+
+
+class HeadWobbler:
+ """Converts audio deltas (base64) into head movement offsets."""
+
+ def __init__(
+ self,
+ set_speech_offsets: Callable[[Tuple[float, float, float, float, float, float]], None],
+ attitude: str = "calm",
+ ) -> None:
+ """Initialize the head wobbler."""
+ self._apply_offsets = set_speech_offsets
+ self._base_ts: float | None = None
+ self._hops_done: int = 0
+
+ self.audio_queue: "queue.Queue[Tuple[int, int, NDArray[np.int16]]]" = queue.Queue()
+ self.sway = SwayRollRT()
+
+ # Synchronization primitives
+ self._state_lock = threading.Lock()
+ self._sway_lock = threading.Lock()
+ self._generation = 0
+ self._speech_motion_scale = resolve_attitude(attitude).speaking_motion_scale
+
+ self._stop_event = threading.Event()
+ self._thread: threading.Thread | None = None
+
+ def feed(self, delta_b64: str) -> None:
+ """Thread-safe: push audio into the consumer queue."""
+ buf = np.frombuffer(base64.b64decode(delta_b64), dtype=np.int16)
+ self.feed_pcm(buf, SAMPLE_RATE)
+
+ def feed_pcm(self, pcm: NDArray[np.int16], sample_rate: int = SAMPLE_RATE) -> None:
+ """Thread-safe: push raw mono PCM into the consumer queue."""
+ buf = np.asarray(pcm, dtype=np.int16).reshape(1, -1)
+ if buf.size == 0:
+ return
+ with self._state_lock:
+ generation = self._generation
+ self.audio_queue.put((generation, int(sample_rate or SAMPLE_RATE), buf))
+
+ def start(self) -> None:
+ """Start the head wobbler loop in a thread."""
+ self._stop_event.clear()
+ self._thread = threading.Thread(target=self.working_loop, daemon=True)
+ self._thread.start()
+ logger.debug("Head wobbler started")
+
+ def set_attitude(self, attitude: str) -> None:
+ """Apply the selected attitude's speech movement scale."""
+ profile = resolve_attitude(attitude)
+ with self._state_lock:
+ self._speech_motion_scale = profile.speaking_motion_scale
+ logger.info("Speech motion attitude set to %s (scale %.2f)", profile.name, profile.speaking_motion_scale)
+
+ def stop(self) -> None:
+ """Stop the head wobbler loop."""
+ self._stop_event.set()
+ if self._thread is not None:
+ self._thread.join()
+ logger.debug("Head wobbler stopped")
+
+ def working_loop(self) -> None:
+ """Convert audio deltas into head movement offsets."""
+ hop_dt = HOP_MS / 1000.0
+
+ logger.debug("Head wobbler thread started")
+ while not self._stop_event.is_set():
+ queue_ref = self.audio_queue
+ try:
+ chunk_generation, sr, chunk = queue_ref.get_nowait() # (gen, sr, data)
+ except queue.Empty:
+ # avoid while to never exit
+ time.sleep(MOVEMENT_LATENCY_S)
+ continue
+
+ try:
+ with self._state_lock:
+ current_generation = self._generation
+ if chunk_generation != current_generation:
+ continue
+
+ if self._base_ts is None:
+ with self._state_lock:
+ if self._base_ts is None:
+ self._base_ts = time.monotonic()
+
+ pcm = np.asarray(chunk).squeeze(0)
+ with self._sway_lock:
+ results = self.sway.feed(pcm, sr)
+
+ i = 0
+ while i < len(results):
+ with self._state_lock:
+ if self._generation != current_generation:
+ break
+ base_ts = self._base_ts
+ hops_done = self._hops_done
+
+ if base_ts is None:
+ base_ts = time.monotonic()
+ with self._state_lock:
+ if self._base_ts is None:
+ self._base_ts = base_ts
+ hops_done = self._hops_done
+
+ target = base_ts + MOVEMENT_LATENCY_S + hops_done * hop_dt
+ now = time.monotonic()
+
+ if now - target >= hop_dt:
+ lag_hops = int((now - target) / hop_dt)
+ drop = min(lag_hops, len(results) - i - 1)
+ if drop > 0:
+ with self._state_lock:
+ self._hops_done += drop
+ hops_done = self._hops_done
+ i += drop
+ continue
+
+ if target > now:
+ time.sleep(target - now)
+ with self._state_lock:
+ if self._generation != current_generation:
+ break
+
+ r = results[i]
+ with self._state_lock:
+ if self._generation != current_generation:
+ break
+ scale = self._speech_motion_scale
+
+ offsets = (
+ (r["x_mm"] / 1000.0) * scale,
+ (r["y_mm"] / 1000.0) * scale,
+ (r["z_mm"] / 1000.0) * scale,
+ r["roll_rad"] * scale,
+ r["pitch_rad"] * scale,
+ r["yaw_rad"] * scale,
+ )
+
+ with self._state_lock:
+ if self._generation != current_generation:
+ break
+
+ self._apply_offsets(offsets)
+
+ with self._state_lock:
+ self._hops_done += 1
+ i += 1
+ finally:
+ queue_ref.task_done()
+ logger.debug("Head wobbler thread exited")
+
+ def drain_audio_queue(self) -> None:
+ """Empty the audio queue."""
+ self._drain_audio_queue()
+
+ def _drain_audio_queue(self) -> bool:
+ """Empty queued audio chunks and return whether anything was drained."""
+ drained_any = False
+ try:
+ while True:
+ self.audio_queue.get_nowait()
+ self.audio_queue.task_done()
+ drained_any = True
+ except queue.Empty:
+ return drained_any
+
+ def reset(self) -> None:
+ """Reset the internal state."""
+ with self._state_lock:
+ self._generation += 1
+ self._base_ts = None
+ self._hops_done = 0
+
+ # Drain any queued audio chunks from previous generations
+ drained_any = self._drain_audio_queue()
+
+ with self._sway_lock:
+ self.sway.reset()
+
+ self._apply_offsets((0.0, 0.0, 0.0, 0.0, 0.0, 0.0))
+
+ if drained_any:
+ logger.debug("Head wobbler queue drained during reset")
diff --git a/src/Reachy_OpenWebUI/audio/speech_tapper.py b/src/Reachy_OpenWebUI/audio/speech_tapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..c61fd6fac277649431d7d1f0737c4ec5e246be68
--- /dev/null
+++ b/src/Reachy_OpenWebUI/audio/speech_tapper.py
@@ -0,0 +1,274 @@
+from __future__ import annotations
+import math
+from typing import Any, Dict, List
+from itertools import islice
+from collections import deque
+
+import numpy as np
+from numpy.typing import NDArray
+
+
+# Tunables
+SR = 16_000
+FRAME_MS = 20
+HOP_MS = 50
+
+SWAY_MASTER = 1.5
+SENS_DB_OFFSET = +4.0
+VAD_DB_ON = -35.0
+VAD_DB_OFF = -45.0
+VAD_ATTACK_MS = 40
+VAD_RELEASE_MS = 250
+ENV_FOLLOW_GAIN = 0.65
+
+# Speech wobble oscillator amplitudes and frequencies.
+# NOTE: The head is world-stabilised (gaze-locked like a gimbal). Yaw
+# directly shifts where the robot looks — even small values make it glance
+# away from the user. Pitch (nodding) and roll (tilting) are far less
+# disruptive to gaze. Keep yaw the SMALLEST amplitude, not the largest.
+# Per-attitude overrides live in AttitudeHeadWobbler (attitude_wobbler.py).
+SWAY_F_PITCH = 2.2
+SWAY_A_PITCH_DEG = 4.5
+SWAY_F_YAW = 0.6
+SWAY_A_YAW_DEG = 7.5 # WARNING: large — shifts gaze noticeably
+SWAY_F_ROLL = 1.3
+SWAY_A_ROLL_DEG = 2.25
+SWAY_F_X = 0.35
+SWAY_A_X_MM = 4.5
+SWAY_F_Y = 0.45
+SWAY_A_Y_MM = 3.75
+SWAY_F_Z = 0.25
+SWAY_A_Z_MM = 2.25
+
+SWAY_DB_LOW = -46.0
+SWAY_DB_HIGH = -18.0
+LOUDNESS_GAMMA = 0.9
+SWAY_ATTACK_MS = 50
+SWAY_RELEASE_MS = 250
+
+# Derived
+FRAME = int(SR * FRAME_MS / 1000)
+HOP = int(SR * HOP_MS / 1000)
+ATTACK_FR = max(1, int(VAD_ATTACK_MS / HOP_MS))
+RELEASE_FR = max(1, int(VAD_RELEASE_MS / HOP_MS))
+SWAY_ATTACK_FR = max(1, int(SWAY_ATTACK_MS / HOP_MS))
+SWAY_RELEASE_FR = max(1, int(SWAY_RELEASE_MS / HOP_MS))
+
+
+def _rms_dbfs(x: NDArray[np.float32]) -> float:
+ """Root-mean-square in dBFS for float32 mono array in [-1,1]."""
+ # numerically stable rms (avoid overflow)
+ x = x.astype(np.float32, copy=False)
+ rms = np.sqrt(np.mean(x * x, dtype=np.float32) + 1e-12, dtype=np.float32)
+ return float(20.0 * math.log10(float(rms) + 1e-12))
+
+
+def _loudness_gain(db: float, offset: float = SENS_DB_OFFSET) -> float:
+ """Normalize dB into [0,1] with gamma; clipped to [0,1]."""
+ t = (db + offset - SWAY_DB_LOW) / (SWAY_DB_HIGH - SWAY_DB_LOW)
+ if t < 0.0:
+ t = 0.0
+ elif t > 1.0:
+ t = 1.0
+ return t**LOUDNESS_GAMMA if LOUDNESS_GAMMA != 1.0 else t
+
+
+def _to_float32_mono(x: NDArray[Any]) -> NDArray[np.float32]:
+ """Convert arbitrary PCM array to float32 mono in [-1,1].
+
+ Accepts shapes: (N,), (1,N), (N,1), (C,N), (N,C).
+ """
+ a = np.asarray(x)
+ if a.ndim == 0:
+ return np.zeros(0, dtype=np.float32)
+
+ # If 2D, decide which axis is channels (prefer small first dim)
+ if a.ndim == 2:
+ # e.g., (channels, samples) if channels is small (<=8)
+ if a.shape[0] <= 8 and a.shape[0] <= a.shape[1]:
+ a = np.mean(a, axis=0)
+ else:
+ a = np.mean(a, axis=1)
+ elif a.ndim > 2:
+ a = np.mean(a.reshape(a.shape[0], -1), axis=0)
+
+ # Now 1D, cast/scale
+ if np.issubdtype(a.dtype, np.floating):
+ return a.astype(np.float32, copy=False)
+ # integer PCM
+ info = np.iinfo(a.dtype)
+ scale = float(max(-info.min, info.max))
+ return a.astype(np.float32) / (scale if scale != 0.0 else 1.0)
+
+
+def _resample_linear(x: NDArray[np.float32], sr_in: int, sr_out: int) -> NDArray[np.float32]:
+ """Lightweight linear resampler for short buffers."""
+ if sr_in == sr_out or x.size == 0:
+ return x
+ # guard tiny sizes
+ n_out = int(round(x.size * sr_out / sr_in))
+ if n_out <= 1:
+ return np.zeros(0, dtype=np.float32)
+ t_in = np.linspace(0.0, 1.0, num=x.size, dtype=np.float32, endpoint=True)
+ t_out = np.linspace(0.0, 1.0, num=n_out, dtype=np.float32, endpoint=True)
+ return np.interp(t_out, t_in, x).astype(np.float32, copy=False)
+
+
+class SwayRollRT:
+ """Feed audio chunks → per-hop sway outputs.
+
+ Usage:
+ rt = SwayRollRT()
+ rt.feed(pcm_int16_or_float, sr) -> List[dict]
+ """
+
+ def __init__(self, rng_seed: int = 7):
+ """Initialize state."""
+ self._seed = int(rng_seed)
+ self.samples: deque[float] = deque(maxlen=10 * SR) # sliding window for VAD/env
+ self.carry: NDArray[np.float32] = np.zeros(0, dtype=np.float32)
+
+ self.vad_on = False
+ self.vad_above = 0
+ self.vad_below = 0
+
+ self.sway_env = 0.0
+ self.sway_up = 0
+ self.sway_down = 0
+
+ rng = np.random.default_rng(self._seed)
+ self.phase_pitch = float(rng.random() * 2 * math.pi)
+ self.phase_yaw = float(rng.random() * 2 * math.pi)
+ self.phase_roll = float(rng.random() * 2 * math.pi)
+ self.phase_x = float(rng.random() * 2 * math.pi)
+ self.phase_y = float(rng.random() * 2 * math.pi)
+ self.phase_z = float(rng.random() * 2 * math.pi)
+ self.t = 0.0
+
+ def reset(self) -> None:
+ """Reset state (VAD/env/buffers/time) but keep initial phases/seed."""
+ self.samples.clear()
+ self.carry = np.zeros(0, dtype=np.float32)
+ self.vad_on = False
+ self.vad_above = 0
+ self.vad_below = 0
+ self.sway_env = 0.0
+ self.sway_up = 0
+ self.sway_down = 0
+ self.t = 0.0
+
+ def feed(self, pcm: NDArray[Any], sr: int | None) -> List[Dict[str, float]]:
+ """Stream in PCM chunk. Returns a list of sway dicts, one per hop (HOP_MS).
+
+ Args:
+ pcm: np.ndarray, shape (N,) or (C,N)/(N,C); int or float.
+ sr: sample rate of `pcm` (None -> assume SR).
+
+ """
+ sr_in = SR if sr is None else int(sr)
+ x = _to_float32_mono(pcm)
+ if x.size == 0:
+ return []
+ if sr_in != SR:
+ x = _resample_linear(x, sr_in, SR)
+ if x.size == 0:
+ return []
+
+ # append to carry and consume fixed HOP chunks
+ if self.carry.size:
+ self.carry = np.concatenate([self.carry, x])
+ else:
+ self.carry = x
+
+ out: List[Dict[str, float]] = []
+
+ while self.carry.size >= HOP:
+ hop = self.carry[:HOP]
+ remaining: NDArray[np.float32] = self.carry[HOP:]
+ self.carry = remaining
+
+ # keep sliding window for VAD/env computation
+ # (deque accepts any iterable; list() for small HOP is fine)
+ self.samples.extend(hop.tolist())
+ if len(self.samples) < FRAME:
+ self.t += HOP_MS / 1000.0
+ continue
+
+ frame = np.fromiter(
+ islice(self.samples, len(self.samples) - FRAME, len(self.samples)),
+ dtype=np.float32,
+ count=FRAME,
+ )
+ db = _rms_dbfs(frame)
+
+ # VAD with hysteresis + attack/release
+ if db >= VAD_DB_ON:
+ self.vad_above += 1
+ self.vad_below = 0
+ if not self.vad_on and self.vad_above >= ATTACK_FR:
+ self.vad_on = True
+ elif db <= VAD_DB_OFF:
+ self.vad_below += 1
+ self.vad_above = 0
+ if self.vad_on and self.vad_below >= RELEASE_FR:
+ self.vad_on = False
+
+ if self.vad_on:
+ self.sway_up = min(SWAY_ATTACK_FR, self.sway_up + 1)
+ self.sway_down = 0
+ else:
+ self.sway_down = min(SWAY_RELEASE_FR, self.sway_down + 1)
+ self.sway_up = 0
+
+ up = self.sway_up / SWAY_ATTACK_FR
+ down = 1.0 - (self.sway_down / SWAY_RELEASE_FR)
+ target = up if self.vad_on else down
+ self.sway_env += ENV_FOLLOW_GAIN * (target - self.sway_env)
+ # clamp
+ if self.sway_env < 0.0:
+ self.sway_env = 0.0
+ elif self.sway_env > 1.0:
+ self.sway_env = 1.0
+
+ loud = _loudness_gain(db) * SWAY_MASTER
+ env = self.sway_env
+ self.t += HOP_MS / 1000.0
+
+ # oscillators
+ pitch = (
+ math.radians(SWAY_A_PITCH_DEG)
+ * loud
+ * env
+ * math.sin(2 * math.pi * SWAY_F_PITCH * self.t + self.phase_pitch)
+ )
+ yaw = (
+ math.radians(SWAY_A_YAW_DEG)
+ * loud
+ * env
+ * math.sin(2 * math.pi * SWAY_F_YAW * self.t + self.phase_yaw)
+ )
+ roll = (
+ math.radians(SWAY_A_ROLL_DEG)
+ * loud
+ * env
+ * math.sin(2 * math.pi * SWAY_F_ROLL * self.t + self.phase_roll)
+ )
+ x_mm = SWAY_A_X_MM * loud * env * math.sin(2 * math.pi * SWAY_F_X * self.t + self.phase_x)
+ y_mm = SWAY_A_Y_MM * loud * env * math.sin(2 * math.pi * SWAY_F_Y * self.t + self.phase_y)
+ z_mm = SWAY_A_Z_MM * loud * env * math.sin(2 * math.pi * SWAY_F_Z * self.t + self.phase_z)
+
+ out.append(
+ {
+ "pitch_rad": pitch,
+ "yaw_rad": yaw,
+ "roll_rad": roll,
+ "pitch_deg": math.degrees(pitch),
+ "yaw_deg": math.degrees(yaw),
+ "roll_deg": math.degrees(roll),
+ "x_mm": x_mm,
+ "y_mm": y_mm,
+ "z_mm": z_mm,
+ },
+ )
+
+ return out
diff --git a/src/Reachy_OpenWebUI/audio/startup_config.py b/src/Reachy_OpenWebUI/audio/startup_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a7149c7db179ba4a331522fd60c22556f8daa84
--- /dev/null
+++ b/src/Reachy_OpenWebUI/audio/startup_config.py
@@ -0,0 +1,68 @@
+"""Startup configuration for the Reachy Mini XVF3800 audio processor.
+
+Ported from the official reachy_mini_conversation_app. Applied at every
+pipeline start so the mic chain recovers from drifted/stuck AGC state.
+"""
+
+from __future__ import annotations
+import logging
+from collections.abc import Sequence
+
+
+AudioControlValue = float | int
+AudioStartupParameter = tuple[str, tuple[AudioControlValue, ...]]
+WRITE_SETTLE_SECONDS = 0.1
+
+AUDIO_STARTUP_CONFIG: tuple[AudioStartupParameter, ...] = (
+ ("PP_AGCMAXGAIN", (10.0,)),
+ ("PP_MIN_NS", (0.8,)),
+ ("PP_MIN_NN", (0.8,)),
+ ("PP_GAMMA_E", (0.5,)),
+ ("PP_GAMMA_ETAIL", (0.5,)),
+ ("PP_NLATTENONOFF", (0,)),
+ ("PP_MGSCALE", (4.0, 1.0, 1.0)),
+)
+
+
+def apply_audio_startup_config(
+ robot: object,
+ *,
+ logger: logging.Logger | None = None,
+ verify: bool = True,
+ write_settle_seconds: float = WRITE_SETTLE_SECONDS,
+) -> bool:
+ """Apply the tuned XVF3800 audio configuration for the conversation app."""
+ log = logger or logging.getLogger(__name__)
+ audio = getattr(getattr(robot, "media", None), "audio", None)
+
+ if audio is None:
+ log.warning("Skipping Reachy audio startup config: robot media audio is unavailable.")
+ return False
+
+ apply_audio_config = getattr(audio, "apply_audio_config", None)
+ if not callable(apply_audio_config):
+ log.warning("Skipping Reachy audio startup config: SDK audio config API is unavailable.")
+ return False
+
+ try:
+ applied = bool(
+ apply_audio_config(
+ AUDIO_STARTUP_CONFIG,
+ verify=verify,
+ write_settle_seconds=write_settle_seconds,
+ )
+ )
+ except Exception as exc:
+ log.warning("Skipping Reachy audio startup config: SDK audio config failed: %s", exc)
+ return False
+
+ if applied:
+ log.info("Applied Reachy audio startup config: %s", _format_config(AUDIO_STARTUP_CONFIG))
+ else:
+ log.warning("Reachy audio startup config was not applied.")
+
+ return applied
+
+
+def _format_config(config: Sequence[AudioStartupParameter]) -> str:
+ return ", ".join(f"{name}={' '.join(str(value) for value in values)}" for name, values in config)
diff --git a/src/Reachy_OpenWebUI/camera_frame_encoding.py b/src/Reachy_OpenWebUI/camera_frame_encoding.py
new file mode 100644
index 0000000000000000000000000000000000000000..510b82b64b2827fa2cc7fbf64e486e9a2af331de
--- /dev/null
+++ b/src/Reachy_OpenWebUI/camera_frame_encoding.py
@@ -0,0 +1,27 @@
+"""Helpers for encoding camera frames."""
+
+from fractions import Fraction
+
+import av
+import numpy as np
+from numpy.typing import NDArray
+
+
+def encode_bgr_frame_as_jpeg(frame: NDArray[np.uint8]) -> bytes:
+ """Encode a BGR camera frame as JPEG bytes."""
+ rgb_frame = np.ascontiguousarray(frame[..., ::-1])
+ video_frame = av.VideoFrame.from_ndarray(rgb_frame, format="rgb24")
+
+ codec = av.CodecContext.create("mjpeg", "w")
+ codec.width = rgb_frame.shape[1] # type: ignore[attr-defined]
+ codec.height = rgb_frame.shape[0] # type: ignore[attr-defined]
+ codec.pix_fmt = "yuvj444p" # type: ignore[attr-defined]
+ codec.time_base = Fraction(1, 1)
+ codec.options = {"qscale": "3"}
+
+ packets = codec.encode(video_frame) # type: ignore[attr-defined]
+ packets += codec.encode(None) # type: ignore[attr-defined]
+ if not packets:
+ raise RuntimeError("Failed to encode frame as JPEG")
+
+ return b"".join(bytes(packet) for packet in packets)
diff --git a/src/Reachy_OpenWebUI/camera_worker.py b/src/Reachy_OpenWebUI/camera_worker.py
new file mode 100644
index 0000000000000000000000000000000000000000..d5eb2c7223898e209f29cedd33f40a913b784951
--- /dev/null
+++ b/src/Reachy_OpenWebUI/camera_worker.py
@@ -0,0 +1,78 @@
+"""Camera worker thread with frame buffering.
+
+Provides:
+- 30Hz+ camera polling with thread-safe frame buffering
+- Latest frame always available for tools
+"""
+
+import time
+import logging
+import threading
+
+import numpy as np
+from numpy.typing import NDArray
+
+from reachy_mini import ReachyMini
+
+
+logger = logging.getLogger(__name__)
+
+
+class CameraWorker:
+ """Thread-safe camera worker with frame buffering."""
+
+ def __init__(self, reachy_mini: ReachyMini) -> None:
+ """Initialize."""
+ self.reachy_mini = reachy_mini
+
+ # Thread-safe frame storage
+ self.latest_frame: NDArray[np.uint8] | None = None
+ self.frame_lock = threading.Lock()
+ self._stop_event = threading.Event()
+ self._thread: threading.Thread | None = None
+
+ def get_latest_frame(self) -> NDArray[np.uint8] | None:
+ """Get the latest frame (thread-safe)."""
+ with self.frame_lock:
+ if self.latest_frame is None:
+ return None
+ # Return a copy in original BGR format (OpenCV native)
+ return self.latest_frame.copy()
+
+ def start(self) -> None:
+ """Start the camera worker loop in a thread."""
+ self._stop_event.clear()
+ self._thread = threading.Thread(target=self.working_loop, daemon=True)
+ self._thread.start()
+ logger.debug("Camera worker started")
+
+ def stop(self) -> None:
+ """Stop the camera worker loop."""
+ self._stop_event.set()
+ if self._thread is not None:
+ self._thread.join()
+
+ logger.debug("Camera worker stopped")
+
+ def working_loop(self) -> None:
+ """Poll frames from the camera and store the latest one."""
+ logger.debug("Starting camera working loop")
+
+ while not self._stop_event.is_set():
+ try:
+ # Get frame from robot
+ frame = self.reachy_mini.media.get_frame()
+
+ if frame is not None:
+ # Thread-safe frame storage
+ with self.frame_lock:
+ self.latest_frame = frame
+
+ # Small sleep to prevent excessive CPU usage
+ time.sleep(0.04)
+
+ except Exception as e:
+ logger.error(f"Camera worker error: {e}")
+ time.sleep(0.1) # Longer sleep on error
+
+ logger.debug("Camera worker thread exited")
diff --git a/src/Reachy_OpenWebUI/config.py b/src/Reachy_OpenWebUI/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d5d5749db777ec597287f72dc0b5d30c9b5eed6
--- /dev/null
+++ b/src/Reachy_OpenWebUI/config.py
@@ -0,0 +1,145 @@
+import os
+import logging
+from pathlib import Path
+
+from dotenv import find_dotenv, load_dotenv
+
+from Reachy_OpenWebUI import settings_keys as keys
+
+
+logger = logging.getLogger(__name__)
+
+STABLE_ENV_PATH = Path.home() / ".config" / "settings" / ".env"
+
+
+def _truthy(value: str | None, default: bool = False) -> bool:
+ raw = (value or "").strip().lower()
+ if not raw:
+ return default
+ return raw in {"1", "true", "yes", "on"}
+
+
+if STABLE_ENV_PATH.exists():
+ load_dotenv(dotenv_path=str(STABLE_ENV_PATH), override=True)
+ logger.info("Stable OpenWebUI configuration loaded from %s", STABLE_ENV_PATH)
+
+# Locate .env file (search upward from current working directory)
+dotenv_path = find_dotenv(usecwd=True)
+
+if dotenv_path:
+ # Load .env but don't override existing environment variables (CLI takes precedence)
+ load_dotenv(dotenv_path=dotenv_path, override=False)
+ logger.info(f"Configuration loaded from {dotenv_path}")
+else:
+ logger.warning("No .env file found, using environment variables")
+
+
+class Config:
+ """Configuration class for the conversation app."""
+
+ # Optional
+ HF_HOME = os.getenv("HF_HOME", "./cache")
+ OPENWEBUI_MODEL = (
+ os.getenv(keys.OPENWEB_LOADED_LLM)
+ or os.getenv(keys.LEGACY_OPENWEB_MODEL)
+ or os.getenv(keys.LEGACY_LOCAL_LLM_MODEL)
+ or "reachy-convo"
+ )
+ OPENWEBUI_URL = (
+ os.getenv(keys.OPENWEBUI_URL)
+ or os.getenv(keys.LEGACY_LOCAL_LLM_URL)
+ or "http://localhost:3001"
+ )
+ OPENWEBUI_API_KEY = (
+ os.getenv(keys.OPENWEBUI_API_KEY)
+ or os.getenv(keys.LEGACY_LOCAL_LLM_API_KEY)
+ or ""
+ )
+ OPENWEBUI_TOKEN = (
+ os.getenv(keys.OPENWEBUI_TOKEN)
+ or os.getenv(keys.LEGACY_OPENWEBUI_TOKEN)
+ or ""
+ )
+ OPENWEBUI_USER_AGENT = (
+ os.getenv(keys.OPENWEBUI_USER_AGENT)
+ or "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36"
+ ).strip()
+ OPENWEBUI_CHAT_ID = (
+ os.getenv(keys.OPENWEBUI_CHAT_ID)
+ or ""
+ ).strip()
+ OPENWEBUI_CHAT_WINDOW_START = (
+ os.getenv(keys.OPENWEBUI_CHAT_WINDOW_START)
+ or ""
+ ).strip()
+ OPENWEBUI_CHAT_PENDING_REASON = (
+ os.getenv(keys.OPENWEBUI_CHAT_PENDING_REASON)
+ or ""
+ ).strip()
+ OPENWEBUI_CHAT_PENDING_EVENT_ID = (
+ os.getenv(keys.OPENWEBUI_CHAT_PENDING_EVENT_ID)
+ or ""
+ ).strip()
+ OPENWEBUI_USER_ID = os.getenv(keys.OPENWEBUI_USER_ID, "").strip()
+ OPENWEBUI_USER_NAME = os.getenv(keys.OPENWEBUI_USER_NAME, "Reachy").strip()
+ OPENWEBUI_USER_EMAIL = os.getenv(keys.OPENWEBUI_USER_EMAIL, "reachy@example.local").strip()
+ OPENWEBUI_USER_LANGUAGE = os.getenv(keys.OPENWEBUI_USER_LANGUAGE, "en-US").strip()
+ OPENWEBUI_USER_LOCATION = os.getenv(keys.OPENWEBUI_USER_LOCATION, "Unknown").strip()
+ OPENWEBUI_USER_TIMEZONE = os.getenv(keys.OPENWEBUI_USER_TIMEZONE, "America/New_York").strip()
+ OPENWEBUI_CONTACTS_REQUIRE_VISION = _truthy(os.getenv(keys.OPENWEBUI_CONTACTS_REQUIRE_VISION), default=True)
+ OPENWEBUI_ENABLED_TOOLS = os.getenv(keys.OPENWEBUI_ENABLED_TOOLS, "").strip()
+ REACHY_MINI_CUSTOM_PROFILE = os.getenv(keys.REACHY_MINI_CUSTOM_PROFILE, "").strip()
+ REACHY_IDLE_ATTITUDE = os.getenv(keys.REACHY_IDLE_ATTITUDE, "calm").strip() or "calm"
+ WEATHER_POSTAL_CODE = os.getenv(keys.WEATHER_POSTAL_CODE, "").strip()
+ OPENWEBUI_TTS_READ_TIMEOUT = float(os.getenv("OPENWEBUI_TTS_READ_TIMEOUT", "") or "15.0")
+ HF_TOKEN = os.getenv("HF_TOKEN") # Optional, falls back to hf auth login if not set
+
+ logger.debug(f"HF_HOME: {HF_HOME}, LLM Model: {OPENWEBUI_MODEL}")
+
+
+
+
+ # Audio Settings
+ MIC_GAIN = float(os.getenv(keys.MIC_GAIN, "") or "1.0")
+ LOCAL_DEV_VISION_MODEL = (
+ os.getenv(keys.LOCAL_DEV_VISION_MODEL)
+ or os.getenv(keys.LEGACY_LOCAL_VISION_MODEL)
+ or "HuggingFaceTB/SmolVLM2-2.2B-Instruct"
+ )
+ VAD_THRESHOLD = float(os.getenv("VAD_THRESHOLD", "") or "0.12")
+ VAD_FALLBACK_THRESHOLD = float(os.getenv("VAD_FALLBACK_THRESHOLD", "") or "0.010")
+ VAD_SPEECH_ONSET_CHUNKS = int(os.getenv("VAD_SPEECH_ONSET_CHUNKS", "") or "2")
+ VAD_SILENCE_END_CHUNKS = int(os.getenv("VAD_SILENCE_END_CHUNKS", "") or "70")
+ VAD_MIN_SPEECH_CHUNKS = int(os.getenv("VAD_MIN_SPEECH_CHUNKS", "") or "8")
+ SILERO_VAD_ONNX_PATH = os.getenv(
+ "SILERO_VAD_ONNX_PATH",
+ str(Path.home() / ".cache" / "reachy-openwebui-vad" / "silero_vad.onnx"),
+ )
+ OPENWEBUI_CONVERSATION_IDLE_RESET_SECONDS = int(
+ os.getenv("OPENWEBUI_CONVERSATION_IDLE_RESET_SECONDS", "0")
+ )
+
+
+
+config = Config()
+
+
+def active_profile(default: str = "default") -> str:
+ """Return the selected profile, falling back to the normal conversation profile."""
+ profile = (config.REACHY_MINI_CUSTOM_PROFILE or os.getenv(keys.REACHY_MINI_CUSTOM_PROFILE, "")).strip()
+ return profile or default
+
+
+def set_runtime_mode(profile: str | None = None, model: str | None = None) -> None:
+ """Set mode-specific runtime values before app-specific modules initialize."""
+ selected_profile = (profile or "").strip()
+ config.REACHY_MINI_CUSTOM_PROFILE = selected_profile
+ if selected_profile:
+ os.environ[keys.REACHY_MINI_CUSTOM_PROFILE] = selected_profile
+ else:
+ os.environ.pop(keys.REACHY_MINI_CUSTOM_PROFILE, None)
+
+ selected_model = (model or "").strip()
+ if selected_model:
+ config.OPENWEBUI_MODEL = selected_model
+ os.environ[keys.OPENWEB_LOADED_LLM] = selected_model
diff --git a/src/Reachy_OpenWebUI/console.py b/src/Reachy_OpenWebUI/console.py
new file mode 100644
index 0000000000000000000000000000000000000000..b44ce2664cce36aed9dcd66b58e5903108d85ba7
--- /dev/null
+++ b/src/Reachy_OpenWebUI/console.py
@@ -0,0 +1,2277 @@
+"""Bidirectional local audio stream with an OpenWebUI settings page.
+
+The app reads OpenWebUI settings from a stable user env file. When launched by
+Reachy Mini Apps it also exposes a compact settings UI on the app webserver.
+"""
+
+import base64
+import json
+import os
+import re
+import shutil
+import asyncio
+import logging
+import subprocess
+import threading
+import time
+import uuid
+import wave
+from typing import Any, List, Optional
+from pathlib import Path
+from urllib.parse import quote, urlencode, urlparse
+
+import numpy as np
+from fastrtc import AdditionalOutputs, audio_to_float32
+from scipy.signal import resample
+
+from reachy_mini import ReachyMini
+from Reachy_OpenWebUI.audio.startup_config import apply_audio_startup_config
+from Reachy_OpenWebUI.sub_apps.conversation_app.chat_history import append_chat_history, clear_chat_history
+from Reachy_OpenWebUI.config import config, set_runtime_mode
+from Reachy_OpenWebUI.moves import available_idle_attitudes
+from Reachy_OpenWebUI import settings_keys as keys
+
+try:
+ from fastapi import FastAPI, Response
+ from pydantic import BaseModel
+ from fastapi.responses import FileResponse, JSONResponse
+ from starlette.staticfiles import StaticFiles
+except Exception: # pragma: no cover - only loaded when the settings app is available
+ FastAPI = object # type: ignore
+ Response = object # type: ignore
+ BaseModel = object # type: ignore
+ FileResponse = object # type: ignore
+ JSONResponse = object # type: ignore
+ StaticFiles = object # type: ignore
+
+
+
+logger = logging.getLogger(__name__)
+
+COOKAIWARE_PROFILE = "cookaiware"
+COOKAIWARE_MODEL = "chef-reachy"
+DEFAULT_PROFILE = "default"
+
+
+def _normalize_chat_id(value: Optional[str]) -> str:
+ raw = (value or "").strip()
+ if not raw:
+ return ""
+ parsed = urlparse(raw)
+ path = parsed.path if parsed.scheme or parsed.netloc else raw
+ marker = "/c/"
+ if marker in path:
+ return path.split(marker, 1)[1].split("/", 1)[0].strip()
+ return raw.strip("/")
+
+
+def _as_bool(value: Any, default: bool = False) -> bool:
+ if isinstance(value, bool):
+ return value
+ raw = str(value or "").strip().lower()
+ if not raw:
+ return default
+ return raw in {"1", "true", "yes", "on"}
+
+
+def _bool_env(value: bool) -> str:
+ return "1" if value else "0"
+
+
+def _csv_list(value: str) -> list[str]:
+ return [part.strip() for part in (value or "").split(",") if part.strip()]
+
+
+def _tool_env_value(tools: Optional[List[str]]) -> str:
+ if tools is None:
+ return config.OPENWEBUI_ENABLED_TOOLS
+ clean = sorted({str(tool).strip() for tool in tools if str(tool).strip()})
+ return ",".join(clean) if clean else "__none__"
+
+
+_ALSA_OUTPUT_CONTROLS = ("PCM", "Speaker", "Headphone", "Master")
+_ALSA_INPUT_CONTROLS = ("Headset", "Capture", "Mic", "Internal Mic", "Digital", "ADC")
+
+
+def _clamp_percent(value: Any, default: int = 100) -> int:
+ try:
+ return min(100, max(0, int(round(float(value)))))
+ except Exception:
+ return default
+
+
+def _amixer_path() -> str:
+ return shutil.which("amixer") or "amixer"
+
+
+def _run_amixer(args: list[str]) -> str:
+ completed = subprocess.run(
+ [_amixer_path(), *args],
+ check=True,
+ capture_output=True,
+ text=True,
+ timeout=2.5,
+ )
+ return (completed.stdout or "").strip()
+
+
+def _alsa_card_index() -> Optional[str]:
+ try:
+ cards = Path("/proc/asound/cards").read_text(encoding="utf-8", errors="ignore")
+ except Exception:
+ return None
+ matches = re.finditer(r"^\s*(\d+)\s+\[([^\]]+)\].*$\n\s*(.*)$", cards, re.MULTILINE)
+ fallback: Optional[str] = None
+ for match in matches:
+ card_index = match.group(1)
+ text = f"{match.group(2)} {match.group(3)}".lower()
+ if "reachy mini audio" in text:
+ return card_index
+ if fallback is None and "usb-audio" in text:
+ fallback = card_index
+ return fallback
+
+
+def _run_card_amixer(args: list[str]) -> str:
+ card_index = _alsa_card_index()
+ if card_index:
+ return _run_amixer(["-c", card_index, *args])
+ return _run_amixer(args)
+
+
+def _alsa_controls() -> set[str]:
+ try:
+ output = _run_card_amixer(["scontrols"])
+ except Exception:
+ return set()
+ controls: set[str] = set()
+ for name, index in re.findall(r"Simple mixer control '([^']+)',(\d+)", output):
+ controls.add(f"{name},{index}")
+ controls.add(name)
+ return controls
+
+
+def _pick_alsa_control(candidates: tuple[str, ...], controls: Optional[set[str]] = None) -> str:
+ available = controls if controls is not None else _alsa_controls()
+ for candidate in candidates:
+ indexed = f"{candidate},0"
+ if indexed in available:
+ return indexed
+ if candidate in available:
+ return candidate
+ return candidates[0]
+
+
+def _read_alsa_percent(candidates: tuple[str, ...], controls: Optional[set[str]] = None, default: int = 100) -> int:
+ control = _pick_alsa_control(candidates, controls)
+ try:
+ output = _run_card_amixer(["sget", control])
+ except Exception:
+ return default
+ raw_percent = _alsa_raw_output_percent(output)
+ if raw_percent is not None:
+ return raw_percent
+ matches = re.findall(r"\[(\d{1,3})%\]", output)
+ if not matches:
+ return default
+ values = [_clamp_percent(match, default) for match in matches]
+ return int(round(sum(values) / len(values)))
+
+
+def _alsa_raw_output_percent(output: str) -> Optional[int]:
+ limits = re.search(r"Limits:\s+(?:Playback|Capture)\s+(-?\d+)\s+-\s+(-?\d+)", output)
+ if not limits:
+ return None
+ min_value = int(limits.group(1))
+ max_value = int(limits.group(2))
+ if max_value <= min_value:
+ return None
+ raw_matches = re.findall(r":\s+(?:Playback|Capture)\s+(-?\d+)\s+\[", output)
+ if not raw_matches:
+ return None
+ values = [int(value) for value in raw_matches]
+ average = sum(values) / len(values)
+ percent = ((average - min_value) / (max_value - min_value)) * 100
+ return _clamp_percent(percent)
+
+
+def _alsa_percent_to_raw(control: str, percent: Any) -> str:
+ value = _clamp_percent(percent)
+ try:
+ output = _run_card_amixer(["sget", control])
+ except Exception:
+ return f"{value}%"
+ limits = re.search(r"Limits:\s+(?:Playback|Capture)\s+(-?\d+)\s+-\s+(-?\d+)", output)
+ if not limits:
+ return f"{value}%"
+ min_value = int(limits.group(1))
+ max_value = int(limits.group(2))
+ if max_value <= min_value:
+ return f"{value}%"
+ raw = round(min_value + ((max_value - min_value) * value / 100))
+ return str(raw)
+
+
+def _set_alsa_percent(
+ candidates: tuple[str, ...],
+ percent: Any,
+ switch_arg: str = "",
+) -> tuple[int, str, bool]:
+ value = _clamp_percent(percent)
+ controls = _alsa_controls()
+ control = _pick_alsa_control(candidates, controls)
+ try:
+ raw_value = _alsa_percent_to_raw(control, value)
+ args = ["sset", control, raw_value]
+ if switch_arg:
+ args.append(switch_arg)
+ try:
+ _run_card_amixer(args)
+ except Exception:
+ _run_card_amixer(["sset", control, raw_value])
+ return value, control, True
+ except Exception as exc:
+ logger.warning("Could not set ALSA mixer %s to %s%%: %s", control, value, exc)
+ return value, control, False
+
+
+def _alsa_audio_levels() -> dict[str, Any]:
+ controls = _alsa_controls()
+ output_control = _pick_alsa_control(_ALSA_OUTPUT_CONTROLS, controls)
+ input_control = _pick_alsa_control(_ALSA_INPUT_CONTROLS, controls)
+ return {
+ "speaker_volume": _read_alsa_percent(_ALSA_OUTPUT_CONTROLS, controls),
+ "mic_volume": _read_alsa_percent(_ALSA_INPUT_CONTROLS, controls),
+ "alsa_available": bool(controls),
+ "alsa_card": _alsa_card_index() or "",
+ "alsa_output_control": output_control,
+ "alsa_input_control": input_control,
+ }
+
+
+def _enabled_tools_from_config(available_tools: list[str]) -> list[str]:
+ raw = (config.OPENWEBUI_ENABLED_TOOLS or "").strip()
+ if raw == "__none__":
+ return []
+ if not raw:
+ return []
+ available = set(available_tools)
+ return [name for name in _csv_list(raw) if name in available]
+
+
+def _tool_spec_name(spec: Any) -> str:
+ if not isinstance(spec, dict):
+ return ""
+ function = spec.get("function")
+ if not isinstance(function, dict):
+ return ""
+ return str(function.get("name") or "").strip()
+
+
+def _model_meta(item: dict[str, Any]) -> dict[str, Any]:
+ info = item.get("info")
+ if isinstance(info, dict):
+ meta = info.get("meta")
+ if isinstance(meta, dict):
+ return meta
+ meta = item.get("meta")
+ return meta if isinstance(meta, dict) else {}
+
+
+def _model_has_vision(item: Any) -> bool:
+ if not isinstance(item, dict):
+ return False
+ capabilities = _model_meta(item).get("capabilities")
+ if isinstance(capabilities, dict):
+ return bool(capabilities.get("vision"))
+ return False
+
+
+def _openwebui_api_v1_root(url: str) -> str:
+ base = (url or "").strip().rstrip("/")
+ lower = base.lower()
+ if lower.endswith("/api/v1"):
+ return base
+ if lower.endswith("/api"):
+ return f"{base}/v1"
+ return f"{base}/api/v1"
+
+
+def _chat_item_id(item: Any) -> str:
+ if not isinstance(item, dict):
+ return ""
+ for key in ("chat_id", "chatId", "conversation_id", "conversationId", "channel_id", "channelId", "id"):
+ value = item.get(key)
+ if value is None:
+ continue
+ chat_id = _normalize_chat_id(str(value))
+ if chat_id:
+ return chat_id
+ for key in ("chat", "meta", "info"):
+ chat_id = _chat_item_id(item.get(key))
+ if chat_id:
+ return chat_id
+ return ""
+
+
+def _chat_item_title(item: Any) -> str:
+ if not isinstance(item, dict):
+ return "Untitled conversation"
+ for key in ("title", "name", "topic", "summary"):
+ value = item.get(key)
+ if isinstance(value, str) and value.strip():
+ return value.strip()
+ for key in ("chat", "meta", "info"):
+ nested = item.get(key)
+ if isinstance(nested, dict):
+ title = _chat_item_title(nested)
+ if title != "Untitled conversation":
+ return title
+ return "Untitled conversation"
+
+
+def _chat_item_timestamp(item: Any, *keys_to_check: str) -> Any:
+ if not isinstance(item, dict):
+ return None
+ for key in keys_to_check:
+ value = item.get(key)
+ if value is not None and value != "":
+ return value
+ for key in ("chat", "meta", "info"):
+ nested = item.get(key)
+ if isinstance(nested, dict):
+ value = _chat_item_timestamp(nested, *keys_to_check)
+ if value is not None and value != "":
+ return value
+ return None
+
+
+def _chat_items_from_payload(payload: Any) -> list[dict[str, Any]]:
+ if isinstance(payload, dict):
+ for key in ("data", "chats", "items", "results"):
+ nested = payload.get(key)
+ if isinstance(nested, (list, dict)):
+ items = _chat_items_from_payload(nested)
+ if items:
+ return items
+ chat_id = _chat_item_id(payload)
+ if not chat_id:
+ return []
+ return [
+ {
+ "id": chat_id,
+ "title": _chat_item_title(payload),
+ "updated_at": _chat_item_timestamp(payload, "updated_at", "updatedAt", "last_activity_at"),
+ "created_at": _chat_item_timestamp(payload, "created_at", "createdAt"),
+ "last_read_at": _chat_item_timestamp(payload, "last_read_at", "lastReadAt"),
+ }
+ ]
+
+ if not isinstance(payload, list):
+ return []
+
+ items: list[dict[str, Any]] = []
+ for raw_item in payload:
+ if not isinstance(raw_item, dict):
+ continue
+ chat_id = _chat_item_id(raw_item)
+ if not chat_id:
+ continue
+ items.append(
+ {
+ "id": chat_id,
+ "title": _chat_item_title(raw_item),
+ "updated_at": _chat_item_timestamp(raw_item, "updated_at", "updatedAt", "last_activity_at"),
+ "created_at": _chat_item_timestamp(raw_item, "created_at", "createdAt"),
+ "last_read_at": _chat_item_timestamp(raw_item, "last_read_at", "lastReadAt"),
+ }
+ )
+ return items
+
+
+def _jwt_payload(token: str) -> dict[str, Any]:
+ parts = (token or "").split(".")
+ if len(parts) < 2:
+ return {}
+ try:
+ payload = parts[1] + "=" * (-len(parts[1]) % 4)
+ decoded = base64.urlsafe_b64decode(payload.encode("utf-8"))
+ data = json.loads(decoded.decode("utf-8"))
+ return data if isinstance(data, dict) else {}
+ except Exception:
+ return {}
+
+
+def _openwebui_user_id() -> str:
+ configured = (config.OPENWEBUI_USER_ID or "").strip()
+ if configured:
+ return configured
+ payload = _jwt_payload(config.OPENWEBUI_TOKEN or "")
+ for key in ("id", "sub", "user_id", "userId"):
+ value = str(payload.get(key) or "").strip()
+ if value:
+ return value
+ return ""
+
+
+def _openwebui_user_name() -> str:
+ configured = (config.OPENWEBUI_USER_NAME or "").strip()
+ if configured:
+ return configured
+ payload = _jwt_payload(config.OPENWEBUI_TOKEN or "")
+ for key in ("name", "username", "email"):
+ value = str(payload.get(key) or "").strip()
+ if value:
+ return value
+ return "You"
+
+
+class LocalStream:
+ """LocalStream using Reachy Mini's recorder/player."""
+
+ def __init__(
+ self,
+ handler: Any,
+ robot: ReachyMini,
+ *,
+ settings_app: Optional[FastAPI] = None,
+ instance_path: Optional[str] = None,
+ ):
+ """Initialize the stream with a local session handler and pipelines.
+
+ - ``settings_app``: the Reachy Mini Apps FastAPI to attach settings routes.
+ - ``instance_path``: directory where per-instance ``.env`` should be stored.
+ """
+ self.handler = handler
+ self._robot = robot
+ self._stop_event = threading.Event() # thread-safe (set from uvicorn, polled from asyncio)
+ self._tasks: List[asyncio.Task[None]] = []
+ # Allow the handler to flush the player queue when appropriate.
+ self.handler._clear_queue = self.clear_audio_queue
+ self._settings_app: Optional[FastAPI] = settings_app
+ self._instance_path: Optional[str] = instance_path
+ self._settings_initialized = False
+ self._asyncio_loop = None
+ self._start_event = threading.Event()
+ self._pipeline_state = "stopped"
+ self._transcript_messages: list[dict[str, str]] = []
+ self._normal_mode_snapshot: dict[str, str] | None = None
+
+ self._init_settings_ui_if_needed()
+ self._attach_app_dependencies()
+
+ # ---- Settings UI ----
+ def _read_env_lines(self, env_path: Path) -> list[str]:
+ """Load env file contents or a template as a list of lines."""
+ inst = env_path.parent
+ try:
+ if env_path.exists():
+ try:
+ return env_path.read_text(encoding="utf-8").splitlines()
+ except Exception:
+ return []
+ template_text = None
+ ex = inst / ".env.example"
+ if ex.exists():
+ try:
+ template_text = ex.read_text(encoding="utf-8")
+ except Exception:
+ template_text = None
+ if template_text is None:
+ try:
+ cwd_example = Path.cwd() / ".env.example"
+ if cwd_example.exists():
+ template_text = cwd_example.read_text(encoding="utf-8")
+ except Exception:
+ template_text = None
+ if template_text is None:
+ packaged = Path(__file__).parent / ".env.example"
+ if packaged.exists():
+ try:
+ template_text = packaged.read_text(encoding="utf-8")
+ except Exception:
+ template_text = None
+ return template_text.splitlines() if template_text else []
+ except Exception:
+ return []
+
+ def _stable_env_path(self) -> Path:
+ return Path.home() / ".config" / "settings" / ".env"
+
+ def _attach_app_dependencies(self) -> None:
+ deps = getattr(self.handler, "deps", None)
+ if deps is None:
+ return
+ try:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.data_store import resolve_data_dir
+
+ deps.data_dir = resolve_data_dir(self._instance_path)
+ except Exception as exc:
+ logger.warning("Could not prepare app data directory: %s", exc)
+ try:
+ deps.handler = self.handler
+ except Exception:
+ pass
+
+ def _speak_cookaiware_line(self, text: str) -> None:
+ loop = self._asyncio_loop
+ deps = getattr(self.handler, "deps", None)
+ speak_func = getattr(deps, "speak_func", None)
+ if loop is None or not loop.is_running() or not callable(speak_func):
+ return
+ try:
+ asyncio.run_coroutine_threadsafe(speak_func(text), loop)
+ except Exception as exc:
+ logger.warning("Could not queue CookAIware speech: %s", exc)
+
+ def _queue_cookaiware_camera_sound(self) -> None:
+ loop = self._asyncio_loop
+ output_queue = getattr(self.handler, "output_queue", None)
+ if loop is None or not loop.is_running() or output_queue is None:
+ return
+ sound_path = Path(__file__).parent / "static" / "assets" / "camera.wav"
+ if not sound_path.exists():
+ return
+ try:
+ with wave.open(str(sound_path), "rb") as sound:
+ sample_rate = sound.getframerate()
+ channels = sound.getnchannels()
+ sample_width = sound.getsampwidth()
+ frames = sound.readframes(sound.getnframes())
+ if sample_width != 2 or not frames:
+ return
+ audio = np.frombuffer(frames, dtype=np.int16)
+ if channels > 1:
+ audio = audio.reshape(-1, channels).mean(axis=1).astype(np.int16)
+ asyncio.run_coroutine_threadsafe(output_queue.put((sample_rate, audio.copy())), loop)
+ except Exception as exc:
+ logger.warning("Could not queue CookAIware camera sound: %s", exc)
+
+ def _queue_cookaiware_scan_pose(self) -> None:
+ try:
+ from Reachy_OpenWebUI.motion_patterns import make_pattern_move
+
+ deps = getattr(self.handler, "deps", None)
+ movement_manager = getattr(deps, "movement_manager", None)
+ robot = getattr(deps, "reachy_mini", None)
+ if movement_manager is None or robot is None:
+ return
+ movement_manager.clear_move_queue()
+ movement_manager.queue_move(make_pattern_move("lookAround", duration_s=1.2))
+ movement_manager.set_moving_state(1.2)
+ except Exception as exc:
+ logger.warning("Could not queue CookAIware scan pose: %s", exc)
+
+ def _queue_cookaiware_scan_done_pose(self) -> None:
+ try:
+ from reachy_mini.utils import create_head_pose
+ from Reachy_OpenWebUI.dance_emotion_moves import GotoQueueMove
+
+ deps = getattr(self.handler, "deps", None)
+ movement_manager = getattr(deps, "movement_manager", None)
+ robot = getattr(deps, "reachy_mini", None)
+ if movement_manager is None or robot is None:
+ return
+ current_head_pose = robot.get_current_head_pose()
+ head_joints, current_antennas = robot.get_current_joint_positions()
+ movement_manager.queue_move(
+ GotoQueueMove(
+ target_head_pose=create_head_pose(0, 0, 0, 0, 0, 0, degrees=True),
+ start_head_pose=current_head_pose,
+ target_antennas=(0.0, 0.0),
+ start_antennas=(current_antennas[0], current_antennas[1]),
+ target_body_yaw=0,
+ start_body_yaw=float(head_joints[0]) if head_joints else 0,
+ duration=0.45,
+ )
+ )
+ movement_manager.set_moving_state(0.6)
+ except Exception as exc:
+ logger.warning("Could not queue CookAIware scan done pose: %s", exc)
+
+ def _ensure_stable_env_file(self) -> None:
+ env_path = self._stable_env_path()
+ if env_path.exists():
+ return
+ self._write_env_values(env_path, keys.DEFAULT_OPENWEBUI_ENV)
+
+ def _write_env_values(self, env_path: Path, updates: dict[str, str]) -> None:
+ env_path.parent.mkdir(parents=True, exist_ok=True)
+ lines = self._read_env_lines(env_path)
+ for env_name, value in updates.items():
+ replaced = False
+ for i, line in enumerate(lines):
+ if line.strip().startswith(f"{env_name}="):
+ lines[i] = f"{env_name}={value}"
+ replaced = True
+ break
+ if not replaced:
+ lines.append(f"{env_name}={value}")
+ env_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
+
+ def _persist_openwebui_settings(self, updates: dict[str, str]) -> None:
+ self._ensure_stable_env_file()
+ persist_keys = (
+ keys.OPENWEBUI_URL,
+ keys.OPENWEB_LOADED_LLM,
+ keys.OPENWEBUI_API_KEY,
+ keys.OPENWEBUI_TOKEN,
+ keys.OPENWEBUI_CHAT_ID,
+ keys.OPENWEBUI_CHAT_WINDOW_START,
+ keys.OPENWEBUI_CHAT_PENDING_REASON,
+ keys.OPENWEBUI_CHAT_PENDING_EVENT_ID,
+ keys.MIC_GAIN,
+ keys.OPENWEBUI_CONTACTS_REQUIRE_VISION,
+ keys.OPENWEBUI_ENABLED_TOOLS,
+ keys.REACHY_IDLE_ATTITUDE,
+ keys.REACHY_MINI_CUSTOM_PROFILE,
+ keys.WEATHER_POSTAL_CODE,
+ )
+ normalized = {key: (updates[key] or "").strip() for key in persist_keys if key in updates}
+ if not normalized:
+ return
+
+ for env_name, value in normalized.items():
+ os.environ[env_name] = value
+ try:
+ if env_name == keys.OPENWEBUI_URL:
+ config.OPENWEBUI_URL = value
+ elif env_name == keys.OPENWEB_LOADED_LLM:
+ config.OPENWEBUI_MODEL = value
+ elif env_name == keys.OPENWEBUI_API_KEY:
+ config.OPENWEBUI_API_KEY = value
+ elif env_name == keys.OPENWEBUI_TOKEN:
+ config.OPENWEBUI_TOKEN = value
+ elif env_name == keys.OPENWEBUI_CHAT_ID:
+ config.OPENWEBUI_CHAT_ID = value
+ elif env_name == keys.OPENWEBUI_CHAT_WINDOW_START:
+ config.OPENWEBUI_CHAT_WINDOW_START = value
+ elif env_name == keys.OPENWEBUI_CHAT_PENDING_REASON:
+ config.OPENWEBUI_CHAT_PENDING_REASON = value
+ elif env_name == keys.OPENWEBUI_CHAT_PENDING_EVENT_ID:
+ config.OPENWEBUI_CHAT_PENDING_EVENT_ID = value
+ elif env_name == keys.MIC_GAIN:
+ config.MIC_GAIN = float(value)
+ elif env_name == keys.OPENWEBUI_CONTACTS_REQUIRE_VISION:
+ config.OPENWEBUI_CONTACTS_REQUIRE_VISION = _as_bool(value, default=True)
+ elif env_name == keys.OPENWEBUI_ENABLED_TOOLS:
+ config.OPENWEBUI_ENABLED_TOOLS = value
+ elif env_name == keys.REACHY_IDLE_ATTITUDE:
+ config.REACHY_IDLE_ATTITUDE = value or "calm"
+ elif env_name == keys.REACHY_MINI_CUSTOM_PROFILE:
+ config.REACHY_MINI_CUSTOM_PROFILE = value
+ elif env_name == keys.WEATHER_POSTAL_CODE:
+ config.WEATHER_POSTAL_CODE = value
+ else:
+ setattr(config, env_name, value)
+ except Exception:
+ pass
+
+ try:
+ self._write_env_values(self._stable_env_path(), normalized)
+ logger.info("Persisted OpenWebUI settings to %s", self._stable_env_path())
+ except Exception as e:
+ logger.warning("Failed to persist stable OpenWebUI settings: %s", e)
+
+ if self._instance_path:
+ try:
+ env_path = Path(self._instance_path) / ".env"
+ self._write_env_values(env_path, normalized)
+ logger.info("Persisted OpenWebUI settings to %s", env_path)
+ try:
+ from dotenv import load_dotenv
+
+ load_dotenv(dotenv_path=str(env_path), override=True)
+ except Exception:
+ pass
+ except Exception as e:
+ logger.warning("Failed to persist instance OpenWebUI settings: %s", e)
+
+ def _reload_openwebui_settings_from_disk(self) -> None:
+ """Refresh runtime config from stable and instance env files."""
+ if self._instance_path:
+ try:
+ from dotenv import load_dotenv
+
+ env_path = Path(self._instance_path) / ".env"
+ if env_path.exists():
+ load_dotenv(dotenv_path=str(env_path), override=False)
+ except Exception:
+ pass
+
+ try:
+ from dotenv import load_dotenv
+
+ stable_env_path = self._stable_env_path()
+ if stable_env_path.exists():
+ load_dotenv(dotenv_path=str(stable_env_path), override=True)
+ except Exception:
+ pass
+
+ for canonical_key, legacy_key, older_legacy_key, attr_name in (
+ (keys.OPENWEBUI_URL, keys.LEGACY_LOCAL_LLM_URL, "", "OPENWEBUI_URL"),
+ (keys.OPENWEB_LOADED_LLM, keys.LEGACY_OPENWEB_MODEL, keys.LEGACY_LOCAL_LLM_MODEL, "OPENWEBUI_MODEL"),
+ (
+ keys.OPENWEBUI_API_KEY,
+ "",
+ keys.LEGACY_LOCAL_LLM_API_KEY,
+ "OPENWEBUI_API_KEY",
+ ),
+ (keys.OPENWEBUI_TOKEN, keys.LEGACY_OPENWEBUI_TOKEN, "", "OPENWEBUI_TOKEN"),
+ (keys.OPENWEBUI_CHAT_ID, "", "", "OPENWEBUI_CHAT_ID"),
+ (keys.OPENWEBUI_CHAT_WINDOW_START, "", "", "OPENWEBUI_CHAT_WINDOW_START"),
+ (keys.OPENWEBUI_CHAT_PENDING_REASON, "", "", "OPENWEBUI_CHAT_PENDING_REASON"),
+ (keys.OPENWEBUI_CHAT_PENDING_EVENT_ID, "", "", "OPENWEBUI_CHAT_PENDING_EVENT_ID"),
+ (keys.OPENWEBUI_CONTACTS_REQUIRE_VISION, "", "", "OPENWEBUI_CONTACTS_REQUIRE_VISION"),
+ (keys.OPENWEBUI_ENABLED_TOOLS, "", "", "OPENWEBUI_ENABLED_TOOLS"),
+ (keys.REACHY_IDLE_ATTITUDE, "", "", "REACHY_IDLE_ATTITUDE"),
+ (keys.REACHY_MINI_CUSTOM_PROFILE, "", "", "REACHY_MINI_CUSTOM_PROFILE"),
+ (keys.WEATHER_POSTAL_CODE, "", "", "WEATHER_POSTAL_CODE"),
+ ):
+ val = ""
+ for env_key in (canonical_key, legacy_key, older_legacy_key):
+ if not env_key:
+ continue
+ val = os.getenv(env_key, "").strip()
+ if val:
+ break
+ if val or canonical_key in {
+ keys.OPENWEBUI_CHAT_ID,
+ keys.OPENWEBUI_CHAT_WINDOW_START,
+ keys.OPENWEBUI_CHAT_PENDING_REASON,
+ keys.OPENWEBUI_CHAT_PENDING_EVENT_ID,
+ }:
+ try:
+ if attr_name == "OPENWEBUI_CONTACTS_REQUIRE_VISION":
+ setattr(config, attr_name, _as_bool(val, default=True))
+ else:
+ setattr(config, attr_name, val)
+ except Exception:
+ pass
+ mic_val = os.getenv(keys.MIC_GAIN, "").strip()
+ if mic_val:
+ try:
+ config.MIC_GAIN = float(mic_val)
+ except Exception:
+ pass
+ def _sync_live_llm_chat_id(self) -> None:
+ llm = getattr(self.handler, "llm", None)
+ if llm is None or not hasattr(llm, "chat_id"):
+ return
+ new_chat_id = _normalize_chat_id(config.OPENWEBUI_CHAT_ID)
+ old_chat_id = _normalize_chat_id(str(getattr(llm, "chat_id", "") or ""))
+ if old_chat_id == new_chat_id:
+ return
+ try:
+ llm.chat_id = new_chat_id
+ if hasattr(llm, "_last_message_id"):
+ llm._last_message_id = None
+ if hasattr(llm, "history"):
+ llm.history = []
+ logger.info("OpenWebUI live chat selection changed to %s", new_chat_id or "")
+ except Exception as exc:
+ logger.warning("Could not sync live OpenWebUI chat id: %s", exc)
+
+ def _has_saved_openwebui_settings(self) -> bool:
+ """Return true when saved settings are enough to launch without setup."""
+ return bool((config.OPENWEBUI_URL or "").strip() and (config.OPENWEBUI_MODEL or "").strip())
+
+ def _has_real_openwebui_api_key(self) -> bool:
+ api_key = (config.OPENWEBUI_API_KEY or "").strip()
+ return bool(api_key and api_key.lower() != "ollama")
+
+ def _has_real_openwebui_token(self) -> bool:
+ token = (config.OPENWEBUI_TOKEN or "").strip()
+ return bool(token and token.lower() != "ollama")
+
+ def _has_openwebui_auth(self) -> bool:
+ return self._has_real_openwebui_api_key() or self._has_real_openwebui_token()
+
+ def _requires_real_openwebui_api_key(self, url: Optional[str] = None) -> bool:
+ value = (url or config.OPENWEBUI_URL or "").strip().lower()
+ if not value.startswith("https://"):
+ return False
+ return not (
+ value.startswith("https://localhost")
+ or value.startswith("https://127.0.0.1")
+ or value.startswith("https://0.0.0.0")
+ )
+
+ def _reachy_tool_specs(self) -> list[dict[str, Any]]:
+ specs: list[dict[str, Any]] = []
+ try:
+ from Reachy_OpenWebUI.tools.core_tools import get_tool_specs
+
+ specs = get_tool_specs(attitude=self._active_tool_attitude())
+ except Exception:
+ specs = getattr(self.handler, "tool_specs", []) or []
+ return [spec for spec in specs if isinstance(spec, dict)]
+
+ def _available_reachy_tools(self) -> list[str]:
+ return sorted({name for spec in self._reachy_tool_specs() if (name := _tool_spec_name(spec))})
+
+ def _settings_reachy_tools(self) -> list[str]:
+ names: list[str] = []
+ seen: set[str] = set()
+ for profile in (DEFAULT_PROFILE, COOKAIWARE_PROFILE):
+ for name in self._profile_tool_names(profile):
+ if name not in seen:
+ names.append(name)
+ seen.add(name)
+ for name in self._available_reachy_tools():
+ if name not in seen:
+ names.append(name)
+ seen.add(name)
+ return names
+
+ def _settings_tool_groups(self) -> dict[str, list[str]]:
+ return {
+ "phone": self._profile_tool_names(DEFAULT_PROFILE),
+ "cookaiware": self._profile_tool_names(COOKAIWARE_PROFILE),
+ }
+
+ def _configured_reachy_tool_specs(self) -> list[dict[str, Any]]:
+ specs = self._reachy_tool_specs()
+ enabled = set(_enabled_tools_from_config(self._available_reachy_tools()))
+ return [spec for spec in specs if _tool_spec_name(spec) in enabled]
+
+ def _profile_tool_names(self, profile: str) -> list[str]:
+ if profile == COOKAIWARE_PROFILE:
+ tools_path = Path(__file__).parent / "cookAIware" / "profiles" / profile / "tools.txt"
+ else:
+ tools_path = Path(__file__).parent / "profiles" / profile / "tools.txt"
+ try:
+ names: list[str] = []
+ for raw_line in tools_path.read_text(encoding="utf-8").splitlines():
+ line = raw_line.strip()
+ if line and not line.startswith("#"):
+ names.append(line)
+ return names
+ except Exception as exc:
+ logger.warning("Could not read profile tool list for %s: %s", profile, exc)
+ return []
+
+ def _refresh_tool_runtime(self) -> None:
+ try:
+ from Reachy_OpenWebUI.tools.core_tools import get_tool_specs
+
+ get_tool_specs(attitude=self._active_tool_attitude())
+ self.handler.tool_specs = self._configured_reachy_tool_specs()
+ except Exception as exc:
+ logger.warning("Could not refresh Reachy tools after app mode change: %s", exc)
+
+ def _active_tool_attitude(self) -> str | None:
+ if (config.REACHY_MINI_CUSTOM_PROFILE or "") == COOKAIWARE_PROFILE:
+ return None
+ return config.REACHY_IDLE_ATTITUDE
+
+ def _apply_live_attitude(self, attitude: str | None) -> None:
+ if not attitude:
+ return
+ deps = getattr(self.handler, "deps", None)
+ movement_manager = getattr(deps, "movement_manager", None)
+ if movement_manager is not None and hasattr(movement_manager, "set_idle_attitude"):
+ try:
+ movement_manager.set_idle_attitude(attitude)
+ except Exception as exc:
+ logger.warning("Could not apply idle attitude %s: %s", attitude, exc)
+ head_wobbler = getattr(deps, "head_wobbler", None)
+ if head_wobbler is not None and hasattr(head_wobbler, "set_attitude"):
+ try:
+ head_wobbler.set_attitude(attitude)
+ except Exception as exc:
+ logger.warning("Could not apply speech attitude %s: %s", attitude, exc)
+
+ def _reset_live_pipeline_for_mode_change(self) -> None:
+ self._pipeline_state = "stopped"
+ self._start_event.clear()
+ self._transcript_messages = []
+ loop = self._asyncio_loop
+ if loop is not None and loop.is_running():
+ for task in self._tasks:
+ if not task.done():
+ loop.call_soon_threadsafe(task.cancel)
+ if hasattr(self.handler, "set_muted"):
+ self.handler.set_muted(False)
+ try:
+ self.handler._refresh_openwebui_runtime_config()
+ except Exception:
+ pass
+ try:
+ self.handler.llm = None
+ self.handler.speech = None
+ self.handler.vad = None
+ except Exception:
+ pass
+ try:
+ self.handler.tool_specs = self._configured_reachy_tool_specs()
+ except Exception as exc:
+ logger.warning("Could not set live tool specs after app mode change: %s", exc)
+
+ def _cooking_data_dir(self) -> Path:
+ deps = getattr(self.handler, "deps", None)
+ data_dir = getattr(deps, "data_dir", None)
+ if data_dir is not None:
+ return Path(data_dir)
+ from Reachy_OpenWebUI.sub_apps.cookAIware.data_store import resolve_data_dir
+
+ resolved = resolve_data_dir(self._instance_path)
+ if deps is not None:
+ try:
+ deps.data_dir = resolved
+ except Exception:
+ pass
+ return resolved
+
+ def _cooking_state_payload(self) -> dict[str, Any]:
+ data_dir = self._cooking_data_dir()
+ from Reachy_OpenWebUI.sub_apps.cookAIware.app_settings import get_settings
+ from Reachy_OpenWebUI.sub_apps.cookAIware.family_profile import load_profile
+ from Reachy_OpenWebUI.sub_apps.cookAIware.inventory import list_inventory, normalize_for_display
+ from Reachy_OpenWebUI.sub_apps.cookAIware.meal_planner import load_plan
+ from Reachy_OpenWebUI.sub_apps.cookAIware.shopping_list import list_items
+
+ settings = get_settings(data_dir)
+ unit_system = str(settings.get("unit_system") or "metric")
+ return {
+ "data_dir": str(data_dir),
+ "inventory": normalize_for_display(list_inventory(data_dir), unit_system),
+ "profile": load_profile(data_dir),
+ "plan": load_plan(data_dir),
+ "shopping": list_items(data_dir),
+ "settings": settings,
+ }
+
+ def _status_payload(self) -> dict[str, Any]:
+ vad = getattr(self.handler, "vad", None)
+ now_mono = time.monotonic()
+ last_user_speech = float(getattr(self.handler, "_last_user_speech_mono", 0.0) or 0.0)
+ last_assistant_typing = float(getattr(self.handler, "_last_assistant_typing_mono", 0.0) or 0.0)
+ tts_inflight = int(getattr(self.handler, "_tts_inflight_count", 0) or 0)
+ user_typing = bool(
+ self._pipeline_state == "running"
+ and not bool(getattr(self.handler, "muted", False))
+ and (
+ bool(getattr(self.handler, "is_speaking", False))
+ or (last_user_speech > 0 and now_mono - last_user_speech <= 1.8)
+ )
+ )
+ assistant_typing = bool(
+ self._pipeline_state == "running"
+ and (
+ int(getattr(self.handler, "_active_pipeline_count", 0) or 0) > 0
+ or tts_inflight > 0
+ or (last_assistant_typing > 0 and now_mono - last_assistant_typing <= 2.2)
+ )
+ )
+ available_tools = self._settings_reachy_tools()
+ tool_groups = self._settings_tool_groups()
+ enabled_tools = _enabled_tools_from_config(available_tools)
+ movement_status: dict[str, Any] = {}
+ movement_manager = getattr(getattr(self.handler, "deps", None), "movement_manager", None)
+ if movement_manager is not None and hasattr(movement_manager, "get_status"):
+ try:
+ movement_status = movement_manager.get_status()
+ except Exception:
+ movement_status = {}
+ idle_attitude = str(movement_status.get("idle_attitude") or config.REACHY_IDLE_ATTITUDE or "calm")
+ audio_levels = _alsa_audio_levels()
+ return {
+ "state": self._pipeline_state,
+ "pipeline_ready": bool(
+ getattr(self.handler, "llm", None) is not None
+ and getattr(self.handler, "speech", None) is not None
+ and vad is not None
+ ),
+ "vad_loaded": bool(getattr(vad, "model", None) is not None),
+ "vad_mode": str(getattr(vad, "mode", "none")),
+ "received_audio_frames": int(getattr(self.handler, "_receive_frame_count", 0)),
+ "can_start": self._has_saved_openwebui_settings(),
+ "openwebui_url": config.OPENWEBUI_URL or "",
+ "openwebui_model": config.OPENWEBUI_MODEL or "",
+ "openwebui_user_id": _openwebui_user_id(),
+ "openwebui_user_name": _openwebui_user_name(),
+ "openwebui_chat_id": config.OPENWEBUI_CHAT_ID or "",
+ "openwebui_chat_window_start": config.OPENWEBUI_CHAT_WINDOW_START or "",
+ "muted": bool(getattr(self.handler, "muted", False)),
+ "speaker_muted": bool(getattr(self.handler, "speaker_muted", False)),
+ "has_openwebui_api_key": self._has_real_openwebui_api_key(),
+ "has_openwebui_token": self._has_real_openwebui_token(),
+ "requires_openwebui_api_key": self._requires_real_openwebui_api_key(),
+ "mic_gain": config.MIC_GAIN,
+ **audio_levels,
+ "contacts_require_vision": bool(config.OPENWEBUI_CONTACTS_REQUIRE_VISION),
+ "active_profile": config.REACHY_MINI_CUSTOM_PROFILE or "",
+ "cookaiware_active": config.REACHY_MINI_CUSTOM_PROFILE == COOKAIWARE_PROFILE,
+ "reachy_idle_attitude": idle_attitude,
+ "available_idle_attitudes": available_idle_attitudes(),
+ "available_tools": available_tools,
+ "phone_tools": tool_groups["phone"],
+ "cookaiware_tools": tool_groups["cookaiware"],
+ "enabled_tools": enabled_tools,
+ "weather_postal_code": config.WEATHER_POSTAL_CODE or "",
+ "env_path": str(self._stable_env_path()),
+ "transcript_messages": list(self._transcript_messages[-20:]),
+ "user_typing": user_typing,
+ "assistant_typing": assistant_typing,
+ }
+
+ def _init_settings_ui_if_needed(self) -> None:
+ """Attach the OpenWebUI-only settings UI to the Reachy settings app."""
+ if self._settings_initialized or self._settings_app is None:
+ return
+
+ static_dir = Path(__file__).parent / "static"
+ index_file = static_dir / "index.html"
+
+ if hasattr(self._settings_app, "mount"):
+ try:
+ self._settings_app.mount("/static", StaticFiles(directory=str(static_dir)), name="static")
+ except Exception:
+ pass
+
+ class OpenWebUISettingsPayload(BaseModel):
+ openwebui_url: str
+ openwebui_model: str
+ openwebui_api_key: Optional[str] = None
+ openwebui_token: Optional[str] = None
+ openwebui_chat_id: Optional[str] = None
+ mic_gain: Optional[str] = None
+ contacts_require_vision: Optional[bool] = None
+ reachy_idle_attitude: Optional[str] = None
+ enabled_tools: Optional[List[str]] = None
+ weather_postal_code: Optional[str] = None
+ app_mode: Optional[str] = None
+
+ class OpenWebUIModelPayload(BaseModel):
+ openwebui_url: Optional[str] = None
+ openwebui_api_key: Optional[str] = None
+ openwebui_token: Optional[str] = None
+ contacts_require_vision: Optional[bool] = None
+
+ class TextInputPayload(BaseModel):
+ text: str
+ images: Optional[List[str]] = None
+
+ class MutePayload(BaseModel):
+ muted: bool
+
+ class VolumePayload(BaseModel):
+ mic_volume: Optional[float] = None
+ speaker_volume: Optional[float] = None
+
+ class StartAppPayload(BaseModel):
+ app_mode: Optional[str] = None
+
+ class CookingInventoryPayload(BaseModel):
+ action: str = "add"
+ items: List[dict[str, Any]] = []
+
+ class CookingProfilePayload(BaseModel):
+ adults: Optional[int] = None
+ children: Optional[int] = None
+ schedule: Optional[dict[str, Any]] = None
+
+ class CookingShoppingPayload(BaseModel):
+ action: str = "add"
+ items: List[dict[str, Any]] = []
+
+ class CookingUpcScanPayload(BaseModel):
+ target: str = "inventory"
+
+ class CookingUpcCachePayload(BaseModel):
+ barcode: str
+ source: Optional[str] = None
+ item: dict[str, Any]
+
+ class CookingSettingsPayload(BaseModel):
+ language: Optional[str] = None
+ unit_system: Optional[str] = None
+ upc_lookup_source: Optional[str] = None
+
+ @self._settings_app.get("/")
+ def _root() -> FileResponse:
+ return FileResponse(str(index_file))
+
+ @self._settings_app.get("/favicon.ico")
+ def _favicon() -> Response:
+ return Response(status_code=204)
+
+ @self._settings_app.get("/service-worker.js")
+ def _service_worker() -> FileResponse:
+ return FileResponse(str(static_dir / "service-worker.js"), media_type="text/javascript")
+
+ @self._settings_app.get("/status")
+ def _status() -> JSONResponse:
+ self._ensure_stable_env_file()
+ self._reload_openwebui_settings_from_disk()
+ return JSONResponse(self._status_payload())
+
+ @self._settings_app.get("/cooking/state")
+ def _cooking_state() -> JSONResponse:
+ return JSONResponse({"ok": True, **self._cooking_state_payload()})
+
+ @self._settings_app.get("/cooking/inventory")
+ def _cooking_inventory() -> JSONResponse:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.app_settings import get_unit_system
+ from Reachy_OpenWebUI.sub_apps.cookAIware.inventory import list_inventory, normalize_for_display
+
+ data_dir = self._cooking_data_dir()
+ return JSONResponse({"ok": True, "items": normalize_for_display(list_inventory(data_dir), get_unit_system(data_dir))})
+
+ @self._settings_app.get("/cooking/upc/{barcode}")
+ def _cooking_upc_lookup(barcode: str) -> JSONResponse:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.app_settings import get_upc_lookup_source
+ from Reachy_OpenWebUI.sub_apps.cookAIware.upc_lookup import lookup_upc
+
+ data_dir = self._cooking_data_dir()
+ result = lookup_upc(barcode, get_upc_lookup_source(data_dir), data_dir)
+ status_code = 200 if result.get("found") else 404
+ return JSONResponse({"ok": bool(result.get("found")), **result}, status_code=status_code)
+
+ @self._settings_app.get("/cooking/camera/frame")
+ def _cooking_camera_frame() -> Response:
+ from Reachy_OpenWebUI.camera_frame_encoding import encode_bgr_frame_as_jpeg
+
+ deps = getattr(self.handler, "deps", None)
+ camera_worker = getattr(deps, "camera_worker", None)
+ if camera_worker is None:
+ return JSONResponse({"ok": False, "error": "camera_unavailable"}, status_code=503)
+ frame = camera_worker.get_latest_frame()
+ if frame is None:
+ return JSONResponse({"ok": False, "error": "no_frame"}, status_code=503)
+ try:
+ jpeg = encode_bgr_frame_as_jpeg(frame)
+ except Exception as exc:
+ logger.warning("Could not encode cooking camera frame: %s", exc)
+ return JSONResponse({"ok": False, "error": "encode_failed"}, status_code=500)
+ return Response(content=jpeg, media_type="image/jpeg")
+
+ @self._settings_app.post("/cooking/upc/cache")
+ def _cooking_upc_cache(payload: CookingUpcCachePayload) -> JSONResponse:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.app_settings import get_upc_lookup_source
+ from Reachy_OpenWebUI.sub_apps.cookAIware.upc_cache import save_cached_upc
+
+ data_dir = self._cooking_data_dir()
+ barcode = re.sub(r"\D", "", payload.barcode or "")
+ if not barcode:
+ return JSONResponse({"ok": False, "error": "missing_barcode", "message": "Enter a UPC barcode."}, status_code=400)
+ item = dict(payload.item or {})
+ name = str(item.get("name") or "").strip()
+ if not name:
+ return JSONResponse({"ok": False, "error": "missing_name", "message": "Enter a food item name."}, status_code=400)
+ source = (payload.source or get_upc_lookup_source(data_dir)).strip().lower()
+ item["name"] = name
+ item["quantity"] = item.get("quantity") or 1
+ item["unit"] = item.get("unit") or "pcs"
+ item["barcode"] = barcode
+ item["source"] = source
+ entry = save_cached_upc(data_dir, source, barcode, item)
+ return JSONResponse({"ok": True, "entry": entry, "item": item})
+
+ @self._settings_app.post("/cooking/upc/scan")
+ def _cooking_upc_scan(payload: CookingUpcScanPayload) -> JSONResponse:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.inventory import add_items
+ from Reachy_OpenWebUI.sub_apps.cookAIware.app_settings import get_upc_lookup_source
+ from Reachy_OpenWebUI.sub_apps.cookAIware.shopping_list import add_items as add_shopping_items
+ from Reachy_OpenWebUI.sub_apps.cookAIware.upc_camera import scan_upc_from_camera
+ from Reachy_OpenWebUI.sub_apps.cookAIware.upc_lookup import lookup_upc
+
+ target = (payload.target or "inventory").strip().lower()
+ if target not in {"inventory", "shopping"}:
+ target = "inventory"
+ deps = getattr(self.handler, "deps", None)
+ self._queue_cookaiware_scan_pose()
+ try:
+ scan = scan_upc_from_camera(
+ getattr(deps, "camera_worker", None),
+ timeout_s=8.0,
+ on_frame=self._queue_cookaiware_camera_sound,
+ )
+ finally:
+ self._queue_cookaiware_scan_done_pose()
+ if not scan.get("ok"):
+ self._speak_cookaiware_line(scan.get("message") or "I could not scan the UPC.")
+ return JSONResponse({"ok": False, **scan}, status_code=503)
+
+ data_dir = self._cooking_data_dir()
+ lookup = lookup_upc(str(scan.get("barcode") or ""), get_upc_lookup_source(data_dir), data_dir)
+ if not lookup.get("found"):
+ self._speak_cookaiware_line(lookup.get("message") or "I found the barcode, but not the item.")
+ return JSONResponse({"ok": False, **lookup}, status_code=404)
+
+ item = lookup.get("item") or {}
+ if target == "shopping":
+ add_shopping_items(
+ data_dir,
+ [{"name": item.get("name"), "quantity": item.get("quantity") or 1, "unit": item.get("unit") or "pcs"}],
+ )
+ spoken = f"All set. I'll add {item.get('name')} to the shopping list."
+ else:
+ add_items(data_dir, [item])
+ spoken = f"All set. I'll add {item.get('name')} to inventory."
+ self._speak_cookaiware_line(spoken)
+ return JSONResponse(
+ {
+ "ok": True,
+ "barcode": scan.get("barcode"),
+ "item": item,
+ "message": spoken,
+ **self._cooking_state_payload(),
+ }
+ )
+
+ @self._settings_app.post("/cooking/inventory")
+ def _cooking_inventory_add(payload: CookingInventoryPayload) -> JSONResponse:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.app_settings import get_unit_system
+ from Reachy_OpenWebUI.sub_apps.cookAIware.inventory import add_items, cook_items, normalize_for_display, set_auto_add_shopping
+
+ data_dir = self._cooking_data_dir()
+ unit_system = get_unit_system(data_dir)
+ action = (payload.action or "add").strip().lower()
+ if action == "set_auto_add":
+ inventory = set_auto_add_shopping(data_dir, payload.items or [])
+ errors = []
+ elif action == "use":
+ inventory, errors = cook_items(data_dir, payload.items or [])
+ else:
+ inventory, errors = add_items(data_dir, payload.items or [])
+ return JSONResponse(
+ {
+ "ok": True,
+ "items": normalize_for_display(inventory, unit_system),
+ "errors": errors,
+ **self._cooking_state_payload(),
+ }
+ )
+
+ @self._settings_app.get("/cooking/profile")
+ def _cooking_profile() -> JSONResponse:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.family_profile import load_profile
+
+ return JSONResponse({"ok": True, "profile": load_profile(self._cooking_data_dir())})
+
+ @self._settings_app.post("/cooking/profile")
+ def _cooking_profile_save(payload: CookingProfilePayload) -> JSONResponse:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.family_profile import update_profile
+
+ profile = update_profile(self._cooking_data_dir(), payload.adults, payload.children, payload.schedule)
+ return JSONResponse({"ok": True, "profile": profile, **self._cooking_state_payload()})
+
+ @self._settings_app.get("/cooking/plan")
+ def _cooking_plan() -> JSONResponse:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.meal_planner import load_plan
+
+ return JSONResponse({"ok": True, "plan": load_plan(self._cooking_data_dir())})
+
+ @self._settings_app.post("/cooking/plan/generate")
+ def _cooking_plan_generate() -> JSONResponse:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.family_profile import load_profile
+ from Reachy_OpenWebUI.sub_apps.cookAIware.inventory import list_inventory
+ from Reachy_OpenWebUI.sub_apps.cookAIware.meal_planner import generate_plan
+ from Reachy_OpenWebUI.sub_apps.cookAIware.app_settings import get_unit_system
+
+ data_dir = self._cooking_data_dir()
+ inventory = list_inventory(data_dir)
+ if not inventory:
+ return JSONResponse(
+ {"ok": False, "error": "missing_inventory", "message": "Add inventory before generating a plan."},
+ status_code=400,
+ )
+ profile = load_profile(data_dir)
+ plan = generate_plan(
+ data_dir,
+ inventory,
+ int(profile.get("adults") or 1),
+ int(profile.get("children") or 0),
+ profile.get("schedule"),
+ get_unit_system(data_dir),
+ )
+ return JSONResponse({"ok": True, "plan": plan, **self._cooking_state_payload()})
+
+ @self._settings_app.get("/cooking/shopping")
+ def _cooking_shopping() -> JSONResponse:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.shopping_list import list_items
+
+ return JSONResponse({"ok": True, "items": list_items(self._cooking_data_dir())})
+
+ @self._settings_app.post("/cooking/shopping")
+ def _cooking_shopping_update(payload: CookingShoppingPayload) -> JSONResponse:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.inventory import list_inventory
+ from Reachy_OpenWebUI.sub_apps.cookAIware.meal_planner import load_plan
+ from Reachy_OpenWebUI.sub_apps.cookAIware.shopping_list import (
+ add_items,
+ clear_list,
+ generate_from_inventory_alerts,
+ generate_from_plan,
+ list_items,
+ remove_items,
+ )
+
+ data_dir = self._cooking_data_dir()
+ action = (payload.action or "add").strip().lower()
+ if action == "generate":
+ plan = load_plan(data_dir)
+ if not plan:
+ return JSONResponse(
+ {"ok": False, "error": "missing_plan", "message": "Generate a meal plan first."},
+ status_code=400,
+ )
+ items = generate_from_plan(data_dir, plan, list_inventory(data_dir))
+ elif action == "auto_inventory":
+ items = generate_from_inventory_alerts(data_dir, list_inventory(data_dir))
+ elif action == "remove":
+ items = remove_items(data_dir, payload.items or [])
+ elif action == "clear":
+ clear_list(data_dir)
+ items = []
+ else:
+ items = add_items(data_dir, payload.items or [])
+ return JSONResponse({"ok": True, "items": items or list_items(data_dir), **self._cooking_state_payload()})
+
+ @self._settings_app.get("/cooking/settings")
+ def _cooking_settings() -> JSONResponse:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.app_settings import get_settings
+
+ return JSONResponse({"ok": True, "settings": get_settings(self._cooking_data_dir())})
+
+ @self._settings_app.post("/cooking/settings")
+ def _cooking_settings_save(payload: CookingSettingsPayload) -> JSONResponse:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.app_settings import (
+ get_settings,
+ set_language,
+ set_unit_system,
+ set_upc_lookup_source,
+ )
+
+ data_dir = self._cooking_data_dir()
+ settings = set_language(data_dir, payload.language) if payload.language is not None else get_settings(data_dir)
+ if payload.unit_system is not None:
+ settings = set_unit_system(data_dir, payload.unit_system)
+ if payload.upc_lookup_source is not None:
+ settings = set_upc_lookup_source(data_dir, payload.upc_lookup_source)
+ return JSONResponse({"ok": True, "settings": settings, **self._cooking_state_payload()})
+
+ @self._settings_app.get("/ready")
+ def _ready() -> JSONResponse:
+ return JSONResponse({"ready": bool(self._status_payload().get("pipeline_ready"))})
+
+ def _weather_condition(code: Any) -> str:
+ try:
+ weather_code = int(code)
+ except Exception:
+ return "Weather"
+ labels = {
+ 0: "Clear",
+ 1: "Mostly clear",
+ 2: "Partly cloudy",
+ 3: "Cloudy",
+ 45: "Fog",
+ 48: "Fog",
+ 51: "Drizzle",
+ 53: "Drizzle",
+ 55: "Drizzle",
+ 56: "Freezing drizzle",
+ 57: "Freezing drizzle",
+ 61: "Rain",
+ 63: "Rain",
+ 65: "Heavy rain",
+ 66: "Freezing rain",
+ 67: "Freezing rain",
+ 71: "Snow",
+ 73: "Snow",
+ 75: "Heavy snow",
+ 77: "Snow grains",
+ 80: "Showers",
+ 81: "Showers",
+ 82: "Heavy showers",
+ 85: "Snow showers",
+ 86: "Snow showers",
+ 95: "Thunderstorms",
+ 96: "Thunderstorms",
+ 99: "Thunderstorms",
+ }
+ return labels.get(weather_code, "Weather")
+
+ @self._settings_app.get("/weather")
+ async def _weather() -> JSONResponse:
+ postal_code = (config.WEATHER_POSTAL_CODE or "").strip()
+ if not postal_code:
+ return JSONResponse({"ok": True, "configured": False, "message": "Set postal code."})
+
+ try:
+ import httpx
+
+ async with httpx.AsyncClient(timeout=8.0, follow_redirects=True) as client:
+ location_response = await client.get(f"https://api.zippopotam.us/us/{quote(postal_code, safe='')}")
+ if location_response.status_code == 404:
+ return JSONResponse(
+ {"ok": False, "configured": True, "error": "postal_code_not_found"},
+ status_code=404,
+ )
+ location_response.raise_for_status()
+ location_data = location_response.json()
+ places = location_data.get("places") if isinstance(location_data, dict) else []
+ if not places:
+ return JSONResponse(
+ {"ok": False, "configured": True, "error": "postal_code_not_found"},
+ status_code=404,
+ )
+ place = places[0]
+ latitude = float(place.get("latitude"))
+ longitude = float(place.get("longitude"))
+ city = str(place.get("place name") or "").strip()
+ state = str(place.get("state abbreviation") or place.get("state") or "").strip()
+ forecast_response = await client.get(
+ "https://api.open-meteo.com/v1/forecast",
+ params={
+ "latitude": latitude,
+ "longitude": longitude,
+ "current": "temperature_2m,weather_code,is_day",
+ "daily": "weather_code,temperature_2m_max,temperature_2m_min",
+ "temperature_unit": "fahrenheit",
+ "timezone": "auto",
+ "forecast_days": 5,
+ },
+ )
+ forecast_response.raise_for_status()
+ forecast = forecast_response.json()
+ current = forecast.get("current") if isinstance(forecast, dict) else {}
+ daily = forecast.get("daily") if isinstance(forecast, dict) else {}
+ temperature = current.get("temperature_2m") if isinstance(current, dict) else None
+ weather_code = current.get("weather_code") if isinstance(current, dict) else None
+ forecast_days: list[dict[str, Any]] = []
+ if isinstance(daily, dict):
+ dates = daily.get("time") if isinstance(daily.get("time"), list) else []
+ highs = daily.get("temperature_2m_max") if isinstance(daily.get("temperature_2m_max"), list) else []
+ lows = daily.get("temperature_2m_min") if isinstance(daily.get("temperature_2m_min"), list) else []
+ codes = daily.get("weather_code") if isinstance(daily.get("weather_code"), list) else []
+ for index, day in enumerate(dates[:5]):
+ high = highs[index] if index < len(highs) else None
+ low = lows[index] if index < len(lows) else None
+ code = codes[index] if index < len(codes) else None
+ forecast_days.append(
+ {
+ "date": day,
+ "high": round(float(high)) if high is not None else None,
+ "low": round(float(low)) if low is not None else None,
+ "condition": _weather_condition(code),
+ }
+ )
+ return JSONResponse(
+ {
+ "ok": True,
+ "configured": True,
+ "postal_code": postal_code,
+ "location": ", ".join(part for part in (city, state) if part),
+ "temperature": round(float(temperature)) if temperature is not None else None,
+ "unit": "F",
+ "condition": _weather_condition(weather_code),
+ "is_day": bool(current.get("is_day", True)) if isinstance(current, dict) else True,
+ "forecast": forecast_days,
+ }
+ )
+ except Exception as exc:
+ logger.warning("Weather lookup failed for postal code %s: %s", postal_code, exc)
+ return JSONResponse(
+ {"ok": False, "configured": True, "error": "weather_lookup_failed"},
+ status_code=502,
+ )
+
+ @self._settings_app.post("/openwebui_models")
+ async def _openwebui_models(payload: OpenWebUIModelPayload) -> JSONResponse:
+ url = (payload.openwebui_url or config.OPENWEBUI_URL or "").strip().rstrip("/")
+ token = (
+ payload.openwebui_api_key
+ or payload.openwebui_token
+ or config.OPENWEBUI_API_KEY
+ or config.OPENWEBUI_TOKEN
+ or ""
+ ).strip()
+ if not url:
+ return JSONResponse({"ok": False, "models": [], "message": "No OpenWebUI URL configured."})
+ require_vision = (
+ bool(payload.contacts_require_vision)
+ if payload.contacts_require_vision is not None
+ else bool(config.OPENWEBUI_CONTACTS_REQUIRE_VISION)
+ )
+
+ headers = {"User-Agent": config.OPENWEBUI_USER_AGENT}
+ if token and token != "ollama":
+ headers["Authorization"] = f"Bearer {token}"
+ if url.endswith("/api"):
+ candidates = [f"{url}/models", f"{url[:-4]}/api/models", f"{url[:-4]}/models"]
+ else:
+ candidates = [f"{url}/api/models", f"{url}/models"]
+
+ try:
+ import httpx
+
+ async with httpx.AsyncClient(timeout=8.0) as client:
+ last_status = None
+ for endpoint in dict.fromkeys(candidates):
+ response = await client.get(endpoint, headers=headers)
+ last_status = response.status_code
+ if response.status_code == 404:
+ continue
+ response.raise_for_status()
+ content_type = response.headers.get("content-type", "")
+ if "json" not in content_type.lower():
+ last_status = f"{response.status_code} non-json"
+ continue
+ try:
+ data = response.json()
+ except ValueError:
+ last_status = f"{response.status_code} invalid-json"
+ continue
+ raw_models = data.get("data") if isinstance(data, dict) else data
+ if not isinstance(raw_models, list):
+ raw_models = data.get("models", []) if isinstance(data, dict) else []
+ models = []
+ for item in raw_models:
+ if isinstance(item, dict):
+ if require_vision and not _model_has_vision(item):
+ continue
+ model_id = str(item.get("id") or item.get("name") or "").strip()
+ elif require_vision:
+ continue
+ else:
+ model_id = str(item).strip()
+ if model_id:
+ models.append(model_id)
+ return JSONResponse(
+ {
+ "ok": True,
+ "models": sorted(set(models)),
+ "message": (
+ f"Loaded {len(set(models))} vision contacts."
+ if require_vision
+ else f"Loaded {len(set(models))} contacts."
+ ),
+ }
+ )
+ return JSONResponse(
+ {"ok": False, "models": [], "message": f"Model endpoint not found ({last_status})."}
+ )
+ except Exception as e:
+ return JSONResponse({"ok": False, "models": [], "message": f"Model refresh failed: {e}"})
+
+ @self._settings_app.post("/openwebui_chats")
+ async def _openwebui_chats(payload: OpenWebUIModelPayload) -> JSONResponse:
+ url = (payload.openwebui_url or config.OPENWEBUI_URL or "").strip().rstrip("/")
+ token = (
+ payload.openwebui_api_key
+ or payload.openwebui_token
+ or config.OPENWEBUI_API_KEY
+ or config.OPENWEBUI_TOKEN
+ or ""
+ ).strip()
+ if not url:
+ return JSONResponse({"ok": False, "chats": [], "message": "No OpenWebUI URL configured."})
+
+ headers = {"User-Agent": config.OPENWEBUI_USER_AGENT, "Accept": "application/json"}
+ if token and token != "ollama":
+ headers["Authorization"] = f"Bearer {token}"
+
+ api_v1_root = _openwebui_api_v1_root(url)
+ chats: list[dict[str, Any]] = []
+ seen: set[str] = set()
+ errors: list[str] = []
+
+ def add_items(items: list[dict[str, Any]]) -> int:
+ added = 0
+ for item in items:
+ chat_id = str(item.get("id") or "").strip()
+ if not chat_id or chat_id in seen:
+ continue
+ seen.add(chat_id)
+ chats.append(item)
+ added += 1
+ return added
+
+ try:
+ import httpx
+
+ async with httpx.AsyncClient(timeout=8.0) as client:
+ active_endpoint = f"{api_v1_root}/tasks/active/chats"
+ try:
+ response = await client.post(active_endpoint, headers=headers, json={})
+ if response.status_code not in {404, 405}:
+ response.raise_for_status()
+ add_items(_chat_items_from_payload(response.json()))
+ except Exception as exc:
+ errors.append(f"active chats: {exc}")
+
+ try:
+ response = await client.get(f"{api_v1_root}/chats/?page=1", headers=headers)
+ if response.status_code != 404:
+ response.raise_for_status()
+ add_items(_chat_items_from_payload(response.json()))
+ except Exception as exc:
+ errors.append(f"chat page 1: {exc}")
+
+ if chats:
+ return JSONResponse(
+ {
+ "ok": True,
+ "chats": chats,
+ "message": f"Loaded {len(chats)} conversations.",
+ }
+ )
+ if errors:
+ return JSONResponse(
+ {"ok": False, "chats": [], "message": f"Conversation refresh failed: {errors[-1]}"}
+ )
+ return JSONResponse({"ok": True, "chats": [], "message": "No conversations found."})
+ except Exception as e:
+ return JSONResponse({"ok": False, "chats": [], "message": f"Conversation refresh failed: {e}"})
+
+ async def _proxy_openwebui_image(path_and_query: str) -> Response:
+ import httpx
+
+ root = (config.OPENWEBUI_URL or "").strip().rstrip("/")
+ if not root:
+ return Response(status_code=404)
+ if root.endswith("/api"):
+ root = root[:-4]
+
+ credential = (config.OPENWEBUI_TOKEN or config.OPENWEBUI_API_KEY or "").strip()
+ headers = {"User-Agent": config.OPENWEBUI_USER_AGENT}
+ if credential and credential != "ollama":
+ headers["Authorization"] = f"Bearer {credential}"
+
+ try:
+ async with httpx.AsyncClient(timeout=8.0, follow_redirects=True) as client:
+ response = await client.get(f"{root}{path_and_query}", headers=headers)
+ content_type = response.headers.get("content-type", "")
+ if response.status_code >= 400 or not content_type.lower().startswith("image/"):
+ return Response(status_code=404)
+ return Response(
+ content=response.content,
+ media_type=content_type,
+ headers={"Cache-Control": "private, max-age=86400"},
+ )
+ except Exception as exc:
+ logger.debug("OpenWebUI avatar proxy failed for %s: %s", path_and_query, exc)
+ return Response(status_code=404)
+
+ @self._settings_app.get("/avatar/model")
+ async def _model_avatar(id: str = "", lang: str = "") -> Response:
+ model_id = (id or config.OPENWEBUI_MODEL or "").strip()
+ if not model_id:
+ return Response(status_code=404)
+ query = urlencode({"id": model_id, "lang": lang or config.OPENWEBUI_USER_LANGUAGE or "en-US"})
+ return await _proxy_openwebui_image(f"/api/v1/models/model/profile/image?{query}")
+
+ @self._settings_app.get("/avatar/user")
+ async def _user_avatar(user_id: str = "") -> Response:
+ resolved_user_id = (user_id or _openwebui_user_id()).strip()
+ if not resolved_user_id:
+ return Response(status_code=404)
+ quoted_user_id = quote(resolved_user_id, safe="")
+ return await _proxy_openwebui_image(f"/api/v1/users/{quoted_user_id}/profile/image")
+
+ @self._settings_app.post("/backend_config")
+ def _save_settings(payload: OpenWebUISettingsPayload) -> JSONResponse:
+ openwebui_url = (payload.openwebui_url or "").strip()
+ openwebui_model = (payload.openwebui_model or "").strip()
+ if not openwebui_url:
+ return JSONResponse({"ok": False, "error": "empty_openwebui_url"}, status_code=400)
+ if not openwebui_model:
+ return JSONResponse({"ok": False, "error": "empty_openwebui_model"}, status_code=400)
+ if (
+ self._requires_real_openwebui_api_key(openwebui_url)
+ and (payload.openwebui_token is not None or payload.openwebui_api_key is not None)
+ and not (payload.openwebui_api_key or payload.openwebui_token or "").strip()
+ and not self._has_openwebui_auth()
+ ):
+ return JSONResponse({"ok": False, "error": "missing_openwebui_api_key"}, status_code=400)
+
+ previous_model = (config.OPENWEBUI_MODEL or "").strip()
+ model_changed = bool(previous_model and previous_model != openwebui_model)
+ requested_chat_id = _normalize_chat_id(payload.openwebui_chat_id)
+ if model_changed and requested_chat_id:
+ logger.info(
+ "OpenWebUI model changed from %s to %s; starting with a new chat.",
+ previous_model,
+ openwebui_model,
+ )
+ requested_chat_id = ""
+
+ self._persist_openwebui_settings(
+ {
+ keys.OPENWEBUI_URL: openwebui_url,
+ keys.OPENWEB_LOADED_LLM: openwebui_model,
+ keys.OPENWEBUI_API_KEY: (
+ config.OPENWEBUI_API_KEY
+ if payload.openwebui_api_key is None
+ else payload.openwebui_api_key
+ ),
+ keys.OPENWEBUI_TOKEN: (
+ config.OPENWEBUI_TOKEN
+ if payload.openwebui_token is None
+ else payload.openwebui_token
+ ),
+ keys.OPENWEBUI_CHAT_ID: requested_chat_id,
+ keys.OPENWEBUI_CHAT_WINDOW_START: "" if model_changed else config.OPENWEBUI_CHAT_WINDOW_START,
+ keys.OPENWEBUI_CHAT_PENDING_REASON: "" if model_changed else config.OPENWEBUI_CHAT_PENDING_REASON,
+ keys.OPENWEBUI_CHAT_PENDING_EVENT_ID: "" if model_changed else config.OPENWEBUI_CHAT_PENDING_EVENT_ID,
+ keys.MIC_GAIN: payload.mic_gain if payload.mic_gain is not None else str(config.MIC_GAIN),
+ keys.OPENWEBUI_CONTACTS_REQUIRE_VISION: _bool_env(
+ bool(payload.contacts_require_vision)
+ if payload.contacts_require_vision is not None
+ else bool(config.OPENWEBUI_CONTACTS_REQUIRE_VISION)
+ ),
+ keys.OPENWEBUI_ENABLED_TOOLS: _tool_env_value(payload.enabled_tools),
+ keys.WEATHER_POSTAL_CODE: (
+ config.WEATHER_POSTAL_CODE
+ if payload.weather_postal_code is None
+ else payload.weather_postal_code.strip()
+ ),
+ keys.REACHY_IDLE_ATTITUDE: (
+ config.REACHY_IDLE_ATTITUDE
+ if payload.reachy_idle_attitude is None
+ else payload.reachy_idle_attitude.strip()
+ ),
+ keys.REACHY_MINI_CUSTOM_PROFILE: (
+ COOKAIWARE_PROFILE
+ if (payload.app_mode or "").strip() == COOKAIWARE_PROFILE
+ else ""
+ ),
+ }
+ )
+ self._reload_openwebui_settings_from_disk()
+ self._sync_live_llm_chat_id()
+ try:
+ self.handler.tool_specs = self._configured_reachy_tool_specs()
+ except Exception as exc:
+ logger.warning("Could not refresh enabled Reachy tools after settings save: %s", exc)
+ self._apply_live_attitude(config.REACHY_IDLE_ATTITUDE)
+ return JSONResponse({"ok": True, "message": "Settings saved.", **self._status_payload()})
+
+ @self._settings_app.post("/apps/cookaiware/enter")
+ def _enter_cookaiware() -> JSONResponse:
+ self._reload_openwebui_settings_from_disk()
+ if (config.REACHY_MINI_CUSTOM_PROFILE or "") != COOKAIWARE_PROFILE:
+ self._normal_mode_snapshot = {
+ "profile": config.REACHY_MINI_CUSTOM_PROFILE or "",
+ "model": config.OPENWEBUI_MODEL or "",
+ "enabled_tools": config.OPENWEBUI_ENABLED_TOOLS or "__none__",
+ }
+ cook_tools = self._profile_tool_names(COOKAIWARE_PROFILE)
+ if not cook_tools:
+ return JSONResponse({"ok": False, "error": "missing_cookaiware_tools"}, status_code=500)
+ tool_value = ",".join(cook_tools)
+ self._persist_openwebui_settings(
+ {
+ keys.OPENWEB_LOADED_LLM: COOKAIWARE_MODEL,
+ keys.OPENWEBUI_CHAT_ID: "",
+ keys.OPENWEBUI_CHAT_WINDOW_START: "",
+ keys.OPENWEBUI_CHAT_PENDING_REASON: "",
+ keys.OPENWEBUI_CHAT_PENDING_EVENT_ID: "",
+ keys.OPENWEBUI_ENABLED_TOOLS: tool_value,
+ keys.REACHY_MINI_CUSTOM_PROFILE: COOKAIWARE_PROFILE,
+ }
+ )
+ set_runtime_mode(profile=COOKAIWARE_PROFILE, model=COOKAIWARE_MODEL)
+ self._refresh_tool_runtime()
+ self._reset_live_pipeline_for_mode_change()
+ return JSONResponse({"ok": True, "message": "CookAIware ready.", **self._status_payload()})
+
+ @self._settings_app.post("/apps/cookaiware/exit")
+ def _exit_cookaiware() -> JSONResponse:
+ snapshot = self._normal_mode_snapshot or {}
+ model = (snapshot.get("model") or config.OPENWEBUI_MODEL or "").strip()
+ enabled_tools = (snapshot.get("enabled_tools") or "__none__").strip() or "__none__"
+ profile = (snapshot.get("profile") or "").strip()
+ updates = {
+ keys.OPENWEBUI_CHAT_ID: "",
+ keys.OPENWEBUI_CHAT_WINDOW_START: "",
+ keys.OPENWEBUI_CHAT_PENDING_REASON: "",
+ keys.OPENWEBUI_CHAT_PENDING_EVENT_ID: "",
+ keys.OPENWEBUI_ENABLED_TOOLS: enabled_tools,
+ keys.REACHY_MINI_CUSTOM_PROFILE: profile,
+ }
+ if model:
+ updates[keys.OPENWEB_LOADED_LLM] = model
+ self._persist_openwebui_settings(updates)
+ set_runtime_mode(profile=profile, model=model)
+ self._normal_mode_snapshot = None
+ self._refresh_tool_runtime()
+ self._apply_live_attitude(config.REACHY_IDLE_ATTITUDE)
+ self._reset_live_pipeline_for_mode_change()
+ return JSONResponse({"ok": True, "message": "CookAIware closed.", **self._status_payload()})
+
+ @self._settings_app.post("/callback")
+ def _callback() -> JSONResponse:
+ old_chat_id = config.OPENWEBUI_CHAT_ID or ""
+ pending_event_id = str(uuid.uuid4())
+ append_chat_history(
+ "callback_requested",
+ pending_event_id=pending_event_id,
+ old_chat_id=old_chat_id,
+ window_start=config.OPENWEBUI_CHAT_WINDOW_START or "",
+ )
+ self._persist_openwebui_settings(
+ {
+ keys.OPENWEBUI_URL: config.OPENWEBUI_URL,
+ keys.OPENWEB_LOADED_LLM: config.OPENWEBUI_MODEL,
+ keys.OPENWEBUI_API_KEY: config.OPENWEBUI_API_KEY,
+ keys.OPENWEBUI_TOKEN: config.OPENWEBUI_TOKEN,
+ keys.OPENWEBUI_CHAT_ID: "",
+ keys.OPENWEBUI_CHAT_WINDOW_START: "",
+ keys.OPENWEBUI_CHAT_PENDING_REASON: "callback",
+ keys.OPENWEBUI_CHAT_PENDING_EVENT_ID: pending_event_id,
+ keys.MIC_GAIN: str(config.MIC_GAIN),
+ keys.OPENWEBUI_CONTACTS_REQUIRE_VISION: _bool_env(bool(config.OPENWEBUI_CONTACTS_REQUIRE_VISION)),
+ keys.OPENWEBUI_ENABLED_TOOLS: config.OPENWEBUI_ENABLED_TOOLS,
+ keys.REACHY_IDLE_ATTITUDE: config.REACHY_IDLE_ATTITUDE,
+ }
+ )
+ config.OPENWEBUI_CHAT_ID = ""
+ config.OPENWEBUI_CHAT_WINDOW_START = ""
+ config.OPENWEBUI_CHAT_PENDING_REASON = "callback"
+ config.OPENWEBUI_CHAT_PENDING_EVENT_ID = pending_event_id
+ os.environ[keys.OPENWEBUI_CHAT_ID] = ""
+ os.environ[keys.OPENWEBUI_CHAT_WINDOW_START] = ""
+ os.environ[keys.OPENWEBUI_CHAT_PENDING_REASON] = "callback"
+ os.environ[keys.OPENWEBUI_CHAT_PENDING_EVENT_ID] = pending_event_id
+ llm = getattr(self.handler, "llm", None)
+ if llm is not None and hasattr(llm, "clear_chat_id"):
+ try:
+ llm.clear_chat_id(
+ window_start=llm.current_chat_window_start(),
+ pending_reason="callback",
+ pending_event_id=pending_event_id,
+ )
+ except Exception as exc:
+ logger.warning("Callback could not clear live chat id: %s", exc)
+ return JSONResponse({"ok": True, "message": "Callback ready. Next message starts a new chat.", **self._status_payload()})
+
+ @self._settings_app.post("/clear_call_cache")
+ def _clear_call_cache() -> JSONResponse:
+ old_chat_id = config.OPENWEBUI_CHAT_ID or ""
+ self._transcript_messages = []
+ self._persist_openwebui_settings(
+ {
+ keys.OPENWEBUI_URL: config.OPENWEBUI_URL,
+ keys.OPENWEB_LOADED_LLM: config.OPENWEBUI_MODEL,
+ keys.OPENWEBUI_API_KEY: config.OPENWEBUI_API_KEY,
+ keys.OPENWEBUI_TOKEN: config.OPENWEBUI_TOKEN,
+ keys.OPENWEBUI_CHAT_ID: "",
+ keys.OPENWEBUI_CHAT_WINDOW_START: "",
+ keys.OPENWEBUI_CHAT_PENDING_REASON: "",
+ keys.OPENWEBUI_CHAT_PENDING_EVENT_ID: "",
+ keys.MIC_GAIN: str(config.MIC_GAIN),
+ keys.OPENWEBUI_CONTACTS_REQUIRE_VISION: _bool_env(bool(config.OPENWEBUI_CONTACTS_REQUIRE_VISION)),
+ keys.OPENWEBUI_ENABLED_TOOLS: config.OPENWEBUI_ENABLED_TOOLS,
+ keys.REACHY_IDLE_ATTITUDE: config.REACHY_IDLE_ATTITUDE,
+ }
+ )
+ config.OPENWEBUI_CHAT_ID = ""
+ config.OPENWEBUI_CHAT_WINDOW_START = ""
+ config.OPENWEBUI_CHAT_PENDING_REASON = ""
+ config.OPENWEBUI_CHAT_PENDING_EVENT_ID = ""
+ os.environ[keys.OPENWEBUI_CHAT_ID] = ""
+ os.environ[keys.OPENWEBUI_CHAT_WINDOW_START] = ""
+ os.environ[keys.OPENWEBUI_CHAT_PENDING_REASON] = ""
+ os.environ[keys.OPENWEBUI_CHAT_PENDING_EVENT_ID] = ""
+ clear_chat_history(old_chat_id=old_chat_id)
+ llm = getattr(self.handler, "llm", None)
+ if llm is not None and hasattr(llm, "clear_chat_id"):
+ try:
+ llm.clear_chat_id(window_start="", pending_reason="", pending_event_id="")
+ except Exception as exc:
+ logger.warning("Clear call cache could not clear live chat id: %s", exc)
+ return JSONResponse({"ok": True, "message": "Call cache cleared.", **self._status_payload()})
+
+ @self._settings_app.post("/mute")
+ def _mute() -> JSONResponse:
+ muted = not bool(getattr(self.handler, "muted", False))
+ if hasattr(self.handler, "set_muted"):
+ self.handler.set_muted(muted)
+ else:
+ self.handler.muted = muted
+ message = "Muted." if muted else "Unmuted."
+ return JSONResponse({"ok": True, "message": message, **self._status_payload()})
+
+ @self._settings_app.post("/mic_mute")
+ def _mic_mute(payload: MutePayload) -> JSONResponse:
+ muted = bool(payload.muted)
+ if hasattr(self.handler, "set_muted"):
+ self.handler.set_muted(muted)
+ else:
+ self.handler.muted = muted
+ message = "Mic muted." if muted else "Mic unmuted."
+ return JSONResponse({"ok": True, "message": message, **self._status_payload()})
+
+ @self._settings_app.post("/speaker_mute")
+ def _speaker_mute(payload: MutePayload) -> JSONResponse:
+ muted = bool(payload.muted)
+ if hasattr(self.handler, "set_speaker_muted"):
+ self.handler.set_speaker_muted(muted)
+ else:
+ self.handler.speaker_muted = muted
+ message = "Speaker muted." if muted else "Speaker unmuted."
+ return JSONResponse({"ok": True, "message": message, **self._status_payload()})
+
+ @self._settings_app.post("/volume")
+ def _volume(payload: VolumePayload) -> JSONResponse:
+ ok = True
+ if payload.speaker_volume is not None:
+ _value, _control, speaker_ok = _set_alsa_percent(
+ _ALSA_OUTPUT_CONTROLS,
+ payload.speaker_volume,
+ "unmute",
+ )
+ ok = ok and speaker_ok
+ if payload.mic_volume is not None:
+ _value, _control, mic_ok = _set_alsa_percent(
+ _ALSA_INPUT_CONTROLS,
+ payload.mic_volume,
+ "cap",
+ )
+ ok = ok and mic_ok
+ message = "Hardware volume updated." if ok else "Hardware mixer not available."
+ return JSONResponse({"ok": ok, "message": message, **self._status_payload()})
+
+ @self._settings_app.post("/start_app")
+ def _start_app(payload: StartAppPayload | None = None) -> JSONResponse:
+ self._reload_openwebui_settings_from_disk()
+ app_mode = ((payload.app_mode if payload else "") or "phone").strip()
+ if app_mode != COOKAIWARE_PROFILE and (config.REACHY_MINI_CUSTOM_PROFILE or "") == COOKAIWARE_PROFILE:
+ self._persist_openwebui_settings({keys.REACHY_MINI_CUSTOM_PROFILE: ""})
+ set_runtime_mode(profile="", model=config.OPENWEBUI_MODEL)
+ self._refresh_tool_runtime()
+ if not self._has_saved_openwebui_settings():
+ return JSONResponse({"ok": False, "error": "missing_openwebui_settings"}, status_code=400)
+ if self._requires_real_openwebui_api_key() and not self._has_openwebui_auth():
+ return JSONResponse({"ok": False, "error": "missing_openwebui_api_key"}, status_code=400)
+ if hasattr(self.handler, "set_muted"):
+ self.handler.set_muted(False)
+ if self._status_payload().get("pipeline_ready"):
+ self._pipeline_state = "running"
+ return JSONResponse({"ok": True, "message": "Call ready.", **self._status_payload()})
+ self._pipeline_state = "configuring"
+ self._start_event.set()
+ return JSONResponse({"ok": True, "message": "Starting convo.", **self._status_payload()})
+
+ @self._settings_app.post("/stop_app")
+ def _stop_app() -> JSONResponse:
+ self._pipeline_state = "stopped"
+ self._start_event.clear()
+ if hasattr(self.handler, "set_muted"):
+ self.handler.set_muted(False)
+ loop = self._asyncio_loop
+ if loop is not None and loop.is_running():
+ for task in self._tasks:
+ if not task.done():
+ loop.call_soon_threadsafe(task.cancel)
+ return JSONResponse({"ok": True, "message": "Call ended.", **self._status_payload()})
+
+ @self._settings_app.post("/text_input")
+ def _text_input(payload: TextInputPayload) -> JSONResponse:
+ text = (payload.text or "").strip()
+ if not text:
+ return JSONResponse({"ok": False, "error": "empty_text"}, status_code=400)
+ if self._pipeline_state != "running" or not self._status_payload().get("pipeline_ready"):
+ return JSONResponse({"ok": False, "error": "conversation_not_running"}, status_code=409)
+ loop = self._asyncio_loop
+ if loop is None or not loop.is_running():
+ return JSONResponse({"ok": False, "error": "conversation_loop_not_ready"}, status_code=503)
+ send_text = getattr(self.handler, "send_text_input", None)
+ if not callable(send_text):
+ return JSONResponse({"ok": False, "error": "text_input_not_available"}, status_code=503)
+ images = [str(item) for item in (payload.images or []) if str(item).startswith("data:image/")]
+ asyncio.run_coroutine_threadsafe(send_text(text, images=images), loop)
+ return JSONResponse({"ok": True, "message": "Message sent.", **self._status_payload()})
+
+ @self._settings_app.post("/restart_app")
+ def _restart_app() -> JSONResponse:
+ def _restart_process() -> None:
+ time.sleep(0.35)
+ logger.info("Restart app requested from settings UI; exiting app process.")
+ os._exit(0)
+
+ threading.Thread(target=_restart_process, daemon=True).start()
+ return JSONResponse({"ok": True, "message": "Restarting app process.", **self._status_payload()})
+
+ class AttitudePayload(BaseModel):
+ attitude: str
+
+ @self._settings_app.post("/set_attitude")
+ def _set_attitude(payload: AttitudePayload) -> JSONResponse:
+ attitude = (payload.attitude or "").strip()
+ if not attitude:
+ return JSONResponse({"ok": False, "error": "missing_attitude"}, status_code=400)
+ from Reachy_OpenWebUI.sub_apps.attitudes import ATTITUDE_PROFILES
+
+ if attitude not in ATTITUDE_PROFILES:
+ return JSONResponse({"ok": False, "error": "unknown_attitude"}, status_code=400)
+ self._persist_openwebui_settings({keys.REACHY_IDLE_ATTITUDE: attitude})
+ self._reload_openwebui_settings_from_disk()
+ self._apply_live_attitude(attitude)
+ return JSONResponse({"ok": True, "message": f"Attitude set to {attitude}.", **self._status_payload()})
+
+ @self._settings_app.post("/test_speech")
+ def _test_speech() -> JSONResponse:
+ head_wobbler = getattr(getattr(self.handler, "deps", None), "head_wobbler", None)
+ if head_wobbler is None:
+ return JSONResponse({"ok": False, "error": "head_wobbler_not_available"}, status_code=503)
+ import numpy as np
+
+ duration_s = 4.0
+ sr = 24000
+ n_samples = int(sr * duration_s)
+ t = np.linspace(0, duration_s, n_samples, dtype=np.float32)
+ tone = np.sin(2 * np.pi * 220 * t) * 0.3
+ noise = np.random.default_rng(42).standard_normal(n_samples).astype(np.float32) * 0.15
+ pcm_float = tone + noise
+ pcm_int16 = (pcm_float * 32767).clip(-32768, 32767).astype(np.int16)
+ head_wobbler.reset()
+ head_wobbler.feed_pcm(pcm_int16, sr)
+ return JSONResponse({"ok": True, "message": "Speech test started."})
+
+ self._settings_initialized = True
+
+ def launch(self) -> None:
+ """Start the recorder/player and run the async processing loops."""
+ self._stop_event.clear()
+
+ self._reload_openwebui_settings_from_disk()
+
+ if not self._has_saved_openwebui_settings():
+ if self._settings_app is None:
+ raise RuntimeError(
+ "OpenWebUI settings are missing. Create "
+ "~/.config/settings/.env with "
+ "OPENWEBUI_URL and OPENWEB_LOADED_LLM."
+ )
+ logger.warning("OpenWebUI settings are missing. Open the app page and save settings.")
+ else:
+ logger.info(
+ "Saved OpenWebUI settings found; waiting for Start (model=%s, url=%s).",
+ config.OPENWEBUI_MODEL,
+ config.OPENWEBUI_URL,
+ )
+
+ async def _main_loop() -> None:
+ """Run persistent loop that supports stop/restart cycles."""
+ loop = asyncio.get_running_loop()
+ self._asyncio_loop = loop # type: ignore[assignment]
+
+ while True:
+ # Clear any leftover stop signal from previous pipeline cycle.
+ # close() sets both _stop_event AND _start_event to unblock,
+ # so a fresh _stop_event during the wait means full shutdown.
+ self._stop_event.clear()
+
+ # Wait for the settings page Start action.
+ while not self._start_event.is_set():
+ if self._stop_event.is_set():
+ break
+ await asyncio.sleep(0.1)
+
+ # If stop was requested while waiting, exit the loop (full shutdown)
+ if self._stop_event.is_set():
+ break
+
+ self._pipeline_state = "running"
+
+ apply_audio_startup_config(self._robot, logger=logger)
+ self._robot.media.start_recording()
+ self._robot.media.start_playing()
+ await asyncio.sleep(1) # give pipelines time to start
+ logger.info(
+ "Reachy media ready: backend=%s input_sr=%s output_sr=%s",
+ self._robot.media.backend,
+ self._robot.media.get_input_audio_samplerate(),
+ self._robot.media.get_output_audio_samplerate(),
+ )
+
+ self._tasks = [
+ asyncio.create_task(self.handler.start_up(), name="local-handler"),
+ asyncio.create_task(self.record_loop(), name="stream-record-loop"),
+ asyncio.create_task(self.play_loop(), name="stream-play-loop"),
+ asyncio.create_task(self._agc_watchdog(), name="agc-watchdog"),
+ ]
+ try:
+ await asyncio.gather(*self._tasks)
+ except asyncio.CancelledError:
+ logger.info("Tasks cancelled during shutdown")
+ except SystemExit:
+ # A dependency (e.g. reachy_mini_toolbox) called exit()
+ logger.error("A dependency called exit() — caught to keep the app alive")
+ except Exception as e:
+ logger.error(f"Pipeline error: {e}", exc_info=True)
+ finally:
+ await self.handler.shutdown()
+ # Stop media here (same thread that started it — no race)
+ try:
+ self._robot.media.stop_recording()
+ except Exception as e:
+ logger.debug(f"Error stopping recording: {e}")
+ try:
+ self._robot.media.stop_playing()
+ except Exception as e:
+ logger.debug(f"Error stopping playback: {e}")
+
+ # If stop was not requested (tasks ended naturally), break out
+ if self._pipeline_state != "stopped":
+ break
+
+ logger.info("Pipeline stopped, awaiting next start signal...")
+
+ asyncio.run(_main_loop())
+
+ def close(self) -> None:
+ """Stop the stream and underlying media pipelines.
+
+ Called from the stop-event polling thread during full app shutdown.
+ Sets flags and schedules cancellation — media cleanup happens in
+ _main_loop() after tasks exit.
+ """
+ logger.info("Stopping LocalStream...")
+
+ # Signal async loops to stop
+ self._pipeline_state = "shutting_down"
+ self._stop_event.set()
+ # Unblock the wait-for-start loop so _main_loop can exit cleanly
+ self._start_event.set()
+
+ # Cancel all running tasks via the event loop thread
+ loop = self._asyncio_loop
+ if loop is not None and loop.is_running():
+ for task in self._tasks:
+ if not task.done():
+ loop.call_soon_threadsafe(task.cancel)
+
+ def clear_audio_queue(self) -> None:
+ """Flush the player's appsrc to drop any queued audio immediately."""
+ logger.info("Flushing player queue")
+ audio = getattr(self._robot.media, "audio", None)
+ if audio is not None:
+ if hasattr(audio, "clear_output_buffer") and callable(audio.clear_output_buffer):
+ audio.clear_output_buffer()
+ elif hasattr(audio, "clear_player") and callable(audio.clear_player):
+ audio.clear_player()
+ self.handler.output_queue = asyncio.Queue()
+
+ async def _agc_watchdog(self, interval_s: float = 20.0, gain: float = 5.0) -> None:
+ """Re-seed the XVF3800 AGC gain while the pipeline runs.
+
+ Residual echo of the robot's own speech makes the AGC wind its gain
+ toward zero over a few conversation turns, leaving the mic effectively
+ deaf. Recovery in silence takes minutes, so we periodically reset the
+ gain instead of trusting the adaptation.
+ """
+ while not self._stop_event.is_set():
+ await asyncio.sleep(interval_s)
+ try:
+ audio = getattr(self._robot.media, "audio", None)
+ apply_config = getattr(audio, "apply_audio_config", None)
+ if callable(apply_config):
+ await asyncio.to_thread(apply_config, (("PP_AGCGAIN", (gain,)),), verify=False)
+ logger.debug("AGC watchdog reseeded PP_AGCGAIN=%s", gain)
+ except Exception as exc:
+ logger.debug("AGC watchdog write failed: %s", exc)
+
+ async def record_loop(self) -> None:
+ """Read mic frames from the recorder and forward them to the handler."""
+ await self._record_loop_sdk()
+
+ async def _record_loop_sdk(self) -> None:
+ """Read mic frames via the robot SDK media backend."""
+ input_sample_rate = self._robot.media.get_input_audio_samplerate()
+ logger.info(f"record_loop (SDK) started (sample_rate={input_sample_rate})")
+
+ frame_count = 0
+ while not self._stop_event.is_set():
+ audio_frame = self._robot.media.get_audio_sample()
+ if audio_frame is not None:
+ frame_count += 1
+ if frame_count == 1 or frame_count % 500 == 0:
+ logger.info(f"record_loop (SDK): {frame_count} frames")
+ await self.handler.receive((input_sample_rate, audio_frame))
+ await asyncio.sleep(0)
+
+ logger.info(f"record_loop (SDK) exited (frames={frame_count})")
+
+ async def play_loop(self) -> None:
+ """Fetch outputs from the handler: log text and play audio frames."""
+ while not self._stop_event.is_set():
+ try:
+ handler_output = await asyncio.wait_for(self.handler.emit(), timeout=0.5)
+ except asyncio.TimeoutError:
+ continue
+
+ if isinstance(handler_output, AdditionalOutputs):
+ for msg in handler_output.args:
+ content = msg.get("content", "")
+ if isinstance(content, str):
+ clean_content = content.strip()
+ if clean_content:
+ role = str(msg.get("role") or "assistant")
+ if role not in {"user", "assistant"}:
+ role = "assistant"
+ self._transcript_messages.append({"role": role, "content": clean_content})
+ self._transcript_messages = self._transcript_messages[-20:]
+ logger.info(
+ "role=%s content=%s",
+ msg.get("role"),
+ content if len(content) < 500 else content[:500] + "…",
+ )
+
+ elif isinstance(handler_output, tuple):
+ input_sample_rate, audio_data = handler_output
+ output_sample_rate = self._robot.media.get_output_audio_samplerate()
+
+ if audio_data is None or getattr(audio_data, "size", 0) == 0:
+ logger.warning("Skipping empty speaker audio frame")
+ continue
+
+ # Reshape if needed
+ if audio_data.ndim == 2:
+ # Scipy channels last convention
+ if audio_data.shape[1] > audio_data.shape[0]:
+ audio_data = audio_data.T
+ # Multiple channels -> Mono channel
+ if audio_data.shape[1] > 1:
+ audio_data = audio_data[:, 0]
+
+ # Cast if needed
+ audio_frame = audio_to_float32(audio_data)
+
+ # Resample if needed
+ if input_sample_rate != output_sample_rate:
+ num_samples = int(len(audio_frame) * output_sample_rate / input_sample_rate)
+ if num_samples <= 0:
+ logger.warning(
+ "Skipping speaker audio after resample calculation: in_sr=%s out_sr=%s len=%s",
+ input_sample_rate,
+ output_sample_rate,
+ len(audio_frame),
+ )
+ continue
+ audio_frame = resample(
+ audio_frame,
+ num_samples,
+ )
+
+ peak = float(np.max(np.abs(audio_frame))) if audio_frame.size else 0.0
+ rms = float(np.sqrt(np.mean(np.square(audio_frame)))) if audio_frame.size else 0.0
+ logger.info(
+ "Pushing speaker audio: in_sr=%s out_sr=%s shape=%s dtype=%s peak=%.4f rms=%.4f",
+ input_sample_rate,
+ output_sample_rate,
+ audio_frame.shape,
+ audio_frame.dtype,
+ peak,
+ rms,
+ )
+ self._robot.media.push_audio_sample(np.ascontiguousarray(audio_frame, dtype=np.float32))
+
+ else:
+ logger.debug("Ignoring output type=%s", type(handler_output).__name__)
+
+ await asyncio.sleep(0) # yield to event loop
diff --git a/src/Reachy_OpenWebUI/dance_emotion_moves.py b/src/Reachy_OpenWebUI/dance_emotion_moves.py
new file mode 100644
index 0000000000000000000000000000000000000000..48fabca9a10c3671b458af5a7ff650cd5fef60a0
--- /dev/null
+++ b/src/Reachy_OpenWebUI/dance_emotion_moves.py
@@ -0,0 +1,154 @@
+"""Dance and emotion moves for the movement queue system.
+
+This module implements dance moves and emotions as Move objects that can be queued
+and executed sequentially by the MovementManager.
+"""
+
+from __future__ import annotations
+import logging
+from typing import Tuple
+
+import numpy as np
+from numpy.typing import NDArray
+
+from reachy_mini.motion.move import Move
+from reachy_mini.motion.recorded_move import RecordedMoves
+from reachy_mini_dances_library.dance_move import DanceMove
+
+
+logger = logging.getLogger(__name__)
+
+
+class DanceQueueMove(Move):
+ """Wrapper for dance moves to work with the movement queue system."""
+
+ def __init__(self, move_name: str):
+ """Initialize a DanceQueueMove."""
+ self.dance_move = DanceMove(move_name)
+ self.move_name = move_name
+
+ @property
+ def duration(self) -> float:
+ """Duration property required by official Move interface."""
+ return float(self.dance_move.duration)
+
+ def evaluate(self, t: float) -> tuple[NDArray[np.float64] | None, NDArray[np.float64] | None, float | None]:
+ """Evaluate dance move at time t."""
+ try:
+ # Get the pose from the dance move
+ head_pose, antennas, body_yaw = self.dance_move.evaluate(t)
+
+ # Convert to numpy array if antennas is tuple and return in official Move format
+ if isinstance(antennas, tuple):
+ antennas = np.array([antennas[0], antennas[1]])
+
+ return (head_pose, antennas, body_yaw)
+
+ except Exception as e:
+ logger.error(f"Error evaluating dance move '{self.move_name}' at t={t}: {e}")
+ # Return neutral pose on error
+ from reachy_mini.utils import create_head_pose
+
+ neutral_head_pose = create_head_pose(0, 0, 0, 0, 0, 0, degrees=True)
+ return (neutral_head_pose, np.array([0.0, 0.0], dtype=np.float64), 0.0)
+
+
+class EmotionQueueMove(Move):
+ """Wrapper for emotion moves to work with the movement queue system."""
+
+ def __init__(self, emotion_name: str, recorded_moves: RecordedMoves):
+ """Initialize an EmotionQueueMove."""
+ self.emotion_move = recorded_moves.get(emotion_name)
+ self.emotion_name = emotion_name
+
+ @property
+ def duration(self) -> float:
+ """Duration property required by official Move interface."""
+ return float(self.emotion_move.duration)
+
+ def evaluate(self, t: float) -> tuple[NDArray[np.float64] | None, NDArray[np.float64] | None, float | None]:
+ """Evaluate emotion move at time t."""
+ try:
+ # Get the pose from the emotion move
+ head_pose, antennas, body_yaw = self.emotion_move.evaluate(t)
+
+ # Convert to numpy array if antennas is tuple and return in official Move format
+ if isinstance(antennas, tuple):
+ antennas = np.array([antennas[0], antennas[1]])
+
+ return (head_pose, antennas, body_yaw)
+
+ except Exception as e:
+ logger.error(f"Error evaluating emotion '{self.emotion_name}' at t={t}: {e}")
+ # Return neutral pose on error
+ from reachy_mini.utils import create_head_pose
+
+ neutral_head_pose = create_head_pose(0, 0, 0, 0, 0, 0, degrees=True)
+ return (neutral_head_pose, np.array([0.0, 0.0], dtype=np.float64), 0.0)
+
+
+class GotoQueueMove(Move):
+ """Wrapper for goto moves to work with the movement queue system."""
+
+ def __init__(
+ self,
+ target_head_pose: NDArray[np.float32],
+ start_head_pose: NDArray[np.float32] | None = None,
+ target_antennas: Tuple[float, float] = (0, 0),
+ start_antennas: Tuple[float, float] | None = None,
+ target_body_yaw: float = 0,
+ start_body_yaw: float | None = None,
+ duration: float = 1.0,
+ ):
+ """Initialize a GotoQueueMove."""
+ self._duration = duration
+ self.target_head_pose = target_head_pose
+ self.start_head_pose = start_head_pose
+ self.target_antennas = target_antennas
+ self.start_antennas = start_antennas or (0, 0)
+ self.target_body_yaw = target_body_yaw
+ self.start_body_yaw = start_body_yaw or 0
+
+ @property
+ def duration(self) -> float:
+ """Duration property required by official Move interface."""
+ return self._duration
+
+ def evaluate(self, t: float) -> tuple[NDArray[np.float64] | None, NDArray[np.float64] | None, float | None]:
+ """Evaluate goto move at time t using linear interpolation."""
+ try:
+ from reachy_mini.utils import create_head_pose
+ from reachy_mini.utils.interpolation import linear_pose_interpolation
+
+ # Clamp t to [0, 1] for interpolation
+ t_clamped = max(0, min(1, t / self.duration))
+
+ # Use start pose if available, otherwise neutral
+ if self.start_head_pose is not None:
+ start_pose = self.start_head_pose
+ else:
+ start_pose = create_head_pose(0, 0, 0, 0, 0, 0, degrees=True)
+
+ # Interpolate head pose
+ head_pose = linear_pose_interpolation(start_pose, self.target_head_pose, t_clamped)
+
+ # Interpolate antennas - return as numpy array
+ antennas = np.array(
+ [
+ self.start_antennas[0] + (self.target_antennas[0] - self.start_antennas[0]) * t_clamped,
+ self.start_antennas[1] + (self.target_antennas[1] - self.start_antennas[1]) * t_clamped,
+ ],
+ dtype=np.float64,
+ )
+
+ # Interpolate body yaw
+ body_yaw = self.start_body_yaw + (self.target_body_yaw - self.start_body_yaw) * t_clamped
+
+ return (head_pose, antennas, body_yaw)
+
+ except Exception as e:
+ logger.error(f"Error evaluating goto move at t={t}: {e}")
+ # Return target pose on error - convert to float64
+ target_head_pose_f64 = self.target_head_pose.astype(np.float64)
+ target_antennas_array = np.array([self.target_antennas[0], self.target_antennas[1]], dtype=np.float64)
+ return (target_head_pose_f64, target_antennas_array, self.target_body_yaw)
diff --git a/src/Reachy_OpenWebUI/images/astronaut.png b/src/Reachy_OpenWebUI/images/astronaut.png
new file mode 100644
index 0000000000000000000000000000000000000000..904629d8dbc6c817b573dfe1028ab05396950d5e
--- /dev/null
+++ b/src/Reachy_OpenWebUI/images/astronaut.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:8696cef88041c72a51e9ee269b10b65813b88bd4df0e27a0b82faea9901cf136
+size 305845
diff --git a/src/Reachy_OpenWebUI/images/captain.png b/src/Reachy_OpenWebUI/images/captain.png
new file mode 100644
index 0000000000000000000000000000000000000000..c881d29bb4d3ec157055ab34df083ba22f1297d4
--- /dev/null
+++ b/src/Reachy_OpenWebUI/images/captain.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:e0de7d69bc703b09358ec85e5fbd09758a054317d270b25db2ce701c44a36140
+size 352341
diff --git a/src/Reachy_OpenWebUI/images/cooking-chief.png b/src/Reachy_OpenWebUI/images/cooking-chief.png
new file mode 100644
index 0000000000000000000000000000000000000000..ee187301071f150bd46e5c8540d430e61c9cffb0
Binary files /dev/null and b/src/Reachy_OpenWebUI/images/cooking-chief.png differ
diff --git a/src/Reachy_OpenWebUI/images/cowboy.png b/src/Reachy_OpenWebUI/images/cowboy.png
new file mode 100644
index 0000000000000000000000000000000000000000..2dc20e4959d68cedc99849791262cb054f11f599
--- /dev/null
+++ b/src/Reachy_OpenWebUI/images/cowboy.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:580f9494599c208c4d78391489b3bab87f05a26524a2fb14251d936957f6a52d
+size 464341
diff --git a/src/Reachy_OpenWebUI/images/explorer.png b/src/Reachy_OpenWebUI/images/explorer.png
new file mode 100644
index 0000000000000000000000000000000000000000..12c6b43646889648a75b3ef8bd7f14e564d44709
--- /dev/null
+++ b/src/Reachy_OpenWebUI/images/explorer.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:607e0816a406bf1ee95eeb6140e7e08592967294c12ef926b1b3fa9b6a1fdf34
+size 309990
diff --git a/src/Reachy_OpenWebUI/images/farmer-2sejRPMv.png b/src/Reachy_OpenWebUI/images/farmer-2sejRPMv.png
new file mode 100644
index 0000000000000000000000000000000000000000..822e92a306d683f3353040dc7f13544c15ab04f4
--- /dev/null
+++ b/src/Reachy_OpenWebUI/images/farmer-2sejRPMv.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:e14661b2ba8b26f0cb69d9ba7d36bc246c2faa8970df353ae07eb1eb6c02ff3b
+size 100908
diff --git a/src/Reachy_OpenWebUI/images/fisherman.png b/src/Reachy_OpenWebUI/images/fisherman.png
new file mode 100644
index 0000000000000000000000000000000000000000..f54f73ecd68f887a34bc894153e0abb69fbfd6fa
Binary files /dev/null and b/src/Reachy_OpenWebUI/images/fisherman.png differ
diff --git a/src/Reachy_OpenWebUI/images/jazzman.png b/src/Reachy_OpenWebUI/images/jazzman.png
new file mode 100644
index 0000000000000000000000000000000000000000..237d1b2cc10f3be4e5b64fab67db42dce6e12cc7
Binary files /dev/null and b/src/Reachy_OpenWebUI/images/jazzman.png differ
diff --git a/src/Reachy_OpenWebUI/images/plumber.png b/src/Reachy_OpenWebUI/images/plumber.png
new file mode 100644
index 0000000000000000000000000000000000000000..8c84db1f1a56f8ee5cedcb9e54b1ab615d1817fc
--- /dev/null
+++ b/src/Reachy_OpenWebUI/images/plumber.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:566f4854832a371d0e6f913cad89d99acc4e5f0fd04d83a4eb0de1cee9220aca
+size 521369
diff --git a/src/Reachy_OpenWebUI/images/reachy hat.png b/src/Reachy_OpenWebUI/images/reachy hat.png
new file mode 100644
index 0000000000000000000000000000000000000000..e07e6344a1e19b9af8f2ee89ea8f6a059ea38d6e
Binary files /dev/null and b/src/Reachy_OpenWebUI/images/reachy hat.png differ
diff --git a/src/Reachy_OpenWebUI/images/reachy-conversation-app.jpg b/src/Reachy_OpenWebUI/images/reachy-conversation-app.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..4a931c38b76d11ea831c2118b28c25561725352a
--- /dev/null
+++ b/src/Reachy_OpenWebUI/images/reachy-conversation-app.jpg
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:0245adfd5b60c2c21bc4ae8f6e31f9565b2a35915c1f171a0538c46ecfc40e70
+size 160198
diff --git a/src/Reachy_OpenWebUI/images/reachy-conversation-app.png b/src/Reachy_OpenWebUI/images/reachy-conversation-app.png
new file mode 100644
index 0000000000000000000000000000000000000000..a6e7a2f91aeef7c19f70652c8d95d149361a04df
--- /dev/null
+++ b/src/Reachy_OpenWebUI/images/reachy-conversation-app.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:8871402e4daf8ae34d56a1139f2b604f6c4dbea4fcc00676a5f2ef0a4c55d4ea
+size 543890
diff --git a/src/Reachy_OpenWebUI/images/reachy-how-to-create-app.png b/src/Reachy_OpenWebUI/images/reachy-how-to-create-app.png
new file mode 100644
index 0000000000000000000000000000000000000000..e1d6aa54c855f8e7fde52c02c0e867ab4901425b
--- /dev/null
+++ b/src/Reachy_OpenWebUI/images/reachy-how-to-create-app.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:2239f9d309419548d12d1c5390e22f502cffc7e845a68236efef6870b197c960
+size 267000
diff --git a/src/Reachy_OpenWebUI/images/reachy-icon.png b/src/Reachy_OpenWebUI/images/reachy-icon.png
new file mode 100644
index 0000000000000000000000000000000000000000..24db9c22469d3c688e1684b6c4e5dfa50be0b067
--- /dev/null
+++ b/src/Reachy_OpenWebUI/images/reachy-icon.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:fe759feac4ae559f25922014942350c24c8475d1e9309aa4c435bef8c7aabfdc
+size 119704
diff --git a/src/Reachy_OpenWebUI/images/reachymini_avatar.png b/src/Reachy_OpenWebUI/images/reachymini_avatar.png
new file mode 100644
index 0000000000000000000000000000000000000000..cb6dee522f40a200b6ddadc13b2afecefbf14f78
--- /dev/null
+++ b/src/Reachy_OpenWebUI/images/reachymini_avatar.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:5a63ac8802ff3542f01292c431c5278296880d74cd3580d219fcf4827bc235f9
+size 1228716
diff --git a/src/Reachy_OpenWebUI/images/sleeping-reachy.png b/src/Reachy_OpenWebUI/images/sleeping-reachy.png
new file mode 100644
index 0000000000000000000000000000000000000000..055a9d4facd3ff3666622f83250e0467950efed2
--- /dev/null
+++ b/src/Reachy_OpenWebUI/images/sleeping-reachy.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:ddedcb1f98fb030f45c9af3f974606d7f0d2cc00edf2167eecf02d2cd76c2ad3
+size 346058
diff --git a/src/Reachy_OpenWebUI/images/user_avatar.png b/src/Reachy_OpenWebUI/images/user_avatar.png
new file mode 100644
index 0000000000000000000000000000000000000000..c297bda9088aa6961fe49c3176ec20a0886149be
--- /dev/null
+++ b/src/Reachy_OpenWebUI/images/user_avatar.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:e97ca125a86bacdaa41c8dca88abd9ca746fd5c9391eda24249c012432b0219b
+size 1111878
diff --git a/src/Reachy_OpenWebUI/main.py b/src/Reachy_OpenWebUI/main.py
new file mode 100644
index 0000000000000000000000000000000000000000..23bc028fb766c57e9c599c417ead2e9bffc8acdb
--- /dev/null
+++ b/src/Reachy_OpenWebUI/main.py
@@ -0,0 +1,181 @@
+"""Entrypoint for the Reachy Mini conversation app."""
+
+import sys
+import time
+import asyncio
+import argparse
+import threading
+from typing import Any, Optional
+from pathlib import Path
+
+from fastapi import FastAPI
+from reachy_mini import ReachyMini, ReachyMiniApp
+from Reachy_OpenWebUI.utils import (
+ parse_args,
+ setup_logger,
+ handle_vision_stuff,
+ log_connection_troubleshooting,
+)
+
+
+def main() -> None:
+ """Entrypoint for the Reachy Mini conversation app."""
+ args, _ = parse_args()
+ run(args)
+
+
+def run(
+ args: argparse.Namespace,
+ robot: Optional[ReachyMini] = None,
+ app_stop_event: Optional[threading.Event] = None,
+ settings_app: Optional[FastAPI] = None,
+ instance_path: Optional[str] = None,
+) -> None:
+ """Run the Reachy Mini conversation app."""
+ # Putting these dependencies here keeps package import light until the app actually runs.
+ from Reachy_OpenWebUI.moves import MovementManager
+ from Reachy_OpenWebUI.console import LocalStream
+ from Reachy_OpenWebUI.config import config
+ from Reachy_OpenWebUI.tools.core_tools import ToolDependencies
+ from Reachy_OpenWebUI.audio.attitude_wobbler import AttitudeHeadWobbler as HeadWobbler
+
+ logger = setup_logger(args.debug)
+ logger.info("Starting Reachy Mini Conversation App")
+
+ if robot is None:
+ try:
+ robot_kwargs = {}
+ if args.robot_name is not None:
+ robot_kwargs["robot_name"] = args.robot_name
+
+ logger.info("Initializing ReachyMini (SDK will auto-detect appropriate backend)")
+ robot = ReachyMini(**robot_kwargs)
+
+ except TimeoutError as e:
+ logger.error(f"Connection timeout: Failed to connect to Reachy Mini daemon. Details: {e}")
+ log_connection_troubleshooting(logger, args.robot_name)
+ sys.exit(1)
+
+ except ConnectionError as e:
+ logger.error(f"Connection failed: Unable to establish connection to Reachy Mini. Details: {e}")
+ log_connection_troubleshooting(logger, args.robot_name)
+ sys.exit(1)
+
+ except Exception as e:
+ logger.error(f"Unexpected error during robot initialization: {type(e).__name__}: {e}")
+ logger.error("Please check your configuration and try again.")
+ sys.exit(1)
+
+ camera_worker, vision_manager = handle_vision_stuff(args, robot)
+
+ movement_manager = MovementManager(
+ current_robot=robot,
+ idle_attitude=config.REACHY_IDLE_ATTITUDE,
+ )
+
+ head_wobbler = HeadWobbler(
+ set_speech_offsets=movement_manager.set_speech_offsets,
+ attitude=config.REACHY_IDLE_ATTITUDE,
+ )
+
+
+ deps = ToolDependencies(
+ reachy_mini=robot,
+ movement_manager=movement_manager,
+ camera_worker=camera_worker,
+ vision_manager=vision_manager,
+ head_wobbler=head_wobbler,
+ )
+
+ from Reachy_OpenWebUI.sub_apps.conversation_app.local.handler import LocalSessionHandler
+
+ logger.info("Using OpenWebUI conversation pipeline")
+ handler: Any = LocalSessionHandler(deps)
+ deps.handler = handler
+
+ # Headless mode: settings are loaded from the stable OpenWebUI env file.
+ stream_manager = LocalStream(
+ handler,
+ robot,
+ settings_app=settings_app,
+ instance_path=instance_path,
+ )
+
+ # Each async service → its own thread/loop
+ movement_manager.start()
+ head_wobbler.start()
+ if camera_worker:
+ camera_worker.start()
+ if vision_manager:
+ vision_manager.start()
+
+ def poll_stop_event() -> None:
+ """Poll the stop event to allow graceful shutdown."""
+ if app_stop_event is not None:
+ app_stop_event.wait()
+
+ logger.info("App stop event detected, shutting down...")
+ try:
+ stream_manager.close()
+ except Exception as e:
+ logger.error(f"Error while closing stream manager: {e}")
+
+ if app_stop_event:
+ threading.Thread(target=poll_stop_event, daemon=True).start()
+
+ try:
+ stream_manager.launch()
+ except KeyboardInterrupt:
+ logger.info("Keyboard interruption in main thread... closing server.")
+ finally:
+ movement_manager.stop()
+ head_wobbler.stop()
+ if camera_worker:
+ camera_worker.stop()
+ if vision_manager:
+ vision_manager.stop()
+
+ # Ensure media is explicitly closed before disconnecting
+ try:
+ robot.media.close()
+ except Exception as e:
+ logger.debug(f"Error closing media during shutdown: {e}")
+
+ # prevent connection to keep alive some threads
+ robot.client.disconnect()
+ time.sleep(1)
+ logger.info("Shutdown complete.")
+
+
+class ReachyMiniConversationOpenWebUIApp(ReachyMiniApp):
+ """Reachy Mini Apps entry point for the local conversation app."""
+
+ custom_app_url = "http://0.0.0.0:7860/"
+ dont_start_webserver = False
+
+ def run(self, reachy_mini: ReachyMini, stop_event: threading.Event) -> None:
+ """Run the Reachy Mini conversation app."""
+ loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(loop)
+
+ args, _ = parse_args()
+
+ instance_path = self._get_instance_path().parent
+ run(
+ args,
+ robot=reachy_mini,
+ app_stop_event=stop_event,
+ settings_app=self.settings_app,
+ instance_path=instance_path,
+ )
+
+
+if __name__ == "__main__":
+ app = ReachyMiniConversationOpenWebUIApp()
+ try:
+ app.wrapped_run()
+ except KeyboardInterrupt:
+ app.stop()
+
+
+ReachyMiniConversationApp = ReachyMiniConversationOpenWebUIApp
diff --git a/src/Reachy_OpenWebUI/motion_patterns.py b/src/Reachy_OpenWebUI/motion_patterns.py
new file mode 100644
index 0000000000000000000000000000000000000000..74c95979432ef9fa1c0e6207e9d61b956988c724
--- /dev/null
+++ b/src/Reachy_OpenWebUI/motion_patterns.py
@@ -0,0 +1,113 @@
+"""Reusable procedural motion patterns for Reachy Mini.
+
+These are lightweight math patterns, not recorded movement assets. They are
+intended for app cues like scanning, idle accents, and simple expressive motion.
+"""
+
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass
+from typing import Callable
+
+import numpy as np
+from numpy.typing import NDArray
+
+from reachy_mini.motion.move import Move
+from reachy_mini.utils import create_head_pose
+
+
+FullBodyPose = tuple[NDArray[np.float64] | None, NDArray[np.float64] | None, float | None]
+PatternFn = Callable[[float], FullBodyPose]
+
+
+@dataclass(frozen=True)
+class PatternSpec:
+ name: str
+ pattern: PatternFn
+ duration_s: float = 1.5
+
+
+class ProceduralPatternMove(Move):
+ """Queueable Reachy move backed by a procedural pattern function."""
+
+ def __init__(self, spec: PatternSpec):
+ self.spec = spec
+
+ @property
+ def duration(self) -> float:
+ return self.spec.duration_s
+
+ def evaluate(self, t: float) -> FullBodyPose:
+ t = max(0.0, min(float(t), self.duration))
+ return self.spec.pattern(t)
+
+
+def _wave(t: float, frequency_hz: float, phase_rad: float = 0.0) -> float:
+ return math.sin(2.0 * math.pi * frequency_hz * t + phase_rad)
+
+
+def sway(t: float) -> FullBodyPose:
+ yaw_deg = 18.0 * _wave(t, 0.28)
+ roll_deg = 4.0 * _wave(t, 0.28, math.pi / 2.0)
+ antennas = np.deg2rad([18.0 * _wave(t, 0.55), -18.0 * _wave(t, 0.55)])
+ return create_head_pose(0, 0, 0, roll_deg, 0, yaw_deg, degrees=True), antennas, 0.0
+
+
+def nod(t: float) -> FullBodyPose:
+ pitch_deg = -8.0 + 10.0 * _wave(t, 0.75)
+ antennas = np.deg2rad([8.0 * _wave(t, 0.75), -8.0 * _wave(t, 0.75)])
+ return create_head_pose(0, 0, 0, 0, pitch_deg, 0, degrees=True), antennas, 0.0
+
+
+def circle(t: float) -> FullBodyPose:
+ frequency_hz = 0.22
+ pitch_deg = 8.0 * math.sin(2.0 * math.pi * frequency_hz * t)
+ yaw_deg = 16.0 * math.cos(2.0 * math.pi * frequency_hz * t)
+ roll_deg = 5.0 * math.sin(2.0 * math.pi * frequency_hz * t + math.pi / 2.0)
+ antennas = np.deg2rad([12.0 * _wave(t, 0.44), -12.0 * _wave(t, 0.44)])
+ return create_head_pose(0, 0, 0, roll_deg, pitch_deg, yaw_deg, degrees=True), antennas, 0.0
+
+
+def breathe(t: float) -> FullBodyPose:
+ z_m = 0.005 * _wave(t, 0.1)
+ pitch_deg = 1.2 * _wave(t, 0.1, math.pi / 2.0)
+ antennas = np.deg2rad([10.0 * _wave(t, 0.35), -10.0 * _wave(t, 0.35)])
+ return create_head_pose(0, 0, z_m, 0, pitch_deg, 0, degrees=True, mm=False), antennas, 0.0
+
+
+def figure8(t: float) -> FullBodyPose:
+ frequency_hz = 0.18
+ yaw_deg = 18.0 * math.sin(2.0 * math.pi * frequency_hz * t)
+ pitch_deg = 7.0 * math.sin(4.0 * math.pi * frequency_hz * t)
+ roll_deg = 3.0 * math.cos(2.0 * math.pi * frequency_hz * t)
+ antennas = np.deg2rad([16.0 * _wave(t, 0.36), -16.0 * _wave(t, 0.36)])
+ return create_head_pose(0, 0, 0, roll_deg, pitch_deg, yaw_deg, degrees=True), antennas, 0.0
+
+
+def look_around(t: float) -> FullBodyPose:
+ yaw_deg = 28.0 * _wave(t, 0.32)
+ pitch_deg = -28.0 + 5.0 * _wave(t, 0.16, math.pi / 2.0)
+ z_m = 0.035
+ antenna_left_deg = 140.0 * _wave(t, 0.55)
+ antenna_right_deg = -135.0 * _wave(t, 0.55, math.radians(6.0))
+ antennas = np.deg2rad([antenna_left_deg, antenna_right_deg])
+ return create_head_pose(0, 0, z_m, 0, pitch_deg, yaw_deg, degrees=True, mm=False), antennas, 0.0
+
+
+PATTERNS: dict[str, PatternFn] = {
+ "sway": sway,
+ "nod": nod,
+ "circle": circle,
+ "breathe": breathe,
+ "figure8": figure8,
+ "lookAround": look_around,
+}
+
+
+def make_pattern_move(name: str, duration_s: float = 1.5) -> ProceduralPatternMove:
+ try:
+ pattern = PATTERNS[name]
+ except KeyError as exc:
+ raise ValueError(f"Unknown motion pattern '{name}'. Available: {sorted(PATTERNS)}") from exc
+ return ProceduralPatternMove(PatternSpec(name=name, pattern=pattern, duration_s=duration_s))
diff --git a/src/Reachy_OpenWebUI/moves.py b/src/Reachy_OpenWebUI/moves.py
new file mode 100644
index 0000000000000000000000000000000000000000..7784cc1f8b76537f37aa000b538f326e4063a970
--- /dev/null
+++ b/src/Reachy_OpenWebUI/moves.py
@@ -0,0 +1,910 @@
+"""Movement system with sequential primary moves and additive secondary moves.
+
+Design overview
+- Primary moves (emotions, dances, goto, breathing) are mutually exclusive and run
+ sequentially.
+- Secondary moves (speech sway) are additive offsets applied on top of the current
+ primary pose.
+- There is a single control point to the robot: `ReachyMini.set_target`.
+- The control loop runs near 100 Hz and is phase-aligned via a monotonic clock.
+- Idle behaviour starts an infinite `BreathingMove` after a short inactivity delay
+ unless listening is active.
+
+Threading model
+- A dedicated worker thread owns all real-time state and issues `set_target`
+ commands.
+- Other threads communicate via a command queue (enqueue moves, mark activity,
+ toggle listening).
+- Secondary offset producers set pending values guarded by locks; the worker
+ snaps them atomically.
+
+Units and frames
+- Secondary offsets are interpreted as metres for x/y/z and radians for
+ roll/pitch/yaw in the world frame (unless noted by `compose_world_offset`).
+- Antennas and `body_yaw` are in radians.
+- Head pose composition uses `compose_world_offset(primary_head, secondary_head)`;
+ the secondary offset must therefore be expressed in the world frame.
+
+Gaze stabilisation
+- The head is world-stabilised — the body base can rotate underneath and the
+ head keeps pointing at the same target (like a camera gimbal / chicken head).
+- body_yaw sway is cosmetic (visual personality); it does NOT shift the camera
+ view or change where the robot appears to look.
+- Head yaw/pitch/roll directly move the gaze. Small yaw values are very
+ visible because nothing else moves with them. Prefer pitch (nod) and roll
+ (tilt) for natural speech motion; use yaw sparingly.
+- Antenna servos are NOT symmetric between left (ID 18) and right — negating
+ a left value does not produce a perfect visual mirror. Tune on hardware.
+
+Safety
+- Listening freezes antennas, then blends them back on unfreeze.
+- Interpolations and blends are used to avoid jumps at all times.
+- `set_target` errors are rate-limited in logs.
+"""
+
+from __future__ import annotations
+import time
+import logging
+import threading
+from queue import Empty, Queue
+from typing import Any, Dict, Tuple
+from collections import deque
+from dataclasses import dataclass
+
+import numpy as np
+from numpy.typing import NDArray
+
+from reachy_mini import ReachyMini
+from reachy_mini.utils import create_head_pose
+from reachy_mini.motion.move import Move
+from reachy_mini.utils.interpolation import (
+ compose_world_offset,
+ linear_pose_interpolation,
+)
+
+from Reachy_OpenWebUI.sub_apps.attitudes import ATTITUDE_PROFILES, AttitudeProfile, available_attitudes, resolve_attitude
+
+
+logger = logging.getLogger(__name__)
+
+# Configuration constants
+CONTROL_LOOP_FREQUENCY_HZ = 100.0 # Hz - Target frequency for the movement control loop
+
+# Type definitions
+FullBodyPose = Tuple[NDArray[np.float32], Tuple[float, float], float] # (head_pose_4x4, antennas, body_yaw)
+
+
+IdleAttitudeProfile = AttitudeProfile
+IDLE_ATTITUDE_PROFILES = ATTITUDE_PROFILES
+
+
+def available_idle_attitudes() -> list[dict[str, str]]:
+ """Return available idle attitude profiles for settings UI."""
+ return available_attitudes()
+
+
+def resolve_idle_attitude(name: str | None) -> IdleAttitudeProfile:
+ """Resolve a configured idle attitude name, falling back to calm."""
+ return resolve_attitude(name)
+
+
+class BreathingMove(Move):
+ """Breathing move with interpolation to neutral and then continuous breathing patterns."""
+
+ def __init__(
+ self,
+ interpolation_start_pose: NDArray[np.float32],
+ interpolation_start_antennas: Tuple[float, float],
+ profile: IdleAttitudeProfile | None = None,
+ ):
+ """Initialize breathing move.
+
+ Args:
+ interpolation_start_pose: 4x4 matrix of current head pose to interpolate from
+ interpolation_start_antennas: Current antenna positions to interpolate from
+ interpolation_duration: Duration of interpolation to neutral (seconds)
+
+ """
+ self.profile = profile or IDLE_ATTITUDE_PROFILES["calm"]
+ self.interpolation_start_pose = interpolation_start_pose
+ self.interpolation_start_antennas = np.array(interpolation_start_antennas)
+ self.interpolation_duration = self.profile.interpolation_s
+
+ # Attitude base pose. The continuous idle sway below moves around this
+ # posture so each attitude has a recognizable resting silhouette.
+ self.neutral_head_pose = create_head_pose(
+ x=self.profile.base_x_m,
+ y=self.profile.base_y_m,
+ z=self.profile.base_z_m,
+ roll=self.profile.base_roll_deg,
+ pitch=self.profile.base_pitch_deg,
+ yaw=self.profile.base_yaw_deg,
+ degrees=True,
+ mm=False,
+ )
+ self.neutral_antennas = np.array(
+ [
+ np.deg2rad(self.profile.base_left_antenna_deg),
+ np.deg2rad(self.profile.base_right_antenna_deg),
+ ],
+ dtype=np.float64,
+ )
+
+ @property
+ def duration(self) -> float:
+ """Duration property required by official Move interface."""
+ return float("inf") # Continuous breathing (never ends naturally)
+
+ def evaluate(self, t: float) -> tuple[NDArray[np.float64] | None, NDArray[np.float64] | None, float | None]:
+ """Evaluate breathing move at time t."""
+ if t < self.interpolation_duration:
+ # Phase 1: Interpolate to neutral base position
+ interpolation_t = t / self.interpolation_duration
+
+ # Interpolate head pose
+ head_pose = linear_pose_interpolation(
+ self.interpolation_start_pose,
+ self.neutral_head_pose,
+ interpolation_t,
+ )
+
+ # Interpolate antennas
+ antennas_interp = (
+ 1 - interpolation_t
+ ) * self.interpolation_start_antennas + interpolation_t * self.neutral_antennas
+ antennas = antennas_interp.astype(np.float64)
+
+ else:
+ # Phase 2: Breathing patterns from neutral base
+ breathing_time = t - self.interpolation_duration
+ profile = self.profile
+
+ # Gentle continuous idle motion.
+ z_offset = profile.breathing_z_amplitude_m * np.sin(
+ 2 * np.pi * profile.breathing_frequency_hz * breathing_time
+ )
+ x_offset = profile.x_sway_m * np.sin(2 * np.pi * profile.head_sway_frequency_hz * breathing_time)
+ y_offset = profile.y_sway_m * np.cos(2 * np.pi * profile.head_sway_frequency_hz * breathing_time)
+ roll = np.deg2rad(profile.roll_sway_deg) * np.sin(
+ 2 * np.pi * profile.head_sway_frequency_hz * breathing_time
+ )
+ pitch = np.deg2rad(profile.pitch_sway_deg) * np.cos(
+ 2 * np.pi * profile.head_sway_frequency_hz * breathing_time
+ )
+ yaw = np.deg2rad(profile.yaw_sway_deg) * np.sin(
+ 2 * np.pi * profile.head_sway_frequency_hz * breathing_time
+ )
+ head_pose = create_head_pose(
+ x=profile.base_x_m + x_offset,
+ y=profile.base_y_m + y_offset,
+ z=profile.base_z_m + z_offset,
+ roll=np.deg2rad(profile.base_roll_deg) + roll,
+ pitch=np.deg2rad(profile.base_pitch_deg) + pitch,
+ yaw=np.deg2rad(profile.base_yaw_deg) + yaw,
+ degrees=False,
+ mm=False,
+ )
+
+ # Antenna sway
+ antenna_sway = np.deg2rad(profile.antenna_sway_deg) * np.sin(
+ 2 * np.pi * profile.antenna_frequency_hz * breathing_time
+ )
+ if profile.antenna_sway_sync:
+ right_sway = antenna_sway
+ else:
+ right_sway = -antenna_sway
+ antennas = np.array(
+ [
+ np.deg2rad(profile.base_left_antenna_deg) + antenna_sway,
+ np.deg2rad(profile.base_right_antenna_deg) + right_sway,
+ ],
+ dtype=np.float64,
+ )
+
+ # Return in official Move interface format: (head_pose, antennas_array, body_yaw)
+ body_time = max(0.0, t - self.interpolation_duration)
+ body_yaw = np.deg2rad(self.profile.base_body_yaw_deg) + np.deg2rad(
+ self.profile.body_yaw_sway_deg
+ ) * np.sin(2 * np.pi * self.profile.body_yaw_frequency_hz * body_time)
+ return (head_pose, antennas, float(body_yaw))
+
+
+def combine_full_body(primary_pose: FullBodyPose, secondary_pose: FullBodyPose) -> FullBodyPose:
+ """Combine primary and secondary full body poses.
+
+ Args:
+ primary_pose: (head_pose, antennas, body_yaw) - primary move
+ secondary_pose: (head_pose, antennas, body_yaw) - secondary offsets
+
+ Returns:
+ Combined full body pose (head_pose, antennas, body_yaw)
+
+ """
+ primary_head, primary_antennas, primary_body_yaw = primary_pose
+ secondary_head, secondary_antennas, secondary_body_yaw = secondary_pose
+
+ # Combine head poses using compose_world_offset; the secondary pose must be an
+ # offset expressed in the world frame (T_off_world) applied to the absolute
+ # primary transform (T_abs).
+ combined_head = compose_world_offset(primary_head, secondary_head, reorthonormalize=True)
+
+ # Sum antennas and body_yaw
+ combined_antennas = (
+ primary_antennas[0] + secondary_antennas[0],
+ primary_antennas[1] + secondary_antennas[1],
+ )
+ combined_body_yaw = primary_body_yaw + secondary_body_yaw
+
+ return (combined_head, combined_antennas, combined_body_yaw)
+
+
+def clone_full_body_pose(pose: FullBodyPose) -> FullBodyPose:
+ """Create a deep copy of a full body pose tuple."""
+ head, antennas, body_yaw = pose
+ return (head.copy(), (float(antennas[0]), float(antennas[1])), float(body_yaw))
+
+
+@dataclass
+class MovementState:
+ """State tracking for the movement system."""
+
+ # Primary move state
+ current_move: Move | None = None
+ move_start_time: float | None = None
+ last_activity_time: float = 0.0
+
+ # Secondary move state (offsets)
+ speech_offsets: Tuple[float, float, float, float, float, float] = (
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ )
+ # Status flags
+ last_primary_pose: FullBodyPose | None = None
+
+ def update_activity(self) -> None:
+ """Update the last activity time."""
+ self.last_activity_time = time.monotonic()
+
+
+@dataclass
+class LoopFrequencyStats:
+ """Track rolling loop frequency statistics."""
+
+ mean: float = 0.0
+ m2: float = 0.0
+ min_freq: float = float("inf")
+ count: int = 0
+ last_freq: float = 0.0
+ potential_freq: float = 0.0
+
+ def reset(self) -> None:
+ """Reset accumulators while keeping the last potential frequency."""
+ self.mean = 0.0
+ self.m2 = 0.0
+ self.min_freq = float("inf")
+ self.count = 0
+
+
+class MovementManager:
+ """Coordinate sequential moves, additive offsets, and robot output at 100 Hz.
+
+ Responsibilities:
+ - Own a real-time loop that samples the current primary move (if any), fuses
+ secondary offsets, and calls `set_target` exactly once per tick.
+ - Start an idle `BreathingMove` after `idle_inactivity_delay` when not
+ listening and no moves are queued.
+ - Expose thread-safe APIs so other threads can enqueue moves, mark activity,
+ or feed secondary offsets without touching internal state.
+
+ Timing:
+ - All elapsed-time calculations rely on `time.monotonic()` through `self._now`
+ to avoid wall-clock jumps.
+ - The loop attempts 100 Hz
+
+ Concurrency:
+ - External threads communicate via `_command_queue` messages.
+ - Secondary offsets are staged via dirty flags guarded by locks and consumed
+ atomically inside the worker loop.
+ """
+
+ def __init__(
+ self,
+ current_robot: ReachyMini,
+ idle_attitude: str = "calm",
+ ):
+ """Initialize movement manager."""
+ self.current_robot = current_robot
+
+ # Single timing source for durations
+ self._now = time.monotonic
+
+ # Movement state
+ self.state = MovementState()
+ self.state.last_activity_time = self._now()
+ neutral_pose = create_head_pose(0, 0, 0, 0, 0, 0, degrees=True)
+ self.state.last_primary_pose = (neutral_pose, (0.0, 0.0), 0.0)
+
+ # Move queue (primary moves)
+ self.move_queue: deque[Move] = deque()
+
+ # Configuration
+ self.idle_profile = resolve_idle_attitude(idle_attitude)
+ self.idle_inactivity_delay = self.idle_profile.idle_delay_s
+ self.target_frequency = CONTROL_LOOP_FREQUENCY_HZ
+ self.target_period = 1.0 / self.target_frequency
+
+ self._stop_event = threading.Event()
+ self._thread: threading.Thread | None = None
+ self._is_listening = False
+ self._last_commanded_pose: FullBodyPose = clone_full_body_pose(self.state.last_primary_pose)
+ self._listening_antennas: Tuple[float, float] = self._last_commanded_pose[1]
+ self._antenna_unfreeze_blend = 1.0
+ self._antenna_blend_duration = 0.4 # seconds to blend back after listening
+ self._last_listening_blend_time = self._now()
+ self._breathing_active = False # true when breathing move is running or queued
+ self._listening_debounce_s = 0.15
+ self._last_listening_toggle_time = self._now()
+ self._last_set_target_err = 0.0
+ self._set_target_err_interval = 1.0 # seconds between error logs
+ self._set_target_err_suppressed = 0
+ self._set_target_retry_after = 0.0
+
+ # Cross-thread signalling
+ self._command_queue: "Queue[Tuple[str, Any]]" = Queue()
+ self._speech_offsets_lock = threading.Lock()
+ self._pending_speech_offsets: Tuple[float, float, float, float, float, float] = (
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ )
+ self._speech_offsets_dirty = False
+
+ self._shared_state_lock = threading.Lock()
+ self._shared_last_activity_time = self.state.last_activity_time
+ self._shared_is_listening = self._is_listening
+ self._status_lock = threading.Lock()
+ self._freq_stats = LoopFrequencyStats()
+ self._freq_snapshot = LoopFrequencyStats()
+
+ def queue_move(self, move: Move) -> None:
+ """Queue a primary move to run after the currently executing one.
+
+ Thread-safe: the move is enqueued via the worker command queue so the
+ control loop remains the sole mutator of movement state.
+ """
+ self._command_queue.put(("queue_move", move))
+
+ def clear_move_queue(self) -> None:
+ """Stop the active move and discard any queued primary moves.
+
+ Thread-safe: executed by the worker thread via the command queue.
+ """
+ self._command_queue.put(("clear_queue", None))
+
+ def set_speech_offsets(self, offsets: Tuple[float, float, float, float, float, float]) -> None:
+ """Update speech-induced secondary offsets (x, y, z, roll, pitch, yaw).
+
+ Offsets are interpreted as metres for translation and radians for
+ rotation in the world frame. Thread-safe via a pending snapshot.
+ """
+ with self._speech_offsets_lock:
+ self._pending_speech_offsets = offsets
+ self._speech_offsets_dirty = True
+
+ def set_moving_state(self, duration: float) -> None:
+ """Mark the robot as actively moving for the provided duration.
+
+ Legacy hook used by goto helpers to keep inactivity and breathing logic
+ aware of manual motions. Thread-safe via the command queue.
+ """
+ self._command_queue.put(("set_moving_state", duration))
+
+ def is_idle(self) -> bool:
+ """Return True when the robot has been inactive longer than the idle delay."""
+ with self._shared_state_lock:
+ last_activity = self._shared_last_activity_time
+ listening = self._shared_is_listening
+
+ if listening:
+ return False
+
+ return self._now() - last_activity >= self.idle_inactivity_delay
+
+ def set_idle_attitude(self, attitude: str) -> None:
+ """Set the automatic idle attitude profile."""
+ self._command_queue.put(("set_idle_attitude", attitude))
+
+ def set_listening(self, listening: bool) -> None:
+ """Enable or disable listening mode without touching shared state directly.
+
+ While listening:
+ - Antenna positions are frozen at the last commanded values.
+ - Blending is reset so that upon unfreezing the antennas return smoothly.
+ - Idle breathing is suppressed.
+
+ Thread-safe: the change is posted to the worker command queue.
+ """
+ with self._shared_state_lock:
+ if self._shared_is_listening == listening:
+ return
+ self._command_queue.put(("set_listening", listening))
+
+ def _poll_signals(self, current_time: float) -> None:
+ """Apply queued commands and pending offset updates."""
+ self._apply_pending_offsets()
+
+ while True:
+ try:
+ command, payload = self._command_queue.get_nowait()
+ except Empty:
+ break
+ self._handle_command(command, payload, current_time)
+
+ def _apply_pending_offsets(self) -> None:
+ """Apply the most recent speech/face offset updates."""
+ speech_offsets: Tuple[float, float, float, float, float, float] | None = None
+ with self._speech_offsets_lock:
+ if self._speech_offsets_dirty:
+ speech_offsets = self._pending_speech_offsets
+ self._speech_offsets_dirty = False
+
+ if speech_offsets is not None:
+ self.state.speech_offsets = speech_offsets
+ self.state.update_activity()
+
+ def _handle_command(self, command: str, payload: Any, current_time: float) -> None:
+ """Handle a single cross-thread command."""
+ if command == "queue_move":
+ if isinstance(payload, Move):
+ self.move_queue.append(payload)
+ self.state.update_activity()
+ duration = getattr(payload, "duration", None)
+ if duration is not None:
+ try:
+ duration_str = f"{float(duration):.2f}"
+ except (TypeError, ValueError):
+ duration_str = str(duration)
+ else:
+ duration_str = "?"
+ logger.debug(
+ "Queued move with duration %ss, queue size: %s",
+ duration_str,
+ len(self.move_queue),
+ )
+ else:
+ logger.warning("Ignored queue_move command with invalid payload: %s", payload)
+ elif command == "clear_queue":
+ self.move_queue.clear()
+ self.state.current_move = None
+ self.state.move_start_time = None
+ self._breathing_active = False
+ logger.info("Cleared move queue and stopped current move")
+ elif command == "set_moving_state":
+ try:
+ duration = float(payload)
+ except (TypeError, ValueError):
+ logger.warning("Invalid moving state duration: %s", payload)
+ return
+ self.state.update_activity()
+ elif command == "set_idle_attitude":
+ profile = resolve_idle_attitude(str(payload or ""))
+ if profile.name == self.idle_profile.name:
+ return
+ self.idle_profile = profile
+ self.idle_inactivity_delay = profile.idle_delay_s
+ if isinstance(self.state.current_move, BreathingMove):
+ self.state.current_move = None
+ self.state.move_start_time = None
+ self._breathing_active = False
+ self.state.update_activity()
+ logger.info("Idle attitude set to %s", profile.name)
+ elif command == "mark_activity":
+ self.state.update_activity()
+ elif command == "set_listening":
+ desired_state = bool(payload)
+ now = self._now()
+ if now - self._last_listening_toggle_time < self._listening_debounce_s:
+ return
+ self._last_listening_toggle_time = now
+
+ if self._is_listening == desired_state:
+ return
+
+ self._is_listening = desired_state
+ self._last_listening_blend_time = now
+ if desired_state:
+ # Freeze: snapshot current commanded antennas and reset blend
+ self._listening_antennas = (
+ float(self._last_commanded_pose[1][0]),
+ float(self._last_commanded_pose[1][1]),
+ )
+ self._antenna_unfreeze_blend = 0.0
+ else:
+ # Unfreeze: restart blending from frozen pose
+ self._antenna_unfreeze_blend = 0.0
+ self.state.update_activity()
+ else:
+ logger.warning("Unknown command received by MovementManager: %s", command)
+
+ def _publish_shared_state(self) -> None:
+ """Expose idle-related state for external threads."""
+ with self._shared_state_lock:
+ self._shared_last_activity_time = self.state.last_activity_time
+ self._shared_is_listening = self._is_listening
+
+ def _manage_move_queue(self, current_time: float) -> None:
+ """Manage the primary move queue (sequential execution)."""
+ if self.state.current_move is None or (
+ self.state.move_start_time is not None
+ and current_time - self.state.move_start_time >= self.state.current_move.duration
+ ):
+ self.state.current_move = None
+ self.state.move_start_time = None
+
+ if self.move_queue:
+ self.state.current_move = self.move_queue.popleft()
+ self.state.move_start_time = current_time
+ # Any real move cancels breathing mode flag
+ self._breathing_active = isinstance(self.state.current_move, BreathingMove)
+ logger.debug(f"Starting new move, duration: {self.state.current_move.duration}s")
+
+ def _manage_breathing(self, current_time: float) -> None:
+ """Manage automatic breathing when idle."""
+ if not self.idle_profile.enabled:
+ if isinstance(self.state.current_move, BreathingMove):
+ self.state.current_move = None
+ self.state.move_start_time = None
+ self._breathing_active = False
+ return
+
+ if (
+ self.state.current_move is None
+ and not self.move_queue
+ and not self._is_listening
+ and not self._breathing_active
+ ):
+ idle_for = current_time - self.state.last_activity_time
+ if idle_for >= self.idle_inactivity_delay:
+ try:
+ # These 2 functions return the latest available sensor data from the robot, but don't perform I/O synchronously.
+ # Therefore, we accept calling them inside the control loop.
+ _, current_antennas = self.current_robot.get_current_joint_positions()
+ current_head_pose = self.current_robot.get_current_head_pose()
+
+ self._breathing_active = True
+ self.state.update_activity()
+
+ breathing_move = BreathingMove(
+ interpolation_start_pose=current_head_pose,
+ interpolation_start_antennas=current_antennas,
+ profile=self.idle_profile,
+ )
+ self.move_queue.append(breathing_move)
+ logger.debug("Started breathing after %.1fs of inactivity", idle_for)
+ except Exception as e:
+ self._breathing_active = False
+ logger.error("Failed to start breathing: %s", e)
+
+ if isinstance(self.state.current_move, BreathingMove) and self.move_queue:
+ self.state.current_move = None
+ self.state.move_start_time = None
+ self._breathing_active = False
+ logger.debug("Stopping breathing due to new move activity")
+
+ if self.state.current_move is not None and not isinstance(self.state.current_move, BreathingMove):
+ self._breathing_active = False
+
+ def _get_primary_pose(self, current_time: float) -> FullBodyPose:
+ """Get the primary full body pose from current move or neutral."""
+ # When a primary move is playing, sample it and cache the resulting pose
+ if self.state.current_move is not None and self.state.move_start_time is not None:
+ move_time = current_time - self.state.move_start_time
+ head, antennas, body_yaw = self.state.current_move.evaluate(move_time)
+
+ if head is None:
+ head = create_head_pose(0, 0, 0, 0, 0, 0, degrees=True)
+ if antennas is None:
+ antennas = np.array([0.0, 0.0])
+ if body_yaw is None:
+ body_yaw = 0.0
+
+ antennas_tuple = (float(antennas[0]), float(antennas[1]))
+ head_copy = head.copy()
+ primary_full_body_pose = (
+ head_copy,
+ antennas_tuple,
+ float(body_yaw),
+ )
+
+ self.state.last_primary_pose = clone_full_body_pose(primary_full_body_pose)
+ # Otherwise reuse the last primary pose so we avoid jumps between moves
+ elif self.state.last_primary_pose is not None:
+ primary_full_body_pose = clone_full_body_pose(self.state.last_primary_pose)
+ else:
+ neutral_head_pose = create_head_pose(0, 0, 0, 0, 0, 0, degrees=True)
+ primary_full_body_pose = (neutral_head_pose, (0.0, 0.0), 0.0)
+ self.state.last_primary_pose = clone_full_body_pose(primary_full_body_pose)
+
+ return primary_full_body_pose
+
+ def _get_secondary_pose(self) -> FullBodyPose:
+ """Get the secondary full body pose from speech offsets."""
+ secondary_head_pose = create_head_pose(
+ x=self.state.speech_offsets[0],
+ y=self.state.speech_offsets[1],
+ z=self.state.speech_offsets[2],
+ roll=self.state.speech_offsets[3],
+ pitch=self.state.speech_offsets[4],
+ yaw=self.state.speech_offsets[5],
+ degrees=False,
+ mm=False,
+ )
+ return (secondary_head_pose, (0.0, 0.0), 0.0)
+
+ def _compose_full_body_pose(self, current_time: float) -> FullBodyPose:
+ """Compose primary and secondary poses into a single command pose."""
+ primary = self._get_primary_pose(current_time)
+ secondary = self._get_secondary_pose()
+ return combine_full_body(primary, secondary)
+
+ def _update_primary_motion(self, current_time: float) -> None:
+ """Advance queue state and idle behaviours for this tick."""
+ self._manage_move_queue(current_time)
+ self._manage_breathing(current_time)
+
+ def _calculate_blended_antennas(self, target_antennas: Tuple[float, float]) -> Tuple[float, float]:
+ """Blend target antennas with listening freeze state and update blending."""
+ now = self._now()
+ listening = self._is_listening
+ listening_antennas = self._listening_antennas
+ blend = self._antenna_unfreeze_blend
+ blend_duration = self._antenna_blend_duration
+ last_update = self._last_listening_blend_time
+ self._last_listening_blend_time = now
+
+ if listening:
+ antennas_cmd = listening_antennas
+ new_blend = 0.0
+ else:
+ dt = max(0.0, now - last_update)
+ if blend_duration <= 0:
+ new_blend = 1.0
+ else:
+ new_blend = min(1.0, blend + dt / blend_duration)
+ antennas_cmd = (
+ listening_antennas[0] * (1.0 - new_blend) + target_antennas[0] * new_blend,
+ listening_antennas[1] * (1.0 - new_blend) + target_antennas[1] * new_blend,
+ )
+
+ if listening:
+ self._antenna_unfreeze_blend = 0.0
+ else:
+ self._antenna_unfreeze_blend = new_blend
+ if new_blend >= 1.0:
+ self._listening_antennas = (
+ float(target_antennas[0]),
+ float(target_antennas[1]),
+ )
+
+ return antennas_cmd
+
+ def _issue_control_command(
+ self, head: NDArray[np.float32], antennas: Tuple[float, float], body_yaw: float
+ ) -> None:
+ """Send the fused pose to the robot with throttled error logging."""
+ now = self._now()
+ if now < self._set_target_retry_after:
+ return
+ try:
+ self.current_robot.set_target(head=head, antennas=antennas, body_yaw=body_yaw)
+ except Exception as e:
+ if now - self._last_set_target_err >= self._set_target_err_interval:
+ msg = f"Failed to set robot target: {e}"
+ if self._set_target_err_suppressed:
+ msg += f" (suppressed {self._set_target_err_suppressed} repeats)"
+ self._set_target_err_suppressed = 0
+ logger.error(msg)
+ self._last_set_target_err = now
+ else:
+ self._set_target_err_suppressed += 1
+ if "lost connection" in str(e).lower():
+ self._set_target_retry_after = now + 2.0
+ else:
+ self._set_target_retry_after = 0.0
+ with self._status_lock:
+ self._last_commanded_pose = clone_full_body_pose((head, antennas, body_yaw))
+
+ def _update_frequency_stats(
+ self,
+ loop_start: float,
+ prev_loop_start: float,
+ stats: LoopFrequencyStats,
+ ) -> LoopFrequencyStats:
+ """Update frequency statistics based on the current loop start time."""
+ period = loop_start - prev_loop_start
+ if period > 0:
+ stats.last_freq = 1.0 / period
+ stats.count += 1
+ delta = stats.last_freq - stats.mean
+ stats.mean += delta / stats.count
+ stats.m2 += delta * (stats.last_freq - stats.mean)
+ stats.min_freq = min(stats.min_freq, stats.last_freq)
+ return stats
+
+ def _schedule_next_tick(self, loop_start: float, stats: LoopFrequencyStats) -> Tuple[float, LoopFrequencyStats]:
+ """Compute sleep time to maintain target frequency and update potential freq."""
+ computation_time = self._now() - loop_start
+ stats.potential_freq = 1.0 / computation_time if computation_time > 0 else float("inf")
+ sleep_time = max(0.0, self.target_period - computation_time)
+ return sleep_time, stats
+
+ def _record_frequency_snapshot(self, stats: LoopFrequencyStats) -> None:
+ """Store a thread-safe snapshot of current frequency statistics."""
+ with self._status_lock:
+ self._freq_snapshot = LoopFrequencyStats(
+ mean=stats.mean,
+ m2=stats.m2,
+ min_freq=stats.min_freq,
+ count=stats.count,
+ last_freq=stats.last_freq,
+ potential_freq=stats.potential_freq,
+ )
+
+ def _maybe_log_frequency(self, loop_count: int, print_interval_loops: int, stats: LoopFrequencyStats) -> None:
+ """Emit frequency telemetry when enough loops have elapsed."""
+ if loop_count % print_interval_loops != 0 or stats.count == 0:
+ return
+
+ variance = stats.m2 / stats.count if stats.count > 0 else 0.0
+ lowest = stats.min_freq if stats.min_freq != float("inf") else 0.0
+ logger.debug(
+ "Loop freq - avg: %.2fHz, variance: %.4f, min: %.2fHz, last: %.2fHz, potential: %.2fHz, target: %.1fHz",
+ stats.mean,
+ variance,
+ lowest,
+ stats.last_freq,
+ stats.potential_freq,
+ self.target_frequency,
+ )
+ stats.reset()
+
+ def start(self) -> None:
+ """Start the worker thread that drives the 100 Hz control loop."""
+ if self._thread is not None and self._thread.is_alive():
+ logger.warning("Move worker already running; start() ignored")
+ return
+ self._stop_event.clear()
+ self._thread = threading.Thread(target=self.working_loop, daemon=True)
+ self._thread.start()
+ logger.debug("Move worker started")
+
+ def stop(self) -> None:
+ """Request the worker thread to stop and wait for it to exit.
+
+ Before stopping, resets the robot to a neutral position.
+ """
+ if self._thread is None or not self._thread.is_alive():
+ logger.debug("Move worker not running; stop() ignored")
+ return
+
+ logger.info("Stopping movement manager and resetting to neutral position...")
+
+ # Clear any queued moves and stop current move
+ self.clear_move_queue()
+
+ # Stop the worker thread first so it doesn't interfere
+ self._stop_event.set()
+ if self._thread is not None:
+ self._thread.join()
+ self._thread = None
+ logger.debug("Move worker stopped")
+
+ # Reset to neutral position using goto_target (same approach as wake_up)
+ try:
+ neutral_head_pose = create_head_pose(0, 0, 0, 0, 0, 0, degrees=True)
+ neutral_antennas = [0.0, 0.0]
+ neutral_body_yaw = 0.0
+
+ # Use goto_target directly on the robot
+ self.current_robot.goto_target(
+ head=neutral_head_pose,
+ antennas=neutral_antennas,
+ duration=2.0,
+ body_yaw=neutral_body_yaw,
+ )
+
+ logger.info("Reset to neutral position completed")
+
+ except Exception as e:
+ logger.error(f"Failed to reset to neutral position: {e}")
+
+ def get_status(self) -> Dict[str, Any]:
+ """Return a lightweight status snapshot for observability."""
+ with self._status_lock:
+ pose_snapshot = clone_full_body_pose(self._last_commanded_pose)
+ freq_snapshot = LoopFrequencyStats(
+ mean=self._freq_snapshot.mean,
+ m2=self._freq_snapshot.m2,
+ min_freq=self._freq_snapshot.min_freq,
+ count=self._freq_snapshot.count,
+ last_freq=self._freq_snapshot.last_freq,
+ potential_freq=self._freq_snapshot.potential_freq,
+ )
+
+ head_matrix = pose_snapshot[0].tolist() if pose_snapshot else None
+ antennas = pose_snapshot[1] if pose_snapshot else None
+ body_yaw = pose_snapshot[2] if pose_snapshot else None
+
+ return {
+ "queue_size": len(self.move_queue),
+ "is_listening": self._is_listening,
+ "breathing_active": self._breathing_active,
+ "idle_attitude": self.idle_profile.name,
+ "last_commanded_pose": {
+ "head": head_matrix,
+ "antennas": antennas,
+ "body_yaw": body_yaw,
+ },
+ "loop_frequency": {
+ "last": freq_snapshot.last_freq,
+ "mean": freq_snapshot.mean,
+ "min": freq_snapshot.min_freq,
+ "potential": freq_snapshot.potential_freq,
+ "samples": freq_snapshot.count,
+ },
+ }
+
+ def working_loop(self) -> None:
+ """Control loop main movements - reproduces main_works.py control architecture.
+
+ Single set_target() call with pose fusion.
+ """
+ logger.debug("Starting enhanced movement control loop (100Hz)")
+
+ loop_count = 0
+ prev_loop_start = self._now()
+ print_interval_loops = max(1, int(self.target_frequency * 2))
+ freq_stats = self._freq_stats
+
+ while not self._stop_event.is_set():
+ loop_start = self._now()
+ loop_count += 1
+
+ if loop_count > 1:
+ freq_stats = self._update_frequency_stats(loop_start, prev_loop_start, freq_stats)
+ prev_loop_start = loop_start
+
+ # 1) Poll external commands and apply pending offsets (atomic snapshot)
+ self._poll_signals(loop_start)
+
+ # 2) Manage the primary move queue (start new move, end finished move, breathing)
+ self._update_primary_motion(loop_start)
+
+ # 3) Build primary and secondary full-body poses, then fuse them
+ head, antennas, body_yaw = self._compose_full_body_pose(loop_start)
+
+ # 4) Apply listening antenna freeze or blend-back
+ antennas_cmd = self._calculate_blended_antennas(antennas)
+
+ # 5) Single set_target call - the only control point
+ self._issue_control_command(head, antennas_cmd, body_yaw)
+
+ # 6) Adaptive sleep to align to next tick, then publish shared state
+ sleep_time, freq_stats = self._schedule_next_tick(loop_start, freq_stats)
+ self._publish_shared_state()
+ self._record_frequency_snapshot(freq_stats)
+
+ # 7) Periodic telemetry on loop frequency
+ self._maybe_log_frequency(loop_count, print_interval_loops, freq_stats)
+
+ if sleep_time > 0:
+ time.sleep(sleep_time)
+
+ logger.debug("Movement control loop stopped")
diff --git a/src/Reachy_OpenWebUI/profiles/__init__.py b/src/Reachy_OpenWebUI/profiles/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a88ce6b410b4951469a530ee9515f9c915ef2208
--- /dev/null
+++ b/src/Reachy_OpenWebUI/profiles/__init__.py
@@ -0,0 +1 @@
+"""Profiles for Reachy Mini conversation app."""
diff --git a/src/Reachy_OpenWebUI/profiles/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/profiles/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3954d3b4009ee418b27edd129d9bfb24aa898a23
Binary files /dev/null and b/src/Reachy_OpenWebUI/profiles/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/profiles/default/instructions.txt b/src/Reachy_OpenWebUI/profiles/default/instructions.txt
new file mode 100644
index 0000000000000000000000000000000000000000..bec811563d3fa0bd9f6182ae5453d965b497ee2d
--- /dev/null
+++ b/src/Reachy_OpenWebUI/profiles/default/instructions.txt
@@ -0,0 +1 @@
+[default_prompt]
diff --git a/src/Reachy_OpenWebUI/profiles/default/tools.txt b/src/Reachy_OpenWebUI/profiles/default/tools.txt
new file mode 100644
index 0000000000000000000000000000000000000000..bd2ef51818c43a3a3828c1a1676c079c4b449f45
--- /dev/null
+++ b/src/Reachy_OpenWebUI/profiles/default/tools.txt
@@ -0,0 +1,9 @@
+dance
+stop_dance
+play_emotion
+stop_emotion
+camera
+idle_do_nothing
+head_tracking
+move_head
+sweep_look
diff --git a/src/Reachy_OpenWebUI/settings_keys.py b/src/Reachy_OpenWebUI/settings_keys.py
new file mode 100644
index 0000000000000000000000000000000000000000..25c5dc9a0878f014f2c1396f1d3342d8b62f6f05
--- /dev/null
+++ b/src/Reachy_OpenWebUI/settings_keys.py
@@ -0,0 +1,56 @@
+"""Canonical environment key names for shared and app-specific settings."""
+
+OPENWEBUI_URL = "OPENWEBUI_URL"
+OPENWEBUI_API_KEY = "OPENWEBUI_API_KEY"
+OPENWEBUI_TOKEN = "OPENWEBUI_TOKEN"
+OPENWEBUI_USER_AGENT = "OPENWEBUI_USER_AGENT"
+OPENWEBUI_CHAT_ID = "OPENWEBUI_CHAT_ID"
+OPENWEBUI_CHAT_WINDOW_START = "OPENWEBUI_CHAT_WINDOW_START"
+OPENWEBUI_CHAT_PENDING_REASON = "OPENWEBUI_CHAT_PENDING_REASON"
+OPENWEBUI_CHAT_PENDING_EVENT_ID = "OPENWEBUI_CHAT_PENDING_EVENT_ID"
+OPENWEB_LOADED_LLM = "OPENWEB_LOADED_LLM"
+MIC_GAIN = "MIC_GAIN"
+OPENWEBUI_USER_ID = "OPENWEBUI_USER_ID"
+OPENWEBUI_USER_NAME = "OPENWEBUI_USER_NAME"
+OPENWEBUI_USER_EMAIL = "OPENWEBUI_USER_EMAIL"
+OPENWEBUI_USER_LANGUAGE = "OPENWEBUI_USER_LANGUAGE"
+OPENWEBUI_USER_LOCATION = "OPENWEBUI_USER_LOCATION"
+OPENWEBUI_USER_TIMEZONE = "OPENWEBUI_USER_TIMEZONE"
+OPENWEBUI_CONTACTS_REQUIRE_VISION = "OPENWEBUI_CONTACTS_REQUIRE_VISION"
+OPENWEBUI_ENABLED_TOOLS = "OPENWEBUI_ENABLED_TOOLS"
+REACHY_IDLE_ATTITUDE = "REACHY_IDLE_ATTITUDE"
+REACHY_MINI_CUSTOM_PROFILE = "REACHY_MINI_CUSTOM_PROFILE"
+WEATHER_POSTAL_CODE = "WEATHER_POSTAL_CODE"
+
+LOCAL_DEV_VISION_MODEL = "LOCAL_DEV_VISION_MODEL"
+
+LEGACY_OPENWEB_MODEL = "OPENWEBUI_MODEL"
+LEGACY_OPENWEBUI_TOKEN = "OPENWEBUI_TOKEN"
+LEGACY_LOCAL_LLM_MODEL = "LOCAL_LLM_MODEL"
+LEGACY_LOCAL_LLM_URL = "LOCAL_LLM_URL"
+LEGACY_LOCAL_LLM_API_KEY = "LOCAL_LLM_API_KEY"
+LEGACY_LOCAL_VISION_MODEL = "LOCAL_VISION_MODEL"
+
+DEFAULT_OPENWEBUI_ENV = {
+ OPENWEBUI_URL: "http://localhost:3001/api",
+ OPENWEB_LOADED_LLM: "reachy-convo",
+ OPENWEBUI_API_KEY: "",
+ OPENWEBUI_TOKEN: "",
+ OPENWEBUI_USER_AGENT: "",
+ OPENWEBUI_CHAT_ID: "",
+ OPENWEBUI_CHAT_WINDOW_START: "",
+ OPENWEBUI_CHAT_PENDING_REASON: "",
+ OPENWEBUI_CHAT_PENDING_EVENT_ID: "",
+ MIC_GAIN: "1.0",
+ OPENWEBUI_USER_ID: "",
+ OPENWEBUI_USER_NAME: "Reachy",
+ OPENWEBUI_USER_EMAIL: "reachy@example.local",
+ OPENWEBUI_USER_LANGUAGE: "en-US",
+ OPENWEBUI_USER_LOCATION: "Unknown",
+ OPENWEBUI_USER_TIMEZONE: "America/New_York",
+ OPENWEBUI_CONTACTS_REQUIRE_VISION: "1",
+ OPENWEBUI_ENABLED_TOOLS: "",
+ REACHY_IDLE_ATTITUDE: "calm",
+ REACHY_MINI_CUSTOM_PROFILE: "",
+ WEATHER_POSTAL_CODE: "",
+}
diff --git a/src/Reachy_OpenWebUI/static/assets/attitudes-icon.png b/src/Reachy_OpenWebUI/static/assets/attitudes-icon.png
new file mode 100644
index 0000000000000000000000000000000000000000..e07e6344a1e19b9af8f2ee89ea8f6a059ea38d6e
Binary files /dev/null and b/src/Reachy_OpenWebUI/static/assets/attitudes-icon.png differ
diff --git a/src/Reachy_OpenWebUI/static/assets/camera.wav b/src/Reachy_OpenWebUI/static/assets/camera.wav
new file mode 100644
index 0000000000000000000000000000000000000000..ba0b0f846437e5fe980f7106f1f6937f716ec5ee
Binary files /dev/null and b/src/Reachy_OpenWebUI/static/assets/camera.wav differ
diff --git a/src/Reachy_OpenWebUI/static/assets/cookaiware-icon.png b/src/Reachy_OpenWebUI/static/assets/cookaiware-icon.png
new file mode 100644
index 0000000000000000000000000000000000000000..ee187301071f150bd46e5c8540d430e61c9cffb0
Binary files /dev/null and b/src/Reachy_OpenWebUI/static/assets/cookaiware-icon.png differ
diff --git a/src/Reachy_OpenWebUI/static/assets/pwa-icon-192.png b/src/Reachy_OpenWebUI/static/assets/pwa-icon-192.png
new file mode 100644
index 0000000000000000000000000000000000000000..6a881e45bf4fb696400939a6a6b751cf265fac78
Binary files /dev/null and b/src/Reachy_OpenWebUI/static/assets/pwa-icon-192.png differ
diff --git a/src/Reachy_OpenWebUI/static/assets/pwa-icon-512.png b/src/Reachy_OpenWebUI/static/assets/pwa-icon-512.png
new file mode 100644
index 0000000000000000000000000000000000000000..569c77283d99f91cc1eed7d7f8b00a914c7338c7
--- /dev/null
+++ b/src/Reachy_OpenWebUI/static/assets/pwa-icon-512.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:65346a118c77f8cb77da6e97f64d132e9bc868641aa4972d7be014ae90d0f453
+size 167028
diff --git a/src/Reachy_OpenWebUI/static/assets/reachy-conversation-app.png b/src/Reachy_OpenWebUI/static/assets/reachy-conversation-app.png
new file mode 100644
index 0000000000000000000000000000000000000000..a6e7a2f91aeef7c19f70652c8d95d149361a04df
--- /dev/null
+++ b/src/Reachy_OpenWebUI/static/assets/reachy-conversation-app.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:8871402e4daf8ae34d56a1139f2b604f6c4dbea4fcc00676a5f2ef0a4c55d4ea
+size 543890
diff --git a/src/Reachy_OpenWebUI/static/assets/settings-icon.png b/src/Reachy_OpenWebUI/static/assets/settings-icon.png
new file mode 100644
index 0000000000000000000000000000000000000000..e1d6aa54c855f8e7fde52c02c0e867ab4901425b
--- /dev/null
+++ b/src/Reachy_OpenWebUI/static/assets/settings-icon.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:2239f9d309419548d12d1c5390e22f502cffc7e845a68236efef6870b197c960
+size 267000
diff --git a/src/Reachy_OpenWebUI/static/global.css b/src/Reachy_OpenWebUI/static/global.css
new file mode 100644
index 0000000000000000000000000000000000000000..cb938f9a8b0b11bf7c213b633189bf2ea23550c4
--- /dev/null
+++ b/src/Reachy_OpenWebUI/static/global.css
@@ -0,0 +1,87 @@
+:root {
+ color-scheme: dark;
+ --page: #08090a;
+ --phone: #101112;
+ --phone-deep: #070808;
+ --topbar: #16181a;
+ --topbar-2: #111315;
+ --surface: #191a1b;
+ --surface-2: #292b2d;
+ --field: #202224;
+ --border: rgba(255, 255, 255, 0.1);
+ --border-strong: rgba(255, 255, 255, 0.16);
+ --text: #d9dcdf;
+ --strong: #f4f6f8;
+ --muted: #8f969c;
+ --accent: #007acc;
+ --accent-strong: #1592e6;
+ --green: #1592e6;
+ --red: #ff4d57;
+ --warn: #ffbd5a;
+ --error: #ff6b75;
+ --shadow: 0 28px 80px rgba(0, 0, 0, 0.56);
+ --control-h: 40px;
+ --radius-control: 8px;
+ --bar-gap: 6px;
+ --bar-pad: 8px 10px 10px;
+ font-family: "Inter", "Segoe UI", Arial, sans-serif;
+}
+
+* {
+ box-sizing: border-box;
+}
+
+html,
+body {
+ min-height: 100%;
+}
+
+body {
+ min-height: 100vh;
+ margin: 0;
+ background: var(--page);
+ color: var(--text);
+}
+
+h1,
+h2,
+p {
+ margin: 0;
+}
+
+.ui-bottom-bar {
+ gap: var(--bar-gap);
+ padding: var(--bar-pad);
+ border-top: 1px solid rgba(255, 255, 255, 0.08);
+ background: var(--phone-deep);
+}
+
+.ui-field {
+ min-height: var(--control-h);
+ padding: 9px 10px;
+ border: 1px solid var(--border);
+ border-radius: var(--radius-control);
+ background: var(--field);
+ color: var(--strong);
+ font: inherit;
+ font-size: 14px;
+ line-height: 1.35;
+ outline: none;
+ transition: border-color 0.15s ease, box-shadow 0.15s ease, background 0.15s ease;
+}
+
+.ui-field:hover {
+ background: #25282a;
+}
+
+.ui-field:focus {
+ border-color: rgba(0, 122, 204, 0.72);
+ box-shadow: 0 0 0 3px rgba(0, 122, 204, 0.16);
+}
+
+.ui-action {
+ min-width: 0;
+ min-height: var(--control-h);
+ margin: 0;
+ border-radius: var(--radius-control);
+}
diff --git a/src/Reachy_OpenWebUI/static/index.html b/src/Reachy_OpenWebUI/static/index.html
new file mode 100644
index 0000000000000000000000000000000000000000..e5471e06a7f75cd8b2f6cccede9df32d59101e16
--- /dev/null
+++ b/src/Reachy_OpenWebUI/static/index.html
@@ -0,0 +1,469 @@
+
+
+
+
+
+
+
+
+
+
+ Reachy Mini OpenWebUI
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Reachy OpenWebUI
+
Getting Ready
+
+
+
+
+
+
+
+
+
+
+
Sunday, October 20
+
+ 8:24
+ PM
+
+
+
+
+
+
+
+
Weather
+
Set ZIP
+
Add postal code in Settings
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Volume
+
+
+
+
+
+
+
+
+
+ R
+
+
+
+
+
+
Loading model
+
00:00
+
Checking saved settings...
+
+
+
+
+
OpenWebUI
+
Contacts
+
+
+
Loading contacts.
+
+
+
+
+
+
OpenWebUI
+
Conversations
+
+
+
Loading conversations.
+
+
+
+
+
+
Reachy
+
Attitudes
+
+
+
+
+
+
+
+
+
+
+
CookAIware
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Show barcode to Reachy
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Waiting
+
+
+
+
Messages will appear here.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Reachy is on another call. He will be right with you.
+
+
+
+
+
+
Settings
+
OpenWebUI
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Reachy_OpenWebUI/static/main.js b/src/Reachy_OpenWebUI/static/main.js
new file mode 100644
index 0000000000000000000000000000000000000000..5016ff5fc8dddde897047367b3061aba6856f316
--- /dev/null
+++ b/src/Reachy_OpenWebUI/static/main.js
@@ -0,0 +1,3086 @@
+const els = {
+ phone: document.getElementById("phone"),
+ homeClock: document.getElementById("home-clock"),
+ homePeriod: document.getElementById("home-period"),
+ homeDate: document.getElementById("home-date"),
+ homeWeather: document.getElementById("home-weather"),
+ weatherLocation: document.getElementById("weather-location"),
+ weatherTemp: document.getElementById("weather-temp"),
+ weatherCondition: document.getElementById("weather-condition"),
+ weatherForecast: document.getElementById("weather-forecast"),
+ topbarTitle: document.getElementById("topbar-title"),
+ stateChip: document.getElementById("state-chip"),
+ modelStage: document.getElementById("model-stage"),
+ modelImage: document.getElementById("model-image"),
+ modelInitial: document.getElementById("model-initial"),
+ topbarModelImage: document.getElementById("topbar-model-image"),
+ topbarModelInitial: document.getElementById("topbar-model-initial"),
+ back: document.getElementById("back-btn"),
+ bottomBack: document.getElementById("bottom-back-btn"),
+ contactName: document.getElementById("contact-name"),
+ callDuration: document.getElementById("call-duration"),
+ connectionText: document.getElementById("connection-text"),
+ connectionSummary: document.getElementById("connection-summary"),
+ activityVisual: document.getElementById("activity-visual"),
+ transcript: document.getElementById("transcript"),
+ modelList: document.getElementById("model-list"),
+ conversationList: document.getElementById("conversation-list"),
+ homeContacts: document.getElementById("home-contacts-btn"),
+ homeMessages: document.getElementById("home-messages-btn"),
+ homeChatHistory: document.getElementById("home-chat-history-btn"),
+ quickConnect: document.getElementById("quick-connect-btn"),
+ callLabel: document.getElementById("call-label"),
+ muteLabel: document.getElementById("mute-label"),
+ homeAttitudes: document.getElementById("home-attitudes-btn"),
+ homeVolume: document.getElementById("home-volume-btn"),
+ volumeScrim: document.getElementById("volume-scrim"),
+ volumePanel: document.getElementById("volume-panel"),
+ homeMicVolume: document.getElementById("home-mic-volume"),
+ homeMicVolumeValue: document.getElementById("home-mic-volume-value"),
+ homeSpeakerVolume: document.getElementById("home-speaker-volume"),
+ homeSpeakerVolumeValue: document.getElementById("home-speaker-volume-value"),
+ attitudesApp: document.getElementById("attitudes-app"),
+ attitudesGrid: document.getElementById("attitudes-grid"),
+ testSpeech: document.getElementById("test-speech-btn"),
+ homeCookAIware: document.getElementById("home-cookaiware-btn"),
+ cookAIwareApp: document.getElementById("cookaiware-app"),
+ cookAIwareBack: document.getElementById("cookaiware-back-btn"),
+ cookAIwareStart: document.getElementById("cookaiware-start-btn"),
+ cookAIwareRefresh: document.getElementById("cookaiware-refresh-btn"),
+ cookAIwareMute: document.getElementById("cookaiware-mute-btn"),
+ cookAddInventoryView: document.getElementById("cook-add-inventory-view-btn"),
+ cookAddShoppingView: document.getElementById("cook-add-shopping-view-btn"),
+ cookInventoryUpc: document.getElementById("cook-inventory-upc-btn"),
+ cookShoppingUpc: document.getElementById("cook-shopping-upc-btn"),
+ cookUpcScanner: document.getElementById("cook-upc-scanner"),
+ cookUpcFrame: document.getElementById("cook-upc-frame"),
+ cookUpcManual: document.getElementById("cook-upc-manual-btn"),
+ cookUpcClose: document.getElementById("cook-upc-close-btn"),
+ cookTabs: Array.from(document.querySelectorAll("[data-cook-view]")),
+ cookPanels: Array.from(document.querySelectorAll("[data-cook-panel]")),
+ cookInventorySearch: document.getElementById("cook-inventory-search"),
+ cookInventoryList: document.getElementById("cook-inventory-list"),
+ cookPlanList: document.getElementById("cook-plan-list"),
+ cookShoppingSearch: document.getElementById("cook-shopping-search"),
+ cookShoppingList: document.getElementById("cook-shopping-list"),
+ cookItemName: document.getElementById("cook-item-name"),
+ cookItemQty: document.getElementById("cook-item-qty"),
+ cookItemUnit: document.getElementById("cook-item-unit"),
+ cookItemExpiration: document.getElementById("cook-item-expiration"),
+ cookItemStorage: document.getElementById("cook-item-storage"),
+ cookItemAutoAdd: document.getElementById("cook-item-auto-add"),
+ cookAddItem: document.getElementById("cook-add-item-btn"),
+ cookGeneratePlan: document.getElementById("cook-generate-plan-btn"),
+ cookShoppingName: document.getElementById("cook-shopping-name"),
+ cookShoppingQty: document.getElementById("cook-shopping-qty"),
+ cookShoppingUnit: document.getElementById("cook-shopping-unit"),
+ cookAddShopping: document.getElementById("cook-add-shopping-btn"),
+ cookGenerateShopping: document.getElementById("cook-generate-shopping-btn"),
+ cookAutoShopping: document.getElementById("cook-auto-shopping-btn"),
+ cookClearShopping: document.getElementById("cook-clear-shopping-btn"),
+ cookAdults: document.getElementById("cook-adults"),
+ cookChildren: document.getElementById("cook-children"),
+ cookLanguage: document.getElementById("cook-language"),
+ cookUnitSystem: document.getElementById("cook-unit-system"),
+ cookUpcSource: document.getElementById("cook-upc-source"),
+ cookSaveProfile: document.getElementById("cook-save-profile-btn"),
+ settingsToggle: document.getElementById("settings-toggle"),
+ settingsPanel: document.getElementById("settings-panel"),
+ envPath: document.getElementById("env-path"),
+ form: document.getElementById("settings-form"),
+ url: document.getElementById("openwebui-url"),
+ model: document.getElementById("openwebui-model"),
+ contactsRequireVision: document.getElementById("contacts-require-vision"),
+ weatherPostalCode: document.getElementById("weather-postal-code"),
+ idleAttitude: document.getElementById("reachy-idle-attitude"),
+ phoneToolsList: document.getElementById("phone-tools-list"),
+ cookAIwareToolsList: document.getElementById("cookaiware-tools-list"),
+ apiKey: document.getElementById("openwebui-api-key"),
+ token: document.getElementById("openwebui-token"),
+ chatId: document.getElementById("openwebui-chat-id"),
+ micGain: document.getElementById("mic-gain"),
+ micGainValue: document.getElementById("mic-gain-value"),
+ save: document.getElementById("save-btn"),
+ start: document.getElementById("start-btn"),
+ stop: document.getElementById("stop-btn"),
+ mute: document.getElementById("mute-btn"),
+ contacts: document.getElementById("contacts-btn"),
+ refresh: document.getElementById("refresh-btn"),
+ refreshModels: document.getElementById("refresh-models-btn"),
+ refreshChats: document.getElementById("refresh-chats-btn"),
+ clearCallCache: document.getElementById("clear-call-cache-btn"),
+ restartApp: document.getElementById("restart-app-btn"),
+ attachImage: document.getElementById("attach-image-btn"),
+ imageAttachmentInput: document.getElementById("image-attachment-input"),
+ attachmentPreview: document.getElementById("attachment-preview"),
+ attachmentName: document.getElementById("attachment-name"),
+ clearAttachment: document.getElementById("clear-attachment-btn"),
+ textMessageInput: document.getElementById("text-message-input"),
+ textBack: document.getElementById("text-back-btn"),
+ sendText: document.getElementById("send-text-btn"),
+ textActions: document.getElementById("text-actions-btn"),
+ textActionsMenu: document.getElementById("text-actions-menu"),
+ textMicMute: document.getElementById("text-mic-mute-btn"),
+ textSpeakerMute: document.getElementById("text-speaker-mute-btn"),
+ textDisconnect: document.getElementById("text-disconnect-btn"),
+ status: document.getElementById("status"),
+ slowStartMessage: document.getElementById("slow-start-message"),
+};
+
+let formDirty = false;
+let savedApiKeyPresent = false;
+let savedTokenPresent = false;
+let apiKeyRequired = false;
+let statusLoaded = false;
+let runtimeStatus = {
+ state: "loading",
+ can_start: null,
+ openwebui_model: "",
+ openwebui_chat_id: "",
+ openwebui_user_id: "",
+ openwebui_user_name: "You",
+ contacts_require_vision: true,
+ weather_postal_code: "",
+ reachy_idle_attitude: "calm",
+ available_idle_attitudes: [],
+ available_tools: [],
+ phone_tools: [],
+ cookaiware_tools: [],
+ enabled_tools: [],
+ active_profile: "",
+ cookaiware_active: false,
+ muted: false,
+ speaker_muted: false,
+ mic_gain: 1,
+ mic_volume: 100,
+ speaker_volume: 100,
+};
+let busy = false;
+let runningStartedAt = null;
+let connectingStartedAt = null;
+let activeModelName = "";
+let activeModelImageUrl = "";
+let renderedTranscriptKey = "";
+let renderedModelDirectoryKey = "";
+let renderedConversationDirectoryKey = "";
+let availableModels = [];
+let availableConversations = [];
+const avatarImageCache = new Map();
+let autoModelRefreshKey = "";
+let autoModelRefreshInFlight = false;
+let lastAutoModelRefreshAttemptAt = 0;
+let pendingStart = false;
+let startFlowActive = false;
+let contactsOpen = false;
+let conversationsOpen = false;
+let attitudesOpen = false;
+let cookAIwareOpen = false;
+let settingsOpen = false;
+let textChatOpen = false;
+let homeOpen = false;
+let volumePanelOpen = false;
+let cookAIwareState = {
+ inventory: [],
+ profile: {},
+ plan: {},
+ shopping: [],
+ settings: {},
+};
+let conversationRefreshInFlight = false;
+let lastAssistantConversationRefreshKey = "";
+let assistantConversationRefreshStarted = false;
+let lastConversationAutoRefreshAt = 0;
+let statusHideTimer = null;
+let lastStatusText = "";
+let lastStatusTone = "";
+let statusChangedAt = 0;
+let weatherRefreshInFlight = false;
+let lastWeatherPostalCode = "";
+let weatherForecastOpen = false;
+let lastWeatherData = {};
+let attachedImage = null;
+let volumeSaveTimer = null;
+let cookUpcPreviewTimer = null;
+let cookUpcActiveTarget = "inventory";
+let pendingVolumeFields = new Set();
+const SETTINGS_CACHE_KEY = "Reachy_OpenWebUI_settings_preview_v1";
+const STATUS_AUTO_HIDE_MS = 3500;
+const STATUS_FADE_MS = 220;
+
+function registerPwaServiceWorker() {
+ if (!("serviceWorker" in navigator)) {
+ return;
+ }
+ window.addEventListener("load", () => {
+ navigator.serviceWorker.register("/service-worker.js").catch(() => {});
+ });
+}
+
+function setStatus(message, tone = "") {
+ const nextText = message || "";
+ const nextTone = tone || "";
+ if (nextText !== lastStatusText || nextTone !== lastStatusTone) {
+ statusChangedAt = Date.now();
+ lastStatusText = nextText;
+ lastStatusTone = nextTone;
+ }
+ els.status.textContent = nextText;
+ els.status.className = `status ${nextTone}`.trim();
+ updateStatusVisibility();
+}
+
+function updateStatusVisibility() {
+ if (!els.status) {
+ return;
+ }
+ if (statusHideTimer) {
+ clearTimeout(statusHideTimer);
+ statusHideTimer = null;
+ }
+
+ const hasMessage = Boolean((els.status.textContent || "").trim());
+ if (!hasMessage) {
+ els.status.hidden = true;
+ els.status.classList.remove("fading");
+ return;
+ }
+
+ const stickyTone = lastStatusTone === "error" || lastStatusTone === "warn";
+ if (!stickyTone) {
+ const elapsed = Date.now() - (statusChangedAt || Date.now());
+ const fadeStartAt = Math.max(0, STATUS_AUTO_HIDE_MS - STATUS_FADE_MS);
+ const remaining = Math.max(0, STATUS_AUTO_HIDE_MS - elapsed);
+ if (remaining === 0) {
+ els.status.hidden = true;
+ els.status.classList.remove("fading");
+ return;
+ }
+ els.status.hidden = false;
+ if (elapsed >= fadeStartAt) {
+ els.status.classList.add("fading");
+ statusHideTimer = window.setTimeout(() => {
+ els.status.hidden = true;
+ els.status.classList.remove("fading");
+ }, remaining);
+ } else {
+ els.status.classList.remove("fading");
+ statusHideTimer = window.setTimeout(() => {
+ updateStatusVisibility();
+ }, fadeStartAt - elapsed);
+ }
+ return;
+ }
+
+ els.status.hidden = false;
+ els.status.classList.remove("fading");
+}
+
+function setBusy(isBusy) {
+ busy = isBusy;
+ els.save.disabled = isBusy;
+ els.refresh.disabled = isBusy;
+ els.refreshModels.disabled = isBusy;
+ if (els.refreshChats) els.refreshChats.disabled = isBusy;
+ els.clearCallCache.disabled = isBusy;
+ if (els.restartApp) els.restartApp.disabled = isBusy || !statusLoaded;
+ renderCallState();
+}
+
+function payloadFromForm() {
+ const payload = {
+ openwebui_url: els.url.value.trim(),
+ openwebui_model: els.model.value.trim(),
+ openwebui_api_key: els.apiKey.value.trim(),
+ openwebui_token: els.token.value.trim(),
+ openwebui_chat_id: els.chatId.value.trim(),
+ mic_gain: els.micGainValue.value.trim() || els.micGain.value.trim(),
+ contacts_require_vision: Boolean(els.contactsRequireVision?.checked),
+ weather_postal_code: els.weatherPostalCode?.value.trim() || "",
+ reachy_idle_attitude: els.idleAttitude?.value || runtimeStatus.reachy_idle_attitude || "calm",
+ };
+ if (els.form?.querySelector('input[name="enabled_tools"]')) {
+ payload.enabled_tools = selectedToolNames();
+ }
+ return payload;
+}
+
+function safeReadCachedSettings() {
+ try {
+ return JSON.parse(window.localStorage.getItem(SETTINGS_CACHE_KEY) || "{}");
+ } catch (_error) {
+ return {};
+ }
+}
+
+function writeCachedSettings(data) {
+ const preview = {
+ openwebui_url: data.openwebui_url || "",
+ openwebui_model: data.openwebui_model || "",
+ openwebui_chat_id: data.openwebui_chat_id || "",
+ mic_gain: data.mic_gain || "",
+ mic_volume: data.mic_volume ?? "",
+ speaker_volume: data.speaker_volume ?? "",
+ contacts_require_vision: data.contacts_require_vision !== false,
+ weather_postal_code: data.weather_postal_code || "",
+ reachy_idle_attitude: data.reachy_idle_attitude || "calm",
+ };
+ try {
+ window.localStorage.setItem(SETTINGS_CACHE_KEY, JSON.stringify(preview));
+ } catch (_error) {}
+}
+
+function clearCachedChatPreview() {
+ const cached = safeReadCachedSettings();
+ cached.openwebui_chat_id = "";
+ try {
+ window.localStorage.setItem(SETTINGS_CACHE_KEY, JSON.stringify(cached));
+ } catch (_error) {}
+}
+
+function applyCachedSettingsPreview() {
+ const cached = safeReadCachedSettings();
+ if (!cached.openwebui_url && !cached.openwebui_model) {
+ return;
+ }
+ if (!els.url.value) els.url.value = cached.openwebui_url || "";
+ if (!els.chatId.value) els.chatId.value = cached.openwebui_chat_id || "";
+ if (cached.openwebui_model) {
+ setSelectedModel(cached.openwebui_model);
+ runtimeStatus.openwebui_model = cached.openwebui_model;
+ }
+ if (els.idleAttitude && cached.reachy_idle_attitude) {
+ els.idleAttitude.value = cached.reachy_idle_attitude;
+ renderIdleAttitudes([], cached.reachy_idle_attitude);
+ }
+ if (els.weatherPostalCode && !els.weatherPostalCode.value) {
+ els.weatherPostalCode.value = cached.weather_postal_code || "";
+ }
+ const gain = Number(cached.mic_gain || 0);
+ if (Number.isFinite(gain) && gain > 0) {
+ const safeGain = Math.min(3, Math.max(0.25, gain));
+ els.micGain.value = String(safeGain);
+ els.micGainValue.value = safeGain.toFixed(2).replace(/\.?0+$/, "");
+ }
+ updateVolumeControls({
+ mic_volume: cached.mic_volume,
+ speaker_volume: cached.speaker_volume,
+ });
+ renderCallState();
+}
+
+function updateSecretPlaceholders() {
+ els.apiKey.placeholder = savedApiKeyPresent ? "Saved API key loaded - leave blank to keep" : "optional";
+ els.token.placeholder = savedTokenPresent ? "Saved JWT token loaded - leave blank to keep" : "required for realtime call mode";
+ els.apiKey.classList.toggle("secret-saved", savedApiKeyPresent && !els.apiKey.value);
+ els.token.classList.toggle("secret-saved", savedTokenPresent && !els.token.value);
+}
+
+function prettyState(state) {
+ const labels = {
+ configuring: "Calling",
+ running: "Live",
+ shutting_down: "Ending",
+ stopped: "Ready",
+ };
+ if (labels[state]) {
+ return labels[state];
+ }
+ const clean = String(state || "loading").replace(/_/g, " ");
+ return clean.charAt(0).toUpperCase() + clean.slice(1);
+}
+
+function initialForModel(modelName) {
+ const clean = String(modelName || "Reachy").trim();
+ const first = clean.match(/[A-Za-z0-9]/);
+ return (first ? first[0] : "R").toUpperCase();
+}
+
+function openWebUIRootUrl() {
+ const raw = (els.url.value || "").trim();
+ if (!raw) return "";
+ return raw.replace(/\/+$/, "").replace(/\/api(?:\/v1)?$/i, "");
+}
+
+function modelProfileImageUrl(modelName) {
+ const model = String(modelName || "").trim();
+ if (!model || model === "No model saved" || model === "Loading model") {
+ return "";
+ }
+ const params = new URLSearchParams({
+ id: model,
+ lang: navigator.language || "en-US",
+ });
+ return `/avatar/model?${params.toString()}`;
+}
+
+function userProfileImageUrl() {
+ const params = new URLSearchParams();
+ const userId = String(runtimeStatus.openwebui_user_id || "").trim();
+ if (userId) {
+ params.set("user_id", userId);
+ }
+ return `/avatar/user${params.toString() ? `?${params.toString()}` : ""}`;
+}
+
+function setAvatarImage(imageEl, initialEl, imageUrl) {
+ if (!imageEl || !initialEl) {
+ return;
+ }
+
+ if ((imageEl.dataset.avatarUrl || "") === imageUrl) {
+ return;
+ }
+
+ if (!imageUrl) {
+ imageEl.dataset.avatarUrl = "";
+ imageEl.hidden = true;
+ imageEl.removeAttribute("src");
+ initialEl.hidden = false;
+ imageEl.parentElement?.classList.remove("has-image");
+ return;
+ }
+
+ const cachedState = avatarImageCache.get(imageUrl);
+ imageEl.dataset.avatarUrl = imageUrl;
+ imageEl.hidden = true;
+ imageEl.removeAttribute("src");
+ initialEl.hidden = false;
+ imageEl.parentElement?.classList.remove("has-image");
+
+ if (cachedState === "loaded") {
+ imageEl.src = imageUrl;
+ imageEl.hidden = false;
+ initialEl.hidden = true;
+ imageEl.parentElement?.classList.add("has-image");
+ return;
+ }
+
+ imageEl.onload = () => {
+ avatarImageCache.set(imageUrl, "loaded");
+ imageEl.hidden = false;
+ initialEl.hidden = true;
+ imageEl.parentElement?.classList.add("has-image");
+ };
+ imageEl.onerror = () => {
+ avatarImageCache.delete(imageUrl);
+ imageEl.hidden = true;
+ imageEl.removeAttribute("src");
+ initialEl.hidden = false;
+ imageEl.parentElement?.classList.remove("has-image");
+ };
+ imageEl.src = imageUrl;
+}
+
+function refreshModelImage(modelName) {
+ const imageUrl = modelProfileImageUrl(modelName);
+ activeModelImageUrl = imageUrl;
+ setAvatarImage(els.modelImage, els.modelInitial, imageUrl);
+ setAvatarImage(els.topbarModelImage, els.topbarModelInitial, imageUrl);
+}
+
+function selectedToolNames() {
+ if (!els.form) {
+ return [];
+ }
+ return Array.from(els.form.querySelectorAll('input[name="enabled_tools"]:checked'))
+ .map((input) => String(input.value || "").trim())
+ .filter(Boolean);
+}
+
+function toolAppGroup(toolName) {
+ const conversationTools = new Set([
+ "dance",
+ "stop_dance",
+ "play_emotion",
+ "stop_emotion",
+ "camera",
+ "idle_do_nothing",
+ "head_tracking",
+ "move_head",
+ "look_around",
+ ]);
+ const cookAIwareTools = new Set([
+ "inventory_action",
+ "family_profile_action",
+ "meal_plan_action",
+ "shopping_list_action",
+ "app_settings_action",
+ ]);
+ if (cookAIwareTools.has(toolName)) {
+ return "cookaiware";
+ }
+ if (conversationTools.has(toolName)) {
+ return "phone";
+ }
+ return "phone";
+}
+
+function renderToolList(container, tools, enabled, emptyText) {
+ if (!container) {
+ return;
+ }
+ container.innerHTML = "";
+ if (!tools.length) {
+ const empty = document.createElement("p");
+ empty.className = "transcript-empty";
+ empty.textContent = emptyText;
+ container.appendChild(empty);
+ return;
+ }
+
+ for (const toolName of tools) {
+ const label = document.createElement("label");
+ label.className = "toggle-row tool-toggle";
+
+ const checkbox = document.createElement("input");
+ checkbox.type = "checkbox";
+ checkbox.name = "enabled_tools";
+ checkbox.value = toolName;
+ checkbox.checked = enabled.has(toolName);
+ checkbox.addEventListener("change", () => {
+ formDirty = true;
+ });
+
+ const text = document.createElement("span");
+ text.textContent = toolName.replace(/_/g, " ");
+
+ label.appendChild(checkbox);
+ label.appendChild(text);
+ container.appendChild(label);
+ }
+}
+
+function cleanToolNames(tools = []) {
+ return Array.from(new Set((tools || []).map((tool) => String(tool || "").trim()).filter(Boolean)));
+}
+
+function renderToolSettings(availableTools = [], enabledTools = [], toolGroups = {}) {
+ if (!els.phoneToolsList && !els.cookAIwareToolsList) {
+ return;
+ }
+ const available = cleanToolNames(availableTools);
+ const enabled = new Set((enabledTools || []).map((tool) => String(tool || "").trim()).filter(Boolean));
+ const groupedPhoneTools = cleanToolNames(toolGroups.phone_tools || toolGroups.phone);
+ const groupedCookAIwareTools = cleanToolNames(toolGroups.cookaiware_tools || toolGroups.cookaiware);
+ const phoneTools = groupedPhoneTools.length
+ ? groupedPhoneTools
+ : available.filter((toolName) => toolAppGroup(toolName) === "phone");
+ const cookAIwareTools = groupedCookAIwareTools.length
+ ? groupedCookAIwareTools
+ : available.filter((toolName) => toolAppGroup(toolName) === "cookaiware");
+ renderToolList(els.phoneToolsList, phoneTools, enabled, "No Phone tools found.");
+ renderToolList(els.cookAIwareToolsList, cookAIwareTools, enabled, "No CookAIware tools found.");
+}
+
+function renderIdleAttitudes(availableAttitudes = [], selected = "calm") {
+ const attitudes = (availableAttitudes || [])
+ .map((item) => ({
+ name: String(item?.name || "").trim(),
+ label: String(item?.label || item?.name || "").trim(),
+ }))
+ .filter((item) => item.name);
+ if (els.idleAttitude) {
+ const current = String(selected || els.idleAttitude.value || "calm").trim() || "calm";
+ els.idleAttitude.innerHTML = "";
+ for (const attitude of attitudes) {
+ const option = document.createElement("option");
+ option.value = attitude.name;
+ option.textContent = attitude.label || attitude.name;
+ els.idleAttitude.appendChild(option);
+ }
+ if (attitudes.some((a) => a.name === current)) {
+ els.idleAttitude.value = current;
+ }
+ }
+ renderAttitudesGrid(attitudes, selected);
+}
+
+function renderAttitudesGrid(attitudes, selected) {
+ if (!els.attitudesGrid) {
+ return;
+ }
+ const current = String(selected || runtimeStatus.reachy_idle_attitude || "calm").trim();
+ els.attitudesGrid.innerHTML = "";
+ const items = attitudes.length ? attitudes : (runtimeStatus.available_idle_attitudes || [])
+ .map((item) => ({
+ name: String(item?.name || "").trim(),
+ label: String(item?.label || item?.name || "").trim(),
+ }))
+ .filter((item) => item.name);
+ for (const attitude of items) {
+ if (attitude.name === "still") continue;
+ const card = document.createElement("button");
+ card.type = "button";
+ card.className = "attitude-card";
+ card.dataset.value = attitude.name;
+ card.setAttribute("role", "option");
+ card.setAttribute("aria-selected", String(attitude.name === current));
+ card.textContent = attitude.label || attitude.name;
+ card.addEventListener("click", () => setAttitude(attitude.name));
+ els.attitudesGrid.appendChild(card);
+ }
+}
+
+async function setAttitude(attitudeName) {
+ if (busy) return;
+ try {
+ const data = await requestJson("/set_attitude", {
+ method: "POST",
+ body: JSON.stringify({ attitude: attitudeName }),
+ });
+ runtimeStatus.reachy_idle_attitude = attitudeName;
+ if (els.idleAttitude) els.idleAttitude.value = attitudeName;
+ writeCachedSettings({ ...safeReadCachedSettings(), reachy_idle_attitude: attitudeName });
+ renderAttitudesGrid([], attitudeName);
+ setStatus(data.message || "Attitude changed.", "ok");
+ } catch (error) {
+ setStatus(`Attitude failed: ${error.message}`, "error");
+ }
+}
+
+async function testSpeech() {
+ if (busy) return;
+ els.testSpeech.disabled = true;
+ setStatus("Testing speech motion...");
+ try {
+ const data = await requestJson("/test_speech", { method: "POST" });
+ setStatus(data.message || "Speech test started.", "ok");
+ } catch (error) {
+ setStatus(`Speech test failed: ${error.message}`, "error");
+ } finally {
+ setTimeout(() => { els.testSpeech.disabled = false; }, 4500);
+ }
+}
+
+function cookDisplayName(item) {
+ return String(item?.display_name || item?.name || "").trim();
+}
+
+function cookQuantity(item) {
+ return String(item?.display_quantity || `${item?.quantity ?? ""} ${item?.unit || ""}`).trim();
+}
+
+const COOK_UNIT_OPTIONS = {
+ metric: [
+ ["pcs", "Pieces"],
+ ["g", "Grams"],
+ ["kg", "Kilograms"],
+ ["ml", "Milliliters"],
+ ["l", "Liters"],
+ ],
+ imperial: [
+ ["pcs", "Pieces"],
+ ["oz", "Ounces"],
+ ["lb", "Pounds"],
+ ["fl oz", "Fluid ounces"],
+ ["qt", "Quarts"],
+ ["gal", "Gallons"],
+ ],
+};
+
+function populateCookUnitSelect(select, unitSystem) {
+ if (!select) return;
+ const selected = String(select.value || "pcs").trim() || "pcs";
+ const options = COOK_UNIT_OPTIONS[unitSystem] || COOK_UNIT_OPTIONS.metric;
+ select.innerHTML = "";
+ for (const [value, label] of options) {
+ const option = document.createElement("option");
+ option.value = value;
+ option.textContent = label;
+ select.appendChild(option);
+ }
+ select.value = options.some(([value]) => value === selected) ? selected : "pcs";
+}
+
+function populateCookUnitSelects(unitSystem = "metric") {
+ populateCookUnitSelect(els.cookItemUnit, unitSystem);
+ populateCookUnitSelect(els.cookShoppingUnit, unitSystem);
+}
+
+function renderCookRows(container, items, emptyText, rowFactory) {
+ if (!container) return;
+ container.innerHTML = "";
+ if (!items || !items.length) {
+ const empty = document.createElement("p");
+ empty.className = "cook-empty";
+ empty.textContent = emptyText;
+ container.appendChild(empty);
+ return;
+ }
+ for (const item of items) {
+ const row = document.createElement("div");
+ row.className = "cook-row";
+ rowFactory(row, item);
+ container.appendChild(row);
+ }
+}
+
+function cookInventoryMatchesSearch(item, query) {
+ const needle = String(query || "").trim().toLowerCase();
+ if (!needle) return true;
+ return [
+ cookDisplayName(item),
+ item?.name,
+ cookQuantity(item),
+ item?.expiration_date,
+ item?.storage_location,
+ ]
+ .map((value) => String(value || "").toLowerCase())
+ .some((value) => value.includes(needle));
+}
+
+function cookShoppingMatchesSearch(item, query) {
+ const needle = String(query || "").trim().toLowerCase();
+ if (!needle) return true;
+ return [cookDisplayName(item), item?.name, cookQuantity(item), item?.unit, item?.reason]
+ .map((value) => String(value || "").toLowerCase())
+ .some((value) => value.includes(needle));
+}
+
+function cookTodayDate() {
+ const now = new Date();
+ return new Date(now.getFullYear(), now.getMonth(), now.getDate());
+}
+
+function cookExpirationInfo(item) {
+ const raw = String(item?.expiration_date || "").trim();
+ if (!raw) {
+ return { state: "unknown", sort: 4, label: "No date", days: Infinity };
+ }
+ const date = new Date(`${raw}T00:00:00`);
+ if (Number.isNaN(date.getTime())) {
+ return { state: "unknown", sort: 4, label: "No date", days: Infinity };
+ }
+ const days = Math.ceil((date - cookTodayDate()) / 86400000);
+ if (days < 0) return { state: "expired", sort: 0, label: "Expired", days };
+ if (days <= 2) return { state: "critical", sort: 1, label: `${days}d`, days };
+ if (days <= 4) return { state: "soon", sort: 2, label: `${days}d`, days };
+ return { state: "good", sort: 3, label: "Good", days };
+}
+
+function sortCookInventory(items) {
+ return [...items].sort((a, b) => {
+ const aExp = cookExpirationInfo(a);
+ const bExp = cookExpirationInfo(b);
+ if (aExp.sort !== bExp.sort) return aExp.sort - bExp.sort;
+ if (aExp.days !== bExp.days) return aExp.days - bExp.days;
+ return cookDisplayName(a).localeCompare(cookDisplayName(b), undefined, { sensitivity: "base" });
+ });
+}
+
+function addCookInventoryCell(row, className, text) {
+ const cell = document.createElement("span");
+ cell.className = className;
+ cell.textContent = text;
+ row.appendChild(cell);
+}
+
+function addCookInventoryAutoCell(row, item) {
+ const cell = document.createElement("span");
+ cell.className = "auto";
+ const checkbox = document.createElement("input");
+ checkbox.type = "checkbox";
+ checkbox.checked = Boolean(item?.auto_add_shopping);
+ checkbox.setAttribute("aria-label", `Auto add ${cookDisplayName(item) || "item"} to shopping`);
+ checkbox.addEventListener("change", () => updateCookInventoryAutoAdd(item, checkbox.checked));
+ cell.appendChild(checkbox);
+ row.appendChild(cell);
+}
+
+function addCookInventoryUsedCell(row, item) {
+ const cell = document.createElement("span");
+ cell.className = "used";
+ const button = document.createElement("button");
+ button.className = "cook-mini-action";
+ button.type = "button";
+ button.textContent = "Use";
+ button.setAttribute("aria-label", `Use some ${cookDisplayName(item) || "item"}`);
+ button.addEventListener("click", () => markCookInventoryItemUsed(item));
+ cell.appendChild(button);
+ row.appendChild(cell);
+}
+
+function renderCookInventory(container, items, emptyText) {
+ if (!container) return;
+ container.innerHTML = "";
+ const header = document.createElement("div");
+ header.className = "cook-inventory-header";
+ for (const label of ["Food", "Qty", "Storage", "Fresh", "Auto", "Used"]) {
+ addCookInventoryCell(header, "", label);
+ }
+ container.appendChild(header);
+ if (!items || !items.length) {
+ const empty = document.createElement("p");
+ empty.className = "cook-empty";
+ empty.textContent = emptyText;
+ container.appendChild(empty);
+ return;
+ }
+ for (const item of sortCookInventory(items)) {
+ const info = cookExpirationInfo(item);
+ const row = document.createElement("div");
+ row.className = "cook-inventory-row";
+ row.dataset.expiration = info.state;
+ addCookInventoryCell(row, "food", cookDisplayName(item) || "Unnamed");
+ addCookInventoryCell(row, "qty", cookQuantity(item));
+ addCookInventoryCell(row, "storage", item?.storage_location || "-");
+ addCookInventoryCell(row, "freshness", info.label);
+ addCookInventoryAutoCell(row, item);
+ addCookInventoryUsedCell(row, item);
+ container.appendChild(row);
+ }
+}
+
+function renderCookAIwareState(data = {}) {
+ cookAIwareState = {
+ inventory: Array.isArray(data.inventory) ? data.inventory : cookAIwareState.inventory || [],
+ profile: data.profile && typeof data.profile === "object" ? data.profile : cookAIwareState.profile || {},
+ plan: data.plan && typeof data.plan === "object" ? data.plan : cookAIwareState.plan || {},
+ shopping: Array.isArray(data.shopping) ? data.shopping : cookAIwareState.shopping || [],
+ settings: data.settings && typeof data.settings === "object" ? data.settings : cookAIwareState.settings || {},
+ };
+
+ const inventoryQuery = els.cookInventorySearch?.value || "";
+ const visibleInventory = cookAIwareState.inventory.filter((item) => cookInventoryMatchesSearch(item, inventoryQuery));
+ renderCookInventory(els.cookInventoryList, visibleInventory, inventoryQuery ? "No matching inventory." : "No inventory yet.");
+
+ const planDays = Array.isArray(cookAIwareState.plan?.days) ? cookAIwareState.plan.days : [];
+ renderCookRows(els.cookPlanList, planDays, "No meal plan yet.", (row, day) => {
+ const title = document.createElement("strong");
+ title.textContent = String(day.day || "Day");
+ const meta = document.createElement("span");
+ const meals = Array.isArray(day.meals) ? day.meals : [];
+ meta.textContent = meals.map((meal) => `${meal.meal}: ${meal.title || "meal"}`).join(" | ") || "No meals";
+ row.appendChild(title);
+ row.appendChild(meta);
+ });
+
+ const shoppingQuery = els.cookShoppingSearch?.value || "";
+ const visibleShopping = cookAIwareState.shopping.filter((item) => cookShoppingMatchesSearch(item, shoppingQuery));
+ renderCookRows(els.cookShoppingList, visibleShopping, shoppingQuery ? "No matching shopping items." : "Shopping list is empty.", (row, item) => {
+ row.classList.add("cook-shopping-row");
+ const copy = document.createElement("div");
+ copy.className = "cook-row-copy";
+ const title = document.createElement("strong");
+ title.textContent = cookDisplayName(item) || "Unnamed item";
+ const meta = document.createElement("span");
+ meta.textContent = [cookQuantity(item), item?.reason].filter(Boolean).join(" - ");
+ copy.appendChild(title);
+ copy.appendChild(meta);
+ const addButton = document.createElement("button");
+ addButton.className = "cook-row-action";
+ addButton.type = "button";
+ addButton.textContent = "+";
+ addButton.setAttribute("aria-label", `Add ${cookDisplayName(item) || "item"} to inventory`);
+ addButton.addEventListener("click", () => moveCookShoppingItemToInventory(item));
+ row.appendChild(copy);
+ row.appendChild(addButton);
+ });
+
+ if (els.cookAdults) els.cookAdults.value = cookAIwareState.profile?.adults ?? "";
+ if (els.cookChildren) els.cookChildren.value = cookAIwareState.profile?.children ?? "";
+ if (els.cookLanguage) els.cookLanguage.value = cookAIwareState.settings?.language || "en";
+ if (els.cookUnitSystem) els.cookUnitSystem.value = cookAIwareState.settings?.unit_system || "metric";
+ if (els.cookUpcSource) els.cookUpcSource.value = cookAIwareState.settings?.upc_lookup_source || "openfoodfacts";
+ populateCookUnitSelects(cookAIwareState.settings?.unit_system || "metric");
+}
+
+function setCookView(view) {
+ const selected = String(view || "inventory");
+ const activeTabView =
+ selected === "inventory-add" ? "inventory" : selected === "shopping-add" ? "shopping" : selected;
+ for (const tab of els.cookTabs || []) {
+ tab.classList.toggle("active", tab.dataset.cookView === activeTabView);
+ }
+ if (els.cookAddInventoryView) {
+ els.cookAddInventoryView.classList.toggle("active", selected === "inventory-add");
+ }
+ if (els.cookAddShoppingView) {
+ els.cookAddShoppingView.classList.toggle("active", selected === "shopping-add");
+ }
+ for (const panel of els.cookPanels || []) {
+ panel.classList.toggle("active", panel.dataset.cookPanel === selected);
+ }
+}
+
+async function loadCookAIwareState({ silent = false } = {}) {
+ if (!runtimeStatus.cookaiware_active && !cookAIwareOpen) return;
+ try {
+ const data = await requestJson("/cooking/state");
+ renderCookAIwareState(data);
+ if (!silent) setStatus("CookAIware refreshed.", "ok");
+ } catch (error) {
+ if (!silent) setStatus(`CookAIware refresh failed: ${error.message}`, "error");
+ }
+}
+
+function openAttitudes() {
+ if (busy) return;
+ if (runtimeStatus.state !== "running") {
+ homeOpen = false;
+ }
+ attitudesOpen = true;
+ contactsOpen = false;
+ conversationsOpen = false;
+ cookAIwareOpen = false;
+ settingsOpen = false;
+ textChatOpen = false;
+ volumePanelOpen = false;
+ renderAttitudesGrid([], runtimeStatus.reachy_idle_attitude);
+ renderCallState();
+}
+
+async function openCookAIware() {
+ if (busy) return;
+ cookAIwareOpen = true;
+ contactsOpen = false;
+ conversationsOpen = false;
+ attitudesOpen = false;
+ settingsOpen = false;
+ textChatOpen = false;
+ homeOpen = false;
+ volumePanelOpen = false;
+ renderCallState();
+ await loadCookAIwareState({ silent: true });
+ setStatus("CookAIware ready.");
+}
+
+function cookItemPayload(nameEl, qtyEl, unitEl, expirationEl = null, storageEl = null, autoAddEl = null) {
+ const name = String(nameEl?.value || "").trim();
+ if (!name) return null;
+ const quantity = Number(qtyEl?.value || 1);
+ const item = {
+ name,
+ quantity: Number.isFinite(quantity) && quantity > 0 ? quantity : 1,
+ unit: String(unitEl?.value || "pcs").trim() || "pcs",
+ };
+ const expirationDate = String(expirationEl?.value || "").trim();
+ const storageLocation = String(storageEl?.value || "").trim();
+ if (expirationDate) item.expiration_date = expirationDate;
+ if (storageLocation) item.storage_location = storageLocation;
+ if (autoAddEl) item.auto_add_shopping = Boolean(autoAddEl.checked);
+ return item;
+}
+
+async function updateCookInventoryAutoAdd(item, autoAdd) {
+ if (busy) return;
+ const payload = {
+ name: item?.name || cookDisplayName(item),
+ unit: item?.unit || "pcs",
+ expiration_date: item?.expiration_date || null,
+ storage_location: item?.storage_location || null,
+ auto_add_shopping: Boolean(autoAdd),
+ };
+ setBusy(true);
+ try {
+ const data = await requestJson("/cooking/inventory", {
+ method: "POST",
+ body: JSON.stringify({ action: "set_auto_add", items: [payload] }),
+ });
+ renderCookAIwareState(data);
+ setStatus(autoAdd ? "Auto Add enabled for inventory item." : "Auto Add disabled for inventory item.", "ok");
+ } catch (error) {
+ renderCookAIwareState();
+ setStatus(`Inventory failed: ${error.message}`, "error");
+ } finally {
+ setBusy(false);
+ }
+}
+
+async function markCookInventoryItemUsed(item) {
+ if (busy) return;
+ const available = Number(item?.quantity || 0);
+ if (available <= 0) {
+ setStatus("Inventory item is already empty.", "warn");
+ return;
+ }
+ const amountText = window.prompt(`Amount used (${item?.unit || "pcs"})`, String(available));
+ if (amountText === null) return;
+ const amountUsed = Number(amountText);
+ const payload = {
+ name: item?.name || cookDisplayName(item),
+ quantity: Number.isFinite(amountUsed) && amountUsed > 0 ? amountUsed : 0,
+ unit: item?.unit || "pcs",
+ };
+ if (!payload.name || payload.quantity <= 0) {
+ setStatus("Enter an amount used.", "warn");
+ return;
+ }
+ setBusy(true);
+ try {
+ const data = await requestJson("/cooking/inventory", {
+ method: "POST",
+ body: JSON.stringify({ action: "use", items: [payload] }),
+ });
+ renderCookAIwareState(data);
+ setStatus("Inventory item marked used.", "ok");
+ } catch (error) {
+ setStatus(`Inventory failed: ${error.message}`, "error");
+ } finally {
+ setBusy(false);
+ }
+}
+
+async function addCookInventoryItem() {
+ if (busy) return;
+ const item = cookItemPayload(
+ els.cookItemName,
+ els.cookItemQty,
+ els.cookItemUnit,
+ els.cookItemExpiration,
+ els.cookItemStorage,
+ els.cookItemAutoAdd
+ );
+ if (!item) {
+ setStatus("Enter an inventory item.", "warn");
+ return;
+ }
+ setBusy(true);
+ try {
+ const data = await requestJson("/cooking/inventory", {
+ method: "POST",
+ body: JSON.stringify({ items: [item] }),
+ });
+ renderCookAIwareState(data);
+ els.cookItemName.value = "";
+ els.cookItemQty.value = "";
+ els.cookItemUnit.value = "";
+ if (els.cookItemExpiration) els.cookItemExpiration.value = "";
+ if (els.cookItemStorage) els.cookItemStorage.value = "";
+ if (els.cookItemAutoAdd) els.cookItemAutoAdd.checked = false;
+ setCookView("inventory");
+ setStatus("Inventory updated.", "ok");
+ } catch (error) {
+ setStatus(`Inventory failed: ${error.message}`, "error");
+ } finally {
+ setBusy(false);
+ }
+}
+
+async function lookupCookUpcItem(barcode) {
+ const code = String(barcode || "").replace(/\D/g, "");
+ if (!code) {
+ setStatus("Enter a UPC barcode.", "warn");
+ return null;
+ }
+ const data = await requestJson(`/cooking/upc/${encodeURIComponent(code)}`).catch((error) => {
+ throw new Error(error.userMessage || error.message || "UPC lookup failed.");
+ });
+ if (!data?.item?.name) {
+ throw new Error(data?.message || "UPC product not found.");
+ }
+ return data.item;
+}
+
+async function saveCookManualUpcItem(barcode) {
+ const code = String(barcode || "").replace(/\D/g, "");
+ const name = window.prompt("Food item name");
+ if (name === null) return null;
+ const cleanName = String(name || "").trim();
+ if (!cleanName) {
+ setStatus("Enter a food item name.", "warn");
+ return null;
+ }
+ const quantityText = window.prompt("Quantity", "1");
+ if (quantityText === null) return null;
+ const quantity = Number(quantityText);
+ const unit = window.prompt("Unit", "pcs");
+ if (unit === null) return null;
+ const item = {
+ name: cleanName,
+ quantity: Number.isFinite(quantity) && quantity > 0 ? quantity : 1,
+ unit: String(unit || "pcs").trim() || "pcs",
+ barcode: code,
+ source: cookAIwareState.settings?.upc_lookup_source || "openfoodfacts",
+ };
+ const data = await requestJson("/cooking/upc/cache", {
+ method: "POST",
+ body: JSON.stringify({ barcode: code, source: item.source, item }),
+ });
+ return data.item || item;
+}
+
+async function addCookUpcResolvedItem(target, item) {
+ if (!item) return;
+ const endpoint = target === "shopping" ? "/cooking/shopping" : "/cooking/inventory";
+ const body =
+ target === "shopping"
+ ? { action: "add", items: [{ name: item.name, quantity: item.quantity || 1, unit: item.unit || "pcs" }] }
+ : { items: [item] };
+ const data = await requestJson(endpoint, {
+ method: "POST",
+ body: JSON.stringify(body),
+ });
+ renderCookAIwareState(data);
+ setCookView(target === "shopping" ? "shopping" : "inventory");
+ setStatus(`${item.name} added from UPC.`, "ok");
+}
+
+async function addCookManualUpcItem(target) {
+ if (busy) return;
+ const barcode = window.prompt("UPC barcode");
+ if (barcode === null) return;
+ const code = String(barcode || "").replace(/\D/g, "");
+ setBusy(true);
+ try {
+ let item = null;
+ try {
+ item = await lookupCookUpcItem(code);
+ } catch (lookupError) {
+ if (!["not_found", "missing_name"].includes(lookupError.code)) throw lookupError;
+ setStatus("Add this UPC to the local database.", "warn");
+ item = await saveCookManualUpcItem(code);
+ }
+ await addCookUpcResolvedItem(target, item);
+ hideCookUpcPreview();
+ } catch (error) {
+ setStatus(error.message || "UPC lookup failed.", "error");
+ } finally {
+ setBusy(false);
+ }
+}
+
+function refreshCookUpcPreviewFrame() {
+ if (!els.cookUpcFrame) return;
+ els.cookUpcFrame.src = `/cooking/camera/frame?t=${Date.now()}`;
+}
+
+function showCookUpcPreview() {
+ if (!els.cookUpcScanner) return;
+ els.cookUpcScanner.hidden = false;
+ refreshCookUpcPreviewFrame();
+ clearInterval(cookUpcPreviewTimer);
+ cookUpcPreviewTimer = setInterval(refreshCookUpcPreviewFrame, 350);
+}
+
+function hideCookUpcPreview() {
+ clearInterval(cookUpcPreviewTimer);
+ cookUpcPreviewTimer = null;
+ if (els.cookUpcScanner) els.cookUpcScanner.hidden = true;
+ if (els.cookUpcFrame) els.cookUpcFrame.removeAttribute("src");
+}
+
+async function addCookUpcItem(target) {
+ if (busy) return;
+ cookUpcActiveTarget = target === "shopping" ? "shopping" : "inventory";
+ setBusy(true);
+ setStatus("Show the UPC barcode to Reachy.");
+ showCookUpcPreview();
+ try {
+ const data = await requestJson("/cooking/upc/scan", {
+ method: "POST",
+ body: JSON.stringify({ target }),
+ });
+ renderCookAIwareState(data);
+ setCookView(target === "shopping" ? "shopping" : "inventory");
+ setStatus(data.message || `${data.item?.name || "Item"} added from UPC.`, "ok");
+ } catch (error) {
+ const message = error.userMessage || error.message || "UPC camera scan failed.";
+ setStatus(message, "error");
+ } finally {
+ setBusy(false);
+ }
+}
+
+async function moveCookShoppingItemToInventory(item) {
+ if (busy) return;
+ const inventoryItem = {
+ name: item?.name || cookDisplayName(item),
+ quantity: Number(item?.quantity || 1),
+ unit: String(item?.unit || "pcs").trim() || "pcs",
+ };
+ if (!inventoryItem.name) {
+ setStatus("Shopping item is missing a name.", "warn");
+ return;
+ }
+ setBusy(true);
+ try {
+ await requestJson("/cooking/inventory", {
+ method: "POST",
+ body: JSON.stringify({ items: [inventoryItem] }),
+ });
+ const data = await requestJson("/cooking/shopping", {
+ method: "POST",
+ body: JSON.stringify({ action: "remove", items: [{ name: inventoryItem.name, unit: inventoryItem.unit }] }),
+ });
+ renderCookAIwareState(data);
+ setStatus("Moved shopping item to inventory.", "ok");
+ } catch (error) {
+ setStatus(`Move failed: ${error.message}`, "error");
+ } finally {
+ setBusy(false);
+ }
+}
+
+async function generateCookPlan() {
+ if (busy) return;
+ setBusy(true);
+ try {
+ const data = await requestJson("/cooking/plan/generate", { method: "POST" });
+ renderCookAIwareState(data);
+ setCookView("plan");
+ setStatus("Meal plan generated.", "ok");
+ } catch (error) {
+ setStatus(`Plan failed: ${error.message}`, "error");
+ } finally {
+ setBusy(false);
+ }
+}
+
+async function updateCookShopping(action, item = null) {
+ if (busy) return;
+ setBusy(true);
+ try {
+ const body = { action };
+ if (item) body.items = [item];
+ const data = await requestJson("/cooking/shopping", {
+ method: "POST",
+ body: JSON.stringify(body),
+ });
+ renderCookAIwareState(data);
+ if (els.cookShoppingName) els.cookShoppingName.value = "";
+ if (els.cookShoppingQty) els.cookShoppingQty.value = "";
+ if (els.cookShoppingUnit) els.cookShoppingUnit.value = "";
+ if (action === "add") setCookView("shopping");
+ setStatus("Shopping updated.", "ok");
+ } catch (error) {
+ setStatus(`Shopping failed: ${error.message}`, "error");
+ } finally {
+ setBusy(false);
+ }
+}
+
+async function addCookShoppingItem() {
+ const item = cookItemPayload(els.cookShoppingName, els.cookShoppingQty, els.cookShoppingUnit);
+ if (!item) {
+ setStatus("Enter a shopping item.", "warn");
+ return;
+ }
+ await updateCookShopping("add", item);
+}
+
+async function saveCookSettings() {
+ if (busy) return;
+ setBusy(true);
+ try {
+ const adults = els.cookAdults?.value === "" ? null : Number(els.cookAdults?.value);
+ const children = els.cookChildren?.value === "" ? null : Number(els.cookChildren?.value);
+ const profilePayload = {
+ adults: Number.isFinite(adults) ? adults : null,
+ children: Number.isFinite(children) ? children : null,
+ };
+ const profileData = await requestJson("/cooking/profile", {
+ method: "POST",
+ body: JSON.stringify(profilePayload),
+ });
+ const settingsData = await requestJson("/cooking/settings", {
+ method: "POST",
+ body: JSON.stringify({
+ language: els.cookLanguage?.value || "en",
+ unit_system: els.cookUnitSystem?.value || "metric",
+ upc_lookup_source: els.cookUpcSource?.value || "openfoodfacts",
+ }),
+ });
+ renderCookAIwareState({ ...profileData, ...settingsData });
+ setStatus("CookAIware settings saved.", "ok");
+ } catch (error) {
+ setStatus(`Settings failed: ${error.message}`, "error");
+ } finally {
+ setBusy(false);
+ }
+}
+
+function leaveCookAIwareView() {
+ if (busy) return;
+ cookAIwareOpen = false;
+ contactsOpen = false;
+ conversationsOpen = false;
+ attitudesOpen = false;
+ settingsOpen = false;
+ textChatOpen = false;
+ homeOpen = true;
+ renderCallState();
+ setStatus(runtimeStatus.cookaiware_active ? "CookAIware is still ready." : "");
+}
+
+function modelDirectoryItems() {
+ const selected = (runtimeStatus.openwebui_model || els.model.value || "").trim();
+ const models = availableModels.map((model) => String(model || "").trim()).filter(Boolean);
+ if (!runtimeStatus.contacts_require_vision && selected) {
+ models.push(selected);
+ }
+ return Array.from(new Set(models));
+}
+
+function renderAvatarSurface(className, imageUrl, initialText) {
+ const avatar = document.createElement("span");
+ avatar.className = className;
+ avatar.setAttribute("aria-hidden", "true");
+
+ const image = document.createElement("img");
+ image.alt = "";
+ image.hidden = true;
+
+ const initial = document.createElement("span");
+ initial.className = "avatar-initial";
+ initial.textContent = initialText;
+
+ avatar.appendChild(image);
+ avatar.appendChild(initial);
+ setAvatarImage(image, initial, imageUrl);
+ return avatar;
+}
+
+function renderModelDirectory() {
+ if (!els.modelList) {
+ return;
+ }
+
+ const selected = (runtimeStatus.openwebui_model || els.model.value || "").trim();
+ const models = modelDirectoryItems();
+ const key = JSON.stringify({
+ models,
+ selected,
+ busy,
+ state: runtimeStatus.state || "",
+ contactsRequireVision: runtimeStatus.contacts_require_vision,
+ });
+ if (key === renderedModelDirectoryKey) {
+ return;
+ }
+ renderedModelDirectoryKey = key;
+ els.modelList.innerHTML = "";
+
+ if (!models.length) {
+ const empty = document.createElement("p");
+ empty.className = "transcript-empty";
+ empty.textContent = statusLoaded ? "No contacts found." : "Loading contacts.";
+ els.modelList.appendChild(empty);
+ return;
+ }
+
+ for (const modelName of models) {
+ const item = document.createElement("button");
+ item.className = "model-contact";
+ item.type = "button";
+ item.disabled = busy || !statusLoaded;
+ item.dataset.selected = modelName === selected ? "true" : "false";
+ item.appendChild(
+ renderAvatarSurface("directory-avatar avatar-surface", modelProfileImageUrl(modelName), initialForModel(modelName))
+ );
+
+ const text = document.createElement("span");
+ text.className = "model-contact-text";
+
+ const name = document.createElement("span");
+ name.className = "model-contact-name";
+ name.textContent = modelName;
+
+ const meta = document.createElement("span");
+ meta.className = "model-contact-meta";
+ meta.textContent = modelName === selected ? "Ready to call" : "Tap to call";
+
+ const arrow = document.createElement("span");
+ arrow.className = "model-contact-arrow";
+ arrow.setAttribute("aria-hidden", "true");
+
+ text.appendChild(name);
+ text.appendChild(meta);
+ item.appendChild(text);
+ item.appendChild(arrow);
+ item.addEventListener("click", () => {
+ if (runtimeStatus.state === "running") {
+ if (modelName === selected) {
+ contactsOpen = false;
+ renderCallState();
+ return;
+ }
+ setStatus("End this call before switching contacts.", "warn");
+ return;
+ }
+ startConversation(modelName);
+ });
+ els.modelList.appendChild(item);
+ }
+}
+
+function shortChatId(chatId) {
+ const id = String(chatId || "").trim();
+ return id ? id.slice(0, 8) : "";
+}
+
+function conversationTimestampLabel(value) {
+ if (value === null || value === undefined || value === "") {
+ return "";
+ }
+ const numeric = Number(value);
+ const date = Number.isFinite(numeric)
+ ? new Date(numeric < 1000000000000 ? numeric * 1000 : numeric)
+ : new Date(String(value));
+ if (Number.isNaN(date.getTime())) {
+ return "";
+ }
+ return date.toLocaleString([], {
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ });
+}
+
+function renderConversationDirectory() {
+ if (!els.conversationList) {
+ return;
+ }
+
+ const selected = (els.chatId.value || runtimeStatus.openwebui_chat_id || "").trim();
+ const key = JSON.stringify({
+ conversations: availableConversations,
+ selected,
+ busy,
+ statusLoaded,
+ });
+ if (key === renderedConversationDirectoryKey) {
+ return;
+ }
+ renderedConversationDirectoryKey = key;
+ els.conversationList.innerHTML = "";
+
+ if (!availableConversations.length) {
+ const empty = document.createElement("p");
+ empty.className = "transcript-empty";
+ empty.textContent = conversationRefreshInFlight ? "Loading conversations." : "No conversations found.";
+ els.conversationList.appendChild(empty);
+ return;
+ }
+
+ for (const conversation of availableConversations) {
+ const chatId = String(conversation.id || "").trim();
+ if (!chatId) {
+ continue;
+ }
+ const title = String(conversation.title || "Untitled conversation").trim() || "Untitled conversation";
+ const updated = conversationTimestampLabel(conversation.updated_at || conversation.created_at);
+ const item = document.createElement("button");
+ item.className = "model-contact conversation-contact";
+ item.type = "button";
+ item.disabled = busy || !statusLoaded;
+ item.dataset.selected = chatId === selected ? "true" : "false";
+
+ const avatar = document.createElement("span");
+ avatar.className = "directory-avatar avatar-surface";
+ avatar.setAttribute("aria-hidden", "true");
+ const initial = document.createElement("span");
+ initial.className = "avatar-initial";
+ initial.textContent = initialForModel(title || "Chat");
+ avatar.appendChild(initial);
+ item.appendChild(avatar);
+
+ const text = document.createElement("span");
+ text.className = "model-contact-text";
+
+ const name = document.createElement("span");
+ name.className = "model-contact-name";
+ name.textContent = title;
+
+ const meta = document.createElement("span");
+ meta.className = "model-contact-meta";
+ const parts = [shortChatId(chatId), updated].filter(Boolean);
+ meta.textContent = chatId === selected
+ ? `Current chat${parts.length ? ` - ${parts.join(" - ")}` : ""}`
+ : parts.join(" - ");
+
+ const arrow = document.createElement("span");
+ arrow.className = "model-contact-arrow";
+ arrow.setAttribute("aria-hidden", "true");
+
+ text.appendChild(name);
+ text.appendChild(meta);
+ item.appendChild(text);
+ item.appendChild(arrow);
+ item.addEventListener("click", () => selectConversation(conversation));
+ els.conversationList.appendChild(item);
+ }
+}
+
+function renderCallState() {
+ const state = runtimeStatus.state || "loading";
+ const canStart = runtimeStatus.can_start === true;
+ const model = (runtimeStatus.openwebui_model || "").trim();
+ const modelName = model || (statusLoaded ? "No model saved" : "Loading model");
+ if (pendingStart || state === "configuring" || state === "shutting_down") {
+ contactsOpen = false;
+ conversationsOpen = false;
+ attitudesOpen = false;
+ textChatOpen = false;
+ if (!runtimeStatus.cookaiware_active && !cookAIwareOpen) {
+ cookAIwareOpen = false;
+ }
+ settingsOpen = false;
+ homeOpen = false;
+ }
+ const view = !statusLoaded
+ ? "readying"
+ : settingsOpen
+ ? "settings"
+ : conversationsOpen
+ ? "conversations"
+ : contactsOpen
+ ? "contacts"
+ : attitudesOpen
+ ? "attitudes"
+ : textChatOpen
+ ? "textchat"
+ : cookAIwareOpen
+ ? "cookaiware"
+ : homeOpen
+ ? "home"
+ : state === "running"
+ ? "chat"
+ : pendingStart || state === "configuring" || state === "shutting_down"
+ ? "calling"
+ : "home";
+
+ activeModelName = modelName;
+ els.phone.dataset.state = state;
+ els.phone.dataset.view = view;
+ if (els.topbarTitle) {
+ els.topbarTitle.textContent =
+ view === "contacts" ? "Contacts" :
+ view === "conversations" ? "Chat History" :
+ view === "attitudes" ? "Attitudes" :
+ view === "textchat" ? "Messages" :
+ view === "cookaiware" ? "CookAIware" :
+ view === "settings" ? "Settings" :
+ view === "calling" || view === "chat" ? modelName :
+ "Reachy OpenWebUI";
+ }
+ els.contactName.textContent = modelName;
+ els.modelInitial.textContent = initialForModel(modelName);
+ if (els.topbarModelInitial) els.topbarModelInitial.textContent = initialForModel(modelName);
+ refreshModelImage(modelName);
+ if (els.stateChip) {
+ els.stateChip.textContent = prettyState(state);
+ els.stateChip.dataset.state = state;
+ }
+
+ let summary = "Checking";
+ let message = "Looking for saved OpenWebUI settings...";
+ let label = "Call";
+ let startDisabled = true;
+ let stopDisabled = true;
+ let muteDisabled = true;
+ let backDisabled = true;
+ let contactsDisabled = true;
+ let activityMode = "waiting";
+
+ if (!statusLoaded) {
+ summary = "Getting Ready";
+ message = "Connecting to Reachy OpenWebUI...";
+ label = "Call";
+ runningStartedAt = null;
+ connectingStartedAt = null;
+ } else if (settingsOpen) {
+ summary = "Settings";
+ message = "Review OpenWebUI and Reachy options.";
+ label = state === "running" ? "Live" : "Call";
+ backDisabled = false;
+ startDisabled = state === "running" || !canStart || busy;
+ stopDisabled = state === "running" ? busy : true;
+ muteDisabled = state === "running" ? busy : true;
+ contactsDisabled = state === "running" ? busy : true;
+ activityMode = "waiting";
+ } else if (conversationsOpen) {
+ summary = "Conversations";
+ message = "Pick an OpenWebUI chat to continue.";
+ label = state === "running" ? "Live" : "Call";
+ backDisabled = false;
+ startDisabled = state === "running" || !canStart || busy;
+ stopDisabled = state === "running" ? busy : true;
+ muteDisabled = state === "running" ? busy : true;
+ contactsDisabled = state === "running" ? busy : true;
+ activityMode = "waiting";
+ } else if (attitudesOpen) {
+ summary = "Attitudes";
+ message = "Pick an attitude for Reachy.";
+ label = state === "running" ? "Live" : "Call";
+ backDisabled = false;
+ startDisabled = state === "running" || !canStart || busy;
+ stopDisabled = state === "running" ? busy : true;
+ muteDisabled = state === "running" ? busy : true;
+ contactsDisabled = state === "running" ? busy : true;
+ activityMode = "waiting";
+ } else if (textChatOpen) {
+ summary = "Messages";
+ message = state === "running" ? "Type a message to Reachy." : "Send will start Reachy before posting.";
+ label = state === "running" ? "Live" : "Call";
+ backDisabled = false;
+ startDisabled = state === "running" || !canStart || busy;
+ stopDisabled = state === "running" ? busy : true;
+ muteDisabled = state === "running" ? busy : true;
+ contactsDisabled = state === "running" ? busy : true;
+ activityMode = "waiting";
+ } else if (cookAIwareOpen) {
+ summary = "CookAIware";
+ message = runtimeStatus.cookaiware_active ? "Chef mode is ready." : "Ready to start chef.";
+ label = state === "running" ? "Live" : state === "configuring" ? "Starting" : state === "shutting_down" ? "Ending" : "Call";
+ if (state === "configuring") {
+ message = "Starting chef.";
+ activityMode = "thinking";
+ } else if (state === "shutting_down") {
+ message = "Closing chef call.";
+ activityMode = "thinking";
+ } else if (state === "running") {
+ activityMode = runtimeStatus.muted ? "waiting" : "listening";
+ }
+ backDisabled = false;
+ startDisabled = state === "running" || !canStart || busy;
+ stopDisabled = state === "running" ? busy : true;
+ muteDisabled = state === "running" ? busy : true;
+ contactsDisabled = true;
+ activityMode = "waiting";
+ } else if (contactsOpen) {
+ summary = "Contacts";
+ message = "Pick a model contact to call.";
+ label = state === "running" ? "Live" : "Call";
+ backDisabled = false;
+ startDisabled = state === "running" || !canStart || busy;
+ stopDisabled = state === "running" ? busy : true;
+ muteDisabled = state === "running" ? busy : true;
+ contactsDisabled = state === "running" ? busy : true;
+ activityMode = "waiting";
+ } else if (!canStart) {
+ summary = "Setup needed";
+ message = "Open settings, save a URL and contact, then Reachy can call.";
+ label = "Call";
+ runningStartedAt = null;
+ connectingStartedAt = null;
+ } else if (state === "running") {
+ pendingStart = false;
+ summary = runtimeStatus.muted ? "Muted" : "Listening";
+ message = runtimeStatus.muted ? "Mic muted." : "Connected.";
+ label = "Live";
+ stopDisabled = busy;
+ muteDisabled = busy;
+ backDisabled = busy;
+ contactsDisabled = busy;
+ activityMode = "listening";
+ if (!runningStartedAt) runningStartedAt = Date.now();
+ connectingStartedAt = null;
+ } else if (state === "configuring") {
+ summary = "Starting chat";
+ message = "Starting chat and settings...";
+ label = "Starting";
+ activityMode = "thinking";
+ stopDisabled = busy;
+ backDisabled = busy;
+ runningStartedAt = null;
+ if (!connectingStartedAt) connectingStartedAt = Date.now();
+ } else if (state === "shutting_down") {
+ summary = "Ending";
+ message = "Closing the call.";
+ label = "Ending";
+ activityMode = "thinking";
+ runningStartedAt = null;
+ connectingStartedAt = null;
+ } else {
+ if (!startFlowActive) {
+ pendingStart = false;
+ }
+ summary = "Ready";
+ message = "Choose a contact to call.";
+ label = "Call";
+ startDisabled = busy;
+ runningStartedAt = null;
+ connectingStartedAt = null;
+ }
+
+ els.settingsToggle.disabled = !statusLoaded;
+ if (!statusLoaded) {
+ settingsOpen = false;
+ }
+ els.settingsToggle.classList.toggle("active", settingsOpen);
+ els.connectionSummary.textContent = summary;
+ els.connectionText.textContent = message;
+ els.callLabel.textContent = label;
+ els.muteLabel.textContent = runtimeStatus.muted ? "Unmute" : "Mute";
+ els.mute.classList.toggle("active", Boolean(runtimeStatus.muted));
+ els.activityVisual.dataset.mode = activityMode;
+ if (els.back) els.back.disabled = backDisabled;
+ if (els.bottomBack) els.bottomBack.disabled = backDisabled;
+ els.contacts.disabled = contactsDisabled;
+ els.contacts.classList.toggle("active", contactsOpen && state === "running");
+ if (els.homeContacts) els.homeContacts.disabled = busy || !statusLoaded;
+ if (els.homeMessages) els.homeMessages.disabled = busy || !statusLoaded;
+ if (els.homeChatHistory) els.homeChatHistory.disabled = busy || !statusLoaded;
+ if (els.homeAttitudes) els.homeAttitudes.disabled = busy || !statusLoaded;
+ if (els.homeVolume) els.homeVolume.disabled = busy || !statusLoaded;
+ if (els.volumePanel) els.volumePanel.hidden = !volumePanelOpen || view !== "home";
+ if (els.volumeScrim) els.volumeScrim.hidden = !volumePanelOpen || view !== "home";
+ if (els.homeCookAIware) {
+ els.homeCookAIware.disabled = busy || !statusLoaded;
+ els.homeCookAIware.classList.toggle("active", Boolean(runtimeStatus.cookaiware_active));
+ }
+ if (els.quickConnect) els.quickConnect.disabled = busy || !statusLoaded || (state !== "running" && !canStart);
+ if (els.sendText) els.sendText.disabled = busy || !statusLoaded || !canStart;
+ if (els.textMessageInput) els.textMessageInput.disabled = busy || !statusLoaded || !canStart;
+ if (els.textBack) els.textBack.disabled = backDisabled;
+ if (els.attachImage) els.attachImage.disabled = busy || !statusLoaded || !canStart;
+ if (els.textActions) {
+ els.textActions.disabled = busy || !statusLoaded;
+ els.textActions.classList.toggle("active", !els.textActionsMenu?.hidden);
+ }
+ if (els.textMicMute) els.textMicMute.textContent = runtimeStatus.muted ? "Unmute mic" : "Mute mic";
+ if (els.textSpeakerMute) {
+ els.textSpeakerMute.textContent = runtimeStatus.speaker_muted ? "Unmute speaker" : "Mute speaker";
+ }
+ if (els.cookAIwareStart) {
+ els.cookAIwareStart.disabled = state === "running" ? stopDisabled : startDisabled;
+ els.cookAIwareStart.textContent = state === "running" && runtimeStatus.cookaiware_active ? "Stop Chef" : "Start Chef";
+ els.cookAIwareStart.classList.toggle("danger", state === "running" && runtimeStatus.cookaiware_active);
+ }
+ if (els.cookAIwareBack) els.cookAIwareBack.disabled = busy;
+ if (els.cookAIwareRefresh) els.cookAIwareRefresh.disabled = busy || !statusLoaded || !runtimeStatus.cookaiware_active;
+ if (els.cookAIwareMute) {
+ els.cookAIwareMute.disabled = muteDisabled;
+ els.cookAIwareMute.textContent = runtimeStatus.muted ? "Unmute" : "Mute";
+ els.cookAIwareMute.classList.toggle("active", Boolean(runtimeStatus.muted));
+ }
+ for (const button of [
+ els.cookAddItem,
+ els.cookGeneratePlan,
+ els.cookAddShopping,
+ els.cookGenerateShopping,
+ els.cookClearShopping,
+ els.cookSaveProfile,
+ ]) {
+ if (button) button.disabled = busy || !runtimeStatus.cookaiware_active;
+ }
+ els.start.disabled = startDisabled;
+ els.stop.disabled = stopDisabled;
+ els.mute.disabled = muteDisabled;
+ renderModelDirectory();
+ renderConversationDirectory();
+ updateTimer();
+ updateStatusVisibility();
+}
+
+function updateTimer() {
+ const startTime = runningStartedAt || connectingStartedAt;
+ if (!startTime) {
+ els.callDuration.textContent = "00:00";
+ els.slowStartMessage.hidden = true;
+ return;
+ }
+ const totalSeconds = Math.max(0, Math.floor((Date.now() - startTime) / 1000));
+ const minutes = String(Math.floor(totalSeconds / 60)).padStart(2, "0");
+ const seconds = String(totalSeconds % 60).padStart(2, "0");
+ els.callDuration.textContent = `${minutes}:${seconds}`;
+ els.slowStartMessage.hidden = !(connectingStartedAt && totalSeconds >= 10);
+}
+
+function updatePhoneClock() {
+ const now = new Date();
+ const statusTime = now.toLocaleTimeString([], {
+ hour: "numeric",
+ minute: "2-digit",
+ hour12: true,
+ });
+ const homeParts = new Intl.DateTimeFormat([], {
+ hour: "numeric",
+ minute: "2-digit",
+ hour12: true,
+ }).formatToParts(now);
+ let homeTime = "";
+ let homePeriod = "";
+ for (const part of homeParts) {
+ if (part.type === "dayPeriod") {
+ homePeriod = part.value.toUpperCase();
+ } else {
+ homeTime += part.value;
+ }
+ }
+ if (els.homeClock) {
+ els.homeClock.textContent = homeTime.trim();
+ }
+ if (els.homePeriod) {
+ els.homePeriod.textContent = homePeriod || "";
+ }
+ if (els.homeDate) {
+ els.homeDate.textContent = now.toLocaleDateString([], {
+ weekday: "long",
+ month: "long",
+ day: "numeric",
+ });
+ }
+}
+
+function initialForRole(role) {
+ if (role === "user") {
+ return initialForModel(runtimeStatus.openwebui_user_name || "You");
+ }
+ return initialForModel(activeModelName || runtimeStatus.openwebui_model || "Reachy");
+}
+
+function avatarUrlForRole(role) {
+ return role === "user" ? userProfileImageUrl() : modelProfileImageUrl(activeModelName);
+}
+
+function renderChatAvatar(role) {
+ return renderAvatarSurface(`chat-avatar avatar-surface ${role}`, avatarUrlForRole(role), initialForRole(role));
+}
+
+function renderMessageRow(role, bubble) {
+ const row = document.createElement("div");
+ row.className = `message-row ${role}`;
+ row.appendChild(renderChatAvatar(role));
+ row.appendChild(bubble);
+ return row;
+}
+
+function renderTypingBubble(role) {
+ const bubble = document.createElement("article");
+ bubble.className = `chat-bubble ${role} typing-bubble`;
+ bubble.setAttribute("aria-label", role === "user" ? "You are speaking" : "Reachy is responding");
+ for (let i = 0; i < 3; i += 1) {
+ bubble.appendChild(document.createElement("span"));
+ }
+ return renderMessageRow(role, bubble);
+}
+
+function renderTranscript(messages = [], indicators = {}) {
+ const safeMessages = Array.isArray(messages) ? messages.slice(-20) : [];
+ const userTyping = Boolean(indicators.user);
+ const assistantTyping = Boolean(indicators.assistant);
+ const key = JSON.stringify({
+ messages: safeMessages,
+ userTyping,
+ assistantTyping,
+ assistantAvatar: modelProfileImageUrl(activeModelName),
+ userAvatar: userProfileImageUrl(),
+ userName: runtimeStatus.openwebui_user_name || "",
+ });
+ if (key === renderedTranscriptKey || !els.transcript) {
+ return;
+ }
+ renderedTranscriptKey = key;
+ els.transcript.innerHTML = "";
+
+ if (!safeMessages.length && !userTyping && !assistantTyping) {
+ const empty = document.createElement("p");
+ empty.className = "transcript-empty";
+ empty.textContent = runtimeStatus.state === "running" ? "Say something to Reachy." : "Messages will appear here.";
+ els.transcript.appendChild(empty);
+ return;
+ }
+
+ for (const msg of safeMessages) {
+ const role = String(msg.role || "assistant").toLowerCase() === "user" ? "user" : "assistant";
+ const content = String(msg.content || "").trim();
+ if (!content) {
+ continue;
+ }
+ const bubble = document.createElement("article");
+ bubble.className = `chat-bubble ${role}`;
+ bubble.textContent = content.length > 500 ? `${content.slice(0, 500)}...` : content;
+ els.transcript.appendChild(renderMessageRow(role, bubble));
+ }
+
+ if (userTyping) {
+ els.transcript.appendChild(renderTypingBubble("user"));
+ }
+
+ if (assistantTyping) {
+ els.transcript.appendChild(renderTypingBubble("assistant"));
+ }
+
+ els.transcript.scrollTop = els.transcript.scrollHeight;
+}
+
+function assistantConversationRefreshKey(data) {
+ const messages = Array.isArray(data?.transcript_messages) ? data.transcript_messages : [];
+ let assistantCount = 0;
+ let lastAssistant = "";
+ for (const message of messages) {
+ const role = String(message?.role || "assistant").toLowerCase();
+ const content = String(message?.content || "").trim();
+ if (role === "user" || !content) {
+ continue;
+ }
+ assistantCount += 1;
+ lastAssistant = content;
+ }
+ if (!assistantCount || !lastAssistant) {
+ return "";
+ }
+ return [
+ data?.openwebui_chat_id || "",
+ assistantCount,
+ messages.length,
+ lastAssistant.slice(0, 160),
+ ].join("|");
+}
+
+function maybeRefreshConversationsAfterAssistantResponse(data) {
+ const key = assistantConversationRefreshKey(data);
+ if (!assistantConversationRefreshStarted) {
+ assistantConversationRefreshStarted = true;
+ lastAssistantConversationRefreshKey = key;
+ return;
+ }
+ if (!key) {
+ return;
+ }
+ if (key === lastAssistantConversationRefreshKey) {
+ return;
+ }
+ if (data?.state !== "running" || data?.assistant_typing) {
+ return;
+ }
+ const now = Date.now();
+ if (now - lastConversationAutoRefreshAt < 1500) {
+ return;
+ }
+ lastConversationAutoRefreshAt = now;
+ lastAssistantConversationRefreshKey = key;
+ refreshConversations({ silent: true, background: true, clearBeforeLoad: false });
+}
+
+function applyRuntimeStatus(data) {
+ statusLoaded = true;
+ runtimeStatus = {
+ state: data.state || "stopped",
+ can_start: Boolean(data.can_start),
+ openwebui_model: data.openwebui_model || "",
+ openwebui_chat_id: data.openwebui_chat_id || "",
+ openwebui_user_id: data.openwebui_user_id || "",
+ openwebui_user_name: data.openwebui_user_name || "You",
+ contacts_require_vision: data.contacts_require_vision !== false,
+ weather_postal_code: data.weather_postal_code || "",
+ reachy_idle_attitude: data.reachy_idle_attitude || "calm",
+ available_idle_attitudes: Array.isArray(data.available_idle_attitudes) ? data.available_idle_attitudes : [],
+ available_tools: Array.isArray(data.available_tools) ? data.available_tools : [],
+ phone_tools: Array.isArray(data.phone_tools) ? data.phone_tools : [],
+ cookaiware_tools: Array.isArray(data.cookaiware_tools) ? data.cookaiware_tools : [],
+ enabled_tools: Array.isArray(data.enabled_tools) ? data.enabled_tools : [],
+ active_profile: data.active_profile || "",
+ cookaiware_active: Boolean(data.cookaiware_active),
+ muted: Boolean(data.muted),
+ speaker_muted: Boolean(data.speaker_muted),
+ mic_gain: Number(data.mic_gain ?? 1),
+ mic_volume: Number(data.mic_volume ?? 100),
+ speaker_volume: Number(data.speaker_volume ?? 100),
+ };
+ if (runtimeStatus.state !== "configuring" && !startFlowActive) {
+ pendingStart = false;
+ }
+ els.envPath.textContent = data.env_path || "";
+ savedApiKeyPresent = Boolean(data.has_openwebui_api_key);
+ savedTokenPresent = Boolean(data.has_openwebui_token);
+ apiKeyRequired = Boolean(data.requires_openwebui_api_key);
+ updateSecretPlaceholders();
+ writeCachedSettings(data);
+ renderCallState();
+ renderTranscript(data.transcript_messages || [], {
+ user: data.user_typing,
+ assistant: data.assistant_typing,
+ });
+ maybeRefreshConversationsAfterAssistantResponse(data);
+}
+
+function applyFormStatus(data, { force = false } = {}) {
+ if (formDirty && !force) {
+ return;
+ }
+ els.url.value = data.openwebui_url || "";
+ setSelectedModel(data.openwebui_model || "");
+ els.chatId.value = data.openwebui_chat_id || "";
+ if (els.contactsRequireVision) {
+ els.contactsRequireVision.checked = data.contacts_require_vision !== false;
+ }
+ if (els.weatherPostalCode) {
+ els.weatherPostalCode.value = data.weather_postal_code || "";
+ }
+ if (!attitudesOpen) {
+ renderIdleAttitudes(data.available_idle_attitudes || [], data.reachy_idle_attitude || "calm");
+ }
+ renderToolSettings(data.available_tools || [], data.enabled_tools || [], {
+ phone_tools: data.phone_tools || [],
+ cookaiware_tools: data.cookaiware_tools || [],
+ });
+
+ const gain = Number(data.mic_gain || 1);
+ const safeGain = Number.isFinite(gain) ? Math.min(3, Math.max(0.25, gain)) : 1;
+ els.micGain.value = String(safeGain);
+ els.micGainValue.value = safeGain.toFixed(2).replace(/\.?0+$/, "");
+ updateVolumeControls({
+ mic_volume: data.mic_volume,
+ speaker_volume: data.speaker_volume,
+ });
+}
+
+function formatVolumePercent(value) {
+ const percent = Math.round(Number(value || 0));
+ return `${percent}%`;
+}
+
+function updateVolumeControls(data = {}) {
+ const micVolume = Number(data.mic_volume ?? runtimeStatus.mic_volume ?? 100);
+ const speakerVolume = Number(data.speaker_volume ?? runtimeStatus.speaker_volume ?? 100);
+ const safeMic = Number.isFinite(micVolume) ? Math.min(100, Math.max(0, micVolume)) : 100;
+ const safeSpeaker = Number.isFinite(speakerVolume) ? Math.min(100, Math.max(0, speakerVolume)) : 100;
+ if (els.homeMicVolume) els.homeMicVolume.value = String(safeMic);
+ if (els.homeMicVolumeValue) els.homeMicVolumeValue.textContent = formatVolumePercent(safeMic);
+ if (els.homeSpeakerVolume) els.homeSpeakerVolume.value = String(safeSpeaker);
+ if (els.homeSpeakerVolumeValue) els.homeSpeakerVolumeValue.textContent = formatVolumePercent(safeSpeaker);
+}
+
+function queueVolumeSave(field) {
+ if (field) {
+ pendingVolumeFields.add(field);
+ }
+ updateVolumeControls({
+ mic_volume: els.homeMicVolume?.value,
+ speaker_volume: els.homeSpeakerVolume?.value,
+ });
+ if (volumeSaveTimer) {
+ window.clearTimeout(volumeSaveTimer);
+ }
+ volumeSaveTimer = window.setTimeout(() => saveVolumeLevels(), 220);
+}
+
+async function saveVolumeLevels() {
+ volumeSaveTimer = null;
+ if (!statusLoaded) return;
+ const micVolume = Number(els.homeMicVolume?.value ?? runtimeStatus.mic_volume ?? 100);
+ const speakerVolume = Number(els.homeSpeakerVolume?.value ?? runtimeStatus.speaker_volume ?? 100);
+ const payload = {};
+ if (pendingVolumeFields.has("mic_volume")) {
+ payload.mic_volume = micVolume;
+ }
+ if (pendingVolumeFields.has("speaker_volume")) {
+ payload.speaker_volume = speakerVolume;
+ }
+ pendingVolumeFields = new Set();
+ if (!Object.keys(payload).length) return;
+ try {
+ const data = await requestJson("/volume", {
+ method: "POST",
+ body: JSON.stringify(payload),
+ });
+ applyStatus(data, { force: true });
+ setStatus(data.message || "Volume updated.", "ok");
+ } catch (error) {
+ setStatus(`Volume failed: ${error.message}`, "error");
+ }
+}
+
+function applyStatus(data, options = {}) {
+ applyRuntimeStatus(data);
+ applyFormStatus(data, options);
+}
+
+async function maybeAutoRefreshContacts(data) {
+ const url = String(data?.openwebui_url || "").trim();
+ if (!url || !statusLoaded) {
+ return;
+ }
+
+ const key = `${url}|${String(data?.openwebui_model || "").trim()}`;
+ const now = Date.now();
+ if (
+ autoModelRefreshInFlight ||
+ autoModelRefreshKey === key ||
+ now - lastAutoModelRefreshAttemptAt < 5000
+ ) {
+ return;
+ }
+
+ lastAutoModelRefreshAttemptAt = now;
+ autoModelRefreshInFlight = true;
+ try {
+ const refreshed = await refreshModels({ silent: true });
+ if (refreshed) {
+ autoModelRefreshKey = key;
+ }
+ } finally {
+ autoModelRefreshInFlight = false;
+ }
+}
+
+async function requestJson(path, options = {}) {
+ const endpoint = new URL(String(path).replace(/^\//, ""), window.location.href);
+ const response = await fetch(endpoint, {
+ headers: { "Content-Type": "application/json" },
+ ...options,
+ });
+ const data = await response.json().catch(() => ({}));
+ if (!response.ok || data.ok === false) {
+ const error = new Error(data.message || data.error || `Request failed: ${response.status}`);
+ error.userMessage = data.message || "";
+ error.code = data.error || "";
+ error.status = response.status;
+ throw error;
+ }
+ return data;
+}
+
+function shortForecastDay(value) {
+ const date = new Date(`${value}T12:00:00`);
+ if (Number.isNaN(date.getTime())) {
+ return "";
+ }
+ return date.toLocaleDateString([], { weekday: "short" });
+}
+
+function weatherConditionKind(condition = "") {
+ const value = String(condition || "").toLowerCase();
+ if (value.includes("thunder")) return "storm";
+ if (value.includes("snow") || value.includes("freezing")) return "snow";
+ if (value.includes("rain") || value.includes("shower") || value.includes("drizzle")) return "rain";
+ if (value.includes("fog")) return "fog";
+ if (value.includes("cloud")) return "cloud";
+ return "sun";
+}
+
+function renderWeatherForecast(data = {}) {
+ if (!els.weatherForecast || !els.homeWeather) {
+ return;
+ }
+ els.homeWeather.classList.toggle("forecast-open", weatherForecastOpen);
+ els.homeWeather.setAttribute("aria-expanded", String(weatherForecastOpen));
+ els.weatherForecast.hidden = !weatherForecastOpen;
+ els.weatherForecast.innerHTML = "";
+ if (!weatherForecastOpen) {
+ return;
+ }
+ const days = Array.isArray(data.forecast) ? data.forecast.slice(0, 5) : [];
+ if (!days.length) {
+ const empty = document.createElement("p");
+ empty.className = "weather-forecast-empty";
+ empty.textContent = data.configured === false ? "Set ZIP" : "Forecast unavailable";
+ els.weatherForecast.appendChild(empty);
+ return;
+ }
+ for (const day of days) {
+ const item = document.createElement("span");
+ item.className = "weather-day";
+
+ const label = document.createElement("strong");
+ label.textContent = shortForecastDay(day.date) || "Day";
+
+ const icon = document.createElement("span");
+ icon.className = `weather-day-icon ${weatherConditionKind(day.condition)}`;
+ icon.setAttribute("aria-hidden", "true");
+
+ const temps = document.createElement("span");
+ temps.className = "weather-day-temp";
+ const high = day.high === null || day.high === undefined ? "--" : day.high;
+ const low = day.low === null || day.low === undefined ? "--" : day.low;
+ temps.textContent = `${high}/${low}`;
+
+ item.appendChild(label);
+ item.appendChild(icon);
+ item.appendChild(temps);
+ els.weatherForecast.appendChild(item);
+ }
+}
+
+function renderWeather(data = {}) {
+ if (!els.weatherTemp || !els.weatherLocation || !els.weatherCondition) {
+ return;
+ }
+ lastWeatherData = data;
+ if (data.configured === false) {
+ els.weatherLocation.textContent = "Weather";
+ els.weatherTemp.textContent = "Set ZIP";
+ els.weatherCondition.textContent = "Add postal code in Settings";
+ renderWeatherForecast(data);
+ return;
+ }
+ if (data.ok === false) {
+ els.weatherLocation.textContent = "Weather";
+ els.weatherTemp.textContent = "--";
+ els.weatherCondition.textContent = "Weather unavailable";
+ renderWeatherForecast(data);
+ return;
+ }
+ const temp = data.temperature;
+ const unit = data.unit || "F";
+ els.weatherLocation.textContent = data.location || data.postal_code || "Weather";
+ els.weatherTemp.textContent = temp === null || temp === undefined ? "--" : `${temp}°${unit}`;
+ els.weatherCondition.textContent = data.condition || "Current conditions";
+ renderWeatherForecast(data);
+}
+
+async function refreshWeather({ force = false } = {}) {
+ const postalCode = String(runtimeStatus.weather_postal_code || els.weatherPostalCode?.value || "").trim();
+ if (!force && weatherRefreshInFlight) {
+ return;
+ }
+ if (!force && postalCode && postalCode === lastWeatherPostalCode) {
+ return;
+ }
+ weatherRefreshInFlight = true;
+ try {
+ const data = await requestJson("/weather");
+ lastWeatherPostalCode = postalCode;
+ renderWeather(data);
+ } catch (_error) {
+ renderWeather({ ok: false, configured: Boolean(postalCode) });
+ } finally {
+ weatherRefreshInFlight = false;
+ }
+}
+
+async function refreshStatus({ silent = false, updateForm = false, updateModels = false } = {}) {
+ try {
+ const data = await requestJson("/status");
+ applyStatus(data, { force: updateForm });
+ if (String(data.weather_postal_code || "").trim() !== lastWeatherPostalCode) {
+ refreshWeather({ force: true });
+ }
+ if (updateModels) {
+ await refreshModels({ silent: true });
+ } else {
+ await maybeAutoRefreshContacts(data);
+ }
+ if (!silent) {
+ setStatus(formDirty ? "Status refreshed. Unsaved edits kept." : "Status refreshed.", formDirty ? "warn" : "ok");
+ }
+ } catch (error) {
+ if (error.status === 404) {
+ statusLoaded = false;
+ renderCallState();
+ if (!silent) {
+ setStatus("Waiting for Reachy app server...", "warn");
+ } else {
+ setStatus("");
+ }
+ return;
+ }
+ setStatus(`Status failed: ${error.message}`, "error");
+ }
+}
+
+function setSelectedModel(model) {
+ const selected = (model || "").trim();
+ if (!selected) {
+ return;
+ }
+ const hasOption = Array.from(els.model.options).some((option) => option.value === selected);
+ if (!hasOption) {
+ const option = document.createElement("option");
+ option.value = selected;
+ option.textContent = selected;
+ els.model.appendChild(option);
+ }
+ els.model.value = selected;
+ renderModelDirectory();
+}
+
+function populateModels(models) {
+ const selected = els.model.value.trim();
+ els.model.innerHTML = "";
+ const cleanModels = Array.from(new Set((models || []).map((model) => String(model).trim()).filter(Boolean)));
+ availableModels = cleanModels;
+ for (const model of cleanModels) {
+ const option = document.createElement("option");
+ option.value = model;
+ option.textContent = model;
+ els.model.appendChild(option);
+ }
+ if (selected) {
+ setSelectedModel(selected);
+ } else if (cleanModels.length) {
+ els.model.value = cleanModels[0];
+ }
+ renderModelDirectory();
+}
+
+async function refreshModels({ silent = false } = {}) {
+ const payload = {
+ openwebui_url: els.url.value.trim(),
+ openwebui_api_key: els.apiKey.value.trim(),
+ openwebui_token: els.token.value.trim(),
+ contacts_require_vision: Boolean(els.contactsRequireVision?.checked),
+ };
+ if (!payload.openwebui_url) {
+ return false;
+ }
+
+ try {
+ const data = await requestJson("/openwebui_models", {
+ method: "POST",
+ body: JSON.stringify(payload),
+ });
+ populateModels(data.models || []);
+ if (!silent) setStatus(data.message || "Contacts refreshed.", "ok");
+ return true;
+ } catch (error) {
+ if (!silent) setStatus(`Contact refresh failed: ${error.message}`, "warn");
+ return false;
+ }
+}
+
+function populateConversations(conversations) {
+ const clean = [];
+ const seen = new Set();
+ for (const conversation of Array.isArray(conversations) ? conversations : []) {
+ const id = String(conversation?.id || "").trim();
+ if (!id || seen.has(id)) {
+ continue;
+ }
+ seen.add(id);
+ clean.push({
+ id,
+ title: String(conversation?.title || "Untitled conversation").trim() || "Untitled conversation",
+ updated_at: conversation?.updated_at ?? null,
+ created_at: conversation?.created_at ?? null,
+ last_read_at: conversation?.last_read_at ?? null,
+ });
+ }
+ availableConversations = clean;
+ renderedConversationDirectoryKey = "";
+ renderConversationDirectory();
+}
+
+async function refreshConversations({ silent = false, background = false, clearBeforeLoad = true } = {}) {
+ if (conversationRefreshInFlight) {
+ return false;
+ }
+
+ const payload = {
+ openwebui_url: els.url.value.trim(),
+ openwebui_api_key: els.apiKey.value.trim(),
+ openwebui_token: els.token.value.trim(),
+ };
+ if (!payload.openwebui_url) {
+ if (!silent) setStatus("Enter OpenWebUI URL first.", "warn");
+ return false;
+ }
+
+ conversationRefreshInFlight = true;
+ if (clearBeforeLoad) {
+ availableConversations = [];
+ renderedConversationDirectoryKey = "";
+ }
+ if (!background) {
+ setBusy(true);
+ }
+ if (!silent) setStatus("Loading conversations...");
+ renderConversationDirectory();
+ try {
+ const data = await requestJson("/openwebui_chats", {
+ method: "POST",
+ body: JSON.stringify(payload),
+ });
+ populateConversations(data.chats || []);
+ if (!silent) setStatus(data.message || "Conversations refreshed.", "ok");
+ return true;
+ } catch (error) {
+ if (!background) {
+ populateConversations([]);
+ }
+ if (!silent) setStatus(`Conversation refresh failed: ${error.message}`, "warn");
+ return false;
+ } finally {
+ conversationRefreshInFlight = false;
+ renderedConversationDirectoryKey = "";
+ if (!background) {
+ setBusy(false);
+ }
+ renderConversationDirectory();
+ }
+}
+
+async function openConversations() {
+ if (busy) {
+ return;
+ }
+ if (runtimeStatus.state !== "running") {
+ homeOpen = false;
+ }
+ conversationsOpen = true;
+ contactsOpen = false;
+ attitudesOpen = false;
+ cookAIwareOpen = false;
+ settingsOpen = false;
+ textChatOpen = false;
+ volumePanelOpen = false;
+ renderCallState();
+ await refreshConversations();
+}
+
+async function setMicMuted(muted, { silent = false } = {}) {
+ try {
+ const data = await requestJson("/mic_mute", {
+ method: "POST",
+ body: JSON.stringify({ muted: Boolean(muted) }),
+ });
+ applyStatus(data);
+ if (!silent) setStatus(data.message || (muted ? "Mic muted." : "Mic unmuted."), "ok");
+ return true;
+ } catch (error) {
+ if (!silent) setStatus(`Mic mute failed: ${error.message}`, "error");
+ return false;
+ }
+}
+
+async function setSpeakerMuted(muted, { silent = false } = {}) {
+ try {
+ const data = await requestJson("/speaker_mute", {
+ method: "POST",
+ body: JSON.stringify({ muted: Boolean(muted) }),
+ });
+ applyStatus(data);
+ if (!silent) setStatus(data.message || (muted ? "Speaker muted." : "Speaker unmuted."), "ok");
+ return true;
+ } catch (error) {
+ if (!silent) setStatus(`Speaker mute failed: ${error.message}`, "error");
+ return false;
+ }
+}
+
+async function ensureTextModeMutes({ silent = true } = {}) {
+ if (!statusLoaded) {
+ return;
+ }
+ const tasks = [];
+ if (!runtimeStatus.muted) tasks.push(setMicMuted(true, { silent }));
+ if (!runtimeStatus.speaker_muted) tasks.push(setSpeakerMuted(true, { silent }));
+ if (tasks.length) {
+ await Promise.all(tasks);
+ }
+}
+
+function openTextChat() {
+ if (busy) {
+ return;
+ }
+ if (runtimeStatus.state !== "running") {
+ homeOpen = false;
+ }
+ textChatOpen = true;
+ conversationsOpen = false;
+ contactsOpen = false;
+ attitudesOpen = false;
+ cookAIwareOpen = false;
+ settingsOpen = false;
+ volumePanelOpen = false;
+ renderCallState();
+ ensureTextModeMutes({ silent: true });
+ els.textMessageInput?.focus();
+}
+
+async function openContactsDirectory() {
+ if (busy) {
+ return;
+ }
+ if (runtimeStatus.state !== "running") {
+ homeOpen = false;
+ }
+ contactsOpen = true;
+ conversationsOpen = false;
+ attitudesOpen = false;
+ cookAIwareOpen = false;
+ settingsOpen = false;
+ textChatOpen = false;
+ volumePanelOpen = false;
+ renderCallState();
+ await refreshModels({ silent: true });
+}
+
+function openSettingsPage() {
+ if (busy || !statusLoaded) {
+ return;
+ }
+ settingsOpen = true;
+ conversationsOpen = false;
+ contactsOpen = false;
+ attitudesOpen = false;
+ cookAIwareOpen = false;
+ textChatOpen = false;
+ homeOpen = false;
+ volumePanelOpen = false;
+ renderCallState();
+}
+
+async function selectConversation(conversation) {
+ if (busy) {
+ return;
+ }
+ const chatId = String(conversation?.id || "").trim();
+ if (!chatId) {
+ setStatus("Conversation is missing a chat ID.", "warn");
+ return;
+ }
+ const title = String(conversation?.title || "Untitled conversation").trim() || "Untitled conversation";
+ els.chatId.value = chatId;
+ runtimeStatus.openwebui_chat_id = chatId;
+ formDirty = true;
+ conversationsOpen = false;
+ homeOpen = runtimeStatus.state === "running";
+ renderedConversationDirectoryKey = "";
+ renderCallState();
+ const saved = await saveSettings();
+ if (saved) {
+ setStatus(`Conversation selected: ${title}`, "ok");
+ }
+}
+
+async function saveSettings(appMode = "phone") {
+ const payload = payloadFromForm();
+ payload.app_mode = appMode === "cookaiware" ? "cookaiware" : "phone";
+ if (!payload.openwebui_url || !payload.openwebui_model) {
+ setStatus("Enter OpenWebUI URL and model.", "warn");
+ return false;
+ }
+ const needsApiKey = apiKeyRequired || payload.openwebui_url.toLowerCase().startsWith("https://");
+ if (
+ statusLoaded &&
+ needsApiKey &&
+ !payload.openwebui_api_key &&
+ !payload.openwebui_token &&
+ !savedApiKeyPresent &&
+ !savedTokenPresent
+ ) {
+ setStatus("Enter OpenWebUI API key or JWT token for this connection.", "warn");
+ return false;
+ }
+ if (!payload.openwebui_api_key && savedApiKeyPresent) {
+ delete payload.openwebui_api_key;
+ }
+ if (!payload.openwebui_token && savedTokenPresent) {
+ delete payload.openwebui_token;
+ }
+
+ setBusy(true);
+ setStatus("Saving settings...");
+ try {
+ const data = await requestJson("/backend_config", {
+ method: "POST",
+ body: JSON.stringify(payload),
+ });
+ formDirty = false;
+ writeCachedSettings({ ...payload, ...data });
+ applyStatus(data, { force: true });
+ refreshWeather({ force: true });
+ els.apiKey.value = "";
+ els.token.value = "";
+ updateSecretPlaceholders();
+ setStatus(data.message || "Settings saved.", "ok");
+ return true;
+ } catch (error) {
+ setStatus(`Save failed: ${error.message}`, "error");
+ return false;
+ } finally {
+ setBusy(false);
+ }
+}
+
+async function startConversation(modelName = "") {
+ if (busy) {
+ return;
+ }
+
+ const selectedModel = String(modelName || "").trim();
+ conversationsOpen = false;
+ contactsOpen = false;
+ cookAIwareOpen = false;
+ settingsOpen = false;
+ if (!textChatOpen) {
+ homeOpen = false;
+ }
+ if (selectedModel) {
+ setSelectedModel(selectedModel);
+ els.chatId.value = "";
+ runtimeStatus.openwebui_model = selectedModel;
+ runtimeStatus.openwebui_chat_id = "";
+ activeModelName = selectedModel;
+ clearCachedChatPreview();
+ formDirty = true;
+ renderCallState();
+ }
+
+ pendingStart = true;
+ startFlowActive = true;
+ setBusy(true);
+ setStatus("Starting chat and settings...");
+ try {
+ const saved = await saveSettings("phone");
+ if (!saved) {
+ cookAIwareOpen = false;
+ pendingStart = false;
+ startFlowActive = false;
+ renderCallState();
+ return;
+ }
+ const data = await requestJson("/start_app", {
+ method: "POST",
+ body: JSON.stringify({ app_mode: "phone" }),
+ });
+ startFlowActive = false;
+ applyStatus(data);
+ cookAIwareOpen = false;
+ renderCallState();
+ setStatus(data.message || "Starting chat.", "ok");
+ } catch (error) {
+ cookAIwareOpen = false;
+ pendingStart = false;
+ startFlowActive = false;
+ renderCallState();
+ setStatus(`Start convo failed: ${error.message}`, "error");
+ } finally {
+ startFlowActive = false;
+ setBusy(false);
+ }
+}
+
+async function waitForRunning(timeoutMs = 14000) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ await refreshStatus({ silent: true });
+ if (runtimeStatus.state === "running") {
+ return true;
+ }
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ }
+ return runtimeStatus.state === "running";
+}
+
+function renderAttachmentPreview() {
+ if (!els.attachmentPreview) return;
+ const hasAttachment = Boolean(attachedImage?.dataUrl);
+ els.attachmentPreview.hidden = !hasAttachment;
+ if (els.attachmentName) {
+ els.attachmentName.textContent = attachedImage?.name || "Image attached";
+ }
+}
+
+function clearAttachedImage() {
+ attachedImage = null;
+ if (els.imageAttachmentInput) {
+ els.imageAttachmentInput.value = "";
+ }
+ renderAttachmentPreview();
+}
+
+function readImageAttachment(file) {
+ if (!file) return;
+ if (!file.type.startsWith("image/")) {
+ setStatus("Choose an image file.", "warn");
+ return;
+ }
+ const reader = new FileReader();
+ reader.onload = () => {
+ attachedImage = {
+ name: file.name || "Image",
+ dataUrl: String(reader.result || ""),
+ };
+ renderAttachmentPreview();
+ setStatus("Image attached.", "ok");
+ };
+ reader.onerror = () => setStatus("Image attach failed.", "error");
+ reader.readAsDataURL(file);
+}
+
+async function sendTextMessage() {
+ if (busy || !els.textMessageInput) {
+ return;
+ }
+ const text = els.textMessageInput.value.trim();
+ if (!text && !attachedImage) {
+ return;
+ }
+ const wasTextChatOpen = textChatOpen;
+ if (runtimeStatus.state !== "running") {
+ setStatus("Starting Reachy...");
+ await startConversation();
+ textChatOpen = wasTextChatOpen;
+ renderCallState();
+ const ready = await waitForRunning();
+ if (!ready) {
+ setStatus("Reachy is still starting. Try Send again in a moment.", "warn");
+ return;
+ }
+ await ensureTextModeMutes({ silent: true });
+ }
+
+ setBusy(true);
+ setStatus("Sending message...");
+ try {
+ const body = { text: text || "Please describe this image." };
+ if (attachedImage?.dataUrl) {
+ body.images = [attachedImage.dataUrl];
+ }
+ const data = await requestJson("/text_input", {
+ method: "POST",
+ body: JSON.stringify(body),
+ });
+ els.textMessageInput.value = "";
+ clearAttachedImage();
+ applyStatus(data);
+ textChatOpen = true;
+ renderCallState();
+ setStatus(data.message || "Message sent.", "ok");
+ } catch (error) {
+ setStatus(`Message failed: ${error.message}`, "error");
+ } finally {
+ setBusy(false);
+ }
+}
+
+async function startCookAIwareConversation() {
+ if (busy) {
+ return;
+ }
+
+ cookAIwareOpen = true;
+ conversationsOpen = false;
+ contactsOpen = false;
+ settingsOpen = false;
+ homeOpen = false;
+ pendingStart = true;
+ startFlowActive = true;
+ setBusy(true);
+ setStatus("Starting chef...");
+ renderCallState();
+ try {
+ const enterData = await requestJson("/apps/cookaiware/enter", { method: "POST" });
+ formDirty = false;
+ applyStatus(enterData, { force: true });
+ const data = await requestJson("/start_app", {
+ method: "POST",
+ body: JSON.stringify({ app_mode: "cookaiware" }),
+ });
+ startFlowActive = false;
+ applyStatus(data, { force: true });
+ cookAIwareOpen = true;
+ renderCallState();
+ setStatus(data.message || enterData.message || "Chef started.", "ok");
+ } catch (error) {
+ pendingStart = false;
+ startFlowActive = false;
+ renderCallState();
+ setStatus(`Start chef failed: ${error.message}`, "error");
+ } finally {
+ startFlowActive = false;
+ setBusy(false);
+ }
+}
+
+async function stopConversation() {
+ if (busy) {
+ return;
+ }
+ const stoppingFromCookAIware = cookAIwareOpen || runtimeStatus.cookaiware_active;
+ contactsOpen = false;
+ conversationsOpen = false;
+ cookAIwareOpen = stoppingFromCookAIware;
+ settingsOpen = false;
+ homeOpen = false;
+ pendingStart = false;
+ startFlowActive = false;
+ setBusy(true);
+ setStatus("Ending call...");
+ try {
+ const data = await requestJson("/stop_app", { method: "POST" });
+ applyStatus(data);
+ pendingStart = false;
+ startFlowActive = false;
+ contactsOpen = false;
+ conversationsOpen = false;
+ cookAIwareOpen = stoppingFromCookAIware && Boolean(data.cookaiware_active ?? runtimeStatus.cookaiware_active);
+ settingsOpen = false;
+ homeOpen = false;
+ renderCallState();
+ setStatus("");
+ } catch (error) {
+ setStatus(`Stop failed: ${error.message}`, "error");
+ } finally {
+ setBusy(false);
+ }
+}
+
+async function restartApp() {
+ if (busy) {
+ return;
+ }
+ const restartingCookAIware = cookAIwareOpen || runtimeStatus.cookaiware_active;
+ contactsOpen = false;
+ conversationsOpen = false;
+ cookAIwareOpen = restartingCookAIware;
+ settingsOpen = false;
+ homeOpen = false;
+ pendingStart = true;
+ startFlowActive = true;
+ setBusy(true);
+ setStatus("Restarting app process...");
+ try {
+ const data = await requestJson("/restart_app", { method: "POST" });
+ applyStatus(data);
+ cookAIwareOpen = restartingCookAIware || runtimeStatus.cookaiware_active;
+ renderCallState();
+ setStatus(data.message || "Restarting app process.", "ok");
+ window.setTimeout(() => {
+ window.location.reload();
+ }, 2500);
+ } catch (error) {
+ pendingStart = false;
+ startFlowActive = false;
+ renderCallState();
+ setStatus(`Restart failed: ${error.message}`, "error");
+ } finally {
+ startFlowActive = false;
+ setBusy(false);
+ }
+}
+
+async function toggleMute() {
+ if (busy) return;
+ setBusy(true);
+ setStatus(runtimeStatus.muted ? "Unmuting..." : "Muting...");
+ try {
+ const data = await requestJson("/mute", { method: "POST" });
+ applyStatus(data);
+ setStatus(data.message || (data.muted ? "Muted." : "Unmuted."), "ok");
+ } catch (error) {
+ setStatus(`Mute failed: ${error.message}`, "error");
+ } finally {
+ setBusy(false);
+ }
+}
+
+function closeTextActionsMenu() {
+ if (!els.textActionsMenu) return;
+ els.textActionsMenu.hidden = true;
+ els.textActions?.setAttribute("aria-expanded", "false");
+ renderCallState();
+}
+
+function toggleTextActionsMenu() {
+ if (!els.textActionsMenu) return;
+ const nextOpen = els.textActionsMenu.hidden;
+ els.textActionsMenu.hidden = !nextOpen;
+ els.textActions?.setAttribute("aria-expanded", String(nextOpen));
+ renderCallState();
+}
+
+async function disconnectFromTextChat() {
+ closeTextActionsMenu();
+ await stopConversation();
+ textChatOpen = false;
+ homeOpen = true;
+ renderCallState();
+}
+
+els.form.addEventListener("submit", async (event) => {
+ event.preventDefault();
+ await saveSettings();
+});
+
+els.start.addEventListener("click", () => startConversation());
+els.quickConnect?.addEventListener("click", () => {
+ if (runtimeStatus.state === "running") {
+ homeOpen = false;
+ contactsOpen = false;
+ conversationsOpen = false;
+ attitudesOpen = false;
+ cookAIwareOpen = false;
+ textChatOpen = false;
+ renderCallState();
+ return;
+ }
+ startConversation();
+});
+els.homeContacts?.addEventListener("click", () => openContactsDirectory());
+els.homeMessages?.addEventListener("click", () => openTextChat());
+els.homeChatHistory?.addEventListener("click", () => openConversations());
+els.homeAttitudes?.addEventListener("click", () => openAttitudes());
+els.homeVolume?.addEventListener("click", () => {
+ volumePanelOpen = true;
+ homeOpen = true;
+ updateVolumeControls();
+ renderCallState();
+});
+els.volumeScrim?.addEventListener("click", () => {
+ volumePanelOpen = false;
+ renderCallState();
+});
+els.homeMicVolume?.addEventListener("input", () => queueVolumeSave("mic_volume"));
+els.homeSpeakerVolume?.addEventListener("input", () => queueVolumeSave("speaker_volume"));
+els.attachImage?.addEventListener("click", () => els.imageAttachmentInput?.click());
+els.imageAttachmentInput?.addEventListener("change", () => {
+ readImageAttachment(els.imageAttachmentInput?.files?.[0]);
+});
+els.clearAttachment?.addEventListener("click", () => clearAttachedImage());
+els.textBack?.addEventListener("click", () => goBackLikePhone());
+els.sendText?.addEventListener("click", () => sendTextMessage());
+els.textMessageInput?.addEventListener("keydown", (event) => {
+ if (event.key === "Enter" && !event.shiftKey) {
+ event.preventDefault();
+ sendTextMessage();
+ }
+});
+els.textActions?.addEventListener("click", () => toggleTextActionsMenu());
+els.textMicMute?.addEventListener("click", async () => {
+ closeTextActionsMenu();
+ await setMicMuted(!runtimeStatus.muted);
+});
+els.textSpeakerMute?.addEventListener("click", async () => {
+ closeTextActionsMenu();
+ await setSpeakerMuted(!runtimeStatus.speaker_muted);
+});
+els.textDisconnect?.addEventListener("click", () => disconnectFromTextChat());
+els.homeCookAIware?.addEventListener("click", () => openCookAIware());
+els.cookAIwareBack?.addEventListener("click", () => leaveCookAIwareView());
+els.cookAIwareStart?.addEventListener("click", () => {
+ if (runtimeStatus.state === "running" && runtimeStatus.cookaiware_active) {
+ stopConversation();
+ return;
+ }
+ startCookAIwareConversation();
+});
+els.cookAIwareRefresh?.addEventListener("click", () => loadCookAIwareState());
+els.cookAIwareMute?.addEventListener("click", () => toggleMute());
+els.cookAddInventoryView?.addEventListener("click", () => setCookView("inventory-add"));
+els.cookAddShoppingView?.addEventListener("click", () => setCookView("shopping-add"));
+els.cookInventoryUpc?.addEventListener("click", () => addCookUpcItem("inventory"));
+els.cookShoppingUpc?.addEventListener("click", () => addCookUpcItem("shopping"));
+els.cookUpcManual?.addEventListener("click", () => addCookManualUpcItem(cookUpcActiveTarget));
+els.cookUpcClose?.addEventListener("click", () => hideCookUpcPreview());
+els.cookInventorySearch?.addEventListener("input", () => renderCookAIwareState());
+els.cookShoppingSearch?.addEventListener("input", () => renderCookAIwareState());
+els.cookAddItem?.addEventListener("click", () => addCookInventoryItem());
+els.cookGeneratePlan?.addEventListener("click", () => generateCookPlan());
+els.cookAddShopping?.addEventListener("click", () => addCookShoppingItem());
+els.cookGenerateShopping?.addEventListener("click", () => updateCookShopping("generate"));
+els.cookAutoShopping?.addEventListener("click", () => updateCookShopping("auto_inventory"));
+els.cookClearShopping?.addEventListener("click", () => updateCookShopping("clear"));
+els.cookSaveProfile?.addEventListener("click", () => saveCookSettings());
+els.cookUnitSystem?.addEventListener("change", () => populateCookUnitSelects(els.cookUnitSystem.value || "metric"));
+for (const tab of els.cookTabs || []) {
+ tab.addEventListener("click", () => setCookView(tab.dataset.cookView || "inventory"));
+}
+els.testSpeech?.addEventListener("click", () => testSpeech());
+
+async function goBackLikePhone() {
+ if (settingsOpen) {
+ settingsOpen = false;
+ volumePanelOpen = false;
+ homeOpen = runtimeStatus.state === "running";
+ renderCallState();
+ return;
+ }
+ if (cookAIwareOpen) {
+ volumePanelOpen = false;
+ leaveCookAIwareView();
+ return;
+ }
+ if (conversationsOpen || contactsOpen || attitudesOpen || textChatOpen) {
+ conversationsOpen = false;
+ contactsOpen = false;
+ attitudesOpen = false;
+ textChatOpen = false;
+ volumePanelOpen = false;
+ homeOpen = runtimeStatus.state === "running";
+ renderCallState();
+ return;
+ }
+ if (runtimeStatus.state === "running") {
+ homeOpen = true;
+ renderCallState();
+ }
+}
+
+els.back?.addEventListener("click", goBackLikePhone);
+els.bottomBack?.addEventListener("click", goBackLikePhone);
+els.stop.addEventListener("click", () => stopConversation());
+
+els.contacts.addEventListener("click", () => {
+ if (busy || runtimeStatus.state !== "running") {
+ return;
+ }
+ conversationsOpen = false;
+ attitudesOpen = false;
+ textChatOpen = false;
+ volumePanelOpen = false;
+ contactsOpen = !contactsOpen;
+ settingsOpen = false;
+ renderCallState();
+});
+
+els.mute.addEventListener("click", () => toggleMute());
+
+els.clearCallCache.addEventListener("click", async () => {
+ setBusy(true);
+ setStatus("Clearing call cache...");
+ try {
+ const data = await requestJson("/clear_call_cache", { method: "POST" });
+ clearCachedChatPreview();
+ formDirty = false;
+ applyStatus(data, { force: true });
+ setStatus(data.message || "Call cache cleared.", "ok");
+ } catch (error) {
+ setStatus(`Clear cache failed: ${error.message}`, "error");
+ } finally {
+ setBusy(false);
+ }
+});
+
+els.restartApp?.addEventListener("click", () => restartApp());
+els.refresh.addEventListener("click", () => refreshStatus({ updateModels: true }));
+els.refreshModels.addEventListener("click", () => refreshModels());
+els.refreshChats?.addEventListener("click", () => openConversations());
+els.settingsToggle.addEventListener("click", () => openSettingsPage());
+els.url.addEventListener("change", () => {
+ availableConversations = [];
+ renderedConversationDirectoryKey = "";
+ refreshModels();
+});
+els.contactsRequireVision?.addEventListener("change", () => refreshModels());
+els.homeWeather?.addEventListener("click", () => {
+ weatherForecastOpen = !weatherForecastOpen;
+ renderWeather(lastWeatherData);
+});
+els.homeWeather?.addEventListener("keydown", (event) => {
+ if (event.key !== "Enter" && event.key !== " ") {
+ return;
+ }
+ event.preventDefault();
+ weatherForecastOpen = !weatherForecastOpen;
+ renderWeather(lastWeatherData);
+});
+els.form.addEventListener("input", () => {
+ formDirty = true;
+ updateSecretPlaceholders();
+});
+els.form.addEventListener("change", () => {
+ formDirty = true;
+});
+
+els.micGain.addEventListener("input", () => {
+ els.micGainValue.value = Number(els.micGain.value).toFixed(2).replace(/\.?0+$/, "");
+});
+
+els.micGainValue.addEventListener("input", () => {
+ const value = Number(els.micGainValue.value);
+ if (Number.isFinite(value)) {
+ els.micGain.value = String(Math.min(3, Math.max(0.25, value)));
+ }
+});
+
+applyCachedSettingsPreview();
+registerPwaServiceWorker();
+renderIdleAttitudes(
+ runtimeStatus.available_idle_attitudes,
+ els.idleAttitude?.value || runtimeStatus.reachy_idle_attitude,
+);
+updatePhoneClock();
+renderCallState();
+refreshStatus({ silent: true, updateForm: true });
+setInterval(() => refreshStatus({ silent: true }), 1000);
+setInterval(updateTimer, 1000);
+setInterval(updatePhoneClock, 30000);
+setInterval(() => refreshWeather({ force: true }), 15 * 60 * 1000);
diff --git a/src/Reachy_OpenWebUI/static/manifest.webmanifest b/src/Reachy_OpenWebUI/static/manifest.webmanifest
new file mode 100644
index 0000000000000000000000000000000000000000..f9fe176e5e2319abff6af81b0597a47dca5b6245
--- /dev/null
+++ b/src/Reachy_OpenWebUI/static/manifest.webmanifest
@@ -0,0 +1,25 @@
+{
+ "name": "Reachy OpenWebUI",
+ "short_name": "Reachy",
+ "description": "Reachy Mini OpenWebUI phone app",
+ "start_url": "/",
+ "scope": "/",
+ "display": "standalone",
+ "background_color": "#101112",
+ "theme_color": "#101112",
+ "orientation": "portrait",
+ "icons": [
+ {
+ "src": "/static/assets/pwa-icon-192.png",
+ "sizes": "192x192",
+ "type": "image/png",
+ "purpose": "any maskable"
+ },
+ {
+ "src": "/static/assets/pwa-icon-512.png",
+ "sizes": "512x512",
+ "type": "image/png",
+ "purpose": "any maskable"
+ }
+ ]
+}
diff --git a/src/Reachy_OpenWebUI/static/service-worker.js b/src/Reachy_OpenWebUI/static/service-worker.js
new file mode 100644
index 0000000000000000000000000000000000000000..4622fc46c815b4774b7aaf79b19c6bc6de06daf3
--- /dev/null
+++ b/src/Reachy_OpenWebUI/static/service-worker.js
@@ -0,0 +1,17 @@
+const CACHE_NAME = "reachy-openwebui-pwa-v1";
+
+self.addEventListener("install", (event) => {
+ event.waitUntil(self.skipWaiting());
+});
+
+self.addEventListener("activate", (event) => {
+ event.waitUntil(
+ caches.keys().then((keys) =>
+ Promise.all(keys.filter((key) => key !== CACHE_NAME).map((key) => caches.delete(key)))
+ ).then(() => self.clients.claim())
+ );
+});
+
+self.addEventListener("fetch", (event) => {
+ event.respondWith(fetch(event.request));
+});
diff --git a/src/Reachy_OpenWebUI/static/style.css b/src/Reachy_OpenWebUI/static/style.css
new file mode 100644
index 0000000000000000000000000000000000000000..a226c0bbe60b0a557bb3e7e1e2fddb03ccdcb151
--- /dev/null
+++ b/src/Reachy_OpenWebUI/static/style.css
@@ -0,0 +1,2895 @@
+.phone-shell {
+ min-height: 100vh;
+ min-height: 100dvh;
+ display: grid;
+ place-items: center;
+ padding: 12px;
+}
+
+.phone {
+ position: relative;
+ width: min(398px, 100%);
+ height: calc(100vh - 24px);
+ height: calc(100dvh - 24px);
+ min-height: min(680px, calc(100vh - 24px));
+ min-height: min(680px, calc(100dvh - 24px));
+ display: grid;
+ grid-template-rows: minmax(0, 1fr) auto auto auto;
+ overflow: hidden;
+ border: 6px solid #050607;
+ border-radius: 34px;
+ background: var(--phone);
+ box-shadow: var(--shadow);
+}
+
+.phone::before {
+ content: none;
+}
+
+@media (max-width: 560px) {
+ html,
+ body,
+ .phone-shell {
+ width: 100%;
+ min-height: 100%;
+ min-height: 100dvh;
+ }
+
+ .phone-shell {
+ display: block;
+ padding: 0;
+ }
+
+ .phone {
+ width: 100%;
+ height: 100vh;
+ height: 100dvh;
+ min-height: 100vh;
+ min-height: 100dvh;
+ border: 0;
+ border-radius: 0;
+ box-shadow: none;
+ }
+
+ .phone-topbar {
+ padding-top: calc(8px + env(safe-area-inset-top, 0px));
+ }
+
+}
+
+.phone-topbar,
+.topbar-contact,
+.call-actions,
+.panel-heading,
+.form-actions,
+.range-row {
+ display: flex;
+ align-items: center;
+}
+
+.phone-topbar {
+ min-height: 42px;
+ display: grid;
+ grid-template-columns: 1fr;
+ padding: 9px 16px 8px;
+ border-bottom: 0;
+ background: #151719;
+}
+
+.appbar {
+ min-height: 42px;
+ display: grid;
+ grid-template-columns: auto minmax(0, 1fr) 30px;
+ align-items: center;
+ gap: 11px;
+ padding-top: 3px;
+}
+
+.phone[data-view="home"] .phone-topbar,
+.phone[data-view="readying"] .phone-topbar {
+ background: #151719;
+}
+
+.phone[data-view="home"] .appbar,
+.phone[data-view="readying"] .appbar {
+ display: none;
+}
+
+.phone:not([data-view="home"]):not([data-view="readying"]) .phone-topbar {
+ border-bottom: 1px solid rgba(255, 255, 255, 0.07);
+ background: linear-gradient(180deg, var(--topbar), var(--topbar-2));
+}
+
+.phone[data-view="cookaiware"] .phone-topbar {
+ display: none;
+}
+
+.topbar-contact {
+ gap: 9px;
+ min-width: 0;
+}
+
+.back-mark {
+ display: block;
+ width: 13px;
+ height: 13px;
+ border-left: 2px solid var(--text);
+ border-bottom: 2px solid var(--text);
+ transform: rotate(45deg);
+ opacity: 0.88;
+}
+
+.phone-topbar .back-btn {
+ width: 30px;
+ height: 38px;
+ margin-left: -5px;
+ display: none !important;
+}
+
+.topbar-avatar {
+ width: 28px;
+ height: 28px;
+ display: grid;
+ place-items: center;
+ border-radius: 50%;
+ background: #0d1014;
+ color: var(--strong);
+ font-size: 14px;
+ font-weight: 800;
+ line-height: 1;
+ overflow: hidden;
+}
+
+.avatar-surface {
+ position: relative;
+ display: grid;
+ place-items: center;
+}
+
+.avatar-surface img,
+.avatar-initial,
+.topbar-model-initial,
+#topbar-model-initial {
+ grid-area: 1 / 1;
+}
+
+.avatar-surface img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+
+.fallback-app-icon {
+ display: block;
+}
+
+.topbar-model-initial {
+ display: block;
+ place-items: center;
+ width: 100%;
+ height: 100%;
+ background: url("/static/assets/reachy-conversation-app.png") center / cover no-repeat;
+ color: transparent;
+ font-size: 0;
+}
+
+.topbar-title {
+ min-width: 0;
+ display: grid;
+ gap: 4px;
+}
+
+.phone-topbar h2 {
+ color: var(--strong);
+ font-size: 16px;
+ line-height: 1.15;
+ font-weight: 760;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.icon-btn {
+ width: 38px;
+ height: 38px;
+ min-height: 0;
+ padding: 0;
+ border: 0;
+ border-radius: 8px;
+ background: transparent;
+ color: var(--text);
+ display: grid;
+ place-content: center;
+ gap: 4px;
+}
+
+.cog-icon {
+ position: relative;
+ width: 18px;
+ height: 18px;
+ display: block;
+ border: 2px solid currentColor;
+ border-radius: 50%;
+}
+
+.cog-icon::before {
+ content: "";
+ position: absolute;
+ inset: 5px;
+ border-radius: 50%;
+ background: currentColor;
+}
+
+.cog-icon::after {
+ content: "";
+ position: absolute;
+ inset: -5px;
+ border-radius: 50%;
+ background: repeating-conic-gradient(currentColor 0deg 12deg, transparent 12deg 45deg);
+ opacity: 0.86;
+ -webkit-mask: radial-gradient(circle, transparent 0 8px, #000 8px 10px, transparent 10px);
+ mask: radial-gradient(circle, transparent 0 8px, #000 8px 10px, transparent 10px);
+}
+
+.icon-btn:hover:not(:disabled),
+.icon-btn.active {
+ background: rgba(255, 255, 255, 0.08);
+ color: var(--strong);
+}
+
+.icon-btn.active {
+ box-shadow: inset 0 0 0 1px rgba(0, 122, 204, 0.42);
+}
+
+.chip {
+ width: fit-content;
+ max-width: 132px;
+ padding: 3px 7px;
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ background: rgba(255, 255, 255, 0.045);
+ color: var(--muted);
+ font-size: 10px;
+ font-weight: 760;
+ line-height: 1.2;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.chip[data-state="running"] {
+ border-color: rgba(0, 122, 204, 0.44);
+ background: rgba(0, 122, 204, 0.14);
+ color: var(--green);
+}
+
+.chip[data-state="configuring"] {
+ border-color: rgba(0, 122, 204, 0.46);
+ background: rgba(0, 122, 204, 0.15);
+ color: #8dcfff;
+}
+
+.phone[data-view="home"] .chip,
+.phone[data-view="readying"] .chip,
+.phone[data-state="running"] .chip {
+ display: none;
+}
+
+.contact-card {
+ display: grid;
+ grid-template-columns: 52px minmax(0, 1fr);
+ gap: 5px 12px;
+ align-items: center;
+ padding: 14px 16px 9px;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.05);
+ background: #111213;
+ text-align: left;
+}
+
+.startup-screen {
+ display: none;
+}
+
+.phone-home {
+ display: none;
+}
+
+.model-directory,
+.conversation-directory,
+.attitudes-app,
+.cookaiware-app {
+ display: none;
+}
+
+.model-stage {
+ position: relative;
+ grid-row: 1 / span 3;
+ width: 52px;
+ aspect-ratio: 1;
+ display: grid;
+ place-items: center;
+ margin: 0;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: 8px;
+ background: linear-gradient(145deg, rgba(0, 122, 204, 0.24), rgba(255, 255, 255, 0.055));
+ overflow: hidden;
+}
+
+.model-stage img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+
+.model-stage.has-image .contact-icon {
+ display: none;
+}
+
+.model-initial {
+ position: relative;
+ z-index: 2;
+ color: var(--strong);
+ font-size: 24px;
+ line-height: 1;
+ font-weight: 820;
+}
+
+.contact-icon {
+ position: absolute;
+ inset: 9px;
+ opacity: 0.12;
+}
+
+.contact-icon span:first-child {
+ position: absolute;
+ left: 50%;
+ top: 7%;
+ width: 38%;
+ aspect-ratio: 1;
+ border-radius: 50%;
+ background: var(--strong);
+ transform: translateX(-50%);
+}
+
+.contact-icon span:last-child {
+ position: absolute;
+ left: 50%;
+ bottom: 5%;
+ width: 78%;
+ height: 42%;
+ border-radius: 999px 999px 8px 8px;
+ background: var(--strong);
+ transform: translateX(-50%);
+}
+
+.phone[data-state="running"] .model-stage {
+ border-color: rgba(0, 122, 204, 0.42);
+ box-shadow: 0 0 0 3px rgba(0, 122, 204, 0.1);
+}
+
+.phone[data-view="home"] .contact-card {
+ display: none;
+}
+
+.phone[data-view="readying"] {
+ filter: grayscale(0.84) saturate(0.42);
+}
+
+.phone[data-view="readying"] .phone-topbar {
+ opacity: 0.46;
+ pointer-events: none;
+}
+
+.phone[data-view="readying"] .startup-screen {
+ grid-row: 1 / -1;
+ min-height: 0;
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ gap: 13px;
+ padding: 32px 28px;
+ background:
+ radial-gradient(circle at 50% 42%, rgba(255, 255, 255, 0.08), transparent 34%),
+ #090a0b;
+ text-align: center;
+}
+
+.phone[data-view="home"] .phone-home {
+ position: relative;
+ grid-row: 1 / -1;
+ min-height: 0;
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ justify-content: space-between;
+ gap: 22px;
+ overflow: hidden;
+ padding: 34px 20px 24px;
+ background:
+ linear-gradient(116deg, rgba(255, 255, 255, 0.14) 0 22%, transparent 22% 100%),
+ linear-gradient(112deg, transparent 0 42%, rgba(255, 255, 255, 0.08) 42% 60%, transparent 60% 100%),
+ radial-gradient(circle at 88% 78%, rgba(255, 255, 255, 0.1), transparent 26%),
+ #2d2f32;
+}
+
+.home-time {
+ min-width: 0;
+ display: grid;
+ gap: 3px;
+ padding: 0;
+ text-align: left;
+}
+
+.home-time p {
+ color: rgba(255, 255, 255, 0.88);
+ font-size: 12px;
+ line-height: 1.1;
+ font-weight: 720;
+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.45);
+}
+
+.home-time h1 {
+ max-width: none;
+ display: flex;
+ align-items: baseline;
+ justify-content: flex-start;
+ gap: 5px;
+ color: #f8f8f8;
+ font-size: 34px;
+ line-height: 0.95;
+ font-weight: 640;
+ text-align: left;
+ letter-spacing: 0;
+ white-space: nowrap;
+ text-shadow: 0 2px 8px rgba(0, 0, 0, 0.5);
+}
+
+.home-period {
+ flex: 0 0 auto;
+ color: rgba(248, 248, 248, 0.88);
+ font-size: 13px;
+ font-weight: 720;
+ letter-spacing: 0;
+}
+
+.home-weather {
+ width: min(100%, 286px);
+ align-self: flex-end;
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) minmax(100px, 0.8fr);
+ align-items: center;
+ gap: 12px;
+ padding: 11px 12px;
+ border: 1px solid rgba(255, 255, 255, 0.16);
+ border-radius: 8px;
+ background: rgba(12, 16, 19, 0.32);
+ backdrop-filter: blur(12px);
+ text-align: left;
+ cursor: pointer;
+ user-select: none;
+}
+
+.home-weather:hover,
+.home-weather:focus-visible {
+ border-color: rgba(255, 255, 255, 0.26);
+ background: rgba(12, 16, 19, 0.42);
+}
+
+.home-weather:focus-visible {
+ outline: 2px solid rgba(0, 122, 204, 0.72);
+ outline-offset: 2px;
+}
+
+.weather-current {
+ min-width: 0;
+ display: grid;
+ grid-template-columns: 32px minmax(0, 1fr);
+ align-items: center;
+ gap: 8px;
+}
+
+.weather-mark {
+ width: 32px;
+ height: 32px;
+ display: grid;
+ place-items: center;
+ border-radius: 7px;
+ background: rgba(0, 122, 204, 0.26);
+}
+
+.weather-mark span {
+ width: 16px;
+ height: 16px;
+ border-radius: 999px;
+ background: #ffbd5a;
+ box-shadow:
+ 8px 6px 0 -3px rgba(244, 246, 248, 0.88),
+ 2px 3px 16px rgba(255, 189, 90, 0.36);
+}
+
+.weather-copy {
+ min-width: 0;
+ display: grid;
+ gap: 2px;
+}
+
+.weather-copy p,
+.weather-copy h2 {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.weather-copy p {
+ color: rgba(255, 255, 255, 0.74);
+ font-size: 11px;
+ line-height: 1.2;
+ font-weight: 720;
+}
+
+.weather-copy h2 {
+ margin: 0;
+ color: #f8f8f8;
+ font-size: 20px;
+ line-height: 1.05;
+ font-weight: 760;
+}
+
+.weather-forecast {
+ grid-column: 1 / -1;
+ display: grid;
+ grid-template-columns: repeat(5, minmax(0, 1fr));
+ gap: 5px;
+ padding-top: 8px;
+ border-top: 1px solid rgba(255, 255, 255, 0.12);
+}
+
+.weather-day {
+ min-width: 0;
+ min-height: 58px;
+ display: grid;
+ align-content: center;
+ justify-items: center;
+ gap: 4px;
+ padding: 6px 4px;
+ border-radius: 6px;
+ background: rgba(255, 255, 255, 0.07);
+ text-align: center;
+}
+
+.weather-day strong,
+.weather-day-temp,
+.weather-forecast-empty {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.weather-day strong {
+ color: rgba(255, 255, 255, 0.72);
+ font-size: 9px;
+ line-height: 1;
+ font-weight: 780;
+ text-transform: uppercase;
+}
+
+.weather-day-temp,
+.weather-forecast-empty {
+ color: #f8f8f8;
+ font-size: 10px;
+ line-height: 1.1;
+ font-weight: 760;
+}
+
+.weather-day-icon {
+ width: 18px;
+ height: 18px;
+ position: relative;
+ display: block;
+ border-radius: 999px;
+}
+
+.weather-day-icon.sun {
+ background: #ffbd5a;
+ box-shadow: 0 0 12px rgba(255, 189, 90, 0.34);
+}
+
+.weather-day-icon.cloud,
+.weather-day-icon.fog {
+ background: rgba(244, 246, 248, 0.84);
+ box-shadow:
+ -6px 4px 0 -4px rgba(244, 246, 248, 0.72),
+ 6px 5px 0 -5px rgba(244, 246, 248, 0.64);
+}
+
+.weather-day-icon.rain,
+.weather-day-icon.storm,
+.weather-day-icon.snow {
+ background: rgba(244, 246, 248, 0.84);
+ box-shadow:
+ -6px 4px 0 -4px rgba(244, 246, 248, 0.72),
+ 6px 5px 0 -5px rgba(244, 246, 248, 0.64);
+}
+
+.weather-day-icon.rain::after,
+.weather-day-icon.storm::after,
+.weather-day-icon.snow::after {
+ content: "";
+ position: absolute;
+ left: 5px;
+ top: 16px;
+ width: 3px;
+ height: 5px;
+ border-radius: 999px;
+}
+
+.weather-day-icon.rain::after {
+ background: #5bbcff;
+ box-shadow: 6px 0 0 #5bbcff;
+}
+
+.weather-day-icon.storm::after {
+ width: 7px;
+ height: 7px;
+ border-radius: 1px;
+ background: #ffbd5a;
+ transform: skewX(-18deg);
+}
+
+.weather-day-icon.snow::after {
+ background: #f8f8f8;
+ box-shadow: 6px 0 0 #f8f8f8;
+}
+
+.home-apps {
+ display: grid;
+ grid-template-columns: repeat(4, minmax(0, 1fr));
+ align-content: start;
+ gap: 13px 8px;
+ margin-top: auto;
+ padding: 0 2px 2px;
+}
+
+.home-dock {
+ display: grid;
+ grid-template-columns: repeat(5, minmax(0, 1fr));
+ gap: 7px;
+ padding: 4px 0 0;
+ border: 0;
+ border-radius: 0;
+ background: transparent;
+ box-shadow: none;
+ backdrop-filter: none;
+}
+
+.dock-app,
+.home-app {
+ min-width: 0;
+ min-height: 68px;
+ display: grid;
+ place-items: center;
+ gap: 6px;
+ padding: 6px 3px 5px;
+ border: 0;
+ border-radius: 15px;
+ background: transparent;
+ color: #f7f7f7;
+ box-shadow: none;
+}
+
+.home-app {
+ border-radius: 13px;
+}
+
+.volume-scrim {
+ position: absolute;
+ inset: 0;
+ z-index: 24;
+ background: transparent;
+}
+
+.volume-scrim[hidden] {
+ display: none;
+}
+
+.volume-panel {
+ position: absolute;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ z-index: 30;
+ display: grid;
+ gap: 18px;
+ padding: 18px 20px calc(22px + env(safe-area-inset-bottom, 0px));
+ border-top: 1px solid rgba(255, 255, 255, 0.16);
+ border-radius: 18px 18px 0 0;
+ background: rgba(21, 23, 25, 0.96);
+ box-shadow: 0 -18px 42px rgba(0, 0, 0, 0.42);
+ backdrop-filter: blur(18px);
+}
+
+.volume-panel[hidden] {
+ display: none;
+}
+
+.volume-panel-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+}
+
+.volume-panel-header h2 {
+ margin: 0;
+ color: #fff;
+ font-size: 17px;
+ line-height: 1.2;
+ font-weight: 760;
+}
+
+.volume-slider-row {
+ display: grid;
+ grid-template-columns: 1fr auto;
+ align-items: center;
+ gap: 8px 12px;
+ width: 100%;
+ color: rgba(255, 255, 255, 0.9);
+ font-size: 13px;
+ font-weight: 720;
+}
+
+.volume-slider-row output {
+ color: rgba(255, 255, 255, 0.68);
+ font-variant-numeric: tabular-nums;
+}
+
+.volume-slider-row input[type="range"] {
+ grid-column: 1 / -1;
+ width: 100%;
+}
+
+.dock-app > span:last-child,
+.home-app > span:last-child {
+ max-width: 100%;
+ color: rgba(255, 255, 255, 0.76);
+ font-size: 10px;
+ line-height: 1.1;
+ font-weight: 720;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.dock-app:hover:not(:disabled),
+.dock-app.active,
+.home-app:hover:not(:disabled),
+.home-app.active,
+.home-app.ready {
+ background: transparent;
+ transform: none;
+}
+
+.dock-icon {
+ width: 40px;
+ height: 40px;
+ padding: 0;
+ display: block;
+ border: 0;
+ border-radius: 0;
+ background: transparent;
+ color: currentColor;
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1.9;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+ vector-effect: non-scaling-stroke;
+}
+
+.dock-image-icon {
+ width: 51px;
+ height: 51px;
+ object-fit: cover;
+ padding: 0;
+ border: 0;
+ background: transparent;
+ stroke: none;
+}
+
+.dock-app:hover:not(:disabled) .dock-icon,
+.dock-app.active .dock-icon,
+.home-app:hover:not(:disabled) .dock-icon,
+.home-app.active .dock-icon,
+.home-app.ready .dock-icon {
+ border-color: transparent;
+ background: transparent;
+}
+
+.home-app.ready > span:last-child {
+ color: #9fd8ff;
+}
+
+.startup-mark {
+ position: relative;
+ width: min(134px, 38vw);
+ aspect-ratio: 1;
+ display: grid;
+ place-items: center;
+ border: 1px solid rgba(255, 255, 255, 0.13);
+ border-radius: 28px;
+ background: linear-gradient(145deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.035));
+ color: rgba(255, 255, 255, 0.72);
+ font-size: clamp(58px, 17vw, 82px);
+ line-height: 1;
+ font-weight: 820;
+ overflow: hidden;
+ animation: power-logo 1.6s ease-in-out infinite;
+}
+
+.startup-mark::after {
+ content: "";
+ position: absolute;
+ inset: -1px;
+ border-radius: inherit;
+ border: 1px solid rgba(255, 255, 255, 0.22);
+ opacity: 0;
+ animation: power-ring 1.6s ease-in-out infinite;
+}
+
+.startup-mark img {
+ width: 100%;
+ height: 100%;
+ display: block;
+ object-fit: cover;
+}
+
+.startup-screen h1 {
+ max-width: 100%;
+ color: rgba(244, 246, 248, 0.82);
+ font-size: clamp(24px, 6.5vw, 34px);
+ line-height: 1.08;
+ font-weight: 820;
+ white-space: normal;
+ overflow-wrap: anywhere;
+}
+
+.startup-screen p {
+ color: rgba(217, 220, 223, 0.62);
+ font-size: 14px;
+ line-height: 1.35;
+ font-weight: 760;
+}
+
+.startup-motion {
+ position: relative;
+ width: min(160px, 52vw);
+ height: 5px;
+ min-height: 5px;
+ display: block;
+ overflow: hidden;
+ border-radius: 999px;
+ background: rgba(255, 255, 255, 0.1);
+}
+
+.startup-motion span {
+ position: absolute;
+ inset: 0 auto 0 0;
+ width: 42%;
+ height: 100%;
+ border-radius: inherit;
+ background: rgba(244, 246, 248, 0.72);
+ animation: power-bar 1.5s ease-in-out infinite;
+}
+
+.startup-motion span:nth-child(2),
+.startup-motion span:nth-child(3) {
+ display: none;
+}
+
+.phone[data-view="contacts"] .model-directory,
+.phone[data-view="conversations"] .conversation-directory,
+.phone[data-view="attitudes"] .attitudes-app,
+.phone[data-view="cookaiware"] .cookaiware-app,
+.phone[data-view="settings"] .settings-panel {
+ grid-row: 1 / -1;
+ min-height: 0;
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ overflow: hidden;
+ padding: 12px 10px;
+ background:
+ linear-gradient(180deg, rgba(255, 255, 255, 0.025), transparent 86px),
+ var(--phone-deep);
+}
+
+.phone[data-view="cookaiware"] .cookaiware-app {
+ grid-row: 1 / 2;
+ height: auto;
+}
+
+.directory-heading {
+ display: grid;
+ gap: 3px;
+ padding: 2px 2px 4px;
+}
+
+.directory-heading h1 {
+ color: var(--strong);
+ font-size: 24px;
+ line-height: 1.08;
+ font-weight: 820;
+}
+
+.attitudes-app .directory-heading h1 {
+ font-size: 18px;
+}
+
+.cookaiware-hero {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 2px 2px 10px;
+}
+
+.cookaiware-hero img {
+ width: 48px;
+ height: 48px;
+ flex: 0 0 auto;
+ object-fit: contain;
+}
+
+.cookaiware-hero h1 {
+ color: var(--strong);
+ font-size: 23px;
+ line-height: 1.08;
+ font-weight: 820;
+}
+
+.cookaiware-tabs {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 5px;
+}
+
+.cookaiware-tab {
+ min-width: 0;
+ min-height: 34px;
+ padding: 7px 4px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: rgba(255, 255, 255, 0.04);
+ color: var(--muted);
+ font-size: 10px;
+ font-weight: 760;
+}
+
+.cookaiware-tab.active {
+ border-color: rgba(0, 122, 204, 0.5);
+ background: rgba(0, 122, 204, 0.16);
+ color: var(--strong);
+}
+
+.cookaiware-panels {
+ flex: 1 1 auto;
+ min-height: 0;
+ display: grid;
+ overflow: hidden;
+}
+
+.cook-panel {
+ min-height: 0;
+ display: none;
+ gap: 8px;
+ overflow: hidden;
+}
+
+.cook-panel.active {
+ display: grid;
+ grid-template-rows: minmax(0, 1fr) auto auto;
+}
+
+.cook-panel[data-cook-panel="inventory"].active {
+ grid-template-rows: auto minmax(0, 1fr);
+}
+
+.cook-panel[data-cook-panel="shopping"].active {
+ grid-template-rows: auto minmax(0, 1fr) auto;
+}
+
+.cook-panel[data-cook-panel="inventory-add"].active {
+ align-content: start;
+ grid-template-rows: auto;
+}
+
+.cook-panel[data-cook-panel="shopping-add"].active {
+ align-content: start;
+ grid-template-rows: auto;
+}
+
+.cook-search {
+ width: 100%;
+ min-height: var(--control-h);
+ padding: 9px 10px;
+ border-radius: var(--radius-control);
+ font-size: 14px;
+ line-height: 1.35;
+}
+
+.cook-list-bar {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) var(--control-h) var(--control-h);
+ gap: 7px;
+ align-items: center;
+}
+
+.cook-icon-button {
+ width: var(--control-h);
+ height: var(--control-h);
+ min-width: 0;
+ padding: 0;
+ border: 1px solid rgba(0, 122, 204, 0.55);
+ border-radius: var(--radius-control);
+ background: rgba(0, 122, 204, 0.16);
+ color: var(--strong);
+ font-size: 22px;
+ line-height: 1;
+ font-weight: 760;
+}
+
+.cook-icon-button:hover,
+.cook-icon-button.active {
+ border-color: rgba(0, 122, 204, 0.78);
+ background: rgba(0, 122, 204, 0.25);
+}
+
+.cook-upc-icon {
+ display: inline-grid;
+ grid-auto-flow: column;
+ justify-content: center;
+ align-content: center;
+ gap: 2px;
+}
+
+.cook-upc-icon span {
+ width: 2px;
+ height: 18px;
+ border-radius: 1px;
+ background: currentColor;
+}
+
+.cook-upc-icon span:nth-child(2) {
+ width: 4px;
+}
+
+.cook-upc-icon span:nth-child(3) {
+ height: 14px;
+}
+
+.cook-upc-scanner {
+ position: absolute;
+ inset: 80px 10px 74px;
+ z-index: 6;
+ display: grid;
+ grid-template-rows: minmax(0, 1fr) auto;
+ gap: 8px;
+ padding: 8px;
+ border: 1px solid rgba(0, 122, 204, 0.5);
+ border-radius: 8px;
+ background: rgba(10, 12, 14, 0.94);
+ box-shadow: 0 18px 50px rgba(0, 0, 0, 0.45);
+}
+
+.cook-upc-scanner[hidden] {
+ display: none;
+}
+
+.cook-upc-scanner img {
+ width: 100%;
+ height: 100%;
+ min-height: 0;
+ border-radius: 6px;
+ background: #050607;
+ object-fit: cover;
+ transform: scaleX(-1);
+}
+
+.cook-upc-scanner-actions {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto auto;
+ gap: 8px;
+ align-items: center;
+}
+
+.cook-upc-scanner-actions span {
+ min-width: 0;
+ overflow: hidden;
+ color: var(--strong);
+ font-size: 12px;
+ font-weight: 760;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.cook-upc-scanner-actions button {
+ min-height: 34px;
+ border-radius: 6px;
+}
+
+.cook-list {
+ min-height: 0;
+ display: grid;
+ align-content: start;
+ gap: 4px;
+ overflow-y: auto;
+ padding-right: 2px;
+}
+
+.cook-inventory-header,
+.cook-inventory-row {
+ display: grid;
+ grid-template-columns: minmax(58px, 1.1fr) minmax(42px, 0.7fr) minmax(48px, 0.72fr) 40px 34px 42px;
+ gap: 5px;
+ align-items: center;
+}
+
+.cook-inventory-header {
+ position: sticky;
+ top: 0;
+ z-index: 1;
+ min-height: 28px;
+ padding: 6px 7px;
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 7px;
+ background: #111314;
+ color: var(--muted);
+ font-size: 9px;
+ font-weight: 820;
+ line-height: 1;
+ text-transform: uppercase;
+}
+
+.cook-inventory-row {
+ min-height: 36px;
+ padding: 7px;
+ border: 1px solid var(--border);
+ border-left-width: 4px;
+ border-radius: 7px;
+ background: rgba(255, 255, 255, 0.045);
+}
+
+.cook-inventory-row[data-expiration="good"] {
+ border-left-color: #37b26c;
+}
+
+.cook-inventory-row[data-expiration="soon"] {
+ border-left-color: #ffbd5a;
+ background: rgba(255, 189, 90, 0.08);
+}
+
+.cook-inventory-row[data-expiration="critical"] {
+ border-left-color: #ff4d57;
+ background: rgba(255, 77, 87, 0.09);
+}
+
+.cook-inventory-row[data-expiration="expired"] {
+ border-left-color: #8b5e3c;
+ background: rgba(139, 94, 60, 0.12);
+}
+
+.cook-inventory-row[data-expiration="unknown"] {
+ border-left-color: rgba(255, 255, 255, 0.2);
+}
+
+.cook-inventory-row span {
+ min-width: 0;
+ overflow: hidden;
+ color: var(--text);
+ font-size: 11px;
+ line-height: 1.2;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.cook-inventory-row .food {
+ color: var(--strong);
+ font-weight: 780;
+}
+
+.cook-inventory-row .qty,
+.cook-inventory-row .storage {
+ color: var(--muted);
+}
+
+.cook-inventory-row .freshness {
+ justify-self: end;
+ color: var(--strong);
+ font-size: 10px;
+ font-weight: 820;
+}
+
+.cook-inventory-row .auto,
+.cook-inventory-row .used {
+ justify-self: center;
+}
+
+.cook-inventory-row .auto input {
+ width: 18px;
+ height: 18px;
+ accent-color: #007acc;
+}
+
+.cook-mini-action {
+ min-width: 0;
+ min-height: 28px;
+ padding: 0 7px;
+ border: 1px solid rgba(0, 122, 204, 0.5);
+ border-radius: 6px;
+ background: rgba(0, 122, 204, 0.15);
+ color: var(--strong);
+ font-size: 10px;
+ font-weight: 820;
+ line-height: 1;
+}
+
+.cook-mini-action:hover {
+ border-color: rgba(0, 122, 204, 0.78);
+ background: rgba(0, 122, 204, 0.24);
+}
+
+.cook-empty,
+.cook-row {
+ padding: 9px 10px;
+ border: 1px solid var(--border);
+ border-radius: 7px;
+ background: rgba(255, 255, 255, 0.045);
+}
+
+.cook-empty {
+ color: var(--muted);
+ font-size: 12px;
+}
+
+.cook-row {
+ display: grid;
+ gap: 2px;
+}
+
+.cook-shopping-row {
+ grid-template-columns: minmax(0, 1fr) 34px;
+ gap: 8px;
+ align-items: center;
+}
+
+.cook-row-copy {
+ min-width: 0;
+ display: grid;
+ gap: 2px;
+}
+
+.cook-row-action {
+ width: 34px;
+ height: 34px;
+ min-width: 0;
+ padding: 0;
+ border: 1px solid rgba(0, 122, 204, 0.5);
+ border-radius: 6px;
+ background: rgba(0, 122, 204, 0.15);
+ color: var(--strong);
+ font-size: 20px;
+ line-height: 1;
+ font-weight: 760;
+}
+
+.cook-row-action:hover {
+ border-color: rgba(0, 122, 204, 0.78);
+ background: rgba(0, 122, 204, 0.24);
+}
+
+.cook-row strong {
+ min-width: 0;
+ overflow: hidden;
+ color: var(--strong);
+ font-size: 12px;
+ line-height: 1.2;
+ font-weight: 780;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.cook-row span {
+ min-width: 0;
+ overflow: hidden;
+ color: var(--muted);
+ font-size: 11px;
+ line-height: 1.3;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.cook-form {
+ display: grid;
+ grid-template-columns: minmax(0, 1.4fr) 72px 64px auto;
+ gap: var(--bar-gap);
+ align-items: end;
+ padding: var(--bar-pad);
+ border-top: 1px solid rgba(255, 255, 255, 0.08);
+ background: var(--phone-deep);
+}
+
+.cook-form input,
+.cook-form select,
+.cook-search {
+ border: 1px solid var(--border);
+ background: var(--field);
+ color: var(--strong);
+ outline: none;
+ transition: border-color 0.15s ease, box-shadow 0.15s ease, background 0.15s ease;
+}
+
+.cook-date-field {
+ min-width: 0;
+ display: grid;
+ gap: 4px;
+}
+
+.cook-check-field {
+ min-width: 0;
+ min-height: var(--control-h);
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 9px 10px;
+ border: 1px solid var(--border);
+ border-radius: var(--radius-control);
+ background: var(--field);
+ color: var(--strong);
+ font-size: 13px;
+ font-weight: 720;
+}
+
+.cook-check-field input {
+ width: 18px;
+ height: 18px;
+ min-height: 0;
+ padding: 0;
+ border: 0;
+ background: transparent;
+ accent-color: #007acc;
+}
+
+.cook-date-field span {
+ color: var(--muted);
+ font-size: 10px;
+ font-weight: 760;
+ line-height: 1;
+ text-transform: uppercase;
+}
+
+.cook-form input,
+.cook-form select {
+ min-height: var(--control-h);
+ padding: 9px 10px;
+ border-radius: var(--radius-control);
+ font-size: 14px;
+ line-height: 1.35;
+}
+
+.cook-form input:hover,
+.cook-form select:hover,
+.cook-search:hover {
+ background: #25282a;
+}
+
+.cook-form input:focus,
+.cook-form select:focus,
+.cook-search:focus {
+ border-color: rgba(0, 122, 204, 0.72);
+ box-shadow: 0 0 0 3px rgba(0, 122, 204, 0.16);
+}
+
+.cook-form button {
+ min-width: 0;
+ min-height: var(--control-h);
+ margin: 0;
+ border-radius: var(--radius-control);
+}
+
+.cook-inventory-form {
+ grid-template-columns: minmax(0, 1fr) 76px;
+}
+
+.cook-inventory-form input:first-child,
+.cook-inventory-form .cook-date-field,
+.cook-inventory-form select,
+.cook-inventory-form .cook-check-field {
+ grid-column: 1 / -1;
+}
+
+.cook-inventory-form button {
+ grid-column: 1 / -1;
+}
+
+.cook-inline-actions,
+.cook-profile-grid {
+ display: grid;
+ gap: 6px;
+}
+
+.cook-inline-actions {
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ padding: 0 10px 10px;
+ background: var(--phone-deep);
+}
+
+.cook-inline-actions button {
+ min-height: 38px;
+ border-radius: var(--radius-control);
+}
+
+.cook-profile-grid {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+}
+
+.cook-profile-grid label {
+ display: grid;
+ gap: 4px;
+}
+
+.cook-profile-grid label:last-child {
+ grid-column: 1 / -1;
+}
+
+.cook-profile-grid span {
+ color: var(--muted);
+ font-size: 10px;
+ font-weight: 760;
+ text-transform: uppercase;
+}
+
+.cookaiware-actions {
+ display: grid;
+ grid-template-columns: repeat(4, minmax(0, 1fr));
+ gap: var(--bar-gap);
+ margin-top: auto;
+ padding: var(--bar-pad);
+ border-top: 1px solid rgba(255, 255, 255, 0.08);
+ background: var(--phone-deep);
+}
+
+.cookaiware-actions button {
+ width: 100%;
+ min-width: 0;
+ min-height: var(--control-h);
+ padding-inline: 6px;
+ border-radius: var(--radius-control);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.model-list {
+ min-height: 0;
+ display: grid;
+ align-content: start;
+ gap: 8px;
+ overflow-y: auto;
+ padding-right: 2px;
+ scrollbar-color: rgba(255, 255, 255, 0.2) transparent;
+ scrollbar-width: thin;
+}
+
+.model-contact {
+ width: 100%;
+ min-height: 58px;
+ display: grid;
+ grid-template-columns: 42px minmax(0, 1fr) 14px;
+ align-items: center;
+ gap: 10px;
+ padding: 8px 10px;
+ border-color: rgba(255, 255, 255, 0.08);
+ border-radius: 10px;
+ background: rgba(255, 255, 255, 0.045);
+ text-align: left;
+}
+
+.model-contact[data-selected="true"] {
+ border-color: rgba(0, 122, 204, 0.42);
+ background: rgba(0, 122, 204, 0.12);
+}
+
+.directory-avatar {
+ width: 42px;
+ height: 42px;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: 50%;
+ overflow: hidden;
+ background: linear-gradient(145deg, rgba(0, 122, 204, 0.24), rgba(255, 255, 255, 0.055));
+ color: var(--strong);
+ font-size: 16px;
+ font-weight: 820;
+ line-height: 1;
+}
+
+.directory-avatar.has-image {
+ background: #121416;
+}
+
+.model-contact-text {
+ min-width: 0;
+ display: grid;
+ gap: 3px;
+}
+
+.model-contact-name,
+.model-contact-meta {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.model-contact-name {
+ color: var(--strong);
+ font-size: 14px;
+ line-height: 1.2;
+ font-weight: 780;
+}
+
+.model-contact-meta {
+ color: var(--muted);
+ font-size: 11px;
+ line-height: 1.2;
+ font-weight: 700;
+}
+
+.model-contact-arrow {
+ width: 9px;
+ height: 9px;
+ border-right: 2px solid rgba(255, 255, 255, 0.5);
+ border-bottom: 2px solid rgba(255, 255, 255, 0.5);
+ transform: rotate(-45deg);
+}
+
+.phone[data-view="home"] .model-stage {
+ grid-row: auto;
+ width: min(168px, 46vw);
+ border-radius: 22px;
+ margin-bottom: 10px;
+}
+
+.phone[data-view="home"] .model-initial {
+ font-size: clamp(58px, 18vw, 86px);
+}
+
+.phone[data-view="home"] .contact-card h1 {
+ max-width: 100%;
+ color: var(--strong);
+ font-size: clamp(22px, 6.2vw, 30px);
+ line-height: 1.12;
+ text-align: center;
+ white-space: normal;
+ overflow-wrap: anywhere;
+}
+
+.phone[data-view="home"] .call-duration {
+ color: var(--accent-strong);
+ font-size: 14px;
+}
+
+.phone[data-view="home"] .connection-text {
+ max-width: 292px;
+ color: var(--muted);
+ font-size: 14px;
+ text-align: center;
+}
+
+.phone[data-view="readying"] .contact-card,
+.phone[data-view="readying"] .phone-home,
+.phone[data-view="readying"] .model-directory,
+.phone[data-view="readying"] .conversation-directory,
+.phone[data-view="readying"] .activity,
+.phone[data-view="readying"] .transcript,
+.phone[data-view="readying"] .call-actions,
+.phone[data-view="home"] .startup-screen,
+.phone[data-view="home"] .model-directory,
+.phone[data-view="home"] .conversation-directory,
+.phone[data-view="home"] .activity,
+.phone[data-view="home"] .transcript,
+.phone[data-view="calling"] .contact-card,
+.phone[data-view="calling"] .phone-home,
+.phone[data-view="calling"] .startup-screen,
+.phone[data-view="calling"] .conversation-directory,
+.phone[data-view="calling"] .transcript,
+.phone[data-view="chat"] .contact-card,
+.phone[data-view="textchat"] .contact-card,
+.phone[data-view="chat"] .phone-home,
+.phone[data-view="textchat"] .phone-home,
+.phone[data-view="chat"] .startup-screen,
+.phone[data-view="textchat"] .startup-screen,
+.phone[data-view="chat"] .model-directory,
+.phone[data-view="textchat"] .model-directory,
+.phone[data-view="chat"] .conversation-directory,
+.phone[data-view="textchat"] .conversation-directory,
+.phone[data-view="chat"] .activity,
+.phone[data-view="textchat"] .activity,
+.phone[data-view="contacts"] .contact-card,
+.phone[data-view="contacts"] .phone-home,
+.phone[data-view="contacts"] .startup-screen,
+.phone[data-view="contacts"] .conversation-directory,
+.phone[data-view="contacts"] .transcript,
+.phone[data-view="contacts"] .activity,
+.phone[data-view="conversations"] .contact-card,
+.phone[data-view="conversations"] .phone-home,
+.phone[data-view="conversations"] .startup-screen,
+.phone[data-view="conversations"] .model-directory,
+.phone[data-view="conversations"] .transcript,
+.phone[data-view="conversations"] .activity,
+.phone[data-view="attitudes"] .contact-card,
+.phone[data-view="attitudes"] .phone-home,
+.phone[data-view="attitudes"] .startup-screen,
+.phone[data-view="attitudes"] .model-directory,
+.phone[data-view="attitudes"] .conversation-directory,
+.phone[data-view="attitudes"] .transcript,
+.phone[data-view="attitudes"] .activity,
+.phone[data-view="settings"] .contact-card,
+.phone[data-view="settings"] .phone-home,
+.phone[data-view="settings"] .startup-screen,
+.phone[data-view="settings"] .model-directory,
+.phone[data-view="settings"] .conversation-directory,
+.phone[data-view="settings"] .attitudes-app,
+.phone[data-view="settings"] .cookaiware-app,
+.phone[data-view="settings"] .transcript,
+.phone[data-view="settings"] .activity,
+.phone[data-view="cookaiware"] .contact-card,
+.phone[data-view="cookaiware"] .phone-home,
+.phone[data-view="cookaiware"] .startup-screen,
+.phone[data-view="cookaiware"] .model-directory,
+.phone[data-view="cookaiware"] .conversation-directory,
+.phone[data-view="cookaiware"] .attitudes-app,
+.phone[data-view="cookaiware"] .activity,
+.phone[data-view="cookaiware"] .transcript,
+.phone[data-view="home"] .attitudes-app,
+.phone[data-view="readying"] .attitudes-app,
+.phone[data-view="calling"] .attitudes-app,
+.phone[data-view="chat"] .attitudes-app,
+.phone[data-view="textchat"] .attitudes-app,
+.phone[data-view="contacts"] .attitudes-app,
+.phone[data-view="conversations"] .attitudes-app,
+.phone[data-view="home"] .cookaiware-app,
+.phone[data-view="readying"] .cookaiware-app,
+.phone[data-view="calling"] .cookaiware-app,
+.phone[data-view="chat"] .cookaiware-app,
+.phone[data-view="textchat"] .cookaiware-app,
+.phone[data-view="contacts"] .cookaiware-app,
+.phone[data-view="conversations"] .cookaiware-app,
+.phone[data-view="attitudes"] .cookaiware-app,
+.phone:not([data-view="settings"]) .settings-panel {
+ display: none;
+}
+
+.text-chat-composer {
+ display: none;
+}
+
+h1 {
+ max-width: 100%;
+ color: var(--strong);
+ font-size: 15px;
+ line-height: 1.2;
+ font-weight: 760;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.call-duration {
+ color: var(--muted);
+ font-size: 12px;
+ font-weight: 720;
+}
+
+.connection-text {
+ max-width: 100%;
+ min-height: 0;
+ color: var(--muted);
+ font-size: 12px;
+ line-height: 1.35;
+ overflow-wrap: anywhere;
+}
+
+.activity {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ padding: 10px 16px;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.05);
+ background: #101112;
+}
+
+.phone[data-view="calling"] .activity {
+ grid-row: 1 / -1;
+ min-height: 0;
+ height: 100%;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ gap: 22px;
+ padding: 34px 26px;
+ border-bottom: 0;
+ background:
+ radial-gradient(circle at 50% 44%, rgba(0, 122, 204, 0.15), transparent 36%),
+ var(--phone-deep);
+ text-align: center;
+}
+
+.activity-visual {
+ width: 30px;
+ height: 30px;
+ flex: 0 0 auto;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 3px;
+ border-radius: 8px;
+ background: rgba(255, 255, 255, 0.055);
+}
+
+.phone[data-view="calling"] .activity-visual {
+ width: 112px;
+ height: 112px;
+ gap: 7px;
+ border-radius: 50%;
+}
+
+.phone[data-view="calling"] .activity-visual[data-mode="thinking"] {
+ border-color: rgba(0, 122, 204, 0.56);
+ background: rgba(0, 122, 204, 0.12);
+}
+
+.activity-visual[data-mode="waiting"] {
+ border: 1px solid rgba(255, 189, 90, 0.28);
+}
+
+.activity-visual[data-mode="thinking"] {
+ border: 1px solid rgba(0, 122, 204, 0.42);
+ background: rgba(0, 122, 204, 0.14);
+}
+
+.activity-visual[data-mode="listening"] {
+ border: 1px solid rgba(0, 122, 204, 0.42);
+ background: rgba(0, 122, 204, 0.12);
+}
+
+.activity-visual span {
+ width: 4px;
+ height: 4px;
+ border-radius: 999px;
+ background: var(--accent-strong);
+}
+
+.activity-visual[data-mode="thinking"] span {
+ animation: pulse-dot 1.1s ease-in-out infinite;
+}
+
+.activity-visual[data-mode="thinking"] span:nth-child(2) {
+ animation-delay: 0.12s;
+}
+
+.activity-visual[data-mode="thinking"] span:nth-child(3) {
+ animation-delay: 0.24s;
+}
+
+.activity-visual[data-mode="thinking"] span:nth-child(4) {
+ display: none;
+}
+
+.activity-visual[data-mode="listening"] span {
+ width: 4px;
+ height: 16px;
+ background: var(--green);
+ animation: listen-bar 0.9s ease-in-out infinite;
+}
+
+.activity-visual[data-mode="listening"] span:nth-child(2) {
+ height: 11px;
+ animation-delay: 0.08s;
+}
+
+.activity-visual[data-mode="listening"] span:nth-child(3) {
+ height: 15px;
+ animation-delay: 0.16s;
+}
+
+.activity-visual[data-mode="listening"] span:nth-child(4) {
+ height: 9px;
+ animation-delay: 0.24s;
+}
+
+.connection-summary {
+ color: var(--text);
+ font-size: 13px;
+ line-height: 1.2;
+ font-weight: 780;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.phone[data-view="calling"] .connection-summary {
+ max-width: 100%;
+ color: var(--strong);
+ font-size: clamp(28px, 8vw, 38px);
+ line-height: 1.05;
+ white-space: normal;
+}
+
+.transcript {
+ min-height: 0;
+ max-height: none;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ overflow-y: auto;
+ padding: 14px 14px 18px;
+ background:
+ linear-gradient(180deg, rgba(255, 255, 255, 0.02), transparent 82px),
+ var(--phone-deep);
+ scrollbar-color: rgba(255, 255, 255, 0.2) transparent;
+ scrollbar-width: thin;
+}
+
+.transcript-empty {
+ width: fit-content;
+ max-width: 78%;
+ margin: 0;
+ padding: 10px 12px;
+ border-radius: 8px;
+ background: var(--surface-2);
+ color: var(--muted);
+ font-size: 13px;
+ line-height: 1.35;
+}
+
+.message-row {
+ width: 100%;
+ display: flex;
+ align-items: flex-end;
+ gap: 8px;
+}
+
+.message-row.assistant {
+ justify-content: flex-start;
+}
+
+.message-row.user {
+ justify-content: flex-end;
+}
+
+.message-row.user .chat-avatar {
+ order: 2;
+}
+
+.message-row.user .chat-bubble {
+ order: 1;
+}
+
+.chat-avatar {
+ width: 28px;
+ height: 28px;
+ flex: 0 0 28px;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: 50%;
+ overflow: hidden;
+ background: linear-gradient(145deg, rgba(0, 122, 204, 0.24), rgba(255, 255, 255, 0.055));
+ color: var(--strong);
+ font-size: 12px;
+ font-weight: 820;
+ line-height: 1;
+}
+
+.chat-avatar.user {
+ border-color: rgba(22, 132, 215, 0.42);
+ background: #1684d7;
+ color: #f5fbff;
+}
+
+.chat-avatar.assistant.has-image,
+.topbar-avatar.has-image {
+ background: #121416;
+}
+
+.chat-bubble {
+ max-width: 78%;
+ padding: 10px 12px;
+ border-radius: 8px;
+ color: var(--text);
+ font-size: 14px;
+ line-height: 1.35;
+ overflow-wrap: anywhere;
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.18);
+}
+
+.message-row .chat-bubble {
+ max-width: min(78%, calc(100% - 42px));
+ align-self: auto;
+}
+
+.chat-bubble.user {
+ align-self: flex-end;
+ border-bottom-right-radius: 3px;
+ background: linear-gradient(180deg, #1684d7, var(--accent));
+ color: #f5fbff;
+}
+
+.chat-bubble.assistant {
+ align-self: flex-start;
+ border: 1px solid rgba(255, 255, 255, 0.04);
+ border-bottom-left-radius: 3px;
+ background: var(--surface-2);
+}
+
+.typing-bubble {
+ width: auto;
+ min-width: 54px;
+ min-height: 38px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 5px;
+ padding: 10px 13px;
+}
+
+.typing-bubble span {
+ width: 6px;
+ height: 6px;
+ border-radius: 999px;
+ background: currentColor;
+ opacity: 0.58;
+ animation: typing-dot 1.05s ease-in-out infinite;
+}
+
+.typing-bubble span:nth-child(2) {
+ animation-delay: 0.13s;
+}
+
+.typing-bubble span:nth-child(3) {
+ animation-delay: 0.26s;
+}
+
+.call-actions {
+ position: relative;
+ gap: 8px;
+ justify-content: center;
+ min-height: 64px;
+ padding: 10px 12px;
+ border-top: 1px solid rgba(255, 255, 255, 0.08);
+ background: linear-gradient(180deg, var(--topbar-2), var(--topbar));
+}
+
+.call-actions::after {
+ content: "";
+ flex: 1 1 auto;
+ min-width: 34px;
+ height: 30px;
+ border-left: 2px solid rgba(255, 255, 255, 0.22);
+ opacity: 0.7;
+ display: none;
+}
+
+.phone[data-view="home"] .call-actions,
+.phone[data-view="calling"] .call-actions {
+ min-height: 82px;
+ padding: 12px 18px 22px;
+ border-top: 0;
+ background: var(--phone-deep);
+}
+
+.phone[data-view="home"] .call-actions {
+ display: none;
+}
+
+.nav-back-btn {
+ display: none;
+}
+
+.phone[data-view="chat"] .nav-back-btn,
+.phone[data-view="textchat"] .nav-back-btn,
+.phone[data-view="contacts"] .nav-back-btn,
+.phone[data-view="conversations"] .nav-back-btn,
+.phone[data-view="attitudes"] .nav-back-btn,
+.phone[data-view="settings"] .nav-back-btn {
+ display: inline-flex;
+}
+
+.phone[data-view="calling"] .call-btn,
+.phone[data-view="calling"] .aux-btn {
+ display: none;
+}
+
+.phone[data-view="calling"] .end-btn {
+ min-width: 156px;
+}
+
+.phone[data-view="contacts"] .call-actions,
+.phone[data-view="conversations"] .call-actions,
+.phone[data-view="attitudes"] .call-actions,
+.phone[data-view="settings"] .call-actions {
+ justify-content: flex-start;
+ min-height: 76px;
+ padding: 10px 18px 20px;
+ border-top: 0;
+ background: var(--phone-deep);
+}
+
+.phone[data-view="cookaiware"] .call-actions {
+ display: none;
+}
+
+.phone[data-view="contacts"] .call-actions button:not(.nav-back-btn),
+.phone[data-view="conversations"] .call-actions button:not(.nav-back-btn),
+.phone[data-view="attitudes"] .call-actions button:not(.nav-back-btn),
+.phone[data-view="settings"] .call-actions button:not(.nav-back-btn) {
+ display: none;
+}
+
+.phone[data-view="cookaiware"] .contacts-btn,
+.phone[data-view="cookaiware"] .nav-back-btn {
+ display: none;
+}
+
+.phone[data-view="conversations"] .contacts-btn {
+ display: none !important;
+}
+
+.phone[data-view="contacts"] .nav-back-btn,
+.phone[data-view="conversations"] .nav-back-btn,
+.phone[data-view="attitudes"] .nav-back-btn,
+.phone[data-view="settings"] .nav-back-btn {
+ min-width: 96px;
+}
+
+.phone[data-view="chat"] .call-actions {
+ justify-content: flex-end;
+}
+
+.phone[data-view="textchat"] .call-actions {
+ display: none;
+}
+
+.phone[data-view="chat"] .nav-back-btn {
+ order: 0;
+}
+
+.phone[data-view="chat"] .contacts-btn,
+.phone[data-view="textchat"] .contacts-btn {
+ display: none !important;
+}
+
+.text-actions-menu {
+ display: none;
+}
+
+.phone[data-view="textchat"] .text-actions-btn.active {
+ border-color: rgba(0, 122, 204, 0.46);
+ background: rgba(0, 122, 204, 0.18);
+ color: #d8f0ff;
+}
+
+.phone[data-view="textchat"] .text-actions-menu {
+ position: absolute;
+ right: 18px;
+ bottom: 62px;
+ z-index: 6;
+ min-width: 174px;
+ display: grid;
+ gap: 6px;
+ padding: 8px;
+ border: 1px solid var(--border-strong);
+ border-radius: 8px;
+ background: #111314;
+ box-shadow: 0 18px 44px rgba(0, 0, 0, 0.48);
+}
+
+.phone[data-view="textchat"] .text-actions-menu[hidden] {
+ display: none;
+}
+
+.text-actions-menu button {
+ width: 100%;
+ min-height: 34px;
+ margin: 0;
+ justify-content: flex-start;
+ border-radius: 6px;
+ text-align: left;
+}
+
+.phone[data-view="chat"] .round-btn:not(.nav-back-btn):not(.contacts-btn),
+.phone[data-view="chat"] .call-btn {
+ order: 3;
+}
+
+.phone[data-view="chat"] .end-btn {
+ order: 4;
+}
+
+.contacts-btn.active {
+ border-color: rgba(0, 122, 204, 0.46);
+ background: rgba(0, 122, 204, 0.18);
+ color: #d8f0ff;
+}
+
+.contacts-btn {
+ width: 40px;
+ padding: 0;
+}
+
+.contacts-btn::before {
+ display: none;
+}
+
+.action-icon {
+ width: 17px;
+ height: 17px;
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 2;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+}
+
+button {
+ min-height: 38px;
+ padding: 9px 12px;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ color: var(--text);
+ background: rgba(255, 255, 255, 0.06);
+ font: inherit;
+ font-size: 13px;
+ font-weight: 760;
+ cursor: pointer;
+ transition: transform 0.14s ease, filter 0.14s ease, border-color 0.14s ease, opacity 0.14s ease, background 0.14s ease;
+}
+
+button:hover:not(:disabled) {
+ transform: translateY(-1px);
+ filter: brightness(1.06);
+}
+
+button:active:not(:disabled) {
+ transform: translateY(0);
+}
+
+button:focus-visible {
+ outline: 2px solid rgba(0, 122, 204, 0.72);
+ outline-offset: 2px;
+}
+
+button:disabled {
+ cursor: not-allowed;
+ opacity: 0.42;
+}
+
+.round-btn,
+.call-btn {
+ width: auto;
+ min-height: 36px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 7px;
+ padding: 0 12px;
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ background: rgba(255, 255, 255, 0.07);
+ box-shadow: none;
+ white-space: nowrap;
+}
+
+.round-btn::before,
+.call-btn::before {
+ content: "";
+ width: 8px;
+ height: 8px;
+ display: block;
+ border-radius: 50%;
+ background: currentColor;
+ box-shadow: none;
+}
+
+.contacts-btn::before {
+ display: none !important;
+}
+
+.nav-back-btn::before {
+ display: none;
+}
+
+.call-btn {
+ border-color: rgba(0, 122, 204, 0.46);
+ background: var(--accent);
+ color: #f6fbff;
+}
+
+.call-btn:disabled {
+ border-color: var(--border);
+ background: rgba(255, 255, 255, 0.08);
+ color: var(--muted);
+}
+
+.aux-btn {
+ color: #9fd8ff;
+}
+
+.aux-btn.active {
+ color: #ffd3d7;
+ border-color: rgba(255, 77, 87, 0.36);
+ background: rgba(255, 77, 87, 0.12);
+}
+
+.end-btn {
+ border-color: rgba(255, 77, 87, 0.38);
+ background: rgba(255, 77, 87, 0.13);
+ color: #ffd7da;
+}
+
+.phone:not([data-state="running"]) .aux-btn:not(.nav-back-btn),
+.phone:not([data-state="running"]):not([data-view="calling"]) .end-btn {
+ display: none;
+}
+
+.phone[data-state="running"] .call-btn,
+.phone[data-view="calling"] .call-btn {
+ display: none;
+}
+
+.mute-icon,
+.hangup-icon,
+.call-icon {
+ display: none;
+}
+
+.hamburger-icon {
+ position: relative;
+ width: 15px;
+ height: 2px;
+ display: block;
+ border-radius: 999px;
+ background: currentColor;
+}
+
+.hamburger-icon::before,
+.hamburger-icon::after {
+ content: "";
+ position: absolute;
+ left: 0;
+ width: 15px;
+ height: 2px;
+ border-radius: 999px;
+ background: currentColor;
+}
+
+.hamburger-icon::before {
+ top: -5px;
+}
+
+.hamburger-icon::after {
+ top: 5px;
+}
+
+.status {
+ min-height: 27px;
+ padding: 5px 14px 9px;
+ background: var(--topbar);
+ color: var(--muted);
+ font-size: 12px;
+ line-height: 1.35;
+ text-align: center;
+ opacity: 1;
+ transition: opacity 0.22s ease;
+}
+
+.status.fading {
+ opacity: 0;
+}
+
+.status[hidden] {
+ display: none;
+}
+
+.status.ok {
+ color: var(--green);
+}
+
+.status.warn {
+ color: var(--warn);
+}
+
+.status.error {
+ color: var(--error);
+}
+
+.slow-start-message {
+ margin: 0;
+ padding: 9px 14px 12px;
+ border-top: 1px solid rgba(255, 189, 90, 0.16);
+ background: rgba(255, 189, 90, 0.08);
+ color: var(--warn);
+ font-size: 12px;
+ line-height: 1.35;
+ text-align: center;
+}
+
+.settings-panel {
+ min-width: 0;
+}
+
+.panel-heading {
+ justify-content: space-between;
+ gap: 10px;
+ flex: 0 0 auto;
+ padding-bottom: 12px;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.08);
+}
+
+.panel-heading h2 {
+ color: var(--strong);
+ font-size: 18px;
+ line-height: 1.2;
+ font-weight: 780;
+}
+
+.eyebrow,
+.label {
+ color: var(--muted);
+ font-size: 10px;
+ font-weight: 760;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+}
+
+.muted {
+ color: var(--muted);
+}
+
+.mono {
+ color: var(--muted);
+ font-family: "Cascadia Mono", Consolas, monospace;
+ font-size: 11px;
+ line-height: 1.45;
+ overflow-wrap: anywhere;
+}
+
+.form-grid {
+ width: 100%;
+ min-width: 0;
+ flex: 1 1 auto;
+ display: grid;
+ grid-template-columns: 1fr;
+ gap: 5px;
+ margin-top: 9px;
+ overflow-y: auto;
+ overflow-x: hidden;
+ padding-right: 2px;
+ scrollbar-color: rgba(255, 255, 255, 0.2) transparent;
+ scrollbar-width: thin;
+}
+
+.phone[data-view="textchat"] .transcript {
+ display: flex;
+}
+
+.phone[data-view="textchat"] .text-chat-composer {
+ position: relative;
+ min-height: 62px;
+ display: grid;
+ grid-template-columns: 38px 38px minmax(0, 1fr) 38px auto;
+ gap: 6px;
+ align-items: end;
+ padding: 8px 10px 10px;
+ border-top: 1px solid rgba(255, 255, 255, 0.08);
+ background: var(--phone-deep);
+}
+
+.text-chat-composer textarea {
+ width: 100%;
+ min-width: 0;
+ min-height: 40px;
+ max-height: 110px;
+ resize: none;
+ padding: 9px 10px;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: var(--field);
+ color: var(--strong);
+ font: inherit;
+ font-size: 14px;
+ line-height: 1.35;
+ outline: none;
+ transition: border-color 0.15s ease, box-shadow 0.15s ease, background 0.15s ease;
+}
+
+.text-chat-composer textarea:hover {
+ background: #25282a;
+}
+
+.text-chat-composer textarea:focus {
+ border-color: rgba(0, 122, 204, 0.72);
+ box-shadow: 0 0 0 3px rgba(0, 122, 204, 0.16);
+}
+
+.text-chat-composer button {
+ min-width: 0;
+ min-height: 40px;
+ margin: 0;
+ border-radius: 8px;
+}
+
+.text-chat-composer .text-icon-btn {
+ min-width: 38px;
+ width: 38px;
+ height: 40px;
+ display: grid;
+ place-items: center;
+ padding: 0;
+ border-radius: 8px;
+ color: #d8f0ff;
+}
+
+.text-chat-composer .primary {
+ min-width: 54px;
+ padding: 0 10px;
+ border-radius: 8px;
+}
+
+.attachment-preview {
+ grid-column: 1 / -1;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ min-width: 0;
+ padding: 7px 9px;
+ border: 1px solid rgba(0, 122, 204, 0.32);
+ border-radius: 8px;
+ background: rgba(0, 122, 204, 0.12);
+ color: var(--text);
+ font-size: 12px;
+ font-weight: 720;
+}
+
+.attachment-preview[hidden] {
+ display: none;
+}
+
+.attachment-preview span {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.attachment-preview button {
+ min-width: 0;
+ min-height: 28px;
+ padding: 4px 8px;
+ border-radius: 6px;
+ font-size: 11px;
+}
+
+.model-row,
+.chat-id-row {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto;
+ gap: 8px;
+}
+
+.toggle-row {
+ min-height: 36px;
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ padding: 8px 10px;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: rgba(255, 255, 255, 0.035);
+ color: var(--text);
+}
+
+.toggle-row input {
+ width: 18px;
+ height: 18px;
+ min-height: 18px;
+ flex: 0 0 18px;
+ padding: 0;
+ border-radius: 4px;
+ background: transparent;
+ accent-color: var(--accent);
+ transform: none;
+}
+
+.toggle-row span {
+ font-size: 12px;
+ line-height: 1.25;
+ font-weight: 760;
+}
+
+label {
+ color: var(--muted);
+ font-size: 12px;
+ font-weight: 720;
+}
+
+input,
+select {
+ width: 100%;
+ max-width: 100%;
+ min-width: 0;
+ min-height: 40px;
+ padding: 9px 11px;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: var(--field);
+ color: var(--strong);
+ font: inherit;
+ font-size: 13px;
+ outline: none;
+ text-overflow: ellipsis;
+ transition: border-color 0.15s ease, box-shadow 0.15s ease, background 0.15s ease;
+}
+
+select {
+ display: block;
+ appearance: none;
+ padding-right: 34px;
+ background:
+ linear-gradient(45deg, transparent 50%, rgba(244, 246, 248, 0.78) 50%) calc(100% - 18px) 17px / 6px 6px no-repeat,
+ linear-gradient(135deg, rgba(244, 246, 248, 0.78) 50%, transparent 50%) calc(100% - 12px) 17px / 6px 6px no-repeat,
+ var(--field);
+ white-space: nowrap;
+}
+
+.native-attitude-select {
+ display: none;
+}
+
+.attitude-picker {
+ width: 100%;
+ min-width: 0;
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 7px;
+ padding: 8px;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: rgba(255, 255, 255, 0.035);
+}
+
+.attitude-option {
+ min-width: 0;
+ min-height: 34px;
+ padding: 7px 8px;
+ border-radius: 6px;
+ color: var(--text);
+ font-size: 12px;
+ font-weight: 760;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.attitude-option[aria-selected="true"] {
+ border-color: rgba(0, 122, 204, 0.7);
+ background: rgba(0, 122, 204, 0.24);
+ color: var(--strong);
+}
+
+input:hover,
+select:hover {
+ background: #25282a;
+}
+
+input[type="checkbox"]:hover {
+ background: transparent;
+}
+
+select:hover {
+ background:
+ linear-gradient(45deg, transparent 50%, rgba(244, 246, 248, 0.84) 50%) calc(100% - 18px) 17px / 6px 6px no-repeat,
+ linear-gradient(135deg, rgba(244, 246, 248, 0.84) 50%, transparent 50%) calc(100% - 12px) 17px / 6px 6px no-repeat,
+ #25282a;
+}
+
+input:focus,
+select:focus {
+ border-color: rgba(0, 122, 204, 0.72);
+ box-shadow: 0 0 0 3px rgba(0, 122, 204, 0.16);
+}
+
+select option {
+ background: #202325;
+ color: var(--strong);
+}
+
+input.secret-saved::placeholder {
+ color: var(--green);
+ opacity: 0.95;
+}
+
+input[type="range"] {
+ min-height: 30px;
+ padding: 0;
+ accent-color: var(--accent);
+ background: transparent;
+}
+
+.range-row {
+ gap: 10px;
+}
+
+.range-row input[type="number"] {
+ max-width: 82px;
+}
+
+.advanced,
+.settings-section,
+.tool-settings,
+.env-row {
+ margin-top: 0;
+}
+
+.advanced,
+.settings-section,
+.tool-settings {
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: rgba(255, 255, 255, 0.035);
+}
+
+.advanced summary,
+.settings-section summary,
+.tool-settings summary {
+ display: flex;
+ align-items: center;
+ min-height: 0;
+ padding: 4px 9px;
+ color: var(--muted);
+ cursor: pointer;
+ font-size: 12px;
+ line-height: 1.1;
+ font-weight: 760;
+}
+
+.advanced summary:hover,
+.advanced[open] summary,
+.settings-section summary:hover,
+.settings-section[open] summary,
+.tool-settings summary:hover,
+.tool-settings[open] summary {
+ color: var(--strong);
+}
+
+.settings-section-body {
+ display: grid;
+ grid-template-columns: 1fr;
+ gap: 8px;
+ padding: 0 12px 12px;
+}
+
+.settings-section-body .advanced,
+.settings-section-body .tool-settings,
+.settings-section-body .env-row {
+ margin-top: 0;
+}
+
+.advanced-grid {
+ display: grid;
+ grid-template-columns: 1fr;
+ gap: 8px;
+ padding: 0 12px 12px;
+}
+
+.tool-list {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 7px;
+ padding: 0 12px 12px;
+}
+
+.tool-toggle {
+ min-height: 38px;
+ display: grid;
+ grid-template-columns: 18px minmax(0, 1fr);
+ align-items: center;
+ padding: 8px 10px;
+ background: rgba(255, 255, 255, 0.026);
+ transition: background 0.15s ease, border-color 0.15s ease;
+ transform: none;
+}
+
+.tool-toggle input {
+ width: 18px;
+ height: 18px;
+ min-height: 18px;
+ padding: 0;
+}
+
+.tool-toggle span {
+ min-width: 0;
+ font-size: 11px;
+ text-transform: none;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.env-row {
+ display: grid;
+ gap: 6px;
+ padding: 10px 11px;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: rgba(255, 255, 255, 0.035);
+}
+
+.form-actions {
+ justify-content: flex-end;
+ gap: 8px;
+ flex-wrap: wrap;
+ margin-top: 4px;
+}
+
+.primary {
+ border-color: rgba(0, 122, 204, 0.5);
+ background: var(--accent);
+ color: #f6fbff;
+}
+
+.primary.danger {
+ border-color: rgba(255, 77, 87, 0.44);
+ background: rgba(255, 77, 87, 0.18);
+ color: #ffd7da;
+}
+
+.secondary {
+ background: rgba(255, 255, 255, 0.07);
+}
+
+@keyframes pulse-dot {
+ 0%,
+ 100% {
+ transform: scale(0.78);
+ opacity: 0.58;
+ }
+ 50% {
+ transform: scale(1.16);
+ opacity: 1;
+ }
+}
+
+@keyframes power-logo {
+ 0%,
+ 100% {
+ filter: brightness(0.74);
+ transform: scale(0.98);
+ }
+ 50% {
+ filter: brightness(1.08);
+ transform: scale(1);
+ }
+}
+
+@keyframes power-ring {
+ 0% {
+ opacity: 0;
+ transform: scale(0.92);
+ }
+ 50% {
+ opacity: 0.55;
+ }
+ 100% {
+ opacity: 0;
+ transform: scale(1.14);
+ }
+}
+
+@keyframes power-bar {
+ 0% {
+ transform: translateX(-110%);
+ }
+ 100% {
+ transform: translateX(260%);
+ }
+}
+
+@keyframes listen-bar {
+ 0%,
+ 100% {
+ transform: scaleY(0.65);
+ }
+ 50% {
+ transform: scaleY(1);
+ }
+}
+
+@keyframes typing-dot {
+ 0%,
+ 100% {
+ transform: translateY(0);
+ opacity: 0.45;
+ }
+ 45% {
+ transform: translateY(-3px);
+ opacity: 1;
+ }
+}
+
+.attitudes-grid {
+ min-height: 0;
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ align-content: start;
+ gap: 6px;
+ overflow-y: auto;
+ padding-right: 2px;
+ scrollbar-color: rgba(255, 255, 255, 0.2) transparent;
+ scrollbar-width: thin;
+}
+
+.attitude-card {
+ min-width: 0;
+ min-height: 38px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 6px 6px;
+ border-radius: 8px;
+ color: var(--text);
+ font-size: 11px;
+ font-weight: 760;
+ text-align: center;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.attitude-card[aria-selected="true"] {
+ border-color: rgba(0, 122, 204, 0.7);
+ background: rgba(0, 122, 204, 0.24);
+ color: var(--strong);
+ box-shadow: inset 0 0 0 1px rgba(0, 122, 204, 0.42);
+}
+
+.attitudes-actions {
+ display: flex;
+ gap: 6px;
+ padding-top: 8px;
+}
+
+.test-speech-btn {
+ flex: 1;
+ min-height: 34px;
+ border-radius: 8px;
+ font-size: 11px;
+ font-weight: 760;
+}
+
+@media (max-width: 440px) {
+ .phone-shell {
+ padding: 0;
+ }
+
+ .phone {
+ width: 100%;
+ height: 100vh;
+ min-height: 100vh;
+ border: 0;
+ border-radius: 0;
+ }
+
+ .settings-panel {
+ padding: 12px 10px;
+ }
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/__init__.py b/src/Reachy_OpenWebUI/sub_apps/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b88adfe2910ecfa51f21b83b1ab7f3a5dff0a19c
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/__init__.py
@@ -0,0 +1 @@
+"""Optional mini-app packages layered on top of the core Reachy app."""
diff --git a/src/Reachy_OpenWebUI/sub_apps/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..66e37f3c4095528e8afb64e990e983a29de9e1b2
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/__init__.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..13a50fa0cd43555518bd15ad7b5481aff89a9fa2
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/__init__.py
@@ -0,0 +1,237 @@
+"""Robot attitude definitions shared by motion and tool filtering.
+
+Each attitude lives in its own sub-package (e.g. attitudes/calm/) with
+separate idle.py, sway.py, and speech.py files. This module assembles
+them into AttitudeProfile instances and exposes the same public API as
+the old monolithic attitudes.py.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, fields
+from typing import Any, Iterable
+
+# ── Dataclass ────────────────────────────────────────────────────────
+
+@dataclass(frozen=True)
+class AttitudeProfile:
+ """One user-facing attitude that controls idle, speech, and accent moves."""
+
+ # Identity
+ name: str
+ label: str
+ enabled: bool = True
+
+ # Idle posture
+ idle_delay_s: float = 0.3
+ interpolation_s: float = 1.0
+ base_x_m: float = 0.0
+ base_y_m: float = 0.0
+ base_z_m: float = 0.0
+ base_roll_deg: float = 0.0
+ base_pitch_deg: float = 0.0
+ base_yaw_deg: float = 0.0
+ base_body_yaw_deg: float = 0.0
+ base_left_antenna_deg: float = 5.0
+ base_right_antenna_deg: float = 0.0
+ breathing_z_amplitude_m: float = 0.005
+ breathing_frequency_hz: float = 0.1
+
+ # Idle sway
+ antenna_sway_deg: float = 15.0
+ antenna_sway_sync: bool = False
+ antenna_frequency_hz: float = 0.5
+ x_sway_m: float = 0.0
+ y_sway_m: float = 0.0
+ roll_sway_deg: float = 0.0
+ pitch_sway_deg: float = 0.0
+ yaw_sway_deg: float = 0.0
+ head_sway_frequency_hz: float = 0.05
+ body_yaw_sway_deg: float = 0.0
+ body_yaw_frequency_hz: float = 0.04
+
+ # Speech motion
+ speaking_motion_scale: float = 1.0
+ speaking_pitch_scale: float = 1.0
+ speaking_yaw_scale: float = 1.0
+ speaking_roll_scale: float = 1.0
+ speaking_x_scale: float = 1.0
+ speaking_y_scale: float = 1.0
+ speaking_z_scale: float = 1.0
+ speaking_frequency_scale: float = 1.0
+ speaking_pitch_offset_deg: float = 0.0
+ speaking_z_offset_m: float = 0.0
+
+ # Behavior filters
+ allowed_emotions: tuple[str, ...] = ()
+ allowed_dances: tuple[str, ...] = ()
+
+
+# ── Hardware reference ────────────────────────────────────────────────
+#
+# GAZE STABILISATION
+# The head is world-stabilised (like a chicken / camera gimbal). The body
+# base can rotate freely underneath and the head will keep pointing at the
+# same target — the camera view never shifts. This means:
+# • body_yaw_sway is cosmetic only — it adds visual personality but does
+# NOT change where the robot looks.
+# • head yaw/pitch/roll directly move the gaze. Even small yaw values
+# make the robot appear to look away from the user. Yaw should be the
+# SMALLEST speech-wobble axis, not the largest.
+#
+# HARDWARE ZEROS (raw servo values, not SDK values)
+# Head pitch / yaw / Y: 0.128 rad ≈ 7.3° is mechanical centre.
+# Left antenna (ID 18): −0.05 rad is mechanical zero.
+# Right antenna: mirrors are NOT symmetric
+# (left −0.693 rad ↔ right +0.707 rad at the same
+# physical position — ~0.8° offset).
+# Antenna max travel: 2.793 rad ≈ 160°.
+#
+# The SDK's create_head_pose(0,0,0,0,0,0) does NOT compensate for the
+# hardware yaw offset. BreathingMove (moves.py) adds HEAD_YAW_OFFSET_RAD
+# (0.128 rad) to all yaw values so attitude base_yaw_deg = 0 means true
+# centre. Antenna values go through np.deg2rad() and are closer to raw —
+# the hardware asymmetry means negating left→right does not produce a
+# perfect visual mirror.
+#
+# This is why the emotion library uses RELATIVE movements (deltas from the
+# current pose) rather than absolute positions — it sidesteps all of the
+# above.
+#
+# ANTENNA RANGE
+# 0 rad (0°) = straight up
+# ±1.5 rad (±86°) = straight out horizontal
+# ±2.8 rad (±160°) = pinned back / fully down (near 2.793 max)
+# Left antenna: negative = out/down. Right antenna: positive = out/down.
+#
+# HEAD RANGE
+# Head pitch: positive = chin down (looking down), negative = chin up
+# Head roll: positive = tilt left, negative = tilt right
+# Head pitch/roll hardware limit: ±40°
+
+
+def _build_profile(name: str) -> AttitudeProfile:
+ """Import a sub-package and merge its idle/sway/speech dicts into a profile."""
+ import importlib
+
+ mod = importlib.import_module(f"Reachy_OpenWebUI.sub_apps.attitudes.{name}")
+ meta = getattr(mod, "META", {})
+ idle = getattr(mod, "IDLE", {})
+ sway = getattr(mod, "SWAY", {})
+ speech = getattr(mod, "SPEECH", {})
+ merged = {**meta, **idle, **sway, **speech}
+ merged.setdefault("name", name)
+ valid_fields = {f.name for f in fields(AttitudeProfile)}
+ cleaned = {k: v for k, v in merged.items() if k in valid_fields}
+ return AttitudeProfile(**cleaned)
+
+
+_ATTITUDE_NAMES = [
+ "still",
+ "calm",
+ "attentive",
+ "curious",
+ "flirty",
+ "silly",
+ "restless",
+ "spaceshot",
+ "shy",
+ "serious",
+ "tough",
+ "angry",
+]
+
+ATTITUDE_PROFILES: dict[str, AttitudeProfile] = {
+ name: _build_profile(name) for name in _ATTITUDE_NAMES
+}
+
+
+# ── Public helpers (same API as before) ──────────────────────────────
+
+def _normalize_attitude_name(name: str | None) -> str:
+ return (name or "").strip().lower().replace(" ", "_").replace("-", "_")
+
+
+def resolve_attitude(name: str | None) -> AttitudeProfile:
+ """Resolve an attitude name, falling back to calm."""
+ return ATTITUDE_PROFILES.get(_normalize_attitude_name(name)) or ATTITUDE_PROFILES["calm"]
+
+
+def available_attitudes() -> list[dict[str, str]]:
+ """Return attitude choices for the settings UI."""
+ return [{"name": profile.name, "label": profile.label} for profile in ATTITUDE_PROFILES.values()]
+
+
+def _normalize_move_name(name: str | None) -> str:
+ return str(name or "").strip().lower()
+
+
+def _filter_allowed(allowed: Iterable[str], available: Iterable[str]) -> list[str]:
+ available_by_normalized = {
+ _normalize_move_name(item): str(item)
+ for item in available
+ if _normalize_move_name(item)
+ }
+ return [
+ available_by_normalized[normalized]
+ for name in allowed
+ if (normalized := _normalize_move_name(name)) in available_by_normalized
+ ]
+
+
+def allowed_emotions_for_attitude(attitude: str | None, available: Iterable[str]) -> list[str]:
+ """Return emotions allowed by the selected attitude and installed library."""
+ profile = resolve_attitude(attitude)
+ return _filter_allowed(profile.allowed_emotions, available)
+
+
+def allowed_dances_for_attitude(attitude: str | None, available: Iterable[str]) -> list[str]:
+ """Return dances allowed by the selected attitude and installed library."""
+ profile = resolve_attitude(attitude)
+ return _filter_allowed(profile.allowed_dances, available)
+
+
+def _describe_allowed(kind: str, attitude: str | None, allowed: list[str]) -> str:
+ profile = resolve_attitude(attitude)
+ if not allowed:
+ return f"No {kind} are available for the current {profile.label} attitude."
+ return f"Current {profile.label} attitude allows: {', '.join(allowed)}."
+
+
+def apply_attitude_to_tool_specs(
+ specs: list[dict[str, Any]],
+ attitude: str | None,
+) -> list[dict[str, Any]]:
+ """Narrow dance/emotion tool schemas to the active attitude."""
+ for spec in specs:
+ function = spec.get("function") if isinstance(spec, dict) else None
+ if not isinstance(function, dict):
+ continue
+ name = str(function.get("name") or "")
+ parameters = function.get("parameters")
+ properties = parameters.get("properties") if isinstance(parameters, dict) else None
+ if not isinstance(properties, dict):
+ continue
+
+ if name == "dance":
+ move = properties.get("move")
+ if isinstance(move, dict):
+ available = move.get("enum") if isinstance(move.get("enum"), list) else []
+ allowed = allowed_dances_for_attitude(attitude, available)
+ move["enum"] = allowed
+ move["description"] = (
+ "Name of the move; omit for a random allowed move. "
+ f"{_describe_allowed('dance moves', attitude, allowed)}"
+ )
+ elif name == "play_emotion":
+ emotion = properties.get("emotion")
+ if isinstance(emotion, dict):
+ available = emotion.get("enum") if isinstance(emotion.get("enum"), list) else []
+ allowed = allowed_emotions_for_attitude(attitude, available)
+ emotion["enum"] = allowed
+ emotion["description"] = (
+ "Name of the emotion to play. "
+ f"{_describe_allowed('emotions', attitude, allowed)}"
+ )
+
+ return specs
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a00c66bc6334dcb7e6213d7c99bbe3bec04b0ddb
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/angry/__init__.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/angry/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5319ce02f90fdabc5101857992814fd89e222e6f
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/angry/__init__.py
@@ -0,0 +1,14 @@
+from Reachy_OpenWebUI.sub_apps.attitudes.angry.idle import IDLE
+from Reachy_OpenWebUI.sub_apps.attitudes.angry.sway import SWAY
+from Reachy_OpenWebUI.sub_apps.attitudes.angry.speech import SPEECH
+
+META = {
+ "name": "angry",
+ "label": "Angry",
+ "allowed_emotions": (
+ "contempt1", "disgusted1", "displeased1", "displeased2",
+ "frustrated1", "furious1", "impatient2", "irritated1",
+ "irritated2", "rage1", "reprimand2", "reprimand3",
+ ),
+ "allowed_dances": ("neck_recoil", "sharp_side_tilt", "grid_snap", "chicken_peck"),
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/angry/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/angry/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d9580ebb8ce426ffc6b7d034f7d13d16078f01e
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/angry/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/angry/__pycache__/idle.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/angry/__pycache__/idle.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b6c2b452e3e2c3c9ded095d9d724d59e93a12c66
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/angry/__pycache__/idle.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/angry/__pycache__/speech.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/angry/__pycache__/speech.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1961ccd4f96e9836bb6abe33cab8c9c9a478ba50
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/angry/__pycache__/speech.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/angry/__pycache__/sway.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/angry/__pycache__/sway.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..459f4bb9e6fdef9bb6f13a2435069ef3a59c2cf4
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/angry/__pycache__/sway.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/angry/idle.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/angry/idle.py
new file mode 100644
index 0000000000000000000000000000000000000000..40800fe27ebc7b379f4d57d3b154b36b785c869f
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/angry/idle.py
@@ -0,0 +1,11 @@
+IDLE = {
+ "idle_delay_s": 0.3,
+ "base_x_m": 0.008,
+ "base_z_m": -0.003,
+ "base_pitch_deg": 7.0,
+ "base_yaw_deg": -1.0,
+ "base_left_antenna_deg": -160.0,
+ "base_right_antenna_deg": 160.0,
+ "breathing_z_amplitude_m": 0.001,
+ "breathing_frequency_hz": 0.04,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/angry/speech.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/angry/speech.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f300bf1c29102a643b5923a10eae53a7a554600
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/angry/speech.py
@@ -0,0 +1,5 @@
+SPEECH = {
+ "speaking_motion_scale": 1.4,
+ "speaking_frequency_scale": 1.3,
+ "speaking_pitch_offset_deg": -3.0,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/angry/sway.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/angry/sway.py
new file mode 100644
index 0000000000000000000000000000000000000000..04da130a819c3a891658bb355ad5e4dc58699af7
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/angry/sway.py
@@ -0,0 +1,11 @@
+SWAY = {
+ "antenna_sway_deg": 3.0,
+ "antenna_frequency_hz": 0.15,
+ "x_sway_m": 0.0008,
+ "roll_sway_deg": 0.3,
+ "pitch_sway_deg": 0.4,
+ "yaw_sway_deg": 0.6,
+ "head_sway_frequency_hz": 0.08,
+ "body_yaw_sway_deg": 0.3,
+ "body_yaw_frequency_hz": 0.012,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/attentive/__init__.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/attentive/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e0f1281fac350fa65ef9b4811ed7c44af27de07
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/attentive/__init__.py
@@ -0,0 +1,13 @@
+from Reachy_OpenWebUI.sub_apps.attitudes.attentive.idle import IDLE
+from Reachy_OpenWebUI.sub_apps.attitudes.attentive.sway import SWAY
+from Reachy_OpenWebUI.sub_apps.attitudes.attentive.speech import SPEECH
+
+META = {
+ "name": "attentive",
+ "label": "Attentive",
+ "allowed_emotions": (
+ "attentive1", "attentive2", "helpful2", "inquiring1",
+ "thoughtful1", "understanding2", "yes1", "no1",
+ ),
+ "allowed_dances": ("simple_nod", "uh_huh_tilt", "chin_lead", "side_glance_flick"),
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/attentive/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/attentive/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e9a52c2d56c93053271a01da1220a6cc6d16e32d
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/attentive/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/attentive/__pycache__/idle.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/attentive/__pycache__/idle.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..149f7b9566a52e2f3bd6377e5de337409289820c
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/attentive/__pycache__/idle.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/attentive/__pycache__/speech.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/attentive/__pycache__/speech.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d109b3fc5c839766a74428830eba5816ba1d1f14
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/attentive/__pycache__/speech.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/attentive/__pycache__/sway.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/attentive/__pycache__/sway.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0f7fe9b5303cf978eef51950262078e31f3c05d4
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/attentive/__pycache__/sway.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/attentive/idle.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/attentive/idle.py
new file mode 100644
index 0000000000000000000000000000000000000000..431b50dd6850271030e06fe0fe9b7361ee6f270b
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/attentive/idle.py
@@ -0,0 +1,10 @@
+IDLE = {
+ "idle_delay_s": 0.5,
+ "base_x_m": 0.006,
+ "base_z_m": 0.002,
+ "base_pitch_deg": -5.0,
+ "base_left_antenna_deg": 10.0,
+ "base_right_antenna_deg": 10.0,
+ "breathing_z_amplitude_m": 0.003,
+ "breathing_frequency_hz": 0.08,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/attentive/speech.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/attentive/speech.py
new file mode 100644
index 0000000000000000000000000000000000000000..f82d438cfc38d6143178926b129706276744ad44
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/attentive/speech.py
@@ -0,0 +1,3 @@
+SPEECH = {
+ "speaking_motion_scale": 0.9,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/attentive/sway.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/attentive/sway.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d153c2dfa28a07fd67e5e9e261237715daa3204
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/attentive/sway.py
@@ -0,0 +1,7 @@
+SWAY = {
+ "antenna_sway_deg": 5.0,
+ "antenna_frequency_hz": 0.2,
+ "pitch_sway_deg": 0.6,
+ "yaw_sway_deg": 0.8,
+ "head_sway_frequency_hz": 0.03,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/calm/__init__.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/calm/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3bfaaac0a7211acf3014e14b715ea5a0112d3f83
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/calm/__init__.py
@@ -0,0 +1,19 @@
+from Reachy_OpenWebUI.sub_apps.attitudes.calm.idle import IDLE
+from Reachy_OpenWebUI.sub_apps.attitudes.calm.sway import SWAY
+from Reachy_OpenWebUI.sub_apps.attitudes.calm.speech import SPEECH
+
+META = {
+ "name": "calm",
+ "label": "Calm",
+ "allowed_emotions": (
+ "attentive1",
+ "calming1",
+ "helpful1",
+ "thoughtful1",
+ "understanding1",
+ "welcoming1",
+ "yes1",
+ "no1",
+ ),
+ "allowed_dances": ("simple_nod", "yeah_nod", "uh_huh_tilt", "side_to_side_sway"),
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/calm/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/calm/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..13bde2d0bfb995a14ea2e6d438807bba06baef2b
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/calm/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/calm/__pycache__/idle.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/calm/__pycache__/idle.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..33b1d34f2d60111aa410ae1e1fdfe77ec051baa0
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/calm/__pycache__/idle.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/calm/__pycache__/speech.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/calm/__pycache__/speech.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f5d683f492b4f46f919b88628fcce161378b7c61
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/calm/__pycache__/speech.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/calm/__pycache__/sway.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/calm/__pycache__/sway.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..af5ecfa47cb5d02a2825e48b1cfde3ffb0b05f3d
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/calm/__pycache__/sway.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/calm/idle.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/calm/idle.py
new file mode 100644
index 0000000000000000000000000000000000000000..6f8c33511e22b61f5c5c740ee49bfad7f08251a6
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/calm/idle.py
@@ -0,0 +1,9 @@
+IDLE = {
+ "idle_delay_s": 0.3,
+ "base_x_m": 0.003,
+ "base_pitch_deg": -2.0,
+ "base_left_antenna_deg": 10.0,
+ "base_right_antenna_deg": 8.0,
+ "breathing_z_amplitude_m": 0.004,
+ "breathing_frequency_hz": 0.1,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/calm/speech.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/calm/speech.py
new file mode 100644
index 0000000000000000000000000000000000000000..599ca04874edd0eb1d63be8804da61e46d507788
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/calm/speech.py
@@ -0,0 +1,3 @@
+SPEECH = {
+ "speaking_motion_scale": 0.75,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/calm/sway.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/calm/sway.py
new file mode 100644
index 0000000000000000000000000000000000000000..86f0d183d48569de856b7c119b07562267b8fa6f
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/calm/sway.py
@@ -0,0 +1,7 @@
+SWAY = {
+ "antenna_sway_deg": 8.0,
+ "antenna_frequency_hz": 0.3,
+ "pitch_sway_deg": 0.5,
+ "yaw_sway_deg": 0.6,
+ "head_sway_frequency_hz": 0.035,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/curious/__init__.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/curious/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c65f5e906b17a1ebeea8288a4ba721ca1fa584aa
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/curious/__init__.py
@@ -0,0 +1,13 @@
+from Reachy_OpenWebUI.sub_apps.attitudes.curious.idle import IDLE
+from Reachy_OpenWebUI.sub_apps.attitudes.curious.sway import SWAY
+from Reachy_OpenWebUI.sub_apps.attitudes.curious.speech import SPEECH
+
+META = {
+ "name": "curious",
+ "label": "Curious",
+ "allowed_emotions": (
+ "amazed1", "confused1", "curious1", "inquiring1",
+ "inquiring2", "inquiring3", "oops1", "surprised1",
+ ),
+ "allowed_dances": ("side_peekaboo", "head_tilt_roll", "side_glance_flick", "chicken_peck", "chin_lead"),
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/curious/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/curious/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..262eb2f65f956a84afd64cf73bc3de6976eb1a64
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/curious/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/curious/__pycache__/idle.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/curious/__pycache__/idle.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3d63ea7ec8c233504fc25cf3f5dda07b2f5a27f6
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/curious/__pycache__/idle.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/curious/__pycache__/speech.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/curious/__pycache__/speech.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..269303d7a91993d151d134da13b266fc23f82791
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/curious/__pycache__/speech.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/curious/__pycache__/sway.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/curious/__pycache__/sway.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..61bbefba98de93d686f76df197b807d78aa8e439
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/curious/__pycache__/sway.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/curious/idle.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/curious/idle.py
new file mode 100644
index 0000000000000000000000000000000000000000..5639fff9ec562d4c1681e7eab17bab908da16ecd
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/curious/idle.py
@@ -0,0 +1,11 @@
+IDLE = {
+ "idle_delay_s": 0.35,
+ "base_x_m": 0.004,
+ "base_roll_deg": 5.0,
+ "base_pitch_deg": -3.0,
+ "base_yaw_deg": 6.0,
+ "base_left_antenna_deg": 5.0,
+ "base_right_antenna_deg": 18.0,
+ "breathing_z_amplitude_m": 0.004,
+ "breathing_frequency_hz": 0.1,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/curious/speech.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/curious/speech.py
new file mode 100644
index 0000000000000000000000000000000000000000..0354f33d299584a0ef53c17dc029e04486d227dc
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/curious/speech.py
@@ -0,0 +1,3 @@
+SPEECH = {
+ "speaking_motion_scale": 1.1,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/curious/sway.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/curious/sway.py
new file mode 100644
index 0000000000000000000000000000000000000000..e562d60e793d215afa73d3702130915813fe13a8
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/curious/sway.py
@@ -0,0 +1,10 @@
+SWAY = {
+ "antenna_sway_deg": 10.0,
+ "antenna_frequency_hz": 0.3,
+ "x_sway_m": 0.002,
+ "y_sway_m": 0.001,
+ "roll_sway_deg": 1.0,
+ "pitch_sway_deg": 1.2,
+ "yaw_sway_deg": 2.5,
+ "head_sway_frequency_hz": 0.06,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/flirty/__init__.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/flirty/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c51fe997788e8c36a0f04da059e91263d5b640a2
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/flirty/__init__.py
@@ -0,0 +1,10 @@
+from Reachy_OpenWebUI.sub_apps.attitudes.flirty.idle import IDLE
+from Reachy_OpenWebUI.sub_apps.attitudes.flirty.sway import SWAY
+from Reachy_OpenWebUI.sub_apps.attitudes.flirty.speech import SPEECH
+
+META = {
+ "name": "flirty",
+ "label": "Flirty",
+ "allowed_emotions": ("shy1", "loving1", "welcoming2", "laughing2", "thoughtful2", "proud1", "grateful1"),
+ "allowed_dances": ("groovy_sway_and_roll", "side_peekaboo", "head_tilt_roll", "side_to_side_sway", "chin_lead"),
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/flirty/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/flirty/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e3c9ad8ef582c1fcd8b508a328ea70ffc314a522
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/flirty/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/flirty/__pycache__/idle.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/flirty/__pycache__/idle.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6f0f9e17ba06e843892b7b687f74d3c038a716df
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/flirty/__pycache__/idle.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/flirty/__pycache__/speech.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/flirty/__pycache__/speech.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..db23fb222714be78974ec199a3a577160c31c7c5
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/flirty/__pycache__/speech.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/flirty/__pycache__/sway.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/flirty/__pycache__/sway.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ec192be2e088e6fa4d8021c808d1ce910bb81578
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/flirty/__pycache__/sway.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/flirty/idle.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/flirty/idle.py
new file mode 100644
index 0000000000000000000000000000000000000000..93ad6a235643d3cc1311640744022f17f4c10f33
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/flirty/idle.py
@@ -0,0 +1,11 @@
+IDLE = {
+ "idle_delay_s": 0.35,
+ "base_y_m": 0.003,
+ "base_roll_deg": 8.0,
+ "base_pitch_deg": -3.0,
+ "base_yaw_deg": 5.0,
+ "base_left_antenna_deg": -25.0,
+ "base_right_antenna_deg": 25.0,
+ "breathing_z_amplitude_m": 0.004,
+ "breathing_frequency_hz": 0.08,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/flirty/speech.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/flirty/speech.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb2d8798f64802c8d0e349eb913ccf4a28ffb801
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/flirty/speech.py
@@ -0,0 +1,3 @@
+SPEECH = {
+ "speaking_motion_scale": 1.05,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/flirty/sway.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/flirty/sway.py
new file mode 100644
index 0000000000000000000000000000000000000000..48294bbf3dc9462604a1afa02f3139787d20dda0
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/flirty/sway.py
@@ -0,0 +1,11 @@
+SWAY = {
+ "antenna_sway_deg": 30.0,
+ "antenna_frequency_hz": 0.25,
+ "y_sway_m": 0.002,
+ "roll_sway_deg": 1.5,
+ "pitch_sway_deg": 0.8,
+ "yaw_sway_deg": 2.0,
+ "head_sway_frequency_hz": 0.04,
+ "body_yaw_sway_deg": 1.0,
+ "body_yaw_frequency_hz": 0.03,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/restless/__init__.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/restless/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..78278a097faf8e54b40786326aae858031d6bc3f
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/restless/__init__.py
@@ -0,0 +1,16 @@
+from Reachy_OpenWebUI.sub_apps.attitudes.restless.idle import IDLE
+from Reachy_OpenWebUI.sub_apps.attitudes.restless.sway import SWAY
+from Reachy_OpenWebUI.sub_apps.attitudes.restless.speech import SPEECH
+
+META = {
+ "name": "restless",
+ "label": "Restless",
+ "allowed_emotions": (
+ "confused1", "impatient1", "impatient2", "irritated1",
+ "oops2", "surprised2", "uncertain1", "enthusiastic1",
+ ),
+ "allowed_dances": (
+ "chicken_peck", "neck_recoil", "sharp_side_tilt",
+ "grid_snap", "dizzy_spin", "stumble_and_recover",
+ ),
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/restless/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/restless/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7dc063889601c76165ff0eaeec2a744b6e0a08cf
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/restless/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/restless/__pycache__/idle.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/restless/__pycache__/idle.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c108fe79c8e1f8826c3a136a20224e18c2ac12d1
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/restless/__pycache__/idle.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/restless/__pycache__/speech.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/restless/__pycache__/speech.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8369c620f225edda399fc219af90e6bb3ea900fd
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/restless/__pycache__/speech.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/restless/__pycache__/sway.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/restless/__pycache__/sway.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..686a6800c5992564e69da8078b69f8c5194de589
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/restless/__pycache__/sway.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/restless/idle.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/restless/idle.py
new file mode 100644
index 0000000000000000000000000000000000000000..ebff577060362722956fc79351e5673e14bf830a
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/restless/idle.py
@@ -0,0 +1,13 @@
+IDLE = {
+ "idle_delay_s": 0.2,
+ "interpolation_s": 0.8,
+ "base_x_m": 0.003,
+ "base_y_m": 0.001,
+ "base_roll_deg": -1.5,
+ "base_pitch_deg": -1.0,
+ "base_yaw_deg": -3.0,
+ "base_left_antenna_deg": -15.0,
+ "base_right_antenna_deg": 10.0,
+ "breathing_z_amplitude_m": 0.006,
+ "breathing_frequency_hz": 0.14,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/restless/speech.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/restless/speech.py
new file mode 100644
index 0000000000000000000000000000000000000000..636bfc8b4af1a2575c1feb7ac4001eb6db45c22b
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/restless/speech.py
@@ -0,0 +1,4 @@
+SPEECH = {
+ "speaking_motion_scale": 1.2,
+ "speaking_frequency_scale": 1.15,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/restless/sway.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/restless/sway.py
new file mode 100644
index 0000000000000000000000000000000000000000..caba3973385e5c72e66427b366804a4a7391d748
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/restless/sway.py
@@ -0,0 +1,12 @@
+SWAY = {
+ "antenna_sway_deg": 12.0,
+ "antenna_frequency_hz": 0.4,
+ "x_sway_m": 0.003,
+ "y_sway_m": 0.002,
+ "roll_sway_deg": 1.5,
+ "pitch_sway_deg": 2.0,
+ "yaw_sway_deg": 4.0,
+ "head_sway_frequency_hz": 0.09,
+ "body_yaw_sway_deg": 1.5,
+ "body_yaw_frequency_hz": 0.05,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/serious/__init__.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/serious/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3caa08c83aa3ff8ada602e389a6625aa6e9907f5
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/serious/__init__.py
@@ -0,0 +1,13 @@
+from Reachy_OpenWebUI.sub_apps.attitudes.serious.idle import IDLE
+from Reachy_OpenWebUI.sub_apps.attitudes.serious.sway import SWAY
+from Reachy_OpenWebUI.sub_apps.attitudes.serious.speech import SPEECH
+
+META = {
+ "name": "serious",
+ "label": "Serious",
+ "allowed_emotions": (
+ "attentive1", "inquiring1", "reprimand1", "thoughtful1",
+ "understanding2", "yes1", "no1",
+ ),
+ "allowed_dances": ("simple_nod", "uh_huh_tilt", "side_glance_flick", "chin_lead"),
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/serious/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/serious/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4d9d41639aafb75409012fc6c1d33c90e7968ba1
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/serious/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/serious/__pycache__/idle.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/serious/__pycache__/idle.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3c8af429ebe6def8cde7b756a83ea3b98f7751f2
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/serious/__pycache__/idle.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/serious/__pycache__/speech.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/serious/__pycache__/speech.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e140ffe858216960ea71729097bfed6907c4c19c
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/serious/__pycache__/speech.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/serious/__pycache__/sway.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/serious/__pycache__/sway.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1908e2eae374692476b2fb55474ce8a7f22e1d65
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/serious/__pycache__/sway.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/serious/idle.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/serious/idle.py
new file mode 100644
index 0000000000000000000000000000000000000000..e74f8e5d1ddb27f2dbe66aaeb412cee2d48564a5
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/serious/idle.py
@@ -0,0 +1,10 @@
+IDLE = {
+ "idle_delay_s": 0.8,
+ "interpolation_s": 1.2,
+ "base_x_m": -0.003,
+ "base_pitch_deg": 4.0,
+ "base_left_antenna_deg": -86.0,
+ "base_right_antenna_deg": 86.0,
+ "breathing_z_amplitude_m": 0.0015,
+ "breathing_frequency_hz": 0.05,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/serious/speech.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/serious/speech.py
new file mode 100644
index 0000000000000000000000000000000000000000..9b3773751455036efe03a6b0075d73f5171b4cce
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/serious/speech.py
@@ -0,0 +1,4 @@
+SPEECH = {
+ "speaking_motion_scale": 0.45,
+ "speaking_frequency_scale": 0.85,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/serious/sway.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/serious/sway.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff4a54bb3f9baebfcc7be2276d35ebc677d08aa2
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/serious/sway.py
@@ -0,0 +1,7 @@
+SWAY = {
+ "antenna_sway_deg": 2.0,
+ "antenna_frequency_hz": 0.08,
+ "pitch_sway_deg": 0.15,
+ "yaw_sway_deg": 0.3,
+ "head_sway_frequency_hz": 0.015,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/shy/__init__.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/shy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9cd1624d3a4d06092760424d3ff90c3e5aa475aa
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/shy/__init__.py
@@ -0,0 +1,13 @@
+from Reachy_OpenWebUI.sub_apps.attitudes.shy.idle import IDLE
+from Reachy_OpenWebUI.sub_apps.attitudes.shy.sway import SWAY
+from Reachy_OpenWebUI.sub_apps.attitudes.shy.speech import SPEECH
+
+META = {
+ "name": "shy",
+ "label": "Shy",
+ "allowed_emotions": (
+ "shy1", "uncomfortable1", "grateful1", "serenity1",
+ "loving1", "thoughtful2", "yes_sad1", "oops1",
+ ),
+ "allowed_dances": ("simple_nod", "side_to_side_sway", "uh_huh_tilt"),
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/shy/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/shy/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ace7472a5a6200e7192921e43c062a4bbe2de87e
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/shy/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/shy/__pycache__/idle.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/shy/__pycache__/idle.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5962da87c5cac94d6f9bb393e12011a80c004b43
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/shy/__pycache__/idle.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/shy/__pycache__/speech.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/shy/__pycache__/speech.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1be8cbf9655a4c5f4bfed2444eb3fe46748e13af
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/shy/__pycache__/speech.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/shy/__pycache__/sway.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/shy/__pycache__/sway.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..32c7c0d46d4bedf8118b3d1603b9940b16fb78cb
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/shy/__pycache__/sway.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/shy/idle.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/shy/idle.py
new file mode 100644
index 0000000000000000000000000000000000000000..213d57020e8f11fda5b36585d7250edde51f0144
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/shy/idle.py
@@ -0,0 +1,13 @@
+IDLE = {
+ "idle_delay_s": 0.6,
+ "interpolation_s": 1.3,
+ "base_x_m": -0.003,
+ "base_z_m": -0.05,
+ "base_roll_deg": 3.0,
+ "base_pitch_deg": 5.0,
+ "base_yaw_deg": 7.0,
+ "base_left_antenna_deg": -120.0,
+ "base_right_antenna_deg": 120.0,
+ "breathing_z_amplitude_m": 0.002,
+ "breathing_frequency_hz": 0.07,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/shy/speech.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/shy/speech.py
new file mode 100644
index 0000000000000000000000000000000000000000..f69c5818db7700ab8173be0cc2b7cc0a5d2cc68f
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/shy/speech.py
@@ -0,0 +1,6 @@
+SPEECH = {
+ "speaking_motion_scale": 0.4,
+ "speaking_frequency_scale": 0.7,
+ "speaking_pitch_offset_deg": -2.0,
+ "speaking_z_offset_m": 0.015,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/shy/sway.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/shy/sway.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e8cef913a21de4f09c25ce2cccff447963999b6
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/shy/sway.py
@@ -0,0 +1,9 @@
+SWAY = {
+ "antenna_sway_deg": 3.0,
+ "antenna_frequency_hz": 0.15,
+ "y_sway_m": 0.001,
+ "roll_sway_deg": 0.4,
+ "pitch_sway_deg": 0.5,
+ "yaw_sway_deg": 0.6,
+ "head_sway_frequency_hz": 0.025,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/silly/__init__.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/silly/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ce2b0328d4f5e6ad880b38ba72958f28df7eec5
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/silly/__init__.py
@@ -0,0 +1,17 @@
+from Reachy_OpenWebUI.sub_apps.attitudes.silly.idle import IDLE
+from Reachy_OpenWebUI.sub_apps.attitudes.silly.sway import SWAY
+from Reachy_OpenWebUI.sub_apps.attitudes.silly.speech import SPEECH
+
+META = {
+ "name": "silly",
+ "label": "Silly",
+ "allowed_emotions": (
+ "amazed1", "curious1", "dance1", "dance2", "dance3",
+ "indifferent1", "laughing2", "oops1", "proud2",
+ ),
+ "allowed_dances": (
+ "chicken_peck", "dizzy_spin", "groovy_sway_and_roll",
+ "jackson_square", "polyrhythm_combo", "side_peekaboo",
+ "stumble_and_recover",
+ ),
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/silly/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/silly/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c6b39b8e1de10d6421e169b84bfca5c812d46521
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/silly/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/silly/__pycache__/idle.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/silly/__pycache__/idle.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2bcb19ae93e284e8543b23c32c217fc1aa286122
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/silly/__pycache__/idle.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/silly/__pycache__/speech.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/silly/__pycache__/speech.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9450180bac1688e382328c517513d3f49189009e
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/silly/__pycache__/speech.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/silly/__pycache__/sway.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/silly/__pycache__/sway.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..939dfcc0055c90ca45bce26755b19db127d93765
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/silly/__pycache__/sway.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/silly/idle.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/silly/idle.py
new file mode 100644
index 0000000000000000000000000000000000000000..a640f785a75171028348b8c21bc8578391b8e5c3
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/silly/idle.py
@@ -0,0 +1,13 @@
+IDLE = {
+ "idle_delay_s": 0.15,
+ "interpolation_s": 0.8,
+ "base_z_m": 0.003,
+ "base_roll_deg": 6.0,
+ "base_pitch_deg": -4.0,
+ "base_yaw_deg": -6.0,
+ "base_body_yaw_deg": -1.5,
+ "base_left_antenna_deg": 5.0,
+ "base_right_antenna_deg": 0.0,
+ "breathing_z_amplitude_m": 0.007,
+ "breathing_frequency_hz": 0.15,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/silly/speech.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/silly/speech.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e54d611de59cb6ce5ba9c95324e5bd295b292e2
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/silly/speech.py
@@ -0,0 +1,4 @@
+SPEECH = {
+ "speaking_motion_scale": 1.4,
+ "speaking_frequency_scale": 1.2,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/silly/sway.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/silly/sway.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c6f9b65790cd54aa10116e6a4dce972fdbb2987
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/silly/sway.py
@@ -0,0 +1,13 @@
+SWAY = {
+ "antenna_sway_deg": 140.0,
+ "antenna_sway_sync": True,
+ "antenna_frequency_hz": 0.2,
+ "x_sway_m": 0.004,
+ "y_sway_m": 0.003,
+ "roll_sway_deg": 2.5,
+ "pitch_sway_deg": 2.8,
+ "yaw_sway_deg": 5.0,
+ "head_sway_frequency_hz": 0.1,
+ "body_yaw_sway_deg": 2.0,
+ "body_yaw_frequency_hz": 0.06,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/spaceshot/__init__.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/spaceshot/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..05d8c8b36b74b6e78f641eae6048492e8d065adf
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/spaceshot/__init__.py
@@ -0,0 +1,13 @@
+from Reachy_OpenWebUI.sub_apps.attitudes.spaceshot.idle import IDLE
+from Reachy_OpenWebUI.sub_apps.attitudes.spaceshot.sway import SWAY
+from Reachy_OpenWebUI.sub_apps.attitudes.spaceshot.speech import SPEECH
+
+META = {
+ "name": "spaceshot",
+ "label": "Spaceshot",
+ "allowed_emotions": (
+ "amazed1", "confused1", "curious1", "incomprehensible2",
+ "indifferent1", "inquiring3", "lost1",
+ ),
+ "allowed_dances": ("dizzy_spin", "interwoven_spirals", "pendulum_swing", "polyrhythm_combo", "side_peekaboo"),
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/spaceshot/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/spaceshot/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..34a21fcc083914b81ffe67c3f6e74b1a5e8bcbb5
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/spaceshot/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/spaceshot/__pycache__/idle.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/spaceshot/__pycache__/idle.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f7886d55c35fe37da5d468902fb9be2c9bee3c14
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/spaceshot/__pycache__/idle.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/spaceshot/__pycache__/speech.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/spaceshot/__pycache__/speech.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a23420745dd3ce99d63615599d8dbd55b771fce3
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/spaceshot/__pycache__/speech.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/spaceshot/__pycache__/sway.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/spaceshot/__pycache__/sway.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a2ee5b308ffe1fc727bcc7a59ee5b94e1eded7a8
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/spaceshot/__pycache__/sway.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/spaceshot/idle.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/spaceshot/idle.py
new file mode 100644
index 0000000000000000000000000000000000000000..020f89b00ada85948270c4f7200a1f9475023f44
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/spaceshot/idle.py
@@ -0,0 +1,14 @@
+IDLE = {
+ "idle_delay_s": 0.25,
+ "interpolation_s": 1.2,
+ "base_x_m": -0.004,
+ "base_z_m": 0.003,
+ "base_roll_deg": -3.0,
+ "base_pitch_deg": -15.0,
+ "base_yaw_deg": 3.0,
+ "base_body_yaw_deg": -1.0,
+ "base_left_antenna_deg": 6.0,
+ "base_right_antenna_deg": 6.0,
+ "breathing_z_amplitude_m": 0.005,
+ "breathing_frequency_hz": 0.06,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/spaceshot/speech.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/spaceshot/speech.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8902d59751b33f6ff544159134630ad159162a6
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/spaceshot/speech.py
@@ -0,0 +1,4 @@
+SPEECH = {
+ "speaking_motion_scale": 0.7,
+ "speaking_frequency_scale": 0.8,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/spaceshot/sway.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/spaceshot/sway.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e6f65a5376e737c4f5adafcceeb6e209a72f4e4
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/spaceshot/sway.py
@@ -0,0 +1,12 @@
+SWAY = {
+ "antenna_sway_deg": 8.0,
+ "antenna_frequency_hz": 0.12,
+ "x_sway_m": 0.002,
+ "y_sway_m": 0.003,
+ "roll_sway_deg": 2.5,
+ "pitch_sway_deg": 1.5,
+ "yaw_sway_deg": 4.0,
+ "head_sway_frequency_hz": 0.025,
+ "body_yaw_sway_deg": 1.5,
+ "body_yaw_frequency_hz": 0.02,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/still/__init__.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/still/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d052082afefba00da0dc668f1d1ca874147693e
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/still/__init__.py
@@ -0,0 +1,9 @@
+from Reachy_OpenWebUI.sub_apps.attitudes.still.idle import IDLE
+from Reachy_OpenWebUI.sub_apps.attitudes.still.sway import SWAY
+from Reachy_OpenWebUI.sub_apps.attitudes.still.speech import SPEECH
+
+META = {
+ "name": "still",
+ "label": "Still",
+ "enabled": False,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/still/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/still/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..342fc9aa656592d9f1de5a8ac435e0952e8297ae
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/still/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/still/__pycache__/idle.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/still/__pycache__/idle.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9c90a1620991297bdeb5270c11010438e44e4546
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/still/__pycache__/idle.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/still/__pycache__/speech.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/still/__pycache__/speech.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c026902de61a1be325ff2140dbe717c71a2237e3
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/still/__pycache__/speech.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/still/__pycache__/sway.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/still/__pycache__/sway.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..df4fd58e293b6b8f90dfde53915d6fb09bc34c98
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/still/__pycache__/sway.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/still/idle.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/still/idle.py
new file mode 100644
index 0000000000000000000000000000000000000000..3786c87edfece79681b484441f9711ed17276205
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/still/idle.py
@@ -0,0 +1,3 @@
+IDLE = {
+ "idle_delay_s": 9999.0,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/still/speech.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/still/speech.py
new file mode 100644
index 0000000000000000000000000000000000000000..ca841e3b1ad40282e9cf26f7f79af59901c8d69c
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/still/speech.py
@@ -0,0 +1,3 @@
+SPEECH = {
+ "speaking_motion_scale": 0.0,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/still/sway.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/still/sway.py
new file mode 100644
index 0000000000000000000000000000000000000000..450c183abb4b05a526dea6451cf3c4f726697d39
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/still/sway.py
@@ -0,0 +1 @@
+SWAY = {}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/tough/__init__.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/tough/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1891236b3f08a5ba7e561dfebca9111facaa26f6
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/tough/__init__.py
@@ -0,0 +1,14 @@
+from Reachy_OpenWebUI.sub_apps.attitudes.tough.idle import IDLE
+from Reachy_OpenWebUI.sub_apps.attitudes.tough.sway import SWAY
+from Reachy_OpenWebUI.sub_apps.attitudes.tough.speech import SPEECH
+
+META = {
+ "name": "tough",
+ "label": "Tough",
+ "allowed_emotions": (
+ "contempt1", "displeased1", "displeased2", "frustrated1",
+ "go_away1", "impatient1", "impatient2", "irritated1",
+ "irritated2", "reprimand2",
+ ),
+ "allowed_dances": ("chicken_peck", "neck_recoil", "sharp_side_tilt", "grid_snap", "chin_lead"),
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/tough/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/tough/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a66f042df16a0243eaa3fe56cbf9c92299d4de39
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/tough/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/tough/__pycache__/idle.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/tough/__pycache__/idle.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..083314c3fb25fb3e2f0a032df4e7c869e095e2ea
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/tough/__pycache__/idle.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/tough/__pycache__/speech.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/tough/__pycache__/speech.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..692c8b3bc0ebbdb10d89ec0664cacfc4ac8f8776
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/tough/__pycache__/speech.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/tough/__pycache__/sway.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/attitudes/tough/__pycache__/sway.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a688b845e884d0d22e9ccd869f314e339855fd8b
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/attitudes/tough/__pycache__/sway.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/tough/idle.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/tough/idle.py
new file mode 100644
index 0000000000000000000000000000000000000000..45e0f6c6f57d891f97658b34a91255557ca828df
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/tough/idle.py
@@ -0,0 +1,13 @@
+IDLE = {
+ "idle_delay_s": 0.5,
+ "interpolation_s": 1.2,
+ "base_x_m": -0.002,
+ "base_z_m": 0.003,
+ "base_pitch_deg": -2.0,
+ "base_yaw_deg": -3.0,
+ "base_body_yaw_deg": 1.5,
+ "base_left_antenna_deg": -160.0,
+ "base_right_antenna_deg": 160.0,
+ "breathing_z_amplitude_m": 0.0015,
+ "breathing_frequency_hz": 0.04,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/tough/speech.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/tough/speech.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9046a32b680725a68bc395adf85ee6fe61fae80
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/tough/speech.py
@@ -0,0 +1,4 @@
+SPEECH = {
+ "speaking_motion_scale": 0.65,
+ "speaking_frequency_scale": 0.9,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/attitudes/tough/sway.py b/src/Reachy_OpenWebUI/sub_apps/attitudes/tough/sway.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6eb58cd3649d695445739c3822b7a963a772907
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/attitudes/tough/sway.py
@@ -0,0 +1,10 @@
+SWAY = {
+ "antenna_sway_deg": 2.5,
+ "antenna_frequency_hz": 0.1,
+ "roll_sway_deg": 0.3,
+ "pitch_sway_deg": 0.35,
+ "yaw_sway_deg": 0.8,
+ "head_sway_frequency_hz": 0.02,
+ "body_yaw_sway_deg": 0.4,
+ "body_yaw_frequency_hz": 0.015,
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/conversation_app/__init__.py b/src/Reachy_OpenWebUI/sub_apps/conversation_app/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..14f7cadda25d248159f48e8c2ce2fd383503187d
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/conversation_app/__init__.py
@@ -0,0 +1 @@
+"""Base conversation app support modules."""
diff --git a/src/Reachy_OpenWebUI/sub_apps/conversation_app/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/conversation_app/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d6543369a1d6fcf24f6e9a61e1ba2b7d7b06161c
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/conversation_app/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/conversation_app/__pycache__/chat_history.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/conversation_app/__pycache__/chat_history.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..32f8a761b0e6171d3047eacee0d1c4510392dcd2
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/conversation_app/__pycache__/chat_history.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/conversation_app/__pycache__/vad.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/conversation_app/__pycache__/vad.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..22c9c3f6ca199e4974b9921e0cb0d74792fa1266
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/conversation_app/__pycache__/vad.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/conversation_app/chat_history.py b/src/Reachy_OpenWebUI/sub_apps/conversation_app/chat_history.py
new file mode 100644
index 0000000000000000000000000000000000000000..50fba93f8885f5e83fa255189fc2f92bcd4b2355
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/conversation_app/chat_history.py
@@ -0,0 +1,55 @@
+from __future__ import annotations
+
+import json
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+
+CHAT_HISTORY_PATH = Path.home() / ".config" / "settings" / "openwebui_chat_history.json"
+
+
+def _timestamp() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def _read_history() -> dict[str, Any]:
+ try:
+ if CHAT_HISTORY_PATH.exists():
+ data = json.loads(CHAT_HISTORY_PATH.read_text(encoding="utf-8"))
+ if isinstance(data, dict):
+ events = data.get("events")
+ if isinstance(events, list):
+ return {"events": events}
+ except Exception:
+ pass
+ return {"events": []}
+
+
+def append_chat_history(event: str, **details: Any) -> None:
+ history = _read_history()
+ clean_details = {key: value for key, value in details.items() if value not in (None, "")}
+ history["events"].append(
+ {
+ "timestamp": _timestamp(),
+ "event": event,
+ **clean_details,
+ }
+ )
+ CHAT_HISTORY_PATH.parent.mkdir(parents=True, exist_ok=True)
+ CHAT_HISTORY_PATH.write_text(json.dumps(history, indent=2) + "\n", encoding="utf-8")
+
+
+def clear_chat_history(**details: Any) -> None:
+ clean_details = {key: value for key, value in details.items() if value not in (None, "")}
+ history = {
+ "events": [
+ {
+ "timestamp": _timestamp(),
+ "event": "call_cache_cleared",
+ **clean_details,
+ }
+ ]
+ }
+ CHAT_HISTORY_PATH.parent.mkdir(parents=True, exist_ok=True)
+ CHAT_HISTORY_PATH.write_text(json.dumps(history, indent=2) + "\n", encoding="utf-8")
diff --git a/src/Reachy_OpenWebUI/sub_apps/conversation_app/local/__init__.py b/src/Reachy_OpenWebUI/sub_apps/conversation_app/local/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a71d71ace7f89bf98441649ea86a373d2c75b8e
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/conversation_app/local/__init__.py
@@ -0,0 +1 @@
+"""OpenWebUI conversation pipeline helpers."""
diff --git a/src/Reachy_OpenWebUI/sub_apps/conversation_app/local/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/conversation_app/local/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c040e61982f0b43e10242ebf1d154219e8735e65
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/conversation_app/local/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/conversation_app/local/__pycache__/handler.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/conversation_app/local/__pycache__/handler.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..54cb27a946b44354192fd3e3f1b6aced20c35c54
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/conversation_app/local/__pycache__/handler.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/conversation_app/local/__pycache__/llm.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/conversation_app/local/__pycache__/llm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..815833a767e0bde5a3623d718930f107ba910179
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/conversation_app/local/__pycache__/llm.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/conversation_app/local/__pycache__/tts.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/conversation_app/local/__pycache__/tts.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c10d3b48144c37867e85395e5ea000428a5d3528
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/conversation_app/local/__pycache__/tts.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/conversation_app/local/handler.py b/src/Reachy_OpenWebUI/sub_apps/conversation_app/local/handler.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b4ee357466a95ea748c063b57e3355d273a6f0a
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/conversation_app/local/handler.py
@@ -0,0 +1,1398 @@
+from __future__ import annotations
+import html
+import io
+import re
+import json
+import time
+import asyncio
+import logging
+import wave
+from typing import TYPE_CHECKING, Tuple, Optional
+from collections import deque
+
+import httpx
+import numpy as np
+from fastrtc import AdditionalOutputs, AsyncStreamHandler, wait_for_item
+from scipy.signal import resample
+
+from Reachy_OpenWebUI.config import config
+from Reachy_OpenWebUI.sub_apps.conversation_app.local.llm import OpenWebUIClient
+from Reachy_OpenWebUI.tools.core_tools import ToolDependencies, get_tool_specs, dispatch_tool_call
+
+COOKAIWARE_PROFILE = "cookaiware"
+
+
+if TYPE_CHECKING:
+ from Reachy_OpenWebUI.sub_apps.conversation_app.local.tts import OpenWebUISpeech
+ from Reachy_OpenWebUI.sub_apps.conversation_app.vad import SileroVAD
+
+
+logger = logging.getLogger(__name__)
+
+
+_REASONING_DETAILS_RE = re.compile(
+ r"]*\btype=[\"']?reasoning[\"']?)[^>]*>.*?",
+ re.IGNORECASE | re.DOTALL,
+)
+_OPEN_REASONING_DETAILS_RE = re.compile(
+ r"]*\btype=[\"']?reasoning[\"']?)[^>]*>.*$",
+ re.IGNORECASE | re.DOTALL,
+)
+
+
+def _friendly_action_label(value: object) -> str:
+ label = str(value or "").strip()
+ label = label.replace("_", " ").replace("-", " ")
+ return " ".join(label.split())
+
+
+def _tool_display_label(func_name: str, args: object, result: dict[str, object]) -> str:
+ if isinstance(result, dict):
+ for key in ("move", "emotion", "name"):
+ label = _friendly_action_label(result.get(key))
+ if label:
+ return label
+
+ args_dict = args if isinstance(args, dict) else {}
+ if isinstance(args_dict, dict):
+ if func_name == "dance":
+ label = _friendly_action_label(args_dict.get("move"))
+ if label and label != "random":
+ return label
+ if func_name == "play_emotion":
+ label = _friendly_action_label(args_dict.get("emotion"))
+ if label:
+ return label
+
+ return _friendly_action_label(func_name)
+
+
+def _append_action_labels(message: str, labels: list[str]) -> str:
+ clean_labels: list[str] = []
+ seen: set[str] = set()
+ for label in labels:
+ clean = _friendly_action_label(label)
+ if clean and clean not in seen:
+ clean_labels.append(clean)
+ seen.add(clean)
+ if not clean_labels:
+ return message
+
+ suffix = " ".join(f"({label})" for label in clean_labels)
+ if message.rstrip().endswith(suffix):
+ return message
+ return f"{message.rstrip()} {suffix}"
+
+
+_IMPLIED_ACTION_CALL_RE = re.compile(
+ r"\b(?Pplay_emotion|dance)\s*\((?P[^)]*)\)",
+ re.IGNORECASE,
+)
+_IMPLIED_ACTION_QUOTED_ARG_RE = re.compile(
+ r"(?:\b(?Pemotion|move)\s*=\s*)?[\"'](?P[^\"']+)[\"']",
+ re.IGNORECASE,
+)
+_IMPLIED_ACTION_REPEAT_RE = re.compile(r"\brepeat\s*=\s*(?P\d+)", re.IGNORECASE)
+
+
+def _implied_action_calls(text: str) -> list[tuple[str, dict[str, object]]]:
+ calls: list[tuple[str, dict[str, object]]] = []
+ for match in _IMPLIED_ACTION_CALL_RE.finditer(text or ""):
+ name = match.group("name").lower()
+ raw_args = match.group("args") or ""
+ args: dict[str, object] = {}
+ quoted = _IMPLIED_ACTION_QUOTED_ARG_RE.search(raw_args)
+ if quoted:
+ value = quoted.group("value").strip()
+ if name == "play_emotion":
+ args["emotion"] = value
+ elif value:
+ args["move"] = value
+ repeat_match = _IMPLIED_ACTION_REPEAT_RE.search(raw_args)
+ if repeat_match:
+ args["repeat"] = int(repeat_match.group("repeat"))
+ calls.append((name, args))
+ return calls
+
+
+def _strip_implied_action_calls(text: str) -> str:
+ return _IMPLIED_ACTION_CALL_RE.sub("", text or "")
+
+
+def _tool_names_from_config() -> set[str]:
+ raw = (config.OPENWEBUI_ENABLED_TOOLS or "").strip()
+ if raw == "__none__":
+ return set()
+ if not raw:
+ return set()
+ return {part.strip() for part in raw.split(",") if part.strip()}
+
+
+def _configured_tool_specs() -> list[dict[str, object]]:
+ attitude = None if (config.REACHY_MINI_CUSTOM_PROFILE or "") == COOKAIWARE_PROFILE else config.REACHY_IDLE_ATTITUDE
+ specs = get_tool_specs(attitude=attitude)
+ enabled = _tool_names_from_config()
+ configured: list[dict[str, object]] = []
+ for spec in specs:
+ function = spec.get("function") if isinstance(spec, dict) else None
+ name = str(function.get("name") or "").strip() if isinstance(function, dict) else ""
+ if name in enabled:
+ configured.append(spec)
+ return configured
+
+
+def _cookaiware_tools_enabled() -> bool:
+ return bool(
+ _tool_names_from_config()
+ & {
+ "inventory_action",
+ "family_profile_action",
+ "meal_plan_action",
+ "shopping_list_action",
+ "app_settings_action",
+ }
+ )
+
+
+_THINK_BLOCK_RE = re.compile(r"]*>.*?", re.IGNORECASE | re.DOTALL)
+_HTML_TAG_RE = re.compile(r"<[^>]+>")
+
+
+def _clean_assistant_text(text: str) -> str:
+ """Remove reasoning markup and HTML wrappers before UI display or speech."""
+ clean = _REASONING_DETAILS_RE.sub("", text or "")
+ clean = _strip_implied_action_calls(clean)
+ clean = _OPEN_REASONING_DETAILS_RE.sub("", clean)
+ clean = _THINK_BLOCK_RE.sub("", clean)
+ clean = _HTML_TAG_RE.sub("", clean)
+ clean = html.unescape(clean)
+ return re.sub(r"\s+", " ", clean).strip()
+
+
+_SENTENCE_SPLIT_RE = re.compile(r"(?<=[.!?…])\s+")
+
+
+def _speakable_prefix(text: str) -> str:
+ """Return the prefix of streamed assistant text that is safe to speak now.
+
+ Complete reasoning blocks are removed; text after an unclosed reasoning tag
+ or a partial trailing HTML tag is held back until the stream closes it, so
+ the emitted prefix only ever grows.
+ """
+ clean = _REASONING_DETAILS_RE.sub("", text or "")
+ clean = _THINK_BLOCK_RE.sub("", clean)
+ lower = clean.lower()
+ for opener in ("= 0:
+ clean = clean[:idx]
+ lower = lower[:idx]
+ tag_start = clean.rfind("<")
+ if tag_start >= 0 and ">" not in clean[tag_start:]:
+ clean = clean[:tag_start]
+ return clean
+
+
+class _SentenceStreamer:
+ """Accumulate streamed tokens and emit complete sentences for TTS.
+
+ Tiny fragments merge into the next sentence; text without punctuation is
+ force-flushed once it grows past max_chars so long unpunctuated answers
+ still produce audio.
+ """
+
+ def __init__(self, min_chars: int = 12, max_chars: int = 260):
+ self.raw = ""
+ self.emitted = 0
+ self.min_chars = min_chars
+ self.max_chars = max_chars
+ self._carry = ""
+
+ def push(self, token: str) -> list[str]:
+ self.raw += token
+ speakable = _speakable_prefix(self.raw)
+ new_text = speakable[self.emitted :]
+ if not new_text:
+ return []
+ parts = _SENTENCE_SPLIT_RE.split(new_text)
+ if len(parts) <= 1:
+ if len(self._carry) + len(new_text) >= self.max_chars:
+ self.emitted += len(new_text)
+ chunk = f"{self._carry} {new_text}".strip()
+ self._carry = ""
+ return [chunk] if chunk else []
+ return []
+ consumed = len(new_text) - len(parts[-1])
+ self.emitted += consumed
+ chunks: list[str] = []
+ for sentence in parts[:-1]:
+ candidate = f"{self._carry} {sentence}".strip() if self._carry else sentence.strip()
+ if not candidate:
+ continue
+ if len(candidate) < self.min_chars:
+ self._carry = candidate
+ continue
+ self._carry = ""
+ chunks.append(candidate)
+ return chunks
+
+ def flush(self) -> list[str]:
+ remainder = _speakable_prefix(self.raw)[self.emitted :]
+ self.emitted = len(_speakable_prefix(self.raw))
+ chunk = f"{self._carry} {remainder}".strip() if self._carry else remainder.strip()
+ self._carry = ""
+ return [chunk] if chunk else []
+
+
+def _dedupe_urls(urls: list[str]) -> list[str]:
+ seen: set[str] = set()
+ clean: list[str] = []
+ for url in urls:
+ normalized = url.strip().rstrip("/")
+ if normalized and normalized not in seen:
+ seen.add(normalized)
+ clean.append(normalized)
+ return clean
+
+
+def _openwebui_audio_candidates(base_url: str, suffix: str) -> list[str]:
+ root = (base_url or "").strip().rstrip("/")
+ if not root:
+ return []
+ suffix = suffix.strip("/")
+ if root.endswith("/api"):
+ return _dedupe_urls([f"{root}/v1/{suffix}", f"{root}/{suffix}"])
+ return _dedupe_urls([
+ f"{root}/api/v1/{suffix}",
+ f"{root}/api/{suffix}",
+ f"{root}/v1/{suffix}",
+ f"{root}/{suffix}",
+ ])
+
+
+_STOP_COMMANDS = {
+ "stop",
+ "stop it",
+ "stop talking",
+ "stop speaking",
+ "quiet",
+ "be quiet",
+ "shut up",
+ "cancel",
+ "cancel that",
+ "enough",
+ "hold on",
+ "pause",
+}
+_STOP_COMMAND_PREFIXES = ("reachy ", "hey reachy ", "ok reachy ", "okay reachy ")
+
+
+def _normalize_stop_command(text: str) -> str:
+ normalized = re.sub(r"[^a-z0-9\s]", " ", text.lower())
+ normalized = re.sub(r"\s+", " ", normalized).strip()
+ for prefix in _STOP_COMMAND_PREFIXES:
+ if normalized.startswith(prefix):
+ normalized = normalized[len(prefix) :].strip()
+ break
+ return normalized
+
+
+def _is_stop_command(text: str) -> bool:
+ normalized = _normalize_stop_command(text)
+ if normalized in _STOP_COMMANDS:
+ return True
+ words = normalized.split()
+ if len(words) <= 3 and words and words[0] in {"stop", "quiet", "cancel", "pause"}:
+ return True
+ return False
+
+
+class LocalSessionHandler(AsyncStreamHandler):
+ """Reachy audio handler using OpenWebUI for transcription, chat, and speech."""
+
+ def __init__(
+ self,
+ deps: ToolDependencies,
+ llm_url: Optional[str] = None,
+ llm_model: Optional[str] = None,
+ enable_signal: bool = True,
+ ):
+ """Initialize the local session handler."""
+ super().__init__(
+ expected_layout="mono",
+ output_sample_rate=24000,
+ input_sample_rate=24000,
+ )
+ self.deps = deps
+ # Inject speech callback into dependencies so tools like 'speak' can use it
+ self.deps.speak_func = self._process_sentence
+ self.deps.handler = self
+
+ self._llm_url_override = llm_url is not None
+ self._llm_model_override = llm_model is not None
+ self.llm_url = llm_url or config.OPENWEBUI_URL
+ self.llm_model = llm_model or config.OPENWEBUI_MODEL
+ self.enable_signal = enable_signal
+
+ self.output_queue: asyncio.Queue[object] = asyncio.Queue()
+ self.audio_buffer: list[np.ndarray] = []
+ self.lookback_buffer: deque[np.ndarray] = deque(maxlen=20) # 20 * 32ms = 640ms lookback
+ self.vad_buffer = np.array([], dtype=np.float32)
+ self.upload_buffer = np.array([], dtype=np.float32)
+
+
+ self.is_speaking = False
+ self.silence_chunks = 0
+ self.speech_chunks = 0
+ self.pending_speech_chunks: list[np.ndarray] = []
+ self.pending_upload_chunks: list[np.ndarray] = []
+ self.muted = False
+ self.speaker_muted = False
+
+ # Initialize runtime pieces lazily in start_up.
+ self.vad: Optional[SileroVAD] = None
+ self.llm: Optional[OpenWebUIClient] = None
+ self.speech: Optional[OpenWebUISpeech] = None
+ self.pipeline_task: Optional[asyncio.Task[None]] = None
+ self._receive_frame_count = 0
+
+ # Echo suppression: prevent VAD from triggering on robot speaker output.
+ self._active_pipeline_count = 0
+ self._suppress_vad_until = 0.0
+ self._playback_end_mono = 0.0 # estimated monotonic time when speaker finishes
+ self._response_cancel_requested = False
+ self._stop_command_cooldown_until = 0.0
+ self._stop_command_task: Optional[asyncio.Task[None]] = None
+ self._stop_vad_buffer = np.array([], dtype=np.float32)
+ self._stop_upload_buffer = np.array([], dtype=np.float32)
+ self._stop_audio_buffer: list[np.ndarray] = []
+ self._last_user_speech_mono = 0.0
+ self._last_assistant_typing_mono = 0.0
+ self._tts_inflight_count = 0
+ self._cookaiware_language = "en"
+ self._cookaiware_unit_system = self._load_cookaiware_unit_system()
+ self._stop_is_speaking = False
+ self._stop_speech_chunks = 0
+ self._stop_silence_chunks = 0
+
+ # Tool specs cache (rebuilt in start_up with feature-based exclusions)
+ self.tool_specs = _configured_tool_specs()
+
+ def _load_cookaiware_unit_system(self) -> str:
+ if self.deps.data_dir is None:
+ return "metric"
+ try:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.app_settings import get_unit_system
+
+ return get_unit_system(self.deps.data_dir)
+ except Exception as exc:
+ logger.debug("Could not load CookAIware unit system: %s", exc)
+ return "metric"
+
+ def _load_cookaiware_language(self) -> str:
+ if self.deps.data_dir is None:
+ return "en"
+ try:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.app_settings import get_language
+
+ return get_language(self.deps.data_dir)
+ except Exception as exc:
+ logger.debug("Could not load CookAIware language: %s", exc)
+ return "en"
+
+ async def apply_language(self, language: str) -> None:
+ self._cookaiware_language = str(language or "").strip() or "en"
+
+ async def apply_unit_system(self, unit_system: str) -> None:
+ normalized = str(unit_system or "").strip().lower()
+ self._cookaiware_unit_system = normalized if normalized in {"metric", "imperial"} else "metric"
+
+ def _cookaiware_turn_context(self) -> str:
+ if not _cookaiware_tools_enabled():
+ return ""
+ self._cookaiware_language = self._load_cookaiware_language()
+ self._cookaiware_unit_system = self._load_cookaiware_unit_system()
+ return (
+ " [CookAIware context: selected language is "
+ f"{self._cookaiware_language}; selected unit system is {self._cookaiware_unit_system}. "
+ "Use these settings unless the user asks otherwise.]"
+ )
+
+ def copy(self) -> "LocalSessionHandler":
+ """Create a copy of the handler."""
+ return LocalSessionHandler(
+ self.deps,
+ self.llm_url if self._llm_url_override else None,
+ self.llm_model if self._llm_model_override else None,
+ self.enable_signal,
+ )
+
+ def set_muted(self, muted: bool) -> None:
+ self.muted = muted
+ self.vad_buffer = np.array([], dtype=np.float32)
+ self.upload_buffer = np.array([], dtype=np.float32)
+ self.lookback_buffer.clear()
+ self.audio_buffer = []
+ self.pending_speech_chunks = []
+ self.pending_upload_chunks = []
+ self.is_speaking = False
+ self.silence_chunks = 0
+ self.speech_chunks = 0
+ try:
+ self.deps.movement_manager.set_listening(False)
+ except Exception:
+ pass
+
+ def set_speaker_muted(self, muted: bool) -> None:
+ self.speaker_muted = muted
+ if muted:
+ self._flush_player_state(reason="speaker muted")
+
+ def _refresh_openwebui_runtime_config(self) -> None:
+ if not self._llm_url_override:
+ self.llm_url = config.OPENWEBUI_URL
+ if not self._llm_model_override:
+ self.llm_model = config.OPENWEBUI_MODEL
+
+ async def start_up(self):
+ """Initialize local models."""
+ logger.info("Initializing OpenWebUI Pipeline...")
+ self._refresh_openwebui_runtime_config()
+ logger.info("OpenWebUI runtime config: model=%s url=%s", self.llm_model, self.llm_url)
+
+ # Lazy imports pull in heavier runtime deps, so defer them until the pipeline starts.
+ from Reachy_OpenWebUI.sub_apps.conversation_app.local.tts import OpenWebUISpeech
+ from Reachy_OpenWebUI.sub_apps.conversation_app.vad import SileroVAD
+
+ try:
+ self.tool_specs = _configured_tool_specs()
+ logger.info(
+ "Reachy tools enabled: %s",
+ ", ".join(
+ str(spec.get("function", {}).get("name") or "").strip()
+ for spec in self.tool_specs
+ if isinstance(spec, dict)
+ )
+ or "",
+ )
+
+ logger.info("Loading VAD...")
+ self.vad = await asyncio.to_thread(SileroVAD)
+ logger.info(
+ "VAD settings: threshold=%.3f onset_chunks=%d silence_end_chunks=%d min_speech_chunks=%d",
+ config.VAD_THRESHOLD,
+ config.VAD_SPEECH_ONSET_CHUNKS,
+ config.VAD_SILENCE_END_CHUNKS,
+ config.VAD_MIN_SPEECH_CHUNKS,
+ )
+
+ logger.info("Using OpenWebUI audio transcription.")
+
+ logger.info("Loading LLM Client...")
+ self.llm = OpenWebUIClient(base_url=self.llm_url, model=self.llm_model)
+ await self.llm.load_voice_context()
+ tts_voice = await self.llm.get_model_tts_voice()
+ if not tts_voice:
+ logger.info("No OpenWebUI model TTS voice found; using OpenWebUI server default voice.")
+
+ logger.info("Loading OpenWebUI speech output...")
+ self.speech = await asyncio.to_thread(OpenWebUISpeech, model=self.llm_model, voice=tts_voice)
+
+ try:
+ session_id = await self.llm.start_conversation_session()
+ logger.info("OpenWebUI conversation socket ready: session_id=%s", session_id or "unavailable")
+ except Exception as e:
+ logger.warning(f"OpenWebUI conversation socket unavailable (non-critical): {e}")
+
+
+ logger.info("OpenWebUI pipeline ready.")
+ except (Exception, SystemExit) as e:
+ logger.error(f"Failed to initialize OpenWebUI pipeline: {e}")
+ logger.error("Pipeline will remain inactive. Check the saved OpenWebUI env file and app logs.")
+
+ async def receive(self, frame: Tuple[int, np.ndarray]) -> None:
+ """Process incoming audio frame."""
+ sr, audio = frame
+ self._receive_frame_count += 1
+
+ if self.muted:
+ if self.is_speaking:
+ self.set_muted(True)
+ return
+
+ # Log audio diagnostics on first frame and periodically
+ if self._receive_frame_count == 1:
+ logger.info(
+ f"Audio frame: dtype={audio.dtype}, shape={audio.shape}, "
+ f"sr={sr}, min={audio.min():.6f}, max={audio.max():.6f}, "
+ f"vad_loaded={self.vad is not None}"
+ )
+
+ # 1. Convert to float32 safely
+ if audio.dtype == np.float32:
+ audio_float = audio.copy()
+ else:
+ audio_float = audio.astype(np.float32) / 32768.0
+
+ # 2. Downmix to mono if needed
+ if audio_float.ndim > 1:
+ if audio_float.shape[0] < audio_float.shape[1]:
+ audio_float = audio_float.T
+ channel_peaks = np.max(np.abs(audio_float), axis=0)
+ channel_index = int(np.argmax(channel_peaks))
+ now = time.monotonic()
+ last_log = float(getattr(type(self).receive, "_last_channel_log", 0.0))
+ if now - last_log >= 5.0:
+ logger.info(
+ "OpenWebUI audio channels: peaks=%s selected=%s",
+ ",".join(f"{float(peak):.6f}" for peak in channel_peaks),
+ channel_index,
+ )
+ setattr(type(self).receive, "_last_channel_log", now)
+ audio_float = audio_float[:, channel_index]
+
+ if config.MIC_GAIN != 1.0:
+ audio_float = np.clip(audio_float * config.MIC_GAIN, -1.0, 1.0).astype(np.float32)
+
+ # 3. Keep uploaded STT audio at 24 kHz, while using 16 kHz only for Silero VAD.
+ upload_sr = 24000
+ vad_sr = 16000
+ if sr != upload_sr:
+ upload_samples = int(len(audio_float) * upload_sr / sr)
+ upload_audio = resample(audio_float, upload_samples).astype(np.float32)
+ else:
+ upload_audio = audio_float.astype(np.float32)
+ vad_samples = int(len(upload_audio) * vad_sr / upload_sr)
+ vad_audio = resample(upload_audio, vad_samples).astype(np.float32) if vad_samples else np.array([], dtype=np.float32)
+
+ # Log RMS level periodically (every 500 frames ~= 25s)
+ if self._receive_frame_count % 500 == 0:
+ rms = float(np.sqrt(np.mean(upload_audio**2)))
+ peak = float(np.abs(upload_audio).max())
+ logger.info(
+ f"Audio level (frame {self._receive_frame_count}): "
+ f"rms={rms:.6f}, peak={peak:.6f}, samples={len(upload_audio)}, sr=24000"
+ )
+
+ # 4. Add to separate VAD and OpenWebUI-STT upload buffers.
+ self.vad_buffer = np.concatenate((self.vad_buffer, vad_audio))
+ self.upload_buffer = np.concatenate((self.upload_buffer, upload_audio))
+
+ # 5. Echo suppression: skip VAD while pipeline is generating/playing speech.
+ now_mono = time.monotonic()
+ if self._active_pipeline_count > 0 or now_mono < self._suppress_vad_until:
+ await self._handle_possible_stop_command_audio(upload_audio, vad_audio, now_mono)
+ # Discard accumulated VAD buffer to avoid processing stale audio.
+ self.vad_buffer = np.array([], dtype=np.float32)
+ self.upload_buffer = np.array([], dtype=np.float32)
+ self.lookback_buffer.clear()
+ if self.is_speaking:
+ self.is_speaking = False
+ self.audio_buffer = []
+ self.speech_chunks = 0
+ self.silence_chunks = 0
+ return
+ # 6. Process VAD in Silero's 512-sample chunks and keep matching 24 kHz chunks for OpenWebUI upload.
+ chunk_size = 512
+ upload_chunk_size = 768
+
+ while len(self.vad_buffer) >= chunk_size and len(self.upload_buffer) >= upload_chunk_size:
+ chunk = self.vad_buffer[:chunk_size]
+ self.vad_buffer = self.vad_buffer[chunk_size:]
+ upload_chunk = self.upload_buffer[:upload_chunk_size]
+ self.upload_buffer = self.upload_buffer[upload_chunk_size:]
+
+ # VAD Check
+ if self.vad:
+ is_speech = self.vad.is_speech(chunk)
+ else:
+ is_speech = False
+
+ if is_speech:
+ self._last_user_speech_mono = time.monotonic()
+ if not self.is_speaking:
+ self.pending_speech_chunks.append(chunk)
+ self.pending_upload_chunks.append(upload_chunk)
+ if len(self.pending_speech_chunks) < max(1, config.VAD_SPEECH_ONSET_CHUNKS):
+ continue
+
+ self.is_speaking = True
+ self.speech_chunks = len(self.pending_speech_chunks)
+ logger.info("Speech detected!")
+
+ self.audio_buffer = list(self.lookback_buffer) + list(self.pending_upload_chunks)
+ self.pending_speech_chunks = []
+ self.pending_upload_chunks = []
+ self.lookback_buffer.clear()
+
+ if self.deps.head_wobbler:
+ self.deps.movement_manager.set_listening(True)
+ continue
+
+ self.silence_chunks = 0
+ if self.is_speaking:
+ self.speech_chunks += 1
+ self.audio_buffer.append(upload_chunk)
+
+ else:
+ if self.is_speaking:
+ # Possibly speech ended, but wait for silence threshold
+ self.silence_chunks += 1
+ self.audio_buffer.append(upload_chunk)
+
+ if self.silence_chunks > config.VAD_SILENCE_END_CHUNKS:
+ self.is_speaking = False
+ logger.info(f"Speech finished ({self.speech_chunks} chunks)")
+ self.deps.movement_manager.set_listening(False)
+
+ # Trigger pipeline if we had enough speech
+ if self.speech_chunks >= config.VAD_MIN_SPEECH_CHUNKS:
+ full_audio = np.concatenate(self.audio_buffer)
+ logger.info("Triggering AI pipeline...")
+ asyncio.create_task(self._run_pipeline(full_audio))
+ else:
+ logger.debug("Speech too short, ignoring.")
+
+ self.audio_buffer = []
+ self.speech_chunks = 0
+ self.pending_speech_chunks = []
+ self.pending_upload_chunks = []
+ else:
+ self.pending_speech_chunks = []
+ self.pending_upload_chunks = []
+ # Not speaking, keep filling lookback buffer
+ self.lookback_buffer.append(upload_chunk)
+
+ async def _run_pipeline(self, audio: np.ndarray):
+ """Run OpenWebUI transcription -> chat -> speech pipeline."""
+ if self.llm is None or self.speech is None:
+ return
+ # --- Latency tracking ---
+ t_pipeline_start = time.monotonic()
+ t_first_token = 0.0
+ t_first_audio = 0.0
+ t_llm_done = 0.0
+ first_token_logged = False
+ llm_token_count = 0
+
+ # 1. OpenWebUI transcription
+ try:
+ transcript = await self._transcribe_openwebui(audio)
+ except Exception as exc:
+ logger.error("OpenWebUI transcription failed: %s", exc)
+ return
+ t_stt_done = time.monotonic()
+ if not transcript.strip():
+ return
+
+ stt_ms = (t_stt_done - t_pipeline_start) * 1000
+ logger.info(f"OpenWebUI transcription: {stt_ms:.0f}ms ({len(audio) / 24000:.1f}s audio, sr=24000)")
+
+ if _is_stop_command(transcript):
+ logger.info("Stop command received while listening: %r", transcript)
+ await self._interrupt_current_response(reason="spoken stop command")
+ return
+
+ self._flush_player_state(reason="new user utterance")
+
+ # Suppress VAD while we generate and play OpenWebUI speech.
+ self._response_cancel_requested = False
+ self._active_pipeline_count += 1
+
+ # Ordered TTS pipeline: sentences synthesize one at a time while later
+ # text still streams, so the first sentence plays long before the reply
+ # is fully generated/synthesized.
+ sentence_queue: asyncio.Queue[Optional[str]] = asyncio.Queue()
+ first_audio_state = {"t": 0.0}
+
+ def _first_audio_cb() -> None:
+ if first_audio_state["t"] == 0.0:
+ first_audio_state["t"] = time.monotonic()
+ elapsed_ms = (first_audio_state["t"] - t_pipeline_start) * 1000
+ logger.info(f"First audio queued: {elapsed_ms:.0f}ms (speech-in to audio-out)")
+
+ async def _tts_worker() -> None:
+ while True:
+ sentence = await sentence_queue.get()
+ try:
+ if sentence is None:
+ return
+ if self._response_cancel_requested:
+ continue
+ self._last_assistant_typing_mono = time.monotonic()
+ self._tts_inflight_count += 1
+ await self._process_sentence(sentence, _latency_cb=_first_audio_cb)
+ except Exception as exc:
+ logger.error("TTS pipeline failed for sentence %r: %s", sentence, exc)
+ finally:
+ if sentence is not None:
+ self._tts_inflight_count = max(0, self._tts_inflight_count - 1)
+ sentence_queue.task_done()
+
+ tts_worker_task = asyncio.create_task(_tts_worker(), name="tts-sentence-worker")
+ try:
+ # 1.5 Inject Vision Context
+ vision_context = ""
+ if self.deps.vision_manager and self.deps.vision_manager.latest_description:
+ vision_context = f" [Visual Context: {self.deps.vision_manager.latest_description}]"
+
+ logger.info(f"User: {transcript}{vision_context}")
+ await self.output_queue.put(AdditionalOutputs({"role": "user", "content": transcript}))
+
+ # 2. LLM Loop (Handling potential tool calls)
+ current_input = transcript + vision_context + self._cookaiware_turn_context()
+ max_turns = 5 # Allow multi-step tool chains
+ turn = 0
+
+ tool_outputs = None # For subsequent turns
+ pending_action_labels: list[str] = []
+
+ while turn < max_turns:
+ turn += 1
+ full_response_text = ""
+ streamer = _SentenceStreamer()
+
+ # If this is the first turn, we pass user input. Subsequent turns are tool outputs.
+ llm_user_input = current_input if turn == 1 else None
+
+ logger.info(f"LLM Turn {turn} (Input: {llm_user_input or 'Tool Outputs'})")
+
+ tool_calls = []
+
+ self.tool_specs = _configured_tool_specs()
+ async for event in self.llm.chat_stream(
+ user_text=llm_user_input, tools=self.tool_specs, tool_outputs=tool_outputs
+ ):
+ if self._response_cancel_requested:
+ logger.info("Assistant response cancelled before processing next stream event")
+ break
+ if event["type"] == "text":
+ token = event["content"]
+ full_response_text += token
+ llm_token_count += 1
+
+ # Hand completed sentences to the TTS worker immediately.
+ for sentence in streamer.push(token):
+ self._last_assistant_typing_mono = time.monotonic()
+ await sentence_queue.put(sentence)
+
+ # Track time-to-first-token (first text turn only)
+ if not first_token_logged and turn == 1:
+ t_first_token = time.monotonic()
+ first_token_logged = True
+ ttft_ms = (t_first_token - t_stt_done) * 1000
+ logger.info(f"LLM first token: {ttft_ms:.0f}ms")
+
+ elif event["type"] == "tool_call":
+ tool_calls.append(event["tool_call"])
+
+ elif event["type"] == "error":
+ logger.error(f"LLM Error: {event['content']}")
+
+ if self._response_cancel_requested:
+ logger.info("Assistant response cancelled; skipping remaining speech/tool work")
+ break
+
+ # Track when LLM finishes generating (first text turn)
+ if turn == 1 and t_llm_done == 0.0:
+ t_llm_done = time.monotonic()
+ llm_gen_ms = (t_llm_done - t_stt_done) * 1000
+ tok_s = llm_token_count / ((t_llm_done - t_stt_done) or 1)
+ logger.info(f"LLM done: {llm_gen_ms:.0f}ms ({llm_token_count} tokens, {tok_s:.1f} tok/s)")
+
+ # Queue any trailing partial sentence for speech.
+ for sentence in streamer.flush():
+ self._last_assistant_typing_mono = time.monotonic()
+ await sentence_queue.put(sentence)
+
+ if full_response_text:
+ implied_action_labels = [
+ _tool_display_label(func_name, args, {})
+ for func_name, args in _implied_action_calls(full_response_text)
+ ]
+ clean_response_text = _clean_assistant_text(full_response_text)
+ if clean_response_text:
+ display_response_text = _append_action_labels(
+ clean_response_text,
+ pending_action_labels + implied_action_labels,
+ )
+ pending_action_labels = []
+ logger.info(f"Assistant: {display_response_text}")
+ await self.output_queue.put(
+ AdditionalOutputs({"role": "assistant", "content": display_response_text})
+ )
+
+ # If no tool calls, we are done
+ if not tool_calls:
+ break
+
+ # Execute Tools
+ tool_outputs = []
+ for tc in tool_calls:
+ function_call = tc.get("function") if isinstance(tc, dict) else None
+ if not isinstance(function_call, dict):
+ logger.warning("Skipping malformed tool call: %r", tc)
+ continue
+ func_name = str(function_call.get("name") or "").strip()
+ args_str = function_call.get("arguments") or {}
+ call_id = str(tc.get("id") or f"call_{len(tool_outputs)}")
+ if not func_name:
+ logger.warning("Skipping unnamed tool call: %r", tc)
+ continue
+
+ logger.info(f"🛠️ Tool Call: {func_name}({args_str})")
+
+ # Execute
+ result = await dispatch_tool_call(func_name, args_str, self.deps)
+ result_str = json.dumps(result)
+ label = _tool_display_label(func_name, args_str, result if isinstance(result, dict) else {})
+ if label:
+ pending_action_labels.append(label)
+
+ tool_outputs.append({"role": "tool", "content": result_str, "tool_call_id": call_id})
+
+ logger.info(f" -> Result: {result_str}")
+
+ # Prepare for next turn
+ # We Loop back with tool_outputs, llm_user_input will be None
+
+ # Wait for queued sentences to finish synthesizing before closing the turn.
+ await sentence_queue.put(None)
+ try:
+ await asyncio.wait_for(tts_worker_task, timeout=180.0)
+ except asyncio.TimeoutError:
+ logger.warning("TTS worker did not drain in time; cancelling")
+ tts_worker_task.cancel()
+
+ # --- Log total pipeline latency ---
+ t_first_audio = first_audio_state["t"]
+ t_pipeline_end = time.monotonic()
+ total_ms = (t_pipeline_end - t_pipeline_start) * 1000
+ ttft_ms = (t_first_token - t_stt_done) * 1000 if t_first_token else 0
+ llm_ms = (t_llm_done - t_stt_done) * 1000 if t_llm_done else 0
+ first_audio_ms = (t_first_audio - t_pipeline_start) * 1000 if t_first_audio else 0
+ tok_s = llm_token_count / ((t_llm_done - t_stt_done) or 1) if t_llm_done else 0
+ logger.info(
+ f"BENCHMARK | STT {stt_ms:.0f}ms | TTFT {ttft_ms:.0f}ms | "
+ f"LLM {llm_ms:.0f}ms ({llm_token_count}tok, {tok_s:.1f}tok/s) | "
+ f"First audio {first_audio_ms:.0f}ms | Total {total_ms:.0f}ms"
+ )
+ finally:
+ if not tts_worker_task.done():
+ tts_worker_task.cancel()
+ self._active_pipeline_count -= 1
+ if self._active_pipeline_count == 0:
+ # Cooldown: wait for speech audio to finish playing through speaker + echo to die.
+ cooldown_s = 1.5
+ self._suppress_vad_until = max(
+ self._playback_end_mono + cooldown_s,
+ time.monotonic() + cooldown_s,
+ )
+ logger.debug("Pipeline done, VAD suppressed until playback ends + cooldown")
+
+ async def send_text_input(self, text: str, images: Optional[list[str]] = None) -> bool:
+ """Run the OpenWebUI conversation pipeline from typed text."""
+ if self.llm is None or self.speech is None:
+ return False
+ user_text = (text or "").strip()
+ if not user_text:
+ return False
+ if _is_stop_command(user_text):
+ await self._interrupt_current_response(reason=f"typed stop command: {user_text!r}")
+ return True
+
+ self._flush_player_state(reason="new typed message")
+ self._last_user_speech_mono = time.monotonic()
+ self._response_cancel_requested = False
+ self._active_pipeline_count += 1
+
+ t_pipeline_start = time.monotonic()
+ t_first_token = 0.0
+ t_llm_done = 0.0
+ first_token_logged = False
+ llm_token_count = 0
+ first_audio_state = {"t": 0.0}
+ sentence_queue: asyncio.Queue[Optional[str]] = asyncio.Queue()
+
+ def _first_audio_cb() -> None:
+ if first_audio_state["t"] == 0.0:
+ first_audio_state["t"] = time.monotonic()
+ elapsed_ms = (first_audio_state["t"] - t_pipeline_start) * 1000
+ logger.info("First audio queued: %.0fms (text-in to audio-out)", elapsed_ms)
+
+ async def _tts_worker() -> None:
+ while True:
+ sentence = await sentence_queue.get()
+ try:
+ if sentence is None:
+ return
+ if self._response_cancel_requested:
+ continue
+ self._last_assistant_typing_mono = time.monotonic()
+ self._tts_inflight_count += 1
+ await self._process_sentence(sentence, _latency_cb=_first_audio_cb)
+ except Exception as exc:
+ logger.error("Typed-message TTS failed for sentence %r: %s", sentence, exc)
+ finally:
+ if sentence is not None:
+ self._tts_inflight_count = max(0, self._tts_inflight_count - 1)
+ sentence_queue.task_done()
+
+ tts_worker_task = asyncio.create_task(_tts_worker(), name="typed-text-tts-worker")
+ try:
+ vision_context = ""
+ if self.deps.vision_manager and self.deps.vision_manager.latest_description:
+ vision_context = f" [Visual Context: {self.deps.vision_manager.latest_description}]"
+
+ logger.info("Typed user: %s%s", user_text, vision_context)
+ image_data_urls = [str(item) for item in (images or []) if str(item).startswith("data:image/")]
+ display_user_text = user_text
+ if image_data_urls:
+ display_user_text = f"{user_text}\n[image attached]" if user_text else "[image attached]"
+ await self.output_queue.put(AdditionalOutputs({"role": "user", "content": display_user_text}))
+
+ current_input = user_text + vision_context + self._cookaiware_turn_context()
+ tool_outputs = None
+ pending_action_labels: list[str] = []
+
+ for turn in range(1, 6):
+ full_response_text = ""
+ streamer = _SentenceStreamer()
+ llm_user_input = current_input if turn == 1 else None
+ tool_calls = []
+
+ self.tool_specs = _configured_tool_specs()
+ async for event in self.llm.chat_stream(
+ user_text=llm_user_input,
+ tools=self.tool_specs,
+ tool_outputs=tool_outputs,
+ image_data_urls=image_data_urls if turn == 1 else None,
+ ):
+ if self._response_cancel_requested:
+ logger.info("Typed assistant response cancelled")
+ break
+ if event["type"] == "text":
+ token = event["content"]
+ full_response_text += token
+ llm_token_count += 1
+ for sentence in streamer.push(token):
+ self._last_assistant_typing_mono = time.monotonic()
+ await sentence_queue.put(sentence)
+ if not first_token_logged and turn == 1:
+ t_first_token = time.monotonic()
+ first_token_logged = True
+ elif event["type"] == "tool_call":
+ tool_calls.append(event["tool_call"])
+ elif event["type"] == "error":
+ logger.error("Typed LLM error: %s", event["content"])
+
+ if self._response_cancel_requested:
+ break
+ if turn == 1 and t_llm_done == 0.0:
+ t_llm_done = time.monotonic()
+ for sentence in streamer.flush():
+ self._last_assistant_typing_mono = time.monotonic()
+ await sentence_queue.put(sentence)
+
+ if full_response_text:
+ implied_action_labels = [
+ _tool_display_label(func_name, args, {})
+ for func_name, args in _implied_action_calls(full_response_text)
+ ]
+ clean_response_text = _clean_assistant_text(full_response_text)
+ if clean_response_text:
+ display_response_text = _append_action_labels(
+ clean_response_text,
+ pending_action_labels + implied_action_labels,
+ )
+ pending_action_labels = []
+ logger.info("Typed assistant: %s", display_response_text)
+ await self.output_queue.put(
+ AdditionalOutputs({"role": "assistant", "content": display_response_text})
+ )
+
+ if not tool_calls:
+ break
+
+ tool_outputs = []
+ for tc in tool_calls:
+ function_call = tc.get("function") if isinstance(tc, dict) else None
+ if not isinstance(function_call, dict):
+ logger.warning("Skipping malformed typed tool call: %r", tc)
+ continue
+ func_name = str(function_call.get("name") or "").strip()
+ args_str = function_call.get("arguments") or {}
+ call_id = str(tc.get("id") or f"call_{len(tool_outputs)}")
+ if not func_name:
+ logger.warning("Skipping unnamed typed tool call: %r", tc)
+ continue
+ logger.info("Typed tool call: %s(%s)", func_name, args_str)
+ result = await dispatch_tool_call(func_name, args_str, self.deps)
+ result_str = json.dumps(result)
+ label = _tool_display_label(func_name, args_str, result if isinstance(result, dict) else {})
+ if label:
+ pending_action_labels.append(label)
+ tool_outputs.append({"role": "tool", "content": result_str, "tool_call_id": call_id})
+
+ await sentence_queue.put(None)
+ try:
+ await asyncio.wait_for(tts_worker_task, timeout=180.0)
+ except asyncio.TimeoutError:
+ logger.warning("Typed TTS worker did not drain in time; cancelling")
+ tts_worker_task.cancel()
+
+ total_ms = (time.monotonic() - t_pipeline_start) * 1000
+ ttft_ms = (t_first_token - t_pipeline_start) * 1000 if t_first_token else 0
+ llm_ms = (t_llm_done - t_pipeline_start) * 1000 if t_llm_done else 0
+ tok_s = llm_token_count / ((t_llm_done - t_pipeline_start) or 1) if t_llm_done else 0
+ first_audio_ms = (
+ (first_audio_state["t"] - t_pipeline_start) * 1000
+ if first_audio_state["t"]
+ else 0
+ )
+ logger.info(
+ "TEXT BENCHMARK | TTFT %.0fms | LLM %.0fms (%stok, %.1f tok/s) | "
+ "First audio %.0fms | Total %.0fms",
+ ttft_ms,
+ llm_ms,
+ llm_token_count,
+ tok_s,
+ first_audio_ms,
+ total_ms,
+ )
+ return True
+ finally:
+ if not tts_worker_task.done():
+ tts_worker_task.cancel()
+ self._active_pipeline_count = max(0, self._active_pipeline_count - 1)
+ if self._active_pipeline_count == 0:
+ cooldown_s = 1.5
+ self._suppress_vad_until = max(
+ self._playback_end_mono + cooldown_s,
+ time.monotonic() + cooldown_s,
+ )
+
+ async def _handle_possible_stop_command_audio(
+ self, upload_audio: np.ndarray, vad_audio: np.ndarray, now_mono: float
+ ) -> None:
+ if self.vad is None or now_mono < self._stop_command_cooldown_until:
+ self._reset_stop_command_buffers()
+ return
+ if self._stop_command_task is not None and not self._stop_command_task.done():
+ return
+
+ self._stop_vad_buffer = np.concatenate((self._stop_vad_buffer, vad_audio))
+ self._stop_upload_buffer = np.concatenate((self._stop_upload_buffer, upload_audio))
+
+ chunk_size = 512
+ upload_chunk_size = 768
+ while len(self._stop_vad_buffer) >= chunk_size and len(self._stop_upload_buffer) >= upload_chunk_size:
+ vad_chunk = self._stop_vad_buffer[:chunk_size]
+ self._stop_vad_buffer = self._stop_vad_buffer[chunk_size:]
+ upload_chunk = self._stop_upload_buffer[:upload_chunk_size]
+ self._stop_upload_buffer = self._stop_upload_buffer[upload_chunk_size:]
+
+ is_speech = self.vad.is_speech(vad_chunk)
+ if is_speech:
+ if not self._stop_is_speaking:
+ self._stop_is_speaking = True
+ self._stop_speech_chunks = 0
+ self._stop_silence_chunks = 0
+ self._stop_audio_buffer = []
+ self._stop_silence_chunks = 0
+ self._stop_speech_chunks += 1
+ self._stop_audio_buffer.append(upload_chunk)
+ if self._stop_speech_chunks > 80:
+ self._reset_stop_command_buffers()
+ continue
+
+ if not self._stop_is_speaking:
+ continue
+
+ self._stop_silence_chunks += 1
+ self._stop_audio_buffer.append(upload_chunk)
+ if self._stop_silence_chunks <= 15:
+ continue
+
+ if 2 <= self._stop_speech_chunks <= 80 and self._stop_audio_buffer:
+ stop_audio = np.concatenate(self._stop_audio_buffer)
+ self._stop_command_task = asyncio.create_task(self._check_stop_command(stop_audio))
+ self._reset_stop_command_buffers()
+ return
+
+ def _reset_stop_command_buffers(self) -> None:
+ self._stop_vad_buffer = np.array([], dtype=np.float32)
+ self._stop_upload_buffer = np.array([], dtype=np.float32)
+ self._stop_audio_buffer = []
+ self._stop_is_speaking = False
+ self._stop_speech_chunks = 0
+ self._stop_silence_chunks = 0
+
+ async def _check_stop_command(self, audio: np.ndarray) -> None:
+ try:
+ transcript = await self._transcribe_openwebui(audio)
+ except Exception as exc:
+ logger.debug("Stop-command transcription failed: %s", exc)
+ return
+ if not transcript.strip():
+ return
+ logger.info("Speech heard during response: %r", transcript)
+ if _is_stop_command(transcript):
+ await self._interrupt_current_response(reason=f"stop command: {transcript!r}")
+
+ async def _interrupt_current_response(self, reason: str) -> None:
+ logger.info("Interrupting current response (%s)", reason)
+ self._response_cancel_requested = True
+ now_mono = time.monotonic()
+ self._stop_command_cooldown_until = now_mono + 1.0
+ self._suppress_vad_until = max(self._suppress_vad_until, now_mono + 0.8)
+ self._flush_player_state(reason=reason)
+
+ try:
+ self.deps.movement_manager.clear_move_queue()
+ except Exception as exc:
+ logger.debug("Could not clear movement queue on stop command: %s", exc)
+
+ self._reset_stop_command_buffers()
+
+ def _flush_player_state(self, reason: str) -> None:
+ """Drop queued speaker audio and reset playback timing for the next turn."""
+ logger.info("Clearing player before response (%s)", reason)
+ self._playback_end_mono = time.monotonic()
+
+ clear_queue = getattr(self, "_clear_queue", None)
+ if callable(clear_queue):
+ clear_queue()
+ else:
+ self.output_queue = asyncio.Queue()
+
+ head_wobbler = getattr(self.deps, "head_wobbler", None)
+ reset_wobbler = getattr(head_wobbler, "reset", None)
+ if callable(reset_wobbler):
+ reset_wobbler()
+
+ async def _transcribe_openwebui(self, audio: np.ndarray) -> str:
+ upload_rate = 24000
+ stt_audio = self._prepare_transcription_audio(audio)
+ wav_bytes = self._float_to_wav_bytes(stt_audio, upload_rate)
+ base_url = (config.OPENWEBUI_URL or "").rstrip("/")
+ if not base_url:
+ return ""
+
+ headers = {
+ "Accept": "application/json",
+ "User-Agent": config.OPENWEBUI_USER_AGENT,
+ }
+ auth_token = (config.OPENWEBUI_TOKEN or config.OPENWEBUI_API_KEY or "").strip()
+ if auth_token and auth_token != "ollama":
+ headers["Authorization"] = f"Bearer {auth_token}"
+
+ files = {
+ "file": (
+ f"reachy_voice_{int(time.time() * 1000)}.wav",
+ wav_bytes,
+ "audio/wav",
+ )
+ }
+ timeout = httpx.Timeout(connect=10.0, read=75.0, write=20.0, pool=10.0)
+ async with httpx.AsyncClient(timeout=timeout) as client:
+ response = None
+ for url in _openwebui_audio_candidates(base_url, "audio/transcriptions"):
+ try:
+ response = await client.post(url, headers=headers, files=files)
+ except httpx.TimeoutException as exc:
+ logger.warning("OpenWebUI transcription timed out at %s: %s", url, exc)
+ continue
+ if response.status_code in (404, 405):
+ logger.info("OpenWebUI transcription endpoint unavailable (%s): %s", response.status_code, url)
+ continue
+ response.raise_for_status()
+ break
+ if response is None or response.status_code in (404, 405):
+ raise RuntimeError("OpenWebUI transcription endpoint not found")
+ transcript, filename = self._extract_transcription_result(response)
+ if filename:
+ logger.info("OpenWebUI transcription audio artifact: %s", filename)
+ if not transcript:
+ logger.info(
+ "OpenWebUI transcription empty response: status=%s content_type=%s body=%s",
+ response.status_code,
+ response.headers.get("content-type", ""),
+ response.text[:500],
+ )
+ return transcript
+
+ @staticmethod
+ def _prepare_transcription_audio(audio: np.ndarray) -> np.ndarray:
+ arr = np.asarray(audio, dtype=np.float32)
+ if arr.ndim > 1:
+ arr = np.mean(arr, axis=1)
+ if not arr.size:
+ return arr
+ peak = float(np.max(np.abs(arr), initial=0.0))
+ if peak <= 0.0:
+ return arr
+ target_peak = 0.35
+ if peak < target_peak:
+ arr = np.clip(arr * (target_peak / peak), -1.0, 1.0).astype(np.float32)
+ return arr
+
+ @staticmethod
+ def _float_to_wav_bytes(audio: np.ndarray, sample_rate: int) -> bytes:
+ arr = np.asarray(audio, dtype=np.float32)
+ if arr.ndim > 1:
+ arr = np.mean(arr, axis=1)
+ arr = np.clip(arr, -1.0, 1.0)
+ pcm = (arr * 32767.0).astype(np.int16)
+ buffer = io.BytesIO()
+ with wave.open(buffer, "wb") as wav:
+ wav.setnchannels(1)
+ wav.setsampwidth(2)
+ wav.setframerate(sample_rate)
+ wav.writeframes(pcm.tobytes())
+ return buffer.getvalue()
+
+ @staticmethod
+ def _extract_transcription_result(response: httpx.Response) -> tuple[str, str]:
+ content_type = response.headers.get("content-type", "")
+ if "application/json" not in content_type:
+ return response.text.strip(), ""
+ data = response.json()
+ if isinstance(data, str):
+ return data.strip(), ""
+ if not isinstance(data, dict):
+ return "", ""
+ filename = ""
+ for key in ("filename", "file", "audio_filename"):
+ value = data.get(key)
+ if isinstance(value, str) and value.strip():
+ filename = value.strip()
+ break
+ for key in ("text", "transcription", "content"):
+ value = data.get(key)
+ if isinstance(value, str) and value.strip():
+ return value.strip(), filename
+ nested = data.get("data")
+ if isinstance(nested, dict):
+ if not filename:
+ nested_filename = nested.get("filename")
+ if isinstance(nested_filename, str):
+ filename = nested_filename.strip()
+ value = nested.get("text")
+ if isinstance(value, str):
+ return value.strip(), filename
+ return "", filename
+
+ @staticmethod
+ def _make_first_audio_cb(t_pipeline_start: float, t_first_audio: float):
+ """Create a callback that logs time-to-first-audio once."""
+ logged = False
+
+ def cb():
+ nonlocal logged
+ if not logged and t_first_audio == 0.0:
+ logged = True
+ elapsed_ms = (time.monotonic() - t_pipeline_start) * 1000
+ logger.info(f"First audio queued: {elapsed_ms:.0f}ms (speech-in to audio-out)")
+
+ return cb
+
+ async def _process_sentence(self, text: str, _latency_cb=None) -> bool:
+ """Ask OpenWebUI for speech audio and queue it for Reachy's speaker."""
+ if self.speech is None or self._response_cancel_requested:
+ return False
+ # --- 1. Extract and Execute Commands (Fallback / Legacy) ---
+ # Kept for backward compatibility if the model emits text calls instead of tool_calls.
+ for func_name, args in _implied_action_calls(text):
+ if func_name == "play_emotion" and not args.get("emotion"):
+ continue
+ logger.info("Executing implied action call: %s(%s)", func_name, args)
+ asyncio.create_task(dispatch_tool_call(func_name, args, self.deps))
+
+ # --- 2. Clean text for OpenWebUI speech ---
+ text = _strip_implied_action_calls(text)
+
+ # Remove bold/italic markdown (*word*, **word**)
+ text = text.replace("**", "").replace("*", "")
+
+ # Remove action descriptions in parentheses or asterisks if they remain
+ # e.g. (waves hands) or *laughs*
+ text = re.sub(r"\s*\([^)]*\)", "", text)
+
+ # Remove emojis (Broad unicode range for common emojis)
+ text = re.sub(r"[\U00010000-\U0010ffff]", "", text)
+
+ # Remove other common artifacts if any
+ text = text.strip()
+
+ if not text:
+ return False
+
+ speed = 1.0
+
+ if "[HAPPY]" in text:
+ text = text.replace("[HAPPY]", "")
+ speed = 1.1
+
+ if "[STORY]" in text:
+ text = text.replace("[STORY]", "")
+ speed = 0.9
+
+ # Synthesize through OpenWebUI with the selected model/contact voice.
+ if self.speaker_muted:
+ logger.info("Speaker muted; skipping speech output for text=%r", text[:120])
+ return True
+
+ t_tts_start = time.monotonic()
+ sr, audio = await self.speech.synthesize(text, speed=speed)
+ if self._response_cancel_requested:
+ return
+ tts_ms = (time.monotonic() - t_tts_start) * 1000
+ logger.info(f"OpenWebUI speech: {tts_ms:.0f}ms ({len(text)} chars)")
+
+ # Convert to 1-D int16 PCM; the console converts this to SDK float32.
+ audio_int16 = np.clip(audio * 32767.0, -32768, 32767).astype(np.int16).reshape(-1)
+ if audio_int16.size == 0:
+ logger.warning("OpenWebUI speech returned empty audio for text=%r", text)
+ return False
+
+ # Send to speaker
+ peak = int(np.max(np.abs(audio_int16))) if audio_int16.size else 0
+ logger.info(
+ "Queueing speaker audio: sr=%s samples=%s peak=%s",
+ sr,
+ audio_int16.size,
+ peak,
+ )
+ await self.output_queue.put((sr, audio_int16))
+
+ # Fire latency callback (first audio queued)
+ if _latency_cb is not None:
+ _latency_cb()
+
+ # Track estimated playback end for echo suppression
+ audio_duration_s = len(audio_int16) / float(sr or 24000)
+ now_mono = time.monotonic()
+ self._playback_end_mono = max(self._playback_end_mono, now_mono) + audio_duration_s
+
+ # Feed head wobbler
+ if self.deps.head_wobbler:
+ feed_pcm = getattr(self.deps.head_wobbler, "feed_pcm", None)
+ if callable(feed_pcm):
+ feed_pcm(audio_int16, sr)
+ else:
+ import base64
+
+ b64_data = base64.b64encode(audio_int16.tobytes()).decode("utf-8")
+ self.deps.head_wobbler.feed(b64_data)
+
+ return True
+
+ async def emit(self):
+ """Return the next output from the handler queue."""
+ return await wait_for_item(self.output_queue)
+
+ async def shutdown(self):
+ """Shutdown the handler and clear conversation state."""
+ if self.llm is not None:
+ self.llm.history = []
diff --git a/src/Reachy_OpenWebUI/sub_apps/conversation_app/local/llm.py b/src/Reachy_OpenWebUI/sub_apps/conversation_app/local/llm.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d1838dbf8ee025ea91935a3d83f534aece43964
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/conversation_app/local/llm.py
@@ -0,0 +1,1423 @@
+import asyncio
+from datetime import datetime, time as datetime_time, timedelta
+import json
+import logging
+import os
+import time
+import uuid
+from urllib.parse import quote, urlencode, urlparse, urlunparse
+from typing import Any, Dict, List, Optional, AsyncGenerator, Callable
+
+import httpx
+import websockets
+
+from Reachy_OpenWebUI.sub_apps.conversation_app.chat_history import append_chat_history
+from Reachy_OpenWebUI.config import STABLE_ENV_PATH, config
+from Reachy_OpenWebUI import settings_keys as keys
+
+
+logger = logging.getLogger(__name__)
+
+
+def _normalize_chat_id(value: Optional[str]) -> str:
+ raw = (value or "").strip()
+ if not raw:
+ return ""
+ parsed = urlparse(raw)
+ path = parsed.path if parsed.scheme or parsed.netloc else raw
+ marker = "/c/"
+ if marker in path:
+ return path.split(marker, 1)[1].split("/", 1)[0].strip()
+ return raw.strip("/")
+
+
+class OpenWebUISocketSession:
+ """Minimal Socket.IO session used so OpenWebUI treats requests like its UI/call clients."""
+
+ def __init__(self, base_url: str, api_key: str):
+ self.base_url = base_url
+ self.api_key = api_key
+ # OpenWebUI socket auth only decodes JWTs. An sk- API key passes HTTP auth,
+ # but user-join returns an empty ack and no chat events are ever delivered.
+ self.auth_token = (config.OPENWEBUI_TOKEN or api_key or "").strip()
+ self.session_id: Optional[str] = None
+ self._ws: Any = None
+ self._reader_task: Optional[asyncio.Task[None]] = None
+ self._lock = asyncio.Lock()
+ self._events: asyncio.Queue[tuple[dict[str, Any], Optional[Callable[[Any], None]]]] = asyncio.Queue()
+
+ async def ensure_connected(self) -> Optional[str]:
+ async with self._lock:
+ if self.session_id and self._ws:
+ return self.session_id
+ await self._connect()
+ return self.session_id
+
+ async def close(self) -> None:
+ if self._reader_task:
+ self._reader_task.cancel()
+ self._reader_task = None
+ if self._ws:
+ await self._ws.close()
+ self._ws = None
+ self.session_id = None
+
+ async def _connect(self) -> None:
+ socket_url = self._socket_url()
+ headers = {"User-Agent": config.OPENWEBUI_USER_AGENT}
+ if self.auth_token and self.auth_token != "ollama":
+ headers["Authorization"] = f"Bearer {self.auth_token}"
+
+ try:
+ try:
+ self._ws = await websockets.connect(socket_url, additional_headers=headers)
+ except TypeError:
+ self._ws = await websockets.connect(socket_url, extra_headers=headers)
+
+ first = await asyncio.wait_for(self._ws.recv(), timeout=10)
+ if isinstance(first, bytes):
+ first = first.decode("utf-8", errors="replace")
+ if not str(first).startswith("0"):
+ raise RuntimeError(f"unexpected Socket.IO hello: {first!r}")
+
+ auth = {"token": self.auth_token} if self.auth_token and self.auth_token != "ollama" else {}
+ await self._ws.send("40" + (json.dumps(auth) if auth else ""))
+
+ deadline = asyncio.get_running_loop().time() + 10
+ while asyncio.get_running_loop().time() < deadline:
+ packet = await asyncio.wait_for(self._ws.recv(), timeout=10)
+ if isinstance(packet, bytes):
+ packet = packet.decode("utf-8", errors="replace")
+ packet = str(packet)
+ if packet == "2":
+ await self._ws.send("3")
+ continue
+ if packet.startswith("40"):
+ payload = packet[2:]
+ if payload:
+ data = json.loads(payload)
+ self.session_id = data.get("sid") or data.get("session_id")
+ break
+
+ if not self.session_id:
+ raise RuntimeError("OpenWebUI socket connected but did not return a session id")
+
+ await self._ws.send(
+ '420["user-join",'
+ + json.dumps({"auth": {"token": self.auth_token}, "user": self._socket_user()})
+ + "]"
+ )
+ await self._await_user_join_ack()
+ self._reader_task = asyncio.create_task(self._read_loop())
+ logger.info("OpenWebUI socket connected: session_id=%s", self.session_id)
+ except Exception as exc:
+ logger.warning("OpenWebUI socket session unavailable; falling back to direct stream: %s", exc)
+ await self.close()
+
+ async def _await_user_join_ack(self, timeout: float = 6.0) -> None:
+ """Wait for the user-join ack. An empty ack means socket auth failed and no chat events will arrive."""
+ deadline = asyncio.get_running_loop().time() + timeout
+ while asyncio.get_running_loop().time() < deadline:
+ remaining = max(0.1, deadline - asyncio.get_running_loop().time())
+ try:
+ packet = await asyncio.wait_for(self._ws.recv(), timeout=remaining)
+ except asyncio.TimeoutError:
+ break
+ if isinstance(packet, bytes):
+ packet = packet.decode("utf-8", errors="replace")
+ packet = str(packet)
+ if packet == "2":
+ await self._ws.send("3")
+ continue
+ if packet.startswith("430"):
+ try:
+ payload = json.loads(packet[3:])
+ except Exception:
+ payload = []
+ joined_user = payload[0] if isinstance(payload, list) and payload else None
+ if isinstance(joined_user, dict) and joined_user.get("id"):
+ logger.info(
+ "OpenWebUI socket user-join authenticated as %s",
+ joined_user.get("name") or joined_user.get("id"),
+ )
+ else:
+ logger.warning(
+ "OpenWebUI socket user-join NOT authenticated (empty ack). "
+ "Realtime chat events will not arrive; set OPENWEBUI_TOKEN to a JWT "
+ "(API keys are rejected by OpenWebUI socket auth)."
+ )
+ return
+ event = self._parse_event_packet(packet)
+ if event:
+ await self._events.put(event)
+ logger.warning("OpenWebUI socket user-join ack not received within %.0fs.", timeout)
+
+ async def _read_loop(self) -> None:
+ try:
+ async for packet in self._ws:
+ if isinstance(packet, bytes):
+ packet = packet.decode("utf-8", errors="replace")
+ packet = str(packet)
+ if packet == "2":
+ await self._ws.send("3")
+ continue
+ event = self._parse_event_packet(packet)
+ if event:
+ await self._events.put(event)
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc:
+ logger.warning("OpenWebUI socket reader stopped: %s", exc)
+ finally:
+ self.session_id = None
+
+ async def next_event(self, timeout: float = 90.0) -> tuple[dict[str, Any], Optional[Callable[[Any], None]]]:
+ return await asyncio.wait_for(self._events.get(), timeout=timeout)
+
+ def drain_events(self) -> int:
+ """Drop queued socket events from earlier turns before starting a new request."""
+ drained = 0
+ while True:
+ try:
+ self._events.get_nowait()
+ except asyncio.QueueEmpty:
+ return drained
+ drained += 1
+
+ def _parse_event_packet(
+ self, packet: str
+ ) -> Optional[tuple[dict[str, Any], Optional[Callable[[Any], None]]]]:
+ if not packet.startswith("42"):
+ return None
+
+ bracket_index = packet.find("[")
+ if bracket_index < 0:
+ return None
+
+ ack_id = packet[2:bracket_index].strip() or None
+ try:
+ payload = json.loads(packet[bracket_index:])
+ except Exception:
+ return None
+
+ if not isinstance(payload, list) or len(payload) < 2:
+ return None
+ event_name = str(payload[0])
+ if event_name not in {"events", "chat-events"}:
+ return None
+
+ data = payload[1]
+ if not isinstance(data, dict):
+ return None
+
+ ack: Optional[Callable[[Any], None]] = None
+ if ack_id:
+ ack = lambda response: asyncio.create_task(self._send_ack(ack_id, response))
+ return data, ack
+
+ async def _send_ack(self, ack_id: str, response: Any) -> None:
+ if not self._ws:
+ return
+ try:
+ await self._ws.send(f"43{ack_id}" + json.dumps([response]))
+ except Exception as exc:
+ logger.warning("OpenWebUI socket ack failed: %s", exc)
+
+ def _socket_url(self) -> str:
+ base = (self.base_url or "").rstrip("/")
+ if base.endswith("/api"):
+ base = base[:-4]
+ parsed = urlparse(base)
+ scheme = "wss" if parsed.scheme == "https" else "ws"
+ path = "/ws/socket.io/"
+ query = "EIO=4&transport=websocket"
+ return urlunparse((scheme, parsed.netloc, path, "", query, ""))
+
+ @staticmethod
+ def _socket_user() -> dict[str, str]:
+ user = {"name": config.OPENWEBUI_USER_NAME or "Reachy Mini"}
+ if config.OPENWEBUI_USER_ID:
+ user["id"] = config.OPENWEBUI_USER_ID
+ if config.OPENWEBUI_USER_EMAIL:
+ user["email"] = config.OPENWEBUI_USER_EMAIL
+ return user
+
+
+class OpenWebUIClient:
+ """OpenWebUI chat client using task socket mode when available."""
+
+ def __init__(
+ self,
+ base_url: Optional[str] = None,
+ model: Optional[str] = None,
+ api_key: Optional[str] = None,
+ ):
+ """Initialize the OpenWebUI client."""
+ base_url = base_url or config.OPENWEBUI_URL
+ api_key = api_key or config.OPENWEBUI_API_KEY
+ self.base_url = base_url.rstrip("/")
+ self.api_key = api_key
+ # Prefer the JWT for HTTP too: chat events are emitted to the room of the
+ # user who made the HTTP request, so HTTP and socket must auth as the same user.
+ self.auth_token = (config.OPENWEBUI_TOKEN or api_key or "").strip()
+ self.model = model
+ # Let OpenWebUI create the real chat id when no saved id exists. If the
+ # settings file already has one, keep using that same conversation.
+ self.chat_id = _normalize_chat_id(config.OPENWEBUI_CHAT_ID)
+ self.socket = OpenWebUISocketSession(base_url, self.auth_token)
+ self.history: List[Dict[str, Any]] = []
+ self.max_history = 10 # Keep last 10 messages
+ self._last_message_id: Optional[str] = None
+ self._last_turn_mono: Optional[float] = None
+ self._model_item: Optional[dict[str, Any]] = None
+ self._voice_context_loaded = False
+ self._openwebui_tools: list[dict[str, Any]] = []
+ self._openwebui_skills: list[dict[str, Any]] = []
+ self._openwebui_functions: list[dict[str, Any]] = []
+
+ async def start_conversation_session(self) -> Optional[str]:
+ """Connect the OpenWebUI socket session without sending a chat turn."""
+ return await self.socket.ensure_connected()
+
+ def _trim_history(self):
+ """Keep history within limits."""
+ if len(self.history) > self.max_history:
+ # Try to keep message pairs (user/assistant) if possible
+ # but simplest is just sliding window
+ self.history = self.history[-self.max_history :]
+
+ def _reset_conversation_if_idle(self) -> None:
+ idle_limit = max(0, int(config.OPENWEBUI_CONVERSATION_IDLE_RESET_SECONDS))
+ if idle_limit <= 0 or self._last_turn_mono is None:
+ return
+ idle_seconds = time.monotonic() - self._last_turn_mono
+ if idle_seconds < idle_limit:
+ return
+ logger.info("OpenWebUI conversation idle for %.0fs; starting a fresh chat.", idle_seconds)
+ self.chat_id = ""
+ self._last_message_id = None
+ self.history = []
+
+ @staticmethod
+ def current_chat_window_start(now: Optional[datetime] = None) -> str:
+ local_now = now or datetime.now().astimezone()
+ boundary = local_now.replace(hour=7, minute=0, second=0, microsecond=0)
+ if local_now.time() < datetime_time(hour=7):
+ boundary -= timedelta(days=1)
+ return boundary.isoformat()
+
+ def clear_chat_id(
+ self,
+ *,
+ window_start: Optional[str] = None,
+ pending_reason: Optional[str] = None,
+ pending_event_id: Optional[str] = None,
+ ) -> None:
+ self.chat_id = ""
+ self._last_message_id = None
+ self.history = []
+ config.OPENWEBUI_CHAT_ID = ""
+ os.environ[keys.OPENWEBUI_CHAT_ID] = ""
+ if window_start is not None:
+ config.OPENWEBUI_CHAT_WINDOW_START = window_start
+ os.environ[keys.OPENWEBUI_CHAT_WINDOW_START] = window_start
+ if pending_reason is not None:
+ config.OPENWEBUI_CHAT_PENDING_REASON = pending_reason
+ os.environ[keys.OPENWEBUI_CHAT_PENDING_REASON] = pending_reason
+ if pending_event_id is not None:
+ config.OPENWEBUI_CHAT_PENDING_EVENT_ID = pending_event_id
+ os.environ[keys.OPENWEBUI_CHAT_PENDING_EVENT_ID] = pending_event_id
+ self._persist_chat_state(
+ "",
+ config.OPENWEBUI_CHAT_WINDOW_START,
+ config.OPENWEBUI_CHAT_PENDING_REASON,
+ config.OPENWEBUI_CHAT_PENDING_EVENT_ID,
+ )
+
+ def _reset_conversation_if_new_chat_window(self) -> None:
+ window_start = self.current_chat_window_start()
+ saved_window = (config.OPENWEBUI_CHAT_WINDOW_START or os.getenv(keys.OPENWEBUI_CHAT_WINDOW_START, "")).strip()
+ if saved_window == window_start:
+ return
+ if self.chat_id:
+ logger.info("OpenWebUI chat window rolled over at 7 AM; starting a fresh chat.")
+ append_chat_history(
+ "daily_rollover",
+ old_chat_id=self.chat_id,
+ window_start=window_start,
+ )
+ self.clear_chat_id(window_start=window_start, pending_reason="daily_rollover", pending_event_id="")
+
+ async def chat_stream(
+ self,
+ user_text: Optional[str] = None,
+ tools: Optional[List[Dict[str, Any]]] = None,
+ tool_outputs: Optional[List[Dict[str, Any]]] = None,
+ image_data_urls: Optional[List[str]] = None,
+ ) -> AsyncGenerator[Dict[str, Any], None]:
+ """Send message and yield response events (text or tool calls)."""
+ if user_text:
+ self._reset_conversation_if_new_chat_window()
+ self._reset_conversation_if_idle()
+ self._trim_history()
+ messages = []
+ messages.extend(self.history)
+
+ if user_text:
+ image_urls = [url for url in (image_data_urls or []) if str(url).startswith("data:image/")]
+ if image_urls:
+ content: list[dict[str, Any]] = [{"type": "text", "text": user_text}]
+ content.extend({"type": "image_url", "image_url": {"url": url}} for url in image_urls)
+ messages.append({"role": "user", "content": content})
+ else:
+ messages.append({"role": "user", "content": user_text})
+
+ if tool_outputs:
+ messages.extend(tool_outputs)
+
+ try:
+ model_item = await self._get_model_item()
+
+ # Direct OpenAI-compatible request (no session_id/chat_id/user_message).
+ # Task/call mode drops client-declared tools, while the direct path
+ # forwards them to the model and streams tool_calls back — the same
+ # client-tools pattern the official app uses with OpenAI realtime.
+ # Keep model_item attached so OpenWebUI still sees the selected
+ # contact/model metadata while the local robot tools stay client-side.
+ payload: Dict[str, Any] = {
+ "stream": True,
+ "model": self.model or "",
+ "messages": messages,
+ "params": {
+ "stream_response": True,
+ },
+ "features": {
+ "voice": True,
+ "image_generation": False,
+ "code_interpreter": False,
+ "web_search": False,
+ },
+ "variables": self._variables(),
+ }
+ if model_item:
+ payload["model_item"] = model_item
+ if tools:
+ payload["tools"] = tools
+ payload["tool_choice"] = "auto"
+ payload["params"]["function_calling"] = "native"
+
+ full_content = ""
+ tool_calls_buffer: Dict[int, Any] = {}
+ stream_to_buffer: Dict[int, int] = {}
+
+ async with httpx.AsyncClient(timeout=120.0) as client:
+ logger.info(
+ "OpenWebUI direct chat request: model=%s messages=%d tools=%d tool_choice=%s",
+ self.model or "",
+ len(messages),
+ len(tools or []),
+ payload.get("tool_choice") or "",
+ )
+ async for event in self._stream_chat_completion(client, payload):
+ if event.get("type") == "text":
+ full_content += event["content"]
+ yield event
+ elif event.get("type") == "tool_delta":
+ self._collect_tool_calls(event.get("tool_calls"), tool_calls_buffer, stream_to_buffer)
+
+ self._last_turn_mono = time.monotonic()
+
+ # Commit user message to history if it was new
+ if user_text:
+ self.history.append({"role": "user", "content": user_text})
+
+ # Commit tool outputs if any
+ if tool_outputs:
+ self.history.extend(tool_outputs)
+
+ # Check if we have tool calls to yield
+ final_tool_calls = []
+ if tool_calls_buffer:
+ for idx in sorted(tool_calls_buffer.keys()):
+ tool_call = tool_calls_buffer[idx]
+ final_tool_calls.append(tool_call)
+ yield {"type": "tool_call", "tool_call": tool_call}
+
+ # Append assistant message with tool calls to history
+ self.history.append(
+ {
+ "role": "assistant",
+ "content": full_content if full_content else None,
+ "tool_calls": final_tool_calls,
+ }
+ )
+ else:
+ # Normal text response
+ self.history.append({"role": "assistant", "content": full_content})
+
+ except Exception as e:
+ logger.exception("OpenWebUI chat error: %s", repr(e))
+ if "context length" in str(e).lower() or "too many tokens" in str(e).lower():
+ logger.warning(
+ "Context length exceeded. Pruning half of the history and retrying is not implemented here, but history will be smaller next time."
+ )
+ self.history = self.history[len(self.history) // 2 :] # Prune half
+ yield {"type": "error", "content": str(e)}
+
+ def _chat_completions_urls(self) -> list[str]:
+ base = self.base_url.rstrip("/")
+ if base.endswith("/api"):
+ return [f"{base}/chat/completions"]
+ return [f"{base}/api/chat/completions"]
+
+ def _capture_chat_id(self, payload: Any) -> None:
+ chat_id = self._extract_chat_id(payload)
+ if not chat_id or chat_id == self.chat_id:
+ return
+ self.chat_id = chat_id
+ config.OPENWEBUI_CHAT_ID = chat_id
+ os.environ[keys.OPENWEBUI_CHAT_ID] = chat_id
+ window_start = self.current_chat_window_start()
+ config.OPENWEBUI_CHAT_WINDOW_START = window_start
+ os.environ[keys.OPENWEBUI_CHAT_WINDOW_START] = window_start
+ pending_reason = (
+ config.OPENWEBUI_CHAT_PENDING_REASON
+ or os.getenv(keys.OPENWEBUI_CHAT_PENDING_REASON, "")
+ ).strip()
+ pending_event_id = (
+ config.OPENWEBUI_CHAT_PENDING_EVENT_ID
+ or os.getenv(keys.OPENWEBUI_CHAT_PENDING_EVENT_ID, "")
+ ).strip()
+ append_chat_history(
+ "chat_id_received",
+ reason=pending_reason or "chat",
+ pending_event_id=pending_event_id,
+ new_chat_id=chat_id,
+ window_start=window_start,
+ )
+ config.OPENWEBUI_CHAT_PENDING_REASON = ""
+ config.OPENWEBUI_CHAT_PENDING_EVENT_ID = ""
+ os.environ[keys.OPENWEBUI_CHAT_PENDING_REASON] = ""
+ os.environ[keys.OPENWEBUI_CHAT_PENDING_EVENT_ID] = ""
+ self._persist_chat_state(chat_id, window_start, "", "")
+ logger.info("OpenWebUI chat_id learned from server: %s", chat_id)
+
+ @staticmethod
+ def _persist_chat_state(
+ chat_id: str,
+ window_start: str,
+ pending_reason: str = "",
+ pending_event_id: str = "",
+ ) -> None:
+ try:
+ STABLE_ENV_PATH.parent.mkdir(parents=True, exist_ok=True)
+ lines = STABLE_ENV_PATH.read_text(encoding="utf-8").splitlines() if STABLE_ENV_PATH.exists() else []
+ updates = {
+ keys.OPENWEBUI_CHAT_ID: chat_id,
+ keys.OPENWEBUI_CHAT_WINDOW_START: window_start,
+ keys.OPENWEBUI_CHAT_PENDING_REASON: pending_reason,
+ keys.OPENWEBUI_CHAT_PENDING_EVENT_ID: pending_event_id,
+ }
+ for env_name, value in updates.items():
+ entry = f"{env_name}={value}"
+ for index, line in enumerate(lines):
+ if line.strip().startswith(f"{env_name}="):
+ lines[index] = entry
+ break
+ else:
+ lines.append(entry)
+ STABLE_ENV_PATH.write_text("\n".join(lines) + "\n", encoding="utf-8")
+ except Exception as exc:
+ logger.debug("Could not persist OpenWebUI chat state: %s", exc)
+
+ @classmethod
+ def _extract_chat_id(cls, payload: Any) -> Optional[str]:
+ if not isinstance(payload, dict):
+ return None
+ for key in ("chat_id", "chatId", "conversation_id", "conversationId", "channel_id", "channelId"):
+ value = payload.get(key)
+ if isinstance(value, str) and value.strip():
+ return _normalize_chat_id(value)
+ for key in ("data", "chat"):
+ nested = payload.get(key)
+ if isinstance(nested, dict):
+ chat_id = cls._extract_chat_id(nested)
+ if chat_id:
+ return chat_id
+ return None
+
+ async def _stream_chat_completion(
+ self, client: httpx.AsyncClient, payload: dict[str, Any]
+ ) -> AsyncGenerator[Dict[str, Any], None]:
+ """POST the chat request and yield text/tool_delta events as they stream in."""
+ last_error: Optional[str] = None
+ for url in self._chat_completions_urls():
+ request = client.build_request("POST", url, headers=self._headers(), json=payload)
+ response = await client.send(request, stream=True)
+ try:
+ if response.status_code == 404:
+ logger.warning("OpenWebUI chat endpoint not found, trying fallback: %s", url)
+ continue
+ if response.status_code >= 400:
+ body = (await response.aread()).decode("utf-8", errors="replace")[:500]
+ last_error = f"HTTP {response.status_code}: {body}"
+ raise RuntimeError(f"OpenWebUI chat failed: {last_error}")
+
+ content_type = response.headers.get("content-type", "")
+ if "text/event-stream" not in content_type and "application/x-ndjson" not in content_type:
+ # Non-streaming JSON response (upstream ignored stream=true).
+ await response.aread()
+ for event in self._events_from_json_response(response):
+ yield event
+ return
+
+ saw_response_text_delta = False
+ async for line in response.aiter_lines():
+ line = line.strip()
+ if not line or not line.startswith("data:"):
+ continue
+ raw = line[5:].strip()
+ if raw == "[DONE]":
+ return
+ try:
+ data = json.loads(raw)
+ except Exception:
+ continue
+ delta = self._choice_delta(data)
+ if delta:
+ content = str(delta.get("content") or "")
+ if content:
+ yield {"type": "text", "content": content}
+ if delta.get("tool_calls"):
+ yield {"type": "tool_delta", "tool_calls": delta.get("tool_calls")}
+ continue
+ response_events = self._events_from_responses_stream(
+ data,
+ saw_text_delta=saw_response_text_delta,
+ )
+ for event in response_events:
+ if event.get("type") == "text":
+ saw_response_text_delta = True
+ yield event
+ return
+ finally:
+ await response.aclose()
+ raise RuntimeError(last_error or "No OpenWebUI chat completion endpoint is configured.")
+
+ @staticmethod
+ def _events_from_json_response(response: httpx.Response) -> list[dict[str, Any]]:
+ events: list[dict[str, Any]] = []
+ try:
+ data = response.json()
+ except Exception:
+ return events
+ choices = data.get("choices") if isinstance(data, dict) else None
+ first_choice = choices[0] if isinstance(choices, list) and choices else {}
+ message = first_choice.get("message") if isinstance(first_choice, dict) else {}
+ if not isinstance(message, dict):
+ message = {}
+ content = str(message.get("content") or "")
+ if content:
+ events.append({"type": "text", "content": content})
+ if message.get("tool_calls"):
+ events.append({"type": "tool_delta", "tool_calls": message.get("tool_calls")})
+ return events
+
+ @classmethod
+ def _events_from_responses_stream(
+ cls,
+ payload: Any,
+ *,
+ saw_text_delta: bool = False,
+ ) -> list[dict[str, Any]]:
+ """Convert Responses API stream payloads into the app's text events."""
+ if not isinstance(payload, dict):
+ return []
+ event_type = str(payload.get("type") or "")
+ if event_type == "response.output_text.delta":
+ delta = payload.get("delta")
+ return [{"type": "text", "content": delta}] if isinstance(delta, str) and delta else []
+ if saw_text_delta:
+ return []
+ if event_type == "response.output_text.done":
+ text = payload.get("text")
+ return [{"type": "text", "content": text}] if isinstance(text, str) and text else []
+ if event_type == "response.completed":
+ text = cls._response_completed_text(payload.get("response"))
+ return [{"type": "text", "content": text}] if text else []
+ return []
+
+ @classmethod
+ def _response_completed_text(cls, response: Any) -> str:
+ if not isinstance(response, dict):
+ return ""
+ parts: list[str] = []
+ output = response.get("output")
+ if not isinstance(output, list):
+ return ""
+ for item in output:
+ if not isinstance(item, dict) or item.get("type") != "message":
+ continue
+ content = item.get("content")
+ if not isinstance(content, list):
+ continue
+ for part in content:
+ if not isinstance(part, dict):
+ continue
+ text = part.get("text") or part.get("content") or part.get("output_text")
+ if isinstance(text, str):
+ parts.append(text)
+ return "".join(parts)
+
+ async def _post_chat_completion(self, client: httpx.AsyncClient, payload: dict[str, Any]) -> httpx.Response:
+ last_response: Optional[httpx.Response] = None
+ for url in self._chat_completions_urls():
+ response = await client.post(url, headers=self._headers(), json=payload)
+ if response.status_code == 404:
+ logger.warning("OpenWebUI chat endpoint not found, trying fallback: %s", url)
+ last_response = response
+ continue
+ response.raise_for_status()
+ if last_response is not None:
+ logger.info("OpenWebUI chat endpoint selected: %s", url)
+ return response
+ if last_response is not None:
+ last_response.raise_for_status()
+ raise RuntimeError("No OpenWebUI chat completion endpoint is configured.")
+
+ async def load_voice_context(self) -> None:
+ """Load the same OpenWebUI context endpoints the browser loads when voice mode opens."""
+ if self._voice_context_loaded:
+ return
+ async with httpx.AsyncClient(timeout=20.0) as client:
+ await self._load_openwebui_context(client)
+ self._voice_context_loaded = True
+
+ async def _load_openwebui_context(self, client: httpx.AsyncClient) -> None:
+ context_targets = (
+ ("tools", f"{self._api_root()}/v1/tools/"),
+ ("skills", f"{self._api_root()}/v1/skills/"),
+ ("functions", f"{self._api_root()}/v1/functions/"),
+ )
+ for name, endpoint in context_targets:
+ try:
+ response = await client.get(endpoint, headers=self._headers())
+ if response.status_code in {401, 403, 404, 405}:
+ logger.debug("OpenWebUI voice context skipped: %s status=%s", endpoint, response.status_code)
+ continue
+ response.raise_for_status()
+ data = response.json()
+ items = data if isinstance(data, list) else data.get("data", []) if isinstance(data, dict) else []
+ if not isinstance(items, list):
+ items = []
+ if name == "tools":
+ self._openwebui_tools = [item for item in items if isinstance(item, dict)]
+ elif name == "skills":
+ self._openwebui_skills = [item for item in items if isinstance(item, dict)]
+ elif name == "functions":
+ self._openwebui_functions = [item for item in items if isinstance(item, dict)]
+ logger.info("OpenWebUI voice context loaded: %s=%d", name, len(items))
+ except Exception as exc:
+ logger.debug("OpenWebUI voice context failed: %s: %s", endpoint, exc)
+
+ async def _restore_latest_parent_message_id(self, client: httpx.AsyncClient) -> None:
+ _, message_id = await self._fetch_latest_chat_assistant_message(client)
+ if message_id:
+ self._last_message_id = message_id
+ logger.info("OpenWebUI parent message restored from chat history: %s", message_id)
+
+ async def _poll_latest_chat_assistant_message(
+ self,
+ client: httpx.AsyncClient,
+ *,
+ previous_parent_id: Optional[str],
+ expected_message_id: str,
+ user_message_id: Optional[str] = None,
+ ) -> tuple[str, str]:
+ last_content = ""
+ last_message_id = ""
+ for attempt in range(10):
+ payload = await self._fetch_chat_payload(client)
+ content, message_id = self._assistant_message_for_turn(
+ payload,
+ user_message_id=user_message_id,
+ expected_message_id=expected_message_id,
+ )
+ if content:
+ logger.info(
+ "OpenWebUI saved response matched turn: user_message_id=%s assistant_id=%s",
+ user_message_id or "",
+ message_id or "",
+ )
+ return content, message_id
+
+ content, message_id = self._latest_assistant_message(payload)
+ if content:
+ last_content = content
+ if message_id:
+ last_message_id = message_id
+ if user_message_id:
+ await asyncio.sleep(0.5)
+ continue
+ if content and (
+ message_id == expected_message_id
+ or (message_id and message_id != previous_parent_id)
+ or attempt >= 2
+ ):
+ return content, message_id
+ await asyncio.sleep(0.5)
+ if user_message_id:
+ logger.warning(
+ "OpenWebUI saved response was not linked to user_message_id=%s; refusing latest-chat fallback.",
+ user_message_id,
+ )
+ return "", ""
+ return last_content, last_message_id
+
+ async def _fetch_latest_chat_assistant_message(self, client: httpx.AsyncClient) -> tuple[str, str]:
+ return self._latest_assistant_message(await self._fetch_chat_payload(client))
+
+ async def _fetch_chat_payload(self, client: httpx.AsyncClient) -> Any:
+ chat_id = _normalize_chat_id(self.chat_id)
+ if not chat_id:
+ return {}
+ url = f"{self._api_root()}/v1/chats/{chat_id}"
+ try:
+ response = await client.get(url, headers=self._headers())
+ if response.status_code in {401, 403}:
+ logger.warning("OpenWebUI saved chat %s is not accessible; clearing chat_id.", chat_id)
+ self.clear_chat_id(
+ window_start=config.OPENWEBUI_CHAT_WINDOW_START or self.current_chat_window_start(),
+ pending_reason="chat_fetch_unauthorized",
+ pending_event_id="",
+ )
+ return {}
+ response.raise_for_status()
+ return response.json()
+ except Exception as exc:
+ logger.debug("OpenWebUI saved chat fallback failed: %s", exc)
+ return {}
+
+ async def _recover_latest_chat_id(self, client: httpx.AsyncClient) -> str:
+ url = f"{self._api_root()}/v1/chats/?page=1"
+ try:
+ response = await client.get(url, headers=self._headers())
+ response.raise_for_status()
+ chat_id = self._latest_chat_id_from_list(response.json())
+ if chat_id:
+ logger.info("OpenWebUI chat_id recovered from chat list: %s", chat_id)
+ else:
+ logger.warning("OpenWebUI chat list returned no recoverable chat id.")
+ return chat_id
+ except Exception as exc:
+ logger.warning("OpenWebUI chat_id recovery failed: %s", exc)
+ return ""
+
+ @classmethod
+ def _latest_chat_id_from_list(cls, payload: Any) -> str:
+ if isinstance(payload, dict):
+ for key in ("data", "chats", "items", "results"):
+ value = payload.get(key)
+ if isinstance(value, list):
+ return cls._latest_chat_id_from_list(value)
+ chat_id = cls._extract_chat_id(payload)
+ return chat_id or ""
+
+ if not isinstance(payload, list):
+ return ""
+
+ best_id = ""
+ best_time = float("-inf")
+ first_id = ""
+ for item in payload:
+ if not isinstance(item, dict):
+ continue
+ chat_id = cls._extract_chat_list_item_id(item)
+ if not chat_id:
+ continue
+ if not first_id:
+ first_id = chat_id
+ timestamp = cls._chat_sort_timestamp(item)
+ if timestamp > best_time:
+ best_time = timestamp
+ best_id = chat_id
+ return best_id or first_id
+
+ @staticmethod
+ def _chat_sort_timestamp(item: dict[str, Any]) -> float:
+ for key in ("updated_at", "created_at", "timestamp", "time"):
+ value = item.get(key)
+ if isinstance(value, (int, float)):
+ return float(value)
+ if isinstance(value, str) and value.strip():
+ try:
+ return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
+ except Exception:
+ continue
+ return 0.0
+
+ @classmethod
+ def _extract_chat_list_item_id(cls, item: dict[str, Any]) -> str:
+ chat_id = cls._extract_chat_id(item)
+ if chat_id:
+ return chat_id
+ value = item.get("id")
+ return _normalize_chat_id(value) if isinstance(value, str) and value.strip() else ""
+
+ @classmethod
+ def _latest_assistant_message(cls, payload: Any) -> tuple[str, str]:
+ messages: list[tuple[str, str, float, int]] = []
+ order = 0
+
+ def walk(value: Any) -> None:
+ nonlocal order
+ if isinstance(value, dict):
+ role = str(value.get("role") or "").lower()
+ content = cls._assistant_text_from_message(value) if role == "assistant" else ""
+ if content:
+ order += 1
+ message_id = str(value.get("id") or value.get("message_id") or "").strip()
+ timestamp = cls._chat_sort_timestamp(value)
+ messages.append((content, message_id, timestamp, order))
+ for nested in value.values():
+ walk(nested)
+ elif isinstance(value, list):
+ for item in value:
+ walk(item)
+
+ walk(payload)
+ if not messages:
+ return "", ""
+ content, message_id, _, _ = max(messages, key=lambda item: (item[2], item[3]))
+ return content, message_id
+
+ @classmethod
+ def _assistant_message_for_turn(
+ cls,
+ payload: Any,
+ *,
+ user_message_id: Optional[str],
+ expected_message_id: str,
+ ) -> tuple[str, str]:
+ message_map = cls._message_map(payload)
+
+ def assistant_content(message_id: Optional[str]) -> tuple[str, str]:
+ if not message_id:
+ return "", ""
+ message = message_map.get(str(message_id))
+ if not isinstance(message, dict):
+ return "", ""
+ role = str(message.get("role") or "").lower()
+ content = cls._assistant_text_from_message(message) if role == "assistant" else ""
+ if content:
+ return content, str(message.get("id") or message_id)
+ return "", ""
+
+ content, message_id = assistant_content(expected_message_id)
+ if content:
+ return content, message_id
+
+ if user_message_id:
+ user_message = message_map.get(str(user_message_id))
+ if isinstance(user_message, dict):
+ children = user_message.get("childrenIds") or user_message.get("children_ids") or []
+ if isinstance(children, list):
+ for child_id in children:
+ content, message_id = assistant_content(str(child_id))
+ if content:
+ return content, message_id
+
+ for candidate in message_map.values():
+ if not isinstance(candidate, dict):
+ continue
+ if str(candidate.get("parentId") or candidate.get("parent_id") or "") == str(user_message_id):
+ content, message_id = assistant_content(str(candidate.get("id") or candidate.get("message_id") or ""))
+ if content:
+ return content, message_id
+
+ return "", ""
+
+ @staticmethod
+ def _assistant_text_from_message(message: dict[str, Any]) -> str:
+ output = message.get("output")
+ if isinstance(output, list):
+ parts: list[str] = []
+ for item in output:
+ if not isinstance(item, dict) or item.get("type") != "message":
+ continue
+ content = item.get("content")
+ if not isinstance(content, list):
+ continue
+ for part in content:
+ if not isinstance(part, dict):
+ continue
+ if part.get("type") != "output_text":
+ continue
+ text = part.get("text")
+ if isinstance(text, str) and text.strip():
+ parts.append(text.strip())
+ if parts:
+ return "\n".join(parts).strip()
+
+ content = message.get("content")
+ return content.strip() if isinstance(content, str) and content.strip() else ""
+
+ @staticmethod
+ def _message_map(payload: Any) -> dict[str, dict[str, Any]]:
+ messages: dict[str, dict[str, Any]] = {}
+
+ def add_message(value: Any) -> None:
+ if not isinstance(value, dict):
+ return
+ message_id = str(value.get("id") or value.get("message_id") or "").strip()
+ role = str(value.get("role") or "").lower()
+ if message_id and role in {"user", "assistant", "tool"}:
+ messages[message_id] = value
+
+ def walk(value: Any) -> None:
+ if isinstance(value, dict):
+ add_message(value)
+ for nested in value.values():
+ walk(nested)
+ elif isinstance(value, list):
+ for item in value:
+ walk(item)
+
+ walk(payload)
+ return messages
+
+ def _headers(self) -> dict[str, str]:
+ headers = {
+ "Accept": "application/json, text/event-stream",
+ "Content-Type": "application/json",
+ "User-Agent": config.OPENWEBUI_USER_AGENT,
+ }
+ if self.auth_token and self.auth_token != "ollama":
+ headers["Authorization"] = f"Bearer {self.auth_token}"
+ return headers
+
+ def _api_root(self) -> str:
+ base = self.base_url.rstrip("/")
+ if base.endswith("/api/v1"):
+ return base[:-3]
+ if base.endswith("/api"):
+ return base
+ return f"{base}/api"
+
+ async def _get_model_item(self) -> Optional[dict[str, Any]]:
+ if self._model_item is not None:
+ return self._model_item
+ model = (self.model or "").strip()
+ if not model:
+ return None
+ query = urlencode({"id": model})
+ quoted_model = quote(model, safe="")
+ endpoints = [
+ f"{self._api_root()}/v1/models/model?{query}",
+ f"{self._api_root()}/models/model?{query}",
+ f"{self._api_root()}/v1/models/{quoted_model}",
+ f"{self._api_root()}/models/{quoted_model}",
+ f"{self._api_root()}/models",
+ f"{self._api_root()}/v1/models",
+ ]
+ try:
+ async with httpx.AsyncClient(timeout=12.0) as client:
+ for endpoint in dict.fromkeys(endpoints):
+ response = await client.get(endpoint, headers=self._headers())
+ if response.status_code in {401, 403, 404, 405}:
+ logger.debug("OpenWebUI model metadata skipped: %s status=%s", endpoint, response.status_code)
+ continue
+ response.raise_for_status()
+ data = response.json()
+ items = self._model_items_from_payload(data)
+ for item in items:
+ if self._model_item_matches(item, model):
+ self._model_item = item
+ logger.info("OpenWebUI model metadata loaded for %s from %s", model, endpoint)
+ return item
+ if "/models/model?" in endpoint:
+ detail_item = self._best_model_detail_item(items)
+ if detail_item:
+ self._model_item = detail_item
+ logger.info("OpenWebUI model detail loaded for %s from %s", model, endpoint)
+ return detail_item
+ except Exception as exc:
+ logger.warning("OpenWebUI model metadata unavailable: %s", exc)
+ return None
+
+ async def get_model_tts_voice(self) -> str:
+ model_item = await self._get_model_item()
+ voice = self._extract_model_tts_voice(model_item)
+ if voice:
+ logger.info("OpenWebUI model TTS voice loaded for %s: %s", self.model or "", voice)
+ else:
+ logger.info("OpenWebUI model TTS voice not set for %s.", self.model or "")
+ return voice
+
+ @classmethod
+ def _extract_model_tts_voice(cls, model_item: Optional[dict[str, Any]]) -> str:
+ paths = (
+ ("meta", "tts", "voice"),
+ ("meta", "tts", "voice_id"),
+ ("meta", "tts_voice"),
+ ("meta", "ttsVoice"),
+ ("meta", "audio", "tts", "voice"),
+ ("meta", "audio", "voice"),
+ ("info", "meta", "tts", "voice"),
+ ("info", "meta", "tts", "voice_id"),
+ ("info", "meta", "tts_voice"),
+ ("info", "meta", "ttsVoice"),
+ ("info", "meta", "audio", "tts", "voice"),
+ ("info", "meta", "audio", "voice"),
+ ("info", "params", "tts", "voice"),
+ ("info", "params", "voice"),
+ ("params", "tts", "voice"),
+ ("params", "voice"),
+ ("tts", "voice"),
+ ("audio", "tts", "voice"),
+ ("audio", "voice"),
+ ("meta", "voice"),
+ ("info", "meta", "voice"),
+ ("tts_voice",),
+ ("ttsVoice",),
+ ("voice",),
+ )
+ for path in paths:
+ value = cls._nested_value(model_item, path)
+ voice = cls._coerce_voice_value(value)
+ if voice:
+ return voice
+ return cls._find_voice_value(model_item)
+
+ @classmethod
+ def _model_items_from_payload(cls, payload: Any) -> list[dict[str, Any]]:
+ items: list[dict[str, Any]] = []
+
+ def collect(value: Any) -> None:
+ if isinstance(value, list):
+ for item in value:
+ collect(item)
+ return
+ if not isinstance(value, dict):
+ return
+ items.append(value)
+ for key in ("data", "model", "models", "item", "result"):
+ nested = value.get(key)
+ if nested is not value:
+ collect(nested)
+
+ collect(payload)
+ return items
+
+ @staticmethod
+ def _model_item_matches(item: Any, model: str) -> bool:
+ if not isinstance(item, dict):
+ return False
+ expected = model.strip()
+ for key in ("id", "name", "model", "model_id", "base_model_id"):
+ value = item.get(key)
+ if value is not None and str(value).strip() == expected:
+ return True
+ return False
+
+ @staticmethod
+ def _best_model_detail_item(items: list[dict[str, Any]]) -> Optional[dict[str, Any]]:
+ for item in reversed(items):
+ if not isinstance(item, dict):
+ continue
+ if any(key in item for key in ("meta", "info", "params", "tts", "voice", "audio")):
+ return item
+ return None
+
+ @classmethod
+ def _coerce_voice_value(cls, value: Any) -> str:
+ if isinstance(value, str):
+ return value.strip()
+ if isinstance(value, dict):
+ for key in ("id", "name", "value", "voice", "voice_id", "voiceId"):
+ voice = cls._coerce_voice_value(value.get(key))
+ if voice:
+ return voice
+ return ""
+
+ @classmethod
+ def _find_voice_value(cls, value: Any, *, in_voice_context: bool = False, depth: int = 0) -> str:
+ if depth > 8:
+ return ""
+ if isinstance(value, dict):
+ for key, nested in value.items():
+ normalized_key = str(key).replace("-", "_").lower()
+ if normalized_key in {"voice", "voice_id", "voiceid", "tts_voice", "ttsvoice"}:
+ voice = cls._coerce_voice_value(nested)
+ if voice:
+ return voice
+ for key, nested in value.items():
+ normalized_key = str(key).replace("-", "_").lower()
+ next_context = (
+ in_voice_context
+ or normalized_key in {"meta", "info", "params", "settings", "profile", "audio", "speech", "tts"}
+ or "voice" in normalized_key
+ or "tts" in normalized_key
+ or "speech" in normalized_key
+ or "audio" in normalized_key
+ )
+ if next_context:
+ voice = cls._find_voice_value(nested, in_voice_context=next_context, depth=depth + 1)
+ if voice:
+ return voice
+ elif isinstance(value, list) and in_voice_context:
+ for item in value:
+ voice = cls._find_voice_value(item, in_voice_context=True, depth=depth + 1)
+ if voice:
+ return voice
+ return ""
+
+ @staticmethod
+ def _nested_value(value: Any, path: tuple[str, ...]) -> Any:
+ current = value
+ for key in path:
+ if not isinstance(current, dict):
+ return None
+ current = current.get(key)
+ return current
+
+ @staticmethod
+ def _model_tool_ids(model_item: Optional[dict[str, Any]]) -> list[str]:
+ if not isinstance(model_item, dict):
+ return []
+ candidates: list[Any] = []
+ meta = model_item.get("meta")
+ if isinstance(meta, dict):
+ candidates.append(meta.get("toolIds"))
+ candidates.append(meta.get("tool_ids"))
+ info = model_item.get("info")
+ if isinstance(info, dict):
+ info_meta = info.get("meta")
+ if isinstance(info_meta, dict):
+ candidates.append(info_meta.get("toolIds"))
+ candidates.append(info_meta.get("tool_ids"))
+ for candidate in candidates:
+ if isinstance(candidate, list):
+ return [str(item).strip() for item in candidate if str(item).strip()]
+ return []
+
+ @staticmethod
+ def _variables() -> dict[str, str]:
+ now = time.localtime()
+ return {
+ "{{CURRENT_DATE}}": time.strftime("%Y-%m-%d", now),
+ "{{CURRENT_TIME}}": time.strftime("%H:%M:%S", now),
+ "{{CURRENT_DATETIME}}": time.strftime("%Y-%m-%d %H:%M:%S", now),
+ "{{CURRENT_WEEKDAY}}": time.strftime("%A", now),
+ "{{CURRENT_TIMEZONE}}": config.OPENWEBUI_USER_TIMEZONE,
+ "{{USER_NAME}}": config.OPENWEBUI_USER_NAME,
+ "{{USER_EMAIL}}": config.OPENWEBUI_USER_EMAIL,
+ "{{USER_LANGUAGE}}": config.OPENWEBUI_USER_LANGUAGE,
+ "{{USER_LOCATION}}": config.OPENWEBUI_USER_LOCATION,
+ }
+
+ @staticmethod
+ def _is_task_socket_response(response: httpx.Response) -> bool:
+ content_type = response.headers.get("content-type", "")
+ if "application/json" not in content_type:
+ return False
+ try:
+ data = response.json()
+ except Exception:
+ return False
+ if not isinstance(data, dict):
+ return False
+ return bool(data.get("task_id") or data.get("task_ids"))
+
+ async def _socket_events(
+ self,
+ *,
+ message_id: str,
+ session_id: Optional[str],
+ first_event_timeout: float = 30.0,
+ idle_timeout: float = 30.0,
+ ) -> AsyncGenerator[tuple[dict[str, Any], Optional[Callable[[Any], None]]], None]:
+ # Timeouts are inactivity-based, not a total-stream deadline: a long answer
+ # or a cold model must not cut the stream mid-response. The caller breaks
+ # on done/chat:active=false; a genuine stall raises TimeoutError and the
+ # caller falls back to polling saved chat history.
+ timeout = first_event_timeout
+ while True:
+ event, ack = await self.socket.next_event(timeout=timeout)
+ timeout = idle_timeout
+ incoming_session = self._extract_session_id(event)
+ incoming_message = self._extract_message_id(event)
+ if incoming_session and session_id and incoming_session != session_id:
+ continue
+ if incoming_message and str(incoming_message) != message_id:
+ logger.debug("Skipping stale OpenWebUI socket event for message_id=%s", incoming_message)
+ continue
+ yield event, ack
+
+ @staticmethod
+ def _event_type(event: tuple[dict[str, Any], Optional[Callable[[Any], None]]]) -> str:
+ data = event[0].get("data")
+ if isinstance(data, dict):
+ return str(data.get("type") or "")
+ return ""
+
+ @staticmethod
+ def _event_payload(event: tuple[dict[str, Any], Optional[Callable[[Any], None]]]) -> Any:
+ data = event[0].get("data")
+ if isinstance(data, dict):
+ return data.get("data")
+ return None
+
+ @staticmethod
+ def _extract_session_id(event: dict[str, Any]) -> Optional[str]:
+ candidate = event.get("session_id") or event.get("sessionId")
+ data = event.get("data")
+ if not candidate and isinstance(data, dict):
+ candidate = data.get("session_id") or data.get("sessionId")
+ inner = data.get("data")
+ if not candidate and isinstance(inner, dict):
+ candidate = inner.get("session_id") or inner.get("sessionId")
+ return str(candidate) if candidate else None
+
+ @staticmethod
+ def _extract_message_id(event: dict[str, Any]) -> Optional[str]:
+ candidates: list[Any] = [
+ event.get("message_id"),
+ event.get("messageId"),
+ ]
+ data = event.get("data")
+ if isinstance(data, dict):
+ candidates.extend([data.get("message_id"), data.get("messageId")])
+ inner = data.get("data")
+ if isinstance(inner, dict):
+ candidates.extend(
+ [
+ inner.get("message_id"),
+ inner.get("messageId"),
+ inner.get("id"),
+ ]
+ )
+ for candidate in candidates:
+ if isinstance(candidate, str) and candidate.strip():
+ return candidate.strip()
+ return None
+
+ @staticmethod
+ def _content_from_payload(payload: Any) -> str:
+ if isinstance(payload, dict):
+ content = payload.get("content")
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ parts: list[str] = []
+ for item in content:
+ if isinstance(item, str):
+ parts.append(item)
+ elif isinstance(item, dict):
+ text = item.get("text") or item.get("content")
+ if isinstance(text, str):
+ parts.append(text)
+ return "".join(parts)
+ return ""
+
+ @staticmethod
+ def _choice_delta(payload: Any) -> Optional[dict[str, Any]]:
+ if not isinstance(payload, dict):
+ return None
+ choices = payload.get("choices")
+ if not isinstance(choices, list) or not choices:
+ return None
+ choice = choices[0]
+ if not isinstance(choice, dict):
+ return None
+ delta = choice.get("delta")
+ return delta if isinstance(delta, dict) else None
+
+ @staticmethod
+ def _error_from_payload(payload: Any) -> str:
+ if isinstance(payload, dict):
+ raw_error = payload.get("error")
+ if isinstance(raw_error, dict):
+ return str(raw_error.get("content") or raw_error.get("message") or "")
+ if raw_error:
+ return str(raw_error)
+ return str(payload.get("message") or "")
+ return str(payload or "")
+
+ @staticmethod
+ def _collect_tool_calls(
+ raw_tool_calls: Any,
+ tool_calls_buffer: Dict[int, Any],
+ stream_to_buffer: Dict[int, int],
+ ) -> None:
+ if not isinstance(raw_tool_calls, list):
+ return
+ for tc in raw_tool_calls:
+ if not isinstance(tc, dict):
+ continue
+ stream_idx = int(tc.get("index") or 0)
+ buf_idx = stream_to_buffer.get(stream_idx, stream_idx)
+ fn = tc.get("function") if isinstance(tc.get("function"), dict) else {}
+ if (
+ buf_idx in tool_calls_buffer
+ and fn.get("name")
+ and tool_calls_buffer[buf_idx]["function"]["name"]
+ ):
+ buf_idx = (max(tool_calls_buffer.keys()) + 1) if tool_calls_buffer else 0
+ stream_to_buffer[stream_idx] = buf_idx
+ if buf_idx not in tool_calls_buffer:
+ tool_calls_buffer[buf_idx] = {
+ "id": tc.get("id") or f"call_{buf_idx}",
+ "type": "function",
+ "function": {"name": "", "arguments": ""},
+ }
+ stream_to_buffer[stream_idx] = buf_idx
+ if tc.get("id"):
+ tool_calls_buffer[buf_idx]["id"] = tc["id"]
+ if fn.get("name"):
+ tool_calls_buffer[buf_idx]["function"]["name"] += str(fn["name"])
+ if fn.get("arguments"):
+ tool_calls_buffer[buf_idx]["function"]["arguments"] += str(fn["arguments"])
+
+ async def _http_stream_events(self, response: httpx.Response) -> AsyncGenerator[dict[str, Any], None]:
+ content_type = response.headers.get("content-type", "")
+ if "application/json" in content_type:
+ data = response.json()
+ chat_id = self._extract_chat_id(data)
+ if chat_id:
+ yield {"type": "meta", "chat_id": chat_id}
+ choices = data.get("choices") if isinstance(data, dict) else None
+ first_choice = choices[0] if isinstance(choices, list) and choices else {}
+ message = first_choice.get("message") if isinstance(first_choice, dict) else {}
+ if not isinstance(message, dict):
+ message = {}
+ content = str(message.get("content") or "")
+ if content:
+ yield {"type": "text", "content": content}
+ tool_calls = message.get("tool_calls")
+ if tool_calls:
+ yield {"type": "tool_delta", "tool_calls": tool_calls}
+ return
+
+ async for line in response.aiter_lines():
+ line = line.strip()
+ if not line or not line.startswith("data:"):
+ continue
+ raw = line[5:].strip()
+ if raw == "[DONE]":
+ break
+ try:
+ data = json.loads(raw)
+ except Exception:
+ continue
+ chat_id = self._extract_chat_id(data)
+ if chat_id:
+ yield {"type": "meta", "chat_id": chat_id}
+ delta = self._choice_delta(data)
+ if not delta:
+ continue
+ content = str(delta.get("content") or "")
+ if content:
+ yield {"type": "text", "content": content}
+ if delta.get("tool_calls"):
+ yield {"type": "tool_delta", "tool_calls": delta.get("tool_calls")}
diff --git a/src/Reachy_OpenWebUI/sub_apps/conversation_app/local/tts.py b/src/Reachy_OpenWebUI/sub_apps/conversation_app/local/tts.py
new file mode 100644
index 0000000000000000000000000000000000000000..afb8a8f7a07aa808b8f40ff45542633f3da06bcc
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/conversation_app/local/tts.py
@@ -0,0 +1,218 @@
+import io
+import json
+import logging
+import wave
+from collections import deque
+from typing import Tuple
+from urllib.parse import urlparse, urlunparse
+
+import av
+import httpx
+import numpy as np
+from scipy.signal import resample
+
+from Reachy_OpenWebUI.config import config
+
+
+logger = logging.getLogger(__name__)
+
+
+def _dedupe_urls(urls: list[str]) -> list[str]:
+ seen: set[str] = set()
+ clean: list[str] = []
+ for url in urls:
+ normalized = url.strip().rstrip("/")
+ if normalized and normalized not in seen:
+ seen.add(normalized)
+ clean.append(normalized)
+ return clean
+
+
+def _openwebui_audio_candidates(root_url: str, suffix: str) -> list[str]:
+ root = (root_url or "").strip().rstrip("/")
+ if not root:
+ return []
+ suffix = suffix.strip("/")
+ if root.endswith("/api"):
+ return _dedupe_urls([f"{root}/v1/{suffix}", f"{root}/{suffix}"])
+ return _dedupe_urls([
+ f"{root}/api/v1/{suffix}",
+ f"{root}/api/{suffix}",
+ f"{root}/v1/{suffix}",
+ f"{root}/{suffix}",
+ ])
+
+
+def _openwebui_root() -> str:
+ base_url = (config.OPENWEBUI_URL or "").rstrip("/")
+ if base_url.endswith("/api"):
+ base_url = base_url[:-4]
+ return base_url
+
+
+def _origin_from_url(url: str) -> str:
+ parsed = urlparse(url)
+ if not parsed.scheme or not parsed.netloc:
+ return ""
+ return urlunparse((parsed.scheme, parsed.netloc, "", "", "", ""))
+
+
+class OpenWebUISpeech:
+ """OpenWebUI audio speech wrapper.
+
+ OpenWebUI owns the speech engine/model. When the selected model/contact
+ declares a voice, that value is sent with the speech request.
+ """
+
+ def __init__(self, openwebui_url: str | None = None, model: str | None = None, voice: str | None = None):
+ self.openwebui_url = (openwebui_url or _openwebui_root()).rstrip("/")
+ self.model = model or "tts-1"
+ self.voice = (voice or "").strip()
+ self._recent_audio: deque[bytes] = deque(maxlen=6)
+ if not self.openwebui_url:
+ logger.warning("OpenWebUI URL is not configured for speech output")
+ else:
+ logger.info(
+ "OpenWebUI speech output configured: %s%s",
+ self.openwebui_url,
+ f" voice={self.voice}" if self.voice else "",
+ )
+
+ async def synthesize(self, text: str, speed: float = 1.0) -> Tuple[int, np.ndarray]:
+ """Synthesize text to audio through OpenWebUI. Returns (sample_rate, mono audio_float32)."""
+ text = (text or "").strip()
+ if not text or not self.openwebui_url:
+ return 24000, np.zeros(0, dtype=np.float32)
+
+ base_payload: dict[str, object] = {"input": text}
+ if self.voice:
+ base_payload["voice"] = self.voice
+ if speed != 1.0:
+ base_payload["speed"] = speed
+
+ origin = _origin_from_url(self.openwebui_url)
+ headers = {
+ "Accept": "*/*",
+ "Content-Type": "application/json",
+ "Accept-Language": "en-US,en;q=0.9",
+ "User-Agent": config.OPENWEBUI_USER_AGENT,
+ }
+ if origin:
+ headers["Origin"] = origin
+ headers["Referer"] = f"{origin}/"
+ auth_token = (config.OPENWEBUI_TOKEN or config.OPENWEBUI_API_KEY or "").strip()
+ if auth_token and auth_token != "ollama":
+ headers["Authorization"] = f"Bearer {auth_token}"
+
+ async def _fetch_audio(speech_payload: dict[str, object]) -> tuple[bytes, str]:
+ last_body = ""
+ read_timeout = max(3.0, float(config.OPENWEBUI_TTS_READ_TIMEOUT))
+ timeout = httpx.Timeout(connect=10.0, read=read_timeout, write=20.0, pool=10.0)
+ async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client:
+ for url in _openwebui_audio_candidates(self.openwebui_url, "audio/speech"):
+ try:
+ response = await client.post(url, headers=headers, json=speech_payload)
+ except httpx.TimeoutException as exc:
+ logger.warning("OpenWebUI speech timed out at %s: %s", url, exc)
+ continue
+
+ if response.status_code in (404, 405):
+ logger.info("OpenWebUI speech endpoint unavailable (%s): %s", response.status_code, url)
+ continue
+
+ if response.status_code >= 400:
+ last_body = response.text[:1000]
+ raise RuntimeError(f"OpenWebUI speech HTTP {response.status_code}: {last_body}")
+
+ return response.content, response.headers.get("content-type", "")
+
+ raise RuntimeError(f"OpenWebUI speech endpoint not found: {last_body}")
+
+ try:
+ logger.info(
+ "Requesting OpenWebUI speech: text=%r voice=%s",
+ text,
+ self.voice or "",
+ )
+ audio_bytes, content_type = await _fetch_audio(base_payload)
+ if not audio_bytes:
+ raise RuntimeError("OpenWebUI speech returned empty response body")
+ self._recent_audio.append(audio_bytes)
+ sample_rate, audio = self._decode_audio_bytes(audio_bytes, content_type)
+ if sample_rate != 24000 and audio.size:
+ target_len = max(1, int(round(audio.size * 24000 / sample_rate)))
+ audio = resample(audio, target_len).astype(np.float32)
+ sample_rate = 24000
+ return sample_rate, np.clip(audio, -1.0, 1.0).astype(np.float32)
+ except Exception as exc:
+ logger.error("OpenWebUI speech synthesis failed: %s", exc)
+ return 24000, np.zeros(0, dtype=np.float32)
+
+ @staticmethod
+ def _decode_audio_bytes(audio_bytes: bytes, content_type: str = "") -> tuple[int, np.ndarray]:
+ """Decode OpenWebUI speech bytes. Browser voice commonly returns audio/mpeg."""
+ if not audio_bytes:
+ return 24000, np.zeros(0, dtype=np.float32)
+
+ try:
+ return OpenWebUISpeech._decode_with_av(audio_bytes)
+ except Exception as exc:
+ logger.debug("PyAV audio decode failed (%s), trying WAV fallback", exc)
+
+ try:
+ with wave.open(io.BytesIO(audio_bytes), "rb") as wav:
+ sample_rate = wav.getframerate()
+ channels = wav.getnchannels()
+ sample_width = wav.getsampwidth()
+ frames = wav.readframes(wav.getnframes())
+
+ if sample_width == 2:
+ audio = np.frombuffer(frames, dtype=np.int16).astype(np.float32) / 32768.0
+ elif sample_width == 4:
+ audio = np.frombuffer(frames, dtype=np.int32).astype(np.float32) / 2147483648.0
+ else:
+ audio = np.frombuffer(frames, dtype=np.uint8).astype(np.float32)
+ audio = (audio - 128.0) / 128.0
+
+ if channels > 1:
+ audio = audio.reshape(-1, channels).mean(axis=1)
+
+ logger.info("Decoded OpenWebUI speech as WAV (%s, %d bytes)", content_type or "unknown", len(audio_bytes))
+ return sample_rate, np.clip(audio, -1.0, 1.0).astype(np.float32)
+ except Exception as exc:
+ raise RuntimeError(
+ f"Could not decode OpenWebUI speech audio ({content_type or 'unknown'}, {len(audio_bytes)} bytes)"
+ ) from exc
+
+ @staticmethod
+ def _decode_with_av(audio_bytes: bytes) -> tuple[int, np.ndarray]:
+ container = av.open(io.BytesIO(audio_bytes))
+ chunks: list[np.ndarray] = []
+ sample_rate = 24000
+ try:
+ for frame in container.decode(audio=0):
+ sample_rate = int(frame.sample_rate or sample_rate)
+ arr = frame.to_ndarray()
+ if arr.ndim > 1:
+ arr = arr.mean(axis=0)
+ if np.issubdtype(arr.dtype, np.floating):
+ chunk = arr.astype(np.float32)
+ elif arr.dtype == np.int16:
+ chunk = arr.astype(np.float32) / 32768.0
+ elif arr.dtype == np.int32:
+ chunk = arr.astype(np.float32) / 2147483648.0
+ elif arr.dtype == np.uint8:
+ chunk = (arr.astype(np.float32) - 128.0) / 128.0
+ else:
+ info = np.iinfo(arr.dtype) if np.issubdtype(arr.dtype, np.integer) else None
+ scale = float(max(abs(info.min), info.max)) if info else 1.0
+ chunk = arr.astype(np.float32) / scale
+ chunks.append(chunk.reshape(-1))
+ finally:
+ container.close()
+
+ if not chunks:
+ return sample_rate, np.zeros(0, dtype=np.float32)
+ audio = np.concatenate(chunks).astype(np.float32)
+ logger.info("Decoded OpenWebUI speech with PyAV: %d samples at %d Hz", audio.size, sample_rate)
+ return sample_rate, audio
diff --git a/src/Reachy_OpenWebUI/sub_apps/conversation_app/vad.py b/src/Reachy_OpenWebUI/sub_apps/conversation_app/vad.py
new file mode 100644
index 0000000000000000000000000000000000000000..736b7d8cf475a7d57cfc6e6d55a7df8774a3f9d6
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/conversation_app/vad.py
@@ -0,0 +1,104 @@
+import logging
+from pathlib import Path
+from urllib.request import urlretrieve
+
+import numpy as np
+
+
+logger = logging.getLogger(__name__)
+
+SILERO_ONNX_URL = "https://raw.githubusercontent.com/snakers4/silero-vad/master/src/silero_vad/data/silero_vad.onnx"
+DEFAULT_MODEL_PATH = Path.home() / ".cache" / "reachy-openwebui-vad" / "silero_vad.onnx"
+
+
+class SileroVAD:
+ """Silero VAD through ONNX Runtime, with audio-level fallback."""
+
+ def __init__(self, sample_rate: int = 16000, threshold: float | None = None):
+ from Reachy_OpenWebUI.config import config
+
+ self.sample_rate = sample_rate
+ self.threshold = config.VAD_THRESHOLD if threshold is None else threshold
+ self.fallback_threshold = config.VAD_FALLBACK_THRESHOLD
+ self.model = None
+ self._state = np.zeros((2, 1, 128), dtype=np.float32)
+ self._sr = np.array(self.sample_rate, dtype=np.int64)
+ self.mode = "audio_level"
+ self._init_model()
+
+ def _init_model(self):
+ try:
+ import onnxruntime as ort
+
+ model_path = self._model_path()
+ options = ort.SessionOptions()
+ options.log_severity_level = 3
+ self.model = ort.InferenceSession(str(model_path), sess_options=options, providers=["CPUExecutionProvider"])
+ self.mode = "onnx"
+ logger.info("Silero VAD ONNX Runtime loaded successfully: %s", model_path)
+ except Exception as e:
+ self.model = None
+ self.mode = "audio_level"
+ logger.warning("Silero VAD ONNX Runtime unavailable; using audio-level fallback: %s", e)
+
+ def _model_path(self) -> Path:
+ from Reachy_OpenWebUI.config import config
+
+ configured = str(getattr(config, "SILERO_VAD_ONNX_PATH", "") or "").strip()
+ model_path = Path(configured).expanduser() if configured else DEFAULT_MODEL_PATH
+ if not model_path.exists():
+ model_path.parent.mkdir(parents=True, exist_ok=True)
+ logger.info("Downloading Silero VAD ONNX model to %s", model_path)
+ urlretrieve(SILERO_ONNX_URL, model_path)
+ return model_path
+
+ def _fallback_rms(self, audio_chunk: np.ndarray) -> float:
+ if audio_chunk.size == 0:
+ return 0.0
+ return float(np.sqrt(np.mean(np.square(audio_chunk.astype(np.float32)))))
+
+ def _fallback_is_speech(self, audio_chunk: np.ndarray) -> bool:
+ if audio_chunk.size == 0:
+ return False
+ return self._fallback_rms(audio_chunk) > self.fallback_threshold
+
+ def is_speech(self, audio_chunk: np.ndarray) -> bool:
+ if self.model is None:
+ return self._fallback_is_speech(audio_chunk)
+
+ chunk = np.asarray(audio_chunk, dtype=np.float32)
+ if chunk.ndim == 1:
+ chunk = chunk.reshape(1, -1)
+
+ outputs = self.model.run(
+ None,
+ {
+ "input": chunk,
+ "state": self._state,
+ "sr": self._sr,
+ },
+ )
+ speech_prob = float(np.asarray(outputs[0]).reshape(-1)[0])
+ self._state = np.asarray(outputs[1], dtype=np.float32)
+ rms = self._fallback_rms(chunk)
+
+ # Periodic probe: max probability over ~3s windows, so threshold tuning
+ # is based on observed values instead of guesswork.
+ self._max_prob = max(getattr(self, "_max_prob", 0.0), speech_prob)
+ self._max_rms = max(getattr(self, "_max_rms", 0.0), rms)
+ self._prob_count = getattr(self, "_prob_count", 0) + 1
+ if self._prob_count >= 100:
+ logger.info(
+ "VAD probe: max speech prob %.3f, max rms %.4f over last %d chunks "
+ "(threshold %.2f, fallback %.4f)",
+ self._max_prob,
+ self._max_rms,
+ self._prob_count,
+ self.threshold,
+ self.fallback_threshold,
+ )
+ self._max_prob = 0.0
+ self._max_rms = 0.0
+ self._prob_count = 0
+
+ return speech_prob > self.threshold or rms > self.fallback_threshold
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/__init__.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0f3fef85eeb72c3cfddeece833a822aa72a0848
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__init__.py
@@ -0,0 +1 @@
+"""CookAIware domain helpers."""
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2f67f5dfca115c66dce69fd5d88bbf597ef8ee5e
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/app_settings.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/app_settings.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..af565fcb6e20796b7d200aa68b1dd2d205634967
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/app_settings.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/camera_worker.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/camera_worker.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..310b6b2fe504ff5dfa513ca3d35d9c71dc3d921c
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/camera_worker.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/dance_emotion_moves.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/dance_emotion_moves.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bf7d278edc1341184413c6a9ffa0ebf35ba5ecbd
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/dance_emotion_moves.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/data_store.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/data_store.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ac103ced75273fedc20d711183bec92d4d06a0ae
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/data_store.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/family_profile.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/family_profile.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4dbc43d728d7c04f895d66cb4ac25a2b563716f6
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/family_profile.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/headless_personality.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/headless_personality.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c374284732a2842374b5ccdbf6fe99a8e20ed3be
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/headless_personality.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/headless_personality_ui.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/headless_personality_ui.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..827023454526f5782c55ffafbb8ca0a8bacb8b66
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/headless_personality_ui.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/inventory.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/inventory.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cce88b92da2ac72122b166953e91f0b301bc552b
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/inventory.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/meal_planner.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/meal_planner.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eae6a38408dec2c0225228e9303a6fbabcf22a39
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/meal_planner.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/moves.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/moves.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3641555407f87f5c9f27b907a4b50129b39717e8
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/moves.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/prompts.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/prompts.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cd7a0d51eed603351e0dc5fd0b01840dd4307652
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/prompts.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/shopping_list.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/shopping_list.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d8ace28741db16d01bac37130406c93a9041466a
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/shopping_list.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/units.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/units.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d14d0766955b75064d45a9278d2f32d19b2eeb7
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/units.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/upc_cache.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/upc_cache.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..af456eea94183c2999a23698909bb2506292a180
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/upc_cache.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/upc_camera.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/upc_camera.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ecfca60e5402eaf8e3a0586ca43246a938bf9686
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/upc_camera.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/upc_lookup.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/upc_lookup.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d54b536e2b498c77e4d58e6a93f466b4c021c707
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/upc_lookup.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/utils.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4301d2fbe8a041433b72ad7c8593779af3f3d3ea
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/__pycache__/utils.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/app_settings.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/app_settings.py
new file mode 100644
index 0000000000000000000000000000000000000000..c92f41e471f0c90ce5b1cbec3ceb770751d6c0c5
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/app_settings.py
@@ -0,0 +1,73 @@
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any, Dict
+
+from Reachy_OpenWebUI.sub_apps.cookAIware.data_store import load_json, save_json
+
+
+SETTINGS_FILE = "app_settings.json"
+DEFAULT_LANGUAGE = "en"
+DEFAULT_UNIT_SYSTEM = "metric"
+DEFAULT_UPC_LOOKUP_SOURCE = "openfoodfacts"
+UPC_LOOKUP_SOURCES = ("openfoodfacts",)
+
+
+def _settings_path(data_dir: Path) -> Path:
+ return data_dir / SETTINGS_FILE
+
+
+def get_settings(data_dir: Path) -> Dict[str, Any]:
+ settings = load_json(_settings_path(data_dir), {})
+ if not isinstance(settings, dict):
+ settings = {}
+ if "language" not in settings:
+ settings["language"] = DEFAULT_LANGUAGE
+ if "unit_system" not in settings:
+ settings["unit_system"] = DEFAULT_UNIT_SYSTEM
+ if "upc_lookup_source" not in settings:
+ settings["upc_lookup_source"] = DEFAULT_UPC_LOOKUP_SOURCE
+ return settings
+
+
+def get_language(data_dir: Path) -> str:
+ settings = get_settings(data_dir)
+ language = str(settings.get("language", DEFAULT_LANGUAGE)).strip()
+ return language or DEFAULT_LANGUAGE
+
+
+def set_language(data_dir: Path, language: str) -> Dict[str, Any]:
+ settings = get_settings(data_dir)
+ lang = str(language or "").strip()
+ settings["language"] = lang or DEFAULT_LANGUAGE
+ save_json(_settings_path(data_dir), settings)
+ return settings
+
+
+def get_unit_system(data_dir: Path) -> str:
+ settings = get_settings(data_dir)
+ unit_system = str(settings.get("unit_system", DEFAULT_UNIT_SYSTEM)).strip().lower()
+ return unit_system if unit_system in ("metric", "imperial") else DEFAULT_UNIT_SYSTEM
+
+
+def set_unit_system(data_dir: Path, unit_system: str) -> Dict[str, Any]:
+ settings = get_settings(data_dir)
+ normalized = str(unit_system or "").strip().lower()
+ settings["unit_system"] = normalized if normalized in ("metric", "imperial") else DEFAULT_UNIT_SYSTEM
+ save_json(_settings_path(data_dir), settings)
+ return settings
+
+
+def get_upc_lookup_source(data_dir: Path) -> str:
+ settings = get_settings(data_dir)
+ source = str(settings.get("upc_lookup_source", DEFAULT_UPC_LOOKUP_SOURCE)).strip().lower()
+ return source if source in UPC_LOOKUP_SOURCES else DEFAULT_UPC_LOOKUP_SOURCE
+
+
+def set_upc_lookup_source(data_dir: Path, source: str) -> Dict[str, Any]:
+ settings = get_settings(data_dir)
+ normalized = str(source or "").strip().lower()
+ settings["upc_lookup_source"] = normalized if normalized in UPC_LOOKUP_SOURCES else DEFAULT_UPC_LOOKUP_SOURCE
+ save_json(_settings_path(data_dir), settings)
+ return settings
+
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/audio/__init__.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/audio/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..31819a0f2cf763696b1ad2bef53e1cb706ca40bc
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/audio/__init__.py
@@ -0,0 +1 @@
+"""Nothing (for ruff)."""
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/audio/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/audio/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dd997d572b3898f4c659aa2e16b5c643299f6c8f
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/audio/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/audio/__pycache__/head_wobbler.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/audio/__pycache__/head_wobbler.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..32e68f9c2a396affc9982c5c7861cbf1087d1db0
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/audio/__pycache__/head_wobbler.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/audio/__pycache__/speech_tapper.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/audio/__pycache__/speech_tapper.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..88c85747507e8a2466c82c53ff2d786d8bf02a10
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/audio/__pycache__/speech_tapper.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/audio/head_wobbler.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/audio/head_wobbler.py
new file mode 100644
index 0000000000000000000000000000000000000000..a7c7deec726cd2a4d84926506eb4d9c023dbb513
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/audio/head_wobbler.py
@@ -0,0 +1,181 @@
+"""Moves head given audio samples."""
+
+import time
+import queue
+import base64
+import logging
+import threading
+from typing import Tuple
+from collections.abc import Callable
+
+import numpy as np
+from numpy.typing import NDArray
+
+from Reachy_OpenWebUI.sub_apps.cookAIware.audio.speech_tapper import HOP_MS, SwayRollRT
+
+
+SAMPLE_RATE = 24000
+MOVEMENT_LATENCY_S = 0.2 # seconds between audio and robot movement
+logger = logging.getLogger(__name__)
+
+
+class HeadWobbler:
+ """Converts audio deltas (base64) into head movement offsets."""
+
+ def __init__(self, set_speech_offsets: Callable[[Tuple[float, float, float, float, float, float]], None]) -> None:
+ """Initialize the head wobbler."""
+ self._apply_offsets = set_speech_offsets
+ self._base_ts: float | None = None
+ self._hops_done: int = 0
+
+ self.audio_queue: "queue.Queue[Tuple[int, int, NDArray[np.int16]]]" = queue.Queue()
+ self.sway = SwayRollRT()
+
+ # Synchronization primitives
+ self._state_lock = threading.Lock()
+ self._sway_lock = threading.Lock()
+ self._generation = 0
+
+ self._stop_event = threading.Event()
+ self._thread: threading.Thread | None = None
+
+ def feed(self, delta_b64: str) -> None:
+ """Thread-safe: push audio into the consumer queue."""
+ buf = np.frombuffer(base64.b64decode(delta_b64), dtype=np.int16).reshape(1, -1)
+ with self._state_lock:
+ generation = self._generation
+ self.audio_queue.put((generation, SAMPLE_RATE, buf))
+
+ def start(self) -> None:
+ """Start the head wobbler loop in a thread."""
+ self._stop_event.clear()
+ self._thread = threading.Thread(target=self.working_loop, daemon=True)
+ self._thread.start()
+ logger.debug("Head wobbler started")
+
+ def stop(self) -> None:
+ """Stop the head wobbler loop."""
+ self._stop_event.set()
+ if self._thread is not None:
+ self._thread.join()
+ logger.debug("Head wobbler stopped")
+
+ def working_loop(self) -> None:
+ """Convert audio deltas into head movement offsets."""
+ hop_dt = HOP_MS / 1000.0
+
+ logger.debug("Head wobbler thread started")
+ while not self._stop_event.is_set():
+ queue_ref = self.audio_queue
+ try:
+ chunk_generation, sr, chunk = queue_ref.get_nowait() # (gen, sr, data)
+ except queue.Empty:
+ # avoid while to never exit
+ time.sleep(MOVEMENT_LATENCY_S)
+ continue
+
+ try:
+ with self._state_lock:
+ current_generation = self._generation
+ if chunk_generation != current_generation:
+ continue
+
+ if self._base_ts is None:
+ with self._state_lock:
+ if self._base_ts is None:
+ self._base_ts = time.monotonic()
+
+ pcm = np.asarray(chunk).squeeze(0)
+ with self._sway_lock:
+ results = self.sway.feed(pcm, sr)
+
+ i = 0
+ while i < len(results):
+ with self._state_lock:
+ if self._generation != current_generation:
+ break
+ base_ts = self._base_ts
+ hops_done = self._hops_done
+
+ if base_ts is None:
+ base_ts = time.monotonic()
+ with self._state_lock:
+ if self._base_ts is None:
+ self._base_ts = base_ts
+ hops_done = self._hops_done
+
+ target = base_ts + MOVEMENT_LATENCY_S + hops_done * hop_dt
+ now = time.monotonic()
+
+ if now - target >= hop_dt:
+ lag_hops = int((now - target) / hop_dt)
+ drop = min(lag_hops, len(results) - i - 1)
+ if drop > 0:
+ with self._state_lock:
+ self._hops_done += drop
+ hops_done = self._hops_done
+ i += drop
+ continue
+
+ if target > now:
+ time.sleep(target - now)
+ with self._state_lock:
+ if self._generation != current_generation:
+ break
+
+ r = results[i]
+ offsets = (
+ r["x_mm"] / 1000.0,
+ r["y_mm"] / 1000.0,
+ r["z_mm"] / 1000.0,
+ r["roll_rad"],
+ r["pitch_rad"],
+ r["yaw_rad"],
+ )
+
+ with self._state_lock:
+ if self._generation != current_generation:
+ break
+
+ self._apply_offsets(offsets)
+
+ with self._state_lock:
+ self._hops_done += 1
+ i += 1
+ finally:
+ queue_ref.task_done()
+ logger.debug("Head wobbler thread exited")
+
+ '''
+ def drain_audio_queue(self) -> None:
+ """Empty the audio queue."""
+ try:
+ while True:
+ self.audio_queue.get_nowait()
+ except QueueEmpty:
+ pass
+ '''
+
+ def reset(self) -> None:
+ """Reset the internal state."""
+ with self._state_lock:
+ self._generation += 1
+ self._base_ts = None
+ self._hops_done = 0
+
+ # Drain any queued audio chunks from previous generations
+ drained_any = False
+ while True:
+ try:
+ _, _, _ = self.audio_queue.get_nowait()
+ except queue.Empty:
+ break
+ else:
+ drained_any = True
+ self.audio_queue.task_done()
+
+ with self._sway_lock:
+ self.sway.reset()
+
+ if drained_any:
+ logger.debug("Head wobbler queue drained during reset")
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/audio/speech_tapper.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/audio/speech_tapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1c1cdbb16b032d46fc384cf2ff107ae9417f3d4
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/audio/speech_tapper.py
@@ -0,0 +1,268 @@
+from __future__ import annotations
+import math
+from typing import Any, Dict, List
+from itertools import islice
+from collections import deque
+
+import numpy as np
+from numpy.typing import NDArray
+
+
+# Tunables
+SR = 16_000
+FRAME_MS = 20
+HOP_MS = 50
+
+SWAY_MASTER = 1.5
+SENS_DB_OFFSET = +4.0
+VAD_DB_ON = -35.0
+VAD_DB_OFF = -45.0
+VAD_ATTACK_MS = 40
+VAD_RELEASE_MS = 250
+ENV_FOLLOW_GAIN = 0.65
+
+SWAY_F_PITCH = 2.2
+SWAY_A_PITCH_DEG = 4.5
+SWAY_F_YAW = 0.6
+SWAY_A_YAW_DEG = 7.5
+SWAY_F_ROLL = 1.3
+SWAY_A_ROLL_DEG = 2.25
+SWAY_F_X = 0.35
+SWAY_A_X_MM = 4.5
+SWAY_F_Y = 0.45
+SWAY_A_Y_MM = 3.75
+SWAY_F_Z = 0.25
+SWAY_A_Z_MM = 2.25
+
+SWAY_DB_LOW = -46.0
+SWAY_DB_HIGH = -18.0
+LOUDNESS_GAMMA = 0.9
+SWAY_ATTACK_MS = 50
+SWAY_RELEASE_MS = 250
+
+# Derived
+FRAME = int(SR * FRAME_MS / 1000)
+HOP = int(SR * HOP_MS / 1000)
+ATTACK_FR = max(1, int(VAD_ATTACK_MS / HOP_MS))
+RELEASE_FR = max(1, int(VAD_RELEASE_MS / HOP_MS))
+SWAY_ATTACK_FR = max(1, int(SWAY_ATTACK_MS / HOP_MS))
+SWAY_RELEASE_FR = max(1, int(SWAY_RELEASE_MS / HOP_MS))
+
+
+def _rms_dbfs(x: NDArray[np.float32]) -> float:
+ """Root-mean-square in dBFS for float32 mono array in [-1,1]."""
+ # numerically stable rms (avoid overflow)
+ x = x.astype(np.float32, copy=False)
+ rms = np.sqrt(np.mean(x * x, dtype=np.float32) + 1e-12, dtype=np.float32)
+ return float(20.0 * math.log10(float(rms) + 1e-12))
+
+
+def _loudness_gain(db: float, offset: float = SENS_DB_OFFSET) -> float:
+ """Normalize dB into [0,1] with gamma; clipped to [0,1]."""
+ t = (db + offset - SWAY_DB_LOW) / (SWAY_DB_HIGH - SWAY_DB_LOW)
+ if t < 0.0:
+ t = 0.0
+ elif t > 1.0:
+ t = 1.0
+ return t**LOUDNESS_GAMMA if LOUDNESS_GAMMA != 1.0 else t
+
+
+def _to_float32_mono(x: NDArray[Any]) -> NDArray[np.float32]:
+ """Convert arbitrary PCM array to float32 mono in [-1,1].
+
+ Accepts shapes: (N,), (1,N), (N,1), (C,N), (N,C).
+ """
+ a = np.asarray(x)
+ if a.ndim == 0:
+ return np.zeros(0, dtype=np.float32)
+
+ # If 2D, decide which axis is channels (prefer small first dim)
+ if a.ndim == 2:
+ # e.g., (channels, samples) if channels is small (<=8)
+ if a.shape[0] <= 8 and a.shape[0] <= a.shape[1]:
+ a = np.mean(a, axis=0)
+ else:
+ a = np.mean(a, axis=1)
+ elif a.ndim > 2:
+ a = np.mean(a.reshape(a.shape[0], -1), axis=0)
+
+ # Now 1D, cast/scale
+ if np.issubdtype(a.dtype, np.floating):
+ return a.astype(np.float32, copy=False)
+ # integer PCM
+ info = np.iinfo(a.dtype)
+ scale = float(max(-info.min, info.max))
+ return a.astype(np.float32) / (scale if scale != 0.0 else 1.0)
+
+
+def _resample_linear(x: NDArray[np.float32], sr_in: int, sr_out: int) -> NDArray[np.float32]:
+ """Lightweight linear resampler for short buffers."""
+ if sr_in == sr_out or x.size == 0:
+ return x
+ # guard tiny sizes
+ n_out = int(round(x.size * sr_out / sr_in))
+ if n_out <= 1:
+ return np.zeros(0, dtype=np.float32)
+ t_in = np.linspace(0.0, 1.0, num=x.size, dtype=np.float32, endpoint=True)
+ t_out = np.linspace(0.0, 1.0, num=n_out, dtype=np.float32, endpoint=True)
+ return np.interp(t_out, t_in, x).astype(np.float32, copy=False)
+
+
+class SwayRollRT:
+ """Feed audio chunks → per-hop sway outputs.
+
+ Usage:
+ rt = SwayRollRT()
+ rt.feed(pcm_int16_or_float, sr) -> List[dict]
+ """
+
+ def __init__(self, rng_seed: int = 7):
+ """Initialize state."""
+ self._seed = int(rng_seed)
+ self.samples: deque[float] = deque(maxlen=10 * SR) # sliding window for VAD/env
+ self.carry: NDArray[np.float32] = np.zeros(0, dtype=np.float32)
+
+ self.vad_on = False
+ self.vad_above = 0
+ self.vad_below = 0
+
+ self.sway_env = 0.0
+ self.sway_up = 0
+ self.sway_down = 0
+
+ rng = np.random.default_rng(self._seed)
+ self.phase_pitch = float(rng.random() * 2 * math.pi)
+ self.phase_yaw = float(rng.random() * 2 * math.pi)
+ self.phase_roll = float(rng.random() * 2 * math.pi)
+ self.phase_x = float(rng.random() * 2 * math.pi)
+ self.phase_y = float(rng.random() * 2 * math.pi)
+ self.phase_z = float(rng.random() * 2 * math.pi)
+ self.t = 0.0
+
+ def reset(self) -> None:
+ """Reset state (VAD/env/buffers/time) but keep initial phases/seed."""
+ self.samples.clear()
+ self.carry = np.zeros(0, dtype=np.float32)
+ self.vad_on = False
+ self.vad_above = 0
+ self.vad_below = 0
+ self.sway_env = 0.0
+ self.sway_up = 0
+ self.sway_down = 0
+ self.t = 0.0
+
+ def feed(self, pcm: NDArray[Any], sr: int | None) -> List[Dict[str, float]]:
+ """Stream in PCM chunk. Returns a list of sway dicts, one per hop (HOP_MS).
+
+ Args:
+ pcm: np.ndarray, shape (N,) or (C,N)/(N,C); int or float.
+ sr: sample rate of `pcm` (None -> assume SR).
+
+ """
+ sr_in = SR if sr is None else int(sr)
+ x = _to_float32_mono(pcm)
+ if x.size == 0:
+ return []
+ if sr_in != SR:
+ x = _resample_linear(x, sr_in, SR)
+ if x.size == 0:
+ return []
+
+ # append to carry and consume fixed HOP chunks
+ if self.carry.size:
+ self.carry = np.concatenate([self.carry, x])
+ else:
+ self.carry = x
+
+ out: List[Dict[str, float]] = []
+
+ while self.carry.size >= HOP:
+ hop = self.carry[:HOP]
+ remaining: NDArray[np.float32] = self.carry[HOP:]
+ self.carry = remaining
+
+ # keep sliding window for VAD/env computation
+ # (deque accepts any iterable; list() for small HOP is fine)
+ self.samples.extend(hop.tolist())
+ if len(self.samples) < FRAME:
+ self.t += HOP_MS / 1000.0
+ continue
+
+ frame = np.fromiter(
+ islice(self.samples, len(self.samples) - FRAME, len(self.samples)),
+ dtype=np.float32,
+ count=FRAME,
+ )
+ db = _rms_dbfs(frame)
+
+ # VAD with hysteresis + attack/release
+ if db >= VAD_DB_ON:
+ self.vad_above += 1
+ self.vad_below = 0
+ if not self.vad_on and self.vad_above >= ATTACK_FR:
+ self.vad_on = True
+ elif db <= VAD_DB_OFF:
+ self.vad_below += 1
+ self.vad_above = 0
+ if self.vad_on and self.vad_below >= RELEASE_FR:
+ self.vad_on = False
+
+ if self.vad_on:
+ self.sway_up = min(SWAY_ATTACK_FR, self.sway_up + 1)
+ self.sway_down = 0
+ else:
+ self.sway_down = min(SWAY_RELEASE_FR, self.sway_down + 1)
+ self.sway_up = 0
+
+ up = self.sway_up / SWAY_ATTACK_FR
+ down = 1.0 - (self.sway_down / SWAY_RELEASE_FR)
+ target = up if self.vad_on else down
+ self.sway_env += ENV_FOLLOW_GAIN * (target - self.sway_env)
+ # clamp
+ if self.sway_env < 0.0:
+ self.sway_env = 0.0
+ elif self.sway_env > 1.0:
+ self.sway_env = 1.0
+
+ loud = _loudness_gain(db) * SWAY_MASTER
+ env = self.sway_env
+ self.t += HOP_MS / 1000.0
+
+ # oscillators
+ pitch = (
+ math.radians(SWAY_A_PITCH_DEG)
+ * loud
+ * env
+ * math.sin(2 * math.pi * SWAY_F_PITCH * self.t + self.phase_pitch)
+ )
+ yaw = (
+ math.radians(SWAY_A_YAW_DEG)
+ * loud
+ * env
+ * math.sin(2 * math.pi * SWAY_F_YAW * self.t + self.phase_yaw)
+ )
+ roll = (
+ math.radians(SWAY_A_ROLL_DEG)
+ * loud
+ * env
+ * math.sin(2 * math.pi * SWAY_F_ROLL * self.t + self.phase_roll)
+ )
+ x_mm = SWAY_A_X_MM * loud * env * math.sin(2 * math.pi * SWAY_F_X * self.t + self.phase_x)
+ y_mm = SWAY_A_Y_MM * loud * env * math.sin(2 * math.pi * SWAY_F_Y * self.t + self.phase_y)
+ z_mm = SWAY_A_Z_MM * loud * env * math.sin(2 * math.pi * SWAY_F_Z * self.t + self.phase_z)
+
+ out.append(
+ {
+ "pitch_rad": pitch,
+ "yaw_rad": yaw,
+ "roll_rad": roll,
+ "pitch_deg": math.degrees(pitch),
+ "yaw_deg": math.degrees(yaw),
+ "roll_deg": math.degrees(roll),
+ "x_mm": x_mm,
+ "y_mm": y_mm,
+ "z_mm": z_mm,
+ },
+ )
+
+ return out
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/camera_worker.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/camera_worker.py
new file mode 100644
index 0000000000000000000000000000000000000000..206e5b4ceee201ce0a75f85fb1997f149ee3fe96
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/camera_worker.py
@@ -0,0 +1,241 @@
+"""Camera worker thread with frame buffering and face tracking.
+
+Ported from main_works.py camera_worker() function to provide:
+- 30Hz+ camera polling with thread-safe frame buffering
+- Face tracking integration with smooth interpolation
+- Latest frame always available for tools
+"""
+
+import time
+import logging
+import threading
+from typing import Any, List, Tuple
+
+import numpy as np
+from numpy.typing import NDArray
+from scipy.spatial.transform import Rotation as R
+
+from reachy_mini import ReachyMini
+from reachy_mini.utils.interpolation import linear_pose_interpolation
+
+
+logger = logging.getLogger(__name__)
+
+
+class CameraWorker:
+ """Thread-safe camera worker with frame buffering and face tracking."""
+
+ def __init__(self, reachy_mini: ReachyMini, head_tracker: Any = None) -> None:
+ """Initialize."""
+ self.reachy_mini = reachy_mini
+ self.head_tracker = head_tracker
+
+ # Thread-safe frame storage
+ self.latest_frame: NDArray[np.uint8] | None = None
+ self.frame_lock = threading.Lock()
+ self._stop_event = threading.Event()
+ self._thread: threading.Thread | None = None
+
+ # Face tracking state
+ self.is_head_tracking_enabled = True
+ self.face_tracking_offsets: List[float] = [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ ] # x, y, z, roll, pitch, yaw
+ self.face_tracking_lock = threading.Lock()
+
+ # Face tracking timing variables (same as main_works.py)
+ self.last_face_detected_time: float | None = None
+ self.interpolation_start_time: float | None = None
+ self.interpolation_start_pose: NDArray[np.float32] | None = None
+ self.face_lost_delay = 2.0 # seconds to wait before starting interpolation
+ self.interpolation_duration = 1.0 # seconds to interpolate back to neutral
+
+ # Track state changes
+ self.previous_head_tracking_state = self.is_head_tracking_enabled
+
+ def get_latest_frame(self) -> NDArray[np.uint8] | None:
+ """Get the latest frame (thread-safe)."""
+ with self.frame_lock:
+ if self.latest_frame is None:
+ return None
+ # Return a copy in original BGR format (OpenCV native)
+ return self.latest_frame.copy()
+
+ def get_face_tracking_offsets(
+ self,
+ ) -> Tuple[float, float, float, float, float, float]:
+ """Get current face tracking offsets (thread-safe)."""
+ with self.face_tracking_lock:
+ offsets = self.face_tracking_offsets
+ return (offsets[0], offsets[1], offsets[2], offsets[3], offsets[4], offsets[5])
+
+ def set_head_tracking_enabled(self, enabled: bool) -> None:
+ """Enable/disable head tracking."""
+ self.is_head_tracking_enabled = enabled
+ logger.info(f"Head tracking {'enabled' if enabled else 'disabled'}")
+
+ def start(self) -> None:
+ """Start the camera worker loop in a thread."""
+ self._stop_event.clear()
+ self._thread = threading.Thread(target=self.working_loop, daemon=True)
+ self._thread.start()
+ logger.debug("Camera worker started")
+
+ def stop(self) -> None:
+ """Stop the camera worker loop."""
+ self._stop_event.set()
+ if self._thread is not None:
+ self._thread.join()
+
+ logger.debug("Camera worker stopped")
+
+ def working_loop(self) -> None:
+ """Enable the camera worker loop.
+
+ Ported from main_works.py camera_worker() with same logic.
+ """
+ logger.debug("Starting camera working loop")
+
+ # Initialize head tracker if available
+ neutral_pose = np.eye(4) # Neutral pose (identity matrix)
+ self.previous_head_tracking_state = self.is_head_tracking_enabled
+
+ while not self._stop_event.is_set():
+ try:
+ current_time = time.time()
+
+ # Get frame from robot
+ frame = self.reachy_mini.media.get_frame()
+
+ if frame is not None:
+ # Thread-safe frame storage
+ with self.frame_lock:
+ self.latest_frame = frame # .copy()
+
+ # Check if face tracking was just disabled
+ if self.previous_head_tracking_state and not self.is_head_tracking_enabled:
+ # Face tracking was just disabled - start interpolation to neutral
+ self.last_face_detected_time = current_time # Trigger the face-lost logic
+ self.interpolation_start_time = None # Will be set by the face-lost interpolation
+ self.interpolation_start_pose = None
+
+ # Update tracking state
+ self.previous_head_tracking_state = self.is_head_tracking_enabled
+
+ # Handle face tracking if enabled and head tracker available
+ if self.is_head_tracking_enabled and self.head_tracker is not None:
+ eye_center, _ = self.head_tracker.get_head_position(frame)
+
+ if eye_center is not None:
+ # Face detected - immediately switch to tracking
+ self.last_face_detected_time = current_time
+ self.interpolation_start_time = None # Stop any interpolation
+
+ # Convert normalized coordinates to pixel coordinates
+ h, w, _ = frame.shape
+ eye_center_norm = (eye_center + 1) / 2
+ eye_center_pixels = [
+ eye_center_norm[0] * w,
+ eye_center_norm[1] * h,
+ ]
+
+ # Get the head pose needed to look at the target, but don't perform movement
+ target_pose = self.reachy_mini.look_at_image(
+ eye_center_pixels[0],
+ eye_center_pixels[1],
+ duration=0.0,
+ perform_movement=False,
+ )
+
+ # Extract translation and rotation from the target pose directly
+ translation = target_pose[:3, 3]
+ rotation = R.from_matrix(target_pose[:3, :3]).as_euler("xyz", degrees=False)
+
+ # Scale down translation and rotation because smaller FOV
+ translation *= 0.6
+ rotation *= 0.6
+
+ # Thread-safe update of face tracking offsets (use pose as-is)
+ with self.face_tracking_lock:
+ self.face_tracking_offsets = [
+ translation[0],
+ translation[1],
+ translation[2], # x, y, z
+ rotation[0],
+ rotation[1],
+ rotation[2], # roll, pitch, yaw
+ ]
+
+ # No face detected while tracking enabled - set face lost timestamp
+ elif self.last_face_detected_time is None or self.last_face_detected_time == current_time:
+ # Only update if we haven't already set a face lost time
+ # (current_time check prevents overriding the disable-triggered timestamp)
+ pass
+
+ # Handle smooth interpolation (works for both face-lost and tracking-disabled cases)
+ if self.last_face_detected_time is not None:
+ time_since_face_lost = current_time - self.last_face_detected_time
+
+ if time_since_face_lost >= self.face_lost_delay:
+ # Start interpolation if not already started
+ if self.interpolation_start_time is None:
+ self.interpolation_start_time = current_time
+ # Capture current pose as start of interpolation
+ with self.face_tracking_lock:
+ current_translation = self.face_tracking_offsets[:3]
+ current_rotation_euler = self.face_tracking_offsets[3:]
+ # Convert to 4x4 pose matrix
+ pose_matrix = np.eye(4, dtype=np.float32)
+ pose_matrix[:3, 3] = current_translation
+ pose_matrix[:3, :3] = R.from_euler(
+ "xyz",
+ current_rotation_euler,
+ ).as_matrix()
+ self.interpolation_start_pose = pose_matrix
+
+ # Calculate interpolation progress (t from 0 to 1)
+ elapsed_interpolation = current_time - self.interpolation_start_time
+ t = min(1.0, elapsed_interpolation / self.interpolation_duration)
+
+ # Interpolate between current pose and neutral pose
+ interpolated_pose = linear_pose_interpolation(
+ self.interpolation_start_pose,
+ neutral_pose,
+ t,
+ )
+
+ # Extract translation and rotation from interpolated pose
+ translation = interpolated_pose[:3, 3]
+ rotation = R.from_matrix(interpolated_pose[:3, :3]).as_euler("xyz", degrees=False)
+
+ # Thread-safe update of face tracking offsets
+ with self.face_tracking_lock:
+ self.face_tracking_offsets = [
+ translation[0],
+ translation[1],
+ translation[2], # x, y, z
+ rotation[0],
+ rotation[1],
+ rotation[2], # roll, pitch, yaw
+ ]
+
+ # If interpolation is complete, reset timing
+ if t >= 1.0:
+ self.last_face_detected_time = None
+ self.interpolation_start_time = None
+ self.interpolation_start_pose = None
+ # else: Keep current offsets (within 2s delay period)
+
+ # Small sleep to prevent excessive CPU usage (same as main_works.py)
+ time.sleep(0.04)
+
+ except Exception as e:
+ logger.error(f"Camera worker error: {e}")
+ time.sleep(0.1) # Longer sleep on error
+
+ logger.debug("Camera worker thread exited")
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/dance_emotion_moves.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/dance_emotion_moves.py
new file mode 100644
index 0000000000000000000000000000000000000000..9fef9955312a3f686df408fb2aff80ea7021d45b
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/dance_emotion_moves.py
@@ -0,0 +1,154 @@
+"""Dance and emotion moves for the movement queue system.
+
+This module implements dance moves and emotions as Move objects that can be queued
+and executed sequentially by the MovementManager.
+"""
+
+from __future__ import annotations
+import logging
+from typing import Tuple
+
+import numpy as np
+from numpy.typing import NDArray
+
+from reachy_mini.motion.move import Move
+from reachy_mini.motion.recorded_move import RecordedMoves
+from reachy_mini_dances_library.dance_move import DanceMove
+
+
+logger = logging.getLogger(__name__)
+
+
+class DanceQueueMove(Move): # type: ignore
+ """Wrapper for dance moves to work with the movement queue system."""
+
+ def __init__(self, move_name: str):
+ """Initialize a DanceQueueMove."""
+ self.dance_move = DanceMove(move_name)
+ self.move_name = move_name
+
+ @property
+ def duration(self) -> float:
+ """Duration property required by official Move interface."""
+ return float(self.dance_move.duration)
+
+ def evaluate(self, t: float) -> tuple[NDArray[np.float64] | None, NDArray[np.float64] | None, float | None]:
+ """Evaluate dance move at time t."""
+ try:
+ # Get the pose from the dance move
+ head_pose, antennas, body_yaw = self.dance_move.evaluate(t)
+
+ # Convert to numpy array if antennas is tuple and return in official Move format
+ if isinstance(antennas, tuple):
+ antennas = np.array([antennas[0], antennas[1]])
+
+ return (head_pose, antennas, body_yaw)
+
+ except Exception as e:
+ logger.error(f"Error evaluating dance move '{self.move_name}' at t={t}: {e}")
+ # Return neutral pose on error
+ from reachy_mini.utils import create_head_pose
+
+ neutral_head_pose = create_head_pose(0, 0, 0, 0, 0, 0, degrees=True)
+ return (neutral_head_pose, np.array([0.0, 0.0], dtype=np.float64), 0.0)
+
+
+class EmotionQueueMove(Move): # type: ignore
+ """Wrapper for emotion moves to work with the movement queue system."""
+
+ def __init__(self, emotion_name: str, recorded_moves: RecordedMoves):
+ """Initialize an EmotionQueueMove."""
+ self.emotion_move = recorded_moves.get(emotion_name)
+ self.emotion_name = emotion_name
+
+ @property
+ def duration(self) -> float:
+ """Duration property required by official Move interface."""
+ return float(self.emotion_move.duration)
+
+ def evaluate(self, t: float) -> tuple[NDArray[np.float64] | None, NDArray[np.float64] | None, float | None]:
+ """Evaluate emotion move at time t."""
+ try:
+ # Get the pose from the emotion move
+ head_pose, antennas, body_yaw = self.emotion_move.evaluate(t)
+
+ # Convert to numpy array if antennas is tuple and return in official Move format
+ if isinstance(antennas, tuple):
+ antennas = np.array([antennas[0], antennas[1]])
+
+ return (head_pose, antennas, body_yaw)
+
+ except Exception as e:
+ logger.error(f"Error evaluating emotion '{self.emotion_name}' at t={t}: {e}")
+ # Return neutral pose on error
+ from reachy_mini.utils import create_head_pose
+
+ neutral_head_pose = create_head_pose(0, 0, 0, 0, 0, 0, degrees=True)
+ return (neutral_head_pose, np.array([0.0, 0.0], dtype=np.float64), 0.0)
+
+
+class GotoQueueMove(Move): # type: ignore
+ """Wrapper for goto moves to work with the movement queue system."""
+
+ def __init__(
+ self,
+ target_head_pose: NDArray[np.float32],
+ start_head_pose: NDArray[np.float32] | None = None,
+ target_antennas: Tuple[float, float] = (0, 0),
+ start_antennas: Tuple[float, float] | None = None,
+ target_body_yaw: float = 0,
+ start_body_yaw: float | None = None,
+ duration: float = 1.0,
+ ):
+ """Initialize a GotoQueueMove."""
+ self._duration = duration
+ self.target_head_pose = target_head_pose
+ self.start_head_pose = start_head_pose
+ self.target_antennas = target_antennas
+ self.start_antennas = start_antennas or (0, 0)
+ self.target_body_yaw = target_body_yaw
+ self.start_body_yaw = start_body_yaw or 0
+
+ @property
+ def duration(self) -> float:
+ """Duration property required by official Move interface."""
+ return self._duration
+
+ def evaluate(self, t: float) -> tuple[NDArray[np.float64] | None, NDArray[np.float64] | None, float | None]:
+ """Evaluate goto move at time t using linear interpolation."""
+ try:
+ from reachy_mini.utils import create_head_pose
+ from reachy_mini.utils.interpolation import linear_pose_interpolation
+
+ # Clamp t to [0, 1] for interpolation
+ t_clamped = max(0, min(1, t / self.duration))
+
+ # Use start pose if available, otherwise neutral
+ if self.start_head_pose is not None:
+ start_pose = self.start_head_pose
+ else:
+ start_pose = create_head_pose(0, 0, 0, 0, 0, 0, degrees=True)
+
+ # Interpolate head pose
+ head_pose = linear_pose_interpolation(start_pose, self.target_head_pose, t_clamped)
+
+ # Interpolate antennas - return as numpy array
+ antennas = np.array(
+ [
+ self.start_antennas[0] + (self.target_antennas[0] - self.start_antennas[0]) * t_clamped,
+ self.start_antennas[1] + (self.target_antennas[1] - self.start_antennas[1]) * t_clamped,
+ ],
+ dtype=np.float64,
+ )
+
+ # Interpolate body yaw
+ body_yaw = self.start_body_yaw + (self.target_body_yaw - self.start_body_yaw) * t_clamped
+
+ return (head_pose, antennas, body_yaw)
+
+ except Exception as e:
+ logger.error(f"Error evaluating goto move at t={t}: {e}")
+ # Return target pose on error - convert to float64
+ target_head_pose_f64 = self.target_head_pose.astype(np.float64)
+ target_antennas_array = np.array([self.target_antennas[0], self.target_antennas[1]], dtype=np.float64)
+ return (target_head_pose_f64, target_antennas_array, self.target_body_yaw)
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/data/app_settings.json b/src/Reachy_OpenWebUI/sub_apps/cookAIware/data/app_settings.json
new file mode 100644
index 0000000000000000000000000000000000000000..60ddcc16cba4444cfd28d4890ce7b9dca8c10fd7
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/data/app_settings.json
@@ -0,0 +1,3 @@
+{
+ "language": "ca"
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/data/family_profile.json b/src/Reachy_OpenWebUI/sub_apps/cookAIware/data/family_profile.json
new file mode 100644
index 0000000000000000000000000000000000000000..f4a4423d092e2faa902c630908dfa248e813e586
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/data/family_profile.json
@@ -0,0 +1,20 @@
+{
+ "adults": 2,
+ "children": 3,
+ "schedule": {
+ "weekday": {
+ "dinner": true,
+ "lunch_adults": 1,
+ "lunch_days": [
+ "monday",
+ "wednesday",
+ "friday"
+ ]
+ },
+ "weekend": {
+ "breakfast": false,
+ "lunch": true,
+ "dinner": true
+ }
+ }
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/data/inventory.json b/src/Reachy_OpenWebUI/sub_apps/cookAIware/data/inventory.json
new file mode 100644
index 0000000000000000000000000000000000000000..d4cb18cbc6fca5fba4c83ae41381a8758de46358
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/data/inventory.json
@@ -0,0 +1,58 @@
+[
+ {
+ "name": "arroz",
+ "display_name": "arroz",
+ "quantity": 600.0,
+ "unit": "g",
+ "expiration_date": "2027-02-07",
+ "storage_location": "armario"
+ },
+ {
+ "name": "pasta",
+ "display_name": "pasta",
+ "quantity": 1000.0,
+ "unit": "g",
+ "expiration_date": "2027-02-07",
+ "storage_location": "armario"
+ },
+ {
+ "name": "pollo",
+ "display_name": "pollo",
+ "quantity": 0.0,
+ "unit": "g",
+ "expiration_date": "2026-02-10",
+ "storage_location": "nevera"
+ },
+ {
+ "name": "tomates cherry",
+ "display_name": "tomates cherry",
+ "quantity": 300.0,
+ "unit": "g",
+ "expiration_date": "2026-02-14",
+ "storage_location": "armario"
+ },
+ {
+ "name": "mix de verduras",
+ "display_name": "mix de verduras",
+ "quantity": 0.0,
+ "unit": "g",
+ "expiration_date": "2026-02-14",
+ "storage_location": null
+ },
+ {
+ "name": "chicken",
+ "display_name": "chicken",
+ "quantity": 0.0,
+ "unit": "g",
+ "expiration_date": "2026-02-10",
+ "storage_location": "nevera"
+ },
+ {
+ "name": "corn on the cob",
+ "display_name": "corn on the cob",
+ "quantity": 0.0,
+ "unit": "pcs",
+ "expiration_date": null,
+ "storage_location": null
+ }
+]
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/data/meal_plan.json b/src/Reachy_OpenWebUI/sub_apps/cookAIware/data/meal_plan.json
new file mode 100644
index 0000000000000000000000000000000000000000..e1b89be607d494ac63c2521f663c3cd6c1b1ccae
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/data/meal_plan.json
@@ -0,0 +1,399 @@
+{
+ "week_start": "2026-02-02",
+ "schedule": {
+ "weekday": {
+ "dinner": true,
+ "lunch_adults": 1,
+ "lunch_days": [
+ "monday",
+ "wednesday",
+ "friday"
+ ]
+ },
+ "weekend": {
+ "breakfast": false,
+ "lunch": true,
+ "dinner": true
+ }
+ },
+ "days": [
+ {
+ "day": "monday",
+ "date": "2026-02-02",
+ "meals": [
+ {
+ "meal": "dinner",
+ "name": "Chicken with Tomates Cherry and Arroz",
+ "servings": 5,
+ "ingredients": [
+ {
+ "name": "chicken",
+ "display_name": "Chicken",
+ "quantity": 750.0,
+ "unit": "g",
+ "display_quantity": "750.00 g"
+ },
+ {
+ "name": "tomates cherry",
+ "display_name": "Tomates Cherry",
+ "quantity": 600.0,
+ "unit": "g",
+ "display_quantity": "600.00 g"
+ },
+ {
+ "name": "arroz",
+ "display_name": "Arroz",
+ "quantity": 500.0,
+ "unit": "g",
+ "display_quantity": "500.00 g"
+ }
+ ]
+ },
+ {
+ "meal": "adult_lunch",
+ "name": "Pollo with Mix De Verduras and Pasta",
+ "servings": 1,
+ "ingredients": [
+ {
+ "name": "pollo",
+ "display_name": "Pollo",
+ "quantity": 150.0,
+ "unit": "g",
+ "display_quantity": "150.00 g"
+ },
+ {
+ "name": "mix de verduras",
+ "display_name": "Mix De Verduras",
+ "quantity": 120.0,
+ "unit": "g",
+ "display_quantity": "120.00 g"
+ },
+ {
+ "name": "pasta",
+ "display_name": "Pasta",
+ "quantity": 100.0,
+ "unit": "g",
+ "display_quantity": "100.00 g"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "day": "tuesday",
+ "date": "2026-02-03",
+ "meals": [
+ {
+ "meal": "dinner",
+ "name": "Chicken with Tomates Cherry and Arroz",
+ "servings": 5,
+ "ingredients": [
+ {
+ "name": "chicken",
+ "display_name": "Chicken",
+ "quantity": 750.0,
+ "unit": "g",
+ "display_quantity": "750.00 g"
+ },
+ {
+ "name": "tomates cherry",
+ "display_name": "Tomates Cherry",
+ "quantity": 600.0,
+ "unit": "g",
+ "display_quantity": "600.00 g"
+ },
+ {
+ "name": "arroz",
+ "display_name": "Arroz",
+ "quantity": 500.0,
+ "unit": "g",
+ "display_quantity": "500.00 g"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "day": "wednesday",
+ "date": "2026-02-04",
+ "meals": [
+ {
+ "meal": "dinner",
+ "name": "Pollo with Mix De Verduras and Pasta",
+ "servings": 5,
+ "ingredients": [
+ {
+ "name": "pollo",
+ "display_name": "Pollo",
+ "quantity": 750.0,
+ "unit": "g",
+ "display_quantity": "750.00 g"
+ },
+ {
+ "name": "mix de verduras",
+ "display_name": "Mix De Verduras",
+ "quantity": 600.0,
+ "unit": "g",
+ "display_quantity": "600.00 g"
+ },
+ {
+ "name": "pasta",
+ "display_name": "Pasta",
+ "quantity": 500.0,
+ "unit": "g",
+ "display_quantity": "500.00 g"
+ }
+ ]
+ },
+ {
+ "meal": "adult_lunch",
+ "name": "Chicken with Tomates Cherry and Arroz",
+ "servings": 1,
+ "ingredients": [
+ {
+ "name": "chicken",
+ "display_name": "Chicken",
+ "quantity": 150.0,
+ "unit": "g",
+ "display_quantity": "150.00 g"
+ },
+ {
+ "name": "tomates cherry",
+ "display_name": "Tomates Cherry",
+ "quantity": 120.0,
+ "unit": "g",
+ "display_quantity": "120.00 g"
+ },
+ {
+ "name": "arroz",
+ "display_name": "Arroz",
+ "quantity": 100.0,
+ "unit": "g",
+ "display_quantity": "100.00 g"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "day": "thursday",
+ "date": "2026-02-05",
+ "meals": [
+ {
+ "meal": "dinner",
+ "name": "Pollo with Mix De Verduras and Pasta",
+ "servings": 5,
+ "ingredients": [
+ {
+ "name": "pollo",
+ "display_name": "Pollo",
+ "quantity": 750.0,
+ "unit": "g",
+ "display_quantity": "750.00 g"
+ },
+ {
+ "name": "mix de verduras",
+ "display_name": "Mix De Verduras",
+ "quantity": 600.0,
+ "unit": "g",
+ "display_quantity": "600.00 g"
+ },
+ {
+ "name": "pasta",
+ "display_name": "Pasta",
+ "quantity": 500.0,
+ "unit": "g",
+ "display_quantity": "500.00 g"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "day": "friday",
+ "date": "2026-02-06",
+ "meals": [
+ {
+ "meal": "dinner",
+ "name": "Chicken with Tomates Cherry and Arroz",
+ "servings": 5,
+ "ingredients": [
+ {
+ "name": "chicken",
+ "display_name": "Chicken",
+ "quantity": 750.0,
+ "unit": "g",
+ "display_quantity": "750.00 g"
+ },
+ {
+ "name": "tomates cherry",
+ "display_name": "Tomates Cherry",
+ "quantity": 600.0,
+ "unit": "g",
+ "display_quantity": "600.00 g"
+ },
+ {
+ "name": "arroz",
+ "display_name": "Arroz",
+ "quantity": 500.0,
+ "unit": "g",
+ "display_quantity": "500.00 g"
+ }
+ ]
+ },
+ {
+ "meal": "adult_lunch",
+ "name": "Pollo with Mix De Verduras and Pasta",
+ "servings": 1,
+ "ingredients": [
+ {
+ "name": "pollo",
+ "display_name": "Pollo",
+ "quantity": 150.0,
+ "unit": "g",
+ "display_quantity": "150.00 g"
+ },
+ {
+ "name": "mix de verduras",
+ "display_name": "Mix De Verduras",
+ "quantity": 120.0,
+ "unit": "g",
+ "display_quantity": "120.00 g"
+ },
+ {
+ "name": "pasta",
+ "display_name": "Pasta",
+ "quantity": 100.0,
+ "unit": "g",
+ "display_quantity": "100.00 g"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "day": "saturday",
+ "date": "2026-02-07",
+ "meals": [
+ {
+ "meal": "lunch",
+ "name": "Chicken with Tomates Cherry and Arroz",
+ "servings": 5,
+ "ingredients": [
+ {
+ "name": "chicken",
+ "display_name": "Chicken",
+ "quantity": 750.0,
+ "unit": "g",
+ "display_quantity": "750.00 g"
+ },
+ {
+ "name": "tomates cherry",
+ "display_name": "Tomates Cherry",
+ "quantity": 600.0,
+ "unit": "g",
+ "display_quantity": "600.00 g"
+ },
+ {
+ "name": "arroz",
+ "display_name": "Arroz",
+ "quantity": 500.0,
+ "unit": "g",
+ "display_quantity": "500.00 g"
+ }
+ ]
+ },
+ {
+ "meal": "dinner",
+ "name": "Pollo with Mix De Verduras and Pasta",
+ "servings": 5,
+ "ingredients": [
+ {
+ "name": "pollo",
+ "display_name": "Pollo",
+ "quantity": 750.0,
+ "unit": "g",
+ "display_quantity": "750.00 g"
+ },
+ {
+ "name": "mix de verduras",
+ "display_name": "Mix De Verduras",
+ "quantity": 600.0,
+ "unit": "g",
+ "display_quantity": "600.00 g"
+ },
+ {
+ "name": "pasta",
+ "display_name": "Pasta",
+ "quantity": 500.0,
+ "unit": "g",
+ "display_quantity": "500.00 g"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "day": "sunday",
+ "date": "2026-02-08",
+ "meals": [
+ {
+ "meal": "lunch",
+ "name": "Chicken with Tomates Cherry and Arroz",
+ "servings": 5,
+ "ingredients": [
+ {
+ "name": "chicken",
+ "display_name": "Chicken",
+ "quantity": 750.0,
+ "unit": "g",
+ "display_quantity": "750.00 g"
+ },
+ {
+ "name": "tomates cherry",
+ "display_name": "Tomates Cherry",
+ "quantity": 600.0,
+ "unit": "g",
+ "display_quantity": "600.00 g"
+ },
+ {
+ "name": "arroz",
+ "display_name": "Arroz",
+ "quantity": 500.0,
+ "unit": "g",
+ "display_quantity": "500.00 g"
+ }
+ ]
+ },
+ {
+ "meal": "dinner",
+ "name": "Pollo with Mix De Verduras and Pasta",
+ "servings": 5,
+ "ingredients": [
+ {
+ "name": "pollo",
+ "display_name": "Pollo",
+ "quantity": 750.0,
+ "unit": "g",
+ "display_quantity": "750.00 g"
+ },
+ {
+ "name": "mix de verduras",
+ "display_name": "Mix De Verduras",
+ "quantity": 600.0,
+ "unit": "g",
+ "display_quantity": "600.00 g"
+ },
+ {
+ "name": "pasta",
+ "display_name": "Pasta",
+ "quantity": 500.0,
+ "unit": "g",
+ "display_quantity": "500.00 g"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+}
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/data/shopping_list.json b/src/Reachy_OpenWebUI/sub_apps/cookAIware/data/shopping_list.json
new file mode 100644
index 0000000000000000000000000000000000000000..fea98059b1491dbcbcc42b259908a72faa701d23
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/data/shopping_list.json
@@ -0,0 +1,27 @@
+[
+ {
+ "name": "arroz",
+ "quantity": 1600,
+ "unit": "g"
+ },
+ {
+ "name": "mix de verduras",
+ "quantity": 2140,
+ "unit": "g"
+ },
+ {
+ "name": "pasta",
+ "quantity": 200,
+ "unit": "g"
+ },
+ {
+ "name": "pollo",
+ "quantity": 6700,
+ "unit": "g"
+ },
+ {
+ "name": "tomates cherry",
+ "quantity": 2620,
+ "unit": "g"
+ }
+]
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/data_store.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/data_store.py
new file mode 100644
index 0000000000000000000000000000000000000000..5da119ed37476da75dca57ca455c8fafb8a99c19
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/data_store.py
@@ -0,0 +1,32 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+
+def resolve_data_dir(instance_path: str | None) -> Path:
+ """Resolve and ensure the data directory for persistence."""
+ if instance_path:
+ base = Path(instance_path)
+ else:
+ base = Path(__file__).parent
+ data_dir = base / "data"
+ data_dir.mkdir(parents=True, exist_ok=True)
+ return data_dir
+
+
+def load_json(path: Path, default: Any) -> Any:
+ """Load JSON from disk, returning default if missing or invalid."""
+ try:
+ if not path.exists():
+ return default
+ return json.loads(path.read_text(encoding="utf-8"))
+ except Exception:
+ return default
+
+
+def save_json(path: Path, data: Any) -> None:
+ """Write JSON to disk."""
+ path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
+
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/family_profile.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/family_profile.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3a0ff93dfbd3a57dc61e94b73c1136dcab7be4a
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/family_profile.py
@@ -0,0 +1,58 @@
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any, Dict
+
+from Reachy_OpenWebUI.sub_apps.cookAIware.data_store import load_json, save_json
+
+
+PROFILE_FILE = "family_profile.json"
+
+
+def _profile_path(data_dir: Path) -> Path:
+ return data_dir / PROFILE_FILE
+
+
+def default_schedule() -> Dict[str, Any]:
+ return {
+ "weekday": {
+ "dinner": True,
+ "lunch_adults": 1,
+ "lunch_days": ["monday", "wednesday", "friday"],
+ },
+ "weekend": {
+ "breakfast": False,
+ "lunch": True,
+ "dinner": True,
+ },
+ }
+
+
+def load_profile(data_dir: Path) -> Dict[str, Any]:
+ profile = load_json(_profile_path(data_dir), {})
+ if not profile:
+ profile = {
+ "adults": None,
+ "children": None,
+ "schedule": default_schedule(),
+ }
+ if "schedule" not in profile or not isinstance(profile.get("schedule"), dict):
+ profile["schedule"] = default_schedule()
+ return profile
+
+
+def save_profile(data_dir: Path, profile: Dict[str, Any]) -> None:
+ save_json(_profile_path(data_dir), profile)
+
+
+def update_profile(data_dir: Path, adults: int | None, children: int | None, schedule: Dict[str, Any] | None) -> Dict[str, Any]:
+ profile = load_profile(data_dir)
+ if adults is not None:
+ profile["adults"] = int(adults)
+ if children is not None:
+ profile["children"] = int(children)
+ if schedule:
+ profile["schedule"] = schedule
+ save_profile(data_dir, profile)
+ return profile
+
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/headless_personality.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/headless_personality.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec56b729f3e5262f63d89ed6130a9faa97fa23c3
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/headless_personality.py
@@ -0,0 +1,102 @@
+"""Headless personality management (console-based).
+
+Provides an interactive CLI to browse, preview, apply, create and edit
+"personalities" (profiles) when running without Gradio.
+
+This module is intentionally not shared with the Gradio implementation to
+avoid coupling and keep responsibilities clear for headless mode.
+"""
+
+from __future__ import annotations
+from typing import List
+from pathlib import Path
+
+
+DEFAULT_OPTION = "(built-in default)"
+
+
+def _profiles_root() -> Path:
+ return Path(__file__).parent / "profiles"
+
+
+def _prompts_dir() -> Path:
+ return Path(__file__).parent / "prompts"
+
+
+def _tools_dir() -> Path:
+ return Path(__file__).parent / "tools"
+
+
+def _sanitize_name(name: str) -> str:
+ import re
+
+ s = name.strip()
+ s = re.sub(r"\s+", "_", s)
+ s = re.sub(r"[^a-zA-Z0-9_-]", "", s)
+ return s
+
+
+def list_personalities() -> List[str]:
+ """List available personality profile names."""
+ names: List[str] = []
+ root = _profiles_root()
+ try:
+ if root.exists():
+ for p in sorted(root.iterdir()):
+ if p.name == "user_personalities":
+ continue
+ if p.is_dir() and (p / "instructions.txt").exists():
+ names.append(p.name)
+ udir = root / "user_personalities"
+ if udir.exists():
+ for p in sorted(udir.iterdir()):
+ if p.is_dir() and (p / "instructions.txt").exists():
+ names.append(f"user_personalities/{p.name}")
+ except Exception:
+ pass
+ return names
+
+
+def resolve_profile_dir(selection: str) -> Path:
+ """Resolve the directory path for the given profile selection."""
+ return _profiles_root() / selection
+
+
+def read_instructions_for(name: str) -> str:
+ """Read the instructions.txt content for the given profile name."""
+ try:
+ if name == DEFAULT_OPTION:
+ df = _prompts_dir() / "default_prompt.txt"
+ return df.read_text(encoding="utf-8").strip() if df.exists() else ""
+ target = resolve_profile_dir(name) / "instructions.txt"
+ return target.read_text(encoding="utf-8").strip() if target.exists() else ""
+ except Exception as e:
+ return f"Could not load instructions: {e}"
+
+
+def available_tools_for(selected: str) -> List[str]:
+ """List available tool modules for the given profile selection."""
+ shared: List[str] = []
+ try:
+ for py in _tools_dir().glob("*.py"):
+ if py.stem in {"__init__", "core_tools"}:
+ continue
+ shared.append(py.stem)
+ except Exception:
+ pass
+ local: List[str] = []
+ try:
+ if selected != DEFAULT_OPTION:
+ for py in resolve_profile_dir(selected).glob("*.py"):
+ local.append(py.stem)
+ except Exception:
+ pass
+ return sorted(set(shared + local))
+
+
+def _write_profile(name_s: str, instructions: str, tools_text: str, voice: str = "cedar") -> None:
+ target_dir = _profiles_root() / "user_personalities" / name_s
+ target_dir.mkdir(parents=True, exist_ok=True)
+ (target_dir / "instructions.txt").write_text(instructions.strip() + "\n", encoding="utf-8")
+ (target_dir / "tools.txt").write_text((tools_text or "").strip() + "\n", encoding="utf-8")
+ (target_dir / "voice.txt").write_text((voice or "cedar").strip() + "\n", encoding="utf-8")
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/headless_personality_ui.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/headless_personality_ui.py
new file mode 100644
index 0000000000000000000000000000000000000000..90b87308070bbb54ff0b1f58ef2b7a01def894d0
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/headless_personality_ui.py
@@ -0,0 +1,287 @@
+"""Settings UI routes for headless personality management.
+
+Exposes REST endpoints on the provided FastAPI settings app. The
+implementation schedules backend actions (apply personality, fetch voices)
+onto the running LocalStream asyncio loop using the supplied get_loop
+callable to avoid cross-thread issues.
+"""
+
+from __future__ import annotations
+import asyncio
+import logging
+from typing import Any, Callable, Optional
+
+from fastapi import FastAPI
+
+from .config import LOCKED_PROFILE, config
+from .openai_realtime import OpenaiRealtimeHandler
+from .headless_personality import (
+ DEFAULT_OPTION,
+ _sanitize_name,
+ _write_profile,
+ list_personalities,
+ available_tools_for,
+ resolve_profile_dir,
+ read_instructions_for,
+)
+
+
+def mount_personality_routes(
+ app: FastAPI,
+ handler: OpenaiRealtimeHandler,
+ get_loop: Callable[[], asyncio.AbstractEventLoop | None],
+ *,
+ persist_personality: Callable[[Optional[str]], None] | None = None,
+ get_persisted_personality: Callable[[], Optional[str]] | None = None,
+) -> None:
+ """Register personality management endpoints on a FastAPI app."""
+ try:
+ from fastapi import Request
+ from pydantic import BaseModel
+ from fastapi.responses import JSONResponse
+ except Exception: # pragma: no cover - only when settings app not available
+ return
+
+ class SavePayload(BaseModel):
+ name: str
+ instructions: str
+ tools_text: str
+ voice: Optional[str] = "cedar"
+
+ class ApplyPayload(BaseModel):
+ name: str
+ persist: Optional[bool] = False
+
+ def _startup_choice() -> Any:
+ """Return the persisted startup personality or default."""
+ try:
+ if get_persisted_personality is not None:
+ stored = get_persisted_personality()
+ if stored:
+ return stored
+ env_val = getattr(config, "REACHY_MINI_CUSTOM_PROFILE", None)
+ if env_val:
+ return env_val
+ except Exception:
+ pass
+ return DEFAULT_OPTION
+
+ def _current_choice() -> str:
+ try:
+ cur = getattr(config, "REACHY_MINI_CUSTOM_PROFILE", None)
+ return cur or DEFAULT_OPTION
+ except Exception:
+ return DEFAULT_OPTION
+
+ @app.get("/personalities")
+ def _list() -> dict: # type: ignore
+ choices = [DEFAULT_OPTION, *list_personalities()]
+ return {
+ "choices": choices,
+ "current": _current_choice(),
+ "startup": _startup_choice(),
+ "locked": LOCKED_PROFILE is not None,
+ "locked_to": LOCKED_PROFILE,
+ }
+
+ @app.get("/personalities/load")
+ def _load(name: str) -> dict: # type: ignore
+ instr = read_instructions_for(name)
+ tools_txt = ""
+ voice = "cedar"
+ if name != DEFAULT_OPTION:
+ pdir = resolve_profile_dir(name)
+ tp = pdir / "tools.txt"
+ if tp.exists():
+ tools_txt = tp.read_text(encoding="utf-8")
+ vf = pdir / "voice.txt"
+ if vf.exists():
+ v = vf.read_text(encoding="utf-8").strip()
+ voice = v or "cedar"
+ avail = available_tools_for(name)
+ enabled = [ln.strip() for ln in tools_txt.splitlines() if ln.strip() and not ln.strip().startswith("#")]
+ return {
+ "instructions": instr,
+ "tools_text": tools_txt,
+ "voice": voice,
+ "available_tools": avail,
+ "enabled_tools": enabled,
+ }
+
+ @app.post("/personalities/save")
+ async def _save(request: Request) -> dict: # type: ignore
+ # Accept raw JSON only to avoid validation-related 422s
+ try:
+ raw = await request.json()
+ except Exception:
+ raw = {}
+ name = str(raw.get("name", ""))
+ instructions = str(raw.get("instructions", ""))
+ tools_text = str(raw.get("tools_text", ""))
+ voice = str(raw.get("voice", "cedar")) if raw.get("voice") is not None else "cedar"
+
+ name_s = _sanitize_name(name)
+ if not name_s:
+ return JSONResponse({"ok": False, "error": "invalid_name"}, status_code=400) # type: ignore
+ try:
+ logger.info(
+ "Headless save: name=%r voice=%r instr_len=%d tools_len=%d",
+ name_s,
+ voice,
+ len(instructions),
+ len(tools_text),
+ )
+ _write_profile(name_s, instructions, tools_text, voice or "cedar")
+ value = f"user_personalities/{name_s}"
+ choices = [DEFAULT_OPTION, *list_personalities()]
+ return {"ok": True, "value": value, "choices": choices}
+ except Exception as e:
+ return JSONResponse({"ok": False, "error": str(e)}, status_code=500) # type: ignore
+
+ @app.post("/personalities/save_raw")
+ async def _save_raw(
+ request: Request,
+ name: Optional[str] = None,
+ instructions: Optional[str] = None,
+ tools_text: Optional[str] = None,
+ voice: Optional[str] = None,
+ ) -> dict: # type: ignore
+ # Accept query params, form-encoded, or raw JSON
+ data = {"name": name, "instructions": instructions, "tools_text": tools_text, "voice": voice}
+ # Prefer form if present
+ try:
+ form = await request.form()
+ for k in ("name", "instructions", "tools_text", "voice"):
+ if k in form and form[k] is not None:
+ data[k] = str(form[k])
+ except Exception:
+ pass
+ # Try JSON
+ try:
+ raw = await request.json()
+ if isinstance(raw, dict):
+ for k in ("name", "instructions", "tools_text", "voice"):
+ if raw.get(k) is not None:
+ data[k] = str(raw.get(k))
+ except Exception:
+ pass
+
+ name_s = _sanitize_name(str(data.get("name") or ""))
+ if not name_s:
+ return JSONResponse({"ok": False, "error": "invalid_name"}, status_code=400) # type: ignore
+ instr = str(data.get("instructions") or "")
+ tools = str(data.get("tools_text") or "")
+ v = str(data.get("voice") or "cedar")
+ try:
+ logger.info(
+ "Headless save_raw: name=%r voice=%r instr_len=%d tools_len=%d", name_s, v, len(instr), len(tools)
+ )
+ _write_profile(name_s, instr, tools, v)
+ value = f"user_personalities/{name_s}"
+ choices = [DEFAULT_OPTION, *list_personalities()]
+ return {"ok": True, "value": value, "choices": choices}
+ except Exception as e:
+ return JSONResponse({"ok": False, "error": str(e)}, status_code=500) # type: ignore
+
+ @app.get("/personalities/save_raw")
+ async def _save_raw_get(name: str, instructions: str = "", tools_text: str = "", voice: str = "cedar") -> dict: # type: ignore
+ name_s = _sanitize_name(name)
+ if not name_s:
+ return JSONResponse({"ok": False, "error": "invalid_name"}, status_code=400) # type: ignore
+ try:
+ logger.info(
+ "Headless save_raw(GET): name=%r voice=%r instr_len=%d tools_len=%d",
+ name_s,
+ voice,
+ len(instructions),
+ len(tools_text),
+ )
+ _write_profile(name_s, instructions, tools_text, voice or "cedar")
+ value = f"user_personalities/{name_s}"
+ choices = [DEFAULT_OPTION, *list_personalities()]
+ return {"ok": True, "value": value, "choices": choices}
+ except Exception as e:
+ return JSONResponse({"ok": False, "error": str(e)}, status_code=500) # type: ignore
+
+ logger = logging.getLogger(__name__)
+
+ @app.post("/personalities/apply")
+ async def _apply(
+ payload: ApplyPayload | None = None,
+ name: str | None = None,
+ persist: Optional[bool] = None,
+ request: Optional[Request] = None,
+ ) -> dict: # type: ignore
+ if LOCKED_PROFILE is not None:
+ return JSONResponse(
+ {"ok": False, "error": "profile_locked", "locked_to": LOCKED_PROFILE},
+ status_code=403,
+ ) # type: ignore
+ loop = get_loop()
+ if loop is None:
+ return JSONResponse({"ok": False, "error": "loop_unavailable"}, status_code=503) # type: ignore
+
+ # Accept both JSON payload and query param for convenience
+ sel_name: Optional[str] = None
+ persist_flag = bool(persist) if persist is not None else False
+ if payload and getattr(payload, "name", None):
+ sel_name = payload.name
+ persist_flag = bool(getattr(payload, "persist", False))
+ elif name:
+ sel_name = name
+ elif request is not None:
+ try:
+ body = await request.json()
+ if isinstance(body, dict) and body.get("name"):
+ sel_name = str(body.get("name"))
+ if isinstance(body, dict) and "persist" in body:
+ persist_flag = bool(body.get("persist"))
+ except Exception:
+ sel_name = None
+ if request is not None:
+ try:
+ q_persist = request.query_params.get("persist")
+ if q_persist is not None:
+ persist_flag = str(q_persist).lower() in {"1", "true", "yes", "on"}
+ except Exception:
+ pass
+ if not sel_name:
+ sel_name = DEFAULT_OPTION
+
+ async def _do_apply() -> str:
+ sel = None if sel_name == DEFAULT_OPTION else sel_name
+ status = await handler.apply_personality(sel)
+ return status
+
+ try:
+ logger.info("Headless apply: requested name=%r", sel_name)
+ fut = asyncio.run_coroutine_threadsafe(_do_apply(), loop)
+ status = fut.result(timeout=10)
+ persisted_choice = _startup_choice()
+ if persist_flag and persist_personality is not None:
+ try:
+ persist_personality(None if sel_name == DEFAULT_OPTION else sel_name)
+ persisted_choice = _startup_choice()
+ except Exception as e:
+ logger.warning("Failed to persist startup personality: %s", e)
+ return {"ok": True, "status": status, "startup": persisted_choice}
+ except Exception as e:
+ return JSONResponse({"ok": False, "error": str(e)}, status_code=500) # type: ignore
+
+ @app.get("/voices")
+ async def _voices() -> list[str]:
+ loop = get_loop()
+ if loop is None:
+ return ["cedar"]
+
+ async def _get_v() -> list[str]:
+ try:
+ return await handler.get_available_voices()
+ except Exception:
+ return ["cedar"]
+
+ try:
+ fut = asyncio.run_coroutine_threadsafe(_get_v(), loop)
+ return fut.result(timeout=10)
+ except Exception:
+ return ["cedar"]
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/inventory.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/inventory.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b8c3bcb2eaffee90789f47fb5327b287c7496e5
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/inventory.py
@@ -0,0 +1,272 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import datetime
+from pathlib import Path
+from typing import Any, Dict, List, Tuple
+
+from Reachy_OpenWebUI.sub_apps.cookAIware.data_store import load_json, save_json
+from Reachy_OpenWebUI.sub_apps.cookAIware.units import normalize_quantity, normalize_unit, format_quantity
+
+
+INVENTORY_FILE = "inventory.json"
+
+
+@dataclass
+class InventoryItem:
+ name: str
+ quantity: float
+ unit: str
+ expiration_date: str | None
+ storage_location: str | None
+
+
+def _inventory_path(data_dir: Path) -> Path:
+ return data_dir / INVENTORY_FILE
+
+
+def _normalize_name(name: str) -> str:
+ return name.strip().lower()
+
+
+def _parse_date(date_str: str | None) -> str | None:
+ if not date_str:
+ return None
+ try:
+ parsed = datetime.fromisoformat(date_str.strip()).date()
+ return parsed.isoformat()
+ except Exception:
+ return None
+
+
+def load_inventory(data_dir: Path) -> List[Dict[str, Any]]:
+ return load_json(_inventory_path(data_dir), [])
+
+
+def save_inventory(data_dir: Path, items: List[Dict[str, Any]]) -> None:
+ save_json(_inventory_path(data_dir), items)
+
+
+def add_items(data_dir: Path, items: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[str]]:
+ inventory = load_inventory(data_dir)
+ errors: List[str] = []
+
+ for item in items:
+ raw_name = str(item.get("name", "")).strip()
+ name = _normalize_name(raw_name)
+ if not name:
+ errors.append("missing_name")
+ continue
+
+ expiration_date = _parse_date(item.get("expiration_date"))
+ if item.get("expiration_date") and not expiration_date:
+ errors.append(f"invalid_expiration_date:{name}")
+ continue
+
+ storage_location = item.get("storage_location")
+ if storage_location is not None:
+ storage_location = str(storage_location).strip() or None
+ auto_add_shopping = bool(item.get("auto_add_shopping"))
+ barcode = str(item.get("barcode") or "").strip() or None
+ brand = str(item.get("brand") or "").strip() or None
+ source = str(item.get("source") or "").strip() or None
+
+ normalized = normalize_quantity(item.get("quantity"), item.get("unit"))
+ if not normalized:
+ errors.append(f"invalid_quantity_or_unit:{name}")
+ continue
+ quantity, unit = normalized
+
+ merged = False
+ for inv in inventory:
+ if (
+ inv.get("name") == name
+ and inv.get("unit") == unit
+ and inv.get("expiration_date") == expiration_date
+ and inv.get("storage_location") == storage_location
+ ):
+ inv["quantity"] = float(inv.get("quantity", 0.0)) + quantity
+ if "auto_add_shopping" in item:
+ inv["auto_add_shopping"] = auto_add_shopping
+ if barcode:
+ inv["barcode"] = barcode
+ if brand:
+ inv["brand"] = brand
+ if source:
+ inv["source"] = source
+ if raw_name:
+ inv["display_name"] = raw_name
+ merged = True
+ break
+
+ if not merged:
+ inventory.append(
+ {
+ "name": name,
+ "display_name": raw_name or name,
+ "quantity": quantity,
+ "unit": unit,
+ "expiration_date": expiration_date,
+ "storage_location": storage_location,
+ "auto_add_shopping": auto_add_shopping,
+ "barcode": barcode,
+ "brand": brand,
+ "source": source,
+ }
+ )
+
+ save_inventory(data_dir, inventory)
+ return inventory, errors
+
+
+def cook_items(data_dir: Path, items: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[str]]:
+ inventory = load_inventory(data_dir)
+ errors: List[str] = []
+
+ for item in items:
+ name = _normalize_name(str(item.get("name", "")))
+ if not name:
+ errors.append("missing_name")
+ continue
+
+ normalized = normalize_quantity(item.get("quantity"), item.get("unit"))
+ if not normalized:
+ errors.append(f"invalid_quantity_or_unit:{name}")
+ continue
+ quantity_needed, unit = normalized
+
+ matching = [
+ inv
+ for inv in inventory
+ if inv.get("name") == name and inv.get("unit") == unit and float(inv.get("quantity", 0.0)) > 0
+ ]
+ if not matching:
+ errors.append(f"not_found:{name}")
+ continue
+
+ matching.sort(key=lambda inv: inv.get("expiration_date") or "9999-12-31")
+ remaining = quantity_needed
+ for inv in matching:
+ available = float(inv.get("quantity", 0.0))
+ if available <= 0:
+ continue
+ take = min(available, remaining)
+ inv["quantity"] = available - take
+ remaining -= take
+ if remaining <= 0:
+ break
+
+ if remaining > 0:
+ errors.append(f"insufficient_quantity:{name}")
+
+ save_inventory(data_dir, inventory)
+ return inventory, errors
+
+
+def list_inventory(data_dir: Path) -> List[Dict[str, Any]]:
+ inventory = load_inventory(data_dir)
+ inventory.sort(key=lambda inv: (inv.get("expiration_date") or "9999-12-31", inv.get("name", "")))
+ return inventory
+
+
+def set_auto_add_shopping(data_dir: Path, items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
+ inventory = load_inventory(data_dir)
+ for item in items:
+ name = _normalize_name(str(item.get("name", "")))
+ unit = str(item.get("unit") or "").strip()
+ expiration_date = _parse_date(item.get("expiration_date"))
+ storage_location = item.get("storage_location")
+ if storage_location is not None:
+ storage_location = str(storage_location).strip() or None
+ for inv in inventory:
+ if (
+ inv.get("name") == name
+ and inv.get("unit") == unit
+ and inv.get("expiration_date") == expiration_date
+ and inv.get("storage_location") == storage_location
+ ):
+ inv["auto_add_shopping"] = bool(item.get("auto_add_shopping"))
+ break
+ save_inventory(data_dir, inventory)
+ return inventory
+
+
+def format_inventory(items: List[Dict[str, Any]], unit_system: str = "metric") -> List[str]:
+ output: List[str] = []
+ for item in items:
+ qty = float(item.get("quantity", 0.0))
+ unit = item.get("unit", "")
+ label = item.get("display_name") or item.get("name", "")
+ exp = item.get("expiration_date")
+ loc = item.get("storage_location")
+ parts = [label, format_quantity(qty, unit, unit_system)]
+ if exp:
+ parts.append(f"exp {exp}")
+ if loc:
+ parts.append(f"stored {loc}")
+ output.append(" - ".join(parts))
+ return output
+
+
+def available_quantity(items: List[Dict[str, Any]], name: str, unit: str) -> float:
+ total = 0.0
+ for item in items:
+ if item.get("name") == name and item.get("unit") == unit:
+ total += float(item.get("quantity", 0.0))
+ return total
+
+
+def unit_for_item(items: List[Dict[str, Any]], name: str) -> str | None:
+ for item in items:
+ if item.get("name") == name:
+ return item.get("unit")
+ return None
+
+
+def normalize_for_display(items: List[Dict[str, Any]], unit_system: str = "metric") -> List[Dict[str, Any]]:
+ result: List[Dict[str, Any]] = []
+ for item in items:
+ unit = item.get("unit")
+ quantity = float(item.get("quantity", 0.0))
+ display_qty = format_quantity(quantity, unit, unit_system) if unit else str(quantity)
+ result.append(
+ {
+ **item,
+ "display_name": item.get("display_name") or item.get("name"),
+ "display_quantity": display_qty,
+ }
+ )
+ return result
+
+
+def normalize_items_for_save(items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
+ normalized_items: List[Dict[str, Any]] = []
+ for item in items:
+ raw_name = str(item.get("name", "")).strip()
+ name = _normalize_name(raw_name)
+ if not name:
+ continue
+ expiration_date = _parse_date(item.get("expiration_date"))
+ storage_location = item.get("storage_location")
+ if storage_location is not None:
+ storage_location = str(storage_location).strip() or None
+ normalized = normalize_quantity(item.get("quantity"), item.get("unit"))
+ if not normalized:
+ continue
+ quantity, unit = normalized
+ normalized_items.append(
+ {
+ "name": name,
+ "display_name": raw_name or name,
+ "quantity": quantity,
+ "unit": unit,
+ "expiration_date": expiration_date,
+ "storage_location": storage_location,
+ "auto_add_shopping": bool(item.get("auto_add_shopping")),
+ "barcode": str(item.get("barcode") or "").strip() or None,
+ "brand": str(item.get("brand") or "").strip() or None,
+ "source": str(item.get("source") or "").strip() or None,
+ }
+ )
+ return normalized_items
+
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/meal_planner.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/meal_planner.py
new file mode 100644
index 0000000000000000000000000000000000000000..dacb5c7bf08f24bdd0c5415f7a8e5f12df95d341
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/meal_planner.py
@@ -0,0 +1,346 @@
+from __future__ import annotations
+
+from datetime import date, datetime, timedelta
+from pathlib import Path
+from typing import Any, Dict, List, Tuple
+
+from Reachy_OpenWebUI.sub_apps.cookAIware.data_store import load_json, save_json
+from Reachy_OpenWebUI.sub_apps.cookAIware.family_profile import default_schedule
+from Reachy_OpenWebUI.sub_apps.cookAIware.inventory import unit_for_item
+from Reachy_OpenWebUI.sub_apps.cookAIware.units import format_quantity
+
+
+MEAL_PLAN_FILE = "meal_plan.json"
+
+
+DAY_NAMES = [
+ "monday",
+ "tuesday",
+ "wednesday",
+ "thursday",
+ "friday",
+ "saturday",
+ "sunday",
+]
+
+
+PROTEIN_KEYS = {
+ "chicken",
+ "turkey",
+ "beef",
+ "pork",
+ "fish",
+ "salmon",
+ "tuna",
+ "tofu",
+}
+LEGUME_KEYS = {"beans", "lentils", "chickpeas"}
+VEG_KEYS = {
+ "broccoli",
+ "carrot",
+ "spinach",
+ "lettuce",
+ "pepper",
+ "tomato",
+ "zucchini",
+ "onion",
+ "salad",
+ "mixed vegetables",
+ "vegetable mix",
+}
+GRAIN_KEYS = {"rice", "pasta", "bread", "oats", "quinoa", "couscous", "wrap", "flatbread"}
+DAIRY_KEYS = {"milk", "yogurt", "cheese"}
+FRUIT_KEYS = {
+ "apple",
+ "banana",
+ "orange",
+ "berries",
+ "grape",
+ "pear",
+}
+
+
+def _plan_path(data_dir: Path) -> Path:
+ return data_dir / MEAL_PLAN_FILE
+
+
+def _normalize_name(name: str) -> str:
+ return name.strip().lower()
+
+
+def _display_name(name: str) -> str:
+ return " ".join(part.capitalize() for part in _normalize_name(name).split())
+
+
+def categorize(name: str) -> str:
+ n = _normalize_name(name)
+ for key in PROTEIN_KEYS:
+ if key in n:
+ return "protein"
+ for key in LEGUME_KEYS:
+ if key in n:
+ return "legume"
+ for key in VEG_KEYS:
+ if key in n:
+ return "veg"
+ for key in GRAIN_KEYS:
+ if key in n:
+ return "grain"
+ for key in DAIRY_KEYS:
+ if key in n:
+ return "dairy"
+ for key in FRUIT_KEYS:
+ if key in n:
+ return "fruit"
+ return "other"
+
+
+def week_start_for(today: date | None = None) -> date:
+ today = today or date.today()
+ return today - timedelta(days=today.weekday())
+
+
+def load_plan(data_dir: Path) -> Dict[str, Any]:
+ return load_json(_plan_path(data_dir), {})
+
+
+def save_plan(data_dir: Path, plan: Dict[str, Any]) -> None:
+ save_json(_plan_path(data_dir), plan)
+
+
+def _default_meal_slots(schedule: Dict[str, Any]) -> List[Dict[str, Any]]:
+ slots: List[Dict[str, Any]] = []
+ weekday = schedule.get("weekday", {})
+ weekend = schedule.get("weekend", {})
+ lunch_days = set((weekday.get("lunch_days") or []))
+
+ for idx, day in enumerate(DAY_NAMES):
+ is_weekend = idx >= 5
+ meals: List[Dict[str, Any]] = []
+ if is_weekend:
+ if weekend.get("breakfast"):
+ meals.append({"meal": "breakfast", "servings": None})
+ if weekend.get("lunch"):
+ meals.append({"meal": "lunch", "servings": None})
+ if weekend.get("dinner"):
+ meals.append({"meal": "dinner", "servings": None})
+ else:
+ if weekday.get("dinner"):
+ meals.append({"meal": "dinner", "servings": None})
+ if day in lunch_days:
+ meals.append({"meal": "adult_lunch", "servings": 1})
+
+ slots.append({"day": day, "meals": meals})
+ return slots
+
+
+def _select_ingredients(inventory: List[Dict[str, Any]], meal_type: str, start_idx: int) -> Tuple[List[str], int]:
+ names = [str(item.get("name")) for item in inventory if item.get("name")]
+ if not names:
+ return [], start_idx
+
+ proteins = [n for n in names if categorize(n) == "protein"]
+ legumes = [n for n in names if categorize(n) == "legume"]
+ vegs = [n for n in names if categorize(n) == "veg"]
+ grains = [n for n in names if categorize(n) == "grain"]
+ dairies = [n for n in names if categorize(n) == "dairy"]
+ fruits = [n for n in names if categorize(n) == "fruit"]
+ others = [n for n in names if categorize(n) == "other"]
+
+ ingredients: List[str] = []
+
+ def pick(pool: List[str]) -> str | None:
+ nonlocal start_idx
+ if not pool:
+ return None
+ choice = pool[start_idx % len(pool)]
+ start_idx += 1
+ return choice
+
+ def pick_from_category(cat: str) -> str | None:
+ pools = {
+ "protein": proteins,
+ "legume": legumes,
+ "veg": vegs,
+ "grain": grains,
+ "dairy": dairies,
+ "fruit": fruits,
+ "other": others,
+ }
+ return pick(pools.get(cat, []))
+
+ if meal_type in ("breakfast",):
+ templates = [
+ ["dairy", "fruit", "grain"],
+ ["fruit", "grain"],
+ ["dairy", "grain"],
+ ]
+ else:
+ templates = [
+ ["protein", "veg", "grain"],
+ ["legume", "veg", "grain"],
+ ["protein", "veg"],
+ ["legume", "veg"],
+ ["grain", "veg"],
+ ]
+
+ for template in templates:
+ candidate: List[str] = []
+ for cat in template:
+ item = pick_from_category(cat)
+ if item and item not in candidate:
+ candidate.append(item)
+ if candidate:
+ ingredients = candidate
+ break
+
+ if not ingredients and names:
+ ingredients = [names[start_idx % len(names)]]
+ start_idx += 1
+
+ return ingredients, start_idx
+
+
+def _estimate_per_serving(unit: str, category: str) -> float:
+ if unit == "g":
+ if category == "protein":
+ return 150.0
+ if category == "legume":
+ return 140.0
+ if category == "veg":
+ return 120.0
+ if category == "grain":
+ return 100.0
+ return 80.0
+ if unit == "ml":
+ return 200.0
+ if unit == "pcs":
+ return 1.0
+ return 1.0
+
+
+def build_ingredient_entries(
+ inventory: List[Dict[str, Any]],
+ ingredient_names: List[str],
+ servings: int,
+ unit_system: str = "metric",
+) -> List[Dict[str, Any]]:
+ entries: List[Dict[str, Any]] = []
+ for ing in ingredient_names:
+ unit = unit_for_item(inventory, ing) or "pcs"
+ per_serving = _estimate_per_serving(unit, categorize(ing))
+ required = per_serving * servings
+ entries.append(
+ {
+ "name": ing,
+ "display_name": _display_name(ing),
+ "quantity": required,
+ "unit": unit,
+ "display_quantity": format_quantity(required, unit, unit_system),
+ }
+ )
+ return entries
+
+
+def generate_plan(
+ data_dir: Path,
+ inventory: List[Dict[str, Any]],
+ adults: int,
+ children: int,
+ schedule_override: Dict[str, Any] | None = None,
+ unit_system: str = "metric",
+) -> Dict[str, Any]:
+ schedule = schedule_override or default_schedule()
+ week_start = week_start_for().isoformat()
+ meal_slots = _default_meal_slots(schedule)
+
+ servings_all = adults + children
+ index = 0
+ plan_days: List[Dict[str, Any]] = []
+ last_signature: str | None = None
+
+ for day_idx, day_slot in enumerate(meal_slots):
+ day_name = day_slot["day"]
+ day_date = (week_start_for() + timedelta(days=day_idx)).isoformat()
+ meals_out: List[Dict[str, Any]] = []
+ for meal in day_slot["meals"]:
+ meal_type = meal["meal"]
+ servings = meal.get("servings") or servings_all
+ ingredients = []
+ for _ in range(3):
+ candidate, index = _select_ingredients(inventory, meal_type, index)
+ signature = ",".join(sorted(candidate))
+ if signature and signature == last_signature:
+ index += 1
+ continue
+ ingredients = candidate
+ last_signature = signature
+ break
+ ingredient_entries: List[Dict[str, Any]] = []
+ for ing in ingredients:
+ unit = unit_for_item(inventory, ing) or "pcs"
+ per_serving = _estimate_per_serving(unit, categorize(ing))
+ required = per_serving * servings
+ ingredient_entries.append(
+ {
+ "name": ing,
+ "display_name": _display_name(ing),
+ "quantity": required,
+ "unit": unit,
+ "display_quantity": format_quantity(required, unit, unit_system),
+ }
+ )
+ if ingredients:
+ if len(ingredients) == 1:
+ meal_name = _display_name(ingredients[0])
+ elif len(ingredients) == 2:
+ meal_name = f"{_display_name(ingredients[0])} with {_display_name(ingredients[1])}"
+ else:
+ meal_name = f"{_display_name(ingredients[0])} with {_display_name(ingredients[1])} and {_display_name(ingredients[2])}"
+ else:
+ meal_name = "No available ingredients"
+ meals_out.append(
+ {
+ "meal": meal_type,
+ "name": meal_name,
+ "servings": servings,
+ "ingredients": ingredient_entries,
+ }
+ )
+ plan_days.append({"day": day_name, "date": day_date, "meals": meals_out})
+
+ plan = {
+ "week_start": week_start,
+ "schedule": schedule,
+ "days": plan_days,
+ }
+ save_plan(data_dir, plan)
+ return plan
+
+
+def meal_for_day(plan: Dict[str, Any], day: str | None, date_str: str | None) -> Dict[str, Any] | None:
+ if not plan:
+ return None
+ if date_str:
+ for entry in plan.get("days", []):
+ if entry.get("date") == date_str:
+ return entry
+ if day:
+ day_norm = day.strip().lower()
+ for entry in plan.get("days", []):
+ if entry.get("day") == day_norm:
+ return entry
+ return None
+
+
+def resolve_day_to_date(day: str) -> str | None:
+ try:
+ day_norm = day.strip().lower()
+ except Exception:
+ return None
+ if day_norm not in DAY_NAMES:
+ return None
+ start = week_start_for()
+ idx = DAY_NAMES.index(day_norm)
+ return (start + timedelta(days=idx)).isoformat()
+
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/moves.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/moves.py
new file mode 100644
index 0000000000000000000000000000000000000000..21c912e7ffed0e0101fdfee3b97e7c9ef84a45e5
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/moves.py
@@ -0,0 +1,849 @@
+"""Movement system with sequential primary moves and additive secondary moves.
+
+Design overview
+- Primary moves (emotions, dances, goto, breathing) are mutually exclusive and run
+ sequentially.
+- Secondary moves (speech sway, face tracking) are additive offsets applied on top
+ of the current primary pose.
+- There is a single control point to the robot: `ReachyMini.set_target`.
+- The control loop runs near 100 Hz and is phase-aligned via a monotonic clock.
+- Idle behaviour starts an infinite `BreathingMove` after a short inactivity delay
+ unless listening is active.
+
+Threading model
+- A dedicated worker thread owns all real-time state and issues `set_target`
+ commands.
+- Other threads communicate via a command queue (enqueue moves, mark activity,
+ toggle listening).
+- Secondary offset producers set pending values guarded by locks; the worker
+ snaps them atomically.
+
+Units and frames
+- Secondary offsets are interpreted as metres for x/y/z and radians for
+ roll/pitch/yaw in the world frame (unless noted by `compose_world_offset`).
+- Antennas and `body_yaw` are in radians.
+- Head pose composition uses `compose_world_offset(primary_head, secondary_head)`;
+ the secondary offset must therefore be expressed in the world frame.
+
+Safety
+- Listening freezes antennas, then blends them back on unfreeze.
+- Interpolations and blends are used to avoid jumps at all times.
+- `set_target` errors are rate-limited in logs.
+"""
+
+from __future__ import annotations
+import time
+import logging
+import threading
+from queue import Empty, Queue
+from typing import Any, Dict, Tuple
+from collections import deque
+from dataclasses import dataclass
+
+import numpy as np
+from numpy.typing import NDArray
+
+from reachy_mini import ReachyMini
+from reachy_mini.utils import create_head_pose
+from reachy_mini.motion.move import Move
+from reachy_mini.utils.interpolation import (
+ compose_world_offset,
+ linear_pose_interpolation,
+)
+
+
+logger = logging.getLogger(__name__)
+
+# Configuration constants
+CONTROL_LOOP_FREQUENCY_HZ = 100.0 # Hz - Target frequency for the movement control loop
+
+# Type definitions
+FullBodyPose = Tuple[NDArray[np.float32], Tuple[float, float], float] # (head_pose_4x4, antennas, body_yaw)
+
+
+class BreathingMove(Move): # type: ignore
+ """Breathing move with interpolation to neutral and then continuous breathing patterns."""
+
+ def __init__(
+ self,
+ interpolation_start_pose: NDArray[np.float32],
+ interpolation_start_antennas: Tuple[float, float],
+ interpolation_duration: float = 1.0,
+ ):
+ """Initialize breathing move.
+
+ Args:
+ interpolation_start_pose: 4x4 matrix of current head pose to interpolate from
+ interpolation_start_antennas: Current antenna positions to interpolate from
+ interpolation_duration: Duration of interpolation to neutral (seconds)
+
+ """
+ self.interpolation_start_pose = interpolation_start_pose
+ self.interpolation_start_antennas = np.array(interpolation_start_antennas)
+ self.interpolation_duration = interpolation_duration
+
+ # Neutral positions for breathing base
+ self.neutral_head_pose = create_head_pose(0, 0, 0, 0, 0, 0, degrees=True)
+ self.neutral_antennas = np.array([0.0, 0.0])
+
+ # Breathing parameters
+ self.breathing_z_amplitude = 0.005 # 5mm gentle breathing
+ self.breathing_frequency = 0.1 # Hz (6 breaths per minute)
+ self.antenna_sway_amplitude = np.deg2rad(15) # 15 degrees
+ self.antenna_frequency = 0.5 # Hz (faster antenna sway)
+
+ @property
+ def duration(self) -> float:
+ """Duration property required by official Move interface."""
+ return float("inf") # Continuous breathing (never ends naturally)
+
+ def evaluate(self, t: float) -> tuple[NDArray[np.float64] | None, NDArray[np.float64] | None, float | None]:
+ """Evaluate breathing move at time t."""
+ if t < self.interpolation_duration:
+ # Phase 1: Interpolate to neutral base position
+ interpolation_t = t / self.interpolation_duration
+
+ # Interpolate head pose
+ head_pose = linear_pose_interpolation(
+ self.interpolation_start_pose, self.neutral_head_pose, interpolation_t,
+ )
+
+ # Interpolate antennas
+ antennas_interp = (
+ 1 - interpolation_t
+ ) * self.interpolation_start_antennas + interpolation_t * self.neutral_antennas
+ antennas = antennas_interp.astype(np.float64)
+
+ else:
+ # Phase 2: Breathing patterns from neutral base
+ breathing_time = t - self.interpolation_duration
+
+ # Gentle z-axis breathing
+ z_offset = self.breathing_z_amplitude * np.sin(2 * np.pi * self.breathing_frequency * breathing_time)
+ head_pose = create_head_pose(x=0, y=0, z=z_offset, roll=0, pitch=0, yaw=0, degrees=True, mm=False)
+
+ # Antenna sway (opposite directions)
+ antenna_sway = self.antenna_sway_amplitude * np.sin(2 * np.pi * self.antenna_frequency * breathing_time)
+ antennas = np.array([antenna_sway, -antenna_sway], dtype=np.float64)
+
+ # Return in official Move interface format: (head_pose, antennas_array, body_yaw)
+ return (head_pose, antennas, 0.0)
+
+
+def combine_full_body(primary_pose: FullBodyPose, secondary_pose: FullBodyPose) -> FullBodyPose:
+ """Combine primary and secondary full body poses.
+
+ Args:
+ primary_pose: (head_pose, antennas, body_yaw) - primary move
+ secondary_pose: (head_pose, antennas, body_yaw) - secondary offsets
+
+ Returns:
+ Combined full body pose (head_pose, antennas, body_yaw)
+
+ """
+ primary_head, primary_antennas, primary_body_yaw = primary_pose
+ secondary_head, secondary_antennas, secondary_body_yaw = secondary_pose
+
+ # Combine head poses using compose_world_offset; the secondary pose must be an
+ # offset expressed in the world frame (T_off_world) applied to the absolute
+ # primary transform (T_abs).
+ combined_head = compose_world_offset(primary_head, secondary_head, reorthonormalize=True)
+
+ # Sum antennas and body_yaw
+ combined_antennas = (
+ primary_antennas[0] + secondary_antennas[0],
+ primary_antennas[1] + secondary_antennas[1],
+ )
+ combined_body_yaw = primary_body_yaw + secondary_body_yaw
+
+ return (combined_head, combined_antennas, combined_body_yaw)
+
+
+def clone_full_body_pose(pose: FullBodyPose) -> FullBodyPose:
+ """Create a deep copy of a full body pose tuple."""
+ head, antennas, body_yaw = pose
+ return (head.copy(), (float(antennas[0]), float(antennas[1])), float(body_yaw))
+
+
+@dataclass
+class MovementState:
+ """State tracking for the movement system."""
+
+ # Primary move state
+ current_move: Move | None = None
+ move_start_time: float | None = None
+ last_activity_time: float = 0.0
+
+ # Secondary move state (offsets)
+ speech_offsets: Tuple[float, float, float, float, float, float] = (
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ )
+ face_tracking_offsets: Tuple[float, float, float, float, float, float] = (
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ )
+
+ # Status flags
+ last_primary_pose: FullBodyPose | None = None
+
+ def update_activity(self) -> None:
+ """Update the last activity time."""
+ self.last_activity_time = time.monotonic()
+
+
+@dataclass
+class LoopFrequencyStats:
+ """Track rolling loop frequency statistics."""
+
+ mean: float = 0.0
+ m2: float = 0.0
+ min_freq: float = float("inf")
+ count: int = 0
+ last_freq: float = 0.0
+ potential_freq: float = 0.0
+
+ def reset(self) -> None:
+ """Reset accumulators while keeping the last potential frequency."""
+ self.mean = 0.0
+ self.m2 = 0.0
+ self.min_freq = float("inf")
+ self.count = 0
+
+
+class MovementManager:
+ """Coordinate sequential moves, additive offsets, and robot output at 100 Hz.
+
+ Responsibilities:
+ - Own a real-time loop that samples the current primary move (if any), fuses
+ secondary offsets, and calls `set_target` exactly once per tick.
+ - Start an idle `BreathingMove` after `idle_inactivity_delay` when not
+ listening and no moves are queued.
+ - Expose thread-safe APIs so other threads can enqueue moves, mark activity,
+ or feed secondary offsets without touching internal state.
+
+ Timing:
+ - All elapsed-time calculations rely on `time.monotonic()` through `self._now`
+ to avoid wall-clock jumps.
+ - The loop attempts 100 Hz
+
+ Concurrency:
+ - External threads communicate via `_command_queue` messages.
+ - Secondary offsets are staged via dirty flags guarded by locks and consumed
+ atomically inside the worker loop.
+ """
+
+ def __init__(
+ self,
+ current_robot: ReachyMini,
+ camera_worker: "Any" = None,
+ ):
+ """Initialize movement manager."""
+ self.current_robot = current_robot
+ self.camera_worker = camera_worker
+
+ # Single timing source for durations
+ self._now = time.monotonic
+
+ # Movement state
+ self.state = MovementState()
+ self.state.last_activity_time = self._now()
+ neutral_pose = create_head_pose(0, 0, 0, 0, 0, 0, degrees=True)
+ self.state.last_primary_pose = (neutral_pose, (0.0, 0.0), 0.0)
+
+ # Move queue (primary moves)
+ self.move_queue: deque[Move] = deque()
+
+ # Configuration
+ self.idle_inactivity_delay = 0.3 # seconds
+ self.target_frequency = CONTROL_LOOP_FREQUENCY_HZ
+ self.target_period = 1.0 / self.target_frequency
+
+ self._stop_event = threading.Event()
+ self._thread: threading.Thread | None = None
+ self._is_listening = False
+ self._last_commanded_pose: FullBodyPose = clone_full_body_pose(self.state.last_primary_pose)
+ self._listening_antennas: Tuple[float, float] = self._last_commanded_pose[1]
+ self._antenna_unfreeze_blend = 1.0
+ self._antenna_blend_duration = 0.4 # seconds to blend back after listening
+ self._last_listening_blend_time = self._now()
+ self._breathing_active = False # true when breathing move is running or queued
+ self._listening_debounce_s = 0.15
+ self._last_listening_toggle_time = self._now()
+ self._last_set_target_err = 0.0
+ self._set_target_err_interval = 1.0 # seconds between error logs
+ self._set_target_err_suppressed = 0
+
+ # Cross-thread signalling
+ self._command_queue: "Queue[Tuple[str, Any]]" = Queue()
+ self._speech_offsets_lock = threading.Lock()
+ self._pending_speech_offsets: Tuple[float, float, float, float, float, float] = (
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ )
+ self._speech_offsets_dirty = False
+
+ self._face_offsets_lock = threading.Lock()
+ self._pending_face_offsets: Tuple[float, float, float, float, float, float] = (
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ )
+ self._face_offsets_dirty = False
+
+ self._shared_state_lock = threading.Lock()
+ self._shared_last_activity_time = self.state.last_activity_time
+ self._shared_is_listening = self._is_listening
+ self._status_lock = threading.Lock()
+ self._freq_stats = LoopFrequencyStats()
+ self._freq_snapshot = LoopFrequencyStats()
+
+ def queue_move(self, move: Move) -> None:
+ """Queue a primary move to run after the currently executing one.
+
+ Thread-safe: the move is enqueued via the worker command queue so the
+ control loop remains the sole mutator of movement state.
+ """
+ self._command_queue.put(("queue_move", move))
+
+ def clear_move_queue(self) -> None:
+ """Stop the active move and discard any queued primary moves.
+
+ Thread-safe: executed by the worker thread via the command queue.
+ """
+ self._command_queue.put(("clear_queue", None))
+
+ def set_speech_offsets(self, offsets: Tuple[float, float, float, float, float, float]) -> None:
+ """Update speech-induced secondary offsets (x, y, z, roll, pitch, yaw).
+
+ Offsets are interpreted as metres for translation and radians for
+ rotation in the world frame. Thread-safe via a pending snapshot.
+ """
+ with self._speech_offsets_lock:
+ self._pending_speech_offsets = offsets
+ self._speech_offsets_dirty = True
+
+ def set_moving_state(self, duration: float) -> None:
+ """Mark the robot as actively moving for the provided duration.
+
+ Legacy hook used by goto helpers to keep inactivity and breathing logic
+ aware of manual motions. Thread-safe via the command queue.
+ """
+ self._command_queue.put(("set_moving_state", duration))
+
+ def is_idle(self) -> bool:
+ """Return True when the robot has been inactive longer than the idle delay."""
+ with self._shared_state_lock:
+ last_activity = self._shared_last_activity_time
+ listening = self._shared_is_listening
+
+ if listening:
+ return False
+
+ return self._now() - last_activity >= self.idle_inactivity_delay
+
+ def set_listening(self, listening: bool) -> None:
+ """Enable or disable listening mode without touching shared state directly.
+
+ While listening:
+ - Antenna positions are frozen at the last commanded values.
+ - Blending is reset so that upon unfreezing the antennas return smoothly.
+ - Idle breathing is suppressed.
+
+ Thread-safe: the change is posted to the worker command queue.
+ """
+ with self._shared_state_lock:
+ if self._shared_is_listening == listening:
+ return
+ self._command_queue.put(("set_listening", listening))
+
+ def _poll_signals(self, current_time: float) -> None:
+ """Apply queued commands and pending offset updates."""
+ self._apply_pending_offsets()
+
+ while True:
+ try:
+ command, payload = self._command_queue.get_nowait()
+ except Empty:
+ break
+ self._handle_command(command, payload, current_time)
+
+ def _apply_pending_offsets(self) -> None:
+ """Apply the most recent speech/face offset updates."""
+ speech_offsets: Tuple[float, float, float, float, float, float] | None = None
+ with self._speech_offsets_lock:
+ if self._speech_offsets_dirty:
+ speech_offsets = self._pending_speech_offsets
+ self._speech_offsets_dirty = False
+
+ if speech_offsets is not None:
+ self.state.speech_offsets = speech_offsets
+ self.state.update_activity()
+
+ face_offsets: Tuple[float, float, float, float, float, float] | None = None
+ with self._face_offsets_lock:
+ if self._face_offsets_dirty:
+ face_offsets = self._pending_face_offsets
+ self._face_offsets_dirty = False
+
+ if face_offsets is not None:
+ self.state.face_tracking_offsets = face_offsets
+ self.state.update_activity()
+
+ def _handle_command(self, command: str, payload: Any, current_time: float) -> None:
+ """Handle a single cross-thread command."""
+ if command == "queue_move":
+ if isinstance(payload, Move):
+ self.move_queue.append(payload)
+ self.state.update_activity()
+ duration = getattr(payload, "duration", None)
+ if duration is not None:
+ try:
+ duration_str = f"{float(duration):.2f}"
+ except (TypeError, ValueError):
+ duration_str = str(duration)
+ else:
+ duration_str = "?"
+ logger.debug(
+ "Queued move with duration %ss, queue size: %s",
+ duration_str,
+ len(self.move_queue),
+ )
+ else:
+ logger.warning("Ignored queue_move command with invalid payload: %s", payload)
+ elif command == "clear_queue":
+ self.move_queue.clear()
+ self.state.current_move = None
+ self.state.move_start_time = None
+ self._breathing_active = False
+ logger.info("Cleared move queue and stopped current move")
+ elif command == "set_moving_state":
+ try:
+ duration = float(payload)
+ except (TypeError, ValueError):
+ logger.warning("Invalid moving state duration: %s", payload)
+ return
+ self.state.update_activity()
+ elif command == "mark_activity":
+ self.state.update_activity()
+ elif command == "set_listening":
+ desired_state = bool(payload)
+ now = self._now()
+ if now - self._last_listening_toggle_time < self._listening_debounce_s:
+ return
+ self._last_listening_toggle_time = now
+
+ if self._is_listening == desired_state:
+ return
+
+ self._is_listening = desired_state
+ self._last_listening_blend_time = now
+ if desired_state:
+ # Freeze: snapshot current commanded antennas and reset blend
+ self._listening_antennas = (
+ float(self._last_commanded_pose[1][0]),
+ float(self._last_commanded_pose[1][1]),
+ )
+ self._antenna_unfreeze_blend = 0.0
+ else:
+ # Unfreeze: restart blending from frozen pose
+ self._antenna_unfreeze_blend = 0.0
+ self.state.update_activity()
+ else:
+ logger.warning("Unknown command received by MovementManager: %s", command)
+
+ def _publish_shared_state(self) -> None:
+ """Expose idle-related state for external threads."""
+ with self._shared_state_lock:
+ self._shared_last_activity_time = self.state.last_activity_time
+ self._shared_is_listening = self._is_listening
+
+ def _manage_move_queue(self, current_time: float) -> None:
+ """Manage the primary move queue (sequential execution)."""
+ if self.state.current_move is None or (
+ self.state.move_start_time is not None
+ and current_time - self.state.move_start_time >= self.state.current_move.duration
+ ):
+ self.state.current_move = None
+ self.state.move_start_time = None
+
+ if self.move_queue:
+ self.state.current_move = self.move_queue.popleft()
+ self.state.move_start_time = current_time
+ # Any real move cancels breathing mode flag
+ self._breathing_active = isinstance(self.state.current_move, BreathingMove)
+ logger.debug(f"Starting new move, duration: {self.state.current_move.duration}s")
+
+ def _manage_breathing(self, current_time: float) -> None:
+ """Manage automatic breathing when idle."""
+ if (
+ self.state.current_move is None
+ and not self.move_queue
+ and not self._is_listening
+ and not self._breathing_active
+ ):
+ idle_for = current_time - self.state.last_activity_time
+ if idle_for >= self.idle_inactivity_delay:
+ try:
+ # These 2 functions return the latest available sensor data from the robot, but don't perform I/O synchronously.
+ # Therefore, we accept calling them inside the control loop.
+ _, current_antennas = self.current_robot.get_current_joint_positions()
+ current_head_pose = self.current_robot.get_current_head_pose()
+
+ self._breathing_active = True
+ self.state.update_activity()
+
+ breathing_move = BreathingMove(
+ interpolation_start_pose=current_head_pose,
+ interpolation_start_antennas=current_antennas,
+ interpolation_duration=1.0,
+ )
+ self.move_queue.append(breathing_move)
+ logger.debug("Started breathing after %.1fs of inactivity", idle_for)
+ except Exception as e:
+ self._breathing_active = False
+ logger.error("Failed to start breathing: %s", e)
+
+ if isinstance(self.state.current_move, BreathingMove) and self.move_queue:
+ self.state.current_move = None
+ self.state.move_start_time = None
+ self._breathing_active = False
+ logger.debug("Stopping breathing due to new move activity")
+
+ if self.state.current_move is not None and not isinstance(self.state.current_move, BreathingMove):
+ self._breathing_active = False
+
+ def _get_primary_pose(self, current_time: float) -> FullBodyPose:
+ """Get the primary full body pose from current move or neutral."""
+ # When a primary move is playing, sample it and cache the resulting pose
+ if self.state.current_move is not None and self.state.move_start_time is not None:
+ move_time = current_time - self.state.move_start_time
+ head, antennas, body_yaw = self.state.current_move.evaluate(move_time)
+
+ if head is None:
+ head = create_head_pose(0, 0, 0, 0, 0, 0, degrees=True)
+ if antennas is None:
+ antennas = np.array([0.0, 0.0])
+ if body_yaw is None:
+ body_yaw = 0.0
+
+ antennas_tuple = (float(antennas[0]), float(antennas[1]))
+ head_copy = head.copy()
+ primary_full_body_pose = (
+ head_copy,
+ antennas_tuple,
+ float(body_yaw),
+ )
+
+ self.state.last_primary_pose = clone_full_body_pose(primary_full_body_pose)
+ # Otherwise reuse the last primary pose so we avoid jumps between moves
+ elif self.state.last_primary_pose is not None:
+ primary_full_body_pose = clone_full_body_pose(self.state.last_primary_pose)
+ else:
+ neutral_head_pose = create_head_pose(0, 0, 0, 0, 0, 0, degrees=True)
+ primary_full_body_pose = (neutral_head_pose, (0.0, 0.0), 0.0)
+ self.state.last_primary_pose = clone_full_body_pose(primary_full_body_pose)
+
+ return primary_full_body_pose
+
+ def _get_secondary_pose(self) -> FullBodyPose:
+ """Get the secondary full body pose from speech and face tracking offsets."""
+ # Combine speech sway offsets + face tracking offsets for secondary pose
+ secondary_offsets = [
+ self.state.speech_offsets[0] + self.state.face_tracking_offsets[0],
+ self.state.speech_offsets[1] + self.state.face_tracking_offsets[1],
+ self.state.speech_offsets[2] + self.state.face_tracking_offsets[2],
+ self.state.speech_offsets[3] + self.state.face_tracking_offsets[3],
+ self.state.speech_offsets[4] + self.state.face_tracking_offsets[4],
+ self.state.speech_offsets[5] + self.state.face_tracking_offsets[5],
+ ]
+
+ secondary_head_pose = create_head_pose(
+ x=secondary_offsets[0],
+ y=secondary_offsets[1],
+ z=secondary_offsets[2],
+ roll=secondary_offsets[3],
+ pitch=secondary_offsets[4],
+ yaw=secondary_offsets[5],
+ degrees=False,
+ mm=False,
+ )
+ return (secondary_head_pose, (0.0, 0.0), 0.0)
+
+ def _compose_full_body_pose(self, current_time: float) -> FullBodyPose:
+ """Compose primary and secondary poses into a single command pose."""
+ primary = self._get_primary_pose(current_time)
+ secondary = self._get_secondary_pose()
+ return combine_full_body(primary, secondary)
+
+ def _update_primary_motion(self, current_time: float) -> None:
+ """Advance queue state and idle behaviours for this tick."""
+ self._manage_move_queue(current_time)
+ self._manage_breathing(current_time)
+
+ def _calculate_blended_antennas(self, target_antennas: Tuple[float, float]) -> Tuple[float, float]:
+ """Blend target antennas with listening freeze state and update blending."""
+ now = self._now()
+ listening = self._is_listening
+ listening_antennas = self._listening_antennas
+ blend = self._antenna_unfreeze_blend
+ blend_duration = self._antenna_blend_duration
+ last_update = self._last_listening_blend_time
+ self._last_listening_blend_time = now
+
+ if listening:
+ antennas_cmd = listening_antennas
+ new_blend = 0.0
+ else:
+ dt = max(0.0, now - last_update)
+ if blend_duration <= 0:
+ new_blend = 1.0
+ else:
+ new_blend = min(1.0, blend + dt / blend_duration)
+ antennas_cmd = (
+ listening_antennas[0] * (1.0 - new_blend) + target_antennas[0] * new_blend,
+ listening_antennas[1] * (1.0 - new_blend) + target_antennas[1] * new_blend,
+ )
+
+ if listening:
+ self._antenna_unfreeze_blend = 0.0
+ else:
+ self._antenna_unfreeze_blend = new_blend
+ if new_blend >= 1.0:
+ self._listening_antennas = (
+ float(target_antennas[0]),
+ float(target_antennas[1]),
+ )
+
+ return antennas_cmd
+
+ def _issue_control_command(self, head: NDArray[np.float32], antennas: Tuple[float, float], body_yaw: float) -> None:
+ """Send the fused pose to the robot with throttled error logging."""
+ try:
+ self.current_robot.set_target(head=head, antennas=antennas, body_yaw=body_yaw)
+ except Exception as e:
+ now = self._now()
+ if now - self._last_set_target_err >= self._set_target_err_interval:
+ msg = f"Failed to set robot target: {e}"
+ if self._set_target_err_suppressed:
+ msg += f" (suppressed {self._set_target_err_suppressed} repeats)"
+ self._set_target_err_suppressed = 0
+ logger.error(msg)
+ self._last_set_target_err = now
+ else:
+ self._set_target_err_suppressed += 1
+ else:
+ with self._status_lock:
+ self._last_commanded_pose = clone_full_body_pose((head, antennas, body_yaw))
+
+ def _update_frequency_stats(
+ self, loop_start: float, prev_loop_start: float, stats: LoopFrequencyStats,
+ ) -> LoopFrequencyStats:
+ """Update frequency statistics based on the current loop start time."""
+ period = loop_start - prev_loop_start
+ if period > 0:
+ stats.last_freq = 1.0 / period
+ stats.count += 1
+ delta = stats.last_freq - stats.mean
+ stats.mean += delta / stats.count
+ stats.m2 += delta * (stats.last_freq - stats.mean)
+ stats.min_freq = min(stats.min_freq, stats.last_freq)
+ return stats
+
+ def _schedule_next_tick(self, loop_start: float, stats: LoopFrequencyStats) -> Tuple[float, LoopFrequencyStats]:
+ """Compute sleep time to maintain target frequency and update potential freq."""
+ computation_time = self._now() - loop_start
+ stats.potential_freq = 1.0 / computation_time if computation_time > 0 else float("inf")
+ sleep_time = max(0.0, self.target_period - computation_time)
+ return sleep_time, stats
+
+ def _record_frequency_snapshot(self, stats: LoopFrequencyStats) -> None:
+ """Store a thread-safe snapshot of current frequency statistics."""
+ with self._status_lock:
+ self._freq_snapshot = LoopFrequencyStats(
+ mean=stats.mean,
+ m2=stats.m2,
+ min_freq=stats.min_freq,
+ count=stats.count,
+ last_freq=stats.last_freq,
+ potential_freq=stats.potential_freq,
+ )
+
+ def _maybe_log_frequency(self, loop_count: int, print_interval_loops: int, stats: LoopFrequencyStats) -> None:
+ """Emit frequency telemetry when enough loops have elapsed."""
+ if loop_count % print_interval_loops != 0 or stats.count == 0:
+ return
+
+ variance = stats.m2 / stats.count if stats.count > 0 else 0.0
+ lowest = stats.min_freq if stats.min_freq != float("inf") else 0.0
+ logger.debug(
+ "Loop freq - avg: %.2fHz, variance: %.4f, min: %.2fHz, last: %.2fHz, potential: %.2fHz, target: %.1fHz",
+ stats.mean,
+ variance,
+ lowest,
+ stats.last_freq,
+ stats.potential_freq,
+ self.target_frequency,
+ )
+ stats.reset()
+
+ def _update_face_tracking(self, current_time: float) -> None:
+ """Get face tracking offsets from camera worker thread."""
+ if self.camera_worker is not None:
+ # Get face tracking offsets from camera worker thread
+ offsets = self.camera_worker.get_face_tracking_offsets()
+ self.state.face_tracking_offsets = offsets
+ else:
+ # No camera worker, use neutral offsets
+ self.state.face_tracking_offsets = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
+
+ def start(self) -> None:
+ """Start the worker thread that drives the 100 Hz control loop."""
+ if self._thread is not None and self._thread.is_alive():
+ logger.warning("Move worker already running; start() ignored")
+ return
+ self._stop_event.clear()
+ self._thread = threading.Thread(target=self.working_loop, daemon=True)
+ self._thread.start()
+ logger.debug("Move worker started")
+
+ def stop(self) -> None:
+ """Request the worker thread to stop and wait for it to exit.
+
+ Before stopping, resets the robot to a neutral position.
+ """
+ if self._thread is None or not self._thread.is_alive():
+ logger.debug("Move worker not running; stop() ignored")
+ return
+
+ logger.info("Stopping movement manager and resetting to neutral position...")
+
+ # Clear any queued moves and stop current move
+ self.clear_move_queue()
+
+ # Stop the worker thread first so it doesn't interfere
+ self._stop_event.set()
+ if self._thread is not None:
+ self._thread.join()
+ self._thread = None
+ logger.debug("Move worker stopped")
+
+ # Reset to neutral position using goto_target (same approach as wake_up)
+ try:
+ neutral_head_pose = create_head_pose(0, 0, 0, 0, 0, 0, degrees=True)
+ neutral_antennas = [0.0, 0.0]
+ neutral_body_yaw = 0.0
+
+ # Use goto_target directly on the robot
+ self.current_robot.goto_target(
+ head=neutral_head_pose,
+ antennas=neutral_antennas,
+ duration=2.0,
+ body_yaw=neutral_body_yaw,
+ )
+
+ logger.info("Reset to neutral position completed")
+
+ except Exception as e:
+ logger.error(f"Failed to reset to neutral position: {e}")
+
+ def get_status(self) -> Dict[str, Any]:
+ """Return a lightweight status snapshot for observability."""
+ with self._status_lock:
+ pose_snapshot = clone_full_body_pose(self._last_commanded_pose)
+ freq_snapshot = LoopFrequencyStats(
+ mean=self._freq_snapshot.mean,
+ m2=self._freq_snapshot.m2,
+ min_freq=self._freq_snapshot.min_freq,
+ count=self._freq_snapshot.count,
+ last_freq=self._freq_snapshot.last_freq,
+ potential_freq=self._freq_snapshot.potential_freq,
+ )
+
+ head_matrix = pose_snapshot[0].tolist() if pose_snapshot else None
+ antennas = pose_snapshot[1] if pose_snapshot else None
+ body_yaw = pose_snapshot[2] if pose_snapshot else None
+
+ return {
+ "queue_size": len(self.move_queue),
+ "is_listening": self._is_listening,
+ "breathing_active": self._breathing_active,
+ "last_commanded_pose": {
+ "head": head_matrix,
+ "antennas": antennas,
+ "body_yaw": body_yaw,
+ },
+ "loop_frequency": {
+ "last": freq_snapshot.last_freq,
+ "mean": freq_snapshot.mean,
+ "min": freq_snapshot.min_freq,
+ "potential": freq_snapshot.potential_freq,
+ "samples": freq_snapshot.count,
+ },
+ }
+
+ def working_loop(self) -> None:
+ """Control loop main movements - reproduces main_works.py control architecture.
+
+ Single set_target() call with pose fusion.
+ """
+ logger.debug("Starting enhanced movement control loop (100Hz)")
+
+ loop_count = 0
+ prev_loop_start = self._now()
+ print_interval_loops = max(1, int(self.target_frequency * 2))
+ freq_stats = self._freq_stats
+
+ while not self._stop_event.is_set():
+ loop_start = self._now()
+ loop_count += 1
+
+ if loop_count > 1:
+ freq_stats = self._update_frequency_stats(loop_start, prev_loop_start, freq_stats)
+ prev_loop_start = loop_start
+
+ # 1) Poll external commands and apply pending offsets (atomic snapshot)
+ self._poll_signals(loop_start)
+
+ # 2) Manage the primary move queue (start new move, end finished move, breathing)
+ self._update_primary_motion(loop_start)
+
+ # 3) Update vision-based secondary offsets
+ self._update_face_tracking(loop_start)
+
+ # 4) Build primary and secondary full-body poses, then fuse them
+ head, antennas, body_yaw = self._compose_full_body_pose(loop_start)
+
+ # 5) Apply listening antenna freeze or blend-back
+ antennas_cmd = self._calculate_blended_antennas(antennas)
+
+ # 6) Single set_target call - the only control point
+ self._issue_control_command(head, antennas_cmd, body_yaw)
+
+ # 7) Adaptive sleep to align to next tick, then publish shared state
+ sleep_time, freq_stats = self._schedule_next_tick(loop_start, freq_stats)
+ self._publish_shared_state()
+ self._record_frequency_snapshot(freq_stats)
+
+ # 8) Periodic telemetry on loop frequency
+ self._maybe_log_frequency(loop_count, print_interval_loops, freq_stats)
+
+ if sleep_time > 0:
+ time.sleep(sleep_time)
+
+ logger.debug("Movement control loop stopped")
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/not used/__pycache__/config.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/not used/__pycache__/config.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3c9f591cf6c3955fe61eecc7c39f58d37cbbfaff
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/not used/__pycache__/config.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/not used/__pycache__/console.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/not used/__pycache__/console.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..07554f1a7cabe5da71ed011a0cad9a3940eca2cc
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/not used/__pycache__/console.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/not used/__pycache__/main.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/not used/__pycache__/main.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..63d729c646a67934dad9800c021f58f8b46a5501
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/not used/__pycache__/main.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/not used/config.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/not used/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..963cc6903bca83763ce69fe82dce9726630dc62d
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/not used/config.py
@@ -0,0 +1,84 @@
+import os
+import sys
+import logging
+from pathlib import Path
+
+from dotenv import find_dotenv, load_dotenv
+
+
+# Locked profile: set to a profile name (e.g., "astronomer") to lock the app
+# to that profile and disable all profile switching. Leave as None for normal behavior.
+LOCKED_PROFILE: str | None = "_cookAIware_locked_profile"
+
+logger = logging.getLogger(__name__)
+
+# Validate LOCKED_PROFILE at startup
+if LOCKED_PROFILE is not None:
+ _profiles_dir = Path(__file__).parent / "profiles"
+ _profile_path = _profiles_dir / LOCKED_PROFILE
+ _instructions_file = _profile_path / "instructions.txt"
+ if not _profile_path.is_dir():
+ print(f"Error: LOCKED_PROFILE '{LOCKED_PROFILE}' does not exist in {_profiles_dir}", file=sys.stderr)
+ sys.exit(1)
+ if not _instructions_file.is_file():
+ print(f"Error: LOCKED_PROFILE '{LOCKED_PROFILE}' has no instructions.txt", file=sys.stderr)
+ sys.exit(1)
+
+# Locate .env file (search upward from current working directory)
+dotenv_path = find_dotenv(usecwd=True)
+if not dotenv_path:
+ module_env = Path(__file__).parent / ".env"
+ if module_env.exists():
+ dotenv_path = str(module_env)
+
+if dotenv_path:
+ # Load .env and override environment variables
+ load_dotenv(dotenv_path=dotenv_path, override=True)
+ logger.info(f"Configuration loaded from {dotenv_path}")
+else:
+ logger.warning("No .env file found, using environment variables")
+
+
+class Config:
+ """Configuration class for the conversation app."""
+
+ # Required
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") # The key is downloaded in console.py if needed
+
+ # Optional
+ MODEL_NAME = os.getenv("MODEL_NAME", "gpt-realtime")
+ HF_HOME = os.getenv("HF_HOME", "./cache")
+ LOCAL_VISION_MODEL = os.getenv("LOCAL_VISION_MODEL", "HuggingFaceTB/SmolVLM2-2.2B-Instruct")
+ HF_TOKEN = os.getenv("HF_TOKEN") # Optional, falls back to hf auth login if not set
+
+ logger.debug(f"Model: {MODEL_NAME}, HF_HOME: {HF_HOME}, Vision Model: {LOCAL_VISION_MODEL}")
+
+ REACHY_MINI_CUSTOM_PROFILE = LOCKED_PROFILE or os.getenv("REACHY_MINI_CUSTOM_PROFILE")
+ logger.debug(f"Custom Profile: {REACHY_MINI_CUSTOM_PROFILE}")
+
+
+config = Config()
+
+
+def set_custom_profile(profile: str | None) -> None:
+ """Update the selected custom profile at runtime and expose it via env.
+
+ This ensures modules that read `config` and code that inspects the
+ environment see a consistent value.
+ """
+ if LOCKED_PROFILE is not None:
+ return
+ try:
+ config.REACHY_MINI_CUSTOM_PROFILE = profile
+ except Exception:
+ pass
+ try:
+ import os as _os
+
+ if profile:
+ _os.environ["REACHY_MINI_CUSTOM_PROFILE"] = profile
+ else:
+ # Remove to reflect default
+ _os.environ.pop("REACHY_MINI_CUSTOM_PROFILE", None)
+ except Exception:
+ pass
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/not used/console.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/not used/console.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc8cc60b0ad555729b95d593e5a4daeebda21a28
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/not used/console.py
@@ -0,0 +1,754 @@
+"""Bidirectional local audio stream with optional settings UI.
+
+In headless mode, there is no Gradio UI. If the OpenAI API key is not
+available via environment/.env, we expose a minimal settings page via the
+Reachy Mini Apps settings server to let non-technical users enter it.
+
+The settings UI is served from this package's ``static/`` folder and offers a
+single password field to set ``OPENAI_API_KEY``. Once set, we persist it to the
+app instance's ``.env`` file (if available) and proceed to start streaming.
+"""
+
+import os
+import sys
+import time
+import asyncio
+import logging
+from typing import List, Optional, Deque, Dict
+from collections import deque
+from pathlib import Path
+
+from fastrtc import AdditionalOutputs, audio_to_float32
+from scipy.signal import resample
+
+from reachy_mini import ReachyMini
+from reachy_mini.media.media_manager import MediaBackend
+from cookAIware.config import LOCKED_PROFILE, config
+from cookAIware.openai_realtime import OpenaiRealtimeHandler
+from Reachy_OpenWebUI.sub_apps.cookAIware.headless_personality_ui import mount_personality_routes
+
+
+try:
+ # FastAPI is provided by the Reachy Mini Apps runtime
+ from fastapi import FastAPI, Response
+ from pydantic import BaseModel
+ from fastapi.responses import FileResponse, JSONResponse
+ from starlette.staticfiles import StaticFiles
+except Exception: # pragma: no cover - only loaded when settings_app is used
+ FastAPI = object # type: ignore
+ FileResponse = object # type: ignore
+ JSONResponse = object # type: ignore
+ StaticFiles = object # type: ignore
+ BaseModel = object # type: ignore
+
+
+logger = logging.getLogger(__name__)
+
+
+class LocalStream:
+ """LocalStream using Reachy Mini's recorder/player."""
+
+ def __init__(
+ self,
+ handler: OpenaiRealtimeHandler,
+ robot: ReachyMini,
+ *,
+ settings_app: Optional[FastAPI] = None,
+ instance_path: Optional[str] = None,
+ ):
+ """Initialize the stream with an OpenAI realtime handler and pipelines.
+
+ - ``settings_app``: the Reachy Mini Apps FastAPI to attach settings endpoints.
+ - ``instance_path``: directory where per-instance ``.env`` should be stored.
+ """
+ self.handler = handler
+ self._robot = robot
+ self._stop_event = asyncio.Event()
+ self._tasks: List[asyncio.Task[None]] = []
+ # Allow the handler to flush the player queue when appropriate.
+ self.handler._clear_queue = self.clear_audio_queue
+ self._settings_app: Optional[FastAPI] = settings_app
+ self._instance_path: Optional[str] = instance_path
+ self._settings_initialized = False
+ self._asyncio_loop = None
+ self._transcript: Deque[Dict[str, str]] = deque(maxlen=200)
+
+ # ---- Settings UI (only when API key is missing) ----
+ def _read_env_lines(self, env_path: Path) -> list[str]:
+ """Load env file contents or a template as a list of lines."""
+ inst = env_path.parent
+ try:
+ if env_path.exists():
+ try:
+ return env_path.read_text(encoding="utf-8").splitlines()
+ except Exception:
+ return []
+ template_text = None
+ ex = inst / ".env.example"
+ if ex.exists():
+ try:
+ template_text = ex.read_text(encoding="utf-8")
+ except Exception:
+ template_text = None
+ if template_text is None:
+ try:
+ cwd_example = Path.cwd() / ".env.example"
+ if cwd_example.exists():
+ template_text = cwd_example.read_text(encoding="utf-8")
+ except Exception:
+ template_text = None
+ if template_text is None:
+ packaged = Path(__file__).parent / ".env.example"
+ if packaged.exists():
+ try:
+ template_text = packaged.read_text(encoding="utf-8")
+ except Exception:
+ template_text = None
+ return template_text.splitlines() if template_text else []
+ except Exception:
+ return []
+
+ def _persist_api_key(self, key: str) -> None:
+ """Persist API key to environment and instance ``.env`` if possible.
+
+ Behavior:
+ - Always sets ``OPENAI_API_KEY`` in process env and in-memory config.
+ - Writes/updates ``/.env``:
+ * If ``.env`` exists, replaces/append OPENAI_API_KEY line.
+ * Else, copies template from ``/.env.example`` when present,
+ otherwise falls back to the packaged template
+ ``cookAIware/.env.example``.
+ * Ensures the resulting file contains the full template plus the key.
+ - Loads the written ``.env`` into the current process environment.
+ """
+ k = (key or "").strip()
+ if not k:
+ return
+ # Update live process env and config so consumers see it immediately
+ try:
+ os.environ["OPENAI_API_KEY"] = k
+ except Exception: # best-effort
+ pass
+ try:
+ config.OPENAI_API_KEY = k
+ except Exception:
+ pass
+
+ if not self._instance_path:
+ return
+ try:
+ inst = Path(self._instance_path)
+ env_path = inst / ".env"
+ lines = self._read_env_lines(env_path)
+ replaced = False
+ for i, ln in enumerate(lines):
+ if ln.strip().startswith("OPENAI_API_KEY="):
+ lines[i] = f"OPENAI_API_KEY={k}"
+ replaced = True
+ break
+ if not replaced:
+ lines.append(f"OPENAI_API_KEY={k}")
+ final_text = "\n".join(lines) + "\n"
+ env_path.write_text(final_text, encoding="utf-8")
+ logger.info("Persisted OPENAI_API_KEY to %s", env_path)
+
+ # Load the newly written .env into this process to ensure downstream imports see it
+ try:
+ from dotenv import load_dotenv
+
+ load_dotenv(dotenv_path=str(env_path), override=True)
+ except Exception:
+ pass
+ except Exception as e:
+ logger.warning("Failed to persist OPENAI_API_KEY: %s", e)
+
+ def _persist_personality(self, profile: Optional[str]) -> None:
+ """Persist the startup personality to the instance .env and config."""
+ if LOCKED_PROFILE is not None:
+ return
+ selection = (profile or "").strip() or None
+ try:
+ from cookAIware.config import set_custom_profile
+
+ set_custom_profile(selection)
+ except Exception:
+ pass
+
+ if not self._instance_path:
+ return
+ try:
+ env_path = Path(self._instance_path) / ".env"
+ lines = self._read_env_lines(env_path)
+ replaced = False
+ for i, ln in enumerate(list(lines)):
+ if ln.strip().startswith("REACHY_MINI_CUSTOM_PROFILE="):
+ if selection:
+ lines[i] = f"REACHY_MINI_CUSTOM_PROFILE={selection}"
+ else:
+ lines.pop(i)
+ replaced = True
+ break
+ if selection and not replaced:
+ lines.append(f"REACHY_MINI_CUSTOM_PROFILE={selection}")
+ if selection is None and not env_path.exists():
+ return
+ final_text = "\n".join(lines) + "\n"
+ env_path.write_text(final_text, encoding="utf-8")
+ logger.info("Persisted startup personality to %s", env_path)
+ try:
+ from dotenv import load_dotenv
+
+ load_dotenv(dotenv_path=str(env_path), override=True)
+ except Exception:
+ pass
+ except Exception as e:
+ logger.warning("Failed to persist REACHY_MINI_CUSTOM_PROFILE: %s", e)
+
+ def _read_persisted_personality(self) -> Optional[str]:
+ """Read persisted startup personality from instance .env (if any)."""
+ if not self._instance_path:
+ return None
+ env_path = Path(self._instance_path) / ".env"
+ try:
+ if env_path.exists():
+ for ln in env_path.read_text(encoding="utf-8").splitlines():
+ if ln.strip().startswith("REACHY_MINI_CUSTOM_PROFILE="):
+ _, _, val = ln.partition("=")
+ v = val.strip()
+ return v or None
+ except Exception:
+ pass
+ return None
+
+ def _init_settings_ui_if_needed(self) -> None:
+ """Attach minimal settings UI to the settings app.
+
+ Always mounts the UI when a settings_app is provided so that users
+ see a confirmation message even if the API key is already configured.
+ """
+ if self._settings_initialized:
+ return
+ if self._settings_app is None:
+ return
+
+ static_dir = Path(__file__).parent / "static"
+ index_file = static_dir / "index.html"
+ data_dir = None
+ try:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.data_store import resolve_data_dir
+
+ data_dir = resolve_data_dir(self._instance_path)
+ except Exception:
+ data_dir = None
+
+ if hasattr(self._settings_app, "mount"):
+ try:
+ # Serve /static/* assets
+ self._settings_app.mount("/static", StaticFiles(directory=str(static_dir)), name="static")
+ except Exception:
+ pass
+
+ class ApiKeyPayload(BaseModel):
+ openai_api_key: str
+
+ class TextPayload(BaseModel):
+ text: str
+
+ class InventoryPayload(BaseModel):
+ items: list[dict]
+
+ class FamilyProfilePayload(BaseModel):
+ adults: int | None = None
+ children: int | None = None
+ schedule: dict | None = None
+
+ class ShoppingListPayload(BaseModel):
+ items: list[dict] | None = None
+
+ class SettingsPayload(BaseModel):
+ language: str | None = None
+
+ @self._settings_app.get("/transcript")
+ def _get_transcript() -> JSONResponse:
+ return JSONResponse({"messages": list(self._transcript)})
+
+ # GET / -> index.html
+ @self._settings_app.get("/")
+ def _root() -> FileResponse:
+ return FileResponse(str(index_file))
+
+ # GET /favicon.ico -> optional, avoid noisy 404s on some browsers
+ @self._settings_app.get("/favicon.ico")
+ def _favicon() -> Response:
+ return Response(status_code=204)
+
+ # GET /status -> whether key is set
+ @self._settings_app.get("/status")
+ def _status() -> JSONResponse:
+ has_key = bool(config.OPENAI_API_KEY and str(config.OPENAI_API_KEY).strip())
+ return JSONResponse({"has_key": has_key})
+
+ @self._settings_app.get("/settings")
+ def _get_settings() -> JSONResponse:
+ if data_dir is None:
+ return JSONResponse({"error": "data_dir_unavailable"}, status_code=500)
+ from Reachy_OpenWebUI.sub_apps.cookAIware.app_settings import get_settings
+
+ return JSONResponse({"settings": get_settings(data_dir)})
+
+ @self._settings_app.post("/settings")
+ async def _set_settings(payload: SettingsPayload) -> JSONResponse:
+ if data_dir is None:
+ return JSONResponse({"error": "data_dir_unavailable"}, status_code=500)
+ from Reachy_OpenWebUI.sub_apps.cookAIware.app_settings import set_language
+
+ language = (payload.language or "").strip()
+ if not language:
+ return JSONResponse({"error": "missing_language"}, status_code=400)
+ settings = set_language(data_dir, language)
+ try:
+ await self.handler.apply_language(language)
+ except Exception:
+ pass
+ return JSONResponse({"settings": settings})
+
+ @self._settings_app.get("/data/inventory")
+ def _get_inventory() -> JSONResponse:
+ if data_dir is None:
+ return JSONResponse({"error": "data_dir_unavailable"}, status_code=500)
+ from Reachy_OpenWebUI.sub_apps.cookAIware.inventory import list_inventory, normalize_for_display
+
+ items = normalize_for_display(list_inventory(data_dir))
+ return JSONResponse({"items": items})
+
+ @self._settings_app.post("/data/inventory/replace")
+ def _replace_inventory(payload: InventoryPayload) -> JSONResponse:
+ if data_dir is None:
+ return JSONResponse({"error": "data_dir_unavailable"}, status_code=500)
+ from Reachy_OpenWebUI.sub_apps.cookAIware.inventory import save_inventory, normalize_items_for_save
+
+ normalized = normalize_items_for_save(payload.items)
+ save_inventory(data_dir, normalized)
+ return JSONResponse({"ok": True})
+
+ @self._settings_app.get("/data/family_profile")
+ def _get_family_profile() -> JSONResponse:
+ if data_dir is None:
+ return JSONResponse({"error": "data_dir_unavailable"}, status_code=500)
+ from Reachy_OpenWebUI.sub_apps.cookAIware.family_profile import load_profile
+
+ profile = load_profile(data_dir)
+ return JSONResponse({"profile": profile})
+
+ @self._settings_app.post("/data/family_profile")
+ def _update_family_profile(payload: FamilyProfilePayload) -> JSONResponse:
+ if data_dir is None:
+ return JSONResponse({"error": "data_dir_unavailable"}, status_code=500)
+ from Reachy_OpenWebUI.sub_apps.cookAIware.family_profile import update_profile
+
+ profile = update_profile(data_dir, payload.adults, payload.children, payload.schedule)
+ return JSONResponse({"profile": profile})
+
+ @self._settings_app.get("/data/meal_plan")
+ def _get_meal_plan() -> JSONResponse:
+ if data_dir is None:
+ return JSONResponse({"error": "data_dir_unavailable"}, status_code=500)
+ from Reachy_OpenWebUI.sub_apps.cookAIware.meal_planner import load_plan
+
+ plan = load_plan(data_dir)
+ return JSONResponse({"plan": plan})
+
+ @self._settings_app.post("/data/meal_plan/generate")
+ def _generate_meal_plan() -> JSONResponse:
+ if data_dir is None:
+ return JSONResponse({"error": "data_dir_unavailable"}, status_code=500)
+ from Reachy_OpenWebUI.sub_apps.cookAIware.inventory import list_inventory
+ from Reachy_OpenWebUI.sub_apps.cookAIware.family_profile import load_profile
+ from Reachy_OpenWebUI.sub_apps.cookAIware.meal_planner import generate_plan
+
+ profile = load_profile(data_dir)
+ adults = profile.get("adults")
+ children = profile.get("children")
+ if adults is None or children is None:
+ return JSONResponse({"error": "missing_family_profile"}, status_code=400)
+ inventory = list_inventory(data_dir)
+ plan = generate_plan(data_dir, inventory, int(adults), int(children))
+ return JSONResponse({"plan": plan})
+
+ @self._settings_app.get("/data/shopping_list")
+ def _get_shopping_list() -> JSONResponse:
+ if data_dir is None:
+ return JSONResponse({"error": "data_dir_unavailable"}, status_code=500)
+ from Reachy_OpenWebUI.sub_apps.cookAIware.shopping_list import list_items
+
+ items = list_items(data_dir)
+ return JSONResponse({"items": items})
+
+ @self._settings_app.post("/data/shopping_list/generate")
+ def _generate_shopping_list() -> JSONResponse:
+ if data_dir is None:
+ return JSONResponse({"error": "data_dir_unavailable"}, status_code=500)
+ from Reachy_OpenWebUI.sub_apps.cookAIware.meal_planner import load_plan
+ from Reachy_OpenWebUI.sub_apps.cookAIware.inventory import list_inventory
+ from Reachy_OpenWebUI.sub_apps.cookAIware.shopping_list import generate_from_plan
+
+ plan = load_plan(data_dir)
+ inventory = list_inventory(data_dir)
+ items = generate_from_plan(data_dir, plan, inventory)
+ return JSONResponse({"items": items})
+
+ @self._settings_app.post("/data/shopping_list/replace")
+ def _replace_shopping_list(payload: ShoppingListPayload) -> JSONResponse:
+ if data_dir is None:
+ return JSONResponse({"error": "data_dir_unavailable"}, status_code=500)
+ from Reachy_OpenWebUI.sub_apps.cookAIware.shopping_list import save_list
+
+ save_list(data_dir, payload.items or [])
+ return JSONResponse({"ok": True})
+
+ # GET /ready -> whether backend finished loading tools
+ @self._settings_app.get("/ready")
+ def _ready() -> JSONResponse:
+ try:
+ mod = sys.modules.get("cookAIware.tools.core_tools")
+ ready = bool(getattr(mod, "_TOOLS_INITIALIZED", False)) if mod else False
+ except Exception:
+ ready = False
+ return JSONResponse({"ready": ready})
+
+ # POST /openai_api_key -> set/persist key
+ @self._settings_app.post("/openai_api_key")
+ def _set_key(payload: ApiKeyPayload) -> JSONResponse:
+ key = (payload.openai_api_key or "").strip()
+ if not key:
+ return JSONResponse({"ok": False, "error": "empty_key"}, status_code=400)
+ self._persist_api_key(key)
+ return JSONResponse({"ok": True})
+
+ # POST /validate_api_key -> validate key without persisting it
+ @self._settings_app.post("/validate_api_key")
+ async def _validate_key(payload: ApiKeyPayload) -> JSONResponse:
+ key = (payload.openai_api_key or "").strip()
+ if not key:
+ return JSONResponse({"valid": False, "error": "empty_key"}, status_code=400)
+
+ # Try to validate by checking if we can fetch the models
+ try:
+ import httpx
+
+ headers = {"Authorization": f"Bearer {key}", "Content-Type": "application/json"}
+ async with httpx.AsyncClient(timeout=10.0) as client:
+ response = await client.get("https://api.openai.com/v1/models", headers=headers)
+ if response.status_code == 200:
+ return JSONResponse({"valid": True})
+ elif response.status_code == 401:
+ return JSONResponse({"valid": False, "error": "invalid_api_key"}, status_code=401)
+ else:
+ return JSONResponse(
+ {"valid": False, "error": "validation_failed"}, status_code=response.status_code
+ )
+ except Exception as e:
+ logger.warning(f"API key validation failed: {e}")
+ return JSONResponse({"valid": False, "error": "validation_error"}, status_code=500)
+
+ @self._settings_app.post("/text_input")
+ async def _text_input(payload: TextPayload) -> JSONResponse:
+ text = (payload.text or "").strip()
+ if not text:
+ return JSONResponse({"ok": False, "error": "empty_text"}, status_code=400)
+ if not self._asyncio_loop:
+ return JSONResponse({"ok": False, "error": "not_ready"}, status_code=400)
+ try:
+ self._transcript.append({"role": "user", "content": text})
+ future = asyncio.run_coroutine_threadsafe(
+ self.handler.send_text(text),
+ self._asyncio_loop,
+ )
+ ok = future.result(timeout=5)
+ return JSONResponse({"ok": bool(ok)})
+ except Exception as e:
+ return JSONResponse({"ok": False, "error": str(e)}, status_code=500)
+
+ self._settings_initialized = True
+
+ def launch(self) -> None:
+ """Start the recorder/player and run the async processing loops.
+
+ If the OpenAI key is missing, expose a tiny settings UI via the
+ Reachy Mini settings server to collect it before starting streams.
+ """
+ self._stop_event.clear()
+
+ # Try to load an existing instance .env first (covers subsequent runs)
+ if self._instance_path:
+ try:
+ from dotenv import load_dotenv
+
+ from cookAIware.config import set_custom_profile
+
+ env_path = Path(self._instance_path) / ".env"
+ if env_path.exists():
+ load_dotenv(dotenv_path=str(env_path), override=True)
+ # Update config with newly loaded values
+ new_key = os.getenv("OPENAI_API_KEY", "").strip()
+ if new_key:
+ try:
+ config.OPENAI_API_KEY = new_key
+ except Exception:
+ pass
+ if LOCKED_PROFILE is None:
+ new_profile = os.getenv("REACHY_MINI_CUSTOM_PROFILE")
+ if new_profile is not None:
+ try:
+ set_custom_profile(new_profile.strip() or None)
+ except Exception:
+ pass # Best-effort profile update
+ except Exception:
+ pass # Instance .env loading is optional; continue with defaults
+
+ # If key is still missing, try to download one from HuggingFace
+ if not (config.OPENAI_API_KEY and str(config.OPENAI_API_KEY).strip()):
+ logger.info("OPENAI_API_KEY not set, attempting to download from HuggingFace...")
+ try:
+ from gradio_client import Client
+
+ client = Client("HuggingFaceM4/gradium_setup", verbose=False)
+ key, status = client.predict(api_name="/claim_b_key")
+ if key and key.strip():
+ logger.info("Successfully downloaded API key from HuggingFace")
+ # Persist it immediately
+ self._persist_api_key(key)
+ except Exception as e:
+ logger.warning(f"Failed to download API key from HuggingFace: {e}")
+
+ # Always expose settings UI if a settings app is available
+ # (do this AFTER loading/downloading the key so status endpoint sees the right value)
+ self._init_settings_ui_if_needed()
+
+ # If key is still missing -> wait until provided via the settings UI
+ if not (config.OPENAI_API_KEY and str(config.OPENAI_API_KEY).strip()):
+ logger.warning("OPENAI_API_KEY not found. Open the app settings page to enter it.")
+ # Poll until the key becomes available (set via the settings UI)
+ try:
+ while not (config.OPENAI_API_KEY and str(config.OPENAI_API_KEY).strip()):
+ time.sleep(0.2)
+ except KeyboardInterrupt:
+ logger.info("Interrupted while waiting for API key.")
+ return
+
+ # Configure audio devices before starting media (best-effort)
+ self._configure_sounddevice()
+
+ # Start media after key is set/available
+ self._robot.media.start_recording()
+ self._robot.media.start_playing()
+ time.sleep(1) # give some time to the pipelines to start
+
+ async def runner() -> None:
+ # Capture loop for cross-thread personality actions
+ loop = asyncio.get_running_loop()
+ self._asyncio_loop = loop # type: ignore[assignment]
+ # Mount personality routes now that loop and handler are available
+ try:
+ if self._settings_app is not None:
+ mount_personality_routes(
+ self._settings_app,
+ self.handler,
+ lambda: self._asyncio_loop,
+ persist_personality=self._persist_personality,
+ get_persisted_personality=self._read_persisted_personality,
+ )
+ except Exception:
+ pass
+ self._tasks = [
+ asyncio.create_task(self.handler.start_up(), name="openai-handler"),
+ asyncio.create_task(self.record_loop(), name="stream-record-loop"),
+ asyncio.create_task(self.play_loop(), name="stream-play-loop"),
+ ]
+ try:
+ await asyncio.gather(*self._tasks)
+ except asyncio.CancelledError:
+ logger.info("Tasks cancelled during shutdown")
+ finally:
+ # Ensure handler connection is closed
+ await self.handler.shutdown()
+
+ asyncio.run(runner())
+
+ def close(self) -> None:
+ """Stop the stream and underlying media pipelines.
+
+ This method:
+ - Stops audio recording and playback first
+ - Sets the stop event to signal async loops to terminate
+ - Cancels all pending async tasks (openai-handler, record-loop, play-loop)
+ """
+ logger.info("Stopping LocalStream...")
+
+ # Stop media pipelines FIRST before cancelling async tasks
+ # This ensures clean shutdown before PortAudio cleanup
+ try:
+ self._robot.media.stop_recording()
+ except Exception as e:
+ logger.debug(f"Error stopping recording (may already be stopped): {e}")
+
+ try:
+ self._robot.media.stop_playing()
+ except Exception as e:
+ logger.debug(f"Error stopping playback (may already be stopped): {e}")
+
+ # Now signal async loops to stop
+ self._stop_event.set()
+
+ # Cancel all running tasks
+ for task in self._tasks:
+ if not task.done():
+ task.cancel()
+
+ def clear_audio_queue(self) -> None:
+ """Flush the player's appsrc to drop any queued audio immediately."""
+ logger.info("User intervention: flushing player queue")
+ if self._robot.media.backend == MediaBackend.GSTREAMER:
+ # Directly flush gstreamer audio pipe
+ self._robot.media.audio.clear_player()
+ elif (
+ self._robot.media.backend == MediaBackend.DEFAULT
+ or self._robot.media.backend == MediaBackend.DEFAULT_NO_VIDEO
+ ):
+ self._robot.media.audio.clear_output_buffer()
+ self.handler.output_queue = asyncio.Queue()
+
+ def _configure_sounddevice(self) -> None:
+ """Best-effort selection of Reachy Mini audio devices on Windows."""
+ try:
+ import sounddevice as sd
+
+ devices = sd.query_devices()
+ if not devices:
+ return
+
+ def _score(name: str) -> int:
+ n = name.lower()
+ if "wasapi" in n:
+ return 4
+ if "wdm-ks" in n:
+ return 3
+ if "directsound" in n:
+ return 2
+ if "mme" in n:
+ return 1
+ return 0
+
+ def _find_device(targets: List[str], io_type: str) -> Optional[int]:
+ candidates = []
+ for idx, dev in enumerate(devices):
+ name = str(dev.get("name", ""))
+ if dev.get(f"max_{io_type}_channels", 0) <= 0:
+ continue
+ for t in targets:
+ if t in name.lower():
+ candidates.append((idx, _score(name)))
+ break
+ if not candidates:
+ return None
+ candidates.sort(key=lambda item: item[1], reverse=True)
+ return candidates[0][0]
+
+ def _from_env(key: str, io_type: str) -> Optional[int]:
+ val = os.getenv(key, "").strip()
+ if not val:
+ return None
+ if val.isdigit():
+ return int(val)
+ return _find_device([val.lower()], io_type)
+
+ input_id = _from_env("COOKAIWARE_AUDIO_INPUT", "input")
+ output_id = _from_env("COOKAIWARE_AUDIO_OUTPUT", "output")
+
+ if input_id is None:
+ input_id = _find_device(["reachy mini audio"], "input")
+ if input_id is None:
+ input_id = _find_device(["reachy mini camera", "reachymini"], "input")
+ if input_id is None:
+ input_id = _find_device(["usb audio", "respeaker"], "input")
+ if output_id is None:
+ output_id = _find_device(["reachy mini audio"], "output")
+ if output_id is None:
+ output_id = _find_device(["usb audio", "respeaker"], "output")
+
+ if input_id is not None or output_id is not None:
+ current = list(sd.default.device)
+ if input_id is not None:
+ current[0] = input_id
+ if output_id is not None:
+ current[1] = output_id
+ sd.default.device = tuple(current)
+ input_name = devices[current[0]]["name"] if current[0] is not None else "unknown"
+ output_name = devices[current[1]]["name"] if current[1] is not None else "unknown"
+ logger.info(
+ "SoundDevice default set to input=%s (%s) output=%s (%s)",
+ current[0],
+ input_name,
+ current[1],
+ output_name,
+ )
+ except Exception as e:
+ logger.warning("Failed to configure SoundDevice defaults: %s", e)
+
+ async def record_loop(self) -> None:
+ """Read mic frames from the recorder and forward them to the handler."""
+ input_sample_rate = self._robot.media.get_input_audio_samplerate()
+ logger.debug(f"Audio recording started at {input_sample_rate} Hz")
+
+ while not self._stop_event.is_set():
+ audio_frame = self._robot.media.get_audio_sample()
+ if audio_frame is not None:
+ await self.handler.receive((input_sample_rate, audio_frame))
+ await asyncio.sleep(0) # avoid busy loop
+
+ async def play_loop(self) -> None:
+ """Fetch outputs from the handler: log text and play audio frames."""
+ while not self._stop_event.is_set():
+ handler_output = await self.handler.emit()
+
+ if isinstance(handler_output, AdditionalOutputs):
+ for msg in handler_output.args:
+ content = msg.get("content", "")
+ if isinstance(content, str):
+ role = str(msg.get("role", "assistant"))
+ self._transcript.append({"role": role, "content": content})
+ logger.info(
+ "role=%s content=%s",
+ msg.get("role"),
+ content if len(content) < 500 else content[:500] + "…",
+ )
+
+ elif isinstance(handler_output, tuple):
+ input_sample_rate, audio_data = handler_output
+ output_sample_rate = self._robot.media.get_output_audio_samplerate()
+
+ # Reshape if needed
+ if audio_data.ndim == 2:
+ # Scipy channels last convention
+ if audio_data.shape[1] > audio_data.shape[0]:
+ audio_data = audio_data.T
+ # Multiple channels -> Mono channel
+ if audio_data.shape[1] > 1:
+ audio_data = audio_data[:, 0]
+
+ # Cast if needed
+ audio_frame = audio_to_float32(audio_data)
+
+ # Resample if needed
+ if input_sample_rate != output_sample_rate:
+ audio_frame = resample(
+ audio_frame,
+ int(len(audio_frame) * output_sample_rate / input_sample_rate),
+ )
+
+ self._robot.media.push_audio_sample(audio_frame)
+
+ else:
+ logger.debug("Ignoring output type=%s", type(handler_output).__name__)
+
+ await asyncio.sleep(0) # yield to event loop
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/not used/main.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/not used/main.py
new file mode 100644
index 0000000000000000000000000000000000000000..abc68eb92677a7857aecf81a1d4025e0c69e21b5
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/not used/main.py
@@ -0,0 +1,451 @@
+"""Entrypoint for the Reachy Mini conversation app."""
+
+import os
+import sys
+import time
+import asyncio
+import argparse
+import threading
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Tuple
+
+import gradio as gr
+from fastapi import FastAPI
+from fastrtc import Stream
+from gradio.utils import get_space
+
+from reachy_mini import ReachyMini, ReachyMiniApp
+from Reachy_OpenWebUI.sub_apps.cookAIware.data_store import resolve_data_dir
+from Reachy_OpenWebUI.sub_apps.cookAIware.utils import (
+ parse_args,
+ setup_logger,
+ handle_vision_stuff,
+ log_connection_troubleshooting,
+)
+
+
+def update_chatbot(chatbot: List[Dict[str, Any]], response: Dict[str, Any]) -> List[Dict[str, Any]]:
+ """Update the chatbot with AdditionalOutputs."""
+ chatbot.append(response)
+ return chatbot
+
+
+def main() -> None:
+ """Entrypoint for the Reachy Mini conversation app."""
+ args, _ = parse_args()
+ run(args)
+
+
+def run(
+ args: argparse.Namespace,
+ robot: ReachyMini = None,
+ app_stop_event: Optional[threading.Event] = None,
+ settings_app: Optional[FastAPI] = None,
+ instance_path: Optional[str] = None,
+) -> None:
+ """Run the Reachy Mini conversation app."""
+ # Putting these dependencies here makes the dashboard faster to load when the conversation app is installed
+ from Reachy_OpenWebUI.sub_apps.cookAIware.moves import MovementManager
+ from cookAIware.console import LocalStream
+ from cookAIware.openai_realtime import OpenaiRealtimeHandler
+ from Reachy_OpenWebUI.sub_apps.cookAIware.tools.core_tools import ToolDependencies
+ from Reachy_OpenWebUI.sub_apps.cookAIware.audio.head_wobbler import HeadWobbler
+
+ logger = setup_logger(args.debug)
+ logger.info("Starting Reachy Mini Conversation App")
+
+ if args.no_camera and args.head_tracker is not None:
+ logger.warning("Head tracking disabled: --no-camera flag is set. Remove --no-camera to enable head tracking.")
+
+ if robot is None:
+ try:
+ robot_kwargs = {}
+ if args.robot_name is not None:
+ robot_kwargs["robot_name"] = args.robot_name
+
+ logger.info("Initializing ReachyMini (SDK will auto-detect appropriate backend)")
+ robot = ReachyMini(**robot_kwargs)
+
+ except TimeoutError as e:
+ logger.error(f"Connection timeout: Failed to connect to Reachy Mini daemon. Details: {e}")
+ log_connection_troubleshooting(logger, args.robot_name)
+ sys.exit(1)
+
+ except ConnectionError as e:
+ logger.error(f"Connection failed: Unable to establish connection to Reachy Mini. Details: {e}")
+ log_connection_troubleshooting(logger, args.robot_name)
+ sys.exit(1)
+
+ except Exception as e:
+ logger.error(f"Unexpected error during robot initialization: {type(e).__name__}: {e}")
+ logger.error("Please check your configuration and try again.")
+ sys.exit(1)
+
+ # Check if running in simulation mode without --gradio
+ if robot.client.get_status()["simulation_enabled"] and not args.gradio:
+ logger.error(
+ "Simulation mode requires Gradio interface. Please use --gradio flag when running in simulation mode."
+ )
+ robot.client.disconnect()
+ sys.exit(1)
+
+ camera_worker, _, vision_manager = handle_vision_stuff(args, robot)
+
+ movement_manager = MovementManager(
+ current_robot=robot,
+ camera_worker=camera_worker,
+ )
+
+ enable_motion = True
+ head_wobbler = HeadWobbler(set_speech_offsets=movement_manager.set_speech_offsets)
+
+ data_dir = resolve_data_dir(instance_path)
+ deps = ToolDependencies(
+ reachy_mini=robot,
+ movement_manager=movement_manager,
+ camera_worker=camera_worker,
+ vision_manager=vision_manager,
+ head_wobbler=head_wobbler,
+ data_dir=data_dir,
+ )
+ current_file_path = os.path.dirname(os.path.abspath(__file__))
+ logger.debug(f"Current file absolute path: {current_file_path}")
+ chatbot = gr.Chatbot(
+ type="messages",
+ resizable=True,
+ avatar_images=(
+ os.path.join(current_file_path, "images", "user_avatar.png"),
+ os.path.join(current_file_path, "images", "reachymini_avatar.png"),
+ ),
+ )
+ logger.debug(f"Chatbot avatar images: {chatbot.avatar_images}")
+
+ handler = OpenaiRealtimeHandler(deps, gradio_mode=args.gradio, instance_path=instance_path)
+ deps.handler = handler
+
+ stream_manager: gr.Blocks | LocalStream | None = None
+ gradio_app: FastAPI | None = None
+
+ if args.gradio:
+ has_env_key = bool(os.getenv("OPENAI_API_KEY")) and not get_space()
+ api_key_textbox = gr.Textbox(
+ label="OPENAI API Key (use .env or secrets)",
+ type="password",
+ value=os.getenv("OPENAI_API_KEY") if has_env_key else "",
+ visible=not has_env_key,
+ )
+ if has_env_key:
+ gr.Markdown("OpenAI API key loaded from `.env`. The input is hidden for safety.")
+
+ from cookAIware.gradio_personality import PersonalityUI
+
+ personality_ui = PersonalityUI()
+ personality_ui.create_components()
+
+ stream = Stream(
+ handler=handler,
+ mode="send-receive",
+ modality="audio",
+ additional_inputs=[
+ chatbot,
+ api_key_textbox,
+ *personality_ui.additional_inputs_ordered(),
+ ],
+ additional_outputs=[chatbot],
+ additional_outputs_handler=update_chatbot,
+ ui_args={"title": "Talk with Reachy Mini"},
+ )
+ stream_manager = stream.ui
+ if not settings_app:
+ app = FastAPI()
+ else:
+ app = settings_app
+
+ personality_ui.wire_events(handler, stream_manager)
+
+ def _plan_to_markdown(plan: Dict[str, Any]) -> str:
+ if not plan:
+ return "No meal plan available."
+ lines = [f"Week starting {plan.get('week_start', '')}"]
+ for day in plan.get("days", []):
+ lines.append(f"\n**{day.get('day', '').capitalize()} ({day.get('date', '')})**")
+ for meal in day.get("meals", []):
+ lines.append(f"- {meal.get('meal')}: {meal.get('name')}")
+ return "\n".join(lines)
+
+ def _list_to_markdown(items: List[Dict[str, Any]]) -> str:
+ if not items:
+ return "No shopping list items."
+ lines = []
+ for item in items:
+ name = item.get("name", "")
+ qty = item.get("quantity", 0)
+ unit = item.get("unit", "")
+ lines.append(f"- {name}: {qty} {unit}")
+ return "\n".join(lines)
+
+ def _load_profile() -> Tuple[int | None, int | None]:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.family_profile import load_profile
+
+ profile = load_profile(data_dir)
+ return profile.get("adults"), profile.get("children")
+
+ def _save_profile(adults: int | None, children: int | None) -> str:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.family_profile import update_profile
+
+ update_profile(data_dir, adults, children, None)
+ return "Profile saved."
+
+ def _load_inventory() -> List[List[Any]]:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.inventory import list_inventory
+
+ items = list_inventory(data_dir)
+ rows = []
+ for item in items:
+ rows.append(
+ [
+ item.get("display_name") or item.get("name", ""),
+ item.get("quantity", 0),
+ item.get("unit", ""),
+ item.get("expiration_date") or "",
+ item.get("storage_location") or "",
+ ]
+ )
+ return rows
+
+ def _save_inventory(rows: List[List[Any]]) -> str:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.inventory import normalize_items_for_save, save_inventory
+
+ items = []
+ for row in rows or []:
+ if not row:
+ continue
+ name = str(row[0]).strip() if len(row) > 0 else ""
+ if not name:
+ continue
+ items.append(
+ {
+ "name": name,
+ "quantity": row[1] if len(row) > 1 else None,
+ "unit": row[2] if len(row) > 2 else None,
+ "expiration_date": row[3] if len(row) > 3 else None,
+ "storage_location": row[4] if len(row) > 4 else None,
+ }
+ )
+ normalized = normalize_items_for_save(items)
+ save_inventory(data_dir, normalized)
+ return "Inventory saved."
+
+ def _generate_plan() -> str:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.inventory import list_inventory
+ from Reachy_OpenWebUI.sub_apps.cookAIware.family_profile import load_profile
+ from Reachy_OpenWebUI.sub_apps.cookAIware.meal_planner import generate_plan
+
+ profile = load_profile(data_dir)
+ adults = profile.get("adults")
+ children = profile.get("children")
+ if adults is None or children is None:
+ return "Set family profile first."
+ inventory = list_inventory(data_dir)
+ plan = generate_plan(data_dir, inventory, int(adults), int(children), profile.get("schedule"))
+ return _plan_to_markdown(plan)
+
+ def _load_plan() -> str:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.meal_planner import load_plan
+
+ return _plan_to_markdown(load_plan(data_dir))
+
+ def _generate_shopping_list() -> Tuple[List[List[Any]], str]:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.meal_planner import load_plan
+ from Reachy_OpenWebUI.sub_apps.cookAIware.inventory import list_inventory
+ from Reachy_OpenWebUI.sub_apps.cookAIware.shopping_list import generate_from_plan
+
+ plan = load_plan(data_dir)
+ inventory = list_inventory(data_dir)
+ items = generate_from_plan(data_dir, plan, inventory)
+ rows = [[item.get("name"), item.get("quantity"), item.get("unit")] for item in items]
+ return rows, _list_to_markdown(items)
+
+ def _load_shopping_list() -> Tuple[List[List[Any]], str]:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.shopping_list import list_items
+
+ items = list_items(data_dir)
+ rows = [[item.get("name"), item.get("quantity"), item.get("unit")] for item in items]
+ return rows, _list_to_markdown(items)
+
+ def _save_shopping_list(rows: List[List[Any]]) -> str:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.shopping_list import save_list
+
+ items = []
+ for row in rows or []:
+ if not row:
+ continue
+ name = str(row[0]).strip() if len(row) > 0 else ""
+ if not name:
+ continue
+ items.append({"name": name, "quantity": row[1] or 0, "unit": row[2] or "pcs"})
+ save_list(data_dir, items)
+ return "Shopping list saved."
+
+ async def _send_command(text: str) -> str:
+ if not text.strip():
+ return "Enter a command."
+ ok = await handler.send_text(text)
+ return "Sent." if ok else "Failed to send."
+
+ hero_image_path = str(Path(__file__).parent / "images" / "cookaiware-hero.png")
+
+ with stream.ui:
+ with gr.Tab("CookAIware"):
+ gr.Image(value=hero_image_path, show_label=False)
+ gr.Markdown("Manage inventory, profile, meal plan, and shopping list.")
+
+ with gr.Row():
+ adults = gr.Number(label="Adults", precision=0)
+ children = gr.Number(label="Children", precision=0)
+ profile_status = gr.Textbox(label="Profile status", interactive=False)
+
+ with gr.Row():
+ load_profile_btn = gr.Button("Load profile")
+ save_profile_btn = gr.Button("Save profile")
+
+ inventory_df = gr.Dataframe(
+ headers=["name", "quantity", "unit", "expiration_date", "storage_location"],
+ datatype=["str", "number", "str", "str", "str"],
+ label="Inventory",
+ interactive=True,
+ row_count=(0, "dynamic"),
+ )
+ inventory_status = gr.Textbox(label="Inventory status", interactive=False)
+ with gr.Row():
+ load_inventory_btn = gr.Button("Load inventory")
+ save_inventory_btn = gr.Button("Save inventory")
+
+ plan_md = gr.Markdown()
+ with gr.Row():
+ load_plan_btn = gr.Button("Load meal plan")
+ generate_plan_btn = gr.Button("Generate meal plan")
+
+ shopping_df = gr.Dataframe(
+ headers=["name", "quantity", "unit"],
+ datatype=["str", "number", "str"],
+ label="Shopping list",
+ interactive=True,
+ row_count=(0, "dynamic"),
+ )
+ shopping_md = gr.Markdown()
+ shopping_status = gr.Textbox(label="Shopping status", interactive=False)
+ with gr.Row():
+ load_shopping_btn = gr.Button("Load shopping list")
+ generate_shopping_btn = gr.Button("Generate shopping list")
+ save_shopping_btn = gr.Button("Save shopping list")
+
+ command_text = gr.Textbox(label="Send a command", placeholder="Plan our meals for this week")
+ send_command_btn = gr.Button("Send")
+ command_status = gr.Textbox(label="Command status", interactive=False)
+
+ load_profile_btn.click(_load_profile, outputs=[adults, children])
+ save_profile_btn.click(_save_profile, inputs=[adults, children], outputs=[profile_status])
+ load_inventory_btn.click(_load_inventory, outputs=[inventory_df])
+ save_inventory_btn.click(_save_inventory, inputs=[inventory_df], outputs=[inventory_status])
+ load_plan_btn.click(_load_plan, outputs=[plan_md])
+ generate_plan_btn.click(_generate_plan, outputs=[plan_md])
+ load_shopping_btn.click(_load_shopping_list, outputs=[shopping_df, shopping_md])
+ generate_shopping_btn.click(_generate_shopping_list, outputs=[shopping_df, shopping_md])
+ save_shopping_btn.click(_save_shopping_list, inputs=[shopping_df], outputs=[shopping_status])
+ send_command_btn.click(_send_command, inputs=[command_text], outputs=[command_status])
+ else:
+ # In headless mode, wire settings_app + instance_path to console LocalStream
+ stream_manager = LocalStream(
+ handler,
+ robot,
+ settings_app=settings_app,
+ instance_path=instance_path,
+ )
+
+ # Each async service → its own thread/loop
+ if enable_motion:
+ movement_manager.start()
+ if head_wobbler:
+ head_wobbler.start()
+ if camera_worker:
+ camera_worker.start()
+ if vision_manager:
+ vision_manager.start()
+
+ def poll_stop_event() -> None:
+ """Poll the stop event to allow graceful shutdown."""
+ if app_stop_event is not None:
+ app_stop_event.wait()
+
+ logger.info("App stop event detected, shutting down...")
+ if stream_manager is not None:
+ try:
+ stream_manager.close()
+ except Exception as e:
+ logger.error(f"Error while closing stream manager: {e}")
+
+ if app_stop_event:
+ threading.Thread(target=poll_stop_event, daemon=True).start()
+
+ try:
+ if stream_manager is None:
+ raise RuntimeError("Stream manager not initialized.")
+ stream_manager.launch()
+ except KeyboardInterrupt:
+ logger.info("Keyboard interruption in main thread... closing server.")
+ finally:
+ if enable_motion:
+ movement_manager.stop()
+ if head_wobbler:
+ head_wobbler.stop()
+ if camera_worker:
+ camera_worker.stop()
+ if vision_manager:
+ vision_manager.stop()
+
+ # Ensure media is explicitly closed before disconnecting
+ try:
+ robot.media.close()
+ except Exception as e:
+ logger.debug(f"Error closing media during shutdown: {e}")
+
+ # prevent connection to keep alive some threads
+ robot.client.disconnect()
+ time.sleep(1)
+ logger.info("Shutdown complete.")
+
+
+class Cookaiware(ReachyMiniApp): # type: ignore[misc]
+ """Reachy Mini Apps entry point for the conversation app."""
+
+ custom_app_url = "http://0.0.0.0:7860/"
+ dont_start_webserver = False
+
+ def run(self, reachy_mini: ReachyMini, stop_event: threading.Event) -> None:
+ """Run the Reachy Mini conversation app."""
+ loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(loop)
+
+ args, _ = parse_args()
+ args.gradio = False
+
+ # is_wireless = reachy_mini.client.get_status()["wireless_version"]
+ # args.head_tracker = None if is_wireless else "mediapipe"
+
+ instance_path = self._get_instance_path().parent
+ run(
+ args,
+ robot=reachy_mini,
+ app_stop_event=stop_event,
+ settings_app=self.settings_app,
+ instance_path=instance_path,
+ )
+
+
+if __name__ == "__main__":
+ app = Cookaiware()
+ try:
+ app.wrapped_run()
+ except KeyboardInterrupt:
+ app.stop()
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/__pycache__/app_settings_action.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/__pycache__/app_settings_action.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c710d795c1c4ef40d0fe2ae8b8409531ba2daad4
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/__pycache__/app_settings_action.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/__pycache__/custom_tool.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/__pycache__/custom_tool.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0e76972f52ad67a7b7bacea95cee09fdb5d3de91
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/__pycache__/custom_tool.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/__pycache__/family_profile_action.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/__pycache__/family_profile_action.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..77d3998d8291065e66f1e42bd7553d95d446170d
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/__pycache__/family_profile_action.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/__pycache__/inventory_action.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/__pycache__/inventory_action.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f632f6c86c43f2d3e68999c400b18c9cc0864e0c
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/__pycache__/inventory_action.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/__pycache__/meal_plan_action.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/__pycache__/meal_plan_action.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bd74a6f933ab6d5b6a0a2f12f8767caacc6e92c3
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/__pycache__/meal_plan_action.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/__pycache__/shopping_list_action.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/__pycache__/shopping_list_action.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a51ef4e1276e62f59841436967cc122f8ce53277
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/__pycache__/shopping_list_action.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/__pycache__/sweep_look.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/__pycache__/sweep_look.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1fa6198805ed86872a5def0098678c47fb625ee1
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/__pycache__/sweep_look.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/app_settings_action.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/app_settings_action.py
new file mode 100644
index 0000000000000000000000000000000000000000..08af13bac4f9b0624b37fab257296a3553697a66
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/app_settings_action.py
@@ -0,0 +1,55 @@
+from __future__ import annotations
+
+from typing import Any, Dict
+
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+from Reachy_OpenWebUI.sub_apps.cookAIware.app_settings import get_settings, set_language, set_unit_system
+
+
+class AppSettingsActionTool(Tool):
+ name = "app_settings_action"
+ description = "Get or update app settings like language or unit system."
+ parameters_schema = {
+ "type": "object",
+ "properties": {
+ "action": {"type": "string", "enum": ["get", "set_language", "set_unit_system"]},
+ "language": {"type": "string"},
+ "unit_system": {"type": "string", "enum": ["metric", "imperial"]},
+ },
+ "required": ["action"],
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ if deps.data_dir is None:
+ return {"status": "error", "message": "Data directory not available."}
+
+ action = kwargs.get("action")
+ if action == "get":
+ return {"status": "ok", "settings": get_settings(deps.data_dir)}
+
+ if action == "set_language":
+ language = (kwargs.get("language") or "").strip()
+ if not language:
+ return {"status": "needs_clarification", "missing": ["language"]}
+ settings = set_language(deps.data_dir, language)
+ if deps.handler is not None:
+ try:
+ await deps.handler.apply_language(language)
+ except Exception:
+ pass
+ return {"status": "ok", "settings": settings}
+
+ if action == "set_unit_system":
+ unit_system = (kwargs.get("unit_system") or "").strip().lower()
+ if unit_system not in ("metric", "imperial"):
+ return {"status": "needs_clarification", "missing": ["unit_system"], "valid": ["metric", "imperial"]}
+ settings = set_unit_system(deps.data_dir, unit_system)
+ if deps.handler is not None:
+ try:
+ await deps.handler.apply_unit_system(unit_system)
+ except Exception:
+ pass
+ return {"status": "ok", "settings": settings}
+
+ return {"status": "error", "message": "Unknown action."}
+
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/custom_tool.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/custom_tool.py
new file mode 100644
index 0000000000000000000000000000000000000000..8adb126561f71f606eeeec0add2ca9c1c2320fef
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/custom_tool.py
@@ -0,0 +1,38 @@
+"""Custom tool template - modify this to create your own tools."""
+
+import logging
+from typing import Any
+
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+
+logger = logging.getLogger(__name__)
+
+
+class CustomTool(Tool):
+ """A custom tool template. Modify this to create your own tool."""
+
+ name = "custom_tool"
+ description = "A placeholder custom tool - replace this with your own implementation"
+ parameters_schema = {
+ "type": "object",
+ "properties": {
+ "message": {
+ "type": "string",
+ "description": "An optional message to log",
+ },
+ },
+ "required": [],
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> dict[str, Any]:
+ """Execute the custom tool."""
+ message = kwargs.get("message", "no message")
+ logger.info(f"CustomTool called with message: {message}")
+
+ # TODO: Add your custom logic here
+ # You have access to:
+ # - deps.reachy_mini: the robot SDK
+ # - deps.movement_manager: for queueing movements
+ # - deps.state: current conversation state
+
+ return {"status": "ok"}
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/family_profile_action.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/family_profile_action.py
new file mode 100644
index 0000000000000000000000000000000000000000..43dfd537d8bb58d82d450395f07a99fb8711b2b5
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/family_profile_action.py
@@ -0,0 +1,51 @@
+from __future__ import annotations
+
+from typing import Any, Dict
+
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+from Reachy_OpenWebUI.sub_apps.cookAIware.family_profile import load_profile, update_profile, default_schedule
+
+
+class FamilyProfileActionTool(Tool):
+ name = "family_profile_action"
+ description = "Get or update the family profile (adults, children, schedule)."
+ parameters_schema = {
+ "type": "object",
+ "properties": {
+ "action": {"type": "string", "enum": ["get", "set"]},
+ "adults": {"type": "integer"},
+ "children": {"type": "integer"},
+ "schedule": {"type": "object"},
+ },
+ "required": ["action"],
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ if deps.data_dir is None:
+ return {"status": "error", "message": "Data directory not available."}
+
+ action = kwargs.get("action")
+ if action == "get":
+ profile = load_profile(deps.data_dir)
+ missing = []
+ if profile.get("adults") in (None, 0):
+ missing.append("adults")
+ if profile.get("children") in (None,):
+ missing.append("children")
+ if not profile.get("schedule"):
+ profile["schedule"] = default_schedule()
+ return {
+ "status": "needs_clarification" if missing else "ok",
+ "profile": profile,
+ "missing": missing,
+ }
+
+ if action == "set":
+ adults = kwargs.get("adults")
+ children = kwargs.get("children")
+ schedule = kwargs.get("schedule")
+ profile = update_profile(deps.data_dir, adults, children, schedule)
+ return {"status": "ok", "profile": profile}
+
+ return {"status": "error", "message": "Unknown action."}
+
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/instructions.txt b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/instructions.txt
new file mode 100644
index 0000000000000000000000000000000000000000..cc20598f34d9c77b8be521e34406cb8d7de1846a
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/instructions.txt
@@ -0,0 +1,37 @@
+You are CookAIware, a helpful Reachy Mini assistant for family food inventory, meal planning, and shopping lists.
+
+Core rules:
+- Use the available tools to read or update data. Do not invent or store state yourself.
+- Never invent food that is not in the inventory.
+- Ask clarifying questions if required data is missing.
+- Use the selected unit system from app settings. Accept metric units (g, kg, ml, l, pcs) and imperial units (oz, lb, fl oz, qt, gal, tsp, tbsp, cup, pcs).
+- Track expiration dates and storage locations for food items. If the user does not know an expiration date, store it as unknown and do not block the flow.
+
+What you can do:
+- Add food items, list inventory, and reduce quantities when cooking.
+- Generate a weekly meal plan based on inventory, family size, and schedule.
+- Answer day-based questions (e.g., what's for dinner on Friday?).
+- Generate and manage a shopping list based on the meal plan and current stock.
+- Auto-add low, depleted, or expired inventory items to the shopping list when asked.
+
+Default schedule (editable per plan):
+- Weekdays: dinner for all; 1 adult lunch on 3 weekdays.
+- Weekends: lunch and dinner for all.
+
+When you need missing details (quantity, unit), ask for them clearly. Expiration date and storage location are optional if unknown.
+Keep responses short and family-friendly. Use the tool results to respond.
+
+Tool usage summary:
+- inventory_action: add, cook, list
+- family_profile_action: get, set
+- meal_plan_action: generate, get, get_day, update_day (use update_day to change a specific day/meal)
+- shopping_list_action: generate, auto_inventory, list, add, remove, clear
+- app_settings_action: get, set_language, set_unit_system
+- Use app_settings_action to change the conversation language or unit system when asked.
+
+Movement and expressions:
+- dance / stop_dance: play a named or random dance move when the user asks you to dance or to celebrate (e.g., a finished meal plan).
+- play_emotion / stop_emotion: express short emotions (happy, curious, sad...) to react to events.
+- move_head: look in a direction when asked.
+- look_around: scan by turning Reachy's head/body and taking center, left, and right images.
+- Use movements sparingly and never let them interrupt an ongoing answer about food data.
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/inventory_action.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/inventory_action.py
new file mode 100644
index 0000000000000000000000000000000000000000..0c365e143fd26e4033521a15b873ac02741fdec9
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/inventory_action.py
@@ -0,0 +1,99 @@
+from __future__ import annotations
+
+from typing import Any, Dict, List
+
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+from Reachy_OpenWebUI.sub_apps.cookAIware.app_settings import get_unit_system
+from Reachy_OpenWebUI.sub_apps.cookAIware.inventory import add_items, cook_items, list_inventory, format_inventory, normalize_for_display
+
+
+class InventoryActionTool(Tool):
+ name = "inventory_action"
+ description = "Add food, cook food, or list inventory items."
+ parameters_schema = {
+ "type": "object",
+ "properties": {
+ "action": {"type": "string", "enum": ["add", "cook", "list"]},
+ "items": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string"},
+ "quantity": {"type": "number"},
+ "unit": {"type": "string"},
+ "expiration_date": {"type": "string"},
+ "storage_location": {"type": "string"},
+ },
+ },
+ },
+ },
+ "required": ["action"],
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ if deps.data_dir is None:
+ return {"status": "error", "message": "Data directory not available."}
+
+ action = kwargs.get("action")
+ items = kwargs.get("items") or []
+
+ if action == "list":
+ inventory = list_inventory(deps.data_dir)
+ unit_system = get_unit_system(deps.data_dir)
+ return {
+ "status": "ok",
+ "message": "Inventory listed.",
+ "items": normalize_for_display(inventory, unit_system),
+ "lines": format_inventory(inventory, unit_system),
+ }
+
+ if action in ("add", "cook") and not items:
+ return {
+ "status": "needs_clarification",
+ "message": "Which items?",
+ "missing": ["items"],
+ }
+
+ missing_fields: List[str] = []
+ for item in items:
+ if not item.get("name"):
+ missing_fields.append("name")
+ if action == "add":
+ if item.get("quantity") is None:
+ missing_fields.append("quantity")
+ if not item.get("unit"):
+ missing_fields.append("unit")
+ if action == "cook":
+ if item.get("quantity") is None:
+ missing_fields.append("quantity")
+ if not item.get("unit"):
+ missing_fields.append("unit")
+
+ if missing_fields:
+ return {
+ "status": "needs_clarification",
+ "message": "Missing details.",
+ "missing": sorted(set(missing_fields)),
+ }
+
+ if action == "add":
+ inventory, errors = add_items(deps.data_dir, items)
+ return {
+ "status": "ok" if not errors else "partial",
+ "message": "Items added." if not errors else "Some items need attention.",
+ "errors": errors,
+ "items": normalize_for_display(inventory, get_unit_system(deps.data_dir)),
+ }
+
+ if action == "cook":
+ inventory, errors = cook_items(deps.data_dir, items)
+ return {
+ "status": "ok" if not errors else "partial",
+ "message": "Inventory updated." if not errors else "Some items need attention.",
+ "errors": errors,
+ "items": normalize_for_display(inventory, get_unit_system(deps.data_dir)),
+ }
+
+ return {"status": "error", "message": "Unknown action."}
+
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/meal_plan_action.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/meal_plan_action.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f649269086a550dac88d85e41b1cfac834130fc
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/meal_plan_action.py
@@ -0,0 +1,165 @@
+from __future__ import annotations
+
+from typing import Any, Dict
+
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+from Reachy_OpenWebUI.sub_apps.cookAIware.app_settings import get_unit_system
+from Reachy_OpenWebUI.sub_apps.cookAIware.family_profile import load_profile
+from Reachy_OpenWebUI.sub_apps.cookAIware.inventory import list_inventory
+from Reachy_OpenWebUI.sub_apps.cookAIware.meal_planner import generate_plan, load_plan, meal_for_day, resolve_day_to_date
+from Reachy_OpenWebUI.sub_apps.cookAIware.units import format_quantity
+
+
+def _reformat_plan(plan: Any, unit_system: str) -> Any:
+ if not isinstance(plan, dict):
+ return plan
+ days = plan.get("days")
+ if not isinstance(days, list):
+ return plan
+ for day in days:
+ for meal in day.get("meals", []):
+ for ing in meal.get("ingredients", []):
+ qty = ing.get("quantity")
+ unit = ing.get("unit")
+ if qty is not None and unit:
+ ing["display_quantity"] = format_quantity(float(qty), unit, unit_system)
+ return plan
+
+
+class MealPlanActionTool(Tool):
+ name = "meal_plan_action"
+ description = "Generate a weekly meal plan, get the plan, query a day, or update a day."
+ parameters_schema = {
+ "type": "object",
+ "properties": {
+ "action": {"type": "string", "enum": ["generate", "get", "get_day", "update_day"]},
+ "schedule_override": {"type": "object"},
+ "day": {"type": "string"},
+ "date": {"type": "string"},
+ "meals": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "meal": {"type": "string"},
+ "name": {"type": "string"},
+ "ingredients": {"type": "array", "items": {"type": "string"}},
+ },
+ },
+ },
+ },
+ "required": ["action"],
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ if deps.data_dir is None:
+ return {"status": "error", "message": "Data directory not available."}
+
+ action = kwargs.get("action")
+ unit_system = get_unit_system(deps.data_dir)
+ if action == "get":
+ plan = load_plan(deps.data_dir)
+ return {"status": "ok" if plan else "empty", "plan": _reformat_plan(plan, unit_system)}
+
+ if action == "generate":
+ profile = load_profile(deps.data_dir)
+ adults = profile.get("adults")
+ children = profile.get("children")
+ if adults is None or children is None:
+ return {
+ "status": "needs_clarification",
+ "message": "Family profile missing.",
+ "missing": ["adults", "children"],
+ }
+ inventory = list_inventory(deps.data_dir)
+ if not inventory:
+ return {
+ "status": "needs_clarification",
+ "message": "Inventory is empty.",
+ "missing": ["inventory"],
+ }
+ schedule_override = kwargs.get("schedule_override") or profile.get("schedule")
+ plan = generate_plan(deps.data_dir, inventory, int(adults), int(children), schedule_override, unit_system)
+ return {"status": "ok", "plan": plan}
+
+ if action == "get_day":
+ plan = load_plan(deps.data_dir)
+ if not plan:
+ return {"status": "empty", "message": "No plan available."}
+ day = kwargs.get("day")
+ date_str = kwargs.get("date")
+ if day and not date_str:
+ date_str = resolve_day_to_date(day)
+ entry = meal_for_day(plan, day, date_str)
+ if not entry:
+ return {"status": "empty", "message": "No meal found for that day."}
+ _reformat_plan({"days": [entry]}, unit_system)
+ return {"status": "ok", "day": entry}
+
+ if action == "update_day":
+ plan = load_plan(deps.data_dir)
+ if not plan:
+ return {"status": "empty", "message": "No plan available."}
+ day = kwargs.get("day")
+ date_str = kwargs.get("date")
+ if day and not date_str:
+ date_str = resolve_day_to_date(day)
+ entry = meal_for_day(plan, day, date_str)
+ if not entry:
+ return {"status": "empty", "message": "No meal found for that day."}
+ meals = kwargs.get("meals") or []
+ if not meals:
+ return {"status": "needs_clarification", "missing": ["meals"]}
+
+ inventory = list_inventory(deps.data_dir)
+ inventory_names = {item.get("name") for item in inventory if item.get("name")}
+ display_map = {
+ (item.get("display_name") or "").strip().lower(): item.get("name")
+ for item in inventory
+ if item.get("name")
+ }
+ for update in meals:
+ meal_name = update.get("meal")
+ if not meal_name:
+ continue
+ target = next((m for m in entry.get("meals", []) if m.get("meal") == meal_name), None)
+ if not target:
+ continue
+ raw_ingredients = update.get("ingredients") or []
+ ingredients = []
+ for ing in raw_ingredients:
+ name = str(ing).strip().lower()
+ if not name:
+ continue
+ mapped = display_map.get(name, name)
+ if mapped not in inventory_names:
+ ingredients.append(name)
+ else:
+ ingredients.append(mapped)
+ if ingredients:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.meal_planner import build_ingredient_entries
+
+ servings = int(target.get("servings") or 1)
+ target["ingredients"] = build_ingredient_entries(inventory, ingredients, servings, unit_system)
+ if update.get("name"):
+ target["name"] = update.get("name")
+ else:
+ if len(ingredients) == 1:
+ target["name"] = ingredients[0]
+ elif len(ingredients) == 2:
+ target["name"] = f"{ingredients[0]} with {ingredients[1]}"
+ else:
+ target["name"] = f"{ingredients[0]} with {ingredients[1]} and {ingredients[2]}"
+ elif update.get("name"):
+ target["name"] = update.get("name")
+
+ from Reachy_OpenWebUI.sub_apps.cookAIware.meal_planner import save_plan
+
+ save_plan(deps.data_dir, plan)
+ return {"status": "ok", "plan": _reformat_plan(plan, unit_system)}
+
+ return {
+ "status": "error",
+ "message": "Unknown action. Use generate, get, get_day, or update_day.",
+ }
+
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/shopping_list_action.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/shopping_list_action.py
new file mode 100644
index 0000000000000000000000000000000000000000..0244609ee05255e2493ac82175b1e6c636bf452c
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/shopping_list_action.py
@@ -0,0 +1,84 @@
+from __future__ import annotations
+
+from typing import Any, Dict
+
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+from Reachy_OpenWebUI.sub_apps.cookAIware.app_settings import get_unit_system
+from Reachy_OpenWebUI.sub_apps.cookAIware.inventory import list_inventory
+from Reachy_OpenWebUI.sub_apps.cookAIware.meal_planner import load_plan
+from Reachy_OpenWebUI.sub_apps.cookAIware.shopping_list import (
+ generate_from_inventory_alerts,
+ generate_from_plan,
+ list_items,
+ add_items,
+ remove_items,
+ clear_list,
+ format_list,
+)
+
+
+class ShoppingListActionTool(Tool):
+ name = "shopping_list_action"
+ description = "Generate or manage the shopping list."
+ parameters_schema = {
+ "type": "object",
+ "properties": {
+ "action": {"type": "string", "enum": ["generate", "auto_inventory", "list", "add", "remove", "clear"]},
+ "items": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string"},
+ "quantity": {"type": "number"},
+ "unit": {"type": "string"},
+ },
+ },
+ },
+ },
+ "required": ["action"],
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ if deps.data_dir is None:
+ return {"status": "error", "message": "Data directory not available."}
+
+ action = kwargs.get("action")
+ unit_system = get_unit_system(deps.data_dir)
+ if action == "list":
+ items = list_items(deps.data_dir)
+ return {"status": "ok", "items": items, "lines": format_list(items, unit_system)}
+
+ if action == "generate":
+ plan = load_plan(deps.data_dir)
+ if not plan:
+ return {"status": "needs_clarification", "message": "No meal plan available.", "missing": ["plan"]}
+ inventory = list_inventory(deps.data_dir)
+ items = generate_from_plan(deps.data_dir, plan, inventory)
+ return {"status": "ok", "items": items, "lines": format_list(items, unit_system)}
+
+ if action == "auto_inventory":
+ inventory = list_inventory(deps.data_dir)
+ items = generate_from_inventory_alerts(deps.data_dir, inventory)
+ return {"status": "ok", "items": items, "lines": format_list(items, unit_system)}
+
+ if action == "add":
+ items = kwargs.get("items") or []
+ if not items:
+ return {"status": "needs_clarification", "missing": ["items"]}
+ updated = add_items(deps.data_dir, items)
+ return {"status": "ok", "items": updated, "lines": format_list(updated, unit_system)}
+
+ if action == "remove":
+ items = kwargs.get("items") or []
+ if not items:
+ return {"status": "needs_clarification", "missing": ["items"]}
+ updated = remove_items(deps.data_dir, items)
+ return {"status": "ok", "items": updated, "lines": format_list(updated, unit_system)}
+
+ if action == "clear":
+ clear_list(deps.data_dir)
+ return {"status": "ok", "items": []}
+
+ return {"status": "error", "message": "Unknown action."}
+
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/sweep_look.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/sweep_look.py
new file mode 100644
index 0000000000000000000000000000000000000000..98e0e175858d316a597e4bf4e78f2e513550a19e
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/sweep_look.py
@@ -0,0 +1,127 @@
+import logging
+from typing import Any, Dict
+
+import numpy as np
+
+from reachy_mini.utils import create_head_pose
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+from Reachy_OpenWebUI.dance_emotion_moves import GotoQueueMove
+
+
+logger = logging.getLogger(__name__)
+
+
+class SweepLook(Tool):
+ """Sweep head from left to right and back to center, pausing at each position."""
+
+ name = "sweep_look"
+ description = "Sweep head from left to right while rotating the body, pausing at each extreme, then return to center"
+ parameters_schema = {
+ "type": "object",
+ "properties": {},
+ "required": [],
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ """Execute sweep look: left -> hold -> right -> hold -> center."""
+ logger.info("Tool call: sweep_look")
+
+ # Clear any existing moves
+ deps.movement_manager.clear_move_queue()
+
+ # Get current state
+ current_head_pose = deps.reachy_mini.get_current_head_pose()
+ head_joints, antenna_joints = deps.reachy_mini.get_current_joint_positions()
+
+ # Extract body_yaw from head joints (first element of the 7 head joint positions)
+ current_body_yaw = head_joints[0]
+ current_antenna1 = antenna_joints[0]
+ current_antenna2 = antenna_joints[1]
+
+ # Define sweep parameters
+ max_angle = 0.9 * np.pi # Maximum rotation angle (radians)
+ transition_duration = 3.0 # Time to move between positions
+ hold_duration = 1.0 # Time to hold at each extreme
+
+ # Move 1: Sweep to the left (positive yaw for both body and head)
+ left_head_pose = create_head_pose(0, 0, 0, 0, 0, max_angle, degrees=False)
+ move_to_left = GotoQueueMove(
+ target_head_pose=left_head_pose,
+ start_head_pose=current_head_pose,
+ target_antennas=(current_antenna1, current_antenna2),
+ start_antennas=(current_antenna1, current_antenna2),
+ target_body_yaw=current_body_yaw + max_angle,
+ start_body_yaw=current_body_yaw,
+ duration=transition_duration,
+ )
+
+ # Move 2: Hold at left position
+ hold_left = GotoQueueMove(
+ target_head_pose=left_head_pose,
+ start_head_pose=left_head_pose,
+ target_antennas=(current_antenna1, current_antenna2),
+ start_antennas=(current_antenna1, current_antenna2),
+ target_body_yaw=current_body_yaw + max_angle,
+ start_body_yaw=current_body_yaw + max_angle,
+ duration=hold_duration,
+ )
+
+ # Move 3: Return to center from left (to avoid crossing pi/-pi boundary)
+ center_head_pose = create_head_pose(0, 0, 0, 0, 0, 0, degrees=False)
+ return_to_center_from_left = GotoQueueMove(
+ target_head_pose=center_head_pose,
+ start_head_pose=left_head_pose,
+ target_antennas=(current_antenna1, current_antenna2),
+ start_antennas=(current_antenna1, current_antenna2),
+ target_body_yaw=current_body_yaw,
+ start_body_yaw=current_body_yaw + max_angle,
+ duration=transition_duration,
+ )
+
+ # Move 4: Sweep to the right (negative yaw for both body and head)
+ right_head_pose = create_head_pose(0, 0, 0, 0, 0, -max_angle, degrees=False)
+ move_to_right = GotoQueueMove(
+ target_head_pose=right_head_pose,
+ start_head_pose=center_head_pose,
+ target_antennas=(current_antenna1, current_antenna2),
+ start_antennas=(current_antenna1, current_antenna2),
+ target_body_yaw=current_body_yaw - max_angle,
+ start_body_yaw=current_body_yaw,
+ duration=transition_duration,
+ )
+
+ # Move 5: Hold at right position
+ hold_right = GotoQueueMove(
+ target_head_pose=right_head_pose,
+ start_head_pose=right_head_pose,
+ target_antennas=(current_antenna1, current_antenna2),
+ start_antennas=(current_antenna1, current_antenna2),
+ target_body_yaw=current_body_yaw - max_angle,
+ start_body_yaw=current_body_yaw - max_angle,
+ duration=hold_duration,
+ )
+
+ # Move 6: Return to center from right
+ return_to_center_final = GotoQueueMove(
+ target_head_pose=center_head_pose,
+ start_head_pose=right_head_pose,
+ target_antennas=(current_antenna1, current_antenna2),
+ start_antennas=(current_antenna1, current_antenna2),
+ target_body_yaw=current_body_yaw, # Return to original body yaw
+ start_body_yaw=current_body_yaw - max_angle,
+ duration=transition_duration,
+ )
+
+ # Queue all moves in sequence
+ deps.movement_manager.queue_move(move_to_left)
+ deps.movement_manager.queue_move(hold_left)
+ deps.movement_manager.queue_move(return_to_center_from_left)
+ deps.movement_manager.queue_move(move_to_right)
+ deps.movement_manager.queue_move(hold_right)
+ deps.movement_manager.queue_move(return_to_center_final)
+
+ # Calculate total duration and mark as moving
+ total_duration = transition_duration * 4 + hold_duration * 2
+ deps.movement_manager.set_moving_state(total_duration)
+
+ return {"status": f"sweeping look left-right-center, total {total_duration:.1f}s"}
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/tools.txt b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/tools.txt
new file mode 100644
index 0000000000000000000000000000000000000000..2d96af1d6a3e65954db421daaff16463d9d91d07
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/profiles/cookaiware/tools.txt
@@ -0,0 +1,12 @@
+# Available tools for this profile
+inventory_action
+family_profile_action
+meal_plan_action
+shopping_list_action
+app_settings_action
+dance
+stop_dance
+play_emotion
+stop_emotion
+move_head
+sweep_look
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/prompts.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/prompts.py
new file mode 100644
index 0000000000000000000000000000000000000000..d59353695ebd99c9ad29e1771b095ca9371aab35
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/prompts.py
@@ -0,0 +1,104 @@
+import re
+import sys
+import logging
+from pathlib import Path
+
+from Reachy_OpenWebUI.config import config
+
+
+logger = logging.getLogger(__name__)
+
+
+PROFILES_DIRECTORY = Path(__file__).parent / "profiles"
+PROMPTS_LIBRARY_DIRECTORY = Path(__file__).parent / "prompts"
+INSTRUCTIONS_FILENAME = "instructions.txt"
+VOICE_FILENAME = "voice.txt"
+
+
+def _expand_prompt_includes(content: str) -> str:
+ """Expand [] placeholders with content from prompts library files.
+
+ Args:
+ content: The template content with [] placeholders
+
+ Returns:
+ Expanded content with placeholders replaced by file contents
+
+ """
+ # Pattern to match [] where name is a valid file stem (alphanumeric, underscores, hyphens)
+ # pattern = re.compile(r'^\[([a-zA-Z0-9_-]+)\]$')
+ # Allow slashes for subdirectories
+ pattern = re.compile(r'^\[([a-zA-Z0-9/_-]+)\]$')
+
+ lines = content.split('\n')
+ expanded_lines = []
+
+ for line in lines:
+ stripped = line.strip()
+ match = pattern.match(stripped)
+
+ if match:
+ # Extract the name from []
+ template_name = match.group(1)
+ template_file = PROMPTS_LIBRARY_DIRECTORY / f"{template_name}.txt"
+
+ try:
+ if template_file.exists():
+ template_content = template_file.read_text(encoding="utf-8").rstrip()
+ expanded_lines.append(template_content)
+ logger.debug("Expanded template: [%s]", template_name)
+ else:
+ logger.warning("Template file not found: %s, keeping placeholder", template_file)
+ expanded_lines.append(line)
+ except Exception as e:
+ logger.warning("Failed to read template '%s': %s, keeping placeholder", template_name, e)
+ expanded_lines.append(line)
+ else:
+ expanded_lines.append(line)
+
+ return '\n'.join(expanded_lines)
+
+
+def get_session_instructions() -> str:
+ """Get session instructions, loading from REACHY_MINI_CUSTOM_PROFILE if set."""
+ profile = config.REACHY_MINI_CUSTOM_PROFILE
+ if not profile:
+ logger.info(f"Loading default prompt from {PROMPTS_LIBRARY_DIRECTORY / 'default_prompt.txt'}")
+ instructions_file = PROMPTS_LIBRARY_DIRECTORY / "default_prompt.txt"
+ else:
+ logger.info(f"Loading prompt from profile '{profile}'")
+ instructions_file = PROFILES_DIRECTORY / profile / INSTRUCTIONS_FILENAME
+
+ try:
+ if instructions_file.exists():
+ instructions = instructions_file.read_text(encoding="utf-8").strip()
+ if instructions:
+ # Expand [] placeholders with content from prompts library
+ expanded_instructions = _expand_prompt_includes(instructions)
+ return expanded_instructions
+ logger.error(f"Profile '{profile}' has empty {INSTRUCTIONS_FILENAME}")
+ sys.exit(1)
+ logger.error(f"Profile {profile} has no {INSTRUCTIONS_FILENAME}")
+ sys.exit(1)
+ except Exception as e:
+ logger.error(f"Failed to load instructions from profile '{profile}': {e}")
+ sys.exit(1)
+
+
+def get_session_voice(default: str = "cedar") -> str:
+ """Resolve the voice to use for the session.
+
+ If a custom profile is selected and contains a voice.txt, return its
+ trimmed content; otherwise return the provided default ("cedar").
+ """
+ profile = config.REACHY_MINI_CUSTOM_PROFILE
+ if not profile:
+ return default
+ try:
+ voice_file = PROFILES_DIRECTORY / profile / VOICE_FILENAME
+ if voice_file.exists():
+ voice = voice_file.read_text(encoding="utf-8").strip()
+ return voice or default
+ except Exception:
+ pass
+ return default
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/shopping_list.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/shopping_list.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5b824bc936a94e63839ef425853f35c821901ed
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/shopping_list.py
@@ -0,0 +1,193 @@
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+from typing import Any, Dict, List, Tuple
+
+from Reachy_OpenWebUI.sub_apps.cookAIware.data_store import load_json, save_json
+from Reachy_OpenWebUI.sub_apps.cookAIware.inventory import available_quantity, unit_for_item
+from Reachy_OpenWebUI.sub_apps.cookAIware.units import format_quantity
+
+
+SHOPPING_LIST_FILE = "shopping_list.json"
+
+
+def _list_path(data_dir: Path) -> Path:
+ return data_dir / SHOPPING_LIST_FILE
+
+
+def load_list(data_dir: Path) -> List[Dict[str, Any]]:
+ return load_json(_list_path(data_dir), [])
+
+
+def save_list(data_dir: Path, items: List[Dict[str, Any]]) -> None:
+ save_json(_list_path(data_dir), items)
+
+
+def list_items(data_dir: Path) -> List[Dict[str, Any]]:
+ items = load_list(data_dir)
+ items.sort(key=lambda item: item.get("name", ""))
+ return items
+
+
+def add_items(data_dir: Path, items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
+ current = load_list(data_dir)
+ for item in items:
+ name = str(item.get("name", "")).strip().lower()
+ if not name:
+ continue
+ qty = float(item.get("quantity", 1.0))
+ unit = item.get("unit") or "pcs"
+ reason = item.get("reason")
+ merged = False
+ for existing in current:
+ if existing.get("name") == name and existing.get("unit") == unit:
+ existing["quantity"] = float(existing.get("quantity", 0.0)) + qty
+ if reason:
+ existing["reason"] = reason
+ merged = True
+ break
+ if not merged:
+ entry = {"name": name, "quantity": qty, "unit": unit}
+ if reason:
+ entry["reason"] = reason
+ current.append(entry)
+ save_list(data_dir, current)
+ return current
+
+
+def remove_items(data_dir: Path, items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
+ current = load_list(data_dir)
+ for item in items:
+ name = str(item.get("name", "")).strip().lower()
+ if not name:
+ continue
+ unit = item.get("unit")
+ current = [
+ entry
+ for entry in current
+ if not (entry.get("name") == name and (unit is None or entry.get("unit") == unit))
+ ]
+ save_list(data_dir, current)
+ return current
+
+
+def clear_list(data_dir: Path) -> None:
+ save_list(data_dir, [])
+
+
+def _is_expired(expiration_date: Any) -> bool:
+ if not expiration_date:
+ return False
+ try:
+ expires = datetime.fromisoformat(str(expiration_date).strip()).date()
+ except ValueError:
+ return False
+ return expires < datetime.now().date()
+
+
+def _low_target(unit: str) -> float:
+ if unit in {"g", "gram", "grams"}:
+ return 500.0
+ if unit in {"ml", "milliliter", "milliliters"}:
+ return 1000.0
+ return 1.0
+
+
+def generate_from_inventory_alerts(
+ data_dir: Path,
+ inventory: List[Dict[str, Any]],
+) -> List[Dict[str, Any]]:
+ shopping: List[Dict[str, Any]] = []
+ for item in inventory:
+ if not item.get("auto_add_shopping"):
+ continue
+ name = str(item.get("name") or item.get("display_name") or "").strip().lower()
+ if not name:
+ continue
+ unit = str(item.get("unit") or "pcs").strip() or "pcs"
+ try:
+ quantity = float(item.get("quantity", 0.0))
+ except (TypeError, ValueError):
+ quantity = 0.0
+
+ target = _low_target(unit)
+ expired = _is_expired(item.get("expiration_date"))
+ depleted = quantity <= 0
+ low = 0 < quantity < target
+ if not (expired or depleted or low):
+ continue
+
+ if expired:
+ add_qty = max(quantity, target)
+ reason = "expired"
+ elif depleted:
+ add_qty = target
+ reason = "depleted"
+ else:
+ add_qty = target - quantity
+ reason = "low"
+
+ shopping.append({"name": name, "quantity": add_qty, "unit": unit, "reason": reason})
+ return add_items(data_dir, shopping)
+
+
+def format_list(items: List[Dict[str, Any]], unit_system: str = "metric") -> List[str]:
+ output: List[str] = []
+ for item in items:
+ qty = float(item.get("quantity", 0.0))
+ unit = item.get("unit", "pcs")
+ name = item.get("name", "")
+ required = item.get("required_quantity")
+ available = item.get("available_quantity")
+ if required is not None and available is not None:
+ output.append(
+ f"{name} - need {format_quantity(float(required), unit, unit_system)}"
+ f" (have {format_quantity(float(available), unit, unit_system)})"
+ )
+ else:
+ reason = item.get("reason")
+ suffix = f" ({reason})" if reason else ""
+ output.append(f"{name} - {format_quantity(qty, unit, unit_system)}{suffix}")
+ return output
+
+
+def generate_from_plan(
+ data_dir: Path,
+ plan: Dict[str, Any],
+ inventory: List[Dict[str, Any]],
+) -> List[Dict[str, Any]]:
+ if not plan:
+ return []
+ required: Dict[Tuple[str, str], float] = {}
+
+ for day in plan.get("days", []):
+ for meal in day.get("meals", []):
+ for ing in meal.get("ingredients", []):
+ name = ing.get("name")
+ if not name:
+ continue
+ unit = ing.get("unit") or unit_for_item(inventory, name) or "pcs"
+ qty = float(ing.get("quantity", 0.0))
+ key = (name, unit)
+ required[key] = required.get(key, 0.0) + qty
+
+ shopping: List[Dict[str, Any]] = []
+ for (name, unit), qty in required.items():
+ available = available_quantity(inventory, name, unit)
+ shortfall = max(0.0, qty - available)
+ if shortfall > 0:
+ shopping.append(
+ {
+ "name": name,
+ "quantity": shortfall,
+ "unit": unit,
+ "required_quantity": qty,
+ "available_quantity": available,
+ "shortfall_quantity": shortfall,
+ }
+ )
+
+ save_list(data_dir, shopping)
+ return shopping
+
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__init__.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..de3b0d82a7e7571caf07f9b62ceb9e246a2ab257
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__init__.py
@@ -0,0 +1,4 @@
+"""Tools library for Reachy Mini conversation app.
+
+Tools are now loaded dynamically based on the profile's tools.txt file.
+"""
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..01aa9afe28654220a11ff272c285de3bcfc32fbb
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/camera.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/camera.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e08b00bc3c039550c8204179f57f91f7a33acc81
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/camera.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/core_tools.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/core_tools.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bb744bda5570b3eb5c93d2cd26c8a9610e0308b1
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/core_tools.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/dance.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/dance.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..75a61c076874df12633d2050197b5cde427420fe
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/dance.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/do_nothing.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/do_nothing.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4f383c42af02cb150cbbed7742755394d6977a95
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/do_nothing.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/head_tracking.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/head_tracking.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e5d4830e37c99ad02bfe02b0a040a32d93e3b43d
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/head_tracking.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/move_head.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/move_head.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..36f5402da3f4d580fba4d058fb1448a3fca67000
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/move_head.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/play_emotion.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/play_emotion.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8a99e9a19fce9888385d0a845a3dc0a0c18a0b5c
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/play_emotion.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/stop_dance.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/stop_dance.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f2deab828c591ac25a26be3eae1d84e24da22c96
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/stop_dance.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/stop_emotion.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/stop_emotion.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5b38cdfee44de101edb9ede89a5e40603455d1b1
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/__pycache__/stop_emotion.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/camera.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/camera.py
new file mode 100644
index 0000000000000000000000000000000000000000..f72d68be1f1f2728a3c032c8a041314bfcd24df1
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/camera.py
@@ -0,0 +1,186 @@
+import asyncio
+import base64
+import logging
+from typing import Any, Dict
+
+import httpx
+
+from Reachy_OpenWebUI.config import config
+from Reachy_OpenWebUI.camera_frame_encoding import encode_bgr_frame_as_jpeg
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+
+
+logger = logging.getLogger(__name__)
+
+
+def _dedupe_urls(urls: list[str]) -> list[str]:
+ seen: set[str] = set()
+ clean: list[str] = []
+ for url in urls:
+ normalized = url.strip().rstrip("/")
+ if normalized and normalized not in seen:
+ seen.add(normalized)
+ clean.append(normalized)
+ return clean
+
+
+def _openwebui_chat_candidates(root_url: str) -> list[str]:
+ root = (root_url or "").strip().rstrip("/")
+ if not root:
+ return []
+ if root.endswith("/api"):
+ return _dedupe_urls([f"{root}/chat/completions"])
+ return _dedupe_urls([f"{root}/api/chat/completions", f"{root}/v1/chat/completions"])
+
+
+def _openwebui_headers() -> dict[str, str]:
+ headers = {
+ "Accept": "application/json",
+ "Content-Type": "application/json",
+ "User-Agent": config.OPENWEBUI_USER_AGENT,
+ }
+ auth_token = (config.OPENWEBUI_TOKEN or config.OPENWEBUI_API_KEY or "").strip()
+ if auth_token and auth_token != "ollama":
+ headers["Authorization"] = f"Bearer {auth_token}"
+ return headers
+
+
+def _assistant_content(payload: Any) -> str:
+ choices = payload.get("choices") if isinstance(payload, dict) else None
+ choice = choices[0] if isinstance(choices, list) and choices else {}
+ message = choice.get("message") if isinstance(choice, dict) else {}
+ if not isinstance(message, dict):
+ return ""
+ content = message.get("content")
+ if isinstance(content, str):
+ return content.strip()
+ if isinstance(content, list):
+ parts: list[str] = []
+ for item in content:
+ if isinstance(item, str):
+ parts.append(item)
+ elif isinstance(item, dict):
+ text = item.get("text") or item.get("content")
+ if isinstance(text, str):
+ parts.append(text)
+ return "\n".join(part.strip() for part in parts if part.strip()).strip()
+ return ""
+
+
+class Camera(Tool):
+ """Take a picture with the camera and ask a question about it."""
+
+ name = "camera"
+ description = "Take a picture of what the robot sees and describe it or answer a question about it. Use this when the user asks 'what do you see?', 'describe the scene', or asks a specific visual question."
+ parameters_schema = {
+ "type": "object",
+ "properties": {
+ "question": {
+ "type": "string",
+ "description": "Optional question to ask about the picture. Defaults to 'Describe what you see in detail.' if omitted.",
+ },
+ },
+ "required": [],
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ """Take a picture with the camera and ask a question about it."""
+ image_query = (kwargs.get("question") or "Describe what you see in detail.").strip()
+
+ logger.info("Tool call: camera question=%s", image_query[:120])
+
+ # Get frame from camera worker buffer (like main_works.py)
+ if deps.camera_worker is not None:
+ frame = deps.camera_worker.get_latest_frame()
+ if frame is None:
+ logger.error("No frame available from camera worker")
+ return {"error": "No frame available"}
+ else:
+ logger.error("Camera worker not available")
+ return {"error": "Camera worker not available"}
+
+ # Use vision manager for processing if available
+ if deps.vision_manager is not None:
+ vision_result = await asyncio.to_thread(
+ deps.vision_manager.processor.process_image,
+ frame,
+ image_query,
+ )
+ if isinstance(vision_result, dict) and "error" in vision_result:
+ return vision_result
+ return (
+ {"image_description": vision_result}
+ if isinstance(vision_result, str)
+ else {"error": "vision returned non-string"}
+ )
+
+ return await self._describe_with_openwebui(frame, image_query)
+
+ async def _describe_with_openwebui(self, frame: Any, question: str) -> Dict[str, Any]:
+ """Send the latest camera frame to OpenWebUI as a vision chat message."""
+ model = (config.OPENWEBUI_MODEL or "").strip()
+ if not model:
+ return {"error": "OpenWebUI model is not configured for camera vision"}
+
+ try:
+ jpeg_bytes = await asyncio.to_thread(encode_bgr_frame_as_jpeg, frame)
+ except Exception as exc:
+ logger.exception("Failed to encode camera frame")
+ return {"error": f"Failed to encode camera frame: {exc}"}
+
+ image_url = "data:image/jpeg;base64," + base64.b64encode(jpeg_bytes).decode("ascii")
+ payload: dict[str, object] = {
+ "stream": False,
+ "model": model,
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": (
+ "You are looking through Reachy's camera. "
+ "Answer the user's visual question directly and briefly.\n\n"
+ f"Question: {question}"
+ ),
+ },
+ {"type": "image_url", "image_url": {"url": image_url}},
+ ],
+ }
+ ],
+ "features": {
+ "image_generation": False,
+ "code_interpreter": False,
+ "web_search": False,
+ },
+ "max_tokens": 300,
+ }
+
+ last_error = ""
+ timeout = httpx.Timeout(connect=10.0, read=60.0, write=20.0, pool=10.0)
+ async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client:
+ for url in _openwebui_chat_candidates(config.OPENWEBUI_URL):
+ try:
+ response = await client.post(url, headers=_openwebui_headers(), json=payload)
+ except Exception as exc:
+ last_error = f"{type(exc).__name__}: {exc}"
+ logger.warning("OpenWebUI camera vision request failed at %s: %s", url, exc)
+ continue
+
+ if response.status_code in {404, 405}:
+ last_error = f"HTTP {response.status_code}"
+ logger.info("OpenWebUI camera vision endpoint unavailable (%s): %s", response.status_code, url)
+ continue
+ if response.status_code >= 400:
+ last_error = f"HTTP {response.status_code}: {response.text[:500]}"
+ logger.warning("OpenWebUI camera vision HTTP error at %s: %s", url, last_error)
+ continue
+
+ content = _assistant_content(response.json())
+ if content:
+ logger.info("OpenWebUI camera vision response: %s", content[:200])
+ return {"image_description": content}
+ last_error = "OpenWebUI vision response was empty"
+
+ return {"error": f"OpenWebUI camera vision failed: {last_error or 'no endpoint available'}"}
+
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/core_tools.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/core_tools.py
new file mode 100644
index 0000000000000000000000000000000000000000..598335fa1e95acee7766b0fbe177675d1818510d
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/core_tools.py
@@ -0,0 +1,261 @@
+from __future__ import annotations
+import abc
+import sys
+import json
+import copy
+import inspect
+import logging
+import importlib
+from typing import TYPE_CHECKING, Any, Dict, List
+from pathlib import Path
+from dataclasses import dataclass
+
+from Reachy_OpenWebUI.sub_apps.attitudes import apply_attitude_to_tool_specs
+from Reachy_OpenWebUI.config import config, active_profile # noqa: F401 — ensures .env is loaded
+
+if TYPE_CHECKING:
+ from reachy_mini import ReachyMini
+
+
+logger = logging.getLogger(__name__)
+
+
+PROFILES_DIRECTORY = "Reachy_OpenWebUI.profiles"
+
+if not logger.handlers:
+ handler = logging.StreamHandler()
+ formatter = logging.Formatter("%(asctime)s %(levelname)s %(name)s:%(lineno)d | %(message)s")
+ handler.setFormatter(formatter)
+ logger.addHandler(handler)
+ logger.setLevel(logging.INFO)
+
+
+ALL_TOOLS: Dict[str, "Tool"] = {}
+ALL_TOOL_SPECS: List[Dict[str, Any]] = []
+_TOOLS_INITIALIZED = False
+_ACTIVE_PROFILE = ""
+
+
+def get_concrete_subclasses(base: type[Tool]) -> List[type[Tool]]:
+ """Recursively find all concrete (non-abstract) subclasses of a base class."""
+ result: List[type[Tool]] = []
+ for cls in base.__subclasses__():
+ if not inspect.isabstract(cls):
+ result.append(cls)
+ # recurse into subclasses
+ result.extend(get_concrete_subclasses(cls))
+ return result
+
+
+@dataclass
+class ToolDependencies:
+ """External dependencies injected into tools."""
+
+ reachy_mini: ReachyMini
+ movement_manager: Any # MovementManager from moves.py
+ # Optional deps
+ camera_worker: Any | None = None # CameraWorker for frame buffering
+ vision_manager: Any | None = None
+ head_wobbler: Any | None = None # HeadWobbler for audio-reactive motion
+ data_dir: Path | None = None
+ handler: Any | None = None
+ motion_duration_s: float = 1.0
+ speak_func: Any | None = None # Async function(text: str) -> None
+
+
+# Tool base class
+class Tool(abc.ABC):
+ """Base abstraction for tools used in function-calling.
+
+ Each tool must define:
+ - name: str
+ - description: str
+ - parameters_schema: Dict[str, Any] # JSON Schema
+ """
+
+ name: str
+ description: str
+ parameters_schema: Dict[str, Any]
+
+ def spec(self) -> Dict[str, Any]:
+ """Return the function spec for OpenWebUI tool calling."""
+ return {
+ "type": "function",
+ "function": {
+ "name": self.name,
+ "description": self.description,
+ "parameters": self.parameters_schema,
+ },
+ }
+
+ @abc.abstractmethod
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ """Async tool execution entrypoint."""
+ raise NotImplementedError
+
+
+# Registry & specs (dynamic)
+def _load_profile_tools(profile: str) -> list[str]:
+ """Load the bot-side Reachy tools list."""
+ logger.info("Loading Reachy tools for profile: %s", profile)
+ profile_module_path = Path(__file__).parent.parent / "profiles" / profile
+ tools_txt_path = profile_module_path / "tools.txt"
+
+ if not tools_txt_path.exists():
+ logger.error(f"✗ tools.txt not found at {tools_txt_path}")
+ sys.exit(1)
+
+ # Read and parse tools.txt
+ try:
+ with open(tools_txt_path, "r") as f:
+ lines = f.readlines()
+ except Exception as e:
+ logger.error(f"✗ Failed to read tools.txt: {e}")
+ sys.exit(1)
+
+ # Parse tool names (skip comments and blank lines)
+ tool_names = []
+ for line in lines:
+ line = line.strip()
+ # Skip blank lines and comments
+ if not line or line.startswith("#"):
+ continue
+ tool_names.append(line)
+
+ logger.info(f"Found {len(tool_names)} tools to load for profile '{profile}': {tool_names}")
+
+ # Import each tool
+ for tool_name in tool_names:
+ loaded = False
+ profile_error = None
+
+ # Try profile-local tool first
+ try:
+ profile_tool_module = f"{PROFILES_DIRECTORY}.{profile}.{tool_name}"
+ importlib.import_module(profile_tool_module)
+ logger.info(f"✓ Loaded profile-local tool: {tool_name}")
+ loaded = True
+ except ModuleNotFoundError as e:
+ # Check if it's the tool module itself that's missing (expected) or a dependency
+ if tool_name in str(e):
+ pass # Tool not in profile directory, try shared tools
+ else:
+ # Missing import dependency within the tool file
+ profile_error = f"Missing dependency: {e}"
+ logger.error(f"❌ Failed to load profile-local tool '{tool_name}': {profile_error}")
+ logger.error(f" Module path: {profile_tool_module}")
+ except ImportError as e:
+ profile_error = f"Import error: {e}"
+ logger.error(f"❌ Failed to load profile-local tool '{tool_name}': {profile_error}")
+ logger.error(f" Module path: {profile_tool_module}")
+ except Exception as e:
+ profile_error = f"{type(e).__name__}: {e}"
+ logger.error(f"❌ Failed to load profile-local tool '{tool_name}': {profile_error}")
+ logger.error(f" Module path: {profile_tool_module}")
+
+ # Try shared tools library if not found in profile
+ if not loaded:
+ try:
+ shared_tool_module = f"Reachy_OpenWebUI.tools.{tool_name}"
+ importlib.import_module(shared_tool_module)
+ logger.info(f"✓ Loaded shared tool: {tool_name}")
+ loaded = True
+ except ModuleNotFoundError:
+ if profile_error:
+ # Already logged error from profile attempt
+ logger.error(f"❌ Tool '{tool_name}' also not found in shared tools")
+ else:
+ logger.warning(f"⚠️ Tool '{tool_name}' not found in profile or shared tools")
+ except ImportError as e:
+ logger.error(f"❌ Failed to load shared tool '{tool_name}': Import error: {e}")
+ logger.error(f" Module path: {shared_tool_module}")
+ except Exception as e:
+ logger.error(f"❌ Failed to load shared tool '{tool_name}': {type(e).__name__}: {e}")
+ logger.error(f" Module path: {shared_tool_module}")
+
+ return tool_names
+
+
+def _initialize_tools() -> None:
+ """Populate registry for the active profile at app startup."""
+ global ALL_TOOLS, ALL_TOOL_SPECS, _TOOLS_INITIALIZED, _ACTIVE_PROFILE
+
+ selected_profile = active_profile()
+ if _TOOLS_INITIALIZED and _ACTIVE_PROFILE == selected_profile:
+ logger.debug("Tools already initialized; skipping reinitialization.")
+ return
+
+ tool_names = _load_profile_tools(selected_profile)
+ tool_name_set = set(tool_names)
+
+ loaded_tools = {
+ cls.name: cls()
+ for cls in get_concrete_subclasses(Tool)
+ if cls.name in tool_name_set
+ } # type: ignore[type-abstract]
+ ALL_TOOLS = {name: loaded_tools[name] for name in tool_names if name in loaded_tools}
+ ALL_TOOL_SPECS = [tool.spec() for tool in ALL_TOOLS.values()]
+ _ACTIVE_PROFILE = selected_profile
+
+ for tool_name, tool in ALL_TOOLS.items():
+ logger.info(f"tool registered for {selected_profile}: {tool_name} - {tool.description}")
+
+ _TOOLS_INITIALIZED = True
+
+
+_initialize_tools()
+
+
+def get_tool_specs(
+ exclusion_list: list[str] | None = None,
+ attitude: str | None = None,
+) -> list[Dict[str, Any]]:
+ """Get tool specs, optionally excluding tools and narrowing moves by attitude."""
+ _initialize_tools()
+ exclusions = set(exclusion_list or [])
+ specs = [copy.deepcopy(spec) for spec in ALL_TOOL_SPECS if spec["function"]["name"] not in exclusions]
+ if attitude is not None:
+ specs = apply_attitude_to_tool_specs(specs, attitude)
+ return specs
+
+
+# Dispatcher
+def _safe_load_obj(args_json: Any) -> Dict[str, Any]:
+ if isinstance(args_json, dict):
+ return args_json
+ if args_json is None:
+ return {}
+ if not isinstance(args_json, str):
+ logger.warning("bad args_json type=%s value=%r", type(args_json).__name__, args_json)
+ return {}
+
+ raw = args_json.strip()
+ if not raw:
+ return {}
+
+ try:
+ parsed_args: Any = json.loads(raw)
+ if isinstance(parsed_args, str):
+ parsed_args = json.loads(parsed_args)
+ return parsed_args if isinstance(parsed_args, dict) else {}
+ except Exception:
+ logger.warning("bad args_json=%r", args_json)
+ return {}
+
+
+async def dispatch_tool_call(tool_name: str, args_json: Any, deps: ToolDependencies) -> Dict[str, Any]:
+ """Dispatch a tool call by name with JSON args and dependencies."""
+ _initialize_tools()
+ tool = ALL_TOOLS.get(tool_name)
+
+ if not tool:
+ return {"error": f"unknown tool: {tool_name}"}
+
+ args = _safe_load_obj(args_json)
+ try:
+ return await tool(deps, **args)
+ except Exception as e:
+ msg = f"{type(e).__name__}: {e}"
+ logger.exception("Tool error in %s: %s", tool_name, msg)
+ return {"error": msg}
+
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/dance.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/dance.py
new file mode 100644
index 0000000000000000000000000000000000000000..e67958b9c66940be18699328158026283f2b6a64
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/dance.py
@@ -0,0 +1,103 @@
+import logging
+from typing import Any, Dict
+
+from Reachy_OpenWebUI.sub_apps.attitudes import allowed_dances_for_attitude, resolve_attitude
+from Reachy_OpenWebUI.config import config
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+
+
+logger = logging.getLogger(__name__)
+COOKAIWARE_PROFILE = "cookaiware"
+
+# Initialize dance library
+try:
+ from reachy_mini_dances_library.collection.dance import AVAILABLE_MOVES
+ from Reachy_OpenWebUI.dance_emotion_moves import DanceQueueMove
+
+ DANCE_AVAILABLE = True
+except ImportError as e:
+ logger.warning(f"Dance library not available: {e}")
+ AVAILABLE_MOVES = {}
+ DANCE_AVAILABLE = False
+
+
+def get_available_dances_and_descriptions() -> str:
+ """Get formatted list of available dance moves with descriptions."""
+ if not DANCE_AVAILABLE or not AVAILABLE_MOVES:
+ return "Dance moves not available."
+ output = ""
+ for move_name, (func, params, metadata) in AVAILABLE_MOVES.items():
+ description = metadata.get("description", "No description available.")
+ output += f" - {move_name}: {description}\n"
+ return output
+
+
+def _attitude_allowed_dances() -> list[str]:
+ if not DANCE_AVAILABLE:
+ return []
+ if (config.REACHY_MINI_CUSTOM_PROFILE or "") == COOKAIWARE_PROFILE:
+ return list(AVAILABLE_MOVES.keys())
+ return allowed_dances_for_attitude(config.REACHY_IDLE_ATTITUDE, AVAILABLE_MOVES.keys())
+
+
+class Dance(Tool):
+ """Play a named or random dance move once (or repeat). Non-blocking."""
+
+ name = "dance"
+ description = "Play a named or random dance move once (or repeat). Non-blocking."
+ parameters_schema = {
+ "type": "object",
+ "properties": {
+ "move": {
+ "type": "string",
+ "enum": list(AVAILABLE_MOVES.keys()) if DANCE_AVAILABLE else [],
+ "description": f"""Name of the move; omit for random. You MUST only choose from these:
+ {get_available_dances_and_descriptions()}
+ """,
+ },
+ "repeat": {
+ "type": "integer",
+ "description": "How many times to repeat the move (default 1).",
+ },
+ },
+ "required": [],
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ """Play a named or random dance move once (or repeat). Non-blocking."""
+ if not DANCE_AVAILABLE:
+ return {"error": "Dance system not available"}
+
+ move_name = kwargs.get("move")
+ repeat = int(kwargs.get("repeat", 1))
+
+ logger.info("Tool call: dance move=%s repeat=%d", move_name, repeat)
+
+ if not move_name or move_name == "random":
+ import random
+
+ allowed_moves = _attitude_allowed_dances()
+ if not allowed_moves:
+ attitude = resolve_attitude(config.REACHY_IDLE_ATTITUDE)
+ return {"error": f"No dance moves are allowed for the current {attitude.label} attitude."}
+ move_name = random.choice(allowed_moves)
+
+ if move_name not in AVAILABLE_MOVES:
+ return {"error": f"Unknown dance move '{move_name}'. Available: {list(AVAILABLE_MOVES.keys())}"}
+ allowed_moves = _attitude_allowed_dances()
+ if move_name not in allowed_moves:
+ attitude = resolve_attitude(config.REACHY_IDLE_ATTITUDE)
+ return {
+ "error": (
+ f"Dance move '{move_name}' is not allowed for the current "
+ f"{attitude.label} attitude. Available: {allowed_moves}"
+ )
+ }
+
+ # Add dance moves to queue
+ movement_manager = deps.movement_manager
+ for _ in range(repeat):
+ dance_move = DanceQueueMove(move_name)
+ movement_manager.queue_move(dance_move)
+
+ return {"status": "queued", "move": move_name, "repeat": repeat}
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/head_tracking.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/head_tracking.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0bd33632e8ceb1963194092d4b16d8cdc0b1b55
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/head_tracking.py
@@ -0,0 +1,32 @@
+import logging
+from typing import Any, Dict
+
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+
+
+logger = logging.getLogger(__name__)
+
+
+class HeadTracking(Tool):
+ """Toggle head tracking state."""
+
+ name = "head_tracking"
+ description = "Toggle head tracking state."
+ parameters_schema = {
+ "type": "object",
+ "properties": {"start": {"type": "boolean"}},
+ "required": ["start"],
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ """Enable or disable head tracking."""
+ enable = bool(kwargs.get("start"))
+
+ # Update camera worker head tracking state
+ if deps.camera_worker is not None:
+ deps.camera_worker.set_head_tracking_enabled(enable)
+
+ status = "started" if enable else "stopped"
+ logger.info("Tool call: head_tracking %s", status)
+ return {"status": f"head tracking {status}"}
+
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/move_head.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/move_head.py
new file mode 100644
index 0000000000000000000000000000000000000000..641be32d2d54202a6f1d92730ceead22af987017
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/move_head.py
@@ -0,0 +1,80 @@
+import logging
+from typing import Any, Dict, Tuple, Literal
+
+from reachy_mini.utils import create_head_pose
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+from Reachy_OpenWebUI.dance_emotion_moves import GotoQueueMove
+
+
+logger = logging.getLogger(__name__)
+
+Direction = Literal["left", "right", "up", "down", "front"]
+
+
+class MoveHead(Tool):
+ """Move head in a given direction."""
+
+ name = "move_head"
+ description = "Move your head in a given direction: left, right, up, down or front."
+ parameters_schema = {
+ "type": "object",
+ "properties": {
+ "direction": {
+ "type": "string",
+ "enum": ["left", "right", "up", "down", "front"],
+ },
+ },
+ "required": ["direction"],
+ }
+
+ # mapping: direction -> args for create_head_pose
+ DELTAS: Dict[str, Tuple[int, int, int, int, int, int]] = {
+ "left": (0, 0, 0, 0, 0, 40),
+ "right": (0, 0, 0, 0, 0, -40),
+ "up": (0, 0, 0, 0, -30, 0),
+ "down": (0, 0, 0, 0, 30, 0),
+ "front": (0, 0, 0, 0, 0, 0),
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ """Move head in a given direction."""
+ direction_raw = kwargs.get("direction")
+ if not isinstance(direction_raw, str):
+ return {"error": "direction must be a string"}
+ direction: Direction = direction_raw # type: ignore[assignment]
+ logger.info("Tool call: move_head direction=%s", direction)
+
+ deltas = self.DELTAS.get(direction, self.DELTAS["front"])
+ target = create_head_pose(*deltas, degrees=True)
+
+ # Use new movement manager
+ try:
+ movement_manager = deps.movement_manager
+
+ # Get current state for interpolation
+ current_head_pose = deps.reachy_mini.get_current_head_pose()
+ _, current_antennas = deps.reachy_mini.get_current_joint_positions()
+
+ # Create goto move
+ goto_move = GotoQueueMove(
+ target_head_pose=target,
+ start_head_pose=current_head_pose,
+ target_antennas=(0, 0), # Reset antennas to default
+ start_antennas=(
+ current_antennas[0],
+ current_antennas[1],
+ ), # Skip body_yaw
+ target_body_yaw=0, # Reset body yaw
+ start_body_yaw=current_antennas[0], # body_yaw is first in joint positions
+ duration=deps.motion_duration_s,
+ )
+
+ movement_manager.queue_move(goto_move)
+ movement_manager.set_moving_state(deps.motion_duration_s)
+
+ return {"status": f"looking {direction}"}
+
+ except Exception as e:
+ logger.error("move_head failed")
+ return {"error": f"move_head failed: {type(e).__name__}: {e}"}
+
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/play_emotion.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/play_emotion.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ff188523883c718d8fe90bc7b9de5dbb3911432
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/play_emotion.py
@@ -0,0 +1,126 @@
+import logging
+import random
+from typing import Any, Dict
+
+from Reachy_OpenWebUI.sub_apps.attitudes import allowed_emotions_for_attitude, resolve_attitude
+from Reachy_OpenWebUI.config import config
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+
+
+logger = logging.getLogger(__name__)
+COOKAIWARE_PROFILE = "cookaiware"
+
+# Initialize emotion library
+try:
+ from reachy_mini.motion.recorded_move import RecordedMoves
+ from Reachy_OpenWebUI.dance_emotion_moves import EmotionQueueMove
+
+ # Note: huggingface_hub automatically reads HF_TOKEN from environment variables
+ RECORDED_MOVES = RecordedMoves("pollen-robotics/reachy-mini-emotions-library")
+ EMOTION_AVAILABLE = True
+except ImportError as e:
+ logger.warning(f"Emotion library not available: {e}")
+ RECORDED_MOVES = None
+ EMOTION_AVAILABLE = False
+
+
+def get_available_emotions_and_descriptions() -> str:
+ """Get formatted list of available emotions with descriptions."""
+ if not EMOTION_AVAILABLE:
+ return "Emotions not available"
+
+ try:
+ emotion_names = RECORDED_MOVES.list_moves()
+ output = "Available emotions:\n"
+ for name in emotion_names:
+ description = RECORDED_MOVES.get(name).description
+ output += f" - {name}: {description}\n"
+ return output
+ except Exception as e:
+ return f"Error getting emotions: {e}"
+
+
+def _normalize_emotion_name(name: Any) -> str:
+ return str(name or "").strip().lower()
+
+
+def _canonical_emotion_name(name: Any, available: list[str]) -> str:
+ normalized = _normalize_emotion_name(name)
+ for emotion_name in available:
+ if _normalize_emotion_name(emotion_name) == normalized:
+ return emotion_name
+ return str(name or "").strip()
+
+
+def _attitude_allowed_emotions() -> list[str]:
+ if not EMOTION_AVAILABLE:
+ return []
+ if (config.REACHY_MINI_CUSTOM_PROFILE or "") == COOKAIWARE_PROFILE:
+ return RECORDED_MOVES.list_moves()
+ return allowed_emotions_for_attitude(config.REACHY_IDLE_ATTITUDE, RECORDED_MOVES.list_moves())
+
+
+class PlayEmotion(Tool):
+ """Play a pre-recorded emotion."""
+
+ name = "play_emotion"
+ description = (
+ "Queue a visible pre-recorded emotion gesture for Reachy. "
+ "Use this when the reply should include a one-shot emotional reaction."
+ )
+ parameters_schema = {
+ "type": "object",
+ "properties": {
+ "emotion": {
+ "type": "string",
+ "enum": list(RECORDED_MOVES.list_moves()) if EMOTION_AVAILABLE else [],
+ "description": f"""Name of the emotion to play; omit for a random allowed emotion.
+ Here is a list of the available emotions, you MUST only choose from these:
+ {get_available_emotions_and_descriptions()}
+ """,
+ },
+ },
+ "required": [],
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ """Play a pre-recorded emotion."""
+ if not EMOTION_AVAILABLE:
+ return {"error": "Emotion system not available"}
+
+ emotion_name = str(kwargs.get("emotion") or "").strip()
+ logger.info("Tool call: play_emotion emotion=%s", emotion_name)
+
+ # Check if emotion exists
+ try:
+ emotion_names = RECORDED_MOVES.list_moves()
+ if not emotion_names:
+ return {"error": "No emotions currently available"}
+ allowed_emotions = _attitude_allowed_emotions()
+ if not allowed_emotions:
+ attitude = resolve_attitude(config.REACHY_IDLE_ATTITUDE)
+ return {"error": f"No emotions are allowed for the current {attitude.label} attitude."}
+ if not emotion_name:
+ emotion_name = random.choice(allowed_emotions)
+ emotion_name = _canonical_emotion_name(emotion_name, emotion_names)
+ if emotion_name not in emotion_names:
+ return {"error": f"Unknown emotion '{emotion_name}'. Available: {emotion_names}"}
+ if emotion_name not in allowed_emotions:
+ attitude = resolve_attitude(config.REACHY_IDLE_ATTITUDE)
+ return {
+ "error": (
+ f"Emotion '{emotion_name}' is not allowed for the current "
+ f"{attitude.label} attitude. Available: {allowed_emotions}"
+ )
+ }
+
+ # Add emotion to queue
+ movement_manager = deps.movement_manager
+ emotion_move = EmotionQueueMove(emotion_name, RECORDED_MOVES)
+ movement_manager.queue_move(emotion_move)
+
+ return {"status": "queued", "emotion": emotion_name}
+
+ except Exception as e:
+ logger.exception("Failed to play emotion")
+ return {"error": f"Failed to play emotion: {e!s}"}
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/stop_dance.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/stop_dance.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c5af4a2abfa646e2b93181d87170d96df12953d
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/stop_dance.py
@@ -0,0 +1,26 @@
+import logging
+from typing import Any, Dict
+
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+
+
+logger = logging.getLogger(__name__)
+
+
+class StopDance(Tool):
+ """Stop the current dance move."""
+
+ name = "stop_dance"
+ description = "Stop the current dance move"
+ parameters_schema = {
+ "type": "object",
+ "properties": {},
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ """Stop the current dance move."""
+ logger.info("Tool call: stop_dance")
+ movement_manager = deps.movement_manager
+ movement_manager.clear_move_queue()
+ return {"status": "stopped dance and cleared queue"}
+
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/stop_emotion.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/stop_emotion.py
new file mode 100644
index 0000000000000000000000000000000000000000..111e4fbd01c027b64b206f3c9bb54fdca02a1ee8
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/tools/stop_emotion.py
@@ -0,0 +1,32 @@
+import logging
+from typing import Any, Dict
+
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+
+
+logger = logging.getLogger(__name__)
+
+
+class StopEmotion(Tool):
+ """Stop the current emotion."""
+
+ name = "stop_emotion"
+ description = "Stop the current emotion"
+ parameters_schema = {
+ "type": "object",
+ "properties": {
+ "dummy": {
+ "type": "boolean",
+ "description": "dummy boolean, set it to true",
+ },
+ },
+ "required": ["dummy"],
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ """Stop the current emotion."""
+ logger.info("Tool call: stop_emotion")
+ movement_manager = deps.movement_manager
+ movement_manager.clear_move_queue()
+ return {"status": "stopped emotion and cleared queue"}
+
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/units.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/units.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a10dc2c559175d2f2092fe2b8196e796be7059a
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/units.py
@@ -0,0 +1,131 @@
+from __future__ import annotations
+
+from typing import Tuple
+
+
+UNIT_ALIASES = {
+ # Metric weight
+ "g": ("g", 1.0),
+ "gram": ("g", 1.0),
+ "grams": ("g", 1.0),
+ "kg": ("g", 1000.0),
+ "kilogram": ("g", 1000.0),
+ "kilograms": ("g", 1000.0),
+ # Metric volume
+ "ml": ("ml", 1.0),
+ "milliliter": ("ml", 1.0),
+ "milliliters": ("ml", 1.0),
+ "l": ("ml", 1000.0),
+ "liter": ("ml", 1000.0),
+ "liters": ("ml", 1000.0),
+ # Count
+ "pcs": ("pcs", 1.0),
+ "pc": ("pcs", 1.0),
+ "piece": ("pcs", 1.0),
+ "pieces": ("pcs", 1.0),
+ "unit": ("pcs", 1.0),
+ "units": ("pcs", 1.0),
+ # US weight
+ "oz": ("g", 28.3495),
+ "ounce": ("g", 28.3495),
+ "ounces": ("g", 28.3495),
+ "lb": ("g", 453.592),
+ "lbs": ("g", 453.592),
+ "pound": ("g", 453.592),
+ "pounds": ("g", 453.592),
+ # US volume
+ "tsp": ("ml", 4.92892),
+ "teaspoon": ("ml", 4.92892),
+ "teaspoons": ("ml", 4.92892),
+ "tbsp": ("ml", 14.7868),
+ "tablespoon": ("ml", 14.7868),
+ "tablespoons": ("ml", 14.7868),
+ "cup": ("ml", 236.588),
+ "cups": ("ml", 236.588),
+ "fl oz": ("ml", 29.5735),
+ "floz": ("ml", 29.5735),
+ "fluid ounce": ("ml", 29.5735),
+ "fluid ounces": ("ml", 29.5735),
+ "qt": ("ml", 946.353),
+ "quart": ("ml", 946.353),
+ "quarts": ("ml", 946.353),
+ "gal": ("ml", 3785.41),
+ "gallon": ("ml", 3785.41),
+ "gallons": ("ml", 3785.41),
+}
+
+_G_PER_OZ = 28.3495
+_OZ_PER_LB = 16.0
+_ML_PER_TSP = 4.92892
+_ML_PER_TBSP = 14.7868
+_ML_PER_CUP = 236.588
+
+
+def _round_frac(value: float, frac: float) -> float:
+ return round(value / frac) * frac
+
+
+def _fmt_us(value: float) -> str:
+ if abs(value - round(value)) < 0.001:
+ return str(int(round(value)))
+ return f"{value:.2f}".rstrip("0")
+
+
+def _format_us(quantity: float, unit: str) -> str:
+ if unit == "g":
+ oz = quantity / _G_PER_OZ
+ if oz < 0.25:
+ return f"{quantity:.1f} g"
+ if oz >= _OZ_PER_LB:
+ return f"{_fmt_us(_round_frac(oz / _OZ_PER_LB, 0.25))} lb"
+ return f"{_fmt_us(_round_frac(oz, 0.25))} oz"
+ if unit == "ml":
+ if quantity < _ML_PER_TSP * 0.25:
+ return f"{quantity:.1f} ml"
+ if quantity < _ML_PER_TBSP:
+ return f"{_fmt_us(_round_frac(quantity / _ML_PER_TSP, 0.25))} tsp"
+ if quantity < _ML_PER_CUP * 0.25:
+ return f"{_fmt_us(_round_frac(quantity / _ML_PER_TBSP, 0.5))} tbsp"
+ return f"{_fmt_us(_round_frac(quantity / _ML_PER_CUP, 0.25))} cup"
+ if unit == "pcs":
+ if abs(quantity - round(quantity)) < 0.001:
+ return f"{int(round(quantity))} pcs"
+ return f"{quantity:.2f} pcs"
+ return f"{quantity:.2f} {unit}"
+
+
+def normalize_unit(unit: str | None) -> Tuple[str, float] | None:
+ if not unit:
+ return None
+ key = unit.strip().lower()
+ return UNIT_ALIASES.get(key)
+
+
+def normalize_quantity(quantity: float | int | str | None, unit: str | None) -> Tuple[float, str] | None:
+ if quantity is None:
+ return None
+ try:
+ qty = float(quantity)
+ except Exception:
+ return None
+ if qty <= 0:
+ return None
+ normalized = normalize_unit(unit)
+ if not normalized:
+ return None
+ base_unit, factor = normalized
+ return qty * factor, base_unit
+
+
+def format_quantity(quantity: float, unit: str, unit_system: str = "metric") -> str:
+ if unit_system == "imperial":
+ return _format_us(quantity, unit)
+ if unit == "g" and quantity >= 1000:
+ return f"{quantity / 1000:.2f} kg"
+ if unit == "ml" and quantity >= 1000:
+ return f"{quantity / 1000:.2f} l"
+ if unit == "pcs":
+ if abs(quantity - round(quantity)) < 0.001:
+ return f"{int(round(quantity))} pcs"
+ return f"{quantity:.2f} {unit}"
+
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/upc_cache.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/upc_cache.py
new file mode 100644
index 0000000000000000000000000000000000000000..e1907902c42735950a36c6de06a2f73cb43213fd
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/upc_cache.py
@@ -0,0 +1,43 @@
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Dict
+
+from Reachy_OpenWebUI.sub_apps.cookAIware.data_store import load_json, save_json
+
+
+UPC_CACHE_FILE = "upc_cache.json"
+
+
+def _cache_path(data_dir: Path) -> Path:
+ return data_dir / UPC_CACHE_FILE
+
+
+def _key(source: str, barcode: str) -> str:
+ return f"{source.strip().lower()}:{barcode.strip()}"
+
+
+def get_cached_upc(data_dir: Path, source: str, barcode: str) -> Dict[str, Any] | None:
+ cache = load_json(_cache_path(data_dir), {})
+ if not isinstance(cache, dict):
+ return None
+ entry = cache.get(_key(source, barcode))
+ return entry if isinstance(entry, dict) else None
+
+
+def save_cached_upc(data_dir: Path, source: str, barcode: str, item: Dict[str, Any]) -> Dict[str, Any]:
+ cache = load_json(_cache_path(data_dir), {})
+ if not isinstance(cache, dict):
+ cache = {}
+ clean_source = source.strip().lower()
+ clean_barcode = barcode.strip()
+ entry = {
+ "barcode": clean_barcode,
+ "source": clean_source,
+ "item": item,
+ "cached_at": datetime.now(timezone.utc).isoformat(),
+ }
+ cache[_key(clean_source, clean_barcode)] = entry
+ save_json(_cache_path(data_dir), cache)
+ return entry
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/upc_camera.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/upc_camera.py
new file mode 100644
index 0000000000000000000000000000000000000000..04a03c7381dca32724a8b4476be9b7372b713b8b
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/upc_camera.py
@@ -0,0 +1,127 @@
+from __future__ import annotations
+
+import re
+import time
+from typing import Any, Callable, Dict
+
+
+def _clean_barcode(value: Any) -> str:
+ return re.sub(r"\D", "", str(value or ""))
+
+
+def _decode_with_zxing(frame: Any) -> str | None:
+ try:
+ import zxingcpp # type: ignore
+ from PIL import Image
+ except Exception:
+ return None
+
+ image = frame
+ try:
+ if getattr(frame, "ndim", 0) == 3 and frame.shape[2] >= 3:
+ image = Image.fromarray(frame[:, :, ::-1])
+ except Exception:
+ image = frame
+
+ try:
+ results = zxingcpp.read_barcodes(image)
+ except Exception:
+ return None
+ for result in results or []:
+ code = _clean_barcode(getattr(result, "text", ""))
+ if code:
+ return code
+ return None
+
+
+def _zxing_available() -> bool:
+ try:
+ import zxingcpp # noqa: F401
+ from PIL import Image # noqa: F401
+ except Exception:
+ return False
+ return True
+
+
+def _decode_with_opencv(frame: Any) -> str | None:
+ try:
+ import cv2 # type: ignore
+ except Exception:
+ return None
+ detector_factory = getattr(getattr(cv2, "barcode", None), "BarcodeDetector", None)
+ if not callable(detector_factory):
+ detector_factory = getattr(cv2, "barcode_BarcodeDetector", None)
+ if not callable(detector_factory):
+ return None
+ detector = detector_factory()
+ try:
+ result = detector.detectAndDecode(frame)
+ except Exception:
+ return None
+ decoded_values: list[Any] = []
+ if isinstance(result, tuple):
+ for part in result:
+ if isinstance(part, (list, tuple)):
+ decoded_values.extend(part)
+ elif isinstance(part, str):
+ decoded_values.append(part)
+ elif isinstance(result, str):
+ decoded_values.append(result)
+ for value in decoded_values:
+ code = _clean_barcode(value)
+ if code:
+ return code
+ return None
+
+
+def _opencv_barcode_available() -> bool:
+ try:
+ import cv2 # type: ignore
+ except Exception:
+ return False
+ return callable(getattr(getattr(cv2, "barcode", None), "BarcodeDetector", None)) or callable(
+ getattr(cv2, "barcode_BarcodeDetector", None)
+ )
+
+
+def scan_upc_from_camera(camera_worker: Any, timeout_s: float = 8.0, on_frame: Callable[[], None] | None = None) -> Dict[str, Any]:
+ if camera_worker is None:
+ return {"ok": False, "error": "camera_unavailable", "message": "Reachy camera is not available."}
+
+ decoder_available = _zxing_available() or _opencv_barcode_available()
+ if not decoder_available:
+ return {
+ "ok": False,
+ "error": "decoder_unavailable",
+ "message": "UPC camera scan needs the barcode decoder installed on the robot.",
+ }
+
+ deadline = time.monotonic() + max(1.0, timeout_s)
+ frame_notified = False
+ while time.monotonic() < deadline:
+ frame = camera_worker.get_latest_frame()
+ if frame is None:
+ time.sleep(0.2)
+ continue
+ if not frame_notified and callable(on_frame):
+ frame_notified = True
+ try:
+ on_frame()
+ except Exception:
+ pass
+
+ code = _decode_with_zxing(frame)
+ if code:
+ return {"ok": True, "barcode": code}
+
+ code = _decode_with_opencv(frame)
+ if code:
+ return {"ok": True, "barcode": code}
+
+ time.sleep(0.25)
+
+ return {
+ "ok": False,
+ "error": "barcode_not_seen",
+ "message": "I could not see a UPC barcode. Hold it closer and try again.",
+ }
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/upc_lookup.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/upc_lookup.py
new file mode 100644
index 0000000000000000000000000000000000000000..9340a778b9f6b7a505af8d68bf81e5a2112dfcef
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/upc_lookup.py
@@ -0,0 +1,161 @@
+from __future__ import annotations
+
+import json
+import re
+import socket
+from pathlib import Path
+from typing import Any, Dict
+from urllib.error import HTTPError, URLError
+from urllib.parse import quote
+from urllib.request import Request, urlopen
+
+from Reachy_OpenWebUI.sub_apps.cookAIware.upc_cache import get_cached_upc, save_cached_upc
+
+
+OPEN_FOOD_FACTS_PRODUCT_URL = "https://world.openfoodfacts.org/api/v2/product/{barcode}"
+DEFAULT_SOURCE = "openfoodfacts"
+SUPPORTED_SOURCES = (DEFAULT_SOURCE,)
+
+
+def _parse_package_quantity(raw_quantity: Any) -> tuple[float, str]:
+ text = str(raw_quantity or "").strip().lower()
+ match = re.search(r"(\d+(?:[.,]\d+)?)\s*(kg|g|l|ml|oz|lb|lbs|fl\s*oz|qt|gal|pcs|pc|count|ct)\b", text)
+ if not match:
+ return 1.0, "pcs"
+ quantity = float(match.group(1).replace(",", "."))
+ unit = match.group(2).replace(" ", "")
+ aliases = {
+ "pc": "pcs",
+ "count": "pcs",
+ "ct": "pcs",
+ "lbs": "lb",
+ "floz": "fl oz",
+ }
+ return quantity, aliases.get(unit, unit)
+
+
+def _product_name(product: Dict[str, Any]) -> str:
+ for key in (
+ "product_name",
+ "product_name_en",
+ "generic_name",
+ "generic_name_en",
+ "abbreviated_product_name",
+ "abbreviated_product_name_en",
+ ):
+ value = str(product.get(key) or "").strip()
+ if value:
+ return value
+ for key, value in product.items():
+ if key.startswith(("product_name_", "generic_name_", "abbreviated_product_name_")):
+ text = str(value or "").strip()
+ if text:
+ return text
+ return ""
+
+
+def lookup_upc(barcode: str, source: str = DEFAULT_SOURCE, data_dir: Path | None = None) -> Dict[str, Any]:
+ code = re.sub(r"\D", "", barcode or "")
+ if not code:
+ return {"found": False, "error": "missing_barcode", "message": "Enter a UPC barcode."}
+ normalized_source = str(source or DEFAULT_SOURCE).strip().lower()
+ if normalized_source not in SUPPORTED_SOURCES:
+ return {
+ "found": False,
+ "barcode": code,
+ "error": "unsupported_source",
+ "message": f"UPC lookup source is not supported: {source}",
+ }
+ if data_dir is not None:
+ cached = get_cached_upc(data_dir, normalized_source, code)
+ if cached and isinstance(cached.get("item"), dict):
+ return {
+ "found": True,
+ "barcode": code,
+ "item": cached["item"],
+ "cached": True,
+ "cached_at": cached.get("cached_at"),
+ }
+
+ fields = ",".join(
+ [
+ "product_name",
+ "product_name_en",
+ "generic_name",
+ "generic_name_en",
+ "abbreviated_product_name",
+ "abbreviated_product_name_en",
+ "quantity",
+ "brands",
+ "categories_tags",
+ ]
+ )
+ url = f"{OPEN_FOOD_FACTS_PRODUCT_URL.format(barcode=quote(code))}?fields={fields}"
+ request = Request(url, headers={"User-Agent": "Reachy_OpenWebUI CookAIware UPC lookup"})
+ try:
+ with urlopen(request, timeout=8) as response:
+ payload = json.loads(response.read().decode("utf-8"))
+ except HTTPError as exc:
+ if exc.code == 404:
+ return {"found": False, "barcode": code, "error": "not_found", "message": "Item not found for that UPC."}
+ return {
+ "found": False,
+ "barcode": code,
+ "error": "server_error",
+ "message": f"UPC lookup server returned HTTP {exc.code}.",
+ }
+ except (TimeoutError, socket.timeout):
+ return {
+ "found": False,
+ "barcode": code,
+ "error": "timeout",
+ "message": "UPC lookup timed out. Check the connection and try again.",
+ }
+ except URLError as exc:
+ return {
+ "found": False,
+ "barcode": code,
+ "error": "connection_failed",
+ "message": f"Could not connect to the UPC lookup server: {exc.reason}",
+ }
+ except json.JSONDecodeError:
+ return {
+ "found": False,
+ "barcode": code,
+ "error": "bad_response",
+ "message": "UPC lookup server returned an unreadable response.",
+ }
+ except Exception as exc:
+ return {"found": False, "barcode": code, "error": "lookup_failed", "message": f"UPC lookup failed: {exc}"}
+
+ if payload.get("status") != 1:
+ return {"found": False, "barcode": code, "error": "not_found", "message": "Item not found for that UPC."}
+
+ product = payload.get("product") or {}
+ name = _product_name(product)
+ if not name:
+ return {
+ "found": False,
+ "barcode": code,
+ "error": "missing_name",
+ "message": "UPC found, but the product name is missing.",
+ "available_fields": sorted(str(key) for key in product.keys()),
+ }
+
+ quantity, unit = _parse_package_quantity(product.get("quantity"))
+ item = {
+ "name": name,
+ "quantity": quantity,
+ "unit": unit,
+ "barcode": code,
+ "brand": product.get("brands") or "",
+ "source": normalized_source,
+ }
+ if data_dir is not None:
+ save_cached_upc(data_dir, normalized_source, code, item)
+ return {
+ "found": True,
+ "barcode": code,
+ "item": item,
+ "cached": False,
+ }
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/utils.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..395738319224dc50143bc63fbb99b84e3948fecb
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/utils.py
@@ -0,0 +1,119 @@
+import logging
+import argparse
+import warnings
+from typing import Any, Tuple, Optional
+
+from reachy_mini import ReachyMini
+from Reachy_OpenWebUI.sub_apps.cookAIware.camera_worker import CameraWorker
+
+
+def parse_args() -> Tuple[argparse.Namespace, list]: # type: ignore
+ """Parse command line arguments."""
+ parser = argparse.ArgumentParser("Reachy Mini Conversation App")
+ parser.add_argument(
+ "--head-tracker",
+ choices=["yolo", "mediapipe", None],
+ default=None,
+ help="Choose head tracker (default: None)",
+ )
+ parser.add_argument("--no-camera", default=False, action="store_true", help="Disable camera usage")
+ parser.add_argument(
+ "--local-vision",
+ default=False,
+ action="store_true",
+ help="Use local vision model instead of gpt-realtime vision",
+ )
+ parser.add_argument("--gradio", default=False, action="store_true", help="Open gradio interface")
+ parser.add_argument("--debug", default=False, action="store_true", help="Enable debug logging")
+ parser.add_argument(
+ "--robot-name",
+ type=str,
+ default=None,
+ help="[Optional] Robot name/prefix for Zenoh topics (must match daemon's --robot-name). Only needed for development with multiple robots.",
+ )
+ return parser.parse_known_args()
+
+
+def handle_vision_stuff(args: argparse.Namespace, current_robot: ReachyMini) -> Tuple[CameraWorker | None, Any, Any]:
+ """Initialize camera, head tracker, camera worker, and vision manager.
+
+ By default, vision is handled by gpt-realtime model when camera tool is used.
+ If --local-vision flag is used, a local vision model will process images periodically.
+ """
+ camera_worker = None
+ head_tracker = None
+ vision_manager = None
+
+ if not args.no_camera:
+ # Initialize head tracker if specified
+ if args.head_tracker is not None:
+ if args.head_tracker == "yolo":
+ from Reachy_OpenWebUI.sub_apps.cookAIware.vision.yolo_head_tracker import HeadTracker
+
+ head_tracker = HeadTracker()
+ elif args.head_tracker == "mediapipe":
+ from reachy_mini_toolbox.vision import HeadTracker # type: ignore[no-redef]
+
+ head_tracker = HeadTracker()
+
+ # Initialize camera worker
+ camera_worker = CameraWorker(current_robot, head_tracker)
+
+ # Initialize vision manager only if local vision is requested
+ if args.local_vision:
+ try:
+ from Reachy_OpenWebUI.sub_apps.cookAIware.vision.processors import initialize_vision_manager
+
+ vision_manager = initialize_vision_manager(camera_worker)
+ except ImportError as e:
+ raise ImportError(
+ "To use --local-vision, please install the extra dependencies: pip install '.[local_vision]'",
+ ) from e
+ else:
+ logging.getLogger(__name__).info(
+ "Using gpt-realtime for vision (default). Use --local-vision for local processing.",
+ )
+
+ return camera_worker, head_tracker, vision_manager
+
+
+def setup_logger(debug: bool) -> logging.Logger:
+ """Setups the logger."""
+ log_level = "DEBUG" if debug else "INFO"
+ logging.basicConfig(
+ level=getattr(logging, log_level, logging.INFO),
+ format="%(asctime)s %(levelname)s %(name)s:%(lineno)d | %(message)s",
+ )
+ logger = logging.getLogger(__name__)
+
+ # Suppress WebRTC warnings
+ warnings.filterwarnings("ignore", message=".*AVCaptureDeviceTypeExternal.*")
+ warnings.filterwarnings("ignore", category=UserWarning, module="aiortc")
+
+ # Tame third-party noise (looser in DEBUG)
+ if log_level == "DEBUG":
+ logging.getLogger("aiortc").setLevel(logging.INFO)
+ logging.getLogger("fastrtc").setLevel(logging.INFO)
+ logging.getLogger("aioice").setLevel(logging.INFO)
+ logging.getLogger("openai").setLevel(logging.INFO)
+ logging.getLogger("websockets").setLevel(logging.INFO)
+ else:
+ logging.getLogger("aiortc").setLevel(logging.ERROR)
+ logging.getLogger("fastrtc").setLevel(logging.ERROR)
+ logging.getLogger("aioice").setLevel(logging.WARNING)
+ return logger
+
+
+def log_connection_troubleshooting(logger: logging.Logger, robot_name: Optional[str]) -> None:
+ """Log troubleshooting steps for connection issues."""
+ logger.error("Troubleshooting steps:")
+ logger.error(" 1. Verify reachy-mini-daemon is running")
+
+ if robot_name is not None:
+ logger.error(f" 2. Daemon must be started with: --robot-name '{robot_name}'")
+ else:
+ logger.error(" 2. If daemon uses --robot-name, add the same flag here: --robot-name ")
+
+ logger.error(" 3. For wireless: check network connectivity")
+ logger.error(" 4. Review daemon logs")
+ logger.error(" 5. Restart the daemon")
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/vision/__init__.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/vision/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..31819a0f2cf763696b1ad2bef53e1cb706ca40bc
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/vision/__init__.py
@@ -0,0 +1 @@
+"""Nothing (for ruff)."""
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/vision/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/vision/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d8028ed6680addd7585db772c1b4753b2c5e16da
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/vision/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/vision/__pycache__/processors.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/vision/__pycache__/processors.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2a9d973e580832f020efb5bef8f7eebb6486db42
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/vision/__pycache__/processors.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/vision/__pycache__/yolo_head_tracker.cpython-311.pyc b/src/Reachy_OpenWebUI/sub_apps/cookAIware/vision/__pycache__/yolo_head_tracker.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d0921ffe53f3e57130aa0eb8628204a1abd39908
Binary files /dev/null and b/src/Reachy_OpenWebUI/sub_apps/cookAIware/vision/__pycache__/yolo_head_tracker.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/vision/processors.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/vision/processors.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1c24644512d1d1759896fb3c5e09fb4fed7c8a0
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/vision/processors.py
@@ -0,0 +1,331 @@
+import os
+import time
+import base64
+import logging
+import threading
+from typing import Any, Dict
+from dataclasses import dataclass
+
+import cv2
+import numpy as np
+import torch
+from numpy.typing import NDArray
+from transformers import AutoProcessor, AutoModelForImageTextToText
+from huggingface_hub import snapshot_download
+
+from Reachy_OpenWebUI.config import config
+
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class VisionConfig:
+ """Configuration for vision processing."""
+
+ model_path: str = config.LOCAL_VISION_MODEL
+ vision_interval: float = 5.0
+ max_new_tokens: int = 64
+ jpeg_quality: int = 85
+ max_retries: int = 3
+ retry_delay: float = 1.0
+ device_preference: str = "auto" # "auto", "cuda", "cpu"
+
+
+class VisionProcessor:
+ """Handles SmolVLM2 model loading and inference."""
+
+ def __init__(self, vision_config: VisionConfig | None = None):
+ """Initialize the vision processor."""
+ self.vision_config = vision_config or VisionConfig()
+ self.model_path = self.vision_config.model_path
+ self.device = self._determine_device()
+ self.processor = None
+ self.model = None
+ self._initialized = False
+
+ def _determine_device(self) -> str:
+ pref = self.vision_config.device_preference
+ if pref == "cpu":
+ return "cpu"
+ if pref == "cuda":
+ return "cuda" if torch.cuda.is_available() else "cpu"
+ if pref == "mps":
+ return "mps" if torch.backends.mps.is_available() else "cpu"
+ # auto: prefer mps on Apple, then cuda, else cpu
+ if torch.backends.mps.is_available():
+ return "mps"
+ return "cuda" if torch.cuda.is_available() else "cpu"
+
+ def initialize(self) -> bool:
+ """Load model and processor onto the selected device."""
+ try:
+ logger.info(f"Loading SmolVLM2 model on {self.device} (HF_HOME={config.HF_HOME})")
+ self.processor = AutoProcessor.from_pretrained(self.model_path) # type: ignore
+
+ # Select dtype depending on device
+ if self.device == "cuda":
+ dtype = torch.bfloat16
+ elif self.device == "mps":
+ dtype = torch.float32 # best for MPS
+ else:
+ dtype = torch.float32
+
+ model_kwargs: Dict[str, Any] = {"dtype": dtype}
+
+ # flash_attention_2 is CUDA-only; skip on MPS/CPU
+ if self.device == "cuda":
+ model_kwargs["_attn_implementation"] = "flash_attention_2"
+
+ # Load model weights
+ self.model = AutoModelForImageTextToText.from_pretrained(self.model_path, **model_kwargs).to(self.device) # type: ignore
+
+ if self.model is not None:
+ self.model.eval()
+ self._initialized = True
+ return True
+
+ except Exception as e:
+ logger.error(f"Failed to initialize vision model: {e}")
+ return False
+
+ def process_image(
+ self,
+ cv2_image: NDArray[np.uint8],
+ prompt: str = "Briefly describe what you see in one sentence.",
+ ) -> str:
+ """Process CV2 image and return description with retry logic."""
+ if not self._initialized or self.processor is None or self.model is None:
+ return "Vision model not initialized"
+
+ for attempt in range(self.vision_config.max_retries):
+ try:
+ # Convert to JPEG bytes
+ success, jpeg_buffer = cv2.imencode(
+ ".jpg",
+ cv2_image,
+ [cv2.IMWRITE_JPEG_QUALITY, self.vision_config.jpeg_quality],
+ )
+ if not success:
+ return "Failed to encode image"
+
+ # Convert to base64
+ image_base64 = base64.b64encode(jpeg_buffer.tobytes()).decode("utf-8")
+
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "image",
+ "url": f"data:image/jpeg;base64,{image_base64}",
+ },
+ {"type": "text", "text": prompt},
+ ],
+ },
+ ]
+
+ inputs = self.processor.apply_chat_template(
+ messages,
+ add_generation_prompt=True,
+ tokenize=True,
+ return_dict=True,
+ return_tensors="pt",
+ )
+
+ # Move tensors to device WITHOUT forcing dtype (keeps input_ids as torch.long)
+ inputs = {k: (v.to(self.device) if hasattr(v, "to") else v) for k, v in inputs.items()}
+
+ with torch.no_grad():
+ generated_ids = self.model.generate(
+ **inputs,
+ do_sample=False,
+ max_new_tokens=self.vision_config.max_new_tokens,
+ pad_token_id=self.processor.tokenizer.eos_token_id,
+ )
+
+ generated_texts = self.processor.batch_decode(
+ generated_ids,
+ skip_special_tokens=True,
+ )
+
+ # Extract just the response part
+ full_text = generated_texts[0]
+ response = self._extract_response(full_text)
+
+ # Clean up GPU memory if using CUDA
+ if self.device == "cuda":
+ torch.cuda.empty_cache()
+ elif self.device == "mps":
+ torch.mps.empty_cache()
+
+ return response.replace(chr(10), " ").strip()
+
+ except torch.cuda.OutOfMemoryError as e:
+ logger.error(f"CUDA OOM on attempt {attempt + 1}: {e}")
+ if self.device == "cuda":
+ torch.cuda.empty_cache()
+ if attempt < self.vision_config.max_retries - 1:
+ time.sleep(self.vision_config.retry_delay * (attempt + 1))
+ else:
+ return "GPU out of memory - vision processing failed"
+
+ except Exception as e:
+ logger.error(f"Vision processing failed (attempt {attempt + 1}): {e}")
+ if attempt < self.vision_config.max_retries - 1:
+ time.sleep(self.vision_config.retry_delay)
+ else:
+ return f"Vision processing error after {self.vision_config.max_retries} attempts"
+
+ def _extract_response(self, full_text: str) -> str:
+ """Extract the assistant's response from the full generated text."""
+ # Handle different response formats
+ markers = ["assistant\n", "Assistant:", "Response:", "\n\n"]
+
+ for marker in markers:
+ if marker in full_text:
+ response = full_text.split(marker)[-1].strip()
+ if response: # Ensure we got a meaningful response
+ return response
+
+ # Fallback: return the full text cleaned up
+ return full_text.strip()
+
+ def get_model_info(self) -> Dict[str, Any]:
+ """Get information about the loaded model."""
+ return {
+ "initialized": self._initialized,
+ "device": self.device,
+ "model_path": self.model_path,
+ "cuda_available": torch.cuda.is_available(),
+ "gpu_memory": torch.cuda.get_device_properties(0).total_memory // (1024**3)
+ if torch.cuda.is_available()
+ else "N/A",
+ }
+
+
+class VisionManager:
+ """Manages periodic vision processing and scene understanding."""
+
+ def __init__(self, camera: Any, vision_config: VisionConfig | None = None):
+ """Initialize vision manager with camera and configuration."""
+ self.camera = camera
+ self.vision_config = vision_config or VisionConfig()
+ self.vision_interval = self.vision_config.vision_interval
+ self.processor = VisionProcessor(self.vision_config)
+
+ self._last_processed_time = 0.0
+ self._stop_event = threading.Event()
+ self._thread: threading.Thread | None = None
+
+ # Initialize processor
+ if not self.processor.initialize():
+ logger.error("Failed to initialize vision processor")
+ raise RuntimeError("Vision processor initialization failed")
+
+ def start(self) -> None:
+ """Start the vision processing loop in a thread."""
+ self._stop_event.clear()
+ self._thread = threading.Thread(target=self._working_loop, daemon=True)
+ self._thread.start()
+ logger.info("Local vision processing started")
+
+ def stop(self) -> None:
+ """Stop the vision processing loop."""
+ self._stop_event.set()
+ if self._thread is not None:
+ self._thread.join()
+ logger.info("Local vision processing stopped")
+
+ def _working_loop(self) -> None:
+ """Vision processing loop (runs in separate thread)."""
+ while not self._stop_event.is_set():
+ try:
+ current_time = time.time()
+
+ if current_time - self._last_processed_time >= self.vision_interval:
+ frame = self.camera.get_latest_frame()
+ if frame is not None:
+ description = self.processor.process_image(
+ frame,
+ "Briefly describe what you see in one sentence.",
+ )
+
+ # Only update if we got a valid response
+ if description and not description.startswith(("Vision", "Failed", "Error")):
+ self._last_processed_time = current_time
+ logger.debug(f"Vision update: {description}")
+ else:
+ logger.warning(f"Invalid vision response: {description}")
+
+ time.sleep(1.0) # Check every second
+
+ except Exception:
+ logger.exception("Vision processing loop error")
+ time.sleep(5.0) # Longer sleep on error
+
+ logger.info("Vision loop finished")
+
+ def get_status(self) -> Dict[str, Any]:
+ """Get comprehensive status information."""
+ return {
+ "last_processed": self._last_processed_time,
+ "processor_info": self.processor.get_model_info(),
+ "config": {
+ "interval": self.vision_interval,
+ },
+ }
+
+
+def initialize_vision_manager(camera_worker: Any) -> VisionManager | None:
+ """Initialize vision manager with model download and configuration.
+
+ Args:
+ camera_worker: CameraWorker instance for frame capture
+ Returns:
+ VisionManager instance or None if initialization fails
+
+ """
+ try:
+ model_id = config.LOCAL_VISION_MODEL
+ cache_dir = os.path.expanduser(config.HF_HOME)
+
+ # Prepare cache directory
+ os.makedirs(cache_dir, exist_ok=True)
+ os.environ["HF_HOME"] = cache_dir
+ logger.info("HF_HOME set to %s", cache_dir)
+
+ # Download model to cache
+ logger.info(f"Downloading vision model {model_id} to cache...")
+ snapshot_download(
+ repo_id=model_id,
+ repo_type="model",
+ cache_dir=cache_dir,
+ )
+ logger.info(f"Model {model_id} downloaded to {cache_dir}")
+
+ # Configure vision processing
+ vision_config = VisionConfig(
+ model_path=model_id,
+ vision_interval=5.0,
+ max_new_tokens=64,
+ jpeg_quality=85,
+ max_retries=3,
+ retry_delay=1.0,
+ device_preference="auto",
+ )
+
+ # Initialize vision manager
+ vision_manager = VisionManager(camera_worker, vision_config)
+
+ # Log device info
+ device_info = vision_manager.processor.get_model_info()
+ logger.info(
+ f"Vision processing enabled: {device_info.get('model_path')} on {device_info.get('device')}",
+ )
+
+ return vision_manager
+
+ except Exception as e:
+ logger.error(f"Failed to initialize vision manager: {e}")
+ return None
diff --git a/src/Reachy_OpenWebUI/sub_apps/cookAIware/vision/yolo_head_tracker.py b/src/Reachy_OpenWebUI/sub_apps/cookAIware/vision/yolo_head_tracker.py
new file mode 100644
index 0000000000000000000000000000000000000000..03054c233f9d9109a87b49481f94e05d1f180f10
--- /dev/null
+++ b/src/Reachy_OpenWebUI/sub_apps/cookAIware/vision/yolo_head_tracker.py
@@ -0,0 +1,148 @@
+from __future__ import annotations
+import logging
+from typing import Tuple
+
+import numpy as np
+from numpy.typing import NDArray
+
+
+try:
+ from supervision import Detections
+ from ultralytics import YOLO # type: ignore
+except ImportError as e:
+ raise ImportError(
+ "To use YOLO head tracker, please install the extra dependencies: pip install '.[yolo_vision]'",
+ ) from e
+from huggingface_hub import hf_hub_download
+
+
+logger = logging.getLogger(__name__)
+
+
+class HeadTracker:
+ """Lightweight head tracker using YOLO for face detection."""
+
+ def __init__(
+ self,
+ model_repo: str = "AdamCodd/YOLOv11n-face-detection",
+ model_filename: str = "model.pt",
+ confidence_threshold: float = 0.3,
+ device: str = "cpu",
+ ) -> None:
+ """Initialize YOLO-based head tracker.
+
+ Args:
+ model_repo: HuggingFace model repository
+ model_filename: Model file name
+ confidence_threshold: Minimum confidence for face detection
+ device: Device to run inference on ('cpu' or 'cuda')
+
+ """
+ self.confidence_threshold = confidence_threshold
+
+ try:
+ # Download and load YOLO model
+ model_path = hf_hub_download(repo_id=model_repo, filename=model_filename)
+ self.model = YOLO(model_path).to(device)
+ logger.info(f"YOLO face detection model loaded from {model_repo}")
+ except Exception as e:
+ logger.error(f"Failed to load YOLO model: {e}")
+ raise
+
+ def _select_best_face(self, detections: Detections) -> int | None:
+ """Select the best face based on confidence and area (largest face with highest confidence).
+
+ Args:
+ detections: Supervision detections object
+
+ Returns:
+ Index of best face or None if no valid faces
+
+ """
+ if detections.xyxy.shape[0] == 0:
+ return None
+
+ # Check if confidence is available
+ if detections.confidence is None:
+ return None
+
+ # Filter by confidence threshold
+ valid_mask = detections.confidence >= self.confidence_threshold
+ if not np.any(valid_mask):
+ return None
+
+ valid_indices = np.where(valid_mask)[0]
+
+ # Calculate areas for valid detections
+ boxes = detections.xyxy[valid_indices]
+ areas = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
+
+ # Combine confidence and area (weighted towards larger faces)
+ confidences = detections.confidence[valid_indices]
+ scores = confidences * 0.7 + (areas / np.max(areas)) * 0.3
+
+ # Return index of best face
+ best_idx = valid_indices[np.argmax(scores)]
+ return int(best_idx)
+
+ def _bbox_to_mp_coords(self, bbox: NDArray[np.float32], w: int, h: int) -> NDArray[np.float32]:
+ """Convert bounding box center to MediaPipe-style coordinates [-1, 1].
+
+ Args:
+ bbox: Bounding box [x1, y1, x2, y2]
+ w: Image width
+ h: Image height
+
+ Returns:
+ Center point in [-1, 1] coordinates
+
+ """
+ center_x = (bbox[0] + bbox[2]) / 2.0
+ center_y = (bbox[1] + bbox[3]) / 2.0
+
+ # Normalize to [0, 1] then to [-1, 1]
+ norm_x = (center_x / w) * 2.0 - 1.0
+ norm_y = (center_y / h) * 2.0 - 1.0
+
+ return np.array([norm_x, norm_y], dtype=np.float32)
+
+ def get_head_position(self, img: NDArray[np.uint8]) -> Tuple[NDArray[np.float32] | None, float | None]:
+ """Get head position from face detection.
+
+ Args:
+ img: Input image
+
+ Returns:
+ Tuple of (eye_center [-1,1], roll_angle)
+
+ """
+ h, w = img.shape[:2]
+
+ try:
+ # Run YOLO inference
+ results = self.model(img, verbose=False)
+ detections = Detections.from_ultralytics(results[0])
+
+ # Select best face
+ face_idx = self._select_best_face(detections)
+ if face_idx is None:
+ logger.debug("No face detected above confidence threshold")
+ return None, None
+
+ bbox = detections.xyxy[face_idx]
+
+ if detections.confidence is not None:
+ confidence = detections.confidence[face_idx]
+ logger.debug(f"Face detected with confidence: {confidence:.2f}")
+
+ # Get face center in [-1, 1] coordinates
+ face_center = self._bbox_to_mp_coords(bbox, w, h)
+
+ # Roll is 0 since we don't have keypoints for precise angle estimation
+ roll = 0.0
+
+ return face_center, roll
+
+ except Exception as e:
+ logger.error(f"Error in head position detection: {e}")
+ return None, None
diff --git a/src/Reachy_OpenWebUI/tools/__init__.py b/src/Reachy_OpenWebUI/tools/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..de3b0d82a7e7571caf07f9b62ceb9e246a2ab257
--- /dev/null
+++ b/src/Reachy_OpenWebUI/tools/__init__.py
@@ -0,0 +1,4 @@
+"""Tools library for Reachy Mini conversation app.
+
+Tools are now loaded dynamically based on the profile's tools.txt file.
+"""
diff --git a/src/Reachy_OpenWebUI/tools/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/tools/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..75c211f3f1a6bb635d9c04173f499f4d911deb7c
Binary files /dev/null and b/src/Reachy_OpenWebUI/tools/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/tools/__pycache__/background_tool_manager.cpython-311.pyc b/src/Reachy_OpenWebUI/tools/__pycache__/background_tool_manager.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..795bc2f57c4d073aa3205d7f8d666ddaec65ce80
Binary files /dev/null and b/src/Reachy_OpenWebUI/tools/__pycache__/background_tool_manager.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/tools/__pycache__/camera.cpython-311.pyc b/src/Reachy_OpenWebUI/tools/__pycache__/camera.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c54ce4ab4acdc587cf45b31b97657e112e04e480
Binary files /dev/null and b/src/Reachy_OpenWebUI/tools/__pycache__/camera.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/tools/__pycache__/core_tools.cpython-311.pyc b/src/Reachy_OpenWebUI/tools/__pycache__/core_tools.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6dfc84c68ceb4d1a21327b1b94a90e4af8bcef4b
Binary files /dev/null and b/src/Reachy_OpenWebUI/tools/__pycache__/core_tools.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/tools/__pycache__/dance.cpython-311.pyc b/src/Reachy_OpenWebUI/tools/__pycache__/dance.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b118db179610b2ce53a91d738c3cfc35d9997340
Binary files /dev/null and b/src/Reachy_OpenWebUI/tools/__pycache__/dance.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/tools/__pycache__/do_nothing.cpython-311.pyc b/src/Reachy_OpenWebUI/tools/__pycache__/do_nothing.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..43a8aa20ffd4bfb521deb338e15ecbf92f04b7e0
Binary files /dev/null and b/src/Reachy_OpenWebUI/tools/__pycache__/do_nothing.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/tools/__pycache__/head_tracking.cpython-311.pyc b/src/Reachy_OpenWebUI/tools/__pycache__/head_tracking.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2ab8f18b3ba26c9831971510ad52efe6f6ec201e
Binary files /dev/null and b/src/Reachy_OpenWebUI/tools/__pycache__/head_tracking.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/tools/__pycache__/idle_do_nothing.cpython-311.pyc b/src/Reachy_OpenWebUI/tools/__pycache__/idle_do_nothing.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a7e116199577be059fe2366687b73447b84e59d9
Binary files /dev/null and b/src/Reachy_OpenWebUI/tools/__pycache__/idle_do_nothing.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/tools/__pycache__/move_head.cpython-311.pyc b/src/Reachy_OpenWebUI/tools/__pycache__/move_head.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8acb24ad18cbcd2e8e51152b3be55df47b217d0f
Binary files /dev/null and b/src/Reachy_OpenWebUI/tools/__pycache__/move_head.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/tools/__pycache__/play_emotion.cpython-311.pyc b/src/Reachy_OpenWebUI/tools/__pycache__/play_emotion.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5ab583932c892418017f0e44dff200bbba17a93a
Binary files /dev/null and b/src/Reachy_OpenWebUI/tools/__pycache__/play_emotion.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/tools/__pycache__/speak.cpython-311.pyc b/src/Reachy_OpenWebUI/tools/__pycache__/speak.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d295a256703bc9bf3652576321356a8c457cd152
Binary files /dev/null and b/src/Reachy_OpenWebUI/tools/__pycache__/speak.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/tools/__pycache__/stop_dance.cpython-311.pyc b/src/Reachy_OpenWebUI/tools/__pycache__/stop_dance.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d1c52abcfb27e2429865552393aa31a767fcafd7
Binary files /dev/null and b/src/Reachy_OpenWebUI/tools/__pycache__/stop_dance.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/tools/__pycache__/stop_emotion.cpython-311.pyc b/src/Reachy_OpenWebUI/tools/__pycache__/stop_emotion.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f032054d36f1fba871a6a6064ace58febcc4413c
Binary files /dev/null and b/src/Reachy_OpenWebUI/tools/__pycache__/stop_emotion.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/tools/__pycache__/sweep_look.cpython-311.pyc b/src/Reachy_OpenWebUI/tools/__pycache__/sweep_look.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7fbb153c76a72ce7e62cf37c80985ce22a047b7d
Binary files /dev/null and b/src/Reachy_OpenWebUI/tools/__pycache__/sweep_look.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/tools/__pycache__/task_cancel.cpython-311.pyc b/src/Reachy_OpenWebUI/tools/__pycache__/task_cancel.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f8c0ae5626f8e75f71d525e08b8ebad56cf8e1f7
Binary files /dev/null and b/src/Reachy_OpenWebUI/tools/__pycache__/task_cancel.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/tools/__pycache__/task_status.cpython-311.pyc b/src/Reachy_OpenWebUI/tools/__pycache__/task_status.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2ccc30669fb3dcb589ac2206e13305fd43b79793
Binary files /dev/null and b/src/Reachy_OpenWebUI/tools/__pycache__/task_status.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/tools/__pycache__/tool_constants.cpython-311.pyc b/src/Reachy_OpenWebUI/tools/__pycache__/tool_constants.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b06141c98f1f1b61259dd491ec7ec8e7f03fe2ed
Binary files /dev/null and b/src/Reachy_OpenWebUI/tools/__pycache__/tool_constants.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/tools/background_tool_manager.py b/src/Reachy_OpenWebUI/tools/background_tool_manager.py
new file mode 100644
index 0000000000000000000000000000000000000000..b12a1bd4d216085cce8db4633e72e6329b979d62
--- /dev/null
+++ b/src/Reachy_OpenWebUI/tools/background_tool_manager.py
@@ -0,0 +1,416 @@
+"""Background tool orchestrator for non-blocking tool execution.
+
+Allows tools to run long operations asynchronously while the robot
+continues conversing. Tools can be tracked, cancelled, and their
+completion is announced vocally via a silent notification queue.
+"""
+
+from __future__ import annotations
+import time
+import asyncio
+import logging
+from typing import Any, Dict, Callable, Optional, Coroutine
+
+from pydantic import Field, BaseModel, PrivateAttr
+
+from Reachy_OpenWebUI.tools.core_tools import (
+ ToolDependencies,
+ dispatch_tool_call,
+ dispatch_tool_call_with_manager,
+)
+from Reachy_OpenWebUI.tools.tool_constants import ToolState, SystemTool
+
+
+logger = logging.getLogger(__name__)
+
+_SYSTEM_TOOL_NAMES: set[str] = {t.value for t in SystemTool}
+
+
+class ToolProgress(BaseModel):
+ """Progress of a background tool."""
+
+ """the progress of the tool"""
+ progress: float = Field(..., ge=0.0, le=1.0)
+
+ """the message of the tool"""
+ message: Optional[str] = None
+
+
+class ToolCallRoutine(BaseModel):
+ """Encapsulates an async callable with its arguments for deferred execution."""
+
+ model_config = {"arbitrary_types_allowed": True}
+
+ """the name of the tool"""
+ tool_name: str
+
+ """the JSON arguments for the tool call"""
+ args_json_str: str
+
+ """the dependencies for the tool call"""
+ deps: "ToolDependencies"
+
+ async def __call__(self, tool_manager: BackgroundToolManager) -> Any:
+ """Execute the stored callable with its arguments."""
+ if self.tool_name in _SYSTEM_TOOL_NAMES:
+ # For safety purposes, we only allow system tools to be called with the tool manager
+ return await dispatch_tool_call_with_manager(
+ tool_name=self.tool_name, args_json=self.args_json_str, deps=self.deps, tool_manager=tool_manager
+ )
+ return await dispatch_tool_call(tool_name=self.tool_name, args_json=self.args_json_str, deps=self.deps)
+
+
+class ToolNotification(BaseModel):
+ """Notification payload for completed tools."""
+
+ """the ID of the tool"""
+ id: str
+
+ """the name of the tool"""
+ tool_name: str
+
+ """whether the tool call was triggered by an idle signal"""
+ is_idle_tool_call: bool
+
+ """the status of the tool"""
+ status: ToolState
+
+ """the result of the tool"""
+ result: Optional[Dict[str, Any]] = None
+
+ """the error of the tool"""
+ error: Optional[str] = None
+
+
+class BackgroundTool(ToolNotification):
+ """Represents a background tool."""
+
+ """the progress of the tool"""
+ progress: Optional[ToolProgress] = None
+
+ """the start time of the tool"""
+ started_at: float = Field(default_factory=time.monotonic)
+
+ """the completion time of the tool"""
+ completed_at: Optional[float] = None
+
+ """the async tool execution task"""
+ _task: Optional[asyncio.Task[None]] = PrivateAttr(default=None)
+
+ @property
+ def tool_id(self) -> str:
+ """Get the name of the tool."""
+ return f"{self.tool_name}-{self.id}-{self.started_at}"
+
+ def get_notification(self) -> ToolNotification:
+ """Get the notification for the tool."""
+ return ToolNotification(
+ id=self.id,
+ tool_name=self.tool_name,
+ is_idle_tool_call=self.is_idle_tool_call,
+ status=self.status,
+ result=self.result,
+ error=self.error,
+ )
+
+
+class BackgroundToolManager(BaseModel):
+ """Manages background tools for non-blocking tool execution.
+
+ Features:
+ - Start async tools without blocking the conversation
+ - Track tool status and progress
+ - Cancel running tools
+
+ """
+
+ """the dictionary of tools"""
+ _tools: Dict[str, BackgroundTool] = PrivateAttr(default_factory=dict)
+
+ """the async queue for notifications"""
+ _notification_queue: asyncio.Queue[ToolNotification] = PrivateAttr(default_factory=asyncio.Queue)
+
+ """the event loop"""
+ _loop: Optional[asyncio.AbstractEventLoop] = PrivateAttr(default=None)
+
+ """internal lifecycle tasks (notification listener, periodic cleanup)"""
+ _lifecycle_tasks: list[asyncio.Task[None]] = PrivateAttr(default_factory=list)
+
+ """the maximum duration of a tool execution in seconds (default: 1 day)"""
+ _max_tool_duration_seconds: float = PrivateAttr(default=86400)
+
+ """the maximum time to keep a completed/failed/cancelled tool in memory (default: 1 hour)"""
+ _max_tool_memory_seconds: float = PrivateAttr(default=3600)
+
+ def set_loop(
+ self,
+ loop: Optional[asyncio.AbstractEventLoop] = None,
+ ) -> None:
+ """Set the event loop.
+
+ Args:
+ loop: The event loop (defaults to current running loop)
+
+ """
+ if loop is not None:
+ self._loop = loop
+ else:
+ try:
+ self._loop = asyncio.get_running_loop()
+ except RuntimeError:
+ self._loop = asyncio.new_event_loop()
+ logger.debug("BackgroundToolManager: event loop set")
+
+ async def start_tool(
+ self,
+ call_id: str,
+ tool_call_routine: ToolCallRoutine,
+ is_idle_tool_call: bool,
+ with_progress: bool = False,
+ ) -> BackgroundTool:
+ """Start a new background tool.
+
+ Args:
+ call_id: The ID of the tool
+ tool_call_routine: The ToolCallRoutine containing the callable and its arguments
+ with_progress: Whether to track progress (0.0-1.0)
+ is_idle_tool_call: Whether the tool call was triggered by an idle signal
+
+ Returns:
+ BackgroundTool object with tool ID
+
+ """
+ tool_name = tool_call_routine.tool_name
+ id = call_id
+ bg_tool = BackgroundTool(
+ id=id,
+ tool_name=tool_name,
+ is_idle_tool_call=is_idle_tool_call,
+ progress=ToolProgress(progress=0.0) if with_progress else None,
+ status=ToolState.RUNNING,
+ )
+ self._tools[bg_tool.tool_id] = bg_tool
+
+ async_task = asyncio.create_task(
+ self._run_tool(bg_tool, tool_call_routine),
+ name=f"bg-{tool_name}-{id}",
+ )
+ bg_tool._task = async_task
+
+ logger.info(f"Started background tool: {bg_tool.tool_name} (id={id})")
+
+ return bg_tool
+
+ async def _run_tool(
+ self,
+ bg_tool: BackgroundTool,
+ tool_call_routine: ToolCallRoutine,
+ ) -> None:
+ """Execute the tool and handle completion."""
+ result: dict[str, Any] = await tool_call_routine(self)
+ bg_tool.completed_at = time.monotonic()
+ error = result.get("error")
+
+ if error is not None:
+ if error == "Tool cancelled":
+ bg_tool.status = ToolState.CANCELLED
+ logger.debug(f"Background tool cancelled: {bg_tool.tool_name} (id={bg_tool.id})")
+ else:
+ bg_tool.status = ToolState.FAILED
+ logger.debug(f"Background tool failed: {bg_tool.tool_name} (id={bg_tool.id}): {bg_tool.error}")
+ bg_tool.error = result["error"]
+
+ else:
+ bg_tool.result = result
+ bg_tool.status = ToolState.COMPLETED
+ logger.debug(f"Background tool completed: {bg_tool.tool_name} (id={bg_tool.id})")
+
+ await self._notification_queue.put(bg_tool.get_notification())
+ logger.debug(f"Queued notification for tool: {bg_tool.tool_name} (id={bg_tool.id})")
+
+ async def update_progress(
+ self,
+ tool_id: str,
+ progress: float,
+ message: Optional[str] = None,
+ ) -> bool:
+ """Update progress for a tool (for tools with with_progress=True).
+
+ Args:
+ tool_id: The tool ID
+ progress: Progress value between 0.0 and 1.0
+ message: Optional progress message (e.g., "50% downloaded")
+
+ Returns:
+ True if updated successfully, False if tool not found or not tracking progress
+
+ """
+ tool = self._tools.get(tool_id)
+ if tool is None:
+ return False
+
+ if tool.progress is None:
+ # Tool not tracking progress
+ return False
+
+ tool.progress = ToolProgress(progress=max(0.0, min(1.0, progress)), message=message)
+ logger.debug(f"Tool {tool_id} progress: {progress:.1%} - {message or ''}")
+ return True
+
+ async def cancel_tool(self, tool_id: str, log: bool = True) -> bool:
+ """Cancel a running tool by ID.
+
+ Args:
+ tool_id: The tool ID to cancel
+ log: Whether to log the cancellation
+
+ Returns:
+ True if cancelled, False if tool not found or not running
+
+ """
+ tool = self._tools.get(tool_id)
+ if tool is None:
+ if log:
+ logger.warning(f"Cannot cancel tool {tool_id}: not found")
+ return False
+
+ if tool.status != ToolState.RUNNING:
+ if log:
+ logger.warning(f"Cannot cancel tool {tool_id}: status is {tool.status.value}")
+ return True
+
+ if tool._task:
+ tool._task.cancel()
+ if log:
+ logger.info(f"Cancelled tool: {tool.tool_name} (id={tool_id})")
+ return True
+
+ return False
+
+ def start_up(self, tool_callbacks: list[Callable[[ToolNotification], Coroutine[Any, Any, None]]]) -> None:
+ """Start the background tool manager.
+
+ This method starts two concurrent tasks:
+ - _listener: Listens for completed BackgroundTool notifications and calls the callbacks.
+ - _cleanup: Cleans up completed/failed/cancelled tools that have been in memory for too long and times out tools that have been running too long.
+
+ Args:
+ tool_callbacks: A list of async or sync callables that receive the completed BackgroundTool notifications.
+
+ """
+ self.set_loop()
+
+ async def _listener() -> None:
+ while True:
+ bg_tool = await self._notification_queue.get()
+ for callback in tool_callbacks:
+ await callback(bg_tool)
+
+ async def _cleanup(interval_seconds: float = 5 * 60) -> None:
+ while True:
+ await asyncio.sleep(interval_seconds)
+ await self.cleanup_tools()
+ await self.timeout_tools()
+
+ self._lifecycle_tasks = [
+ asyncio.create_task(_cleanup(), name="bg-tool-cleanup"),
+ asyncio.create_task(_listener(), name="bg-tool-listener-callback"),
+ ]
+
+ logger.info(
+ "BackgroundToolManager started. "
+ "Max tool execution duration: %s seconds (tools running longer will be auto-cancelled). "
+ "Max tool memory retention: %s seconds (completed/failed/cancelled tools older than this are purged).",
+ self._max_tool_duration_seconds,
+ self._max_tool_memory_seconds,
+ )
+
+ async def shutdown(self) -> None:
+ """Cancel all background tasks (listener, cleanup) and running tools."""
+ for task in self._lifecycle_tasks:
+ task.cancel()
+ for task in self._lifecycle_tasks:
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ self._lifecycle_tasks.clear()
+
+ for tool_id in list(self._tools):
+ await self.cancel_tool(tool_id, log=False)
+
+ logger.info("BackgroundToolManager shut down")
+
+ async def timeout_tools(self) -> int:
+ """Cancel tools that have been running too long.
+
+ Returns:
+ Number of tools cancelled
+
+ """
+ now = time.monotonic()
+ to_cancel = []
+
+ for tool_id, tool in self._tools.items():
+ if tool.status == ToolState.RUNNING:
+ if tool.started_at and (now - tool.started_at) > self._max_tool_duration_seconds:
+ to_cancel.append(tool_id)
+
+ for tool_id in to_cancel:
+ await self.cancel_tool(tool_id)
+
+ if to_cancel:
+ logger.debug(f"Timed out {len(to_cancel)} tools")
+
+ return len(to_cancel)
+
+ async def cleanup_tools(self) -> int:
+ """Remove completed/failed/cancelled tools that have been in memory for too long.
+
+ Returns:
+ Number of tools removed
+
+ """
+ now = time.monotonic()
+ to_remove = []
+
+ for tool_id, tool in self._tools.items():
+ if tool.status in (ToolState.COMPLETED, ToolState.FAILED, ToolState.CANCELLED):
+ if tool.completed_at and (now - tool.completed_at) > self._max_tool_memory_seconds:
+ to_remove.append(tool_id)
+
+ for tool_id in to_remove:
+ del self._tools[tool_id]
+
+ if to_remove:
+ logger.debug(f"Cleaned up {len(to_remove)} old tools")
+
+ return len(to_remove)
+
+ def get_tool(self, tool_id: str) -> Optional[BackgroundTool]:
+ """Get a tool by ID."""
+ return self._tools.get(tool_id)
+
+ def get_running_tools(self) -> list[BackgroundTool]:
+ """Get all currently running tools."""
+ return [t for t in self._tools.values() if t.status == ToolState.RUNNING]
+
+ def get_all_tools(self, limit: Optional[int] = None) -> list[BackgroundTool]:
+ """Get recent tools (most recent first).
+
+ Args:
+ limit: Maximum number of tools to return (None means all)
+
+ Returns:
+ List of tools sorted by start time (most recent first)
+
+ """
+ sorted_tools = sorted(
+ self._tools.values(),
+ key=lambda t: t.started_at,
+ reverse=True,
+ )
+ if limit is not None:
+ return sorted_tools[:limit]
+ return sorted_tools
+
diff --git a/src/Reachy_OpenWebUI/tools/camera.py b/src/Reachy_OpenWebUI/tools/camera.py
new file mode 100644
index 0000000000000000000000000000000000000000..f804736afd3726209174dea31b7ac7e860161b03
--- /dev/null
+++ b/src/Reachy_OpenWebUI/tools/camera.py
@@ -0,0 +1,186 @@
+import asyncio
+import base64
+import logging
+from typing import Any, Dict
+
+import httpx
+
+from Reachy_OpenWebUI.config import config
+from Reachy_OpenWebUI.camera_frame_encoding import encode_bgr_frame_as_jpeg
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+
+
+logger = logging.getLogger(__name__)
+
+
+def _dedupe_urls(urls: list[str]) -> list[str]:
+ seen: set[str] = set()
+ clean: list[str] = []
+ for url in urls:
+ normalized = url.strip().rstrip("/")
+ if normalized and normalized not in seen:
+ seen.add(normalized)
+ clean.append(normalized)
+ return clean
+
+
+def _openwebui_chat_candidates(root_url: str) -> list[str]:
+ root = (root_url or "").strip().rstrip("/")
+ if not root:
+ return []
+ if root.endswith("/api"):
+ return _dedupe_urls([f"{root}/chat/completions"])
+ return _dedupe_urls([f"{root}/api/chat/completions", f"{root}/v1/chat/completions"])
+
+
+def _openwebui_headers() -> dict[str, str]:
+ headers = {
+ "Accept": "application/json",
+ "Content-Type": "application/json",
+ "User-Agent": config.OPENWEBUI_USER_AGENT,
+ }
+ auth_token = (config.OPENWEBUI_TOKEN or config.OPENWEBUI_API_KEY or "").strip()
+ if auth_token and auth_token != "ollama":
+ headers["Authorization"] = f"Bearer {auth_token}"
+ return headers
+
+
+def _assistant_content(payload: Any) -> str:
+ choices = payload.get("choices") if isinstance(payload, dict) else None
+ choice = choices[0] if isinstance(choices, list) and choices else {}
+ message = choice.get("message") if isinstance(choice, dict) else {}
+ if not isinstance(message, dict):
+ return ""
+ content = message.get("content")
+ if isinstance(content, str):
+ return content.strip()
+ if isinstance(content, list):
+ parts: list[str] = []
+ for item in content:
+ if isinstance(item, str):
+ parts.append(item)
+ elif isinstance(item, dict):
+ text = item.get("text") or item.get("content")
+ if isinstance(text, str):
+ parts.append(text)
+ return "\n".join(part.strip() for part in parts if part.strip()).strip()
+ return ""
+
+
+class Camera(Tool):
+ """Take a picture with the camera and ask a question about it."""
+
+ name = "camera"
+ description = "Take a picture of what the robot sees and describe it or answer a question about it. Use this when the user asks 'what do you see?', 'describe the scene', or asks a specific visual question."
+ parameters_schema = {
+ "type": "object",
+ "properties": {
+ "question": {
+ "type": "string",
+ "description": "Optional question to ask about the picture. Defaults to 'Describe what you see in detail.' if omitted.",
+ },
+ },
+ "required": [],
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ """Take a picture with the camera and ask a question about it."""
+ image_query = (kwargs.get("question") or "Describe what you see in detail.").strip()
+
+ logger.info("Tool call: camera question=%s", image_query[:120])
+
+ # Get frame from camera worker buffer (like main_works.py)
+ if deps.camera_worker is not None:
+ frame = deps.camera_worker.get_latest_frame()
+ if frame is None:
+ logger.error("No frame available from camera worker")
+ return {"error": "No frame available"}
+ else:
+ logger.error("Camera worker not available")
+ return {"error": "Camera worker not available"}
+
+ # Use vision manager for processing if available
+ if deps.vision_manager is not None:
+ vision_result = await asyncio.to_thread(
+ deps.vision_manager.processor.process_image,
+ frame,
+ image_query,
+ )
+ if isinstance(vision_result, dict) and "error" in vision_result:
+ return vision_result
+ return (
+ {"image_description": vision_result}
+ if isinstance(vision_result, str)
+ else {"error": "vision returned non-string"}
+ )
+
+ return await self._describe_with_openwebui(frame, image_query)
+
+ async def _describe_with_openwebui(self, frame: Any, question: str) -> Dict[str, Any]:
+ """Send the latest camera frame to OpenWebUI as a vision chat message."""
+ model = (config.OPENWEBUI_MODEL or "").strip()
+ if not model:
+ return {"error": "OpenWebUI model is not configured for camera vision"}
+
+ try:
+ jpeg_bytes = await asyncio.to_thread(encode_bgr_frame_as_jpeg, frame)
+ except Exception as exc:
+ logger.exception("Failed to encode camera frame")
+ return {"error": f"Failed to encode camera frame: {exc}"}
+
+ image_url = "data:image/jpeg;base64," + base64.b64encode(jpeg_bytes).decode("ascii")
+ payload: dict[str, object] = {
+ "stream": False,
+ "model": model,
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": (
+ "You are looking through Reachy's camera. "
+ "Answer the user's visual question directly and briefly.\n\n"
+ f"Question: {question}"
+ ),
+ },
+ {"type": "image_url", "image_url": {"url": image_url}},
+ ],
+ }
+ ],
+ "features": {
+ "image_generation": False,
+ "code_interpreter": False,
+ "web_search": False,
+ },
+ "max_tokens": 300,
+ }
+
+ last_error = ""
+ timeout = httpx.Timeout(connect=10.0, read=60.0, write=20.0, pool=10.0)
+ async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client:
+ for url in _openwebui_chat_candidates(config.OPENWEBUI_URL):
+ try:
+ response = await client.post(url, headers=_openwebui_headers(), json=payload)
+ except Exception as exc:
+ last_error = f"{type(exc).__name__}: {exc}"
+ logger.warning("OpenWebUI camera vision request failed at %s: %s", url, exc)
+ continue
+
+ if response.status_code in {404, 405}:
+ last_error = f"HTTP {response.status_code}"
+ logger.info("OpenWebUI camera vision endpoint unavailable (%s): %s", response.status_code, url)
+ continue
+ if response.status_code >= 400:
+ last_error = f"HTTP {response.status_code}: {response.text[:500]}"
+ logger.warning("OpenWebUI camera vision HTTP error at %s: %s", url, last_error)
+ continue
+
+ content = _assistant_content(response.json())
+ if content:
+ logger.info("OpenWebUI camera vision response: %s", content[:200])
+ return {"image_description": content}
+ last_error = "OpenWebUI vision response was empty"
+
+ return {"error": f"OpenWebUI camera vision failed: {last_error or 'no endpoint available'}"}
+
diff --git a/src/Reachy_OpenWebUI/tools/core_tools.py b/src/Reachy_OpenWebUI/tools/core_tools.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ddc4185ffb212fbe86326a592ec7ef8d521caff
--- /dev/null
+++ b/src/Reachy_OpenWebUI/tools/core_tools.py
@@ -0,0 +1,273 @@
+from __future__ import annotations
+import abc
+import sys
+import json
+import copy
+import inspect
+import logging
+import importlib
+from typing import TYPE_CHECKING, Any, Dict, List
+from pathlib import Path
+from dataclasses import dataclass
+
+from Reachy_OpenWebUI.sub_apps.attitudes import apply_attitude_to_tool_specs
+from Reachy_OpenWebUI.app_profiles import resolve_tool_profile_source
+from Reachy_OpenWebUI.config import active_profile # noqa: F401 — ensures .env is loaded
+
+if TYPE_CHECKING:
+ from reachy_mini import ReachyMini
+
+
+logger = logging.getLogger(__name__)
+
+
+if not logger.handlers:
+ handler = logging.StreamHandler()
+ formatter = logging.Formatter("%(asctime)s %(levelname)s %(name)s:%(lineno)d | %(message)s")
+ handler.setFormatter(formatter)
+ logger.addHandler(handler)
+ logger.setLevel(logging.INFO)
+
+
+ALL_TOOLS: Dict[str, "Tool"] = {}
+ALL_TOOL_SPECS: List[Dict[str, Any]] = []
+_TOOLS_INITIALIZED = False
+_ACTIVE_PROFILE = ""
+
+
+def _module_not_found_is_target(exc: ModuleNotFoundError, module_name: str) -> bool:
+ """Return True when the requested module is missing, not its dependency."""
+ missing_name = getattr(exc, "name", "") or ""
+ return missing_name == module_name or module_name.endswith(f".{missing_name}")
+
+
+def get_concrete_subclasses(base: type[Tool]) -> List[type[Tool]]:
+ """Recursively find all concrete (non-abstract) subclasses of a base class."""
+ result: List[type[Tool]] = []
+ for cls in base.__subclasses__():
+ if not inspect.isabstract(cls):
+ result.append(cls)
+ # recurse into subclasses
+ result.extend(get_concrete_subclasses(cls))
+ return result
+
+
+@dataclass
+class ToolDependencies:
+ """External dependencies injected into tools."""
+
+ reachy_mini: ReachyMini
+ movement_manager: Any # MovementManager from moves.py
+ # Optional deps
+ camera_worker: Any | None = None # CameraWorker for frame buffering
+ vision_manager: Any | None = None
+ head_wobbler: Any | None = None # HeadWobbler for audio-reactive motion
+ data_dir: Path | None = None
+ handler: Any | None = None
+ motion_duration_s: float = 1.0
+ speak_func: Any | None = None # Async function(text: str) -> None
+
+
+# Tool base class
+class Tool(abc.ABC):
+ """Base abstraction for tools used in function-calling.
+
+ Each tool must define:
+ - name: str
+ - description: str
+ - parameters_schema: Dict[str, Any] # JSON Schema
+ """
+
+ name: str
+ description: str
+ parameters_schema: Dict[str, Any]
+
+ def spec(self) -> Dict[str, Any]:
+ """Return the function spec for OpenWebUI tool calling."""
+ return {
+ "type": "function",
+ "function": {
+ "name": self.name,
+ "description": self.description,
+ "parameters": self.parameters_schema,
+ },
+ }
+
+ @abc.abstractmethod
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ """Async tool execution entrypoint."""
+ raise NotImplementedError
+
+
+# Registry & specs (dynamic)
+def _load_profile_tools(profile: str) -> list[str]:
+ """Load the bot-side Reachy tools list."""
+ source = resolve_tool_profile_source(profile)
+ logger.info("Loading Reachy tools for profile: %s", source.profile)
+ tools_txt_path = source.tools_txt_path
+
+ if not tools_txt_path.exists():
+ logger.error(f"✗ tools.txt not found at {tools_txt_path}")
+ sys.exit(1)
+
+ # Read and parse tools.txt
+ try:
+ with open(tools_txt_path, "r") as f:
+ lines = f.readlines()
+ except Exception as e:
+ logger.error(f"✗ Failed to read tools.txt: {e}")
+ sys.exit(1)
+
+ # Parse tool names (skip comments and blank lines)
+ tool_names = []
+ for line in lines:
+ line = line.strip()
+ # Skip blank lines and comments
+ if not line or line.startswith("#"):
+ continue
+ tool_names.append(line)
+
+ logger.info(f"Found {len(tool_names)} tools to load for profile '{profile}': {tool_names}")
+
+ # Import each tool
+ for tool_name in tool_names:
+ loaded = False
+ profile_error = None
+
+ # Try profile-local tool first
+ try:
+ profile_tool_module = f"{source.profile_package}.{tool_name}"
+ importlib.import_module(profile_tool_module)
+ logger.info(f"✓ Loaded profile-local tool: {tool_name}")
+ loaded = True
+ except ModuleNotFoundError as e:
+ # Check if it's the tool module itself that's missing (expected) or a dependency
+ if _module_not_found_is_target(e, profile_tool_module):
+ pass # Tool not in profile directory, try shared tools
+ else:
+ # Missing import dependency within the tool file
+ profile_error = f"Missing dependency: {e}"
+ logger.error(f"❌ Failed to load profile-local tool '{tool_name}': {profile_error}")
+ logger.error(f" Module path: {profile_tool_module}")
+ except ImportError as e:
+ profile_error = f"Import error: {e}"
+ logger.error(f"❌ Failed to load profile-local tool '{tool_name}': {profile_error}")
+ logger.error(f" Module path: {profile_tool_module}")
+ except Exception as e:
+ profile_error = f"{type(e).__name__}: {e}"
+ logger.error(f"❌ Failed to load profile-local tool '{tool_name}': {profile_error}")
+ logger.error(f" Module path: {profile_tool_module}")
+
+ # Try app/shared tools library if not found in profile
+ if not loaded:
+ for shared_package in source.shared_tool_packages:
+ shared_tool_module = f"{shared_package}.{tool_name}"
+ try:
+ importlib.import_module(shared_tool_module)
+ logger.info(f"✓ Loaded shared tool: {tool_name}")
+ loaded = True
+ break
+ except ModuleNotFoundError as e:
+ if _module_not_found_is_target(e, shared_tool_module):
+ continue
+ logger.error(f"❌ Failed to load shared tool '{tool_name}': Missing dependency: {e}")
+ logger.error(f" Module path: {shared_tool_module}")
+ except ImportError as e:
+ logger.error(f"❌ Failed to load shared tool '{tool_name}': Import error: {e}")
+ logger.error(f" Module path: {shared_tool_module}")
+ except Exception as e:
+ logger.error(f"❌ Failed to load shared tool '{tool_name}': {type(e).__name__}: {e}")
+ logger.error(f" Module path: {shared_tool_module}")
+
+ if not loaded:
+ if profile_error:
+ logger.error(f"❌ Tool '{tool_name}' also not found in shared tools")
+ else:
+ logger.warning(f"⚠️ Tool '{tool_name}' not found in profile or shared tools")
+
+ return tool_names
+
+
+def _initialize_tools() -> None:
+ """Populate registry for the active profile at app startup."""
+ global ALL_TOOLS, ALL_TOOL_SPECS, _TOOLS_INITIALIZED, _ACTIVE_PROFILE
+
+ selected_profile = active_profile()
+ if _TOOLS_INITIALIZED and _ACTIVE_PROFILE == selected_profile:
+ logger.debug("Tools already initialized; skipping reinitialization.")
+ return
+
+ tool_names = _load_profile_tools(selected_profile)
+ tool_name_set = set(tool_names)
+
+ loaded_tools = {
+ cls.name: cls()
+ for cls in get_concrete_subclasses(Tool)
+ if cls.name in tool_name_set
+ } # type: ignore[type-abstract]
+ ALL_TOOLS = {name: loaded_tools[name] for name in tool_names if name in loaded_tools}
+ ALL_TOOL_SPECS = [tool.spec() for tool in ALL_TOOLS.values()]
+ _ACTIVE_PROFILE = selected_profile
+
+ for tool_name, tool in ALL_TOOLS.items():
+ logger.info(f"tool registered for {selected_profile}: {tool_name} - {tool.description}")
+
+ _TOOLS_INITIALIZED = True
+
+
+_initialize_tools()
+
+
+def get_tool_specs(
+ exclusion_list: list[str] | None = None,
+ attitude: str | None = None,
+) -> list[Dict[str, Any]]:
+ """Get tool specs, optionally excluding tools and narrowing moves by attitude."""
+ _initialize_tools()
+ exclusions = set(exclusion_list or [])
+ specs = [copy.deepcopy(spec) for spec in ALL_TOOL_SPECS if spec["function"]["name"] not in exclusions]
+ if attitude is not None:
+ specs = apply_attitude_to_tool_specs(specs, attitude)
+ return specs
+
+
+# Dispatcher
+def _safe_load_obj(args_json: Any) -> Dict[str, Any]:
+ if isinstance(args_json, dict):
+ return args_json
+ if args_json is None:
+ return {}
+ if not isinstance(args_json, str):
+ logger.warning("bad args_json type=%s value=%r", type(args_json).__name__, args_json)
+ return {}
+
+ raw = args_json.strip()
+ if not raw:
+ return {}
+
+ try:
+ parsed_args: Any = json.loads(raw)
+ if isinstance(parsed_args, str):
+ parsed_args = json.loads(parsed_args)
+ return parsed_args if isinstance(parsed_args, dict) else {}
+ except Exception:
+ logger.warning("bad args_json=%r", args_json)
+ return {}
+
+
+async def dispatch_tool_call(tool_name: str, args_json: Any, deps: ToolDependencies) -> Dict[str, Any]:
+ """Dispatch a tool call by name with JSON args and dependencies."""
+ _initialize_tools()
+ tool = ALL_TOOLS.get(tool_name)
+
+ if not tool:
+ return {"error": f"unknown tool: {tool_name}"}
+
+ args = _safe_load_obj(args_json)
+ try:
+ return await tool(deps, **args)
+ except Exception as e:
+ msg = f"{type(e).__name__}: {e}"
+ logger.exception("Tool error in %s: %s", tool_name, msg)
+ return {"error": msg}
+
diff --git a/src/Reachy_OpenWebUI/tools/dance.py b/src/Reachy_OpenWebUI/tools/dance.py
new file mode 100644
index 0000000000000000000000000000000000000000..e67958b9c66940be18699328158026283f2b6a64
--- /dev/null
+++ b/src/Reachy_OpenWebUI/tools/dance.py
@@ -0,0 +1,103 @@
+import logging
+from typing import Any, Dict
+
+from Reachy_OpenWebUI.sub_apps.attitudes import allowed_dances_for_attitude, resolve_attitude
+from Reachy_OpenWebUI.config import config
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+
+
+logger = logging.getLogger(__name__)
+COOKAIWARE_PROFILE = "cookaiware"
+
+# Initialize dance library
+try:
+ from reachy_mini_dances_library.collection.dance import AVAILABLE_MOVES
+ from Reachy_OpenWebUI.dance_emotion_moves import DanceQueueMove
+
+ DANCE_AVAILABLE = True
+except ImportError as e:
+ logger.warning(f"Dance library not available: {e}")
+ AVAILABLE_MOVES = {}
+ DANCE_AVAILABLE = False
+
+
+def get_available_dances_and_descriptions() -> str:
+ """Get formatted list of available dance moves with descriptions."""
+ if not DANCE_AVAILABLE or not AVAILABLE_MOVES:
+ return "Dance moves not available."
+ output = ""
+ for move_name, (func, params, metadata) in AVAILABLE_MOVES.items():
+ description = metadata.get("description", "No description available.")
+ output += f" - {move_name}: {description}\n"
+ return output
+
+
+def _attitude_allowed_dances() -> list[str]:
+ if not DANCE_AVAILABLE:
+ return []
+ if (config.REACHY_MINI_CUSTOM_PROFILE or "") == COOKAIWARE_PROFILE:
+ return list(AVAILABLE_MOVES.keys())
+ return allowed_dances_for_attitude(config.REACHY_IDLE_ATTITUDE, AVAILABLE_MOVES.keys())
+
+
+class Dance(Tool):
+ """Play a named or random dance move once (or repeat). Non-blocking."""
+
+ name = "dance"
+ description = "Play a named or random dance move once (or repeat). Non-blocking."
+ parameters_schema = {
+ "type": "object",
+ "properties": {
+ "move": {
+ "type": "string",
+ "enum": list(AVAILABLE_MOVES.keys()) if DANCE_AVAILABLE else [],
+ "description": f"""Name of the move; omit for random. You MUST only choose from these:
+ {get_available_dances_and_descriptions()}
+ """,
+ },
+ "repeat": {
+ "type": "integer",
+ "description": "How many times to repeat the move (default 1).",
+ },
+ },
+ "required": [],
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ """Play a named or random dance move once (or repeat). Non-blocking."""
+ if not DANCE_AVAILABLE:
+ return {"error": "Dance system not available"}
+
+ move_name = kwargs.get("move")
+ repeat = int(kwargs.get("repeat", 1))
+
+ logger.info("Tool call: dance move=%s repeat=%d", move_name, repeat)
+
+ if not move_name or move_name == "random":
+ import random
+
+ allowed_moves = _attitude_allowed_dances()
+ if not allowed_moves:
+ attitude = resolve_attitude(config.REACHY_IDLE_ATTITUDE)
+ return {"error": f"No dance moves are allowed for the current {attitude.label} attitude."}
+ move_name = random.choice(allowed_moves)
+
+ if move_name not in AVAILABLE_MOVES:
+ return {"error": f"Unknown dance move '{move_name}'. Available: {list(AVAILABLE_MOVES.keys())}"}
+ allowed_moves = _attitude_allowed_dances()
+ if move_name not in allowed_moves:
+ attitude = resolve_attitude(config.REACHY_IDLE_ATTITUDE)
+ return {
+ "error": (
+ f"Dance move '{move_name}' is not allowed for the current "
+ f"{attitude.label} attitude. Available: {allowed_moves}"
+ )
+ }
+
+ # Add dance moves to queue
+ movement_manager = deps.movement_manager
+ for _ in range(repeat):
+ dance_move = DanceQueueMove(move_name)
+ movement_manager.queue_move(dance_move)
+
+ return {"status": "queued", "move": move_name, "repeat": repeat}
diff --git a/src/Reachy_OpenWebUI/tools/head_tracking.py b/src/Reachy_OpenWebUI/tools/head_tracking.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0bd33632e8ceb1963194092d4b16d8cdc0b1b55
--- /dev/null
+++ b/src/Reachy_OpenWebUI/tools/head_tracking.py
@@ -0,0 +1,32 @@
+import logging
+from typing import Any, Dict
+
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+
+
+logger = logging.getLogger(__name__)
+
+
+class HeadTracking(Tool):
+ """Toggle head tracking state."""
+
+ name = "head_tracking"
+ description = "Toggle head tracking state."
+ parameters_schema = {
+ "type": "object",
+ "properties": {"start": {"type": "boolean"}},
+ "required": ["start"],
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ """Enable or disable head tracking."""
+ enable = bool(kwargs.get("start"))
+
+ # Update camera worker head tracking state
+ if deps.camera_worker is not None:
+ deps.camera_worker.set_head_tracking_enabled(enable)
+
+ status = "started" if enable else "stopped"
+ logger.info("Tool call: head_tracking %s", status)
+ return {"status": f"head tracking {status}"}
+
diff --git a/src/Reachy_OpenWebUI/tools/idle_do_nothing.py b/src/Reachy_OpenWebUI/tools/idle_do_nothing.py
new file mode 100644
index 0000000000000000000000000000000000000000..6941275d540699d7b5a9aac499b6d8e7beed19a6
--- /dev/null
+++ b/src/Reachy_OpenWebUI/tools/idle_do_nothing.py
@@ -0,0 +1,34 @@
+import logging
+from typing import Any, Dict
+
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+
+
+logger = logging.getLogger(__name__)
+
+
+class IdleDoNothing(Tool):
+ """Explicitly choose no action during an idle turn."""
+
+ name = "idle_do_nothing"
+ description = (
+ "Use only in response to an idle time update when you intentionally want Reachy to stay still and silent "
+ "instead of choosing another idle action."
+ )
+ parameters_schema = {
+ "type": "object",
+ "properties": {
+ "reason": {
+ "type": "string",
+ "description": "Optional reason for staying idle during this idle turn.",
+ },
+ },
+ "required": [],
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ """Stay still and silent for the current idle turn."""
+ reason = kwargs.get("reason", "idle turn")
+ logger.info("Tool call: idle_do_nothing reason=%s", reason)
+ return {"status": "idle", "reason": reason}
+
diff --git a/src/Reachy_OpenWebUI/tools/move_head.py b/src/Reachy_OpenWebUI/tools/move_head.py
new file mode 100644
index 0000000000000000000000000000000000000000..641be32d2d54202a6f1d92730ceead22af987017
--- /dev/null
+++ b/src/Reachy_OpenWebUI/tools/move_head.py
@@ -0,0 +1,80 @@
+import logging
+from typing import Any, Dict, Tuple, Literal
+
+from reachy_mini.utils import create_head_pose
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+from Reachy_OpenWebUI.dance_emotion_moves import GotoQueueMove
+
+
+logger = logging.getLogger(__name__)
+
+Direction = Literal["left", "right", "up", "down", "front"]
+
+
+class MoveHead(Tool):
+ """Move head in a given direction."""
+
+ name = "move_head"
+ description = "Move your head in a given direction: left, right, up, down or front."
+ parameters_schema = {
+ "type": "object",
+ "properties": {
+ "direction": {
+ "type": "string",
+ "enum": ["left", "right", "up", "down", "front"],
+ },
+ },
+ "required": ["direction"],
+ }
+
+ # mapping: direction -> args for create_head_pose
+ DELTAS: Dict[str, Tuple[int, int, int, int, int, int]] = {
+ "left": (0, 0, 0, 0, 0, 40),
+ "right": (0, 0, 0, 0, 0, -40),
+ "up": (0, 0, 0, 0, -30, 0),
+ "down": (0, 0, 0, 0, 30, 0),
+ "front": (0, 0, 0, 0, 0, 0),
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ """Move head in a given direction."""
+ direction_raw = kwargs.get("direction")
+ if not isinstance(direction_raw, str):
+ return {"error": "direction must be a string"}
+ direction: Direction = direction_raw # type: ignore[assignment]
+ logger.info("Tool call: move_head direction=%s", direction)
+
+ deltas = self.DELTAS.get(direction, self.DELTAS["front"])
+ target = create_head_pose(*deltas, degrees=True)
+
+ # Use new movement manager
+ try:
+ movement_manager = deps.movement_manager
+
+ # Get current state for interpolation
+ current_head_pose = deps.reachy_mini.get_current_head_pose()
+ _, current_antennas = deps.reachy_mini.get_current_joint_positions()
+
+ # Create goto move
+ goto_move = GotoQueueMove(
+ target_head_pose=target,
+ start_head_pose=current_head_pose,
+ target_antennas=(0, 0), # Reset antennas to default
+ start_antennas=(
+ current_antennas[0],
+ current_antennas[1],
+ ), # Skip body_yaw
+ target_body_yaw=0, # Reset body yaw
+ start_body_yaw=current_antennas[0], # body_yaw is first in joint positions
+ duration=deps.motion_duration_s,
+ )
+
+ movement_manager.queue_move(goto_move)
+ movement_manager.set_moving_state(deps.motion_duration_s)
+
+ return {"status": f"looking {direction}"}
+
+ except Exception as e:
+ logger.error("move_head failed")
+ return {"error": f"move_head failed: {type(e).__name__}: {e}"}
+
diff --git a/src/Reachy_OpenWebUI/tools/play_emotion.py b/src/Reachy_OpenWebUI/tools/play_emotion.py
new file mode 100644
index 0000000000000000000000000000000000000000..ecfda1af3ce3de664fc120c54b37f385708b7917
--- /dev/null
+++ b/src/Reachy_OpenWebUI/tools/play_emotion.py
@@ -0,0 +1,126 @@
+import logging
+import random
+from typing import Any, Dict
+
+from Reachy_OpenWebUI.sub_apps.attitudes import allowed_emotions_for_attitude, resolve_attitude
+from Reachy_OpenWebUI.config import config
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+
+
+logger = logging.getLogger(__name__)
+COOKAIWARE_PROFILE = "cookaiware"
+
+# Initialize emotion library
+try:
+ from reachy_mini.motion.recorded_move import RecordedMoves
+ from Reachy_OpenWebUI.dance_emotion_moves import EmotionQueueMove
+
+ # Note: huggingface_hub automatically reads HF_TOKEN from environment variables
+ RECORDED_MOVES = RecordedMoves("pollen-robotics/reachy-mini-emotions-library")
+ EMOTION_AVAILABLE = True
+except ImportError as e:
+ logger.warning(f"Emotion library not available: {e}")
+ RECORDED_MOVES = None
+ EMOTION_AVAILABLE = False
+
+
+def get_available_emotions_and_descriptions() -> str:
+ """Get formatted list of available emotions with descriptions."""
+ if not EMOTION_AVAILABLE:
+ return "Emotions not available"
+
+ try:
+ emotion_names = RECORDED_MOVES.list_moves()
+ output = "Available emotions:\n"
+ for name in emotion_names:
+ description = RECORDED_MOVES.get(name).description
+ output += f" - {name}: {description}\n"
+ return output
+ except Exception as e:
+ return f"Error getting emotions: {e}"
+
+
+def _normalize_emotion_name(name: Any) -> str:
+ return str(name or "").strip().lower()
+
+
+def _canonical_emotion_name(name: Any, available: list[str]) -> str:
+ normalized = _normalize_emotion_name(name)
+ for emotion_name in available:
+ if _normalize_emotion_name(emotion_name) == normalized:
+ return emotion_name
+ return str(name or "").strip()
+
+
+def _attitude_allowed_emotions() -> list[str]:
+ if not EMOTION_AVAILABLE:
+ return []
+ if (config.REACHY_MINI_CUSTOM_PROFILE or "") == COOKAIWARE_PROFILE:
+ return RECORDED_MOVES.list_moves()
+ return allowed_emotions_for_attitude(config.REACHY_IDLE_ATTITUDE, RECORDED_MOVES.list_moves())
+
+
+class PlayEmotion(Tool):
+ """Play a pre-recorded emotion."""
+
+ name = "play_emotion"
+ description = (
+ "Queue a visible pre-recorded emotion gesture for Reachy. "
+ "Use this when the reply should include a one-shot emotional reaction."
+ )
+ parameters_schema = {
+ "type": "object",
+ "properties": {
+ "emotion": {
+ "type": "string",
+ "enum": list(RECORDED_MOVES.list_moves()) if EMOTION_AVAILABLE else [],
+ "description": f"""Name of the emotion to play; omit for a random allowed emotion.
+ Here is a list of the available emotions, you MUST only choose from these:
+ {get_available_emotions_and_descriptions()}
+ """,
+ },
+ },
+ "required": [],
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ """Play a pre-recorded emotion."""
+ if not EMOTION_AVAILABLE:
+ return {"error": "Emotion system not available"}
+
+ emotion_name = str(kwargs.get("emotion") or "").strip()
+ logger.info("Tool call: play_emotion emotion=%s", emotion_name)
+
+ # Check if emotion exists
+ try:
+ emotion_names = RECORDED_MOVES.list_moves()
+ if not emotion_names:
+ return {"error": "No emotions currently available"}
+ allowed_emotions = _attitude_allowed_emotions()
+ if not allowed_emotions:
+ attitude = resolve_attitude(config.REACHY_IDLE_ATTITUDE)
+ return {"error": f"No emotions are allowed for the current {attitude.label} attitude."}
+ if not emotion_name:
+ emotion_name = random.choice(allowed_emotions)
+ emotion_name = _canonical_emotion_name(emotion_name, emotion_names)
+ if emotion_name not in emotion_names:
+ return {"error": f"Unknown emotion '{emotion_name}'. Available: {emotion_names}"}
+ if emotion_name not in allowed_emotions:
+ attitude = resolve_attitude(config.REACHY_IDLE_ATTITUDE)
+ return {
+ "error": (
+ f"Emotion '{emotion_name}' is not allowed for the current "
+ f"{attitude.label} attitude. Available: {allowed_emotions}"
+ )
+ }
+
+ # Add emotion to queue
+ movement_manager = deps.movement_manager
+ emotion_move = EmotionQueueMove(emotion_name, RECORDED_MOVES)
+ movement_manager.queue_move(emotion_move)
+
+ return {"status": "queued", "emotion": emotion_name}
+
+ except Exception as e:
+ logger.exception("Failed to play emotion")
+ return {"error": f"Failed to play emotion: {e!s}"}
diff --git a/src/Reachy_OpenWebUI/tools/speak.py b/src/Reachy_OpenWebUI/tools/speak.py
new file mode 100644
index 0000000000000000000000000000000000000000..b804e214d5286bcd126f2aeaf260ecdf8e37973b
--- /dev/null
+++ b/src/Reachy_OpenWebUI/tools/speak.py
@@ -0,0 +1,38 @@
+from typing import Any, Dict
+
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+
+
+class Speak(Tool):
+ """Tool for the robot to speak a given text."""
+
+ name = "speak"
+ description = "Make the robot speak the provided text out loud. Use this when you want to initiate a verbal statement or respond while performing other actions."
+ parameters_schema = {
+ "type": "object",
+ "properties": {
+ "text": {"type": "string", "description": "The text to speak."},
+ "emotion": {
+ "type": "string",
+ "description": "Optional emotion to express while speaking (e.g., 'happy', 'sad').",
+ },
+ },
+ "required": ["text"],
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ """Execute the speak tool."""
+ text: str = kwargs.get("text", "")
+ emotion: str | None = kwargs.get("emotion")
+ # If emotion is provided, we could optionally trigger play_emotion here or append it to text
+ full_text = text
+ if emotion:
+ full_text = f"[{emotion.upper()}] {text}"
+
+ if deps.speak_func:
+ # speak_func is expected to be an async function
+ await deps.speak_func(full_text)
+ return {"status": "success", "message": f"Spoke: {text}"}
+ else:
+ return {"status": "error", "message": "Speech function not available."}
+
diff --git a/src/Reachy_OpenWebUI/tools/stop_dance.py b/src/Reachy_OpenWebUI/tools/stop_dance.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c5af4a2abfa646e2b93181d87170d96df12953d
--- /dev/null
+++ b/src/Reachy_OpenWebUI/tools/stop_dance.py
@@ -0,0 +1,26 @@
+import logging
+from typing import Any, Dict
+
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+
+
+logger = logging.getLogger(__name__)
+
+
+class StopDance(Tool):
+ """Stop the current dance move."""
+
+ name = "stop_dance"
+ description = "Stop the current dance move"
+ parameters_schema = {
+ "type": "object",
+ "properties": {},
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ """Stop the current dance move."""
+ logger.info("Tool call: stop_dance")
+ movement_manager = deps.movement_manager
+ movement_manager.clear_move_queue()
+ return {"status": "stopped dance and cleared queue"}
+
diff --git a/src/Reachy_OpenWebUI/tools/stop_emotion.py b/src/Reachy_OpenWebUI/tools/stop_emotion.py
new file mode 100644
index 0000000000000000000000000000000000000000..111e4fbd01c027b64b206f3c9bb54fdca02a1ee8
--- /dev/null
+++ b/src/Reachy_OpenWebUI/tools/stop_emotion.py
@@ -0,0 +1,32 @@
+import logging
+from typing import Any, Dict
+
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+
+
+logger = logging.getLogger(__name__)
+
+
+class StopEmotion(Tool):
+ """Stop the current emotion."""
+
+ name = "stop_emotion"
+ description = "Stop the current emotion"
+ parameters_schema = {
+ "type": "object",
+ "properties": {
+ "dummy": {
+ "type": "boolean",
+ "description": "dummy boolean, set it to true",
+ },
+ },
+ "required": ["dummy"],
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ """Stop the current emotion."""
+ logger.info("Tool call: stop_emotion")
+ movement_manager = deps.movement_manager
+ movement_manager.clear_move_queue()
+ return {"status": "stopped emotion and cleared queue"}
+
diff --git a/src/Reachy_OpenWebUI/tools/sweep_look.py b/src/Reachy_OpenWebUI/tools/sweep_look.py
new file mode 100644
index 0000000000000000000000000000000000000000..27caaab6f5434825c559364e90b7a8e4580daf40
--- /dev/null
+++ b/src/Reachy_OpenWebUI/tools/sweep_look.py
@@ -0,0 +1,115 @@
+import logging
+from typing import Any, Dict
+
+import numpy as np
+
+from reachy_mini.utils import create_head_pose
+from Reachy_OpenWebUI.dance_emotion_moves import GotoQueueMove
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+
+
+logger = logging.getLogger(__name__)
+
+
+class SweepLook(Tool):
+ """Sweep head from left to right and back to center."""
+
+ name = "sweep_look"
+ description = "Sweep head from left to right while rotating the body, pausing at each extreme, then return to center."
+ parameters_schema = {
+ "type": "object",
+ "properties": {},
+ "required": [],
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ logger.info("Tool call: sweep_look")
+
+ deps.movement_manager.clear_move_queue()
+
+ current_head_pose = deps.reachy_mini.get_current_head_pose()
+ head_joints, antenna_joints = deps.reachy_mini.get_current_joint_positions()
+
+ current_body_yaw = head_joints[0]
+ current_antenna1 = antenna_joints[0]
+ current_antenna2 = antenna_joints[1]
+
+ max_angle = 0.9 * np.pi
+ transition_duration = 3.0
+ hold_duration = 1.0
+
+ left_head_pose = create_head_pose(0, 0, 0, 0, 0, max_angle, degrees=False)
+ center_head_pose = create_head_pose(0, 0, 0, 0, 0, 0, degrees=False)
+ right_head_pose = create_head_pose(0, 0, 0, 0, 0, -max_angle, degrees=False)
+
+ deps.movement_manager.queue_move(
+ GotoQueueMove(
+ target_head_pose=left_head_pose,
+ start_head_pose=current_head_pose,
+ target_antennas=(current_antenna1, current_antenna2),
+ start_antennas=(current_antenna1, current_antenna2),
+ target_body_yaw=current_body_yaw + max_angle,
+ start_body_yaw=current_body_yaw,
+ duration=transition_duration,
+ )
+ )
+ deps.movement_manager.queue_move(
+ GotoQueueMove(
+ target_head_pose=left_head_pose,
+ start_head_pose=left_head_pose,
+ target_antennas=(current_antenna1, current_antenna2),
+ start_antennas=(current_antenna1, current_antenna2),
+ target_body_yaw=current_body_yaw + max_angle,
+ start_body_yaw=current_body_yaw + max_angle,
+ duration=hold_duration,
+ )
+ )
+ deps.movement_manager.queue_move(
+ GotoQueueMove(
+ target_head_pose=center_head_pose,
+ start_head_pose=left_head_pose,
+ target_antennas=(current_antenna1, current_antenna2),
+ start_antennas=(current_antenna1, current_antenna2),
+ target_body_yaw=current_body_yaw,
+ start_body_yaw=current_body_yaw + max_angle,
+ duration=transition_duration,
+ )
+ )
+ deps.movement_manager.queue_move(
+ GotoQueueMove(
+ target_head_pose=right_head_pose,
+ start_head_pose=center_head_pose,
+ target_antennas=(current_antenna1, current_antenna2),
+ start_antennas=(current_antenna1, current_antenna2),
+ target_body_yaw=current_body_yaw - max_angle,
+ start_body_yaw=current_body_yaw,
+ duration=transition_duration,
+ )
+ )
+ deps.movement_manager.queue_move(
+ GotoQueueMove(
+ target_head_pose=right_head_pose,
+ start_head_pose=right_head_pose,
+ target_antennas=(current_antenna1, current_antenna2),
+ start_antennas=(current_antenna1, current_antenna2),
+ target_body_yaw=current_body_yaw - max_angle,
+ start_body_yaw=current_body_yaw - max_angle,
+ duration=hold_duration,
+ )
+ )
+ deps.movement_manager.queue_move(
+ GotoQueueMove(
+ target_head_pose=center_head_pose,
+ start_head_pose=right_head_pose,
+ target_antennas=(current_antenna1, current_antenna2),
+ start_antennas=(current_antenna1, current_antenna2),
+ target_body_yaw=current_body_yaw,
+ start_body_yaw=current_body_yaw - max_angle,
+ duration=transition_duration,
+ )
+ )
+
+ total_duration = transition_duration * 4 + hold_duration * 2
+ deps.movement_manager.set_moving_state(total_duration)
+
+ return {"status": f"sweeping look left-right-center, total {total_duration:.1f}s"}
diff --git a/src/Reachy_OpenWebUI/tools/task_cancel.py b/src/Reachy_OpenWebUI/tools/task_cancel.py
new file mode 100644
index 0000000000000000000000000000000000000000..e784843fe700d555933b757a34e52ace69aeaba7
--- /dev/null
+++ b/src/Reachy_OpenWebUI/tools/task_cancel.py
@@ -0,0 +1,75 @@
+"""Tool cancel tool - cancel running background tools."""
+
+import logging
+from typing import TYPE_CHECKING, Any, Dict
+
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+from Reachy_OpenWebUI.tools.tool_constants import ToolState
+
+
+if TYPE_CHECKING:
+ from Reachy_OpenWebUI.tools.background_tool_manager import BackgroundToolManager
+
+
+logger = logging.getLogger(__name__)
+
+
+class TaskCancel(Tool):
+ """Cancel a running background tool task."""
+
+ name = "task_cancel"
+ description = (
+ "Cancel a running background tool task. "
+ "Use this when the user wants to stop a tool that's running in the background. "
+ "Requires confirmation before cancelling."
+ )
+ parameters_schema = {
+ "type": "object",
+ "properties": {
+ "tool_id": {
+ "type": "string",
+ "description": "The tool ID to cancel",
+ }
+ },
+ "required": ["tool_id"],
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ """Cancel a background tool."""
+ tool_id = kwargs.get("tool_id", "")
+ tool_manager: BackgroundToolManager | None = kwargs.get("tool_manager")
+
+ if tool_manager is None:
+ return {"error": "Tool manager is required."}
+
+ logger.info(f"Tool call: tool_cancel tool_id={tool_id}")
+
+ if not tool_id:
+ return {"error": "Tool ID is required."}
+
+ tool = tool_manager.get_tool(tool_id)
+
+ if not tool:
+ return {"error": f"Tool {tool_id} not found."}
+
+ # Check if tool is still running
+ if tool.status != ToolState.RUNNING:
+ return {
+ "status": f"{tool.status.value}",
+ "message": f"Tool '{tool.tool_name}' is not running (status: {tool.status.value}).",
+ "tool_id": tool_id,
+ }
+
+ # Cancel the tool
+ if await tool_manager.cancel_tool(tool_id):
+ return {
+ "status": "cancelled",
+ "message": f"Tool '{tool.tool_name}' has been cancelled.",
+ "tool_id": tool_id,
+ "tool_name": tool.tool_name,
+ }
+ else:
+ return {
+ "error": f"Could not cancel tool {tool_id}. It may have already completed.",
+ }
+
diff --git a/src/Reachy_OpenWebUI/tools/task_status.py b/src/Reachy_OpenWebUI/tools/task_status.py
new file mode 100644
index 0000000000000000000000000000000000000000..e040dace296b028bb84a5034c1db6cee46080928
--- /dev/null
+++ b/src/Reachy_OpenWebUI/tools/task_status.py
@@ -0,0 +1,107 @@
+"""Tool status tool - check status of background tools."""
+
+import time
+import logging
+from typing import TYPE_CHECKING, Any, Dict
+
+from Reachy_OpenWebUI.tools.core_tools import Tool, ToolDependencies
+from Reachy_OpenWebUI.tools.tool_constants import SystemTool
+
+
+if TYPE_CHECKING:
+ from Reachy_OpenWebUI.tools.background_tool_manager import BackgroundToolManager
+
+
+logger = logging.getLogger(__name__)
+
+
+class TaskStatus(Tool):
+ """Check status of background tool tasks."""
+
+ name = "task_status"
+ description = (
+ "Check the status of background tool tasks. "
+ "Use this when the user asks about running tools or wants to know what's happening in the background."
+ )
+ parameters_schema = {
+ "type": "object",
+ "properties": {
+ "tool_id": {
+ "type": "string",
+ "description": "Specific tool ID to check (optional, shows all running tools if omitted)",
+ },
+ },
+ "required": [],
+ }
+
+ async def __call__(self, deps: ToolDependencies, **kwargs: Any) -> Dict[str, Any]:
+ """Get status of background tools."""
+ tool_id: str | None = kwargs.get("tool_id")
+ tool_manager: BackgroundToolManager | None = kwargs.get("tool_manager")
+
+ if tool_manager is None:
+ return {"error": "Tool manager is required."}
+
+ logger.info(f"Tool call: tool_status tool_id={tool_id}")
+
+ if tool_id:
+ tool = tool_manager.get_tool(tool_id)
+ if not tool:
+ return {"error": f"Tool {tool_id} not found."}
+
+ result: Dict[str, Any] = {
+ "tool_id": tool.tool_id,
+ "name": tool.tool_name,
+ "status": tool.status.value,
+ "started_at": tool.started_at,
+ }
+ if tool.completed_at:
+ result["completed_at"] = tool.completed_at
+
+ if tool.progress is not None:
+ result["progress_percent"] = f"{tool.progress.progress:.0%}"
+ if tool.progress.message:
+ result["progress_message"] = tool.progress.message
+
+ if tool.result:
+ result["result"] = tool.result
+ if tool.error:
+ result["error"] = tool.error
+
+ return result
+
+ # Get all running tools
+ running = tool_manager.get_running_tools()
+ if not running:
+ return {
+ "status": "idle",
+ "message": "No tools running in the background.",
+ }
+
+ tools_info = []
+ for tool in [
+ tool for tool in running if tool.tool_name not in [system_tool.value for system_tool in SystemTool]
+ ]:
+ elapsed = time.monotonic() - tool.started_at
+ tool_info: Dict[str, Any] = {
+ "tool_id": tool.tool_id,
+ "name": tool.tool_name,
+ "status": tool.status.value,
+ "elapsed_seconds": round(elapsed, 1),
+ }
+
+ # Add progress if tracking
+ if tool.progress is not None:
+ tool_info["progress_percent"] = f"{tool.progress.progress:.0%}"
+ if tool.progress.message:
+ tool_info["progress_message"] = tool.progress.message
+
+ tools_info.append(tool_info)
+
+ return {
+ "status": "running",
+ "count": len(tools_info),
+ "message": f"{len(tools_info)} tool(s) running in the background.",
+ "tools": tools_info,
+ }
+
diff --git a/src/Reachy_OpenWebUI/tools/tool_constants.py b/src/Reachy_OpenWebUI/tools/tool_constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..02af5e0e35a7ed4a891806a75e4413fcf56a04f9
--- /dev/null
+++ b/src/Reachy_OpenWebUI/tools/tool_constants.py
@@ -0,0 +1,17 @@
+from enum import Enum
+
+
+class ToolState(Enum):
+ """Status of a background tool."""
+
+ RUNNING = "running"
+ COMPLETED = "completed"
+ FAILED = "failed"
+ CANCELLED = "cancelled"
+
+
+class SystemTool(Enum):
+ """System tools are tools that are used to manage the background tool manager."""
+
+ TASK_STATUS = "task_status"
+ TASK_CANCEL = "task_cancel"
diff --git a/src/Reachy_OpenWebUI/utils.py b/src/Reachy_OpenWebUI/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..5edeaa0ee1d59bbb3ba6556f5f666e9ddcbaa9a6
--- /dev/null
+++ b/src/Reachy_OpenWebUI/utils.py
@@ -0,0 +1,103 @@
+import logging
+import argparse
+import warnings
+from typing import Any, Tuple, Optional
+
+from reachy_mini import ReachyMini
+from Reachy_OpenWebUI.camera_worker import CameraWorker
+
+
+def parse_args() -> Tuple[argparse.Namespace, list]:
+ """Parse command line arguments."""
+ parser = argparse.ArgumentParser("Reachy Openwebui")
+ parser.add_argument("--no-camera", default=False, action="store_true", help="Disable camera usage")
+ parser.add_argument(
+ "--smolvlm",
+ default=False,
+ action="store_true",
+ help="Use SmolVLM local vision model for periodic scene description.",
+ )
+ parser.add_argument("--debug", default=False, action="store_true", help="Enable debug logging")
+ parser.add_argument(
+ "--robot-name",
+ type=str,
+ default=None,
+ help="[Optional] Robot name/prefix for Zenoh topics (must match daemon's --robot-name). Only needed for development with multiple robots.",
+ )
+ return parser.parse_known_args()
+
+
+def handle_vision_stuff(args: argparse.Namespace, current_robot: ReachyMini) -> Tuple[CameraWorker | None, Any]:
+ """Initialize camera worker and vision manager.
+
+ By default, vision is handled by the LLM via camera tool.
+ If --smolvlm flag is used, SmolVLM will process images periodically.
+ """
+ camera_worker = None
+ vision_manager = None
+
+ if not args.no_camera:
+ # Initialize camera worker
+ camera_worker = CameraWorker(current_robot)
+
+ # Initialize Vision Manager (On-Demand Mode by default)
+ # This allows tools like 'camera' to use the configured Local VLM without
+ # running a continuous background process.
+ try:
+ from Reachy_OpenWebUI.vision.processors import initialize_vision_manager
+
+ # continuous_mode=False ensures we don't run the heavy background loop
+ vision_manager = initialize_vision_manager(camera_worker, continuous_mode=False)
+ if vision_manager:
+ logging.getLogger(__name__).info("Vision Manager initialized (On-Demand Mode).")
+ except ImportError:
+ logging.getLogger(__name__).warning(
+ "Vision dependencies missing, camera tool may not work for description."
+ )
+ except Exception as e:
+ logging.getLogger(__name__).error(f"Failed to init vision: {e}")
+
+ return camera_worker, vision_manager
+
+
+def setup_logger(debug: bool) -> logging.Logger:
+ """Setups the logger."""
+ log_level = "DEBUG" if debug else "INFO"
+ logging.basicConfig(
+ level=getattr(logging, log_level, logging.INFO),
+ format="%(asctime)s %(levelname)s %(name)s:%(lineno)d | %(message)s",
+ )
+ logger = logging.getLogger(__name__)
+
+ # Suppress WebRTC warnings
+ warnings.filterwarnings("ignore", message=".*AVCaptureDeviceTypeExternal.*")
+ warnings.filterwarnings("ignore", category=UserWarning, module="aiortc")
+
+ # Tame third-party noise (looser in DEBUG)
+ if log_level == "DEBUG":
+ logging.getLogger("aiortc").setLevel(logging.INFO)
+ logging.getLogger("fastrtc").setLevel(logging.INFO)
+ logging.getLogger("aioice").setLevel(logging.INFO)
+ logging.getLogger("openai").setLevel(logging.INFO)
+ logging.getLogger("websockets").setLevel(logging.INFO)
+ else:
+ logging.getLogger("aiortc").setLevel(logging.ERROR)
+ logging.getLogger("fastrtc").setLevel(logging.ERROR)
+ logging.getLogger("aioice").setLevel(logging.WARNING)
+ return logger
+
+
+def log_connection_troubleshooting(logger: logging.Logger, robot_name: Optional[str]) -> None:
+ """Log troubleshooting steps for connection issues."""
+ logger.error("Troubleshooting steps:")
+ logger.error(" 1. Verify reachy-mini-daemon is running")
+
+ if robot_name is not None:
+ logger.error(f" 2. Daemon must be started with: --robot-name '{robot_name}'")
+ else:
+ logger.error(" 2. If daemon uses --robot-name, add the same flag here: --robot-name ")
+
+ logger.error(" 3. For wireless: check network connectivity")
+ logger.error(" 4. Review daemon logs")
+ logger.error(" 5. Restart the daemon")
+
diff --git a/src/Reachy_OpenWebUI/vision/__init__.py b/src/Reachy_OpenWebUI/vision/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..92a27c9fbce1b3e04057d68e7e24ac5359c6a896
--- /dev/null
+++ b/src/Reachy_OpenWebUI/vision/__init__.py
@@ -0,0 +1 @@
+"""Vision utilities for local image analysis and head tracking."""
diff --git a/src/Reachy_OpenWebUI/vision/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/vision/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..247b86ba658e9fa6ebc6a64901990f485e4906d8
Binary files /dev/null and b/src/Reachy_OpenWebUI/vision/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/vision/__pycache__/local_vision.cpython-311.pyc b/src/Reachy_OpenWebUI/vision/__pycache__/local_vision.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fb6f27ec39fef086d526ffb9d66464a0631cea8b
Binary files /dev/null and b/src/Reachy_OpenWebUI/vision/__pycache__/local_vision.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/vision/head_tracking/__init__.py b/src/Reachy_OpenWebUI/vision/head_tracking/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..251e09c702645b7c66e21aa42beaf5c367bd906d
--- /dev/null
+++ b/src/Reachy_OpenWebUI/vision/head_tracking/__init__.py
@@ -0,0 +1,16 @@
+"""Head-tracking backends and process helpers."""
+
+from typing import Protocol, TypeAlias, SupportsFloat
+
+import numpy as np
+from numpy.typing import NDArray
+
+
+HeadTrackerResult: TypeAlias = tuple[NDArray[np.float32] | None, SupportsFloat | None]
+
+
+class HeadTracker(Protocol):
+ """Shared interface for optional head-tracking backends."""
+
+ def get_head_position(self, img: NDArray[np.uint8]) -> HeadTrackerResult:
+ """Return the detected head position for a frame."""
diff --git a/src/Reachy_OpenWebUI/vision/head_tracking/__pycache__/__init__.cpython-311.pyc b/src/Reachy_OpenWebUI/vision/head_tracking/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..54173585806878e77c99c57357a36ba07b2ea7a7
Binary files /dev/null and b/src/Reachy_OpenWebUI/vision/head_tracking/__pycache__/__init__.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/vision/head_tracking/__pycache__/mediapipe.cpython-311.pyc b/src/Reachy_OpenWebUI/vision/head_tracking/__pycache__/mediapipe.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dff99ca6c6138c98266833ef2250041677e67a31
Binary files /dev/null and b/src/Reachy_OpenWebUI/vision/head_tracking/__pycache__/mediapipe.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/vision/head_tracking/__pycache__/yolo.cpython-311.pyc b/src/Reachy_OpenWebUI/vision/head_tracking/__pycache__/yolo.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2677a936fd3f99d0af3081b3c543e74d3e3a1e2b
Binary files /dev/null and b/src/Reachy_OpenWebUI/vision/head_tracking/__pycache__/yolo.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/vision/head_tracking/__pycache__/yolo_process.cpython-311.pyc b/src/Reachy_OpenWebUI/vision/head_tracking/__pycache__/yolo_process.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..abe315dd51ad6652cb39656739c0b99d8517c908
Binary files /dev/null and b/src/Reachy_OpenWebUI/vision/head_tracking/__pycache__/yolo_process.cpython-311.pyc differ
diff --git a/src/Reachy_OpenWebUI/vision/head_tracking/mediapipe.py b/src/Reachy_OpenWebUI/vision/head_tracking/mediapipe.py
new file mode 100644
index 0000000000000000000000000000000000000000..c34c553a46218215c5a50bfee1b2935a21e2abe3
--- /dev/null
+++ b/src/Reachy_OpenWebUI/vision/head_tracking/mediapipe.py
@@ -0,0 +1,20 @@
+"""MediaPipe head tracker backed by reachy_mini_toolbox."""
+
+import numpy as np
+from numpy.typing import NDArray
+
+from reachy_mini_conversation_app.vision.head_tracking import HeadTracker, HeadTrackerResult
+
+
+class MediapipeHeadTracker:
+ """MediaPipe head tracker provided by reachy_mini_toolbox."""
+
+ def __init__(self) -> None:
+ """Initialize the toolbox head tracker lazily."""
+ from reachy_mini_toolbox import vision
+
+ self._tracker: HeadTracker = vision.HeadTracker()
+
+ def get_head_position(self, img: NDArray[np.uint8]) -> HeadTrackerResult:
+ """Return the detected head position for a frame."""
+ return self._tracker.get_head_position(img)
diff --git a/src/Reachy_OpenWebUI/vision/head_tracking/yolo.py b/src/Reachy_OpenWebUI/vision/head_tracking/yolo.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6be30ef9513ed136fcdbbe3005d6adc6e4e137d
--- /dev/null
+++ b/src/Reachy_OpenWebUI/vision/head_tracking/yolo.py
@@ -0,0 +1,110 @@
+from __future__ import annotations
+import logging
+from typing import Protocol, cast
+from collections.abc import Sequence
+
+import numpy as np
+from numpy.typing import NDArray
+
+from reachy_mini_conversation_app.vision.head_tracking import HeadTrackerResult
+
+
+try:
+ from supervision import Detections
+ from ultralytics import YOLO # type: ignore[attr-defined]
+except ImportError as e:
+ raise ImportError(
+ "To use YOLO head tracker, please install the extra dependencies: pip install '.[yolo_vision]'",
+ ) from e
+from huggingface_hub import hf_hub_download
+
+
+logger = logging.getLogger(__name__)
+
+
+class _YoloModel(Protocol):
+ """Minimal YOLO model interface used by the head tracker."""
+
+ def __call__(self, source: NDArray[np.uint8], **kwargs: object) -> Sequence[object]: ...
+
+ def to(self, device: str) -> _YoloModel: ...
+
+
+class YoloHeadTracker:
+ """Lightweight head tracker using YOLO for face detection."""
+
+ def __init__(
+ self,
+ model_repo: str = "AdamCodd/YOLOv11n-face-detection",
+ model_filename: str = "model.pt",
+ confidence_threshold: float = 0.3,
+ device: str = "cpu",
+ ) -> None:
+ """Initialize YOLO-based head tracker."""
+ self.confidence_threshold = confidence_threshold
+
+ try:
+ model_path = hf_hub_download(repo_id=model_repo, filename=model_filename)
+ self.model = cast(_YoloModel, YOLO(model_path).to(device))
+ logger.info("YOLO face detection model loaded from %s", model_repo)
+ except Exception as e:
+ logger.error("Failed to load YOLO model: %s", e)
+ raise
+
+ def _select_best_face(self, detections: Detections) -> int | None:
+ """Select the best face based on confidence and area (largest face with highest confidence)."""
+ if detections.xyxy.shape[0] == 0:
+ return None
+
+ if detections.confidence is None:
+ return None
+
+ valid_mask = detections.confidence >= self.confidence_threshold
+ if not np.any(valid_mask):
+ return None
+
+ valid_indices = np.where(valid_mask)[0]
+ boxes = detections.xyxy[valid_indices]
+ areas = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
+
+ confidences = detections.confidence[valid_indices]
+ scores = confidences * 0.7 + (areas / np.max(areas)) * 0.3
+
+ best_idx = valid_indices[np.argmax(scores)]
+ return int(best_idx)
+
+ def _bbox_to_mp_coords(self, bbox: NDArray[np.float32], w: int, h: int) -> NDArray[np.float32]:
+ """Convert bounding box center to MediaPipe-style coordinates [-1, 1]."""
+ center_x = (bbox[0] + bbox[2]) / 2.0
+ center_y = (bbox[1] + bbox[3]) / 2.0
+
+ norm_x = (center_x / w) * 2.0 - 1.0
+ norm_y = (center_y / h) * 2.0 - 1.0
+
+ return np.array([norm_x, norm_y], dtype=np.float32)
+
+ def get_head_position(self, img: NDArray[np.uint8]) -> HeadTrackerResult:
+ """Get head position from face detection."""
+ h, w = img.shape[:2]
+
+ try:
+ results = self.model(img, verbose=False)
+ detections = Detections.from_ultralytics(results[0])
+
+ face_idx = self._select_best_face(detections)
+ if face_idx is None:
+ logger.debug("No face detected above confidence threshold")
+ return None, None
+
+ bbox = detections.xyxy[face_idx]
+
+ if detections.confidence is not None:
+ confidence = detections.confidence[face_idx]
+ logger.debug("Face detected with confidence: %.2f", confidence)
+
+ face_center = self._bbox_to_mp_coords(bbox, w, h)
+ return face_center, 0.0
+
+ except Exception as e:
+ logger.error("Error in head position detection: %s", e)
+ return None, None
diff --git a/src/Reachy_OpenWebUI/vision/head_tracking/yolo_process.py b/src/Reachy_OpenWebUI/vision/head_tracking/yolo_process.py
new file mode 100644
index 0000000000000000000000000000000000000000..6143e2825814cd611131eb63507e7b6c1915c29f
--- /dev/null
+++ b/src/Reachy_OpenWebUI/vision/head_tracking/yolo_process.py
@@ -0,0 +1,396 @@
+"""Run the optional YOLO head tracker in a dedicated subprocess."""
+
+from __future__ import annotations
+import os
+import sys
+import time
+import queue
+import atexit
+import pickle
+import struct
+import logging
+import threading
+import subprocess
+import importlib.util
+from typing import IO, TypeGuard
+from pathlib import Path
+
+import numpy as np
+from numpy.typing import NDArray
+
+from reachy_mini_conversation_app.vision.head_tracking import HeadTracker, HeadTrackerResult
+
+
+logger = logging.getLogger(__name__)
+
+_PROCESS_START_TIMEOUT = 20.0
+_REQUEST_TIMEOUT = 0.5
+_SHUTDOWN_TIMEOUT = 2.0
+_HEADER_STRUCT = struct.Struct("!I")
+
+
+def _build_tracker_backend() -> HeadTracker:
+ """Instantiate a concrete head-tracker backend."""
+ from reachy_mini_conversation_app.vision.head_tracking.yolo import YoloHeadTracker
+
+ return YoloHeadTracker()
+
+
+def _read_exact(stream: IO[bytes], size: int) -> bytes:
+ """Read exactly `size` bytes or raise EOFError."""
+ chunks = bytearray()
+ while len(chunks) < size:
+ chunk = stream.read(size - len(chunks))
+ if not chunk:
+ raise EOFError("Unexpected EOF while reading tracker message")
+ chunks.extend(chunk)
+ return bytes(chunks)
+
+
+def _send_message(stream: IO[bytes], payload: object) -> None:
+ """Serialize and write a single message."""
+ data = pickle.dumps(payload, protocol=pickle.HIGHEST_PROTOCOL)
+ stream.write(_HEADER_STRUCT.pack(len(data)))
+ stream.write(data)
+ stream.flush()
+
+
+def _receive_message(stream: IO[bytes]) -> object:
+ """Read and deserialize a single message."""
+ header = _read_exact(stream, _HEADER_STRUCT.size)
+ (size,) = _HEADER_STRUCT.unpack(header)
+ data = _read_exact(stream, size)
+ return pickle.loads(data)
+
+
+def _reader_loop(stream: IO[bytes], messages: queue.Queue[tuple[str, object | None]]) -> None:
+ """Read responses from the child process in the background."""
+ try:
+ while True:
+ payload = _receive_message(stream)
+ messages.put(("message", payload))
+ except EOFError:
+ messages.put(("eof", None))
+ except Exception as exc:
+ messages.put(("error", repr(exc)))
+
+
+def _worker_main() -> int:
+ """Run the tracker worker protocol."""
+ protocol_out = sys.stdout.buffer
+ sys.stdout = sys.stderr
+
+ try:
+ tracker = _build_tracker_backend()
+ _send_message(protocol_out, ("ready", None))
+ except Exception as exc:
+ _send_message(protocol_out, ("error", repr(exc)))
+ return 1
+
+ while True:
+ try:
+ message = _receive_message(sys.stdin.buffer)
+ except (EOFError, KeyboardInterrupt):
+ return 0
+
+ if not isinstance(message, tuple) or not message or not isinstance(message[0], str):
+ _send_message(protocol_out, ("error", -1, f"Invalid command: {message!r}"))
+ continue
+
+ command = message[0]
+ if command == "close":
+ return 0
+ if command != "frame" or len(message) != 3 or not isinstance(message[1], int):
+ _send_message(protocol_out, ("error", -1, f"Unknown command: {message!r}"))
+ continue
+
+ request_id = message[1]
+ payload = message[2]
+ try:
+ result = tracker.get_head_position(payload)
+ _send_message(protocol_out, ("result", request_id, result))
+ except Exception as exc:
+ _send_message(protocol_out, ("error", request_id, repr(exc)))
+
+
+def _is_tracker_result(payload: object) -> TypeGuard[HeadTrackerResult]:
+ """Return whether the payload matches a tracker result."""
+ if not isinstance(payload, tuple) or len(payload) != 2:
+ return False
+
+ eye_center, roll = payload
+ if eye_center is not None and not isinstance(eye_center, np.ndarray):
+ return False
+ if roll is not None and not isinstance(roll, (float, np.floating)):
+ return False
+ return True
+
+
+class YoloHeadTrackerProcess:
+ """Proxy that runs the optional YOLO head tracker out of process."""
+
+ def __init__(self, *, request_timeout: float = _REQUEST_TIMEOUT) -> None:
+ """Start the child process and wait until the tracker is ready."""
+ self.request_timeout = request_timeout
+ self._closed = False
+ self._send_lock = threading.Lock()
+ self._messages: queue.Queue[tuple[str, object | None]] = queue.Queue()
+ self._next_request_id = 0
+ self._timed_out_request_id: int | None = None
+ self._recovery_call_pending = False
+ self._tracker_name = "yolo"
+
+ module_path = "reachy_mini_conversation_app.vision.head_tracking.yolo_process"
+ env = os.environ.copy()
+ package_spec = importlib.util.find_spec("reachy_mini_conversation_app")
+ package_locations = None if package_spec is None else package_spec.submodule_search_locations
+ if not package_locations:
+ raise RuntimeError("Unable to determine the reachy_mini_conversation_app package path")
+ project_src = Path(next(iter(package_locations))).resolve().parent
+ existing_pythonpath = env.get("PYTHONPATH")
+ env["PYTHONPATH"] = (
+ str(project_src) if not existing_pythonpath else f"{project_src}{os.pathsep}{existing_pythonpath}"
+ )
+ env["PYTHONUNBUFFERED"] = "1"
+
+ self._process = subprocess.Popen(
+ [sys.executable, "-m", module_path],
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=None,
+ bufsize=0,
+ env=env,
+ start_new_session=True,
+ )
+
+ if self._process.stdin is None or self._process.stdout is None:
+ self.close()
+ raise RuntimeError("Failed to create pipes for yolo head tracker process")
+
+ self._stdin = self._process.stdin
+ self._stdout = self._process.stdout
+ self._reader = threading.Thread(
+ target=_reader_loop,
+ args=(self._stdout, self._messages),
+ daemon=True,
+ name="yolo-head-tracker-reader",
+ )
+ self._reader.start()
+ atexit.register(self.close)
+
+ message = self._wait_for_message(_PROCESS_START_TIMEOUT)
+ if not (isinstance(message, tuple) and len(message) == 2 and isinstance(message[0], str)):
+ self.close()
+ raise RuntimeError(f"yolo head tracker returned an invalid startup message: {message!r}")
+
+ status, payload = message
+ if status != "ready":
+ self.close()
+ raise RuntimeError(f"Failed to initialize yolo head tracker: {payload}")
+
+ def _wait_for_message(self, timeout: float | None = None) -> object | None:
+ """Return the next child-process message payload, or None if no queued payload is available."""
+ try:
+ if timeout is None:
+ event, payload = self._messages.get_nowait()
+ else:
+ event, payload = self._messages.get(timeout=timeout)
+ except queue.Empty as exc:
+ if timeout is None:
+ return None
+ raise TimeoutError(f"{self._tracker_name} head tracker timed out after {timeout:.2f}s") from exc
+
+ if event == "message":
+ return payload
+ if event == "eof":
+ raise RuntimeError(f"{self._tracker_name} head tracker exited unexpectedly")
+ raise RuntimeError(f"{self._tracker_name} head tracker reader failed: {payload}")
+
+ def _unpack_response(self, message: object) -> tuple[str, int, object]:
+ """Validate a tracker response and return its fields."""
+ if not (
+ isinstance(message, tuple)
+ and len(message) == 3
+ and isinstance(message[0], str)
+ and isinstance(message[1], int)
+ ):
+ raise RuntimeError(f"{self._tracker_name} head tracker returned an invalid response: {message!r}")
+
+ status, message_request_id, payload = message
+ return status, message_request_id, payload
+
+ def _wait_for_response(self, request_id: int, timeout: float) -> tuple[str, object]:
+ """Wait for the response matching the requested frame."""
+ deadline = time.monotonic() + timeout
+ while True:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise TimeoutError(f"{self._tracker_name} head tracker timed out after {timeout:.2f}s")
+
+ wait_started = time.monotonic()
+ try:
+ message = self._wait_for_message(remaining)
+ except TimeoutError as exc:
+ raise TimeoutError(f"{self._tracker_name} head tracker timed out after {timeout:.2f}s") from exc
+ status, message_request_id, payload = self._unpack_response(message)
+ if message_request_id < request_id:
+ deadline += time.monotonic() - wait_started
+ logger.debug(
+ "Discarding stale reply from %s head tracker: expected request %s, got %s",
+ self._tracker_name,
+ request_id,
+ message_request_id,
+ )
+ continue
+
+ if time.monotonic() > deadline:
+ raise TimeoutError(f"{self._tracker_name} head tracker timed out after {timeout:.2f}s")
+
+ if message_request_id > request_id:
+ raise RuntimeError(
+ f"{self._tracker_name} head tracker returned out-of-order response "
+ f"{message_request_id} while waiting for {request_id}"
+ )
+
+ return status, payload
+
+ def _drain_timed_out_reply(self) -> bool:
+ """Return whether the last timed-out request has been consumed."""
+ if self._timed_out_request_id is None:
+ return True
+
+ while True:
+ message = self._wait_for_message()
+ if message is None:
+ return False
+
+ status, message_request_id, payload = self._unpack_response(message)
+ if message_request_id < self._timed_out_request_id:
+ logger.debug(
+ "Discarding stale reply from %s head tracker: expected request %s, got %s",
+ self._tracker_name,
+ self._timed_out_request_id,
+ message_request_id,
+ )
+ continue
+
+ if message_request_id > self._timed_out_request_id:
+ raise RuntimeError(
+ f"{self._tracker_name} head tracker returned out-of-order response "
+ f"{message_request_id} while waiting for {self._timed_out_request_id}"
+ )
+
+ logger.debug(
+ "Discarding delayed %s reply from %s head tracker for request %s: %r",
+ status,
+ self._tracker_name,
+ message_request_id,
+ payload,
+ )
+ self._timed_out_request_id = None
+ return True
+
+ def get_head_position(
+ self,
+ frame: NDArray[np.uint8],
+ ) -> tuple[NDArray[np.float32] | None, float | None]:
+ """Return the detected head position from the child process."""
+ if self._closed:
+ return None, None
+
+ if self._process.poll() is not None:
+ logger.error("Head tracker process for %s is not alive", self._tracker_name)
+ return None, None
+
+ request_id: int | None = None
+ try:
+ with self._send_lock:
+ # Reserve the immediate next call after a timeout for recovery
+ # only. Later calls may drain a delayed reply and continue with
+ # a fresh request in the same turn.
+ if self._recovery_call_pending:
+ self._recovery_call_pending = False
+ self._drain_timed_out_reply()
+ return None, None
+ if self._timed_out_request_id is not None and not self._drain_timed_out_reply():
+ return None, None
+
+ request_id = self._next_request_id
+ self._next_request_id += 1
+ _send_message(self._stdin, ("frame", request_id, frame))
+ status, payload = self._wait_for_response(request_id, self.request_timeout)
+ except TimeoutError as exc:
+ if request_id is not None:
+ self._timed_out_request_id = request_id
+ self._recovery_call_pending = True
+ logger.warning("Head tracker %s communication timed out: %s", self._tracker_name, exc)
+ return None, None
+ except Exception as exc:
+ logger.error("Head tracker %s communication failed: %s", self._tracker_name, exc)
+ return None, None
+
+ if status == "result":
+ if _is_tracker_result(payload):
+ eye_center, roll = payload
+ return eye_center, None if roll is None else float(roll)
+
+ logger.error("%s head tracker returned an invalid result: %r", self._tracker_name, payload)
+ return None, None
+
+ logger.error("%s head tracker failed to process frame: %s", self._tracker_name, payload)
+ return None, None
+
+ def close(self) -> None:
+ """Stop the child process."""
+ if self._closed:
+ return
+
+ self._closed = True
+
+ try:
+ if self._process.poll() is None:
+ with self._send_lock:
+ _send_message(self._stdin, ("close", None))
+ except Exception:
+ pass
+
+ try:
+ self._stdin.close()
+ except Exception:
+ pass
+
+ try:
+ self._process.wait(timeout=_SHUTDOWN_TIMEOUT)
+ except subprocess.TimeoutExpired:
+ logger.warning("Force-terminating %s head tracker process", self._tracker_name)
+ self._process.terminate()
+ try:
+ self._process.wait(timeout=_SHUTDOWN_TIMEOUT)
+ except subprocess.TimeoutExpired:
+ logger.warning("Force-killing %s head tracker process", self._tracker_name)
+ self._process.kill()
+ self._process.wait()
+
+ try:
+ self._stdout.close()
+ except Exception:
+ pass
+
+ def __del__(self) -> None:
+ """Best-effort shutdown when the proxy is garbage-collected."""
+ self.close()
+
+
+def main() -> int:
+ """CLI entrypoint for the head-tracker worker process."""
+ if len(sys.argv) != 1:
+ print(
+ "usage: python -m reachy_mini_conversation_app.vision.head_tracking.yolo_process",
+ file=sys.stderr,
+ )
+ return 2
+ return _worker_main()
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/src/Reachy_OpenWebUI/vision/local_vision.py b/src/Reachy_OpenWebUI/vision/local_vision.py
new file mode 100644
index 0000000000000000000000000000000000000000..0754e636926d4745296b461167563429f02a9a18
--- /dev/null
+++ b/src/Reachy_OpenWebUI/vision/local_vision.py
@@ -0,0 +1,250 @@
+from __future__ import annotations
+import os
+import time
+import logging
+from typing import Any, Protocol, cast
+from dataclasses import dataclass
+from collections.abc import Mapping, Sequence
+
+import numpy as np
+import torch
+from PIL import Image
+from numpy.typing import NDArray
+from transformers import AutoProcessor, AutoModelForImageTextToText
+from huggingface_hub import snapshot_download
+
+from reachy_mini_conversation_app.config import config
+
+
+logger = logging.getLogger(__name__)
+
+LOCAL_VISION_RESPONSE_INSTRUCTIONS = (
+ "Respond to the request using only details that are clearly visible in the image. "
+ "Do not guess, infer hidden details, or invent missing information. "
+ "If the answer is not clearly visible, say exactly: I can't tell from this image. "
+ "Keep the answer short and factual."
+)
+
+
+class _VisionInputs(Mapping[str, object]):
+ """Tokenized processor inputs that can be moved to the inference device."""
+
+ def to(self, device: str) -> _VisionInputs:
+ """Move inputs to the selected inference device."""
+ raise NotImplementedError
+
+
+class _VisionTokenizer(Protocol):
+ """Tokenizer attributes used by generation."""
+
+ eos_token_id: int | None
+
+
+class _VisionProcessor(Protocol):
+ """Small interface required from the Hugging Face image-text processor."""
+
+ tokenizer: _VisionTokenizer
+
+ def apply_chat_template(
+ self,
+ conversation: object,
+ *,
+ add_generation_prompt: bool,
+ tokenize: bool,
+ return_dict: bool,
+ return_tensors: str,
+ ) -> _VisionInputs: ...
+
+ def batch_decode(self, sequences: object, *, skip_special_tokens: bool) -> list[str]: ...
+
+
+class _VisionModel(Protocol):
+ """Small interface required from the Hugging Face image-text model."""
+
+ def to(self, device: str) -> _VisionModel: ...
+
+ def eval(self) -> object: ...
+
+ def generate(self, **kwargs: object) -> Any: ...
+
+
+@dataclass
+class VisionConfig:
+ """Configuration for vision processing."""
+
+ model_path: str = config.LOCAL_VISION_MODEL
+ max_new_tokens: int = 64
+ max_retries: int = 3
+ retry_delay: float = 1.0
+ device_preference: str = "auto" # "auto", "cuda", "mps", "cpu"
+
+
+class VisionProcessor:
+ """Handles SmolVLM2 model loading and inference."""
+
+ def __init__(self, vision_config: VisionConfig | None = None):
+ """Initialize the vision processor."""
+ self.vision_config = vision_config or VisionConfig()
+ self.device = self._determine_device()
+ self.processor: _VisionProcessor | None = None
+ self.model: _VisionModel | None = None
+ self._initialized = False
+
+ def _determine_device(self) -> str:
+ """Choose the execution device from the configured preference."""
+ pref = self.vision_config.device_preference
+ if pref == "cpu":
+ return "cpu"
+ if pref == "cuda":
+ return "cuda" if torch.cuda.is_available() else "cpu"
+ if pref == "mps":
+ return "mps" if torch.backends.mps.is_available() else "cpu"
+ # auto: prefer mps on Apple, then cuda, else cpu
+ if torch.backends.mps.is_available():
+ return "mps"
+ return "cuda" if torch.cuda.is_available() else "cpu"
+
+ def initialize(self) -> None:
+ """Load model and processor onto the selected device."""
+ logger.info("Loading SmolVLM2 model on %s (HF_HOME=%s)", self.device, config.HF_HOME)
+ processor = cast(
+ _VisionProcessor,
+ AutoProcessor.from_pretrained(self.vision_config.model_path), # type: ignore[no-untyped-call]
+ )
+
+ model_kwargs: dict[str, object] = {
+ "dtype": torch.bfloat16 if self.device == "cuda" else torch.float32,
+ }
+
+ model = cast(
+ _VisionModel,
+ AutoModelForImageTextToText.from_pretrained(
+ self.vision_config.model_path,
+ **model_kwargs,
+ ),
+ )
+ model = model.to(self.device)
+
+ model.eval()
+ self.processor = processor
+ self.model = model
+ self._initialized = True
+
+ def process_image(
+ self,
+ frame: NDArray[np.uint8],
+ prompt: str,
+ ) -> str:
+ """Process a BGR camera frame and return a text description."""
+ prompt_text = prompt.strip()
+ if not prompt_text:
+ raise ValueError("prompt must be a non-empty string")
+
+ if not self._initialized or self.processor is None or self.model is None:
+ return "Vision model not initialized"
+
+ processor = self.processor
+ model = self.model
+ rgb_image = Image.fromarray(np.ascontiguousarray(frame[..., ::-1]))
+ request_parts = [LOCAL_VISION_RESPONSE_INSTRUCTIONS]
+ request_parts.insert(0, prompt_text)
+ request = "\n\n".join(request_parts)
+
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "image", "image": rgb_image},
+ {"type": "text", "text": request},
+ ],
+ },
+ ]
+
+ for attempt in range(self.vision_config.max_retries):
+ try:
+ inputs = processor.apply_chat_template(
+ messages,
+ add_generation_prompt=True,
+ tokenize=True,
+ return_dict=True,
+ return_tensors="pt",
+ )
+ inputs = inputs.to(self.device)
+ prompt_len = _last_shape_dim(inputs.get("input_ids"))
+
+ with torch.inference_mode():
+ generated_ids = model.generate(
+ **inputs,
+ do_sample=False,
+ max_new_tokens=self.vision_config.max_new_tokens,
+ pad_token_id=processor.tokenizer.eos_token_id,
+ )
+
+ # Decode only the newly generated tokens, skipping the prompt
+ if prompt_len is None:
+ new_token_ids = generated_ids
+ elif getattr(generated_ids, "shape", None) is not None:
+ new_token_ids = generated_ids[:, prompt_len:]
+ else:
+ new_token_ids = [token_ids[prompt_len:] for token_ids in generated_ids]
+ response = processor.batch_decode(
+ new_token_ids,
+ skip_special_tokens=True,
+ )[0]
+
+ return str(response).replace("\n", " ").strip()
+
+ except Exception as e:
+ oom_error = getattr(getattr(torch, "cuda", None), "OutOfMemoryError", None)
+ if isinstance(oom_error, type) and issubclass(oom_error, BaseException) and isinstance(e, oom_error):
+ logger.error(f"CUDA OOM on attempt {attempt + 1}: {e}")
+ if self.device == "cuda":
+ torch.cuda.empty_cache()
+ if attempt < self.vision_config.max_retries - 1:
+ time.sleep(self.vision_config.retry_delay * (attempt + 1))
+ continue
+ return "GPU out of memory - vision processing failed"
+
+ logger.error("Vision processing failed (attempt %s): %s", attempt + 1, e)
+ if attempt < self.vision_config.max_retries - 1:
+ time.sleep(self.vision_config.retry_delay)
+ else:
+ return f"Vision processing error after {self.vision_config.max_retries} attempts"
+
+ return f"Vision processing error after {self.vision_config.max_retries} attempts"
+
+
+def _last_shape_dim(value: object) -> int | None:
+ """Return the last dimension from tensor-like objects that expose a shape."""
+ shape = getattr(value, "shape", None)
+ if not isinstance(shape, Sequence) or not shape:
+ return None
+ return int(shape[-1])
+
+
+def initialize_vision_processor() -> VisionProcessor:
+ """Download the vision model and return an initialized VisionProcessor."""
+ try:
+ model_id = config.LOCAL_VISION_MODEL
+ cache_dir = os.path.expanduser(config.HF_HOME)
+
+ os.makedirs(cache_dir, exist_ok=True)
+ os.environ["HF_HOME"] = cache_dir
+ logger.info("HF_HOME set to %s", cache_dir)
+
+ logger.info("Downloading vision model %s to cache...", model_id)
+ snapshot_download(repo_id=model_id, repo_type="model", cache_dir=cache_dir)
+
+ vision_processor = VisionProcessor()
+ vision_processor.initialize()
+
+ logger.info(
+ "Vision processing enabled: %s on %s",
+ vision_processor.vision_config.model_path,
+ vision_processor.device,
+ )
+
+ return vision_processor
+ except Exception:
+ logger.exception("Failed to initialize vision processor")
+ raise
diff --git a/src/reachy_talk_data/__init__.py b/src/reachy_talk_data/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..75b2f5e71e635e581b770d7dc1640ea0e154be83
--- /dev/null
+++ b/src/reachy_talk_data/__init__.py
@@ -0,0 +1 @@
+"""Packaged data for the Reachy Mini conversation app."""
diff --git a/src/reachy_talk_data/__pycache__/__init__.cpython-311.pyc b/src/reachy_talk_data/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..94a23b393a5c29698a64e70dc80cbf39c1c1001f
Binary files /dev/null and b/src/reachy_talk_data/__pycache__/__init__.cpython-311.pyc differ
diff --git a/style.css b/style.css
index 114adf441e9032febb46bc056b2a8bb651075f0d..c948c45e691ca9ccd613a5e514b5033ee69aad55 100644
--- a/style.css
+++ b/style.css
@@ -1,28 +1,386 @@
-body {
- padding: 2rem;
- font-family: -apple-system, BlinkMacSystemFont, "Arial", sans-serif;
-}
-
-h1 {
- font-size: 16px;
- margin-top: 0;
-}
-
-p {
- color: rgb(107, 114, 128);
- font-size: 15px;
- margin-bottom: 10px;
- margin-top: 5px;
-}
-
-.card {
- max-width: 620px;
- margin: 0 auto;
- padding: 16px;
- border: 1px solid lightgray;
- border-radius: 16px;
-}
-
-.card p:last-child {
- margin-bottom: 0;
-}
+:root {
+ --bg: #060c1d;
+ --panel: #0c172b;
+ --glass: rgba(17, 27, 48, 0.7);
+ --card: rgba(255, 255, 255, 0.04);
+ --accent: #7af5c4;
+ --accent-2: #f6c452;
+ --text: #e8edf7;
+ --muted: #9fb3ce;
+ --border: rgba(255, 255, 255, 0.08);
+ --shadow: 0 25px 70px rgba(0, 0, 0, 0.45);
+ font-family: "Space Grotesk", "Manrope", system-ui, -apple-system, sans-serif;
+}
+
+* {
+ margin: 0;
+ padding: 0;
+ box-sizing: border-box;
+}
+
+body {
+ background: radial-gradient(circle at 20% 20%, rgba(122, 245, 196, 0.12), transparent 30%),
+ radial-gradient(circle at 80% 0%, rgba(246, 196, 82, 0.14), transparent 32%),
+ radial-gradient(circle at 50% 70%, rgba(124, 142, 255, 0.1), transparent 30%),
+ var(--bg);
+ color: var(--text);
+ min-height: 100vh;
+ line-height: 1.6;
+ padding-bottom: 3rem;
+}
+
+a {
+ color: inherit;
+ text-decoration: none;
+}
+
+.hero {
+ padding: 3.5rem clamp(1.5rem, 3vw, 3rem) 2.5rem;
+ position: relative;
+ overflow: hidden;
+}
+
+.hero::after {
+ content: "";
+ position: absolute;
+ inset: 0;
+ background: linear-gradient(120deg, rgba(122, 245, 196, 0.12), rgba(246, 196, 82, 0.08), transparent);
+ pointer-events: none;
+}
+
+.topline {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ max-width: 1200px;
+ margin: 0 auto 2rem;
+ position: relative;
+ z-index: 2;
+}
+
+.brand {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ font-weight: 700;
+ letter-spacing: 0.5px;
+ color: var(--text);
+}
+
+.logo {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 2.2rem;
+ height: 2.2rem;
+ border-radius: 10px;
+ background: linear-gradient(145deg, rgba(122, 245, 196, 0.15), rgba(124, 142, 255, 0.15));
+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.25);
+}
+
+.brand-name {
+ font-size: 1.1rem;
+}
+
+.pill {
+ background: rgba(255, 255, 255, 0.06);
+ border: 1px solid var(--border);
+ padding: 0.6rem 1rem;
+ border-radius: 999px;
+ color: var(--muted);
+ font-size: 0.9rem;
+ box-shadow: 0 12px 30px rgba(0, 0, 0, 0.2);
+}
+
+.hero-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
+ gap: clamp(1.5rem, 2.5vw, 2.5rem);
+ max-width: 1200px;
+ margin: 0 auto;
+ position: relative;
+ z-index: 2;
+ align-items: center;
+}
+
+.hero-copy h1 {
+ font-size: clamp(2.6rem, 4vw, 3.6rem);
+ margin-bottom: 1rem;
+ line-height: 1.1;
+ letter-spacing: -0.5px;
+}
+
+.eyebrow {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.5rem;
+ text-transform: uppercase;
+ letter-spacing: 1px;
+ font-size: 0.8rem;
+ color: var(--muted);
+ margin-bottom: 0.75rem;
+}
+
+.eyebrow::before {
+ content: "";
+ display: inline-block;
+ width: 24px;
+ height: 2px;
+ background: linear-gradient(90deg, var(--accent), var(--accent-2));
+ border-radius: 999px;
+}
+
+.lede {
+ font-size: 1.1rem;
+ color: var(--muted);
+ max-width: 620px;
+}
+
+.hero-actions {
+ display: flex;
+ gap: 1rem;
+ align-items: center;
+ margin: 1.6rem 0 1.2rem;
+ flex-wrap: wrap;
+}
+
+.btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 0.6rem;
+ padding: 0.85rem 1.4rem;
+ border-radius: 12px;
+ font-weight: 700;
+ border: 1px solid transparent;
+ cursor: pointer;
+ transition: transform 0.2s ease, box-shadow 0.2s ease, background 0.2s ease, border-color 0.2s ease;
+}
+
+.btn.primary {
+ background: linear-gradient(135deg, #7af5c4, #7c8eff);
+ color: #0a0f1f;
+ box-shadow: 0 15px 30px rgba(122, 245, 196, 0.25);
+}
+
+.btn.primary:hover {
+ transform: translateY(-2px);
+ box-shadow: 0 25px 45px rgba(122, 245, 196, 0.35);
+}
+
+.btn.ghost {
+ background: rgba(255, 255, 255, 0.05);
+ border-color: var(--border);
+ color: var(--text);
+}
+
+.btn.ghost:hover {
+ border-color: rgba(255, 255, 255, 0.3);
+ transform: translateY(-2px);
+}
+
+.btn.wide {
+ width: 100%;
+ justify-content: center;
+}
+
+.hero-badges {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.6rem;
+ color: var(--muted);
+ font-size: 0.9rem;
+}
+
+.hero-badges span {
+ padding: 0.5rem 0.8rem;
+ border-radius: 10px;
+ border: 1px solid var(--border);
+ background: rgba(255, 255, 255, 0.04);
+}
+
+.hero-visual .glass-card {
+ background: rgba(255, 255, 255, 0.03);
+ border: 1px solid var(--border);
+ border-radius: 18px;
+ padding: 1.2rem;
+ box-shadow: var(--shadow);
+ backdrop-filter: blur(10px);
+}
+
+.hero-gif {
+ width: 100%;
+ display: block;
+ border-radius: 14px;
+ border: 1px solid var(--border);
+ box-shadow: 0 12px 35px rgba(0, 0, 0, 0.35);
+}
+
+.caption {
+ margin-top: 0.75rem;
+ color: var(--muted);
+ font-size: 0.95rem;
+}
+
+.section {
+ max-width: 1200px;
+ margin: 0 auto;
+ padding: clamp(2rem, 4vw, 3.5rem) clamp(1.5rem, 3vw, 3rem);
+}
+
+.section-header {
+ text-align: center;
+ max-width: 780px;
+ margin: 0 auto 2rem;
+}
+
+.section-header h2 {
+ font-size: clamp(2rem, 3vw, 2.6rem);
+ margin-bottom: 0.5rem;
+}
+
+.intro {
+ color: var(--muted);
+ font-size: 1.05rem;
+}
+
+.feature-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
+ gap: 1rem;
+}
+
+.feature-card {
+ background: rgba(255, 255, 255, 0.03);
+ border: 1px solid var(--border);
+ border-radius: 16px;
+ padding: 1.25rem;
+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
+ transition: transform 0.2s ease, border-color 0.2s ease, box-shadow 0.2s ease;
+}
+
+.feature-card:hover {
+ transform: translateY(-4px);
+ border-color: rgba(122, 245, 196, 0.3);
+ box-shadow: 0 18px 40px rgba(0, 0, 0, 0.3);
+}
+
+.feature-card .icon {
+ width: 48px;
+ height: 48px;
+ border-radius: 12px;
+ display: grid;
+ place-items: center;
+ background: rgba(122, 245, 196, 0.14);
+ margin-bottom: 0.8rem;
+ font-size: 1.4rem;
+}
+
+.feature-card h3 {
+ margin-bottom: 0.35rem;
+}
+
+.feature-card p {
+ color: var(--muted);
+}
+
+.story {
+ padding-top: 1rem;
+}
+
+.story-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
+ gap: 1rem;
+}
+
+.story-card {
+ background: rgba(255, 255, 255, 0.03);
+ border: 1px solid var(--border);
+ border-radius: 18px;
+ padding: 1.5rem;
+ box-shadow: var(--shadow);
+}
+
+.story-card.secondary {
+ background: linear-gradient(145deg, rgba(124, 142, 255, 0.08), rgba(122, 245, 196, 0.06));
+}
+
+.story-card h3 {
+ margin-bottom: 0.8rem;
+}
+
+.story-list {
+ list-style: none;
+ display: grid;
+ gap: 0.7rem;
+ color: var(--muted);
+ font-size: 0.98rem;
+}
+
+.story-list li {
+ display: flex;
+ gap: 0.7rem;
+ align-items: flex-start;
+}
+
+.story-text {
+ color: var(--muted);
+ line-height: 1.7;
+ margin-bottom: 1rem;
+}
+
+.chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.5rem;
+}
+
+.chip {
+ padding: 0.45rem 0.8rem;
+ border-radius: 12px;
+ background: rgba(0, 0, 0, 0.2);
+ border: 1px solid var(--border);
+ color: var(--text);
+ font-size: 0.9rem;
+}
+
+.footer {
+ text-align: center;
+ color: var(--muted);
+ padding: 2rem 1.5rem 0;
+}
+
+.footer a {
+ color: var(--text);
+ border-bottom: 1px solid transparent;
+}
+
+.footer a:hover {
+ border-color: rgba(255, 255, 255, 0.5);
+}
+
+@media (max-width: 768px) {
+ .hero {
+ padding-top: 2.5rem;
+ }
+
+ .topline {
+ flex-direction: column;
+ gap: 0.8rem;
+ align-items: flex-start;
+ }
+
+ .hero-actions {
+ width: 100%;
+ }
+
+ .btn {
+ width: 100%;
+ justify-content: center;
+ }
+
+ .hero-badges {
+ gap: 0.4rem;
+ }
+}