diff --git a/.env.example b/.env.example index be2f9ef..9b5fd8c 100644 --- a/.env.example +++ b/.env.example @@ -27,6 +27,12 @@ LAZYBOY_COMPUTER_DRIVER=cua # Linux only (optional): point this at the host's LXCFS root to make htop/free # report the per-Agent cgroup quota. Leave the default empty directory on macOS. LAZYBOY_LXCFS_ROOT=./data/lxcfs +# 群組聊天「誰該回應」:沒被 @ 的時候,由一次短短的模型問從成員的工作內容與簡介裡 +# 挑出最多三個人回覆。留空(預設)=沿用空間的預設模型,多數人不用理這行; +# 想省 token 就填一個便宜快速的 model id(要跟空間預設來自同一家 provider)。 +# 挑不到人、模型不能用、或超過 1.2 秒,一律由主持人(群組第一位成員)收場。 +LAZYBOY_ROUTER_MODEL= + # 任務長度政策:不再用固定輪數掐掉任務。正常任務一路做到驗證完成,只有 # 真的鬼打牆(同一個動作重複、同一個錯誤一直失敗、很久沒有新的成功)才會被 # 提示、接著暫停等你決定;最後兩個是防迴圈失控烧 token 的保險絲,不是額度。 diff --git a/README.md b/README.md index 45e189a..bb43f0a 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ A self-hosted AI agent workspace. Assign tasks in text or voice, watch the deskt -![LazyBoy workspace: agent list, chat, and live desktop](./docs/readme-hero.png) +![LazyBoy group chat routing one message to a single agent, with that agent's live desktop on the right](./docs/readme-hero.png) LazyBoy gives each agent its own Linux desktop in Docker — browser, terminal, and files. You can run several agents, put them in a group, turn a demonstration into a skill, and schedule it to run again. @@ -24,8 +24,10 @@ This is an early `0.1.0` release with desktop and phone browser UIs. You bring y - **A lasting workspace**: each agent has its own chats, run history, and optional long-term memory. - **A real computer**: open pages, use the terminal, organize files, drive the GUI — and watch it live. +- **Attachments in chat**: send files or images along with the message; the agent can open them on its own desktop, and inbox copies expire on their own. - **Take over any time**: sign in, pass a check, or nudge things by hand on the same desktop, then hand it back. -- **Several agents and groups**: shared Team computers or private dedicated desktops. +- **Saved logins**: keep site credentials in the agent's encrypted vault, so it can fill them in at a login wall without the password ever passing through the model. +- **Several agents and groups**: shared Team computers or private dedicated desktops; `@name` decides who answers, so a message wakes the one agent it is for instead of all of them. - **Teach by demo, then schedule**: turn a walkthrough into a skill; use cron for repeat work. - **Your models and tools**: xAI, OpenCode Go, OpenAI-compatible endpoints, MCP, and file skills. - **Voice calls**: after you enable a voice provider, you can talk to the agent on a call. @@ -69,7 +71,7 @@ For resource limits, environment variables, HTTPS, and in-container sudo, see [O ## On a phone -Desktop and phone share the same web UI. After you deploy on a host the phone can reach, open that URL in the phone browser. `127.0.0.1` is the phone itself — it will not reach another machine. +Desktop and phone share the same web UI. The API listens on `127.0.0.1` by default, so set `LAZYBOY_BIND_IP=0.0.0.0` (or one network card's address) in `.env` and recreate the api container before a phone on your network can reach it; off-loopback the login token has to be at least 32 characters. Then open that address in the phone browser — `127.0.0.1` there is the phone itself and will not reach another machine. Tap outside the chat sidebar to collapse it. On the remote desktop you can switch between tap-to-click and trackpad, and use the toolbar for keyboard, right-click, or drag. Put the service behind HTTPS before you expose it; see [Operations](./docs/operations.md#安全模型). @@ -79,7 +81,7 @@ Tap outside the chat sidebar to collapse it. On the remote desktop you can switc - **Backend**: Rust 2024, Axum, Tokio - **Data**: PostgreSQL, pgvector, SQLx - **Desktop**: Docker, Debian, XFCE, Chromium, Xvfb -- **Computer control**: CDP, AT-SPI, X11 +- **Computer control**: Cua Driver over X11, AT-SPI, and Chromium - **Extensions**: MCP, file skills, demonstration playbooks Flow diagrams, handoff, component roles, and the computer lifecycle live in **[Architecture](./docs/architecture.md)**. The older **[interactive diagram](./docs/workflow.html)** is still there — download it and open it in a browser. @@ -108,30 +110,59 @@ Open [http://127.0.0.1:5173](http://127.0.0.1:5173). Tests and the tree layout a The guides below are currently in Traditional Chinese. -| Doc | Contents | -| --- | --- | -| [Architecture](./docs/architecture.md) | Task flow, system architecture, computer lifecycle | -| [Interactive diagram](./docs/workflow.html) | Zoomable, searchable HTML chart; download and open | -| [Operations](./docs/operations.md) | Resources, env vars, security, site checks, sudo | -| [Agent experience](./docs/agent-experience.md) | Turn limits, persistent terminal, live chat | +| Doc | Contents | +| -------------------------------------------------------- | ---------------------------------------------------- | +| [Architecture](./docs/architecture.md) | Task flow, system architecture, computer lifecycle | +| [Interactive diagram](./docs/workflow.html) | Zoomable, searchable HTML chart; download and open | +| [Operations](./docs/operations.md) | Resources, env vars, security, site checks, sudo | +| [Agent experience](./docs/agent-experience.md) | Turn limits, persistent terminal, live chat | | [hermes-agent review](./docs/hermes-agent-cua-review.md) | Cua harness smoothness: comparison with hermes-agent | -| [Development](./docs/development.md) | Local dev, checks and tests, directory layout | -| [Env example](./.env.example) | Environment variables and defaults | +| [Development](./docs/development.md) | Local dev, checks and tests, directory layout | +| [Env example](./.env.example) | Environment variables and defaults | ## Data Chats, memory, browser profiles, and encrypted credentials stay on your host. When you use an external model, the prompts, tool results, and screenshots the task needs may still be sent to that provider. +## Acknowledgements + +LazyBoy is mostly other people's software, carefully assembled. The projects we lean on hardest: + +**Special thanks** + +- **[Cua](https://github.com/trycua/cua)** — the Linux desktop driver behind every click, keystroke, and screenshot. We rebuild `cua-driver-rs` v0.23.2 from source with two small patches kept in this repo: one lets the agent cursor wear the bot's own colour, the other swaps the embedded Latin-only badge font for [jf open Huninn](https://github.com/justfont/open-huninn-font) so Chinese renders. Neither patch touches input handling or permissions. +- **[hermes-agent](https://github.com/NousResearch/hermes-agent)** — not a dependency, but the reference we kept returning to while tuning how smooth an agent's desktop should feel. The comparison is written up in the [hermes-agent review](./docs/hermes-agent-cua-review.md). + +**Agents and retrieval** — [rig](https://github.com/0xPlaygrounds/rig) · [rmcp](https://github.com/modelcontextprotocol/rust-sdk) · [fastembed-rs](https://github.com/Anush008/fastembed-rs) and [ONNX Runtime](https://github.com/microsoft/onnxruntime), running [paraphrase-multilingual-MiniLM-L12-v2](https://huggingface.co/sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2) + +**Rust** — Tokio · Axum · tower-http · SQLx · reqwest · rustls · Bollard · tracing · aes-gcm and hmac from [RustCrypto](https://github.com/RustCrypto) · cap-std · cron · chrono · uuid · thiserror · dotenvy + +**Web** — React · Vite · TypeScript · [noVNC](https://github.com/novnc/noVNC) · react-markdown with [remark-gfm](https://github.com/remarkjs/remark-gfm) and [remark-breaks](https://github.com/remarkjs/remark-breaks) · [Blobatar](https://github.com/Alain00/blobatar) avatars · [react-useanimations](https://github.com/useAnimations/react-useanimations) icons + +**Data** — [PostgreSQL](https://www.postgresql.org) · [pgvector](https://github.com/pgvector/pgvector) + +**The desktop inside each container** — [Docker](https://www.docker.com) · [Debian](https://www.debian.org) · [XFCE](https://www.xfce.org) · [Chromium](https://www.chromium.org) · [Xvfb](https://www.x.org) · Thunar · [x11vnc](https://github.com/LibVNC/x11vnc) · [websockify](https://github.com/novnc/websockify) · [AT-SPI2](https://gitlab.gnome.org/GNOME/at-spi2-core) · [gosu](https://github.com/tianon/gosu) · [LXCFS](https://github.com/lxc/lxcfs) · git · zsh with [Powerlevel10k](https://github.com/romkatv/powerlevel10k) · htop + +**Type and theme** — [jf open Huninn](https://github.com/justfont/open-huninn-font) (SIL OFL) in the UI and on the agent badge · [Noto CJK](https://github.com/notofonts/noto-cjk), DejaVu, and Liberation as fallbacks · [MesloLGS NF](https://github.com/romkatv/powerlevel10k-media) in the terminal · [Arc Dark](https://github.com/horst3180/arc-theme) and [Papirus](https://github.com/PapirusDevelopmentTeam/papirus-icon-theme) for the look of the room + +Every version above is pinned in `Cargo.lock`, `apps/web/package.json`, and `image/computer/Dockerfile`. LazyBoy is Apache-2.0; each project keeps its own license. Thanks also to the maintainers whose names never make it into a README, and to everyone who files a good bug report. + ---
+LazyBoy + +**LazyBoy is free and open source.** If it hands you back an afternoon, a coffee is the nicest way to say so. + +Buy Me a Coffee + +Apache License 2.0 +Release 0.1.0 +Rust and React + **Daniel Wang** Taiwan -[igs170911@gmail.com](mailto:igs170911@gmail.com) - -Buy Me a Coffee - -[Apache License 2.0](./LICENSE) +[igs170911@gmail.com](mailto:igs170911@gmail.com) · [Apache License 2.0](./LICENSE)
diff --git a/README.zh-TW.md b/README.zh-TW.md index b79e244..4054d5f 100644 --- a/README.zh-TW.md +++ b/README.zh-TW.md @@ -14,7 +14,7 @@ -![LazyBoy 工作空間:Agent 清單、對話與即時桌面](./docs/readme-hero.png) +![LazyBoy 群組對話:訊息由其中一個 Agent 接手回覆,右側是它自己的即時桌面](./docs/readme-hero.zh-TW.png) LazyBoy 讓 Agent 在 Docker 裡使用自己的 Linux 桌面,操作瀏覽器、終端與檔案。你可以建立不同的 Agent、在群組中協作,把示範整理成技能,再安排定時執行。 @@ -24,8 +24,10 @@ LazyBoy 讓 Agent 在 Docker 裡使用自己的 Linux 桌面,操作瀏覽器 - **持續的工作空間**:每個 Agent 有自己的對話、工作紀錄與可設定的長期記憶。 - **真的能操作電腦**:開網頁、使用終端、整理檔案、操作圖形介面,過程可即時觀看。 +- **附件直接丟進對話**:訊息可帶檔案或圖片,Agent 能在自己的桌面開啟,放在收件匣的複本會自動到期清除。 - **隨時人工接管**:在同一個桌面完成登入、驗證或手動調整,再交回 Agent。 -- **多 Agent 與群組**:支援 Team 共用電腦與 Private 獨立電腦模式。 +- **登入帳密進保險庫**:帳密加密存在 Agent 自己的保險庫,遇到登入頁由它填寫,密碼不會經過模型。 +- **多 Agent 與群組**:支援 Team 共用電腦與 Private 獨立電腦模式;群組裡 @誰就由誰回,沒點名時只叫醒工作內容相關的那個,不會全部出動。 - **示範教學與排程**:把操作示範整理成技能,使用 cron 安排重複工作。 - **自選模型與工具**:支援 xAI、OpenCode Go、OpenAI 相容端點,以及 MCP 與檔案技能。 - **語音通話**:設定語音服務後,可以透過通話與 Agent 互動。 @@ -69,7 +71,7 @@ make down # 停止服務,保留 PostgreSQL 資料 ## 在手機上使用 -手機與桌面使用同一個 Web 介面。將服務部署在可連線的主機後,用手機瀏覽器開啟該服務的網址即可;`127.0.0.1` 只代表手機本身,不能拿來連另一台電腦。 +手機與桌面使用同一個 Web 介面。API 預設只綁 `127.0.0.1`,請在 `.env` 設定 `LAZYBOY_BIND_IP=0.0.0.0`(或指定網卡位址)並重建 api 容器,區網裡的手機才連得到;綁非 loopback 時登入 token 需至少 32 字元。接著用手機瀏覽器開啟該位址——手機上的 `127.0.0.1` 只代表手機本身,不能拿來連另一台電腦。 聊天側欄可點外側空白處收合。操作遠端桌面時,可切換直接點選與觸控板模式,使用工具列叫出鍵盤、按右鍵或拖曳。對外提供服務時請設定 HTTPS,詳見 [部署指南](./docs/operations.md#安全模型)。 @@ -79,7 +81,7 @@ make down # 停止服務,保留 PostgreSQL 資料 - **後端**:Rust 2024、Axum、Tokio - **資料**:PostgreSQL、pgvector、SQLx - **桌面**:Docker、Debian、XFCE、Chromium、Xvfb -- **電腦控制**:CDP、AT-SPI、X11 +- **電腦控制**:Cua Driver(X11、AT-SPI、Chromium) - **擴充**:MCP、檔案技能、示範 playbook 流程圖、控制權交接、元件職責與電腦生命週期狀態機,集中在 **[架構與流程](./docs/architecture.md)**。原有的 **[互動流程圖](./docs/workflow.html)** 也保留;下載後用瀏覽器開啟即可操作。 @@ -112,6 +114,7 @@ npm run dev | [互動流程圖](./docs/workflow.html) | 可縮放、搜尋的 HTML 圖表;下載後開啟 | | [部署與操作](./docs/operations.md) | 資源、環境變數、安全設定、網站驗證、sudo | | [AI 使用體驗](./docs/agent-experience.md) | 輪次政策、持久終端機、聊天即時推送 | +| [hermes-agent 比較](./docs/hermes-agent-cua-review.md) | Cua 操作流暢度:與 hermes-agent 對照 | | [開發指南](./docs/development.md) | 本機開發、檢查與測試、目錄結構 | | [設定範例](./.env.example) | 環境變數與預設值 | @@ -119,16 +122,45 @@ npm run dev 對話、記憶、瀏覽器設定檔與加密憑證保存在自架主機。使用外部模型時,任務所需的提示詞、工具結果與截圖仍可能傳送給該模型供應商。 +## 特別感謝 + +LazyBoy 站在許多開源專案的肩上,下面是我們用到最多、也最想致謝的專案。 + +**首要致謝** + +- **[Cua](https://github.com/trycua/cua)**:每一次點擊、鍵盤輸入與截圖,都由它的 Linux 桌面驅動完成。我們從原始碼重建 `cua-driver-rs` v0.23.2,並在本專案內維護兩處小修補:一處讓 Agent 游標套用機器人自己的顏色,另一處把內嵌的純英文徽章字型換成 [jf open Huninn](https://github.com/justfont/open-huninn-font),讓中文能正確顯示。兩處修補都不碰輸入處理與權限邏輯。 +- **[hermes-agent](https://github.com/NousResearch/hermes-agent)**:它不是相依套件,卻是我們調整操作流暢度時一再回頭參照的對象。對照分析見 [hermes-agent 比較](./docs/hermes-agent-cua-review.md)。 + +**Agent 與記憶檢索**:[rig](https://github.com/0xPlaygrounds/rig) · [rmcp](https://github.com/modelcontextprotocol/rust-sdk) · [fastembed-rs](https://github.com/Anush008/fastembed-rs) 與 [ONNX Runtime](https://github.com/microsoft/onnxruntime),嵌入模型為 [paraphrase-multilingual-MiniLM-L12-v2](https://huggingface.co/sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2) + +**Rust**:Tokio · Axum · tower-http · SQLx · reqwest · rustls · Bollard · tracing · [RustCrypto](https://github.com/RustCrypto) 的 aes-gcm 與 hmac · cap-std · cron · chrono · uuid · thiserror · dotenvy + +**前端**:React · Vite · TypeScript · [noVNC](https://github.com/novnc/noVNC) · react-markdown 搭配 [remark-gfm](https://github.com/remarkjs/remark-gfm) 與 [remark-breaks](https://github.com/remarkjs/remark-breaks) · [Blobatar](https://github.com/Alain00/blobatar) 頭像 · [react-useanimations](https://github.com/useAnimations/react-useanimations) 圖示 + +**資料**:[PostgreSQL](https://www.postgresql.org) · [pgvector](https://github.com/pgvector/pgvector) + +**容器裡的桌面**:[Docker](https://www.docker.com) · [Debian](https://www.debian.org) · [XFCE](https://www.xfce.org) · [Chromium](https://www.chromium.org) · [Xvfb](https://www.x.org) · Thunar · [x11vnc](https://github.com/LibVNC/x11vnc) · [websockify](https://github.com/novnc/websockify) · [AT-SPI2](https://gitlab.gnome.org/GNOME/at-spi2-core) · [gosu](https://github.com/tianon/gosu) · [LXCFS](https://github.com/lxc/lxcfs) · git · 搭配 [Powerlevel10k](https://github.com/romkatv/powerlevel10k) 的 zsh · htop + +**字型與佈景主題**:介面與 Agent 徽章使用 [jf open Huninn](https://github.com/justfont/open-huninn-font)(SIL OFL)· 備援字型為 [Noto CJK](https://github.com/notofonts/noto-cjk)、DejaVu 與 Liberation · 終端機使用 [MesloLGS NF](https://github.com/romkatv/powerlevel10k-media) · 外觀採用 [Arc Dark](https://github.com/horst3180/arc-theme) 與 [Papirus](https://github.com/PapirusDevelopmentTeam/papirus-icon-theme) + +以上版本都釘選在 `Cargo.lock`、`apps/web/package.json` 與 `image/computer/Dockerfile`。LazyBoy 以 Apache-2.0 釋出,上述每個專案保留各自的授權條款。也謝謝那些名字從不出現在 README 裡的維護者,以及每一位認真回報問題的使用者。 + ---
+LazyBoy + +**LazyBoy 是免費的開源專案。** 如果它幫你省下一個下午,一杯咖啡是最好的回禮。 + +請我喝杯咖啡 + +Apache License 2.0 +Release 0.1.0 +Rust and React + **danielwang** Taiwan -[igs170911@gmail.com](mailto:igs170911@gmail.com) - -請我喝杯咖啡 - -[Apache License 2.0](./LICENSE) +[igs170911@gmail.com](mailto:igs170911@gmail.com) · [Apache License 2.0](./LICENSE)
diff --git a/a.md b/a.md deleted file mode 100644 index 0e0baa0..0000000 --- a/a.md +++ /dev/null @@ -1,2210 +0,0 @@ -# LazyBoy → Cua Driver Migration Plan - -> 2026-09-07 檢查:Phase 1 規格尚未全部勾完(生產預設仍是 legacy;takeover/錄製端到端未另開測)。opt-in Cua 已可在現有桌面容器使用,驗收見 [docs/cua-review.md](docs/cua-review.md)。本文件仍是目標規格,不能視為完成證明。 - -> **Purpose:** This document is an implementation specification for a coding agent. -> -> Repository: `https://code.30cm.net/daniel.w/lazyBoy` -> -> Cua: `https://github.com/trycua/cua` -> -> Cua docs: `https://cua.ai/docs` -> -> **Main principle:** Do **NOT** rewrite LazyBoy into Cua. Keep LazyBoy as the agent/workspace/product layer and replace the low-level computer-control implementation with Cua Driver incrementally. - ---- - -## 0. Agent Instructions - -You are modifying **LazyBoy**, a self-hosted AI agent workspace. - -The goal is to migrate the low-level GUI/browser computer-control implementation from custom CDP / AT-SPI / X11 code to **Cua Driver**, without breaking LazyBoy's existing product architecture. - -### Non-negotiable rules - -1. **Do not perform a Big Bang rewrite.** -2. **Do not remove the legacy computer-control implementation in the first PR.** -3. Keep LazyBoy's current public Agent tool schema stable unless absolutely necessary. -4. Keep: - - `computer_observe` - - `computer_act` - - `browser` - - `shell` - - file tools - - takeover flow - - memory - - schedule - - vault - - skills/playbooks -5. Cua must initially be an **implementation detail behind LazyBoy abstractions**. -6. Do not expose all Cua MCP tools directly to the LLM. -7. Do not replace `DockerSandbox`, `Supervisor`, noVNC, or persistent bot homes during Phase 1. -8. Add a feature flag / backend selector so legacy behavior can be restored immediately. -9. Every migrated action must have observable verification. -10. Do not guess Cua API/tool names from this document. - -### Cua API freshness rule - -Cua changes quickly. - -Before implementing anything: - -```bash -cua-driver --version -cua-driver doctor -cua-driver list-tools -``` - -For every Cua tool you plan to call: - -```bash -cua-driver describe -``` - -Use the schema reported by the installed Cua Driver version as the source of truth. - -Do not hard-code assumptions from old blog posts, old examples, or this document when the installed version differs. - ---- - -# 1. Current LazyBoy Architecture - -The current architecture is approximately: - -```text -User - │ - ▼ -React Web UI - │ - ▼ -crates/api - │ - ├── Agent loop - ├── Sessions / Runs - ├── Memory - ├── Schedule - ├── Vault - ├── Skills - ├── MCP - └── Tool definitions - │ - ▼ -SandboxProvider - │ - ▼ -crates/sandbox - │ - ▼ -DockerSandbox - │ - ▼ -crates/supervisor - │ - ▼ -Linux Desktop Container - │ - ├── XFCE - ├── Chromium - ├── Xvfb - ├── x11vnc - ├── websockify - └── controld - │ - ├── CDP - ├── AT-SPI - ├── X11 - └── screenshots -``` - -Relevant current components: - -```text -apps/web -crates/api -crates/contracts -crates/control -crates/controld -crates/harness -crates/sandbox -crates/supervisor -``` - -The existing `SandboxProvider` abstraction is an important migration seam and should be preserved. - -Current methods include approximately: - -```rust -async fn provision(...) -async fn prepare(...) -async fn capabilities(...) -async fn ensure_screen(...) -async fn reconnect(...) -async fn suspend(...) -async fn resume(...) -async fn execute(...) -async fn observe(...) -async fn act(...) -async fn connect_screen(...) -async fn list_files(...) -async fn read_file(...) -async fn write_file(...) -async fn stop(...) -async fn destroy(...) -``` - -Do not collapse this abstraction. - ---- - -# 2. Target Architecture - -Phase 1 target: - -```text - LazyBoy Web - │ - ▼ - LazyBoy API - │ - LazyBoy Agent Loop - │ - ┌────────────────┼────────────────┐ - │ │ │ - ▼ ▼ ▼ - Memory Skills Schedule - │ - ▼ - LazyBoy Tool Layer - │ - computer / browser / shell - │ - ▼ - ComputerController - abstraction - │ │ - ┌───────────┘ └────────────┐ - ▼ ▼ - LegacyController CuaController - │ │ - CDP / AT-SPI / X11 Cua Driver - │ - ┌──────────────┼──────────────┐ - ▼ ▼ ▼ - X11 AT-SPI Browser - │ - ▼ - Existing Desktop - Container -``` - -### Important - -Cua is initially used as the **computer-control backend**. - -It is **not** the Agent runtime. - -It is **not** the memory system. - -It is **not** the scheduler. - -It is **not** the user-facing product. - -It is **not** the first-phase sandbox lifecycle owner. - ---- - -# 3. What Must Stay in LazyBoy - -The following are LazyBoy product responsibilities and must remain owned by LazyBoy. - -## Keep unchanged unless required - -### Frontend - -```text -apps/web -``` - -Keep: - -- Chat UI -- remote desktop -- noVNC -- mobile controls -- takeover UI -- bot management -- session UI - -### API / Agent layer - -```text -crates/api -``` - -Keep: - -- Agent loop -- model interaction -- run management -- session management -- tool policy -- takeover workflow -- credential flow -- memory -- schedules -- skills -- MCP integrations - -### Harness - -```text -crates/harness -``` - -Keep model-provider support. - -Cua Driver must not decide which model LazyBoy uses. - -### Supervisor - -```text -crates/supervisor -``` - -Phase 1: keep current behavior. - -Keep: - -- Docker lifecycle -- pause/resume -- resource limits -- persisted bot homes -- screen lifecycle - -### Sandbox - -```text -crates/sandbox -``` - -Phase 1: keep `DockerSandbox`. - -Do **not** replace it with Cua Sandbox yet. - ---- - -# 4. What Cua Should Replace - -The long-term goal is to reduce LazyBoy-owned OS automation. - -Current files that are candidates for replacement or simplification: - -```text -crates/control/src/a11y.py -crates/control/src/a11y.rs - -crates/control/src/cdp.py -crates/control/src/cdp.rs - -crates/control/src/x11.rs -crates/control/src/screen.rs -crates/control/src/overlay.rs -``` - -Do not delete them during the initial migration. - -Instead place them behind a legacy backend. - -The responsibilities that should gradually move to Cua: - -- screenshots -- application/window enumeration -- accessibility tree -- native UI element actions -- pointer input -- keyboard input -- scrolling -- browser state -- browser semantic actions -- window-scoped control -- recording / trajectory capture - ---- - -# 5. Do NOT Expose Raw Cua to the LLM - -LazyBoy currently has a relatively compact Agent-facing tool surface. - -Preserve this. - -Preferred model: - -```text -LLM - │ - ▼ -LazyBoy tools - │ - ├── computer_observe - ├── computer_act - ├── browser - ├── shell - ├── file tools - └── request_takeover - │ - ▼ -LazyBoy policy / safety / vault / state - │ - ▼ -Cua adapter - │ - ▼ -Cua Driver -``` - -Avoid this: - -```text -LLM - │ - ▼ -50+ raw Cua tools - │ - ▼ -OS -``` - -Reasons: - -- larger tool schemas consume context -- LazyBoy loses policy control -- LazyBoy loses stable abstraction -- Cua version changes would leak into prompts -- takeover behavior becomes harder to control -- credential handling becomes harder to constrain -- Agent behavior becomes coupled to Cua implementation details - -Cua should initially behave like a device driver. - ---- - -# 6. Introduce a ComputerController Abstraction - -Create a low-level computer-control abstraction separate from sandbox lifecycle. - -Suggested location: - -```text -crates/control/src/controller.rs -``` - -Possible interface: - -```rust -#[async_trait::async_trait] -pub trait ComputerController: Send + Sync { - async fn health(&self, ctx: &ControlContext) - -> Result; - - async fn observe( - &self, - request: ObserveRequest, - ctx: &ControlContext, - ) -> Result; - - async fn act( - &self, - request: ActionRequest, - ctx: &ControlContext, - ) -> Result; - - async fn browser( - &self, - request: BrowserRequest, - ctx: &ControlContext, - ) -> Result; - - async fn start_recording( - &self, - request: RecordingRequest, - ctx: &ControlContext, - ) -> Result; - - async fn stop_recording( - &self, - ctx: &ControlContext, - ) -> Result; -} -``` - -Names may be adjusted to match existing LazyBoy contracts. - -Do not introduce unnecessary abstractions if equivalent types already exist. - ---- - -# 7. Backend Implementations - -Implement: - -```text -LegacyController -CuaController -``` - -Suggested layout: - -```text -crates/control/src/ -├── controller.rs -├── legacy/ -│ ├── mod.rs -│ ├── a11y.rs -│ ├── cdp.rs -│ ├── x11.rs -│ └── screen.rs -└── cua/ - ├── mod.rs - ├── client.rs - ├── translate.rs - ├── observe.rs - ├── actions.rs - ├── browser.rs - └── recording.rs -``` - -Do not spend the first PR moving all old files if it creates noisy diffs. - -It is acceptable to initially keep existing file locations and only add: - -```text -controller.rs -cua.rs -``` - -Refactor structure after behavior is stable. - ---- - -# 8. Backend Configuration - -Add a configuration value: - -```bash -LAZYBOY_COMPUTER_DRIVER=legacy -``` - -or: - -```bash -LAZYBOY_COMPUTER_DRIVER=cua -``` - -Default during initial rollout: - -```bash -LAZYBOY_COMPUTER_DRIVER=legacy -``` - -After Cua passes production-equivalent validation, the default may become: - -```bash -LAZYBOY_COMPUTER_DRIVER=cua -``` - -Do not remove the legacy option until Cua has passed the migration acceptance suite. - -If configuration already has a typed settings system, add this there instead of reading environment variables throughout the code. - -Suggested enum: - -```rust -pub enum ComputerDriver { - Legacy, - Cua, -} -``` - ---- - -# 9. Recommended Cua Integration Mode - -LazyBoy is an application with built-in computer-use. - -Preferred order for experimentation: - -## POC - -Use the Cua Driver CLI / daemon boundary first if it allows fast validation. - -Examples: - -```bash -cua-driver call '' -``` - -or a controlled local process interface. - -This proves Cua works inside the existing Linux desktop container. - -## Production integration - -Prefer a typed/stable integration boundary. - -Evaluate, based on the installed Cua release: - -1. direct in-process SDK if suitable for LazyBoy's process model -2. private worker / daemon -3. CLI JSON calls as fallback - -Do not choose MCP merely because Agent frameworks often use MCP. - -LazyBoy is embedding computer use inside a product. The internal integration does not have to look like the Agent-facing integration. - -### Rust note - -Cua Driver's core runtime is Rust-based, but public application SDK support may differ by release. - -Do not write custom unsafe bindings unless there is a strong reason. - -Prefer an officially supported application integration surface. - ---- - -# 10. Phase 0 — Discovery / Compatibility Check - -Before changing LazyBoy behavior, create a short engineering report. - -The coding agent must verify the actual runtime environment. - -Inside a real LazyBoy desktop container: - -```bash -echo "$DISPLAY" -ps aux -env | sort -``` - -Confirm: - -- X11 display exists -- XFCE session exists -- AT-SPI bus is available -- Chromium exists -- Cua Driver can start -- Cua Driver can capture the current display -- Cua Driver can enumerate apps/windows -- Cua Driver can operate in Xvfb -- Cua Driver can access Chromium in this environment - -Install Cua Driver using the current official installation method. - -Then run: - -```bash -cua-driver --version -cua-driver doctor -cua-driver list-tools -``` - -Save results in: - -```text -docs/cua-compatibility.md -``` - -Include: - -- installed Cua version -- Linux distribution -- display server -- Cua doctor output summary -- supported Cua tools relevant to LazyBoy -- missing dependencies -- known limitations - -### Stop condition - -If Cua cannot reliably control the existing `XFCE + Xvfb` environment, do **not** proceed with architecture replacement. - -Instead document the blocker first. - ---- - -# 11. Phase 1 — Five-Action POC - -Do not begin by migrating the whole control crate. - -First prove these five capabilities inside the existing LazyBoy desktop: - -1. screenshot -2. accessibility/window observation -3. click native GUI element -4. type text -5. browser semantic action - -Optional sixth: - -6. scroll - -Create a standalone POC path. - -Example: - -```text -scripts/cua-smoke-test.sh -``` - -or: - -```text -crates/control/examples/cua_smoke.rs -``` - -### POC flow - -Suggested test: - -```text -1. Open a native/simple XFCE application. -2. Observe window state. -3. Click an accessible element. -4. Type text. -5. Launch/use Chromium. -6. Navigate to example.com. -7. Read browser state. -8. Trigger a semantic browser interaction if available. -9. Capture final screenshot. -``` - -### POC success criteria - -All five core actions succeed 10 consecutive times without: - -- wrong window actions -- stale element actions -- focus corruption -- unexplained timeouts -- leaving Cua processes behind -- breaking noVNC control - -Do not migrate production paths until this passes. - ---- - -# 12. Phase 2 — Migrate `computer_observe` - -First production migration target: - -```text -computer_observe -``` - -Current LazyBoy observation must remain compatible with the Agent. - -Do not change the Agent prompt contract unless required. - -Cua result must be translated into: - -```rust -ComputerObservation -``` - -Preserve existing concepts where possible: - -- screenshot/image -- dimensions -- cursor -- active window -- UI elements - -### Translation layer - -Implement: - -```text -Cua state - ↓ -CuaObservationAdapter - ↓ -LazyBoy ComputerObservation -``` - -Do not expose Cua-native short-lived element identifiers directly as permanent LazyBoy identifiers. - -Element references may only be valid for a specific observation. - -Treat each observation as a snapshot. - -### Observation ID - -Strongly consider adding or preserving an observation/snapshot identifier. - -Example: - -```rust -pub struct ComputerObservation { - pub observation_id: String, - ... -} -``` - -If changing the contract is too invasive, keep this internal first. - -This will later help detect stale actions. - ---- - -# 13. Phase 3 — Migrate `computer_act` - -Preserve the existing LazyBoy `ComputerAction` DSL. - -Current behavior such as: - -- click -- move -- pointer down/up -- hover -- drag -- type -- keyboard -- wait -- semantic references - -should remain Agent-facing LazyBoy concepts. - -Create a translator: - -```text -LazyBoy ComputerAction - │ - ▼ - CuaActionTranslator - │ - ▼ - Cua Driver -``` - -Example conceptual mapping: - -```text -LazyBoy click(element) - → semantic Cua action when possible - -LazyBoy click(x, y) - → pixel Cua action - -LazyBoy type(text) - → Cua text input - -LazyBoy key(...) - → Cua key action - -LazyBoy scroll(...) - → Cua scroll -``` - -Exact tool names MUST come from: - -```bash -cua-driver list-tools -cua-driver describe ... -``` - -### Preserve semantic-first behavior - -Prefer: - -```text -Accessibility / browser semantic action -``` - -over: - -```text -screen coordinate -``` - -Coordinate action should be fallback, not default. - ---- - -# 14. Preserve LazyBoy Action Safety Logic - -Do not delete useful behavior from: - -```text -crates/control/src/actions.rs -``` - -Existing logic includes concepts such as: - -- action batch limits -- coordinate validation -- element lookup -- stale click prevention -- browser semantic-routing preference -- double-click expansion -- drag normalization - -These should become policy/translation logic above Cua. - -Desired layering: - -```text -Agent request - │ - ▼ -LazyBoy validation - │ - ▼ -LazyBoy action policy - │ - ▼ -Cua translation - │ - ▼ -Cua Driver -``` - -Cua is not a replacement for LazyBoy product policy. - ---- - -# 15. Stale Element Handling - -This is critical. - -Do not assume: - -```text -element 12 -``` - -from one Cua observation refers to the same UI element later. - -The migration must treat element references as snapshot-scoped. - -Preferred flow: - -```text -observe - ↓ -snapshot A - ↓ -Agent selects element - ↓ -act against snapshot A - ↓ -UI changes - ↓ -observe again - ↓ -snapshot B -``` - -If the UI changed materially, do not retry an old semantic reference blindly. - -### Retry rule - -When an action fails: - -1. re-observe -2. re-resolve the target -3. retry with bounded count - -Never loop the same stale action indefinitely. - ---- - -# 16. Phase 4 — Migrate Browser Control - -LazyBoy currently separates browser actions from generic computer actions. - -Keep that separation for the Agent. - -Agent-facing: - -```text -browser -``` - -Internal: - -```text -LazyBoy BrowserRequest - │ - ▼ -Cua Browser Adapter - │ - ▼ -Cua Driver browser tools -``` - -Cua browser control should replace custom CDP behavior gradually. - -### Important - -Preserve the current policy: - -```text -When semantic browser state is available, -prefer browser semantic actions over pixel clicking Chromium. -``` - -Do not make browser automation less reliable during migration. - -### Test cases - -At minimum test: - -- navigate URL -- inspect page -- click semantic element -- type into input -- scroll -- multiple tabs if LazyBoy currently depends on them -- file picker transition -- page refresh -- browser restart -- authenticated persistent profile - ---- - -# 17. Browser Profile Compatibility - -LazyBoy persists browser profiles per computer/bot. - -This is product-critical. - -Do not let Cua silently replace LazyBoy's profile with an ephemeral managed browser unless explicitly intended. - -Verify: - -- existing Chromium profile path remains usable -- cookies survive container pause/resume -- login sessions survive LazyBoy restart behavior as expected -- takeover user and Agent see the same session -- Cua attaches to the correct browser/window - -If Cua requires an explicit browser preparation/attach step, integrate that into LazyBoy lifecycle. - -Do not auto-create a separate profile that breaks existing saved logins. - ---- - -# 18. Phase 5 — Recording Integration - -LazyBoy has an important feature: - -```text -Human demonstration - ↓ -record context/actions - ↓ -model generates playbook - ↓ -future run resolves current UI -``` - -Preserve this architecture. - -Do **not** downgrade it into raw coordinate replay. - -Cua recording should be used as richer source data. - -Target: - -```text -Human / Agent demonstration - │ - ▼ - Cua trajectory - │ - ├── before state - ├── action - ├── after state - ├── screenshots - └── optional video - │ - ▼ - LazyBoy Skill Compiler - │ - ▼ - Semantic Playbook -``` - -Cua trajectory is evidence. - -LazyBoy skill/playbook is the reusable automation. - -### Do not do - -```text -record x=312,y=441 -replay x=312,y=441 forever -``` - -### Do - -Store semantic intent when possible: - -```text -Click the "Sign in" button -``` - -Then resolve it on the current screen during replay. - ---- - -# 19. Takeover Must Keep Working - -User takeover is a core LazyBoy feature. - -Migration acceptance requires: - -```text -Agent running - ↓ -request_takeover - ↓ -Agent stops issuing input - ↓ -User controls noVNC desktop - ↓ -User releases takeover - ↓ -Agent re-observes - ↓ -Agent resumes from current state -``` - -### Required rule - -After takeover ends: - -**Always perform a fresh observation before the Agent performs another UI action.** - -Never reuse pre-takeover element references. - ---- - -# 20. Credential / Vault Boundary - -Cua must not get broad access to LazyBoy secrets by default. - -Keep credential policy in LazyBoy. - -Preferred flow: - -```text -Agent wants login - │ - ▼ -LazyBoy checks: -- allowed domain -- saved credential exists -- HTTPS / policy - │ - ▼ -LazyBoy authorizes injection - │ - ▼ -Cua performs allowed typing/action -``` - -Do not make the Cua integration read the entire Vault. - -Secrets should not appear: - -- in command-line arguments -- in logs -- in Cua debug output -- in trajectory metadata -- in screenshots longer than unavoidable -- in error messages - -Audit recording behavior around passwords. - -If recording is active, ensure sensitive typing can be masked or recording paused. - ---- - -# 21. `controld` Migration Strategy - -Do not delete `crates/controld` during Phase 1. - -It is a useful compatibility boundary. - -Current conceptual API: - -```text -POST /observe -POST /act -``` - -Recommended first migration: - -```text -POST /observe - ↓ -selected ComputerController - ↓ -CuaController or LegacyController -``` - -```text -POST /act - ↓ -LazyBoy validation - ↓ -selected ComputerController - ↓ -CuaController or LegacyController -``` - -This keeps: - -```text -API -SandboxProvider -Supervisor -``` - -largely unchanged. - -Later, if Cua integration makes `controld` unnecessary, remove it in a dedicated architectural PR. - -Do not mix that cleanup into the initial migration. - ---- - -# 22. Docker Image Changes - -Add Cua dependencies to the LazyBoy desktop image. - -The coding agent must locate the actual Dockerfile(s) used for desktop computers. - -Do not assume the path. - -Changes may include: - -- Cua Driver install -- required X11 packages -- AT-SPI dependencies -- ffmpeg if recording/video is enabled -- runtime directories -- permissions -- PATH configuration - -Run: - -```bash -cua-driver doctor -``` - -inside the built desktop container as part of the smoke test. - -### Image versioning - -Pin a known-working Cua version for reproducible builds. - -Do not install uncontrolled nightly builds in the default production image. - -Optionally allow: - -```bash -LAZYBOY_CUA_CHANNEL=stable -LAZYBOY_CUA_VERSION= -``` - -or equivalent build args. - ---- - -# 23. Cua Process Lifecycle - -Do not start one uncontrolled global Cua process for every LazyBoy computer unless architecture requires it. - -Determine which process should own: - -- display connection -- accessibility session -- browser connection -- recordings -- Cua lifecycle - -For LazyBoy's existing architecture, the safest initial design is usually: - -```text -one desktop container - │ - ├── XFCE/Xvfb - ├── Chromium - ├── noVNC - ├── LazyBoy controld - └── Cua runtime/driver -``` - -The driver should only see/control that computer's desktop session. - -### Isolation - -Bot A must never control Bot B's display. - -Tests must explicitly verify isolation. - ---- - -# 24. Health Checks - -Add a Cua health check. - -Possible information: - -```rust -pub struct ControllerHealth { - pub backend: String, - pub version: Option, - pub healthy: bool, - pub degraded: bool, - pub details: Vec, -} -``` - -Surface useful failures: - -- driver not installed -- X11 unavailable -- AT-SPI unavailable -- screenshot unavailable -- browser unavailable -- incompatible Cua version - -Do not return generic: - -```text -computer failed -``` - -when a meaningful diagnosis is available. - ---- - -# 25. Fallback Behavior - -During migration: - -```text -LAZYBOY_COMPUTER_DRIVER=legacy -``` - -must work. - -For `cua` mode, avoid silent fallback for individual actions unless explicitly designed. - -Bad: - -```text -Cua click failed -→ silently xdotool click -``` - -This makes failures impossible to debug. - -Preferred: - -```text -Cua action failed -→ return classified error -→ Agent re-observes / retries / requests takeover -``` - -A feature-flag-level fallback is acceptable. - -An invisible per-action fallback is not. - ---- - -# 26. Logging / Observability - -Add structured logs around Cua calls. - -Include: - -- operation ID -- run ID -- bot ID -- screen ID -- backend -- Cua tool -- duration -- success/failure -- action route if Cua reports it -- observation ID if available - -Never log secret text. - -For typing actions: - -```text -text="" -length=12 -``` - -not: - -```text -text="actual-password" -``` - ---- - -# 27. Metrics - -If LazyBoy has metrics infrastructure, add: - -```text -computer_action_total -computer_action_failed_total -computer_observe_duration_ms -computer_action_duration_ms -computer_browser_action_duration_ms -computer_stale_reference_total -computer_takeover_total -cua_driver_restart_total -``` - -Useful labels: - -```text -backend -action_type -route -result -``` - -Avoid high-cardinality IDs such as `run_id` as metric labels. - ---- - -# 28. Testing Strategy - -## Unit tests - -Test translation only. - -Examples: - -```text -LazyBoy click semantic ref → expected Cua request - -LazyBoy coordinate click → expected Cua request - -LazyBoy type → expected Cua request - -Cua observation → LazyBoy ComputerObservation - -unsupported Cua response → classified error -``` - -Use fake/mocked Cua responses. - ---- - -## Contract tests - -The Agent-facing tool results should remain equivalent between: - -```text -LegacyController -CuaController -``` - -for common scenarios. - -Test: - -- observation shape -- action result shape -- error behavior -- browser results -- takeover interaction - ---- - -## Integration tests - -Run against a real desktop container. - -Test native GUI: - -```text -open app -observe -click -type -verify application state -``` - -Do not validate only that Cua returned `"ok"`. - -Validate independent application state. - ---- - -## Browser E2E - -Use a deterministic local test page rather than an external website. - -Create fixtures for: - -- button -- input -- checkbox -- select -- scroll area -- delayed DOM update -- modal -- new tab -- canvas fallback if needed - -Verify actual DOM/application state. - ---- - -# 29. Migration Acceptance Suite - -Cua backend is not considered ready until all of the following pass. - -## Desktop - -- [ ] screenshot works -- [ ] window enumeration works -- [ ] active window works -- [ ] accessibility elements work -- [ ] semantic click works -- [ ] coordinate click works -- [ ] type text works -- [ ] hotkey works -- [ ] scroll works -- [ ] drag works if supported -- [ ] desktop stays usable through noVNC - -## Browser - -- [ ] attach to correct Chromium -- [ ] use persistent LazyBoy profile -- [ ] navigate -- [ ] observe DOM/browser state -- [ ] semantic click -- [ ] type -- [ ] scroll -- [ ] refresh -- [ ] profile survives pause/resume -- [ ] same browser is visible to human takeover - -## Lifecycle - -- [ ] fresh container -- [ ] existing persisted container -- [ ] pause -- [ ] resume -- [ ] stop -- [ ] restart -- [ ] concurrent bots -- [ ] no cross-bot control - -## Agent flow - -- [ ] `computer_observe` -- [ ] `computer_act` -- [ ] `browser` -- [ ] `shell` -- [ ] takeover -- [ ] resume after takeover -- [ ] skill recording -- [ ] scheduled run - ---- - -# 30. Performance Benchmark - -Before defaulting to Cua, compare against legacy. - -Create a benchmark report: - -```text -docs/cua-benchmark.md -``` - -Measure: - -| Scenario | Legacy | Cua | Winner | -| -------------------- | -----: | --: | ------ | -| screenshot | | | | -| observe desktop | | | | -| native click | | | | -| type text | | | | -| browser snapshot | | | | -| browser click | | | | -| 20-step browser task | | | | - -Also measure: - -- tool-call count -- bytes returned to model -- screenshot count -- total model-visible observation size -- end-to-end task completion time -- failure rate - -The goal is not only faster pointer execution. - -The real goal is: - -```text -fewer Agent turns -+ -less context -+ -higher task success rate -``` - ---- - -# 31. Rollout Plan - -## Step A - -Add: - -```text -ComputerController -LegacyController -``` - -No behavior change. - -All tests must pass. - ---- - -## Step B - -Add Cua smoke test. - -No production traffic. - ---- - -## Step C - -Implement: - -```text -CuaController.observe -``` - -Feature flagged. - ---- - -## Step D - -Implement simple actions: - -```text -click -type -keyboard -scroll -``` - ---- - -## Step E - -Migrate browser state/actions. - ---- - -## Step F - -Add recording integration. - ---- - -## Step G - -Run acceptance suite and benchmark. - ---- - -## Step H - -Change default: - -```text -legacy -→ -cua -``` - -but keep legacy rollback. - ---- - -## Step I - -After stable operation, delete obsolete low-level code in separate PRs. - -Possible deletion candidates: - -```text -a11y.py -a11y.rs -cdp.py -cdp.rs -x11.rs -screen implementation portions -``` - -Only delete code proven unused. - ---- - -# 32. Suggested PR Sequence - -Keep PRs small. - -### PR 1 - -```text -refactor(control): introduce pluggable ComputerController -``` - -- add interface -- wrap legacy -- no behavior change -- tests - -### PR 2 - -```text -build(desktop): install and validate Cua Driver -``` - -- image changes -- doctor -- smoke test -- compatibility doc - -### PR 3 - -```text -feat(control): add Cua observation backend -``` - -### PR 4 - -```text -feat(control): route computer actions through Cua -``` - -### PR 5 - -```text -feat(browser): add Cua browser adapter -``` - -### PR 6 - -```text -feat(skills): ingest Cua trajectories for demonstrations -``` - -### PR 7 - -```text -test(control): add Cua acceptance and benchmark suite -``` - -### PR 8 - -```text -chore(control): make Cua the default backend -``` - -### Later - -```text -chore(control): remove obsolete legacy OS automation -``` - ---- - -# 33. Error Model - -Map Cua failures to typed LazyBoy errors. - -Suggested categories: - -```rust -pub enum ControlError { - DriverUnavailable, - DriverUnhealthy, - DisplayUnavailable, - AccessibilityUnavailable, - BrowserUnavailable, - TargetNotFound, - StaleReference, - PermissionDenied, - Timeout, - Unsupported, - Busy, - InvalidAction, - Internal(String), -} -``` - -Do not expose Cua raw errors directly to the Agent when a stable LazyBoy error can represent them. - -Log the raw cause internally. - ---- - -# 34. Retry Policy - -Do not blindly retry UI actions. - -Recommended: - -### Observation failure - -Retry a small bounded number if transport/runtime error appears transient. - -### Semantic target not found - -```text -re-observe -→ re-resolve -→ retry once -``` - -### Stale target - -```text -re-observe -→ never retry original snapshot ref directly -``` - -### Pixel miss - -Do not repeat the same click indefinitely. - -Preserve LazyBoy's stale-click protection concept. - -### Driver crash - -Restart driver/runtime if safe, then require a fresh observation. - ---- - -# 35. Screenshot Policy - -Avoid sending screenshots to the model when structured UI state is sufficient. - -Prefer: - -```text -semantic / accessibility observation -``` - -Use screenshots when: - -- layout matters -- semantic state is incomplete -- canvas/WebGL is involved -- visual verification is needed - -This reduces: - -- latency -- model context -- vision token cost -- accidental secret exposure - ---- - -# 36. Cua Permission Policy - -If the chosen Cua deployment mode supports permission policies, use allow-list behavior. - -LazyBoy only needs a subset of Cua capabilities. - -Allow only required operations. - -Example conceptual set: - -```text -health/doctor-like observation -window/app listing -screenshot -window state -click -type -key -scroll -browser state -browser click -browser type -browser navigation -recording -``` - -Do not allow unrelated capabilities automatically. - -Use actual current Cua tool names from the installed version. - ---- - -# 37. Security Requirements - -- Cua must not access the host Docker socket from Agent desktops. -- Each bot must remain isolated. -- Keep LazyBoy supervisor on internal network. -- Keep `controld` localhost/internal where applicable. -- Do not expose Cua daemon ports publicly. -- Do not log passwords/tokens. -- Verify trajectory storage permissions. -- Verify screenshots are covered by LazyBoy retention policy. -- Do not allow an Agent to change Cua policies. -- Do not let the Agent select another bot's display/session. -- Cua executable/version should be controlled by LazyBoy image/build process. - ---- - -# 38. Multi-Screen Considerations - -LazyBoy already has screen concepts: - -```text -screen_lease_id -screen_id -screen_slot -display -``` - -Do not discard these. - -Cua must be bound to the LazyBoy-selected display/screen. - -Verify multi-screen behavior before enabling Cua for multi-screen bots. - -If Cua does not safely support LazyBoy's current multi-screen semantics: - -- support one screen first -- return explicit capability information -- do not fake support - ---- - -# 39. Cua Capability Mapping - -LazyBoy should expose backend capabilities. - -Suggested internal structure: - -```rust -pub struct ComputerCapabilities { - pub multi_screen: bool, - pub semantic_desktop: bool, - pub semantic_browser: bool, - pub pixel_actions: bool, - pub recording: bool, - pub background_input: bool, -} -``` - -Only add fields if needed and compatible with existing contract evolution. - -Use capability checks instead of OS-name conditionals where possible. - -Bad: - -```rust -if linux { - ... -} -``` - -Better: - -```rust -if capabilities.semantic_browser { - ... -} -``` - ---- - -# 40. Future Phase — Cua Sandbox - -Do **not** implement this during the Driver migration. - -Later, LazyBoy may support: - -```text -SandboxProvider - │ - ├── LazyBoyDocker - └── CuaSandbox -``` - -Possible future computer types: - -```text -Lightweight Linux -Linux VM -Windows VM -macOS VM -Cloud Computer -``` - -This should be a separate project after Cua Driver migration is stable. - -The current `SandboxProvider` abstraction should make this possible. - ---- - -# 41. Future Phase — Windows / macOS - -One strategic reason for Cua is avoiding custom implementations for: - -```text -Linux AT-SPI/X11 -Windows UIA/input/capture -macOS AX/input/capture -``` - -Do not add Windows/macOS support during the initial Linux migration. - -First ensure the LazyBoy control contract is OS-neutral. - -Then add backend capabilities and sandbox providers later. - ---- - -# 42. Definition of Done — Phase 1 - -Phase 1 is complete when: - -1. LazyBoy can run with: - -```bash -LAZYBOY_COMPUTER_DRIVER=legacy -``` - -and: - -```bash -LAZYBOY_COMPUTER_DRIVER=cua -``` - -2. Existing Agent tool schemas remain compatible. - -3. Cua works in the existing LazyBoy Linux desktop container. - -4. `computer_observe` works through Cua. - -5. `computer_act` core actions work through Cua. - -6. Browser semantic operations work through Cua. - -7. noVNC human takeover still works. - -8. Persistent Chromium sessions still work. - -9. Docker pause/resume still works. - -10. Multi-bot isolation is verified. - -11. Legacy backend remains available for rollback. - -12. No secret is exposed in logs or recording metadata. - -13. Acceptance tests pass. - -14. Benchmark results are documented. - ---- - -# 43. First Task for the Coding Agent - -Do this first and nothing larger: - -## Task - -Create a branch: - -```text -feat/cua-driver-poc -``` - -Then: - -1. inspect current LazyBoy computer-control flow -2. identify actual desktop Dockerfile/image entrypoint -3. install a pinned stable Cua Driver in that image -4. make no Agent-facing schema changes -5. create a Cua smoke test that runs inside a LazyBoy desktop -6. verify: - - `cua-driver --version` - - `cua-driver doctor` - - screenshot - - window/accessibility observation - - native click - - typing - - Chromium/browser state -7. write results to: - -```text -docs/cua-compatibility.md -``` - -8. stop after the POC -9. do not delete any legacy control code -10. report blockers before starting the controller refactor - -### Expected output - -The first PR should answer only: - -> "Can Cua Driver reliably control the existing LazyBoy XFCE + Xvfb desktop container?" - -If the answer is yes, proceed to the next PR. - ---- - -# 44. Second Task After POC Passes - -Create: - -```text -ComputerController -``` - -with: - -```text -LegacyController -CuaController -``` - -Initially make all production requests use: - -```text -LegacyController -``` - -Then route only test/flagged traffic to: - -```text -CuaController -``` - -Do not migrate browser and recording in the same PR. - ---- - -# 45. Architecture Decision - -The intended ownership after migration is: - -| Concern | Owner | -| ----------------------------------- | ------- | -| Product UI | LazyBoy | -| Agent loop | LazyBoy | -| Model provider | LazyBoy | -| Memory | LazyBoy | -| Schedules | LazyBoy | -| Vault | LazyBoy | -| Takeover | LazyBoy | -| Skills/playbooks | LazyBoy | -| Sandbox lifecycle (Phase 1) | LazyBoy | -| Docker resources | LazyBoy | -| Remote desktop/noVNC | LazyBoy | -| Computer observation | Cua | -| Native UI control | Cua | -| Pointer/keyboard | Cua | -| Browser semantic control | Cua | -| OS-specific accessibility | Cua | -| Trajectory capture | Cua | -| Workflow abstraction from recording | LazyBoy | - -This is the central design decision. - -Do not invert it. - ---- - -# 46. Final Principle - -LazyBoy's competitive/product value is: - -```text -Agent workspace -Multi-agent -Persistent computers -Human takeover -Memory -Schedules -Vault -Skills -Demo → reusable workflow -Web/mobile UX -Model choice -``` - -The goal of using Cua is to stop spending LazyBoy engineering effort on: - -```text -X11 automation -AT-SPI edge cases -CDP plumbing -screen capture -OS-specific input -window enumeration -cross-platform UI automation -``` - -Build LazyBoy **on top of** Cua. - -Do not turn LazyBoy **into** Cua. - ---- - -# References - -LazyBoy: - -- https://code.30cm.net/daniel.w/lazyBoy -- https://code.30cm.net/daniel.w/lazyBoy/src/branch/main/docs/architecture.md -- https://code.30cm.net/daniel.w/lazyBoy/src/branch/main/crates/control -- https://code.30cm.net/daniel.w/lazyBoy/src/branch/main/crates/control/src/sandbox.rs -- https://code.30cm.net/daniel.w/lazyBoy/src/branch/main/crates/control/src/actions.rs -- https://code.30cm.net/daniel.w/lazyBoy/src/branch/main/crates/sandbox - -Cua: - -- https://github.com/trycua/cua -- https://cua.ai/docs -- https://cua.ai/docs/how-to-guides/driver/install -- https://cua.ai/docs/concepts/choose-a-cua-driver-integration -- https://cua.ai/docs/how-to-guides/driver/connect-your-agent -- https://cua.ai/docs/reference/cua-driver/cli-reference -- https://cua.ai/docs/reference/cua-driver/mcp-tools -- https://cua.ai/docs/how-to-guides/driver/record-and-render-a-trajectory -- https://cua.ai/docs/how-to-guides/driver/restrict-tool-access diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index fadaa74..bdba7f1 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -1,4 +1,4 @@ -import { FormEvent, KeyboardEvent as ReactKeyboardEvent, useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { FormEvent, Fragment, KeyboardEvent as ReactKeyboardEvent, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { BotIcon, Brain, ChevronDown, ChevronsRight, CircleHelp, ClipboardPaste, Computer, Download, Ellipsis, Info, LogOut, Megaphone, Paperclip, Pencil, Pin, Plug, Plus, RefreshCw, Settings, Smartphone, Sparkle, Square, Upload, Users, X } from "./animated-icons"; import UseAnimations from "./use-animations"; import loading from "react-useanimations/lib/loading"; @@ -17,6 +17,8 @@ import searchToX from "react-useanimations/lib/searchToX"; import { api, ApiError } from "./api"; import { createCoalescer, subscribeToSession } from "./live"; import { applyReplyEvent, type ReplyDrafts } from "./reply-stream"; +import { acceptMention, mentionChoices, mentionToken } from "./mentions"; +import { clockTime, dayLabel, sameDay } from "./chat-time"; import { HANDOFF_MS, VEIL_FADE_MS, handoffRemaining, keepScreenUrl, nextVeil, viewOnlyFor, viewerPath, type Veil } from "./handoff"; import { Avatar, AvatarLookProvider, AvatarStack, BLOBATAR_BACKGROUNDS, BLOBATAR_EXPRESSIONS, BLOBATAR_SHAPES, DEFAULT_LOOK, persistBlobatarShape, readAvatarLooks, resolveBlobatarShape, writeAvatarLook, type AvatarBackground, type AvatarExpression, type AvatarLook } from "./avatar"; import { dateLocale, getLocale, listJoin, setLocale, t, useLocale, type MessageKey } from "./i18n"; @@ -55,10 +57,17 @@ type WorkspacePrefs={name:string;showHidden:boolean}; function isDefaultWorkspaceName(name?:string|null){return !name||name==="Local workspace"||name==="本機工作區"} function readWorkspace():WorkspacePrefs{try{const raw=localStorage.getItem(WORKSPACE_STORE);if(!raw)return{name:t("localWorkspace"),showHidden:false};const value=JSON.parse(raw) as {name?:string;showHidden?:boolean};const name=value.name?.trim();return{name:isDefaultWorkspaceName(name)?t("localWorkspace"):name||t("localWorkspace"),showHidden:Boolean(value.showHidden)}}catch{return{name:t("localWorkspace"),showHidden:false}}} +// A message shows only its clock time; the day it belongs to is written once, +// in the divider above the first message of that day, the way chat apps do. function MessageTime({value}:{value:string}){ const date=new Date(value); if(!Number.isFinite(date.getTime()))return null; - return ; + return ; +} +function DayDivider({value}:{value:string}){ + const date=new Date(value); + if(!Number.isFinite(date.getTime()))return null; + return
; } function WorkspaceAvatar({name}:{name:string}){const parts=name.trim().split(/\s+/).filter(Boolean);const initials=(parts.length>1?parts.map(part=>part[0]).join(""):parts[0]?.slice(0,2)||"LB").slice(0,2).toUpperCase();return } function modeLabel(mode:ComputerMode){return mode==="team"?t("sharedComputer"):t("privateComputer")} @@ -217,6 +226,20 @@ export function App(){ const [slashIndex,setSlashIndex]=useState(0); const [slashDismissed,setSlashDismissed]=useState(false); useEffect(()=>{setSlashIndex(0);setSlashDismissed(false)},[draft]); + // Who answers a group message is decided by the server; here it is only + // typed. The `@` list opens on `@`, closes on the first space, and remembers + // nothing, because choosing who should talk must never feel like setup. + const [mentionIndex,setMentionIndex]=useState(0); + const [mentionDismissed,setMentionDismissed]=useState(false); + const [caretAt,setCaretAt]=useState(0); + const composerRef=useRef(null); + const [hostMenuOpen,setHostMenuOpen]=useState(false); + useEffect(()=>{setMentionIndex(0);setMentionDismissed(false);setHostMenuOpen(false)},[draft,activeRoomId]); + useEffect(()=>{setCaretAt(current=>current>draft.length?draft.length:current)},[draft]); + const mentionQuery=activeRoom&&!mentionDismissed?mentionToken(draft,caretAt):null; + const mentionList=mentionQuery===null||!activeRoom?[]:mentionChoices(mentionQuery,activeRoom.members,t("everyoneMention")); + const roomHostId=activeRoom?activeRoom.hostBotId||activeRoom.members[0]?.id||null:null; + const roomHost=activeRoom?.members.find(member=>member.id===roomHostId)||null; const slashToken=draft.trimStart().split(/\s/,1)[0].slice(1).toLowerCase(); const slashSuggestions=!slashDismissed&&/^\/[^\s]*$/.test(draft.trimStart()) ? [{name:"goal",description:t("goalCommandHint"),kind:t("slashMode")},...fileSkills.map(skill=>({...skill,kind:t("slashFileSkill")}))].filter(skill=>!slashToken||skill.name.startsWith(slashToken)).slice(0,8) @@ -290,7 +313,12 @@ export function App(){ useEffect(()=>{if(!handingOff)return;handoffAtRef.current=Date.now();const timer=setTimeout(()=>{expectedHolderRef.current=null;setHandingOff(false)},HANDOFF_MS);return()=>clearTimeout(timer)},[handingOff]); useEffect(()=>{const frame=desktopFrameRef.current;if(!frame?.contentWindow||!screenUrl)return;frame.contentWindow.postMessage({type:"lazyboy-view-only",viewOnly:!desktopInteractive},location.origin)},[desktopInteractive,screenUrl,desktopReady]); useEffect(()=>{const listener=(event:MessageEvent)=>{if(event.origin!==location.origin||event.source!==desktopFrameRef.current?.contentWindow||event.data?.type!=="lazyboy-request-control"||!paneBotId)return;if(computer.sharedInput){pushViewOnly(!desktopInteractive);return}void setControl("user")};window.addEventListener("message",listener);return()=>window.removeEventListener("message",listener)},[paneBotId,computer.sharedInput,desktopInteractive]); - useEffect(()=>{const close=(event:MouseEvent)=>{const target=event.target;if(target instanceof Element&&target.closest(".create-menu-wrap,.account-wrap,.session-picker,.context-menu,.plus-menu-wrap"))return;setContext(null);setRoomContext(null);setSessionMenuOpen(false);setAccountOpen(false);setCreateMenuOpen(false);setPlusOpen(false)};window.addEventListener("click",close);return()=>window.removeEventListener("click",close)},[]); + async function setRoomHost(botId:string){ + setHostMenuOpen(false); + if(!activeRoom||botId===roomHostId)return; + try{await api(`/api/rooms/${activeRoom.id}`,{method:"PATCH",body:JSON.stringify({hostBotId:botId})});await loadBots()}catch(error){setError(localizeError(error instanceof Error?error.message:t("operationFailed")))} + } + useEffect(()=>{const close=(event:MouseEvent)=>{const target=event.target;if(target instanceof Element&&target.closest(".create-menu-wrap,.account-wrap,.session-picker,.context-menu,.plus-menu-wrap,.host-chip-wrap"))return;setContext(null);setRoomContext(null);setSessionMenuOpen(false);setAccountOpen(false);setCreateMenuOpen(false);setPlusOpen(false);setHostMenuOpen(false)};window.addEventListener("click",close);return()=>window.removeEventListener("click",close)},[]); useEffect(()=>{const onKey=(event:KeyboardEvent)=>{if(event.key!=="Escape")return;setAccountOpen(false);setAccountDialog(null);setCreateMenuOpen(false);setPlusOpen(false);setTeachOpen(false);setEditingSkillId(null);setSessionMenuOpen(false);setContext(null);setRoomContext(null)};window.addEventListener("keydown",onKey);return()=>window.removeEventListener("keydown",onKey)},[]); useEffect(()=>{setWorkspaceName(name=>isDefaultWorkspaceName(name)?t("localWorkspace"):name)},[locale]); useEffect(()=>{localStorage.setItem(WORKSPACE_STORE,JSON.stringify({name:workspaceName,showHidden}))},[workspaceName,showHidden]); @@ -365,7 +393,8 @@ export function App(){ })}finally{sendingRef.current=false;setSendingMessage(false)} } - function composerKeyDown(event:ReactKeyboardEvent){if(event.nativeEvent.isComposing||event.key==="Process")return;if(slashSuggestions.length){if(event.key==="Escape"){event.preventDefault();setSlashDismissed(true);return}if(event.key==="ArrowDown"||event.key==="ArrowUp"){event.preventDefault();setSlashIndex(index=>(index+(event.key==="ArrowDown"?1:slashSuggestions.length-1))%slashSuggestions.length);return}if(event.key==="Tab"||(event.key==="Enter"&&!event.shiftKey)){event.preventDefault();setDraft(`/${slashSuggestions[slashIndex%slashSuggestions.length].name} `);return}}const history=sentHistoryRef.current;if(event.key==="ArrowUp"&&history.length>0&&(!event.currentTarget.value.includes("\n")||event.currentTarget.selectionStart===0)){event.preventDefault();if(historyIndexRef.current===null){historyDraftRef.current=draft;historyIndexRef.current=history.length-1}else historyIndexRef.current=Math.max(0,historyIndexRef.current-1);setDraft(history[historyIndexRef.current]);return}if(event.key==="ArrowDown"&&historyIndexRef.current!==null&&(!event.currentTarget.value.includes("\n")||event.currentTarget.selectionEnd===event.currentTarget.value.length)){event.preventDefault();if(historyIndexRef.currentcomposerRef.current?.focus())} + function composerKeyDown(event:ReactKeyboardEvent){if(event.nativeEvent.isComposing||event.key==="Process")return;if(mentionList.length){if(event.key==="Escape"){event.preventDefault();setMentionDismissed(true);return}if(event.key==="ArrowDown"||event.key==="ArrowUp"){event.preventDefault();setMentionIndex(index=>(index+(event.key==="ArrowDown"?1:mentionList.length-1))%mentionList.length);return}if(event.key==="Tab"||(event.key==="Enter"&&!event.shiftKey)){event.preventDefault();pickMention(mentionList[mentionIndex%mentionList.length]);return}}if(slashSuggestions.length){if(event.key==="Escape"){event.preventDefault();setSlashDismissed(true);return}if(event.key==="ArrowDown"||event.key==="ArrowUp"){event.preventDefault();setSlashIndex(index=>(index+(event.key==="ArrowDown"?1:slashSuggestions.length-1))%slashSuggestions.length);return}if(event.key==="Tab"||(event.key==="Enter"&&!event.shiftKey)){event.preventDefault();setDraft(`/${slashSuggestions[slashIndex%slashSuggestions.length].name} `);return}}const history=sentHistoryRef.current;if(event.key==="ArrowUp"&&history.length>0&&(!event.currentTarget.value.includes("\n")||event.currentTarget.selectionStart===0)){event.preventDefault();if(historyIndexRef.current===null){historyDraftRef.current=draft;historyIndexRef.current=history.length-1}else historyIndexRef.current=Math.max(0,historyIndexRef.current-1);setDraft(history[historyIndexRef.current]);return}if(event.key==="ArrowDown"&&historyIndexRef.current!==null&&(!event.currentTarget.value.includes("\n")||event.currentTarget.selectionEnd===event.currentTarget.value.length)){event.preventDefault();if(historyIndexRef.current(sessionsPath,{method:"POST",body:JSON.stringify({title:t("newConversation")})});writeSessionStore(sessionStoreKey,session.id);const next=await api(sessionsPath);setSessions(next);setActiveSessionId(session.id);setMessages([])}catch(e){setError(e instanceof Error?localizeError(e.message):t("operationFailed"))}finally{setBusy(false)}} // A run that stopped to ask keeps its harness state, so the answer is just a @@ -525,14 +554,14 @@ export function App(){
-
{activeRoom?<>member.id)}/>{activeRoom.name}{setSessionMenuOpen(false);setSessionToDelete(id)}} onClear={()=>{setSessionMenuOpen(false);setClearOpen(true)}}/>{topTools}:active?<>{active.name}{setSessionMenuOpen(false);setSessionToDelete(id)}} onClear={()=>{setSessionMenuOpen(false);setClearOpen(true)}}/>{topTools}:<>{t("chooseBot")}{topTools}}
+
{activeRoom?<>member.id)}/>{activeRoom.name}event.stopPropagation()}>{hostMenuOpen&&
{t("hostMenuLabel")}{activeRoom.members.map(member=>)}
}
{setSessionMenuOpen(false);setSessionToDelete(id)}} onClear={()=>{setSessionMenuOpen(false);setClearOpen(true)}}/>{topTools}:active?<>{active.name}{setSessionMenuOpen(false);setSessionToDelete(id)}} onClear={()=>{setSessionMenuOpen(false);setClearOpen(true)}}/>{topTools}:<>{t("chooseBot")}{topTools}}
{callOpen&&voiceSettings?.enabled&&active&&activeSessionId&&!activeRoomId?setCallOpen(false)} onTakeOver={()=>{setRightPart("computer");setRightCollapsed(false);setComputerOpen(true);if(active&&!computer.sharedInput)void setControl("user",active.id)}}/>:null} -
{(activeRoom||active)&&messages.length===0?
{activeRoom?:}

{activeRoom?t("startRoomDiscussion",{name:activeRoom.name}):t("startBotWork",{name:active!.name})}

{activeRoom?t("roomWillReply",{names:listJoin(activeRoom.members.map(member=>member.name))}):active!.description||t("botWelcome")}

:messages.map(message=>{const spoken=message.role!=="user"&&Boolean(activeRoom);const speakerName=message.speakerName||(spoken?paneBot?.name:undefined);const speakerShape=(message.speakerShape||paneBot?.avatarShape||"blob") as AvatarShape;const files=messageFiles(message.blocks);const chips=chipBlocks(message.blocks);const hideBody=isAutoAttachCaption(message.body,files)||isAutoScheduleCaption(message.body,chips);return
{spoken&&}{spoken&&{speakerName}}{files.length>0&&
{files.map(file=>)}
}{chips.map((chip,index)=>chip.kind==="error"?
{errorTitle(chip.code)}
{errorActions(chip.code).map(next=>next==="retry"?:next==="screen"?:)}
:chip.kind==="resume"?
{resumeTitle(chip.reason)}
{(chip.limit||0)>0?
{t("resumeProgress",{turns:chip.turns||0,limit:chip.limit||0})}
:null}{resumedChips[message.id]||(message.seq??0)
}
:chip.kind==="login"?
{t("loginNeedsYou")}
{chip.site||message.body}
{chip.why?
{t("loginWhy",{why:chip.why})}
:null}
:chip.kind==="schedule"?
{t("scheduleChip")}
{chip.name}{scheduleWhen(chip.cron,chip.human)}
:
{t("scheduleRunChip")}
{chip.name}{scheduleWhen(chip.cron,chip.human)}
)}{!hideBody&&(message.role==="assistant"?
{message.body}
{message.body.trim()?:null}{message.runId&&{t("messageRunDetails")}}
:{message.body})}{!hideBody&&message.body.trim()&&}
})}{pausedForUser&&paneBot&&
{computer.sharedInput?t("sharedNeedsUser",{name:paneBot.name}):computer.controlHolder==="user"?t("pausedUserControl",{name:paneBot.name}):t("pausedNeedsUser",{name:paneBot.name})}{(computer.queuedRuns||0)>0&&<> {t("queuedMessages",{count:computer.queuedRuns||0})}}{computer.sharedInput||computer.controlHolder==="user"?:}
}{teaching&&active&&
{t("teachingLive",{goal:teaching.goal})}{t("teachingHint")}{teaching.eventCount>0&&<> · {t("teachingCaptured",{count:teaching.eventCount})}}
}{drafting&&
{t("distilling",{goal:drafting.goal})}
}{skillDraft&&active&&void saveSkill(skillDraft,name,playbook)} onTest={(name,playbook)=>void testSkill(skillDraft,name,playbook)} onDiscard={()=>void discardSkill(skillDraft)} onEdit={()=>setEditingSkillId(skillDraft.id)} onExport={(name,playbook)=>downloadSkill(name,skillDraft.goal,playbook)}/>}{Object.values(replyDrafts).filter(reply=>reply.text&&(!reply.messageId||!messages.some(message=>message.id===reply.messageId))).map(reply=>{const speaker=bots.find(bot=>bot.id===reply.botId);return
{activeRoom&&speaker&&<>{speaker.name}}
{reply.text}
})} +
{(activeRoom||active)&&messages.length===0?
{activeRoom?:}

{activeRoom?t("startRoomDiscussion",{name:activeRoom.name}):t("startBotWork",{name:active!.name})}

{activeRoom?t("roomWillReply",{names:listJoin(activeRoom.members.map(member=>member.name))}):active!.description||t("botWelcome")}

:messages.map((message,index)=>{const spoken=message.role!=="user"&&Boolean(activeRoom);const speakerName=message.speakerName||(spoken?paneBot?.name:undefined);const speakerShape=(message.speakerShape||paneBot?.avatarShape||"blob") as AvatarShape;const files=messageFiles(message.blocks);const chips=chipBlocks(message.blocks);const hideBody=isAutoAttachCaption(message.body,files)||isAutoScheduleCaption(message.body,chips);const previous=index>0?messages[index-1]:null;const newDay=!previous||!sameDay(previous.createdAt,message.createdAt);return {newDay&&}
{spoken&&}{spoken&&{speakerName}}{files.length>0&&
{files.map(file=>)}
}{chips.map((chip,index)=>chip.kind==="error"?
{errorTitle(chip.code)}
{errorActions(chip.code).map(next=>next==="retry"?:next==="screen"?:)}
:chip.kind==="resume"?
{resumeTitle(chip.reason)}
{(chip.limit||0)>0?
{t("resumeProgress",{turns:chip.turns||0,limit:chip.limit||0})}
:null}{resumedChips[message.id]||(message.seq??0)
}
:chip.kind==="login"?
{t("loginNeedsYou")}
{chip.site||message.body}
{chip.why?
{t("loginWhy",{why:chip.why})}
:null}
:chip.kind==="schedule"?
{t("scheduleChip")}
{chip.name}{scheduleWhen(chip.cron,chip.human)}
:
{t("scheduleRunChip")}
{chip.name}{scheduleWhen(chip.cron,chip.human)}
)}{!hideBody&&(message.role==="assistant"?
{message.body}
{message.body.trim()?:null}{message.runId&&{t("messageRunDetails")}}
:{message.body})}{!hideBody&&message.body.trim()&&}{message.replyBots&&message.replyBots.length>0&&
{message.role==="user"?t("routedTo",{names:listJoin(message.replyBots.map(reply=>reply.name))}):t("handedTo",{name:message.replyBots[0].name})}
}
})}{pausedForUser&&paneBot&&
{computer.sharedInput?t("sharedNeedsUser",{name:paneBot.name}):computer.controlHolder==="user"?t("pausedUserControl",{name:paneBot.name}):t("pausedNeedsUser",{name:paneBot.name})}{(computer.queuedRuns||0)>0&&<> {t("queuedMessages",{count:computer.queuedRuns||0})}}{computer.sharedInput||computer.controlHolder==="user"?:}
}{teaching&&active&&
{t("teachingLive",{goal:teaching.goal})}{t("teachingHint")}{teaching.eventCount>0&&<> · {t("teachingCaptured",{count:teaching.eventCount})}}
}{drafting&&
{t("distilling",{goal:drafting.goal})}
}{skillDraft&&active&&void saveSkill(skillDraft,name,playbook)} onTest={(name,playbook)=>void testSkill(skillDraft,name,playbook)} onDiscard={()=>void discardSkill(skillDraft)} onEdit={()=>setEditingSkillId(skillDraft.id)} onExport={(name,playbook)=>downloadSkill(name,skillDraft.goal,playbook)}/>}{Object.values(replyDrafts).filter(reply=>reply.text&&(!reply.messageId||!messages.some(message=>message.id===reply.messageId))).map(reply=>{const speaker=bots.find(bot=>bot.id===reply.botId);return
{activeRoom&&speaker&&<>{speaker.name}}
{reply.text}
})}
{error&&
{error}
} {otherSessionBusy&&
{t("anotherConversationQueued")}
} {statusMembers.map(member=>{const step=computer.busyStep&&member.id===computer.botId?computer.busyStep:null;const transition=isTransitionStep(step);const label=t("working",{name:member.name});return
{label}{!transition&&step?{localizeStep(step)}:null}
})} -
{event.preventDefault()}} onDrop={event=>{event.preventDefault();if(event.dataTransfer.files.length)addPendingFiles(event.dataTransfer.files)}}>
event.stopPropagation()}>{plusOpen&&
{savedSkills.length>0&&<>
{t("taughtSkills")}{savedSkills.length>5?` · ${savedSkills.length}`:""}{savedSkills.length>=6&&setSkillQuery(e.target.value)} placeholder={t("searchSkills")} aria-label={t("searchSkills")} onClick={e=>e.stopPropagation()}/>}
{listedSkills.map(skill=>
)}{listedSkills.length===0&&{t("noMatchingSkills")}}
}
}
{const file=event.target.files?.[0];event.currentTarget.value="";if(file)void importSkillFile(file)}}/>{const files=[...event.target.files||[]];event.currentTarget.value="";if(files.length)addPendingFiles(files)}}/>{pendingFiles.length>0&&
{pendingFiles.map(item=>removePendingFile(item.id)}/>)}
}{slashSuggestions.length>0&&
{slashSuggestions.map((skill,index)=>)}
}