diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dd0205b7..654e45a2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -123,6 +123,8 @@ jobs: run: | python -m playwright install --with-deps chromium make test PYTHON=python + - name: HTTP API acceptance + run: make api-acceptance PYTHON=python - name: Agent workflow acceptance run: make agent-acceptance PYTHON=python - name: Syntax and shell checks diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e3555109..28f52f36 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -46,7 +46,7 @@ jobs: - name: Run source release regressions run: | python -m unittest \ - tests.test_server.ServerBoundaryTests.test_browser_token_bootstrap_uses_httponly_cookie_and_rejects_invalid_tokens \ + tests.test_server.ServerBoundaryTests.test_api_token_headers_are_required_when_configured \ tests.test_task_consistency.TaskConsistencyTests.test_multi_task_plan_reconciles_receipts_without_taskdone_and_survives_restart - name: Run clean installed-artifact smoke test @@ -93,7 +93,7 @@ jobs: $bin = Join-Path $auditHome ".local\bin" & (Join-Path $bin "kyrozen.exe") --version & (Join-Path $bin "kyrozen.exe") --help *> $null - & (Join-Path $bin "kyrozen-web.exe") --help *> $null + & (Join-Path $bin "kyrozen-api.exe") --help *> $null $revision = & (Join-Path $auditHome ".kyrozen\bin\openkyrozen-tui.exe") --revision if ($revision -ne $env:RELEASE_TAG) { throw "Installed TUI revision does not match release" } @@ -108,7 +108,7 @@ jobs: $bin = Join-Path $auditHome ".local\bin" & (Join-Path $bin "kyrozen.exe") --version & (Join-Path $bin "kyrozen.exe") --help *> $null - & (Join-Path $bin "kyrozen-web.exe") --help *> $null + & (Join-Path $bin "kyrozen-api.exe") --help *> $null $revision = & (Join-Path $auditHome ".kyrozen\bin\openkyrozen-tui.exe") --revision if ($revision -ne $env:RELEASE_TAG) { throw "Installed TUI revision does not match release" } @@ -137,5 +137,5 @@ jobs: curl -fsSL "https://raw.githubusercontent.com/EvanProgramming/OpenKyrozen/$RELEASE_TAG/install.sh" | sh "$HOME/.local/bin/kyrozen" --version "$HOME/.local/bin/kyrozen" --help >/dev/null - "$HOME/.local/bin/kyrozen-web" --help >/dev/null + "$HOME/.local/bin/kyrozen-api" --help >/dev/null test "$("$HOME/.kyrozen/bin/openkyrozen-tui" --revision)" = "$RELEASE_TAG" diff --git a/AGENTS.md b/AGENTS.md index 2caa9284..8cefa40b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,7 +2,7 @@ ## Project Structure & Module Organization -OpenKyrozen v3.0.0 is a Python 3.12–3.13 agent with terminal and web interfaces. +OpenKyrozen v3.0.0 is a Python 3.12–3.13 agent with a terminal interface and an HTTP API. - `main.py` and `server.py` launch the packaged CLI and FastAPI server. Interface code lives in `openkyrozen/interfaces/` and the Go terminal UI lives in `tui/`. - `openkyrozen/agent/` owns the agent loop and execution receipts. `openkyrozen/tasks/` owns plans and task lifecycle, and `openkyrozen/learning/` owns self-learning. @@ -21,7 +21,7 @@ Use Python 3.12 or 3.13; Python 3.14 is intentionally unsupported by the Makefil make install # create the full development environment make install-core # install the smaller development profile make run # start the terminal agent -make web # install web extras and start the server +make api # start the HTTP API server make check # quick syntax and tool-inventory checks make docs-check # check guides and the generated runtime inventory make lint # compile-based syntax checks diff --git a/Dockerfile b/Dockerfile index 2630da16..7df2eb3c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,6 @@ # OpenKyrozen Docker Image # Build: docker build -t openkyrozen . -# Run: docker run -p 8000:8000 -v kyrozen-data:/data openkyrozen +# Run: docker run -e KYROZEN_SERVER_TOKEN -p 127.0.0.1:8000:8000 -v kyrozen-data:/data openkyrozen FROM python:3.12-slim @@ -34,11 +34,11 @@ USER kyrozen VOLUME ["/data"] -# Expose web server port +# Expose the API port EXPOSE 8000 HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \ - CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/', timeout=3)" + CMD python -c "import os, urllib.request; token = os.environ.get('KYROZEN_SERVER_TOKEN', '').strip(); req = urllib.request.Request('http://127.0.0.1:8000/api/health', headers={'Authorization': 'Bearer ' + token} if token else {}); urllib.request.urlopen(req, timeout=3).close()" -# Default: run web server -CMD ["python", "-m", "openkyrozen.interfaces.web.app", "--project", "/app", "--host", "0.0.0.0", "--port", "8000"] +# Default: run the HTTP API +CMD ["kyrozen-api", "--project", "/app", "--host", "0.0.0.0", "--port", "8000"] diff --git a/Makefile b/Makefile index 73fd734a..34094242 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: install install-core run clean lint test test-core tui-test check docs-check shell-check benchmark agent-acceptance subagent-acceptance tui-acceptance wheel-smoke docker-smoke git-status git-diff git-log web +.PHONY: install install-core run clean lint test test-core tui-test check docs-check shell-check benchmark agent-acceptance subagent-acceptance tui-acceptance wheel-smoke docker-smoke git-status git-diff git-log web api api-acceptance # Tests parse the benchmark target's stdout as JSON; do not inject GNU make's # recursive directory banners into that machine-readable output. @@ -35,12 +35,22 @@ install: install-core run: @command -v $(PYTHON) >/dev/null 2>&1 || { echo "Error: venv requires $(PYTHON). Run 'make install' with $(PYTHON) installed."; exit 1; } - $(VENV_PYTHON) -m openkyrozen.interfaces.cli.launcher --project . + @if [ -t 0 ] && [ -t 1 ] && [ "$${KYROZEN_DISABLE_TUI:-0}" != 1 ] && command -v go >/dev/null; then \ + binary=$$(mktemp "$${TMPDIR:-/tmp}/openkyrozen-dev.XXXXXX") || exit 1; \ + trap 'rm -f "$$binary"' EXIT; \ + (cd tui && go build -o "$$binary" .) && \ + KYROZEN_BACKEND_PYTHON="$(VENV_PYTHON)" KYROZEN_EXECUTION_SURFACE=tui \ + KYROZEN_TUI_CAPABILITIES="$${KYROZEN_TUI_CAPABILITIES:-full}" "$$binary" --project .; \ + else \ + $(VENV_PYTHON) -m openkyrozen.interfaces.cli.launcher --project .; \ + fi tui-test: @if command -v go >/dev/null 2>&1; then (cd tui && go test ./...); else echo "Go toolchain not found; TUI tests skipped (install Go 1.27.1 or run install.sh)."; fi -web: +web: api + +api: @command -v $(PYTHON) >/dev/null 2>&1 || { echo "Error: venv requires $(PYTHON)."; exit 1; } $(VENV_PYTHON) -m pip install fastapi uvicorn -q && $(VENV_PYTHON) -m openkyrozen.interfaces.web.app --project . @@ -91,6 +101,9 @@ wheel-smoke: $(VENV_PYTHON) -m pip install build -q $(VENV_PYTHON) scripts/wheel_smoke.py +api-acceptance: + $(VENV_PYTHON) scripts/api_workflow_acceptance.py + agent-acceptance: $(VENV_PYTHON) scripts/agent_workflow_acceptance.py diff --git a/README.ja.md b/README.ja.md index db9f97d5..639f0841 100644 --- a/README.ja.md +++ b/README.ja.md @@ -78,13 +78,7 @@ uv tool install --python 3.12 --force --with fastapi --with uvicorn https://gith /quit 終了する ``` -ブラウザー UI のメンテナンスは終了しました。通常は `kyrozen` でターミナル UI を起動してください。既存のブラウザー UI は次のコマンドで開けます。 - -```bash -kyrozen-web -``` - -既定の URL は http://localhost:8000 です。特定のプロジェクトを操作する場合は kyrozen --project /path/to/project または kyrozen-web --project /path/to/project を使います。通常の kyrozen は ~/.kyrozen/workspace のグローバルワークスペースを使います。 +対話操作には `kyrozen` を使います。外部プログラムから REST、SSE、MCP を利用するには、ソース版では `kyrozen-api`(v3.0.0 では `kyrozen-web`)を起動します。`http://127.0.0.1:8000/api/health` で状態を確認できます。`--project /path/to/project` で対象を指定でき、省略時は `~/.kyrozen/workspace` を使います。 ## OpenKyrozen の要点 @@ -110,7 +104,7 @@ kyrozen-web | コマンド、権限、ローカルデータ | [コマンド一覧](docs/commands.md) · [セキュリティ](docs/security.md) · [ストレージ](docs/memory-and-storage.md) | | タスク、履歴、拡張機能 | [タスク](docs/tasks-and-automation.md) · [履歴とロールバック](docs/history-and-rollback.md) · [拡張機能](docs/extensions.md) | | 使用量、費用、トラブル対応 | [使用量](docs/usage-and-cost.md) · [トラブルシューティング](docs/troubleshooting.md) | -| Web、REST、MCP | [API ガイド](docs/api.md) | +| REST、SSE、MCP | [API ガイド](docs/api.md) | | 自動サブエージェント、独立コンテキスト、相互検証 | [サブエージェントガイド](docs/subagents.md) | | 自己学習、メモリ、証拠 | [自己学習ガイド](docs/self-evolution.md) | | Jev Decision と校正された証拠 | [Jev Decision](docs/decision-assist-validation.md) · [System One](docs/system-one-benchmark.md) | diff --git a/README.ko.md b/README.ko.md index 026dcac2..c0533c7f 100644 --- a/README.ko.md +++ b/README.ko.md @@ -78,13 +78,7 @@ uv tool install --python 3.12 --force --with fastapi --with uvicorn https://gith /quit 종료 ``` -브라우저 UI는 더 이상 유지보수하지 않습니다. 평소에는 `kyrozen`으로 터미널 UI를 실행하세요. 기존 브라우저 UI는 다음 명령으로 열 수 있습니다. - -```bash -kyrozen-web -``` - -기본 주소는 http://localhost:8000입니다. 특정 프로젝트를 사용하려면 kyrozen --project /path/to/project 또는 kyrozen-web --project /path/to/project를 사용합니다. 일반 kyrozen은 ~/.kyrozen/workspace 전역 workspace를 사용합니다. +대화형 작업에는 `kyrozen`을 사용하세요. 다른 프로그램에서 REST, SSE 또는 MCP를 사용하려면 소스 설치판에서 `kyrozen-api`를 실행하세요(v3.0.0에서는 `kyrozen-web`). `http://127.0.0.1:8000/api/health`에서 상태를 확인할 수 있습니다. `--project /path/to/project`로 프로젝트를 지정할 수 있으며, 기본 작업 공간은 `~/.kyrozen/workspace`입니다. ## OpenKyrozen 핵심 기능 @@ -110,7 +104,7 @@ kyrozen-web | 명령, 권한, 로컬 데이터 | [명령 참고](docs/commands.md) · [보안](docs/security.md) · [저장소](docs/memory-and-storage.md) | | 작업, 기록, 확장 | [작업](docs/tasks-and-automation.md) · [기록 및 롤백](docs/history-and-rollback.md) · [확장](docs/extensions.md) | | 사용량, 비용, 문제 해결 | [사용량](docs/usage-and-cost.md) · [문제 해결](docs/troubleshooting.md) | -| Web, REST, MCP | [API 가이드](docs/api.md) | +| REST, SSE, MCP | [API 가이드](docs/api.md) | | 자동 하위 에이전트, 독립 컨텍스트, 상호 검증 | [하위 에이전트 가이드](docs/subagents.md) | | self-learning, memory, evidence | [Self-learning 가이드](docs/self-evolution.md) | | Jev Decision 및 교정 증거 | [Jev Decision](docs/decision-assist-validation.md) · [System One](docs/system-one-benchmark.md) | diff --git a/README.md b/README.md index 1502fb61..804833b1 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ You: accept the plan and fix the test You: search for the latest Python release and cite the source ``` -`kyrozen` opens the global workspace; `kyrozen --project /path/to/repo` binds a session to a project. The browser UI is unmaintained. To open the existing UI, run `kyrozen-web --host 127.0.0.1 --port 8000` and visit `http://127.0.0.1:8000`. Configure `KYROZEN_SERVER_TOKEN` before binding beyond loopback. +`kyrozen` opens the global workspace; `kyrozen --project /path/to/repo` binds a session to a project. For HTTP integrations, a source install provides `kyrozen-api` (called `kyrozen-web` in v3.0.0). Use `GET /api/health` to check the server. Configure `KYROZEN_SERVER_TOKEN` before binding beyond loopback. The interaction modes make authority visible: Ask and Plan are read/network-only; Agent carries out explicitly requested or accepted work under capability and approval checks. Managed shell commands also use an available OS filesystem sandbox; see [security and permissions](docs/security.md) for supported backends and limitations. diff --git a/README.zh-CN.md b/README.zh-CN.md index 73f1caf9..5031f0bf 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -78,13 +78,7 @@ uv tool install --python 3.12 --force --with fastapi --with uvicorn https://gith /quit 退出 ``` -浏览器界面已停止维护。日常使用请运行 `kyrozen` 打开终端界面。如需打开现有的网页界面,可运行以下命令。 - -```bash -kyrozen-web -``` - -默认打开 http://localhost:8000。若要操作指定项目,使用 kyrozen --project /path/to/project 或 kyrozen-web --project /path/to/project。直接运行 kyrozen 使用 ~/.kyrozen/workspace 全局工作区。 +交互使用请运行 `kyrozen`。若要从其他程序接入 REST、SSE 或 MCP,源码版可运行 `kyrozen-api`(v3.0.0 的命令为 `kyrozen-web`),再请求 `http://127.0.0.1:8000/api/health` 检查服务。通过 `--project /path/to/project` 绑定项目,默认使用 `~/.kyrozen/workspace` 全局工作区。 ## OpenKyrozen 的主要能力 @@ -107,7 +101,7 @@ kyrozen-web | 命令、模式和工作区 | [使用指南](docs/usage.md) | | 运行时流程和安全边界 | [架构](docs/architecture.md) | | 服务商、环境变量和状态目录 | [配置](docs/configuration.md) | -| Web、REST 和 MCP | [API 指南](docs/api.md) | +| REST、SSE 和 MCP | [API 指南](docs/api.md) | | 命令、权限和本地数据 | [命令参考](docs/commands.md) · [安全](docs/security.md) · [存储](docs/memory-and-storage.md) | | 任务、恢复与扩展 | [任务](docs/tasks-and-automation.md) · [历史与回滚](docs/history-and-rollback.md) · [扩展](docs/extensions.md) | | 用量与常见问题 | [费用说明](docs/usage-and-cost.md) · [故障排查](docs/troubleshooting.md) | diff --git a/SUPPORT.md b/SUPPORT.md index ee6dd1e2..3db129a3 100644 --- a/SUPPORT.md +++ b/SUPPORT.md @@ -1,6 +1,6 @@ # Support -OpenKyrozen maintains the CLI and terminal UI for interactive use. The browser UI bundled with v3.0.0 is unmaintained. +Use the CLI or terminal UI for interactive work. Integrations can use the HTTP API for REST, streaming chat, webhooks, and MCP. See the [API guide](docs/api.md). For setup and usage, start with the [documentation index](docs/index.md), [installation](docs/installation.md), [usage](docs/usage.md), [configuration](docs/configuration.md), and [development](docs/development.md) guides. diff --git a/docs/agentic-runtime-roadmap.md b/docs/agentic-runtime-roadmap.md index dc0ce64b..864aaf4d 100644 --- a/docs/agentic-runtime-roadmap.md +++ b/docs/agentic-runtime-roadmap.md @@ -1,7 +1,7 @@ # Agentic runtime roadmap OpenKyrozen now has one durable interaction state machine across the classic -CLI, Bubble Tea TUI, web UI, REST, and SSE. Ask and Plan are read-only; accepted +CLI, Bubble Tea TUI, REST, and SSE. Ask and Plan are read-only; accepted plans become evidence-gated `TaskManager` work in Agent mode. V3 supports native tool calls on capable providers, archives older tool results and compacts history while preserving call and reply identities. Managed shell commands can use filesystem sandboxing on Linux and macOS. [Provider contracts](providers.md) · [Context and receipts](architecture.md) · [Sandbox availability](security.md) ## Further work diff --git a/docs/api.md b/docs/api.md index a2b0bc06..f044a2a4 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1,12 +1,16 @@ -# Web, REST, streaming, webhooks, and MCP +# HTTP API, streaming, webhooks, and MCP -The browser UI is unmaintained. For interactive use, start the terminal UI with `kyrozen`. +Start `kyrozen` for interactive terminal sessions. Integrations use `kyrozen-api` to access the same runtime, workspace, SQLite store, and permission gates over HTTP. The compatibility command `kyrozen-web` also works and is the name shipped in v3.0.0. -`kyrozen-web` serves the browser UI and API through the same runtime, workspace, SQLite store, permission gates, provider configuration, and tool adapters used by the terminal. Bind to loopback for local use: +```sh +kyrozen-api --host 127.0.0.1 --port 8000 +``` + +In another terminal, request service health and the JSON OpenAPI schema: ```sh -kyrozen-web --host 127.0.0.1 --port 8000 curl http://127.0.0.1:8000/api/health +curl http://127.0.0.1:8000/openapi.json ``` The [generated runtime inventory](tool-inventory.md) is authoritative for every live HTTP method/path, tool, capability label, and MCP input schema. This guide explains common payloads and the shared boundaries. `server:app` remains an import-compatible application object; lifecycle setup is performed when the ASGI application starts. @@ -21,8 +25,6 @@ Authorization: Bearer or `X-Kyrozen-Token: `. The token is compared as a secret. Do not put it in a URL, client-side source, logs, or a public curl example. To bind beyond loopback, always configure it; otherwise direct non-loopback API requests receive HTTP 503. Use HTTPS through a trusted reverse proxy for remote traffic. -The browser login endpoint accepts `POST /api/auth/session` with `{"token":"..."}` and returns `{"authenticated":true}` plus a short-lived HttpOnly, SameSite=Strict cookie when a token is configured. `DELETE /api/auth/session` revokes that in-memory cookie and clears it. This browser session does not issue a bearer token for scripts. If no server token is set, login returns authenticated for local UI startup. - REST handlers expect JSON objects for JSON bodies. Invalid JSON or a non-object body returns 400. Session IDs are at most 128 characters and allow letters, digits, `_`, `.`, `:`, and `-`. Chat messages are limited to 12,000 characters. Profiles are `auto`, `coder`, or `researcher`. The web process assigns one server actor (`KYROZEN_SERVER_ACTOR`); a request body cannot select another private user. Common errors are HTTP 400 for invalid payloads, 401 for a missing/invalid configured token, 403 for a capability refusal, 404 for a missing scoped record, 409 for stale state or unmet evidence, 413 for oversized input, 429 for bounded webhook registration capacity, 500 for an unexpected handler failure, and 503 for provider unavailability or a non-loopback request without configured server authentication. Individual endpoints can use other status codes; check the response `detail` and the handler contract. @@ -68,7 +70,8 @@ All protected routes require the authentication above. Exact parameter spelling | Route group | Operations and effects | |---|---| -| Health and UI: `/`, `/manifest.json`, `/api/health` | Serve the chat page/PWA manifest or report service health. Health is authenticated when a server token is configured. | +| Health: `/api/health` | Report service and provider status. Requires authentication when a server token is configured. | +| Schema: `/openapi.json` | Retrieve the public JSON API description. | | Cost: `/api/cost`, `/api/cost/reset` | Read usage/cost for a requested supported scope or reset selected local counters. Reset is a destructive local bookkeeping action, not a provider refund. | | Decisions: `/api/v2/decision-assist`, `/api/v2/system-one/diagnostics`, `/api/v2/fast/diagnostics` | Read backend state and session-scoped decision/usage diagnostics. A diagnostic query can initialize the named session. | | Memory: `/api/memory`, `/api/v2/memory`, `/api/v2/memory/claims` | Read or create scoped claims and inspect/delete a particular claim. Creation is a durable write. Deletion deactivates the claim and handles dependent learning state; it is not a database wipe. | diff --git a/docs/architecture.md b/docs/architecture.md index 1b68bd12..c917972a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -4,7 +4,7 @@ OpenKyrozen is a modular monolith. Its Python package contains the implementatio root scripts are launchers. The Bubble Tea client remains in the `tui` Go package. ```text -CLI / TUI JSONL / web REST and SSE / MCP +CLI / TUI JSONL / REST and SSE / HTTP MCP │ ▼ AgentRuntime.chat(session, message) @@ -27,7 +27,7 @@ CLI / TUI JSONL / web REST and SSE / MCP services and the runtime. `Application.close` releases owned worker and browser resources. Importing core modules or `server:app` creates no database, client, worker or terminal UI. The web factory `openkyrozen.interfaces.web.app.create_app(application=None)` accepts an -injected application, or creates one during startup. Web chat and MCP retain request +injected application, or creates one during startup. REST, streaming chat, and MCP retain request serialization while using explicit sessions; they do not swap agent globals. | Owner | State | @@ -105,7 +105,7 @@ prompt state, so conversation compaction cannot discard its current bounds or ta | persistence | SQLite connections/schema and repositories for events, history, tasks, memory, learning, usage and catalogs | | skills, plugins | Existing loading, registry and lifecycle behavior | | updates | Verified downloads, package updates and Go/TUI installation | -| interfaces | Rich CLI, Python JSONL backend, web feature routes/templates and MCP | +| interfaces | Rich CLI, Python JSONL backend, HTTP routes and MCP | Compatible providers share the OpenAI transport; native Responses, Anthropic, Google, Azure, Bedrock, Perplexity and Ollama transports retain their existing contracts. diff --git a/docs/commands.md b/docs/commands.md index ff360a07..642fb3c4 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -1,6 +1,6 @@ # Command and keyboard reference -The Rich command loop, Bubble Tea TUI, and web UI share the agent modes and durable runtime, but their keyboard and session controls differ. Slash commands are entered in the conversation input. A slash in the middle of a sentence, URL, filesystem path, or code is ordinary text. In the terminal UI, press `/` at the beginning of a line to open command suggestions; type to filter, use arrows to choose, and Enter to insert the selection. +The Rich command loop and Bubble Tea TUI share agent modes and durable sessions. Slash commands are entered in the conversation input. A slash in the middle of a sentence, URL, filesystem path, or code is ordinary text. In the terminal UI, press `/` at the beginning of a line to open command suggestions; type to filter, use arrows to choose, and Enter to insert the selection. ## Launch commands @@ -11,7 +11,7 @@ The Rich command loop, Bubble Tea TUI, and web UI share the agent modes and dura | `kyrozen --global` | Explicitly use the global workspace. | | `kyrozen --init` | Run the legacy one-shot configuration and memory setup flow. | | `kyrozen --version`, `kyrozen --help` | Show version or supported options without starting an interactive turn. | -| `kyrozen-web --host HOST --port PORT [--project PATH]` | Start the web application. Bind to loopback for local use; set a server token for a non-loopback bind. | +| `kyrozen-api --host HOST --port PORT [--project PATH]` | Start the HTTP API for REST, SSE, webhooks, and MCP. Bind to loopback for local use; set a server token for a non-loopback bind. | | `kyrozen-backend` | Start the JSON-lines backend used to connect the terminal UI. | | `kyrozen migrate v1 [SOURCE]` | Import a legacy Chroma memory directory into the configured SQLite store. Default source: `./chroma_memory`. | | `kyrozen learning benchmark [OPTIONS]` | Run the deterministic learning benchmark; see [self-learning](self-evolution.md#benchmark-replay). | @@ -34,6 +34,8 @@ The Bubble Tea terminal binary is normally selected by the installer. `KYROZEN_D | `/model [name\|auto]` | Pin one main-agent model or restore automatic simple/complex selection. | | `/custom-provider list\|create\|edit \|use \|remove ` | Manage named OpenAI-compatible profiles; API keys are masked and encrypted locally. | | `/api_key` | Set the active provider credential. `/key` is an alias. | +| `/help`, `/instructions` | Read terminal controls or the instructions loaded for the current workspace. | +| `/queue` | Review, edit, withdraw, or resume queued follow-ups. | | `/settings` | Open terminal preferences. | | `/update` | Update installed Python and TUI components; restart after a successful update when prompted. | | `/quit` | Exit. `/exit` is an alias. | diff --git a/docs/configuration.md b/docs/configuration.md index cfc6d7f1..8dd8f29f 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -117,11 +117,11 @@ encrypted in `~/.kyrozen_config.json`. Set `provider: custom` and `custom_profile: ` in a sub-agent role to use a different profile; a `model` value can override the profile's complex model for that role. -## Web server +## HTTP API server ```bash -kyrozen-web --host 127.0.0.1 --port 8000 -KYROZEN_SERVER_TOKEN=change-me kyrozen-web --host 0.0.0.0 --port 8000 +kyrozen-api --host 127.0.0.1 --port 8000 +KYROZEN_SERVER_TOKEN=change-me kyrozen-api --host 0.0.0.0 --port 8000 ``` Use a token whenever the server is reachable beyond localhost. The Docker image uses /app as its project root; mount persistent state separately when deploying it. diff --git a/docs/development.md b/docs/development.md index b69d64d3..63e0e7e0 100644 --- a/docs/development.md +++ b/docs/development.md @@ -12,6 +12,8 @@ make install Use Python 3.12 or 3.13. make install installs the full optional set and Chromium; make install-core is enough for the non-browser path. +With Go installed, `make run` in an interactive terminal builds the TUI from this checkout and starts its Python backend in the project directory. The temporary binary is removed when the session exits. + ## Checks ```bash @@ -34,6 +36,7 @@ python -m unittest discover -s tests -p 'test_*.py' -v make benchmark make wheel-smoke make agent-acceptance +make api-acceptance make tui-test make tui-acceptance make docker-smoke diff --git a/docs/extensions.md b/docs/extensions.md index b5167048..ea36179d 100644 --- a/docs/extensions.md +++ b/docs/extensions.md @@ -4,7 +4,7 @@ OpenKyrozen loads reusable guidance from bundled skills, user-installed skill pa ## Skills -Use `/skills` to inspect available skill versions and `/api/v2/skills` in the authenticated web interface to inspect installed records. Bundled packages live in `builtin_skills/` and include a manifest, instructions, and applicable license or notice. User or project skills are read as instruction content. The registry checks package structure and selection status; skill text can still be wrong or malicious. +Use `/skills` to inspect available skill versions and `/api/v2/skills` in the authenticated HTTP API to inspect installed records. Bundled packages live in `builtin_skills/` and include a manifest, instructions, and applicable license or notice. User or project skills are read as instruction content. The registry checks package structure and selection status; skill text can still be wrong or malicious. Before installation or activation, review the source, publisher, requested behavior, license, and external commands. Pin or record the source when repeatable deployments matter. Skills inform how the agent approaches a request; they do not override user intent, mode restrictions, capability policy, approvals, or the tool executor. Roll back a skill if the active version is harmful or no longer appropriate. diff --git a/docs/index.md b/docs/index.md index a09f2083..774758cf 100644 --- a/docs/index.md +++ b/docs/index.md @@ -16,7 +16,7 @@ This index covers the current product guides, developer references, and dated en | Area | Guides | |---|---| -| Safety and deployment | [Security and permissions](security.md) · [API, web, and MCP](api.md) · [Troubleshooting](troubleshooting.md) | +| Safety and deployment | [Security and permissions](security.md) · [REST, SSE, webhooks, and MCP](api.md) · [Troubleshooting](troubleshooting.md) | | Data and outcomes | [Memory and storage](memory-and-storage.md) · [Tasks and automation](tasks-and-automation.md) · [History and rollback](history-and-rollback.md) · [Usage and cost](usage-and-cost.md) | | Tool execution | [Shell execution and process handles](shell-tools.md) · [Large tool outputs](tool-output-artifacts.md) | | Improvement and extension | [Self-learning](self-evolution.md) · [Extensions](extensions.md) · [Sub-agents](subagents.md) · [Project intelligence](native-project-intelligence.md) | diff --git a/docs/installation.md b/docs/installation.md index 22296401..324dafd0 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -45,17 +45,17 @@ make run `make install` creates `venv/`, installs the project and optional integrations, and downloads Playwright Chromium for browser tests. `make install-core` installs the smaller web and Anthropic development environment without the complete browser extras. On Windows, use the supplied `setup.bat` and `run.bat`; the Makefile targets macOS, Linux, and WSL. -To run against a project directory, use `kyrozen --project /path/to/project` or `kyrozen-web --project /path/to/project`. Bare `kyrozen` uses the persistent global workspace. See [usage](usage.md) for workspace rules. +To run against a project directory, use `kyrozen --project /path/to/project` or `kyrozen-api --project /path/to/project`. Bare `kyrozen` uses the persistent global workspace. See [usage](usage.md) for workspace rules. -## Start the browser UI +## Start the HTTP API -The browser UI is unmaintained. Run `kyrozen` for the maintained terminal interface. +The source checkout provides `kyrozen-api` and its compatibility alias `kyrozen-web`. With the pinned v3.0.0 release, use `kyrozen-web`. ```sh -kyrozen-web --host 127.0.0.1 --port 8000 +kyrozen-api --host 127.0.0.1 --port 8000 ``` -Open `http://127.0.0.1:8000`. To bind beyond loopback, set a non-empty `KYROZEN_SERVER_TOKEN` before starting the server and protect that secret. The server refuses unauthenticated non-loopback clients when no token is configured. See [security](security.md) and the [API guide](api.md). +Run `curl http://127.0.0.1:8000/api/health` in a second terminal. To bind beyond loopback, set a non-empty `KYROZEN_SERVER_TOKEN` before starting the server and protect that secret. The server refuses unauthenticated non-loopback clients when no token is configured. See [security](security.md) and the [API guide](api.md). ## Configure a provider diff --git a/docs/native-project-intelligence.md b/docs/native-project-intelligence.md index 10a26a05..2d5f6d2c 100644 --- a/docs/native-project-intelligence.md +++ b/docs/native-project-intelligence.md @@ -21,8 +21,8 @@ Ask and Plan can use `graph_status`, `graph_query`, `graph_explain`, cache. Failed updates restore the last valid graph. Query output maps private mirror paths back to project paths before it reaches the model or UI. -The Bubble Tea activity rail always shows a deterministic community-colored -mini-map. Press `g` or use `/graph open`; then use arrows or `hjkl` to select, +Open the project graph with `/graph open`. Its detail screen lists nodes, +neighbors and source locations. Use arrows or `hjkl` to select, `+`/`-` to zoom, `/` to search, `Tab` to cycle communities, `Enter` for neighbors, `p` to select path endpoints, `r` to refresh, and `Esc` to close. Mouse clicks select and the wheel zooms. diff --git a/docs/security.md b/docs/security.md index 57eb8ab5..7dd6f8f0 100644 --- a/docs/security.md +++ b/docs/security.md @@ -29,11 +29,11 @@ Downloaded skills and plugins execute or influence behavior according to their i ## Server authentication -Loopback web requests may be made without a token. If `KYROZEN_SERVER_TOKEN` is set, API and MCP callers must send it as `Authorization: Bearer TOKEN` or `X-Kyrozen-Token: TOKEN`. The browser login route exchanges the configured token for a short-lived HttpOnly browser session; cookies are not API bearer tokens. Without a token, direct non-loopback requests are rejected. +Direct loopback API requests may be made without a token. If `KYROZEN_SERVER_TOKEN` is set, API and MCP callers must send it as `Authorization: Bearer TOKEN` or `X-Kyrozen-Token: TOKEN`. Without a token, direct non-loopback requests are rejected. ```sh export KYROZEN_SERVER_TOKEN="a-long-random-secret" -kyrozen-web --host 0.0.0.0 --port 8000 +kyrozen-api --host 0.0.0.0 --port 8000 curl -H "Authorization: Bearer $KYROZEN_SERVER_TOKEN" \ http://127.0.0.1:8000/api/health ``` diff --git a/docs/self-evolution.md b/docs/self-evolution.md index bd7d6558..2749a71b 100644 --- a/docs/self-evolution.md +++ b/docs/self-evolution.md @@ -120,16 +120,16 @@ explicit user confirmation is required. For research, requested sources, structure, or artifact creation must be observable, or the user must confirm success. Otherwise the run remains unverified. -## Web API +## HTTP API Install the web extras and start the server: ```bash pip install -e '.[web]' -KYROZEN_SERVER_TOKEN=change-me kyrozen-web --project . --host 127.0.0.1 --port 8000 +KYROZEN_SERVER_TOKEN=change-me kyrozen-api --project . --host 127.0.0.1 --port 8000 ``` -Loopback requests may omit the token. Any non-loopback deployment must send +Loopback requests may omit the token only when no token is configured. Clients of any token-protected deployment must send `Authorization: Bearer ` (or `X-Kyrozen-Token`) and should bind to an explicit interface. diff --git a/docs/subagents.md b/docs/subagents.md index 6f4de99c..5c98963c 100644 --- a/docs/subagents.md +++ b/docs/subagents.md @@ -125,8 +125,8 @@ identicon. After the first cycle, names use suffixes such as `Evan2`, then ## Surfaces -The TUI activity rail shows name/icon, specialty, objective, provider/model and -state, including singleton reviewers. `/agents` or `Ctrl+E` opens inspection, including while a turn is running. +Open the agent inspector with `/agents` or `Ctrl+E`, including while a turn is running. +It shows each agent’s name, icon, specialty, assignment, provider/model and state. Use left/right to choose agents, arrows/PgUp/PgDn to scroll, Enter to load complete assignment/history/receipts/reviews, `c` to cancel and Esc/q to return to the composer. Reviewers have their own identity/icon in inspection. Snapshots and diff --git a/docs/tasks-and-automation.md b/docs/tasks-and-automation.md index 3d073aa7..3a14361e 100644 --- a/docs/tasks-and-automation.md +++ b/docs/tasks-and-automation.md @@ -62,7 +62,7 @@ An ordinary Working Plan task can declare a command check with a `criterion` and A builtin input error rejected before any plan transaction may be corrected by a later successful plan edit in the same turn. It stops blocking turn completion only after the same scoped, nonempty Working Plan completes with verified task evidence; the failed receipt remains in history. A transaction attempt, including a rollback or unknown/post-commit outcome, is never treated as this no-effect input correction. Denials and failed reads or effects retain their failure evidence. -The TUI and Web chat show the current Working Plan revision, its user-facing revision reason, and tasks in scheduler order. Progress is updated from typed task events; successful tasks are shown as verified, and cancelled replacements remain marked as superseded. The Web view restores the active plan snapshot when a saved session is reopened. These observer projections contain task descriptions, statuses, supersession links, and rationale only; execution evidence and tool arguments remain private. +The TUI shows the current Working Plan revision, its user-facing revision reason, and tasks in scheduler order. Progress is updated from typed task events; successful tasks are shown as verified, and cancelled replacements remain marked as superseded. API clients can read the active plan snapshot from the saved session endpoint. These observer projections contain task descriptions, statuses, supersession links, and rationale only; execution evidence and tool arguments remain private. The tool executor makes at most one automatic retry, and only when a typed error marks a normal-risk read or an allowlisted built-in network lookup as retriable. It rechecks task binding and child cancellation before dispatching the retry. Filesystem, process, Git, stateful, custom network, and other mutation-capable calls are never automatically retried. After interruption or restart, unfinished side effects remain uncertain; inspect the current workspace and recorded receipts before requesting the mutation again. @@ -90,4 +90,4 @@ IP hostname checks cannot fully prevent DNS rebinding. Run with outbound firewal ## Inspect and recover -Use the web UI's task and agent panels, `/api/v2/tasks`, `/api/v2/agents/runs`, and `/api/v2/agents/runs/{run_id}` to inspect status. Correct an incomplete goal or replay a failed request only after reading tool receipts and checking whether its earlier actions took effect. See [history and rollback](history-and-rollback.md) for conversation restore and [memory and storage](memory-and-storage.md) for durable state. +Use `/api/v2/tasks`, `/api/v2/agents/runs`, and `/api/v2/agents/runs/{run_id}` to inspect status. Correct an incomplete goal or replay a failed request only after reading tool receipts and checking whether its earlier actions took effect. See [history and rollback](history-and-rollback.md) for conversation restore and [memory and storage](memory-and-storage.md) for durable state. diff --git a/docs/tool-inventory.md b/docs/tool-inventory.md index c0b564fc..30f2528b 100644 --- a/docs/tool-inventory.md +++ b/docs/tool-inventory.md @@ -10,7 +10,7 @@ Run `make docs-check` after changing a tool, endpoint, or MCP contract. - Built-in runtime tools: **55** - Names with the `git_` prefix: **14** - The CLI Action contract is a plain string in the `args` field. -- Web and MCP exposure is filtered by the configured capability profile. +- REST and MCP exposure is filtered by the configured capability profile. | Tool | Capability | Side effects | Parallel safe | Plain-string Action contract | MCP object input schema | |---|---|---|---|---|---| @@ -77,9 +77,6 @@ Parameterized names are part of the contract; clients may substitute a value for | Method | Path | |---|---| -| `GET` | `/` | -| `DELETE` | `/api/auth/session` | -| `POST` | `/api/auth/session` | | `POST` | `/api/chat` | | `POST` | `/api/chat/stream` | | `POST` | `/api/chat/{session_id}/cancel` | @@ -134,6 +131,7 @@ Parameterized names are part of the contract; clients may substitute a value for | `POST` | `/api/webhooks/register` | | `POST` | `/api/webhooks/test` | | `POST` | `/mcp` | +| `GET` | `/openapi.json` | ## Compatibility contract diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 59356b31..af519dda 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -20,7 +20,7 @@ Check that the selected provider name matches `/provider`, that its key is prese If the agent sees the wrong files, inspect `--project`, `KYROZEN_WORKSPACE_ROOT`, and `/project`; an existing session retains its original workspace. If an action is rejected, inspect the interaction mode, permission profile, required tool capability, and approval response. Ask/Plan cannot be made writable by model instructions. -For HTTP 401, provide a valid bearer token or `X-Kyrozen-Token`. For a 503 on a non-loopback connection, configure `KYROZEN_SERVER_TOKEN` and restart the server. Browser authentication uses a short-lived browser cookie after login; it does not authorize unrelated API clients. Do not put the token in a query string. +For HTTP 401, provide a valid bearer token or `X-Kyrozen-Token`. For a 503 on a non-loopback connection, configure `KYROZEN_SERVER_TOKEN` and restart the server. Do not put the token in a query string. ## Memory and learning diff --git a/docs/usage.md b/docs/usage.md index 4dd14830..54689652 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -10,12 +10,28 @@ kyrozen --project /path/to/repo # operate on a project kyrozen --global # explicit spelling of the global mode ``` -The same choice is available in the web server: +To use the same workspace through the API: ```bash -kyrozen-web --project /path/to/repo --port 8000 +kyrozen-api --project /path/to/repo --port 8000 ``` +## Work in the terminal + +On first launch, choose a provider, enter its key if prompted, choose a model, and review permissions. Open `/settings` later to change terminal preferences. + +| To | Use | +| --- | --- | +| Send a message, or queue it while Kyrozen works | Enter | +| Add another line to your draft | Ctrl+J | +| Find an action while keeping your draft | Ctrl+P, then type to filter | +| Read earlier messages and return to the latest reply | Mouse wheel or PgUp/PgDn, then End | +| Expand or collapse a tool result | Click its summary, or use Ctrl+R for the latest visible result | +| Switch projects and chats | Ctrl+B | +| Read project instructions or inspect tasks and usage | `/instructions`, `/tasks`, `/usage` | + +Open `/queue` to review follow-ups for the current chat. Enter edits the selected message, D removes it, and R resumes a paused queue. Drafts and queues are kept per chat while the terminal is open. + ## Interaction modes | Mode | Use | Boundary | @@ -48,19 +64,18 @@ Set the preference with /mode auto, /mode ask, /mode plan, or /mode agent. Plan Type / at the start of a line to open the command palette. A slash inside a URL, path, or normal sentence remains ordinary text. -## Web mode +## HTTP API -The browser UI is unmaintained. Use `kyrozen` for interactive sessions in the terminal. +Start the server with `kyrozen-api` from a source install. The v3.0.0 release names this command `kyrozen-web`. In another terminal, check its health: ```bash -kyrozen-web -open http://localhost:8000 +curl http://127.0.0.1:8000/api/health ``` For LAN or container use, bind explicitly and set a token: ```bash -KYROZEN_SERVER_TOKEN=change-me kyrozen-web --host 0.0.0.0 --port 8000 +KYROZEN_SERVER_TOKEN=change-me kyrozen-api --host 0.0.0.0 --port 8000 ``` See the [API guide](api.md) for authentication, streaming, and route details. diff --git a/docs/v3-finalization-status.md b/docs/v3-finalization-status.md index 946d277f..6fcb4e43 100644 --- a/docs/v3-finalization-status.md +++ b/docs/v3-finalization-status.md @@ -10,7 +10,7 @@ OpenKyrozen v3.0.0 shipped on December 2, 2026. The signed tag points to `b63c91 | Public installation | The public installers passed on Ubuntu, macOS and Windows, including Windows PowerShell 5.1 and PowerShell 7. The English and Chinese install pages point to the release. [Installer results](https://github.com/EvanProgramming/OpenKyrozen/actions/runs/46887391680) | | Formal live benchmarks | R259 (protocol recovery), R262 (replanning), R263 (matched task success) and R264 (request and token efficiency) were skipped and remain unmeasured. The maintainer closed both benchmark issues as not planned. [Matched comparison and protocol recovery](https://github.com/EvanProgramming/OpenKyrozen/issues/266) · [Replanning and churn](https://github.com/EvanProgramming/OpenKyrozen/issues/267) | -The browser UI bundled with V3 is unmaintained. The CLI and terminal UI are the maintained interactive interfaces. [Support](../SUPPORT.md) +The CLI and terminal UI are the supported interactive interfaces. [Support](../SUPPORT.md) ## Implemented safeguards diff --git a/install.ps1 b/install.ps1 index 9a1b3fdd..a39433b5 100644 --- a/install.ps1 +++ b/install.ps1 @@ -243,5 +243,6 @@ Write-Output "" Write-Output "Installation complete." Write-Output " kyrozen Start the full-screen terminal UI" Write-Output " kyrozen --project . Work directly in the current project" -Write-Output " kyrozen-web Start the local web server" +$apiCommand = if (Test-Path (Join-Path $localBin "kyrozen-api.exe")) { "kyrozen-api" } else { "kyrozen-web" } +Write-Output " $apiCommand Start the HTTP API server" Write-Output "The first kyrozen launch will open Bubble Tea onboarding for provider and self-learning setup; updates preserve existing settings. This installer never handles API keys." diff --git a/install.sh b/install.sh index fbfe8226..06ceae9d 100755 --- a/install.sh +++ b/install.sh @@ -228,9 +228,14 @@ case "$installed_version" in esac "$kyrozen_bin" --help >/dev/null +api_command='kyrozen-api' +if [ ! -x "$(dirname "$kyrozen_bin")/$api_command" ]; then + api_command='kyrozen-web' +fi + printf '%s\n' '' 'Installation complete.' \ ' kyrozen Start the full-screen terminal UI' \ ' kyrozen --project . Work directly in the current project' \ - ' kyrozen-web Start the local web server' \ + " $api_command Start the HTTP API server" \ '' 'Restart your shell if the kyrozen command is not yet available.' \ 'The first kyrozen launch will open Bubble Tea onboarding for provider and self-learning setup; updates preserve existing settings. This installer never handles API keys.' diff --git a/openkyrozen/interfaces/cli/onboarding.py b/openkyrozen/interfaces/cli/onboarding.py index 77c86ddb..cdbae513 100644 --- a/openkyrozen/interfaces/cli/onboarding.py +++ b/openkyrozen/interfaces/cli/onboarding.py @@ -4,7 +4,6 @@ import os import sys from typing import Any -from rich.panel import Panel from openkyrozen.tasks.engine import TaskWorker from openkyrozen.providers import ProviderConfig, PROVIDER_ENV_VARS, PROVIDER_FALLBACKS @@ -77,27 +76,8 @@ def _print_banner(self, config: ProviderConfig | None = None) -> None: config = config or self._provider_config provider_name = config.provider.title() if config else "Unknown" model_name = config.model_simple if config else "unresolved" - fallback_names = self._available_fallback_names(config) - fallback_status = "" - if fallback_names: - fallback_status = f" {self._DOT} Fallbacks available: {', '.join(name.title() for name in fallback_names)}" - # Platform tag - if self._IS_WINDOWS: - platform_tag = "Windows" - elif self._IS_MACOS: - platform_tag = "macOS" - elif self._IS_LINUX: - platform_tag = "Linux" - else: - platform_tag = self._PLATFORM - banner = ( - f"[bold white]OPEN[/bold white][bold {self._ACCENT}]KYROZEN[/bold {self._ACCENT}]\n" - f"[{self._MUTED}]self{self._NBHYPHEN}learning AI agent {self._DOT} " - f"{provider_name} {self._DOT} {model_name}{fallback_status}[/{self._MUTED}]\n" - f"[{self._MUTED}]Platform: {platform_tag} {self._DOT} Python " - f"{sys.version_info.major}.{sys.version_info.minor}[/{self._MUTED}]" - ) - self.console.print(Panel(banner, border_style=self._ACCENT_DIM, padding=(1, 2), expand=False)) + self.console.print(f"[bold {self._ACCENT}]OpenKyrozen[/] {provider_name} · {model_name}") + self.console.print(f"[{self._MUTED}]/help for commands · /quit to close[/]") def _run_recovered_tasks(self, *, max_tasks: int = 20) -> list[dict[str, Any]]: diff --git a/openkyrozen/interfaces/tui/backend.py b/openkyrozen/interfaces/tui/backend.py index 3c95cbbd..fe2a0674 100644 --- a/openkyrozen/interfaces/tui/backend.py +++ b/openkyrozen/interfaces/tui/backend.py @@ -217,7 +217,7 @@ def validate(payload: Any) -> tuple[dict[str, Any] | None, str | None]: from .navigation import (_new_chat_id, _register_chat, _chat_title, _scope_chats, _navigation_groups, navigation, _bind_chat, _switch_chat, _emit_bound_state, _delete_navigation_item, _delete_navigation_item_locked, _trash_project, _trash_vectors, _history_path, _remove_tree) from .onboarding import (start, _check_for_update, prompt_api_key, prompt_provider, prompt_model, - configure_main_model, _prompt_onboarding_learning, _complete_onboarding, + configure_main_model, _complete_onboarding, _continue_onboarding, configure_provider, custom_provider_command, custom_provider_input_prompt, custom_provider_input) diff --git a/openkyrozen/interfaces/tui/commands.py b/openkyrozen/interfaces/tui/commands.py index fa5e3129..0bbe2560 100644 --- a/openkyrozen/interfaces/tui/commands.py +++ b/openkyrozen/interfaces/tui/commands.py @@ -22,6 +22,14 @@ def _command(self, name: str, args: Any, request_id: str) -> None: session = runtime.current_session cancelled = runtime.cancel_turn(session.session_id, user_id=session.memory.user_id) self.emit("response", request_id, text="Cancellation requested." if cancelled else "No active turn to cancel.") + elif command in {"/instructions", "instructions"}: + from openkyrozen.skills.instructions import load_instructions + for layer in load_instructions(runtime._get_workspace_root()): + content = _redact(layer["content"], limit=len(layer["content"])) + self.emit("instruction_source", request_id, path=layer["path"]) + for start in range(0, len(content), 6000): + self.emit("instruction_text", request_id, text=content[start:start + 6000]) + self.emit("instructions_complete", request_id) elif command in {"/quit", "/exit", "quit", "exit", "shutdown"}: self.stop() elif command in {"/provider", "provider"}: @@ -110,11 +118,8 @@ def _command(self, name: str, args: Any, request_id: str) -> None: try: mode = runtime.set_learning_policy(str(args.get("mode") or args["policy"])) self.emit("response", request_id, text=f"learning mode: {mode}") - if args.get("onboarding") and self._onboarding_kind == "new": - self._complete_onboarding(request_id) - else: - self.emit("prompt", request_id, kind="self_learning", features=self._features(), - runtime=runtime.learning_runtime(), cost_source=runtime.learning_cost_source()) + self.emit("prompt", request_id, kind="self_learning", features=self._features(), + runtime=runtime.learning_runtime(), cost_source=runtime.learning_cost_source()) except ValueError as exc: self.emit("error", request_id, text=str(exc)) elif isinstance(args, Mapping) and args.get("feature") in runtime._SELF_LEARNING_FLAGS: @@ -254,7 +259,10 @@ def _command(self, name: str, args: Any, request_id: str) -> None: mode, jev_api_key=args.get("api_key") if isinstance(args, Mapping) else None, ) self.emit("response", request_id, text=f"Permissions set to {state['permission_mode']}.") - self.interaction(request_id) + if self._onboarding_kind: + self._complete_onboarding(request_id) + else: + self.interaction(request_id) except (runtime.InteractionError, RuntimeError, OSError, ValueError) as exc: self.emit("error", request_id, code="invalid_permissions", error=str(exc)) elif command in {"/mode", "mode"}: @@ -363,7 +371,7 @@ def _command(self, name: str, args: Any, request_id: str) -> None: self._quiet_call( runtime.restore_history, target["id"], confirm="rollback", expected_head=current["id"], ) - self.navigation(request_id) + self.navigation(request_id, replace_messages=True) self.interaction(request_id) self.graph_state(request_id) self.usage(request_id) diff --git a/openkyrozen/interfaces/tui/navigation.py b/openkyrozen/interfaces/tui/navigation.py index f61e1f32..120922ac 100644 --- a/openkyrozen/interfaces/tui/navigation.py +++ b/openkyrozen/interfaces/tui/navigation.py @@ -114,7 +114,7 @@ def _navigation_groups(self) -> list[dict[str, Any]]: return groups -def navigation(self, request_id: str | None = None) -> None: +def navigation(self, request_id: str | None = None, *, replace_messages: bool = False) -> None: runtime = self.agent context = runtime.get_launch_context() messages = [] @@ -130,7 +130,7 @@ def navigation(self, request_id: str | None = None) -> None: active_scope_id=runtime.interaction_workspace_id(context), scope=context.mode if context else "global", workspace=str(runtime._get_workspace_root()), - groups=self._navigation_groups(), messages=messages, + groups=self._navigation_groups(), messages=messages, replace_messages=replace_messages, ) diff --git a/openkyrozen/interfaces/tui/onboarding.py b/openkyrozen/interfaces/tui/onboarding.py index bd17cfda..b0dfc38a 100644 --- a/openkyrozen/interfaces/tui/onboarding.py +++ b/openkyrozen/interfaces/tui/onboarding.py @@ -71,11 +71,7 @@ def start(self, payload: dict[str, Any], request_id: str) -> None: self.navigation(request_id) self.usage(request_id) if self._onboarding_kind: - self.emit( - "prompt", request_id, kind="onboarding", onboarding=self._onboarding_kind, - previous_version=onboarding_previous_version, - version=getattr(runtime, "RELEASE_VERSION", ""), - ) + self._continue_onboarding(request_id) elif (not configured and getattr(config, "provider", "") == "ollama" and not (config.model_main not in {"", "auto"} or config.model_simple or config.model_complex)): self.prompt_model(request_id) @@ -125,15 +121,18 @@ def prompt_provider(self, request_id: str | None = None) -> None: def prompt_model(self, request_id: str | None = None) -> None: runtime = self.agent config = runtime._provider_config or self._quiet_call(runtime.detect_provider) - choices = [] + choices = list(dict.fromkeys(["auto", *(model for model in runtime.PROVIDER_DEFAULT_MODELS.get(config.provider, ()) if model)])) + hint = "Use Tab to cycle suggestions, type a model name, or keep auto." if config.provider == "ollama": choices = [item[0] for item in runtime.discover_ollama_models(config.base_url)] + hint = "Enter an installed Ollama tag." + if choices: + hint = "Tab cycles installed tags: " + ", ".join(choices) self.emit( "prompt", request_id, kind="model", provider=config.provider, current=config.model_main or "auto", choices=choices, onboarding=bool(self._onboarding_kind), - message=("Installed Ollama models (suggestions only): " + ", ".join(choices) - if choices else "Enter the exact model name. For Ollama, choose an installed tag."), + message=hint, ) @@ -153,7 +152,7 @@ def configure_main_model(self, model: str | None = None, request_id: str | None ) self.emit("response", request_id, text=message) if configured and self._onboarding_kind == "new": - self._prompt_onboarding_learning(request_id) + self.emit("prompt", request_id, kind="permissions", selected=runtime.interaction_envelope()["permission_mode"]) elif configured and self._onboarding_kind == "update": self._complete_onboarding(request_id) elif not configured and config.provider == "ollama": @@ -166,15 +165,6 @@ def configure_main_model(self, model: str | None = None, request_id: str | None self.emit("error", request_id, code="model_setup_failed", error=_redact(exc)) -def _prompt_onboarding_learning(self, request_id: str | None = None) -> None: - runtime = self.agent - self.emit( - "prompt", request_id, kind="self_learning", features=self._features(), - runtime=runtime.learning_runtime(), cost_source=runtime.learning_cost_source(), - onboarding=True, - ) - - def _complete_onboarding(self, request_id: str | None = None) -> None: kind = self._onboarding_kind self._onboarding_kind = "" @@ -239,7 +229,7 @@ def configure_provider(self, provider: str, api_key: str | None = None, if not configured and not self._quiet_call(runtime.provider_is_configured, config): self.prompt_api_key(request_id=request_id) elif self._onboarding_kind == "new": - self._prompt_onboarding_learning(request_id) + self.prompt_model(request_id) elif self._onboarding_kind == "update": self._complete_onboarding(request_id) else: @@ -309,7 +299,7 @@ def custom_provider_input(self, value: str, request_id: str | None = None) -> No self.emit("ready", request_id, configured=True, provider="custom", model=self.agent._provider_config.model_simple) if self._onboarding_kind == "new": - self._prompt_onboarding_learning(request_id) + self.prompt_model(request_id) elif self._onboarding_kind == "update": self._complete_onboarding(request_id) except (ValueError, OSError) as exc: diff --git a/openkyrozen/interfaces/tui/turns.py b/openkyrozen/interfaces/tui/turns.py index 5e9b5978..a5a0be08 100644 --- a/openkyrozen/interfaces/tui/turns.py +++ b/openkyrozen/interfaces/tui/turns.py @@ -29,7 +29,7 @@ def set_api_key(self, api_key: str, request_id: str | None = None) -> None: main_model=config.model_main, workspace=str(runtime._get_workspace_root())) if configured and self._onboarding_kind == "new": - self._prompt_onboarding_learning(request_id) + self.prompt_model(request_id) elif configured and self._onboarding_kind == "update": self._complete_onboarding(request_id) else: diff --git a/openkyrozen/interfaces/web/auth.py b/openkyrozen/interfaces/web/auth.py index 0219b7fa..be91000b 100644 --- a/openkyrozen/interfaces/web/auth.py +++ b/openkyrozen/interfaces/web/auth.py @@ -4,40 +4,9 @@ import time import hmac import ipaddress -import secrets from pathlib import Path -from fastapi import FastAPI, Request, HTTPException, Depends -from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse -import uvicorn - -def _issue_browser_auth_session(self) -> str: - service = self - """Issue a short-lived, HttpOnly browser session without retaining the server token.""" - now = time.time() - value = secrets.token_urlsafe(32) - with service._browser_auth_lock: - expired = [key for key, deadline in service._browser_auth_sessions.items() if deadline <= now] - for key in expired: - service._browser_auth_sessions.pop(key, None) - service._browser_auth_sessions[value] = now + service._BROWSER_AUTH_TTL_SECONDS - return value - - -def _browser_auth_session_valid(self, request: Request) -> bool: - service = self - value = request.cookies.get(service._BROWSER_AUTH_COOKIE, "") - if not value: - return False - now = time.time() - with service._browser_auth_lock: - deadline = service._browser_auth_sessions.get(value) - if deadline is None: - return False - if deadline <= now: - service._browser_auth_sessions.pop(value, None) - return False - return True +from fastapi import HTTPException, Request def _is_loopback_client(self, request: Request) -> bool: @@ -63,8 +32,6 @@ def require_api_access(self, request: Request) -> None: supplied = request.headers.get("x-kyrozen-token", "").strip() if hmac.compare_digest(supplied, service._SERVER_TOKEN): return - if service._browser_auth_session_valid(request): - return raise HTTPException( status_code=401, detail="Authentication required", @@ -106,36 +73,3 @@ def _audit(self, event: str, detail: str = "", user: str = "anonymous") -> None: f.write(f"[{ts}] [{user}] {event} | {detail}\n") except Exception: pass - - -async def api_auth_session(self, request: Request): - service = self - """Exchange a user-entered server token for an HttpOnly browser session.""" - if not service._SERVER_TOKEN: - return {"authenticated": True} - body = await service._json_object(request) - supplied = str(body.get("token", "")).strip() - if not hmac.compare_digest(supplied, service._SERVER_TOKEN): - service._audit("AUTH_FAILURE", "browser bootstrap rejected") - response = JSONResponse({"detail": "Invalid server token"}, status_code=401) - response.headers["WWW-Authenticate"] = "Bearer" - return response - cookie = service._issue_browser_auth_session() - response = JSONResponse({"authenticated": True}) - response.set_cookie( - service._BROWSER_AUTH_COOKIE, cookie, max_age=service._BROWSER_AUTH_TTL_SECONDS, - httponly=True, secure=request.url.scheme == "https", samesite="strict", path="/", - ) - return response - - -async def api_auth_session_logout(self, request: Request): - service = self - """Revoke the current in-memory browser session and clear its cookie.""" - value = request.cookies.get(service._BROWSER_AUTH_COOKIE, "") - if value: - with service._browser_auth_lock: - service._browser_auth_sessions.pop(value, None) - response = JSONResponse({"authenticated": False}) - response.delete_cookie(service._BROWSER_AUTH_COOKIE, path="/") - return response diff --git a/openkyrozen/interfaces/web/chat.py b/openkyrozen/interfaces/web/chat.py index 5ed3799c..1a127c39 100644 --- a/openkyrozen/interfaces/web/chat.py +++ b/openkyrozen/interfaces/web/chat.py @@ -17,7 +17,7 @@ from openkyrozen.agent.compaction import retain_context_digests from fastapi import FastAPI, Request, HTTPException, Depends -from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse +from fastapi.responses import StreamingResponse, JSONResponse import uvicorn def _normalise_session_id(self, raw_session_id: Any) -> str: diff --git a/openkyrozen/interfaces/web/pages.py b/openkyrozen/interfaces/web/diagnostics.py similarity index 73% rename from openkyrozen/interfaces/web/pages.py rename to openkyrozen/interfaces/web/diagnostics.py index 7f2d5c8a..41840a74 100644 --- a/openkyrozen/interfaces/web/pages.py +++ b/openkyrozen/interfaces/web/diagnostics.py @@ -1,14 +1,6 @@ from __future__ import annotations - - -from fastapi import FastAPI, Request, HTTPException, Depends -from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse -import uvicorn - -async def chat_page(self): - service = self - return service.CHAT_HTML +from fastapi import Request async def fast_diagnostics(self, request: Request, session_id: str): @@ -37,15 +29,3 @@ async def fast_diagnostics(self, request: Request, session_id: str): async def decision_assist_status(self): service = self return service._agent.decision_assist_state() - - -async def pwa_manifest(self): - service = self - return { - "name": "OpenKyrozen", - "short_name": "Kyrozen", - "start_url": "/", - "display": "standalone", - "background_color": "#050608", - "theme_color": "#00f0ff", - } diff --git a/openkyrozen/interfaces/web/history.py b/openkyrozen/interfaces/web/history.py index 6c752ef4..8f59d31f 100644 --- a/openkyrozen/interfaces/web/history.py +++ b/openkyrozen/interfaces/web/history.py @@ -4,7 +4,7 @@ from openkyrozen.agent.compaction import retain_context_digests from fastapi import FastAPI, Request, HTTPException, Depends -from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse +from fastapi.responses import StreamingResponse, JSONResponse import uvicorn async def api_v2_events(self, event_type: str | None = None, session_id: str | None = None, limit: int = 100): diff --git a/openkyrozen/interfaces/web/learning.py b/openkyrozen/interfaces/web/learning.py index fe841604..8fecfc85 100644 --- a/openkyrozen/interfaces/web/learning.py +++ b/openkyrozen/interfaces/web/learning.py @@ -4,7 +4,7 @@ import asyncio from fastapi import FastAPI, Request, HTTPException, Depends -from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse +from fastapi.responses import StreamingResponse, JSONResponse import uvicorn async def api_v2_learning(self, status: str | None = None, profile: str | None = None, limit: int = 50): diff --git a/openkyrozen/interfaces/web/lifecycle.py b/openkyrozen/interfaces/web/lifecycle.py index 3e9f9c59..d8f70f6b 100644 --- a/openkyrozen/interfaces/web/lifecycle.py +++ b/openkyrozen/interfaces/web/lifecycle.py @@ -5,7 +5,7 @@ from pathlib import Path from fastapi import FastAPI, Request, HTTPException, Depends -from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse +from fastapi.responses import StreamingResponse, JSONResponse import uvicorn def _load_plugins(self): @@ -71,7 +71,7 @@ def _server_parser(self): service = self import argparse - parser = argparse.ArgumentParser(description="OpenKyrozen Web Server") + parser = argparse.ArgumentParser(description="OpenKyrozen HTTP API server") mode = parser.add_mutually_exclusive_group() mode.add_argument("--project", metavar="PATH", help="operate directly on this project directory") mode.add_argument("--global", dest="global_mode", action="store_true", diff --git a/openkyrozen/interfaces/web/media.py b/openkyrozen/interfaces/web/media.py index 592dcc86..ca842972 100644 --- a/openkyrozen/interfaces/web/media.py +++ b/openkyrozen/interfaces/web/media.py @@ -4,7 +4,7 @@ import subprocess from fastapi import FastAPI, Request, HTTPException, Depends -from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse +from fastapi.responses import StreamingResponse, JSONResponse import uvicorn async def api_transcribe(self, request: Request): diff --git a/openkyrozen/interfaces/web/memory.py b/openkyrozen/interfaces/web/memory.py index 03b4f982..ded0b2a9 100644 --- a/openkyrozen/interfaces/web/memory.py +++ b/openkyrozen/interfaces/web/memory.py @@ -3,7 +3,7 @@ from openkyrozen.memory.service import MemoryBank from fastapi import FastAPI, Request, HTTPException, Depends -from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse +from fastapi.responses import StreamingResponse, JSONResponse import uvicorn async def api_memory(self, q: str = "", limit: int = 10): diff --git a/openkyrozen/interfaces/web/service.py b/openkyrozen/interfaces/web/service.py index b7f7e740..847bf752 100644 --- a/openkyrozen/interfaces/web/service.py +++ b/openkyrozen/interfaces/web/service.py @@ -3,9 +3,7 @@ import os import re import threading -from importlib import resources from fastapi import FastAPI, Depends -from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse from openkyrozen import __version__ from openkyrozen.tasks.scheduler import JobScheduler @@ -14,17 +12,9 @@ def __init__(self, application=None): self._owns_application = application is None self._application = application self._scheduler_instance = None - self.app = FastAPI(title="OpenKyrozen API", description="Self-learning AI Agent — REST API + Web Chat", version=__version__) + self.app = FastAPI(title="OpenKyrozen API", version=__version__, docs_url=None, redoc_url=None) self._SERVER_TOKEN = os.environ.get("KYROZEN_SERVER_TOKEN", "").strip() - self._BROWSER_AUTH_COOKIE = "openkyrozen_browser_session" - - self._BROWSER_AUTH_TTL_SECONDS = 3600 - - self._browser_auth_sessions: dict[str, float] = {} - - self._browser_auth_lock = threading.RLock() - self._CONFIGURED_SERVER_ACTOR = os.environ.get("KYROZEN_SERVER_ACTOR", "local").strip() self._SERVER_ACTOR_ID = (self._CONFIGURED_SERVER_ACTOR @@ -61,9 +51,6 @@ def __init__(self, application=None): self._WEBHOOK_SUMMARY_CHARS = 500 - self.app.post('/api/auth/session')(self.api_auth_session) - self.app.delete('/api/auth/session')(self.api_auth_session_logout) - self.app.get('/', response_class=HTMLResponse)(self.chat_page) self.app.get('/api/v2/system-one/diagnostics', dependencies=[Depends(self.require_api_access)])(self.fast_diagnostics) self.app.get('/api/v2/fast/diagnostics', dependencies=[Depends(self.require_api_access)])(self.fast_diagnostics) self.app.get('/api/v2/decision-assist', dependencies=[Depends(self.require_api_access)])(self.decision_assist_status) @@ -118,7 +105,6 @@ def __init__(self, application=None): self.app.post('/api/webhooks/register', dependencies=[Depends(self.require_api_access)])(self.register_webhook) self.app.get('/api/webhooks', dependencies=[Depends(self.require_api_access)])(self.list_webhooks) self.app.post('/api/webhooks/test', dependencies=[Depends(self.require_api_access)])(self.test_webhook) - self.app.get('/manifest.json')(self.pwa_manifest) self.app.on_event('startup')(self.startup) self.app.on_event('shutdown')(self.shutdown) @@ -141,17 +127,13 @@ def _scheduler(self): self._scheduler_instance.register_callback(name, self._run_scheduled_job) return self._scheduler_instance - @property - def CHAT_HTML(self): - return resources.files("openkyrozen.interfaces.web").joinpath("templates/chat.html").read_text(encoding="utf-8") - - from openkyrozen.interfaces.web.auth import (_issue_browser_auth_session, _browser_auth_session_valid, _is_loopback_client, require_api_access, _sanitize_api_message, _audit_log_path, _audit, api_auth_session, api_auth_session_logout) + from openkyrozen.interfaces.web.auth import (_is_loopback_client, require_api_access, _sanitize_api_message, _audit_log_path, _audit) from openkyrozen.interfaces.web.tasks import (_execute_durable_task, _task_manager, _task_worker, _task_scopes, _recover_task_scopes, _run_task_worker_cycle, _run_scheduled_job, api_v2_tasks, api_v2_create_task, api_v2_resume_task, api_v2_schedules, api_v2_create_schedule, api_v2_disable_schedule) from openkyrozen.interfaces.web.chat import (_normalise_session_id, _normalise_profile, _normalise_memory_actor, _normalise_memory_context, _initialise_session_defaults, _set_memory_context, _actor_for_request, _get_or_create_session, _interaction_for_session, _history_for_session, _ensure_history_baseline, _public_history_node, _apply_chat_controls, _run_session_chat, _validate_message, _server_capabilities, _allowed_server_tools, _cost_summary, _cost_report, _json_object, api_chat, api_chat_stream, api_cancel_chat) - from openkyrozen.interfaces.web.pages import (chat_page, fast_diagnostics, decision_assist_status, pwa_manifest) + from openkyrozen.interfaces.web.diagnostics import fast_diagnostics, decision_assist_status from openkyrozen.interfaces.web.memory import (api_memory, api_v2_memory, api_v2_memory_claims, api_v2_create_memory_claim, api_v2_memory_claim, api_v2_memory_forget_claim) diff --git a/openkyrozen/interfaces/web/tasks.py b/openkyrozen/interfaces/web/tasks.py index d1e16854..fa7349fa 100644 --- a/openkyrozen/interfaces/web/tasks.py +++ b/openkyrozen/interfaces/web/tasks.py @@ -6,7 +6,7 @@ from openkyrozen.security.capabilities import issue_capability_token from fastapi import FastAPI, Request, HTTPException, Depends -from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse +from fastapi.responses import StreamingResponse, JSONResponse import uvicorn def _execute_durable_task(self, task: dict[str, Any]) -> dict[str, Any]: diff --git a/openkyrozen/interfaces/web/templates/__init__.py b/openkyrozen/interfaces/web/templates/__init__.py deleted file mode 100644 index 8320b5b1..00000000 --- a/openkyrozen/interfaces/web/templates/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""OpenKyrozen templates module.""" diff --git a/openkyrozen/interfaces/web/templates/chat.html b/openkyrozen/interfaces/web/templates/chat.html deleted file mode 100644 index 8744f888..00000000 --- a/openkyrozen/interfaces/web/templates/chat.html +++ /dev/null @@ -1,768 +0,0 @@ - - - - - -OpenKyrozen Chat - - - -
-

OpenKyrozen

- Self-learning AI Agent - -
- Context: unavailable -
-
-
-
- - - - - - - - - - - System One makes typed routing decisions. Jev uses paid TypeSafe calls; local Kev-0.8B is less accurate. - - - - - - Checks learning evidence, memory relevance, and suspicious tool instructions. Jev uses paid TypeSafe calls; it never approves tools. - -
- - -
- - -
- - -
-
Ready
- - - diff --git a/openkyrozen/interfaces/web/usage.py b/openkyrozen/interfaces/web/usage.py index 02755da6..ae9d9931 100644 --- a/openkyrozen/interfaces/web/usage.py +++ b/openkyrozen/interfaces/web/usage.py @@ -3,7 +3,7 @@ from openkyrozen.providers import reset_cost_tracker from fastapi import FastAPI, Request, HTTPException, Depends -from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse +from fastapi.responses import StreamingResponse, JSONResponse import uvicorn async def api_cost(self, scope: str = "installation", session_id: str | None = None): diff --git a/openkyrozen/interfaces/web/webhooks.py b/openkyrozen/interfaces/web/webhooks.py index 09b9015a..8f66974e 100644 --- a/openkyrozen/interfaces/web/webhooks.py +++ b/openkyrozen/interfaces/web/webhooks.py @@ -7,7 +7,7 @@ from urllib.parse import urlparse from fastapi import FastAPI, Request, HTTPException, Depends -from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse +from fastapi.responses import StreamingResponse, JSONResponse import uvicorn def _redact_webhook_value(self, value: Any, limit: int = 500) -> str: diff --git a/pyproject.toml b/pyproject.toml index 64875b3f..f27cdeac 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -54,6 +54,7 @@ all = [ [project.scripts] kyrozen = "openkyrozen.interfaces.cli.launcher:main" kyrozen-backend = "openkyrozen.interfaces.tui.backend:main" +kyrozen-api = "openkyrozen.interfaces.web.app:main_entry" kyrozen-web = "openkyrozen.interfaces.web.app:main_entry" kyrozen-bootstrap-gh = "openkyrozen.tools.github_cli:main" @@ -70,7 +71,6 @@ include-package-data = true include = ["openkyrozen*", "plugins*", "prompts*", "builtin_skills*"] [tool.setuptools.package-data] -"openkyrozen.interfaces.web" = ["templates/*.html"] plugins = ["*.py"] prompts = ["*.md"] builtin_skills = ["manifest.json", "NOTICE.md", "*/SKILL.md", "*/skill.json", "*/LICENSE*", "*/NOTICE"] diff --git a/scripts/api_workflow_acceptance.py b/scripts/api_workflow_acceptance.py new file mode 100644 index 00000000..a9f71d35 --- /dev/null +++ b/scripts/api_workflow_acceptance.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python3 +"""Exercise the HTTP API and restart recovery with an offline provider fixture. + +Run with the checkout's interpreter, or run an installed candidate's interpreter +with --installed to require package imports outside the source tree. +""" +import argparse +from contextlib import closing, contextmanager +import json +import os +from pathlib import Path +import socket +import subprocess +import sys +import tempfile +import time +import urllib.error +import urllib.request + +ROOT = Path(__file__).resolve().parents[1] +TOKEN = "acceptance-token" + + +def serve(workdir, installed): + if not installed: + sys.path.insert(0, str(ROOT)) + import uvicorn + from openkyrozen.app import bootstrap + from openkyrozen.interfaces.web.app import create_app + from openkyrozen.providers.base import LLMProvider + from openkyrozen.providers.config import ProviderConfig + from openkyrozen.tools import ToolAdapters + + if installed: + source = Path(bootstrap.__file__).resolve() + if source.is_relative_to(ROOT) or "site-packages" not in source.parts: + raise AssertionError(f"Expected an installed package, imported {source}") + + class Fixture(LLMProvider): + def chat(self, messages, model=None): + prompt = next(str(msg["content"]) for msg in reversed(messages) if msg["role"] == "user") + reply = "bravo reply" if "BRAVO" in prompt else "alpha reply" + return reply, {"prompt_tokens": 1, "completion_tokens": 1} + + with closing(bootstrap.build_application(surface="web", tools=ToolAdapters(workdir))) as app: + runtime = app.runtime + config = ProviderConfig(provider="ollama", model_main="fixture", model_simple="fixture", + model_complex="fixture", base_url="http://127.0.0.1:9/v1") + runtime._provider_config = config + runtime.llm_provider = Fixture(config) + runtime.configure_launch_context(project_path=workdir) + runtime.get_provider = lambda _: runtime.llm_provider + runtime._prompt_and_init_deepseek = lambda **_: None + runtime._SELF_LEARNING_FLAGS = dict.fromkeys(runtime._SELF_LEARNING_FLAGS, False) + runtime._touch_detached_learning_heartbeat = lambda: None + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + (workdir.parent / "port").write_text(str(sock.getsockname()[1])) + uvicorn.Server(uvicorn.Config(create_app(app))).run(sockets=[sock]) + + +def request(url, path, body=None, *, token=TOKEN, expected=200): + headers = {"Content-Type": "application/json"} + if token: + headers["Authorization"] = "Bearer " + token + req = urllib.request.Request(url + path, data=json.dumps(body).encode() if body is not None else None, + headers=headers) + try: + response = urllib.request.urlopen(req, timeout=30) + except urllib.error.HTTPError as exc: + response = exc + with response: + payload = response.read() + assert response.status == expected, (path, response.status, payload) + if response.headers.get_content_type() == "text/event-stream": + return [line[6:] for line in payload.decode().splitlines() if line.startswith("data: ")] + return json.loads(payload) + + +@contextmanager +def server(workdir, env, installed): + port_file = workdir.parent / "port" + port_file.unlink(missing_ok=True) + cmd = [sys.executable, "-I", str(Path(__file__).resolve()), "--serve", str(workdir)] + if installed: + cmd.append("--installed") + with tempfile.TemporaryFile(mode="w+") as log: + process = subprocess.Popen(cmd, env=env, cwd=workdir, stdout=log, stderr=log) + try: + deadline = time.monotonic() + 60 + while process.poll() is None and time.monotonic() < deadline: + if port_file.is_file() and (port := port_file.read_text()): + url = f"http://127.0.0.1:{port}" + try: + health = request(url, "/api/health") + assert health["status"] == "ok", health + break + except urllib.error.URLError: + pass + time.sleep(0.1) + else: + log.seek(0) + raise AssertionError("API startup failed:\n" + log.read()) + yield url + finally: + process.terminate() + try: + process.wait(timeout=15) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + + +def acceptance(installed): + with tempfile.TemporaryDirectory(prefix="openkyrozen-api-") as directory: + root = Path(directory) + home = root / "home" + project = root / "project" + home.mkdir() + project.mkdir() + env = {key: value for key, value in os.environ.items() + if not key.startswith("KYROZEN_") and not key.endswith("_API_KEY")} + env.update(HOME=str(home), USERPROFILE=str(home), KYROZEN_DB_PATH=str(root / "state.sqlite3"), + KYROZEN_DISABLE_VECTOR_INDEX="1", KYROZEN_WORKSPACE_ROOT=str(project), + KYROZEN_SERVER_TOKEN=TOKEN, ANONYMIZED_TELEMETRY="False") + with server(project, env, installed) as url: + request(url, "/api/health", token=None, expected=401) + request(url, "/api/health", token="wrong", expected=401) + request(url, "/", expected=404) + schema = request(url, "/openapi.json") + assert "/mcp" in schema["paths"] and "/" not in schema["paths"] + # Register for the test event only. No webhook traffic leaves the host. + hook = {"url": "https://example.invalid/acceptance", "events": ["test"]} + registered = request(url, "/api/webhooks/register", hook) + assert registered["status"] == "registered", registered + hooks = request(url, "/api/webhooks")["webhooks"] + assert len(hooks) == 1 and hooks[0]["url"] == hook["url"], hooks + mcp = request(url, "/mcp", {"jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-06-18"}}) + assert mcp["result"]["serverInfo"]["name"] == "openkyrozen", mcp + alpha = request(url, "/api/chat", {"session_id": "alpha", "message": "Hello ALPHA"}) + assert alpha["reply"] == "alpha reply", alpha + frames = request(url, "/api/chat/stream", {"session_id": "bravo", "message": "Hello BRAVO"}) + assert frames[-1] == "[DONE]", frames + events = [json.loads(frame) for frame in frames[:-1]] + assert events[-1]["event"] == "completion" and events[-1]["reply"] == "bravo reply", events + assert "".join(e["chunk"] for e in events if e["event"] == "content") == "bravo reply", events + + with server(project, env, installed) as url: + for name in ("alpha", "bravo"): + session = request(url, "/api/v2/sessions/" + name) + replies = [m["content"] for m in session["messages"] if m["role"] == "assistant"] + assert replies == [name + " reply"], session + + print("API workflow acceptance passed (HTTP auth, OpenAPI, REST, SSE, webhooks, MCP, restart recovery).") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--installed", action="store_true") + parser.add_argument("--serve", type=Path, help=argparse.SUPPRESS) + args = parser.parse_args() + if args.serve: + serve(args.serve, args.installed) + else: + acceptance(args.installed) diff --git a/scripts/ci_changes.py b/scripts/ci_changes.py index c7a5be4f..98769fba 100644 --- a/scripts/ci_changes.py +++ b/scripts/ci_changes.py @@ -31,6 +31,7 @@ } DOCKER_FILES = {"Dockerfile", ".dockerignore", "requirements.txt"} WHEEL_SCRIPTS = { + "scripts/api_workflow_acceptance.py", "scripts/wheel_smoke.py", "scripts/tui_workflow_acceptance.py", } diff --git a/scripts/docker_persistence_smoke.sh b/scripts/docker_persistence_smoke.sh index 2d7291a3..0c0a6882 100755 --- a/scripts/docker_persistence_smoke.sh +++ b/scripts/docker_persistence_smoke.sh @@ -30,7 +30,8 @@ wait_for_server() { local response for _ in $(seq 1 90); do - if response="$(curl --silent --show-error --fail --max-time 3 \ + if [[ "$(docker inspect --format '{{.State.Health.Status}}' "$container")" == healthy ]] \ + && response="$(curl --silent --show-error --fail --max-time 3 \ -H "Authorization: Bearer ${TOKEN}" \ "http://127.0.0.1:${port}/api/health" 2>/dev/null)" \ && python3 -c 'import json, sys; data = json.load(sys.stdin); raise SystemExit(0 if data.get("status") == "ok" and data.get("provider") == "ollama" else 1)' <<<"$response"; then @@ -48,7 +49,7 @@ run_server() { local container="$1" local port="$2" - docker run --detach --name "$container" \ + docker run --detach --health-interval=2s --name "$container" \ --publish "127.0.0.1:${port}:8000" \ --env KYROZEN_PROVIDER=ollama \ --env KYROZEN_MODEL_MAIN=docker-smoke-model \ diff --git a/scripts/generate_tool_inventory.py b/scripts/generate_tool_inventory.py index 4b792fbe..3d3497d1 100755 --- a/scripts/generate_tool_inventory.py +++ b/scripts/generate_tool_inventory.py @@ -42,7 +42,7 @@ def runtime_routes(server: Any) -> list[tuple[str, str]]: """Return the documented HTTP routes registered by the FastAPI app.""" rows: set[tuple[str, str]] = set() for route in server.app.routes: - if route.path != "/" and not route.path.startswith("/api/") and route.path != "/mcp": + if not route.path.startswith("/api/") and route.path not in {"/mcp", "/openapi.json"}: continue for method in (route.methods or set()) - {"HEAD", "OPTIONS"}: rows.add((method, route.path)) @@ -88,7 +88,7 @@ def render_inventory() -> str: f"- Built-in runtime tools: **{len(tools)}**", f"- Names with the `git_` prefix: **{git_count}**", "- The CLI Action contract is a plain string in the `args` field.", - "- Web and MCP exposure is filtered by the configured capability profile.", + "- REST and MCP exposure is filtered by the configured capability profile.", "", "| Tool | Capability | Side effects | Parallel safe | Plain-string Action contract | MCP object input schema |", "|---|---|---|---|---|---|", diff --git a/scripts/installed_web_acceptance.py b/scripts/installed_web_acceptance.py deleted file mode 100644 index d9f8bf3f..00000000 --- a/scripts/installed_web_acceptance.py +++ /dev/null @@ -1,138 +0,0 @@ -#!/usr/bin/env python3 -"""Exercise installed web UI with a deterministic local provider and real HTTP/SSE. - -The --python interpreter must belong to an installed candidate outside the checkout. -Provider initialization is injected; credentials and production state are not used. -""" -from pathlib import Path -import sys - -def serve(): - import inspect, json, os, importlib.metadata - from pathlib import Path - import uvicorn - from openkyrozen.app.bootstrap import build_application, build_memory - from openkyrozen.interfaces.web.app import create_app - from openkyrozen.providers.config import ProviderConfig - from openkyrozen.providers.base import LLMProvider - from openkyrozen.tools import ToolAdapters - - class Fixture(LLMProvider): - - def chat(self, messages, model=None): - text = next((str(m['content']) for m in reversed(messages) if m['role'] == 'user'), '') - return ('UI_B_OK' if 'UI_B' in text else 'UI_A_OK', {'prompt_tokens': 1, 'completion_tokens': 1}) - root = Path(os.environ['KYROZEN_WORKSPACE_ROOT']) - app = build_application(surface='web', memory=build_memory(Path(os.environ['KYROZEN_DB_PATH'])), tools=ToolAdapters(root)) - runtime = app.runtime - config = ProviderConfig(provider='ollama', api_key='', model_simple='fixture', model_complex='fixture', base_url='http://127.0.0.1:9/v1') - runtime._provider_config = config - runtime.llm_provider = Fixture(config) - runtime.configure_launch_context(project_path=root) - runtime.get_provider = lambda _: Fixture(config) - runtime._prompt_and_init_deepseek = lambda **_: None - runtime._SELF_LEARNING_FLAGS = {key: False for key in runtime._SELF_LEARNING_FLAGS} - runtime._touch_detached_learning_heartbeat = lambda: None - distribution = importlib.metadata.distribution('openkyrozen') - print(json.dumps({'installed_source': inspect.getsourcefile(build_application), 'version': distribution.version, 'package_source': json.loads(distribution.read_text('direct_url.json') or '{}')}), flush=True) - uvicorn.run(create_app(app), host='127.0.0.1', port=int(os.environ['AUDIT_PORT']), log_level='info') - -def acceptance(python, output): - import json, os, socket, subprocess, tempfile, time, urllib.request - from playwright.sync_api import sync_playwright, expect - with tempfile.TemporaryDirectory(prefix='openkyrozen-installed-ui-') as directory: - root = Path(directory) - home = root / 'home' - home.mkdir() - project = root / 'project' - project.mkdir() - with socket.socket() as s: - s.bind(('127.0.0.1', 0)) - port = s.getsockname()[1] - env = os.environ.copy() - for name in list(env): - if name.endswith('_API_KEY') or name in ('PYTHONPATH', 'KYROZEN_AGENT_CONFIG', 'KYROZEN_DISABLE_VECTOR_INDEX'): - env.pop(name, None) - env.update(HOME=str(home), KYROZEN_DB_PATH=str(root / 'state.sqlite3'), KYROZEN_WORKSPACE_ROOT=str(project), KYROZEN_SERVER_TOKEN='synthetic-ui-token', AUDIT_PORT=str(port), KYROZEN_SKILLS_DIR=str(root / 'skills')) - url = f'http://127.0.0.1:{port}' - log = (root / 'server.log').open('w') - - def start(): - p = subprocess.Popen([str(python), '-I', str(Path(__file__).resolve()), '--serve'], cwd=project, env=env, stdout=log, stderr=log) - deadline = time.monotonic() + 45 - while time.monotonic() < deadline: - try: - urllib.request.urlopen(url, timeout=1) - return p - except OSError: - if p.poll() is not None: - break - time.sleep(0.2) - log.flush() - output.with_suffix('.server.log').write_text((root / 'server.log').read_text()) - p.terminate() if p.poll() is None else None - raise AssertionError('Installed UI server startup failed: ' + (root / 'server.log').read_text()[-3000:]) - p = start() - try: - with sync_playwright() as pw: - browser = pw.chromium.launch(headless=True) - page = browser.new_page() - page.goto(url) - expect(page.locator('#auth-controls')).to_be_visible() - page.locator('#server-token').fill('incorrect') - page.locator('#authenticate').click() - expect(page.locator('#auth-status')).to_contain_text('Invalid server token') - page.locator('#server-token').fill('synthetic-ui-token') - page.locator('#authenticate').click() - expect(page.locator('#auth-controls')).to_be_hidden() - page.locator('#user-input').fill('UI_A') - page.locator('#send-btn').click() - expect(page.locator('#chat')).to_contain_text('UI_A_OK', timeout=60000) - expect(page.locator('#send-btn')).to_be_enabled(timeout=60000) - page.locator('#new-session').click() - expect(page.locator('#chat')).not_to_contain_text('UI_A_OK') - page.locator('#user-input').fill('UI_B') - page.locator('#send-btn').click() - expect(page.locator('#chat')).to_contain_text('UI_B_OK', timeout=60000) - expect(page.locator('#send-btn')).to_be_enabled(timeout=60000) - page.reload() - expect(page.locator('#chat')).to_contain_text('UI_B_OK', timeout=30000) - p.terminate() - p.wait(15) - p = start() - page.reload() - expect(page.locator('#auth-controls')).to_be_visible() - page.locator('#server-token').fill('synthetic-ui-token') - page.locator('#authenticate').click() - expect(page.locator('#auth-controls')).to_be_hidden() - expect(page.locator('#chat')).to_contain_text('UI_B_OK', timeout=30000) - expect(page.locator('#chat')).not_to_contain_text('UI_A_OK') - page.screenshot(path=str(output.with_suffix('.png')), full_page=True) - browser.close() - log.flush() - source = (root / 'server.log').read_text().splitlines()[0] - assert '/site-packages/' in source, source - from audit_identity import audit_identity - result = {'identity': audit_identity(), 'status': 'PASS', 'installed_source': json.loads(source), 'checks': ['authentication', 'invalid-token', 'streaming-render', 'session-isolation', 'reload-reconnect', 'restart-recovery'], 'provider': 'deterministic local fixture; no external requests'} - output.write_text(json.dumps(result, indent=2)) - print(json.dumps(result)) - finally: - p.terminate() - p.wait(15) - log.flush() - output.with_suffix('.server.log').write_text((root / 'server.log').read_text()) - log.close() -if __name__ == '__main__': - if sys.argv[1:] == ['--serve']: - serve() - else: - import argparse, json - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--python', type=Path, required=True) - parser.add_argument('--output', type=Path, required=True) - args = parser.parse_args() - try: - acceptance(args.python.absolute(), args.output) - except Exception as exc: - args.output.write_text(json.dumps({'status': 'FAIL', 'error': str(exc)}, indent=2)) - raise diff --git a/scripts/tui_workflow_acceptance.py b/scripts/tui_workflow_acceptance.py index 0dbb42c4..4e3653c6 100644 --- a/scripts/tui_workflow_acceptance.py +++ b/scripts/tui_workflow_acceptance.py @@ -77,6 +77,16 @@ def chat(self, messages, model=None): text = 'Action: ' + json.dumps({'action': 'spawn_agents', 'args': json.dumps({'assignments': assignments})}) elif 'approval request' in latest: text = 'Action: {"action":"git_reset","args":"--hard HEAD"}' + elif 'long transcript fixture' in latest: + # Distinct endpoints survive a terminal renderer that writes + # only differing cells when scrollback lines share a prefix. + text = '\n\n'.join(['松竹梅冬青', *(f'History marker {i:03}' for i in range(1, 79)), '江海河溪流']) + elif 'hold for follow-ups' in latest: + release = Path(os.environ['KYROZEN_TUI_ACCEPTANCE_EVENTS']).with_suffix('.release') + deadline = time.monotonic() + 20 + while not release.exists() and time.monotonic() < deadline: + time.sleep(0.05) + text = 'Completed held turn.' else: text = 'Fixture reply: ' + latest return text, None @@ -156,11 +166,11 @@ def acceptance(binary: Path): KYROZEN_BACKEND_COMMAND=str(command), KYROZEN_TUI_ACCEPTANCE_EVENTS=str(events_file), TERM='xterm-256color') master, slave = pty.openpty() + initial_terminal_state = termios.tcgetattr(slave) fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack('HHHH', 35, 120, 0, 0)) process = subprocess.Popen([str(binary), 'onboarding', '--project', str(project)], stdin=slave, stdout=slave, stderr=slave, env=env, cwd=ROOT, start_new_session=True) - os.close(slave) terminal = bytearray() def drain(timeout=0.1): @@ -214,15 +224,83 @@ def submit(text): wait(lambda rows: sum(r.get('event') == 'status' and r.get('state') == 'ready' for r in rows) > ready_count, 'turn completion') + def exercise_terminal_input(): + assert not termios.tcgetattr(slave)[3] & (termios.ECHO | termios.ICANON) + ready_count = sum(r.get('event') == 'status' and r.get('state') == 'ready' for r in events()) + draft = 'draft 你好 [<65;60;20M' + send(b'draft ') + # Split both the escape introducer and its coordinates across PTY + # reads, with gaps longer than Bubble Tea's default escape timeout. + send(b'\x1b') + time.sleep(0.18) + send(b'[<65;') + time.sleep(0.45) + send(b'60;20M') + send(b'\x1b[<64;60;20M\x1b[<65;60;20M' * 32) + send(b'\x1b[200~') + for fragment in ('你'.encode()[:1], '你'.encode()[1:], '好 [<65;60;20M'.encode()): + send(fragment) + time.sleep(0.18) + send(b'\x1b[201~\r') + wait(lambda rows: any(r.get('input', {}).get('command') == 'submit' for r in rows), + 'PTY input received by backend') + received = next(r['input']['text'] for r in events() if r.get('input', {}).get('command') == 'submit') + assert received == draft, f'expected {draft!r}, backend received {received!r}' + wait(lambda rows: sum(r.get('event') == 'status' and r.get('state') == 'ready' + for r in rows) > ready_count, 'fragmented mouse and literal UTF-8 paste preserve draft') + + def rendered_since(mark, text): + data = re.sub(rb'\x1b\[[0-?]*[ -/]*[@-~]', b'', terminal[mark:]) + return text.encode() in data + + def exercise_history_and_queue(): + submit('long transcript fixture') + mark = len(terminal) + send(b'\x1b') + time.sleep(0.18) + send(b'[<64;60;20M' + b'\x1b[<64;60;20M' * 79) + wait(lambda _: rendered_since(mark, '松竹梅冬青') and rendered_since(mark, 'Latest'), + 'fragmented wheel burst scrolls to earlier history') + mark = len(terminal) + send(b'\x1b[F') + wait(lambda _: rendered_since(mark, '江海河溪流'), 'End returns to latest reply') + + mark = len(terminal) + send(b'\x10') # Ctrl+P + wait(lambda _: rendered_since(mark, 'Commands'), 'command palette') + send(b'usage\r') + wait(lambda _: rendered_since(mark, 'Session usage'), 'filtered command selection') + mark = len(terminal) + send(b'\x1b') + wait(lambda _: rendered_since(mark, '江海河溪流'), 'standalone Escape returns to conversation') + + ready_count = sum(r.get('event') == 'status' and r.get('state') == 'ready' for r in events()) + send(b'hold for follow-ups\r') + wait(lambda rows: any(r.get('input', {}).get('text') == 'hold for follow-ups' for r in rows), + 'held fixture turn') + mark = len(terminal) + send(b'first follow-up\rsecond follow-up\r/queue\r') + wait(lambda _: all(rendered_since(mark, label) for label in + ('Queued follow-ups', 'first follow-up', 'second follow-up')), + 'queue lists both follow-ups during active turn') + assert not any(r.get('input', {}).get('text') in ('first follow-up', 'second follow-up') for r in events()) + send(b'\x1b') + events_file.with_suffix('.release').touch() + wait(lambda rows: sum(r.get('event') == 'status' and r.get('state') == 'ready' + for r in rows) >= ready_count + 3, 'queued turns complete') + submissions = [r['input']['text'] for r in events() if r.get('input', {}).get('command') == 'submit'] + assert submissions[-3:] == ['hold for follow-ups', 'first follow-up', 'second follow-up'], submissions[-3:] + try: - wait(prompt('onboarding'), 'onboarding') - send(b'\r') wait(prompt('provider'), 'provider selection') send(b'\r') - wait(prompt('self_learning'), 'learning selection') - send(b'r') + wait(prompt('model'), 'model selection') + send(b'\r') + wait(prompt('permissions'), 'permission selection') + send(b'\r') wait(lambda rows: any(r.get('event') == 'onboarding_complete' for r in rows), 'setup completed') wait(lambda rows: any(r.get('event') == 'update_available' for r in rows), 'startup update notice') + exercise_terminal_input() submit('first conversation') first_session = next(r['session_id'] for r in events() if r.get('event') == 'ready' and r.get('session_id')) ready_count = sum(r.get('event') == 'ready' for r in events()) @@ -234,7 +312,7 @@ def submit(text): send(b'\x1b[B\r') # Select the older chat. wait(lambda rows: any(r.get('input', {}).get('command') == 'navigate' and r['input'].get('session_id') == first_session for r in rows), 'chat switching') - send(b'\x02') + exercise_history_and_queue() submit('/mode agent') submit('/permissions full') if not any(r.get('event') == 'interaction' and @@ -289,17 +367,30 @@ def submit(text): os.kill(process.pid, signal.SIGWINCH) wait(lambda rows: len(terminal) > previous, f'resize {width}x{height}') plain = re.sub(rb'\x1b\[[0-?]*[ -/]*[@-~]', b'', terminal).decode(errors='replace') - assert 'APPROVAL REQUIRED' in plain and 'Choose a provider' in plain + assert 'approval required' in plain.lower() and 'Choose a provider' in plain assert 'first conversation' in plain and 'second conversation' in plain - assert '2.0.5 available' in plain and 'Run /update' in plain + assert 'Update available' in plain and '/update' in plain send(b'\x1b') # Dismiss the expected error/agent dialog before the next command. drain(0.3) send(b'/update\r') wait(lambda rows: any(r.get('event') == 'restart' for r in rows), 'update command requests restart') process.wait(timeout=10) assert process.returncode == 75 - assert 'AGENTS' in plain and 'REVIEWER' in plain - print('TUI acceptance passed: startup update notice and command, onboarding, chat isolation, approvals, sub-agent updates/inspection/scrolling/cancellation, and 3 terminal sizes.') + restored = termios.tcgetattr(slave) + # macOS marks any pending input for reprocessing when canonical + # mode is restored. PENDIN is a transient kernel status bit. + for attributes in (restored, initial_terminal_state): + attributes[3] &= ~getattr(termios, 'PENDIN', 0) + assert restored == initial_terminal_state, 'TTY attributes changed after exit' + while select.select([master], [], [], 0)[0]: + drain(0) + for mode in (1049, 2004, 1002, 1006): + switches = [state for params, state in re.findall(rb'\x1b\[\?([0-9;]+)([hl])', terminal) + if str(mode).encode() in params.split(b';')] + assert b'h' in switches and switches[-1] == b'l', f'terminal mode {mode} leaked: {switches}' + assert 'Agents' in plain and 'reviewer' in plain.lower() + print('TUI acceptance passed: onboarding, fragmented mouse and paste, history, queued follow-ups, ' + 'commands, sessions, approvals, agents, updates, resize, and terminal restoration.') finally: if process.poll() is None: try: @@ -308,6 +399,7 @@ def submit(text): pass process.wait() os.close(master) + os.close(slave) if __name__ == '__main__': diff --git a/scripts/wheel_smoke.py b/scripts/wheel_smoke.py index 2560f11c..9397af03 100755 --- a/scripts/wheel_smoke.py +++ b/scripts/wheel_smoke.py @@ -14,6 +14,7 @@ import subprocess import sys import tempfile +import zipfile from pathlib import Path @@ -43,16 +44,17 @@ def _install(python: Path, artifact: Path, extras: str, *, cwd: Path, env: dict[ _run(command + [str(artifact) + extras], cwd=cwd, env=env) -def _web_smoke(python: Path, *, cwd: Path, env: dict[str, str]) -> None: +def _api_smoke(python: Path, *, cwd: Path, env: dict[str, str]) -> None: with socket.socket() as socket_probe: socket_probe.bind(("127.0.0.1", 0)) port = socket_probe.getsockname()[1] - web_env = env | {"KYROZEN_SERVER_TOKEN": "installed-smoke-token"} + api_env = env | {"KYROZEN_SERVER_TOKEN": "installed-smoke-token"} url = f"http://127.0.0.1:{port}" - with (cwd / "web.log").open("w+") as log: - process = subprocess.Popen([str(python), "-m", "openkyrozen.interfaces.web.app", + executable = python.parent / ("kyrozen-api.exe" if os.name == "nt" else "kyrozen-api") + with (cwd / "api.log").open("w+") as log: + process = subprocess.Popen([str(executable), "--global", "--host", "127.0.0.1", "--port", str(port)], - cwd=cwd, env=web_env, stdout=log, stderr=log) + cwd=cwd, env=api_env, stdout=log, stderr=log) try: deadline = time.monotonic() + 45 while time.monotonic() < deadline and process.poll() is None: @@ -65,15 +67,16 @@ def _web_smoke(python: Path, *, cwd: Path, env: dict[str, str]) -> None: time.sleep(0.2) else: log.seek(0) - raise RuntimeError("Installed web startup failed:\n" + log.read()) - with urllib.request.urlopen(url, timeout=5) as response: - assert b"OpenKyrozen" in response.read() + raise RuntimeError("Installed API startup failed:\n" + log.read()) + with urllib.request.urlopen(url + "/openapi.json", timeout=5) as response: + paths = json.load(response)["paths"] + assert "/mcp" in paths and "/api/chat/stream" in paths and "/" not in paths try: urllib.request.urlopen(url + "/api/health", timeout=5) except urllib.error.HTTPError as error: assert error.code in {401, 403} else: - raise AssertionError("Installed web API did not enforce authentication") + raise AssertionError("Installed API did not enforce authentication") finally: process.terminate() try: @@ -104,6 +107,9 @@ def main() -> int: if len(wheels) != 1: raise RuntimeError(f"expected one wheel, found {wheels}") + with zipfile.ZipFile(wheels[0]) as wheel: + assert not any(name.startswith("openkyrozen/interfaces/web/templates/") for name in wheel.namelist()) + _run([sys.executable, "-m", "venv", str(venv)], cwd=ROOT, env=base_env) bin_dir = venv / ("Scripts" if os.name == "nt" else "bin") python = bin_dir / ("python.exe" if os.name == "nt" else "python") @@ -136,7 +142,7 @@ def main() -> int: raise RuntimeError(f"installed CLI did not bind the global root:\n{launched.stdout}{launched.stderr}") # Every shipped command and detached-worker module must resolve outside the source tree. - for command in ("kyrozen-backend", "kyrozen-web", "kyrozen-bootstrap-gh"): + for command in ("kyrozen-backend", "kyrozen-api", "kyrozen-web", "kyrozen-bootstrap-gh"): executable = bin_dir / (command + ".exe" if os.name == "nt" else command) _run([str(executable), "--help"], cwd=caller, env=env) backend = _run([str(bin_dir / ("kyrozen-backend.exe" if os.name == "nt" else "kyrozen-backend"))], @@ -146,7 +152,9 @@ def main() -> int: raise RuntimeError(f"installed JSONL backend did not become ready: {events}") _run([str(python), "-c", "import openkyrozen.learning.worker; import server; assert server.app.state.service._application is None"], cwd=caller, env=env) _run([str(python), "-m", "openkyrozen.learning.worker"], cwd=caller, env=env) - _web_smoke(python, cwd=caller, env=env) + _api_smoke(python, cwd=caller, env=env) + _run([str(python), str(ROOT / "scripts" / "api_workflow_acceptance.py"), "--installed"], + cwd=caller, env=env) probe_code = """ import tempfile @@ -156,7 +164,7 @@ def main() -> int: main = _application.runtime from openkyrozen.interfaces.web.service import WebService server = WebService(_application) -assert any(r.path == "/api/auth/session" and "POST" in (r.methods or set()) for r in server.app.routes) +assert server.app.docs_url is None and server.app.redoc_url is None from openkyrozen.persistence.store import EventStore from openkyrozen.tasks.engine import TaskManager @@ -215,7 +223,7 @@ def main() -> int: _install(sdist_python, sdists[0], "[web]", cwd=caller, env=base_env) _run([str(sdist_bin / ("kyrozen.exe" if os.name == "nt" else "kyrozen")), "--help"], cwd=caller, env=env) _run([str(sdist_python), "-c", probe_code], cwd=caller, env=env) - _web_smoke(sdist_python, cwd=caller, env=env) + _api_smoke(sdist_python, cwd=caller, env=env) print("Wheel and sdist installation smoke passed: all commands, resources and runtime contracts ran outside the checkout.") return 0 diff --git a/tests/test_browser_manager.py b/tests/test_browser_manager.py index 37ca9899..84e885f4 100644 --- a/tests/test_browser_manager.py +++ b/tests/test_browser_manager.py @@ -8,8 +8,8 @@ from unittest.mock import patch from openkyrozen.tools.browser_manager import BrowserManager, validate_browser_url -from openkyrozen.interfaces.web.service import WebService -server = WebService(None) + + class BrowserManagerTests(unittest.TestCase): def test_browser_url_boundary(self): with patch("openkyrozen.tools.browser_manager.socket.gethostbyname", return_value="93.184.216.34"): @@ -125,119 +125,6 @@ def log_message(self, *_args): self.assertIn("updated", clicked) closed = manager.close(session_id) self.assertIn("closed", closed) - - class ChatHandler(http.server.BaseHTTPRequestHandler): - def do_GET(self): # noqa: N802 - stdlib HTTP server contract - if self.path == "/": - body = server.CHAT_HTML.encode("utf-8") - content_type = "text/html; charset=utf-8" - elif self.path == "/api/cost": - body = b'{"summary":"initial-cost"}' - content_type = "application/json" - else: - self.send_error(404) - return - self.send_response(200) - self.send_header("Content-Type", content_type) - self.send_header("Content-Length", str(len(body))) - self.end_headers() - self.wfile.write(body) - - def log_message(self, *_args): - return - - chat_httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), ChatHandler) - chat_thread = threading.Thread(target=chat_httpd.serve_forever, daemon=True) - chat_thread.start() - playwright = None - browser = None - try: - from playwright.sync_api import sync_playwright - - playwright = sync_playwright().start() - browser = playwright.chromium.launch(headless=True) - page = browser.new_page() - page.add_init_script(r""" -const originalFetch = window.fetch.bind(window); -let streamCall = 0; -window.fetch = async (input, init) => { - const url = typeof input === 'string' ? input : input.url; - if (url.endsWith('/api/cost')) { - return new Response(JSON.stringify({summary: 'initial-cost'}), { - status: 200, headers: {'Content-Type': 'application/json'} - }); - } - if (!url.endsWith('/api/chat/stream')) return originalFetch(input, init); - streamCall += 1; - const frames = streamCall === 1 ? [ - 'data: {"chunk":"Hello "}\n\n', - 'data: {"chunk":"世界"}\n\n', - 'data: {"cost":"Cost: split-stream"}\n\n', - 'data: [DONE]\n\n' - ] : ['data: {"event":"error","code":"provider_unavailable","error":"No LLM provider is configured. Configure a provider before sending chat."}\n\n']; - const bytes = new TextEncoder().encode(frames.join('')); - return new Response(new ReadableStream({ - start(controller) { - let offset = 0; - let part = 0; - const sizes = [1, 4, 2, 7, 3, 5]; - function enqueueNext() { - if (offset >= bytes.length) { - controller.close(); - return; - } - const end = Math.min(bytes.length, offset + sizes[part % sizes.length]); - controller.enqueue(bytes.slice(offset, end)); - offset = end; - part += 1; - setTimeout(enqueueNext, 20); - } - enqueueNext(); - } - }), {status: 200, headers: {'Content-Type': 'text/event-stream'}}); -}; -""") - page.goto( - f"http://127.0.0.1:{chat_httpd.server_port}/", - wait_until="domcontentloaded", - ) - page.fill("#user-input", "split boundary") - page.click("#send-btn") - page.wait_for_function( - "document.querySelector('.msg.assistant .content').textContent.includes('Hello')" - ) - self.assertEqual(page.locator("#status").text_content(), "Thinking...") - page.wait_for_function( - "document.getElementById('status').textContent === 'Ready'" - ) - assistant = page.locator(".msg.assistant .content").nth(0) - self.assertEqual(assistant.text_content(), "Hello 世界") - self.assertEqual( - page.locator("#cost-display").text_content(), "Cost: split-stream" - ) - self.assertNotIn("parse error", assistant.text_content().lower()) - - page.fill("#user-input", "error boundary") - page.click("#send-btn") - page.wait_for_function( - "document.querySelectorAll('.msg.assistant .content')[1].textContent.includes('No LLM provider is configured')" - ) - page.wait_for_function( - "document.getElementById('status').textContent === 'Error'" - ) - self.assertEqual(page.locator("#status").text_content(), "Error") - self.assertEqual( - page.locator(".msg.assistant .content").nth(1).text_content(), - "Error: No LLM provider is configured. Configure a provider before sending chat.", - ) - finally: - if browser is not None: - browser.close() - if playwright is not None: - playwright.stop() - chat_httpd.shutdown() - chat_httpd.server_close() - chat_thread.join(timeout=5) finally: if manager is not None: manager.close_all() diff --git a/tests/test_context_compaction.py b/tests/test_context_compaction.py index f7fcc8ac..491b2e59 100644 --- a/tests/test_context_compaction.py +++ b/tests/test_context_compaction.py @@ -385,11 +385,7 @@ def setUp(self): def _history_stub(self): return SimpleNamespace(current=lambda: None) - def test_api_sse_ui_and_restore_expose_content_free_context_status(self): - self.assertIn('id="context-display"', server.CHAT_HTML) - self.assertIn('id="context-breakdown"', server.CHAT_HTML) - self.assertIn("function renderContext", server.CHAT_HTML) - + def test_api_sse_and_restore_expose_content_free_context_status(self): def run(session, _message, **_kwargs): session["context"] = dict(self.context) return "ok" diff --git a/tests/test_distribution.py b/tests/test_distribution.py index 28d8a934..67ce38cd 100644 --- a/tests/test_distribution.py +++ b/tests/test_distribution.py @@ -48,6 +48,7 @@ def test_ci_change_routing_covers_known_inputs_and_fails_open(self): "installer-update": (["install.ps1", "openkyrozen/updates/service.py"], {"python", "wheel", "updates", "docker"}), "package": (["pyproject.toml"], {"python", "wheel", "updates", "docker"}), "wheel-acceptance": (["scripts/wheel_smoke.py"], {"python", "wheel"}), + "api-acceptance": (["scripts/api_workflow_acceptance.py"], {"python", "wheel"}), "update-acceptance": (["scripts/update_workflow_acceptance.py"], {"python", "updates"}), "docker": (["Dockerfile"], {"docker"}), "workflow": ([".github/workflows/ci.yml"], {"all"}), @@ -106,6 +107,7 @@ def test_pyproject_exposes_both_entry_points_and_launch_module(self): self.assertEqual(project["requires-python"], ">=3.12,<3.14") self.assertEqual(project["scripts"]["kyrozen"], "openkyrozen.interfaces.cli.launcher:main") self.assertEqual(project["scripts"]["kyrozen-backend"], "openkyrozen.interfaces.tui.backend:main") + self.assertEqual(project["scripts"]["kyrozen-api"], "openkyrozen.interfaces.web.app:main_entry") self.assertEqual(project["scripts"]["kyrozen-web"], "openkyrozen.interfaces.web.app:main_entry") self.assertEqual(project["scripts"]["kyrozen-bootstrap-gh"], "openkyrozen.tools.github_cli:main") self.assertIn("tui_launcher", document["tool"]["setuptools"]["py-modules"]) @@ -163,7 +165,7 @@ def test_tag_release_workflow_validates_source_and_installed_artifacts(self): self.assertIn("RELEASE_TAG", workflow) self.assertIn('test "$tag_version" = "$package_version"', workflow) self.assertIn('python -m pip install -e ".[web]"', workflow) - self.assertIn("tests.test_server.ServerBoundaryTests.test_browser_token_bootstrap", workflow) + self.assertIn("tests.test_server.ServerBoundaryTests.test_api_token_headers_are_required_when_configured", workflow) self.assertIn("tests.test_task_consistency.TaskConsistencyTests.test_multi_task_plan", workflow) self.assertIn("python scripts/wheel_smoke.py", workflow) self.assertIn("openkyrozen-tui-", workflow) @@ -173,7 +175,7 @@ def test_tag_release_workflow_validates_source_and_installed_artifacts(self): self.assertIn("Install the tagged release with PowerShell 7", workflow) self.assertIn("irm \"https://raw.githubusercontent.com/EvanProgramming/OpenKyrozen/$env:RELEASE_TAG/install.ps1\" | iex", workflow) smoke = (ROOT / "scripts" / "wheel_smoke.py").read_text(encoding="utf-8") - self.assertIn("/api/auth/session", smoke) + self.assertIn("api_workflow_acceptance.py", smoke) self.assertIn("_task_status_counts", smoke) def test_public_install_paths_pin_the_verified_release(self): @@ -564,7 +566,7 @@ def test_launcher_passes_onboarding_subcommand_to_bubble_tea(self): def test_docker_starts_server_in_explicit_project_mode(self): dockerfile = (ROOT / "Dockerfile").read_text(encoding="utf-8") - self.assertIn('"openkyrozen.interfaces.web.app", "--project", "/app"', dockerfile) + self.assertIn('"kyrozen-api", "--project", "/app"', dockerfile) self.assertIn("pip install --no-cache-dir --no-deps .", dockerfile) diff --git a/tests/test_fast_mode.py b/tests/test_fast_mode.py index 63d1fd5b..6ec3ca01 100644 --- a/tests/test_fast_mode.py +++ b/tests/test_fast_mode.py @@ -138,17 +138,13 @@ def test_private_question_text_is_screened_before_jev_call(self): self.assertIsNone(result) request.assert_not_called() - def test_web_and_tui_controls_keep_key_out_of_replies(self): + def test_api_and_tui_controls_keep_key_out_of_replies(self): with tempfile.TemporaryDirectory() as directory, ExitStack() as sqlite_owners: memory = sqlite_owners.enter_context(closing(MemoryBank(Path(directory) / "state.sqlite3", workspace_id="fast-web"))) client = TestClient(server.app) original_sessions = server._sessions server._sessions = {} try: - page = client.get("/") - self.assertIn('id="fast-select"', page.text) - self.assertIn("Kev-0.8B", page.text) - self.assertIn('id="decision-assist-select"', page.text) with patch.object(server._agent.current_session, "memory", memory), \ patch.object(server._agent.fast_mode, "save_jev_key") as save, \ patch.object(server._agent.fast_mode, "jev_key", return_value="test-key"), \ diff --git a/tests/test_server.py b/tests/test_server.py index 77870c82..117ff667 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -618,16 +618,19 @@ def test_missing_provider_fails_honestly_across_rest_stream_and_mcp(self): ) self.assertEqual(messages, [], session_id) - def test_pwa_manifest_declares_only_served_icons(self): + def test_http_service_exposes_json_openapi_without_browser_routes(self): client = TestClient(server.app) - response = client.get("/manifest.json") - self.assertEqual(response.status_code, 200, response.text) - manifest = response.json() - for icon in manifest.get("icons", []): - icon_response = client.get(icon["src"]) - self.assertEqual(icon_response.status_code, 200, icon["src"]) - self.assertTrue(icon_response.headers["content-type"].startswith(icon["type"])) - self.assertNotIn("/static/icon.png", json.dumps(manifest)) + schema = client.get("/openapi.json") + self.assertEqual(schema.status_code, 200) + for path in ("/api/health", "/api/chat/stream", "/mcp", "/api/webhooks"): + self.assertIn(path, schema.json()["paths"]) + for method, path in (("GET", "/"), ("GET", "/manifest.json"), ("GET", "/docs"), + ("GET", "/docs/oauth2-redirect"), ("GET", "/redoc"), + ("POST", "/api/auth/session"), ("DELETE", "/api/auth/session")): + with self.subTest(method=method, path=path): + response = client.request(method, path) + self.assertEqual(response.status_code, 404) + self.assertTrue(response.headers["content-type"].startswith("application/json")) def test_ollama_initialization_requires_model_without_prompting_for_a_key(self): original_config = server._agent._provider_config @@ -932,44 +935,33 @@ def test_server_actor_is_stable_across_authentication_modes(self): self.assertEqual(server._get_or_create_session("single-user-test", "alice")["user_id"], server._SERVER_ACTOR_ID) - def test_browser_token_bootstrap_uses_httponly_cookie_and_rejects_invalid_tokens(self): - original_token = server._SERVER_TOKEN - original_sessions = dict(server._browser_auth_sessions) - server._SERVER_TOKEN = "browser-test-token" - server._browser_auth_sessions.clear() - try: - client = TestClient(server.app) - self.assertEqual(client.get("/api/v2/sessions").status_code, 401) - invalid = client.post("/api/auth/session", json={"token": "wrong-token"}) - self.assertEqual(invalid.status_code, 401) - self.assertNotIn("browser-test-token", invalid.text) - - authenticated = client.post("/api/auth/session", json={"token": "browser-test-token"}) - self.assertEqual(authenticated.status_code, 200, authenticated.text) - cookie = authenticated.headers.get("set-cookie", "") - self.assertIn("HttpOnly", cookie) - self.assertIn("SameSite=strict", cookie) - self.assertNotIn("browser-test-token", cookie) - self.assertEqual(client.get("/api/v2/sessions").status_code, 200) - - self.assertEqual(client.delete("/api/auth/session").status_code, 200) - self.assertEqual(client.get("/api/v2/sessions").status_code, 401) - finally: - server._SERVER_TOKEN = original_token - server._browser_auth_sessions.clear() - server._browser_auth_sessions.update(original_sessions) - - def test_browser_ui_uses_auth_bootstrap_and_cookie_credentials(self): - html = TestClient(server.app).get("/").text - self.assertIn('id="server-token"', html) - self.assertIn("/api/auth/session", html) - self.assertIn("credentials: 'same-origin'", html) - self.assertIn("apiFetch('/api/chat/stream'", html) - self.assertIn('id="history-panel"', html) - self.assertIn("Restore [${selector}]", html) - self.assertIn('id="history-session"', html) - self.assertIn("node.selector", html) - self.assertNotIn("localStorage.setItem('server-token'", html) + def test_tokenless_access_uses_direct_peer_address(self): + from starlette.requests import Request + + with patch.object(server, "_SERVER_TOKEN", ""): + for address in ("127.0.0.1", "::1", "192.0.2.1"): + request = Request({"type": "http", "client": (address, 8421), + "headers": [(b"x-forwarded-for", b"127.0.0.1")]}) + with self.subTest(address=address): + if address == "192.0.2.1": + with self.assertRaises(HTTPException) as error: + server.require_api_access(request) + self.assertEqual(error.exception.status_code, 503) + else: + server.require_api_access(request) + + def test_api_token_headers_are_required_when_configured(self): + client = TestClient(server.app) + with patch.object(server, "_SERVER_TOKEN", "test-token"): + for headers in ({}, {"Authorization": "Bearer wrong"}, + {"Cookie": "openkyrozen_browser_session=test-token"}): + with self.subTest(headers=headers): + response = client.get("/api/health", headers=headers) + self.assertEqual(response.status_code, 401) + self.assertEqual(response.headers["www-authenticate"], "Bearer") + for headers in ({"Authorization": "Bearer test-token"}, {"X-Kyrozen-Token": "test-token"}): + with self.subTest(headers=headers): + self.assertEqual(client.get("/api/health", headers=headers).status_code, 200) def test_profile_validation(self): self.assertEqual(server._normalise_profile(None), "auto") diff --git a/tests/test_tui_protocol.py b/tests/test_tui_protocol.py index c7215614..15284f78 100644 --- a/tests/test_tui_protocol.py +++ b/tests/test_tui_protocol.py @@ -778,7 +778,7 @@ def test_start_launches_detached_learning_worker_when_provider_is_ready(self): self.assertEqual(events[-1]["event"], "status") self.assertEqual(events[-1]["state"], "ready") - def test_new_install_onboarding_defers_provider_prompt(self): + def test_new_install_onboarding_opens_provider_picker(self): context = type("Context", (), { "active_root": Path("/tmp/openkyrozen-onboarding-workspace"), "is_global": True, @@ -800,15 +800,15 @@ def test_new_install_onboarding_defers_provider_prompt(self): events = [json.loads(line) for line in self.output.getvalue().splitlines()] prompts = [event for event in events if event["event"] == "prompt"] self.assertEqual(len(prompts), 1) - self.assertEqual(prompts[0]["kind"], "onboarding") + self.assertEqual(prompts[0]["kind"], "provider") self.assertNotIn("api_key", [event.get("kind") for event in prompts]) - def test_onboarding_learning_choice_completes_setup(self): + def test_onboarding_permission_choice_completes_setup(self): self.backend._onboarding_kind = "new" - with patch.object(self.backend.agent, "set_learning_policy", return_value="remote"), \ + with patch.object(self.backend.agent, "set_permission_mode", return_value={"permission_mode": "ask"}), \ patch.object(self.backend, "interaction"), \ patch.object(self.backend, "status"): - self.backend._command("self_learning", {"mode": "remote", "onboarding": True}, "learning-1") + self.backend._command("permissions", "ask", "permissions-1") events = [json.loads(line) for line in self.output.getvalue().splitlines()] self.assertEqual([event["event"] for event in events], ["response", "onboarding_complete"]) self.assertEqual(events[-1]["kind"], "new") @@ -955,7 +955,7 @@ def test_history_commands_require_explicit_rollback_confirmation(self): self.assertIn("chat-current", events[0]["text"]) self.assertIn("/rollback 1 confirm", events[1]["text"]) restore.assert_called_once_with("hist_current", confirm="rollback", expected_head="hist_current") - navigation.assert_called_once_with("rollback-2") + navigation.assert_called_once_with("rollback-2", replace_messages=True) interaction.assert_called_once_with("rollback-2") graph_state.assert_called_once_with("rollback-2") usage.assert_called_once_with("rollback-2") diff --git a/tests/test_web_auth.py b/tests/test_web_auth.py deleted file mode 100644 index b92c1d5a..00000000 --- a/tests/test_web_auth.py +++ /dev/null @@ -1,150 +0,0 @@ -from contextlib import ExitStack, closing -import json -import os -import socket -import subprocess -import sys -import tempfile -import time -import unittest -import urllib.error -import urllib.request -from pathlib import Path - -from openkyrozen.persistence.store import EventStore - - -class WebAuthBrowserTests(unittest.TestCase): - @staticmethod - def _free_port() -> int: - with socket.socket() as sock: - sock.bind(("127.0.0.1", 0)) - return int(sock.getsockname()[1]) - - @staticmethod - def _health(base_url: str) -> dict: - request = urllib.request.Request( - base_url + "/api/health", - headers={"Authorization": "Bearer browser-ui-token"}, - ) - with urllib.request.urlopen(request, timeout=5) as response: - return json.loads(response.read().decode("utf-8")) - - @staticmethod - def _stop_server(process: subprocess.Popen) -> None: - if process.poll() is None: - process.terminate() - process.wait(timeout=5) - if process.stdout: - process.stdout.close() - - @staticmethod - def _start_server(workspace: Path, database: Path, port: int) -> tuple[subprocess.Popen, str]: - repository = Path(__file__).parents[1] - environment = os.environ.copy() - environment.update({ - "HOME": str(workspace / "home"), - "KYROZEN_DB_PATH": str(database), - "KYROZEN_DISABLE_VECTOR_INDEX": "1", - "KYROZEN_PROVIDER": "ollama", - "KYROZEN_BASE_URL": "http://127.0.0.1:11434/v1", - "KYROZEN_SERVER_TOKEN": "browser-ui-token", - }) - for variable in ("KYROZEN_API_KEY", "DEEPSEEK_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY"): - environment.pop(variable, None) - process = subprocess.Popen( - [sys.executable, str(repository / "server.py"), "--project", str(workspace), - "--host", "127.0.0.1", "--port", str(port)], - cwd=workspace, env=environment, stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, text=True, - ) - base_url = f"http://127.0.0.1:{port}" - deadline = time.monotonic() + 20 - while time.monotonic() < deadline: - if process.poll() is not None: - output = process.stdout.read() if process.stdout else "" - raise AssertionError(f"Web server exited before becoming ready: {output}") - try: - if WebAuthBrowserTests._health(base_url).get("status") in {"ok", "degraded"}: - return process, base_url - except (OSError, urllib.error.URLError): - time.sleep(0.1) - WebAuthBrowserTests._stop_server(process) - raise AssertionError("Web server did not become ready") - - @unittest.skipUnless( - os.environ.get("KYROZEN_BROWSER_TESTS") == "1", - "browser integration requires `make install` (Playwright and Chromium)", - ) - def test_token_enabled_ui_authenticates_loads_sessions_streams_and_reports_invalid_token(self): - with tempfile.TemporaryDirectory(prefix="openkyrozen-web-auth-") as directory, ExitStack() as sqlite_owners: - root = Path(directory) - workspace = root / "workspace" - workspace.mkdir() - (workspace / "home").mkdir() - database = root / "state.sqlite3" - store = sqlite_owners.enter_context(closing(EventStore(database))) - store.append_event( - "session.message", {"role": "assistant", "content": "AUTH_UI_HISTORY"}, - user_id="local", workspace_id="default", session_id="auth-ui-session", - ) - process, base_url = self._start_server(workspace, database, self._free_port()) - playwright = browser = bad_context = None - try: - from playwright.sync_api import sync_playwright - - playwright = sync_playwright().start() - browser = playwright.chromium.launch(headless=True) - page = browser.new_page() - page.add_init_script( - "localStorage.setItem('openkyrozen.active-session', 'auth-ui-session');" - ) - stream_headers = {} - - def stream_route(route): - stream_headers.update(route.request.all_headers()) - route.fulfill( - status=200, - headers={"Content-Type": "text/event-stream"}, - body='data: {"chunk":"AUTH_UI_STREAM"}\n\ndata: [DONE]\n\n', - ) - - page.route("**/api/chat/stream", stream_route) - page.goto(base_url, wait_until="domcontentloaded") - page.wait_for_function( - "document.getElementById('auth-controls').hidden === false" - ) - page.fill("#server-token", "browser-ui-token") - page.click("#authenticate") - page.wait_for_function("document.body.innerText.includes('AUTH_UI_HISTORY')") - self.assertTrue(page.locator("#auth-controls").is_hidden()) - - page.fill("#user-input", "stream through the authenticated UI") - page.click("#send-btn") - page.wait_for_function("document.body.innerText.includes('AUTH_UI_STREAM')") - page.wait_for_function("document.getElementById('status').textContent === 'Ready'") - self.assertIn("openkyrozen_browser_session=", stream_headers.get("cookie", "")) - - bad_context = browser.new_context() - bad_page = bad_context.new_page() - bad_page.goto(base_url, wait_until="domcontentloaded") - bad_page.wait_for_function( - "document.getElementById('auth-controls').hidden === false" - ) - bad_page.fill("#server-token", "wrong-token") - bad_page.click("#authenticate") - bad_page.wait_for_function( - "document.getElementById('auth-status').textContent.includes('Invalid server token')" - ) - finally: - if bad_context is not None: - bad_context.close() - if browser is not None: - browser.close() - if playwright is not None: - playwright.stop() - self._stop_server(process) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_web_sessions.py b/tests/test_web_sessions.py deleted file mode 100644 index b7e3157b..00000000 --- a/tests/test_web_sessions.py +++ /dev/null @@ -1,212 +0,0 @@ -from contextlib import ExitStack, closing -import json -import os -import socket -import subprocess -import sys -import tempfile -import time -import unittest -import urllib.error -import urllib.request -from pathlib import Path - -from openkyrozen.persistence.store import EventStore -from openkyrozen.tasks.engine import TaskManager -from openkyrozen.workspace.context import source_scope_id - - -class WebSessionBrowserTests(unittest.TestCase): - @staticmethod - def _free_port() -> int: - with socket.socket() as sock: - sock.bind(("127.0.0.1", 0)) - return int(sock.getsockname()[1]) - - @staticmethod - def _request(base_url: str, path: str) -> dict: - request = urllib.request.Request(base_url + path) - with urllib.request.urlopen(request, timeout=5) as response: - return json.loads(response.read().decode("utf-8")) - - def _start_server(self, workspace: Path, db_path: Path, port: int) -> tuple[subprocess.Popen, str]: - repository = Path(__file__).parents[1] - env = os.environ.copy() - env.update({ - "HOME": str(workspace / "home"), - "KYROZEN_DB_PATH": str(db_path), - "KYROZEN_DISABLE_VECTOR_INDEX": "1", - # This UI fixture must not leave a detached worker writing after cleanup. - "KYROZEN_LEARNING_WORKER": "1", - "KYROZEN_PROVIDER": "ollama", - "KYROZEN_BASE_URL": "http://127.0.0.1:11434/v1", - }) - for variable in ("KYROZEN_API_KEY", "DEEPSEEK_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY", - "KYROZEN_SERVER_TOKEN"): - env.pop(variable, None) - process = subprocess.Popen( - [sys.executable, str(repository / "server.py"), "--project", str(workspace), - "--host", "127.0.0.1", "--port", str(port)], - cwd=workspace, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, - ) - base_url = f"http://127.0.0.1:{port}" - deadline = time.monotonic() + 20 - while time.monotonic() < deadline: - if process.poll() is not None: - output = process.stdout.read() if process.stdout else "" - self.fail(f"Web server exited before becoming ready: {output}") - try: - if self._request(base_url, "/api/health").get("status") in {"ok", "degraded"}: - return process, base_url - except (OSError, urllib.error.URLError): - time.sleep(0.1) - process.terminate() - process.wait(timeout=5) - self.fail("Web server did not become ready") - - @staticmethod - def _stop_server(process: subprocess.Popen) -> None: - if process.poll() is None: - process.terminate() - process.wait(timeout=5) - if process.stdout: - process.stdout.close() - - @unittest.skipUnless( - os.environ.get("KYROZEN_BROWSER_TESTS") == "1", - "browser integration requires `make install` (Playwright and Chromium)", - ) - def test_browser_restores_switches_and_retains_durable_sessions_after_restart(self): - with tempfile.TemporaryDirectory(prefix="openkyrozen-web-sessions-") as directory, ExitStack() as sqlite_owners: - root = Path(directory) - workspace = root / "workspace" - workspace.mkdir() - (workspace / "home").mkdir() - db_path = root / "state.sqlite3" - store = sqlite_owners.enter_context(closing(EventStore(db_path))) - interaction_workspace_id = source_scope_id(workspace) - for session_id, messages in { - "session-one": [("user", "first user"), ("assistant", "UI_你好_✅")], - "session-two": [("user", "second user"), ("assistant", "Second_会话_✅")], - }.items(): - for role, content in messages: - store.append_event( - "session.message", {"role": role, "content": content}, - user_id="local", workspace_id="default", session_id=session_id, - ) - tasks = TaskManager(store, workspace_id=interaction_workspace_id, session_id="session-one") - first = tasks.edit_plan(complexity="complex", expected_revision=0, operations=[ - {"op": "add", "ref": "broad", "task": { - "description": "Investigate all", "acceptance": ["Source is inspected"], - }}, - ], reason="Start with a broad inspection") - tasks.edit_plan(plan_id=first["plan_id"], expected_revision=1, operations=[ - {"op": "split", "task": first["tasks"][0]["id"], "children": [ - {"ref": "inspect", "task": {"description": "Inspect source", "acceptance": ["Source checked"]}}, - {"ref": "verify", "task": {"description": "Verify behavior", "acceptance": ["Behavior checked"]}}, - ]}, - ], reason="Separate inspection from verification") - store.append_event( - "interaction.question_requested", { - "request_id": "browser-question", "original_input": "Implement the feature", - "resume_mode": "plan", "questions": [{ - "id": "scope", "header": "Scope", "prompt": "Which browser target?", - "choices": [ - {"id": "core", "label": "Core", "description": "Limit the change"}, - {"id": "all", "label": "All", "description": "Cover every surface"}, - ], - }], - }, user_id="local", workspace_id=interaction_workspace_id, session_id="session-one", - ) - - port = self._free_port() - process, base_url = self._start_server(workspace, db_path, port) - playwright = browser = None - try: - from playwright.sync_api import sync_playwright - - playwright = sync_playwright().start() - browser = playwright.chromium.launch(headless=True) - page = browser.new_page() - page.add_init_script( - "if (!localStorage.getItem('openkyrozen.active-session')) " - "localStorage.setItem('openkyrozen.active-session', 'session-one');" - ) - page.goto(base_url, wait_until="domcontentloaded") - page.wait_for_function("document.body.innerText.includes('UI_你好_✅')") - page.wait_for_function("document.body.innerText.includes('Which browser target?')") - page.wait_for_function("document.body.innerText.includes('Working Plan · revision 2 · active')") - self.assertIn("Separate inspection from verification", page.locator("#working-plan").inner_text()) - self.assertIn("Inspect source", page.locator("#working-plan").inner_text()) - self.assertIn("Verify behavior", page.locator("#working-plan").inner_text()) - self.assertIn("superseded by", page.locator("#working-plan").inner_text()) - self.assertEqual(page.locator('#interaction-card input[type="radio"]').count(), 2) - self.assertEqual(page.locator('#interaction-card input[placeholder="Other (optional)"]').count(), 1) - self.assertEqual(page.get_by_role("button", name="Submit answers").count(), 1) - page.locator('#interaction-card input[value="core"]').check() - page.get_by_role("button", name="Cancel").click() - page.wait_for_function("document.getElementById('interaction-card').hidden") - - page.select_option("#mode-select", "plan") - page.wait_for_function("document.getElementById('status').textContent === 'Ready'") - self.assertEqual( - self._request(base_url, "/api/v2/sessions/session-one")["interaction"]["preference_mode"], - "plan", - ) - - store.append_event( - "interaction.plan_proposed", { - "plan_id": "browser-plan", "version": 1, "title": "Browser plan", - "summary": "Exercise the plan card.", "assumptions": [], - "original_input": "Implement the feature", "steps": [{ - "id": "step-1", "title": "Verify controls", - "description": "Use the browser UI.", "acceptance": ["Controls respond"], - }], - }, user_id="local", workspace_id=interaction_workspace_id, session_id="session-one", - ) - page.reload(wait_until="domcontentloaded") - page.wait_for_function("document.body.innerText.includes('Browser plan · v1')") - self.assertEqual(page.get_by_role("button", name="Accept").count(), 1) - page.get_by_role("button", name="Revise").click() - self.assertEqual(page.locator("#user-input").get_attribute("placeholder"), - "Describe the plan revision…") - page.get_by_role("button", name="Cancel").click() - page.wait_for_function("document.getElementById('interaction-card').hidden") - self.assertIsNone( - self._request(base_url, "/api/v2/sessions/session-one")["interaction"]["pending_plan"] - ) - self.assertEqual( - page.locator("#session-select").evaluate("element => element.labels[0].textContent"), - "Saved conversation", - ) - self.assertIn("durable history is never deleted", page.locator("#session-limit").text_content()) - - page.select_option("#session-select", "session-two") - page.wait_for_function("document.body.innerText.includes('Second_会话_✅')") - self.assertNotIn("first user", page.locator("#chat").inner_text()) - page.reload(wait_until="domcontentloaded") - page.wait_for_function("document.body.innerText.includes('Second_会话_✅')") - - self._stop_server(process) - process, base_url = self._start_server(workspace, db_path, port) - page.reload(wait_until="domcontentloaded") - page.wait_for_function("document.body.innerText.includes('Second_会话_✅')") - page.select_option("#session-select", "session-one") - page.wait_for_function("document.body.innerText.includes('UI_你好_✅')") - - page.evaluate( - "localStorage.setItem('openkyrozen.active-session', 'invalid/session'); location.reload();" - ) - page.wait_for_function( - "document.getElementById('status').textContent === 'Could not load this conversation.'" - ) - finally: - if browser is not None: - browser.close() - if playwright is not None: - playwright.stop() - self._stop_server(process) - - -if __name__ == "__main__": - unittest.main() diff --git a/tui/agents.go b/tui/agents.go index 365b3e58..2a2de006 100644 --- a/tui/agents.go +++ b/tui/agents.go @@ -74,7 +74,7 @@ func agentIcon(agent map[string]any) string { func (m model) agentExplorer() string { width := maxInt(1, m.width-2) - lines := []string{titleStyle.Render("AGENTS · independent contexts and verification")} + lines := []string{brandStyle.Render("Agents")} if len(m.agents) == 0 { lines = append(lines, "No delegated work in this chat.") } else { @@ -102,5 +102,5 @@ func (m model) agentExplorer() string { end := minInt(len(wrapped), start+height) body := strings.Join(wrapped[start:end], "\n") footer := "←→ agent · ↑↓/PgUp/PgDn scroll · Enter inspect · c cancel · Esc/q back" - return lipgloss.NewStyle().Width(maxInt(1, m.width)).Height(maxInt(1, m.height)).MaxHeight(maxInt(1, m.height)).MaxWidth(maxInt(1, m.width)).Render(body + "\n" + compactText(footer, width)) + return detailPage(strings.Split(body, "\n"), footer, width, m.height) } diff --git a/tui/chat_view.go b/tui/chat_view.go index 8630fe43..8ec130e1 100644 --- a/tui/chat_view.go +++ b/tui/chat_view.go @@ -1,318 +1,127 @@ package main import ( - "charm.land/lipgloss/v2" "fmt" "path/filepath" "strings" + + "charm.land/lipgloss/v2" ) func (m model) chatView() string { - contentWidth := m.contentWidth() - mainWidth, panelWidth := m.layoutWidths() - header := m.chatHeader() - historyHeight := m.historyHeight() - main := lipgloss.NewStyle().Width(mainWidth).MaxWidth(mainWidth).Height(historyHeight).MaxHeight(historyHeight).Render( - limitRows(m.view.View(), historyHeight), - ) - if panelWidth > 0 { - main = lipgloss.JoinHorizontal(lipgloss.Top, main, " ", m.activityRail()) - } - if navigationWidth := m.navigationWidth(); navigationWidth > 0 { - main = lipgloss.JoinHorizontal(lipgloss.Top, m.navigationSidebar(navigationWidth, historyHeight), " ", main) - } else if m.navigationOpen { - main = m.navigationSidebar(minInt(34, contentWidth), historyHeight) - } - blocks := []string{header} - blocks = append(blocks, main) - if progress := m.progressBlock(contentWidth); progress != "" { - blocks = append(blocks, progress) - } + width := m.contentWidth() + blocks := []string{m.chatHeader()} + history := m.view.View() + blocks = append(blocks, fitBody(history, m.historyHeight())) if len(m.palette) > 0 { - blocks = append(blocks, m.paletteView(contentWidth)) - } - blocks = append(blocks, m.modeControls(contentWidth)) - blocks = append(blocks, m.composer(contentWidth)) - blocks = append(blocks, m.chatFooter(contentWidth)) - return strings.Join(blocks, "\n") -} - -func (m model) modeControls(width int) string { - modes := []string{"auto", "ask", "plan", "agent"} - labels := []string{"AUTO", "ASK", "PLAN", "AGENT"} - modePrefix := "MODE " - compactControls := width < 32 - if compactControls { - modePrefix = "M" - labels = []string{"A", "Q", "P", "G"} - } else if width < 44 { - modePrefix = "MODE " - labels = []string{"A", "Q", "P", "G"} - } else if width < 64 { - labels[0] = "A" - } - mode := modePrefix - for index, name := range modes { - label := " " + labels[index] + " " - if compactControls { - label = labels[index] - } - if name == m.interactionMode { - mode += titleStyle.Render("[" + label + "]") - } else { - mode += mutedStyle.Render("[" + label + "]") - } - if index < len(modes)-1 && !compactControls { - mode += " " - } - } - if m.interactionMode == "auto" && m.effectiveMode != "" && m.effectiveMode != "auto" { - mode += mutedStyle.Render(" → " + strings.ToUpper(m.effectiveMode)) - } - permission := "PERMISSIONS " - labels, compactPermissions := permissionModeControlLabels(width) - choices := []struct{ id, label string }{{"ask", labels[0]}, {"full_jev", labels[1]}, {"full", labels[2]}} - permissionPrefix := "PERMISSIONS " - if compactPermissions && compactControls { - permissionPrefix = "P" - } else if width < 44 { - permissionPrefix = "ACCESS " - } - permission = permissionPrefix - for index, choice := range choices { - label := " " + choice.label + " " - if compactControls { - label = choice.label - } - if choice.id == m.permissionMode { - permission += amberStyle.Render("[" + label + "]") - } else { - permission += mutedStyle.Render("[" + label + "]") - } - if index < len(choices)-1 && !compactControls { - permission += " " - } - } - if m.permissionStatus == "checking" { - permission += amberStyle.Render(" Jev checking…") - } else if m.permissionStatus == "approval_required" { - permission += amberStyle.Render(" approval required") - } else if m.permissionMode == "full_jev" && !m.jeVConfigured { - permission += mutedStyle.Render(" Jev unavailable") - } - separator := mutedStyle.Render(" │ ") - if m.height > 0 && m.height < 18 && width >= 100 { - return lipgloss.NewStyle().Width(width).MaxWidth(width).Render(mode + separator + permission) - } - return lipgloss.NewStyle().Width(width).MaxWidth(width).Render(mode + "\n" + permission) -} - -func permissionModeControlLabels(width int) ([]string, bool) { - labels := []string{"ASK", "FULL + JEV", "FULL NO JEV"} - if width < 32 { - return []string{"A", "J", "O"}, true - } - if width < 44 { - return []string{"A", "J", "O"}, false - } - if width < 76 { - return []string{"ASK", "JEV", "NO JEV"}, false - } - return labels, false -} - -func (m model) modeControlsModeWidth(width int) int { - labels := []string{"AUTO", "ASK", "PLAN", "AGENT"} - prefix := "MODE " - if width < 32 { - prefix, labels = "M", []string{"A", "Q", "P", "G"} - } else if width < 44 { - prefix, labels = "MODE ", []string{"A", "Q", "P", "G"} - } else if width < 64 { - labels[0] = "A" - } - result := len(prefix) - for index, label := range labels { - result += len(label) + 4 - if width < 32 { - result -= 2 - } - if index < len(labels)-1 && width >= 32 { - result++ - } - } - if m.interactionMode == "auto" && m.effectiveMode != "" && m.effectiveMode != "auto" { - result += 4 + len(strings.ToUpper(m.effectiveMode)) - } - return result -} - -func (m model) modeControlsStartY() int { - rows := lipgloss.Height(m.chatHeader()) + m.historyHeight() - if progress := m.progressBlock(m.contentWidth()); progress != "" { - rows += lipgloss.Height(progress) + blocks = append(blocks, m.paletteView(width)) } - if len(m.palette) > 0 { - rows += lipgloss.Height(m.paletteView(m.contentWidth())) + blocks = append(blocks, m.chatStatus(width), m.composer(width), m.chatFooter(width)) + content := strings.Join(blocks, "\n") + if m.navigationOpen && m.screen == screenChat { + return m.bottomSheet(content, m.navigationSidebar(width, maxInt(3, m.height*2/3))) } - return rows + return content } -func (m model) modeTabAt(x, y int) int { - if y != m.modeControlsStartY() { - return -1 - } - start := len("MODE ") - labels := []string{"AUTO", "ASK", "PLAN", "AGENT"} - compactControls := m.contentWidth() < 32 - if compactControls { - start, labels = len("M"), []string{"A", "Q", "P", "G"} - } else if m.contentWidth() < 44 { - start, labels = len("MODE "), []string{"A", "Q", "P", "G"} - } else if m.contentWidth() < 64 { - labels[0] = "A" +func fitBody(content string, height int) string { + lines := strings.Split(content, "\n") + if len(lines) > height { + lines = lines[:height] } - for index, label := range labels { - padding := 4 - if compactControls { - padding = 2 - } - end := start + len(label) + padding - if x >= start && x < end { - return index - } - start = end - if !compactControls { - start++ - } - } - return -1 + return strings.Join(lines, "\n") + strings.Repeat("\n", maxInt(0, height-len(lines))) } -func (m model) permissionTabAt(x, y int) int { - row := m.modeControlsStartY() + 1 - compactHeight := m.height > 0 && m.height < 18 && m.contentWidth() >= 100 - if compactHeight { - row = m.modeControlsStartY() - } - if y != row { - return -1 +// Fit one row by dropping the lowest-priority fields before truncating either edge. +func edgeRow(left, right string, width int) string { + if right == "" { + return clipRow(left, width) } - start := len("PERMISSIONS ") - if compactHeight { - start += m.modeControlsModeWidth(m.contentWidth()) + 3 + spare := width - lipgloss.Width(right) - 2 + if spare < 4 { + return clipRow(right, width) } - labels, compactControls := permissionModeControlLabels(m.contentWidth()) - if compactControls { - start = len("P") - } else if m.contentWidth() < 44 { - start = len("ACCESS ") - } - for index, label := range labels { - padding := 4 - if compactControls { - padding = 2 - } - end := start + len(label) + padding - if x >= start && x < end { - return index - } - start = end - if !compactControls { - start++ - } - } - return -1 + left = clipRow(left, spare) + return left + strings.Repeat(" ", maxInt(2, width-lipgloss.Width(left)-lipgloss.Width(right))) + right } func (m model) chatHeader() string { width := m.contentWidth() - if width < 4 { - return brandStyle.Render(compactText("K", width)) + workspace := filepath.Base(firstNonEmpty(m.workspace, m.project, "Global")) + context := workspace + for _, group := range m.navigation { + if group.scopeID != m.activeScopeID { + continue + } + context = firstNonEmpty(group.name, workspace) + for _, chat := range group.chats { + if chat.id == m.activeSessionID { + context += " / " + firstNonEmpty(chat.title, "New chat") + break + } + } + break } - innerWidth := maxInt(1, width-2) - brand := "◆ OPENKYROZEN" - if innerWidth < 24 { - brand = "◆ KYROZEN" + left := brandStyle.Render("OpenKyrozen") + " " + mutedStyle.Render(context) + right := "" + if m.availableVersion != "" { + right = amberStyle.Render("Update available · /update") } - left := brandStyle.Render(compactText(brand, innerWidth)) - mode := strings.ToUpper(firstNonEmpty(m.effectiveMode, m.interactionMode, "ask")) + return contextStyle.Copy().Render(edgeRow(left, right, width)) +} - statusText := compactText(firstNonEmpty(m.status, "Ready"), maxInt(4, minInt(18, innerWidth/3))) - status := mutedStyle.Render("● " + statusText) +func (m model) chatStatus(width int) string { + status := m.thinkingText if m.busy { - status = amberStyle.Render(taskSpinner(m.motionFrame) + " " + statusText) - } else if strings.EqualFold(statusText, "ready") { - status = greenStyle.Render("● READY") - } - right := "" - leftBudget := innerWidth - if innerWidth >= 38 { - right = status - leftBudget = maxInt(1, innerWidth-lipgloss.Width(right)-2) + status = taskSpinner(m.motionFrame) + " " + firstNonEmpty(status, m.status, "Working…") } - add := func(item string) { - candidate := left + mutedStyle.Render(" · ") + item - if lipgloss.Width(candidate) <= leftBudget { - left = candidate - } - } - add(badgeStyle.Render(mode)) - _, panelWidth := m.layoutWidths() - if panelWidth == 0 { - graphStatus := strings.ToUpper(firstNonEmpty(m.graph.status, "missing")) - add(graphStatusStyle(graphStatus).Render("◇ " + graphStatus)) + if m.permissionStatus == "checking" { + status = "Jev checking…" + } else if m.permissionStatus == "approval_required" { + status = "Approval required" } - if m.modelName != "" { - add(softStyle.Render(compactText(m.modelName, 22))) + if hint := m.queueHint(); hint != "" { + status = strings.TrimSpace(hint + " " + status) } - tokens := m.usagePromptTokens + m.usageCompletionTokens + m.usageReasoningTokens - usage := formatUsageTokens(tokens) + " TOK" - if m.usageCostPicos > 0 { - usage += " · " + formatUsageCost(m.usageCostPicos) + if !m.followTail { + status = strings.TrimSpace("↓ Latest · End " + status) } - add(mutedStyle.Render(usage)) - - row := left - if right != "" { - gap := maxInt(2, innerWidth-lipgloss.Width(left)-lipgloss.Width(right)) - row += strings.Repeat(" ", gap) + right + if status == "" && m.status != "" && !strings.EqualFold(m.status, "ready") { + status = m.status } - header := contextStyle.Copy().Width(innerWidth).MaxWidth(innerWidth).Render(row) - if m.availableVersion != "" { - notice := "↑ OpenKyrozen " + m.availableVersion + " available · Run /update" - if width < 64 { - notice = "Update available\nRun /update" - } - if width < 20 { - notice = "Update available\n/update" - } - header += "\n" + amberStyle.Copy().Width(width).MaxWidth(width).Render(notice) + if status == "" { + return rule(width) } - return header + status = compactText(status, maxInt(1, width-4)) + return mutedStyle.Render(" "+status+" ") + rule(maxInt(1, width-lipgloss.Width(status)-3)) } func (m model) chatFooter(width int) string { - if width < 4 { - return "" + mode := firstNonEmpty(m.interactionMode, "auto") + if m.effectiveMode != "" && mode != m.effectiveMode { + mode += " → " + m.effectiveMode } - hints := "↵ send · / commands · ^C quit" - if width >= 44 { - hints = "Tab mode · Ctrl+P permissions · ↵ send · / commands · ^C quit" + access := map[string]string{"ask": "Ask before tools", "full_jev": "Full access + Jev", "full": "Full access"}[m.permissionMode] + left := brandStyle.Render(mode) + " · " + mutedStyle.Render(access) + hints := "Enter send" + if m.busy { + hints = "Enter queue" } - if width >= 72 && m.height >= 18 { - hints = "Tab mode · Ctrl+P permissions · Enter send · / commands · Ctrl+B chats · Ctrl+N new · Ctrl+O project · Ctrl+C quit" + if width >= 50 { + hints += " / Commands" } - workspace := "" - if m.workspace != "" && width >= 52 { - workspace = compactText(filepath.Base(m.workspace), maxInt(8, width/4)) + modelName := m.modelName + if m.mainModel != "" && m.mainModel != "auto" { + modelName = m.mainModel } - if workspace == "" { - return mutedStyle.Copy().Width(width).MaxWidth(width).Render(compactText(hints, width)) + if modelName != "" { + left += " · " + mutedStyle.Render(compactText(modelName, maxInt(8, width/3))) } - right := compactText(hints, maxInt(1, width-lipgloss.Width(workspace)-2)) - gap := maxInt(2, width-lipgloss.Width(workspace)-lipgloss.Width(right)) - return mutedStyle.Copy().Width(width).MaxWidth(width).Render(workspace + strings.Repeat(" ", gap) + right) + return edgeRow(left, mutedStyle.Render(hints), width) +} + +func (m model) composer(width int) string { + return composerStyle.Copy().Width(width).MaxWidth(width).Render(m.input.View()) } func (m model) paletteView(width int) string { @@ -320,7 +129,7 @@ func (m model) paletteView(width int) string { return "" } if width < 12 { - return titleStyle.Render(compactText("COMMANDS", width)) + return titleStyle.Render(compactText("Commands", width)) } rowWidth := maxInt(1, width-6) visible := maxInt(1, minInt(len(m.palette), 5)) @@ -329,9 +138,9 @@ func (m model) paletteView(width int) string { start = m.paletteIndex - visible + 1 } end := minInt(len(m.palette), start+visible) - title := fmt.Sprintf("COMMANDS %d–%d OF %d", start+1, end, len(m.palette)) + title := fmt.Sprintf("Commands %d–%d of %d", start+1, end, len(m.palette)) if len(m.palette) > visible { - title += " · ↑↓ MORE" + title += " · ↑↓ more" } lines := []string{sectionStyle.Render(title)} for index := start; index < end; index++ { @@ -353,136 +162,27 @@ func (m model) paletteView(width int) string { return paletteStyle.Copy().Width(panelWidth).MaxWidth(panelWidth).Render(strings.Join(lines, "\n")) } -func (m model) composer(width int) string { - if m.height > 0 && m.height < 12 { - return lipgloss.NewStyle().Width(width).MaxWidth(width).Render(m.input.View()) - } - panelWidth := maxInt(1, width-4) - style := composerStyle.Copy().Width(panelWidth).MaxWidth(panelWidth) - if m.input.Focused() { - style = style.BorderForeground(lipgloss.Color(cyan)) +func (m model) overPalette(y int) bool { + if len(m.palette) == 0 { + return false } - return style.Render(m.input.View()) + start := 1 + m.historyHeight() + return y >= start && y < start+lipgloss.Height(m.paletteView(m.contentWidth())) } - -func (m model) progressBlock(width int) string { - if !m.busy && m.thinkingText == "" { - return "" - } - message := firstNonEmpty(m.thinkingText, m.status, "Working…") - innerWidth := maxInt(1, width-2) - line := amberStyle.Render(taskSpinner(m.motionFrame)) + " " + softStyle.Render(compactText(message, maxInt(1, innerWidth-3))) - return contextStyle.Copy().Width(innerWidth).MaxWidth(innerWidth).Render(line) +func (m model) overLatest(x, y int) bool { + return !m.navigationOpen && !m.followTail && x >= 2 && x < 2+lipgloss.Width("↓ Latest · End") && y == m.height-m.composerHeight()-2 } - -func (m model) activityRail() string { - _, panelWidth := m.layoutWidths() - width := maxInt(1, panelWidth-2) - textWidth := maxInt(1, width-2) - height := m.historyHeight() - graphStatus := firstNonEmpty(m.graph.status, "missing") - mapHeight := 3 - if height >= 22 { - mapHeight = 5 - } - taskList := m.tasks - planTitle := fmt.Sprintf("TASKS %d", len(m.tasks)) - if m.workingPlan != nil { - taskList = m.workingPlan.tasks - planTitle = fmt.Sprintf("WORKING PLAN v%d · %s", m.workingPlan.revision, m.workingPlan.status) - } - lines := []string{ - sectionStyle.Render("PROJECT GRAPH") + " " + graphStatusStyle(graphStatus).Render(strings.ToUpper(graphStatus)), - m.graphMini(minInt(22, textWidth), mapHeight), - mutedStyle.Render(fmt.Sprintf("%d nodes · %d edges", m.graph.nodes, m.graph.edges)), - "", - sectionStyle.Render(planTitle), - } - if m.workingPlan != nil && m.workingPlan.reason != "" { - reason := lipgloss.NewStyle().Width(textWidth).MaxWidth(textWidth).Render("Reason: " + m.workingPlan.reason) - for _, line := range strings.Split(reason, "\n") { - lines = append(lines, mutedStyle.Render(line)) - } - } - if len(m.agents) > 0 { - agents := m.activityAgents() - agentLines := []string{sectionStyle.Render(fmt.Sprintf("AGENTS %d · /agents", len(agents)))} - for index, agent := range agents { - if index >= maxInt(1, minInt(3, height/8)) { - agentLines = append(agentLines, mutedStyle.Render(fmt.Sprintf("+%d more", len(agents)-index))) - break - } - brief, _ := agent["assignment"].(map[string]any) - description := compactText(stringValue(agent, "name")+" · "+stringValue(agent, "profile")+" · "+stringValue(agent, "status"), maxInt(1, textWidth-6)) - avatar := agentIcon(agent) - agentLines = append(agentLines, lipgloss.JoinHorizontal(lipgloss.Top, avatar, " ", description+"\n"+compactText(stringValue(brief, "objective"), maxInt(1, textWidth-6))+"\n"+compactText(stringValue(agent, "provider_model"), maxInt(1, textWidth-6)))) - } - lines = append(agentLines, append([]string{""}, lines...)...) - } - if len(taskList) == 0 { - lines = append(lines, mutedStyle.Render("No active tasks")) - } - maxTasks := maxInt(1, height-mapHeight-12) - planTaskNames := make(map[string]string, len(taskList)) - for _, task := range taskList { - planTaskNames[task.id] = task.description - } - for index, task := range taskList { - if index >= maxTasks { - lines = append(lines, mutedStyle.Render(fmt.Sprintf("+%d more", len(taskList)-index))) - break - } - icon, stateStyle, label := taskState(task.status, m.motionFrame) - if task.status == "succeeded" { - label = "verified" - } - if task.status == "cancelled" && len(task.supersededBy) > 0 { - label = "superseded" - } - if task.id == m.taskFlashID && m.taskFlashTick > 0 && task.status == "succeeded" { - label = "verified ·" - } - row := stateStyle.Render(icon) + " " + softStyle.Render(compactText(task.description, maxInt(4, textWidth-lipgloss.Width(label)-4))) + " " + stateStyle.Render(label) - lines = append(lines, row) - if len(task.supersededBy) > 0 { - replacements := make([]string, 0, len(task.supersededBy)) - for _, replacement := range task.supersededBy { - if description := planTaskNames[replacement]; description != "" { - replacements = append(replacements, description) - } - } - if len(replacements) > 0 { - lines = append(lines, mutedStyle.Render(compactText(" Replaced by: "+strings.Join(replacements, ", "), textWidth))) - } - } - if task.status == "blocked" && task.reason != "" { - lines = append(lines, mutedStyle.Render(compactText(" "+task.reason, textWidth))) - } - } - workspace := "global workspace" - if m.workspace != "" { - workspace = filepath.Base(m.workspace) - } - usage := "No usage yet" - if m.usageAttempts > 0 { - usage = fmt.Sprintf("%d calls · %s", m.usageAttempts, firstNonEmpty(m.usageScope, "workspace")) - } - lines = append(lines, "", sectionStyle.Render("SESSION"), softStyle.Render(compactText(workspace, textWidth)), mutedStyle.Render(compactText(usage, textWidth))) - backend := firstNonEmpty(m.fastBackend, "off") - lines = append(lines, mutedStyle.Render(compactText("System One: "+backend, textWidth))) - lines = append(lines, mutedStyle.Render(compactText("Decision Assist: "+firstNonEmpty(m.decisionAssistBackend, "off"), textWidth))) - preferredMode := firstNonEmpty(m.interactionMode, "auto") - activeMode := firstNonEmpty(m.effectiveMode, "ask") - if m.interactionMode != "" && m.effectiveMode != "" && preferredMode != activeMode { - lines = append(lines, - mutedStyle.Render(compactText("preference "+preferredMode, textWidth)), - mutedStyle.Render(compactText("active "+activeMode, textWidth)), - ) - } - // Keep the rail inside the transcript row budget. Without this cap, - // JoinHorizontal adopts a task-heavy rail's natural height and pushes the - // composer/footer below the terminal viewport. - return activityStyle.Copy().Width(width).MaxWidth(width).Height(height).MaxHeight(height).Render(limitRows(strings.Join(lines, "\n"), height)) +func (m model) sheetStartRow() int { + var sheet string + switch { + case m.navigationOpen && m.screen == screenChat: + sheet = m.navigationSidebar(m.contentWidth(), maxInt(3, m.height*2/3)) + case m.screen == screenPlan: + sheet = m.planModal(maxInt(1, m.width-6)) + case m.screen == screenApproval: + sheet = m.approvalBody() + default: + return m.height + } + return m.sheetTop(sheet) } - -func (m model) taskPanel() string { return m.activityRail() } diff --git a/tui/dialogs.go b/tui/dialogs.go index 7558efa6..ccb210a2 100644 --- a/tui/dialogs.go +++ b/tui/dialogs.go @@ -14,30 +14,41 @@ func (m model) settingsRow(index int, label, value string) string { return cursor + " " + labelStyle.Render(label) + " " + mutedStyle.Render(value) } -func (m model) modal(_ string) string { - modalWidth := maxInt(1, minInt(78, m.width-4)) +func (m model) modal(background string) string { + modalWidth := maxInt(1, m.width-2) var body string switch m.screen { case screenProvider: - lines := []string{brandStyle.Render("PROVIDER SETUP"), titleStyle.Render("Choose a provider"), mutedStyle.Render("↑↓ select Enter confirm Esc cancel"), ""} - for index, provider := range m.providerList { - cursor, style := mutedStyle.Render("·"), softStyle - rowStyle := lipgloss.NewStyle().Padding(0, 1) - if index == m.providerIdx { - cursor, style = brandStyle.Render("›"), titleStyle - rowStyle = rowStyle.Background(lipgloss.Color(surfaceHi)) + lines := []string{m.setupTitle("Providers", 1), titleStyle.Render("Choose a provider"), m.pickerPrompt(), ""} + indices := m.providerIndices() + limit := maxInt(1, m.height-8) + start := 0 + for i, id := range indices { + if id == m.providerIdx { + start = maxInt(0, i-limit+1) + break } - lines = append(lines, rowStyle.Render(cursor+" "+style.Render(provider))) } - if len(m.providerList) == 0 { - lines = append(lines, mutedStyle.Render("No providers are available.")) + for _, id := range indices[start:minInt(len(indices), start+limit)] { + marker, style := " ", softStyle + if id == m.providerIdx { + marker, style = "› ", brandStyle + } + lines = append(lines, style.Render(marker+m.providerList[id])) } - body = strings.Join(lines, "\n") + if len(indices) == 0 { + lines = append(lines, "No matching providers") + } + hint := "↑↓ select Enter choose Ctrl+F search Esc back" + if m.width < 52 { + hint = "Enter choose · Esc back" + } + return detailPage(lines, hint, m.width, m.height) case screenOnboarding: if m.onboardingKind == "update" { previous := firstNonEmpty(m.onboardingPreviousVersion, "an earlier release") body = strings.Join([]string{ - brandStyle.Render("OPENKYROZEN UPDATE"), + brandStyle.Render("OpenKyrozen update"), titleStyle.Render("Your setup is already here"), softStyle.Render(fmt.Sprintf("Updated from %s to %s.", previous, version)), mutedStyle.Render("Your provider, workspace, memory, and settings stay in place."), @@ -46,36 +57,41 @@ func (m model) modal(_ string) string { mutedStyle.Render("Ctrl+C quit"), }, "\n") } else { - body = strings.Join([]string{ - brandStyle.Render("WELCOME TO OPENKYROZEN"), - titleStyle.Render("Let’s get your workspace ready"), - softStyle.Render("This first-run setup takes care of the provider and self-learning choices."), - mutedStyle.Render("Nothing is sent anywhere until you choose a provider and start chatting."), - "", - brandStyle.Render("1") + " Choose a provider", - brandStyle.Render("2") + " Add a key if that provider needs one", - brandStyle.Render("3") + " Choose local or remote self-learning", - "", - greenStyle.Render("Enter begin setup"), - mutedStyle.Render("Ctrl+C quit"), - }, "\n") + prompt := "Enter to choose a provider" + if m.onboardingWaiting { + prompt = "Waiting for setup…" + } + body = brandStyle.Render("OpenKyrozen setup") + "\n" + mutedStyle.Render(prompt) } case screenAPIKey: - body = brandStyle.Render("API KEY SETUP") + "\n" + titleStyle.Render("Add your API key") + "\n" + mutedStyle.Render("Your key is masked and stored encrypted locally.") + "\n\n" + focusStyle.Copy().Width(maxInt(1, m.width-12)).MaxWidth(maxInt(1, m.width-12)).Render(m.apiInput.View()) + "\n\n" + mutedStyle.Render("Enter confirm · Esc cancel") + field := m.apiInput + field.Placeholder = "API key" + body = m.formBody(m.setupTitle("API key", 1), firstNonEmpty(m.apiInput.Placeholder, "Enter your API key. It is stored encrypted locally."), field.View(), "Enter confirm · Esc cancel") case screenModel: - body = brandStyle.Render("MAIN MODEL") + "\n" + titleStyle.Render("Choose one model for the main agent") + "\n" + mutedStyle.Render(firstNonEmpty(m.modelPromptMessage, "Ollama choices are suggestions; type an exact installed model tag or 'auto'.")) + "\n\n" + focusStyle.Copy().Width(maxInt(1, m.width-12)).MaxWidth(maxInt(1, m.width-12)).Render(m.apiInput.View()) + "\n\n" + mutedStyle.Render("Enter save · Esc cancel") + body = m.formBody(m.setupTitle("Main model", 2), firstNonEmpty(m.modelPromptMessage, "Enter a model tag or auto."), m.apiInput.View(), "Enter save · Esc cancel") case screenCustomProvider: - body = brandStyle.Render("CUSTOM PROVIDER") + "\n" + titleStyle.Render("Configure OpenAI-compatible profile") + "\n" + mutedStyle.Render(m.apiInput.Prompt) + "\n\n" + focusStyle.Copy().Width(maxInt(1, m.width-12)).MaxWidth(maxInt(1, m.width-12)).Render(m.apiInput.View()) + "\n\n" + mutedStyle.Render("Enter continue · Esc cancel") + field := m.apiInput + field.Prompt = "" + body = m.formBody(m.setupTitle("Custom provider", 1), m.apiInput.Prompt, field.View(), "Enter continue · Esc cancel") case screenProject: - body = brandStyle.Render("NEW PROJECT") + "\n" + titleStyle.Render("Create or open a project directory") + "\n" + mutedStyle.Render("Enter a folder path. OpenKyrozen creates it if needed and starts a new chat.") + "\n\n" + focusStyle.Copy().Width(maxInt(1, m.width-12)).MaxWidth(maxInt(1, m.width-12)).Render(m.projectInput.View()) + "\n\n" + mutedStyle.Render("Enter create / open · Esc cancel") + body = m.formBody(brandStyle.Render("New project"), "Enter a project directory. OpenKyrozen creates it if needed.", m.projectInput.View(), "Enter open · Esc cancel") case screenDeleteConfirm: + title, consequence := "Delete conversation", "Saved conversation data and history snapshots will be removed." if m.pendingDeleteKind == "delete_project" { - body = redStyle.Render("DELETE PROJECT") + "\n" + titleStyle.Render(m.pendingDeleteTitle) + "\n" + softStyle.Render(m.pendingDeletePath) + "\n\n" + mutedStyle.Render("The workspace folder will move to system trash. Project chats and stored project data will be removed.") + "\n\n" + greenStyle.Render("Y / Enter move to trash") + " " + redStyle.Render("N / Esc cancel") - } else { - body = redStyle.Render("DELETE CONVERSATION") + "\n" + titleStyle.Render(m.pendingDeleteTitle) + "\n\n" + mutedStyle.Render("Saved conversation data and history snapshots will be removed. Workspace files will stay.") + "\n\n" + greenStyle.Render("Y / Enter delete") + " " + redStyle.Render("N / Esc cancel") + title = "Delete project" + consequence = m.pendingDeletePath + "\nThe project folder moves to system trash. Project chats and data will be removed." } + if m.pendingDeleteKind == "delete_project" && m.pendingDeletePath == "" { + consequence = strings.TrimSpace(consequence) + } + message := limitRows(ansiWrap(consequence, maxInt(1, m.width-2)), maxInt(1, m.height-6)) + actions := redStyle.Render("Y delete") + " " + softStyle.Render("N / Esc cancel") + if m.pendingDeleteKind == "delete_project" { + actions = redStyle.Render("Y trash") + " " + softStyle.Render("N / Esc cancel") + } + body = strings.Join([]string{redStyle.Render(title), titleStyle.Render(m.pendingDeleteTitle), mutedStyle.Render(message), actions}, "\n") case screenApproval: - body = amberStyle.Render("! APPROVAL REQUIRED") + "\n" + titleStyle.Render("Confirm this action") + "\n\n" + softStyle.Render(m.approvalTool) + "\n" + m.approvalView.View() + "\n" + mutedStyle.Render("↑↓ / PgUp PgDn inspect all arguments") + "\n\n" + mutedStyle.Render("This may change local or remote state.") + "\n\n" + greenStyle.Render("Y / Enter approve") + " " + redStyle.Render("N / Esc deny") + body = m.approvalBody() case screenSelfLearning: if m.onboardingSelfLearning { localCursor, localStyle := mutedStyle.Render("·"), softStyle @@ -86,7 +102,7 @@ func (m model) modal(_ string) string { remoteCursor, remoteStyle = brandStyle.Render("›"), titleStyle } body = strings.Join([]string{ - brandStyle.Render("MEMORY"), + brandStyle.Render("Memory"), titleStyle.Render("Choose self-learning"), mutedStyle.Render("Pick how Kyrozen should learn during setup."), "", @@ -108,7 +124,7 @@ func (m model) modal(_ string) string { if m.onboardingSelfLearning { hint = "L local free Qwen2.5 · R remote provider-backed learning · choose one to finish setup" } - lines := []string{brandStyle.Render("MEMORY"), titleStyle.Render("Self-learning settings"), mutedStyle.Render(runtime), mutedStyle.Render(m.learningDetail), mutedStyle.Render(m.learningCostSource), mutedStyle.Render(hint), ""} + lines := []string{brandStyle.Render("Memory"), titleStyle.Render("Self-learning settings"), mutedStyle.Render(runtime), mutedStyle.Render(m.learningDetail), mutedStyle.Render(m.learningCostSource), mutedStyle.Render(hint), ""} for index, item := range m.features { cursor, style := mutedStyle.Render("·"), softStyle rowStyle := lipgloss.NewStyle().Padding(0, 1) @@ -135,30 +151,33 @@ func (m model) modal(_ string) string { if m.decisionAssistConsent { consent = "ON" } - body = strings.Join([]string{ - brandStyle.Render("SETTINGS"), - titleStyle.Render("Controls and session"), - mutedStyle.Render("↑↓ select ←→/Space change · Esc close"), - "", - brandStyle.Render("CONTROLS"), - m.settingsRow(0, "Show tool details", toolDetails), - m.settingsRow(1, "Interaction mode", strings.ToUpper(firstNonEmpty(m.interactionMode, "auto"))), - m.settingsRow(2, "System One backend", strings.ToUpper(firstNonEmpty(m.fastBackend, "off"))), - m.settingsRow(3, "Decision Assist", strings.ToUpper(firstNonEmpty(m.decisionAssistBackend, "off"))), - m.settingsRow(4, "Kev private context", consent), - m.settingsRow(5, "Main model", firstNonEmpty(m.mainModel, "AUTO (simple / complex)")), - mutedStyle.Render("Jev uses paid TypeSafe calls; Kev is local and less accurate. Kev needs private-context consent."), - mutedStyle.Render("/fast remains a legacy command alias for System One."), - mutedStyle.Render("Jev model " + firstNonEmpty(m.systemOneModel, "jev-latest") + " · release " + firstNonEmpty(m.systemOneRelease, "release unknown") + " · health " + firstNonEmpty(m.systemOneHealth, "unknown") + " · calibration " + firstNonEmpty(m.systemOneCalibration, "not calibrated")), - "", - brandStyle.Render("SESSION"), - softStyle.Render("MODEL " + compactText(firstNonEmpty(m.provider, "pending")+" · "+firstNonEmpty(m.modelName, "pending"), modalWidth-10)), - softStyle.Render("USAGE " + compactText(m.usageSummary()+" · "+usageScope, modalWidth-10)), - softStyle.Render("MEMORY " + compactText(learning, modalWidth-10)), - }, "\n") + rows := []string{toolDetails, strings.ToUpper(firstNonEmpty(m.interactionMode, "auto")), strings.ToUpper(firstNonEmpty(m.fastBackend, "off")), strings.ToUpper(firstNonEmpty(m.decisionAssistBackend, "off")), consent, firstNonEmpty(m.mainModel, "AUTO (simple / complex)")} + lines := []string{brandStyle.Render("Settings"), m.pickerPrompt(), ""} + indices := m.settingIndices() + for _, i := range indices { + lines = append(lines, m.settingsRow(i, settingLabels[i], rows[i])) + } + if len(indices) == 0 { + lines = append(lines, "No matching controls") + } + if m.pickerFilter == "" { + if m.settingsIdx >= 2 && m.settingsIdx <= 4 { + lines = append(lines, "", mutedStyle.Render("Jev uses paid TypeSafe calls. Kev runs locally and needs consent for private context."), + mutedStyle.Render("Jev "+firstNonEmpty(m.systemOneModel, "jev-latest")+" · "+firstNonEmpty(m.systemOneRelease, "release unknown")+" · "+firstNonEmpty(m.systemOneHealth, "health unknown")+" · "+firstNonEmpty(m.systemOneCalibration, "not calibrated"))) + } + lines = append(lines, "", titleStyle.Render("Session"), softStyle.Render("Model "+firstNonEmpty(m.modelName, "pending")), softStyle.Render("Usage "+m.usageSummary()+" · "+usageScope), softStyle.Render("Memory "+learning)) + } + if m.startupBackup != "" && m.pickerFilter == "" { + lines = append(lines, mutedStyle.Render("Migration backup "+m.startupBackup)) + } + hint := "↑↓ select ←→/Space change Ctrl+F search Esc close" + if m.width < 60 { + hint = "Space change · Esc back" + } + return detailPage(lines, hint, m.width, m.height) case screenMode: modes := []string{"auto", "ask", "plan", "agent"} - lines := []string{brandStyle.Render("INTERACTION MODE"), titleStyle.Render("Choose how Kyrozen responds"), mutedStyle.Render("↑↓ select Enter confirm Esc cancel"), ""} + lines := []string{brandStyle.Render("Interaction mode"), titleStyle.Render("Choose how Kyrozen responds"), mutedStyle.Render("↑↓ select Enter confirm Esc cancel"), ""} for index, mode := range modes { cursor, style := mutedStyle.Render("·"), softStyle row := lipgloss.NewStyle().Padding(0, 1) @@ -175,66 +194,33 @@ func (m model) modal(_ string) string { {"full_jev", "Full access with Jev detection", "Jev checks sensitive and high impact actions; uncertain checks ask you."}, {"full", "Full access without Jev protection", "Run within configured capability and workspace limits."}, } - lines := []string{brandStyle.Render("PERMISSIONS"), titleStyle.Render("Choose the action approval level"), mutedStyle.Render("↑↓ select Enter confirm Esc cancel"), ""} + lines := []string{m.setupTitle("Permissions", 3)} for index, choice := range choices { - cursor, style := mutedStyle.Render("·"), softStyle - row := lipgloss.NewStyle().Padding(0, 1) + label := " " + choice.title if index == m.permissionIdx { - cursor, style = amberStyle.Render("›"), titleStyle - row = row.Background(lipgloss.Color(surfaceHi)) + label = amberStyle.Render("› " + choice.title) } - lines = append(lines, row.Render(cursor+" "+style.Render(choice.title)), mutedStyle.Render(" "+choice.detail)) + lines = append(lines, label) } + lines = append(lines, mutedStyle.Render(choices[m.permissionIdx].detail), m.chooseHint()) body = strings.Join(lines, "\n") case screenQuestion: - lines := []string{brandStyle.Render("CLARIFICATION"), titleStyle.Render("Kyrozen needs a decision")} - if m.pendingQuestion != nil && len(m.pendingQuestion.questions) > 0 { - question := m.pendingQuestion.questions[minInt(m.questionIdx, len(m.pendingQuestion.questions)-1)] - lines = append(lines, mutedStyle.Render(fmt.Sprintf("Question %d of %d", m.questionIdx+1, len(m.pendingQuestion.questions))), "", titleStyle.Render(question.header), softStyle.Render(question.prompt), "") - for index, choice := range question.choices { - cursor, style := mutedStyle.Render("·"), softStyle - if index == m.choiceIdx { - cursor, style = brandStyle.Render("›"), titleStyle - } - label := choice.label - if choice.description != "" { - label += " — " + choice.description - } - lines = append(lines, cursor+" "+style.Render(label)) - } - extra := []string{"Other (type your own answer)", "Skip"} - for offset, label := range extra { - index := len(question.choices) + offset - cursor, style := mutedStyle.Render("·"), softStyle - if index == m.choiceIdx { - cursor, style = brandStyle.Render("›"), titleStyle - } - lines = append(lines, cursor+" "+style.Render(label)) - } - lines = append(lines, "", mutedStyle.Render("↑↓ select Enter confirm Esc cancel")) - } - body = strings.Join(lines, "\n") + body = m.questionBody() case screenPlan: body = m.planModal(maxInt(1, modalWidth-4)) case screenGithubAuth: - body = brandStyle.Render("GITHUB AUTHENTICATION") + "\n" + titleStyle.Render("Sign in through GitHub CLI") + "\n\n" + + body = brandStyle.Render("GitHub authentication") + "\n" + titleStyle.Render("Sign in through GitHub CLI") + "\n\n" + softStyle.Render("OpenKyrozen will suspend the TUI while gh opens the browser login for "+firstNonEmpty(m.githubHostname, "github.com")+".") + "\n" + mutedStyle.Render("Credentials remain owned by gh and are never read by OpenKyrozen.") + "\n\n" + greenStyle.Render("Enter continue") + " " + redStyle.Render("Esc cancel") case screenError: - body = redStyle.Render("ERROR") + "\n" + titleStyle.Render("OpenKyrozen needs attention") + "\n\n" + softStyle.Render(m.errorText) + "\n\n" + mutedStyle.Render("Press Enter or Esc to return to chat.") - } - style := modalStyle.Copy() - if m.transitionTick > 0 { - style = style.BorderForeground(lipgloss.Color(cyan)) + body = redStyle.Render("Error") + "\n" + softStyle.Render(m.errorText) + "\n" + mutedStyle.Render("Enter / Esc back") } - body = lipgloss.NewStyle().Width(maxInt(1, modalWidth-4)).MaxWidth(maxInt(1, modalWidth-4)).Render(body) - modal := style.Width(modalWidth).MaxWidth(modalWidth).Render(body) - return lipgloss.NewStyle().Width(maxInt(1, m.width)).Height(maxInt(1, m.height)).Align(lipgloss.Center, lipgloss.Center).Render(modal) + return m.bottomSheet(background, body) } func (m model) planPageHeight() int { - return maxInt(1, m.height-12) + return maxInt(1, minInt(m.height-9, m.height/2)) } func (m model) planLines(width int) []string { @@ -252,7 +238,7 @@ func (m model) planLines(width int) []string { } func (m model) planMaxScroll() int { - modalWidth := maxInt(1, minInt(78, m.width-4)) + modalWidth := maxInt(1, m.width-2) return maxInt(0, len(m.planLines(maxInt(1, modalWidth-4)))-m.planPageHeight()) } @@ -262,14 +248,109 @@ func (m *model) scrollPlan(delta int) { func (m model) planModal(width int) string { if m.pendingPlan == nil { - return brandStyle.Render("PLAN PROPOSAL") + return brandStyle.Render("Plan proposal") } lines := m.planLines(width) pageHeight := m.planPageHeight() start := maxInt(0, minInt(m.planScroll, maxInt(0, len(lines)-pageHeight))) end := minInt(len(lines), start+pageHeight) position := mutedStyle.Render(fmt.Sprintf("Lines %d–%d of %d · ↑↓/PgUp/PgDn scroll", start+1, end, len(lines))) - header := brandStyle.Render("PLAN PROPOSAL") + "\n" + titleStyle.Render(fmt.Sprintf("%s · v%d", m.pendingPlan.title, m.pendingPlan.version)) + header := brandStyle.Render("Plan proposal") + "\n" + titleStyle.Render(fmt.Sprintf("%s · v%d", m.pendingPlan.title, m.pendingPlan.version)) footer := position + "\n" + greenStyle.Render("A / Enter accept") + " " + amberStyle.Render("R revise") + " " + redStyle.Render("C / Esc cancel") + if m.height < 15 || m.width < 63 { + action := greenStyle.Render("A accept") + " " + amberStyle.Render("R revise") + " " + redStyle.Render("C cancel") + position = mutedStyle.Render(fmt.Sprintf("%d–%d / %d · ↑↓", start+1, end, len(lines))) + return header + "\n" + strings.Join(lines[start:end], "\n") + "\n" + position + "\n" + action + } return header + "\n\n" + strings.Join(lines[start:end], "\n") + "\n\n" + footer } + +func (m model) approvalBody() string { + action := greenStyle.Render("Y / Enter approve") + " " + redStyle.Render("N / Esc deny") + if m.width < 45 { + action = greenStyle.Render("Y approve") + " " + redStyle.Render("N deny") + } + lines := []string{amberStyle.Render("Approval required"), titleStyle.Render(m.approvalTool), m.approvalView.View()} + if m.height >= 12 { + lines = append(lines, mutedStyle.Render("↑↓ / PgUp PgDn inspect arguments")) + } + return strings.Join(append(lines, action), "\n") +} + +func (m model) setupTitle(title string, stage int) string { + if m.onboardingKind == "new" { + return brandStyle.Render(fmt.Sprintf("Setup %d/3 %s", stage, title)) + } + return brandStyle.Render(title) +} +func (m model) pickerPrompt() string { + if m.pickerSearching { + return brandStyle.Render("Search " + m.pickerFilter + "▏") + } + if m.pickerFilter != "" { + return mutedStyle.Render("Filter " + m.pickerFilter) + } + return mutedStyle.Render("Ctrl+F search") +} + +func (m model) chooseHint() string { + if m.width < 42 { + return mutedStyle.Render("Enter · Esc back") + } + return mutedStyle.Render("↑↓ select Enter choose Esc back") +} +func (m model) questionBody() string { + if m.pendingQuestion == nil || len(m.pendingQuestion.questions) == 0 { + return titleStyle.Render("Clarification") + } + q := m.pendingQuestion.questions[minInt(m.questionIdx, len(m.pendingQuestion.questions)-1)] + title := fmt.Sprintf("Question %d of %d", m.questionIdx+1, len(m.pendingQuestion.questions)) + if q.header != "" { + title += " " + q.header + } + lines := []string{brandStyle.Render(compactText(title, m.width-2)), softStyle.Render(q.prompt)} + choices := make([]string, 0, len(q.choices)+2) + for _, choice := range q.choices { + choices = append(choices, choice.label) + } + choices = append(choices, "Other (write an answer)", "Skip") + selected := minInt(m.choiceIdx, len(choices)-1) + // Window the choices around the current answer. Keep the prompt, selected + // description and actions in the sheet even when the terminal is short. + width := maxInt(1, m.width-2) + prompt := ansiWrap(lines[1], width) + prompt = limitRows(prompt, maxInt(1, m.height/4)) + lines[1] = prompt + description := "" + if selected < len(q.choices) && q.choices[selected].description != "" { + description = limitRows(ansiWrap(q.choices[selected].description, width), maxInt(1, m.height/5)) + } + available := maxInt(1, m.height-5-lipgloss.Height(prompt)) + if description != "" { + available = maxInt(1, available-lipgloss.Height(description)) + } + start := maxInt(0, selected-available+1) + for i := start; i < minInt(len(choices), start+available); i++ { + text := compactText(choices[i], width-2) + if i == selected { + lines = append(lines, brandStyle.Render("› "+text)) + } else { + lines = append(lines, " "+text) + } + } + if description != "" { + lines = append(lines, mutedStyle.Render(description)) + } + return strings.Join(append(lines, m.chooseHint()), "\n") +} + +func (m model) formBody(title, description, field, actions string) string { + width := maxInt(1, m.width-2) + // Reserve a row for the value and actions before wrapping provider feedback. + help := limitRows(ansiWrap(description, width), maxInt(1, m.height-6)) + box := contextStyle.Copy().MaxWidth(width).Render(field) + if width < 28 { + actions = "Enter save · Esc back" + } + return strings.Join([]string{title, softStyle.Render(help), box, mutedStyle.Render(actions)}, "\n") +} diff --git a/tui/events.go b/tui/events.go index b89600a4..eb317a2a 100644 --- a/tui/events.go +++ b/tui/events.go @@ -5,7 +5,6 @@ import ( "encoding/json" "fmt" "strings" - "time" ) func stringValue(event map[string]any, key string) string { @@ -24,8 +23,47 @@ func stringList(value any) []string { return result } +// Close only a still-streaming row. A completed response already owns its row. +func (m *model) finishInterruptedReply(message string) { + for i := len(m.messages) - 1; i >= 0; i-- { + if m.messages[i].streaming { + if m.messages[i].text != "" { + m.messages[i].text += "\n\n" + } + m.messages[i].text += message + m.messages[i].streaming = false + m.view.invalidate(i) + return + } + } +} + func (m *model) handleBackendEvent(event backendEvent) { - switch stringValue(event, "event") { + kind := stringValue(event, "event") + id := stringValue(event, "request_id") + // A bound-state snapshot sends navigation and interaction before ready. + // Deleting an inactive item instead finishes with a response. + if id != "" && id == m.navigationRequest && (kind == "ready" || kind == "response" || kind == "error") { + m.navigationRequest = "" + } + switch kind { + case "instruction_source", "instruction_text", "instructions_complete": + if id != m.instructionRequest || m.utility != "instructions" || m.screen != screenUtility { + return + } + if kind == "instruction_source" { + if m.instructionText != "" { + m.instructionText += "\n\n" + } + m.instructionText += stringValue(event, "path") + "\n" + } + if kind == "instruction_text" { + m.instructionText += stringValue(event, "text") + } + if kind == "instructions_complete" && m.instructionText == "" { + m.instructionText = "No instruction files apply to this workspace." + } + return case "update_available": m.availableVersion = stringValue(event, "version") case "agents_reset", "agent_detail": @@ -77,8 +115,28 @@ func (m *model) handleBackendEvent(event backendEvent) { m.updateAgent(agent) m.agentSelected = minInt(m.agentSelected, maxInt(0, len(m.agents)-1)) } + case "runtime_event": + if id != "" && id == m.activeTurn { + if runtime, ok := event["runtime_event"].(map[string]any); ok { + switch stringValue(runtime, "kind") { + case "turn.failed", "turn.cancelled": + m.conversation().paused = true + } + } + } case "status": state := stringValue(event, "state") + if state == "thinking" && boolValue(event, "busy") && m.activeTurn == "" { + m.activeTurn = id + } + if m.activeTurn != "" && id == m.activeTurn && !boolValue(event, "busy") && (state == "ready" || state == "waiting") { + m.activeTurn = "" + m.busy = false + if state == "waiting" { + m.conversation().paused = true + m.finishInterruptedReply(firstNonEmpty(stringValue(event, "message"), "Waiting for setup.")) + } + } m.status = firstNonEmpty(stringValue(event, "message"), state) if state == "updating" { m.updateInProgress = true @@ -114,15 +172,11 @@ func (m *model) handleBackendEvent(event backendEvent) { m.mainModel = stringValue(event, "main_model") m.workspace = stringValue(event, "workspace") m.startupBackup = stringValue(event, "backup_path") - m.activeSessionID = firstNonEmpty(stringValue(event, "session_id"), m.activeSessionID) + m.selectConversation(m.activeScopeID, stringValue(event, "session_id")) m.status = "Ready" m.busy = false m.backendReady = true - m.readyAt = time.Now() m.thinkingText = "" - if m.screen == screenSplash && (m.reducedMotion || m.canLeaveSplash(time.Now())) { - m.screen = screenChat - } case "usage": m.usageScope = firstNonEmpty(stringValue(event, "scope"), "workspace") m.usageAttempts = numberValue(event["attempts"]) @@ -133,10 +187,10 @@ func (m *model) handleBackendEvent(event backendEvent) { case "stream_delta": m.busy, m.status = true, "Generating…" m.thinkingText = "" - m.cursorVisible = true text := stringValue(event, "text") for i := len(m.messages) - 1; i >= 0; i-- { if m.messages[i].role == "assistant" && m.messages[i].streaming { + m.view.invalidate(i) m.messages[i].text += text return } @@ -148,6 +202,10 @@ func (m *model) handleBackendEvent(event backendEvent) { m.status = "Thinking…" case "response": text := stringValue(event, "text") + if m.activeTurn != "" && id != m.activeTurn && !m.updateInProgress { + m.messages = append(m.messages, chatMessage{role: "assistant", text: text}) + return + } if m.updateInProgress { m.updateInProgress = false m.errorText = firstNonEmpty(text, "The update did not complete.") @@ -159,7 +217,8 @@ func (m *model) handleBackendEvent(event backendEvent) { } m.input.Placeholder = "Ask Kyrozen anything…" for i := len(m.messages) - 1; i >= 0; i-- { - if m.messages[i].role == "assistant" && m.messages[i].streaming { + if m.messages[i].role == "assistant" && m.messages[i].streaming && (m.activeTurn == "" || m.activeTurn == id) { + m.view.invalidate(i) m.messages[i].text, m.messages[i].streaming = text, false m.messages[i].rendered = "" m.messages[i].renderedWidth = 0 @@ -180,7 +239,7 @@ func (m *model) handleBackendEvent(event backendEvent) { if receipt, ok := event["receipt"].(map[string]any); ok { m.messages = append(m.messages, chatMessage{ role: "receipt", status: receiptStatus(receipt), - text: stringValue(receipt, "action"), toolAction: stringValue(receipt, "action"), + text: receiptSummary(receipt), toolAction: stringValue(receipt, "action"), toolDetail: safeToolDetail(stringValue(receipt, "result")), }) } @@ -260,6 +319,28 @@ func (m *model) handleBackendEvent(event backendEvent) { m.approvalDetailsComplete = true } case "error": + if id == m.activeTurn || m.activeTurn == "" { + m.conversation().paused = true + } + if id != "" && id == m.activeTurn { + m.finishInterruptedReply("Turn failed · " + firstNonEmpty(stringValue(event, "error"), "Backend error")) + // A submit rejected before the worker starts has no final idle event. + if stringValue(event, "code") == "busy" { + m.activeTurn = "" + } + } + if m.onboardingKind != "" { + switch stringValue(event, "code") { + case "model_setup_failed": + m.recoveryScreen = screenModel + case "provider_setup_failed", "invalid_provider": + m.recoveryScreen = screenProvider + case "api_key_setup_failed", "empty_api_key": + m.recoveryScreen = screenAPIKey + case "invalid_permissions": + m.recoveryScreen = screenPermissions + } + } m.setError(firstNonEmpty(stringValue(event, "error"), "Backend error")) case "exit": m.status, m.busy = "Stopped", false @@ -415,13 +496,13 @@ func parseWorkingPlan(value any) *workingPlanView { } func (m *model) applyNavigation(event backendEvent) { - if stringValue(event, "active_session_id") != m.activeSessionID || stringValue(event, "active_scope_id") != m.activeScopeID { + changed := stringValue(event, "active_session_id") != m.activeSessionID || stringValue(event, "active_scope_id") != m.activeScopeID + if changed { m.agents = nil m.agentSelected, m.agentScroll = 0, 0 m.workingPlan = nil } - m.activeSessionID = stringValue(event, "active_session_id") - m.activeScopeID = stringValue(event, "active_scope_id") + m.selectConversation(stringValue(event, "active_scope_id"), stringValue(event, "active_session_id")) m.workspace = firstNonEmpty(stringValue(event, "workspace"), m.workspace) m.navigation = nil if groups, ok := event["groups"].([]any); ok { @@ -448,6 +529,10 @@ func (m *model) applyNavigation(event backendEvent) { break } } + if !changed && !boolValue(event, "replace_messages") && len(m.messages) > 0 { + return + } + m.view.reset() m.messages = nil if messages, ok := event["messages"].([]any); ok { for _, raw := range messages { @@ -522,6 +607,8 @@ func (m *model) handlePrompt(event backendEvent) { m.apiInput.Placeholder = firstNonEmpty(stringValue(event, "message"), "Enter Jev API key for protected full access") m.apiInput.Focus() case "provider": + m.pickerFilter = "" + m.pickerSearching = false m.onboardingWaiting = false m.providerList = nil if providers, ok := event["providers"].([]any); ok { @@ -532,13 +619,23 @@ func (m *model) handlePrompt(event backendEvent) { } } m.providerIdx, m.screen = 0, screenProvider + for i, name := range m.providerList { + if name == stringValue(event, "current") { + m.providerIdx = i + break + } + } + case "permissions": + m.openPermissions(stringValue(event, "selected")) m.startTransition() case "model": + m.modelChoices = stringList(event["choices"]) m.modelPromptReturn = m.screen m.modelPromptMessage = stringValue(event, "message") m.apiInput.EchoMode = textinput.EchoNormal m.apiInput.Reset() - m.apiInput.Placeholder = firstNonEmpty(stringValue(event, "current"), "model name or auto") + m.apiInput.Placeholder = "Model name or auto" + m.apiInput.SetValue(firstNonEmpty(stringValue(event, "current"), "auto")) m.apiInput.Focus() m.screen = screenModel m.startTransition() diff --git a/tui/go.mod b/tui/go.mod index b2784bb2..14dddd63 100644 --- a/tui/go.mod +++ b/tui/go.mod @@ -7,6 +7,9 @@ require ( charm.land/bubbletea/v2 v2.0.9 charm.land/glamour/v2 v2.0.0 charm.land/lipgloss/v2 v2.0.6 + github.com/charmbracelet/x/ansi v0.11.8 + github.com/charmbracelet/x/term v0.2.2 + golang.org/x/sys v0.47.0 ) require ( @@ -15,9 +18,7 @@ require ( github.com/aymerick/douceur v0.2.0 // indirect github.com/charmbracelet/colorprofile v0.4.3 // indirect github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 // indirect - github.com/charmbracelet/x/ansi v0.11.8 // indirect github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf // indirect - github.com/charmbracelet/x/term v0.2.2 // indirect github.com/charmbracelet/x/termios v0.1.1 // indirect github.com/charmbracelet/x/windows v0.2.2 // indirect github.com/clipperhouse/displaywidth v0.11.0 // indirect @@ -34,6 +35,5 @@ require ( github.com/yuin/goldmark-emoji v1.0.5 // indirect golang.org/x/net v0.39.0 // indirect golang.org/x/sync v0.22.0 // indirect - golang.org/x/sys v0.47.0 // indirect golang.org/x/text v0.24.0 // indirect ) diff --git a/tui/graph.go b/tui/graph.go index 7d54e6d2..bda68f7e 100644 --- a/tui/graph.go +++ b/tui/graph.go @@ -117,11 +117,16 @@ func (m model) graphMini(width, height int) string { grid[y][x] = '·' } } - for index, node := range m.graph.miniNodes { + selected := "" + nodes := m.visibleGraphNodes() + if len(nodes) > 0 { + selected = nodes[minInt(len(nodes)-1, m.graphSelected)].id + } + for _, node := range m.graph.miniNodes { point := positions[node.id] grid[point[1]][point[0]] = '●' communities[point[1]][point[0]] = node.community - if index == m.graphSelected { + if node.id == selected { grid[point[1]][point[0]] = '◆' } } @@ -147,44 +152,40 @@ func (m model) graphCompact() string { mutedStyle.Render(fmt.Sprintf(" %d nodes · %d edges", m.graph.nodes, m.graph.edges)) } +func (m model) graphNodeStartRow() int { + row := 3 + if m.graphSearching { + row++ + } + return row +} + func (m model) graphExplorer() string { - width, height := maxInt(1, m.width-4), maxInt(1, m.height-2) + width := maxInt(1, m.width) status := firstNonEmpty(m.graph.status, "missing") - lines := []string{ - brandStyle.Render("◆ PROJECT GRAPH") + " " + graphStatusStyle(status).Render(strings.ToUpper(status)), - mutedStyle.Render(fmt.Sprintf("%d nodes · %d edges · %d communities", m.graph.nodes, m.graph.edges, m.graph.communities)), - "", - m.graphMini(minInt(48, maxInt(22, width/2)), minInt(14, maxInt(8, height/3))), - "", - } + lines := []string{brandStyle.Render("Project graph") + " " + graphStatusStyle(status).Render(strings.ToUpper(status)), + mutedStyle.Render(fmt.Sprintf("%d nodes · %d edges · %d communities", m.graph.nodes, m.graph.edges, m.graph.communities)), ""} if m.graphSearching { - lines = append(lines, focusStyle.Copy().Width(minInt(60, width-4)).Render(m.graphInput.View()), "") + lines = append(lines, focusStyle.Copy().Render(m.graphInput.View())) } nodes := m.visibleGraphNodes() - for index, node := range nodes { - marker, style := "·", softStyle - rowStyle := lipgloss.NewStyle() - if index == minInt(m.graphSelected, maxInt(0, len(nodes)-1)) { - marker, style = "›", titleStyle - rowStyle = rowStyle.Background(lipgloss.Color(surfaceHi)).Padding(0, 1) + for i, node := range nodes { + marker, style := " ", softStyle + if i == minInt(m.graphSelected, len(nodes)-1) { + marker, style = "› ", brandStyle } - color := communityColors[node.community%len(communityColors)] - row := lipgloss.NewStyle().Foreground(lipgloss.Color(color)).Render("●") + " " + style.Render(compactText(node.label, maxInt(8, width-20))) - lines = append(lines, rowStyle.Render(marker+" "+row+mutedStyle.Render(fmt.Sprintf(" degree %d", node.degree)))) + lines = append(lines, marker+style.Render(compactText(node.label, maxInt(8, width-18)))+" "+mutedStyle.Render(fmt.Sprintf("degree %d", node.degree))) } if len(nodes) == 0 { lines = append(lines, mutedStyle.Render(firstNonEmpty(m.graph.message, "No indexed nodes yet."))) - } - if m.graph.detail != "" { - lines = append(lines, "", titleStyle.Render("PATH / DETAILS"), softStyle.Render(compactText(m.graph.detail, width-2))) - } else if len(nodes) > 0 { + } else { node := nodes[minInt(m.graphSelected, len(nodes)-1)] - location := firstNonEmpty(node.source, "source unavailable") + source := firstNonEmpty(node.source, "Source unavailable") if node.location != "" { - location += ":" + node.location + source += ":" + node.location } - lines = append(lines, "", titleStyle.Render(node.label), mutedStyle.Render(location)) - shownEdges := 0 + lines = append(lines, "", titleStyle.Render(node.label), mutedStyle.Render(source)) + shown := 0 for _, edge := range m.graph.miniEdges { neighbor := "" if edge.source == node.id { @@ -193,23 +194,33 @@ func (m model) graphExplorer() string { neighbor = edge.source } if neighbor != "" { - lines = append(lines, mutedStyle.Render(fmt.Sprintf(" %s [%s] → %s", firstNonEmpty(edge.relation, "related"), firstNonEmpty(edge.confidence, "unknown"), neighbor))) - shownEdges++ - if shownEdges == 2 { + lines = append(lines, mutedStyle.Render(fmt.Sprintf("%s [%s] → %s", firstNonEmpty(edge.relation, "related"), firstNonEmpty(edge.confidence, "unknown"), neighbor))) + shown++ + if shown == 2 { break } } } } - help := "↑↓ select · Enter open · Esc close" - if width >= 60 { + if m.graph.detail != "" { + lines = append(lines, "", softStyle.Render(m.graph.detail)) + } + if len(nodes) > 0 && m.height >= 32 { + lines = append(lines, "", m.graphMini(22, 5)) + } + help := "↑↓ select · Enter neighbors · Esc close" + if width >= 64 { help = "↑↓ select · / search · Enter neighbors · r refresh · Esc close" } - if width >= 100 { + if width >= 96 { help = "↑↓/hjkl select · +/- zoom · / search · Tab communities · Enter neighbors · p path · r refresh · Esc close" } - lines = append(lines, "", contextStyle.Copy().Width(maxInt(1, width-2)).Render(mutedStyle.Render(help))) - return lipgloss.NewStyle().Background(lipgloss.Color(deep)).Width(width).MaxWidth(width).Height(height).MaxHeight(height).Border(lipgloss.RoundedBorder()).BorderForeground(lipgloss.Color(cyan)).Padding(0, 1).Render(strings.Join(lines, "\n")) + return detailPage(lines, help, width, m.height) +} + +func detailPage(lines []string, hint string, width, height int) string { + body := ansiWrap(strings.Join(lines, "\n"), maxInt(1, width)) + return fitBody(body, maxInt(1, height-1)) + "\n" + mutedStyle.Render(clipRow(hint, width)) } func (m model) visibleGraphNodes() []graphNode { @@ -230,7 +241,6 @@ func (m model) visibleGraphNodes() []graphNode { return nodes[i].label < nodes[j].label }) limit := minInt(len(nodes), maxInt(4, 10+m.graphZoom*4)) - miniHeight := minInt(14, maxInt(8, maxInt(1, m.height-2)/3)) - limit = minInt(limit, maxInt(2, m.height-miniHeight-12)) + limit = minInt(limit, maxInt(2, m.height-m.graphNodeStartRow()-7)) return nodes[:limit] } diff --git a/tui/input.go b/tui/input.go index 84e18ee8..16bd9839 100644 --- a/tui/input.go +++ b/tui/input.go @@ -3,10 +3,8 @@ package main import ( "charm.land/bubbles/v2/textinput" tea "charm.land/bubbletea/v2" - "fmt" "os/exec" "strings" - "unicode" ) func (m *model) handleKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { @@ -17,6 +15,23 @@ func (m *model) handleKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { if m.updateInProgress { return nil, false } + // A decision can arrive before the proposing worker releases its turn. + // Approval prompts are different: the worker is waiting for their reply. + if m.activeTurn != "" || m.navigationRequest != "" { + savingDecision := m.screen == screenUtility && m.editing && (m.utility == "answer" || m.utility == "revision") && key == "enter" + answering := m.screen == screenQuestion && (key == "enter" || key == "esc") + actingOnPlan := m.screen == screenPlan && (key == "enter" || key == "esc" || strings.EqualFold(key, "a") || strings.EqualFold(key, "c")) + if savingDecision || answering || actingOnPlan { + m.status = "Wait for the current turn to finish." + return nil, false + } + } + if m.screen == screenUtility { + return m.utilityKey(msg), false + } + if m.filterPicker(msg) { + return nil, false + } if m.screen == screenOnboarding { if key == "enter" && !m.onboardingWaiting { m.onboardingWaiting = true @@ -27,7 +42,14 @@ func (m *model) handleKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { } if m.screen == screenError { if key == "esc" || key == "enter" { - if m.onboardingKind != "" { + if m.recoveryScreen != "" { + m.screen = m.recoveryScreen + if m.screen == screenAPIKey || m.screen == screenModel { + m.apiInput.Focus() + } + m.recoveryScreen = "" + m.onboardingWaiting = false + } else if m.onboardingKind != "" { m.screen = screenOnboarding } else { m.screen = screenChat @@ -135,6 +157,10 @@ func (m *model) handleKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { choices := []string{"ask", "full_jev", "full"} switch key { case "esc": + if m.onboardingKind != "" { + m.send("command", map[string]any{"name": "model"}) + return nil, false + } m.screen = screenChat m.input.Focus() case "up", "k": @@ -143,6 +169,10 @@ func (m *model) handleKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { m.permissionIdx = (m.permissionIdx + 1) % len(choices) case "enter": m.send("command", map[string]any{"name": "permissions", "args": choices[m.permissionIdx]}) + if m.onboardingKind != "" { + m.screen, m.onboardingWaiting = screenOnboarding, true + return nil, false + } m.screen = screenChat m.input.Focus() } @@ -177,9 +207,8 @@ func (m *model) handleKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { } m.screen = screenChat case "r", "R": - m.screen = screenChat - m.input.Placeholder = "Describe the plan revision…" - m.input.Focus() + m.openUtility("revision") + return m.startEditor(""), false } return nil, false } @@ -212,6 +241,28 @@ func (m *model) handleKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { return cmd, false } if m.screen == screenModel { + if (key == "tab" || key == "down" || key == "up") && len(m.modelChoices) > 0 { + query := strings.ToLower(m.apiInput.Value()) + next := "" + for i, name := range m.modelChoices { + if strings.EqualFold(query, name) { + d := 1 + if key == "up" { + d = -1 + } + next = m.modelChoices[(i+len(m.modelChoices)+d)%len(m.modelChoices)] + break + } + if next == "" && strings.Contains(strings.ToLower(name), query) { + next = name + } + } + if next != "" { + m.apiInput.SetValue(next) + m.apiInput.CursorEnd() + } + return nil, false + } if key == "esc" { m.apiInput.Reset() m.apiInput.Blur() @@ -225,10 +276,10 @@ func (m *model) handleKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { } if key == "enter" { value := strings.TrimSpace(m.apiInput.Value()) - if value != "" { - m.send("command", map[string]any{"name": "model", "args": map[string]any{"model": value}}) + if value == "" { + return nil, false } - m.apiInput.Reset() + m.send("command", map[string]any{"name": "model", "args": map[string]any{"model": value}}) m.apiInput.Blur() if m.onboardingKind != "" { m.screen = screenOnboarding @@ -322,20 +373,19 @@ func (m *model) handleKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { m.send("command", map[string]any{"name": "mode", "args": mode}) return nil, false } - if m.screen == screenChat && !m.busy && key == "ctrl+p" { - m.permissionIdx = 0 - for i, mode := range []string{"ask", "full_jev", "full"} { - if mode == m.permissionMode { - m.permissionIdx = i - } + if action, ok := chatActions[key]; ok && m.screen == screenChat && !m.navigationFocused { + if action == "details" { + m.toggleReceipt() + } else { + m.runAction(action) } - m.input.Blur() - m.screen = screenPermissions return nil, false } if m.screen == screenChat && (key == "ctrl+b" || key == "ctrl+\\") { m.navigationOpen = !m.navigationOpen m.navigationFocused = m.navigationOpen + m.navigationFilter = "" + m.navigationSearching = false if m.navigationFocused { m.input.Blur() } else { @@ -348,6 +398,20 @@ func (m *model) handleKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { return nil, false } if m.screen == screenChat && m.navigationFocused { + if key == "ctrl+f" { + m.navigationSearching = true + return nil, false + } + if m.navigationSearching && key != "up" && key != "down" && key != "enter" { + if key == "esc" { + m.navigationFilter = "" + m.navigationSearching = false + } else { + m.navigationFilter = editFilter(m.navigationFilter, msg) + } + m.navigationIndex = 0 + return nil, false + } switch key { case "esc": m.navigationFocused, m.navigationOpen = false, false @@ -359,7 +423,9 @@ func (m *model) handleKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { case "enter": targets := m.navigationTargets() if len(targets) > 0 { - target := targets[m.navigationIndex] + target := targets[minInt(m.navigationIndex, len(targets)-1)] + m.navigationFocused, m.navigationOpen = false, false + m.input.Focus() switch target.kind { case "chat": m.send("navigate", map[string]any{"action": "switch", "scope_id": target.scopeID, "session_id": target.id}) @@ -440,9 +506,14 @@ func (m *model) handleKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { m.followTail = m.view.AtBottom() return nil, false } - if key == "g" && len(m.palette) == 0 && strings.TrimSpace(m.input.Value()) == "" { - m.screen = screenGraph - m.send("graph_request", map[string]any{"action": "snapshot"}) + if key == "end" && !m.followTail { + m.followTail = true + m.view.GotoBottom() + return nil, false + } + if key == "ctrl+j" || key == "alt+enter" || key == "shift+enter" { + m.input.InsertString("\n") + m.refreshPalette() return nil, false } if len(m.palette) > 0 { @@ -576,20 +647,20 @@ func (m *model) questionKey(key string) tea.Cmd { return nil } if m.choiceIdx == len(question.choices) { + m.openUtility("answer") + return m.startEditor("") + } + return m.answerQuestion(question.choices[m.choiceIdx].id) +} + +func (m *model) answerQuestion(answer string) tea.Cmd { + if m.pendingQuestion == nil || m.questionIdx >= len(m.pendingQuestion.questions) { m.screen = screenChat - parts := make([]string, 0, len(m.questionAnswers)+1) - for _, item := range m.pendingQuestion.questions { - if answer := m.questionAnswers[item.id]; answer != nil { - parts = append(parts, item.id+": "+fmt.Sprint(answer)) - } - } - parts = append(parts, question.id+": ") - m.input.SetValue(strings.Join(parts, "; ")) - m.input.Placeholder = "Type your own clarification…" - m.input.Focus() return nil } - m.questionAnswers[question.id] = question.choices[m.choiceIdx].id + question := m.pendingQuestion.questions[m.questionIdx] + m.questionAnswers[question.id] = answer + m.screen = screenQuestion if m.questionIdx+1 < len(m.pendingQuestion.questions) { m.questionIdx++ m.choiceIdx = 0 @@ -602,38 +673,36 @@ func (m *model) questionKey(key string) tea.Cmd { func (m *model) submit() tea.Cmd { text := strings.TrimSpace(m.input.Value()) - if text == "" || (m.busy && !strings.EqualFold(text, "/agents")) { + if text == "" { return nil } - if strings.HasPrefix(strings.TrimLeftFunc(m.input.Value(), unicode.IsSpace), "/") { - if strings.EqualFold(text, "/settings") { - m.screen = screenSettings - m.settingsIdx = 0 - m.input.Reset() - m.palette = nil - m.input.SetHeight(m.composerHeight()) - return nil - } - m.send("command", map[string]any{"name": text}) - if strings.EqualFold(text, "/quit") || strings.EqualFold(text, "/exit") { - return tea.Quit - } - m.input.Reset() - m.palette = nil - m.input.SetHeight(m.composerHeight()) + if m.navigationRequest != "" { + m.status = "Waiting for workspace navigation…" + return nil + } + if !m.backendReady && !strings.HasPrefix(text, "/") { + m.status = "Starting workspace…" return nil } - m.messages = append(m.messages, chatMessage{role: "user", text: text}) - m.messages = append(m.messages, chatMessage{role: "assistant", streaming: true}) - m.busy = true - m.status = "Thinking…" - m.thinkingText = "" - m.cursorVisible = true - m.followTail = true m.input.Reset() m.palette = nil m.input.SetHeight(m.composerHeight()) - m.send("submit", map[string]any{"text": text}) + if strings.HasPrefix(text, "/") { + action := strings.TrimPrefix(text, "/") + if strings.EqualFold(action, "quit") || strings.EqualFold(action, "exit") { + return tea.Quit + } + m.runAction(action) + return nil + } + state := m.conversation() + if m.busy || m.activeTurn != "" || len(state.queue) > 0 { + state.queue = append(state.queue, text) + m.status = "Follow-up queued" + return nil + } + state.paused = false + m.startTurn(text) return nil } @@ -661,6 +730,9 @@ func (m *model) providerKey(key string) tea.Cmd { } return nil } + if len(m.providerList) == 0 { + return nil + } if key == "up" || key == "k" { m.providerIdx = (m.providerIdx - 1 + len(m.providerList)) % len(m.providerList) return nil diff --git a/tui/layout.go b/tui/layout.go index 49c3d29d..4ebd3d12 100644 --- a/tui/layout.go +++ b/tui/layout.go @@ -1,84 +1,57 @@ package main import ( - "charm.land/lipgloss/v2" "fmt" "strings" + + "charm.land/lipgloss/v2" + "github.com/charmbracelet/x/ansi" ) func (m *model) resize() { - width := m.contentWidth() - mainWidth, _ := m.layoutWidths() - composerWidth := width - if m.height >= 12 { - composerWidth = maxInt(1, width-4) - } - m.input.SetWidth(composerWidth) - m.input.SetHeight(m.composerHeight()) - m.apiInput.SetWidth(maxInt(1, minInt(68, m.width-14))) - m.view.SetWidth(mainWidth) - m.view.SetHeight(m.historyHeight()) + m.input.SetWidth(maxInt(1, m.contentWidth()-2)) + m.apiInput.SetWidth(maxInt(1, minInt(68, m.width-6))) + m.projectInput.SetWidth(maxInt(1, minInt(68, m.width-6))) m.setApprovalContent() - m.approvalView.SetHeight(maxInt(1, m.height-18)) + m.approvalView.SetHeight(maxInt(1, m.height/2-4)) m.planScroll = minInt(m.planScroll, m.planMaxScroll()) m.syncViewport() } func (m *model) setApprovalContent() { - width := maxInt(1, minInt(70, m.width-14)) + width := maxInt(1, m.width-4) m.approvalView.SetWidth(width) m.approvalView.SetContent(lipgloss.Wrap(m.approvalArgs, width, "")) } -func (m model) contentWidth() int { - return maxInt(1, m.width-4) -} - -func (m model) navigationWidth() int { - if m.width < 100 || m.height < 16 { - return 0 - } - return minInt(28, maxInt(20, m.contentWidth()/5)) -} - -func (m model) layoutWidths() (int, int) { - available := m.contentWidth() - if navigationWidth := m.navigationWidth(); navigationWidth > 0 { - available = maxInt(1, available-navigationWidth-1) - } - if m.width < 120 || m.height < 24 { - return available, 0 - } - railWidth := minInt(30, maxInt(24, available/4)) - return maxInt(1, available-railWidth-1), railWidth -} - +func (m model) contentWidth() int { return maxInt(1, m.width) } func (m model) composerHeight() int { - if m.height > 0 && m.height < 16 { - return 1 + if m.input.LineCount() == 1 { + return minInt(5, maxInt(1, m.input.LineInfo().Height)) } - return 3 + wrapped := ansi.Hardwrap(ansi.Wordwrap(m.input.Value(), maxInt(1, m.input.Width()), ""), maxInt(1, m.input.Width()), true) + return minInt(5, 1+strings.Count(wrapped, "\n")) } - -func (m model) compactChat() bool { return m.height > 0 && m.height < 14 } - -func (m model) historyHeight() int { - return maxInt(1, m.height-m.chatChromeHeight()) +func (m model) historyHeight() int { return maxInt(1, m.height-m.chatChromeHeight()) } +func (m model) chatChromeHeight() int { + height := 3 + m.composerHeight() + if len(m.palette) > 0 { + height += lipgloss.Height(m.paletteView(m.contentWidth())) + } + return height } - func formatUsageTokens(value int) string { - if value <= 0 { + switch { + case value < 1: return "0" - } - if value < 1000 { + case value < 1000: return fmt.Sprintf("%d", value) - } - if value < 1_000_000 { + case value < 1_000_000: return fmt.Sprintf("%.1fK", float64(value)/1000) + default: + return fmt.Sprintf("%.1fM", float64(value)/1_000_000) } - return fmt.Sprintf("%.1fM", float64(value)/1_000_000) } - func formatUsageCost(picos int) string { if picos <= 0 { return "$0.00" @@ -89,7 +62,6 @@ func formatUsageCost(picos int) string { } return fmt.Sprintf("$%.2f", dollars) } - func (m model) usageSummary() string { tokens := m.usagePromptTokens + m.usageCompletionTokens + m.usageReasoningTokens if m.usageAttempts == 0 && tokens == 0 && m.usageCostPicos == 0 { @@ -97,128 +69,20 @@ func (m model) usageSummary() string { } return fmt.Sprintf("%s tokens · %s · %d call(s)", formatUsageTokens(tokens), formatUsageCost(m.usageCostPicos), m.usageAttempts) } - -func (m model) chatChromeHeight() int { - width := m.contentWidth() - nonViewport := []string{m.chatHeader()} - if progress := m.progressBlock(width); progress != "" { - nonViewport = append(nonViewport, progress) - } - if len(m.palette) > 0 { - nonViewport = append(nonViewport, m.paletteView(width)) - } - nonViewport = append(nonViewport, m.modeControls(width), m.composer(width), m.chatFooter(width)) - return lipgloss.Height(strings.Join(nonViewport, "\n")) -} - -func maxInt(a, b int) int { - if a > b { - return a - } - return b -} - +func maxInt(a, b int) int { return max(a, b) } +func minInt(a, b int) int { return min(a, b) } func limitRows(value string, height int) string { if height < 1 { return "" } lines := strings.Split(value, "\n") - if len(lines) > height { - lines = lines[:height] - } - return strings.Join(lines, "\n") -} - -func minInt(a, b int) int { - if a < b { - return a - } - return b + return strings.Join(lines[:min(len(lines), height)], "\n") } -func (m *model) syncViewport() { - if m.width < 1 || m.height < 1 { - return - } - offset := m.view.YOffset() - mainWidth, _ := m.layoutWidths() - m.view.SetWidth(mainWidth) - m.view.SetHeight(m.historyHeight()) - m.view.SetContent(m.history(mainWidth)) - if m.followTail { - m.view.GotoBottom() - } else { - m.view.SetYOffset(offset) - } +func clipRow(value string, width int) string { + return ansi.Truncate(strings.ReplaceAll(value, "\n", " "), maxInt(0, width), "") } -func (m *model) history(width int) string { - if len(m.messages) == 0 { - if m.screen != screenChat { - return "" - } - content := renderOpenKyrozenBanner(m.motionFrame, !m.reducedMotion) - if lipgloss.Width(content) > width || lipgloss.Height(content) > m.historyHeight() { - content = brandStyle.Render(compactText("OPENKYROZEN", width)) - } - return lipgloss.NewStyle().Width(width).MaxWidth(width).Height(m.historyHeight()).MaxHeight(m.historyHeight()).Align(lipgloss.Center, lipgloss.Center).Render(content) - } - var lines []string - for index := range m.messages { - message := &m.messages[index] - label, body := "KYROZEN", message.text - labelStyle := brandStyle - switch message.role { - case "user": - label, labelStyle = "YOU", titleStyle - case "thinking": - label, labelStyle = "THINKING", amberStyle - case "receipt": - status := strings.ToUpper(firstNonEmpty(message.status, "success")) - action := firstNonEmpty(message.toolAction, message.text, "unknown tool") - label, labelStyle = "TOOL · "+action+" · "+status, receiptStyle(message.status) - body = "" - if m.showToolDetails { - body = message.toolDetail - } - } - innerWidth := maxInt(1, width-5) - if message.role == "assistant" && body != "" && !message.streaming { - renderWidth := innerWidth - if message.renderedWidth != renderWidth { - message.rendered = renderMarkdown(body, renderWidth) - message.renderedWidth = renderWidth - } - body = message.rendered - } else if body != "" { - body = softStyle.Render(body) - } - if message.role == "assistant" && message.streaming { - cursor := mutedStyle.Render("▌") - if m.cursorVisible { - cursor = brandStyle.Render("▌") - } - body += cursor - } - if width < 12 { - lines = append(lines, softStyle.Render(compactText(label+" "+body, width))) - continue - } - block := labelStyle.Render(label) - if body != "" { - block += "\n" + body - } - boxWidth := maxInt(1, width-5) - style := assistantStyle - switch message.role { - case "user": - style = userStyle - case "thinking": - style = thinkingStyle - case "receipt": - style = receiptBoxStyle - } - lines = append(lines, style.Copy().Width(boxWidth).MaxWidth(boxWidth).Render(block)) - } - return strings.Join(lines, "\n\n") +func ansiWrap(body string, width int) string { + return ansi.Hardwrap(ansi.Wordwrap(body, width, ""), width, true) } diff --git a/tui/main.go b/tui/main.go index 09f644e8..cda5340d 100644 --- a/tui/main.go +++ b/tui/main.go @@ -1,7 +1,6 @@ package main import ( - tea "charm.land/bubbletea/v2" "flag" "fmt" "os" @@ -36,8 +35,7 @@ func main() { m.onboardingKind = "new" m.onboardingPreviousVersion = "" } - p := tea.NewProgram(m) - finalModel, err := p.Run() + finalModel, err := runTerminal(m) if err != nil { fmt.Fprintln(os.Stderr, "OpenKyrozen TUI:", err) os.Exit(1) diff --git a/tui/main_test.go b/tui/main_test.go index 7551385c..0cd9d5d6 100644 --- a/tui/main_test.go +++ b/tui/main_test.go @@ -9,7 +9,6 @@ import ( "path/filepath" "strings" "testing" - "time" "charm.land/bubbles/v2/textinput" tea "charm.land/bubbletea/v2" @@ -31,7 +30,7 @@ func TestOnboardingDistinguishesNewAndUpdatedInstall(t *testing.T) { } fresh.width, fresh.height, fresh.screen = 80, 24, screenOnboarding fresh.resize() - if !strings.Contains(fresh.View().Content, "WELCOME TO OPENKYROZEN") { + if !strings.Contains(fresh.View().Content, "OpenKyrozen setup") { t.Fatal("fresh install did not render the themed welcome screen") } @@ -76,7 +75,7 @@ func TestReducerProjectsStreamingResponseTasksAndApproval(t *testing.T) { if m.provider != "ollama" || m.modelName != "llama3.2" || m.workspace != "/tmp/workspace" { t.Fatalf("ready event was not reduced: %#v", m) } - if m.startupBackup != "/tmp/openkyrozen.sqlite3.backup.1" || !strings.Contains(m.splash(), m.startupBackup) { + if m.startupBackup != "/tmp/openkyrozen.sqlite3.backup.1" { t.Fatalf("migration backup was not shown during startup: %#v", m) } m.messages = append(m.messages, chatMessage{role: "assistant", streaming: true}) @@ -111,14 +110,14 @@ func TestWorkingPlanRevisionsRenderRationaleSupersessionAndVerifiedProgress(t *t map[string]any{"id": "verify", "description": "Verify behavior", "status": "pending", "supersedes": []any{"old"}}, }, }) - view := m.activityRail() - for _, want := range []string{"WORKING PLAN", "Separate", "verification", "superseded", "Replaced by", "Inspect", "Verify"} { + view := strings.Join(m.taskDetailLines(), "\n") + for _, want := range []string{"Working plan", "Separate", "verification", "superseded", "Replaced by", "Inspect", "Verify"} { if !strings.Contains(view, want) { t.Fatalf("working plan view omitted %q: %s", want, view) } } m.handleBackendEvent(backendEvent{"event": "task_update", "task_id": "inspect", "status": "succeeded"}) - if view = m.activityRail(); !strings.Contains(view, "verified") { + if view = strings.Join(m.taskDetailLines(), "\n"); !strings.Contains(view, "verified") { t.Fatalf("successful task was not presented as verified: %s", view) } } @@ -290,8 +289,8 @@ func TestToolDetailsAreHiddenByDefaultAndPersistWhenEnabled(t *testing.T) { m.handleBackendEvent(backendEvent{"event": "tool_receipt", "receipt": map[string]any{ "action": "inspect_config", "result": "api_key=super-secret", "success": true, }}) - hidden := m.history(100) - if !strings.Contains(hidden, "TOOL · read_file · SUCCESS") || strings.Contains(hidden, "secret file contents") || strings.Contains(hidden, "super-secret") { + hidden := testHistory(&m, 100) + if !strings.Contains(hidden, "read_file") || strings.Contains(hidden, "secret file contents") || strings.Contains(hidden, "super-secret") { t.Fatalf("tool receipt default visibility is unsafe: %q", hidden) } m.screen = screenSettings @@ -299,7 +298,7 @@ func TestToolDetailsAreHiddenByDefaultAndPersistWhenEnabled(t *testing.T) { t.Fatal("settings toggle did not enable tool details") } m.screen = screenChat - shown := m.history(100) + shown := testHistory(&m, 100) if !strings.Contains(shown, "secret file contents") || strings.Contains(shown, "super-secret") || !strings.Contains(shown, "api_key=") { t.Fatalf("enabled tool details were not rendered: %q", shown) } @@ -409,15 +408,15 @@ func TestUsageEventAppearsInChatAndSettings(t *testing.T) { }) m.resize() chat := m.View().Content - if !strings.Contains(chat, "deepseek-chat") || !strings.Contains(chat, "2.1K TOK") || !strings.Contains(chat, "$0.01") { - t.Fatalf("chat header omitted model or usage summary: %s", chat) + if !strings.Contains(chat, "deepseek-chat") || strings.Contains(chat, "2.1K TOK") || strings.Contains(chat, "$0.01") { + t.Fatalf("chat did not keep model and detailed usage in their respective views: %s", chat) } if got := lipgloss.Height(m.chatHeader()); got != 1 { t.Fatalf("context bar rendered %d rows, want 1", got) } m.screen = screenSettings settings := m.View().Content - if !strings.Contains(settings, "SESSION") || !strings.Contains(settings, "MEMORY") || !strings.Contains(settings, "workspace") { + if !strings.Contains(settings, "Session") || !strings.Contains(settings, "Memory") || !strings.Contains(settings, "workspace") { t.Fatalf("settings did not show session details: %s", settings) } } @@ -476,19 +475,6 @@ func TestPasteMsgReachesChatComposer(t *testing.T) { } } -func TestSplashFitsNarrowTerminalSizes(t *testing.T) { - for width := 1; width <= 60; width++ { - m := initialModel("", true) - m.width, m.height, m.screen = width, 8, screenSplash - m.reducedMotion = true - for index, line := range strings.Split(m.View().Content, "\n") { - if renderedWidth := lipgloss.Width(line); renderedWidth > width { - t.Fatalf("splash width %d line %d is %d cells wide", width, index, renderedWidth) - } - } - } -} - func assertChatFits(t *testing.T, width, height int) { t.Helper() m := initialModel("", true) @@ -523,7 +509,7 @@ func TestActivityRailCannotPushComposerOffscreen(t *testing.T) { } m.resize() content := m.View().Content - if !strings.Contains(content, "Ctrl+C quit") { + if !strings.Contains(content, "/ Commands") { t.Fatalf("footer was pushed below a 120x30 terminal: %s", content) } if !strings.Contains(content, "Kyrozen anything") { @@ -552,8 +538,8 @@ func TestProjectChatSidebarExposesCreationAndKeepsSelectedChatVisible(t *testing eventGroups = append(eventGroups, map[string]any{"scope_id": group.scopeID, "name": group.name, "chats": chats}) } m.applyNavigation(backendEvent{"active_scope_id": m.activeScopeID, "active_session_id": m.activeSessionID, "groups": eventGroups}) - view := m.navigationSidebar(m.navigationWidth(), m.historyHeight()) - for _, text := range []string{"+ New chat", "+ New project", "Project 7", "Chat 2"} { + view := m.navigationSidebar(m.width, m.historyHeight()) + for _, text := range []string{"N new chat", "P new project", "Project 7", "Chat 2"} { if !strings.Contains(view, text) { t.Fatalf("vertical project/chat navigation lost %q: %s", text, view) } @@ -671,73 +657,7 @@ func TestReducedMotionSkipsSplashAndBackgroundFillsWindow(t *testing.T) { } } -func TestSplashWaitsForBackendMinimumAndReadyHold(t *testing.T) { - m := initialModel("", false) - m.width, m.height = 90, 24 - m.reducedMotion = false - now := time.Now() - m.backendReady = true - m.splashStarted = now.Add(-3 * time.Second) - m.readyAt = now.Add(-100 * time.Millisecond) - updated, _ := m.Update(tickMsg(now)) - if updated.(model).screen != screenSplash { - t.Fatal("splash left before the ready hold elapsed") - } - m = updated.(model) - m.readyAt = now.Add(-readyHoldDuration) - updated, _ = m.Update(tickMsg(now)) - if updated.(model).screen != screenChat { - t.Fatal("splash did not leave after the minimum duration and ready hold") - } -} - -func TestSplashBannerFitsSupportedSizes(t *testing.T) { - for _, size := range [][2]int{{60, 16}, {90, 24}, {140, 40}} { - m := initialModel("", false) - m.width, m.height = size[0], size[1] - m.reducedMotion = true - for index, line := range strings.Split(m.splash(), "\n") { - if width := lipgloss.Width(line); width > size[0] { - t.Fatalf("%dx%d splash line %d is %d cells wide", size[0], size[1], index, width) - } - } - if !strings.Contains(m.splash(), "OPENKYROZEN") { - t.Fatalf("%dx%d splash lost the wordmark", size[0], size[1]) - } - if len(bannerRows(size[0]-4)) < 5 { - t.Fatal("banner is not multi-row") - } - } -} - -func TestReducedMotionKeepsStaticFinalBanner(t *testing.T) { - m := initialModel("", true) - m.width, m.height = 60, 16 - m.reducedMotion = true - first := m.splash() - m.splashFrame = 20 - if second := m.splash(); first != second { - t.Fatal("reduced-motion splash changed between frames") - } -} - -func TestSplashRevealHasSignalLogoTaglineAndMilestones(t *testing.T) { - m := initialModel("", false) - m.width, m.height = 90, 24 - m.reducedMotion = false - for frame := 0; frame <= 8; frame++ { - m.splashFrame = frame - view := m.splash() - if frame >= 3 && !strings.Contains(view, "OPENKYROZEN") { - t.Fatalf("frame %d did not reveal the logo", frame) - } - if frame >= 8 && !strings.Contains(view, "workspace") { - t.Fatalf("frame %d did not render startup milestones", frame) - } - } -} - -func TestThinkingCoalescesAndStreamingCursorPulses(t *testing.T) { +func TestThinkingCoalescesAndStreamingTextIsMarked(t *testing.T) { m := initialModel("", false) m.messages = []chatMessage{{role: "user", text: "hello"}} m.handleBackendEvent(backendEvent{"event": "thinking", "text": "Inspecting"}) @@ -746,12 +666,8 @@ func TestThinkingCoalescesAndStreamingCursorPulses(t *testing.T) { t.Fatalf("thinking events were appended instead of coalesced: %#v", m) } m.messages = append(m.messages, chatMessage{role: "assistant", streaming: true}) - m.cursorVisible = true - first := m.history(60) - m.cursorVisible = false - second := m.history(60) - if !strings.Contains(first, "▌") || !strings.Contains(second, "▌") || first == second { - t.Fatal("streaming cursor did not pulse") + if !strings.Contains(testHistory(&m, 60), "▌") { + t.Fatal("stream is missing its cursor") } } @@ -759,7 +675,7 @@ func TestStreamingAssistantSkipsMarkdownUntilResponse(t *testing.T) { m := initialModel("", true) m.messages = []chatMessage{{role: "assistant", text: "**bold**", streaming: true}} - streaming := m.history(60) + streaming := testHistory(&m, 60) if !strings.Contains(streaming, "**bold**") { t.Fatalf("streaming output was parsed as Markdown: %q", streaming) } @@ -768,12 +684,12 @@ func TestStreamingAssistantSkipsMarkdownUntilResponse(t *testing.T) { } m.handleBackendEvent(backendEvent{"event": "response", "text": "**bold**"}) - completed := m.history(60) + completed := testHistory(&m, 60) if strings.Contains(completed, "**bold**") || m.messages[0].renderedWidth == 0 { t.Fatalf("completed output did not render Markdown once: %q", completed) } rendered := m.messages[0].rendered - m.history(60) + testHistory(&m, 60) if m.messages[0].rendered != rendered { t.Fatal("completed Markdown render was not reused") } @@ -789,143 +705,46 @@ func TestToolReceiptsKeepSemanticStatus(t *testing.T) { } } -func TestTaskStateTransitionAndAdaptiveRail(t *testing.T) { +func TestTaskStateTransition(t *testing.T) { m := initialModel("", false) - m.reducedMotion = false - m.width, m.height = 140, 30 m.tasks = []taskItem{{id: "t1", description: "Build", status: "running"}} - if _, rail := m.layoutWidths(); rail == 0 { - t.Fatal("wide layout did not allocate an activity rail") - } - if !m.animating() { - t.Fatal("running task did not keep its activity indicator animated") - } m.handleBackendEvent(backendEvent{"event": "tasks", "tasks": []any{map[string]any{"id": "t1", "description": "Build", "status": "succeeded"}}}) if m.taskFlashID != "t1" || m.taskFlashTick == 0 { - t.Fatal("running to completed task transition lost its one-shot state") - } - m.width = 90 - if _, rail := m.layoutWidths(); rail != 0 { - t.Fatal("medium layout did not collapse the rail") + t.Fatal("task completion was lost") } } -func TestFocusedCockpitRailBreakpointAndCompactGraph(t *testing.T) { - m := initialModel("", true) - m.graph = graphSnapshot{status: "ready", nodes: 12, edges: 18} - for _, size := range [][2]int{{119, 40}, {120, 23}} { - m.width, m.height = size[0], size[1] - if _, rail := m.layoutWidths(); rail != 0 { - t.Fatalf("terminal %dx%d unexpectedly rendered a rail", size[0], size[1]) +func TestFullWidthConversationAtEveryBreakpoint(t *testing.T) { + for _, width := range []int{60, 80, 120, 160} { + m := initialModel("", true) + m.width, m.height = width, 30 + m.resize() + if m.view.width != width || m.view.height < 24 { + t.Fatalf("%d columns: transcript is %dx%d", width, m.view.width, m.view.height) } - if header := m.chatHeader(); !strings.Contains(header, "READY") { - t.Fatalf("terminal %dx%d lost compact graph state: %s", size[0], size[1], header) + for _, noise := range []string{"PROJECT GRAPH", "PROJECTS & CHATS", "No active tasks"} { + if strings.Contains(m.View().Content, noise) { + t.Fatalf("conversation contains %s", noise) + } } } - m.width, m.height = 120, 24 - if _, rail := m.layoutWidths(); rail == 0 { - t.Fatal("120x24 did not enable the contextual rail") - } - if header := m.chatHeader(); strings.Contains(header, "◇ READY") { - t.Fatalf("wide header duplicated graph telemetry: %s", header) - } } -func TestFocusedCockpitMessageHierarchyAndEmptyState(t *testing.T) { - m := initialModel("", true) - m.width, m.height, m.screen = 120, 30, screenChat - mainWidth, _ := m.layoutWidths() - empty := m.history(mainWidth) - for _, unwanted := range []string{"WORKSPACE READY", "/plan", "/attach", "/graph", "ASK ANYTHING"} { - if strings.Contains(empty, unwanted) { - t.Fatalf("empty state contains unwanted text %q: %s", unwanted, empty) - } - } - if lipgloss.Height(empty) != m.historyHeight() { - t.Fatalf("empty state height is %d, want %d", lipgloss.Height(empty), m.historyHeight()) - } - if !strings.Contains(empty, "█") || !strings.Contains(empty, "░") { - t.Fatalf("empty state lost the readable face or 3D shadow: %s", empty) - } - bannerLine := -1 - for index, line := range strings.Split(empty, "\n") { - if strings.Contains(line, "█") { - bannerLine = index - break - } - } - if bannerLine < 2 || bannerLine > m.historyHeight()-lipgloss.Height(renderOpenKyrozenBanner(0, false))-2 { - t.Fatalf("empty-state banner is not vertically centered: line %d of %d", bannerLine, m.historyHeight()) - } - compact := m.history(20) - if !strings.Contains(compact, "OPENKYROZEN") || strings.Contains(compact, "░") { - t.Fatalf("narrow empty state did not use the compact wordmark: %s", compact) - } - for _, size := range [][2]int{{1, 1}, {20, 8}, {40, 12}, {60, 16}, {80, 24}, {120, 30}, {140, 40}, {200, 60}, {800, 200}} { - sized := initialModel("", true) - sized.width, sized.height, sized.screen = size[0], size[1], screenChat - sized.resize() - content := sized.View().Content - if size[0] >= 11 && size[0] < 80 && !strings.Contains(content, "OPENKYROZEN") { - t.Fatalf("%dx%d empty state lost the compact wordmark", size[0], size[1]) - } - if size[0] >= 80 && (!strings.Contains(content, "█") || !strings.Contains(content, "░")) { - t.Fatalf("%dx%d empty state lost the 3D wordmark", size[0], size[1]) - } - if len(strings.Split(content, "\n")) != size[1] { - t.Fatalf("%dx%d empty state exceeded terminal height", size[0], size[1]) - } - for index, line := range strings.Split(content, "\n") { - if width := lipgloss.Width(line); width > size[0] { - t.Fatalf("%dx%d empty-state line %d is %d cells wide", size[0], size[1], index, width) - } - } - } - m.reducedMotion = false - m.motionFrame = 12 - animated := m.history(mainWidth) - m.motionFrame = 32 - if animated == m.history(mainWidth) || !m.animating() { - t.Fatal("empty banner did not animate its light sweep") +func TestEmptyChatIsReadyForText(t *testing.T) { + m := initialModel("/tmp/payments", false) + m.width, m.height = 120, 30 + m.resize() + if m.screen != screenChat || !m.input.Focused() { + t.Fatal("composer not ready") } - m.reducedMotion = true - still := m.history(mainWidth) - m.motionFrame = 64 - if still != m.history(mainWidth) || m.animating() { - t.Fatal("reduced motion did not freeze the banner") - } - m.messages = []chatMessage{ - {role: "user", text: "Review this"}, - {role: "assistant", text: "Working **carefully**.", streaming: true}, - {role: "thinking", text: "Inspecting the graph"}, - {role: "receipt", toolAction: "read_file", status: "success", toolDetail: "private details"}, - } - history := m.history(80) - for _, label := range []string{"YOU", "KYROZEN", "THINKING", "TOOL · read_file · SUCCESS", "▌"} { - if !strings.Contains(history, label) { - t.Fatalf("message hierarchy omitted %q: %s", label, history) + view := m.View().Content + for _, want := range []string{"OpenKyrozen", "payments", "Kyrozen anything", "Enter send"} { + if !strings.Contains(view, want) { + t.Fatal(want) } } - if strings.Contains(history, "private details") { - t.Fatalf("collapsed tool receipt exposed details: %s", history) - } - if strings.Contains(history, "░") { - t.Fatal("empty-state banner remained after the conversation started") - } -} - -func TestEmptyBannerIsHiddenOutsideChat(t *testing.T) { - for _, current := range []screen{ - screenSplash, screenOnboarding, screenProvider, screenAPIKey, screenApproval, - screenSelfLearning, screenMode, screenPermissions, screenQuestion, screenPlan, screenGraph, - screenGithubAuth, screenSettings, screenUpdating, screenError, - } { - m := initialModel("", true) - m.width, m.height, m.screen = 120, 30, current - m.resize() - if content := m.View().Content; strings.Contains(content, "░") { - t.Fatalf("empty banner remained visible on %s screen", current) - } + if m.view.View() != "" { + t.Fatal("empty chat should have a quiet transcript") } } @@ -940,7 +759,7 @@ func TestFocusedCockpitDoesNotDuplicateModelTelemetry(t *testing.T) { if got := strings.Count(view, "deepseek-v4-flash"); got != 1 { t.Fatalf("model telemetry appeared %d times, want once: %s", got, view) } - if got := strings.Count(view, "7.8K TOK"); got != 1 || !strings.Contains(view, "4 calls · workspace") { + if got := strings.Count(view, "7.8K TOK"); got != 0 || strings.Contains(view, "4 calls · workspace") { t.Fatalf("session usage hierarchy is incomplete or duplicated: %s", view) } } @@ -949,14 +768,14 @@ func TestFocusedCockpitPaletteAndModalUseUnifiedFrame(t *testing.T) { m := initialModel("", true) m.palette = commandMatches("/") palette := m.paletteView(80) - if !strings.Contains(palette, "╭") || !strings.Contains(palette, "COMMANDS") { + if !strings.Contains(palette, "╭") || !strings.Contains(palette, "Commands") { t.Fatalf("command palette lost the cockpit frame: %s", palette) } m.width, m.height, m.screen = 80, 24, screenApproval m.approvalTool = "run_cmd" m.resize() modal := m.View().Content - if !strings.Contains(modal, "╭") || !strings.Contains(modal, "APPROVAL REQUIRED") { + if !strings.Contains(modal, "─") || !strings.Contains(modal, "Approval required") { t.Fatalf("approval modal lost the cockpit frame: %s", modal) } } @@ -988,7 +807,7 @@ func TestGraphStateRendersWideNarrowAndExplorer(t *testing.T) { }}) m.width, m.height = 140, 40 m.resize() - if rail := m.activityRail(); !strings.Contains(rail, "PROJECT GRAPH") || !strings.Contains(rail, "2 nodes") { + if rail := m.graphExplorer(); !strings.Contains(rail, "Project graph") || !strings.Contains(rail, "2 nodes") { t.Fatalf("wide graph rail is incomplete: %s", rail) } m.width = 80 @@ -1032,7 +851,7 @@ func TestMouseWheelStaysInsideViewportAndPreservesManualScroll(t *testing.T) { m := initialModel("", true) m.width, m.height = 80, 24 m.screen = screenChat - m.messages = []chatMessage{{role: "assistant", text: strings.Repeat("line of transcript\n", 80)}} + m.messages = []chatMessage{{role: "assistant", text: strings.Repeat("- line of transcript\n", 80)}} m.resize() m.view.GotoBottom() m.followTail = true @@ -1060,7 +879,7 @@ func TestStreamingPreservesManualViewportOffset(t *testing.T) { m := initialModel("", true) m.width, m.height = 80, 24 m.screen = screenChat - m.messages = []chatMessage{{role: "assistant", text: strings.Repeat("line of transcript\n", 100)}} + m.messages = []chatMessage{{role: "assistant", text: strings.Repeat("- line of transcript\n", 100)}} m.resize() m.view.GotoBottom() m.followTail = true @@ -1192,15 +1011,10 @@ func TestEffectiveAgentModeIsProminentDuringPlanExecution(t *testing.T) { }) m.resize() view := m.View().Content - if !strings.Contains(view, "AGENT") { + if !strings.Contains(view, "plan → agent") { t.Fatalf("header did not show effective Agent mode: %s", view) } - if !strings.Contains(view, "preference plan") || !strings.Contains(view, "agent") { - t.Fatalf("activity rail did not distinguish preference and active mode: %s", view) - } - if !strings.Contains(view, "System One: kev") { - t.Fatalf("activity rail did not show System One setting: %s", view) - } + } func TestProviderKeyIsMaskedAndApprovalArgsAreRedacted(t *testing.T) { @@ -1232,17 +1046,11 @@ func TestModeAndPermissionControlsPreserveComposerAndStayVisibleWhenNarrow(t *te m.input.SetValue("keep this draft") m.resize() view := m.View().Content - for _, want := range []string{"MODE", "PERMISSIONS", "[ ASK ]", "[ JEV ]", "[ NO JEV ]"} { + for _, want := range []string{"auto", "Ask before tools", "Enter send"} { if !strings.Contains(view, want) { - t.Fatalf("compact controls omitted %q: %s", want, view) + t.Fatal(want) } } - if rows := len(strings.Split(view, "\n")); rows > m.height { - t.Fatalf("compact controls overflowed terminal height: %d > %d", rows, m.height) - } - if m.modeTabAt(8, m.modeControlsStartY()) != 0 || m.permissionTabAt(14, m.modeControlsStartY()+1) != 0 { - t.Fatal("mode or permission click target did not resolve") - } var sent bytes.Buffer m.bridge.stdin = bufio.NewWriter(&sent) if _, quit := m.handleKey(tea.KeyPressMsg{Code: 't', Mod: tea.ModCtrl}); quit { @@ -1292,57 +1100,6 @@ func TestTabCyclesInteractionModeWithoutClearingComposer(t *testing.T) { } } -func TestChatFooterExplainsModeAndPermissionShortcuts(t *testing.T) { - m := initialModel("", true) - footer := m.chatFooter(120) - for _, want := range []string{"Tab mode", "Ctrl+P permissions"} { - if !strings.Contains(footer, want) { - t.Fatalf("chat footer omitted %q: %s", want, footer) - } - } -} - -func TestMouseSelectsModeAndPermissionWithoutClearingComposer(t *testing.T) { - m := initialModel("", true) - m.width, m.height, m.screen = 120, 30, screenChat - m.input.SetValue("keep this draft") - m.resize() - var sent bytes.Buffer - m.bridge.stdin = bufio.NewWriter(&sent) - for _, point := range [][2]int{{24, m.modeControlsStartY()}, {36, m.modeControlsStartY() + 1}} { - updated, _ := m.Update(tea.MouseClickMsg{X: point[0], Y: point[1], Button: tea.MouseLeft}) - m = updated.(model) - } - lines := strings.Split(strings.TrimSpace(sent.String()), "\n") - if len(lines) != 2 || m.input.Value() != "keep this draft" { - t.Fatalf("mouse controls did not preserve the composer and send both changes: %q", sent.String()) - } - var mode, permission map[string]any - if err := json.Unmarshal([]byte(lines[0]), &mode); err != nil { - t.Fatal(err) - } - if err := json.Unmarshal([]byte(lines[1]), &permission); err != nil { - t.Fatal(err) - } - if mode["name"] != "mode" || mode["args"] != "plan" || permission["name"] != "permissions" || permission["args"] != "full" { - t.Fatalf("mouse selections sent incorrect commands: %#v %#v", mode, permission) - } -} - -func TestPermissionHitTargetsMatchRenderedLabels(t *testing.T) { - for _, test := range []struct { - width int - x int - }{{120, 50}, {60, 38}} { - m := initialModel("", true) - m.width, m.height, m.screen = test.width, 30, screenChat - m.resize() - if index := m.permissionTabAt(test.x, m.modeControlsStartY()+1); index != 2 { - t.Fatalf("width %d: right edge of full-without-Jev tab selected %d, want 2", test.width, index) - } - } -} - func TestPermissionSelectorSendsSelectedMode(t *testing.T) { m := initialModel("", true) m.screen, m.permissionIdx = screenPermissions, 2 @@ -1360,21 +1117,6 @@ func TestPermissionSelectorSendsSelectedMode(t *testing.T) { } } -func TestBusyChatIgnoresModeAndPermissionClicks(t *testing.T) { - m := initialModel("", true) - m.width, m.height, m.screen, m.busy = 120, 30, screenChat, true - m.resize() - var sent bytes.Buffer - m.bridge.stdin = bufio.NewWriter(&sent) - for _, point := range [][2]int{{8, m.modeControlsStartY()}, {16, m.modeControlsStartY() + 1}} { - updated, _ := m.Update(tea.MouseClickMsg{X: point[0], Y: point[1], Button: tea.MouseLeft}) - m = updated.(model) - } - if sent.Len() != 0 { - t.Fatalf("busy chat sent a mode or permission change: %s", sent.String()) - } -} - func TestStartupUpdateNoticeFitsAndPreservesChat(t *testing.T) { for _, size := range [][2]int{{120, 36}, {80, 24}, {40, 16}, {26, 12}} { m := initialModel("", true) @@ -1403,3 +1145,11 @@ func TestStartupUpdateNoticeFitsAndPreservesChat(t *testing.T) { t.Fatalf("update command missing from palette: %v", matches) } } + +func testHistory(m *model, width int) string { + var rows []string + for index := range m.messages { + rows = append(rows, m.messageRows(index, width)...) + } + return strings.Join(rows, "\n") +} diff --git a/tui/model.go b/tui/model.go index 2cc6a3a6..3f234178 100644 --- a/tui/model.go +++ b/tui/model.go @@ -10,20 +10,9 @@ import ( var version = "3.0.0" -var openKyrozenBanner = []string{ - " ███ ████ █████ █ █ █ █ █ █ ████ ███ █████ █████ █ █", - "█ █ █ █ █ ██ █ █ █ █ █ █ █ █ █ █ █ ██ █", - "█ █ █ █ █ ██ █ █ █ █ █ █ █ █ █ █ █ ██ █", - "█ █ ████ ████ █ █ █ ██ █ ████ █ █ █ ████ █ █ █", - "█ █ █ █ █ ██ █ █ █ █ █ █ █ █ █ █ ██", - "█ █ █ █ █ ██ █ █ █ █ █ █ █ █ █ █ ██", - " ███ █ █████ █ █ █ █ █ █ █ ███ █████ █████ █ █", -} - type screen string const ( - screenSplash screen = "splash" screenOnboarding screen = "onboarding" screenChat screen = "chat" screenProvider screen = "provider" @@ -52,6 +41,7 @@ type chatMessage struct { status string toolAction string toolDetail string + toggleDetails bool streaming bool rendered string renderedWidth int @@ -106,17 +96,18 @@ type planStep struct { type planProposal struct { planID, fingerprint, title, summary string - version int - steps []planStep + version int + steps []planStep } type model struct { + workspaceUI bridge *bridge project string global bool width int height int - view viewport.Model + view transcriptViewport approvalView viewport.Model input textarea.Model apiInput textinput.Model @@ -146,6 +137,8 @@ type model struct { navigation []navigationGroup navigationIndex int navigationOpen bool + navigationFilter string + navigationSearching bool navigationFocused bool pendingDeleteKind string pendingDeleteScopeID string @@ -201,12 +194,8 @@ type model struct { approvalArgs string approvalDetailsComplete bool errorText string - splashFrame int - splashStarted time.Time - readyAt time.Time backendReady bool motionFrame int - cursorVisible bool thinkingText string taskFlashID string taskFlashTick int @@ -235,9 +224,7 @@ type githubAuthDoneMsg struct{ err error } type backendEventsMsg struct{ lines []backendLineMsg } const ( - splashMinimumDuration = 2400 * time.Millisecond - readyHoldDuration = 300 * time.Millisecond - mouseWheelScrollStep = 5 + mouseWheelScrollStep = 5 ) var uiSensitiveArgRE = regexp.MustCompile(`(?i)(api[_-]?key|secret|password|token)\s*[:=]\s*[^\s,;]+`) diff --git a/tui/navigation.go b/tui/navigation.go index 63965887..3daf5236 100644 --- a/tui/navigation.go +++ b/tui/navigation.go @@ -1,81 +1,135 @@ package main import ( + "fmt" "strings" + + "charm.land/lipgloss/v2" ) -type navigationTarget struct{ scopeID, id, path, kind string } +type navigationTarget struct{ scopeID, id, path, kind, label string } func (m model) navigationTargets() []navigationTarget { - var targets []navigationTarget + filter := strings.ToLower(strings.TrimSpace(m.navigationFilter)) + var rows []navigationTarget for _, group := range m.navigation { - kind := "workspace" - if group.scope == "project" { - kind = "project" - } - targets = append(targets, navigationTarget{scopeID: group.scopeID, path: group.path, kind: kind}) + matches := strings.Contains(strings.ToLower(group.name), filter) + var children []navigationTarget for _, chat := range group.chats { - targets = append(targets, navigationTarget{scopeID: group.scopeID, id: chat.id, path: group.path, kind: "chat"}) + label := firstNonEmpty(chat.title, "New chat") + if matches || strings.Contains(strings.ToLower(label), filter) { + children = append(children, navigationTarget{scopeID: group.scopeID, id: chat.id, path: group.path, kind: "chat", label: label}) + } + } + if matches || len(children) > 0 { + kind := "workspace" + if group.scope == "project" { + kind = "project" + } + rows = append(rows, navigationTarget{scopeID: group.scopeID, path: group.path, kind: kind, label: group.name}) + rows = append(rows, children...) } } - return targets + return rows } -func (m model) navigationSidebar(panelWidth, height int) string { - width := maxInt(1, panelWidth-2) - textWidth := maxInt(1, width-2) - lines := []string{ - sectionStyle.Render("PROJECTS & CHATS"), - brandStyle.Render("N + New chat"), - brandStyle.Render("P + New project"), - mutedStyle.Render("Ctrl+B focus / close"), - mutedStyle.Render("d delete selected chat / project"), +func (m model) navigationSidebar(width, height int) string { + lines := []string{brandStyle.Render("Sessions")} + if m.navigationSearching || m.navigationFilter != "" { + lines = append(lines, titleStyle.Render("Search "+m.navigationFilter+"▏")) + } + rows := m.navigationTargets() + available := maxInt(1, height-len(lines)-2) + selected := maxInt(0, minInt(len(rows)-1, m.navigationIndex)) + start := maxInt(0, selected-available+1) + for i := start; i < minInt(start+available, len(rows)); i++ { + row := rows[i] + prefix, style := " ", titleStyle + if row.kind == "chat" { + prefix, style = " ", softStyle + } + marker := " " + if i == selected { + marker, style = "› ", brandStyle + } + label := row.label + if row.kind == "chat" && row.id == m.activeSessionID { + label += " · current" + } + lines = append(lines, style.Render(clipRow(marker+prefix+label, width-2))) } - if height > 9 { - lines = append(lines, "") + if len(rows) == 0 { + lines = append(lines, mutedStyle.Render("No matching sessions")) } - body := []string{} - selectedRow, activeRow := -1, -1 - index := 0 - for _, group := range m.navigation { - groupStyle := softStyle - if group.scopeID == m.activeScopeID { - groupStyle = brandStyle + lines = append(lines, "", mutedStyle.Render(clipRow("Enter open Ctrl+F search N new chat P new project D delete Esc close", width-2))) + return strings.Join(lines, "\n") +} + +func (m model) taskDetailLines() []string { + list := m.tasks + lines := []string{} + if plan := m.workingPlan; plan != nil { + list = plan.tasks + lines = append(lines, titleStyle.Render(fmt.Sprintf("Working plan · v%d · %s", plan.revision, plan.status))) + if plan.reason != "" { + lines = append(lines, softStyle.Render(plan.reason)) } - body = append(body, groupStyle.Render(compactText(group.name, textWidth))) - if m.navigationFocused && index == m.navigationIndex { - selectedRow = len(body) - 1 + } + names := map[string]string{} + for _, task := range list { + names[task.id] = task.description + } + for _, task := range list { + icon, style, label := taskState(task.status, m.motionFrame) + if task.status == "succeeded" { + label = "verified" } - index++ - if len(group.chats) == 0 { - body = append(body, mutedStyle.Render(" No chats")) + if len(task.supersededBy) > 0 && task.status == "cancelled" { + label = "superseded" } - for _, chat := range group.chats { - marker := " " - style := mutedStyle - if chat.id == m.activeSessionID { - marker, style = "● ", titleStyle - activeRow = len(body) - } - if m.navigationFocused && index == m.navigationIndex { - marker, style = "› ", brandStyle - selectedRow = len(body) + lines = append(lines, style.Render(icon+" "+label)+" "+softStyle.Render(task.description)) + if task.reason != "" { + lines = append(lines, mutedStyle.Render(" "+task.reason)) + } + if len(task.supersededBy) > 0 { + replaced := []string{} + for _, id := range task.supersededBy { + replaced = append(replaced, firstNonEmpty(names[id], id)) } - body = append(body, style.Render(marker+compactText(firstNonEmpty(chat.title, "New chat"), maxInt(1, textWidth-2)))) - index++ + lines = append(lines, mutedStyle.Render(" Replaced by "+strings.Join(replaced, ", "))) } - body = append(body, "") } - visible := maxInt(1, height-len(lines)) - focusRow := activeRow - if selectedRow >= 0 { - focusRow = selectedRow + if len(lines) == 0 { + lines = append(lines, "No active tasks") } - start := 0 - if focusRow >= visible { - start = focusRow - visible + 1 + return lines +} + +// A decision sheet occupies the lower part of the current conversation. Its +// final action row stays visible even when terminal space is constrained. +func (m model) bottomSheet(background, body string) string { + width, height := maxInt(1, m.width), maxInt(1, m.height) + style := lipgloss.NewStyle().Background(lipgloss.Color(surface)).Width(width).MaxWidth(width).Padding(0, 1) + lines := strings.Split(ansiWrap(body, maxInt(1, width-2)), "\n") + room := maxInt(1, height-2) + if len(lines) > room { + lines = append(lines[:maxInt(0, room-1)], lines[len(lines)-1]) + } + sheet := rule(width) + "\n" + style.Render(strings.Join(lines, "\n")) + remaining := height - lipgloss.Height(sheet) + if remaining <= 0 { + return limitRows(sheet, height) + } + if m.followTail && len(m.messages) > 0 && remaining > 1 { + v := m.view + v.height = remaining - 1 + v.GotoBottom() + return m.chatHeader() + "\n" + fitBody(v.View(), v.height) + "\n" + sheet } - end := minInt(len(body), start+visible) - lines = append(lines, body[start:end]...) - return activityStyle.Copy().Width(width).MaxWidth(width).Height(height).MaxHeight(height).Render(limitRows(strings.Join(lines, "\n"), height)) + return fitBody(background, remaining) + "\n" + sheet +} + +func (m model) sheetTop(body string) int { + rows := strings.Count(ansiWrap(body, maxInt(1, m.width-2)), "\n") + 1 + return maxInt(0, m.height-1-minInt(rows, maxInt(1, m.height-2))) } diff --git a/tui/screenshots/focused-cockpit-after.svg b/tui/screenshots/focused-cockpit-after.svg deleted file mode 100644 index 47ccd4c3..00000000 --- a/tui/screenshots/focused-cockpit-after.svg +++ /dev/null @@ -1 +0,0 @@ -OpenKyrozen TUI — focused cockpit◆ OPENKYROZEN · ASK · deepseek-v4-flash · 7.8K TOK · $0.02● READYYOUPROJECT GRAPHREADYMake the terminal feel focused, calm, and unmistakably Kyrozen.◆ ·· KYROZEN · ●## Focused cockpit●● The transcript now owns the screen while graph, tasks, and memory stay close at hand. 38 nodes · 61 edges • Calm context hierarchy TASKS 3 • Compact, privacy-safe receipts ✓Map terminal…completed • Responsive from tiny terminals to fullscreen ◐Polish focused…running○Verify respons…pendingTOOL · read_file · SUCCESSSESSIONkyrozen-demo4 calls · workspacepreference autoactive ask╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮│› Ask Kyrozen anything…││› ││› │╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯kyrozen-demo Enter send · Shift+Enter newline · / commands · PgUp/PgDn scroll · Ctrl+C quit \ No newline at end of file diff --git a/tui/screenshots/focused-cockpit-before.svg b/tui/screenshots/focused-cockpit-before.svg deleted file mode 100644 index 90875dee..00000000 --- a/tui/screenshots/focused-cockpit-before.svg +++ /dev/null @@ -1 +0,0 @@ -OpenKyrozen TUI — beforeOPENKYROZENASKMODEL deepseek · deepseek-v4-flashUSAGE 7.8K tokens · $0.02 · 4 call(s)WORKSPACE /tmp/kyrozen-demo────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────YOUPROJECT GRAPHREADYMake the terminal feel focused, calm, and unmistakably Kyrozen.◆KYROZEN · · ## Focused cockpit · ●●The transcript now owns the screen while graph, tasks, and memory stay close at hand. • Calm context hierarchy • Compact, privacy-safe receipts ●• Responsive from tiny terminals to fullscreen 38 nodes · 61 edgesTOOL · read_file · SUCCESSACTIVITY────────────────────────────PROVIDERdeepseekdeepseek-v4-flashWORKSPACE/tmp/kyrozen-demoUSAGE7.8K tokens · $0.02 · 4call(s)MODEpreference auto · active askTASKS 3✓Map terminal layoutcompleted◐Polish focused cockpit› Ask Kyrozen anything…› › ○ ReadyEnter send · Shift+Enter newline · ↑↓ commands · PgUp/PgDn scroll · Ctrl+C quit \ No newline at end of file diff --git a/tui/slash.go b/tui/slash.go index 89718067..4f69fa34 100644 --- a/tui/slash.go +++ b/tui/slash.go @@ -12,6 +12,11 @@ type command struct { } var commands = []command{ + {name: "help", description: "Read keyboard shortcuts and command instructions"}, + {name: "instructions", description: "Read instructions applied to this workspace"}, + {name: "queue", description: "Edit, withdraw or resume queued follow-ups"}, + {name: "latest", description: "Jump to the newest message"}, + {name: "usage", description: "Inspect token usage and cost"}, {name: "mode", aliases: nil, description: "Switch auto, ask, plan, or agent interaction mode"}, {name: "ask", aliases: nil, description: "Use read-only Ask mode"}, {name: "plan", aliases: nil, description: "Use Plan mode or accept/cancel a plan"}, diff --git a/tui/slash_test.go b/tui/slash_test.go index 0b8f97f0..5dbbf095 100644 --- a/tui/slash_test.go +++ b/tui/slash_test.go @@ -26,17 +26,17 @@ func TestCommandMatchesOnlyAtFirstNonWhitespaceCharacter(t *testing.T) { } } -func TestInteractionCommandsAreVisibleOnTheFirstPalettePage(t *testing.T) { - want := []string{"mode", "ask", "plan", "question", "agent"} - for index, name := range want { - if commands[index].name != name { - t.Fatalf("first palette page[%d] = %q, want %q", index, commands[index].name, name) +func TestInteractionCommandsAreSearchableAndPaletteReportsItsPosition(t *testing.T) { + for _, name := range []string{"mode", "ask", "plan", "question", "agent"} { + matches := commandMatches("/" + name) + if len(matches) == 0 { + t.Fatalf("interaction command %q is missing", name) } } m := initialModel(".", true) m.palette = commandMatches("/") view := m.paletteView(80) - if !strings.Contains(view, "1–5 OF ") || !strings.Contains(view, "↑↓ MORE") { + if !strings.Contains(view, "1–5 of ") || !strings.Contains(view, "↑↓ more") { t.Fatalf("palette did not disclose hidden commands: %s", view) } } diff --git a/tui/startup.go b/tui/startup.go index 5f7f4035..c6416fd5 100644 --- a/tui/startup.go +++ b/tui/startup.go @@ -8,6 +8,7 @@ import ( "charm.land/lipgloss/v2" "fmt" "os" + "strings" "time" ) @@ -20,7 +21,7 @@ func initialModel(project string, global bool) model { input.Prompt = "› " input.CharLimit = 12_000 input.ShowLineNumbers = false - input.SetHeight(3) + input.SetHeight(1) input.SetWidth(60) input.Focus() inputStyles := input.Styles() @@ -51,9 +52,6 @@ func initialModel(project string, global bool) model { projectInput.Placeholder = "Project directory" projectInput.CharLimit = 4096 projectInput.SetStyles(apiStyles) - transcript := viewport.New() - transcript.MouseWheelEnabled = true - transcript.MouseWheelDelta = mouseWheelScrollStep approval := viewport.New() approval.MouseWheelEnabled = true approval.MouseWheelDelta = mouseWheelScrollStep @@ -61,16 +59,13 @@ func initialModel(project string, global bool) model { bridge: newBridge(), project: project, global: global, - view: transcript, approvalView: approval, input: input, apiInput: apiInput, graphInput: graphInput, projectInput: projectInput, - screen: screenSplash, + screen: screenChat, status: "Starting the workspace…", - splashStarted: time.Now(), - cursorVisible: true, followTail: true, reducedMotion: reducedMotion, showToolDetails: settings.ShowToolDetails, @@ -87,11 +82,7 @@ func initialModel(project string, global bool) model { } func (m model) Init() tea.Cmd { - cmds := []tea.Cmd{startBackend(m.bridge)} - if !m.reducedMotion { - cmds = append(cmds, motionTick()) - } - return tea.Batch(cmds...) + return startBackend(m.bridge) } func startBackend(b *bridge) tea.Cmd { @@ -133,7 +124,27 @@ func isUpdateStatus(line backendLineMsg) bool { return line.err == nil && stringValue(line.event, "event") == "status" && stringValue(line.event, "state") == "updating" } +func bindsConversation(command string, payload map[string]any) bool { + if command == "navigate" { + return true + } + if command != "command" { + return false + } + words := strings.Fields(strings.TrimPrefix(strings.ToLower(stringValue(payload, "name")), "/")) + return len(words) > 0 && (words[0] == "new" || (len(words) > 1 && (words[0] == "project" || words[0] == "session"))) +} + func (m *model) send(command string, payload map[string]any) { + if m.navigationRequest != "" { + m.status = "Waiting for workspace navigation…" + return + } + changesConversation := bindsConversation(command, payload) + if changesConversation && (m.activeTurn != "" || m.busy) { + m.status = "Wait for the current turn before changing chats." + return + } if payload == nil { payload = map[string]any{} } @@ -144,6 +155,8 @@ func (m *model) send(command string, payload map[string]any) { } if err := m.bridge.send(payload); err != nil { m.setError(err.Error()) + } else if changesConversation { + m.navigationRequest = stringValue(payload, "request_id") } } diff --git a/tui/startup_view.go b/tui/startup_view.go index e6b6927a..9d15ff53 100644 --- a/tui/startup_view.go +++ b/tui/startup_view.go @@ -3,47 +3,12 @@ package main import ( tea "charm.land/bubbletea/v2" "charm.land/lipgloss/v2" - "strings" ) -func renderOpenKyrozenBanner(frame int, animated bool) string { - glyphs := make([][]rune, len(openKyrozenBanner)) - for index, row := range openKyrozenBanner { - glyphs[index] = []rune(row) - } - width := len(glyphs[0]) + 2 - height := len(glyphs) + 1 - highlightX := -10 - if animated { - highlightX = (frame/2)%(width+12) - 6 - } - front, highlight, shadow := brandStyle.Render("█"), titleStyle.Render("█"), ruleStyle.Render("░") - lines := make([]string, height) - for y := 0; y < height; y++ { - var line strings.Builder - for x := 0; x < width; x++ { - isFront := y < len(glyphs) && x < len(glyphs[y]) && glyphs[y][x] != ' ' - isShadow := y > 0 && x > 1 && x-2 < len(glyphs[y-1]) && glyphs[y-1][x-2] != ' ' - switch { - case isFront && x >= highlightX-1 && x <= highlightX+1: - line.WriteString(highlight) - case isFront: - line.WriteString(front) - case isShadow: - line.WriteString(shadow) - default: - line.WriteByte(' ') - } - } - lines[y] = line.String() - } - return strings.Join(lines, "\n") -} - func (m model) View() tea.View { var content string - if m.screen == screenSplash { - content = m.splash() + if m.screen == screenUtility { + content = m.utilityView() } else if m.screen == screenGraph { content = m.graphExplorer() } else if m.screen == screenAgents { @@ -66,48 +31,6 @@ func (m model) View() tea.View { } func (m model) updatingView() string { - width := maxInt(1, m.width-8) - lines := []string{ - brandStyle.Render("OPENKYROZEN"), - "", - titleStyle.Render("Updating OpenKyrozen"), - "", - amberStyle.Render(taskSpinner(m.motionFrame) + " " + firstNonEmpty(m.status, "Updating files and preparing the restart…")), - "", - softStyle.Render("Your workspace is temporarily locked while the update is installed."), - softStyle.Render("OpenKyrozen will restart automatically when it is ready."), - "", - mutedStyle.Render("Ctrl+C emergency quit"), - } - return lipgloss.NewStyle().Width(maxInt(1, m.width)).Height(maxInt(1, m.height)).Align(lipgloss.Center, lipgloss.Center).Render( - lipgloss.NewStyle().Width(width).MaxWidth(width).Align(lipgloss.Center).Render(strings.Join(lines, "\n")), - ) -} - -func (m model) splash() string { - width := maxInt(1, minInt(56, m.width-4)) - rows := bannerRows(width) - visible := len(rows) - if !m.reducedMotion { - visible = minInt(len(rows), maxInt(0, m.splashFrame-1)) - } - logo := make([]string, 0, len(rows)) - for index, row := range rows { - if index >= visible { - row = strings.Repeat(" ", lipgloss.Width(row)) - } - style := softStyle - if index != 3 { - style = brandStyle - } - logo = append(logo, style.Copy().Width(width).Align(lipgloss.Center).Render(row)) - } - lines := append(logo, "") - lines = append(lines, startupMilestones(m)...) - if m.startupBackup != "" { - lines = append(lines, mutedStyle.Render("SQLite backup: "+m.startupBackup)) - } - lines = append(lines, "", splashStatus(m)) - content := strings.Join(lines, "\n") - return lipgloss.NewStyle().Width(maxInt(1, m.width)).Height(maxInt(1, m.height)).Align(lipgloss.Center, lipgloss.Center).Render(content) + lines := []string{brandStyle.Render("OpenKyrozen"), "", titleStyle.Render("Updating OpenKyrozen"), amberStyle.Render(taskSpinner(m.motionFrame) + " " + firstNonEmpty(m.status, "Preparing the update…")), "", softStyle.Render("OpenKyrozen will restart when the update finishes.")} + return detailPage(lines, "Ctrl+C emergency quit", m.width, m.height) } diff --git a/tui/terminal_other.go b/tui/terminal_other.go new file mode 100644 index 00000000..8f15b846 --- /dev/null +++ b/tui/terminal_other.go @@ -0,0 +1,10 @@ +//go:build !unix + +package main + +import tea "charm.land/bubbletea/v2" + +func runTerminal(m tea.Model) (tea.Model, error) { + // Keep the native Windows console event reader and its mode restoration. + return tea.NewProgram(m).Run() +} diff --git a/tui/terminal_unix.go b/tui/terminal_unix.go new file mode 100644 index 00000000..3e9349e9 --- /dev/null +++ b/tui/terminal_unix.go @@ -0,0 +1,127 @@ +//go:build unix + +package main + +import ( + "bytes" + "os" + "unicode/utf8" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/term" + "golang.org/x/sys/unix" +) + +func runTerminal(m tea.Model) (tea.Model, error) { + input := os.Stdin + if !term.IsTerminal(input.Fd()) { + var err error + input, _, err = tea.OpenTTY() + if err != nil { + return nil, err + } + defer input.Close() + } + return tea.NewProgram(m, tea.WithInput(&terminalInput{File: input})).Run() +} + +// Keep the original TTY descriptor so Bubble Tea still owns raw mode, +// cancellation, suspend/resume and terminal restoration. +type terminalInput struct { + *os.File + pending []byte +} + +const ( + fragmentWaitMillis = 250 + maxControlBytes = 64 +) + +func (in *terminalInput) Read(p []byte) (int, error) { + n := copy(p, in.pending) + in.pending = in.pending[n:] + if n == len(p) { + return n, nil + } + // Reserve room for a sequence that starts at the last byte of a large + // paste or wheel burst. Only a partial sequence needs another read. + first := len(p) + if first-n > maxControlBytes { + first -= maxControlBytes + } + more, err := in.File.Read(p[n:first]) + if more == 0 && err != nil { + return 0, err + } + n += more + for err == nil && n > 0 && n < len(p) { + start := terminalFragmentStart(p[:n]) + if start < 0 { + break + } + fds := []unix.PollFd{{Fd: int32(in.Fd()), Events: unix.POLLIN}} + ready, pollErr := unix.Poll(fds, fragmentWaitMillis) + if pollErr == unix.EINTR { + continue + } + if ready == 0 && pollErr == nil { + fragment := p[start:n] + if bytes.HasPrefix(fragment, []byte("\x1b[<")) || bytes.HasPrefix(fragment, []byte("\x1b[M")) { + // A mouse introducer is unambiguous. Keep its partial payload + // across idle reads without blocking the cancellable TTY reader. + in.pending = append(in.pending[:0], p[start:n]...) + return start, nil + } + break + } + if pollErr != nil { + break + } + more, err = in.File.Read(p[n : n+1]) + n += more + } + // Deliver these bytes first. The next read will observe EOF/hangup. + if n > 0 { + return n, nil + } + return n, err +} + +func terminalFragmentStart(b []byte) int { + // A split code point can also occur inside a bracketed paste. + if b[len(b)-1] >= utf8.RuneSelf { + i := len(b) - 1 + for i > 0 && !utf8.RuneStart(b[i]) && len(b)-i < utf8.UTFMax { + i-- + } + if !utf8.FullRune(b[i:]) { + return i + } + } + i := bytes.LastIndexByte(b, '\x1b') + if i < 0 || len(b)-i >= maxControlBytes { + return -1 + } + seq := b[i:] + if len(seq) == 1 { + return i + } + if seq[1] != '[' { + return -1 + } + // X10 mouse reports end with three payload bytes after CSI M. + if len(seq) > 2 && seq[2] == 'M' { + if len(seq) < 6 { + return i + } + return -1 + } + // SGR mouse, cursor keys and paste delimiters all finish with a CSI + // final byte (0x40..0x7e). Stop at an invalid byte as well. + for _, c := range seq[2:] { + if c < 0x20 || c > 0x3f { + return -1 + } + } + return i +} diff --git a/tui/terminal_unix_test.go b/tui/terminal_unix_test.go new file mode 100644 index 00000000..1685df59 --- /dev/null +++ b/tui/terminal_unix_test.go @@ -0,0 +1,109 @@ +//go:build unix + +package main + +import ( + "bytes" + "io" + "os" + "strings" + "testing" + "time" +) + +func TestTerminalFragments(t *testing.T) { + for _, sequence := range []string{ + "\x1b[<65;60;20M", "\x1b[<0;7;4m", "\x1b[M\x60\x37\x42", + "\x1b[200~", "\x1b[201~", "\x1b[A", "你", "😀", + } { + for cut := 1; cut < len(sequence); cut++ { + if terminalFragmentStart([]byte("draft"+sequence[:cut])) != len("draft") { + t.Errorf("prematurely released %q", sequence[:cut]) + } + } + if terminalFragmentStart([]byte(sequence)) >= 0 { + t.Errorf("held complete input %q", sequence) + } + } + for _, text := range []string{"[<65;60;20M", "draft 你好", "\x1b[<64;6;4Mabc", "\x1b[\n"} { + if terminalFragmentStart([]byte(text)) >= 0 { + t.Errorf("held literal or malformed input %q", text) + } + } +} + +func TestTerminalReadCompletesMouseAtBurstBoundary(t *testing.T) { + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer r.Close() + defer w.Close() + const report = "\x1b[<65;60;20M" + const readSize = 512 + prefix := strings.Repeat("a", readSize-maxControlBytes-1) + go func() { + _, _ = io.WriteString(w, prefix+report[:1]) + time.Sleep(80 * time.Millisecond) + _, _ = io.WriteString(w, report[1:]+strings.Repeat(report, 64)) + _ = w.Close() + }() + in := terminalInput{File: r} + buf := make([]byte, readSize) + n, err := in.Read(buf) + if err != nil || string(buf[:n]) != prefix+report { + t.Fatalf("first read should end with a complete wheel report, suffix=%q, err=%v", buf[max(0, n-20):n], err) + } + rest, err := io.ReadAll(&in) + if err != nil || !bytes.Equal(rest, []byte(strings.Repeat(report, 64))) { + t.Fatalf("wheel burst changed: %d bytes, %v", len(rest), err) + } +} + +func TestTerminalReadStandaloneEscape(t *testing.T) { + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer r.Close() + defer w.Close() + _, _ = io.WriteString(w, "\x1b") + done := make(chan string, 1) + go func() { + var buf [128]byte + in := terminalInput{File: r} + n, _ := in.Read(buf[:]) + done <- string(buf[:n]) + }() + select { + case s := <-done: + if s != "\x1b" { + t.Fatalf("standalone Escape became %q", s) + } + case <-time.After(time.Second): + t.Fatal("standalone Escape remained buffered") + } +} + +func TestTerminalReadDelayedCoordinates(t *testing.T) { + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer r.Close() + defer w.Close() + // Once CSI < identifies a mouse report, a slow link is no longer + // ambiguous with the Escape key. + _, _ = io.WriteString(w, "draft\x1b[<65;") + in := terminalInput{File: r} + var buf [128]byte + n, err := in.Read(buf[:]) + if err != nil || string(buf[:n]) != "draft" { + t.Fatalf("partial mouse coordinates reached the decoder: %q, %v", buf[:n], err) + } + _, _ = io.WriteString(w, "60;20M!") + n, err = in.Read(buf[:]) + if err != nil || string(buf[:n]) != "\x1b[<65;60;20M!" { + t.Fatalf("resumed mouse report = %q, %v", buf[:n], err) + } +} diff --git a/tui/theme.go b/tui/theme.go index 628cacc5..af1808c9 100644 --- a/tui/theme.go +++ b/tui/theme.go @@ -30,20 +30,12 @@ var ( softStyle = lipgloss.NewStyle().Foreground(lipgloss.Color(offWhite)) mutedStyle = lipgloss.NewStyle().Foreground(lipgloss.Color(muted)) ruleStyle = lipgloss.NewStyle().Foreground(lipgloss.Color(border)) - quietStyle = lipgloss.NewStyle().Background(lipgloss.Color(deep)).Padding(0, 1) focusStyle = lipgloss.NewStyle().Background(lipgloss.Color(surface)).BorderBottom(true).BorderForeground(lipgloss.Color(cyan)).Padding(0, 1) - modalStyle = lipgloss.NewStyle().Background(lipgloss.Color(surface)).Border(lipgloss.RoundedBorder()).BorderForeground(lipgloss.Color(border)).Padding(1, 2) - contextStyle = lipgloss.NewStyle().Background(lipgloss.Color(deep)) - badgeStyle = lipgloss.NewStyle().Foreground(lipgloss.Color(cyan)).Background(lipgloss.Color(surfaceHi)).Bold(true).Padding(0, 1) - sectionStyle = lipgloss.NewStyle().Foreground(lipgloss.Color(muted)).Bold(true) - assistantStyle = lipgloss.NewStyle().BorderLeft(true).BorderForeground(lipgloss.Color(border)).PaddingLeft(1) - userStyle = lipgloss.NewStyle().Background(lipgloss.Color(surface)).BorderLeft(true).BorderForeground(lipgloss.Color(cyan)).Padding(0, 1) - thinkingStyle = lipgloss.NewStyle().BorderLeft(true).BorderForeground(lipgloss.Color(amber)).PaddingLeft(1) - receiptBoxStyle = lipgloss.NewStyle().Background(lipgloss.Color(deep)).Padding(0, 1) - paletteStyle = lipgloss.NewStyle().Background(lipgloss.Color(surface)).Border(lipgloss.RoundedBorder()).BorderForeground(lipgloss.Color(border)).Padding(0, 1) - composerStyle = lipgloss.NewStyle().Background(lipgloss.Color(deep)).Border(lipgloss.RoundedBorder()).BorderForeground(lipgloss.Color(border)).Padding(0, 1) - activityStyle = lipgloss.NewStyle().Background(lipgloss.Color(deep)).BorderLeft(true).BorderForeground(lipgloss.Color(border)).PaddingLeft(1) + contextStyle = lipgloss.NewStyle().Background(lipgloss.Color(deep)) + sectionStyle = lipgloss.NewStyle().Foreground(lipgloss.Color(muted)).Bold(true) + paletteStyle = lipgloss.NewStyle().Background(lipgloss.Color(surface)).Border(lipgloss.RoundedBorder()).BorderForeground(lipgloss.Color(border)).Padding(0, 1) + composerStyle = lipgloss.NewStyle().Background(lipgloss.Color(deep)).Padding(0, 1) amberStyle = lipgloss.NewStyle().Foreground(lipgloss.Color(amber)) greenStyle = lipgloss.NewStyle().Foreground(lipgloss.Color(green)) @@ -55,6 +47,10 @@ func colorPtr(value string) *string { return &value } func kyrozenMarkdownStyles() ansi.StyleConfig { style := glamourstyles.DarkStyleConfig style.Document.Color = colorPtr(white) + margin := uint(0) + style.Document.Margin = &margin + style.Document.BlockPrefix = "" + style.Document.BlockSuffix = "" style.Paragraph.Color = colorPtr(white) style.Text.Color = colorPtr(white) style.Heading.Color = colorPtr(cyan) @@ -121,7 +117,7 @@ func fillBackground(content string, width, height int) string { } style := lipgloss.NewStyle().Background(lipgloss.Color(ink)).Foreground(lipgloss.Color(white)).Width(width).MaxWidth(width) for index, line := range lines { - lines[index] = style.Render(line) + lines[index] = style.Render(clipRow(line, width)) } return strings.Join(lines, "\n") } diff --git a/tui/transcript.go b/tui/transcript.go new file mode 100644 index 00000000..6e5d38bc --- /dev/null +++ b/tui/transcript.go @@ -0,0 +1,260 @@ +package main + +import ( + "path/filepath" + "sort" + "strings" + "unicode" + + "charm.land/lipgloss/v2" + "github.com/charmbracelet/x/ansi" +) + +// blocks are measured once per width. starts indexes each message's first +// physical row, so moving through a large conversation only visits the window. +type transcriptViewport struct { + blocks [][]string + starts []int + width, height, total, offset int + dirtyFrom int + dirtyBlocks map[int]bool + showDetails bool +} + +func (v *transcriptViewport) reset() { *v = transcriptViewport{} } +func (v *transcriptViewport) invalidate(index int) { + if len(v.dirtyBlocks) == 0 || index < v.dirtyFrom { + v.dirtyFrom = index + } + if v.dirtyBlocks == nil { + v.dirtyBlocks = make(map[int]bool) + } + v.dirtyBlocks[index] = true +} +func (v transcriptViewport) YOffset() int { return v.offset } +func (v transcriptViewport) maxOffset() int { return maxInt(0, v.total-v.height) } +func (v transcriptViewport) AtBottom() bool { return v.offset >= v.maxOffset() } +func (v transcriptViewport) PastBottom() bool { return v.offset > v.maxOffset() } +func (v *transcriptViewport) SetYOffset(off int) { v.offset = maxInt(0, minInt(v.maxOffset(), off)) } +func (v *transcriptViewport) GotoBottom() { v.offset = v.maxOffset() } +func (v *transcriptViewport) ScrollUp(n int) { v.SetYOffset(v.offset - n) } +func (v *transcriptViewport) ScrollDown(n int) { v.SetYOffset(v.offset + n) } +func (v *transcriptViewport) PageUp() { v.ScrollUp(v.height) } +func (v *transcriptViewport) PageDown() { v.ScrollDown(v.height) } +func (v transcriptViewport) messageAt(row int) int { + return sort.Search(len(v.starts), func(i int) bool { return v.starts[i] > row }) - 1 +} +func (v transcriptViewport) View() string { + i := v.messageAt(v.offset) + if i < 0 { + return "" + } + rows := make([]string, 0, v.height) + skip := v.offset - v.starts[i] + for ; i < len(v.blocks) && len(rows) < v.height; i++ { + block := v.blocks[i][skip:] + rows = append(rows, block[:minInt(len(block), v.height-len(rows))]...) + skip = 0 + } + return strings.Join(rows, "\n") +} + +// A logical offset survives wrapping around a different terminal width. +// Ignore whitespace introduced by indentation, padding and line wrapping. +func glyphCount(row string) int { + n := 0 + for _, r := range ansi.Strip(row) { + if !unicode.IsSpace(r) { + n++ + } + } + return n +} + +func (m *model) syncViewport() { + if m.width < 1 || m.height < 1 { + return + } + h := m.composerHeight() + if m.input.Height() != h { + m.input.SetHeight(h) + } + v := &m.view + width := m.contentWidth() + count := len(v.blocks) + start := count + rebuild := width != v.width || v.showDetails != m.showToolDetails || len(m.messages) < count + if rebuild { + start = 0 + } + if len(v.dirtyBlocks) > 0 { + start = minInt(start, v.dirtyFrom) + } + anchor := v.messageAt(v.offset) + anchorRow := 0 + rewrap := width != v.width && anchor >= 0 && !m.followTail + if anchor >= 0 { + anchorRow = v.offset - v.starts[anchor] + } + glyph := 0 + if rewrap { + for _, row := range v.blocks[anchor][:anchorRow] { + glyph += glyphCount(row) + } + } + v.height = m.historyHeight() + if start < len(m.messages) || start < len(v.blocks) { + // Rebuild from the earliest changed message, preserving the measured prefix. + total := 0 + if start < len(v.starts) { + total = v.starts[start] + } else { + total = v.total + } + if len(v.blocks) > len(m.messages) { + v.blocks = v.blocks[:len(m.messages)] + v.starts = v.starts[:len(m.messages)] + } + for i := start; i < len(m.messages); i++ { + if i >= count { + v.blocks = append(v.blocks, m.messageRows(i, width)) + v.starts = append(v.starts, total) + } else { + if rebuild || v.dirtyBlocks[i] { + v.blocks[i] = m.messageRows(i, width) + } + v.starts[i] = total + } + total += len(v.blocks[i]) + } + v.total = total + } + clear(v.dirtyBlocks) + v.width = width + v.showDetails = m.showToolDetails + if m.followTail { + v.GotoBottom() + return + } + if anchor >= 0 && anchor < len(v.starts) { + block := v.blocks[anchor] + if rewrap { + anchorRow = 0 + for anchorRow < len(block)-1 { + count := glyphCount(block[anchorRow]) + if glyph < count { + break + } + glyph -= count + anchorRow++ + } + } + v.SetYOffset(v.starts[anchor] + minInt(anchorRow, len(block)-1)) + } else { + v.SetYOffset(v.offset) + } +} + +func (m *model) messageRows(index, width int) []string { + msg := &m.messages[index] + var body string + inner := maxInt(1, width-2) + switch msg.role { + case "user": + body = brandStyle.Render("›") + " " + titleStyle.Render(msg.text) + case "receipt": + action := firstNonEmpty(msg.text, msg.toolAction, "Tool") + status := strings.ToUpper(firstNonEmpty(msg.status, "success")) + expanded := m.showToolDetails != msg.toggleDetails + marker := "▸ Details" + if expanded { + marker = "▾ Details" + } + summary := compactText(action, maxInt(1, width-lipgloss.Width(status)-16)) + symbol := status + if status == "SUCCESS" { + symbol = "✓" + } + body = " " + receiptStyle(msg.status).Render(symbol) + " " + softStyle.Render(summary) + " " + mutedStyle.Render(marker) + body = clipRow(body, width) + if expanded && msg.toolDetail != "" { + body += "\n" + mutedStyle.Render(msg.toolDetail) + } + case "thinking": + body = amberStyle.Render("Thinking") + " " + mutedStyle.Render(msg.text) + default: + if msg.streaming { + body = softStyle.Render(msg.text) + brandStyle.Render("▌") + } else if msg.text != "" { + if msg.renderedWidth != inner { + msg.rendered = renderMarkdown(msg.text, inner) + msg.renderedWidth = inner + } + body = msg.rendered + } + } + rows := strings.Split(ansi.Hardwrap(ansi.Wordwrap(body, width, ""), width, true), "\n") + // Use a single line of breathing room before each human turn. + if index > 0 && msg.role == "user" { + rows = append([]string{""}, rows...) + } + return rows +} + +// Expand the newest receipt inside the reader's window. +func (m *model) toggleReceipt() { + first := maxInt(0, m.view.messageAt(m.view.offset)) + last := minInt(len(m.messages)-1, m.view.messageAt(m.view.offset+m.view.height-1)) + for i := last; i >= first; i-- { + if m.messages[i].role == "receipt" { + m.messages[i].toggleDetails = !m.messages[i].toggleDetails + m.view.invalidate(i) + return + } + } +} + +func (m *model) toggleReceiptAt(y int) bool { + if y < 1 || y > m.view.height { + return false + } + row := m.view.offset + y - 1 + if row >= m.view.total { + return false + } + index := m.view.messageAt(row) + if index < 0 || index >= len(m.messages) || m.messages[index].role != "receipt" || m.view.starts[index] != row { + return false + } + m.messages[index].toggleDetails = !m.messages[index].toggleDetails + m.view.invalidate(index) + return true +} + +func receiptSummary(receipt map[string]any) string { + action := firstNonEmpty(stringValue(receipt, "action"), "Tool") + if receiptStatus(receipt) != "success" { + return action + } + var verb string + switch action { + case "write_file": + verb = "Wrote" + case "read_file": + verb = "Read" + case "edit_file": + verb = "Edited" + case "list_dir": + verb = "Listed" + case "run_cmd", "run_command", "execute_terminal_command": + return "Ran command" + default: + return action + } + args, _ := receipt["args"].(map[string]any) + path := stringValue(args, "path") + if path == "" { + return action + } + return verb + " " + filepath.Base(path) +} diff --git a/tui/transcript_test.go b/tui/transcript_test.go new file mode 100644 index 00000000..a66bc507 --- /dev/null +++ b/tui/transcript_test.go @@ -0,0 +1,115 @@ +package main + +import ( + "fmt" + "sort" + "strings" + "testing" + "time" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" +) + +func TestTranscriptScrollFrameTime(t *testing.T) { + m := initialModel("", true) + m.width, m.height = 120, 30 + for i := 0; i < 1000; i++ { + m.messages = append(m.messages, chatMessage{role: "user", text: fmt.Sprintf("Review export %d", i)}, + chatMessage{role: "assistant", text: "I reviewed **export.go** and the integration test. Both use the same schema."}) + } + m.resize() + var frames []time.Duration + for i := 0; i < 120; i++ { + started := time.Now() + updated, _ := m.Update(tea.MouseWheelMsg{Y: 2, Button: tea.MouseWheelUp}) + m = updated.(model) + _ = m.View().Content + frames = append(frames, time.Since(started)) + } + sort.Slice(frames, func(i, j int) bool { return frames[i] < frames[j] }) + p95 := frames[len(frames)*95/100] + t.Logf("120×30, 1000 user/assistant turns, 120 wheel updates + frame renders, p95 %v", p95) + if p95 > 16*time.Millisecond { + t.Fatalf("scroll frame p95 exceeds 16ms: %v", p95) + } +} +func TestResizeKeepsReadPositionInsideMessage(t *testing.T) { + m := initialModel("", true) + m.width, m.height = 64, 14 + var words []string + for i := 0; i < 400; i++ { + words = append(words, fmt.Sprintf("word%03d", i)) + } + m.messages = []chatMessage{{role: "user", text: "hello"}, {role: "user", text: strings.Join(words, " ")}} + m.resize() + m.followTail = false + m.view.SetYOffset(17) + before := strings.Fields(ansi.Strip(strings.Split(m.view.View(), "\n")[0]))[0] + m.width = 97 + m.resize() + if top := ansi.Strip(strings.Split(m.view.View(), "\n")[0]); !strings.Contains(top, before) { + t.Fatalf("anchor %q missing from first row %q", before, top) + } + if !strings.Contains(ansi.Strip(m.View().Content), "Latest") { + t.Fatal("missing jump to latest") + } +} +func TestComposerGrowsAndReturnsSpace(t *testing.T) { + m := initialModel("", true) + m.width, m.height = 80, 24 + m.resize() + base := m.historyHeight() + for n := 2; n <= 8; n++ { + m.input.SetValue(strings.Repeat("abc\n", n-1) + "last") + m.syncViewport() + if got, want := m.input.Height(), minInt(n, 5); got != want { + t.Fatalf("%d lines: got %d rows, want %d", n, got, want) + } + } + m.input.Reset() + m.syncViewport() + if m.input.Height() != 1 || m.historyHeight() != base { + t.Fatal("clearing draft did not restore viewport space") + } +} + +func TestShortDecisionSheetsKeepSelectionAndActions(t *testing.T) { + for _, size := range [][2]int{{32, 8}, {40, 12}, {60, 16}, {80, 24}} { + m := initialModel("", true) + m.width, m.height = size[0], size[1] + m.onboardingKind = "new" + m.pendingQuestion = &questionRequest{questions: []interactionQuestion{{header: "Scope", prompt: "What should I change?", choices: []interactionChoice{{label: "One file"}, {label: "Both files"}}}}} + m.choiceIdx = 3 + m.permissionIdx = 2 + m.pendingPlan = &planProposal{title: "Export", version: 1, summary: strings.Repeat("Summary ", 15), steps: []planStep{{title: "One"}}} + m.pendingDeleteKind = "delete_chat" + m.pendingDeleteTitle = "Session 7" + m.apiInput.SetValue("private-test-key") + m.approvalTool = "write_file" + m.approvalArgs = strings.Repeat("long args ", 120) + m.modelPromptMessage = strings.Repeat("Provider feedback ", 30) + m.resize() + for _, spec := range []struct { + screen screen + required []string + }{ + {screenPermissions, []string{"Permissions", "Full access without Jev", "Enter", "Esc"}}, + {screenQuestion, []string{"Question", "Skip", "Enter", "Esc"}}, + {screenAPIKey, []string{"API key", "•", "Enter", "Esc"}}, + {screenModel, []string{"Main model", "Enter", "Esc"}}, + {screenApproval, []string{"Approval required", "write_file", "approve", "deny"}}, + {screenError, []string{"Error", "Esc back"}}, + {screenPlan, []string{"Export", "accept", "revise", "cancel"}}, + {screenDeleteConfirm, []string{"Session 7", "delete", "cancel"}}, + } { + m.screen = spec.screen + frame := ansi.Strip(m.View().Content) + for _, want := range spec.required { + if !strings.Contains(frame, want) { + t.Fatalf("%v %s clipped %q:\n%s", size, m.screen, want, frame) + } + } + } + } +} diff --git a/tui/update.go b/tui/update.go index 52427593..e04179ab 100644 --- a/tui/update.go +++ b/tui/update.go @@ -3,7 +3,6 @@ package main import ( tea "charm.land/bubbletea/v2" "strings" - "time" ) func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { @@ -46,49 +45,67 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { // Capture wheel input while the TUI is active. Without mouse reporting, // Warp and native terminals scroll their own screen instead of this // viewport, which makes the full-screen app appear to disappear. - if m.screen == screenGraph { + if msg.Button != tea.MouseWheelUp && msg.Button != tea.MouseWheelDown { + break + } + step := 1 + if msg.Button == tea.MouseWheelUp { + step = -1 + } + if m.screen == screenUtility && m.editing { + break + } + if m.screen == screenUtility { + m.selected = minInt(maxInt(0, len(m.utilityRows())-1), maxInt(0, m.selected+step*3)) + } else if m.screen == screenChat && m.navigationFocused && msg.Y >= m.sheetStartRow() { + m.navigationIndex = minInt(maxInt(0, len(m.navigationTargets())-1), maxInt(0, m.navigationIndex+step)) + } else if m.screen == screenChat && len(m.palette) > 0 && m.overPalette(msg.Y) { + m.paletteIndex = minInt(len(m.palette)-1, maxInt(0, m.paletteIndex+step)) + } else if m.screen == screenProvider || m.screen == screenSettings || m.screen == screenPermissions || m.screen == screenMode || m.screen == screenQuestion || m.screen == screenSelfLearning { + key := tea.KeyDown + if step < 0 { + key = tea.KeyUp + } + m.handleKey(tea.KeyPressMsg{Code: key}) + } else if m.screen == screenAgents { + m.agentScroll = maxInt(0, m.agentScroll+3*step) + } else if m.screen == screenGraph { if msg.Button == tea.MouseWheelUp { m.graphZoom = minInt(5, m.graphZoom+1) } else { m.graphZoom = maxInt(-1, m.graphZoom-1) } - } else if m.screen == screenPlan { + } else if m.screen == screenPlan && msg.Y >= m.sheetStartRow() { if msg.Button == tea.MouseWheelUp { m.scrollPlan(-3) } else { m.scrollPlan(3) } - } else if m.screen == screenApproval { + } else if m.screen == screenApproval && msg.Y >= m.sheetStartRow() { if msg.Button == tea.MouseWheelUp { m.approvalView.ScrollUp(mouseWheelScrollStep) } else { m.approvalView.ScrollDown(mouseWheelScrollStep) } - } else if m.screen == screenChat { + } else if m.screen == screenChat || m.screen == screenApproval || m.screen == screenPlan { switch msg.Button { case tea.MouseWheelUp: m.view.ScrollUp(mouseWheelScrollStep) case tea.MouseWheelDown: m.view.ScrollDown(mouseWheelScrollStep) default: - m.view, _ = m.view.Update(msg) } m.followTail = m.view.AtBottom() } case tea.MouseClickMsg: - if m.screen == screenChat && !m.busy && msg.Button == tea.MouseLeft { - if index := m.modeTabAt(msg.X, msg.Y); index >= 0 { - m.send("command", map[string]any{"name": "mode", "args": []string{"auto", "ask", "plan", "agent"}[index]}) - } else if index := m.permissionTabAt(msg.X, msg.Y); index >= 0 { - m.send("command", map[string]any{"name": "permissions", "args": []string{"ask", "full_jev", "full"}[index]}) - } + if m.screen == screenChat && msg.Button == tea.MouseLeft && m.overLatest(msg.X, msg.Y) { + m.followTail = true + m.view.GotoBottom() + } else if m.screen == screenChat && !m.navigationOpen && msg.Button == tea.MouseLeft { + m.toggleReceiptAt(msg.Y) } else if m.screen == screenGraph && msg.Button == tea.MouseLeft { nodes := m.visibleGraphNodes() - miniHeight := minInt(14, maxInt(8, maxInt(1, m.height-2)/3)) - firstNodeRow := miniHeight + 5 - if m.graphSearching { - firstNodeRow += 2 - } + firstNodeRow := m.graphNodeStartRow() index := msg.Y - firstNodeRow if index >= 0 && index < len(nodes) { m.graphSelected = index @@ -102,20 +119,18 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.send("command", map[string]any{"name": "/github status"}) case backendExitMsg: if m.screen != screenError { - m.status = "Backend stopped" + m.setError("Backend stopped. Restart Kyrozen to reconnect.") } + if m.activeTurn != "" { + m.finishInterruptedReply("Backend disconnected.") + } + m.conversation().paused = true + m.backendReady = false + m.activeTurn = "" + m.navigationRequest = "" case tickMsg: - now := time.Time(msg) + m.motionScheduled = false m.motionFrame++ - if m.screen == screenSplash { - m.splashFrame++ - if m.reducedMotion || m.canLeaveSplash(now) { - m.screen = screenChat - } - } - if m.busy { - m.cursorVisible = !m.cursorVisible - } if m.taskFlashTick > 0 { m.taskFlashTick-- if m.taskFlashTick == 0 { @@ -151,7 +166,21 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } case screenProject: m.projectInput, cmd = m.projectInput.Update(msg) + case screenUtility: + if m.editing { + m.editor, cmd = m.editor.Update(msg) + } else if m.utility == "commands" { + m.filter += msg.Content + m.selected = 0 + } case screenChat: + if m.navigationFocused { + if m.navigationSearching { + m.navigationFilter += msg.Content + m.navigationIndex = 0 + } + break + } m.input, cmd = m.input.Update(msg) m.refreshPalette() } @@ -159,26 +188,18 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { cmds = append(cmds, cmd) } } + m.dispatchNext() m.syncViewport() return m, tea.Batch(cmds...) } -func (m model) canLeaveSplash(now time.Time) bool { - if !m.backendReady { - return false - } - started := m.splashStarted - ready := m.readyAt - return (started.IsZero() || now.Sub(started) >= splashMinimumDuration) && - (ready.IsZero() || now.Sub(ready) >= readyHoldDuration) -} - func (m model) animating() bool { - return !m.reducedMotion && (m.screen == screenSplash || (m.screen == screenChat && len(m.messages) == 0) || m.updateInProgress || m.busy || m.hasRunningTask() || m.taskFlashTick > 0 || m.transitionTick > 0) + return !m.reducedMotion && (m.updateInProgress || m.busy || m.hasRunningTask() || m.taskFlashTick > 0 || m.transitionTick > 0) } func (m *model) maybeMotion(cmds *[]tea.Cmd) { - if m.animating() { + if m.animating() && !m.motionScheduled { + m.motionScheduled = true *cmds = append(*cmds, motionTick()) } } diff --git a/tui/view_helpers.go b/tui/view_helpers.go index 91d12027..422fd74f 100644 --- a/tui/view_helpers.go +++ b/tui/view_helpers.go @@ -2,63 +2,12 @@ package main import ( "charm.land/lipgloss/v2" + "github.com/charmbracelet/x/ansi" "strings" ) func rule(width int) string { return ruleStyle.Render(strings.Repeat("─", maxInt(1, width))) } -func bannerRows(width int) []string { - if width < 8 { - return []string{centerText("OPENKYROZEN", width)} - } - inner := width - 2 - line := strings.Repeat("─", inner) - return []string{ - "╭" + line + "╮", - "│" + centerText("◈ OPENKYROZEN ◈", inner) + "│", - "│" + centerText("COMPUTER-NATIVE / SELF-LEARNING", inner) + "│", - "│" + centerText("A LOCAL WORKBENCH FOR YOUR IDEAS", inner) + "│", - "╰" + line + "╯", - } -} - -func centerText(value string, width int) string { - if lipgloss.Width(value) > width { - value = string([]rune(value)[:maxInt(0, width)]) - } - padding := maxInt(0, width-lipgloss.Width(value)) - return strings.Repeat(" ", padding/2) + value + strings.Repeat(" ", padding-padding/2) -} - -func startupMilestones(m model) []string { - phase := m.splashFrame / 3 - if m.reducedMotion { - phase = 5 - } - return []string{ - startupMilestone("workspace", phase >= 2, phase == 1), - startupMilestone("provider", m.backendReady, !m.backendReady && phase >= 2), - startupMilestone("memory", m.backendReady && phase >= 5, m.backendReady && phase < 5), - } -} - -func startupMilestone(name string, done, active bool) string { - icon, style := "·", mutedStyle - if done { - icon, style = "✓", greenStyle - } else if active { - icon, style = taskSpinner(1), amberStyle - } - return style.Render(icon) + " " + softStyle.Render(name) -} - -func splashStatus(m model) string { - if m.backendReady { - return greenStyle.Render("READY") + " " + softStyle.Render("Opening your workbench…") - } - return amberStyle.Render(taskSpinner(m.splashFrame)) + " " + softStyle.Render(firstNonEmpty(m.status, "Starting the workspace…")) -} - func taskSpinner(frame int) string { return []string{"◐", "◓", "◑", "◒"}[maxInt(0, frame)%4] } @@ -90,13 +39,5 @@ func receiptStyle(status string) lipgloss.Style { } func compactText(value string, width int) string { - value = strings.TrimSpace(value) - if width < 1 || lipgloss.Width(value) <= width { - return value - } - runes := []rune(value) - if len(runes) <= width { - return value - } - return string(runes[:maxInt(1, width-1)]) + "…" + return ansi.Truncate(strings.TrimSpace(strings.ReplaceAll(value, "\n", " ")), maxInt(0, width), "…") } diff --git a/tui/workspace_ui.go b/tui/workspace_ui.go new file mode 100644 index 00000000..62e57542 --- /dev/null +++ b/tui/workspace_ui.go @@ -0,0 +1,423 @@ +package main + +import ( + "fmt" + "strings" + + "charm.land/bubbles/v2/textarea" + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" + "github.com/charmbracelet/x/ansi" +) + +const screenUtility screen = "utility" + +type conversationKey struct { + scope, session string +} + +type conversationInput struct { + draft string + queue []string + paused bool +} + +type workspaceUI struct { + pickerFilter string + pickerSearching bool + modelChoices []string + recoveryScreen screen + + conversations map[conversationKey]*conversationInput + navigationRequest string + activeTurn string + utility string + filter string + selected int + instructionText string + instructionRequest string + editing bool + editor textarea.Model + motionScheduled bool +} + +func (m *model) conversation() *conversationInput { + if m.conversations == nil { + m.conversations = make(map[conversationKey]*conversationInput) + } + id := conversationKey{m.activeScopeID, m.activeSessionID} + if m.conversations[id] == nil { + m.conversations[id] = &conversationInput{} + } + return m.conversations[id] +} + +func (m *model) selectConversation(scope, id string) { + if id == "" || (scope == m.activeScopeID && id == m.activeSessionID) { + return + } + if m.activeSessionID == "" || (m.activeScopeID == "" && id == m.activeSessionID) { + state := m.conversation() + delete(m.conversations, conversationKey{m.activeScopeID, m.activeSessionID}) + m.activeScopeID, m.activeSessionID = scope, id + m.conversations[conversationKey{scope, id}] = state + state.draft = m.input.Value() + return + } + m.conversation().draft = m.input.Value() + m.activeScopeID, m.activeSessionID = scope, id + m.input.SetValue(m.conversation().draft) + m.refreshPalette() + m.followTail = true +} + +func (m model) queueHint() string { + state := m.conversations[conversationKey{m.activeScopeID, m.activeSessionID}] + if state == nil || len(state.queue) == 0 { + return "" + } + label := "queued" + if state.paused { + label = "paused" + } + return fmt.Sprintf("%d %s · /queue", len(state.queue), label) +} + +func (m *model) dispatchNext() { + state := m.conversation() + if m.navigationRequest != "" || state.paused || len(state.queue) == 0 || m.busy || m.activeTurn != "" || m.screen != screenChat || m.navigationFocused || m.pendingQuestion != nil || m.pendingPlan != nil || !m.backendReady { + return + } + text := state.queue[0] + state.queue = state.queue[1:] + m.startTurn(text) +} + +func (m *model) startTurn(text string) { + m.activeTurn = fmt.Sprintf("tui-%d", m.requestCount+1) + m.send("submit", map[string]any{"text": text}) + if m.screen == screenError { + m.activeTurn = "" + state := m.conversation() + state.queue = append([]string{text}, state.queue...) + state.paused = true + return + } + m.messages = append(m.messages, chatMessage{role: "user", text: text}, chatMessage{role: "assistant", streaming: true}) + m.busy, m.followTail = true, true + m.status = "Working…" + m.thinkingText = "" +} + +func (m *model) openUtility(name string) { + m.utility, m.screen, m.filter, m.selected, m.editing = name, screenUtility, "", 0, false + if name == "instructions" { + m.instructionText = "" + m.instructionRequest = fmt.Sprintf("tui-%d", m.requestCount+1) + m.send("command", map[string]any{"name": "instructions"}) + } +} + +func (m model) actionMatches() []command { + q := strings.ToLower(strings.TrimSpace(m.filter)) + items := []command{} + var descriptions []command + for _, c := range commands { + if strings.HasPrefix(c.name, q) { + items = append(items, c) + continue + } + if strings.Contains(strings.ToLower(c.name+" "+strings.Join(c.aliases, " ")+" "+c.description), q) { + descriptions = append(descriptions, c) + } + } + return append(items, descriptions...) +} + +func (m *model) runAction(name string) { + m.pickerSearching = false + m.pickerFilter = "" + switch name { + case "help", "instructions", "queue", "tasks", "usage", "commands": + m.openUtility(name) + case "settings": + m.screen = screenSettings + m.settingsIdx = 0 + case "permissions", "permission": + if m.activeTurn != "" || m.busy { + m.status = "Change permissions after this turn finishes." + return + } + m.openPermissions(m.permissionMode) + case "latest": + m.followTail = true + m.view.GotoBottom() + default: + words := strings.Fields(strings.ToLower(name)) + if len(words) > 0 { + switch words[0] { + case "cancel": + m.conversation().paused = true + case "update": + if m.activeTurn != "" || m.busy { + m.status = "Wait for the current turn before updating." + return + } + } + } + m.send("command", map[string]any{"name": "/" + name}) + } +} + +func (m *model) openPermissions(mode string) { + m.screen = screenPermissions + m.permissionIdx = 0 + for i, s := range []string{"ask", "full_jev", "full"} { + if s == mode { + m.permissionIdx = i + } + } +} + +// Keep input routing and the shortcut reference in the same table. +var chatActions = map[string]string{"ctrl+p": "commands", "f1": "help", "ctrl+r": "details"} + +func (m model) utilityRows() []string { + rows := []string{} + switch m.utility { + case "commands", "help": + if m.utility == "help" { + for _, key := range []string{"ctrl+p", "ctrl+r", "f1"} { + rows = append(rows, key+" "+chatActions[key]) + } + rows = append(rows, "Ctrl+B Projects and chats", "Enter Send or queue", "Ctrl+J New line", "PgUp / PgDn Read conversation", "") + } + for _, c := range m.actionMatches() { + rows = append(rows, "/"+c.name+" "+c.description) + } + case "instructions": + content := m.instructionText + if content == "" { + content = "Reading workspace instructions…" + } + return strings.Split(lipgloss.Wrap(ansi.Strip(content), maxInt(1, m.width-6), ""), "\n") + case "tasks": + return m.taskDetailLines() + case "usage": + return []string{m.usageSummary(), fmt.Sprintf("%d provider attempts · %s", m.usageAttempts, m.usageScope)} + case "queue": + if state := m.conversations[conversationKey{m.activeScopeID, m.activeSessionID}]; state != nil { + for i, v := range state.queue { + rows = append(rows, fmt.Sprintf("%d %s", i+1, strings.Join(strings.Fields(v), " "))) + } + } + } + return rows +} + +func (m model) utilityView() string { + title := map[string]string{"commands": "Commands", "help": "Keyboard and commands", "instructions": "Workspace instructions", "tasks": "Tasks", "queue": "Queued follow-ups", "usage": "Session usage", "answer": "Your answer", "revision": "Revise the plan"}[m.utility] + width := maxInt(1, m.width-4) + lines := []string{titleStyle.Render(title), ""} + hint := "PgUp/PgDn scroll · Esc back" + if m.editing { + lines = append(lines, m.editor.View()) + hint = "Enter save · Ctrl+J new line · Esc discard" + } else { + rows := m.utilityRows() + picker := m.utility == "commands" || m.utility == "queue" + if m.utility == "commands" { + lines = append(lines, "Search › "+m.filter) + hint = "Type to filter · Enter choose · Esc back" + } + if m.utility == "queue" { + hint = "Enter edit · D withdraw · R resume · Esc back" + } + height := maxInt(1, m.height-len(lines)-2) + start := minInt(m.selected, maxInt(0, len(rows)-height)) + if picker { + start = maxInt(0, m.selected-height+1) + } + if len(rows) == 0 { + lines = append(lines, mutedStyle.Render("No items")) + } + for i := start; i < minInt(len(rows), start+height); i++ { + s := compactText(rows[i], width-2) + if m.utility == "instructions" { + s = rows[i] + } + if i == m.selected && picker { + s = brandStyle.Render("› " + s) + } else { + s = " " + s + } + lines = append(lines, s) + } + } + lines = append(lines, "", mutedStyle.Render(compactText(hint, width))) + return limitRows(strings.Join(lines, "\n"), m.height) +} + +func (m *model) utilityKey(msg tea.KeyPressMsg) tea.Cmd { + key := msg.String() + state := m.conversation() + if m.editing { + switch key { + case "esc": + m.editing = false + if m.utility == "answer" { + m.screen = screenQuestion + } else if m.utility == "revision" { + m.screen = screenPlan + } + case "ctrl+j": + m.editor.InsertString("\n") + case "enter": + if s := strings.TrimSpace(m.editor.Value()); s != "" && m.utility == "answer" { + m.editing = false + return m.answerQuestion(s) + } + if s := strings.TrimSpace(m.editor.Value()); s != "" && m.utility == "revision" { + m.editing = false + m.screen = screenChat + m.startTurn(s) + return nil + } + if s := strings.TrimSpace(m.editor.Value()); s != "" && m.selected < len(state.queue) { + state.queue[m.selected] = s + m.editing = false + } + default: + var cmd tea.Cmd + m.editor, cmd = m.editor.Update(msg) + return cmd + } + return nil + } + rows := m.utilityRows() + last := maxInt(0, len(rows)-1) + switch key { + case "esc": + m.screen = screenChat + return m.input.Focus() + case "up": + m.selected = maxInt(0, m.selected-1) + case "down": + m.selected = minInt(last, m.selected+1) + case "pgup": + m.selected = maxInt(0, m.selected-maxInt(1, m.height-5)) + case "pgdown": + m.selected = minInt(last, m.selected+maxInt(1, m.height-5)) + case "home": + m.selected = 0 + case "end": + m.selected = last + case "enter": + if m.utility == "commands" && len(rows) > 0 { + name := m.actionMatches()[m.selected].name + m.screen = screenChat + if name == "quit" { + return tea.Quit + } + m.runAction(name) + } else if m.utility == "queue" && m.selected < len(state.queue) { + return m.startEditor(state.queue[m.selected]) + } + default: + switch m.utility { + case "commands": + m.filter = editFilter(m.filter, msg) + m.selected = 0 + case "queue": + if key == "d" && m.selected < len(state.queue) { + state.queue = append(state.queue[:m.selected], state.queue[m.selected+1:]...) + m.selected = minInt(m.selected, maxInt(0, len(state.queue)-1)) + } + if key == "r" { + state.paused = false + m.screen = screenChat + } + } + } + return nil +} + +func editFilter(current string, msg tea.KeyPressMsg) string { + if msg.String() == "backspace" { + r := []rune(current) + if len(r) > 0 { + return string(r[:len(r)-1]) + } + return "" + } + return current + msg.Text +} + +var settingLabels = []string{"Show tool details", "Interaction mode", "System One backend", "Decision Assist", "Kev private context", "Main model"} + +func filterIndices(items []string, query string) []int { + var result []int + for i, item := range items { + if strings.Contains(strings.ToLower(item), strings.ToLower(query)) { + result = append(result, i) + } + } + return result +} +func (m model) providerIndices() []int { return filterIndices(m.providerList, m.pickerFilter) } +func (m model) settingIndices() []int { return filterIndices(settingLabels, m.pickerFilter) } +func (m *model) filterPicker(msg tea.KeyPressMsg) bool { + if m.screen != screenSettings && m.screen != screenProvider { + return false + } + key := msg.String() + if key == "ctrl+f" { + m.pickerSearching = true + return true + } + if !m.pickerSearching { + return false + } + pick := &m.providerIdx + indices := m.providerIndices + if m.screen == screenSettings { + pick = &m.settingsIdx + indices = m.settingIndices + } + switch key { + case "esc": + m.pickerFilter = "" + m.pickerSearching = false + case "up", "down": + items := indices() + for i, n := range items { + if n == *pick { + direction := 1 + if key == "up" { + direction = -1 + } + *pick = items[(i+direction+len(items))%len(items)] + break + } + } + case "enter": + return len(indices()) == 0 + default: + m.pickerFilter = editFilter(m.pickerFilter, msg) + if items := indices(); len(items) > 0 { + *pick = items[0] + } + } + return true +} + +func (m *model) startEditor(value string) tea.Cmd { + m.editor = textarea.New() + m.editor.ShowLineNumbers = false + m.editor.CharLimit = 12000 + m.editor.SetWidth(maxInt(1, m.width-6)) + m.editor.SetHeight(minInt(5, maxInt(1, m.height-5))) + m.editor.SetValue(value) + m.editing = true + return m.editor.Focus() +} diff --git a/tui/workspace_ui_test.go b/tui/workspace_ui_test.go new file mode 100644 index 00000000..772c249b --- /dev/null +++ b/tui/workspace_ui_test.go @@ -0,0 +1,288 @@ +package main + +import ( + "bufio" + "bytes" + "strings" + "testing" + + tea "charm.land/bubbletea/v2" +) + +func queueModel(t *testing.T) (model, *bytes.Buffer) { + t.Helper() + t.Setenv("HOME", t.TempDir()) + t.Setenv("KYROZEN_REDUCED_MOTION", "1") + m := initialModel("", true) + m.screen, m.backendReady, m.activeSessionID = screenChat, true, "first" + m.width, m.height = 120, 30 + m.resize() + out := new(bytes.Buffer) + m.bridge.stdin = bufio.NewWriter(out) + return m, out +} + +func TestQueuedTurnsWaitForMatchingIdleAndRetainDraft(t *testing.T) { + m, out := queueModel(t) + m.startTurn("first") + id := m.activeTurn + m.input.SetValue("next") + m.submit() + m.input.SetValue("unfinished") + m.handleBackendEvent(backendEvent{"event": "response", "request_id": id, "text": "done"}) + m.handleBackendEvent(backendEvent{"event": "status", "request_id": "other", "state": "ready", "busy": false}) + m.dispatchNext() + if strings.Count(out.String(), `"command":"submit"`) != 1 { + t.Fatal("sent during active turn") + } + m.handleBackendEvent(backendEvent{"event": "status", "request_id": id, "state": "ready", "busy": false}) + m.dispatchNext() + m.dispatchNext() + if strings.Count(out.String(), `"command":"submit"`) != 2 || !strings.Contains(out.String(), `"text":"next"`) || m.input.Value() != "unfinished" { + t.Fatal(out.String(), m.input.Value()) + } +} + +func TestQueueEditWithdrawPauseAndChatSwitch(t *testing.T) { + m, out := queueModel(t) + s := m.conversation() + s.queue = []string{"one", "two"} + s.paused = true + m.input.SetValue("first draft") + m.openUtility("queue") + m.utilityKey(tea.KeyPressMsg{Code: tea.KeyEnter}) + m.editor.SetValue("edited") + m.utilityKey(tea.KeyPressMsg{Code: tea.KeyEnter}) + if s.queue[0] != "edited" { + t.Fatal(s.queue) + } + m.utilityKey(tea.KeyPressMsg{Code: 'd', Text: "d"}) + m.utilityKey(tea.KeyPressMsg{Code: tea.KeyEscape}) + m.selectConversation("global", "second") + m.input.SetValue("second draft") + m.dispatchNext() + m.selectConversation("", "first") + m.dispatchNext() + if out.Len() != 0 || m.input.Value() != "first draft" || len(s.queue) != 1 || s.queue[0] != "two" { + t.Fatal(out.String(), s) + } + m.openUtility("queue") + m.utilityKey(tea.KeyPressMsg{Code: 'r', Text: "r"}) + m.dispatchNext() + if !strings.Contains(out.String(), `"text":"two"`) { + t.Fatal(out.String()) + } +} + +func TestToolDecisionAndErrorPauseDispatch(t *testing.T) { + m, out := queueModel(t) + m.startTurn("query") + id := m.activeTurn + m.conversation().queue = []string{"next"} + m.handleBackendEvent(backendEvent{"event": "error", "request_id": id, "error": "Provider disconnected"}) + m.handleBackendEvent(backendEvent{"event": "status", "request_id": id, "state": "ready", "busy": false}) + m.screen = screenChat + m.dispatchNext() + if !m.conversation().paused || strings.Contains(out.String(), `"text":"next"`) { + t.Fatal(m.conversation()) + } + m.conversation().paused = false + m.pendingPlan = &planProposal{} + m.dispatchNext() + if strings.Contains(out.String(), `"text":"next"`) { + t.Fatal("sent during plan decision") + } +} + +func TestInstructionsAndPalettePreserveDraft(t *testing.T) { + m, _ := queueModel(t) + m.input.SetValue("草稿") + m.handleKey(tea.KeyPressMsg{Code: 'p', Mod: tea.ModCtrl}) + for _, r := range "instr" { + m.handleKey(tea.KeyPressMsg{Code: r, Text: string(r)}) + } + m.handleKey(tea.KeyPressMsg{Code: tea.KeyEnter}) + id := m.instructionRequest + m.handleBackendEvent(backendEvent{"event": "instruction_source", "request_id": id, "path": "AGENTS.md"}) + m.handleBackendEvent(backendEvent{"event": "instruction_text", "request_id": id, "text": "Use short functions."}) + m.handleBackendEvent(backendEvent{"event": "instruction_text", "request_id": "stale", "text": "ignored"}) + if !strings.Contains(m.utilityView(), "short functions") || strings.Contains(m.utilityView(), "ignored") { + t.Fatal(m.utilityView()) + } + m.handleKey(tea.KeyPressMsg{Code: tea.KeyEscape}) + if m.input.Value() != "草稿" { + t.Fatal(m.input.Value()) + } +} + +func TestSetupRetriesEditableModelAndPreservesEarlyDraft(t *testing.T) { + m, out := queueModel(t) + m.activeSessionID, m.backendReady = "", false + m.input.SetValue("early draft") + m.submit() + m.selectConversation("global", "new") + if m.input.Value() != "early draft" || out.Len() != 0 { + t.Fatal(m.input.Value(), out.String()) + } + m.onboardingKind = "new" + m.handlePrompt(backendEvent{"kind": "model", "current": "auto"}) + enter := tea.KeyPressMsg{Code: tea.KeyEnter} + m.apiInput.Reset() + m.handleKey(enter) + if m.screen != screenModel || out.Len() != 0 { + t.Fatal("empty model advanced setup") + } + m.apiInput.SetValue("example-model") + m.handleKey(enter) + m.handleBackendEvent(backendEvent{"event": "error", "code": "model_setup_failed", "error": "Try another model"}) + m.handleKey(enter) + if m.screen != screenModel || !m.apiInput.Focused() || m.apiInput.Value() != "example-model" { + t.Fatal("retry did not restore model editor") + } + m.openPermissions("ask") + m.handleKey(tea.KeyPressMsg{Code: tea.KeyEscape}) + if m.screen == screenChat || !strings.Contains(out.String(), `"name":"model"`) { + t.Fatal("back from permissions skipped setup", out.String()) + } +} + +func TestNavigationWaitsForBoundSessionBeforeSendingQueuedInput(t *testing.T) { + m, out := queueModel(t) + m.activeScopeID = "project-a" + old := m.conversation() + old.queue = []string{"follow up in project A"} + m.input.SetValue("draft in project A") + m.navigation = []navigationGroup{{scope: "project", scopeID: "project-b", path: "/B", + chats: []navigationChat{{id: "first", title: "project B chat"}}}} + m.navigationFocused, m.navigationOpen = true, true + for i, target := range m.navigationTargets() { + if target.kind == "chat" { + m.navigationIndex = i + } + } + + next, _ := m.Update(tea.KeyPressMsg{Code: tea.KeyEnter}) + m = next.(model) + id := m.navigationRequest + if id == "" || strings.Contains(out.String(), `"command":"submit"`) { + t.Fatalf("dispatch before navigation acknowledgement: %s", out.String()) + } + m.submit() + if m.input.Value() != "draft in project A" || len(old.queue) != 1 { + t.Fatal("early enter consumed source draft or queued text") + } + m.handleBackendEvent(backendEvent{"event": "navigation", "request_id": id, "active_session_id": "first", "active_scope_id": "project-b"}) + if m.input.Value() != "" || len(m.conversation().queue) != 0 { + t.Fatal("same session ID in different workspaces shared input") + } + m.conversation().queue = []string{"follow up in project B"} + m.handleBackendEvent(backendEvent{"event": "ready", "request_id": "other"}) + m.dispatchNext() + if strings.Contains(out.String(), `"command":"submit"`) { + t.Fatal("dispatch before matching ready") + } + m.handleBackendEvent(backendEvent{"event": "ready", "request_id": id, "session_id": "first"}) + m.dispatchNext() + if len(old.queue) != 1 || old.draft != "draft in project A" || !strings.Contains(out.String(), "follow up in project B") || strings.Contains(out.String(), "follow up in project A") { + t.Fatalf("follow-up delivered to the wrong conversation: %s", out.String()) + } +} + +func TestBusyNavigationCannotDisturbTheTurn(t *testing.T) { + m, out := queueModel(t) + m.startTurn("active") + id := m.activeTurn + for _, name := range []string{"/new", "/project /other", "/session another"} { + m.send("command", map[string]any{"name": name}) + } + m.send("navigate", map[string]any{"action": "switch"}) + if m.activeTurn != id || m.navigationRequest != "" || strings.Count(out.String(), "\n") != 1 || m.screen == screenError { + t.Fatal("busy navigation disturbed the turn", out.String()) + } +} + +func TestFailedNavigationRetainsAndPausesSourceQueue(t *testing.T) { + m, out := queueModel(t) + m.conversation().queue = []string{"source follow-up"} + m.send("command", map[string]any{"name": "/project /missing"}) + m.handleBackendEvent(backendEvent{"event": "error", "request_id": m.navigationRequest, "error": "cannot open project"}) + m.screen = screenChat + m.dispatchNext() + if m.navigationRequest != "" || !m.conversation().paused || len(m.conversation().queue) != 1 || strings.Contains(out.String(), `"command":"submit"`) { + t.Fatalf("lost paused queue after navigation failed: %s", out.String()) + } +} + +func TestRuntimeFailureAndCancellationPauseAfterVisibleReply(t *testing.T) { + for _, kind := range []string{"turn.failed", "turn.cancelled"} { + t.Run(kind, func(t *testing.T) { + m, out := queueModel(t) + m.startTurn("request") + id := m.activeTurn + m.conversation().queue = []string{"follow-up"} + m.handleBackendEvent(backendEvent{"event": "runtime_event", "request_id": id, "runtime_event": map[string]any{"kind": kind}}) + m.handleBackendEvent(backendEvent{"event": "response", "request_id": id, "text": "The turn could not finish."}) + m.handleBackendEvent(backendEvent{"event": "status", "request_id": id, "state": "ready", "busy": false}) + m.dispatchNext() + if !m.conversation().paused || len(m.conversation().queue) != 1 || strings.Count(out.String(), "\n") != 1 { + t.Fatal("failed turn drained queued text", out.String()) + } + }) + } +} + +func TestAncillaryReplyAndRejectedSubmitKeepTurnOwnership(t *testing.T) { + m, _ := queueModel(t) + m.startTurn("query") + id := m.activeTurn + m.handleBackendEvent(backendEvent{"event": "response", "request_id": "info", "text": "command output"}) + if m.activeTurn != id || !m.busy { + t.Fatal("command reply finished an unrelated turn") + } + m.handleBackendEvent(backendEvent{"event": "error", "request_id": id, "code": "busy", "error": "A turn is already running."}) + if m.activeTurn != "" || !m.conversation().paused { + t.Fatal("rejected submit left queue waiting on a nonexistent worker") + } +} + +func TestSetupWaitClosesUnansweredTurn(t *testing.T) { + m, _ := queueModel(t) + m.startTurn("run report") + m.handleBackendEvent(backendEvent{"event": "status", "request_id": m.activeTurn, "state": "waiting", "busy": false, "message": "Provider setup required."}) + m.handleBackendEvent(backendEvent{"event": "response", "request_id": "setup", "text": "Model configured."}) + if m.messages[1].streaming || m.messages[1].text != "Provider setup required." || len(m.messages) != 3 || !m.conversation().paused { + t.Fatal(m.messages) + } +} + +func TestPlanRevisionCannotReplaceAStillRunningTurn(t *testing.T) { + m, out := queueModel(t) + m.startTurn("propose a plan") + id := m.activeTurn + m.openUtility("revision") + m.startEditor("change step one") + enter := tea.KeyPressMsg{Code: tea.KeyEnter} + m.handleKey(enter) + if m.activeTurn != id || !m.editing || m.editor.Value() != "change step one" || strings.Count(out.String(), "\n") != 1 { + t.Fatal("early revision replaced proposing turn") + } + m.handleBackendEvent(backendEvent{"event": "status", "request_id": id, "state": "ready", "busy": false}) + m.handleKey(enter) + if m.activeTurn == id || !strings.Contains(out.String(), "change step one") { + t.Fatal("idle revision did not send") + } +} + +func TestWheelPreservesQueueEditTarget(t *testing.T) { + m, _ := queueModel(t) + m.conversation().queue = []string{"one", "two"} + m.openUtility("queue") + m.utilityKey(tea.KeyPressMsg{Code: tea.KeyEnter}) + u, _ := m.Update(tea.MouseWheelMsg{Button: tea.MouseWheelDown}) + m = u.(model) + m.editor.SetValue("edited") + m.utilityKey(tea.KeyPressMsg{Code: tea.KeyEnter}) + if got := strings.Join(m.conversation().queue, ","); got != "edited,two" { + t.Fatal(got) + } +} diff --git a/website/assets/cockpit.svg b/website/assets/cockpit.svg deleted file mode 100644 index 47ccd4c3..00000000 --- a/website/assets/cockpit.svg +++ /dev/null @@ -1 +0,0 @@ -OpenKyrozen TUI — focused cockpit◆ OPENKYROZEN · ASK · deepseek-v4-flash · 7.8K TOK · $0.02● READYYOUPROJECT GRAPHREADYMake the terminal feel focused, calm, and unmistakably Kyrozen.◆ ·· KYROZEN · ●## Focused cockpit●● The transcript now owns the screen while graph, tasks, and memory stay close at hand. 38 nodes · 61 edges • Calm context hierarchy TASKS 3 • Compact, privacy-safe receipts ✓Map terminal…completed • Responsive from tiny terminals to fullscreen ◐Polish focused…running○Verify respons…pendingTOOL · read_file · SUCCESSSESSIONkyrozen-demo4 calls · workspacepreference autoactive ask╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮│› Ask Kyrozen anything…││› ││› │╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯kyrozen-demo Enter send · Shift+Enter newline · / commands · PgUp/PgDn scroll · Ctrl+C quit \ No newline at end of file diff --git a/website/assets/terminal.png b/website/assets/terminal.png new file mode 100644 index 00000000..510634f1 Binary files /dev/null and b/website/assets/terminal.png differ diff --git a/website/build_site.py b/website/build_site.py index eeb35e7d..4d72bc18 100644 --- a/website/build_site.py +++ b/website/build_site.py @@ -70,7 +70,7 @@ "intro": "Explore a terminal AI agent for coding, research, and workspace tasks, with project tools, persistent memory, model choice, and explicit limits on actions and learning.", "body": """
-
01

TERMINAL-NATIVE

Work where your project lives.

Use the Bubble Tea terminal interface or the command-line agent to explore a workspace, edit files, run commands, work with Git, and inspect project history. The local browser UI is unmaintained. REST and MCP interfaces are available for integrations.

CLI + TUIOptional Web APIMCP
+
01

TERMINAL-NATIVE

Work where your project lives.

Use the Bubble Tea terminal interface or the command-line agent to explore a workspace, edit files, run commands, work with Git, and inspect project history. Integrations use REST, streaming chat, webhooks, or HTTP MCP.

CLI + TUIHTTP APIMCP
02

EVIDENCE-BASED LEARNING

Improve from outcomes, not guesswork.

OpenKyrozen records corrections, tool receipts, and acceptance evidence. Its learning system can propose reusable skills and workflow improvements after repeated work, then applies evidence gates before promotion. It does not grant capabilities, approve actions, or modify model weights.

How self-learning works
ReceiptsAcceptance evidencePromotion gates
03

DURABLE CONTEXT

Carry useful knowledge across sessions.

SQLite is the authoritative store for sessions, events, tasks, memory claims, and learning state. The optional Chroma index is derived and can be rebuilt; it is not the only copy of durable records.

Read the architecture guide
SQLiteScoped memoryRebuildable index
04

YOUR MODEL CHOICE

Bring the provider that fits the task.

Configure supported hosted providers or a local Ollama model, set defaults, and use documented fallback behavior. Credentials belong in environment variables or OpenKyrozen’s encrypted configuration flow.

See provider configuration
Hosted modelsOllamaConfigurable routing
@@ -122,7 +122,7 @@
Does OpenKyrozen keep all data on my computer?

Application state is stored locally by default, with SQLite as the authoritative store. When you use a hosted model provider, the prompt content needed for that request is sent to that provider. A local model such as Ollama can be configured when you want local inference.

Which model providers can I use?

OpenKyrozen supports multiple hosted provider families and local Ollama. You can configure provider defaults and fallback behavior. See the configuration guide for the current list and setup details.

Provider configuration
Can it run commands or change files without asking?

Ask and Plan modes are read-only. Agent actions go through capability checks and approval controls. Review the active mode and approval settings before granting access to high-impact tools.

-
Does it include a web interface?

Yes. The browser UI is unmaintained. Run kyrozen for the maintained terminal interface.

+
How do I connect another application?

Start the HTTP API server for REST, streaming chat, webhooks, or MCP. Use kyrozen for an interactive terminal session.

Which operating systems and Python versions are supported?

The project documents installation for macOS, Linux, and Windows, and supports Python 3.12 and 3.13.

Is OpenKyrozen open source?

Yes. The project is released under the MIT License.

View the source on GitHub
@@ -176,7 +176,7 @@ "intro": "了解这款用于编程、研究和工作区任务的终端 AI 智能体,以及它的项目工具、持久记忆、模型选择和操作边界。", "body": """
-
01

终端原生

在项目所在的位置工作。

使用 Bubble Tea 终端界面或命令行智能体探索工作区、编辑文件、运行命令、操作 Git 并查看项目历史。本地浏览器界面已停止维护。其他工具可以通过 REST API 或 MCP 接入。

CLI + TUI可选 Web APIMCP
+
01

终端原生

在项目所在的位置工作。

使用 Bubble Tea 终端界面或命令行智能体探索工作区、编辑文件、运行命令、操作 Git 并查看项目历史。其他工具可以通过 REST、流式聊天、Webhook 或 HTTP MCP 接入。

CLI + TUIHTTP APIMCP
02

基于证据的学习

根据结果改进,而不是猜测。

OpenKyrozen 会记录纠正、工具回执和验收证据。重复的工作可以形成可复用技能和流程改进,但晋升前必须经过证据检查。它不会增加能力权限、批准操作或修改模型权重。

自学习如何运作
工具回执验收证据晋升门槛
03

持久上下文

在不同会话间保留有用知识。

SQLite 是会话、事件、任务、记忆声明和学习状态的权威存储。可选的 Chroma 索引是派生数据,可以重建,不是持久记录的唯一副本。

阅读架构说明
SQLite作用域记忆可重建索引
04

模型由你选择

为任务选择合适的服务商。

配置托管模型服务商或本地 Ollama 模型,设置默认项并使用文档说明的回退行为。凭据应存放在环境变量或 OpenKyrozen 的加密配置流程中。

查看服务商配置
托管模型Ollama可配置路由
@@ -228,7 +228,7 @@
所有数据都会留在我的电脑上吗?

默认情况下,应用状态保存在本地,SQLite 是权威存储。使用托管模型服务商时,该请求所需的提示内容会发送给相应服务商。如果希望本地推理,可以配置 Ollama 等本地模型。

可以使用哪些模型服务商?

OpenKyrozen 支持多种托管模型服务商,也支持本地 Ollama。你可以配置默认服务商和回退行为。当前列表与设置细节见配置指南。

模型服务商配置
它会不会不经询问就运行命令或修改文件?

Ask 和 Plan 模式为只读。Agent 操作受能力权限和审批控制。启用高影响工具前,请检查当前模式与审批设置。

-
它有网页界面吗?

有。浏览器界面已停止维护。运行 kyrozen 可打开持续维护的终端界面。

+
怎样接入其他应用?

启动 HTTP API 服务即可使用 REST、流式聊天、Webhook 或 MCP。交互操作请运行 kyrozen 打开终端。

支持哪些操作系统和 Python 版本?

项目提供 macOS、Linux 和 Windows 的安装说明,支持 Python 3.12 和 3.13。

OpenKyrozen 是开源软件吗?

是。项目使用 MIT 许可证发布。

在 GitHub 查看源码
@@ -319,7 +319,7 @@ def document(lang, slug, page): schema_data = {"@context": "https://schema.org", "@graph": graph} schema = '' label = "OpenKyrozen — A local-first terminal agent" if lang == "en" else "OpenKyrozen — 本地优先的终端智能体" - image_alt = "OpenKyrozen terminal interface showing a project, task progress, and workspace context" if lang == "en" else "OpenKyrozen 终端界面,展示项目、任务进度与工作区上下文" + image_alt = "OpenKyrozen conversation about an empty CSV export, with tool results and the message editor" if lang == "en" else "OpenKyrozen 终端中的 CSV 导出对话、工具结果和消息输入框" main_label = "Main content" if lang == "en" else "主要内容" return f""" @@ -359,7 +359,7 @@ def document(lang, slug, page):

{escape(page['intro'])}

{home_install_html(lang) if slug == 'home' else ''} - {('
OPENKYROZEN / TUIPROJECT CONTEXT
' + escape(image_alt, quote=True) + '
' + ('Terminal-native · Evidence-backed · Local-first' if lang == 'en' else '终端原生 · 证据驱动 · 本地优先') + '
') if slug == 'home' else ''} + {('
' + escape(image_alt, quote=True) + '
' + ('Example session · Fixing a CSV export' if lang == 'en' else '示例对话 · 修复 CSV 导出') + '
') if slug == 'home' else ''} {page['body']}