diff --git a/.changeset/config.json b/.changeset/config.json index 310bc510947..e2acc376621 100644 --- a/.changeset/config.json +++ b/.changeset/config.json @@ -7,5 +7,5 @@ "access": "restricted", "baseBranch": "main", "updateInternalDependencies": "patch", - "ignore": ["@roo-code/cli"] + "ignore": [] } diff --git a/.dockerignore b/.dockerignore index 4579d61580e..63599788338 100644 --- a/.dockerignore +++ b/.dockerignore @@ -76,18 +76,14 @@ src/node_modules !pnpm-workspace.yaml !scripts/bootstrap.mjs !apps/web-evals/ -!apps/cli/ !src/ !webview-ui/ !packages/evals/.docker/entrypoints/runner.sh !packages/build/ !packages/config-eslint/ !packages/config-typescript/ -!packages/core/ !packages/evals/ !packages/ipc/ !packages/telemetry/ !packages/types/ -!packages/vscode-shim/ -!packages/cloud/ !locales/ diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 443842c856f..34ac70a6cfd 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -81,9 +81,11 @@ body: - DeepSeek - Featherless AI - Fireworks AI + - Glama - Google Gemini - Google Vertex AI - Groq + - Human Relay Provider - LiteLLM - LM Studio - Mistral AI diff --git a/.gitignore b/.gitignore index 364b391a012..e044fc32a7b 100644 --- a/.gitignore +++ b/.gitignore @@ -49,8 +49,3 @@ logs # Qdrant qdrant_storage/ - -# Architect plans -plans/ - -roo-cli-*.tar.gz* diff --git a/.roo/commands/cli-release.md b/.roo/commands/cli-release.md deleted file mode 100644 index c90b2392152..00000000000 --- a/.roo/commands/cli-release.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -description: "Create a new release of the Roo Code CLI" -argument-hint: "[version-description]" -mode: code ---- - -1. Identify changes since the last CLI release: - - - Get the last CLI release tag: `gh release list --limit 10 | grep "cli-v"` - - View changes since last release: `git log cli-v..HEAD -- apps/cli --oneline` - - Or for uncommitted changes: `git diff --stat -- apps/cli` - -2. Review and summarize the changes to determine an appropriate changelog entry. Group changes by type: - - - **Added**: New features - - **Changed**: Changes to existing functionality - - **Fixed**: Bug fixes - - **Removed**: Removed features - - **Tests**: New or updated tests - -3. Bump the version in `apps/cli/package.json`: - - - Increment the patch version (e.g., 0.0.43 → 0.0.44) for bug fixes and minor changes - - Increment the minor version (e.g., 0.0.43 → 0.1.0) for new features - - Increment the major version (e.g., 0.0.43 → 1.0.0) for breaking changes - -4. Update `apps/cli/CHANGELOG.md` with a new entry: - - - Add a new section at the top (below the header) following this format: - - ```markdown - ## [X.Y.Z] - YYYY-MM-DD - - ### Added - - - Description of new features - - ### Changed - - - Description of changes - - ### Fixed - - - Description of bug fixes - ``` - - - Use the current date in YYYY-MM-DD format - - Include links to relevant source files where helpful - - Describe changes from the user's perspective - -5. Commit the version bump and changelog update: - - ```bash - git add apps/cli/package.json apps/cli/CHANGELOG.md - git commit -m "chore(cli): prepare release v" - ``` - -6. Run the release script from the monorepo root: - - ```bash - ./apps/cli/scripts/release.sh - ``` - - The release script will automatically: - - - Build the extension and CLI - - Create a platform-specific tarball - - Verify the installation works correctly (runs --help, --version, and e2e test) - - Extract changelog content and include it in the GitHub release notes - - Create the GitHub release with the tarball attached - -7. After a successful release, verify: - - Check the release page: https://github.com/RooCodeInc/Roo-Code/releases - - Verify the "What's New" section contains the changelog content - - Test installation: `curl -fsSL https://raw.githubusercontent.com/RooCodeInc/Roo-Code/main/apps/cli/install.sh | sh` - -**Notes:** - -- The release script requires GitHub CLI (`gh`) to be installed and authenticated -- If a release already exists for the tag, the script will prompt to delete and recreate it -- The script creates a tarball for the current platform only (darwin-arm64, darwin-x64, linux-arm64, or linux-x64) -- Multi-platform releases require running the script on each platform and manually uploading additional tarballs diff --git a/.roo/commands/commit.md b/.roo/commands/commit.md deleted file mode 100644 index 7796c49fa99..00000000000 --- a/.roo/commands/commit.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -description: "Commit and push changes with a descriptive message" -argument-hint: "[optional-context]" -mode: code ---- - -1. Analyze the current changes to understand what needs to be committed: - - ```bash - # Check for staged and unstaged changes - git status --short - - # View the diff of all changes (staged and unstaged) - git diff HEAD - ``` - -2. Based on the diff output, formulate a commit message following conventional commit format: - - - **feat**: New feature or functionality - - **fix**: Bug fix - - **refactor**: Code restructuring without behavior change - - **docs**: Documentation changes - - **test**: Adding or updating tests - - **chore**: Maintenance tasks, dependencies, configs - - **style**: Formatting, whitespace, no logic changes - - Format: `type(scope): brief description` - - Examples: - - - `feat(api): add user authentication endpoint` - - `fix(ui): resolve button alignment on mobile` - - `refactor(core): simplify error handling logic` - - `docs(readme): update installation instructions` - -3. Stage all unstaged changes: - - ```bash - git add -A - ``` - -4. Commit with the generated message: - - ```bash - git commit -m "type(scope): brief description" - ``` - - **If pre-commit hooks fail:** - - - Review the error output (linter errors, type checking errors, etc.) - - Fix the identified issues in the affected files - - Re-stage the fixes: `git add -A` - - Retry the commit: `git commit -m "type(scope): brief description"` - -5. Push to the remote repository: - - ```bash - git push - ``` - - **If pre-push hooks fail:** - - - Review the error output (test failures, linter errors, etc.) - - Fix the identified issues in the affected files - - Stage and commit the fixes using steps 3-4 - - Retry the push: `git push` - -**Tips for good commit messages:** - -- Keep the first line under 72 characters -- Use imperative mood ("add", "fix", "update", not "added", "fixes", "updated") -- Be specific but concise -- If multiple unrelated changes exist, consider splitting into separate commits - -**Common hook failures and fixes:** - -- **Linter errors**: Run the project's linter (e.g., `npm run lint` or `pnpm lint`) to see all issues, then fix them -- **Type checking errors**: Run type checker (e.g., `npx tsc --noEmit`) to identify type issues -- **Test failures**: Run tests (e.g., `npm test` or `pnpm test`) to identify failing tests and fix them -- **Format issues**: Run formatter (e.g., `npm run format` or `pnpm format`) to auto-fix formatting diff --git a/.roo/commands/release.md b/.roo/commands/release.md index 2e09783a58e..707844cdc4e 100644 --- a/.roo/commands/release.md +++ b/.roo/commands/release.md @@ -1,7 +1,6 @@ --- description: "Create a new release of the Roo Code extension" argument-hint: patch | minor | major -mode: code --- 1. Identify the SHA corresponding to the most recent release using GitHub CLI: `gh release view --json tagName,targetCommitish,publishedAt` diff --git a/.roo/roomotes.yml b/.roo/roomotes.yml index 0ea30b93af7..33f6b3bd57c 100644 --- a/.roo/roomotes.yml +++ b/.roo/roomotes.yml @@ -1,6 +1,25 @@ version: "1.0" commands: + - name: Pull latest changes + run: git pull + timeout: 60 + execution_phase: task_run - name: Install dependencies run: pnpm install timeout: 60 + execution_phase: task_run + +github_events: + - event: issues.opened + action: + name: github.issue.fix + - event: issue_comment.created + action: + name: github.issue.comment.respond + - event: pull_request.opened + action: + name: github.pr.review + - event: pull_request_review_comment.created + action: + name: github.pr.comment.respond diff --git a/.roo/rules-debug/cli.md b/.roo/rules-debug/cli.md deleted file mode 100644 index 7992718ffad..00000000000 --- a/.roo/rules-debug/cli.md +++ /dev/null @@ -1,67 +0,0 @@ -# CLI Debugging with File-Based Logging - -When debugging the CLI, `console.log` will break the TUI (Terminal User Interface). Use file-based logging to capture debug output without interfering with the application's display. - -## File-Based Logging Strategy - -1. **Write logs to a temporary file instead of console**: - - - Create a log file at a known location, e.g., `/tmp/roo-cli-debug.log` - - Use `fs.appendFileSync()` to write timestamped log entries - - Example logging utility: - - ```typescript - import fs from "fs" - const DEBUG_LOG = "/tmp/roo-cli-debug.log" - - function debugLog(message: string, data?: unknown) { - const timestamp = new Date().toISOString() - const entry = data - ? `[${timestamp}] ${message}: ${JSON.stringify(data, null, 2)}\n` - : `[${timestamp}] ${message}\n` - fs.appendFileSync(DEBUG_LOG, entry) - } - ``` - -2. **Clear the log file before each debugging session**: - - Run `echo "" > /tmp/roo-cli-debug.log` or use `fs.writeFileSync(DEBUG_LOG, "")` at app startup during debugging - -## Iterative Debugging Workflow - -Follow this feedback loop to systematically narrow down issues: - -1. **Add targeted logging** at suspected problem areas based on your hypotheses -2. **Instruct the user** to reproduce the issue using the CLI normally -3. **Read the log file** after the user completes testing: - - Run `cat /tmp/roo-cli-debug.log` to retrieve the captured output -4. **Analyze the log output** to gather clues about: - - Execution flow and timing - - Variable values at key points - - Which code paths were taken - - Error conditions or unexpected states -5. **Refine your logging** based on findings—add more detail where needed, remove noise -6. **Ask the user to test again** with updated logging -7. **Repeat** until the root cause is identified - -## Best Practices - -- Log entry/exit points of functions under investigation -- Include relevant variable values and state information -- Use descriptive prefixes to categorize logs: `[STATE]`, `[EVENT]`, `[ERROR]`, `[FLOW]` -- Log both the "happy path" and error handling branches -- When dealing with async operations, log before and after `await` statements -- For user interactions, log the received input and the resulting action - -## Example Debug Session - -```typescript -// Add logging to investigate a picker selection issue -debugLog("[FLOW] PickerSelect onSelect called", { selectedIndex, item }) -debugLog("[STATE] Current selection state", { currentValue, isOpen }) - -// After async operation -const result = await fetchOptions() -debugLog("[FLOW] fetchOptions completed", { resultCount: result.length }) -``` - -Then ask: "Please reproduce the issue by [specific steps]. When you're done, let me know and I'll analyze the debug logs." diff --git a/.roo/rules-translate/instructions-zh-cn.md b/.roo/rules-translate/instructions-zh-cn.md index b166a1e6a8d..6141038728c 100644 --- a/.roo/rules-translate/instructions-zh-cn.md +++ b/.roo/rules-translate/instructions-zh-cn.md @@ -16,6 +16,7 @@ | Auto-approve | 自动批准 | 始终批准 | 权限相关术语 | | Checkpoint | 存档点 | 检查点/快照 | 技术概念统一 | | MCP Server | MCP 服务 | MCP 服务器 | 技术组件 | +| Human Relay | 人工辅助模式 | 人工中继 | 功能描述清晰 | | Network Timeout | 请求超时 | 网络超时 | 更准确描述 | | Terminal | 终端 | 命令行 | 技术术语统一 | | diff | 差异更新 | 差分/补丁 | 代码变更 | diff --git a/.roo/skills/evals-context/SKILL.md b/.roo/skills/evals-context/SKILL.md deleted file mode 100644 index 985b788b94f..00000000000 --- a/.roo/skills/evals-context/SKILL.md +++ /dev/null @@ -1,188 +0,0 @@ ---- -name: evals-context -description: Provides context about the Roo Code evals system structure in this monorepo. Use when tasks mention "evals", "evaluation", "eval runs", "eval exercises", or working with the evals infrastructure. Helps distinguish between the evals execution system (packages/evals, apps/web-evals) and the public website evals display page (apps/web-roo-code/src/app/evals). ---- - -# Evals Codebase Context - -## When to Use This Skill - -Use this skill when the task involves: - -- Modifying or debugging the evals execution infrastructure -- Adding new eval exercises or languages -- Working with the evals web interface (apps/web-evals) -- Modifying the public evals display page on roocode.com -- Understanding where evals code lives in this monorepo - -## When NOT to Use This Skill - -Do NOT use this skill when: - -- Working on unrelated parts of the codebase (extension, webview-ui, etc.) -- The task is purely about the VS Code extension's core functionality -- Working on the main website pages that don't involve evals - -## Key Disambiguation: Two "Evals" Locations - -This monorepo has **two distinct evals-related locations** that can cause confusion: - -| Component | Path | Purpose | -| --------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | -| **Evals Execution System** | `packages/evals/` | Core eval infrastructure: CLI, DB schema, Docker configs | -| **Evals Management UI** | `apps/web-evals/` | Next.js app for creating/monitoring eval runs (localhost:3446) | -| **Website Evals Page** | `apps/web-roo-code/src/app/evals/` | Public roocode.com page displaying eval results | -| **External Exercises Repo** | [Roo-Code-Evals](https://github.com/RooCodeInc/Roo-Code-Evals) | Actual coding exercises (NOT in this monorepo) | - -## Directory Structure Reference - -### `packages/evals/` - Core Evals Package - -``` -packages/evals/ -├── ARCHITECTURE.md # Detailed architecture documentation -├── ADDING-EVALS.md # Guide for adding new exercises/languages -├── README.md # Setup and running instructions -├── docker-compose.yml # Container orchestration -├── Dockerfile.runner # Runner container definition -├── Dockerfile.web # Web app container -├── drizzle.config.ts # Database ORM config -├── src/ -│ ├── index.ts # Package exports -│ ├── cli/ # CLI commands for running evals -│ │ ├── runEvals.ts # Orchestrates complete eval runs -│ │ ├── runTask.ts # Executes individual tasks in containers -│ │ ├── runUnitTest.ts # Validates task completion via tests -│ │ └── redis.ts # Redis pub/sub integration -│ ├── db/ -│ │ ├── schema.ts # Database schema (runs, tasks) -│ │ ├── queries/ # Database query functions -│ │ └── migrations/ # SQL migrations -│ └── exercises/ -│ └── index.ts # Exercise loading utilities -└── scripts/ - └── setup.sh # Local macOS setup script -``` - -### `apps/web-evals/` - Evals Management Web App - -``` -apps/web-evals/ -├── src/ -│ ├── app/ -│ │ ├── page.tsx # Home page (runs list) -│ │ ├── runs/ -│ │ │ ├── new/ # Create new eval run -│ │ │ └── [id]/ # View specific run status -│ │ └── api/runs/ # SSE streaming endpoint -│ ├── actions/ # Server actions -│ │ ├── runs.ts # Run CRUD operations -│ │ ├── tasks.ts # Task queries -│ │ ├── exercises.ts # Exercise listing -│ │ └── heartbeat.ts # Controller health checks -│ ├── hooks/ # React hooks (SSE, models, etc.) -│ └── lib/ # Utilities and schemas -``` - -### `apps/web-roo-code/src/app/evals/` - Public Website Evals Page - -``` -apps/web-roo-code/src/app/evals/ -├── page.tsx # Fetches and displays public eval results -├── evals.tsx # Main evals display component -├── plot.tsx # Visualization component -└── types.ts # EvalRun type (extends packages/evals types) -``` - -This page **displays** eval results on the public roocode.com website. It imports types from `@roo-code/evals` but does NOT run evals. - -## Architecture Overview - -The evals system is a distributed evaluation platform that runs AI coding tasks in isolated VS Code environments: - -``` -┌─────────────────────────────────────────────────────────────┐ -│ Web App (apps/web-evals) ──────────────────────────────── │ -│ │ │ -│ ▼ │ -│ PostgreSQL ◄────► Controller Container │ -│ │ │ │ -│ ▼ ▼ │ -│ Redis ◄───► Runner Containers (1-25 parallel) │ -└─────────────────────────────────────────────────────────────┘ -``` - -**Key components:** - -- **Controller**: Orchestrates eval runs, spawns runners, manages task queue (p-queue) -- **Runner**: Isolated Docker container with VS Code + Roo Code extension + language runtimes -- **Redis**: Pub/sub for real-time events (NOT task queuing) -- **PostgreSQL**: Stores runs, tasks, metrics - -## Common Tasks Quick Reference - -### Adding a New Eval Exercise - -1. Add exercise to [Roo-Code-Evals](https://github.com/RooCodeInc/Roo-Code-Evals) repo (external) -2. See [`packages/evals/ADDING-EVALS.md`](packages/evals/ADDING-EVALS.md) for structure - -### Modifying Eval CLI Behavior - -Edit files in [`packages/evals/src/cli/`](packages/evals/src/cli/): - -- [`runEvals.ts`](packages/evals/src/cli/runEvals.ts) - Run orchestration -- [`runTask.ts`](packages/evals/src/cli/runTask.ts) - Task execution -- [`runUnitTest.ts`](packages/evals/src/cli/runUnitTest.ts) - Test validation - -### Modifying the Evals Web Interface - -Edit files in [`apps/web-evals/src/`](apps/web-evals/src/): - -- [`app/runs/new/new-run.tsx`](apps/web-evals/src/app/runs/new/new-run.tsx) - New run form -- [`actions/runs.ts`](apps/web-evals/src/actions/runs.ts) - Run server actions - -### Modifying the Public Evals Display Page - -Edit files in [`apps/web-roo-code/src/app/evals/`](apps/web-roo-code/src/app/evals/): - -- [`evals.tsx`](apps/web-roo-code/src/app/evals/evals.tsx) - Display component -- [`plot.tsx`](apps/web-roo-code/src/app/evals/plot.tsx) - Charts - -### Database Schema Changes - -1. Edit [`packages/evals/src/db/schema.ts`](packages/evals/src/db/schema.ts) -2. Generate migration: `cd packages/evals && pnpm drizzle-kit generate` -3. Apply migration: `pnpm drizzle-kit migrate` - -## Running Evals Locally - -```bash -# From repo root -pnpm evals - -# Opens web UI at http://localhost:3446 -``` - -**Ports (defaults):** - -- PostgreSQL: 5433 -- Redis: 6380 -- Web: 3446 - -## Testing - -```bash -# packages/evals tests -cd packages/evals && npx vitest run - -# apps/web-evals tests -cd apps/web-evals && npx vitest run -``` - -## Key Types/Exports from `@roo-code/evals` - -The package exports are defined in [`packages/evals/src/index.ts`](packages/evals/src/index.ts): - -- Database queries: `getRuns`, `getTasks`, `getTaskMetrics`, etc. -- Schema types: `Run`, `Task`, `TaskMetrics` -- Used by both `apps/web-evals` and `apps/web-roo-code` diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c559b5f9a0..bca24b66dde 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,374 +1,5 @@ # Roo Code Changelog -## [3.39.3] - 2026-01-10 - -![3.39.3 Release - Roo Code Router](/releases/3.39.3-release.png) - -- Rename Roo Code Cloud Provider to Roo Code Router for clearer branding (PR #10560 by @roomote) -- Update Roo Code Router service name throughout the codebase (PR #10607 by @mrubens) -- Update router name in types for consistency (PR #10605 by @mrubens) -- Improve ExtensionHost code organization and cleanup (PR #10600 by @cte) -- Add local installation option to CLI release script for testing (PR #10597 by @cte) -- Reorganize CLI file structure for better maintainability (PR #10599 by @cte) -- Add TUI to CLI (PR #10480 by @cte) - -## [3.39.2] - 2026-01-09 - -- Fix: Ensure all tools have consistent strict mode values for Cerebras compatibility (#10334 by @brianboysen51, PR #10589 by @app/roomote) -- Fix: Remove convertToSimpleMessages to restore tool calling for OpenAI-compatible providers (PR #10575 by @daniel-lxs) -- Fix: Make edit_file matching more resilient to prevent false negatives (PR #10585 by @hannesrudolph) -- Fix: Order text parts before tool calls in assistant messages for vscode-lm (PR #10573 by @daniel-lxs) -- Fix: Ensure assistant message content is never undefined for Gemini compatibility (PR #10559 by @daniel-lxs) -- Fix: Merge approval feedback into tool result instead of pushing duplicate messages (PR #10519 by @daniel-lxs) -- Fix: Round-trip Gemini thought signatures for tool calls (PR #10590 by @hannesrudolph) -- Feature: Improve error messaging for stream termination errors from provider (PR #10548 by @daniel-lxs) -- Feature: Add debug setting to settings page for easier troubleshooting (PR #10580 by @hannesrudolph) -- Chore: Disable edit_file tool for Gemini/Vertex providers (PR #10594 by @hannesrudolph) -- Chore: Stop overriding tool allow/deny lists for Gemini (PR #10592 by @hannesrudolph) -- Chore: Change default CLI model to anthropic/claude-opus-4.5 (PR #10544 by @mrubens) -- Chore: Update Terms of Service effective January 9, 2026 (PR #10568 by @mrubens) -- Chore: Move more types to @roo-code/types for CLI support (PR #10583 by @cte) -- Chore: Add functionality to @roo-code/core for CLI support (PR #10584 by @cte) -- Chore: Add slash commands useful for CLI development (PR #10586 by @cte) - -## [3.39.1] - 2026-01-08 - -- Fix: Stabilize file paths during native tool call streaming to prevent path corruption (PR #10555 by @daniel-lxs) -- Fix: Disable Gemini thought signature persistence to prevent corrupted signature errors (PR #10554 by @daniel-lxs) -- Fix: Change minItems from 2 to 1 for Anthropic API compatibility (PR #10551 by @daniel-lxs) - -## [3.39.0] - 2026-01-08 - -![3.39.0 Release - Kangaroo go BRRR](/releases/3.39.0-release.png) - -- Implement sticky provider profile for task-level API config persistence (#8010 by @hannesrudolph, PR #10018 by @hannesrudolph) -- Add support for image file @mentions (PR #10189 by @hannesrudolph) -- Rename YOLO to BRRR (#8574 by @mojomast, PR #10507 by @roomote) -- Add debug-mode proxy routing for debugging API calls (#7042 by @SleeperSmith, PR #10467 by @hannesrudolph) -- Add Kimi K2 thinking model to Fireworks AI provider (#9201 by @kavehsfv, PR #9202 by @roomote) -- Add xhigh reasoning effort to OpenAI compatible endpoints (#10060 by @Soorma718, PR #10061 by @roomote) -- Filter @ mention file search results using .rooignore (#10169 by @jerrill-johnson-bitwerx, PR #10174 by @roomote) -- Add image support documentation to read_file native tool description (#10440 by @nabilfreeman, PR #10442 by @roomote) -- Add zai-glm-4.7 to Cerebras models (PR #10500 by @sebastiand-cerebras) -- VSCode shim and basic CLI for running Roo Code headlessly (PR #10452 by @cte) -- Add CLI installer for headless Roo Code (PR #10474 by @cte) -- Add option to use CLI for evals (PR #10456 by @cte) -- Remember last Roo model selection in web-evals and add evals skill (PR #10470 by @hannesrudolph) -- Tweak the style of follow up suggestion modes (PR #9260 by @mrubens) -- Fix: Handle PowerShell ENOENT error in os-name on Windows (#9859 by @Yang-strive, PR #9897 by @roomote) -- Fix: Make command chaining examples shell-aware for Windows compatibility (#10352 by @AlexNek, PR #10434 by @roomote) -- Fix: Preserve tool_use blocks for all tool_results in kept messages during condensation (PR #10471 by @daniel-lxs) -- Fix: Add additionalProperties: false to MCP tool schemas for OpenAI Responses API (PR #10472 by @daniel-lxs) -- Fix: Prevent duplicate tool_result blocks causing API errors (PR #10497 by @daniel-lxs) -- Fix: Add explicit deduplication for duplicate tool_result blocks (#10465 by @nabilfreeman, PR #10466 by @roomote) -- Fix: Use task stored API config as fallback for rate limit (PR #10266 by @roomote) -- Fix: Remove legacy Claude 2 series models from Bedrock provider (#9220 by @KevinZhao, PR #10501 by @roomote) -- Fix: Add missing description fields for debugProxy configuration (PR #10505 by @roomote) -- Fix: Glitchy kangaroo bounce animation on welcome screen (PR #10035 by @objectiveSee) - -## [3.38.3] - 2026-01-03 - -- Feat: Add option in Context settings to recursively load `.roo/rules` and `AGENTS.md` from subdirectories (PR #10446 by @mrubens) -- Fix: Stop frequent Claude Code sign-ins by hardening OAuth refresh token handling (PR #10410 by @hannesrudolph) -- Fix: Add `maxConcurrentFileReads` limit to native `read_file` tool schema (PR #10449 by @app/roomote) -- Fix: Add type check for `lastMessage.text` in TTS useEffect to prevent runtime errors (PR #10431 by @app/roomote) - -## [3.38.2] - 2025-12-31 - -![3.38.2 Release - Skill Alignment](/releases/3.38.2-release.png) - -- Align skills system with Agent Skills specification (PR #10409 by @hannesrudolph) -- Prevent write_to_file from creating files at truncated paths (PR #10415 by @mrubens and @daniel-lxs) -- Update Cerebras maxTokens to 16384 (PR #10387 by @sebastiand-cerebras) -- Fix rate limit wait display (PR #10389 by @hannesrudolph) -- Remove human-relay provider (PR #10388 by @hannesrudolph) -- Replace Todo Lists video with Context Management video in documentation (PR #10375 by @SannidhyaSah) - -## [3.38.1] - 2025-12-29 - -![3.38.1 Release - Bug Fixes and Stability](/releases/3.38.1-release.png) - -- Fix: Flush pending tool results before condensing context (PR #10379 by @daniel-lxs) -- Fix: Revert mergeToolResultText for OpenAI-compatible providers (PR #10381 by @hannesrudolph) -- Fix: Enforce maxConcurrentFileReads limit in read_file tool (PR #10363 by @roomote) -- Fix: Improve feedback message when read_file is used on a directory (PR #10371 by @roomote) -- Fix: Handle custom tool use similarly to MCP tools for IPC schema purposes (PR #10364 by @jr) -- Fix: Correct GitHub repository URL in marketing page (#10376 by @jishnuteegala, PR #10377 by @roomote) -- Docs: Clarify path to Security Settings in privacy policy (PR #10367 by @roomote) - -## [3.38.0] - 2025-12-27 - -![3.38.0 Release - Skills](/releases/3.38.0-release.png) - -- Add support for [Agent Skills](https://agentskills.io/), enabling reusable packages of prompts, tools, and resources to extend Roo's capabilities (PR #10335 by @mrubens) -- Add optional mode field to slash command front matter, allowing commands to automatically switch to a specific mode when triggered (PR #10344 by @app/roomote) -- Add support for npm packages and .env files to custom tools, allowing custom tools to import dependencies and access environment variables (PR #10336 by @cte) -- Remove simpleReadFileTool feature, streamlining the file reading experience (PR #10254 by @app/roomote) -- Remove OpenRouter Transforms feature (PR #10341 by @app/roomote) -- Fix mergeToolResultText handling in Roo provider (PR #10359 by @mrubens) - -## [3.37.1] - 2025-12-23 - -![3.37.1 Release - Tool Fixes and Provider Improvements](/releases/3.37.1-release.png) - -- Fix: Send native tool definitions by default for OpenAI to ensure proper tool usage (PR #10314 by @hannesrudolph) -- Fix: Preserve reasoning_details shape to prevent malformed responses when processing model output (PR #10313 by @hannesrudolph) -- Fix: Drain queued messages while waiting for ask to prevent message loss (PR #10315 by @hannesrudolph) -- Feat: Add grace retry for empty assistant messages to improve reliability (PR #10297 by @hannesrudolph) -- Feat: Enable mergeToolResultText for all OpenAI-compatible providers for better tool result handling (PR #10299 by @hannesrudolph) -- Feat: Enable mergeToolResultText for Roo Code Router (PR #10301 by @hannesrudolph) -- Feat: Strengthen native tool-use guidance in prompts for improved model behavior (PR #10311 by @hannesrudolph) -- UX: Account-centric signup flow for improved onboarding experience (PR #10306 by @brunobergher) - -## [3.37.0] - 2025-12-22 - -![3.37.0 Release - Custom Tool Calling](/releases/3.37.0-release.png) - -- Add MiniMax M2.1 and improve environment_details handling for Minimax thinking models (PR #10284 by @hannesrudolph) -- Add GLM-4.7 model with thinking mode support for Zai provider (PR #10282 by @hannesrudolph) -- Add experimental custom tool calling - define custom tools that integrate seamlessly with your AI workflow (PR #10083 by @cte) -- Deprecate XML tool protocol selection and force native tool format for new tasks (PR #10281 by @daniel-lxs) -- Fix: Emit tool_call_end events in OpenAI handler when streaming ends (#10275 by @torxeon, PR #10280 by @daniel-lxs) -- Fix: Emit tool_call_end events in BaseOpenAiCompatibleProvider (PR #10293 by @hannesrudolph) -- Fix: Disable strict mode for MCP tools to preserve optional parameters (PR #10220 by @daniel-lxs) -- Fix: Move array-specific properties into anyOf variant in normalizeToolSchema (PR #10276 by @daniel-lxs) -- Fix: Add CRLF line ending normalization to search_replace and search_and_replace tools (PR #10288 by @hannesrudolph) -- Fix: Add graceful fallback for model parsing in Chutes provider (PR #10279 by @hannesrudolph) -- Fix: Enable Requesty refresh models with credentials (PR #10273 by @daniel-lxs) -- Fix: Improve reasoning_details accumulation and serialization (PR #10285 by @hannesrudolph) -- Fix: Preserve reasoning_content in condense summary for DeepSeek-reasoner (PR #10292 by @hannesrudolph) -- Refactor Zai provider to merge environment_details into tool result instead of system message (PR #10289 by @hannesrudolph) -- Remove parallel_tool_calls parameter from litellm provider (PR #10274 by @roomote) -- Add Cloud Team page with comprehensive team management features (PR #10267 by @roomote) -- Add message log deduper utility for evals (PR #10286 by @hannesrudolph) - -## [3.36.16] - 2025-12-19 - -- Fix: Normalize tool schemas for VS Code LM API to resolve error 400 when using VS Code Language Model API providers (PR #10221 by @hannesrudolph) - -## [3.36.15] - 2025-12-19 - -![3.36.15 Release - 1M Context Window Support](/releases/3.36.15-release.png) - -- Add 1M context window beta support for Claude Sonnet 4 on Vertex AI, enabling significantly larger context for complex tasks (PR #10209 by @hannesrudolph) -- Add native tool calling support for LM Studio and Qwen-Code providers, improving compatibility with local models (PR #10208 by @hannesrudolph) -- Add native tool call defaults for OpenAI-compatible providers, expanding native function calling across more configurations (PR #10213 by @hannesrudolph) -- Enable native tool calls for Requesty provider (PR #10211 by @daniel-lxs) -- Improve API error handling and visibility with clearer error messages and better user feedback (PR #10204 by @brunobergher) -- Add downloadable error diagnostics from chat errors, making it easier to troubleshoot and report issues (PR #10188 by @brunobergher) -- Fix refresh models button not properly flushing the cache, ensuring model lists update correctly (#9682 by @tl-hbk, PR #9870 by @pdecat) -- Fix additionalProperties handling for strict mode compatibility, resolving schema validation issues with certain providers (PR #10210 by @daniel-lxs) - -## [3.36.14] - 2025-12-18 - -![3.36.14 Release - Native Tool Calling for Claude on Vertex AI](/releases/3.36.14-release.png) - -- Add native tool calling support for Claude models on Vertex AI, enabling more efficient and reliable tool interactions (PR #10197 by @hannesrudolph) -- Fix JSON Schema format value stripping for OpenAI compatibility, resolving issues with unsupported format values (PR #10198 by @daniel-lxs) -- Improve "no tools used" error handling with graceful retry mechanism for better reliability when tools fail to execute (PR #10196 by @hannesrudolph) - -## [3.36.13] - 2025-12-18 - -![3.36.13 Release - Native Tool Protocol](/releases/3.36.13-release.png) - -- Change default tool protocol from XML to native for improved reliability and performance (PR #10186 by @mrubens) -- Add native tool support for VS Code Language Model API providers (PR #10191 by @daniel-lxs) -- Lock task tool protocol for consistent task resumption, ensuring tasks resume with the same protocol they started with (PR #10192 by @daniel-lxs) -- Replace edit_file tool alias with actual edit_file tool for improved diff editing capabilities (PR #9983 by @hannesrudolph) -- Fix LiteLLM router models by merging default model info for native tool calling support (PR #10187 by @daniel-lxs) -- Add PostHog exception tracking for consecutive mistake errors to improve error monitoring (PR #10193 by @daniel-lxs) - -## [3.36.12] - 2025-12-18 - -![3.36.12 Release - Better telemetry and Bedrock fixes](/releases/3.36.12-release.png) - -- Fix: Add userAgentAppId to Bedrock embedder for code indexing (#10165 by @jackrein, PR #10166 by @roomote) -- Update OpenAI and Gemini tool preferences for improved model behavior (PR #10170 by @hannesrudolph) -- Extract error messages from JSON payloads for better PostHog error grouping (PR #10163 by @daniel-lxs) - -## [3.36.11] - 2025-12-17 - -![3.36.11 Release - Native Tool Calling Enhancements](/releases/3.36.11-release.png) - -- Add support for Claude Code Provider native tool calling, improving tool execution performance and reliability (PR #10077 by @hannesrudolph) -- Enable native tool calling by default for Z.ai models for better model compatibility (PR #10158 by @app/roomote) -- Enable native tools by default for OpenAI compatible provider to improve tool calling support (PR #10159 by @daniel-lxs) -- Fix: Normalize MCP tool schemas for Bedrock and OpenAI strict mode to ensure proper tool compatibility (PR #10148 by @daniel-lxs) -- Fix: Remove dots and colons from MCP tool names for Bedrock compatibility (PR #10152 by @daniel-lxs) -- Fix: Convert tool_result to XML text when native tools disabled for Bedrock (PR #10155 by @daniel-lxs) -- Fix: Refresh Roo models cache with session token on auth state change to resolve model list refresh issues (PR #10156 by @daniel-lxs) -- Fix: Support AWS GovCloud and China region ARNs in Bedrock provider for expanded regional support (PR #10157 by @app/roomote) - -## [3.36.10] - 2025-12-17 - -![3.36.10 Release - Gemini 3 Flash Preview](/releases/3.36.10-release.png) - -- Add support for Gemini 3 Flash Preview model in the Gemini provider (PR #10151 by @hannesrudolph) -- Implement interleaved thinking mode for DeepSeek Reasoner, enabling streaming reasoning output (PR #9969 by @hannesrudolph) -- Fix: Preserve reasoning_content during tool call sequences in DeepSeek (PR #10141 by @hannesrudolph) -- Fix: Correct token counting for context truncation display (PR #9961 by @hannesrudolph) -- Update Next.js dependency to ~15.2.8 (PR #10140 by @jr) - -## [3.36.9] - 2025-12-15 - -![3.36.9 Release - Cross-Provider Compatibility](/releases/3.36.9-release.png) - -- Fix: Normalize tool call IDs for cross-provider compatibility via OpenRouter, ensuring consistent handling across different AI providers (PR #10102 by @daniel-lxs) -- Fix: Add additionalProperties: false to nested MCP tool schemas, improving schema validation and preventing unexpected properties (PR #10109 by @daniel-lxs) -- Fix: Validate tool_result IDs in delegation resume flow, preventing errors when resuming delegated tasks (PR #10135 by @daniel-lxs) -- Feat: Add full error details to streaming failure dialog, providing more comprehensive information for debugging streaming issues (PR #10131 by @roomote) -- Feat: Improve evals UI with tool groups and duration fix, enhancing the evaluation interface organization and timing accuracy (PR #10133 by @hannesrudolph) - -## [3.36.8] - 2025-12-16 - -![3.36.8 Release - Native Tools Enabled by Default](/releases/3.36.8-release.png) - -- Implement incremental token-budgeted file reading for smarter, more efficient file content retrieval (PR #10052 by @jr) -- Enable native tools by default for multiple providers including OpenAI, Azure, Google, Vertex, and more (PR #10059 by @daniel-lxs) -- Enable native tools by default for Anthropic and add telemetry tracking for tool format usage (PR #10021 by @daniel-lxs) -- Fix: Prevent race condition from deleting wrong API messages during streaming (PR #10113 by @hannesrudolph) -- Fix: Prevent duplicate MCP tools error by deduplicating servers at source (PR #10096 by @daniel-lxs) -- Remove strict ARN validation for Bedrock custom ARN users allowing more flexibility (#10108 by @wisestmumbler, PR #10110 by @roomote) -- Add metadata to error details dialog for improved debugging (PR #10050 by @roomote) -- Add configuration to control public sharing feature (PR #10105 by @mrubens) -- Remove description from Bedrock service tiers for cleaner UI (PR #10118 by @mrubens) -- Fix: Correct link to provider pricing page on web (PR #10107 by @brunobergher) - -## [3.36.7] - 2025-12-15 - -- Improve tool configuration for OpenAI models in OpenRouter (PR #10082 by @hannesrudolph) -- Capture more detailed provider-specific error information from OpenRouter for better debugging (PR #10073 by @jr) -- Add Amazon Nova 2 Lite model to Bedrock provider (#9802 by @Smartsheet-JB-Brown, PR #9830 by @roomote) -- Add AWS Bedrock service tier support (#9874 by @Smartsheet-JB-Brown, PR #9955 by @roomote) -- Remove auto-approve toggles for to-do and retry actions to simplify the approval workflow (PR #10062 by @hannesrudolph) -- Move isToolAllowedForMode out of shared directory for better code organization (PR #10089 by @cte) -- Improve run logs and formatters in web-evals for better evaluation tracking (PR #10081 by @hannesrudolph) - -## [3.36.6] - 2025-12-12 - -![3.36.6 Release - Tool Alias Support](/releases/3.36.6-release.png) - -- Add tool alias support for model-specific tool customization, allowing users to configure how tools are presented to different AI models (PR #9989 by @daniel-lxs) -- Sanitize MCP server and tool names for API compatibility, ensuring special characters don't cause issues with API calls (PR #10054 by @daniel-lxs) -- Improve auto-approve timer visibility in follow-up suggestions for better user awareness of pending actions (PR #10048 by @brunobergher) -- Fix: Cancel auto-approval timeout when user starts typing, preventing accidental auto-approvals during user interaction (PR #9937 by @roomote) -- Add WorkspaceTaskVisibility type for organization cloud settings to support team visibility controls (PR #10020 by @roomote) -- Fix: Extract raw error message from OpenRouter metadata for clearer error reporting (PR #10039 by @daniel-lxs) -- Fix: Show tool protocol dropdown for LiteLLM provider, restoring missing configuration option (PR #10053 by @daniel-lxs) - -## [3.36.5] - 2025-12-11 - -![3.36.5 Release - GPT-5.2](/releases/3.36.5-release.png) - -- Add: GPT-5.2 model to openai-native provider (PR #10024 by @hannesrudolph) -- Add: Toggle for Enter key behavior in chat input allowing users to configure whether Enter sends or creates new line (#8555 by @lmtr0, PR #10002 by @hannesrudolph) -- Add: App version to telemetry exception captures and filter 402 errors (PR #9996 by @daniel-lxs) -- Fix: Handle empty Gemini responses and reasoning loops to prevent infinite retries (PR #10007 by @hannesrudolph) -- Fix: Add missing tool_result blocks to prevent API errors when tool results are expected (PR #10015 by @daniel-lxs) -- Fix: Filter orphaned tool_results when more results than tool_uses to prevent message validation errors (PR #10027 by @daniel-lxs) -- Fix: Add general API endpoints for Z.ai provider (#9879 by @richtong, PR #9894 by @roomote) -- Fix: Apply versioned settings on nightly builds (PR #9997 by @hannesrudolph) -- Remove: Glama provider (PR #9801 by @hannesrudolph) -- Remove: Deprecated list_code_definition_names tool (PR #10005 by @hannesrudolph) - -## [3.36.4] - 2025-12-10 - -![3.36.4 Release - Error Details Modal](/releases/3.36.4-release.png) - -- Add error details modal with on-demand display for improved error visibility when debugging issues (PR #9985 by @roomote) -- Fix: Prevent premature rawChunkTracker clearing for MCP tools, improving reliability of MCP tool streaming (PR #9993 by @daniel-lxs) -- Fix: Filter out 429 rate limit errors from API error telemetry for cleaner metrics (PR #9987 by @daniel-lxs) -- Fix: Correct TODO list display order in chat view to show items in proper sequence (PR #9991 by @roomote) - -## [3.36.3] - 2025-12-09 - -![3.36.3 Release](/releases/3.36.3-release.png) - -- Refactor: Unified context-management architecture with improved UX for better context control (PR #9795 by @hannesrudolph) -- Add new `search_replace` native tool for single-replacement operations with improved editing precision (PR #9918 by @hannesrudolph) -- Streaming tool stats and token usage throttling for better real-time feedback during generation (PR #9926 by @hannesrudolph) -- Add versioned settings support with minPluginVersion gating for Roo provider (PR #9934 by @hannesrudolph) -- Make Architect mode save plans to `/plans` directory and gitignore it (PR #9944 by @brunobergher) -- Add announcement support CTA and social icons to UI (PR #9945 by @hannesrudolph) -- Add ability to save screenshots from the browser tool (PR #9963 by @mrubens) -- Refactor: Decouple tools from system prompt for cleaner architecture (PR #9784 by @daniel-lxs) -- Update DeepSeek models to V3.2 with new pricing (PR #9962 by @hannesrudolph) -- Add minimal and medium reasoning effort levels for Gemini models (PR #9973 by @hannesrudolph) -- Update xAI models catalog with latest model options (PR #9872 by @hannesrudolph) -- Add DeepSeek V3-2 support for Baseten provider (PR #9861 by @AlexKer) -- Tweaks to Baseten model definitions for better defaults (PR #9866 by @mrubens) -- Fix: Add xhigh reasoning effort support for gpt-5.1-codex-max (#9891 by @andrewginns, PR #9900 by @andrewginns) -- Fix: Add Kimi, MiniMax, and Qwen model configurations for Bedrock (#9902 by @jbearak, PR #9905 by @app/roomote) -- Configure tool preferences for xAI models (PR #9923 by @hannesrudolph) -- Default to using native tools when supported on OpenRouter (PR #9878 by @mrubens) -- Fix: Exclude apply_diff from native tools when diffEnabled is false (#9919 by @denis-kudelin, PR #9920 by @app/roomote) -- Fix: Always show tool protocol selector for openai-compatible provider (#9965 by @bozoweed, PR #9966 by @hannesrudolph) -- Fix: Respect explicit supportsReasoningEffort array values for proper model configuration (PR #9970 by @hannesrudolph) -- Add timeout configuration to OpenAI Compatible Provider Client (PR #9898 by @dcbartlett) -- Revert default tool protocol change from xml to native for stability (PR #9956 by @mrubens) -- Remove defaultTemperature from Roo provider configuration (PR #9932 by @mrubens) -- Improve OpenAI error messages to be more useful for debugging (PR #9639 by @mrubens) -- Better error logs for parseToolCall exceptions (PR #9857 by @cte) -- Improve cloud job error logging for RCC provider errors (PR #9924 by @cte) -- Fix: Display actual API error message instead of generic text on retry (PR #9954 by @hannesrudolph) -- Add API error telemetry to OpenRouter provider for better diagnostics (PR #9953 by @daniel-lxs) -- Fix: Sanitize removed/invalid API providers to prevent infinite loop (PR #9869 by @hannesrudolph) -- Fix: Use foreground color for context-management icons (PR #9912 by @hannesrudolph) -- Fix: Suppress 'ask promise was ignored' error in handleError (PR #9914 by @daniel-lxs) -- Fix: Process finish_reason to emit tool_call_end events properly (PR #9927 by @daniel-lxs) -- Fix: Add finish_reason processing to xai.ts provider (PR #9929 by @daniel-lxs) -- Fix: Validate and fix tool_result IDs before API requests (PR #9952 by @daniel-lxs) -- Fix: Return undefined instead of 0 for disabled API timeout (PR #9960 by @hannesrudolph) -- Stop making unnecessary count_tokens requests for better performance (PR #9884 by @mrubens) -- Refactor: Consolidate ThinkingBudget components and fix disable handling (PR #9930 by @hannesrudolph) -- Forbid time estimates in architect mode for more focused planning (PR #9931 by @app/roomote) -- Web: Add product pages (PR #9865 by @brunobergher) -- Make eval runs deleteable in the web UI (PR #9909 by @mrubens) -- Feat: Change defaultToolProtocol default from xml to native (later reverted) (PR #9892 by @app/roomote) - -## [3.36.2] - 2025-12-04 - -![3.36.2 Release - Dynamic API Settings](/releases/3.36.2-release.png) - -- Restrict GPT-5 tool set to apply_patch for improved compatibility (PR #9853 by @hannesrudolph) -- Add dynamic settings support for Roo models from API, allowing model-specific configurations to be fetched dynamically (PR #9852 by @hannesrudolph) -- Fix: Resolve Chutes provider model fetching issue (PR #9854 by @cte) - -## [3.36.1] - 2025-12-04 - -![3.36.1 Release - Message Management & Stability Improvements](/releases/3.36.1-release.png) - -- Add MessageManager layer for centralized history coordination, fixing message synchronization issues (PR #9842 by @hannesrudolph) -- Fix: Prevent cascading truncation loop by only truncating visible messages (PR #9844 by @hannesrudolph) -- Fix: Handle unknown/invalid native tool calls to prevent extension freeze (PR #9834 by @daniel-lxs) -- Always enable reasoning for models that require it (PR #9836 by @cte) -- ChatView: Smoother stick-to-bottom behavior during streaming (PR #8999 by @hannesrudolph) -- UX: Improved error messages and documentation links (PR #9777 by @brunobergher) -- Fix: Overly round follow-up question suggestions styling (PR #9829 by @brunobergher) -- Add symlink support for slash commands in .roo/commands folder (PR #9838 by @mrubens) -- Ignore input to the execa terminal process for safer command execution (PR #9827 by @mrubens) -- Be safer about large file reads (PR #9843 by @jr) -- Add gpt-5.1-codex-max model to OpenAI provider (PR #9848 by @hannesrudolph) -- Evals UI: Add filtering, bulk delete, tool consolidation, and run notes (PR #9837 by @hannesrudolph) -- Evals UI: Add multi-model launch and UI improvements (PR #9845 by @hannesrudolph) -- Web: New pricing page (PR #9821 by @brunobergher) - -## [3.36.0] - 2025-12-04 - -![3.36.0 Release - Rewind Kangaroo](/releases/3.36.0-release.png) - -- Fix: Restore context when rewinding after condense (#8295 by @hannesrudolph, PR #9665 by @hannesrudolph) -- Add reasoning_details support to Roo provider for enhanced model reasoning visibility (PR #9796 by @app/roomote) -- Default to native tools for all models in the Roo provider for improved performance (PR #9811 by @mrubens) -- Enable search_and_replace for Minimax models (PR #9780 by @mrubens) -- Fix: Resolve Vercel AI Gateway model fetching issues (PR #9791 by @cte) -- Fix: Apply conservative max tokens for Cerebras provider (PR #9804 by @sebastiand-cerebras) -- Fix: Remove omission detection logic to eliminate false positives (#9785 by @Michaelzag, PR #9787 by @app/roomote) -- Refactor: Remove deprecated insert_content tool (PR #9751 by @daniel-lxs) -- Chore: Hide parallel tool calls experiment and disable feature (PR #9798 by @hannesrudolph) -- Update next.js documentation site dependencies (PR #9799 by @jr) -- Fix: Correct download count display on homepage (PR #9807 by @mrubens) - ## [3.35.5] - 2025-12-03 - Feat: Add provider routing selection for OpenRouter embeddings (#9144 by @SannidhyaSah, PR #9693 by @SannidhyaSah) @@ -410,7 +41,7 @@ - Native tool calling support expanded across many providers: Bedrock (PR #9698 by @mrubens), Cerebras (PR #9692 by @mrubens), Chutes with auto-detection from API (PR #9715 by @daniel-lxs), DeepInfra (PR #9691 by @mrubens), DeepSeek and Doubao (PR #9671 by @daniel-lxs), Groq (PR #9673 by @daniel-lxs), LiteLLM (PR #9719 by @daniel-lxs), Ollama (PR #9696 by @mrubens), OpenAI-compatible providers (PR #9676 by @daniel-lxs), Requesty (PR #9672 by @daniel-lxs), Unbound (PR #9699 by @mrubens), Vercel AI Gateway (PR #9697 by @mrubens), Vertex Gemini (PR #9678 by @daniel-lxs), and xAI with new Grok 4 Fast and Grok 4.1 Fast models (PR #9690 by @mrubens) - Fix: Preserve tool_use blocks in summary for parallel tool calls (#9700 by @SilentFlower, PR #9714 by @SilentFlower) - Default Grok Code Fast to native tools for better performance (PR #9717 by @mrubens) -- UX improvements to the Roo Code Router-centric onboarding flow (PR #9709 by @brunobergher) +- UX improvements to the Roo Code Cloud provider-centric onboarding flow (PR #9709 by @brunobergher) - UX toolbar cleanup and settings consolidation for a cleaner interface (PR #9710 by @brunobergher) - Add model-specific tool customization via `excludedTools` and `includedTools` configuration (PR #9641 by @daniel-lxs) - Add new `apply_patch` native tool for more efficient file editing operations (PR #9663 by @hannesrudolph) @@ -509,7 +140,7 @@ - Show the prompt for image generation in the UI (PR #9505 by @mrubens) - Fix double todo list display issue (PR #9517 by @mrubens) - Add tracking for cloud synced messages (PR #9518 by @mrubens) -- Enable the Roo Code Router in evals (PR #9492 by @cte) +- Enable the Roo Code Cloud provider in evals (PR #9492 by @cte) ## [3.34.0] - 2025-11-21 @@ -569,7 +200,7 @@ ## [3.33.0] - 2025-11-18 -![3.33.0 Release - Twin Kangaroos and the Gemini Constellation](/releases/3.33.0-release.png) +![v3.33.0 Release - Twin Kangaroos and the Gemini Constellation](/releases/v3.33.0-release.png) - Add Gemini 3 Pro Preview model (PR #9357 by @hannesrudolph) - Improve Google Gemini defaults with better temperature and cost reporting (PR #9327 by @hannesrudolph) @@ -589,7 +220,7 @@ - Use VSCode theme color for outline button borders (PR #9336 by @app/roomote) - Replace broken badgen.net badges with shields.io (PR #9318 by @app/roomote) - Add max git status files setting to evals (PR #9322 by @mrubens) -- Roo Code Router pricing page and changes elsewhere (PR #9195 by @brunobergher) +- Roo Code Cloud Provider pricing page and changes elsewhere (PR #9195 by @brunobergher) ## [3.32.1] - 2025-11-14 @@ -615,7 +246,7 @@ ![3.31.3 Release - Kangaroo Decrypting a Message](/releases/3.31.3-release.png) - Fix: OpenAI Native encrypted_content handling and remove gpt-5-chat-latest verbosity flag (#9225 by @politsin, PR by @hannesrudolph) -- Fix: Roo Code Router Anthropic input token normalization to avoid double-counting (thanks @hannesrudolph!) +- Fix: Roo Code Cloud provider Anthropic input token normalization to avoid double-counting (thanks @hannesrudolph!) - Refactor: Rename sliding-window to context-management and truncateConversationIfNeeded to manageContext (thanks @hannesrudolph!) ## [3.31.2] - 2025-11-12 @@ -755,7 +386,7 @@ - Add token-budget based file reading with intelligent preview to avoid context overruns (thanks @daniel-lxs!) - Enable browser-use tool for all image-capable models (#8116 by @hannesrudolph, PR by @app/roomote!) -- Add dynamic model loading for Roo Code Router (thanks @app/roomote!) +- Add dynamic model loading for Roo Code Cloud provider (thanks @app/roomote!) - Fix: Respect nested .gitignore files in search_files (#7921 by @hannesrudolph, PR by @daniel-lxs) - Fix: Preserve trailing newlines in stripLineNumbers for apply_diff (#8020 by @liyi3c, PR by @app/roomote) - Fix: Exclude max tokens field for models that don't support it in export (#7944 by @hannesrudolph, PR by @elianiva) @@ -913,7 +544,7 @@ - UX: Responsive Auto-Approve (thanks @brunobergher!) - Add telemetry retry queue for network resilience (thanks @daniel-lxs!) - Fix: Transform keybindings in nightly build to fix command+y shortcut (thanks @app/roomote!) -- New code-supernova stealth model in the Roo Code Router (thanks @mrubens!) +- New code-supernova stealth model in the Roo Code Cloud provider (thanks @mrubens!) ## [3.28.3] - 2025-09-16 @@ -1124,11 +755,11 @@ ## [3.25.19] - 2025-08-19 -- Fix issue where new users couldn't select the Roo Code Router (thanks @daniel-lxs!) +- Fix issue where new users couldn't select the Roo Code Cloud provider (thanks @daniel-lxs!) ## [3.25.18] - 2025-08-19 -- Add new stealth Sonic model through the Roo Code Router +- Add new stealth Sonic model through the Roo Code Cloud provider - Fix: respect enableReasoningEffort setting when determining reasoning usage (#7048 by @ikbencasdoei, PR by @app/roomote) - Fix: prevent duplicate LM Studio models with case-insensitive deduplication (#6954 by @fbuechler, PR by @daniel-lxs) - Feat: simplify ask_followup_question prompt documentation (thanks @daniel-lxs!) diff --git a/README.md b/README.md index 75f37762f93..9e98cd88456 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ Learn more: [Using Modes](https://docs.roocode.com/basic-usage/using-modes) • | | | | | :-----------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------: | |
Installing Roo Code |
Configuring Profiles |
Codebase Indexing | -|
Custom Modes |
Checkpoints |
Context Management | +|
Custom Modes |
Checkpoints |
Todo Lists |

diff --git a/apps/cli/CHANGELOG.md b/apps/cli/CHANGELOG.md deleted file mode 100644 index c2682a591f0..00000000000 --- a/apps/cli/CHANGELOG.md +++ /dev/null @@ -1,116 +0,0 @@ -# Changelog - -All notable changes to the `@roo-code/cli` package will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [0.0.45] - 2026-01-08 - -### Changed - -- **Major Refactor**: Extracted ~1400 lines from [`App.tsx`](src/ui/App.tsx) into reusable hooks and utilities for better maintainability: - - - [`useExtensionHost`](src/ui/hooks/useExtensionHost.ts) - Extension host connection and lifecycle management - - [`useMessageHandlers`](src/ui/hooks/useMessageHandlers.ts) - Message processing and state updates - - [`useTaskSubmit`](src/ui/hooks/useTaskSubmit.ts) - Task submission logic - - [`useGlobalInput`](src/ui/hooks/useGlobalInput.ts) - Global keyboard shortcut handling - - [`useFollowupCountdown`](src/ui/hooks/useFollowupCountdown.ts) - Auto-approval countdown logic - - [`useFocusManagement`](src/ui/hooks/useFocusManagement.ts) - Input focus state management - - [`usePickerHandlers`](src/ui/hooks/usePickerHandlers.ts) - Picker component event handling - - [`uiStateStore`](src/ui/stores/uiStateStore.ts) - UI-specific state (showExitHint, countdown, etc.) - - Tool data utilities ([`extractToolData`](src/ui/utils/toolDataUtils.ts), `formatToolOutput`, etc.) - - [`HorizontalLine`](src/ui/components/HorizontalLine.tsx) component - -- **Performance Optimizations**: - - - Added RAF-style scroll throttling to reduce state updates - - Stabilized `useExtensionHost` hook return values with `useCallback`/`useMemo` - - Added streaming message debouncing to batch rapid partial updates - - Added shallow array equality checks to prevent unnecessary re-renders - -- Simplified [`ModeTool`](src/ui/components/tools/ModeTool.tsx) layout to horizontal with mode suffix -- Simplified logging by removing verbose debug output and adding first/last partial message logging pattern -- Updated Nerd Font icon codepoints in [`Icon`](src/ui/components/Icon.tsx) component - -### Added - -- `#` shortcut in help trigger for quick access to task history autocomplete - -### Fixed - -- Fixed a crash in message handling -- Added protected file warning in tool approval prompts -- Enabled `alwaysAllowWriteProtected` for non-interactive mode - -### Removed - -- Removed unused `renderLogger.ts` utility file - -### Tests - -- Updated extension-host tests to expect `[Tool Request]` format -- Updated Icon tests to expect single-char Nerd Font icons - -## [0.0.44] - 2026-01-08 - -### Added - -- **Tool Renderer Components**: Specialized renderers for displaying tool outputs with optimized formatting for each tool type. Each renderer provides a focused view of its data structure. - - - [`FileReadTool`](src/ui/components/tools/FileReadTool.tsx) - Display file read operations with syntax highlighting - - [`FileWriteTool`](src/ui/components/tools/FileWriteTool.tsx) - Show file write/edit operations with diff views - - [`SearchTool`](src/ui/components/tools/SearchTool.tsx) - Render search results with context - - [`CommandTool`](src/ui/components/tools/CommandTool.tsx) - Display command execution with output - - [`BrowserTool`](src/ui/components/tools/BrowserTool.tsx) - Show browser automation actions - - [`ModeTool`](src/ui/components/tools/ModeTool.tsx) - Display mode switching operations - - [`CompletionTool`](src/ui/components/tools/CompletionTool.tsx) - Show task completion status - - [`GenericTool`](src/ui/components/tools/GenericTool.tsx) - Fallback renderer for other tools - -- **History Trigger**: New `#` trigger for task history autocomplete with fuzzy search support. Type `#` at the start of a line to browse and resume previous tasks. - - - [`HistoryTrigger.tsx`](src/ui/components/autocomplete/triggers/HistoryTrigger.tsx) - Trigger implementation with fuzzy filtering - - Shows task status, mode, and relative timestamps - - Supports keyboard navigation for quick task selection - -- **Release Confirmation Prompt**: The release script now prompts for confirmation before creating a release. - -### Fixed - -- Task history picker selection and navigation issues -- Mode switcher keyboard handling bug - -### Changed - -- Reorganized test files into `__tests__` directories for better project structure -- Refactored utility modules into dedicated `utils/` directory - -## [0.0.43] - 2026-01-07 - -### Added - -- **Toast Notification System**: New toast notifications for user feedback with support for info, success, warning, and error types. Toasts auto-dismiss after a configurable duration and are managed via Zustand store. - - - New [`ToastDisplay`](src/ui/components/ToastDisplay.tsx) component for rendering toast messages - - New [`useToast`](src/ui/hooks/useToast.ts) hook for managing toast state and displaying notifications - -- **Global Input Sequences Registry**: Centralized system for handling keyboard shortcuts at the application level, preventing conflicts with input components. - - - New [`globalInputSequences.ts`](src/ui/utils/globalInputSequences.ts) utility module - - Support for Kitty keyboard protocol (CSI u encoding) for better terminal compatibility - - Built-in sequences for `Ctrl+C` (exit) and `Ctrl+M` (mode cycling) - -- **Local Tarball Installation**: The install script now supports installing from a local tarball via the `ROO_LOCAL_TARBALL` environment variable, useful for offline installation or testing pre-release builds. - -### Changed - -- **MultilineTextInput**: Updated to respect global input sequences, preventing the component from consuming shortcuts meant for application-level handling. - -### Tests - -- Added comprehensive tests for the toast notification system -- Added tests for global input sequence matching - -## [0.0.42] - 2025-01-07 - -The cli is alive! diff --git a/apps/cli/README.md b/apps/cli/README.md deleted file mode 100644 index d4405364405..00000000000 --- a/apps/cli/README.md +++ /dev/null @@ -1,262 +0,0 @@ -# @roo-code/cli - -Command Line Interface for Roo Code - Run the Roo Code agent from the terminal without VSCode. - -## Overview - -This CLI uses the `@roo-code/vscode-shim` package to provide a VSCode API compatibility layer, allowing the main Roo Code extension to run in a Node.js environment. - -## Installation - -### Quick Install (Recommended) - -Install the Roo Code CLI with a single command: - -```bash -curl -fsSL https://raw.githubusercontent.com/RooCodeInc/Roo-Code/main/apps/cli/install.sh | sh -``` - -**Requirements:** - -- Node.js 20 or higher -- macOS (Intel or Apple Silicon) or Linux (x64 or ARM64) - -**Custom installation directory:** - -```bash -ROO_INSTALL_DIR=/opt/roo-code ROO_BIN_DIR=/usr/local/bin curl -fsSL ... | sh -``` - -**Install a specific version:** - -```bash -ROO_VERSION=0.1.0 curl -fsSL https://raw.githubusercontent.com/RooCodeInc/Roo-Code/main/apps/cli/install.sh | sh -``` - -### Updating - -Re-run the install script to update to the latest version: - -```bash -curl -fsSL https://raw.githubusercontent.com/RooCodeInc/Roo-Code/main/apps/cli/install.sh | sh -``` - -### Uninstalling - -```bash -rm -rf ~/.roo/cli ~/.local/bin/roo -``` - -### Development Installation - -For contributing or development: - -```bash -# From the monorepo root. -pnpm install - -# Build the main extension first. -pnpm --filter roo-cline bundle - -# Build the cli. -pnpm --filter @roo-code/cli build -``` - -## Usage - -### Interactive Mode (Default) - -By default, the CLI prompts for approval before executing actions: - -```bash -export OPENROUTER_API_KEY=sk-or-v1-... - -roo ~/Documents/my-project -P "What is this project?" -``` - -You can also run without a prompt and enter it interactively in TUI mode: - -```bash -roo ~/Documents/my-project -``` - -In interactive mode: - -- Tool executions prompt for yes/no approval -- Commands prompt for yes/no approval -- Followup questions show suggestions and wait for user input -- Browser and MCP actions prompt for approval - -### Non-Interactive Mode (`-y`) - -For automation and scripts, use `-y` to auto-approve all actions: - -```bash -roo ~/Documents/my-project -y -P "Refactor the utils.ts file" -``` - -In non-interactive mode: - -- Tool, command, browser, and MCP actions are auto-approved -- Followup questions show a 60-second timeout, then auto-select the first suggestion -- Typing any key cancels the timeout and allows manual input - -### Roo Code Cloud Authentication - -To use Roo Code Cloud features (like the provider proxy), you need to authenticate: - -```bash -# Log in to Roo Code Cloud (opens browser) -roo auth login - -# Check authentication status -roo auth status - -# Log out -roo auth logout -``` - -The `auth login` command: - -1. Opens your browser to authenticate with Roo Code Cloud -2. Receives a secure token via localhost callback -3. Stores the token in `~/.config/roo/credentials.json` - -Tokens are valid for 90 days. The CLI will prompt you to re-authenticate when your token expires. - -**Authentication Flow:** - -``` -┌──────┐ ┌─────────┐ ┌───────────────┐ -│ CLI │ │ Browser │ │ Roo Code Cloud│ -└──┬───┘ └────┬────┘ └───────┬───────┘ - │ │ │ - │ Open auth URL │ │ - │─────────────────>│ │ - │ │ │ - │ │ Authenticate │ - │ │─────────────────────>│ - │ │ │ - │ │<─────────────────────│ - │ │ Token via callback │ - │<─────────────────│ │ - │ │ │ - │ Store token │ │ - │ │ │ -``` - -## Options - -| Option | Description | Default | -| --------------------------------- | --------------------------------------------------------------------------------------- | ----------------------------- | -| `[workspace]` | Workspace path to operate in (positional argument) | Current directory | -| `-P, --prompt ` | The prompt/task to execute (optional in TUI mode) | None | -| `-e, --extension ` | Path to the extension bundle directory | Auto-detected | -| `-d, --debug` | Enable debug output (includes detailed debug information, prompts, paths, etc) | `false` | -| `-x, --exit-on-complete` | Exit the process when task completes (useful for testing) | `false` | -| `-y, --yes` | Non-interactive mode: auto-approve all actions | `false` | -| `-k, --api-key ` | API key for the LLM provider | From env var | -| `-p, --provider ` | API provider (anthropic, openai, openrouter, etc.) | `openrouter` | -| `-m, --model ` | Model to use | `anthropic/claude-sonnet-4.5` | -| `-M, --mode ` | Mode to start in (code, architect, ask, debug, etc.) | `code` | -| `-r, --reasoning-effort ` | Reasoning effort level (unspecified, disabled, none, minimal, low, medium, high, xhigh) | `medium` | -| `--ephemeral` | Run without persisting state (uses temporary storage) | `false` | -| `--no-tui` | Disable TUI, use plain text output | `false` | - -## Auth Commands - -| Command | Description | -| ----------------- | ---------------------------------- | -| `roo auth login` | Authenticate with Roo Code Cloud | -| `roo auth logout` | Clear stored authentication token | -| `roo auth status` | Show current authentication status | - -## Environment Variables - -The CLI will look for API keys in environment variables if not provided via `--api-key`: - -| Provider | Environment Variable | -| ------------- | -------------------- | -| anthropic | `ANTHROPIC_API_KEY` | -| openai | `OPENAI_API_KEY` | -| openrouter | `OPENROUTER_API_KEY` | -| google/gemini | `GOOGLE_API_KEY` | -| ... | ... | - -**Authentication Environment Variables:** - -| Variable | Description | -| ----------------- | -------------------------------------------------------------------- | -| `ROO_WEB_APP_URL` | Override the Roo Code Cloud URL (default: `https://app.roocode.com`) | - -## Architecture - -``` -┌─────────────────┐ -│ CLI Entry │ -│ (index.ts) │ -└────────┬────────┘ - │ - ▼ -┌─────────────────┐ -│ ExtensionHost │ -│ (extension- │ -│ host.ts) │ -└────────┬────────┘ - │ - ┌────┴────┐ - │ │ - ▼ ▼ -┌───────┐ ┌──────────┐ -│vscode │ │Extension │ -│-shim │ │ Bundle │ -└───────┘ └──────────┘ -``` - -## How It Works - -1. **CLI Entry Point** (`index.ts`): Parses command line arguments and initializes the ExtensionHost - -2. **ExtensionHost** (`extension-host.ts`): - - - Creates a VSCode API mock using `@roo-code/vscode-shim` - - Intercepts `require('vscode')` to return the mock - - Loads and activates the extension bundle - - Manages bidirectional message flow - -3. **Message Flow**: - - CLI → Extension: `emit("webviewMessage", {...})` - - Extension → CLI: `emit("extensionWebviewMessage", {...})` - -## Development - -```bash -# Watch mode for development -pnpm dev - -# Run tests -pnpm test - -# Type checking -pnpm check-types - -# Linting -pnpm lint -``` - -## Releasing - -To create a new release, execute the /cli-release slash command: - -```bash -roo ~/Documents/Roo-Code -P "/cli-release" -y -``` - -The workflow will: - -1. Bump the version -2. Update the CHANGELOG -3. Build the extension and CLI -4. Create a platform-specific tarball (for your current OS/architecture) -5. Test the install script -6. Create a GitHub release with the tarball attached diff --git a/apps/cli/docs/AGENT_LOOP.md b/apps/cli/docs/AGENT_LOOP.md deleted file mode 100644 index a7b1d9eed40..00000000000 --- a/apps/cli/docs/AGENT_LOOP.md +++ /dev/null @@ -1,355 +0,0 @@ -# CLI Agent Loop - -This document explains how the Roo Code CLI detects and tracks the agent loop state. - -## Overview - -The CLI needs to know when the agent is: - -- **Running** (actively processing) -- **Streaming** (receiving content from the API) -- **Waiting for input** (needs user approval or answer) -- **Idle** (task completed or failed) - -This is accomplished by analyzing the messages the extension sends to the client. - -## The Message Model - -All agent activity is communicated through **ClineMessages** - a stream of timestamped messages that represent everything the agent does. - -### Message Structure - -```typescript -interface ClineMessage { - ts: number // Unique timestamp identifier - type: "ask" | "say" // Message category - ask?: ClineAsk // Specific ask type (when type="ask") - say?: ClineSay // Specific say type (when type="say") - text?: string // Message content - partial?: boolean // Is this message still streaming? -} -``` - -### Two Types of Messages - -| Type | Purpose | Blocks Agent? | -| ------- | ---------------------------------------------- | ------------- | -| **say** | Informational - agent is telling you something | No | -| **ask** | Interactive - agent needs something from you | Usually yes | - -## The Key Insight - -> **The agent loop stops whenever the last message is an `ask` type (with `partial: false`).** - -The specific `ask` value tells you exactly what the agent needs. - -## Ask Categories - -The CLI categorizes asks into four groups: - -### 1. Interactive Asks → `WAITING_FOR_INPUT` state - -These require user action to continue: - -| Ask Type | What It Means | Required Response | -| ----------------------- | --------------------------------- | ----------------- | -| `tool` | Wants to edit/create/delete files | Approve or Reject | -| `command` | Wants to run a terminal command | Approve or Reject | -| `followup` | Asking a question | Text answer | -| `browser_action_launch` | Wants to use the browser | Approve or Reject | -| `use_mcp_server` | Wants to use an MCP server | Approve or Reject | - -### 2. Idle Asks → `IDLE` state - -These indicate the task has stopped: - -| Ask Type | What It Means | Response Options | -| ------------------------------- | --------------------------- | --------------------------- | -| `completion_result` | Task completed successfully | New task or feedback | -| `api_req_failed` | API request failed | Retry or new task | -| `mistake_limit_reached` | Too many errors | Continue anyway or new task | -| `auto_approval_max_req_reached` | Auto-approval limit hit | Continue manually or stop | -| `resume_completed_task` | Viewing completed task | New task | - -### 3. Resumable Asks → `RESUMABLE` state - -| Ask Type | What It Means | Response Options | -| ------------- | ------------------------- | ----------------- | -| `resume_task` | Task paused mid-execution | Resume or abandon | - -### 4. Non-Blocking Asks → `RUNNING` state - -| Ask Type | What It Means | Response Options | -| ---------------- | ------------------ | ----------------- | -| `command_output` | Command is running | Continue or abort | - -## Streaming Detection - -The agent is **streaming** when: - -1. **`partial: true`** on the last message, OR -2. **An `api_req_started` message exists** with `cost: undefined` in its text field - -```typescript -// Streaming detection pseudocode -function isStreaming(messages) { - const lastMessage = messages.at(-1) - - // Check partial flag (primary indicator) - if (lastMessage?.partial === true) { - return true - } - - // Check for in-progress API request - const apiReq = messages.findLast((m) => m.say === "api_req_started") - if (apiReq?.text) { - const data = JSON.parse(apiReq.text) - if (data.cost === undefined) { - return true // API request not yet complete - } - } - - return false -} -``` - -## State Machine - -``` - ┌─────────────────┐ - │ NO_TASK │ (no messages) - └────────┬────────┘ - │ newTask - ▼ - ┌─────────────────────────────┐ - ┌───▶│ RUNNING │◀───┐ - │ └──────────┬──────────────────┘ │ - │ │ │ - │ ┌──────────┼──────────────┐ │ - │ │ │ │ │ - │ ▼ ▼ ▼ │ - │ ┌──────┐ ┌─────────┐ ┌──────────┐ │ - │ │STREAM│ │WAITING_ │ │ IDLE │ │ - │ │ ING │ │FOR_INPUT│ │ │ │ - │ └──┬───┘ └────┬────┘ └────┬─────┘ │ - │ │ │ │ │ - │ │ done │ approved │ newTask │ - └────┴───────────┴────────────┘ │ - │ - ┌──────────────┐ │ - │ RESUMABLE │────────────────────────┘ - └──────────────┘ resumed -``` - -## Architecture - -``` -┌─────────────────────────────────────────────────────────────────┐ -│ ExtensionHost │ -│ │ -│ ┌──────────────────┐ │ -│ │ Extension │──── extensionWebviewMessage ─────┐ │ -│ │ (Task.ts) │ │ │ -│ └──────────────────┘ │ │ -│ ▼ │ -│ ┌───────────────────────────────────────────────────────────┐ │ -│ │ ExtensionClient │ │ -│ │ (Single Source of Truth) │ │ -│ │ │ │ -│ │ ┌─────────────────┐ ┌────────────────────┐ │ │ -│ │ │ MessageProcessor │───▶│ StateStore │ │ │ -│ │ │ │ │ (clineMessages) │ │ │ -│ │ └─────────────────┘ └────────┬───────────┘ │ │ -│ │ │ │ │ -│ │ ▼ │ │ -│ │ detectAgentState() │ │ -│ │ │ │ │ -│ │ ▼ │ │ -│ │ Events: stateChange, message, waitingForInput, etc. │ │ -│ └───────────────────────────────────────────────────────────┘ │ -│ │ │ -│ ▼ │ -│ ┌────────────────┐ ┌────────────────┐ ┌────────────────┐ │ -│ │ OutputManager │ │ AskDispatcher │ │ PromptManager │ │ -│ │ (stdout) │ │ (ask routing) │ │ (user input) │ │ -│ └────────────────┘ └────────────────┘ └────────────────┘ │ -└─────────────────────────────────────────────────────────────────┘ -``` - -## Component Responsibilities - -### ExtensionClient - -The **single source of truth** for agent state, including the current mode. It: - -- Receives all messages from the extension -- Stores them in the `StateStore` -- Tracks the current mode from state messages -- Computes the current state via `detectAgentState()` -- Emits events when state changes (including mode changes) - -```typescript -const client = new ExtensionClient({ - sendMessage: (msg) => extensionHost.sendToExtension(msg), - debug: true, // Writes to ~/.roo/cli-debug.log -}) - -// Query state at any time -const state = client.getAgentState() -if (state.isWaitingForInput) { - console.log(`Agent needs: ${state.currentAsk}`) -} - -// Query current mode -const mode = client.getCurrentMode() -console.log(`Current mode: ${mode}`) // e.g., "code", "architect", "ask" - -// Subscribe to events -client.on("waitingForInput", (event) => { - console.log(`Waiting for: ${event.ask}`) -}) - -// Subscribe to mode changes -client.on("modeChanged", (event) => { - console.log(`Mode changed: ${event.previousMode} -> ${event.currentMode}`) -}) -``` - -### StateStore - -Holds the `clineMessages` array, computed state, and current mode: - -```typescript -interface StoreState { - messages: ClineMessage[] // The raw message array - agentState: AgentStateInfo // Computed state - isInitialized: boolean // Have we received any state? - currentMode: string | undefined // Current mode (e.g., "code", "architect") -} -``` - -### MessageProcessor - -Handles incoming messages from the extension: - -- `"state"` messages → Update `clineMessages` array and track mode -- `"messageUpdated"` messages → Update single message in array -- Emits events for state transitions and mode changes - -### AskDispatcher - -Routes asks to appropriate handlers: - -- Uses type guards: `isIdleAsk()`, `isInteractiveAsk()`, etc. -- Coordinates between `OutputManager` and `PromptManager` -- In non-interactive mode (`-y` flag), auto-approves everything - -### OutputManager - -Handles all CLI output: - -- Streams partial content with delta computation -- Tracks what's been displayed to avoid duplicates -- Writes directly to `process.stdout` (bypasses quiet mode) - -### PromptManager - -Handles user input: - -- Yes/no prompts -- Text input prompts -- Timed prompts with auto-defaults - -## Response Messages - -When the agent is waiting, send these responses: - -```typescript -// Approve an action (tool, command, browser, MCP) -client.sendMessage({ - type: "askResponse", - askResponse: "yesButtonClicked", -}) - -// Reject an action -client.sendMessage({ - type: "askResponse", - askResponse: "noButtonClicked", -}) - -// Answer a question -client.sendMessage({ - type: "askResponse", - askResponse: "messageResponse", - text: "My answer here", -}) - -// Start a new task -client.sendMessage({ - type: "newTask", - text: "Build a web app", -}) - -// Cancel current task -client.sendMessage({ - type: "cancelTask", -}) -``` - -## Type Guards - -The CLI uses type guards from `@roo-code/types` for categorization: - -```typescript -import { isIdleAsk, isInteractiveAsk, isResumableAsk, isNonBlockingAsk } from "@roo-code/types" - -const ask = message.ask -if (isInteractiveAsk(ask)) { - // Needs approval: tool, command, followup, etc. -} else if (isIdleAsk(ask)) { - // Task stopped: completion_result, api_req_failed, etc. -} else if (isResumableAsk(ask)) { - // Task paused: resume_task -} else if (isNonBlockingAsk(ask)) { - // Command running: command_output -} -``` - -## Debug Logging - -Enable with `-d` flag. Logs go to `~/.roo/cli-debug.log`: - -```bash -roo -d -y -P "Build something" --no-tui -``` - -View logs: - -```bash -tail -f ~/.roo/cli-debug.log -``` - -Example output: - -``` -[MessageProcessor] State update: { - "messageCount": 5, - "lastMessage": { - "msgType": "ask:completion_result" - }, - "stateTransition": "running → idle", - "currentAsk": "completion_result", - "isWaitingForInput": true -} -[MessageProcessor] EMIT waitingForInput: { "ask": "completion_result" } -[MessageProcessor] EMIT taskCompleted: { "success": true } -``` - -## Summary - -1. **Agent communicates via `ClineMessage` stream** -2. **Last message determines state** -3. **`ask` messages (non-partial) block the agent** -4. **Ask category determines required action** -5. **`partial: true` or `api_req_started` without cost = streaming** -6. **`ExtensionClient` is the single source of truth** diff --git a/apps/cli/eslint.config.mjs b/apps/cli/eslint.config.mjs deleted file mode 100644 index 694bf736642..00000000000 --- a/apps/cli/eslint.config.mjs +++ /dev/null @@ -1,4 +0,0 @@ -import { config } from "@roo-code/config-eslint/base" - -/** @type {import("eslint").Linter.Config} */ -export default [...config] diff --git a/apps/cli/install.sh b/apps/cli/install.sh deleted file mode 100755 index 1b01e51aa58..00000000000 --- a/apps/cli/install.sh +++ /dev/null @@ -1,305 +0,0 @@ -#!/bin/sh -# Roo Code CLI Installer -# Usage: curl -fsSL https://raw.githubusercontent.com/RooCodeInc/Roo-Code/main/apps/cli/install.sh | sh -# -# Environment variables: -# ROO_INSTALL_DIR - Installation directory (default: ~/.roo/cli) -# ROO_BIN_DIR - Binary symlink directory (default: ~/.local/bin) -# ROO_VERSION - Specific version to install (default: latest) -# ROO_LOCAL_TARBALL - Path to local tarball to install (skips download) - -set -e - -# Configuration -INSTALL_DIR="${ROO_INSTALL_DIR:-$HOME/.roo/cli}" -BIN_DIR="${ROO_BIN_DIR:-$HOME/.local/bin}" -REPO="RooCodeInc/Roo-Code" -MIN_NODE_VERSION=20 - -# Color output (only if terminal supports it) -if [ -t 1 ]; then - RED='\033[0;31m' - GREEN='\033[0;32m' - YELLOW='\033[1;33m' - BLUE='\033[0;34m' - BOLD='\033[1m' - NC='\033[0m' -else - RED='' - GREEN='' - YELLOW='' - BLUE='' - BOLD='' - NC='' -fi - -info() { printf "${GREEN}==>${NC} %s\n" "$1"; } -warn() { printf "${YELLOW}Warning:${NC} %s\n" "$1"; } -error() { printf "${RED}Error:${NC} %s\n" "$1" >&2; exit 1; } - -# Check Node.js version -check_node() { - if ! command -v node >/dev/null 2>&1; then - error "Node.js is not installed. Please install Node.js $MIN_NODE_VERSION or higher. - -Install Node.js: - - macOS: brew install node - - Linux: https://nodejs.org/en/download/package-manager - - Or use a version manager like fnm, nvm, or mise" - fi - - NODE_VERSION=$(node -v | sed 's/v//' | cut -d. -f1) - if [ "$NODE_VERSION" -lt "$MIN_NODE_VERSION" ]; then - error "Node.js $MIN_NODE_VERSION+ required. Found: $(node -v) - -Please upgrade Node.js to version $MIN_NODE_VERSION or higher." - fi - - info "Found Node.js $(node -v)" -} - -# Detect OS and architecture -detect_platform() { - OS=$(uname -s | tr '[:upper:]' '[:lower:]') - ARCH=$(uname -m) - - case "$OS" in - darwin) OS="darwin" ;; - linux) OS="linux" ;; - mingw*|msys*|cygwin*) - error "Windows is not supported by this installer. Please use WSL or install manually." - ;; - *) error "Unsupported OS: $OS" ;; - esac - - case "$ARCH" in - x86_64|amd64) ARCH="x64" ;; - arm64|aarch64) ARCH="arm64" ;; - *) error "Unsupported architecture: $ARCH" ;; - esac - - PLATFORM="${OS}-${ARCH}" - info "Detected platform: $PLATFORM" -} - -# Get latest release version or use specified version -get_version() { - # Skip version fetch if using local tarball - if [ -n "$ROO_LOCAL_TARBALL" ]; then - VERSION="${ROO_VERSION:-local}" - info "Using local tarball (version: $VERSION)" - return - fi - - if [ -n "$ROO_VERSION" ]; then - VERSION="$ROO_VERSION" - info "Using specified version: $VERSION" - return - fi - - info "Fetching latest version..." - - # Try to get the latest cli release - RELEASES_JSON=$(curl -fsSL "https://api.github.com/repos/$REPO/releases" 2>/dev/null) || { - error "Failed to fetch releases from GitHub. Check your internet connection." - } - - # Extract the latest cli-v* tag - VERSION=$(echo "$RELEASES_JSON" | - grep -o '"tag_name": "cli-v[^"]*"' | - head -1 | - sed 's/"tag_name": "cli-v//' | - sed 's/"//') - - if [ -z "$VERSION" ]; then - error "Could not find any CLI releases. The CLI may not have been released yet." - fi - - info "Latest version: $VERSION" -} - -# Download and extract -download_and_install() { - TARBALL="roo-cli-${PLATFORM}.tar.gz" - - # Create temp directory - TMP_DIR=$(mktemp -d) - trap "rm -rf $TMP_DIR" EXIT - - # Use local tarball if provided, otherwise download - if [ -n "$ROO_LOCAL_TARBALL" ]; then - if [ ! -f "$ROO_LOCAL_TARBALL" ]; then - error "Local tarball not found: $ROO_LOCAL_TARBALL" - fi - info "Using local tarball: $ROO_LOCAL_TARBALL" - cp "$ROO_LOCAL_TARBALL" "$TMP_DIR/$TARBALL" - else - URL="https://github.com/$REPO/releases/download/cli-v${VERSION}/${TARBALL}" - - info "Downloading from $URL..." - - # Download with progress indicator - HTTP_CODE=$(curl -fsSL -w "%{http_code}" "$URL" -o "$TMP_DIR/$TARBALL" 2>/dev/null) || { - if [ "$HTTP_CODE" = "404" ]; then - error "Release not found for platform $PLATFORM version $VERSION. - -Available at: https://github.com/$REPO/releases" - fi - error "Download failed. HTTP code: $HTTP_CODE" - } - - # Verify we got something - if [ ! -s "$TMP_DIR/$TARBALL" ]; then - error "Downloaded file is empty. Please try again." - fi - fi - - # Remove old installation if exists - if [ -d "$INSTALL_DIR" ]; then - info "Removing previous installation..." - rm -rf "$INSTALL_DIR" - fi - - mkdir -p "$INSTALL_DIR" - - # Extract - info "Extracting to $INSTALL_DIR..." - tar -xzf "$TMP_DIR/$TARBALL" -C "$INSTALL_DIR" --strip-components=1 || { - error "Failed to extract tarball. The download may be corrupted." - } - - # Save ripgrep binary before npm install (npm install will overwrite node_modules) - RIPGREP_BIN="" - if [ -f "$INSTALL_DIR/node_modules/@vscode/ripgrep/bin/rg" ]; then - RIPGREP_BIN="$TMP_DIR/rg" - cp "$INSTALL_DIR/node_modules/@vscode/ripgrep/bin/rg" "$RIPGREP_BIN" - fi - - # Install npm dependencies - info "Installing dependencies..." - cd "$INSTALL_DIR" - npm install --production --silent 2>/dev/null || { - warn "npm install failed, trying with --legacy-peer-deps..." - npm install --production --legacy-peer-deps --silent 2>/dev/null || { - error "Failed to install dependencies. Make sure npm is available." - } - } - cd - > /dev/null - - # Restore ripgrep binary after npm install - if [ -n "$RIPGREP_BIN" ] && [ -f "$RIPGREP_BIN" ]; then - mkdir -p "$INSTALL_DIR/node_modules/@vscode/ripgrep/bin" - cp "$RIPGREP_BIN" "$INSTALL_DIR/node_modules/@vscode/ripgrep/bin/rg" - chmod +x "$INSTALL_DIR/node_modules/@vscode/ripgrep/bin/rg" - fi - - # Make executable - chmod +x "$INSTALL_DIR/bin/roo" - - # Also make ripgrep executable if it exists - if [ -f "$INSTALL_DIR/bin/rg" ]; then - chmod +x "$INSTALL_DIR/bin/rg" - fi -} - -# Create symlink in bin directory -setup_bin() { - mkdir -p "$BIN_DIR" - - # Remove old symlink if exists - if [ -L "$BIN_DIR/roo" ] || [ -f "$BIN_DIR/roo" ]; then - rm -f "$BIN_DIR/roo" - fi - - ln -sf "$INSTALL_DIR/bin/roo" "$BIN_DIR/roo" - info "Created symlink: $BIN_DIR/roo" -} - -# Check if bin dir is in PATH and provide instructions -check_path() { - case ":$PATH:" in - *":$BIN_DIR:"*) - # Already in PATH - return 0 - ;; - esac - - warn "$BIN_DIR is not in your PATH" - echo "" - echo "Add this line to your shell profile:" - echo "" - - # Detect shell and provide specific instructions - SHELL_NAME=$(basename "$SHELL") - case "$SHELL_NAME" in - zsh) - echo " echo 'export PATH=\"$BIN_DIR:\$PATH\"' >> ~/.zshrc" - echo " source ~/.zshrc" - ;; - bash) - if [ -f "$HOME/.bashrc" ]; then - echo " echo 'export PATH=\"$BIN_DIR:\$PATH\"' >> ~/.bashrc" - echo " source ~/.bashrc" - else - echo " echo 'export PATH=\"$BIN_DIR:\$PATH\"' >> ~/.bash_profile" - echo " source ~/.bash_profile" - fi - ;; - fish) - echo " set -Ux fish_user_paths $BIN_DIR \$fish_user_paths" - ;; - *) - echo " export PATH=\"$BIN_DIR:\$PATH\"" - ;; - esac - echo "" -} - -# Verify installation -verify_install() { - if [ -x "$BIN_DIR/roo" ]; then - info "Verifying installation..." - # Just check if it runs without error - "$BIN_DIR/roo" --version >/dev/null 2>&1 || true - fi -} - -# Print success message -print_success() { - echo "" - printf "${GREEN}${BOLD}✓ Roo Code CLI installed successfully!${NC}\n" - echo "" - echo " Installation: $INSTALL_DIR" - echo " Binary: $BIN_DIR/roo" - echo " Version: $VERSION" - echo "" - echo " ${BOLD}Get started:${NC}" - echo " roo --help" - echo "" - echo " ${BOLD}Example:${NC}" - echo " export OPENROUTER_API_KEY=sk-or-v1-..." - echo " roo ~/my-project -P \"What is this project?\"" - echo "" -} - -# Main -main() { - echo "" - printf "${BLUE}${BOLD}" - echo " ╭─────────────────────────────────╮" - echo " │ Roo Code CLI Installer │" - echo " ╰─────────────────────────────────╯" - printf "${NC}" - echo "" - - check_node - detect_platform - get_version - download_and_install - setup_bin - check_path - verify_install - print_success -} - -main "$@" diff --git a/apps/cli/package.json b/apps/cli/package.json deleted file mode 100644 index 3939a0aa584..00000000000 --- a/apps/cli/package.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "name": "@roo-code/cli", - "version": "0.0.45", - "description": "Roo Code CLI - Run the Roo Code agent from the command line", - "private": true, - "type": "module", - "main": "dist/index.js", - "bin": { - "roo": "dist/index.js" - }, - "scripts": { - "format": "prettier --write 'src/**/*.ts'", - "lint": "eslint src --ext .ts --max-warnings=0", - "check-types": "tsc --noEmit", - "test": "vitest run", - "build": "tsup", - "dev": "tsup --watch", - "start": "ROO_SDK_BASE_URL=http://localhost:3001 ROO_AUTH_BASE_URL=http://localhost:3000 node dist/index.js", - "start:production": "node dist/index.js", - "release": "scripts/release.sh", - "clean": "rimraf dist .turbo" - }, - "dependencies": { - "@inkjs/ui": "^2.0.0", - "@roo-code/core": "workspace:^", - "@roo-code/types": "workspace:^", - "@roo-code/vscode-shim": "workspace:^", - "@trpc/client": "^11.8.1", - "@vscode/ripgrep": "^1.15.9", - "commander": "^12.1.0", - "fuzzysort": "^3.1.0", - "ink": "^6.6.0", - "p-wait-for": "^5.0.2", - "react": "^19.1.0", - "superjson": "^2.2.6", - "zustand": "^5.0.0" - }, - "devDependencies": { - "@roo-code/config-eslint": "workspace:^", - "@roo-code/config-typescript": "workspace:^", - "@types/node": "^24.1.0", - "@types/react": "^19.1.6", - "ink-testing-library": "^4.0.0", - "rimraf": "^6.0.1", - "tsup": "^8.4.0", - "vitest": "^3.2.3" - } -} diff --git a/apps/cli/scripts/release.sh b/apps/cli/scripts/release.sh deleted file mode 100755 index 2e678dc7960..00000000000 --- a/apps/cli/scripts/release.sh +++ /dev/null @@ -1,714 +0,0 @@ -#!/bin/bash -# Roo Code CLI Release Script -# -# Usage: -# ./apps/cli/scripts/release.sh [options] [version] -# -# Options: -# --dry-run Run all steps except creating the GitHub release -# --local Build for local testing only (no GitHub checks, no changelog prompts) -# --install Install locally after building (only with --local) -# --skip-verify Skip end-to-end verification tests (faster local builds) -# -# Examples: -# ./apps/cli/scripts/release.sh # Use version from package.json -# ./apps/cli/scripts/release.sh 0.1.0 # Specify version -# ./apps/cli/scripts/release.sh --dry-run # Test the release flow without pushing -# ./apps/cli/scripts/release.sh --dry-run 0.1.0 # Dry run with specific version -# ./apps/cli/scripts/release.sh --local # Build for local testing -# ./apps/cli/scripts/release.sh --local --install # Build and install locally -# ./apps/cli/scripts/release.sh --local --skip-verify # Fast local build -# -# This script: -# 1. Builds the extension and CLI -# 2. Creates a tarball for the current platform -# 3. Creates a GitHub release and uploads the tarball (unless --dry-run or --local) -# -# Prerequisites: -# - GitHub CLI (gh) installed and authenticated (not needed for --local) -# - pnpm installed -# - Run from the monorepo root directory - -set -e - -# Parse arguments -DRY_RUN=false -LOCAL_BUILD=false -LOCAL_INSTALL=false -SKIP_VERIFY=false -VERSION_ARG="" - -while [[ $# -gt 0 ]]; do - case $1 in - --dry-run) - DRY_RUN=true - shift - ;; - --local) - LOCAL_BUILD=true - shift - ;; - --install) - LOCAL_INSTALL=true - shift - ;; - --skip-verify) - SKIP_VERIFY=true - shift - ;; - -*) - echo "Unknown option: $1" >&2 - exit 1 - ;; - *) - VERSION_ARG="$1" - shift - ;; - esac -done - -# Validate option combinations -if [ "$LOCAL_INSTALL" = true ] && [ "$LOCAL_BUILD" = false ]; then - echo "Error: --install can only be used with --local" >&2 - exit 1 -fi - -# Colors -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -BLUE='\033[0;34m' -BOLD='\033[1m' -NC='\033[0m' - -info() { printf "${GREEN}==>${NC} %s\n" "$1"; } -warn() { printf "${YELLOW}Warning:${NC} %s\n" "$1"; } -error() { printf "${RED}Error:${NC} %s\n" "$1" >&2; exit 1; } -step() { printf "${BLUE}${BOLD}[%s]${NC} %s\n" "$1" "$2"; } - -# Get script directory and repo root -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)" -CLI_DIR="$REPO_ROOT/apps/cli" - -# Detect current platform -detect_platform() { - OS=$(uname -s | tr '[:upper:]' '[:lower:]') - ARCH=$(uname -m) - - case "$OS" in - darwin) OS="darwin" ;; - linux) OS="linux" ;; - *) error "Unsupported OS: $OS" ;; - esac - - case "$ARCH" in - x86_64|amd64) ARCH="x64" ;; - arm64|aarch64) ARCH="arm64" ;; - *) error "Unsupported architecture: $ARCH" ;; - esac - - PLATFORM="${OS}-${ARCH}" -} - -# Check prerequisites -check_prerequisites() { - step "1/8" "Checking prerequisites..." - - # Skip GitHub CLI checks for local builds - if [ "$LOCAL_BUILD" = false ]; then - if ! command -v gh &> /dev/null; then - error "GitHub CLI (gh) is not installed. Install it with: brew install gh" - fi - - if ! gh auth status &> /dev/null; then - error "GitHub CLI is not authenticated. Run: gh auth login" - fi - fi - - if ! command -v pnpm &> /dev/null; then - error "pnpm is not installed." - fi - - if ! command -v node &> /dev/null; then - error "Node.js is not installed." - fi - - info "Prerequisites OK" -} - -# Get version -get_version() { - if [ -n "$VERSION_ARG" ]; then - VERSION="$VERSION_ARG" - else - VERSION=$(node -p "require('$CLI_DIR/package.json').version") - fi - - # For local builds, append a local suffix with git short hash - # This creates versions like: 0.1.0-local.abc1234 - if [ "$LOCAL_BUILD" = true ]; then - GIT_SHORT_HASH=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown") - # Only append suffix if not already a local version - if ! echo "$VERSION" | grep -qE '\-local\.'; then - VERSION="${VERSION}-local.${GIT_SHORT_HASH}" - fi - fi - - # Validate semver format (allow -local.hash suffix) - if ! echo "$VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9.]+)?$'; then - error "Invalid version format: $VERSION (expected semver like 0.1.0)" - fi - - TAG="cli-v$VERSION" - info "Version: $VERSION (tag: $TAG)" -} - -# Extract changelog content for a specific version -# Returns the content between the version header and the next version header (or EOF) -get_changelog_content() { - CHANGELOG_FILE="$CLI_DIR/CHANGELOG.md" - - if [ ! -f "$CHANGELOG_FILE" ]; then - warn "No CHANGELOG.md found at $CHANGELOG_FILE" - CHANGELOG_CONTENT="" - return - fi - - # Try to find the version section (handles both "[0.0.43]" and "[0.0.43] - date" formats) - # Also handles "Unreleased" marker - VERSION_PATTERN="^\#\# \[${VERSION}\]" - - # Check if the version exists in the changelog - if ! grep -qE "$VERSION_PATTERN" "$CHANGELOG_FILE"; then - warn "No changelog entry found for version $VERSION" - # Skip prompts for local builds - if [ "$LOCAL_BUILD" = true ]; then - info "Skipping changelog prompt for local build" - CHANGELOG_CONTENT="" - return - fi - warn "Please add an entry to $CHANGELOG_FILE before releasing" - echo "" - echo "Expected format:" - echo " ## [$VERSION] - $(date +%Y-%m-%d)" - echo " " - echo " ### Added" - echo " - Your changes here" - echo "" - read -p "Continue without changelog content? [y/N] " -n 1 -r - echo - if [[ ! $REPLY =~ ^[Yy]$ ]]; then - error "Aborted. Please add a changelog entry and try again." - fi - CHANGELOG_CONTENT="" - return - fi - - # Extract content between this version and the next version header (or EOF) - # Uses awk to capture everything between ## [VERSION] and the next ## [ - # Using index() with "[VERSION]" ensures exact matching (1.0.1 won't match 1.0.10) - CHANGELOG_CONTENT=$(awk -v version="$VERSION" ' - BEGIN { found = 0; content = ""; target = "[" version "]" } - /^## \[/ { - if (found) { exit } - if (index($0, target) > 0) { found = 1; next } - } - found { content = content $0 "\n" } - END { print content } - ' "$CHANGELOG_FILE") - - # Trim leading/trailing whitespace - CHANGELOG_CONTENT=$(echo "$CHANGELOG_CONTENT" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//') - - if [ -n "$CHANGELOG_CONTENT" ]; then - info "Found changelog content for version $VERSION" - else - warn "Changelog entry for $VERSION appears to be empty" - fi -} - -# Build everything -build() { - step "2/8" "Building extension bundle..." - cd "$REPO_ROOT" - pnpm bundle - - step "3/8" "Building CLI..." - pnpm --filter @roo-code/cli build - - info "Build complete" -} - -# Create release tarball -create_tarball() { - step "4/8" "Creating release tarball for $PLATFORM..." - - RELEASE_DIR="$REPO_ROOT/roo-cli-${PLATFORM}" - TARBALL="roo-cli-${PLATFORM}.tar.gz" - - # Clean up any previous build - rm -rf "$RELEASE_DIR" - rm -f "$REPO_ROOT/$TARBALL" - - # Create directory structure - mkdir -p "$RELEASE_DIR/bin" - mkdir -p "$RELEASE_DIR/lib" - mkdir -p "$RELEASE_DIR/extension" - - # Copy CLI dist files - info "Copying CLI files..." - cp -r "$CLI_DIR/dist/"* "$RELEASE_DIR/lib/" - - # Create package.json for npm install (runtime dependencies that can't be bundled) - info "Creating package.json..." - node -e " - const pkg = require('$CLI_DIR/package.json'); - const newPkg = { - name: '@roo-code/cli', - version: '$VERSION', - type: 'module', - dependencies: { - '@inkjs/ui': pkg.dependencies['@inkjs/ui'], - '@trpc/client': pkg.dependencies['@trpc/client'], - 'commander': pkg.dependencies.commander, - 'fuzzysort': pkg.dependencies.fuzzysort, - 'ink': pkg.dependencies.ink, - 'react': pkg.dependencies.react, - 'superjson': pkg.dependencies.superjson, - 'zustand': pkg.dependencies.zustand - } - }; - console.log(JSON.stringify(newPkg, null, 2)); - " > "$RELEASE_DIR/package.json" - - # Copy extension bundle - info "Copying extension bundle..." - cp -r "$REPO_ROOT/src/dist/"* "$RELEASE_DIR/extension/" - - # Add package.json to extension directory to mark it as CommonJS - # This is necessary because the main package.json has "type": "module" - # but the extension bundle is CommonJS - echo '{"type": "commonjs"}' > "$RELEASE_DIR/extension/package.json" - - # Find and copy ripgrep binary - # The extension looks for ripgrep at: appRoot/node_modules/@vscode/ripgrep/bin/rg - # The CLI sets appRoot to the CLI package root, so we need to put ripgrep there - info "Looking for ripgrep binary..." - RIPGREP_PATH=$(find "$REPO_ROOT/node_modules" -path "*/@vscode/ripgrep/bin/rg" -type f 2>/dev/null | head -1) - if [ -n "$RIPGREP_PATH" ] && [ -f "$RIPGREP_PATH" ]; then - info "Found ripgrep at: $RIPGREP_PATH" - # Create the expected directory structure for the extension to find ripgrep - mkdir -p "$RELEASE_DIR/node_modules/@vscode/ripgrep/bin" - cp "$RIPGREP_PATH" "$RELEASE_DIR/node_modules/@vscode/ripgrep/bin/" - chmod +x "$RELEASE_DIR/node_modules/@vscode/ripgrep/bin/rg" - # Also keep a copy in bin/ for direct access - mkdir -p "$RELEASE_DIR/bin" - cp "$RIPGREP_PATH" "$RELEASE_DIR/bin/" - chmod +x "$RELEASE_DIR/bin/rg" - else - warn "ripgrep binary not found - users will need ripgrep installed" - fi - - # Create the wrapper script - info "Creating wrapper script..." - cat > "$RELEASE_DIR/bin/roo" << 'WRAPPER_EOF' -#!/usr/bin/env node - -import { fileURLToPath } from 'url'; -import { dirname, join } from 'path'; - -const __filename = fileURLToPath(import.meta.url); -const __dirname = dirname(__filename); - -// Set environment variables for the CLI -// ROO_CLI_ROOT is the installed CLI package root (where node_modules/@vscode/ripgrep is) -process.env.ROO_CLI_ROOT = join(__dirname, '..'); -process.env.ROO_EXTENSION_PATH = join(__dirname, '..', 'extension'); -process.env.ROO_RIPGREP_PATH = join(__dirname, 'rg'); - -// Import and run the actual CLI -await import(join(__dirname, '..', 'lib', 'index.js')); -WRAPPER_EOF - - chmod +x "$RELEASE_DIR/bin/roo" - - # Create empty .env file to suppress dotenvx warnings - touch "$RELEASE_DIR/.env" - - # Create empty .env file to suppress dotenvx warnings - touch "$RELEASE_DIR/.env" - - # Create tarball - info "Creating tarball..." - cd "$REPO_ROOT" - tar -czvf "$TARBALL" "$(basename "$RELEASE_DIR")" - - # Clean up release directory - rm -rf "$RELEASE_DIR" - - # Show size - TARBALL_PATH="$REPO_ROOT/$TARBALL" - TARBALL_SIZE=$(ls -lh "$TARBALL_PATH" | awk '{print $5}') - info "Created: $TARBALL ($TARBALL_SIZE)" -} - -# Verify local installation -verify_local_install() { - if [ "$SKIP_VERIFY" = true ]; then - step "5/8" "Skipping verification (--skip-verify)" - return - fi - - step "5/8" "Verifying local installation..." - - VERIFY_DIR="$REPO_ROOT/.verify-release" - VERIFY_INSTALL_DIR="$VERIFY_DIR/cli" - VERIFY_BIN_DIR="$VERIFY_DIR/bin" - - # Clean up any previous verification directory - rm -rf "$VERIFY_DIR" - mkdir -p "$VERIFY_DIR" - - # Run the actual install script with the local tarball - info "Running install script with local tarball..." - TARBALL_PATH="$REPO_ROOT/$TARBALL" - - ROO_LOCAL_TARBALL="$TARBALL_PATH" \ - ROO_INSTALL_DIR="$VERIFY_INSTALL_DIR" \ - ROO_BIN_DIR="$VERIFY_BIN_DIR" \ - ROO_VERSION="$VERSION" \ - "$CLI_DIR/install.sh" || { - echo "" - warn "Install script failed. Showing tarball contents:" - tar -tzf "$TARBALL_PATH" 2>&1 || true - echo "" - rm -rf "$VERIFY_DIR" - error "Installation verification failed! The install script could not complete successfully." - } - - # Verify the CLI runs correctly with basic commands - info "Testing installed CLI..." - - # Test --help - if ! "$VERIFY_BIN_DIR/roo" --help > /dev/null 2>&1; then - echo "" - warn "CLI --help output:" - "$VERIFY_BIN_DIR/roo" --help 2>&1 || true - echo "" - rm -rf "$VERIFY_DIR" - error "CLI --help check failed! The release tarball may have missing dependencies." - fi - info "CLI --help check passed" - - # Test --version - if ! "$VERIFY_BIN_DIR/roo" --version > /dev/null 2>&1; then - echo "" - warn "CLI --version output:" - "$VERIFY_BIN_DIR/roo" --version 2>&1 || true - echo "" - rm -rf "$VERIFY_DIR" - error "CLI --version check failed! The release tarball may have missing dependencies." - fi - info "CLI --version check passed" - - # Run a simple end-to-end test to verify the CLI actually works - info "Running end-to-end verification test..." - - # Create a temporary workspace for the test - VERIFY_WORKSPACE="$VERIFY_DIR/workspace" - mkdir -p "$VERIFY_WORKSPACE" - - # Run the CLI with a simple prompt - # Use timeout to prevent hanging if something goes wrong - if timeout 60 "$VERIFY_BIN_DIR/roo" --yes --exit-on-complete --prompt "1+1=?" "$VERIFY_WORKSPACE" > "$VERIFY_DIR/test-output.log" 2>&1; then - info "End-to-end test passed" - else - EXIT_CODE=$? - echo "" - warn "End-to-end test failed (exit code: $EXIT_CODE). Output:" - cat "$VERIFY_DIR/test-output.log" 2>&1 || true - echo "" - rm -rf "$VERIFY_DIR" - error "CLI end-to-end test failed! The CLI may be broken." - fi - - # Clean up verification directory - cd "$REPO_ROOT" - rm -rf "$VERIFY_DIR" - - info "Local verification passed!" -} - -# Create checksum -create_checksum() { - step "6/8" "Creating checksum..." - cd "$REPO_ROOT" - - if command -v sha256sum &> /dev/null; then - sha256sum "$TARBALL" > "${TARBALL}.sha256" - elif command -v shasum &> /dev/null; then - shasum -a 256 "$TARBALL" > "${TARBALL}.sha256" - else - warn "No sha256sum or shasum found, skipping checksum" - return - fi - - info "Checksum: $(cat "${TARBALL}.sha256")" -} - -# Check if release already exists -check_existing_release() { - step "7/8" "Checking for existing release..." - - if gh release view "$TAG" &> /dev/null; then - warn "Release $TAG already exists" - read -p "Do you want to delete it and create a new one? [y/N] " -n 1 -r - echo - if [[ $REPLY =~ ^[Yy]$ ]]; then - info "Deleting existing release..." - gh release delete "$TAG" --yes - # Also delete the tag if it exists - git tag -d "$TAG" 2>/dev/null || true - git push origin ":refs/tags/$TAG" 2>/dev/null || true - else - error "Aborted. Use a different version or delete the existing release manually." - fi - fi -} - -# Create GitHub release -create_release() { - step "8/8" "Creating GitHub release..." - cd "$REPO_ROOT" - - # Get the current commit SHA for the release target - COMMIT_SHA=$(git rev-parse HEAD) - - # Verify the commit exists on GitHub before attempting to create the release - # This prevents the "Release.target_commitish is invalid" error - info "Verifying commit ${COMMIT_SHA:0:8} exists on GitHub..." - git fetch origin 2>/dev/null || true - if ! git branch -r --contains "$COMMIT_SHA" 2>/dev/null | grep -q "origin/"; then - warn "Commit ${COMMIT_SHA:0:8} has not been pushed to GitHub" - echo "" - echo "The release script needs to create a release at your current commit," - echo "but this commit hasn't been pushed to GitHub yet." - echo "" - read -p "Push current branch to origin now? [Y/n] " -n 1 -r - echo - if [[ ! $REPLY =~ ^[Nn]$ ]]; then - info "Pushing to origin..." - git push origin HEAD || error "Failed to push to origin. Please push manually and try again." - else - error "Aborted. Please push your commits to GitHub and try again." - fi - fi - info "Commit verified on GitHub" - - # Build the What's New section from changelog content - WHATS_NEW_SECTION="" - if [ -n "$CHANGELOG_CONTENT" ]; then - WHATS_NEW_SECTION="## What's New - -$CHANGELOG_CONTENT - -" - fi - - RELEASE_NOTES=$(cat << EOF -${WHATS_NEW_SECTION}## Installation - -\`\`\`bash -curl -fsSL https://raw.githubusercontent.com/RooCodeInc/Roo-Code/main/apps/cli/install.sh | sh -\`\`\` - -Or install a specific version: -\`\`\`bash -ROO_VERSION=$VERSION curl -fsSL https://raw.githubusercontent.com/RooCodeInc/Roo-Code/main/apps/cli/install.sh | sh -\`\`\` - -## Requirements - -- Node.js 20 or higher -- macOS (Intel or Apple Silicon) or Linux (x64 or ARM64) - -## Usage - -\`\`\`bash -# Set your API key -export OPENROUTER_API_KEY=sk-or-v1-... - -# Run a task -roo "What is this project?" ~/my-project - -# See all options -roo --help -\`\`\` - -## Platform Support - -This release includes: -- \`roo-cli-${PLATFORM}.tar.gz\` - Built on $(uname -s) $(uname -m) - -> **Note:** Additional platforms will be added as needed. If you need a different platform, please open an issue. - -## Checksum - -\`\`\` -$(cat "${TARBALL}.sha256" 2>/dev/null || echo "N/A") -\`\`\` -EOF -) - - info "Creating release at commit: ${COMMIT_SHA:0:8}" - - # Create release (gh will create the tag automatically) - info "Creating release..." - RELEASE_FILES="$TARBALL" - if [ -f "${TARBALL}.sha256" ]; then - RELEASE_FILES="$RELEASE_FILES ${TARBALL}.sha256" - fi - - gh release create "$TAG" \ - --title "Roo Code CLI v$VERSION" \ - --notes "$RELEASE_NOTES" \ - --prerelease \ - --target "$COMMIT_SHA" \ - $RELEASE_FILES - - info "Release created!" -} - -# Cleanup -cleanup() { - info "Cleaning up..." - cd "$REPO_ROOT" - rm -f "$TARBALL" "${TARBALL}.sha256" -} - -# Print summary -print_summary() { - echo "" - printf "${GREEN}${BOLD}✓ Release v$VERSION created successfully!${NC}\n" - echo "" - echo " Release URL: https://github.com/RooCodeInc/Roo-Code/releases/tag/$TAG" - echo "" - echo " Install with:" - echo " curl -fsSL https://raw.githubusercontent.com/RooCodeInc/Roo-Code/main/apps/cli/install.sh | sh" - echo "" -} - -# Print dry-run summary -print_dry_run_summary() { - echo "" - printf "${YELLOW}${BOLD}✓ Dry run complete for v$VERSION${NC}\n" - echo "" - echo " The following artifacts were created:" - echo " - $TARBALL" - if [ -f "${TARBALL}.sha256" ]; then - echo " - ${TARBALL}.sha256" - fi - echo "" - echo " To complete the release, run without --dry-run:" - echo " ./apps/cli/scripts/release.sh $VERSION" - echo "" - echo " Or manually upload the tarball to a new GitHub release." - echo "" -} - -# Print local build summary -print_local_summary() { - echo "" - printf "${GREEN}${BOLD}✓ Local build complete for v$VERSION${NC}\n" - echo "" - echo " Tarball: $REPO_ROOT/$TARBALL" - if [ -f "${TARBALL}.sha256" ]; then - echo " Checksum: $REPO_ROOT/${TARBALL}.sha256" - fi - echo "" - echo " To install manually:" - echo " ROO_LOCAL_TARBALL=$REPO_ROOT/$TARBALL ./apps/cli/install.sh" - echo "" - echo " Or re-run with --install to install automatically:" - echo " ./apps/cli/scripts/release.sh --local --install" - echo "" -} - -# Install locally using the install script -install_local() { - step "7/8" "Installing locally..." - - TARBALL_PATH="$REPO_ROOT/$TARBALL" - - ROO_LOCAL_TARBALL="$TARBALL_PATH" \ - ROO_VERSION="$VERSION" \ - "$CLI_DIR/install.sh" || { - error "Local installation failed!" - } - - info "Local installation complete!" -} - -# Print local install summary -print_local_install_summary() { - echo "" - printf "${GREEN}${BOLD}✓ Local build installed for v$VERSION${NC}\n" - echo "" - echo " Tarball: $REPO_ROOT/$TARBALL" - echo " Installed to: ~/.roo/cli" - echo " Binary: ~/.local/bin/roo" - echo "" - echo " Test it out:" - echo " roo --version" - echo " roo --help" - echo "" -} - -# Main -main() { - echo "" - printf "${BLUE}${BOLD}" - echo " ╭─────────────────────────────────╮" - echo " │ Roo Code CLI Release Script │" - echo " ╰─────────────────────────────────╯" - printf "${NC}" - - if [ "$DRY_RUN" = true ]; then - printf "${YELLOW} (DRY RUN MODE)${NC}\n" - elif [ "$LOCAL_BUILD" = true ]; then - printf "${YELLOW} (LOCAL BUILD MODE)${NC}\n" - fi - echo "" - - detect_platform - check_prerequisites - get_version - get_changelog_content - build - create_tarball - verify_local_install - create_checksum - - if [ "$LOCAL_BUILD" = true ]; then - step "7/8" "Skipping GitHub checks (local build)" - if [ "$LOCAL_INSTALL" = true ]; then - install_local - print_local_install_summary - else - step "8/8" "Skipping installation (use --install to auto-install)" - print_local_summary - fi - elif [ "$DRY_RUN" = true ]; then - step "7/8" "Skipping existing release check (dry run)" - step "8/8" "Skipping GitHub release creation (dry run)" - print_dry_run_summary - else - check_existing_release - create_release - cleanup - print_summary - fi -} - -main diff --git a/apps/cli/src/__tests__/index.test.ts b/apps/cli/src/__tests__/index.test.ts deleted file mode 100644 index aa9649373d0..00000000000 --- a/apps/cli/src/__tests__/index.test.ts +++ /dev/null @@ -1,126 +0,0 @@ -/** - * Integration tests for CLI - * - * These tests require: - * 1. RUN_CLI_INTEGRATION_TESTS=true environment variable (opt-in) - * 2. A valid OPENROUTER_API_KEY environment variable - * 3. A built CLI at apps/cli/dist (will auto-build if missing) - * 4. A built extension at src/dist (will auto-build if missing) - * - * Run with: RUN_CLI_INTEGRATION_TESTS=true OPENROUTER_API_KEY=sk-or-v1-... pnpm test - */ - -// pnpm --filter @roo-code/cli test src/__tests__/index.test.ts - -import path from "path" -import fs from "fs" -import { execSync, spawn, type ChildProcess } from "child_process" -import { fileURLToPath } from "url" - -const __filename = fileURLToPath(import.meta.url) -const __dirname = path.dirname(__filename) - -const RUN_INTEGRATION_TESTS = process.env.RUN_CLI_INTEGRATION_TESTS === "true" -const OPENROUTER_API_KEY = process.env.OPENROUTER_API_KEY -const hasApiKey = !!OPENROUTER_API_KEY - -function findCliRoot(): string { - // From apps/cli/src/__tests__, go up to apps/cli. - return path.resolve(__dirname, "../..") -} - -function findMonorepoRoot(): string { - // From apps/cli/src/__tests__, go up to monorepo root. - return path.resolve(__dirname, "../../../..") -} - -function isCliBuilt(): boolean { - return fs.existsSync(path.join(findCliRoot(), "dist", "index.js")) -} - -function isExtensionBuilt(): boolean { - const monorepoRoot = findMonorepoRoot() - const extensionPath = path.join(monorepoRoot, "src/dist") - return fs.existsSync(path.join(extensionPath, "extension.js")) -} - -function buildCliIfNeeded(): void { - if (!isCliBuilt()) { - execSync("pnpm build", { cwd: findCliRoot(), stdio: "inherit" }) - console.log("CLI build complete.") - } -} - -function buildExtensionIfNeeded(): void { - if (!isExtensionBuilt()) { - execSync("pnpm --filter roo-cline bundle", { cwd: findMonorepoRoot(), stdio: "inherit" }) - console.log("Extension build complete.") - } -} - -function runCli( - args: string[], - options: { timeout?: number } = {}, -): Promise<{ stdout: string; stderr: string; exitCode: number }> { - return new Promise((resolve) => { - const timeout = options.timeout ?? 60000 - - let stdout = "" - let stderr = "" - let timedOut = false - - const proc: ChildProcess = spawn("pnpm", ["start", ...args], { - cwd: findCliRoot(), - env: { ...process.env, OPENROUTER_API_KEY, NO_COLOR: "1", FORCE_COLOR: "0" }, - stdio: ["pipe", "pipe", "pipe"], - }) - - const timeoutId = setTimeout(() => { - timedOut = true - proc.kill("SIGTERM") - }, timeout) - - proc.stdout?.on("data", (data: Buffer) => { - stdout += data.toString() - }) - - proc.stderr?.on("data", (data: Buffer) => { - stderr += data.toString() - }) - - proc.on("close", (code: number | null) => { - clearTimeout(timeoutId) - resolve({ stdout, stderr, exitCode: timedOut ? -1 : (code ?? 1) }) - }) - - proc.on("error", (error: Error) => { - clearTimeout(timeoutId) - stderr += error.message - resolve({ stdout, stderr, exitCode: 1 }) - }) - }) -} - -describe.skipIf(!RUN_INTEGRATION_TESTS || !hasApiKey)("CLI Integration Tests", () => { - beforeAll(() => { - buildExtensionIfNeeded() - buildCliIfNeeded() - }) - - it("should complete end-to-end task execution via CLI", async () => { - const result = await runCli( - ["--no-tui", "-m", "anthropic/claude-sonnet-4.5", "-M", "ask", "-r", "disabled", "-P", "1+1=?"], - { timeout: 30_000 }, - ) - - console.log("CLI stdout:", result.stdout) - - if (result.stderr) { - console.log("CLI stderr:", result.stderr) - } - - expect(result.exitCode).toBe(0) - expect(result.stdout).toContain("2") - expect(result.stdout).toContain("[task complete]") - }, 30_000) -}) diff --git a/apps/cli/src/agent/__tests__/extension-client.test.ts b/apps/cli/src/agent/__tests__/extension-client.test.ts deleted file mode 100644 index 3d87a30200f..00000000000 --- a/apps/cli/src/agent/__tests__/extension-client.test.ts +++ /dev/null @@ -1,858 +0,0 @@ -import { - type ClineMessage, - type ExtensionMessage, - isIdleAsk, - isResumableAsk, - isInteractiveAsk, - isNonBlockingAsk, -} from "@roo-code/types" - -import { AgentLoopState, detectAgentState } from "../agent-state.js" -import { createMockClient } from "../extension-client.js" - -function createMessage(overrides: Partial): ClineMessage { - return { ts: Date.now() + Math.random() * 1000, type: "say", ...overrides } -} - -function createStateMessage(messages: ClineMessage[], mode?: string): ExtensionMessage { - return { type: "state", state: { clineMessages: messages, mode } } as ExtensionMessage -} - -describe("detectAgentState", () => { - describe("NO_TASK state", () => { - it("should return NO_TASK for empty messages array", () => { - const state = detectAgentState([]) - expect(state.state).toBe(AgentLoopState.NO_TASK) - expect(state.isWaitingForInput).toBe(false) - expect(state.isRunning).toBe(false) - }) - - it("should return NO_TASK for undefined messages", () => { - const state = detectAgentState(undefined as unknown as ClineMessage[]) - expect(state.state).toBe(AgentLoopState.NO_TASK) - }) - }) - - describe("STREAMING state", () => { - it("should detect streaming when partial is true", () => { - const messages = [createMessage({ type: "ask", ask: "tool", partial: true })] - const state = detectAgentState(messages) - expect(state.state).toBe(AgentLoopState.STREAMING) - expect(state.isStreaming).toBe(true) - expect(state.isWaitingForInput).toBe(false) - }) - - it("should detect streaming when api_req_started has no cost", () => { - const messages = [ - createMessage({ - say: "api_req_started", - text: JSON.stringify({ tokensIn: 100 }), // No cost field. - }), - ] - const state = detectAgentState(messages) - expect(state.state).toBe(AgentLoopState.STREAMING) - expect(state.isStreaming).toBe(true) - }) - - it("should NOT be streaming when api_req_started has cost", () => { - const messages = [ - createMessage({ - say: "api_req_started", - text: JSON.stringify({ cost: 0.001, tokensIn: 100 }), - }), - ] - const state = detectAgentState(messages) - expect(state.state).toBe(AgentLoopState.RUNNING) - expect(state.isStreaming).toBe(false) - }) - }) - - describe("WAITING_FOR_INPUT state", () => { - it("should detect waiting for tool approval", () => { - const messages = [createMessage({ type: "ask", ask: "tool", partial: false })] - const state = detectAgentState(messages) - expect(state.state).toBe(AgentLoopState.WAITING_FOR_INPUT) - expect(state.isWaitingForInput).toBe(true) - expect(state.currentAsk).toBe("tool") - expect(state.requiredAction).toBe("approve") - }) - - it("should detect waiting for command approval", () => { - const messages = [createMessage({ type: "ask", ask: "command", partial: false })] - const state = detectAgentState(messages) - expect(state.state).toBe(AgentLoopState.WAITING_FOR_INPUT) - expect(state.currentAsk).toBe("command") - expect(state.requiredAction).toBe("approve") - }) - - it("should detect waiting for followup answer", () => { - const messages = [createMessage({ type: "ask", ask: "followup", partial: false })] - const state = detectAgentState(messages) - expect(state.state).toBe(AgentLoopState.WAITING_FOR_INPUT) - expect(state.currentAsk).toBe("followup") - expect(state.requiredAction).toBe("answer") - }) - - it("should detect waiting for browser_action_launch approval", () => { - const messages = [createMessage({ type: "ask", ask: "browser_action_launch", partial: false })] - const state = detectAgentState(messages) - expect(state.state).toBe(AgentLoopState.WAITING_FOR_INPUT) - expect(state.requiredAction).toBe("approve") - }) - - it("should detect waiting for use_mcp_server approval", () => { - const messages = [createMessage({ type: "ask", ask: "use_mcp_server", partial: false })] - const state = detectAgentState(messages) - expect(state.state).toBe(AgentLoopState.WAITING_FOR_INPUT) - expect(state.requiredAction).toBe("approve") - }) - }) - - describe("IDLE state", () => { - it("should detect completion_result as idle", () => { - const messages = [createMessage({ type: "ask", ask: "completion_result", partial: false })] - const state = detectAgentState(messages) - expect(state.state).toBe(AgentLoopState.IDLE) - expect(state.isWaitingForInput).toBe(true) - expect(state.requiredAction).toBe("start_task") - }) - - it("should detect api_req_failed as idle", () => { - const messages = [createMessage({ type: "ask", ask: "api_req_failed", partial: false })] - const state = detectAgentState(messages) - expect(state.state).toBe(AgentLoopState.IDLE) - expect(state.requiredAction).toBe("retry_or_new_task") - }) - - it("should detect mistake_limit_reached as idle", () => { - const messages = [createMessage({ type: "ask", ask: "mistake_limit_reached", partial: false })] - const state = detectAgentState(messages) - expect(state.state).toBe(AgentLoopState.IDLE) - expect(state.requiredAction).toBe("proceed_or_new_task") - }) - - it("should detect auto_approval_max_req_reached as idle", () => { - const messages = [createMessage({ type: "ask", ask: "auto_approval_max_req_reached", partial: false })] - const state = detectAgentState(messages) - expect(state.state).toBe(AgentLoopState.IDLE) - expect(state.requiredAction).toBe("start_new_task") - }) - - it("should detect resume_completed_task as idle", () => { - const messages = [createMessage({ type: "ask", ask: "resume_completed_task", partial: false })] - const state = detectAgentState(messages) - expect(state.state).toBe(AgentLoopState.IDLE) - expect(state.requiredAction).toBe("start_new_task") - }) - }) - - describe("RESUMABLE state", () => { - it("should detect resume_task as resumable", () => { - const messages = [createMessage({ type: "ask", ask: "resume_task", partial: false })] - const state = detectAgentState(messages) - expect(state.state).toBe(AgentLoopState.RESUMABLE) - expect(state.isWaitingForInput).toBe(true) - expect(state.requiredAction).toBe("resume_or_abandon") - }) - }) - - describe("RUNNING state", () => { - it("should detect running for say messages", () => { - const messages = [ - createMessage({ - say: "api_req_started", - text: JSON.stringify({ cost: 0.001 }), - }), - createMessage({ say: "text", text: "Working on it..." }), - ] - const state = detectAgentState(messages) - expect(state.state).toBe(AgentLoopState.RUNNING) - expect(state.isRunning).toBe(true) - expect(state.isWaitingForInput).toBe(false) - }) - - it("should detect running for command_output (non-blocking)", () => { - const messages = [createMessage({ type: "ask", ask: "command_output", partial: false })] - const state = detectAgentState(messages) - expect(state.state).toBe(AgentLoopState.RUNNING) - expect(state.requiredAction).toBe("continue_or_abort") - }) - }) -}) - -describe("Type Guards", () => { - describe("isIdleAsk", () => { - it("should return true for idle asks", () => { - expect(isIdleAsk("completion_result")).toBe(true) - expect(isIdleAsk("api_req_failed")).toBe(true) - expect(isIdleAsk("mistake_limit_reached")).toBe(true) - expect(isIdleAsk("auto_approval_max_req_reached")).toBe(true) - expect(isIdleAsk("resume_completed_task")).toBe(true) - }) - - it("should return false for non-idle asks", () => { - expect(isIdleAsk("tool")).toBe(false) - expect(isIdleAsk("followup")).toBe(false) - expect(isIdleAsk("resume_task")).toBe(false) - }) - }) - - describe("isInteractiveAsk", () => { - it("should return true for interactive asks", () => { - expect(isInteractiveAsk("tool")).toBe(true) - expect(isInteractiveAsk("command")).toBe(true) - expect(isInteractiveAsk("followup")).toBe(true) - expect(isInteractiveAsk("browser_action_launch")).toBe(true) - expect(isInteractiveAsk("use_mcp_server")).toBe(true) - }) - - it("should return false for non-interactive asks", () => { - expect(isInteractiveAsk("completion_result")).toBe(false) - expect(isInteractiveAsk("command_output")).toBe(false) - }) - }) - - describe("isResumableAsk", () => { - it("should return true for resumable asks", () => { - expect(isResumableAsk("resume_task")).toBe(true) - }) - - it("should return false for non-resumable asks", () => { - expect(isResumableAsk("completion_result")).toBe(false) - expect(isResumableAsk("tool")).toBe(false) - }) - }) - - describe("isNonBlockingAsk", () => { - it("should return true for non-blocking asks", () => { - expect(isNonBlockingAsk("command_output")).toBe(true) - }) - - it("should return false for blocking asks", () => { - expect(isNonBlockingAsk("tool")).toBe(false) - expect(isNonBlockingAsk("followup")).toBe(false) - }) - }) -}) - -describe("ExtensionClient", () => { - describe("State queries", () => { - it("should return NO_TASK when not initialized", () => { - const { client } = createMockClient() - expect(client.getCurrentState()).toBe(AgentLoopState.NO_TASK) - expect(client.isInitialized()).toBe(false) - }) - - it("should update state when receiving messages", () => { - const { client } = createMockClient() - - const message = createStateMessage([createMessage({ type: "ask", ask: "tool", partial: false })]) - - client.handleMessage(message) - - expect(client.isInitialized()).toBe(true) - expect(client.getCurrentState()).toBe(AgentLoopState.WAITING_FOR_INPUT) - expect(client.isWaitingForInput()).toBe(true) - expect(client.getCurrentAsk()).toBe("tool") - }) - }) - - describe("Event emission", () => { - it("should emit stateChange events", () => { - const { client } = createMockClient() - const stateChanges: AgentLoopState[] = [] - - client.onStateChange((event) => { - stateChanges.push(event.currentState.state) - }) - - client.handleMessage(createStateMessage([createMessage({ type: "ask", ask: "tool", partial: false })])) - - expect(stateChanges).toContain(AgentLoopState.WAITING_FOR_INPUT) - }) - - it("should emit waitingForInput events", () => { - const { client } = createMockClient() - const waitingEvents: string[] = [] - - client.onWaitingForInput((event) => { - waitingEvents.push(event.ask) - }) - - client.handleMessage(createStateMessage([createMessage({ type: "ask", ask: "followup", partial: false })])) - - expect(waitingEvents).toContain("followup") - }) - - it("should allow unsubscribing from events", () => { - const { client } = createMockClient() - let callCount = 0 - - const unsubscribe = client.onStateChange(() => { - callCount++ - }) - - client.handleMessage(createStateMessage([createMessage({ say: "text" })])) - expect(callCount).toBe(1) - - unsubscribe() - - client.handleMessage(createStateMessage([createMessage({ say: "text", ts: Date.now() + 1 })])) - expect(callCount).toBe(1) // Should not increase. - }) - - it("should emit modeChanged events", () => { - const { client } = createMockClient() - const modeChanges: { previousMode: string | undefined; currentMode: string }[] = [] - - client.onModeChanged((event) => { - modeChanges.push(event) - }) - - // Set initial mode - client.handleMessage(createStateMessage([createMessage({ say: "text" })], "code")) - - expect(modeChanges).toHaveLength(1) - expect(modeChanges[0]).toEqual({ previousMode: undefined, currentMode: "code" }) - - // Change mode - client.handleMessage(createStateMessage([createMessage({ say: "text" })], "architect")) - - expect(modeChanges).toHaveLength(2) - expect(modeChanges[1]).toEqual({ previousMode: "code", currentMode: "architect" }) - }) - - it("should not emit modeChanged when mode stays the same", () => { - const { client } = createMockClient() - let modeChangeCount = 0 - - client.onModeChanged(() => { - modeChangeCount++ - }) - - // Set initial mode - client.handleMessage(createStateMessage([createMessage({ say: "text" })], "code")) - expect(modeChangeCount).toBe(1) - - // Same mode - should not emit - client.handleMessage(createStateMessage([createMessage({ say: "text", ts: Date.now() + 1 })], "code")) - expect(modeChangeCount).toBe(1) - }) - }) - - describe("Response methods", () => { - it("should send approve response", () => { - const { client, sentMessages } = createMockClient() - - client.approve() - - expect(sentMessages).toHaveLength(1) - expect(sentMessages[0]).toEqual({ - type: "askResponse", - askResponse: "yesButtonClicked", - text: undefined, - images: undefined, - }) - }) - - it("should send reject response", () => { - const { client, sentMessages } = createMockClient() - - client.reject() - - expect(sentMessages).toHaveLength(1) - const msg = sentMessages[0] - expect(msg).toBeDefined() - expect(msg?.askResponse).toBe("noButtonClicked") - }) - - it("should send text response", () => { - const { client, sentMessages } = createMockClient() - - client.respond("My answer", ["image-data"]) - - expect(sentMessages).toHaveLength(1) - expect(sentMessages[0]).toEqual({ - type: "askResponse", - askResponse: "messageResponse", - text: "My answer", - images: ["image-data"], - }) - }) - - it("should send newTask message", () => { - const { client, sentMessages } = createMockClient() - - client.newTask("Build a web app") - - expect(sentMessages).toHaveLength(1) - expect(sentMessages[0]).toEqual({ - type: "newTask", - text: "Build a web app", - images: undefined, - }) - }) - - it("should send clearTask message", () => { - const { client, sentMessages } = createMockClient() - - client.clearTask() - - expect(sentMessages).toHaveLength(1) - expect(sentMessages[0]).toEqual({ - type: "clearTask", - }) - }) - - it("should send cancelTask message", () => { - const { client, sentMessages } = createMockClient() - - client.cancelTask() - - expect(sentMessages).toHaveLength(1) - expect(sentMessages[0]).toEqual({ - type: "cancelTask", - }) - }) - - it("should send terminal continue operation", () => { - const { client, sentMessages } = createMockClient() - - client.continueTerminal() - - expect(sentMessages).toHaveLength(1) - expect(sentMessages[0]).toEqual({ - type: "terminalOperation", - terminalOperation: "continue", - }) - }) - - it("should send terminal abort operation", () => { - const { client, sentMessages } = createMockClient() - - client.abortTerminal() - - expect(sentMessages).toHaveLength(1) - expect(sentMessages[0]).toEqual({ - type: "terminalOperation", - terminalOperation: "abort", - }) - }) - }) - - describe("Message handling", () => { - it("should handle JSON string messages", () => { - const { client } = createMockClient() - - const message = JSON.stringify( - createStateMessage([createMessage({ type: "ask", ask: "completion_result", partial: false })]), - ) - - client.handleMessage(message) - - expect(client.getCurrentState()).toBe(AgentLoopState.IDLE) - }) - - it("should ignore invalid JSON", () => { - const { client } = createMockClient() - - client.handleMessage("not valid json") - - expect(client.getCurrentState()).toBe(AgentLoopState.NO_TASK) - }) - - it("should handle messageUpdated messages", () => { - const { client } = createMockClient() - - // First, set initial state. - client.handleMessage( - createStateMessage([createMessage({ ts: 123, type: "ask", ask: "tool", partial: true })]), - ) - - expect(client.isStreaming()).toBe(true) - - // Now update the message. - client.handleMessage({ - type: "messageUpdated", - clineMessage: createMessage({ ts: 123, type: "ask", ask: "tool", partial: false }), - }) - - expect(client.isStreaming()).toBe(false) - expect(client.isWaitingForInput()).toBe(true) - }) - }) - - describe("Reset functionality", () => { - it("should reset state", () => { - const { client } = createMockClient() - - client.handleMessage(createStateMessage([createMessage({ type: "ask", ask: "tool", partial: false })])) - - expect(client.isInitialized()).toBe(true) - expect(client.getCurrentState()).toBe(AgentLoopState.WAITING_FOR_INPUT) - - client.reset() - - expect(client.isInitialized()).toBe(false) - expect(client.getCurrentState()).toBe(AgentLoopState.NO_TASK) - }) - - it("should reset mode on reset", () => { - const { client } = createMockClient() - - client.handleMessage(createStateMessage([createMessage({ say: "text" })], "code")) - expect(client.getCurrentMode()).toBe("code") - - client.reset() - - expect(client.getCurrentMode()).toBeUndefined() - }) - }) - - describe("Mode tracking", () => { - it("should return undefined mode when not initialized", () => { - const { client } = createMockClient() - expect(client.getCurrentMode()).toBeUndefined() - }) - - it("should track mode from state messages", () => { - const { client } = createMockClient() - - client.handleMessage(createStateMessage([createMessage({ say: "text" })], "code")) - - expect(client.getCurrentMode()).toBe("code") - }) - - it("should update mode when it changes", () => { - const { client } = createMockClient() - - client.handleMessage(createStateMessage([createMessage({ say: "text" })], "code")) - expect(client.getCurrentMode()).toBe("code") - - client.handleMessage(createStateMessage([createMessage({ say: "text", ts: Date.now() + 1 })], "architect")) - expect(client.getCurrentMode()).toBe("architect") - }) - - it("should preserve mode when state message has no mode", () => { - const { client } = createMockClient() - - // Set initial mode - client.handleMessage(createStateMessage([createMessage({ say: "text" })], "code")) - expect(client.getCurrentMode()).toBe("code") - - // State update without mode - should preserve existing mode - client.handleMessage(createStateMessage([createMessage({ say: "text", ts: Date.now() + 1 })])) - expect(client.getCurrentMode()).toBe("code") - }) - - it("should preserve mode when task is cleared", () => { - const { client } = createMockClient() - - client.handleMessage(createStateMessage([createMessage({ say: "text" })], "architect")) - expect(client.getCurrentMode()).toBe("architect") - - client.clearTask() - // Mode should be preserved after clear - expect(client.getCurrentMode()).toBe("architect") - }) - }) -}) - -describe("Integration", () => { - it("should handle a complete task flow", () => { - const { client } = createMockClient() - const states: AgentLoopState[] = [] - - client.onStateChange((event) => { - states.push(event.currentState.state) - }) - - // 1. Task starts, API request begins. - client.handleMessage( - createStateMessage([ - createMessage({ - say: "api_req_started", - text: JSON.stringify({}), // No cost = streaming. - }), - ]), - ) - expect(client.isStreaming()).toBe(true) - - // 2. API request completes. - client.handleMessage( - createStateMessage([ - createMessage({ - say: "api_req_started", - text: JSON.stringify({ cost: 0.001 }), - }), - createMessage({ say: "text", text: "I'll help you with that." }), - ]), - ) - expect(client.isStreaming()).toBe(false) - expect(client.isRunning()).toBe(true) - - // 3. Tool ask (partial). - client.handleMessage( - createStateMessage([ - createMessage({ - say: "api_req_started", - text: JSON.stringify({ cost: 0.001 }), - }), - createMessage({ say: "text", text: "I'll help you with that." }), - createMessage({ type: "ask", ask: "tool", partial: true }), - ]), - ) - expect(client.isStreaming()).toBe(true) - - // 4. Tool ask (complete). - client.handleMessage( - createStateMessage([ - createMessage({ - say: "api_req_started", - text: JSON.stringify({ cost: 0.001 }), - }), - createMessage({ say: "text", text: "I'll help you with that." }), - createMessage({ type: "ask", ask: "tool", partial: false }), - ]), - ) - expect(client.isWaitingForInput()).toBe(true) - expect(client.getCurrentAsk()).toBe("tool") - - // 5. User approves, task completes. - client.handleMessage( - createStateMessage([ - createMessage({ - say: "api_req_started", - text: JSON.stringify({ cost: 0.001 }), - }), - createMessage({ say: "text", text: "I'll help you with that." }), - createMessage({ type: "ask", ask: "tool", partial: false }), - createMessage({ say: "text", text: "File created." }), - createMessage({ type: "ask", ask: "completion_result", partial: false }), - ]), - ) - expect(client.getCurrentState()).toBe(AgentLoopState.IDLE) - expect(client.getCurrentAsk()).toBe("completion_result") - - // Verify we saw the expected state transitions. - expect(states).toContain(AgentLoopState.STREAMING) - expect(states).toContain(AgentLoopState.RUNNING) - expect(states).toContain(AgentLoopState.WAITING_FOR_INPUT) - expect(states).toContain(AgentLoopState.IDLE) - }) -}) - -describe("Edge Cases", () => { - describe("Messages with missing or empty text field", () => { - it("should handle ask message with missing text field", () => { - const messages = [createMessage({ type: "ask", ask: "tool", partial: false })] - // Text is undefined by default. - const state = detectAgentState(messages) - expect(state.state).toBe(AgentLoopState.WAITING_FOR_INPUT) - expect(state.currentAsk).toBe("tool") - }) - - it("should handle ask message with empty text field", () => { - const messages = [createMessage({ type: "ask", ask: "followup", partial: false, text: "" })] - const state = detectAgentState(messages) - expect(state.state).toBe(AgentLoopState.WAITING_FOR_INPUT) - expect(state.currentAsk).toBe("followup") - }) - - it("should handle say message with missing text field", () => { - const messages = [createMessage({ say: "text" })] - const state = detectAgentState(messages) - expect(state.state).toBe(AgentLoopState.RUNNING) - }) - }) - - describe("api_req_started edge cases", () => { - it("should handle api_req_started with empty text field as streaming", () => { - const messages = [createMessage({ say: "api_req_started", text: "" })] - const state = detectAgentState(messages) - // Empty text is treated as "no text yet" = still in progress (streaming). - // This matches the behavior: !message.text is true for "" (falsy). - expect(state.state).toBe(AgentLoopState.STREAMING) - expect(state.isStreaming).toBe(true) - }) - - it("should handle api_req_started with invalid JSON", () => { - const messages = [createMessage({ say: "api_req_started", text: "not valid json" })] - const state = detectAgentState(messages) - // Invalid JSON should not crash, should return not streaming. - expect(state.state).toBe(AgentLoopState.RUNNING) - expect(state.isStreaming).toBe(false) - }) - - it("should handle api_req_started with null text", () => { - const messages = [createMessage({ say: "api_req_started", text: undefined })] - const state = detectAgentState(messages) - // No text means still in progress (streaming). - expect(state.state).toBe(AgentLoopState.STREAMING) - expect(state.isStreaming).toBe(true) - }) - - it("should handle api_req_started with cost of 0", () => { - const messages = [createMessage({ say: "api_req_started", text: JSON.stringify({ cost: 0 }) })] - const state = detectAgentState(messages) - // cost: 0 is defined (not undefined), so NOT streaming. - expect(state.state).toBe(AgentLoopState.RUNNING) - expect(state.isStreaming).toBe(false) - }) - - it("should handle api_req_started with cost of null", () => { - const messages = [createMessage({ say: "api_req_started", text: JSON.stringify({ cost: null }) })] - const state = detectAgentState(messages) - // cost: null is defined (not undefined), so NOT streaming. - expect(state.state).toBe(AgentLoopState.RUNNING) - expect(state.isStreaming).toBe(false) - }) - - it("should find api_req_started when it's not the last message", () => { - const messages = [ - createMessage({ say: "api_req_started", text: JSON.stringify({ tokensIn: 100 }) }), // No cost = streaming - createMessage({ say: "text", text: "Some text" }), - ] - const state = detectAgentState(messages) - // Last message is say:text, but api_req_started has no cost. - expect(state.state).toBe(AgentLoopState.STREAMING) - expect(state.isStreaming).toBe(true) - }) - }) - - describe("Rapid state transitions", () => { - it("should handle multiple rapid state changes", () => { - const { client } = createMockClient() - const states: AgentLoopState[] = [] - - client.onStateChange((event) => { - states.push(event.currentState.state) - }) - - // Rapid updates. - client.handleMessage(createStateMessage([createMessage({ say: "text" })])) - client.handleMessage(createStateMessage([createMessage({ type: "ask", ask: "tool", partial: true })])) - client.handleMessage(createStateMessage([createMessage({ type: "ask", ask: "tool", partial: false })])) - client.handleMessage( - createStateMessage([createMessage({ type: "ask", ask: "completion_result", partial: false })]), - ) - - // Should have tracked all transitions. - expect(states.length).toBeGreaterThanOrEqual(3) - expect(states).toContain(AgentLoopState.STREAMING) - expect(states).toContain(AgentLoopState.WAITING_FOR_INPUT) - expect(states).toContain(AgentLoopState.IDLE) - }) - }) - - describe("Message array edge cases", () => { - it("should handle single message array", () => { - const messages = [createMessage({ say: "text", text: "Hello" })] - const state = detectAgentState(messages) - expect(state.state).toBe(AgentLoopState.RUNNING) - expect(state.lastMessage).toBeDefined() - expect(state.lastMessageTs).toBe(messages[0]!.ts) - }) - - it("should use last message for state detection", () => { - // Multiple messages, last one determines state. - const messages = [ - createMessage({ type: "ask", ask: "tool", partial: false }), - createMessage({ say: "text", text: "Tool executed" }), - createMessage({ type: "ask", ask: "completion_result", partial: false }), - ] - const state = detectAgentState(messages) - // Last message is completion_result, so IDLE. - expect(state.state).toBe(AgentLoopState.IDLE) - expect(state.currentAsk).toBe("completion_result") - }) - - it("should handle very long message arrays", () => { - // Create many messages. - const messages: ClineMessage[] = [] - - for (let i = 0; i < 100; i++) { - messages.push(createMessage({ say: "text", text: `Message ${i}` })) - } - - messages.push(createMessage({ type: "ask", ask: "followup", partial: false })) - - const state = detectAgentState(messages) - expect(state.state).toBe(AgentLoopState.WAITING_FOR_INPUT) - expect(state.currentAsk).toBe("followup") - }) - }) - - describe("State message edge cases", () => { - it("should handle state message with empty clineMessages", () => { - const { client } = createMockClient() - client.handleMessage({ type: "state", state: { clineMessages: [] } } as unknown as ExtensionMessage) - expect(client.getCurrentState()).toBe(AgentLoopState.NO_TASK) - expect(client.isInitialized()).toBe(true) - }) - - it("should handle state message with missing clineMessages", () => { - const { client } = createMockClient() - - client.handleMessage({ - type: "state", - // eslint-disable-next-line @typescript-eslint/no-explicit-any - state: {} as any, - }) - - // Should not crash, state should remain unchanged. - expect(client.getCurrentState()).toBe(AgentLoopState.NO_TASK) - }) - - it("should handle state message with missing state field", () => { - const { client } = createMockClient() - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - client.handleMessage({ type: "state" } as any) - - // Should not crash - expect(client.getCurrentState()).toBe(AgentLoopState.NO_TASK) - }) - }) - - describe("Partial to complete transitions", () => { - it("should transition from streaming to waiting when partial becomes false", () => { - const ts = Date.now() - const messages1 = [createMessage({ ts, type: "ask", ask: "tool", partial: true })] - const messages2 = [createMessage({ ts, type: "ask", ask: "tool", partial: false })] - - const state1 = detectAgentState(messages1) - const state2 = detectAgentState(messages2) - - expect(state1.state).toBe(AgentLoopState.STREAMING) - expect(state1.isWaitingForInput).toBe(false) - - expect(state2.state).toBe(AgentLoopState.WAITING_FOR_INPUT) - expect(state2.isWaitingForInput).toBe(true) - }) - - it("should handle partial say messages", () => { - const messages = [createMessage({ say: "text", text: "Typing...", partial: true })] - const state = detectAgentState(messages) - expect(state.state).toBe(AgentLoopState.STREAMING) - expect(state.isStreaming).toBe(true) - }) - }) - - describe("Unknown message types", () => { - it("should handle unknown ask types gracefully", () => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const messages = [createMessage({ type: "ask", ask: "unknown_type" as any, partial: false })] - const state = detectAgentState(messages) - // Unknown ask type should default to RUNNING. - expect(state.state).toBe(AgentLoopState.RUNNING) - }) - - it("should handle unknown say types gracefully", () => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const messages = [createMessage({ say: "unknown_say_type" as any })] - const state = detectAgentState(messages) - expect(state.state).toBe(AgentLoopState.RUNNING) - }) - }) -}) diff --git a/apps/cli/src/agent/__tests__/extension-host.test.ts b/apps/cli/src/agent/__tests__/extension-host.test.ts deleted file mode 100644 index 38edf50d283..00000000000 --- a/apps/cli/src/agent/__tests__/extension-host.test.ts +++ /dev/null @@ -1,596 +0,0 @@ -// pnpm --filter @roo-code/cli test src/agent/__tests__/extension-host.test.ts - -import { EventEmitter } from "events" -import fs from "fs" - -import type { ExtensionMessage, WebviewMessage } from "@roo-code/types" - -import { type ExtensionHostOptions, ExtensionHost } from "../extension-host.js" -import { ExtensionClient } from "../extension-client.js" -import { AgentLoopState } from "../agent-state.js" - -vi.mock("@roo-code/vscode-shim", () => ({ - createVSCodeAPI: vi.fn(() => ({ - context: { extensionPath: "/test/extension" }, - })), - setRuntimeConfigValues: vi.fn(), -})) - -vi.mock("@/lib/storage/index.js", () => ({ - createEphemeralStorageDir: vi.fn(() => Promise.resolve("/tmp/roo-cli-test-ephemeral")), -})) - -/** - * Create a test ExtensionHost with default options. - */ -function createTestHost({ - mode = "code", - provider = "openrouter", - model = "test-model", - ...options -}: Partial = {}): ExtensionHost { - return new ExtensionHost({ - mode, - user: null, - provider, - model, - workspacePath: "/test/workspace", - extensionPath: "/test/extension", - ...options, - }) -} - -// Type for accessing private members -type PrivateHost = Record - -/** - * Helper to access private members for testing - */ -function getPrivate(host: ExtensionHost, key: string): T { - return (host as unknown as PrivateHost)[key] as T -} - -/** - * Helper to set private members for testing - */ -function setPrivate(host: ExtensionHost, key: string, value: unknown): void { - ;(host as unknown as PrivateHost)[key] = value -} - -/** - * Helper to call private methods for testing - * This uses a more permissive type to avoid TypeScript errors with private methods - */ -function callPrivate(host: ExtensionHost, method: string, ...args: unknown[]): T { - const fn = (host as unknown as PrivateHost)[method] as ((...a: unknown[]) => T) | undefined - if (!fn) throw new Error(`Method ${method} not found`) - return fn.apply(host, args) -} - -/** - * Helper to spy on private methods - * This uses a more permissive type to avoid TypeScript errors with vi.spyOn on private methods - */ -function spyOnPrivate(host: ExtensionHost, method: string) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return vi.spyOn(host as any, method) -} - -describe("ExtensionHost", () => { - beforeEach(() => { - vi.resetAllMocks() - // Clean up globals - delete (global as Record).vscode - delete (global as Record).__extensionHost - }) - - describe("constructor", () => { - it("should store options correctly", () => { - const options: ExtensionHostOptions = { - mode: "code", - workspacePath: "/my/workspace", - extensionPath: "/my/extension", - user: null, - apiKey: "test-key", - provider: "openrouter", - model: "test-model", - } - - const host = new ExtensionHost(options) - - // Options are stored but integrationTest is set to true - const storedOptions = getPrivate(host, "options") - expect(storedOptions.mode).toBe(options.mode) - expect(storedOptions.workspacePath).toBe(options.workspacePath) - expect(storedOptions.extensionPath).toBe(options.extensionPath) - expect(storedOptions.integrationTest).toBe(true) // Always set to true in constructor - }) - - it("should be an EventEmitter instance", () => { - const host = createTestHost() - expect(host).toBeInstanceOf(EventEmitter) - }) - - it("should initialize with default state values", () => { - const host = createTestHost() - - expect(getPrivate(host, "isReady")).toBe(false) - expect(getPrivate(host, "vscode")).toBeNull() - expect(getPrivate(host, "extensionModule")).toBeNull() - }) - - it("should initialize managers", () => { - const host = createTestHost() - - // Should have client, outputManager, promptManager, and askDispatcher - expect(getPrivate(host, "client")).toBeDefined() - expect(getPrivate(host, "outputManager")).toBeDefined() - expect(getPrivate(host, "promptManager")).toBeDefined() - expect(getPrivate(host, "askDispatcher")).toBeDefined() - }) - }) - - describe("webview provider registration", () => { - it("should register webview provider without throwing", () => { - const host = createTestHost() - const mockProvider = { resolveWebviewView: vi.fn() } - - // registerWebviewProvider is now a no-op, just ensure it doesn't throw - expect(() => { - host.registerWebviewProvider("test-view", mockProvider) - }).not.toThrow() - }) - - it("should unregister webview provider without throwing", () => { - const host = createTestHost() - const mockProvider = { resolveWebviewView: vi.fn() } - - host.registerWebviewProvider("test-view", mockProvider) - - // unregisterWebviewProvider is now a no-op, just ensure it doesn't throw - expect(() => { - host.unregisterWebviewProvider("test-view") - }).not.toThrow() - }) - - it("should handle unregistering non-existent provider gracefully", () => { - const host = createTestHost() - - expect(() => { - host.unregisterWebviewProvider("non-existent") - }).not.toThrow() - }) - }) - - describe("webview ready state", () => { - describe("isInInitialSetup", () => { - it("should return true before webview is ready", () => { - const host = createTestHost() - expect(host.isInInitialSetup()).toBe(true) - }) - - it("should return false after markWebviewReady is called", () => { - const host = createTestHost() - host.markWebviewReady() - expect(host.isInInitialSetup()).toBe(false) - }) - }) - - describe("markWebviewReady", () => { - it("should set isReady to true", () => { - const host = createTestHost() - host.markWebviewReady() - expect(getPrivate(host, "isReady")).toBe(true) - }) - - it("should send webviewDidLaunch message", () => { - const host = createTestHost() - const emitSpy = vi.spyOn(host, "emit") - - host.markWebviewReady() - - expect(emitSpy).toHaveBeenCalledWith("webviewMessage", { type: "webviewDidLaunch" }) - }) - - it("should send updateSettings message", () => { - const host = createTestHost() - const emitSpy = vi.spyOn(host, "emit") - - host.markWebviewReady() - - // Check that updateSettings was called - const updateSettingsCall = emitSpy.mock.calls.find( - (call) => - call[0] === "webviewMessage" && - typeof call[1] === "object" && - call[1] !== null && - (call[1] as WebviewMessage).type === "updateSettings", - ) - expect(updateSettingsCall).toBeDefined() - }) - }) - }) - - describe("sendToExtension", () => { - it("should throw error when extension not ready", () => { - const host = createTestHost() - const message: WebviewMessage = { type: "requestModes" } - - expect(() => { - host.sendToExtension(message) - }).toThrow("You cannot send messages to the extension before it is ready") - }) - - it("should emit webviewMessage event when webview is ready", () => { - const host = createTestHost() - const emitSpy = vi.spyOn(host, "emit") - const message: WebviewMessage = { type: "requestModes" } - - host.markWebviewReady() - emitSpy.mockClear() // Clear the markWebviewReady calls - host.sendToExtension(message) - - expect(emitSpy).toHaveBeenCalledWith("webviewMessage", message) - }) - - it("should not throw when webview is ready", () => { - const host = createTestHost() - - host.markWebviewReady() - - expect(() => { - host.sendToExtension({ type: "requestModes" }) - }).not.toThrow() - }) - }) - - describe("message handling via client", () => { - it("should forward extension messages to the client", () => { - const host = createTestHost() - const client = getPrivate(host, "client") as ExtensionClient - - // Simulate extension message. - host.emit("extensionWebviewMessage", { - type: "state", - state: { clineMessages: [] }, - } as unknown as ExtensionMessage) - - // Message listener is set up in activate(), which we can't easily call in unit tests. - // But we can verify the client exists and has the handleMessage method. - expect(typeof client.handleMessage).toBe("function") - }) - }) - - describe("public agent state API", () => { - it("should return agent state from getAgentState()", () => { - const host = createTestHost() - const state = host.getAgentState() - - expect(state).toBeDefined() - expect(state.state).toBeDefined() - expect(state.isWaitingForInput).toBeDefined() - expect(state.isRunning).toBeDefined() - }) - - it("should return isWaitingForInput() status", () => { - const host = createTestHost() - expect(typeof host.isWaitingForInput()).toBe("boolean") - }) - }) - - describe("quiet mode", () => { - describe("setupQuietMode", () => { - it("should not modify console when integrationTest is true", () => { - // By default, constructor sets integrationTest = true - const host = createTestHost() - const originalLog = console.log - - callPrivate(host, "setupQuietMode") - - // Console should not be modified since integrationTest is true - expect(console.log).toBe(originalLog) - }) - - it("should suppress console when integrationTest is false", () => { - const host = createTestHost() - const originalLog = console.log - - // Override integrationTest to false - const options = getPrivate(host, "options") - options.integrationTest = false - - callPrivate(host, "setupQuietMode") - - // Console should be modified - expect(console.log).not.toBe(originalLog) - - // Restore for other tests - callPrivate(host, "restoreConsole") - }) - - it("should preserve console.error even when suppressing", () => { - const host = createTestHost() - const originalError = console.error - - // Override integrationTest to false - const options = getPrivate(host, "options") - options.integrationTest = false - - callPrivate(host, "setupQuietMode") - - expect(console.error).toBe(originalError) - - callPrivate(host, "restoreConsole") - }) - }) - - describe("restoreConsole", () => { - it("should restore original console methods when suppressed", () => { - const host = createTestHost() - const originalLog = console.log - - // Override integrationTest to false to actually suppress - const options = getPrivate(host, "options") - options.integrationTest = false - - callPrivate(host, "setupQuietMode") - callPrivate(host, "restoreConsole") - - expect(console.log).toBe(originalLog) - }) - - it("should handle case where console was not suppressed", () => { - const host = createTestHost() - - expect(() => { - callPrivate(host, "restoreConsole") - }).not.toThrow() - }) - }) - }) - - describe("dispose", () => { - let host: ExtensionHost - - beforeEach(() => { - host = createTestHost() - }) - - it("should remove message listener", async () => { - const listener = vi.fn() - setPrivate(host, "messageListener", listener) - host.on("extensionWebviewMessage", listener) - - await host.dispose() - - expect(getPrivate(host, "messageListener")).toBeNull() - }) - - it("should call extension deactivate if available", async () => { - const deactivateMock = vi.fn() - setPrivate(host, "extensionModule", { - deactivate: deactivateMock, - }) - - await host.dispose() - - expect(deactivateMock).toHaveBeenCalled() - }) - - it("should clear vscode reference", async () => { - setPrivate(host, "vscode", { context: {} }) - - await host.dispose() - - expect(getPrivate(host, "vscode")).toBeNull() - }) - - it("should clear extensionModule reference", async () => { - setPrivate(host, "extensionModule", {}) - - await host.dispose() - - expect(getPrivate(host, "extensionModule")).toBeNull() - }) - - it("should delete global vscode", async () => { - ;(global as Record).vscode = {} - - await host.dispose() - - expect((global as Record).vscode).toBeUndefined() - }) - - it("should delete global __extensionHost", async () => { - ;(global as Record).__extensionHost = {} - - await host.dispose() - - expect((global as Record).__extensionHost).toBeUndefined() - }) - - it("should call restoreConsole", async () => { - const restoreConsoleSpy = spyOnPrivate(host, "restoreConsole") - - await host.dispose() - - expect(restoreConsoleSpy).toHaveBeenCalled() - }) - }) - - describe("runTask", () => { - it("should send newTask message when called", async () => { - const host = createTestHost() - host.markWebviewReady() - - const emitSpy = vi.spyOn(host, "emit") - const client = getPrivate(host, "client") as ExtensionClient - - // Start the task (will hang waiting for completion) - const taskPromise = host.runTask("test prompt") - - // Emit completion to resolve the promise via the client's emitter - const taskCompletedEvent = { - success: true, - stateInfo: { - state: AgentLoopState.IDLE, - isWaitingForInput: false, - isRunning: false, - isStreaming: false, - requiredAction: "start_task" as const, - description: "Task completed", - }, - } - setTimeout(() => client.getEmitter().emit("taskCompleted", taskCompletedEvent), 10) - - await taskPromise - - expect(emitSpy).toHaveBeenCalledWith("webviewMessage", { type: "newTask", text: "test prompt" }) - }) - - it("should resolve when taskCompleted is emitted on client", async () => { - const host = createTestHost() - host.markWebviewReady() - - const client = getPrivate(host, "client") as ExtensionClient - const taskPromise = host.runTask("test prompt") - - // Emit completion after a short delay via the client's emitter - const taskCompletedEvent = { - success: true, - stateInfo: { - state: AgentLoopState.IDLE, - isWaitingForInput: false, - isRunning: false, - isStreaming: false, - requiredAction: "start_task" as const, - description: "Task completed", - }, - } - setTimeout(() => client.getEmitter().emit("taskCompleted", taskCompletedEvent), 10) - - await expect(taskPromise).resolves.toBeUndefined() - }) - }) - - describe("initial settings", () => { - it("should set mode from options", () => { - const host = createTestHost({ mode: "architect" }) - - const initialSettings = getPrivate>(host, "initialSettings") - expect(initialSettings.mode).toBe("architect") - }) - - it("should enable auto-approval in non-interactive mode", () => { - const host = createTestHost({ nonInteractive: true }) - - const initialSettings = getPrivate>(host, "initialSettings") - expect(initialSettings.autoApprovalEnabled).toBe(true) - expect(initialSettings.alwaysAllowReadOnly).toBe(true) - expect(initialSettings.alwaysAllowWrite).toBe(true) - expect(initialSettings.alwaysAllowExecute).toBe(true) - }) - - it("should disable auto-approval in interactive mode", () => { - const host = createTestHost({ nonInteractive: false }) - - const initialSettings = getPrivate>(host, "initialSettings") - expect(initialSettings.autoApprovalEnabled).toBe(false) - }) - - it("should set reasoning effort when specified", () => { - const host = createTestHost({ reasoningEffort: "high" }) - - const initialSettings = getPrivate>(host, "initialSettings") - expect(initialSettings.enableReasoningEffort).toBe(true) - expect(initialSettings.reasoningEffort).toBe("high") - }) - - it("should disable reasoning effort when set to disabled", () => { - const host = createTestHost({ reasoningEffort: "disabled" }) - - const initialSettings = getPrivate>(host, "initialSettings") - expect(initialSettings.enableReasoningEffort).toBe(false) - }) - - it("should not set reasoning effort when unspecified", () => { - const host = createTestHost({ reasoningEffort: "unspecified" }) - - const initialSettings = getPrivate>(host, "initialSettings") - expect(initialSettings.enableReasoningEffort).toBeUndefined() - expect(initialSettings.reasoningEffort).toBeUndefined() - }) - }) - - describe("ephemeral mode", () => { - it("should store ephemeral option correctly", () => { - const host = createTestHost({ ephemeral: true }) - - const options = getPrivate(host, "options") - expect(options.ephemeral).toBe(true) - }) - - it("should default ephemeralStorageDir to null", () => { - const host = createTestHost() - - expect(getPrivate(host, "ephemeralStorageDir")).toBeNull() - }) - - it("should clean up ephemeral storage directory on dispose", async () => { - const host = createTestHost({ ephemeral: true }) - - // Set up a mock ephemeral storage directory - const mockEphemeralDir = "/tmp/roo-cli-test-ephemeral-cleanup" - setPrivate(host, "ephemeralStorageDir", mockEphemeralDir) - - // Mock fs.promises.rm - const rmMock = vi.spyOn(fs.promises, "rm").mockResolvedValue(undefined) - - await host.dispose() - - expect(rmMock).toHaveBeenCalledWith(mockEphemeralDir, { recursive: true, force: true }) - expect(getPrivate(host, "ephemeralStorageDir")).toBeNull() - - rmMock.mockRestore() - }) - - it("should not clean up when ephemeralStorageDir is null", async () => { - const host = createTestHost() - - // ephemeralStorageDir is null by default - expect(getPrivate(host, "ephemeralStorageDir")).toBeNull() - - const rmMock = vi.spyOn(fs.promises, "rm").mockResolvedValue(undefined) - - await host.dispose() - - // rm should not be called when there's no ephemeral storage - expect(rmMock).not.toHaveBeenCalled() - - rmMock.mockRestore() - }) - - it("should handle ephemeral storage cleanup errors gracefully", async () => { - const host = createTestHost({ ephemeral: true }) - - // Set up a mock ephemeral storage directory - setPrivate(host, "ephemeralStorageDir", "/tmp/roo-cli-test-ephemeral-error") - - // Mock fs.promises.rm to throw an error - const rmMock = vi.spyOn(fs.promises, "rm").mockRejectedValue(new Error("Cleanup failed")) - - // dispose should not throw even if cleanup fails - await expect(host.dispose()).resolves.toBeUndefined() - - rmMock.mockRestore() - }) - - it("should not affect normal mode when ephemeral is false", () => { - const host = createTestHost({ ephemeral: false }) - - const options = getPrivate(host, "options") - expect(options.ephemeral).toBe(false) - expect(getPrivate(host, "ephemeralStorageDir")).toBeNull() - }) - }) -}) diff --git a/apps/cli/src/agent/agent-state.ts b/apps/cli/src/agent/agent-state.ts deleted file mode 100644 index ca4a099ccab..00000000000 --- a/apps/cli/src/agent/agent-state.ts +++ /dev/null @@ -1,466 +0,0 @@ -/** - * Agent Loop State Detection - * - * This module provides the core logic for detecting the current state of the - * Roo Code agent loop. The state is determined by analyzing the clineMessages - * array, specifically the last message's type and properties. - * - * Key insight: The agent loop stops whenever a message with `type: "ask"` arrives, - * and the specific `ask` value determines what kind of response the agent is waiting for. - */ - -import { ClineMessage, ClineAsk, isIdleAsk, isResumableAsk, isInteractiveAsk, isNonBlockingAsk } from "@roo-code/types" - -// ============================================================================= -// Agent Loop State Enum -// ============================================================================= - -/** - * The possible states of the agent loop. - * - * State Machine: - * ``` - * ┌─────────────────┐ - * │ NO_TASK │ (initial state) - * └────────┬────────┘ - * │ newTask - * ▼ - * ┌─────────────────────────────┐ - * ┌───▶│ RUNNING │◀───┐ - * │ └──────────┬──────────────────┘ │ - * │ │ │ - * │ ┌──────────┼──────────────┐ │ - * │ │ │ │ │ - * │ ▼ ▼ ▼ │ - * │ ┌──────┐ ┌─────────┐ ┌──────────┐ │ - * │ │STREAM│ │INTERACT │ │ IDLE │ │ - * │ │ ING │ │ IVE │ │ │ │ - * │ └──┬───┘ └────┬────┘ └────┬─────┘ │ - * │ │ │ │ │ - * │ │ done │ approved │ newTask │ - * └────┴───────────┴────────────┘ │ - * │ - * ┌──────────────┐ │ - * │ RESUMABLE │────────────────────────┘ - * └──────────────┘ resumed - * ``` - */ -export enum AgentLoopState { - /** - * No active task. This is the initial state before any task is started, - * or after a task has been cleared. - */ - NO_TASK = "no_task", - - /** - * Agent is actively processing. This means: - * - The last message is a "say" type (informational), OR - * - The last message is a non-blocking ask (command_output) - * - * In this state, the agent may be: - * - Executing tools - * - Thinking/reasoning - * - Processing between API calls - */ - RUNNING = "running", - - /** - * Agent is streaming a response. This is detected when: - * - `partial === true` on the last message, OR - * - The last `api_req_started` message has no `cost` in its text field - * - * Do NOT consider the agent "waiting" while streaming. - */ - STREAMING = "streaming", - - /** - * Agent is waiting for user approval or input. This includes: - * - Tool approvals (file operations) - * - Command execution permission - * - Browser action permission - * - MCP server permission - * - Follow-up questions - * - * User must approve, reject, or provide input to continue. - */ - WAITING_FOR_INPUT = "waiting_for_input", - - /** - * Task is in an idle/terminal state. This includes: - * - Task completed successfully (completion_result) - * - API request failed (api_req_failed) - * - Too many errors (mistake_limit_reached) - * - Auto-approval limit reached - * - Completed task waiting to be resumed - * - * User can start a new task or retry. - */ - IDLE = "idle", - - /** - * Task is paused and can be resumed. This happens when: - * - User navigated away from a task - * - Extension was restarted mid-task - * - * User can resume or abandon the task. - */ - RESUMABLE = "resumable", -} - -// ============================================================================= -// Detailed State Info -// ============================================================================= - -/** - * What action the user should/can take in the current state. - */ -export type RequiredAction = - | "none" // No action needed (running/streaming) - | "approve" // Can approve/reject (tool, command, browser, mcp) - | "answer" // Need to answer a question (followup) - | "retry_or_new_task" // Can retry or start new task (api_req_failed) - | "proceed_or_new_task" // Can proceed or start new task (mistake_limit) - | "start_task" // Should start a new task (completion_result) - | "resume_or_abandon" // Can resume or abandon (resume_task) - | "start_new_task" // Should start new task (resume_completed_task, no_task) - | "continue_or_abort" // Can continue or abort (command_output) - -/** - * Detailed information about the current agent state. - * Provides everything needed to render UI or make decisions. - */ -export interface AgentStateInfo { - /** The high-level state of the agent loop */ - state: AgentLoopState - - /** Whether the agent is waiting for user input/action */ - isWaitingForInput: boolean - - /** Whether the agent loop is actively processing */ - isRunning: boolean - - /** Whether content is being streamed */ - isStreaming: boolean - - /** The specific ask type if waiting on an ask, undefined otherwise */ - currentAsk?: ClineAsk - - /** What action the user should/can take */ - requiredAction: RequiredAction - - /** The timestamp of the last message, useful for tracking */ - lastMessageTs?: number - - /** The full last message for advanced usage */ - lastMessage?: ClineMessage - - /** Human-readable description of the current state */ - description: string -} - -// ============================================================================= -// State Detection Functions -// ============================================================================= - -/** - * Structure of the text field in api_req_started messages. - * Used to determine if the API request has completed (cost is defined). - */ -export interface ApiReqStartedText { - cost?: number // Undefined while streaming, defined when complete. - tokensIn?: number - tokensOut?: number - cacheWrites?: number - cacheReads?: number -} - -/** - * Check if an API request is still in progress (streaming). - * - * API requests are considered in-progress when: - * - An api_req_started message exists - * - Its text field, when parsed, has `cost: undefined` - * - * Once the request completes, the cost field will be populated. - */ -function isApiRequestInProgress(messages: ClineMessage[]): boolean { - // Find the last api_req_started message. - // Using reverse iteration for efficiency (most recent first). - for (let i = messages.length - 1; i >= 0; i--) { - const message = messages[i] - - if (!message) { - continue - } - - if (message.say === "api_req_started") { - if (!message.text) { - // No text yet means still in progress. - return true - } - - try { - const data: ApiReqStartedText = JSON.parse(message.text) - // cost is undefined while streaming, defined when complete. - return data.cost === undefined - } catch { - // Parse error - assume not in progress. - return false - } - } - } - return false -} - -/** - * Determine the required action based on the current ask type. - */ -function getRequiredAction(ask: ClineAsk): RequiredAction { - switch (ask) { - case "followup": - return "answer" - case "command": - case "tool": - case "browser_action_launch": - case "use_mcp_server": - return "approve" - case "command_output": - return "continue_or_abort" - case "api_req_failed": - return "retry_or_new_task" - case "mistake_limit_reached": - return "proceed_or_new_task" - case "completion_result": - return "start_task" - case "resume_task": - return "resume_or_abandon" - case "resume_completed_task": - case "auto_approval_max_req_reached": - return "start_new_task" - default: - return "none" - } -} - -/** - * Get a human-readable description for the current state. - */ -function getStateDescription(state: AgentLoopState, ask?: ClineAsk): string { - switch (state) { - case AgentLoopState.NO_TASK: - return "No active task. Ready to start a new task." - - case AgentLoopState.RUNNING: - return "Agent is actively processing." - - case AgentLoopState.STREAMING: - return "Agent is streaming a response." - - case AgentLoopState.WAITING_FOR_INPUT: - switch (ask) { - case "followup": - return "Agent is asking a follow-up question. Please provide an answer." - case "command": - return "Agent wants to execute a command. Approve or reject." - case "tool": - return "Agent wants to perform a file operation. Approve or reject." - case "browser_action_launch": - return "Agent wants to use the browser. Approve or reject." - case "use_mcp_server": - return "Agent wants to use an MCP server. Approve or reject." - default: - return "Agent is waiting for user input." - } - - case AgentLoopState.IDLE: - switch (ask) { - case "completion_result": - return "Task completed successfully. You can provide feedback or start a new task." - case "api_req_failed": - return "API request failed. You can retry or start a new task." - case "mistake_limit_reached": - return "Too many errors encountered. You can proceed anyway or start a new task." - case "auto_approval_max_req_reached": - return "Auto-approval limit reached. Manual approval required." - case "resume_completed_task": - return "Previously completed task. Start a new task to continue." - default: - return "Task is idle." - } - - case AgentLoopState.RESUMABLE: - return "Task is paused. You can resume or start a new task." - - default: - return "Unknown state." - } -} - -/** - * Detect the current state of the agent loop from the clineMessages array. - * - * This is the main state detection function. It analyzes the messages array - * and returns detailed information about the current agent state. - * - * @param messages - The clineMessages array from extension state - * @returns Detailed state information - */ -export function detectAgentState(messages: ClineMessage[]): AgentStateInfo { - // No messages means no task - if (!messages || messages.length === 0) { - return { - state: AgentLoopState.NO_TASK, - isWaitingForInput: false, - isRunning: false, - isStreaming: false, - requiredAction: "start_new_task", - description: getStateDescription(AgentLoopState.NO_TASK), - } - } - - const lastMessage = messages[messages.length - 1] - - // Guard against undefined (should never happen after length check, but TypeScript requires it) - if (!lastMessage) { - return { - state: AgentLoopState.NO_TASK, - isWaitingForInput: false, - isRunning: false, - isStreaming: false, - requiredAction: "start_new_task", - description: getStateDescription(AgentLoopState.NO_TASK), - } - } - - // Check if the message is still streaming (partial) - // This is the PRIMARY indicator of streaming - if (lastMessage.partial === true) { - return { - state: AgentLoopState.STREAMING, - isWaitingForInput: false, - isRunning: true, - isStreaming: true, - currentAsk: lastMessage.ask, - requiredAction: "none", - lastMessageTs: lastMessage.ts, - lastMessage, - description: getStateDescription(AgentLoopState.STREAMING), - } - } - - // Handle "ask" type messages - if (lastMessage.type === "ask" && lastMessage.ask) { - const ask = lastMessage.ask - - // Non-blocking asks (command_output) - agent is running but can be interrupted - if (isNonBlockingAsk(ask)) { - return { - state: AgentLoopState.RUNNING, - isWaitingForInput: false, - isRunning: true, - isStreaming: false, - currentAsk: ask, - requiredAction: "continue_or_abort", - lastMessageTs: lastMessage.ts, - lastMessage, - description: "Command is running. You can continue or abort.", - } - } - - // Idle asks - task has stopped - if (isIdleAsk(ask)) { - return { - state: AgentLoopState.IDLE, - isWaitingForInput: true, // User needs to decide what to do next - isRunning: false, - isStreaming: false, - currentAsk: ask, - requiredAction: getRequiredAction(ask), - lastMessageTs: lastMessage.ts, - lastMessage, - description: getStateDescription(AgentLoopState.IDLE, ask), - } - } - - // Resumable asks - task is paused - if (isResumableAsk(ask)) { - return { - state: AgentLoopState.RESUMABLE, - isWaitingForInput: true, - isRunning: false, - isStreaming: false, - currentAsk: ask, - requiredAction: getRequiredAction(ask), - lastMessageTs: lastMessage.ts, - lastMessage, - description: getStateDescription(AgentLoopState.RESUMABLE, ask), - } - } - - // Interactive asks - waiting for approval/input - if (isInteractiveAsk(ask)) { - return { - state: AgentLoopState.WAITING_FOR_INPUT, - isWaitingForInput: true, - isRunning: false, - isStreaming: false, - currentAsk: ask, - requiredAction: getRequiredAction(ask), - lastMessageTs: lastMessage.ts, - lastMessage, - description: getStateDescription(AgentLoopState.WAITING_FOR_INPUT, ask), - } - } - } - - // For "say" type messages, check if API request is in progress - if (isApiRequestInProgress(messages)) { - return { - state: AgentLoopState.STREAMING, - isWaitingForInput: false, - isRunning: true, - isStreaming: true, - requiredAction: "none", - lastMessageTs: lastMessage.ts, - lastMessage, - description: getStateDescription(AgentLoopState.STREAMING), - } - } - - // Default: agent is running - return { - state: AgentLoopState.RUNNING, - isWaitingForInput: false, - isRunning: true, - isStreaming: false, - requiredAction: "none", - lastMessageTs: lastMessage.ts, - lastMessage, - description: getStateDescription(AgentLoopState.RUNNING), - } -} - -/** - * Quick check: Is the agent waiting for user input? - * - * This is a convenience function for simple use cases where you just need - * to know if user action is required. - */ -export function isAgentWaitingForInput(messages: ClineMessage[]): boolean { - return detectAgentState(messages).isWaitingForInput -} - -/** - * Quick check: Is the agent actively running (not waiting)? - */ -export function isAgentRunning(messages: ClineMessage[]): boolean { - const state = detectAgentState(messages) - return state.isRunning && !state.isWaitingForInput -} - -/** - * Quick check: Is content currently streaming? - */ -export function isContentStreaming(messages: ClineMessage[]): boolean { - return detectAgentState(messages).isStreaming -} diff --git a/apps/cli/src/agent/ask-dispatcher.ts b/apps/cli/src/agent/ask-dispatcher.ts deleted file mode 100644 index 8d57e4547cd..00000000000 --- a/apps/cli/src/agent/ask-dispatcher.ts +++ /dev/null @@ -1,681 +0,0 @@ -/** - * AskDispatcher - Routes ask messages to appropriate handlers - * - * This dispatcher is responsible for: - * - Categorizing ask types using type guards from client module - * - Routing to the appropriate handler based on ask category - * - Coordinating between OutputManager and PromptManager - * - Tracking which asks have been handled (to avoid duplicates) - * - * Design notes: - * - Uses isIdleAsk, isInteractiveAsk, isResumableAsk, isNonBlockingAsk type guards - * - Single responsibility: Ask routing and handling only - * - Delegates output to OutputManager, input to PromptManager - * - Sends responses back through a provided callback - */ - -import { - type WebviewMessage, - type ClineMessage, - type ClineAsk, - type ClineAskResponse, - isIdleAsk, - isInteractiveAsk, - isResumableAsk, - isNonBlockingAsk, -} from "@roo-code/types" -import { debugLog } from "@roo-code/core/cli" - -import { FOLLOWUP_TIMEOUT_SECONDS } from "@/types/index.js" - -import type { OutputManager } from "./output-manager.js" -import type { PromptManager } from "./prompt-manager.js" - -// ============================================================================= -// Types -// ============================================================================= - -/** - * Configuration for AskDispatcher. - */ -export interface AskDispatcherOptions { - /** - * OutputManager for displaying ask-related output. - */ - outputManager: OutputManager - - /** - * PromptManager for collecting user input. - */ - promptManager: PromptManager - - /** - * Callback to send responses to the extension. - */ - sendMessage: (message: WebviewMessage) => void - - /** - * Whether running in non-interactive mode (auto-approve). - */ - nonInteractive?: boolean - - /** - * Whether to disable ask handling (for TUI mode). - * In TUI mode, the TUI handles asks directly. - */ - disabled?: boolean -} - -/** - * Result of handling an ask. - */ -export interface AskHandleResult { - /** Whether the ask was handled */ - handled: boolean - /** The response sent (if any) */ - response?: ClineAskResponse - /** Any error that occurred */ - error?: Error -} - -// ============================================================================= -// AskDispatcher Class -// ============================================================================= - -export class AskDispatcher { - private outputManager: OutputManager - private promptManager: PromptManager - private sendMessage: (message: WebviewMessage) => void - private nonInteractive: boolean - private disabled: boolean - - /** - * Track which asks have been handled to avoid duplicates. - * Key: message ts - */ - private handledAsks = new Set() - - constructor(options: AskDispatcherOptions) { - this.outputManager = options.outputManager - this.promptManager = options.promptManager - this.sendMessage = options.sendMessage - this.nonInteractive = options.nonInteractive ?? false - this.disabled = options.disabled ?? false - } - - // =========================================================================== - // Public API - // =========================================================================== - - /** - * Handle an ask message. - * Routes to the appropriate handler based on ask type. - * - * @param message - The ClineMessage with type="ask" - * @returns Promise - */ - async handleAsk(message: ClineMessage): Promise { - // Disabled in TUI mode - TUI handles asks directly - if (this.disabled) { - return { handled: false } - } - - const ts = message.ts - const ask = message.ask - const text = message.text || "" - - // Check if already handled - if (this.handledAsks.has(ts)) { - return { handled: true } - } - - // Must be an ask message - if (message.type !== "ask" || !ask) { - return { handled: false } - } - - // Skip partial messages (wait for complete) - if (message.partial) { - return { handled: false } - } - - // Mark as being handled - this.handledAsks.add(ts) - - try { - // Route based on ask category - if (isNonBlockingAsk(ask)) { - return await this.handleNonBlockingAsk(ts, ask, text) - } - - if (isIdleAsk(ask)) { - return await this.handleIdleAsk(ts, ask, text) - } - - if (isResumableAsk(ask)) { - return await this.handleResumableAsk(ts, ask, text) - } - - if (isInteractiveAsk(ask)) { - return await this.handleInteractiveAsk(ts, ask, text) - } - - // Unknown ask type - log and handle generically - debugLog("[AskDispatcher] Unknown ask type", { ask, ts }) - return await this.handleUnknownAsk(ts, ask, text) - } catch (error) { - // Re-allow handling on error - this.handledAsks.delete(ts) - return { - handled: false, - error: error instanceof Error ? error : new Error(String(error)), - } - } - } - - /** - * Check if an ask has been handled. - */ - isHandled(ts: number): boolean { - return this.handledAsks.has(ts) - } - - /** - * Clear handled asks (call when starting new task). - */ - clear(): void { - this.handledAsks.clear() - } - - // =========================================================================== - // Category Handlers - // =========================================================================== - - /** - * Handle non-blocking asks (command_output). - * These don't actually block the agent - just need acknowledgment. - */ - private async handleNonBlockingAsk(_ts: number, _ask: ClineAsk, _text: string): Promise { - // command_output - output is handled by OutputManager - // Just send approval to continue - this.sendApprovalResponse(true) - return { handled: true, response: "yesButtonClicked" } - } - - /** - * Handle idle asks (completion_result, api_req_failed, etc.). - * These indicate the task has stopped. - */ - private async handleIdleAsk(ts: number, ask: ClineAsk, text: string): Promise { - switch (ask) { - case "completion_result": - // Task complete - nothing to do here, TaskCompleted event handles it - return { handled: true } - - case "api_req_failed": - return await this.handleApiFailedRetry(ts, text) - - case "mistake_limit_reached": - return await this.handleMistakeLimitReached(ts, text) - - case "resume_completed_task": - return await this.handleResumeTask(ts, ask, text) - - case "auto_approval_max_req_reached": - return await this.handleAutoApprovalMaxReached(ts, text) - - default: - return { handled: false } - } - } - - /** - * Handle resumable asks (resume_task). - */ - private async handleResumableAsk(ts: number, ask: ClineAsk, text: string): Promise { - return await this.handleResumeTask(ts, ask, text) - } - - /** - * Handle interactive asks (followup, command, tool, browser_action_launch, use_mcp_server). - * These require user approval or input. - */ - private async handleInteractiveAsk(ts: number, ask: ClineAsk, text: string): Promise { - switch (ask) { - case "followup": - return await this.handleFollowupQuestion(ts, text) - - case "command": - return await this.handleCommandApproval(ts, text) - - case "tool": - return await this.handleToolApproval(ts, text) - - case "browser_action_launch": - return await this.handleBrowserApproval(ts, text) - - case "use_mcp_server": - return await this.handleMcpApproval(ts, text) - - default: - return { handled: false } - } - } - - /** - * Handle unknown ask types. - */ - private async handleUnknownAsk(ts: number, ask: ClineAsk, text: string): Promise { - if (this.nonInteractive) { - if (text) { - this.outputManager.output(`\n[${ask}]`, text) - } - return { handled: true } - } - - return await this.handleGenericApproval(ts, ask, text) - } - - // =========================================================================== - // Specific Ask Handlers - // =========================================================================== - - /** - * Handle followup questions - prompt for text input with suggestions. - */ - private async handleFollowupQuestion(ts: number, text: string): Promise { - let question = text - let suggestions: Array<{ answer: string; mode?: string | null }> = [] - - try { - const data = JSON.parse(text) - question = data.question || text - suggestions = Array.isArray(data.suggest) ? data.suggest : [] - } catch { - // Use raw text if not JSON - } - - this.outputManager.output("\n[question]", question) - - if (suggestions.length > 0) { - this.outputManager.output("\nSuggested answers:") - suggestions.forEach((suggestion, index) => { - const suggestionText = suggestion.answer || String(suggestion) - const modeHint = suggestion.mode ? ` (mode: ${suggestion.mode})` : "" - this.outputManager.output(` ${index + 1}. ${suggestionText}${modeHint}`) - }) - this.outputManager.output("") - } - - const firstSuggestion = suggestions.length > 0 ? suggestions[0] : null - const defaultAnswer = firstSuggestion?.answer ?? "" - - if (this.nonInteractive) { - // Use timeout prompt in non-interactive mode - const timeoutMs = FOLLOWUP_TIMEOUT_SECONDS * 1000 - const result = await this.promptManager.promptWithTimeout( - suggestions.length > 0 - ? `Enter number (1-${suggestions.length}) or type your answer (auto-select in ${Math.round(timeoutMs / 1000)}s): ` - : `Your answer (auto-select in ${Math.round(timeoutMs / 1000)}s): `, - timeoutMs, - defaultAnswer, - ) - - let responseText = result.value.trim() - responseText = this.resolveNumberedSuggestion(responseText, suggestions) - - if (result.timedOut || result.cancelled) { - this.outputManager.output(`[Using default: ${defaultAnswer || "(empty)"}]`) - } - - this.sendFollowupResponse(responseText) - return { handled: true, response: "messageResponse" } - } - - // Interactive mode - try { - const answer = await this.promptManager.promptForInput( - suggestions.length > 0 - ? `Enter number (1-${suggestions.length}) or type your answer: ` - : "Your answer: ", - ) - - let responseText = answer.trim() - responseText = this.resolveNumberedSuggestion(responseText, suggestions) - - this.sendFollowupResponse(responseText) - return { handled: true, response: "messageResponse" } - } catch { - this.outputManager.output(`[Using default: ${defaultAnswer || "(empty)"}]`) - this.sendFollowupResponse(defaultAnswer) - return { handled: true, response: "messageResponse" } - } - } - - /** - * Handle command execution approval. - */ - private async handleCommandApproval(ts: number, text: string): Promise { - this.outputManager.output("\n[command request]") - this.outputManager.output(` Command: ${text || "(no command specified)"}`) - this.outputManager.markDisplayed(ts, text || "", false) - - if (this.nonInteractive) { - // Auto-approved by extension settings - return { handled: true } - } - - try { - const approved = await this.promptManager.promptForYesNo("Execute this command? (y/n): ") - this.sendApprovalResponse(approved) - return { handled: true, response: approved ? "yesButtonClicked" : "noButtonClicked" } - } catch { - this.outputManager.output("[Defaulting to: no]") - this.sendApprovalResponse(false) - return { handled: true, response: "noButtonClicked" } - } - } - - /** - * Handle tool execution approval. - */ - private async handleToolApproval(ts: number, text: string): Promise { - let toolName = "unknown" - let toolInfo: Record = {} - - try { - toolInfo = JSON.parse(text) as Record - toolName = (toolInfo.tool as string) || "unknown" - } catch { - // Use raw text if not JSON - } - - const isProtected = toolInfo.isProtected === true - - if (isProtected) { - this.outputManager.output(`\n[Tool Request] ${toolName} [PROTECTED CONFIGURATION FILE]`) - this.outputManager.output(`⚠️ WARNING: This tool wants to modify a protected configuration file.`) - this.outputManager.output( - ` Protected files include .rooignore, .roo/*, and other sensitive config files.`, - ) - } else { - this.outputManager.output(`\n[Tool Request] ${toolName}`) - } - - // Display tool details - for (const [key, value] of Object.entries(toolInfo)) { - if (key === "tool" || key === "isProtected") continue - - let displayValue: string - if (typeof value === "string") { - displayValue = value.length > 200 ? value.substring(0, 200) + "..." : value - } else if (typeof value === "object" && value !== null) { - const json = JSON.stringify(value) - displayValue = json.length > 200 ? json.substring(0, 200) + "..." : json - } else { - displayValue = String(value) - } - - this.outputManager.output(` ${key}: ${displayValue}`) - } - - this.outputManager.markDisplayed(ts, text || "", false) - - if (this.nonInteractive) { - // Auto-approved by extension settings (unless protected) - return { handled: true } - } - - try { - const approved = await this.promptManager.promptForYesNo("Approve this action? (y/n): ") - this.sendApprovalResponse(approved) - return { handled: true, response: approved ? "yesButtonClicked" : "noButtonClicked" } - } catch { - this.outputManager.output("[Defaulting to: no]") - this.sendApprovalResponse(false) - return { handled: true, response: "noButtonClicked" } - } - } - - /** - * Handle browser action approval. - */ - private async handleBrowserApproval(ts: number, text: string): Promise { - this.outputManager.output("\n[browser action request]") - if (text) { - this.outputManager.output(` Action: ${text}`) - } - this.outputManager.markDisplayed(ts, text || "", false) - - if (this.nonInteractive) { - // Auto-approved by extension settings - return { handled: true } - } - - try { - const approved = await this.promptManager.promptForYesNo("Allow browser action? (y/n): ") - this.sendApprovalResponse(approved) - return { handled: true, response: approved ? "yesButtonClicked" : "noButtonClicked" } - } catch { - this.outputManager.output("[Defaulting to: no]") - this.sendApprovalResponse(false) - return { handled: true, response: "noButtonClicked" } - } - } - - /** - * Handle MCP server access approval. - */ - private async handleMcpApproval(ts: number, text: string): Promise { - let serverName = "unknown" - let toolName = "" - let resourceUri = "" - - try { - const mcpInfo = JSON.parse(text) - serverName = mcpInfo.server_name || "unknown" - - if (mcpInfo.type === "use_mcp_tool") { - toolName = mcpInfo.tool_name || "" - } else if (mcpInfo.type === "access_mcp_resource") { - resourceUri = mcpInfo.uri || "" - } - } catch { - // Use raw text if not JSON - } - - this.outputManager.output("\n[mcp request]") - this.outputManager.output(` Server: ${serverName}`) - if (toolName) { - this.outputManager.output(` Tool: ${toolName}`) - } - if (resourceUri) { - this.outputManager.output(` Resource: ${resourceUri}`) - } - this.outputManager.markDisplayed(ts, text || "", false) - - if (this.nonInteractive) { - // Auto-approved by extension settings - return { handled: true } - } - - try { - const approved = await this.promptManager.promptForYesNo("Allow MCP access? (y/n): ") - this.sendApprovalResponse(approved) - return { handled: true, response: approved ? "yesButtonClicked" : "noButtonClicked" } - } catch { - this.outputManager.output("[Defaulting to: no]") - this.sendApprovalResponse(false) - return { handled: true, response: "noButtonClicked" } - } - } - - /** - * Handle API request failed - retry prompt. - */ - private async handleApiFailedRetry(ts: number, text: string): Promise { - this.outputManager.output("\n[api request failed]") - this.outputManager.output(` Error: ${text || "Unknown error"}`) - this.outputManager.markDisplayed(ts, text || "", false) - - if (this.nonInteractive) { - this.outputManager.output("\n[retrying api request]") - // Auto-retry in non-interactive mode - return { handled: true } - } - - try { - const retry = await this.promptManager.promptForYesNo("Retry the request? (y/n): ") - this.sendApprovalResponse(retry) - return { handled: true, response: retry ? "yesButtonClicked" : "noButtonClicked" } - } catch { - this.outputManager.output("[Defaulting to: no]") - this.sendApprovalResponse(false) - return { handled: true, response: "noButtonClicked" } - } - } - - /** - * Handle mistake limit reached. - */ - private async handleMistakeLimitReached(ts: number, text: string): Promise { - this.outputManager.output("\n[mistake limit reached]") - if (text) { - this.outputManager.output(` Details: ${text}`) - } - this.outputManager.markDisplayed(ts, text || "", false) - - if (this.nonInteractive) { - // Auto-proceed in non-interactive mode - this.sendApprovalResponse(true) - return { handled: true, response: "yesButtonClicked" } - } - - try { - const proceed = await this.promptManager.promptForYesNo("Continue anyway? (y/n): ") - this.sendApprovalResponse(proceed) - return { handled: true, response: proceed ? "yesButtonClicked" : "noButtonClicked" } - } catch { - this.outputManager.output("[Defaulting to: no]") - this.sendApprovalResponse(false) - return { handled: true, response: "noButtonClicked" } - } - } - - /** - * Handle auto-approval max reached. - */ - private async handleAutoApprovalMaxReached(ts: number, text: string): Promise { - this.outputManager.output("\n[auto-approval limit reached]") - if (text) { - this.outputManager.output(` Details: ${text}`) - } - this.outputManager.markDisplayed(ts, text || "", false) - - if (this.nonInteractive) { - // Auto-proceed in non-interactive mode - this.sendApprovalResponse(true) - return { handled: true, response: "yesButtonClicked" } - } - - try { - const proceed = await this.promptManager.promptForYesNo("Continue with manual approval? (y/n): ") - this.sendApprovalResponse(proceed) - return { handled: true, response: proceed ? "yesButtonClicked" : "noButtonClicked" } - } catch { - this.outputManager.output("[Defaulting to: no]") - this.sendApprovalResponse(false) - return { handled: true, response: "noButtonClicked" } - } - } - - /** - * Handle task resume prompt. - */ - private async handleResumeTask(ts: number, ask: ClineAsk, text: string): Promise { - const isCompleted = ask === "resume_completed_task" - this.outputManager.output(`\n[Resume ${isCompleted ? "Completed " : ""}Task]`) - if (text) { - this.outputManager.output(` ${text}`) - } - this.outputManager.markDisplayed(ts, text || "", false) - - if (this.nonInteractive) { - this.outputManager.output("\n[continuing task]") - // Auto-resume in non-interactive mode - this.sendApprovalResponse(true) - return { handled: true, response: "yesButtonClicked" } - } - - try { - const resume = await this.promptManager.promptForYesNo("Continue with this task? (y/n): ") - this.sendApprovalResponse(resume) - return { handled: true, response: resume ? "yesButtonClicked" : "noButtonClicked" } - } catch { - this.outputManager.output("[Defaulting to: no]") - this.sendApprovalResponse(false) - return { handled: true, response: "noButtonClicked" } - } - } - - /** - * Handle generic approval prompts for unknown ask types. - */ - private async handleGenericApproval(ts: number, ask: ClineAsk, text: string): Promise { - this.outputManager.output(`\n[${ask}]`) - if (text) { - this.outputManager.output(` ${text}`) - } - this.outputManager.markDisplayed(ts, text || "", false) - - try { - const approved = await this.promptManager.promptForYesNo("Approve? (y/n): ") - this.sendApprovalResponse(approved) - return { handled: true, response: approved ? "yesButtonClicked" : "noButtonClicked" } - } catch { - this.outputManager.output("[Defaulting to: no]") - this.sendApprovalResponse(false) - return { handled: true, response: "noButtonClicked" } - } - } - - // =========================================================================== - // Response Helpers - // =========================================================================== - - /** - * Send a followup response (text answer) to the extension. - */ - private sendFollowupResponse(text: string): void { - this.sendMessage({ type: "askResponse", askResponse: "messageResponse", text }) - } - - /** - * Send an approval response (yes/no) to the extension. - */ - private sendApprovalResponse(approved: boolean): void { - this.sendMessage({ - type: "askResponse", - askResponse: approved ? "yesButtonClicked" : "noButtonClicked", - }) - } - - /** - * Resolve a numbered suggestion selection. - */ - private resolveNumberedSuggestion( - input: string, - suggestions: Array<{ answer: string; mode?: string | null }>, - ): string { - const num = parseInt(input, 10) - if (!isNaN(num) && num >= 1 && num <= suggestions.length) { - const selectedSuggestion = suggestions[num - 1] - if (selectedSuggestion) { - const selected = selectedSuggestion.answer || String(selectedSuggestion) - this.outputManager.output(`Selected: ${selected}`) - return selected - } - } - return input - } -} diff --git a/apps/cli/src/agent/events.ts b/apps/cli/src/agent/events.ts deleted file mode 100644 index 9b374310ad7..00000000000 --- a/apps/cli/src/agent/events.ts +++ /dev/null @@ -1,372 +0,0 @@ -/** - * Event System for Agent State Changes - * - * This module provides a strongly-typed event emitter specifically designed - * for tracking agent state changes. It uses Node.js EventEmitter under the hood - * but provides type safety for all events. - */ - -import { EventEmitter } from "events" - -import { ClineMessage, ClineAsk } from "@roo-code/types" - -import type { AgentStateInfo } from "./agent-state.js" - -// ============================================================================= -// Event Types -// ============================================================================= - -/** - * All events that can be emitted by the client. - * - * Design note: We use a string literal union type for event names to ensure - * type safety when subscribing to events. The payload type is determined by - * the event name. - */ -export interface ClientEventMap { - /** - * Emitted whenever the agent state changes. - * This is the primary event for tracking state. - */ - stateChange: AgentStateChangeEvent - - /** - * Emitted when a new message is added to the message list. - */ - message: ClineMessage - - /** - * Emitted when an existing message is updated (e.g., partial -> complete). - */ - messageUpdated: ClineMessage - - /** - * Emitted when the agent starts waiting for user input. - * Convenience event - you can also use stateChange. - */ - waitingForInput: WaitingForInputEvent - - /** - * Emitted when the agent stops waiting and resumes running. - */ - resumedRunning: void - - /** - * Emitted when the agent starts streaming content. - */ - streamingStarted: void - - /** - * Emitted when streaming ends. - */ - streamingEnded: void - - /** - * Emitted when a task completes (either successfully or with error). - */ - taskCompleted: TaskCompletedEvent - - /** - * Emitted when a task is cleared/cancelled. - */ - taskCleared: void - - /** - * Emitted when the current mode changes. - */ - modeChanged: ModeChangedEvent - - /** - * Emitted on any error during message processing. - */ - error: Error -} - -/** - * Event payload for state changes. - */ -export interface AgentStateChangeEvent { - /** The previous state info */ - previousState: AgentStateInfo - /** The new/current state info */ - currentState: AgentStateInfo - /** Whether this is a significant state transition (state enum changed) */ - isSignificantChange: boolean -} - -/** - * Event payload when agent starts waiting for input. - */ -export interface WaitingForInputEvent { - /** The specific ask type */ - ask: ClineAsk - /** Full state info for context */ - stateInfo: AgentStateInfo - /** The message that triggered this wait */ - message: ClineMessage -} - -/** - * Event payload when a task completes. - */ -export interface TaskCompletedEvent { - /** Whether the task completed successfully */ - success: boolean - /** The final state info */ - stateInfo: AgentStateInfo - /** The completion message if available */ - message?: ClineMessage -} - -/** - * Event payload when mode changes. - */ -export interface ModeChangedEvent { - /** The previous mode (undefined if first mode set) */ - previousMode: string | undefined - /** The new/current mode */ - currentMode: string -} - -// ============================================================================= -// Typed Event Emitter -// ============================================================================= - -/** - * Type-safe event emitter for client events. - * - * Usage: - * ```typescript - * const emitter = new TypedEventEmitter() - * - * // Type-safe subscription - * emitter.on('stateChange', (event) => { - * console.log(event.currentState) // TypeScript knows this is AgentStateChangeEvent - * }) - * - * // Type-safe emission - * emitter.emit('stateChange', { previousState, currentState, isSignificantChange }) - * ``` - */ -export class TypedEventEmitter { - private emitter = new EventEmitter() - - /** - * Subscribe to an event. - * - * @param event - The event name - * @param listener - The callback function - * @returns Function to unsubscribe - */ - on(event: K, listener: (payload: ClientEventMap[K]) => void): () => void { - this.emitter.on(event, listener) - return () => this.emitter.off(event, listener) - } - - /** - * Subscribe to an event, but only once. - * - * @param event - The event name - * @param listener - The callback function - */ - once(event: K, listener: (payload: ClientEventMap[K]) => void): void { - this.emitter.once(event, listener) - } - - /** - * Unsubscribe from an event. - * - * @param event - The event name - * @param listener - The callback function to remove - */ - off(event: K, listener: (payload: ClientEventMap[K]) => void): void { - this.emitter.off(event, listener) - } - - /** - * Emit an event. - * - * @param event - The event name - * @param payload - The event payload - */ - emit(event: K, payload: ClientEventMap[K]): void { - this.emitter.emit(event, payload) - } - - /** - * Remove all listeners for an event, or all events. - * - * @param event - Optional event name. If not provided, removes all listeners. - */ - removeAllListeners(event?: K): void { - if (event) { - this.emitter.removeAllListeners(event) - } else { - this.emitter.removeAllListeners() - } - } - - /** - * Get the number of listeners for an event. - */ - listenerCount(event: K): number { - return this.emitter.listenerCount(event) - } -} - -// ============================================================================= -// State Change Detector -// ============================================================================= - -/** - * Helper to determine if a state change is "significant". - * - * A significant change is when the AgentLoopState enum value changes, - * as opposed to just internal state updates within the same state. - */ -export function isSignificantStateChange(previous: AgentStateInfo, current: AgentStateInfo): boolean { - return previous.state !== current.state -} - -/** - * Helper to determine if we transitioned to waiting for input. - */ -export function transitionedToWaiting(previous: AgentStateInfo, current: AgentStateInfo): boolean { - return !previous.isWaitingForInput && current.isWaitingForInput -} - -/** - * Helper to determine if we transitioned from waiting to running. - */ -export function transitionedToRunning(previous: AgentStateInfo, current: AgentStateInfo): boolean { - return previous.isWaitingForInput && !current.isWaitingForInput && current.isRunning -} - -/** - * Helper to determine if streaming started. - */ -export function streamingStarted(previous: AgentStateInfo, current: AgentStateInfo): boolean { - return !previous.isStreaming && current.isStreaming -} - -/** - * Helper to determine if streaming ended. - */ -export function streamingEnded(previous: AgentStateInfo, current: AgentStateInfo): boolean { - return previous.isStreaming && !current.isStreaming -} - -/** - * Helper to determine if task completed. - */ -export function taskCompleted(previous: AgentStateInfo, current: AgentStateInfo): boolean { - const completionAsks = ["completion_result", "api_req_failed", "mistake_limit_reached"] - const wasNotComplete = !previous.currentAsk || !completionAsks.includes(previous.currentAsk) - const isNowComplete = current.currentAsk !== undefined && completionAsks.includes(current.currentAsk) - return wasNotComplete && isNowComplete -} - -// ============================================================================= -// Observable Pattern (Alternative API) -// ============================================================================= - -/** - * Subscription function type for observable pattern. - */ -export type Observer = (value: T) => void - -/** - * Unsubscribe function type. - */ -export type Unsubscribe = () => void - -/** - * Simple observable for state. - * - * This provides an alternative to the event emitter pattern - * for those who prefer a more functional approach. - * - * Usage: - * ```typescript - * const stateObservable = new Observable() - * - * const unsubscribe = stateObservable.subscribe((state) => { - * console.log('New state:', state) - * }) - * - * // Later... - * unsubscribe() - * ``` - */ -export class Observable { - private observers: Set> = new Set() - private currentValue: T | undefined - - /** - * Create an observable with an optional initial value. - */ - constructor(initialValue?: T) { - this.currentValue = initialValue - } - - /** - * Subscribe to value changes. - * - * @param observer - Function called when value changes - * @returns Unsubscribe function - */ - subscribe(observer: Observer): Unsubscribe { - this.observers.add(observer) - - // Immediately emit current value if we have one - if (this.currentValue !== undefined) { - observer(this.currentValue) - } - - return () => { - this.observers.delete(observer) - } - } - - /** - * Update the value and notify all subscribers. - */ - next(value: T): void { - this.currentValue = value - for (const observer of this.observers) { - try { - observer(value) - } catch (error) { - console.error("Error in observer:", error) - } - } - } - - /** - * Get the current value without subscribing. - */ - getValue(): T | undefined { - return this.currentValue - } - - /** - * Check if there are any subscribers. - */ - hasSubscribers(): boolean { - return this.observers.size > 0 - } - - /** - * Get the number of subscribers. - */ - getSubscriberCount(): number { - return this.observers.size - } - - /** - * Remove all subscribers. - */ - clear(): void { - this.observers.clear() - } -} diff --git a/apps/cli/src/agent/extension-client.ts b/apps/cli/src/agent/extension-client.ts deleted file mode 100644 index c2d77dfdd91..00000000000 --- a/apps/cli/src/agent/extension-client.ts +++ /dev/null @@ -1,580 +0,0 @@ -/** - * Roo Code Client - * - * This is the main entry point for the client library. It provides a high-level - * API for: - * - Processing messages from the extension host - * - Querying the current agent state - * - Subscribing to state change events - * - Sending responses back to the extension - * - * The client is designed to be transport-agnostic. You provide a way to send - * messages to the extension, and you feed incoming messages to the client. - * - * Architecture: - * ``` - * ┌───────────────────────────────────────────────┐ - * │ ExtensionClient │ - * │ │ - * Extension ──────▶ │ MessageProcessor ──▶ StateStore │ - * Messages │ │ │ │ - * │ ▼ ▼ │ - * │ TypedEventEmitter ◀── State/Events │ - * │ │ │ - * │ ▼ │ - * │ Your Event Handlers │ - * └───────────────────────────────────────────────┘ - * ``` - */ - -import type { ExtensionMessage, WebviewMessage, ClineAskResponse, ClineMessage, ClineAsk } from "@roo-code/types" - -import { StateStore } from "./state-store.js" -import { MessageProcessor, parseExtensionMessage } from "./message-processor.js" -import { - TypedEventEmitter, - type ClientEventMap, - type AgentStateChangeEvent, - type WaitingForInputEvent, - type ModeChangedEvent, -} from "./events.js" -import { AgentLoopState, type AgentStateInfo } from "./agent-state.js" - -// ============================================================================= -// Extension Client Configuration -// ============================================================================= - -/** - * Configuration options for the ExtensionClient. - */ -export interface ExtensionClientConfig { - /** - * Function to send messages to the extension host. - * This is how the client communicates back to the extension. - * - * Example implementations: - * - VSCode webview: (msg) => vscode.postMessage(msg) - * - WebSocket: (msg) => socket.send(JSON.stringify(msg)) - * - IPC: (msg) => process.send(msg) - */ - sendMessage: (message: WebviewMessage) => void - - /** - * Whether to emit events for all state changes or only significant ones. - * Default: true - */ - emitAllStateChanges?: boolean - - /** - * Enable debug logging. - * Default: false - */ - debug?: boolean - - /** - * Maximum state history size (for debugging). - * Set to 0 to disable history tracking. - * Default: 0 - */ - maxHistorySize?: number -} - -// ============================================================================= -// Main Client Class -// ============================================================================= - -/** - * ExtensionClient is the main interface for interacting with the Roo Code extension. - * - * Basic usage: - * ```typescript - * // Create client with message sender - * const client = new ExtensionClient({ - * sendMessage: (msg) => vscode.postMessage(msg) - * }) - * - * // Subscribe to state changes - * client.on('stateChange', (event) => { - * console.log('State:', event.currentState.state) - * }) - * - * // Subscribe to specific events - * client.on('waitingForInput', (event) => { - * console.log('Waiting for:', event.ask) - * }) - * - * // Feed messages from extension - * window.addEventListener('message', (e) => { - * client.handleMessage(e.data) - * }) - * - * // Query state at any time - * const state = client.getAgentState() - * if (state.isWaitingForInput) { - * // Show approval UI - * } - * - * // Send responses - * client.approve() // or client.reject() or client.respond('answer') - * ``` - */ -export class ExtensionClient { - private store: StateStore - private processor: MessageProcessor - private emitter: TypedEventEmitter - private sendMessage: (message: WebviewMessage) => void - private debug: boolean - - constructor(config: ExtensionClientConfig) { - this.sendMessage = config.sendMessage - this.debug = config.debug ?? false - this.store = new StateStore({ maxHistorySize: config.maxHistorySize ?? 0 }) - this.emitter = new TypedEventEmitter() - - this.processor = new MessageProcessor(this.store, this.emitter, { - emitAllStateChanges: config.emitAllStateChanges ?? true, - debug: config.debug ?? false, - }) - } - - // =========================================================================== - // Message Handling - // =========================================================================== - - /** - * Handle an incoming message from the extension host. - * - * Call this method whenever you receive a message from the extension. - * The client will parse, validate, and process the message, updating - * internal state and emitting appropriate events. - * - * @param message - The raw message (can be ExtensionMessage or JSON string) - */ - handleMessage(message: ExtensionMessage | string): void { - let parsed: ExtensionMessage | undefined - - if (typeof message === "string") { - parsed = parseExtensionMessage(message) - - if (!parsed) { - if (this.debug) { - console.log("[ExtensionClient] Failed to parse message:", message) - } - - return - } - } else { - parsed = message - } - - this.processor.processMessage(parsed) - } - - /** - * Handle multiple messages at once. - */ - handleMessages(messages: (ExtensionMessage | string)[]): void { - for (const message of messages) { - this.handleMessage(message) - } - } - - // =========================================================================== - // State Queries - Always know the current state - // =========================================================================== - - /** - * Get the complete agent state information. - * - * This returns everything you need to know about the current state: - * - The high-level state (running, streaming, waiting, idle, etc.) - * - Whether input is needed - * - The specific ask type if waiting - * - What action is required - * - Human-readable description - */ - getAgentState(): AgentStateInfo { - return this.store.getAgentState() - } - - /** - * Get just the current state enum value. - */ - getCurrentState(): AgentLoopState { - return this.store.getCurrentState() - } - - /** - * Check if the agent is waiting for user input. - */ - isWaitingForInput(): boolean { - return this.store.isWaitingForInput() - } - - /** - * Check if the agent is actively running. - */ - isRunning(): boolean { - return this.store.isRunning() - } - - /** - * Check if content is currently streaming. - */ - isStreaming(): boolean { - return this.store.isStreaming() - } - - /** - * Check if there is an active task. - */ - hasActiveTask(): boolean { - return this.store.getCurrentState() !== AgentLoopState.NO_TASK - } - - /** - * Get all messages in the current task. - */ - getMessages(): ClineMessage[] { - return this.store.getMessages() - } - - /** - * Get the last message. - */ - getLastMessage(): ClineMessage | undefined { - return this.store.getLastMessage() - } - - /** - * Get the current ask type if the agent is waiting for input. - */ - getCurrentAsk(): ClineAsk | undefined { - return this.store.getAgentState().currentAsk - } - - /** - * Check if the client has received any state from the extension. - */ - isInitialized(): boolean { - return this.store.isInitialized() - } - - /** - * Get the current mode (e.g., "code", "architect", "ask"). - * Returns undefined if no mode has been received yet. - */ - getCurrentMode(): string | undefined { - return this.store.getCurrentMode() - } - - // =========================================================================== - // Event Subscriptions - Realtime notifications - // =========================================================================== - - /** - * Subscribe to an event. - * - * Returns an unsubscribe function for easy cleanup. - * - * @param event - The event to subscribe to - * @param listener - The callback function - * @returns Unsubscribe function - * - * @example - * ```typescript - * const unsubscribe = client.on('stateChange', (event) => { - * console.log(event.currentState) - * }) - * - * // Later, to unsubscribe: - * unsubscribe() - * ``` - */ - on(event: K, listener: (payload: ClientEventMap[K]) => void): () => void { - return this.emitter.on(event, listener) - } - - /** - * Subscribe to an event, triggered only once. - */ - once(event: K, listener: (payload: ClientEventMap[K]) => void): void { - this.emitter.once(event, listener) - } - - /** - * Unsubscribe from an event. - */ - off(event: K, listener: (payload: ClientEventMap[K]) => void): void { - this.emitter.off(event, listener) - } - - /** - * Remove all listeners for an event, or all events. - */ - removeAllListeners(event?: K): void { - this.emitter.removeAllListeners(event) - } - - /** - * Convenience method: Subscribe only to state changes. - */ - onStateChange(listener: (event: AgentStateChangeEvent) => void): () => void { - return this.on("stateChange", listener) - } - - /** - * Convenience method: Subscribe only to waiting events. - */ - onWaitingForInput(listener: (event: WaitingForInputEvent) => void): () => void { - return this.on("waitingForInput", listener) - } - - /** - * Convenience method: Subscribe only to mode changes. - */ - onModeChanged(listener: (event: ModeChangedEvent) => void): () => void { - return this.on("modeChanged", listener) - } - - // =========================================================================== - // Response Methods - Send actions to the extension - // =========================================================================== - - /** - * Approve the current action (tool, command, browser, MCP). - * - * Use when the agent is waiting for approval (interactive asks). - */ - approve(): void { - this.sendResponse("yesButtonClicked") - } - - /** - * Reject the current action. - * - * Use when you want to deny a tool, command, or other action. - */ - reject(): void { - this.sendResponse("noButtonClicked") - } - - /** - * Send a text response. - * - * Use for: - * - Answering follow-up questions - * - Providing additional context - * - Giving feedback on completion - * - * @param text - The response text - * @param images - Optional base64-encoded images - */ - respond(text: string, images?: string[]): void { - this.sendResponse("messageResponse", text, images) - } - - /** - * Generic method to send any ask response. - * - * @param response - The response type - * @param text - Optional text content - * @param images - Optional images - */ - sendResponse(response: ClineAskResponse, text?: string, images?: string[]): void { - const message: WebviewMessage = { - type: "askResponse", - askResponse: response, - text, - images, - } - this.sendMessage(message) - } - - // =========================================================================== - // Task Control Methods - // =========================================================================== - - /** - * Start a new task with the given prompt. - * - * @param text - The task description/prompt - * @param images - Optional base64-encoded images - */ - newTask(text: string, images?: string[]): void { - const message: WebviewMessage = { - type: "newTask", - text, - images, - } - this.sendMessage(message) - } - - /** - * Clear the current task. - * - * This ends the current task and resets to a fresh state. - */ - clearTask(): void { - const message: WebviewMessage = { - type: "clearTask", - } - this.sendMessage(message) - this.processor.notifyTaskCleared() - } - - /** - * Cancel a running task. - * - * Use this to interrupt a task that is currently processing. - */ - cancelTask(): void { - const message: WebviewMessage = { - type: "cancelTask", - } - this.sendMessage(message) - } - - /** - * Resume a paused task. - * - * Use when the agent state is RESUMABLE (resume_task ask). - */ - resumeTask(): void { - this.approve() // Resume uses the same response as approve - } - - /** - * Retry a failed API request. - * - * Use when the agent state shows api_req_failed. - */ - retryApiRequest(): void { - this.approve() // Retry uses the same response as approve - } - - // =========================================================================== - // Terminal Operation Methods - // =========================================================================== - - /** - * Continue terminal output (don't wait for more output). - * - * Use when the agent is showing command_output and you want to proceed. - */ - continueTerminal(): void { - const message: WebviewMessage = { - type: "terminalOperation", - terminalOperation: "continue", - } - this.sendMessage(message) - } - - /** - * Abort terminal command. - * - * Use when you want to kill a running terminal command. - */ - abortTerminal(): void { - const message: WebviewMessage = { - type: "terminalOperation", - terminalOperation: "abort", - } - this.sendMessage(message) - } - - // =========================================================================== - // Utility Methods - // =========================================================================== - - /** - * Reset the client state. - * - * This clears all internal state and history. - * Useful when disconnecting or starting fresh. - */ - reset(): void { - this.store.reset() - this.emitter.removeAllListeners() - } - - /** - * Get the state history (if history tracking is enabled). - */ - getStateHistory() { - return this.store.getHistory() - } - - /** - * Enable or disable debug mode. - */ - setDebug(enabled: boolean): void { - this.debug = enabled - this.processor.setDebug(enabled) - } - - // =========================================================================== - // Advanced: Direct Store Access - // =========================================================================== - - /** - * Get direct access to the state store. - * - * This is for advanced use cases where you need more control. - * Most users should use the methods above instead. - */ - getStore(): StateStore { - return this.store - } - - /** - * Get direct access to the event emitter. - */ - getEmitter(): TypedEventEmitter { - return this.emitter - } -} - -// ============================================================================= -// Factory Functions -// ============================================================================= - -/** - * Create a new ExtensionClient instance. - * - * This is a convenience function that creates a client with default settings. - * - * @param sendMessage - Function to send messages to the extension - * @returns A new ExtensionClient instance - */ -export function createClient(sendMessage: (message: WebviewMessage) => void): ExtensionClient { - return new ExtensionClient({ sendMessage }) -} - -/** - * Create a mock client for testing. - * - * The mock client captures all sent messages for verification. - * - * @returns An object with the client and captured messages - */ -export function createMockClient(): { - client: ExtensionClient - sentMessages: WebviewMessage[] - clearMessages: () => void -} { - const sentMessages: WebviewMessage[] = [] - - const client = new ExtensionClient({ - sendMessage: (message) => sentMessages.push(message), - debug: false, - }) - - return { - client, - sentMessages, - clearMessages: () => { - sentMessages.length = 0 - }, - } -} diff --git a/apps/cli/src/agent/extension-host.ts b/apps/cli/src/agent/extension-host.ts deleted file mode 100644 index 8ddbce2eb04..00000000000 --- a/apps/cli/src/agent/extension-host.ts +++ /dev/null @@ -1,542 +0,0 @@ -/** - * ExtensionHost - Loads and runs the Roo Code extension in CLI mode - * - * This class is a thin coordination layer responsible for: - * 1. Creating the vscode-shim mock - * 2. Loading the extension bundle via require() - * 3. Activating the extension - * 4. Wiring up managers for output, prompting, and ask handling - */ - -import { createRequire } from "module" -import path from "path" -import { fileURLToPath } from "url" -import fs from "fs" -import { EventEmitter } from "events" - -import pWaitFor from "p-wait-for" - -import type { - ClineMessage, - ExtensionMessage, - ReasoningEffortExtended, - RooCodeSettings, - WebviewMessage, -} from "@roo-code/types" -import { createVSCodeAPI, IExtensionHost, ExtensionHostEventMap, setRuntimeConfigValues } from "@roo-code/vscode-shim" -import { DebugLogger } from "@roo-code/core/cli" - -import type { SupportedProvider } from "@/types/index.js" -import type { User } from "@/lib/sdk/index.js" -import { getProviderSettings } from "@/lib/utils/provider.js" -import { createEphemeralStorageDir } from "@/lib/storage/index.js" - -import type { WaitingForInputEvent, TaskCompletedEvent } from "./events.js" -import type { AgentStateInfo } from "./agent-state.js" -import { ExtensionClient } from "./extension-client.js" -import { OutputManager } from "./output-manager.js" -import { PromptManager } from "./prompt-manager.js" -import { AskDispatcher } from "./ask-dispatcher.js" - -// Pre-configured logger for CLI message activity debugging. -const cliLogger = new DebugLogger("CLI") - -// Get the CLI package root directory (for finding node_modules/@vscode/ripgrep) -// When running from a release tarball, ROO_CLI_ROOT is set by the wrapper script. -// In development, we fall back to calculating from __dirname. -// After bundling with tsup, the code is in dist/index.js (flat), so we go up one level. -const __dirname = path.dirname(fileURLToPath(import.meta.url)) -const CLI_PACKAGE_ROOT = process.env.ROO_CLI_ROOT || path.resolve(__dirname, "..") - -export interface ExtensionHostOptions { - mode: string - reasoningEffort?: ReasoningEffortExtended | "unspecified" | "disabled" - user: User | null - provider: SupportedProvider - apiKey?: string - model: string - workspacePath: string - extensionPath: string - nonInteractive?: boolean - debug?: boolean - /** - * When true, completely disables all direct stdout/stderr output. - * Use this when running in TUI mode where Ink controls the terminal. - */ - disableOutput?: boolean - /** - * When true, uses a temporary storage directory that is cleaned up on exit. - */ - ephemeral?: boolean - /** - * When true, don't suppress node warnings and console output since we're - * running in an integration test and we want to see the output. - */ - integrationTest?: boolean -} - -interface ExtensionModule { - activate: (context: unknown) => Promise - deactivate?: () => Promise -} - -interface WebviewViewProvider { - resolveWebviewView?(webviewView: unknown, context: unknown, token: unknown): void | Promise -} - -export interface ExtensionHostInterface extends IExtensionHost { - client: ExtensionClient - activate(): Promise - runTask(prompt: string): Promise - sendToExtension(message: WebviewMessage): void - dispose(): Promise -} - -export class ExtensionHost extends EventEmitter implements ExtensionHostInterface { - // Extension lifecycle. - private vscode: ReturnType | null = null - private extensionModule: ExtensionModule | null = null - private extensionAPI: unknown = null - private options: ExtensionHostOptions - private isReady = false - private messageListener: ((message: ExtensionMessage) => void) | null = null - private initialSettings: RooCodeSettings - - // Console suppression. - private originalConsole: { - log: typeof console.log - warn: typeof console.warn - error: typeof console.error - debug: typeof console.debug - info: typeof console.info - } | null = null - - private originalProcessEmitWarning: typeof process.emitWarning | null = null - - // Ephemeral storage. - private ephemeralStorageDir: string | null = null - - // ========================================================================== - // Managers - These do all the heavy lifting - // ========================================================================== - - /** - * ExtensionClient: Single source of truth for agent loop state. - * Handles message processing and state detection. - */ - public readonly client: ExtensionClient - - /** - * OutputManager: Handles all CLI output and streaming. - * Uses Observable pattern internally for stream tracking. - */ - private outputManager: OutputManager - - /** - * PromptManager: Handles all user input collection. - * Provides readline, yes/no, and timed prompts. - */ - private promptManager: PromptManager - - /** - * AskDispatcher: Routes asks to appropriate handlers. - * Uses type guards (isIdleAsk, isInteractiveAsk, etc.) from client module. - */ - private askDispatcher: AskDispatcher - - // ========================================================================== - // Constructor - // ========================================================================== - - constructor(options: ExtensionHostOptions) { - super() - - this.options = options - this.options.integrationTest = true - - // Initialize client - single source of truth for agent state (including mode). - this.client = new ExtensionClient({ - sendMessage: (msg) => this.sendToExtension(msg), - debug: options.debug, // Enable debug logging in the client. - }) - - // Initialize output manager. - this.outputManager = new OutputManager({ - disabled: options.disableOutput, - }) - - // Initialize prompt manager with console mode callbacks. - this.promptManager = new PromptManager({ - onBeforePrompt: () => this.restoreConsole(), - onAfterPrompt: () => this.setupQuietMode(), - }) - - // Initialize ask dispatcher. - this.askDispatcher = new AskDispatcher({ - outputManager: this.outputManager, - promptManager: this.promptManager, - sendMessage: (msg) => this.sendToExtension(msg), - nonInteractive: options.nonInteractive, - disabled: options.disableOutput, // TUI mode handles asks directly. - }) - - // Wire up client events. - this.setupClientEventHandlers() - - // Populate initial settings. - const baseSettings: RooCodeSettings = { - mode: this.options.mode, - commandExecutionTimeout: 30, - browserToolEnabled: false, - enableCheckpoints: false, - ...getProviderSettings(this.options.provider, this.options.apiKey, this.options.model), - } - - this.initialSettings = this.options.nonInteractive - ? { - autoApprovalEnabled: true, - alwaysAllowReadOnly: true, - alwaysAllowReadOnlyOutsideWorkspace: true, - alwaysAllowWrite: true, - alwaysAllowWriteOutsideWorkspace: true, - alwaysAllowWriteProtected: true, - alwaysAllowBrowser: true, - alwaysAllowMcp: true, - alwaysAllowModeSwitch: true, - alwaysAllowSubtasks: true, - alwaysAllowExecute: true, - allowedCommands: ["*"], - ...baseSettings, - } - : { - autoApprovalEnabled: false, - ...baseSettings, - } - - if (this.options.reasoningEffort && this.options.reasoningEffort !== "unspecified") { - if (this.options.reasoningEffort === "disabled") { - this.initialSettings.enableReasoningEffort = false - } else { - this.initialSettings.enableReasoningEffort = true - this.initialSettings.reasoningEffort = this.options.reasoningEffort - } - } - - this.setupQuietMode() - } - - // ========================================================================== - // Client Event Handlers - // ========================================================================== - - /** - * Wire up client events to managers. - * The client emits events, managers handle them. - */ - private setupClientEventHandlers(): void { - // Handle new messages - delegate to OutputManager. - this.client.on("message", (msg: ClineMessage) => { - this.logMessageDebug(msg, "new") - this.outputManager.outputMessage(msg) - }) - - // Handle message updates - delegate to OutputManager. - this.client.on("messageUpdated", (msg: ClineMessage) => { - this.logMessageDebug(msg, "updated") - this.outputManager.outputMessage(msg) - }) - - // Handle waiting for input - delegate to AskDispatcher. - this.client.on("waitingForInput", (event: WaitingForInputEvent) => { - this.askDispatcher.handleAsk(event.message) - }) - - // Handle task completion. - this.client.on("taskCompleted", (event: TaskCompletedEvent) => { - // Output completion message via OutputManager. - // Note: completion_result is an "ask" type, not a "say" type. - if (event.message && event.message.type === "ask" && event.message.ask === "completion_result") { - this.outputManager.outputCompletionResult(event.message.ts, event.message.text || "") - } - }) - } - - // ========================================================================== - // Logging + Console Suppression - // ========================================================================== - - private setupQuietMode(): void { - if (this.options.integrationTest) { - return - } - - // Suppress node warnings. - this.originalProcessEmitWarning = process.emitWarning - process.emitWarning = () => {} - process.on("warning", () => {}) - - // Suppress console output. - this.originalConsole = { - log: console.log, - warn: console.warn, - error: console.error, - debug: console.debug, - info: console.info, - } - - console.log = () => {} - console.warn = () => {} - console.debug = () => {} - console.info = () => {} - } - - private restoreConsole(): void { - if (this.options.integrationTest) { - return - } - - if (this.originalConsole) { - console.log = this.originalConsole.log - console.warn = this.originalConsole.warn - console.error = this.originalConsole.error - console.debug = this.originalConsole.debug - console.info = this.originalConsole.info - this.originalConsole = null - } - - if (this.originalProcessEmitWarning) { - process.emitWarning = this.originalProcessEmitWarning - this.originalProcessEmitWarning = null - } - } - - private logMessageDebug(msg: ClineMessage, type: "new" | "updated"): void { - if (msg.partial) { - if (!this.outputManager.hasLoggedFirstPartial(msg.ts)) { - this.outputManager.setLoggedFirstPartial(msg.ts) - cliLogger.debug("message:start", { ts: msg.ts, type: msg.say || msg.ask }) - } - } else { - cliLogger.debug(`message:${type === "new" ? "new" : "complete"}`, { ts: msg.ts, type: msg.say || msg.ask }) - this.outputManager.clearLoggedFirstPartial(msg.ts) - } - } - - // ========================================================================== - // Extension Lifecycle - // ========================================================================== - - public async activate(): Promise { - const bundlePath = path.join(this.options.extensionPath, "extension.js") - - if (!fs.existsSync(bundlePath)) { - this.restoreConsole() - throw new Error(`Extension bundle not found at: ${bundlePath}`) - } - - let storageDir: string | undefined - - if (this.options.ephemeral) { - this.ephemeralStorageDir = await createEphemeralStorageDir() - storageDir = this.ephemeralStorageDir - } - - // Create VSCode API mock. - this.vscode = createVSCodeAPI(this.options.extensionPath, this.options.workspacePath, undefined, { - appRoot: CLI_PACKAGE_ROOT, - storageDir, - }) - ;(global as Record).vscode = this.vscode - ;(global as Record).__extensionHost = this - - // Set up module resolution. - const require = createRequire(import.meta.url) - const Module = require("module") - const originalResolve = Module._resolveFilename - - Module._resolveFilename = function (request: string, parent: unknown, isMain: boolean, options: unknown) { - if (request === "vscode") return "vscode-mock" - return originalResolve.call(this, request, parent, isMain, options) - } - - require.cache["vscode-mock"] = { - id: "vscode-mock", - filename: "vscode-mock", - loaded: true, - exports: this.vscode, - children: [], - paths: [], - path: "", - isPreloading: false, - parent: null, - require: require, - } as unknown as NodeJS.Module - - try { - this.extensionModule = require(bundlePath) as ExtensionModule - } catch (error) { - Module._resolveFilename = originalResolve - - throw new Error( - `Failed to load extension bundle: ${error instanceof Error ? error.message : String(error)}`, - ) - } - - Module._resolveFilename = originalResolve - - try { - this.extensionAPI = await this.extensionModule.activate(this.vscode.context) - } catch (error) { - throw new Error(`Failed to activate extension: ${error instanceof Error ? error.message : String(error)}`) - } - - // Set up message listener - forward all messages to client. - this.messageListener = (message: ExtensionMessage) => this.client.handleMessage(message) - this.on("extensionWebviewMessage", this.messageListener) - - await pWaitFor(() => this.isReady, { interval: 100, timeout: 10_000 }) - } - - public registerWebviewProvider(_viewId: string, _provider: WebviewViewProvider): void {} - - public unregisterWebviewProvider(_viewId: string): void {} - - public markWebviewReady(): void { - this.isReady = true - - // Send initial webview messages to trigger proper extension initialization. - // This is critical for the extension to start sending state updates properly. - this.sendToExtension({ type: "webviewDidLaunch" }) - - setRuntimeConfigValues("roo-cline", this.initialSettings as Record) - this.sendToExtension({ type: "updateSettings", updatedSettings: this.initialSettings }) - } - - public isInInitialSetup(): boolean { - return !this.isReady - } - - // ========================================================================== - // Message Handling - // ========================================================================== - - public sendToExtension(message: WebviewMessage): void { - if (!this.isReady) { - throw new Error("You cannot send messages to the extension before it is ready") - } - - this.emit("webviewMessage", message) - } - - // ========================================================================== - // Task Management - // ========================================================================== - - public async runTask(prompt: string): Promise { - this.sendToExtension({ type: "newTask", text: prompt }) - - return new Promise((resolve, reject) => { - let timeoutId: NodeJS.Timeout | null = null - const timeoutMs: number = 110_000 - - const completeHandler = () => { - cleanup() - resolve() - } - - const errorHandler = (error: Error) => { - cleanup() - reject(error) - } - - const cleanup = () => { - if (timeoutId) { - clearTimeout(timeoutId) - timeoutId = null - } - - this.client.off("taskCompleted", completeHandler) - this.client.off("error", errorHandler) - } - - // Set timeout to prevent indefinite hanging. - timeoutId = setTimeout(() => { - cleanup() - reject( - new Error(`Task completion timeout after ${timeoutMs}ms - no completion or error event received`), - ) - }, timeoutMs) - - this.client.once("taskCompleted", completeHandler) - this.client.once("error", errorHandler) - }) - } - - // ========================================================================== - // Public Agent State API - // ========================================================================== - - /** - * Get the current agent loop state. - */ - public getAgentState(): AgentStateInfo { - return this.client.getAgentState() - } - - /** - * Check if the agent is currently waiting for user input. - */ - public isWaitingForInput(): boolean { - return this.client.getAgentState().isWaitingForInput - } - - // ========================================================================== - // Cleanup - // ========================================================================== - - async dispose(): Promise { - // Clear managers. - this.outputManager.clear() - this.askDispatcher.clear() - - // Remove message listener. - if (this.messageListener) { - this.off("extensionWebviewMessage", this.messageListener) - this.messageListener = null - } - - // Reset client. - this.client.reset() - - // Deactivate extension. - if (this.extensionModule?.deactivate) { - try { - await this.extensionModule.deactivate() - } catch { - // NO-OP - } - } - - // Clear references. - this.vscode = null - this.extensionModule = null - this.extensionAPI = null - - // Clear globals. - delete (global as Record).vscode - delete (global as Record).__extensionHost - - // Restore console. - this.restoreConsole() - - // Clean up ephemeral storage. - if (this.ephemeralStorageDir) { - try { - await fs.promises.rm(this.ephemeralStorageDir, { recursive: true, force: true }) - this.ephemeralStorageDir = null - } catch { - // NO-OP - } - } - } -} diff --git a/apps/cli/src/agent/index.ts b/apps/cli/src/agent/index.ts deleted file mode 100644 index 23cbaacb4d1..00000000000 --- a/apps/cli/src/agent/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./extension-host.js" diff --git a/apps/cli/src/agent/message-processor.ts b/apps/cli/src/agent/message-processor.ts deleted file mode 100644 index 2b9fd13602f..00000000000 --- a/apps/cli/src/agent/message-processor.ts +++ /dev/null @@ -1,479 +0,0 @@ -/** - * Message Processor - * - * This module handles incoming messages from the extension host and dispatches - * appropriate state updates and events. It acts as the bridge between raw - * extension messages and the client's internal state management. - * - * Message Flow: - * ``` - * Extension Host ──▶ MessageProcessor ──▶ StateStore ──▶ Events - * ``` - * - * The processor handles different message types: - * - "state": Full state update from extension - * - "messageUpdated": Single message update - * - "action": UI action triggers - * - "invoke": Command invocations - */ - -import { ExtensionMessage, ClineMessage } from "@roo-code/types" -import { debugLog } from "@roo-code/core/cli" - -import type { StateStore } from "./state-store.js" -import type { TypedEventEmitter, AgentStateChangeEvent, WaitingForInputEvent, TaskCompletedEvent } from "./events.js" -import { - isSignificantStateChange, - transitionedToWaiting, - transitionedToRunning, - streamingStarted, - streamingEnded, - taskCompleted, -} from "./events.js" -import type { AgentStateInfo } from "./agent-state.js" - -// ============================================================================= -// Message Processor Options -// ============================================================================= - -export interface MessageProcessorOptions { - /** - * Whether to emit events for every state change, or only significant ones. - * Default: true (emit all changes) - */ - emitAllStateChanges?: boolean - - /** - * Whether to log debug information. - * Default: false - */ - debug?: boolean -} - -// ============================================================================= -// Message Processor Class -// ============================================================================= - -/** - * MessageProcessor handles incoming extension messages and updates state accordingly. - * - * It is responsible for: - * 1. Parsing and validating incoming messages - * 2. Updating the state store - * 3. Emitting appropriate events - * - * Usage: - * ```typescript - * const store = new StateStore() - * const emitter = new TypedEventEmitter() - * const processor = new MessageProcessor(store, emitter) - * - * // Process a message from the extension - * processor.processMessage(extensionMessage) - * ``` - */ -export class MessageProcessor { - private store: StateStore - private emitter: TypedEventEmitter - private options: Required - - constructor(store: StateStore, emitter: TypedEventEmitter, options: MessageProcessorOptions = {}) { - this.store = store - this.emitter = emitter - this.options = { - emitAllStateChanges: options.emitAllStateChanges ?? true, - debug: options.debug ?? false, - } - } - - // =========================================================================== - // Main Processing Methods - // =========================================================================== - - /** - * Process an incoming message from the extension host. - * - * This is the main entry point for all extension messages. - * It routes messages to the appropriate handler based on type. - * - * @param message - The raw message from the extension - */ - processMessage(message: ExtensionMessage): void { - if (this.options.debug) { - debugLog("[MessageProcessor] Received message", { type: message.type }) - } - - try { - switch (message.type) { - case "state": - this.handleStateMessage(message) - break - - case "messageUpdated": - this.handleMessageUpdated(message) - break - - case "action": - this.handleAction(message) - break - - case "invoke": - this.handleInvoke(message) - break - - default: - // Other message types are not relevant to state detection - if (this.options.debug) { - debugLog("[MessageProcessor] Ignoring message", { type: message.type }) - } - } - } catch (error) { - const err = error instanceof Error ? error : new Error(String(error)) - debugLog("[MessageProcessor] Error processing message", { error: err.message }) - this.emitter.emit("error", err) - } - } - - /** - * Process an array of messages (for batch updates). - */ - processMessages(messages: ExtensionMessage[]): void { - for (const message of messages) { - this.processMessage(message) - } - } - - // =========================================================================== - // Message Type Handlers - // =========================================================================== - - /** - * Handle a "state" message - full state update from extension. - * - * This is the most important message type for state detection. - * It contains the complete clineMessages array which is the source of truth. - */ - private handleStateMessage(message: ExtensionMessage): void { - if (!message.state) { - if (this.options.debug) { - debugLog("[MessageProcessor] State message missing state payload") - } - return - } - - const { clineMessages, mode } = message.state - - // Track mode changes. - if (mode && typeof mode === "string") { - const previousMode = this.store.getCurrentMode() - - if (previousMode !== mode) { - if (this.options.debug) { - debugLog("[MessageProcessor] Mode changed", { from: previousMode, to: mode }) - } - - this.store.setCurrentMode(mode) - this.emitter.emit("modeChanged", { previousMode, currentMode: mode }) - } - } - - if (!clineMessages) { - if (this.options.debug) { - debugLog("[MessageProcessor] State message missing clineMessages") - } - return - } - - // Get previous state for comparison. - const previousState = this.store.getAgentState() - - // Update the store with new messages - // Note: We only call setMessages, NOT setExtensionState, to avoid - // double processing (setExtensionState would call setMessages again) - this.store.setMessages(clineMessages) - - // Get new state after update - const currentState = this.store.getAgentState() - - // Debug logging for state message - if (this.options.debug) { - const lastMsg = clineMessages[clineMessages.length - 1] - const lastMsgInfo = lastMsg - ? { - msgType: lastMsg.type === "ask" ? `ask:${lastMsg.ask}` : `say:${lastMsg.say}`, - partial: lastMsg.partial, - textPreview: lastMsg.text?.substring(0, 50), - } - : null - debugLog("[MessageProcessor] State update", { - messageCount: clineMessages.length, - lastMessage: lastMsgInfo, - stateTransition: `${previousState.state} → ${currentState.state}`, - currentAsk: currentState.currentAsk, - isWaitingForInput: currentState.isWaitingForInput, - isStreaming: currentState.isStreaming, - isRunning: currentState.isRunning, - }) - } - - // Emit events based on state changes - this.emitStateChangeEvents(previousState, currentState) - - // Emit new message events for any messages we haven't seen - this.emitNewMessageEvents(previousState, currentState, clineMessages) - } - - /** - * Handle a "messageUpdated" message - single message update. - * - * This is sent when a message is modified (e.g., partial -> complete). - */ - private handleMessageUpdated(message: ExtensionMessage): void { - if (!message.clineMessage) { - if (this.options.debug) { - debugLog("[MessageProcessor] messageUpdated missing clineMessage") - } - return - } - - const clineMessage = message.clineMessage - const previousState = this.store.getAgentState() - - // Update the message in the store - this.store.updateMessage(clineMessage) - - const currentState = this.store.getAgentState() - - // Emit message updated event - this.emitter.emit("messageUpdated", clineMessage) - - // Emit state change events - this.emitStateChangeEvents(previousState, currentState) - } - - /** - * Handle an "action" message - UI action trigger. - * - * These are typically used to trigger UI behaviors and don't - * directly affect agent state, but we can track them if needed. - */ - private handleAction(message: ExtensionMessage): void { - if (this.options.debug) { - debugLog("[MessageProcessor] Action", { action: message.action }) - } - // Actions don't affect agent state, but subclasses could override this - } - - /** - * Handle an "invoke" message - command invocation. - * - * These are commands that should trigger specific behaviors. - */ - private handleInvoke(message: ExtensionMessage): void { - if (this.options.debug) { - debugLog("[MessageProcessor] Invoke", { invoke: message.invoke }) - } - // Invokes don't directly affect state detection - // But they might trigger state changes through subsequent messages - } - - // =========================================================================== - // Event Emission Helpers - // =========================================================================== - - /** - * Emit events based on state changes. - */ - private emitStateChangeEvents(previousState: AgentStateInfo, currentState: AgentStateInfo): void { - const isSignificant = isSignificantStateChange(previousState, currentState) - - // Emit stateChange event - if (this.options.emitAllStateChanges || isSignificant) { - const changeEvent: AgentStateChangeEvent = { - previousState, - currentState, - isSignificantChange: isSignificant, - } - this.emitter.emit("stateChange", changeEvent) - } - - // Emit specific transition events - - // Waiting for input - if (transitionedToWaiting(previousState, currentState)) { - if (currentState.currentAsk && currentState.lastMessage) { - if (this.options.debug) { - debugLog("[MessageProcessor] EMIT waitingForInput", { - ask: currentState.currentAsk, - action: currentState.requiredAction, - }) - } - const waitingEvent: WaitingForInputEvent = { - ask: currentState.currentAsk, - stateInfo: currentState, - message: currentState.lastMessage, - } - this.emitter.emit("waitingForInput", waitingEvent) - } - } - - // Resumed running - if (transitionedToRunning(previousState, currentState)) { - if (this.options.debug) { - debugLog("[MessageProcessor] EMIT resumedRunning") - } - this.emitter.emit("resumedRunning", undefined as void) - } - - // Streaming started - if (streamingStarted(previousState, currentState)) { - if (this.options.debug) { - debugLog("[MessageProcessor] EMIT streamingStarted") - } - this.emitter.emit("streamingStarted", undefined as void) - } - - // Streaming ended - if (streamingEnded(previousState, currentState)) { - if (this.options.debug) { - debugLog("[MessageProcessor] EMIT streamingEnded") - } - this.emitter.emit("streamingEnded", undefined as void) - } - - // Task completed - if (taskCompleted(previousState, currentState)) { - if (this.options.debug) { - debugLog("[MessageProcessor] EMIT taskCompleted", { - success: currentState.currentAsk === "completion_result", - }) - } - const completedEvent: TaskCompletedEvent = { - success: currentState.currentAsk === "completion_result", - stateInfo: currentState, - message: currentState.lastMessage, - } - this.emitter.emit("taskCompleted", completedEvent) - } - } - - /** - * Emit events for new messages. - * - * We compare the previous and current message counts to find new messages. - * This is a simple heuristic - for more accuracy, we'd track by timestamp. - */ - private emitNewMessageEvents( - _previousState: AgentStateInfo, - _currentState: AgentStateInfo, - messages: ClineMessage[], - ): void { - // For now, just emit the last message as new - // A more sophisticated implementation would track seen message timestamps - const lastMessage = messages[messages.length - 1] - if (lastMessage) { - this.emitter.emit("message", lastMessage) - } - } - - // =========================================================================== - // Utility Methods - // =========================================================================== - - /** - * Manually trigger a task cleared event. - * Call this when you send a clearTask message to the extension. - */ - notifyTaskCleared(): void { - this.store.clear() - this.emitter.emit("taskCleared", undefined as void) - } - - /** - * Enable or disable debug logging. - */ - setDebug(enabled: boolean): void { - this.options.debug = enabled - } -} - -// ============================================================================= -// Message Validation Helpers -// ============================================================================= - -/** - * Check if a message is a valid ClineMessage. - * Useful for validating messages before processing. - */ -export function isValidClineMessage(message: unknown): message is ClineMessage { - if (!message || typeof message !== "object") { - return false - } - - const msg = message as Record - - // Required fields - if (typeof msg.ts !== "number") { - return false - } - - if (msg.type !== "ask" && msg.type !== "say") { - return false - } - - return true -} - -/** - * Check if a message is a valid ExtensionMessage. - */ -export function isValidExtensionMessage(message: unknown): message is ExtensionMessage { - if (!message || typeof message !== "object") { - return false - } - - const msg = message as Record - - // Must have a type - if (typeof msg.type !== "string") { - return false - } - - return true -} - -// ============================================================================= -// Message Parsing Utilities -// ============================================================================= - -/** - * Parse a JSON string into an ExtensionMessage. - * Returns undefined if parsing fails. - */ -export function parseExtensionMessage(json: string): ExtensionMessage | undefined { - try { - const parsed = JSON.parse(json) - if (isValidExtensionMessage(parsed)) { - return parsed - } - return undefined - } catch { - return undefined - } -} - -/** - * Parse the text field of an api_req_started message. - * Returns undefined if parsing fails or text is not present. - */ -export function parseApiReqStartedText(message: ClineMessage): { cost?: number } | undefined { - if (message.say !== "api_req_started" || !message.text) { - return undefined - } - - try { - return JSON.parse(message.text) - } catch { - return undefined - } -} diff --git a/apps/cli/src/agent/output-manager.ts b/apps/cli/src/agent/output-manager.ts deleted file mode 100644 index 0863546f6c4..00000000000 --- a/apps/cli/src/agent/output-manager.ts +++ /dev/null @@ -1,414 +0,0 @@ -/** - * OutputManager - Handles all CLI output and streaming - * - * This manager is responsible for: - * - Writing messages to stdout/stderr - * - Tracking what's been displayed (to avoid duplicates) - * - Managing streaming content with delta computation - * - Formatting different message types appropriately - * - * Design notes: - * - Uses the Observable pattern from client/events.ts for internal state - * - Single responsibility: CLI output only (no prompting, no state detection) - * - Can be disabled for TUI mode where Ink controls the terminal - */ - -import { ClineMessage, ClineSay } from "@roo-code/types" - -import { Observable } from "./events.js" - -// ============================================================================= -// Types -// ============================================================================= - -/** - * Tracks what we've displayed for a specific message ts. - */ -export interface DisplayedMessage { - ts: number - text: string - partial: boolean -} - -/** - * Tracks streaming state for a message. - */ -export interface StreamState { - ts: number - text: string - headerShown: boolean -} - -/** - * Configuration options for OutputManager. - */ -export interface OutputManagerOptions { - /** - * When true, completely disables all output. - * Use for TUI mode where another system controls the terminal. - */ - disabled?: boolean - - /** - * Stream for normal output (default: process.stdout). - */ - stdout?: NodeJS.WriteStream - - /** - * Stream for error output (default: process.stderr). - */ - stderr?: NodeJS.WriteStream -} - -// ============================================================================= -// OutputManager Class -// ============================================================================= - -export class OutputManager { - private disabled: boolean - private stdout: NodeJS.WriteStream - private stderr: NodeJS.WriteStream - - /** - * Track displayed messages by ts to avoid duplicate output. - * Observable pattern allows external systems to subscribe if needed. - */ - private displayedMessages = new Map() - - /** - * Track streamed content by ts for delta computation. - */ - private streamedContent = new Map() - - /** - * Track which ts is currently streaming (for newline management). - */ - private currentlyStreamingTs: number | null = null - - /** - * Track first partial logs (for debugging first/last pattern). - */ - private loggedFirstPartial = new Set() - - /** - * Observable for streaming state changes. - * External systems can subscribe to know when streaming starts/ends. - */ - public readonly streamingState = new Observable<{ ts: number | null; isStreaming: boolean }>({ - ts: null, - isStreaming: false, - }) - - constructor(options: OutputManagerOptions = {}) { - this.disabled = options.disabled ?? false - this.stdout = options.stdout ?? process.stdout - this.stderr = options.stderr ?? process.stderr - } - - // =========================================================================== - // Public API - // =========================================================================== - - /** - * Output a ClineMessage based on its type. - * This is the main entry point for message output. - * - * @param msg - The message to output - * @param skipFirstUserMessage - If true, skip the first "text" message (user prompt echo) - */ - outputMessage(msg: ClineMessage, skipFirstUserMessage = true): void { - const ts = msg.ts - const text = msg.text || "" - const isPartial = msg.partial === true - const previousDisplay = this.displayedMessages.get(ts) - const alreadyDisplayedComplete = previousDisplay && !previousDisplay.partial - - if (msg.type === "say" && msg.say) { - this.outputSayMessage(ts, msg.say, text, isPartial, alreadyDisplayedComplete, skipFirstUserMessage) - } else if (msg.type === "ask" && msg.ask) { - // For ask messages, we only output command_output here - // Other asks are handled by AskDispatcher - if (msg.ask === "command_output") { - this.outputCommandOutput(ts, text, isPartial, alreadyDisplayedComplete) - } - } - } - - /** - * Output a simple text line with a label. - */ - output(label: string, text?: string): void { - if (this.disabled) return - const message = text ? `${label} ${text}\n` : `${label}\n` - this.stdout.write(message) - } - - /** - * Output an error message. - */ - outputError(label: string, text?: string): void { - if (this.disabled) return - const message = text ? `${label} ${text}\n` : `${label}\n` - this.stderr.write(message) - } - - /** - * Write raw text to stdout (for streaming). - */ - writeRaw(text: string): void { - if (this.disabled) return - this.stdout.write(text) - } - - /** - * Check if a message has already been fully displayed. - */ - isAlreadyDisplayed(ts: number): boolean { - const displayed = this.displayedMessages.get(ts) - return displayed !== undefined && !displayed.partial - } - - /** - * Check if we're currently streaming any message. - */ - isCurrentlyStreaming(): boolean { - return this.currentlyStreamingTs !== null - } - - /** - * Get the ts of the currently streaming message. - */ - getCurrentlyStreamingTs(): number | null { - return this.currentlyStreamingTs - } - - /** - * Mark a message as displayed (useful for external coordination). - */ - markDisplayed(ts: number, text: string, partial: boolean): void { - this.displayedMessages.set(ts, { ts, text, partial }) - } - - /** - * Clear all tracking state. - * Call this when starting a new task. - */ - clear(): void { - this.displayedMessages.clear() - this.streamedContent.clear() - this.currentlyStreamingTs = null - this.loggedFirstPartial.clear() - this.streamingState.next({ ts: null, isStreaming: false }) - } - - /** - * Get debugging info about first partial logging. - */ - hasLoggedFirstPartial(ts: number): boolean { - return this.loggedFirstPartial.has(ts) - } - - /** - * Record that we've logged the first partial for a ts. - */ - setLoggedFirstPartial(ts: number): void { - this.loggedFirstPartial.add(ts) - } - - /** - * Clear the first partial record (when complete). - */ - clearLoggedFirstPartial(ts: number): void { - this.loggedFirstPartial.delete(ts) - } - - // =========================================================================== - // Say Message Output - // =========================================================================== - - private outputSayMessage( - ts: number, - say: ClineSay, - text: string, - isPartial: boolean, - alreadyDisplayedComplete: boolean | undefined, - skipFirstUserMessage: boolean, - ): void { - switch (say) { - case "text": - this.outputTextMessage(ts, text, isPartial, alreadyDisplayedComplete, skipFirstUserMessage) - break - - // case "thinking": - not a valid ClineSay type - case "reasoning": - this.outputReasoningMessage(ts, text, isPartial, alreadyDisplayedComplete) - break - - case "command_output": - this.outputCommandOutput(ts, text, isPartial, alreadyDisplayedComplete) - break - - // Note: completion_result is an "ask" type, not a "say" type. - // It is handled via the TaskCompleted event in extension-host.ts - - case "error": - if (!alreadyDisplayedComplete) { - this.outputError("\n[error]", text || "Unknown error") - this.displayedMessages.set(ts, { ts, text: text || "", partial: false }) - } - break - - case "api_req_started": - // Silent - no output needed - break - - default: - // NO-OP for unknown say types - break - } - } - - private outputTextMessage( - ts: number, - text: string, - isPartial: boolean, - alreadyDisplayedComplete: boolean | undefined, - skipFirstUserMessage: boolean, - ): void { - // Skip the initial user prompt echo (first message with no prior messages) - if (skipFirstUserMessage && this.displayedMessages.size === 0 && !this.displayedMessages.has(ts)) { - this.displayedMessages.set(ts, { ts, text, partial: !!isPartial }) - return - } - - if (isPartial && text) { - // Stream partial content - this.streamContent(ts, text, "[assistant]") - this.displayedMessages.set(ts, { ts, text, partial: true }) - } else if (!isPartial && text && !alreadyDisplayedComplete) { - // Message complete - ensure all content is output - const streamed = this.streamedContent.get(ts) - - if (streamed) { - // We were streaming - output any remaining delta and finish - if (text.length > streamed.text.length && text.startsWith(streamed.text)) { - const delta = text.slice(streamed.text.length) - this.writeRaw(delta) - } - this.finishStream(ts) - } else { - // Not streamed yet - output complete message - this.output("\n[assistant]", text) - } - - this.displayedMessages.set(ts, { ts, text, partial: false }) - this.streamedContent.set(ts, { ts, text, headerShown: true }) - } - } - - private outputReasoningMessage( - ts: number, - text: string, - isPartial: boolean, - alreadyDisplayedComplete: boolean | undefined, - ): void { - if (isPartial && text) { - this.streamContent(ts, text, "[reasoning]") - this.displayedMessages.set(ts, { ts, text, partial: true }) - } else if (!isPartial && text && !alreadyDisplayedComplete) { - // Reasoning complete - finish the stream - const streamed = this.streamedContent.get(ts) - - if (streamed) { - if (text.length > streamed.text.length && text.startsWith(streamed.text)) { - const delta = text.slice(streamed.text.length) - this.writeRaw(delta) - } - this.finishStream(ts) - } else { - this.output("\n[reasoning]", text) - } - - this.displayedMessages.set(ts, { ts, text, partial: false }) - } - } - - /** - * Output command_output (shared between say and ask types). - */ - outputCommandOutput( - ts: number, - text: string, - isPartial: boolean, - alreadyDisplayedComplete: boolean | undefined, - ): void { - if (isPartial && text) { - this.streamContent(ts, text, "[command output]") - this.displayedMessages.set(ts, { ts, text, partial: true }) - } else if (!isPartial && text && !alreadyDisplayedComplete) { - const streamed = this.streamedContent.get(ts) - - if (streamed) { - if (text.length > streamed.text.length && text.startsWith(streamed.text)) { - const delta = text.slice(streamed.text.length) - this.writeRaw(delta) - } - this.finishStream(ts) - } else { - this.writeRaw("\n[command output] ") - this.writeRaw(text) - this.writeRaw("\n") - } - - this.displayedMessages.set(ts, { ts, text, partial: false }) - this.streamedContent.set(ts, { ts, text, headerShown: true }) - } - } - - // =========================================================================== - // Streaming Helpers - // =========================================================================== - - /** - * Stream content with delta computation - only output new characters. - */ - streamContent(ts: number, text: string, header: string): void { - const previous = this.streamedContent.get(ts) - - if (!previous) { - // First time seeing this message - output header and initial text - this.writeRaw(`\n${header} `) - this.writeRaw(text) - this.streamedContent.set(ts, { ts, text, headerShown: true }) - this.currentlyStreamingTs = ts - this.streamingState.next({ ts, isStreaming: true }) - } else if (text.length > previous.text.length && text.startsWith(previous.text)) { - // Text has grown - output delta - const delta = text.slice(previous.text.length) - this.writeRaw(delta) - this.streamedContent.set(ts, { ts, text, headerShown: true }) - } - } - - /** - * Finish streaming a message (add newline). - */ - finishStream(ts: number): void { - if (this.currentlyStreamingTs === ts) { - this.writeRaw("\n") - this.currentlyStreamingTs = null - this.streamingState.next({ ts: null, isStreaming: false }) - } - } - - /** - * Output completion message (called from TaskCompleted handler). - */ - outputCompletionResult(ts: number, text: string): void { - const previousDisplay = this.displayedMessages.get(ts) - if (!previousDisplay || previousDisplay.partial) { - this.output("\n[task complete]", text || "") - this.displayedMessages.set(ts, { ts, text: text || "", partial: false }) - } - } -} diff --git a/apps/cli/src/agent/prompt-manager.ts b/apps/cli/src/agent/prompt-manager.ts deleted file mode 100644 index 40f1c38d586..00000000000 --- a/apps/cli/src/agent/prompt-manager.ts +++ /dev/null @@ -1,297 +0,0 @@ -/** - * PromptManager - Handles all user input collection - * - * This manager is responsible for: - * - Collecting user input via readline - * - Yes/No prompts with proper defaults - * - Timed prompts that auto-select after timeout - * - Raw mode input for character-by-character handling - * - * Design notes: - * - Single responsibility: User input only (no output formatting) - * - Returns Promises for all input operations - * - Handles console mode switching (quiet mode restore) - * - Can be disabled for programmatic (non-interactive) use - */ - -import readline from "readline" - -// ============================================================================= -// Types -// ============================================================================= - -/** - * Configuration options for PromptManager. - */ -export interface PromptManagerOptions { - /** - * Called before prompting to restore console output. - * Used to exit quiet mode temporarily. - */ - onBeforePrompt?: () => void - - /** - * Called after prompting to re-enable quiet mode. - */ - onAfterPrompt?: () => void - - /** - * Stream for input (default: process.stdin). - */ - stdin?: NodeJS.ReadStream - - /** - * Stream for prompt output (default: process.stdout). - */ - stdout?: NodeJS.WriteStream -} - -/** - * Result of a timed prompt. - */ -export interface TimedPromptResult { - /** The user's input, or default if timed out */ - value: string - /** Whether the result came from timeout */ - timedOut: boolean - /** Whether the user cancelled (Ctrl+C) */ - cancelled: boolean -} - -// ============================================================================= -// PromptManager Class -// ============================================================================= - -export class PromptManager { - private onBeforePrompt?: () => void - private onAfterPrompt?: () => void - private stdin: NodeJS.ReadStream - private stdout: NodeJS.WriteStream - - /** - * Track if a prompt is currently active. - */ - private isPrompting = false - - constructor(options: PromptManagerOptions = {}) { - this.onBeforePrompt = options.onBeforePrompt - this.onAfterPrompt = options.onAfterPrompt - this.stdin = options.stdin ?? (process.stdin as NodeJS.ReadStream) - this.stdout = options.stdout ?? process.stdout - } - - // =========================================================================== - // Public API - // =========================================================================== - - /** - * Check if a prompt is currently active. - */ - isActive(): boolean { - return this.isPrompting - } - - /** - * Prompt for text input using readline. - * - * @param prompt - The prompt text to display - * @returns The user's input - * @throws If input is cancelled or an error occurs - */ - async promptForInput(prompt: string): Promise { - return new Promise((resolve, reject) => { - this.beforePrompt() - this.isPrompting = true - - const rl = readline.createInterface({ - input: this.stdin, - output: this.stdout, - }) - - rl.question(prompt, (answer) => { - rl.close() - this.isPrompting = false - this.afterPrompt() - resolve(answer) - }) - - rl.on("close", () => { - this.isPrompting = false - this.afterPrompt() - }) - - rl.on("error", (err) => { - rl.close() - this.isPrompting = false - this.afterPrompt() - reject(err) - }) - }) - } - - /** - * Prompt for yes/no input. - * - * @param prompt - The prompt text to display - * @param defaultValue - Default value if empty input (default: false) - * @returns true for yes, false for no - */ - async promptForYesNo(prompt: string, defaultValue = false): Promise { - const answer = await this.promptForInput(prompt) - const normalized = answer.trim().toLowerCase() - if (normalized === "" && defaultValue !== undefined) { - return defaultValue - } - return normalized === "y" || normalized === "yes" - } - - /** - * Prompt for input with a timeout. - * Uses raw mode for character-by-character input handling. - * - * @param prompt - The prompt text to display - * @param timeoutMs - Timeout in milliseconds - * @param defaultValue - Value to use if timed out - * @returns TimedPromptResult with value, timedOut flag, and cancelled flag - */ - async promptWithTimeout(prompt: string, timeoutMs: number, defaultValue: string): Promise { - return new Promise((resolve) => { - this.beforePrompt() - this.isPrompting = true - - // Track the original raw mode state to restore it later - const wasRaw = this.stdin.isRaw - - // Enable raw mode for character-by-character input if TTY - if (this.stdin.isTTY) { - this.stdin.setRawMode(true) - } - - this.stdin.resume() - - let inputBuffer = "" - let timeoutCancelled = false - let resolved = false - - // Set up timeout - const timeout = setTimeout(() => { - if (!resolved) { - resolved = true - cleanup() - this.stdout.write(`\n[Timeout - using default: ${defaultValue || "(empty)"}]\n`) - resolve({ value: defaultValue, timedOut: true, cancelled: false }) - } - }, timeoutMs) - - // Display prompt - this.stdout.write(prompt) - - // Cleanup function to restore state - const cleanup = () => { - clearTimeout(timeout) - this.stdin.removeListener("data", onData) - - if (this.stdin.isTTY && wasRaw !== undefined) { - this.stdin.setRawMode(wasRaw) - } - - this.stdin.pause() - this.isPrompting = false - this.afterPrompt() - } - - // Handle incoming data - const onData = (data: Buffer) => { - const char = data.toString() - - // Handle Ctrl+C - if (char === "\x03") { - cleanup() - resolved = true - this.stdout.write("\n[cancelled]\n") - resolve({ value: defaultValue, timedOut: false, cancelled: true }) - return - } - - // Cancel timeout on first input - if (!timeoutCancelled) { - timeoutCancelled = true - clearTimeout(timeout) - } - - // Handle Enter - if (char === "\r" || char === "\n") { - if (!resolved) { - resolved = true - cleanup() - this.stdout.write("\n") - resolve({ value: inputBuffer, timedOut: false, cancelled: false }) - } - return - } - - // Handle Backspace - if (char === "\x7f" || char === "\b") { - if (inputBuffer.length > 0) { - inputBuffer = inputBuffer.slice(0, -1) - this.stdout.write("\b \b") - } - return - } - - // Normal character - add to buffer and echo - inputBuffer += char - this.stdout.write(char) - } - - this.stdin.on("data", onData) - }) - } - - /** - * Prompt for yes/no with timeout. - * - * @param prompt - The prompt text to display - * @param timeoutMs - Timeout in milliseconds - * @param defaultValue - Default boolean value if timed out - * @returns true for yes, false for no - */ - async promptForYesNoWithTimeout(prompt: string, timeoutMs: number, defaultValue: boolean): Promise { - const result = await this.promptWithTimeout(prompt, timeoutMs, defaultValue ? "y" : "n") - const normalized = result.value.trim().toLowerCase() - if (result.timedOut || result.cancelled || normalized === "") { - return defaultValue - } - return normalized === "y" || normalized === "yes" - } - - /** - * Display a message on stdout (utility for prompting context). - */ - write(text: string): void { - this.stdout.write(text) - } - - /** - * Display a message with newline. - */ - writeLine(text: string): void { - this.stdout.write(text + "\n") - } - - // =========================================================================== - // Private Helpers - // =========================================================================== - - private beforePrompt(): void { - if (this.onBeforePrompt) { - this.onBeforePrompt() - } - } - - private afterPrompt(): void { - if (this.onAfterPrompt) { - this.onAfterPrompt() - } - } -} diff --git a/apps/cli/src/agent/state-store.ts b/apps/cli/src/agent/state-store.ts deleted file mode 100644 index 68dcfc40698..00000000000 --- a/apps/cli/src/agent/state-store.ts +++ /dev/null @@ -1,415 +0,0 @@ -/** - * State Store - * - * This module manages the client's internal state, including: - * - The clineMessages array (source of truth for agent state) - * - The computed agent state info - * - Any extension state we want to cache - * - * The store is designed to be: - * - Immutable: State updates create new objects, not mutations - * - Observable: Changes trigger notifications - * - Queryable: Current state is always accessible - */ - -import { ClineMessage, ExtensionState } from "@roo-code/types" - -import { detectAgentState, AgentStateInfo, AgentLoopState } from "./agent-state.js" -import { Observable } from "./events.js" - -// ============================================================================= -// Store State Interface -// ============================================================================= - -/** - * The complete state managed by the store. - */ -export interface StoreState { - /** - * The array of messages from the extension. - * This is the primary data used to compute agent state. - */ - messages: ClineMessage[] - - /** - * The computed agent state info. - * Updated automatically when messages change. - */ - agentState: AgentStateInfo - - /** - * Whether we have received any state from the extension. - * Useful to distinguish "no task" from "not yet connected". - */ - isInitialized: boolean - - /** - * The last time state was updated. - */ - lastUpdatedAt: number - - /** - * The current mode (e.g., "code", "architect", "ask"). - * Tracked from state messages received from the extension. - */ - currentMode: string | undefined - - /** - * Optional: Cache of extension state fields we might need. - * This is a subset of the full ExtensionState. - */ - extensionState?: Partial -} - -/** - * Create the initial store state. - */ -function createInitialState(): StoreState { - return { - messages: [], - agentState: detectAgentState([]), - isInitialized: false, - lastUpdatedAt: Date.now(), - currentMode: undefined, - } -} - -// ============================================================================= -// State Store Class -// ============================================================================= - -/** - * StateStore manages all client state and provides reactive updates. - * - * Key features: - * - Stores the clineMessages array - * - Automatically computes agent state when messages change - * - Provides observable pattern for state changes - * - Tracks state history for debugging (optional) - * - * Usage: - * ```typescript - * const store = new StateStore() - * - * // Subscribe to state changes - * store.subscribe((state) => { - * console.log('New state:', state.agentState.state) - * }) - * - * // Update messages - * store.setMessages(newMessages) - * - * // Query current state - * const currentState = store.getState() - * ``` - */ -export class StateStore { - private state: StoreState - private stateObservable: Observable - private agentStateObservable: Observable - - /** - * Optional: Track state history for debugging. - * Set maxHistorySize to enable. - */ - private stateHistory: StoreState[] = [] - private maxHistorySize: number - - constructor(options: { maxHistorySize?: number } = {}) { - this.state = createInitialState() - this.stateObservable = new Observable(this.state) - this.agentStateObservable = new Observable(this.state.agentState) - this.maxHistorySize = options.maxHistorySize ?? 0 - } - - // =========================================================================== - // State Queries - // =========================================================================== - - /** - * Get the current complete state. - */ - getState(): StoreState { - return this.state - } - - /** - * Get just the agent state info. - * This is a convenience method for the most common query. - */ - getAgentState(): AgentStateInfo { - return this.state.agentState - } - - /** - * Get the current messages array. - */ - getMessages(): ClineMessage[] { - return this.state.messages - } - - /** - * Get the last message, if any. - */ - getLastMessage(): ClineMessage | undefined { - return this.state.messages[this.state.messages.length - 1] - } - - /** - * Check if the store has been initialized with extension state. - */ - isInitialized(): boolean { - return this.state.isInitialized - } - - /** - * Quick check: Is the agent currently waiting for input? - */ - isWaitingForInput(): boolean { - return this.state.agentState.isWaitingForInput - } - - /** - * Quick check: Is the agent currently running? - */ - isRunning(): boolean { - return this.state.agentState.isRunning - } - - /** - * Quick check: Is content currently streaming? - */ - isStreaming(): boolean { - return this.state.agentState.isStreaming - } - - /** - * Get the current agent loop state enum value. - */ - getCurrentState(): AgentLoopState { - return this.state.agentState.state - } - - /** - * Get the current mode (e.g., "code", "architect", "ask"). - */ - getCurrentMode(): string | undefined { - return this.state.currentMode - } - - // =========================================================================== - // State Updates - // =========================================================================== - - /** - * Set the complete messages array. - * This is typically called when receiving a full state update from the extension. - * - * @param messages - The new messages array - * @returns The previous agent state (for comparison) - */ - setMessages(messages: ClineMessage[]): AgentStateInfo { - const previousAgentState = this.state.agentState - const newAgentState = detectAgentState(messages) - - this.updateState({ - messages, - agentState: newAgentState, - isInitialized: true, - lastUpdatedAt: Date.now(), - currentMode: this.state.currentMode, // Preserve mode across message updates - }) - - return previousAgentState - } - - /** - * Add a single message to the end of the messages array. - * Useful when receiving incremental updates. - * - * @param message - The message to add - * @returns The previous agent state - */ - addMessage(message: ClineMessage): AgentStateInfo { - const newMessages = [...this.state.messages, message] - return this.setMessages(newMessages) - } - - /** - * Update a message in place (e.g., when partial becomes complete). - * Finds the message by timestamp and replaces it. - * - * @param message - The updated message - * @returns The previous agent state, or undefined if message not found - */ - updateMessage(message: ClineMessage): AgentStateInfo | undefined { - const index = this.state.messages.findIndex((m) => m.ts === message.ts) - if (index === -1) { - // Message not found, add it instead - return this.addMessage(message) - } - - const newMessages = [...this.state.messages] - newMessages[index] = message - return this.setMessages(newMessages) - } - - /** - * Clear all messages and reset to initial state. - * Called when a task is cleared/cancelled. - */ - clear(): void { - this.updateState({ - messages: [], - agentState: detectAgentState([]), - isInitialized: true, // Still initialized, just empty - lastUpdatedAt: Date.now(), - currentMode: this.state.currentMode, // Preserve mode when clearing task - extensionState: undefined, - }) - } - - /** - * Set the current mode. - * Called when mode changes are detected from extension state messages. - * - * @param mode - The new mode value - */ - setCurrentMode(mode: string | undefined): void { - if (this.state.currentMode !== mode) { - this.updateState({ - ...this.state, - currentMode: mode, - lastUpdatedAt: Date.now(), - }) - } - } - - /** - * Reset to completely uninitialized state. - * Called on disconnect or reset. - */ - reset(): void { - this.state = createInitialState() - this.stateHistory = [] - // Don't notify on reset - we're starting fresh - } - - /** - * Update cached extension state. - * This stores any additional extension state fields we might need. - * - * @param extensionState - The extension state to cache - */ - setExtensionState(extensionState: Partial): void { - // Extract and store messages if present - if (extensionState.clineMessages) { - this.setMessages(extensionState.clineMessages) - } - - // Store the rest of the extension state - this.updateState({ - ...this.state, - extensionState: { - ...this.state.extensionState, - ...extensionState, - }, - }) - } - - // =========================================================================== - // Subscriptions - // =========================================================================== - - /** - * Subscribe to all state changes. - * - * @param observer - Callback function receiving the new state - * @returns Unsubscribe function - */ - subscribe(observer: (state: StoreState) => void): () => void { - return this.stateObservable.subscribe(observer) - } - - /** - * Subscribe to agent state changes only. - * This is more efficient if you only care about agent state. - * - * @param observer - Callback function receiving the new agent state - * @returns Unsubscribe function - */ - subscribeToAgentState(observer: (state: AgentStateInfo) => void): () => void { - return this.agentStateObservable.subscribe(observer) - } - - // =========================================================================== - // History (for debugging) - // =========================================================================== - - /** - * Get the state history (if enabled). - */ - getHistory(): StoreState[] { - return [...this.stateHistory] - } - - /** - * Clear the state history. - */ - clearHistory(): void { - this.stateHistory = [] - } - - // =========================================================================== - // Private Methods - // =========================================================================== - - /** - * Internal method to update state and notify observers. - */ - private updateState(newState: StoreState): void { - // Track history if enabled - if (this.maxHistorySize > 0) { - this.stateHistory.push(this.state) - if (this.stateHistory.length > this.maxHistorySize) { - this.stateHistory.shift() - } - } - - this.state = newState - - // Notify observers - this.stateObservable.next(this.state) - this.agentStateObservable.next(this.state.agentState) - } -} - -// ============================================================================= -// Singleton Store (optional convenience) -// ============================================================================= - -let defaultStore: StateStore | null = null - -/** - * Get the default singleton store instance. - * Useful for simple applications that don't need multiple stores. - */ -export function getDefaultStore(): StateStore { - if (!defaultStore) { - defaultStore = new StateStore() - } - - return defaultStore -} - -/** - * Reset the default store instance. - * Useful for testing or when you need a fresh start. - */ -export function resetDefaultStore(): void { - if (defaultStore) { - defaultStore.reset() - } - - defaultStore = null -} diff --git a/apps/cli/src/commands/auth/index.ts b/apps/cli/src/commands/auth/index.ts deleted file mode 100644 index 52ae7673a7e..00000000000 --- a/apps/cli/src/commands/auth/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from "./login.js" -export * from "./logout.js" -export * from "./status.js" diff --git a/apps/cli/src/commands/auth/login.ts b/apps/cli/src/commands/auth/login.ts deleted file mode 100644 index 14966f2d156..00000000000 --- a/apps/cli/src/commands/auth/login.ts +++ /dev/null @@ -1,186 +0,0 @@ -import http from "http" -import { randomBytes } from "crypto" -import net from "net" -import { exec } from "child_process" - -import { AUTH_BASE_URL } from "@/types/index.js" -import { saveToken } from "@/lib/storage/index.js" - -export interface LoginOptions { - timeout?: number - verbose?: boolean -} - -export interface LoginResult { - success: boolean - error?: string - userId?: string - orgId?: string | null -} - -const LOCALHOST = "127.0.0.1" - -export async function login({ timeout = 5 * 60 * 1000, verbose = false }: LoginOptions = {}): Promise { - const state = randomBytes(16).toString("hex") - const port = await getAvailablePort() - const host = `http://${LOCALHOST}:${port}` - - if (verbose) { - console.log(`[Auth] Starting local callback server on port ${port}`) - } - - // Create promise that will be resolved when we receive the callback. - const tokenPromise = new Promise<{ token: string; state: string }>((resolve, reject) => { - const server = http.createServer((req, res) => { - const url = new URL(req.url!, host) - - if (url.pathname === "/callback") { - const receivedState = url.searchParams.get("state") - const token = url.searchParams.get("token") - const error = url.searchParams.get("error") - - if (error) { - const errorUrl = new URL(`${AUTH_BASE_URL}/cli/sign-in?error=error-in-callback`) - errorUrl.searchParams.set("message", error) - res.writeHead(302, { Location: errorUrl.toString() }) - res.end() - // Wait for response to be fully sent before closing server and rejecting. - // The 'close' event fires when the underlying connection is terminated, - // ensuring the browser has received the redirect before we shut down. - res.on("close", () => { - server.close() - reject(new Error(error)) - }) - } else if (!token) { - const errorUrl = new URL(`${AUTH_BASE_URL}/cli/sign-in?error=missing-token`) - errorUrl.searchParams.set("message", "Missing token in callback") - res.writeHead(302, { Location: errorUrl.toString() }) - res.end() - res.on("close", () => { - server.close() - reject(new Error("Missing token in callback")) - }) - } else if (receivedState !== state) { - const errorUrl = new URL(`${AUTH_BASE_URL}/cli/sign-in?error=invalid-state-parameter`) - errorUrl.searchParams.set("message", "Invalid state parameter (possible CSRF attack)") - res.writeHead(302, { Location: errorUrl.toString() }) - res.end() - res.on("close", () => { - server.close() - reject(new Error("Invalid state parameter")) - }) - } else { - res.writeHead(302, { Location: `${AUTH_BASE_URL}/cli/sign-in?success=true` }) - res.end() - res.on("close", () => { - server.close() - resolve({ token, state: receivedState }) - }) - } - } else { - res.writeHead(404, { "Content-Type": "text/plain" }) - res.end("Not found") - } - }) - - server.listen(port, LOCALHOST) - - const timeoutId = setTimeout(() => { - server.close() - reject(new Error("Authentication timed out")) - }, timeout) - - server.on("listening", () => { - console.log(`[Auth] Callback server listening on port ${port}`) - }) - - server.on("close", () => { - console.log("[Auth] Callback server closed") - clearTimeout(timeoutId) - }) - }) - - const authUrl = new URL(`${AUTH_BASE_URL}/cli/sign-in`) - authUrl.searchParams.set("state", state) - authUrl.searchParams.set("callback", `${host}/callback`) - - console.log("Opening browser for authentication...") - console.log(`If the browser doesn't open, visit: ${authUrl.toString()}`) - - try { - await openBrowser(authUrl.toString()) - } catch (error) { - if (verbose) { - console.warn("[Auth] Failed to open browser automatically:", error) - } - - console.log("Please open the URL above in your browser manually.") - } - - try { - const { token } = await tokenPromise - await saveToken(token) - console.log("✓ Successfully authenticated!") - return { success: true } - } catch (error) { - const message = error instanceof Error ? error.message : String(error) - console.error(`✗ Authentication failed: ${message}`) - return { success: false, error: message } - } -} - -async function getAvailablePort(startPort = 49152, endPort = 65535): Promise { - return new Promise((resolve, reject) => { - const server = net.createServer() - let port = startPort - - const tryPort = () => { - server.once("error", (err: NodeJS.ErrnoException) => { - if (err.code === "EADDRINUSE" && port < endPort) { - port++ - tryPort() - } else { - reject(err) - } - }) - - server.once("listening", () => { - server.close(() => { - resolve(port) - }) - }) - - server.listen(port, LOCALHOST) - } - - tryPort() - }) -} - -function openBrowser(url: string): Promise { - return new Promise((resolve, reject) => { - const platform = process.platform - let command: string - - switch (platform) { - case "darwin": - command = `open "${url}"` - break - case "win32": - command = `start "" "${url}"` - break - default: - // Linux and other Unix-like systems. - command = `xdg-open "${url}"` - break - } - - exec(command, (error) => { - if (error) { - reject(error) - } else { - resolve() - } - }) - }) -} diff --git a/apps/cli/src/commands/auth/logout.ts b/apps/cli/src/commands/auth/logout.ts deleted file mode 100644 index 61c3cb37a49..00000000000 --- a/apps/cli/src/commands/auth/logout.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { clearToken, hasToken, getCredentialsPath } from "@/lib/storage/index.js" - -export interface LogoutOptions { - verbose?: boolean -} - -export interface LogoutResult { - success: boolean - wasLoggedIn: boolean -} - -export async function logout({ verbose = false }: LogoutOptions = {}): Promise { - const wasLoggedIn = await hasToken() - - if (!wasLoggedIn) { - console.log("You are not currently logged in.") - return { success: true, wasLoggedIn: false } - } - - if (verbose) { - console.log(`[Auth] Removing credentials from ${getCredentialsPath()}`) - } - - await clearToken() - console.log("✓ Successfully logged out") - return { success: true, wasLoggedIn: true } -} diff --git a/apps/cli/src/commands/auth/status.ts b/apps/cli/src/commands/auth/status.ts deleted file mode 100644 index 9e81adfda8a..00000000000 --- a/apps/cli/src/commands/auth/status.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { loadToken, loadCredentials, getCredentialsPath } from "@/lib/storage/index.js" -import { isTokenExpired, isTokenValid, getTokenExpirationDate } from "@/lib/auth/index.js" - -export interface StatusOptions { - verbose?: boolean -} - -export interface StatusResult { - authenticated: boolean - expired?: boolean - expiringSoon?: boolean - userId?: string - orgId?: string | null - expiresAt?: Date - createdAt?: Date -} - -export async function status(options: StatusOptions = {}): Promise { - const { verbose = false } = options - - const token = await loadToken() - - if (!token) { - console.log("✗ Not authenticated") - console.log("") - console.log("Run: roo auth login") - return { authenticated: false } - } - - const expiresAt = getTokenExpirationDate(token) - const expired = !isTokenValid(token) - const expiringSoon = isTokenExpired(token, 24 * 60 * 60) && !expired - - const credentials = await loadCredentials() - const createdAt = credentials?.createdAt ? new Date(credentials.createdAt) : undefined - - if (expired) { - console.log("✗ Authentication token expired") - console.log("") - console.log("Run: roo auth login") - - return { - authenticated: false, - expired: true, - expiresAt: expiresAt ?? undefined, - } - } - - if (expiringSoon) { - console.log("⚠ Expires soon; refresh with `roo auth login`") - } else { - console.log("✓ Authenticated") - } - - if (expiresAt) { - const remaining = getTimeRemaining(expiresAt) - console.log(` Expires: ${formatDate(expiresAt)} (${remaining})`) - } - - if (createdAt && verbose) { - console.log(` Created: ${formatDate(createdAt)}`) - } - - if (verbose) { - console.log(` Credentials: ${getCredentialsPath()}`) - } - - return { - authenticated: true, - expired: false, - expiringSoon, - expiresAt: expiresAt ?? undefined, - createdAt, - } -} - -function formatDate(date: Date): string { - return date.toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" }) -} - -function getTimeRemaining(date: Date): string { - const now = new Date() - const diff = date.getTime() - now.getTime() - - if (diff <= 0) { - return "expired" - } - - const days = Math.floor(diff / (1000 * 60 * 60 * 24)) - const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) - - if (days > 0) { - return `${days} day${days === 1 ? "" : "s"}` - } - - return `${hours} hour${hours === 1 ? "" : "s"}` -} diff --git a/apps/cli/src/commands/cli/index.ts b/apps/cli/src/commands/cli/index.ts deleted file mode 100644 index 89e8e9f1ba6..00000000000 --- a/apps/cli/src/commands/cli/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./run.js" diff --git a/apps/cli/src/commands/cli/run.ts b/apps/cli/src/commands/cli/run.ts deleted file mode 100644 index 5b305ce2751..00000000000 --- a/apps/cli/src/commands/cli/run.ts +++ /dev/null @@ -1,219 +0,0 @@ -import fs from "fs" -import path from "path" -import { fileURLToPath } from "url" - -import { createElement } from "react" - -import { isProviderName } from "@roo-code/types" -import { setLogger } from "@roo-code/vscode-shim" - -import { - FlagOptions, - isSupportedProvider, - OnboardingProviderChoice, - supportedProviders, - ASCII_ROO, - DEFAULT_FLAGS, - REASONING_EFFORTS, - SDK_BASE_URL, -} from "@/types/index.js" - -import { type User, createClient } from "@/lib/sdk/index.js" -import { loadToken, hasToken, loadSettings } from "@/lib/storage/index.js" -import { getEnvVarName, getApiKeyFromEnv } from "@/lib/utils/provider.js" -import { runOnboarding } from "@/lib/utils/onboarding.js" -import { getDefaultExtensionPath } from "@/lib/utils/extension.js" -import { VERSION } from "@/lib/utils/version.js" - -import { ExtensionHost, ExtensionHostOptions } from "@/agent/index.js" - -const __dirname = path.dirname(fileURLToPath(import.meta.url)) - -export async function run(workspaceArg: string, options: FlagOptions) { - setLogger({ - info: () => {}, - warn: () => {}, - error: () => {}, - debug: () => {}, - }) - - const isTuiSupported = process.stdin.isTTY && process.stdout.isTTY - const isTuiEnabled = options.tui && isTuiSupported - const extensionPath = options.extension || getDefaultExtensionPath(__dirname) - const workspacePath = path.resolve(workspaceArg) - - if (!isSupportedProvider(options.provider)) { - console.error( - `[CLI] Error: Invalid provider: ${options.provider}; must be one of: ${supportedProviders.join(", ")}`, - ) - - process.exit(1) - } - - let apiKey = options.apiKey || getApiKeyFromEnv(options.provider) - let provider = options.provider - let user: User | null = null - let useCloudProvider = false - - if (isTuiEnabled) { - let { onboardingProviderChoice } = await loadSettings() - - if (!onboardingProviderChoice) { - const result = await runOnboarding() - onboardingProviderChoice = result.choice - } - - if (onboardingProviderChoice === OnboardingProviderChoice.Roo) { - useCloudProvider = true - const authenticated = await hasToken() - - if (authenticated) { - const token = await loadToken() - - if (token) { - try { - const client = createClient({ url: SDK_BASE_URL, authToken: token }) - const me = await client.auth.me.query() - provider = "roo" - apiKey = token - user = me?.type === "user" ? me.user : null - } catch { - // Token may be expired or invalid - user will need to re-authenticate. - } - } - } - } - } - - if (!apiKey) { - if (useCloudProvider) { - console.error("[CLI] Error: Authentication with Roo Code Cloud failed or was cancelled.") - console.error("[CLI] Please run: roo auth login") - console.error("[CLI] Or use --api-key to provide your own API key.") - } else { - console.error( - `[CLI] Error: No API key provided. Use --api-key or set the appropriate environment variable.`, - ) - console.error(`[CLI] For ${provider}, set ${getEnvVarName(provider)}`) - } - - process.exit(1) - } - - if (!fs.existsSync(workspacePath)) { - console.error(`[CLI] Error: Workspace path does not exist: ${workspacePath}`) - process.exit(1) - } - - if (!isProviderName(options.provider)) { - console.error(`[CLI] Error: Invalid provider: ${options.provider}`) - process.exit(1) - } - - if (options.reasoningEffort && !REASONING_EFFORTS.includes(options.reasoningEffort)) { - console.error( - `[CLI] Error: Invalid reasoning effort: ${options.reasoningEffort}, must be one of: ${REASONING_EFFORTS.join(", ")}`, - ) - process.exit(1) - } - - if (options.tui && !isTuiSupported) { - console.log("[CLI] TUI disabled (no TTY support), falling back to plain text mode") - } - - if (!isTuiEnabled && !options.prompt) { - console.error("[CLI] Error: prompt is required in plain text mode") - console.error("[CLI] Usage: roo [workspace] -P [options]") - console.error("[CLI] Use TUI mode (without --no-tui) for interactive input") - process.exit(1) - } - - if (isTuiEnabled) { - try { - const { render } = await import("ink") - const { App } = await import("../../ui/App.js") - - render( - createElement(App, { - initialPrompt: options.prompt || "", - workspacePath: workspacePath, - extensionPath: path.resolve(extensionPath), - user, - provider, - apiKey, - model: options.model || DEFAULT_FLAGS.model, - mode: options.mode || DEFAULT_FLAGS.mode, - nonInteractive: options.yes, - debug: options.debug, - exitOnComplete: options.exitOnComplete, - reasoningEffort: options.reasoningEffort, - ephemeral: options.ephemeral, - version: VERSION, - // Create extension host factory for dependency injection. - createExtensionHost: (opts: ExtensionHostOptions) => new ExtensionHost(opts), - }), - // Handle Ctrl+C in App component for double-press exit. - { exitOnCtrlC: false }, - ) - } catch (error) { - console.error("[CLI] Failed to start TUI:", error instanceof Error ? error.message : String(error)) - - if (error instanceof Error) { - console.error(error.stack) - } - - process.exit(1) - } - } else { - console.log(ASCII_ROO) - console.log() - console.log( - `[roo] Running ${options.model || "default"} (${options.reasoningEffort || "default"}) on ${provider} in ${options.mode || "default"} mode in ${workspacePath}`, - ) - - const host = new ExtensionHost({ - mode: options.mode || DEFAULT_FLAGS.mode, - reasoningEffort: options.reasoningEffort === "unspecified" ? undefined : options.reasoningEffort, - user, - provider, - apiKey, - model: options.model || DEFAULT_FLAGS.model, - workspacePath, - extensionPath: path.resolve(extensionPath), - nonInteractive: options.yes, - ephemeral: options.ephemeral, - debug: options.debug, - }) - - process.on("SIGINT", async () => { - console.log("\n[CLI] Received SIGINT, shutting down...") - await host.dispose() - process.exit(130) - }) - - process.on("SIGTERM", async () => { - console.log("\n[CLI] Received SIGTERM, shutting down...") - await host.dispose() - process.exit(143) - }) - - try { - await host.activate() - await host.runTask(options.prompt!) - await host.dispose() - - if (!options.waitOnComplete) { - process.exit(0) - } - } catch (error) { - console.error("[CLI] Error:", error instanceof Error ? error.message : String(error)) - - if (error instanceof Error) { - console.error(error.stack) - } - - await host.dispose() - process.exit(1) - } - } -} diff --git a/apps/cli/src/commands/index.ts b/apps/cli/src/commands/index.ts deleted file mode 100644 index 717a7040ef6..00000000000 --- a/apps/cli/src/commands/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./auth/index.js" -export * from "./cli/index.js" diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.ts deleted file mode 100644 index 8d3f5af521e..00000000000 --- a/apps/cli/src/index.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { Command } from "commander" - -import { DEFAULT_FLAGS } from "@/types/constants.js" -import { VERSION } from "@/lib/utils/version.js" -import { run, login, logout, status } from "@/commands/index.js" - -const program = new Command() - -program.name("roo").description("Roo Code CLI - Run the Roo Code agent from the command line").version(VERSION) - -program - .argument("[workspace]", "Workspace path to operate in", process.cwd()) - .option("-P, --prompt ", "The prompt/task to execute (optional in TUI mode)") - .option("-e, --extension ", "Path to the extension bundle directory") - .option("-d, --debug", "Enable debug output (includes detailed debug information)", false) - .option("-y, --yes", "Auto-approve all prompts (non-interactive mode)", false) - .option("-k, --api-key ", "API key for the LLM provider (defaults to OPENROUTER_API_KEY env var)") - .option("-p, --provider ", "API provider (anthropic, openai, openrouter, etc.)", "openrouter") - .option("-m, --model ", "Model to use", DEFAULT_FLAGS.model) - .option("-M, --mode ", "Mode to start in (code, architect, ask, debug, etc.)", DEFAULT_FLAGS.mode) - .option( - "-r, --reasoning-effort ", - "Reasoning effort level (unspecified, disabled, none, minimal, low, medium, high, xhigh)", - DEFAULT_FLAGS.reasoningEffort, - ) - .option("-x, --exit-on-complete", "Exit the process when the task completes (applies to TUI mode only)", false) - .option( - "-w, --wait-on-complete", - "Keep the process running when the task completes (applies to plain text mode only)", - false, - ) - .option("--ephemeral", "Run without persisting state (uses temporary storage)", false) - .option("--no-tui", "Disable TUI, use plain text output") - .action(run) - -const authCommand = program.command("auth").description("Manage authentication for Roo Code Cloud") - -authCommand - .command("login") - .description("Authenticate with Roo Code Cloud") - .option("-v, --verbose", "Enable verbose output", false) - .action(async (options: { verbose: boolean }) => { - const result = await login({ verbose: options.verbose }) - process.exit(result.success ? 0 : 1) - }) - -authCommand - .command("logout") - .description("Log out from Roo Code Cloud") - .option("-v, --verbose", "Enable verbose output", false) - .action(async (options: { verbose: boolean }) => { - const result = await logout({ verbose: options.verbose }) - process.exit(result.success ? 0 : 1) - }) - -authCommand - .command("status") - .description("Show authentication status") - .option("-v, --verbose", "Enable verbose output", false) - .action(async (options: { verbose: boolean }) => { - const result = await status({ verbose: options.verbose }) - process.exit(result.authenticated ? 0 : 1) - }) - -program.parse() diff --git a/apps/cli/src/lib/auth/index.ts b/apps/cli/src/lib/auth/index.ts deleted file mode 100644 index ec1a4598356..00000000000 --- a/apps/cli/src/lib/auth/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./token.js" diff --git a/apps/cli/src/lib/auth/token.ts b/apps/cli/src/lib/auth/token.ts deleted file mode 100644 index 34365223a47..00000000000 --- a/apps/cli/src/lib/auth/token.ts +++ /dev/null @@ -1,61 +0,0 @@ -export interface DecodedToken { - iss: string - sub: string - exp: number - iat: number - nbf: number - v: number - r?: { - u?: string - o?: string - t: string - } -} - -function decodeToken(token: string): DecodedToken | null { - try { - const parts = token.split(".") - - if (parts.length !== 3) { - return null - } - - const payload = parts[1] - - if (!payload) { - return null - } - - const padded = payload + "=".repeat((4 - (payload.length % 4)) % 4) - const decoded = Buffer.from(padded, "base64url").toString("utf-8") - return JSON.parse(decoded) as DecodedToken - } catch { - return null - } -} - -export function isTokenExpired(token: string, bufferSeconds = 24 * 60 * 60): boolean { - const decoded = decodeToken(token) - - if (!decoded?.exp) { - return true - } - - const expiresAt = decoded.exp - const bufferTime = Math.floor(Date.now() / 1000) + bufferSeconds - return expiresAt < bufferTime -} - -export function isTokenValid(token: string): boolean { - return !isTokenExpired(token, 0) -} - -export function getTokenExpirationDate(token: string): Date | null { - const decoded = decodeToken(token) - - if (!decoded?.exp) { - return null - } - - return new Date(decoded.exp * 1000) -} diff --git a/apps/cli/src/lib/sdk/client.ts b/apps/cli/src/lib/sdk/client.ts deleted file mode 100644 index ff60e798ef6..00000000000 --- a/apps/cli/src/lib/sdk/client.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { createTRPCProxyClient, httpBatchLink } from "@trpc/client" -import superjson from "superjson" - -import type { User, Org } from "./types.js" - -export interface ClientConfig { - url: string - authToken: string -} - -export interface RooClient { - auth: { - me: { - query: () => Promise<{ type: "user"; user: User } | { type: "org"; org: Org } | null> - } - } -} - -export const createClient = ({ url, authToken }: ClientConfig): RooClient => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return createTRPCProxyClient({ - links: [ - httpBatchLink({ - url: `${url}/trpc`, - transformer: superjson, - headers: () => (authToken ? { Authorization: `Bearer ${authToken}` } : {}), - }), - ], - }) as unknown as RooClient -} diff --git a/apps/cli/src/lib/sdk/index.ts b/apps/cli/src/lib/sdk/index.ts deleted file mode 100644 index f45970d7d12..00000000000 --- a/apps/cli/src/lib/sdk/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./types.js" -export * from "./client.js" diff --git a/apps/cli/src/lib/sdk/types.ts b/apps/cli/src/lib/sdk/types.ts deleted file mode 100644 index 9f0511bb2ce..00000000000 --- a/apps/cli/src/lib/sdk/types.ts +++ /dev/null @@ -1,31 +0,0 @@ -export interface User { - id: string - name: string - email: string - imageUrl: string | null - entity: { - id: string - username: string | null - image_url: string - last_name: string - first_name: string - email_addresses: { email_address: string }[] - public_metadata: Record - } - publicMetadata: Record - stripeCustomerId: string | null - lastSyncAt: string - deletedAt: string | null - createdAt: string - updatedAt: string -} - -export interface Org { - id: string - name: string - slug: string - imageUrl: string | null - createdAt: string - updatedAt: string - deletedAt: string | null -} diff --git a/apps/cli/src/lib/storage/__tests__/credentials.test.ts b/apps/cli/src/lib/storage/__tests__/credentials.test.ts deleted file mode 100644 index 574b1b6bf40..00000000000 --- a/apps/cli/src/lib/storage/__tests__/credentials.test.ts +++ /dev/null @@ -1,152 +0,0 @@ -import fs from "fs/promises" -import path from "path" - -// Use vi.hoisted to make the test directory available to the mock -// This must return the path synchronously since CREDENTIALS_FILE is computed at import time -const { getTestConfigDir } = vi.hoisted(() => { - // eslint-disable-next-line @typescript-eslint/no-require-imports - const os = require("os") - // eslint-disable-next-line @typescript-eslint/no-require-imports - const path = require("path") - const testRunId = Date.now().toString() - const testConfigDir = path.join(os.tmpdir(), `roo-cli-test-${testRunId}`) - return { getTestConfigDir: () => testConfigDir } -}) - -vi.mock("../config-dir.js", () => ({ - getConfigDir: getTestConfigDir, -})) - -// Import after mocking -import { saveToken, loadToken, loadCredentials, clearToken, hasToken, getCredentialsPath } from "../credentials.js" - -// Re-derive the test config dir for use in tests (must match the hoisted one) -const actualTestConfigDir = getTestConfigDir() - -describe("Token Storage", () => { - const expectedCredentialsFile = path.join(actualTestConfigDir, "cli-credentials.json") - - beforeEach(async () => { - // Clear test directory before each test - await fs.rm(actualTestConfigDir, { recursive: true, force: true }) - }) - - afterAll(async () => { - // Clean up test directory - await fs.rm(actualTestConfigDir, { recursive: true, force: true }) - }) - - describe("getCredentialsPath", () => { - it("should return the correct credentials file path", () => { - expect(getCredentialsPath()).toBe(expectedCredentialsFile) - }) - }) - - describe("saveToken", () => { - it("should save token to disk", async () => { - const token = "test-token-123" - await saveToken(token) - - const savedData = await fs.readFile(expectedCredentialsFile, "utf-8") - const credentials = JSON.parse(savedData) - - expect(credentials.token).toBe(token) - expect(credentials.createdAt).toBeDefined() - }) - - it("should save token with user info", async () => { - const token = "test-token-456" - await saveToken(token, { userId: "user_123", orgId: "org_456" }) - - const savedData = await fs.readFile(expectedCredentialsFile, "utf-8") - const credentials = JSON.parse(savedData) - - expect(credentials.token).toBe(token) - expect(credentials.userId).toBe("user_123") - expect(credentials.orgId).toBe("org_456") - }) - - it("should create config directory if it doesn't exist", async () => { - const token = "test-token-789" - await saveToken(token) - - const dirStats = await fs.stat(actualTestConfigDir) - expect(dirStats.isDirectory()).toBe(true) - }) - - // Unix file permissions don't apply on Windows - skip this test - it.skipIf(process.platform === "win32")("should set restrictive file permissions", async () => { - const token = "test-token-perms" - await saveToken(token) - - const stats = await fs.stat(expectedCredentialsFile) - // Check that only owner has read/write (mode 0o600) - const mode = stats.mode & 0o777 - expect(mode).toBe(0o600) - }) - }) - - describe("loadToken", () => { - it("should load saved token", async () => { - const token = "test-token-abc" - await saveToken(token) - - const loaded = await loadToken() - expect(loaded).toBe(token) - }) - - it("should return null if no token exists", async () => { - const loaded = await loadToken() - expect(loaded).toBeNull() - }) - }) - - describe("loadCredentials", () => { - it("should load full credentials", async () => { - const token = "test-token-def" - await saveToken(token, { userId: "user_789" }) - - const credentials = await loadCredentials() - - expect(credentials).not.toBeNull() - expect(credentials?.token).toBe(token) - expect(credentials?.userId).toBe("user_789") - expect(credentials?.createdAt).toBeDefined() - }) - - it("should return null if no credentials exist", async () => { - const credentials = await loadCredentials() - expect(credentials).toBeNull() - }) - }) - - describe("clearToken", () => { - it("should remove saved token", async () => { - const token = "test-token-ghi" - await saveToken(token) - - await clearToken() - - const loaded = await loadToken() - expect(loaded).toBeNull() - }) - - it("should not throw if no token exists", async () => { - await expect(clearToken()).resolves.not.toThrow() - }) - }) - - describe("hasToken", () => { - it("should return true if token exists", async () => { - await saveToken("test-token-jkl") - - const exists = await hasToken() - expect(exists).toBe(true) - }) - - it("should return false if no token exists", async () => { - const exists = await hasToken() - expect(exists).toBe(false) - }) - }) -}) diff --git a/apps/cli/src/lib/storage/__tests__/history.test.ts b/apps/cli/src/lib/storage/__tests__/history.test.ts deleted file mode 100644 index f928c2fb426..00000000000 --- a/apps/cli/src/lib/storage/__tests__/history.test.ts +++ /dev/null @@ -1,240 +0,0 @@ -import * as fs from "fs/promises" -import * as path from "path" - -import { getHistoryFilePath, loadHistory, saveHistory, addToHistory, MAX_HISTORY_ENTRIES } from "../history.js" - -vi.mock("fs/promises") - -vi.mock("os", async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - default: { - ...actual, - homedir: vi.fn(() => "/home/testuser"), - }, - homedir: vi.fn(() => "/home/testuser"), - } -}) - -describe("historyStorage", () => { - beforeEach(() => { - vi.resetAllMocks() - }) - - describe("getHistoryFilePath", () => { - it("should return the correct path to cli-history.json", () => { - const result = getHistoryFilePath() - expect(result).toBe(path.join("/home/testuser", ".roo", "cli-history.json")) - }) - }) - - describe("loadHistory", () => { - it("should return empty array when file does not exist", async () => { - const error = new Error("ENOENT") as NodeJS.ErrnoException - error.code = "ENOENT" - vi.mocked(fs.readFile).mockRejectedValue(error) - - const result = await loadHistory() - - expect(result).toEqual([]) - }) - - it("should return entries from valid JSON file", async () => { - const mockData = { - version: 1, - entries: ["first command", "second command", "third command"], - } - vi.mocked(fs.readFile).mockResolvedValue(JSON.stringify(mockData)) - - const result = await loadHistory() - - expect(result).toEqual(["first command", "second command", "third command"]) - }) - - it("should return empty array for invalid JSON", async () => { - vi.mocked(fs.readFile).mockResolvedValue("not valid json") - - // Suppress console.error for this test - const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {}) - - const result = await loadHistory() - - expect(result).toEqual([]) - consoleSpy.mockRestore() - }) - - it("should filter out non-string entries", async () => { - const mockData = { - version: 1, - entries: ["valid", 123, "also valid", null, ""], - } - vi.mocked(fs.readFile).mockResolvedValue(JSON.stringify(mockData)) - - const result = await loadHistory() - - expect(result).toEqual(["valid", "also valid"]) - }) - - it("should return empty array when entries is not an array", async () => { - const mockData = { - version: 1, - entries: "not an array", - } - vi.mocked(fs.readFile).mockResolvedValue(JSON.stringify(mockData)) - - const result = await loadHistory() - - expect(result).toEqual([]) - }) - }) - - describe("saveHistory", () => { - it("should create directory and save history", async () => { - vi.mocked(fs.mkdir).mockResolvedValue(undefined) - vi.mocked(fs.writeFile).mockResolvedValue(undefined) - - await saveHistory(["command1", "command2"]) - - expect(fs.mkdir).toHaveBeenCalledWith(path.join("/home/testuser", ".roo"), { recursive: true }) - expect(fs.writeFile).toHaveBeenCalled() - - // Verify the content written - const writeCall = vi.mocked(fs.writeFile).mock.calls[0] - const writtenContent = JSON.parse(writeCall?.[1] as string) - expect(writtenContent.version).toBe(1) - expect(writtenContent.entries).toEqual(["command1", "command2"]) - }) - - it("should trim entries to MAX_HISTORY_ENTRIES", async () => { - vi.mocked(fs.mkdir).mockResolvedValue(undefined) - vi.mocked(fs.writeFile).mockResolvedValue(undefined) - - // Create array larger than MAX_HISTORY_ENTRIES - const manyEntries = Array.from({ length: MAX_HISTORY_ENTRIES + 100 }, (_, i) => `command${i}`) - - await saveHistory(manyEntries) - - const writeCall = vi.mocked(fs.writeFile).mock.calls[0] - const writtenContent = JSON.parse(writeCall?.[1] as string) - expect(writtenContent.entries.length).toBe(MAX_HISTORY_ENTRIES) - // Should keep the most recent entries (last 500) - expect(writtenContent.entries[0]).toBe(`command100`) - expect(writtenContent.entries[MAX_HISTORY_ENTRIES - 1]).toBe(`command${MAX_HISTORY_ENTRIES + 99}`) - }) - - it("should handle directory already exists error", async () => { - const error = new Error("EEXIST") as NodeJS.ErrnoException - error.code = "EEXIST" - vi.mocked(fs.mkdir).mockRejectedValue(error) - vi.mocked(fs.writeFile).mockResolvedValue(undefined) - - // Should not throw - await expect(saveHistory(["command"])).resolves.not.toThrow() - }) - - it("should log warning on write error but not throw", async () => { - vi.mocked(fs.mkdir).mockResolvedValue(undefined) - vi.mocked(fs.writeFile).mockRejectedValue(new Error("Permission denied")) - - const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {}) - - await expect(saveHistory(["command"])).resolves.not.toThrow() - expect(consoleSpy).toHaveBeenCalledWith( - expect.stringContaining("Could not save CLI history"), - expect.any(String), - ) - - consoleSpy.mockRestore() - }) - }) - - describe("addToHistory", () => { - it("should add new entry to history", async () => { - const mockData = { - version: 1, - entries: ["existing command"], - } - vi.mocked(fs.readFile).mockResolvedValue(JSON.stringify(mockData)) - vi.mocked(fs.mkdir).mockResolvedValue(undefined) - vi.mocked(fs.writeFile).mockResolvedValue(undefined) - - const result = await addToHistory("new command") - - expect(result).toEqual(["existing command", "new command"]) - }) - - it("should not add empty strings", async () => { - const mockData = { - version: 1, - entries: ["existing command"], - } - vi.mocked(fs.readFile).mockResolvedValue(JSON.stringify(mockData)) - - const result = await addToHistory("") - - expect(result).toEqual(["existing command"]) - expect(fs.writeFile).not.toHaveBeenCalled() - }) - - it("should not add whitespace-only strings", async () => { - const mockData = { - version: 1, - entries: ["existing command"], - } - vi.mocked(fs.readFile).mockResolvedValue(JSON.stringify(mockData)) - - const result = await addToHistory(" ") - - expect(result).toEqual(["existing command"]) - expect(fs.writeFile).not.toHaveBeenCalled() - }) - - it("should not add consecutive duplicates", async () => { - const mockData = { - version: 1, - entries: ["first", "second"], - } - vi.mocked(fs.readFile).mockResolvedValue(JSON.stringify(mockData)) - - const result = await addToHistory("second") - - expect(result).toEqual(["first", "second"]) - expect(fs.writeFile).not.toHaveBeenCalled() - }) - - it("should add non-consecutive duplicates", async () => { - const mockData = { - version: 1, - entries: ["first", "second"], - } - vi.mocked(fs.readFile).mockResolvedValue(JSON.stringify(mockData)) - vi.mocked(fs.mkdir).mockResolvedValue(undefined) - vi.mocked(fs.writeFile).mockResolvedValue(undefined) - - const result = await addToHistory("first") - - expect(result).toEqual(["first", "second", "first"]) - }) - - it("should trim whitespace from entry before adding", async () => { - const mockData = { - version: 1, - entries: ["existing"], - } - vi.mocked(fs.readFile).mockResolvedValue(JSON.stringify(mockData)) - vi.mocked(fs.mkdir).mockResolvedValue(undefined) - vi.mocked(fs.writeFile).mockResolvedValue(undefined) - - const result = await addToHistory(" new command ") - - expect(result).toEqual(["existing", "new command"]) - }) - }) - - describe("MAX_HISTORY_ENTRIES", () => { - it("should be 500", () => { - expect(MAX_HISTORY_ENTRIES).toBe(500) - }) - }) -}) diff --git a/apps/cli/src/lib/storage/config-dir.ts b/apps/cli/src/lib/storage/config-dir.ts deleted file mode 100644 index 6d6542ef88f..00000000000 --- a/apps/cli/src/lib/storage/config-dir.ts +++ /dev/null @@ -1,22 +0,0 @@ -import fs from "fs/promises" -import os from "os" -import path from "path" - -const CONFIG_DIR = path.join(os.homedir(), ".roo") - -export function getConfigDir(): string { - return CONFIG_DIR -} - -export async function ensureConfigDir(): Promise { - try { - await fs.mkdir(CONFIG_DIR, { recursive: true }) - } catch (err) { - // Directory may already exist, that's fine. - const error = err as NodeJS.ErrnoException - - if (error.code !== "EEXIST") { - throw err - } - } -} diff --git a/apps/cli/src/lib/storage/credentials.ts b/apps/cli/src/lib/storage/credentials.ts deleted file mode 100644 index b687111c16f..00000000000 --- a/apps/cli/src/lib/storage/credentials.ts +++ /dev/null @@ -1,72 +0,0 @@ -import fs from "fs/promises" -import path from "path" - -import { getConfigDir } from "./index.js" - -const CREDENTIALS_FILE = path.join(getConfigDir(), "cli-credentials.json") - -export interface Credentials { - token: string - createdAt: string - userId?: string - orgId?: string -} - -export async function saveToken(token: string, options?: { userId?: string; orgId?: string }): Promise { - await fs.mkdir(getConfigDir(), { recursive: true }) - - const credentials: Credentials = { - token, - createdAt: new Date().toISOString(), - userId: options?.userId, - orgId: options?.orgId, - } - - await fs.writeFile(CREDENTIALS_FILE, JSON.stringify(credentials, null, 2), { - mode: 0o600, // Read/write for owner only - }) -} - -export async function loadToken(): Promise { - try { - const data = await fs.readFile(CREDENTIALS_FILE, "utf-8") - const credentials: Credentials = JSON.parse(data) - return credentials.token - } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") { - return null - } - throw error - } -} - -export async function loadCredentials(): Promise { - try { - const data = await fs.readFile(CREDENTIALS_FILE, "utf-8") - return JSON.parse(data) as Credentials - } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") { - return null - } - throw error - } -} - -export async function clearToken(): Promise { - try { - await fs.unlink(CREDENTIALS_FILE) - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ENOENT") { - throw error - } - } -} - -export async function hasToken(): Promise { - const token = await loadToken() - return token !== null -} - -export function getCredentialsPath(): string { - return CREDENTIALS_FILE -} diff --git a/apps/cli/src/lib/storage/ephemeral.ts b/apps/cli/src/lib/storage/ephemeral.ts deleted file mode 100644 index 28984cfe587..00000000000 --- a/apps/cli/src/lib/storage/ephemeral.ts +++ /dev/null @@ -1,10 +0,0 @@ -import path from "path" -import os from "os" -import fs from "fs" - -export async function createEphemeralStorageDir(): Promise { - const uniqueId = `${Date.now()}-${Math.random().toString(36).slice(2, 11)}` - const tmpDir = path.join(os.tmpdir(), `roo-cli-${uniqueId}`) - await fs.promises.mkdir(tmpDir, { recursive: true }) - return tmpDir -} diff --git a/apps/cli/src/lib/storage/history.ts b/apps/cli/src/lib/storage/history.ts deleted file mode 100644 index f00a976b106..00000000000 --- a/apps/cli/src/lib/storage/history.ts +++ /dev/null @@ -1,109 +0,0 @@ -import * as fs from "fs/promises" -import * as path from "path" - -import { ensureConfigDir, getConfigDir } from "./config-dir.js" - -/** Maximum number of history entries to keep */ -export const MAX_HISTORY_ENTRIES = 500 - -/** History file format version for future migrations */ -const HISTORY_VERSION = 1 - -interface HistoryData { - version: number - entries: string[] -} - -/** - * Get the path to the history file - */ -export function getHistoryFilePath(): string { - return path.join(getConfigDir(), "cli-history.json") -} - -/** - * Load history entries from file - * Returns empty array if file doesn't exist or is invalid - */ -export async function loadHistory(): Promise { - const filePath = getHistoryFilePath() - - try { - const content = await fs.readFile(filePath, "utf-8") - const data: HistoryData = JSON.parse(content) - - // Validate structure - if (!data || typeof data !== "object") { - return [] - } - - if (!Array.isArray(data.entries)) { - return [] - } - - // Filter to only valid strings - return data.entries.filter((entry): entry is string => typeof entry === "string" && entry.trim().length > 0) - } catch (err) { - const error = err as NodeJS.ErrnoException - // File doesn't exist - that's expected on first run - if (error.code === "ENOENT") { - return [] - } - - // JSON parse error or other issue - log and return empty - console.error("Warning: Could not load CLI history:", error.message) - return [] - } -} - -/** - * Save history entries to file - * Creates the .roo directory if needed - * Trims to MAX_HISTORY_ENTRIES - */ -export async function saveHistory(entries: string[]): Promise { - const filePath = getHistoryFilePath() - - // Trim to max entries (keep most recent) - const trimmedEntries = entries.slice(-MAX_HISTORY_ENTRIES) - - const data: HistoryData = { - version: HISTORY_VERSION, - entries: trimmedEntries, - } - - try { - await ensureConfigDir() - await fs.writeFile(filePath, JSON.stringify(data, null, "\t"), "utf-8") - } catch (err) { - const error = err as NodeJS.ErrnoException - // Log but don't throw - history persistence is not critical - console.error("Warning: Could not save CLI history:", error.message) - } -} - -/** - * Add a new entry to history and save - * Avoids adding consecutive duplicates or empty entries - * Returns the updated history array - */ -export async function addToHistory(entry: string): Promise { - const trimmed = entry.trim() - - // Don't add empty entries - if (!trimmed) { - return await loadHistory() - } - - const history = await loadHistory() - - // Don't add consecutive duplicates - if (history.length > 0 && history[history.length - 1] === trimmed) { - return history - } - - const updated = [...history, trimmed] - await saveHistory(updated) - - return updated.slice(-MAX_HISTORY_ENTRIES) -} diff --git a/apps/cli/src/lib/storage/index.ts b/apps/cli/src/lib/storage/index.ts deleted file mode 100644 index 53424472c2a..00000000000 --- a/apps/cli/src/lib/storage/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * from "./config-dir.js" -export * from "./settings.js" -export * from "./credentials.js" -export * from "./ephemeral.js" diff --git a/apps/cli/src/lib/storage/settings.ts b/apps/cli/src/lib/storage/settings.ts deleted file mode 100644 index 86a2d9243e5..00000000000 --- a/apps/cli/src/lib/storage/settings.ts +++ /dev/null @@ -1,40 +0,0 @@ -import fs from "fs/promises" -import path from "path" - -import type { CliSettings } from "@/types/index.js" - -import { getConfigDir } from "./index.js" - -export function getSettingsPath(): string { - return path.join(getConfigDir(), "cli-settings.json") -} - -export async function loadSettings(): Promise { - try { - const settingsPath = getSettingsPath() - const data = await fs.readFile(settingsPath, "utf-8") - return JSON.parse(data) as CliSettings - } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") { - return {} - } - - throw error - } -} - -export async function saveSettings(settings: Partial): Promise { - const configDir = getConfigDir() - await fs.mkdir(configDir, { recursive: true }) - - const existing = await loadSettings() - const merged = { ...existing, ...settings } - - await fs.writeFile(getSettingsPath(), JSON.stringify(merged, null, 2), { - mode: 0o600, - }) -} - -export async function resetOnboarding(): Promise { - await saveSettings({ onboardingProviderChoice: undefined }) -} diff --git a/apps/cli/src/lib/utils/__tests__/commands.test.ts b/apps/cli/src/lib/utils/__tests__/commands.test.ts deleted file mode 100644 index ccae8401bda..00000000000 --- a/apps/cli/src/lib/utils/__tests__/commands.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { - type GlobalCommand, - type GlobalCommandAction, - GLOBAL_COMMANDS, - getGlobalCommand, - getGlobalCommandsForAutocomplete, -} from "../commands.js" - -describe("globalCommands", () => { - describe("GLOBAL_COMMANDS", () => { - it("should contain the /new command", () => { - const newCommand = GLOBAL_COMMANDS.find((cmd) => cmd.name === "new") - expect(newCommand).toBeDefined() - expect(newCommand?.action).toBe("clearTask") - expect(newCommand?.description).toBe("Start a new task") - }) - - it("should have valid structure for all commands", () => { - for (const cmd of GLOBAL_COMMANDS) { - expect(cmd.name).toBeTruthy() - expect(typeof cmd.name).toBe("string") - expect(cmd.description).toBeTruthy() - expect(typeof cmd.description).toBe("string") - expect(cmd.action).toBeTruthy() - expect(typeof cmd.action).toBe("string") - } - }) - }) - - describe("getGlobalCommand", () => { - it("should return the command when found", () => { - const cmd = getGlobalCommand("new") - expect(cmd).toBeDefined() - expect(cmd?.name).toBe("new") - expect(cmd?.action).toBe("clearTask") - }) - - it("should return undefined for unknown commands", () => { - const cmd = getGlobalCommand("unknown-command") - expect(cmd).toBeUndefined() - }) - - it("should be case-sensitive", () => { - const cmd = getGlobalCommand("NEW") - expect(cmd).toBeUndefined() - }) - }) - - describe("getGlobalCommandsForAutocomplete", () => { - it("should return commands in autocomplete format", () => { - const commands = getGlobalCommandsForAutocomplete() - expect(commands.length).toBe(GLOBAL_COMMANDS.length) - - for (const cmd of commands) { - expect(cmd.name).toBeTruthy() - expect(cmd.source).toBe("global") - expect(cmd.action).toBeTruthy() - } - }) - - it("should include the /new command with correct format", () => { - const commands = getGlobalCommandsForAutocomplete() - const newCommand = commands.find((cmd) => cmd.name === "new") - - expect(newCommand).toBeDefined() - expect(newCommand?.description).toBe("Start a new task") - expect(newCommand?.source).toBe("global") - expect(newCommand?.action).toBe("clearTask") - }) - - it("should not include argumentHint for action commands", () => { - const commands = getGlobalCommandsForAutocomplete() - // Action commands don't have argument hints - for (const cmd of commands) { - expect(cmd).not.toHaveProperty("argumentHint") - } - }) - }) - - describe("type safety", () => { - it("should have valid GlobalCommandAction types", () => { - // This test ensures the type is properly constrained - const validActions: GlobalCommandAction[] = ["clearTask"] - - for (const cmd of GLOBAL_COMMANDS) { - expect(validActions).toContain(cmd.action) - } - }) - - it("should match GlobalCommand interface", () => { - const testCommand: GlobalCommand = { - name: "test", - description: "Test command", - action: "clearTask", - } - - expect(testCommand.name).toBe("test") - expect(testCommand.description).toBe("Test command") - expect(testCommand.action).toBe("clearTask") - }) - }) -}) diff --git a/apps/cli/src/lib/utils/__tests__/extension.test.ts b/apps/cli/src/lib/utils/__tests__/extension.test.ts deleted file mode 100644 index 31fdbe87f00..00000000000 --- a/apps/cli/src/lib/utils/__tests__/extension.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import fs from "fs" -import path from "path" - -import { getDefaultExtensionPath } from "../extension.js" - -vi.mock("fs") - -describe("getDefaultExtensionPath", () => { - const originalEnv = process.env - - beforeEach(() => { - vi.resetAllMocks() - // Reset process.env to avoid ROO_EXTENSION_PATH from installed CLI affecting tests. - process.env = { ...originalEnv } - delete process.env.ROO_EXTENSION_PATH - }) - - afterEach(() => { - process.env = originalEnv - }) - - it("should return monorepo path when extension.js exists there", () => { - const mockDirname = "/test/apps/cli/dist" - const expectedMonorepoPath = path.resolve(mockDirname, "../../../src/dist") - - vi.mocked(fs.existsSync).mockReturnValue(true) - - const result = getDefaultExtensionPath(mockDirname) - - expect(result).toBe(expectedMonorepoPath) - expect(fs.existsSync).toHaveBeenCalledWith(path.join(expectedMonorepoPath, "extension.js")) - }) - - it("should return package path when extension.js does not exist in monorepo path", () => { - const mockDirname = "/test/apps/cli/dist" - const expectedPackagePath = path.resolve(mockDirname, "../extension") - - vi.mocked(fs.existsSync).mockReturnValue(false) - - const result = getDefaultExtensionPath(mockDirname) - - expect(result).toBe(expectedPackagePath) - }) - - it("should check monorepo path first", () => { - const mockDirname = "/some/path" - vi.mocked(fs.existsSync).mockReturnValue(false) - - getDefaultExtensionPath(mockDirname) - - const expectedMonorepoPath = path.resolve(mockDirname, "../../../src/dist") - expect(fs.existsSync).toHaveBeenCalledWith(path.join(expectedMonorepoPath, "extension.js")) - }) -}) diff --git a/apps/cli/src/lib/utils/__tests__/input.test.ts b/apps/cli/src/lib/utils/__tests__/input.test.ts deleted file mode 100644 index c346e60d6d0..00000000000 --- a/apps/cli/src/lib/utils/__tests__/input.test.ts +++ /dev/null @@ -1,128 +0,0 @@ -import type { Key } from "ink" - -import { GLOBAL_INPUT_SEQUENCES, isGlobalInputSequence, matchesGlobalSequence } from "../input.js" - -function createKey(overrides: Partial = {}): Key { - return { - upArrow: false, - downArrow: false, - leftArrow: false, - rightArrow: false, - pageDown: false, - pageUp: false, - home: false, - end: false, - return: false, - escape: false, - ctrl: false, - shift: false, - tab: false, - backspace: false, - delete: false, - meta: false, - ...overrides, - } -} - -describe("globalInputSequences", () => { - describe("GLOBAL_INPUT_SEQUENCES registry", () => { - it("should have ctrl-c registered", () => { - const seq = GLOBAL_INPUT_SEQUENCES.find((s) => s.id === "ctrl-c") - expect(seq).toBeDefined() - expect(seq?.description).toContain("Exit") - }) - - it("should have ctrl-m registered", () => { - const seq = GLOBAL_INPUT_SEQUENCES.find((s) => s.id === "ctrl-m") - expect(seq).toBeDefined() - expect(seq?.description).toContain("mode") - }) - }) - - describe("isGlobalInputSequence", () => { - describe("Ctrl+C detection", () => { - it("should match standard Ctrl+C", () => { - const result = isGlobalInputSequence("c", createKey({ ctrl: true })) - expect(result).toBeDefined() - expect(result?.id).toBe("ctrl-c") - }) - - it("should not match plain 'c' key", () => { - const result = isGlobalInputSequence("c", createKey()) - expect(result).toBeUndefined() - }) - }) - - describe("Ctrl+M detection", () => { - it("should match standard Ctrl+M", () => { - const result = isGlobalInputSequence("m", createKey({ ctrl: true })) - expect(result).toBeDefined() - expect(result?.id).toBe("ctrl-m") - }) - - it("should match CSI u encoding for Ctrl+M", () => { - const result = isGlobalInputSequence("\x1b[109;5u", createKey()) - expect(result).toBeDefined() - expect(result?.id).toBe("ctrl-m") - }) - - it("should match input ending with CSI u sequence", () => { - const result = isGlobalInputSequence("[109;5u", createKey()) - expect(result).toBeDefined() - expect(result?.id).toBe("ctrl-m") - }) - - it("should not match plain 'm' key", () => { - const result = isGlobalInputSequence("m", createKey()) - expect(result).toBeUndefined() - }) - }) - - it("should return undefined for non-global sequences", () => { - const result = isGlobalInputSequence("a", createKey()) - expect(result).toBeUndefined() - }) - - it("should return undefined for regular text input", () => { - const result = isGlobalInputSequence("hello", createKey()) - expect(result).toBeUndefined() - }) - }) - - describe("matchesGlobalSequence", () => { - it("should return true for matching sequence ID", () => { - const result = matchesGlobalSequence("c", createKey({ ctrl: true }), "ctrl-c") - expect(result).toBe(true) - }) - - it("should return false for non-matching sequence ID", () => { - const result = matchesGlobalSequence("c", createKey({ ctrl: true }), "ctrl-m") - expect(result).toBe(false) - }) - - it("should return false for non-existent sequence ID", () => { - const result = matchesGlobalSequence("c", createKey({ ctrl: true }), "non-existent") - expect(result).toBe(false) - }) - - it("should match ctrl-m with CSI u encoding", () => { - const result = matchesGlobalSequence("\x1b[109;5u", createKey(), "ctrl-m") - expect(result).toBe(true) - }) - }) - - describe("extensibility", () => { - it("should have unique IDs for all sequences", () => { - const ids = GLOBAL_INPUT_SEQUENCES.map((s) => s.id) - const uniqueIds = new Set(ids) - expect(uniqueIds.size).toBe(ids.length) - }) - - it("should have descriptions for all sequences", () => { - for (const seq of GLOBAL_INPUT_SEQUENCES) { - expect(seq.description).toBeTruthy() - expect(seq.description.length).toBeGreaterThan(0) - } - }) - }) -}) diff --git a/apps/cli/src/lib/utils/__tests__/path.test.ts b/apps/cli/src/lib/utils/__tests__/path.test.ts deleted file mode 100644 index 69c79ca196f..00000000000 --- a/apps/cli/src/lib/utils/__tests__/path.test.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { normalizePath, arePathsEqual } from "../path.js" - -// Helper to create platform-specific expected paths -const expectedPath = (...segments: string[]) => { - // On Windows, path.normalize converts forward slashes to backslashes - // and paths like /Users become \Users (without a drive letter) - if (process.platform === "win32") { - return "\\" + segments.join("\\") - } - - return "/" + segments.join("/") -} - -describe("normalizePath", () => { - it("should remove trailing slashes", () => { - expect(normalizePath("/Users/test/project/")).toBe(expectedPath("Users", "test", "project")) - expect(normalizePath("/Users/test/project//")).toBe(expectedPath("Users", "test", "project")) - }) - - it("should handle paths without trailing slashes", () => { - expect(normalizePath("/Users/test/project")).toBe(expectedPath("Users", "test", "project")) - }) - - it("should normalize path separators", () => { - // path.normalize handles this - expect(normalizePath("/Users//test/project")).toBe(expectedPath("Users", "test", "project")) - }) -}) - -describe("arePathsEqual", () => { - it("should return true for identical paths", () => { - expect(arePathsEqual("/Users/test/project", "/Users/test/project")).toBe(true) - }) - - it("should return true for paths differing only by trailing slash", () => { - expect(arePathsEqual("/Users/test/project", "/Users/test/project/")).toBe(true) - expect(arePathsEqual("/Users/test/project/", "/Users/test/project")).toBe(true) - }) - - it("should return false for undefined or empty paths", () => { - expect(arePathsEqual(undefined, "/Users/test/project")).toBe(false) - expect(arePathsEqual("/Users/test/project", undefined)).toBe(false) - expect(arePathsEqual(undefined, undefined)).toBe(false) - expect(arePathsEqual("", "/Users/test/project")).toBe(false) - expect(arePathsEqual("/Users/test/project", "")).toBe(false) - }) - - it("should return false for different paths", () => { - expect(arePathsEqual("/Users/test/project1", "/Users/test/project2")).toBe(false) - expect(arePathsEqual("/Users/test/project", "/Users/other/project")).toBe(false) - }) - - // Case sensitivity behavior depends on platform - if (process.platform === "darwin" || process.platform === "win32") { - it("should be case-insensitive on macOS/Windows", () => { - expect(arePathsEqual("/Users/Test/Project", "/users/test/project")).toBe(true) - expect(arePathsEqual("/USERS/TEST/PROJECT", "/Users/test/project")).toBe(true) - }) - } else { - it("should be case-sensitive on Linux", () => { - expect(arePathsEqual("/Users/Test/Project", "/users/test/project")).toBe(false) - }) - } - - it("should handle paths with multiple trailing slashes", () => { - expect(arePathsEqual("/Users/test/project///", "/Users/test/project")).toBe(true) - }) -}) diff --git a/apps/cli/src/lib/utils/__tests__/provider.test.ts b/apps/cli/src/lib/utils/__tests__/provider.test.ts deleted file mode 100644 index 70d8a2a5557..00000000000 --- a/apps/cli/src/lib/utils/__tests__/provider.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { getApiKeyFromEnv } from "../provider.js" - -describe("getApiKeyFromEnv", () => { - const originalEnv = process.env - - beforeEach(() => { - // Reset process.env before each test. - process.env = { ...originalEnv } - }) - - afterEach(() => { - process.env = originalEnv - }) - - it("should return API key from environment variable for anthropic", () => { - process.env.ANTHROPIC_API_KEY = "test-anthropic-key" - expect(getApiKeyFromEnv("anthropic")).toBe("test-anthropic-key") - }) - - it("should return API key from environment variable for openrouter", () => { - process.env.OPENROUTER_API_KEY = "test-openrouter-key" - expect(getApiKeyFromEnv("openrouter")).toBe("test-openrouter-key") - }) - - it("should return API key from environment variable for openai", () => { - process.env.OPENAI_API_KEY = "test-openai-key" - expect(getApiKeyFromEnv("openai-native")).toBe("test-openai-key") - }) - - it("should return undefined when API key is not set", () => { - delete process.env.ANTHROPIC_API_KEY - expect(getApiKeyFromEnv("anthropic")).toBeUndefined() - }) -}) diff --git a/apps/cli/src/lib/utils/commands.ts b/apps/cli/src/lib/utils/commands.ts deleted file mode 100644 index 32459e0a2a4..00000000000 --- a/apps/cli/src/lib/utils/commands.ts +++ /dev/null @@ -1,62 +0,0 @@ -/** - * CLI-specific global slash commands - * - * These commands are handled entirely within the CLI and trigger actions - * by sending messages to the extension host. They are separate from the - * extension's built-in commands which expand into prompt content. - */ - -/** - * Action types that can be triggered by global commands. - * Each action corresponds to a message type sent to the extension host. - */ -export type GlobalCommandAction = "clearTask" - -/** - * Definition of a CLI global command - */ -export interface GlobalCommand { - /** Command name (without the leading /) */ - name: string - /** Description shown in the autocomplete picker */ - description: string - /** Action to trigger when the command is executed */ - action: GlobalCommandAction -} - -/** - * CLI-specific global slash commands - * These commands trigger actions rather than expanding into prompt content. - */ -export const GLOBAL_COMMANDS: GlobalCommand[] = [ - { - name: "new", - description: "Start a new task", - action: "clearTask", - }, -] - -/** - * Get a global command by name - */ -export function getGlobalCommand(name: string): GlobalCommand | undefined { - return GLOBAL_COMMANDS.find((cmd) => cmd.name === name) -} - -/** - * Get global commands formatted for autocomplete - * Returns commands in the SlashCommandResult format expected by the autocomplete trigger - */ -export function getGlobalCommandsForAutocomplete(): Array<{ - name: string - description?: string - source: "global" | "project" | "built-in" - action?: string -}> { - return GLOBAL_COMMANDS.map((cmd) => ({ - name: cmd.name, - description: cmd.description, - source: "global" as const, - action: cmd.action, - })) -} diff --git a/apps/cli/src/lib/utils/context-window.ts b/apps/cli/src/lib/utils/context-window.ts deleted file mode 100644 index c1224c8b1ec..00000000000 --- a/apps/cli/src/lib/utils/context-window.ts +++ /dev/null @@ -1,67 +0,0 @@ -import type { ProviderSettings } from "@roo-code/types" - -import type { RouterModels } from "@/ui/store.js" - -const DEFAULT_CONTEXT_WINDOW = 200_000 - -/** - * Looks up the context window size for the current model from routerModels. - * - * @param routerModels - The router models data containing model info per provider - * @param apiConfiguration - The current API configuration with provider and model ID - * @returns The context window size, or DEFAULT_CONTEXT_WINDOW (200K) if not found - */ -export function getContextWindow(routerModels: RouterModels | null, apiConfiguration: ProviderSettings | null): number { - if (!routerModels || !apiConfiguration) { - return DEFAULT_CONTEXT_WINDOW - } - - const provider = apiConfiguration.apiProvider - const modelId = getModelIdForProvider(apiConfiguration) - - if (!provider || !modelId) { - return DEFAULT_CONTEXT_WINDOW - } - - const providerModels = routerModels[provider] - const modelInfo = providerModels?.[modelId] - - return modelInfo?.contextWindow ?? DEFAULT_CONTEXT_WINDOW -} - -/** - * Gets the model ID from the API configuration based on the provider type. - * - * Different providers store their model ID in different fields of ProviderSettings. - */ -function getModelIdForProvider(config: ProviderSettings): string | undefined { - switch (config.apiProvider) { - case "openrouter": - return config.openRouterModelId - case "ollama": - return config.ollamaModelId - case "lmstudio": - return config.lmStudioModelId - case "openai": - return config.openAiModelId - case "requesty": - return config.requestyModelId - case "litellm": - return config.litellmModelId - case "deepinfra": - return config.deepInfraModelId - case "huggingface": - return config.huggingFaceModelId - case "unbound": - return config.unboundModelId - case "vercel-ai-gateway": - return config.vercelAiGatewayModelId - case "io-intelligence": - return config.ioIntelligenceModelId - default: - // For anthropic, bedrock, vertex, gemini, xai, groq, etc. - return config.apiModelId - } -} - -export { DEFAULT_CONTEXT_WINDOW } diff --git a/apps/cli/src/lib/utils/extension.ts b/apps/cli/src/lib/utils/extension.ts deleted file mode 100644 index 904940ec004..00000000000 --- a/apps/cli/src/lib/utils/extension.ts +++ /dev/null @@ -1,33 +0,0 @@ -import path from "path" -import fs from "fs" - -/** - * Get the default path to the extension bundle. - * This assumes the CLI is installed alongside the built extension. - * - * @param dirname - The __dirname equivalent for the calling module - */ -export function getDefaultExtensionPath(dirname: string): string { - // Check for environment variable first (set by install script) - if (process.env.ROO_EXTENSION_PATH) { - const envPath = process.env.ROO_EXTENSION_PATH - - if (fs.existsSync(path.join(envPath, "extension.js"))) { - return envPath - } - } - - // __dirname is apps/cli/dist when bundled - // The extension is at src/dist (relative to monorepo root) - // So from apps/cli/dist, we need to go ../../../src/dist - const monorepoPath = path.resolve(dirname, "../../../src/dist") - - // Try monorepo path first (for development) - if (fs.existsSync(path.join(monorepoPath, "extension.js"))) { - return monorepoPath - } - - // Fallback: when installed via curl script, extension is at ../extension - const packagePath = path.resolve(dirname, "../extension") - return packagePath -} diff --git a/apps/cli/src/lib/utils/input.ts b/apps/cli/src/lib/utils/input.ts deleted file mode 100644 index 792f38ee59d..00000000000 --- a/apps/cli/src/lib/utils/input.ts +++ /dev/null @@ -1,122 +0,0 @@ -/** - * Global Input Sequences Registry - * - * This module centralizes the definition of input sequences that should be - * handled at the App level (or other top-level components) and ignored by - * child components like MultilineTextInput. - * - * When adding new global shortcuts: - * 1. Add the sequence definition to GLOBAL_INPUT_SEQUENCES - * 2. The App.tsx useInput handler should check for and handle the sequence - * 3. Child components automatically ignore these via isGlobalInputSequence() - */ - -import type { Key } from "ink" - -/** - * Definition of a global input sequence - */ -export interface GlobalInputSequence { - /** Unique identifier for the sequence */ - id: string - /** Human-readable description */ - description: string - /** - * Matcher function - returns true if the input matches this sequence. - * @param input - The raw input string from useInput - * @param key - The parsed key object from useInput - */ - matches: (input: string, key: Key) => boolean -} - -/** - * Registry of all global input sequences that should be handled at the App level - * and ignored by child components (like MultilineTextInput). - * - * Add new global shortcuts here to ensure they're properly handled throughout - * the application. - */ -export const GLOBAL_INPUT_SEQUENCES: GlobalInputSequence[] = [ - { - id: "ctrl-c", - description: "Exit application (with confirmation)", - matches: (input, key) => key.ctrl && input === "c", - }, - { - id: "ctrl-m", - description: "Cycle through modes", - matches: (input, key) => { - // Standard Ctrl+M detection - if (key.ctrl && input === "m") return true - // CSI u encoding: ESC [ 109 ; 5 u (kitty keyboard protocol) - // 109 = 'm' ASCII code, 5 = Ctrl modifier - if (input === "\x1b[109;5u") return true - if (input.endsWith("[109;5u")) return true - return false - }, - }, - { - id: "ctrl-t", - description: "Toggle TODO list viewer", - matches: (input, key) => { - // Standard Ctrl+T detection - if (key.ctrl && input === "t") return true - // CSI u encoding: ESC [ 116 ; 5 u (kitty keyboard protocol) - // 116 = 't' ASCII code, 5 = Ctrl modifier - if (input === "\x1b[116;5u") return true - if (input.endsWith("[116;5u")) return true - return false - }, - }, - // Add more global sequences here as needed: - // { - // id: "ctrl-n", - // description: "New task", - // matches: (input, key) => key.ctrl && input === "n", - // }, -] - -/** - * Check if an input matches any global input sequence. - * - * Use this in child components (like MultilineTextInput) to determine - * if input should be ignored because it will be handled by a parent component. - * - * @param input - The raw input string from useInput - * @param key - The parsed key object from useInput - * @returns The matching GlobalInputSequence, or undefined if no match - * - * @example - * ```tsx - * useInput((input, key) => { - * // Ignore inputs handled at App level - * if (isGlobalInputSequence(input, key)) { - * return - * } - * // Handle component-specific input... - * }) - * ``` - */ -export function isGlobalInputSequence(input: string, key: Key): GlobalInputSequence | undefined { - return GLOBAL_INPUT_SEQUENCES.find((seq) => seq.matches(input, key)) -} - -/** - * Check if an input matches a specific global input sequence by ID. - * - * @param input - The raw input string from useInput - * @param key - The parsed key object from useInput - * @param id - The sequence ID to check for - * @returns true if the input matches the specified sequence - * - * @example - * ```tsx - * if (matchesGlobalSequence(input, key, "ctrl-m")) { - * // Handle mode cycling - * } - * ``` - */ -export function matchesGlobalSequence(input: string, key: Key, id: string): boolean { - const seq = GLOBAL_INPUT_SEQUENCES.find((s) => s.id === id) - return seq ? seq.matches(input, key) : false -} diff --git a/apps/cli/src/lib/utils/onboarding.ts b/apps/cli/src/lib/utils/onboarding.ts deleted file mode 100644 index 176bc6a3441..00000000000 --- a/apps/cli/src/lib/utils/onboarding.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { createElement } from "react" - -import { type OnboardingResult, OnboardingProviderChoice } from "@/types/index.js" -import { login } from "@/commands/index.js" -import { saveSettings } from "@/lib/storage/index.js" - -export async function runOnboarding(): Promise { - const { render } = await import("ink") - const { OnboardingScreen } = await import("../../ui/components/onboarding/index.js") - - return new Promise((resolve) => { - const onSelect = async (choice: OnboardingProviderChoice) => { - await saveSettings({ onboardingProviderChoice: choice }) - - app.unmount() - - console.log("") - - if (choice === OnboardingProviderChoice.Roo) { - const { success: authenticated } = await login() - await saveSettings({ onboardingProviderChoice: choice }) - resolve({ choice: OnboardingProviderChoice.Roo, authenticated, skipped: false }) - } else { - console.log("Using your own API key.") - console.log("Set your API key via --api-key or environment variable.") - console.log("") - resolve({ choice: OnboardingProviderChoice.Byok, skipped: false }) - } - } - - const app = render(createElement(OnboardingScreen, { onSelect })) - }) -} diff --git a/apps/cli/src/lib/utils/path.ts b/apps/cli/src/lib/utils/path.ts deleted file mode 100644 index ccaecd80819..00000000000 --- a/apps/cli/src/lib/utils/path.ts +++ /dev/null @@ -1,35 +0,0 @@ -import * as path from "path" - -/** - * Normalize a path by removing trailing slashes and converting separators. - * This handles cross-platform path comparison issues. - */ -export function normalizePath(p: string): string { - // Remove trailing slashes - let normalized = p.replace(/[/\\]+$/, "") - // Convert to consistent separators using path.normalize - normalized = path.normalize(normalized) - return normalized -} - -/** - * Compare two paths for equality, handling: - * - Trailing slashes - * - Path separator differences - * - Case sensitivity (case-insensitive on Windows/macOS) - */ -export function arePathsEqual(path1?: string, path2?: string): boolean { - if (!path1 || !path2) { - return false - } - - const normalizedPath1 = normalizePath(path1) - const normalizedPath2 = normalizePath(path2) - - // On Windows and macOS, file paths are case-insensitive - if (process.platform === "win32" || process.platform === "darwin") { - return normalizedPath1.toLowerCase() === normalizedPath2.toLowerCase() - } - - return normalizedPath1 === normalizedPath2 -} diff --git a/apps/cli/src/lib/utils/provider.ts b/apps/cli/src/lib/utils/provider.ts deleted file mode 100644 index 64aec430c1b..00000000000 --- a/apps/cli/src/lib/utils/provider.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { RooCodeSettings } from "@roo-code/types" - -import type { SupportedProvider } from "@/types/index.js" - -const envVarMap: Record = { - anthropic: "ANTHROPIC_API_KEY", - "openai-native": "OPENAI_API_KEY", - gemini: "GOOGLE_API_KEY", - openrouter: "OPENROUTER_API_KEY", - "vercel-ai-gateway": "VERCEL_AI_GATEWAY_API_KEY", - roo: "ROO_API_KEY", -} - -export function getEnvVarName(provider: SupportedProvider): string { - return envVarMap[provider] -} - -export function getApiKeyFromEnv(provider: SupportedProvider): string | undefined { - const envVar = getEnvVarName(provider) - return process.env[envVar] -} - -export function getProviderSettings( - provider: SupportedProvider, - apiKey: string | undefined, - model: string | undefined, -): RooCodeSettings { - const config: RooCodeSettings = { apiProvider: provider } - - switch (provider) { - case "anthropic": - if (apiKey) config.apiKey = apiKey - if (model) config.apiModelId = model - break - case "openai-native": - if (apiKey) config.openAiNativeApiKey = apiKey - if (model) config.apiModelId = model - break - case "gemini": - if (apiKey) config.geminiApiKey = apiKey - if (model) config.apiModelId = model - break - case "openrouter": - if (apiKey) config.openRouterApiKey = apiKey - if (model) config.openRouterModelId = model - break - case "vercel-ai-gateway": - if (apiKey) config.vercelAiGatewayApiKey = apiKey - if (model) config.vercelAiGatewayModelId = model - break - case "roo": - if (apiKey) config.rooApiKey = apiKey - if (model) config.apiModelId = model - break - default: - if (apiKey) config.apiKey = apiKey - if (model) config.apiModelId = model - } - - return config -} diff --git a/apps/cli/src/lib/utils/version.ts b/apps/cli/src/lib/utils/version.ts deleted file mode 100644 index e4f2ce59b21..00000000000 --- a/apps/cli/src/lib/utils/version.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { createRequire } from "module" - -const require = createRequire(import.meta.url) -const packageJson = require("../package.json") - -export const VERSION = packageJson.version diff --git a/apps/cli/src/types/constants.ts b/apps/cli/src/types/constants.ts deleted file mode 100644 index 5b3dc577786..00000000000 --- a/apps/cli/src/types/constants.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { reasoningEffortsExtended } from "@roo-code/types" - -export const DEFAULT_FLAGS = { - mode: "code", - reasoningEffort: "medium" as const, - model: "anthropic/claude-opus-4.5", -} - -export const REASONING_EFFORTS = [...reasoningEffortsExtended, "unspecified", "disabled"] - -/** - * Default timeout in seconds for auto-approving followup questions. - * Used in both the TUI (App.tsx) and the extension host (extension-host.ts). - */ -export const FOLLOWUP_TIMEOUT_SECONDS = 60 - -export const ASCII_ROO = ` _,' ___ - <__\\__/ \\ - \\_ / _\\ - \\,\\ / \\\\ - // \\\\ - ,/' \`\\_,` - -export const AUTH_BASE_URL = process.env.ROO_AUTH_BASE_URL ?? "https://app.roocode.com" - -export const SDK_BASE_URL = process.env.ROO_SDK_BASE_URL ?? "https://cloud-api.roocode.com" diff --git a/apps/cli/src/types/index.ts b/apps/cli/src/types/index.ts deleted file mode 100644 index 0ed3db23507..00000000000 --- a/apps/cli/src/types/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./types.js" -export * from "./constants.js" diff --git a/apps/cli/src/types/types.ts b/apps/cli/src/types/types.ts deleted file mode 100644 index cd64c9b1629..00000000000 --- a/apps/cli/src/types/types.ts +++ /dev/null @@ -1,49 +0,0 @@ -import type { ProviderName, ReasoningEffortExtended } from "@roo-code/types" - -export const supportedProviders = [ - "anthropic", - "openai-native", - "gemini", - "openrouter", - "vercel-ai-gateway", - "roo", -] as const satisfies ProviderName[] - -export type SupportedProvider = (typeof supportedProviders)[number] - -export function isSupportedProvider(provider: string): provider is SupportedProvider { - return supportedProviders.includes(provider as SupportedProvider) -} - -export type ReasoningEffortFlagOptions = ReasoningEffortExtended | "unspecified" | "disabled" - -export type FlagOptions = { - prompt?: string - extension?: string - debug: boolean - yes: boolean - apiKey?: string - provider: SupportedProvider - model?: string - mode?: string - reasoningEffort?: ReasoningEffortFlagOptions - exitOnComplete: boolean - waitOnComplete: boolean - ephemeral: boolean - tui: boolean -} - -export enum OnboardingProviderChoice { - Roo = "roo", - Byok = "byok", -} - -export interface OnboardingResult { - choice: OnboardingProviderChoice - authenticated?: boolean - skipped: boolean -} - -export interface CliSettings { - onboardingProviderChoice?: OnboardingProviderChoice -} diff --git a/apps/cli/src/ui/App.tsx b/apps/cli/src/ui/App.tsx deleted file mode 100644 index fdb8644f53b..00000000000 --- a/apps/cli/src/ui/App.tsx +++ /dev/null @@ -1,621 +0,0 @@ -import { Box, Text, useApp, useInput } from "ink" -import { Select } from "@inkjs/ui" -import { useState, useEffect, useCallback, useRef, useMemo } from "react" - -import { ExtensionHostInterface, ExtensionHostOptions } from "@/agent/index.js" - -import { getGlobalCommandsForAutocomplete } from "@/lib/utils/commands.js" -import { arePathsEqual } from "@/lib/utils/path.js" -import { getContextWindow } from "@/lib/utils/context-window.js" - -import * as theme from "./theme.js" -import { useCLIStore } from "./store.js" -import { useUIStateStore } from "./stores/uiStateStore.js" - -// Import extracted hooks. -import { - TerminalSizeProvider, - useTerminalSize, - useToast, - useExtensionHost, - useMessageHandlers, - useTaskSubmit, - useGlobalInput, - useFollowupCountdown, - useFocusManagement, - usePickerHandlers, -} from "./hooks/index.js" - -// Import extracted utilities. -import { getView } from "./utils/index.js" - -// Import components. -import Header from "./components/Header.js" -import ChatHistoryItem from "./components/ChatHistoryItem.js" -import LoadingText from "./components/LoadingText.js" -import ToastDisplay from "./components/ToastDisplay.js" -import TodoDisplay from "./components/TodoDisplay.js" -import { HorizontalLine } from "./components/HorizontalLine.js" -import { - type AutocompleteInputHandle, - type AutocompleteTrigger, - type FileResult, - type SlashCommandResult, - AutocompleteInput, - PickerSelect, - createFileTrigger, - createSlashCommandTrigger, - createModeTrigger, - createHelpTrigger, - createHistoryTrigger, - toFileResult, - toSlashCommandResult, - toModeResult, - toHistoryResult, -} from "./components/autocomplete/index.js" -import { ScrollArea, useScrollToBottom } from "./components/ScrollArea.js" -import ScrollIndicator from "./components/ScrollIndicator.js" - -const PICKER_HEIGHT = 10 - -export interface TUIAppProps extends ExtensionHostOptions { - initialPrompt: string - debug: boolean - exitOnComplete: boolean - version: string - createExtensionHost: (options: ExtensionHostOptions) => ExtensionHostInterface -} - -/** - * Inner App component that uses the terminal size context - */ -function AppInner({ - initialPrompt, - workspacePath, - extensionPath, - user, - provider, - apiKey, - model, - mode, - nonInteractive = false, - debug, - exitOnComplete, - reasoningEffort, - ephemeral, - version, - createExtensionHost, -}: TUIAppProps) { - const { exit } = useApp() - - const { - messages, - pendingAsk, - isLoading, - isComplete, - hasStartedTask: _hasStartedTask, - error, - fileSearchResults, - allSlashCommands, - availableModes, - taskHistory, - currentMode, - tokenUsage, - routerModels, - apiConfiguration, - currentTodos, - } = useCLIStore() - - // Access UI state from the UI store - const { - showExitHint, - countdownSeconds, - showCustomInput, - isTransitioningToCustomInput, - showTodoViewer, - pickerState, - setIsTransitioningToCustomInput, - } = useUIStateStore() - - // Compute context window from router models and API configuration - const contextWindow = useMemo(() => { - return getContextWindow(routerModels, apiConfiguration) - }, [routerModels, apiConfiguration]) - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const autocompleteRef = useRef>(null) - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const followupAutocompleteRef = useRef>(null) - - // Stable refs for autocomplete data - prevents useMemo from recreating triggers on every data change - const fileSearchResultsRef = useRef(fileSearchResults) - const allSlashCommandsRef = useRef(allSlashCommands) - const availableModesRef = useRef(availableModes) - const taskHistoryRef = useRef(taskHistory) - - // Keep refs in sync with current state - useEffect(() => { - fileSearchResultsRef.current = fileSearchResults - }, [fileSearchResults]) - useEffect(() => { - allSlashCommandsRef.current = allSlashCommands - }, [allSlashCommands]) - useEffect(() => { - availableModesRef.current = availableModes - }, [availableModes]) - useEffect(() => { - taskHistoryRef.current = taskHistory - }, [taskHistory]) - - // Scroll area state - const { rows } = useTerminalSize() - const [scrollState, setScrollState] = useState({ scrollTop: 0, maxScroll: 0, isAtBottom: true }) - const { scrollToBottomTrigger, scrollToBottom } = useScrollToBottom() - - // RAF-style throttle refs for scroll updates (prevents multiple state updates per event loop tick). - const rafIdRef = useRef(null) - const pendingScrollRef = useRef<{ scrollTop: number; maxScroll: number; isAtBottom: boolean } | null>(null) - - // Toast notifications for ephemeral messages (e.g., mode changes). - const { currentToast, showInfo } = useToast() - - const { - handleExtensionMessage, - seenMessageIds, - pendingCommandRef: _pendingCommandRef, - firstTextMessageSkipped, - } = useMessageHandlers({ - nonInteractive, - }) - - const { sendToExtension, runTask, cleanup } = useExtensionHost({ - initialPrompt, - mode, - reasoningEffort, - user, - provider, - apiKey, - model, - workspacePath, - extensionPath, - debug, - nonInteractive, - ephemeral, - exitOnComplete, - onExtensionMessage: handleExtensionMessage, - createExtensionHost, - }) - - // Initialize task submit hook - const { handleSubmit, handleApprove, handleReject } = useTaskSubmit({ - sendToExtension, - runTask, - seenMessageIds, - firstTextMessageSkipped, - }) - - // Initialize focus management hook - const { canToggleFocus, isScrollAreaActive, isInputAreaActive, toggleFocus } = useFocusManagement({ - showApprovalPrompt: Boolean(pendingAsk && pendingAsk.type !== "followup"), - pendingAsk, - }) - - // Initialize countdown hook for followup auto-accept - const { cancelCountdown } = useFollowupCountdown({ - pendingAsk, - onAutoSubmit: handleSubmit, - }) - - // Initialize picker handlers hook - const { handlePickerStateChange, handlePickerSelect, handlePickerClose, handlePickerIndexChange } = - usePickerHandlers({ - autocompleteRef, - followupAutocompleteRef, - sendToExtension, - showInfo, - seenMessageIds, - firstTextMessageSkipped, - }) - - // Initialize global input hook - useGlobalInput({ - canToggleFocus, - isScrollAreaActive, - pickerIsOpen: pickerState.isOpen, - availableModes, - currentMode, - mode, - sendToExtension, - showInfo, - exit, - cleanup, - toggleFocus, - closePicker: handlePickerClose, - }) - - // Determine current view - const view = getView(messages, pendingAsk, isLoading) - - // Determine if we should show the approval prompt (Y/N) instead of text input - const showApprovalPrompt = pendingAsk && pendingAsk.type !== "followup" - - // Display all messages including partial (streaming) ones - const displayMessages = useMemo(() => { - return messages - }, [messages]) - - // Scroll to bottom when new messages arrive (if auto-scroll is enabled) - const prevMessageCount = useRef(messages.length) - useEffect(() => { - if (messages.length > prevMessageCount.current && scrollState.isAtBottom) { - scrollToBottom() - } - prevMessageCount.current = messages.length - }, [messages.length, scrollState.isAtBottom, scrollToBottom]) - - // Handle scroll state changes from ScrollArea (RAF-throttled to coalesce rapid updates) - const handleScroll = useCallback((scrollTop: number, maxScroll: number, isAtBottom: boolean) => { - // Store the latest scroll values in ref - pendingScrollRef.current = { scrollTop, maxScroll, isAtBottom } - - // Only schedule one update per event loop tick - if (rafIdRef.current === null) { - rafIdRef.current = setImmediate(() => { - rafIdRef.current = null - const pending = pendingScrollRef.current - if (pending) { - setScrollState(pending) - pendingScrollRef.current = null - } - }) - } - }, []) - - // Cleanup RAF-style timer on unmount - useEffect(() => { - return () => { - if (rafIdRef.current !== null) { - clearImmediate(rafIdRef.current) - } - } - }, []) - - // File search handler for the file trigger - const handleFileSearch = useCallback( - (query: string) => { - if (!sendToExtension) { - return - } - sendToExtension({ type: "searchFiles", query }) - }, - [sendToExtension], - ) - - // Create autocomplete triggers - // Using 'any' to allow mixing different trigger types (FileResult, SlashCommandResult, ModeResult, HelpShortcutResult, HistoryResult) - // IMPORTANT: We use refs here to avoid recreating triggers every time data changes. - // This prevents the UI flash caused by: data change -> memo recreation -> re-render with stale state - // The getResults/getCommands/getModes/getHistory callbacks always read from refs to get fresh data. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const autocompleteTriggers = useMemo((): AutocompleteTrigger[] => { - const fileTrigger = createFileTrigger({ - onSearch: handleFileSearch, - getResults: () => { - const results = fileSearchResultsRef.current - return results.map(toFileResult) - }, - }) - - const slashCommandTrigger = createSlashCommandTrigger({ - getCommands: () => { - // Merge CLI global commands with extension commands - const extensionCommands = allSlashCommandsRef.current.map(toSlashCommandResult) - const globalCommands = getGlobalCommandsForAutocomplete().map(toSlashCommandResult) - // Global commands appear first, then extension commands - return [...globalCommands, ...extensionCommands] - }, - }) - - const modeTrigger = createModeTrigger({ - getModes: () => availableModesRef.current.map(toModeResult), - }) - - const helpTrigger = createHelpTrigger() - - // History trigger - type # to search and resume previous tasks - const historyTrigger = createHistoryTrigger({ - getHistory: () => { - // Filter to only show tasks for the current workspace - // Use arePathsEqual for proper cross-platform path comparison - // (handles trailing slashes, separators, and case sensitivity) - const history = taskHistoryRef.current - const filtered = history.filter((item) => arePathsEqual(item.workspace, workspacePath)) - return filtered.map(toHistoryResult) - }, - }) - - return [fileTrigger, slashCommandTrigger, modeTrigger, helpTrigger, historyTrigger] - }, [handleFileSearch, workspacePath]) // Only depend on handleFileSearch and workspacePath - data accessed via refs - - // Refresh search results when fileSearchResults changes while file picker is open - // This handles the async timing where API results arrive after initial search - // IMPORTANT: Only run when fileSearchResults array identity changes (new API response) - // We use a ref to track this and avoid depending on pickerState in the effect - const prevFileSearchResultsRef = useRef(fileSearchResults) - const pickerStateRef = useRef(pickerState) - pickerStateRef.current = pickerState - - useEffect(() => { - // Only run if fileSearchResults actually changed (different array reference) - if (fileSearchResults === prevFileSearchResultsRef.current) { - return - } - - const currentPickerState = pickerStateRef.current - const willRefresh = - currentPickerState.isOpen && currentPickerState.activeTrigger?.id === "file" && fileSearchResults.length > 0 - - prevFileSearchResultsRef.current = fileSearchResults - - // Only refresh when file picker is open and we have new results - if (willRefresh) { - autocompleteRef.current?.refreshSearch() - followupAutocompleteRef.current?.refreshSearch() - } - }, [fileSearchResults]) // Only depend on fileSearchResults - read pickerState from ref - - // Handle Y/N input for approval prompts - useInput((input) => { - if (pendingAsk && pendingAsk.type !== "followup") { - const lower = input.toLowerCase() - - if (lower === "y") { - handleApprove() - } else if (lower === "n") { - handleReject() - } - } - }) - - // Cancel countdown timer when user navigates in the followup suggestion menu - // This provides better UX - any user interaction cancels the auto-accept timer - const showFollowupSuggestions = - pendingAsk?.type === "followup" && - pendingAsk.suggestions && - pendingAsk.suggestions.length > 0 && - !showCustomInput - - useInput((_input, key) => { - // Only handle when followup suggestions are shown and countdown is active - if (showFollowupSuggestions && countdownSeconds !== null) { - // Cancel countdown on any arrow key navigation - if (key.upArrow || key.downArrow) { - cancelCountdown() - } - } - }) - - // Error display - if (error) { - return ( - - - Error: {error} - - - Press Ctrl+C to exit - - - ) - } - - // Status bar content - // Priority: Toast > Exit hint > Loading > Scroll indicator > Input hint - // Don't show spinner when waiting for user input (pendingAsk is set) - const statusBarMessage = currentToast ? ( - - ) : showExitHint ? ( - Press Ctrl+C again to exit - ) : isLoading && !pendingAsk ? ( - - {view === "ToolUse" ? "Using tool" : "Thinking"} - - Esc to cancel - {isScrollAreaActive && ( - <> - - - - )} - - ) : isScrollAreaActive ? ( - - ) : isInputAreaActive ? ( - ? for shortcuts - ) : null - - const getPickerRenderItem = () => { - if (pickerState.activeTrigger) { - return pickerState.activeTrigger.renderItem - } - - return (item: FileResult | SlashCommandResult, isSelected: boolean) => ( - - {item.key} - - ) - } - - return ( - - {/* Header - fixed size */} - -

- - - {/* Scrollable message history area - fills remaining space via flexGrow */} - - {displayMessages.map((message) => ( - - ))} - - - {/* Input area - with borders like Claude Code - fixed size */} - - {pendingAsk?.type === "followup" ? ( - - {pendingAsk.content} - {pendingAsk.suggestions && pendingAsk.suggestions.length > 0 && !showCustomInput ? ( - - - { - onSelect(value as OnboardingProviderChoice) - }} - /> - - ) -} diff --git a/apps/cli/src/ui/components/onboarding/index.ts b/apps/cli/src/ui/components/onboarding/index.ts deleted file mode 100644 index b88ef3ce444..00000000000 --- a/apps/cli/src/ui/components/onboarding/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./OnboardingScreen.js" diff --git a/apps/cli/src/ui/components/tools/BrowserTool.tsx b/apps/cli/src/ui/components/tools/BrowserTool.tsx deleted file mode 100644 index 5e6d51857ab..00000000000 --- a/apps/cli/src/ui/components/tools/BrowserTool.tsx +++ /dev/null @@ -1,87 +0,0 @@ -import { Box, Text } from "ink" - -import * as theme from "../../theme.js" -import { Icon } from "../Icon.js" - -import type { ToolRendererProps } from "./types.js" -import { getToolDisplayName, getToolIconName } from "./utils.js" - -const ACTION_LABELS: Record = { - launch: "Launch Browser", - click: "Click", - hover: "Hover", - type: "Type Text", - press: "Press Key", - scroll_down: "Scroll Down", - scroll_up: "Scroll Up", - resize: "Resize Window", - close: "Close Browser", - screenshot: "Take Screenshot", -} - -export function BrowserTool({ toolData }: ToolRendererProps) { - const iconName = getToolIconName(toolData.tool) - const displayName = getToolDisplayName(toolData.tool) - const action = toolData.action || "" - const url = toolData.url || "" - const coordinate = toolData.coordinate || "" - const content = toolData.content || "" // May contain text for type action. - - const actionLabel = ACTION_LABELS[action] || action - - return ( - - {/* Header */} - - - - {" "} - {displayName} - - {action && ( - - {" "} - → {actionLabel} - - )} - - - {/* Action details */} - - {/* URL for launch action */} - {url && ( - - url: - - {url} - - - )} - - {/* Coordinates for click/hover actions */} - {coordinate && ( - - at: - {coordinate} - - )} - - {/* Text content for type action */} - {content && action === "type" && ( - - text: - "{content}" - - )} - - {/* Key for press action */} - {content && action === "press" && ( - - key: - {content} - - )} - - - ) -} diff --git a/apps/cli/src/ui/components/tools/CommandTool.tsx b/apps/cli/src/ui/components/tools/CommandTool.tsx deleted file mode 100644 index 969836ce958..00000000000 --- a/apps/cli/src/ui/components/tools/CommandTool.tsx +++ /dev/null @@ -1,50 +0,0 @@ -import { Box, Text } from "ink" - -import * as theme from "../../theme.js" -import { Icon } from "../Icon.js" - -import type { ToolRendererProps } from "./types.js" -import { truncateText, sanitizeContent, getToolIconName } from "./utils.js" - -const MAX_OUTPUT_LINES = 10 - -export function CommandTool({ toolData }: ToolRendererProps) { - const iconName = getToolIconName(toolData.tool) - const command = toolData.command || "" - const output = toolData.output ? sanitizeContent(toolData.output) : "" - const content = toolData.content ? sanitizeContent(toolData.content) : "" - const displayOutput = output || content - const { text: previewOutput, truncated, hiddenLines } = truncateText(displayOutput, MAX_OUTPUT_LINES) - - return ( - - - - {command && ( - - $ - - {command} - - - )} - - {previewOutput && ( - - - {previewOutput.split("\n").map((line, i) => ( - - {line} - - ))} - - {truncated && ( - - ... ({hiddenLines} more lines) - - )} - - )} - - ) -} diff --git a/apps/cli/src/ui/components/tools/CompletionTool.tsx b/apps/cli/src/ui/components/tools/CompletionTool.tsx deleted file mode 100644 index cc648902acf..00000000000 --- a/apps/cli/src/ui/components/tools/CompletionTool.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import { Box, Text } from "ink" - -import * as theme from "../../theme.js" - -import type { ToolRendererProps } from "./types.js" -import { truncateText, sanitizeContent } from "./utils.js" - -const MAX_CONTENT_LINES = 15 - -export function CompletionTool({ toolData }: ToolRendererProps) { - const result = toolData.result ? sanitizeContent(toolData.result) : "" - const question = toolData.question ? sanitizeContent(toolData.question) : "" - const content = toolData.content ? sanitizeContent(toolData.content) : "" - const isQuestion = toolData.tool.includes("question") || toolData.tool.includes("Question") - const displayContent = result || question || content - const { text: previewContent, truncated, hiddenLines } = truncateText(displayContent, MAX_CONTENT_LINES) - - return previewContent ? ( - - {isQuestion ? ( - - {previewContent} - - ) : ( - - {previewContent.split("\n").map((line, i) => ( - - {line} - - ))} - - )} - {truncated && ( - - ... ({hiddenLines} more lines) - - )} - - ) : null -} diff --git a/apps/cli/src/ui/components/tools/FileReadTool.tsx b/apps/cli/src/ui/components/tools/FileReadTool.tsx deleted file mode 100644 index b61e443614f..00000000000 --- a/apps/cli/src/ui/components/tools/FileReadTool.tsx +++ /dev/null @@ -1,131 +0,0 @@ -import { Box, Text } from "ink" - -import * as theme from "../../theme.js" -import { Icon } from "../Icon.js" - -import type { ToolRendererProps } from "./types.js" -import { truncateText, sanitizeContent, getToolDisplayName, getToolIconName } from "./utils.js" - -const MAX_PREVIEW_LINES = 12 - -/** - * Check if content looks like actual file content vs just path info - * File content typically has newlines or is longer than a typical path - */ -function isActualContent(content: string, path: string): boolean { - if (!content) return false - // If content equals path or is just the path, it's not actual content - if (content === path || content.endsWith(path)) return false - // Check if it looks like a plain path (no newlines, starts with / or drive letter) - if (!content.includes("\n") && (content.startsWith("/") || /^[A-Z]:\\/.test(content))) return false - // Has newlines or doesn't look like a path - treat as content - return content.includes("\n") || content.length > 200 -} - -export function FileReadTool({ toolData }: ToolRendererProps) { - const iconName = getToolIconName(toolData.tool) - const displayName = getToolDisplayName(toolData.tool) - const path = toolData.path || "" - const rawContent = toolData.content ? sanitizeContent(toolData.content) : "" - const isOutsideWorkspace = toolData.isOutsideWorkspace - const isList = toolData.tool.includes("list") || toolData.tool.includes("List") - - // Only show content if it's actual file content, not just path info - const content = isActualContent(rawContent, path) ? rawContent : "" - - // Handle batch file reads - if (toolData.batchFiles && toolData.batchFiles.length > 0) { - return ( - - {/* Header */} - - - - {" "} - {displayName} - - ({toolData.batchFiles.length} files) - - - {/* File list */} - - {toolData.batchFiles.slice(0, 10).map((file, index) => ( - - - {file.path} - - {file.lineSnippet && ({file.lineSnippet})} - {file.isOutsideWorkspace && ( - - {" "} - ⚠ outside workspace - - )} - - ))} - {toolData.batchFiles.length > 10 && ( - ... and {toolData.batchFiles.length - 10} more files - )} - - - ) - } - - // Single file read - const { text: previewContent, truncated, hiddenLines } = truncateText(content, MAX_PREVIEW_LINES) - - return ( - - {/* Header with path on same line for single file */} - - - - {displayName} - - {path && ( - <> - · - - {path} - - {isOutsideWorkspace && ( - - {" "} - ⚠ outside workspace - - )} - - )} - - - {/* Content preview - only if we have actual file content */} - {previewContent && ( - - {isList ? ( - // Directory listing - show as tree-like structure - - {previewContent.split("\n").map((line, i) => ( - - {line} - - ))} - - ) : ( - // File content - show in a box - - - {previewContent} - - - )} - - {truncated && ( - - ... ({hiddenLines} more lines) - - )} - - )} - - ) -} diff --git a/apps/cli/src/ui/components/tools/FileWriteTool.tsx b/apps/cli/src/ui/components/tools/FileWriteTool.tsx deleted file mode 100644 index 0523f2f696a..00000000000 --- a/apps/cli/src/ui/components/tools/FileWriteTool.tsx +++ /dev/null @@ -1,165 +0,0 @@ -import { Box, Text } from "ink" - -import * as theme from "../../theme.js" -import { Icon } from "../Icon.js" - -import type { ToolRendererProps } from "./types.js" -import { truncateText, sanitizeContent, getToolDisplayName, getToolIconName, parseDiff } from "./utils.js" - -const MAX_DIFF_LINES = 15 - -export function FileWriteTool({ toolData }: ToolRendererProps) { - const iconName = getToolIconName(toolData.tool) - const displayName = getToolDisplayName(toolData.tool) - const path = toolData.path || "" - const diffStats = toolData.diffStats - const diff = toolData.diff ? sanitizeContent(toolData.diff) : "" - const isProtected = toolData.isProtected - const isOutsideWorkspace = toolData.isOutsideWorkspace - const isNewFile = toolData.tool === "newFileCreated" || toolData.tool === "write_to_file" - - // Handle batch diff operations - if (toolData.batchDiffs && toolData.batchDiffs.length > 0) { - return ( - - {/* Header */} - - - - {" "} - {displayName} - - ({toolData.batchDiffs.length} files) - - - {/* File list with stats */} - - {toolData.batchDiffs.slice(0, 8).map((file, index) => ( - - - {file.path} - - {file.diffStats && ( - - +{file.diffStats.added} - / - -{file.diffStats.removed} - - )} - - ))} - {toolData.batchDiffs.length > 8 && ( - ... and {toolData.batchDiffs.length - 8} more files - )} - - - ) - } - - // Single file write - const { text: previewDiff, truncated, hiddenLines } = truncateText(diff, MAX_DIFF_LINES) - const diffHunks = diff ? parseDiff(diff) : [] - - return ( - - {/* Header row with path on same line */} - - - - {displayName} - - {path && ( - <> - · - - {path} - - - )} - {isNewFile && ( - - {" "} - NEW - - )} - - {/* Diff stats badge */} - {diffStats && ( - <> - - - +{diffStats.added} - - / - - -{diffStats.removed} - - - )} - - {/* Warning badges */} - {isProtected && 🔒 protected} - {isOutsideWorkspace && ( - - {" "} - ⚠ outside workspace - - )} - - - {/* Diff preview */} - {diffHunks.length > 0 && ( - - {diffHunks.slice(0, 2).map((hunk, hunkIndex) => ( - - {/* Hunk header */} - - {hunk.header} - - - {/* Diff lines */} - {hunk.lines.slice(0, 8).map((line, lineIndex) => ( - - {line.type === "added" ? "+" : line.type === "removed" ? "-" : " "} - {line.content} - - ))} - - {hunk.lines.length > 8 && ( - - ... ({hunk.lines.length - 8} more lines in hunk) - - )} - - ))} - - {diffHunks.length > 2 && ( - - ... ({diffHunks.length - 2} more hunks) - - )} - - )} - - {/* Fallback to raw diff if no hunks parsed */} - {diffHunks.length === 0 && previewDiff && ( - - {previewDiff} - {truncated && ( - - ... ({hiddenLines} more lines) - - )} - - )} - - ) -} diff --git a/apps/cli/src/ui/components/tools/GenericTool.tsx b/apps/cli/src/ui/components/tools/GenericTool.tsx deleted file mode 100644 index 00f835d8ad2..00000000000 --- a/apps/cli/src/ui/components/tools/GenericTool.tsx +++ /dev/null @@ -1,93 +0,0 @@ -import { Box, Text } from "ink" - -import * as theme from "../../theme.js" -import { Icon } from "../Icon.js" - -import type { ToolRendererProps } from "./types.js" -import { truncateText, sanitizeContent, getToolDisplayName, getToolIconName } from "./utils.js" - -const MAX_CONTENT_LINES = 12 - -export function GenericTool({ toolData, rawContent }: ToolRendererProps) { - const iconName = getToolIconName(toolData.tool) - const displayName = getToolDisplayName(toolData.tool) - - // Gather all available information - const path = toolData.path - const content = toolData.content ? sanitizeContent(toolData.content) : "" - const reason = toolData.reason ? sanitizeContent(toolData.reason) : "" - const mode = toolData.mode - - // Build display content from available fields - let displayContent = content || reason || "" - - // If we have no structured content but have raw content, try to parse it - if (!displayContent && rawContent) { - try { - const parsed = JSON.parse(rawContent) - // Extract any content-like fields - displayContent = sanitizeContent(parsed.content || parsed.output || parsed.result || parsed.reason || "") - } catch { - // Use raw content as-is if not JSON - displayContent = sanitizeContent(rawContent) - } - } - - const { text: previewContent, truncated, hiddenLines } = truncateText(displayContent, MAX_CONTENT_LINES) - - return ( - - {/* Header */} - - - - {" "} - {displayName} - - - - {/* Path if present */} - {path && ( - - path: - - {path} - - {toolData.isOutsideWorkspace && ( - - {" "} - ⚠ outside workspace - - )} - {toolData.isProtected && 🔒 protected} - - )} - - {/* Mode if present */} - {mode && ( - - mode: - - {mode} - - - )} - - {/* Content */} - {previewContent && ( - - {previewContent.split("\n").map((line, i) => ( - - {line} - - ))} - {truncated && ( - - ... ({hiddenLines} more lines) - - )} - - )} - - ) -} diff --git a/apps/cli/src/ui/components/tools/ModeTool.tsx b/apps/cli/src/ui/components/tools/ModeTool.tsx deleted file mode 100644 index 8a7771a7ab4..00000000000 --- a/apps/cli/src/ui/components/tools/ModeTool.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import { Box, Text } from "ink" - -import * as theme from "../../theme.js" -import { Icon } from "../Icon.js" - -import type { ToolRendererProps } from "./types.js" -import { getToolIconName } from "./utils.js" - -export function ModeTool({ toolData }: ToolRendererProps) { - const iconName = getToolIconName(toolData.tool) - const mode = toolData.mode || "" - const isSwitch = toolData.tool.includes("switch") || toolData.tool.includes("Switch") - - return ( - - - {isSwitch && mode && ( - - Switching to - - {mode} - - mode - - )} - - ) -} diff --git a/apps/cli/src/ui/components/tools/SearchTool.tsx b/apps/cli/src/ui/components/tools/SearchTool.tsx deleted file mode 100644 index 4b55607a6f2..00000000000 --- a/apps/cli/src/ui/components/tools/SearchTool.tsx +++ /dev/null @@ -1,113 +0,0 @@ -import { Box, Text } from "ink" - -import * as theme from "../../theme.js" -import { Icon } from "../Icon.js" - -import type { ToolRendererProps } from "./types.js" -import { truncateText, sanitizeContent, getToolDisplayName, getToolIconName } from "./utils.js" - -const MAX_RESULT_LINES = 15 - -export function SearchTool({ toolData }: ToolRendererProps) { - const iconName = getToolIconName(toolData.tool) - const displayName = getToolDisplayName(toolData.tool) - const regex = toolData.regex || "" - const query = toolData.query || "" - const filePattern = toolData.filePattern || "" - const path = toolData.path || "" - const content = toolData.content ? sanitizeContent(toolData.content) : "" - - // Parse search results if content looks like results. - const resultLines = content.split("\n").filter((line) => line.trim()) - const matchCount = resultLines.length - - const { text: previewContent, truncated, hiddenLines } = truncateText(content, MAX_RESULT_LINES) - - return ( - - {/* Header */} - - - - {" "} - {displayName} - - {matchCount > 0 && ({matchCount} matches)} - - - {/* Search parameters */} - - {/* Regex/Query */} - {regex && ( - - regex: - - {regex} - - - )} - {query && ( - - query: - - {query} - - - )} - - {/* Search scope */} - - {path && ( - <> - path: - {path} - - )} - {filePattern && ( - <> - pattern: - {filePattern} - - )} - - - - {/* Results */} - {previewContent && ( - - - Results: - - - {previewContent.split("\n").map((line, i) => { - // Try to highlight file:line patterns - const match = line.match(/^([^:]+):(\d+):(.*)$/) - if (match) { - const [, file, lineNum, context] = match - return ( - - {file} - : - {lineNum} - : - {context} - - ) - } - return ( - - {line} - - ) - })} - - {truncated && ( - - ... ({hiddenLines} more results) - - )} - - )} - - ) -} diff --git a/apps/cli/src/ui/components/tools/__tests__/CommandTool.test.tsx b/apps/cli/src/ui/components/tools/__tests__/CommandTool.test.tsx deleted file mode 100644 index ea097e9ef1c..00000000000 --- a/apps/cli/src/ui/components/tools/__tests__/CommandTool.test.tsx +++ /dev/null @@ -1,164 +0,0 @@ -import { render } from "ink-testing-library" - -import type { ToolRendererProps } from "../types.js" -import { CommandTool } from "../CommandTool.js" - -describe("CommandTool", () => { - describe("command display", () => { - it("displays the command when toolData.command is provided", () => { - const props: ToolRendererProps = { - toolData: { - tool: "execute_command", - command: "npm test", - output: "All tests passed", - }, - } - - const { lastFrame } = render() - const output = lastFrame() - - // Command should be displayed with $ prefix - expect(output).toContain("$") - expect(output).toContain("npm test") - }) - - it("does not display command section when toolData.command is empty", () => { - const props: ToolRendererProps = { - toolData: { - tool: "execute_command", - command: "", - output: "All tests passed", - }, - } - - const { lastFrame } = render() - const output = lastFrame() - - // The output should be displayed but no command line with $ - expect(output).toContain("All tests passed") - // Should not have a standalone $ followed by a command - // (just checking the output is present without command) - }) - - it("does not display command section when toolData.command is undefined", () => { - const props: ToolRendererProps = { - toolData: { - tool: "execute_command", - output: "All tests passed", - }, - } - - const { lastFrame } = render() - const output = lastFrame() - - // The output should be displayed - expect(output).toContain("All tests passed") - }) - - it("displays command with complex arguments", () => { - const props: ToolRendererProps = { - toolData: { - tool: "execute_command", - command: 'git commit -m "fix: resolve issue"', - output: "[main abc123] fix: resolve issue", - }, - } - - const { lastFrame } = render() - const output = lastFrame() - - expect(output).toContain("$") - expect(output).toContain('git commit -m "fix: resolve issue"') - }) - }) - - describe("output display", () => { - it("displays output when provided", () => { - const props: ToolRendererProps = { - toolData: { - tool: "execute_command", - command: "echo hello", - output: "hello", - }, - } - - const { lastFrame } = render() - const output = lastFrame() - - expect(output).toContain("hello") - }) - - it("displays multi-line output", () => { - const props: ToolRendererProps = { - toolData: { - tool: "execute_command", - command: "ls", - output: "file1.txt\nfile2.txt\nfile3.txt", - }, - } - - const { lastFrame } = render() - const output = lastFrame() - - expect(output).toContain("file1.txt") - expect(output).toContain("file2.txt") - expect(output).toContain("file3.txt") - }) - - it("uses content as fallback when output is not provided", () => { - const props: ToolRendererProps = { - toolData: { - tool: "execute_command", - command: "ls", - content: "fallback content", - }, - } - - const { lastFrame } = render() - const output = lastFrame() - - expect(output).toContain("fallback content") - }) - - it("truncates output to MAX_OUTPUT_LINES", () => { - // Create output with more than 10 lines (MAX_OUTPUT_LINES = 10) - const longOutput = Array.from({ length: 20 }, (_, i) => `line ${i + 1}`).join("\n") - - const props: ToolRendererProps = { - toolData: { - tool: "execute_command", - command: "cat longfile.txt", - output: longOutput, - }, - } - - const { lastFrame } = render() - const output = lastFrame() - - // First 10 lines should be visible - expect(output).toContain("line 1") - expect(output).toContain("line 10") - - // Should show truncation indicator - expect(output).toContain("more lines") - }) - }) - - describe("header display", () => { - it("displays terminal icon when rendered", () => { - const props: ToolRendererProps = { - toolData: { - tool: "execute_command", - command: "echo test", - }, - } - - const { lastFrame } = render() - const output = lastFrame() - - // The terminal icon fallback is "$", which also appears before the command - expect(output).toContain("$") - expect(output).toContain("echo test") - }) - }) -}) diff --git a/apps/cli/src/ui/components/tools/index.ts b/apps/cli/src/ui/components/tools/index.ts deleted file mode 100644 index c6284320029..00000000000 --- a/apps/cli/src/ui/components/tools/index.ts +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Tool renderer components for CLI TUI - * - * Each tool type has a specialized renderer that optimizes the display - * of its unique data structure. - */ - -import type React from "react" - -import type { ToolRendererProps } from "./types.js" -import { getToolCategory } from "./types.js" - -// Import all renderers -import { FileReadTool } from "./FileReadTool.js" -import { FileWriteTool } from "./FileWriteTool.js" -import { SearchTool } from "./SearchTool.js" -import { CommandTool } from "./CommandTool.js" -import { BrowserTool } from "./BrowserTool.js" -import { ModeTool } from "./ModeTool.js" -import { CompletionTool } from "./CompletionTool.js" -import { GenericTool } from "./GenericTool.js" - -// Re-export types -export type { ToolRendererProps } from "./types.js" -export { getToolCategory } from "./types.js" - -// Re-export utilities -export * from "./utils.js" - -// Re-export individual components for direct usage -export { FileReadTool } from "./FileReadTool.js" -export { FileWriteTool } from "./FileWriteTool.js" -export { SearchTool } from "./SearchTool.js" -export { CommandTool } from "./CommandTool.js" -export { BrowserTool } from "./BrowserTool.js" -export { ModeTool } from "./ModeTool.js" -export { CompletionTool } from "./CompletionTool.js" -export { GenericTool } from "./GenericTool.js" - -/** - * Map of tool categories to their renderer components - */ -const CATEGORY_RENDERERS: Record> = { - "file-read": FileReadTool, - "file-write": FileWriteTool, - search: SearchTool, - command: CommandTool, - browser: BrowserTool, - mode: ModeTool, - completion: CompletionTool, - other: GenericTool, -} - -/** - * Get the appropriate renderer component for a tool - * - * @param toolName - The tool name/identifier - * @returns The renderer component for this tool type - */ -export function getToolRenderer(toolName: string): React.FC { - const category = getToolCategory(toolName) - return CATEGORY_RENDERERS[category] || GenericTool -} diff --git a/apps/cli/src/ui/components/tools/types.ts b/apps/cli/src/ui/components/tools/types.ts deleted file mode 100644 index 28a1b5faa02..00000000000 --- a/apps/cli/src/ui/components/tools/types.ts +++ /dev/null @@ -1,52 +0,0 @@ -import type { ToolData } from "../../types.js" - -export interface ToolRendererProps { - toolData: ToolData - rawContent?: string -} - -export type ToolCategory = - | "file-read" - | "file-write" - | "search" - | "command" - | "browser" - | "mode" - | "completion" - | "other" - -export function getToolCategory(toolName: string): ToolCategory { - const fileReadTools = [ - "readFile", - "read_file", - "fetchInstructions", - "fetch_instructions", - "listFilesTopLevel", - "listFilesRecursive", - "list_files", - ] - - const fileWriteTools = [ - "editedExistingFile", - "appliedDiff", - "apply_diff", - "newFileCreated", - "write_to_file", - "writeToFile", - ] - - const searchTools = ["searchFiles", "search_files", "codebaseSearch", "codebase_search"] - const commandTools = ["execute_command", "executeCommand"] - const browserTools = ["browser_action", "browserAction"] - const modeTools = ["switchMode", "switch_mode", "newTask", "new_task", "finishTask"] - const completionTools = ["attempt_completion", "attemptCompletion", "ask_followup_question", "askFollowupQuestion"] - - if (fileReadTools.includes(toolName)) return "file-read" - if (fileWriteTools.includes(toolName)) return "file-write" - if (searchTools.includes(toolName)) return "search" - if (commandTools.includes(toolName)) return "command" - if (browserTools.includes(toolName)) return "browser" - if (modeTools.includes(toolName)) return "mode" - if (completionTools.includes(toolName)) return "completion" - return "other" -} diff --git a/apps/cli/src/ui/components/tools/utils.ts b/apps/cli/src/ui/components/tools/utils.ts deleted file mode 100644 index 5eaee33b127..00000000000 --- a/apps/cli/src/ui/components/tools/utils.ts +++ /dev/null @@ -1,222 +0,0 @@ -import type { IconName } from "../Icon.js" - -/** - * Truncate text and return truncation info - */ -export function truncateText( - text: string, - maxLines: number = 10, -): { text: string; truncated: boolean; totalLines: number; hiddenLines: number } { - const lines = text.split("\n") - const totalLines = lines.length - - if (lines.length <= maxLines) { - return { text, truncated: false, totalLines, hiddenLines: 0 } - } - - const truncatedText = lines.slice(0, maxLines).join("\n") - return { - text: truncatedText, - truncated: true, - totalLines, - hiddenLines: totalLines - maxLines, - } -} - -/** - * Sanitize content for terminal display - * - Replaces tabs with spaces - * - Strips carriage returns - */ -export function sanitizeContent(text: string): string { - return text.replace(/\t/g, " ").replace(/\r/g, "") -} - -/** - * Format diff stats as a colored string representation - */ -export function formatDiffStats(stats: { added: number; removed: number }): { added: string; removed: string } { - return { - added: `+${stats.added}`, - removed: `-${stats.removed}`, - } -} - -/** - * Get a friendly display name for a tool - */ -export function getToolDisplayName(toolName: string): string { - const displayNames: Record = { - // File read operations - readFile: "Read", - read_file: "Read", - fetchInstructions: "Fetch Instructions", - fetch_instructions: "Fetch Instructions", - listFilesTopLevel: "List Files", - listFilesRecursive: "List Files (Recursive)", - list_files: "List Files", - - // File write operations - editedExistingFile: "Edit", - appliedDiff: "Diff", - apply_diff: "Diff", - newFileCreated: "Create File", - write_to_file: "Write File", - writeToFile: "Write File", - - // Search operations - searchFiles: "Search Files", - search_files: "Search Files", - codebaseSearch: "Codebase Search", - codebase_search: "Codebase Search", - - // Command operations - execute_command: "Execute Command", - executeCommand: "Execute Command", - - // Browser operations - browser_action: "Browser Action", - browserAction: "Browser Action", - - // Mode operations - switchMode: "Switch Mode", - switch_mode: "Switch Mode", - newTask: "New Task", - new_task: "New Task", - finishTask: "Finish Task", - - // Completion operations - attempt_completion: "Task Complete", - attemptCompletion: "Task Complete", - ask_followup_question: "Question", - askFollowupQuestion: "Question", - - // TODO operations - update_todo_list: "Update TODO List", - updateTodoList: "Update TODO List", - } - - return displayNames[toolName] || toolName -} - -/** - * Get the IconName for a tool (for use with Icon component) - */ -export function getToolIconName(toolName: string): IconName { - const iconNames: Record = { - // File read operations - readFile: "file", - read_file: "file", - fetchInstructions: "file", - fetch_instructions: "file", - listFilesTopLevel: "folder", - listFilesRecursive: "folder", - list_files: "folder", - - // File write operations - editedExistingFile: "file-edit", - appliedDiff: "diff", - apply_diff: "diff", - newFileCreated: "file-edit", - write_to_file: "file-edit", - writeToFile: "file-edit", - - // Search operations - searchFiles: "search", - search_files: "search", - codebaseSearch: "search", - codebase_search: "search", - - // Command operations - execute_command: "terminal", - executeCommand: "terminal", - - // Browser operations - browser_action: "browser", - browserAction: "browser", - - // Mode operations - switchMode: "switch", - switch_mode: "switch", - newTask: "switch", - new_task: "switch", - finishTask: "check", - - // Completion operations - attempt_completion: "check", - attemptCompletion: "check", - ask_followup_question: "question", - askFollowupQuestion: "question", - - // TODO operations - update_todo_list: "check", - updateTodoList: "check", - } - - return iconNames[toolName] || "gear" -} - -/** - * Format a file path for display, optionally with workspace indicator - */ -export function formatPath(path: string, isOutsideWorkspace?: boolean, isProtected?: boolean): string { - let result = path - const badges: string[] = [] - - if (isOutsideWorkspace) { - badges.push("outside workspace") - } - - if (isProtected) { - badges.push("protected") - } - - if (badges.length > 0) { - result += ` (${badges.join(", ")})` - } - - return result -} - -/** - * Parse diff content into structured hunks for rendering - */ -export interface DiffHunk { - header: string - lines: Array<{ - type: "context" | "added" | "removed" | "header" - content: string - lineNumber?: number - }> -} - -export function parseDiff(diffContent: string): DiffHunk[] { - const hunks: DiffHunk[] = [] - const lines = diffContent.split("\n") - - let currentHunk: DiffHunk | null = null - - for (const line of lines) { - if (line.startsWith("@@")) { - // New hunk header - if (currentHunk) { - hunks.push(currentHunk) - } - currentHunk = { header: line, lines: [] } - } else if (currentHunk) { - if (line.startsWith("+") && !line.startsWith("+++")) { - currentHunk.lines.push({ type: "added", content: line.substring(1) }) - } else if (line.startsWith("-") && !line.startsWith("---")) { - currentHunk.lines.push({ type: "removed", content: line.substring(1) }) - } else if (line.startsWith(" ") || line === "") { - currentHunk.lines.push({ type: "context", content: line.substring(1) || "" }) - } - } - } - - if (currentHunk) { - hunks.push(currentHunk) - } - - return hunks -} diff --git a/apps/cli/src/ui/hooks/TerminalSizeContext.tsx b/apps/cli/src/ui/hooks/TerminalSizeContext.tsx deleted file mode 100644 index c8718abb97c..00000000000 --- a/apps/cli/src/ui/hooks/TerminalSizeContext.tsx +++ /dev/null @@ -1,38 +0,0 @@ -/** - * TerminalSizeContext - Provides terminal dimensions via React Context - * This ensures only one instance of useTerminalSize exists in the app - */ - -import { createContext, useContext, ReactNode } from "react" -import { useTerminalSize as useTerminalSizeHook } from "./useTerminalSize.js" - -interface TerminalSizeContextValue { - columns: number - rows: number -} - -const TerminalSizeContext = createContext(null) - -interface TerminalSizeProviderProps { - children: ReactNode -} - -/** - * Provider component that wraps the app and provides terminal size to all children - */ -export function TerminalSizeProvider({ children }: TerminalSizeProviderProps) { - const size = useTerminalSizeHook() - return {children} -} - -/** - * Hook to access terminal size from context - * Must be used within a TerminalSizeProvider - */ -export function useTerminalSize(): TerminalSizeContextValue { - const context = useContext(TerminalSizeContext) - if (!context) { - throw new Error("useTerminalSize must be used within a TerminalSizeProvider") - } - return context -} diff --git a/apps/cli/src/ui/hooks/__tests__/useToast.test.ts b/apps/cli/src/ui/hooks/__tests__/useToast.test.ts deleted file mode 100644 index 67729d09f8d..00000000000 --- a/apps/cli/src/ui/hooks/__tests__/useToast.test.ts +++ /dev/null @@ -1,190 +0,0 @@ -import { useToastStore } from "../useToast.js" - -describe("useToastStore", () => { - beforeEach(() => { - // Reset the store before each test - useToastStore.setState({ toasts: [] }) - vi.useFakeTimers() - }) - - afterEach(() => { - vi.useRealTimers() - }) - - describe("initial state", () => { - it("should start with an empty toast queue", () => { - const state = useToastStore.getState() - expect(state.toasts).toEqual([]) - }) - }) - - describe("addToast", () => { - it("should add a toast to the queue", () => { - const { addToast } = useToastStore.getState() - - const id = addToast("Test message") - - const state = useToastStore.getState() - expect(state.toasts).toHaveLength(1) - expect(state.toasts[0]).toMatchObject({ - id, - message: "Test message", - type: "info", - duration: 3000, - }) - }) - - it("should add a toast with custom type", () => { - const { addToast } = useToastStore.getState() - - const id = addToast("Error message", "error") - - const state = useToastStore.getState() - expect(state.toasts[0]).toMatchObject({ - id, - message: "Error message", - type: "error", - }) - }) - - it("should add a toast with custom duration", () => { - const { addToast } = useToastStore.getState() - - const id = addToast("Custom duration", "info", 5000) - - const state = useToastStore.getState() - expect(state.toasts[0]).toMatchObject({ - id, - duration: 5000, - }) - }) - - it("should replace existing toast when adding a new one (immediate display)", () => { - const { addToast } = useToastStore.getState() - - addToast("First message") - addToast("Second message") - addToast("Third message") - - const state = useToastStore.getState() - // New toasts replace existing ones for immediate display - expect(state.toasts).toHaveLength(1) - expect(state.toasts[0]?.message).toBe("Third message") - }) - - it("should generate unique IDs for each toast", () => { - const { addToast } = useToastStore.getState() - - const id1 = addToast("First") - const id2 = addToast("Second") - const id3 = addToast("Third") - - expect(id1).not.toBe(id2) - expect(id2).not.toBe(id3) - expect(id1).not.toBe(id3) - }) - - it("should set createdAt timestamp", () => { - const { addToast } = useToastStore.getState() - const beforeTime = Date.now() - - addToast("Timestamped message") - - const state = useToastStore.getState() - expect(state.toasts[0]?.createdAt).toBeGreaterThanOrEqual(beforeTime) - expect(state.toasts[0]?.createdAt).toBeLessThanOrEqual(Date.now()) - }) - - it("should support success type", () => { - const { addToast } = useToastStore.getState() - - addToast("Success", "success") - - const state = useToastStore.getState() - expect(state.toasts[0]?.type).toBe("success") - }) - - it("should support warning type", () => { - const { addToast } = useToastStore.getState() - - addToast("Warning", "warning") - - const state = useToastStore.getState() - expect(state.toasts[0]?.type).toBe("warning") - }) - }) - - describe("removeToast", () => { - it("should remove a toast by ID", () => { - const { addToast, removeToast } = useToastStore.getState() - - const id = addToast("Only toast") - - removeToast(id) - - const state = useToastStore.getState() - expect(state.toasts).toHaveLength(0) - }) - - it("should handle removing non-existent toast gracefully", () => { - const { addToast, removeToast } = useToastStore.getState() - - addToast("Only toast") - - removeToast("non-existent-id") - - const state = useToastStore.getState() - expect(state.toasts).toHaveLength(1) - }) - }) - - describe("clearToasts", () => { - it("should clear all toasts", () => { - const { addToast, clearToasts } = useToastStore.getState() - - addToast("First") - addToast("Second") - addToast("Third") - - clearToasts() - - const state = useToastStore.getState() - expect(state.toasts).toHaveLength(0) - }) - - it("should handle clearing empty queue", () => { - const { clearToasts } = useToastStore.getState() - - clearToasts() - - const state = useToastStore.getState() - expect(state.toasts).toHaveLength(0) - }) - }) - - describe("immediate replacement behavior", () => { - it("should show latest toast immediately when multiple are added", () => { - const { addToast } = useToastStore.getState() - - addToast("First") - addToast("Second") - const id3 = addToast("Third") - - const state = useToastStore.getState() - // Only most recent toast is present - expect(state.toasts).toHaveLength(1) - expect(state.toasts[0]?.id).toBe(id3) - expect(state.toasts[0]?.message).toBe("Third") - }) - - it("should return empty when toast is removed", () => { - const { addToast, removeToast } = useToastStore.getState() - - const id = addToast("Only toast") - removeToast(id) - - const state = useToastStore.getState() - expect(state.toasts).toHaveLength(0) - }) - }) -}) diff --git a/apps/cli/src/ui/hooks/index.ts b/apps/cli/src/ui/hooks/index.ts deleted file mode 100644 index 9e12cd9b0e7..00000000000 --- a/apps/cli/src/ui/hooks/index.ts +++ /dev/null @@ -1,22 +0,0 @@ -// Export existing hooks -export { TerminalSizeProvider, useTerminalSize } from "./TerminalSizeContext.js" -export { useToast, useToastStore } from "./useToast.js" -export { useInputHistory } from "./useInputHistory.js" - -// Export new extracted hooks -export { useFollowupCountdown } from "./useFollowupCountdown.js" -export { useFocusManagement } from "./useFocusManagement.js" -export { useMessageHandlers } from "./useMessageHandlers.js" -export { useExtensionHost } from "./useExtensionHost.js" -export { useTaskSubmit } from "./useTaskSubmit.js" -export { useGlobalInput } from "./useGlobalInput.js" -export { usePickerHandlers } from "./usePickerHandlers.js" - -// Export types -export type { UseFollowupCountdownOptions } from "./useFollowupCountdown.js" -export type { UseFocusManagementOptions, UseFocusManagementReturn } from "./useFocusManagement.js" -export type { UseMessageHandlersOptions, UseMessageHandlersReturn } from "./useMessageHandlers.js" -export type { UseExtensionHostOptions, UseExtensionHostReturn } from "./useExtensionHost.js" -export type { UseTaskSubmitOptions, UseTaskSubmitReturn } from "./useTaskSubmit.js" -export type { UseGlobalInputOptions } from "./useGlobalInput.js" -export type { UsePickerHandlersOptions, UsePickerHandlersReturn } from "./usePickerHandlers.js" diff --git a/apps/cli/src/ui/hooks/useExtensionHost.ts b/apps/cli/src/ui/hooks/useExtensionHost.ts deleted file mode 100644 index 91bdac2bf01..00000000000 --- a/apps/cli/src/ui/hooks/useExtensionHost.ts +++ /dev/null @@ -1,150 +0,0 @@ -import { useEffect, useRef, useCallback, useMemo } from "react" -import { useApp } from "ink" -import { randomUUID } from "crypto" -import type { ExtensionMessage, WebviewMessage } from "@roo-code/types" - -import { ExtensionHostInterface, ExtensionHostOptions } from "@/agent/index.js" - -import { useCLIStore } from "../store.js" - -export interface UseExtensionHostOptions extends ExtensionHostOptions { - initialPrompt?: string - exitOnComplete?: boolean - onExtensionMessage: (msg: ExtensionMessage) => void - createExtensionHost: (options: ExtensionHostOptions) => ExtensionHostInterface -} - -export interface UseExtensionHostReturn { - isReady: boolean - sendToExtension: ((msg: WebviewMessage) => void) | null - runTask: ((prompt: string) => Promise) | null - cleanup: () => Promise -} - -/** - * Hook to manage the extension host lifecycle. - * - * Responsibilities: - * - Initialize the extension host - * - Set up event listeners for messages, task completion, and errors - * - Handle cleanup/disposal - * - Expose methods for sending messages and running tasks - */ -export function useExtensionHost({ - initialPrompt, - mode, - reasoningEffort, - user, - provider, - apiKey, - model, - workspacePath, - extensionPath, - nonInteractive, - ephemeral, - exitOnComplete, - onExtensionMessage, - createExtensionHost, -}: UseExtensionHostOptions): UseExtensionHostReturn { - const { exit } = useApp() - const { addMessage, setComplete, setLoading, setHasStartedTask, setError } = useCLIStore() - - const hostRef = useRef(null) - const isReadyRef = useRef(false) - - const cleanup = useCallback(async () => { - if (hostRef.current) { - await hostRef.current.dispose() - hostRef.current = null - isReadyRef.current = false - } - }, []) - - useEffect(() => { - const init = async () => { - try { - const host = createExtensionHost({ - mode, - user, - reasoningEffort, - provider, - apiKey, - model, - workspacePath, - extensionPath, - nonInteractive, - disableOutput: true, - ephemeral, - }) - - hostRef.current = host - isReadyRef.current = true - - host.on("extensionWebviewMessage", (msg) => onExtensionMessage(msg as ExtensionMessage)) - - host.client.on("taskCompleted", async () => { - setComplete(true) - setLoading(false) - - if (exitOnComplete) { - await cleanup() - exit() - setTimeout(() => process.exit(0), 100) - } - }) - - host.client.on("error", (err: Error) => { - setError(err.message) - setLoading(false) - }) - - await host.activate() - - // Request initial state from extension (triggers - // postStateToWebview which includes taskHistory). - host.sendToExtension({ type: "requestCommands" }) - host.sendToExtension({ type: "requestModes" }) - - setLoading(false) - - if (initialPrompt) { - setHasStartedTask(true) - setLoading(true) - addMessage({ id: randomUUID(), role: "user", content: initialPrompt }) - await host.runTask(initialPrompt) - } - } catch (err) { - setError(err instanceof Error ? err.message : String(err)) - setLoading(false) - } - } - - init() - - return () => { - cleanup() - } - }, []) // Run once on mount - - // Stable sendToExtension - uses ref to always access current host. - // This function reference never changes, preventing downstream - // useCallback/useMemo invalidations. - const sendToExtension = useCallback((msg: WebviewMessage) => { - hostRef.current?.sendToExtension(msg) - }, []) - - // Stable runTask - uses ref to always access current host. - const runTask = useCallback((prompt: string): Promise => { - if (!hostRef.current) { - return Promise.reject(new Error("Extension host not ready")) - } - - return hostRef.current.runTask(prompt) - }, []) - - // Memoized return object to prevent unnecessary re-renders in consumers. - return useMemo( - () => ({ isReady: isReadyRef.current, sendToExtension, runTask, cleanup }), - [sendToExtension, runTask, cleanup], - ) -} diff --git a/apps/cli/src/ui/hooks/useFocusManagement.ts b/apps/cli/src/ui/hooks/useFocusManagement.ts deleted file mode 100644 index dd0b30c61c0..00000000000 --- a/apps/cli/src/ui/hooks/useFocusManagement.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { useEffect } from "react" -import { useUIStateStore } from "../stores/uiStateStore.js" -import type { PendingAsk } from "../types.js" - -export interface UseFocusManagementOptions { - showApprovalPrompt: boolean - pendingAsk: PendingAsk | null -} - -export interface UseFocusManagementReturn { - /** Whether focus can be toggled between scroll and input areas */ - canToggleFocus: boolean - /** Whether scroll area should capture keyboard input */ - isScrollAreaActive: boolean - /** Whether input area is active (for visual focus indicator) */ - isInputAreaActive: boolean - /** Manual focus override */ - manualFocus: "scroll" | "input" | null - /** Set manual focus override */ - setManualFocus: (focus: "scroll" | "input" | null) => void - /** Toggle focus between scroll and input */ - toggleFocus: () => void -} - -/** - * Hook to manage focus state between scroll area and input area. - * - * Focus can be toggled when text input is available (not showing approval prompt). - * The hook automatically resets manual focus when the view changes. - */ -export function useFocusManagement({ - showApprovalPrompt, - pendingAsk, -}: UseFocusManagementOptions): UseFocusManagementReturn { - const { showCustomInput, manualFocus, setManualFocus } = useUIStateStore() - - // Determine if we're in a mode where focus can be toggled (text input is available) - const canToggleFocus = - !showApprovalPrompt && - (!pendingAsk || // Initial input or task complete or loading - pendingAsk.type === "followup" || // Followup question with suggestions or custom input - showCustomInput) // Custom input mode - - // Determine if scroll area should capture keyboard input - const isScrollAreaActive: boolean = - manualFocus === "scroll" ? true : manualFocus === "input" ? false : Boolean(showApprovalPrompt) - - // Determine if input area is active (for visual focus indicator) - const isInputAreaActive: boolean = - manualFocus === "input" ? true : manualFocus === "scroll" ? false : !showApprovalPrompt - - // Reset manual focus when view changes (e.g., agent starts responding) - useEffect(() => { - if (!canToggleFocus) { - setManualFocus(null) - } - }, [canToggleFocus, setManualFocus]) - - /** - * Toggle focus between scroll and input areas - */ - const toggleFocus = () => { - if (!canToggleFocus) { - return - } - - const prev = manualFocus - if (prev === "scroll") { - setManualFocus("input") - } else if (prev === "input") { - setManualFocus("scroll") - } else { - setManualFocus(isScrollAreaActive ? "input" : "scroll") - } - } - - return { - canToggleFocus, - isScrollAreaActive, - isInputAreaActive, - manualFocus, - setManualFocus, - toggleFocus, - } -} diff --git a/apps/cli/src/ui/hooks/useFollowupCountdown.ts b/apps/cli/src/ui/hooks/useFollowupCountdown.ts deleted file mode 100644 index c46f2c7774a..00000000000 --- a/apps/cli/src/ui/hooks/useFollowupCountdown.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { useEffect, useRef } from "react" -import { FOLLOWUP_TIMEOUT_SECONDS } from "../../types/constants.js" -import { useUIStateStore } from "../stores/uiStateStore.js" -import type { PendingAsk } from "../types.js" - -export interface UseFollowupCountdownOptions { - pendingAsk: PendingAsk | null - onAutoSubmit: (text: string) => void -} - -/** - * Hook to manage auto-accept countdown timer for followup questions with suggestions. - * - * When a followup question appears with suggestions (and not in custom input mode), - * starts a countdown timer that auto-submits the first suggestion when it reaches zero. - * - * The countdown can be canceled by: - * - User navigating with arrow keys - * - User switching to custom input mode - * - Followup question changing/disappearing - */ -export function useFollowupCountdown({ pendingAsk, onAutoSubmit }: UseFollowupCountdownOptions) { - const { showCustomInput, countdownSeconds, setCountdownSeconds } = useUIStateStore() - const countdownIntervalRef = useRef(null) - - // Use ref for onAutoSubmit to avoid stale closure issues without needing it in dependencies - const onAutoSubmitRef = useRef(onAutoSubmit) - useEffect(() => { - onAutoSubmitRef.current = onAutoSubmit - }, [onAutoSubmit]) - - // Cleanup interval on unmount - useEffect(() => { - return () => { - if (countdownIntervalRef.current) { - clearInterval(countdownIntervalRef.current) - } - } - }, []) - - // Start countdown when a followup question with suggestions appears - useEffect(() => { - // Clear any existing countdown - if (countdownIntervalRef.current) { - clearInterval(countdownIntervalRef.current) - countdownIntervalRef.current = null - } - - // Only start countdown for followup questions with suggestions (not custom input mode) - if ( - pendingAsk?.type === "followup" && - pendingAsk.suggestions && - pendingAsk.suggestions.length > 0 && - !showCustomInput - ) { - // Start countdown - setCountdownSeconds(FOLLOWUP_TIMEOUT_SECONDS) - - countdownIntervalRef.current = setInterval(() => { - const currentSeconds = useUIStateStore.getState().countdownSeconds - if (currentSeconds === null || currentSeconds <= 1) { - // Time's up! Auto-select first option - if (countdownIntervalRef.current) { - clearInterval(countdownIntervalRef.current) - countdownIntervalRef.current = null - } - setCountdownSeconds(null) - // Auto-submit the first suggestion - if (pendingAsk?.suggestions && pendingAsk.suggestions.length > 0) { - const firstSuggestion = pendingAsk.suggestions[0] - if (firstSuggestion) { - onAutoSubmitRef.current(firstSuggestion.answer) - } - } - } else { - setCountdownSeconds(currentSeconds - 1) - } - }, 1000) - } else { - // Only set to null if not already null to prevent unnecessary state updates - // This is critical to avoid infinite render loops - if (countdownSeconds !== null) { - setCountdownSeconds(null) - } - } - - return () => { - if (countdownIntervalRef.current) { - clearInterval(countdownIntervalRef.current) - countdownIntervalRef.current = null - } - } - // Note: countdownSeconds is intentionally NOT in deps - we only read it to avoid - // unnecessary state updates, not to react to its changes - }, [pendingAsk?.id, pendingAsk?.type, showCustomInput, setCountdownSeconds]) - - /** - * Cancel the countdown timer (called when user interacts with the menu) - */ - const cancelCountdown = () => { - if (countdownIntervalRef.current) { - clearInterval(countdownIntervalRef.current) - countdownIntervalRef.current = null - } - setCountdownSeconds(null) - } - - return { - countdownSeconds, - cancelCountdown, - } -} diff --git a/apps/cli/src/ui/hooks/useGlobalInput.ts b/apps/cli/src/ui/hooks/useGlobalInput.ts deleted file mode 100644 index 31d0f1b8406..00000000000 --- a/apps/cli/src/ui/hooks/useGlobalInput.ts +++ /dev/null @@ -1,170 +0,0 @@ -import { useEffect, useRef } from "react" -import { useInput } from "ink" -import type { WebviewMessage } from "@roo-code/types" - -import { matchesGlobalSequence } from "@/lib/utils/input.js" - -import type { ModeResult } from "../components/autocomplete/index.js" -import { useUIStateStore } from "../stores/uiStateStore.js" -import { useCLIStore } from "../store.js" - -export interface UseGlobalInputOptions { - canToggleFocus: boolean - isScrollAreaActive: boolean - pickerIsOpen: boolean - availableModes: ModeResult[] - currentMode: string | null - mode: string - sendToExtension: ((msg: WebviewMessage) => void) | null - showInfo: (msg: string, duration?: number) => void - exit: () => void - cleanup: () => Promise - toggleFocus: () => void - closePicker: () => void -} - -/** - * Hook to handle global keyboard shortcuts. - * - * Shortcuts: - * - Ctrl+C: Double-press to exit - * - Tab: Toggle focus between scroll area and input - * - Ctrl+M: Cycle through available modes - * - Ctrl+T: Toggle TODO list viewer - * - Escape: Cancel task (when loading) or close TODO viewer - */ -export function useGlobalInput({ - canToggleFocus, - isScrollAreaActive: _isScrollAreaActive, - pickerIsOpen, - availableModes, - currentMode, - mode, - sendToExtension, - showInfo, - exit, - cleanup, - toggleFocus, - closePicker, -}: UseGlobalInputOptions): void { - const { isLoading, currentTodos } = useCLIStore() - const { - showTodoViewer, - setShowTodoViewer, - showExitHint: _showExitHint, - setShowExitHint, - pendingExit, - setPendingExit, - } = useUIStateStore() - - // Track Ctrl+C presses for "press again to exit" behavior - const exitHintTimeout = useRef(null) - - // Cleanup timeout on unmount - useEffect(() => { - return () => { - if (exitHintTimeout.current) { - clearTimeout(exitHintTimeout.current) - } - } - }, []) - - // Handle global keyboard shortcuts - useInput((input, key) => { - // Tab to toggle focus between scroll area and input (only when input is available) - if (key.tab && canToggleFocus && !pickerIsOpen) { - toggleFocus() - return - } - - // Ctrl+M to cycle through modes (only when not loading and we have available modes) - // Uses centralized global input sequence detection - if (matchesGlobalSequence(input, key, "ctrl-m")) { - // Don't allow mode switching while a task is in progress (loading) - if (isLoading) { - showInfo("Cannot switch modes while task is in progress", 2000) - return - } - - // Need at least 2 modes to cycle - if (availableModes.length < 2) { - return - } - - // Find current mode index - const currentModeSlug = currentMode || mode - const currentIndex = availableModes.findIndex((m) => m.slug === currentModeSlug) - const nextIndex = currentIndex === -1 ? 0 : (currentIndex + 1) % availableModes.length - const nextMode = availableModes[nextIndex] - - if (nextMode && sendToExtension) { - sendToExtension({ type: "mode", text: nextMode.slug }) - showInfo(`Switched to ${nextMode.name}`, 2000) - } - - return - } - - // Ctrl+T to toggle TODO list viewer - if (matchesGlobalSequence(input, key, "ctrl-t")) { - // Close picker if open - if (pickerIsOpen) { - closePicker() - } - // Toggle TODO viewer - setShowTodoViewer(!showTodoViewer) - if (!showTodoViewer && currentTodos.length === 0) { - showInfo("No TODO list available", 2000) - setShowTodoViewer(false) - } - return - } - - // Escape key to close TODO viewer - if (key.escape && showTodoViewer) { - setShowTodoViewer(false) - return - } - - // Escape key to cancel/pause task when loading (streaming) - if (key.escape && isLoading && sendToExtension) { - // If picker is open, let the picker handle escape first - if (pickerIsOpen) { - return - } - // Send cancel message to extension (same as webview-ui Cancel button) - sendToExtension({ type: "cancelTask" }) - return - } - - // Ctrl+C to exit - if (key.ctrl && input === "c") { - // If picker is open, close it first - if (pickerIsOpen) { - closePicker() - return - } - - if (pendingExit) { - // Second press - exit immediately - if (exitHintTimeout.current) { - clearTimeout(exitHintTimeout.current) - } - cleanup().finally(() => { - exit() - process.exit(0) - }) - } else { - // First press - show hint and wait for second press - setPendingExit(true) - setShowExitHint(true) - - exitHintTimeout.current = setTimeout(() => { - setPendingExit(false) - setShowExitHint(false) - exitHintTimeout.current = null - }, 2000) - } - } - }) -} diff --git a/apps/cli/src/ui/hooks/useInputHistory.ts b/apps/cli/src/ui/hooks/useInputHistory.ts deleted file mode 100644 index a30be52c397..00000000000 --- a/apps/cli/src/ui/hooks/useInputHistory.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { useState, useEffect, useCallback, useRef } from "react" - -import { loadHistory, addToHistory } from "../../lib/storage/history.js" - -export interface UseInputHistoryOptions { - isActive?: boolean - getCurrentInput?: () => string -} - -export interface UseInputHistoryReturn { - addEntry: (entry: string) => Promise - historyValue: string | null - isBrowsing: boolean - resetBrowsing: (currentInput?: string) => void - history: string[] - draft: string - setDraft: (value: string) => void - navigateUp: () => void - navigateDown: () => void -} - -export function useInputHistory(options: UseInputHistoryOptions = {}): UseInputHistoryReturn { - const { isActive = true, getCurrentInput } = options - - // All history entries (oldest first, newest at end) - const [history, setHistory] = useState([]) - - // Current position in history (-1 = not browsing, 0 = oldest, history.length-1 = newest) - const [historyIndex, setHistoryIndex] = useState(-1) - - // The user's typed text before they started navigating history - const [draft, setDraft] = useState("") - - // Flag to track if history has been loaded - const historyLoaded = useRef(false) - - // Load history on mount - useEffect(() => { - if (!historyLoaded.current) { - historyLoaded.current = true - loadHistory() - .then(setHistory) - .catch(() => { - // Ignore load errors - history is not critical - }) - } - }, []) - - // Navigate to older history entry - const navigateUp = useCallback(() => { - if (!isActive) return - if (history.length === 0) return - - if (historyIndex === -1) { - // Starting to browse - save current input as draft - if (getCurrentInput) { - setDraft(getCurrentInput()) - } - // Go to newest entry - setHistoryIndex(history.length - 1) - } else if (historyIndex > 0) { - // Go to older entry - setHistoryIndex(historyIndex - 1) - } - // At oldest entry - stay there - }, [isActive, history, historyIndex, getCurrentInput]) - - // Navigate to newer history entry - const navigateDown = useCallback(() => { - if (!isActive) return - if (historyIndex === -1) return // Not browsing - - if (historyIndex < history.length - 1) { - // Go to newer entry - setHistoryIndex(historyIndex + 1) - } else { - // At newest entry - return to draft - setHistoryIndex(-1) - } - }, [isActive, historyIndex, history.length]) - - // Add new entry to history - const addEntry = useCallback(async (entry: string) => { - const trimmed = entry.trim() - if (!trimmed) return - - try { - const updated = await addToHistory(trimmed) - setHistory(updated) - } catch { - // Ignore save errors - history is not critical - } - - // Reset navigation state - setHistoryIndex(-1) - setDraft("") - }, []) - - // Reset browsing state - const resetBrowsing = useCallback((currentInput?: string) => { - setHistoryIndex(-1) - if (currentInput !== undefined) { - setDraft(currentInput) - } - }, []) - - // Calculate the current history value to display - // When browsing, show history entry; when returning from browsing, show draft - let historyValue: string | null = null - if (historyIndex >= 0 && historyIndex < history.length) { - historyValue = history[historyIndex] ?? null - } - - const isBrowsing = historyIndex !== -1 - - return { - addEntry, - historyValue, - isBrowsing, - resetBrowsing, - history, - draft, - setDraft, - navigateUp, - navigateDown, - } -} diff --git a/apps/cli/src/ui/hooks/useMessageHandlers.ts b/apps/cli/src/ui/hooks/useMessageHandlers.ts deleted file mode 100644 index 68695e39c74..00000000000 --- a/apps/cli/src/ui/hooks/useMessageHandlers.ts +++ /dev/null @@ -1,410 +0,0 @@ -import { useCallback, useRef } from "react" -import type { ExtensionMessage, ClineMessage, ClineAsk, ClineSay, TodoItem } from "@roo-code/types" -import { consolidateTokenUsage, consolidateApiRequests, consolidateCommands } from "@roo-code/core/cli" - -import type { TUIMessage, ToolData } from "../types.js" -import type { FileResult, SlashCommandResult, ModeResult } from "../components/autocomplete/index.js" -import { useCLIStore } from "../store.js" -import { extractToolData, formatToolOutput, formatToolAskMessage, parseTodosFromToolInfo } from "../utils/tools.js" - -export interface UseMessageHandlersOptions { - nonInteractive: boolean -} - -export interface UseMessageHandlersReturn { - handleExtensionMessage: (msg: ExtensionMessage) => void - seenMessageIds: React.MutableRefObject> - pendingCommandRef: React.MutableRefObject - firstTextMessageSkipped: React.MutableRefObject -} - -/** - * Hook to handle messages from the extension. - * - * Processes three types of messages: - * 1. "say" messages - Information from the agent (text, tool output, reasoning) - * 2. "ask" messages - Requests for user input (approvals, followup questions) - * 3. Extension state updates - Mode changes, task history, file search results - * - * Transforms ClineMessage format to TUIMessage format and updates the store. - */ -export function useMessageHandlers({ nonInteractive }: UseMessageHandlersOptions): UseMessageHandlersReturn { - const { - addMessage, - setPendingAsk, - setComplete, - setLoading, - setHasStartedTask, - setFileSearchResults, - setAllSlashCommands, - setAvailableModes, - setCurrentMode, - setTokenUsage, - setRouterModels, - setTaskHistory, - currentTodos, - setTodos, - } = useCLIStore() - - // Track seen message timestamps to filter duplicates and the prompt echo - const seenMessageIds = useRef>(new Set()) - const firstTextMessageSkipped = useRef(false) - - // Track pending command for injecting into command_output toolData - const pendingCommandRef = useRef(null) - - /** - * Map extension "say" messages to TUI messages - */ - const handleSayMessage = useCallback( - (ts: number, say: ClineSay, text: string, partial: boolean) => { - const messageId = ts.toString() - const isResuming = useCLIStore.getState().isResumingTask - - if (say === "checkpoint_saved") { - return - } - - if (say === "api_req_started") { - return - } - - if (say === "user_feedback") { - seenMessageIds.current.add(messageId) - return - } - - // Skip first text message ONLY for new tasks, not resumed tasks - // When resuming, we want to show all historical messages including the first one - if (say === "text" && !firstTextMessageSkipped.current && !isResuming) { - firstTextMessageSkipped.current = true - seenMessageIds.current.add(messageId) - return - } - - if (seenMessageIds.current.has(messageId) && !partial) { - return - } - - let role: TUIMessage["role"] = "assistant" - let toolName: string | undefined - let toolDisplayName: string | undefined - let toolDisplayOutput: string | undefined - let toolData: ToolData | undefined - - if (say === "command_output") { - role = "tool" - toolName = "execute_command" - toolDisplayName = "bash" - toolDisplayOutput = text - const trackedCommand = pendingCommandRef.current - toolData = { tool: "execute_command", command: trackedCommand || undefined, output: text } - pendingCommandRef.current = null - } else if (say === "reasoning") { - role = "thinking" - } - - seenMessageIds.current.add(messageId) - - addMessage({ - id: messageId, - role, - content: text || "", - toolName, - toolDisplayName, - toolDisplayOutput, - partial, - originalType: say, - toolData, - }) - }, - [addMessage], - ) - - /** - * Handle extension "ask" messages - */ - const handleAskMessage = useCallback( - (ts: number, ask: ClineAsk, text: string, partial: boolean) => { - const messageId = ts.toString() - - if (partial) { - return - } - - if (seenMessageIds.current.has(messageId)) { - return - } - - if (ask === "command_output") { - seenMessageIds.current.add(messageId) - return - } - - // Handle resume_task and resume_completed_task - stop loading and show text input - // Do not set pendingAsk - just stop loading so user sees normal input to type new message - if (ask === "resume_task" || ask === "resume_completed_task") { - seenMessageIds.current.add(messageId) - setLoading(false) - // Mark that a task has been started so subsequent messages continue the task - // (instead of starting a brand new task via runTask) - setHasStartedTask(true) - // Clear the resuming flag since we're now ready for interaction - // Historical messages should already be displayed from state processing - useCLIStore.getState().setIsResumingTask(false) - // Do not set pendingAsk - let the normal text input appear - return - } - - if (ask === "completion_result") { - seenMessageIds.current.add(messageId) - setComplete(true) - setLoading(false) - - // Parse the completion result and add a message for CompletionTool to render - try { - const completionInfo = JSON.parse(text) as Record - const toolData: ToolData = { - tool: "attempt_completion", - result: completionInfo.result as string | undefined, - content: completionInfo.result as string | undefined, - } - - addMessage({ - id: messageId, - role: "tool", - content: text, - toolName: "attempt_completion", - toolDisplayName: "Task Complete", - toolDisplayOutput: formatToolOutput({ tool: "attempt_completion", ...completionInfo }), - originalType: ask, - toolData, - }) - } catch { - // If parsing fails, still add a basic completion message - addMessage({ - id: messageId, - role: "tool", - content: text || "Task completed", - toolName: "attempt_completion", - toolDisplayName: "Task Complete", - toolDisplayOutput: "✅ Task completed", - originalType: ask, - toolData: { - tool: "attempt_completion", - content: text, - }, - }) - } - return - } - - // Track pending command BEFORE nonInteractive handling - // This ensures we capture the command text for later injection into command_output toolData - if (ask === "command") { - pendingCommandRef.current = text - } - - if (nonInteractive && ask !== "followup") { - seenMessageIds.current.add(messageId) - - if (ask === "tool") { - let toolName: string | undefined - let toolDisplayName: string | undefined - let toolDisplayOutput: string | undefined - let formattedContent = text || "" - let toolData: ToolData | undefined - let todos: TodoItem[] | undefined - let previousTodos: TodoItem[] | undefined - - try { - const toolInfo = JSON.parse(text) as Record - toolName = toolInfo.tool as string - toolDisplayName = toolInfo.tool as string - toolDisplayOutput = formatToolOutput(toolInfo) - formattedContent = formatToolAskMessage(toolInfo) - // Extract structured toolData for rich rendering - toolData = extractToolData(toolInfo) - - // Special handling for update_todo_list tool - extract todos - if (toolName === "update_todo_list" || toolName === "updateTodoList") { - const parsedTodos = parseTodosFromToolInfo(toolInfo) - if (parsedTodos && parsedTodos.length > 0) { - todos = parsedTodos - // Capture previous todos before updating global state - previousTodos = [...currentTodos] - setTodos(parsedTodos) - } - } - } catch { - // Use raw text if not valid JSON - } - - addMessage({ - id: messageId, - role: "tool", - content: formattedContent, - toolName, - toolDisplayName, - toolDisplayOutput, - originalType: ask, - toolData, - todos, - previousTodos, - }) - } else { - addMessage({ - id: messageId, - role: "assistant", - content: text || "", - originalType: ask, - }) - } - return - } - - let suggestions: Array<{ answer: string; mode?: string | null }> | undefined - let questionText = text - - if (ask === "followup") { - try { - const data = JSON.parse(text) - questionText = data.question || text - suggestions = Array.isArray(data.suggest) ? data.suggest : undefined - } catch { - // Use raw text - } - } else if (ask === "tool") { - try { - const toolInfo = JSON.parse(text) as Record - questionText = formatToolAskMessage(toolInfo) - } catch { - // Use raw text if not valid JSON - } - } - // Note: ask === "command" is handled above before the nonInteractive block - - seenMessageIds.current.add(messageId) - - setPendingAsk({ - id: messageId, - type: ask, - content: questionText, - suggestions, - }) - }, - [addMessage, setPendingAsk, setComplete, setLoading, setHasStartedTask, nonInteractive, currentTodos, setTodos], - ) - - /** - * Handle all extension messages - */ - const handleExtensionMessage = useCallback( - (msg: ExtensionMessage) => { - if (msg.type === "state") { - const state = msg.state - - if (!state) { - return - } - - // Extract and update current mode from state - const newMode = state.mode - - if (newMode) { - setCurrentMode(newMode) - } - - // Extract and update task history from state - const newTaskHistory = state.taskHistory - - if (newTaskHistory && Array.isArray(newTaskHistory)) { - setTaskHistory(newTaskHistory) - } - - const clineMessages = state.clineMessages - - if (clineMessages) { - for (const clineMsg of clineMessages) { - const ts = clineMsg.ts - const type = clineMsg.type - const say = clineMsg.say - const ask = clineMsg.ask - const text = clineMsg.text || "" - const partial = clineMsg.partial || false - - if (type === "say" && say) { - handleSayMessage(ts, say, text, partial) - } else if (type === "ask" && ask) { - handleAskMessage(ts, ask, text, partial) - } - } - - // Compute token usage metrics from clineMessages - // Skip first message (task prompt) as per webview UI pattern - if (clineMessages.length > 1) { - const processed = consolidateApiRequests( - consolidateCommands(clineMessages.slice(1) as ClineMessage[]), - ) - - const metrics = consolidateTokenUsage(processed) - setTokenUsage(metrics) - } - } - - // After processing state, clear the resuming flag if it was set - // This ensures the flag is cleared even if no resume_task ask message is received - if (useCLIStore.getState().isResumingTask) { - useCLIStore.getState().setIsResumingTask(false) - } - } else if (msg.type === "messageUpdated") { - const clineMessage = msg.clineMessage - - if (!clineMessage) { - return - } - - const ts = clineMessage.ts - const type = clineMessage.type - const say = clineMessage.say - const ask = clineMessage.ask - const text = clineMessage.text || "" - const partial = clineMessage.partial || false - - if (type === "say" && say) { - handleSayMessage(ts, say, text, partial) - } else if (type === "ask" && ask) { - handleAskMessage(ts, ask, text, partial) - } - } else if (msg.type === "fileSearchResults") { - setFileSearchResults((msg.results as FileResult[]) || []) - } else if (msg.type === "commands") { - setAllSlashCommands((msg.commands as SlashCommandResult[]) || []) - } else if (msg.type === "modes") { - setAvailableModes((msg.modes as ModeResult[]) || []) - } else if (msg.type === "routerModels") { - if (msg.routerModels) { - setRouterModels(msg.routerModels) - } - } - }, - [ - handleSayMessage, - handleAskMessage, - setFileSearchResults, - setAllSlashCommands, - setAvailableModes, - setCurrentMode, - setTokenUsage, - setRouterModels, - setTaskHistory, - ], - ) - - return { - handleExtensionMessage, - seenMessageIds, - pendingCommandRef, - firstTextMessageSkipped, - } -} diff --git a/apps/cli/src/ui/hooks/usePickerHandlers.ts b/apps/cli/src/ui/hooks/usePickerHandlers.ts deleted file mode 100644 index a27bdad3f0a..00000000000 --- a/apps/cli/src/ui/hooks/usePickerHandlers.ts +++ /dev/null @@ -1,168 +0,0 @@ -import { useCallback } from "react" -import type { WebviewMessage } from "@roo-code/types" - -import type { - AutocompletePickerState, - AutocompleteInputHandle, - ModeResult, - HistoryResult, -} from "../components/autocomplete/index.js" -import { useCLIStore } from "../store.js" -import { useUIStateStore } from "../stores/uiStateStore.js" - -export interface UsePickerHandlersOptions { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - autocompleteRef: React.RefObject> - // eslint-disable-next-line @typescript-eslint/no-explicit-any - followupAutocompleteRef: React.RefObject> - sendToExtension: ((msg: WebviewMessage) => void) | null - showInfo: (msg: string, duration?: number) => void - seenMessageIds: React.MutableRefObject> - firstTextMessageSkipped: React.MutableRefObject -} - -export interface UsePickerHandlersReturn { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - handlePickerStateChange: (state: AutocompletePickerState) => void - // eslint-disable-next-line @typescript-eslint/no-explicit-any - handlePickerSelect: (item: any) => void - handlePickerClose: () => void - handlePickerIndexChange: (index: number) => void -} - -/** - * Hook to handle autocomplete picker interactions. - * - * Responsibilities: - * - Handle picker state changes from AutocompleteInput - * - Handle item selection (special handling for modes and history items) - * - Handle mode switching via picker - * - Handle task switching via history picker - * - Handle picker close and index change - */ -export function usePickerHandlers({ - autocompleteRef, - followupAutocompleteRef, - sendToExtension, - showInfo, - seenMessageIds, - firstTextMessageSkipped, -}: UsePickerHandlersOptions): UsePickerHandlersReturn { - const { isLoading, currentTaskId, setCurrentTaskId } = useCLIStore() - const { pickerState, setPickerState } = useUIStateStore() - - /** - * Handle picker state changes from AutocompleteInput - */ - const handlePickerStateChange = useCallback( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (state: AutocompletePickerState) => { - setPickerState(state) - }, - [setPickerState], - ) - - /** - * Handle item selection from external PickerSelect - */ - const handlePickerSelect = useCallback( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (item: any) => { - // Check if this is a mode selection. - if (pickerState.activeTrigger?.id === "mode" && item && typeof item === "object" && "slug" in item) { - const modeItem = item as ModeResult - - if (sendToExtension) { - sendToExtension({ type: "mode", text: modeItem.slug }) - } - - autocompleteRef.current?.closePicker() - followupAutocompleteRef.current?.closePicker() - } - // Check if this is a history item selection. - else if (pickerState.activeTrigger?.id === "history" && item && typeof item === "object" && "id" in item) { - const historyItem = item as HistoryResult - - // Don't allow task switching while a task is in progress (loading). - if (isLoading) { - showInfo("Cannot switch tasks while task is in progress", 2000) - autocompleteRef.current?.closePicker() - followupAutocompleteRef.current?.closePicker() - return - } - - // If selecting the same task that's already loaded, just close the picker. - if (historyItem.id === currentTaskId) { - autocompleteRef.current?.closePicker() - followupAutocompleteRef.current?.closePicker() - return - } - - // Send showTaskWithId message to extension to resume the task - if (sendToExtension) { - // Use selective reset that preserves global state (taskHistory, modes, commands) - useCLIStore.getState().resetForTaskSwitch() - // Set the resuming flag so message handlers know we're resuming - // This prevents skipping the first text message (which is historical) - useCLIStore.getState().setIsResumingTask(true) - // Track which task we're switching to - setCurrentTaskId(historyItem.id) - // Reset refs to avoid stale state across task switches - seenMessageIds.current.clear() - firstTextMessageSkipped.current = false - - // Send message to resume the selected task - // This triggers createTaskWithHistoryItem -> postStateToWebview - // which includes clineMessages and handles mode restoration - sendToExtension({ type: "showTaskWithId", text: historyItem.id }) - } - - // Close the picker - autocompleteRef.current?.closePicker() - followupAutocompleteRef.current?.closePicker() - } else { - // Handle other item selections normally - autocompleteRef.current?.handleItemSelect(item) - followupAutocompleteRef.current?.handleItemSelect(item) - } - }, - [ - pickerState.activeTrigger, - isLoading, - showInfo, - currentTaskId, - setCurrentTaskId, - sendToExtension, - autocompleteRef, - followupAutocompleteRef, - seenMessageIds, - firstTextMessageSkipped, - ], - ) - - /** - * Handle picker close from external PickerSelect - */ - const handlePickerClose = useCallback(() => { - autocompleteRef.current?.closePicker() - followupAutocompleteRef.current?.closePicker() - }, [autocompleteRef, followupAutocompleteRef]) - - /** - * Handle picker index change from external PickerSelect - */ - const handlePickerIndexChange = useCallback( - (index: number) => { - autocompleteRef.current?.handleIndexChange(index) - followupAutocompleteRef.current?.handleIndexChange(index) - }, - [autocompleteRef, followupAutocompleteRef], - ) - - return { - handlePickerStateChange, - handlePickerSelect, - handlePickerClose, - handlePickerIndexChange, - } -} diff --git a/apps/cli/src/ui/hooks/useTaskSubmit.ts b/apps/cli/src/ui/hooks/useTaskSubmit.ts deleted file mode 100644 index 0ae752a7aca..00000000000 --- a/apps/cli/src/ui/hooks/useTaskSubmit.ts +++ /dev/null @@ -1,183 +0,0 @@ -import { useCallback } from "react" -import { randomUUID } from "crypto" -import type { WebviewMessage } from "@roo-code/types" - -import { getGlobalCommand } from "../../lib/utils/commands.js" - -import { useCLIStore } from "../store.js" -import { useUIStateStore } from "../stores/uiStateStore.js" - -export interface UseTaskSubmitOptions { - sendToExtension: ((msg: WebviewMessage) => void) | null - runTask: ((prompt: string) => Promise) | null - seenMessageIds: React.MutableRefObject> - firstTextMessageSkipped: React.MutableRefObject -} - -export interface UseTaskSubmitReturn { - handleSubmit: (text: string) => Promise - handleApprove: () => void - handleReject: () => void -} - -/** - * Hook to handle task submission, user responses, and approvals. - * - * Responsibilities: - * - Process user message submissions - * - Detect and handle global commands (like /new) - * - Handle pending ask responses - * - Start new tasks or continue existing ones - * - Handle Y/N approval responses - */ -export function useTaskSubmit({ - sendToExtension, - runTask, - seenMessageIds, - firstTextMessageSkipped, -}: UseTaskSubmitOptions): UseTaskSubmitReturn { - const { - pendingAsk, - hasStartedTask, - isComplete, - addMessage, - setPendingAsk, - setHasStartedTask, - setLoading, - setComplete, - setError, - } = useCLIStore() - - const { setShowCustomInput, setIsTransitioningToCustomInput } = useUIStateStore() - - /** - * Handle user text submission (from input or followup question) - */ - const handleSubmit = useCallback( - async (text: string) => { - if (!sendToExtension || !text.trim()) { - return - } - - const trimmedText = text.trim() - - if (trimmedText === "__CUSTOM__") { - return - } - - // Check for CLI global action commands (e.g., /new) - if (trimmedText.startsWith("/")) { - const commandMatch = trimmedText.match(/^\/(\w+)(?:\s|$)/) - - if (commandMatch && commandMatch[1]) { - const globalCommand = getGlobalCommand(commandMatch[1]) - - if (globalCommand?.action === "clearTask") { - // Reset CLI state and send clearTask to extension. - useCLIStore.getState().reset() - - // Reset component-level refs to avoid stale message tracking. - seenMessageIds.current.clear() - firstTextMessageSkipped.current = false - sendToExtension({ type: "clearTask" }) - - // Re-request state, commands and modes since reset() cleared them. - sendToExtension({ type: "requestCommands" }) - sendToExtension({ type: "requestModes" }) - return - } - } - } - - if (pendingAsk) { - addMessage({ id: randomUUID(), role: "user", content: trimmedText }) - - sendToExtension({ - type: "askResponse", - askResponse: "messageResponse", - text: trimmedText, - }) - - setPendingAsk(null) - setShowCustomInput(false) - setIsTransitioningToCustomInput(false) - setLoading(true) - } else if (!hasStartedTask) { - setHasStartedTask(true) - setLoading(true) - addMessage({ id: randomUUID(), role: "user", content: trimmedText }) - - try { - if (runTask) { - await runTask(trimmedText) - } - } catch (err) { - setError(err instanceof Error ? err.message : String(err)) - setLoading(false) - } - } else { - if (isComplete) { - setComplete(false) - } - - setLoading(true) - addMessage({ id: randomUUID(), role: "user", content: trimmedText }) - - sendToExtension({ - type: "askResponse", - askResponse: "messageResponse", - text: trimmedText, - }) - } - }, - [ - sendToExtension, - runTask, - pendingAsk, - hasStartedTask, - isComplete, - addMessage, - setPendingAsk, - setHasStartedTask, - setLoading, - setComplete, - setError, - setShowCustomInput, - setIsTransitioningToCustomInput, - seenMessageIds, - firstTextMessageSkipped, - ], - ) - - /** - * Handle approval (Y key) - */ - const handleApprove = useCallback(() => { - if (!sendToExtension) { - return - } - - sendToExtension({ type: "askResponse", askResponse: "yesButtonClicked" }) - setPendingAsk(null) - setLoading(true) - }, [sendToExtension, setPendingAsk, setLoading]) - - /** - * Handle rejection (N key) - */ - const handleReject = useCallback(() => { - if (!sendToExtension) { - return - } - - sendToExtension({ type: "askResponse", askResponse: "noButtonClicked" }) - setPendingAsk(null) - setLoading(true) - }, [sendToExtension, setPendingAsk, setLoading]) - - return { - handleSubmit, - handleApprove, - handleReject, - } -} diff --git a/apps/cli/src/ui/hooks/useTerminalSize.ts b/apps/cli/src/ui/hooks/useTerminalSize.ts deleted file mode 100644 index 01ea262f6af..00000000000 --- a/apps/cli/src/ui/hooks/useTerminalSize.ts +++ /dev/null @@ -1,59 +0,0 @@ -/** - * useTerminalSize - Hook that tracks terminal dimensions and re-renders on resize - * Includes debouncing to prevent rendering issues during rapid resizing - */ - -import { useState, useEffect, useRef } from "react" - -interface TerminalSize { - columns: number - rows: number -} - -/** - * Returns the current terminal size and re-renders when it changes - * Debounces resize events to prevent rendering artifacts - */ -export function useTerminalSize(): TerminalSize { - // Get initial size synchronously - this is the value used for first render - const [size, setSize] = useState(() => ({ - columns: process.stdout.columns || 80, - rows: process.stdout.rows || 24, - })) - - const debounceTimer = useRef(null) - - useEffect(() => { - const handleResize = () => { - // Clear any pending debounce - if (debounceTimer.current) { - clearTimeout(debounceTimer.current) - } - - // Debounce resize events by 50ms - debounceTimer.current = setTimeout(() => { - // Clear the terminal before updating size to prevent artifacts - process.stdout.write("\x1b[2J\x1b[H") - - setSize({ - columns: process.stdout.columns || 80, - rows: process.stdout.rows || 24, - }) - debounceTimer.current = null - }, 50) - } - - // Listen for resize events - process.stdout.on("resize", handleResize) - - // Cleanup - return () => { - process.stdout.off("resize", handleResize) - if (debounceTimer.current) { - clearTimeout(debounceTimer.current) - } - } - }, []) - - return size -} diff --git a/apps/cli/src/ui/hooks/useToast.ts b/apps/cli/src/ui/hooks/useToast.ts deleted file mode 100644 index 18d5bcda07d..00000000000 --- a/apps/cli/src/ui/hooks/useToast.ts +++ /dev/null @@ -1,196 +0,0 @@ -import { create } from "zustand" -import { useEffect, useCallback, useRef } from "react" - -/** - * Toast message types for different visual styles - */ -export type ToastType = "info" | "success" | "warning" | "error" - -/** - * A single toast message in the queue - */ -export interface Toast { - id: string - message: string - type: ToastType - /** Duration in milliseconds before auto-dismiss (default: 3000) */ - duration: number - /** Timestamp when the toast was created */ - createdAt: number -} - -/** - * Toast queue store state - */ -interface ToastState { - /** Queue of active toasts (FIFO - first one is displayed) */ - toasts: Toast[] - /** Add a toast to the queue */ - addToast: (message: string, type?: ToastType, duration?: number) => string - /** Remove a specific toast by ID */ - removeToast: (id: string) => void - /** Clear all toasts */ - clearToasts: () => void -} - -/** - * Default toast duration in milliseconds - */ -const DEFAULT_DURATION = 3000 - -/** - * Generate a unique ID for toasts - */ -let toastIdCounter = 0 -function generateToastId(): string { - return `toast-${Date.now()}-${++toastIdCounter}` -} - -/** - * Zustand store for toast queue management - */ -export const useToastStore = create((set) => ({ - toasts: [], - - addToast: (message: string, type: ToastType = "info", duration: number = DEFAULT_DURATION) => { - const id = generateToastId() - const toast: Toast = { - id, - message, - type, - duration, - createdAt: Date.now(), - } - - // Replace any existing toasts - new toast shows immediately - // This provides better UX as users see the most recent message right away - set(() => ({ - toasts: [toast], - })) - - return id - }, - - removeToast: (id: string) => { - set((state) => ({ - toasts: state.toasts.filter((t) => t.id !== id), - })) - }, - - clearToasts: () => { - set({ toasts: [] }) - }, -})) - -/** - * Hook for displaying and managing toasts with auto-expiry. - * Returns the current toast (if any) and utility functions. - * - * The hook handles auto-dismissal of toasts after their duration expires. - */ -export function useToast() { - const { toasts, addToast, removeToast, clearToasts } = useToastStore() - - // Track active timers for cleanup - const timersRef = useRef>(new Map()) - - // Get the current toast to display (first in queue) - const currentToast = toasts.length > 0 ? toasts[0] : null - - // Set up auto-dismissal timer for current toast - useEffect(() => { - if (!currentToast) { - return - } - - // Check if timer already exists for this toast - if (timersRef.current.has(currentToast.id)) { - return - } - - // Calculate remaining time (accounts for time already elapsed) - const elapsed = Date.now() - currentToast.createdAt - const remainingTime = Math.max(0, currentToast.duration - elapsed) - - const timer = setTimeout(() => { - removeToast(currentToast.id) - timersRef.current.delete(currentToast.id) - }, remainingTime) - - timersRef.current.set(currentToast.id, timer) - - return () => { - // Clean up timer if toast is removed before expiry - const existingTimer = timersRef.current.get(currentToast.id) - if (existingTimer) { - clearTimeout(existingTimer) - timersRef.current.delete(currentToast.id) - } - } - }, [currentToast?.id, currentToast?.createdAt, currentToast?.duration, removeToast]) - - // Cleanup all timers on unmount - useEffect(() => { - return () => { - timersRef.current.forEach((timer) => clearTimeout(timer)) - timersRef.current.clear() - } - }, []) - - // Convenience methods for different toast types - const showToast = useCallback( - (message: string, type?: ToastType, duration?: number) => { - return addToast(message, type, duration) - }, - [addToast], - ) - - const showInfo = useCallback( - (message: string, duration?: number) => { - return addToast(message, "info", duration) - }, - [addToast], - ) - - const showSuccess = useCallback( - (message: string, duration?: number) => { - return addToast(message, "success", duration) - }, - [addToast], - ) - - const showWarning = useCallback( - (message: string, duration?: number) => { - return addToast(message, "warning", duration) - }, - [addToast], - ) - - const showError = useCallback( - (message: string, duration?: number) => { - return addToast(message, "error", duration) - }, - [addToast], - ) - - return { - /** Current toast being displayed (first in queue) */ - currentToast, - /** All toasts in the queue */ - toasts, - /** Generic toast display method */ - showToast, - /** Show an info toast */ - showInfo, - /** Show a success toast */ - showSuccess, - /** Show a warning toast */ - showWarning, - /** Show an error toast */ - showError, - /** Remove a specific toast by ID */ - removeToast, - /** Clear all toasts */ - clearToasts, - } -} diff --git a/apps/cli/src/ui/store.ts b/apps/cli/src/ui/store.ts deleted file mode 100644 index 6c9566a0067..00000000000 --- a/apps/cli/src/ui/store.ts +++ /dev/null @@ -1,295 +0,0 @@ -import { create } from "zustand" - -import type { TokenUsage, ProviderSettings, TodoItem } from "@roo-code/types" - -import type { TUIMessage, PendingAsk, TaskHistoryItem } from "./types.js" -import type { FileResult, SlashCommandResult, ModeResult } from "./components/autocomplete/index.js" - -/** - * Shallow array equality check - compares array length and element references. - * Used to prevent unnecessary state updates when array content hasn't changed. - */ -function shallowArrayEqual(a: T[], b: T[]): boolean { - if (a === b) return true - if (a.length !== b.length) return false - for (let i = 0; i < a.length; i++) { - if (a[i] !== b[i]) return false - } - return true -} - -/** - * Streaming message debounce configuration. - * Batches rapid partial message updates to reduce re-renders during streaming. - * Higher values = fewer renders but text appears more "chunky" - * Lower values = smoother text but more renders - */ -const STREAMING_DEBOUNCE_MS = 150 // 150ms debounce for aggressive batching - -// Pending streaming updates - batched and flushed after debounce interval -interface PendingStreamUpdate { - id: string - content: string - partial: boolean - timestamp: number -} - -const pendingStreamUpdates: Map = new Map() -let streamingDebounceTimer: ReturnType | null = null - -/** - * RouterModels type for context window lookup. - * Simplified version - we only need contextWindow from ModelInfo. - */ -export type RouterModels = Record> - -/** - * CLI application state. - * - * Note: Autocomplete picker UI state (isOpen, selectedIndex) is now managed - * by the useAutocompletePicker hook. The store only holds data that needs - * to be shared between components or persisted (like search results from API). - */ -interface CLIState { - // Message history - messages: TUIMessage[] - pendingAsk: PendingAsk | null - - // Task state - isLoading: boolean - isComplete: boolean - hasStartedTask: boolean - error: string | null - - // Task resumption flag - true when resuming a task from history - // Used to modify message processing behavior (e.g., don't skip first text message) - isResumingTask: boolean - - // Autocomplete data (from API/extension) - fileSearchResults: FileResult[] - allSlashCommands: SlashCommandResult[] - availableModes: ModeResult[] - - // Task history (for resuming previous tasks) - taskHistory: TaskHistoryItem[] - - // Current task ID (for detecting same-task reselection) - currentTaskId: string | null - - // Current mode (updated reactively when mode changes) - currentMode: string | null - - // Token usage metrics (from getApiMetrics) - tokenUsage: TokenUsage | null - - // Model info for context window lookup - routerModels: RouterModels | null - apiConfiguration: ProviderSettings | null - - // Todo list tracking - currentTodos: TodoItem[] - previousTodos: TodoItem[] -} - -interface CLIActions { - // Message actions - addMessage: (msg: TUIMessage) => void - updateMessage: (id: string, content: string, partial?: boolean) => void - - // Task actions - setPendingAsk: (ask: PendingAsk | null) => void - setLoading: (loading: boolean) => void - setComplete: (complete: boolean) => void - setHasStartedTask: (started: boolean) => void - setError: (error: string | null) => void - reset: () => void - /** Reset for task switching - preserves global state (taskHistory, modes, commands) */ - resetForTaskSwitch: () => void - /** Set the isResumingTask flag - used when resuming a task from history */ - setIsResumingTask: (isResuming: boolean) => void - - // Autocomplete data actions - setFileSearchResults: (results: FileResult[]) => void - setAllSlashCommands: (commands: SlashCommandResult[]) => void - setAvailableModes: (modes: ModeResult[]) => void - - // Task history action - setTaskHistory: (history: TaskHistoryItem[]) => void - - // Current task ID action - setCurrentTaskId: (taskId: string | null) => void - - // Current mode action - setCurrentMode: (mode: string | null) => void - - // Metrics actions - setTokenUsage: (usage: TokenUsage | null) => void - setRouterModels: (models: RouterModels | null) => void - setApiConfiguration: (config: ProviderSettings | null) => void - - // Todo actions - setTodos: (todos: TodoItem[]) => void -} - -const initialState: CLIState = { - messages: [], - pendingAsk: null, - isLoading: false, - isComplete: false, - hasStartedTask: false, - error: null, - isResumingTask: false, - fileSearchResults: [], - allSlashCommands: [], - availableModes: [], - taskHistory: [], - currentTaskId: null, - currentMode: null, - tokenUsage: null, - routerModels: null, - apiConfiguration: null, - currentTodos: [], - previousTodos: [], -} - -export const useCLIStore = create((set, get) => ({ - ...initialState, - - addMessage: (msg) => { - const state = get() - // Check if message already exists (by ID). - const existingIndex = state.messages.findIndex((m) => m.id === msg.id) - - // For NEW messages (not updates) - always apply immediately - if (existingIndex === -1) { - set({ messages: [...state.messages, msg] }) - return - } - - // For UPDATES to existing messages: - // If partial (streaming) and message exists, debounce the update - if (msg.partial) { - // Queue the update - pendingStreamUpdates.set(msg.id, { - id: msg.id, - content: msg.content, - partial: true, - timestamp: Date.now(), - }) - - // Schedule flush if not already scheduled - if (!streamingDebounceTimer) { - streamingDebounceTimer = setTimeout(() => { - // Flush all pending updates as a single batch - const currentState = get() - const updates = Array.from(pendingStreamUpdates.values()) - pendingStreamUpdates.clear() - streamingDebounceTimer = null - - if (updates.length === 0) return - - // Apply all pending updates in one state change - const newMessages = [...currentState.messages] - let hasChanges = false - - for (const update of updates) { - const idx = newMessages.findIndex((m) => m.id === update.id) - if (idx !== -1 && newMessages[idx]) { - newMessages[idx] = { - ...newMessages[idx], - content: update.content, - partial: update.partial, - } - hasChanges = true - } - } - - if (hasChanges) { - set({ messages: newMessages }) - } - }, STREAMING_DEBOUNCE_MS) - } - return - } - - // Non-partial update (final message) - apply immediately and clear any pending - // This ensures the final complete message is always shown - pendingStreamUpdates.delete(msg.id) - - const updated = [...state.messages] - updated[existingIndex] = msg - set({ messages: updated }) - }, - - updateMessage: (id, content, partial) => - set((state) => { - const index = state.messages.findIndex((m) => m.id === id) - - if (index === -1) { - return state - } - - const existing = state.messages[index] - - if (!existing) { - return state - } - - const updated = [...state.messages] - - updated[index] = { - ...existing, - content, - partial: partial !== undefined ? partial : existing.partial, - } - - return { messages: updated } - }), - - setPendingAsk: (ask) => set({ pendingAsk: ask }), - setLoading: (loading) => set({ isLoading: loading }), - setComplete: (complete) => set({ isComplete: complete }), - setHasStartedTask: (started) => set({ hasStartedTask: started }), - setError: (error) => set({ error }), - reset: () => set(initialState), - resetForTaskSwitch: () => - set((state) => ({ - // Clear task-specific state - messages: [], - pendingAsk: null, - isLoading: false, - isComplete: false, - hasStartedTask: false, - error: null, - isResumingTask: false, - tokenUsage: null, - currentTodos: [], - previousTodos: [], - // currentTaskId is preserved - will be updated to new task ID by caller - currentTaskId: state.currentTaskId, - // PRESERVE global state - don't clear these - taskHistory: state.taskHistory, - availableModes: state.availableModes, - allSlashCommands: state.allSlashCommands, - fileSearchResults: state.fileSearchResults, - currentMode: state.currentMode, - routerModels: state.routerModels, - apiConfiguration: state.apiConfiguration, - })), - setIsResumingTask: (isResuming) => set({ isResumingTask: isResuming }), - // Use shallow equality to prevent unnecessary re-renders when array content is the same - setFileSearchResults: (results) => - set((state) => (shallowArrayEqual(state.fileSearchResults, results) ? state : { fileSearchResults: results })), - setAllSlashCommands: (commands) => - set((state) => (shallowArrayEqual(state.allSlashCommands, commands) ? state : { allSlashCommands: commands })), - setAvailableModes: (modes) => - set((state) => (shallowArrayEqual(state.availableModes, modes) ? state : { availableModes: modes })), - setTaskHistory: (history) => - set((state) => (shallowArrayEqual(state.taskHistory, history) ? state : { taskHistory: history })), - setCurrentTaskId: (taskId) => set({ currentTaskId: taskId }), - setCurrentMode: (mode) => set({ currentMode: mode }), - setTokenUsage: (usage) => set({ tokenUsage: usage }), - setRouterModels: (models) => set({ routerModels: models }), - setApiConfiguration: (config) => set({ apiConfiguration: config }), - setTodos: (todos) => set((state) => ({ previousTodos: state.currentTodos, currentTodos: todos })), -})) diff --git a/apps/cli/src/ui/stores/uiStateStore.ts b/apps/cli/src/ui/stores/uiStateStore.ts deleted file mode 100644 index d7abe598451..00000000000 --- a/apps/cli/src/ui/stores/uiStateStore.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { create } from "zustand" -import type { AutocompletePickerState } from "../components/autocomplete/types.js" - -/** - * UI-specific state that doesn't need to persist across task switches. - * This separates UI state from task/message state in the main CLI store. - */ -interface UIState { - // Exit handling state - showExitHint: boolean - pendingExit: boolean - - // Countdown timer for auto-accepting followup questions - countdownSeconds: number | null - - // Custom input mode for followup questions - showCustomInput: boolean - isTransitioningToCustomInput: boolean - - // Focus management for scroll area vs input - manualFocus: "scroll" | "input" | null - - // TODO viewer overlay - showTodoViewer: boolean - - // Autocomplete picker state - // eslint-disable-next-line @typescript-eslint/no-explicit-any - pickerState: AutocompletePickerState -} - -interface UIActions { - // Exit handling actions - setShowExitHint: (show: boolean) => void - setPendingExit: (pending: boolean) => void - - // Countdown timer actions - setCountdownSeconds: (seconds: number | null) => void - - // Custom input mode actions - setShowCustomInput: (show: boolean) => void - setIsTransitioningToCustomInput: (transitioning: boolean) => void - - // Focus management actions - setManualFocus: (focus: "scroll" | "input" | null) => void - - // TODO viewer actions - setShowTodoViewer: (show: boolean) => void - - // Picker state actions - // eslint-disable-next-line @typescript-eslint/no-explicit-any - setPickerState: (state: AutocompletePickerState) => void - - // Reset all UI state to defaults - resetUIState: () => void -} - -const initialState: UIState = { - showExitHint: false, - pendingExit: false, - countdownSeconds: null, - showCustomInput: false, - isTransitioningToCustomInput: false, - manualFocus: null, - showTodoViewer: false, - pickerState: { - activeTrigger: null, - results: [], - selectedIndex: 0, - isOpen: false, - isLoading: false, - triggerInfo: null, - }, -} - -export const useUIStateStore = create((set) => ({ - ...initialState, - - setShowExitHint: (show) => set({ showExitHint: show }), - setPendingExit: (pending) => set({ pendingExit: pending }), - setCountdownSeconds: (seconds) => set({ countdownSeconds: seconds }), - setShowCustomInput: (show) => set({ showCustomInput: show }), - setIsTransitioningToCustomInput: (transitioning) => set({ isTransitioningToCustomInput: transitioning }), - setManualFocus: (focus) => set({ manualFocus: focus }), - setShowTodoViewer: (show) => set({ showTodoViewer: show }), - setPickerState: (state) => set({ pickerState: state }), - resetUIState: () => set(initialState), -})) diff --git a/apps/cli/src/ui/theme.ts b/apps/cli/src/ui/theme.ts deleted file mode 100644 index bce18f76290..00000000000 --- a/apps/cli/src/ui/theme.ts +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Theme configuration for Roo Code CLI TUI - * Using Hardcore color scheme - */ - -// Hardcore palette -const hardcore = { - // Accent colors - pink: "#F92672", - pinkLight: "#FF669D", - green: "#A6E22E", - greenLight: "#BEED5F", - orange: "#FD971F", - yellow: "#E6DB74", - cyan: "#66D9EF", - purple: "#9E6FFE", - - // Text colors - text: "#F8F8F2", - subtext1: "#CCCCC6", - subtext0: "#A3BABF", - - // Overlay colors - overlay2: "#A3BABF", - overlay1: "#5E7175", - overlay0: "#505354", - - // Surface colors - surface2: "#505354", - surface1: "#383a3e", - surface0: "#2d2e2e", - - // Base colors - base: "#1B1D1E", - mantle: "#161819", - crust: "#101112", -} - -// Title and branding colors -export const titleColor = hardcore.orange // Orange for title -export const welcomeText = hardcore.text // Standard text -export const asciiColor = hardcore.cyan // Cyan for ASCII art - -// Tips section colors -export const tipsHeader = hardcore.orange // Orange for tips headers -export const tipsText = hardcore.subtext0 // Subtle text for tips - -// Header text colors (for messages) -export const userHeader = hardcore.purple // Purple for user header -export const rooHeader = hardcore.yellow // Yellow for roo -export const toolHeader = hardcore.cyan // Cyan for tool headers -export const thinkingHeader = hardcore.overlay1 // Subtle gray for thinking header - -// Message text colors -export const userText = hardcore.text // Standard text for user -export const rooText = hardcore.text // Standard text for roo -export const toolText = hardcore.subtext0 // Subtle text for tool output -export const thinkingText = hardcore.overlay2 // Subtle gray for thinking text - -// UI element colors -export const borderColor = hardcore.surface1 // Surface color for borders -export const borderColorActive = hardcore.purple // Active/focused border color -export const dimText = hardcore.overlay1 // Dim text -export const promptColor = hardcore.overlay2 // Prompt indicator -export const promptColorActive = hardcore.cyan // Active prompt color -export const placeholderColor = hardcore.overlay0 // Placeholder text - -// Status colors -export const successColor = hardcore.green // Green for success -export const errorColor = hardcore.pink // Pink for errors -export const warningColor = hardcore.yellow // Yellow for warnings - -// Focus indicator colors -export const focusColor = hardcore.cyan // Focus indicator (cyan accent) -export const scrollActiveColor = hardcore.purple // Scroll area active indicator (purple) -export const scrollTrackColor = hardcore.surface1 // Muted scrollbar track color - -// Base text color -export const text = hardcore.text // Standard text color diff --git a/apps/cli/src/ui/types.ts b/apps/cli/src/ui/types.ts deleted file mode 100644 index c2187fb2b66..00000000000 --- a/apps/cli/src/ui/types.ts +++ /dev/null @@ -1,123 +0,0 @@ -import type { ClineAsk, ClineSay, TodoItem } from "@roo-code/types" - -export type MessageRole = "system" | "user" | "assistant" | "tool" | "thinking" - -export interface ToolData { - /** Tool identifier (e.g., "readFile", "appliedDiff", "searchFiles") */ - tool: string - - // File operation fields - /** File path */ - path?: string - /** Whether the file is outside the workspace */ - isOutsideWorkspace?: boolean - /** Whether the file is write-protected */ - isProtected?: boolean - /** Unified diff content */ - diff?: string - /** Diff statistics */ - diffStats?: { added: number; removed: number } - /** General content (file content, search results, etc.) */ - content?: string - - // Search operation fields - /** Search regex pattern */ - regex?: string - /** File pattern filter */ - filePattern?: string - /** Search query (for codebase search) */ - query?: string - - // Mode operation fields - /** Target mode slug */ - mode?: string - /** Reason for mode switch or other actions */ - reason?: string - - // Command operation fields - /** Command string */ - command?: string - /** Command output */ - output?: string - - // Browser operation fields - /** Browser action type */ - action?: string - /** Browser URL */ - url?: string - /** Click/hover coordinates */ - coordinate?: string - - // Batch operation fields - /** Batch file reads */ - batchFiles?: Array<{ - path: string - lineSnippet?: string - isOutsideWorkspace?: boolean - key?: string - content?: string - }> - /** Batch diff operations */ - batchDiffs?: Array<{ - path: string - changeCount?: number - key?: string - content?: string - diffStats?: { added: number; removed: number } - diffs?: Array<{ - content: string - startLine?: number - }> - }> - - // Question/completion fields - /** Question text for ask_followup_question */ - question?: string - /** Result text for attempt_completion */ - result?: string - - // Additional display hints - /** Line number for context */ - lineNumber?: number - /** Additional file count for batch operations */ - additionalFileCount?: number -} - -export interface TUIMessage { - id: string - role: MessageRole - content: string - toolName?: string - toolDisplayName?: string - toolDisplayOutput?: string - hasPendingToolCalls?: boolean - partial?: boolean - originalType?: ClineAsk | ClineSay - /** TODO items for update_todo_list tool messages */ - todos?: TodoItem[] - /** Previous TODO items for diff display */ - previousTodos?: TodoItem[] - /** Structured tool data for rich rendering */ - toolData?: ToolData -} - -export interface PendingAsk { - id: string - type: ClineAsk - content: string - suggestions?: Array<{ answer: string; mode?: string | null }> -} - -export type View = "UserInput" | "AgentResponse" | "ToolUse" | "Default" - -export interface TaskHistoryItem { - id: string - task: string - ts: number - totalCost?: number - workspace?: string - mode?: string - status?: "active" | "completed" | "delegated" - tokensIn?: number - tokensOut?: number -} diff --git a/apps/cli/src/ui/utils/index.ts b/apps/cli/src/ui/utils/index.ts deleted file mode 100644 index 9c55726d641..00000000000 --- a/apps/cli/src/ui/utils/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./tools.js" -export * from "./views.js" diff --git a/apps/cli/src/ui/utils/tools.ts b/apps/cli/src/ui/utils/tools.ts deleted file mode 100644 index be3ff9484db..00000000000 --- a/apps/cli/src/ui/utils/tools.ts +++ /dev/null @@ -1,346 +0,0 @@ -import type { TodoItem } from "@roo-code/types" - -import type { ToolData } from "../types.js" - -/** - * Extract structured ToolData from parsed tool JSON - * This provides rich data for tool-specific renderers - */ -export function extractToolData(toolInfo: Record): ToolData { - const toolName = (toolInfo.tool as string) || "unknown" - - // Base tool data with common fields - const toolData: ToolData = { - tool: toolName, - path: toolInfo.path as string | undefined, - isOutsideWorkspace: toolInfo.isOutsideWorkspace as boolean | undefined, - isProtected: toolInfo.isProtected as boolean | undefined, - content: toolInfo.content as string | undefined, - reason: toolInfo.reason as string | undefined, - } - - // Extract diff-related fields - if (toolInfo.diff !== undefined) { - toolData.diff = toolInfo.diff as string - } - if (toolInfo.diffStats !== undefined) { - const stats = toolInfo.diffStats as { added?: number; removed?: number } - if (typeof stats.added === "number" && typeof stats.removed === "number") { - toolData.diffStats = { added: stats.added, removed: stats.removed } - } - } - - // Extract search-related fields - if (toolInfo.regex !== undefined) { - toolData.regex = toolInfo.regex as string - } - if (toolInfo.filePattern !== undefined) { - toolData.filePattern = toolInfo.filePattern as string - } - if (toolInfo.query !== undefined) { - toolData.query = toolInfo.query as string - } - - // Extract mode-related fields - if (toolInfo.mode !== undefined) { - toolData.mode = toolInfo.mode as string - } - if (toolInfo.mode_slug !== undefined) { - toolData.mode = toolInfo.mode_slug as string - } - - // Extract command-related fields - if (toolInfo.command !== undefined) { - toolData.command = toolInfo.command as string - } - if (toolInfo.output !== undefined) { - toolData.output = toolInfo.output as string - } - - // Extract browser-related fields - if (toolInfo.action !== undefined) { - toolData.action = toolInfo.action as string - } - if (toolInfo.url !== undefined) { - toolData.url = toolInfo.url as string - } - if (toolInfo.coordinate !== undefined) { - toolData.coordinate = toolInfo.coordinate as string - } - - // Extract batch file operations - if (Array.isArray(toolInfo.files)) { - toolData.batchFiles = (toolInfo.files as Array>).map((f) => ({ - path: (f.path as string) || "", - lineSnippet: f.lineSnippet as string | undefined, - isOutsideWorkspace: f.isOutsideWorkspace as boolean | undefined, - key: f.key as string | undefined, - content: f.content as string | undefined, - })) - } - - // Extract batch diff operations - if (Array.isArray(toolInfo.batchDiffs)) { - toolData.batchDiffs = (toolInfo.batchDiffs as Array>).map((d) => ({ - path: (d.path as string) || "", - changeCount: d.changeCount as number | undefined, - key: d.key as string | undefined, - content: d.content as string | undefined, - diffStats: d.diffStats as { added: number; removed: number } | undefined, - diffs: d.diffs as Array<{ content: string; startLine?: number }> | undefined, - })) - } - - // Extract question/completion fields - if (toolInfo.question !== undefined) { - toolData.question = toolInfo.question as string - } - if (toolInfo.result !== undefined) { - toolData.result = toolInfo.result as string - } - - // Extract additional display hints - if (toolInfo.lineNumber !== undefined) { - toolData.lineNumber = toolInfo.lineNumber as number - } - if (toolInfo.additionalFileCount !== undefined) { - toolData.additionalFileCount = toolInfo.additionalFileCount as number - } - - return toolData -} - -/** - * Format tool output for display (used in the message body, header shows tool name separately) - */ -export function formatToolOutput(toolInfo: Record): string { - const toolName = (toolInfo.tool as string) || "unknown" - - switch (toolName) { - case "switchMode": { - const mode = (toolInfo.mode as string) || "unknown" - const reason = toolInfo.reason as string - return `→ ${mode} mode${reason ? `\n ${reason}` : ""}` - } - - case "switch_mode": { - const mode = (toolInfo.mode_slug as string) || (toolInfo.mode as string) || "unknown" - const reason = toolInfo.reason as string - return `→ ${mode} mode${reason ? `\n ${reason}` : ""}` - } - - case "execute_command": { - const command = toolInfo.command as string - return `$ ${command || "(no command)"}` - } - - case "read_file": { - const files = toolInfo.files as Array<{ path: string }> | undefined - const path = toolInfo.path as string - if (files && files.length > 0) { - return files.map((f) => `📄 ${f.path}`).join("\n") - } - return `📄 ${path || "(no path)"}` - } - - case "write_to_file": { - const writePath = toolInfo.path as string - return `📝 ${writePath || "(no path)"}` - } - - case "apply_diff": { - const diffPath = toolInfo.path as string - return `✏️ ${diffPath || "(no path)"}` - } - - case "search_files": { - const searchPath = toolInfo.path as string - const regex = toolInfo.regex as string - return `🔍 "${regex}" in ${searchPath || "."}` - } - - case "list_files": { - const listPath = toolInfo.path as string - const recursive = toolInfo.recursive as boolean - return `📁 ${listPath || "."}${recursive ? " (recursive)" : ""}` - } - - case "browser_action": { - const action = toolInfo.action as string - const url = toolInfo.url as string - return `🌐 ${action || "action"}${url ? `: ${url}` : ""}` - } - - case "attempt_completion": { - const result = toolInfo.result as string - if (result) { - const truncated = result.length > 100 ? result.substring(0, 100) + "..." : result - return `✅ ${truncated}` - } - return "✅ Task completed" - } - - case "ask_followup_question": { - const question = toolInfo.question as string - return `❓ ${question || "(no question)"}` - } - - case "new_task": { - const taskMode = toolInfo.mode as string - return `📋 Creating subtask${taskMode ? ` in ${taskMode} mode` : ""}` - } - - case "update_todo_list": - case "updateTodoList": { - // Special marker - actual rendering is handled by TodoChangeDisplay component - return "☑ TODO list updated" - } - - default: { - const params = Object.entries(toolInfo) - .filter(([key]) => key !== "tool") - .map(([key, value]) => { - const displayValue = typeof value === "string" ? value : JSON.stringify(value) - const truncated = displayValue.length > 100 ? displayValue.substring(0, 100) + "..." : displayValue - return `${key}: ${truncated}` - }) - .join("\n") - return params || "(no parameters)" - } - } -} - -/** - * Format tool ask message for user approval prompt - */ -export function formatToolAskMessage(toolInfo: Record): string { - const toolName = (toolInfo.tool as string) || "unknown" - - switch (toolName) { - case "switchMode": - case "switch_mode": { - const mode = (toolInfo.mode as string) || (toolInfo.mode_slug as string) || "unknown" - const reason = toolInfo.reason as string - return `Switch to ${mode} mode?${reason ? `\nReason: ${reason}` : ""}` - } - - case "execute_command": { - const command = toolInfo.command as string - return `Run command?\n$ ${command || "(no command)"}` - } - - case "read_file": { - const files = toolInfo.files as Array<{ path: string }> | undefined - const path = toolInfo.path as string - if (files && files.length > 0) { - return `Read ${files.length} file(s)?\n${files.map((f) => ` ${f.path}`).join("\n")}` - } - return `Read file: ${path || "(no path)"}` - } - - case "write_to_file": { - const writePath = toolInfo.path as string - return `Write to file: ${writePath || "(no path)"}` - } - - case "apply_diff": { - const diffPath = toolInfo.path as string - return `Apply changes to: ${diffPath || "(no path)"}` - } - - case "browser_action": { - const action = toolInfo.action as string - const url = toolInfo.url as string - return `Browser: ${action || "action"}${url ? ` - ${url}` : ""}` - } - - default: { - const params = Object.entries(toolInfo) - .filter(([key]) => key !== "tool") - .map(([key, value]) => { - const displayValue = typeof value === "string" ? value : JSON.stringify(value) - const truncated = displayValue.length > 80 ? displayValue.substring(0, 80) + "..." : displayValue - return ` ${key}: ${truncated}` - }) - .join("\n") - return `${toolName}${params ? `\n${params}` : ""}` - } - } -} - -/** - * Parse TODO items from tool info - * Handles both array format and markdown checklist string format - */ -export function parseTodosFromToolInfo(toolInfo: Record): TodoItem[] | null { - // Try to get todos directly as an array - const todosArray = toolInfo.todos as unknown[] | undefined - if (Array.isArray(todosArray)) { - return todosArray - .map((item, index) => { - if (typeof item === "object" && item !== null) { - const todo = item as Record - return { - id: (todo.id as string) || `todo-${index}`, - content: (todo.content as string) || "", - status: ((todo.status as string) || "pending") as TodoItem["status"], - } - } - return null - }) - .filter((item): item is TodoItem => item !== null) - } - - // Try to parse markdown checklist format from todos string - const todosString = toolInfo.todos as string | undefined - if (typeof todosString === "string") { - return parseMarkdownChecklist(todosString) - } - - return null -} - -/** - * Parse a markdown checklist string into TodoItem array - * Format: - * [ ] pending item - * [-] in progress item - * [x] completed item - */ -export function parseMarkdownChecklist(markdown: string): TodoItem[] { - const lines = markdown.split("\n") - const todos: TodoItem[] = [] - - for (let i = 0; i < lines.length; i++) { - const line = lines[i] - - if (!line) { - continue - } - - const trimmedLine = line.trim() - - if (!trimmedLine) { - continue - } - - // Match markdown checkbox patterns - const checkboxMatch = trimmedLine.match(/^\[([x\-\s])\]\s*(.+)$/i) - - if (checkboxMatch) { - const statusChar = checkboxMatch[1] ?? " " - const content = checkboxMatch[2] ?? "" - let status: TodoItem["status"] = "pending" - - if (statusChar.toLowerCase() === "x") { - status = "completed" - } else if (statusChar === "-") { - status = "in_progress" - } - - todos.push({ id: `todo-${i}`, content: content.trim(), status }) - } - } - - return todos -} diff --git a/apps/cli/src/ui/utils/views.ts b/apps/cli/src/ui/utils/views.ts deleted file mode 100644 index 0e2ea07c8b4..00000000000 --- a/apps/cli/src/ui/utils/views.ts +++ /dev/null @@ -1,52 +0,0 @@ -import type { TUIMessage, PendingAsk, View } from "../types.js" - -/** - * Determine the current view state based on messages and pending asks - */ -export function getView(messages: TUIMessage[], pendingAsk: PendingAsk | null, isLoading: boolean): View { - // If there's a pending ask requiring text input, show input - if (pendingAsk?.type === "followup") { - return "UserInput" - } - - // If there's any pending ask (approval), don't show thinking - if (pendingAsk) { - return "UserInput" - } - - // Initial state or empty - awaiting user input - if (messages.length === 0) { - return "UserInput" - } - - const lastMessage = messages.at(-1) - if (!lastMessage) { - return "UserInput" - } - - // User just sent a message, waiting for response - if (lastMessage.role === "user") { - return "AgentResponse" - } - - // Assistant replied - if (lastMessage.role === "assistant") { - if (lastMessage.hasPendingToolCalls) { - return "ToolUse" - } - - // If loading, still waiting for more - if (isLoading) { - return "AgentResponse" - } - - return "UserInput" - } - - // Tool result received, waiting for next assistant response - if (lastMessage.role === "tool") { - return "AgentResponse" - } - - return "Default" -} diff --git a/apps/cli/tsconfig.json b/apps/cli/tsconfig.json deleted file mode 100644 index c4f8a15a490..00000000000 --- a/apps/cli/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "@roo-code/config-typescript/base.json", - "compilerOptions": { - "types": ["vitest/globals"], - "outDir": "dist", - "jsx": "react-jsx", - "jsxImportSource": "react", - "baseUrl": ".", - "paths": { - "@/*": ["src/*"] - } - }, - "include": ["src", "*.config.ts"], - "exclude": ["node_modules"] -} diff --git a/apps/cli/tsup.config.ts b/apps/cli/tsup.config.ts deleted file mode 100644 index eff2c14e2c9..00000000000 --- a/apps/cli/tsup.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { defineConfig } from "tsup" - -export default defineConfig({ - entry: ["src/index.ts"], - format: ["esm"], - dts: true, - clean: true, - sourcemap: true, - target: "node20", - platform: "node", - banner: { - js: "#!/usr/bin/env node", - }, - // Bundle workspace packages that export TypeScript - noExternal: ["@roo-code/core", "@roo-code/core/cli", "@roo-code/types", "@roo-code/vscode-shim"], - external: [ - // Keep native modules external - "@anthropic-ai/sdk", - "@anthropic-ai/bedrock-sdk", - "@anthropic-ai/vertex-sdk", - // Keep @vscode/ripgrep external - we bundle the binary separately - "@vscode/ripgrep", - // Optional dev dependency of ink - not needed at runtime - "react-devtools-core", - ], - esbuildOptions(options) { - // Enable JSX for React/Ink components - options.jsx = "automatic" - options.jsxImportSource = "react" - }, -}) diff --git a/apps/cli/vitest.config.ts b/apps/cli/vitest.config.ts deleted file mode 100644 index 5b6e725d8c6..00000000000 --- a/apps/cli/vitest.config.ts +++ /dev/null @@ -1,17 +0,0 @@ -import path from "path" -import { defineConfig } from "vitest/config" - -export default defineConfig({ - resolve: { - alias: { - "@": path.resolve(__dirname, "src"), - }, - }, - test: { - globals: true, - environment: "node", - watch: false, - testTimeout: 120_000, // 2m for integration tests. - include: ["src/**/*.test.ts", "src/**/*.test.tsx"], - }, -}) diff --git a/apps/vscode-e2e/package.json b/apps/vscode-e2e/package.json index 900ac6d753c..d366f72a2d3 100644 --- a/apps/vscode-e2e/package.json +++ b/apps/vscode-e2e/package.json @@ -20,6 +20,7 @@ "@vscode/test-electron": "^2.4.0", "glob": "^11.1.0", "mocha": "^11.1.0", - "rimraf": "^6.0.1" + "rimraf": "^6.0.1", + "typescript": "5.8.3" } } diff --git a/apps/vscode-e2e/src/suite/extension.test.ts b/apps/vscode-e2e/src/suite/extension.test.ts index c5340a882d6..5d59e003eff 100644 --- a/apps/vscode-e2e/src/suite/extension.test.ts +++ b/apps/vscode-e2e/src/suite/extension.test.ts @@ -19,6 +19,10 @@ suite("Roo Code Extension", function () { "openInNewTab", "settingsButtonClicked", "historyButtonClicked", + "showHumanRelayDialog", + "registerHumanRelayCallback", + "unregisterHumanRelayCallback", + "handleHumanRelayResponse", "newTask", "setCustomStoragePath", "focusInput", diff --git a/apps/vscode-e2e/src/suite/modes.test.ts b/apps/vscode-e2e/src/suite/modes.test.ts index 3c9d9a2418e..7982f3cf22b 100644 --- a/apps/vscode-e2e/src/suite/modes.test.ts +++ b/apps/vscode-e2e/src/suite/modes.test.ts @@ -15,13 +15,15 @@ suite("Roo Code Modes", function () { const switchModesTaskId = await globalThis.api.startNewTask({ configuration: { mode: "code", alwaysAllowModeSwitch: true, autoApprovalEnabled: true }, - text: "Use the `switch_mode` tool to switch to ask mode.", + text: "For each of `architect`, `ask`, and `debug` use the `switch_mode` tool to switch to that mode.", }) await waitUntilCompleted({ api: globalThis.api, taskId: switchModesTaskId }) await globalThis.api.cancelCurrentTask() + assert.ok(modes.includes("architect")) assert.ok(modes.includes("ask")) - assert.ok(modes.length === 1) + assert.ok(modes.includes("debug")) + assert.ok(modes.length === 3) }) }) diff --git a/apps/web-evals/package.json b/apps/web-evals/package.json index 9ba2c98c2c9..b2ac0d43460 100644 --- a/apps/web-evals/package.json +++ b/apps/web-evals/package.json @@ -35,7 +35,7 @@ "cmdk": "^1.1.0", "fuzzysort": "^3.1.0", "lucide-react": "^0.518.0", - "next": "~15.2.8", + "next": "~15.2.6", "next-themes": "^0.4.6", "p-map": "^7.0.3", "react": "^18.3.1", diff --git a/apps/web-evals/src/actions/runs.ts b/apps/web-evals/src/actions/runs.ts index f0c1578aed1..a3fb3feccc8 100644 --- a/apps/web-evals/src/actions/runs.ts +++ b/apps/web-evals/src/actions/runs.ts @@ -13,9 +13,6 @@ import { exerciseLanguages, createRun as _createRun, deleteRun as _deleteRun, - updateRun as _updateRun, - getIncompleteRuns as _getIncompleteRuns, - deleteRunsByIds as _deleteRunsByIds, createTask, getExercisesForLanguage, } from "@roo-code/evals" @@ -23,23 +20,12 @@ import { import { CreateRun } from "@/lib/schemas" import { redisClient } from "@/lib/server/redis" -// Storage base path for eval logs -const EVALS_STORAGE_PATH = "/tmp/evals/runs" - const EVALS_REPO_PATH = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../../../evals") -export async function createRun({ - suite, - exercises = [], - timeout, - iterations = 1, - executionMethod = "vscode", - ...values -}: CreateRun) { +export async function createRun({ suite, exercises = [], timeout, iterations = 1, ...values }: CreateRun) { const run = await _createRun({ ...values, timeout, - executionMethod, socketPath: "", // TODO: Get rid of this. }) @@ -228,150 +214,3 @@ export async function killRun(runId: number): Promise { errors, } } - -export type DeleteIncompleteRunsResult = { - success: boolean - deletedCount: number - deletedRunIds: number[] - storageErrors: string[] -} - -/** - * Delete all incomplete runs (runs without a taskMetricsId/final score). - * Removes both database records and storage folders. - */ -export async function deleteIncompleteRuns(): Promise { - const storageErrors: string[] = [] - - // Get all incomplete runs - const incompleteRuns = await _getIncompleteRuns() - const runIds = incompleteRuns.map((run) => run.id) - - if (runIds.length === 0) { - return { - success: true, - deletedCount: 0, - deletedRunIds: [], - storageErrors: [], - } - } - - // Delete storage folders for each run - for (const runId of runIds) { - const storagePath = path.join(EVALS_STORAGE_PATH, String(runId)) - try { - if (fs.existsSync(storagePath)) { - fs.rmSync(storagePath, { recursive: true, force: true }) - console.log(`Deleted storage folder: ${storagePath}`) - } - } catch (error) { - console.error(`Failed to delete storage folder ${storagePath}:`, error) - storageErrors.push(`Failed to delete storage for run ${runId}`) - } - - // Also try to clear Redis state for any potentially running incomplete runs - try { - const redis = await redisClient() - await redis.del(`heartbeat:${runId}`) - await redis.del(`runners:${runId}`) - } catch (error) { - // Non-critical error, just log it - console.error(`Failed to clear Redis state for run ${runId}:`, error) - } - } - - // Delete from database - await _deleteRunsByIds(runIds) - - revalidatePath("/runs") - - return { - success: true, - deletedCount: runIds.length, - deletedRunIds: runIds, - storageErrors, - } -} - -/** - * Get count of incomplete runs (for UI display) - */ -export async function getIncompleteRunsCount(): Promise { - const incompleteRuns = await _getIncompleteRuns() - return incompleteRuns.length -} - -/** - * Delete all runs older than 30 days. - * Removes both database records and storage folders. - */ -export async function deleteOldRuns(): Promise { - const storageErrors: string[] = [] - - // Get all runs older than 30 days - const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) - const { getRuns } = await import("@roo-code/evals") - const allRuns = await getRuns() - const oldRuns = allRuns.filter((run) => run.createdAt < thirtyDaysAgo) - const runIds = oldRuns.map((run) => run.id) - - if (runIds.length === 0) { - return { - success: true, - deletedCount: 0, - deletedRunIds: [], - storageErrors: [], - } - } - - // Delete storage folders for each run - for (const runId of runIds) { - const storagePath = path.join(EVALS_STORAGE_PATH, String(runId)) - try { - if (fs.existsSync(storagePath)) { - fs.rmSync(storagePath, { recursive: true, force: true }) - console.log(`Deleted storage folder: ${storagePath}`) - } - } catch (error) { - console.error(`Failed to delete storage folder ${storagePath}:`, error) - storageErrors.push(`Failed to delete storage for run ${runId}`) - } - - // Also try to clear Redis state - try { - const redis = await redisClient() - await redis.del(`heartbeat:${runId}`) - await redis.del(`runners:${runId}`) - } catch (error) { - // Non-critical error, just log it - console.error(`Failed to clear Redis state for run ${runId}:`, error) - } - } - - // Delete from database - await _deleteRunsByIds(runIds) - - revalidatePath("/runs") - - return { - success: true, - deletedCount: runIds.length, - deletedRunIds: runIds, - storageErrors, - } -} - -/** - * Update the description of a run. - */ -export async function updateRunDescription(runId: number, description: string | null): Promise<{ success: boolean }> { - try { - await _updateRun(runId, { description }) - revalidatePath("/runs") - revalidatePath(`/runs/${runId}`) - return { success: true } - } catch (error) { - console.error("Failed to update run description:", error) - return { success: false } - } -} diff --git a/apps/web-evals/src/app/api/runs/[id]/logs/failed/route.ts b/apps/web-evals/src/app/api/runs/[id]/logs/failed/route.ts index 8b2760df987..f8c6cec06be 100644 --- a/apps/web-evals/src/app/api/runs/[id]/logs/failed/route.ts +++ b/apps/web-evals/src/app/api/runs/[id]/logs/failed/route.ts @@ -61,7 +61,7 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{ archive.on("error", reject) }) - // Add each failed task's log file and history files to the archive + // Add each failed task's log file to the archive const logDir = path.join(LOG_BASE_PATH, String(runId)) let filesAdded = 0 @@ -69,36 +69,18 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{ // Sanitize language and exercise to prevent path traversal const safeLanguage = sanitizePathComponent(task.language) const safeExercise = sanitizePathComponent(task.exercise) - const expectedBase = path.resolve(LOG_BASE_PATH) - - // Add the log file const logFileName = `${safeLanguage}-${safeExercise}.log` const logFilePath = path.join(logDir, logFileName) // Verify the resolved path is within the expected directory (defense in depth) - const resolvedLogPath = path.resolve(logFilePath) - if (resolvedLogPath.startsWith(expectedBase) && fs.existsSync(logFilePath)) { - archive.file(logFilePath, { name: logFileName }) - filesAdded++ - } - - // Add the API conversation history file - // Format: {language}-{exercise}.{iteration}_api_conversation_history.json - const apiHistoryFileName = `${safeLanguage}-${safeExercise}.${task.iteration}_api_conversation_history.json` - const apiHistoryFilePath = path.join(logDir, apiHistoryFileName) - const resolvedApiHistoryPath = path.resolve(apiHistoryFilePath) - if (resolvedApiHistoryPath.startsWith(expectedBase) && fs.existsSync(apiHistoryFilePath)) { - archive.file(apiHistoryFilePath, { name: apiHistoryFileName }) - filesAdded++ + const resolvedPath = path.resolve(logFilePath) + const expectedBase = path.resolve(LOG_BASE_PATH) + if (!resolvedPath.startsWith(expectedBase)) { + continue // Skip files with suspicious paths } - // Add the UI messages file - // Format: {language}-{exercise}.{iteration}_ui_messages.json - const uiMessagesFileName = `${safeLanguage}-${safeExercise}.${task.iteration}_ui_messages.json` - const uiMessagesFilePath = path.join(logDir, uiMessagesFileName) - const resolvedUiMessagesPath = path.resolve(uiMessagesFilePath) - if (resolvedUiMessagesPath.startsWith(expectedBase) && fs.existsSync(uiMessagesFilePath)) { - archive.file(uiMessagesFilePath, { name: uiMessagesFileName }) + if (fs.existsSync(logFilePath)) { + archive.file(logFilePath, { name: logFileName }) filesAdded++ } } diff --git a/apps/web-evals/src/app/runs/[id]/run.tsx b/apps/web-evals/src/app/runs/[id]/run.tsx index badd77741e0..a4b39100245 100644 --- a/apps/web-evals/src/app/runs/[id]/run.tsx +++ b/apps/web-evals/src/app/runs/[id]/run.tsx @@ -1,8 +1,8 @@ "use client" -import { useMemo, useState, useCallback, useEffect, Fragment } from "react" +import { useMemo, useState, useCallback, useEffect } from "react" import { toast } from "sonner" -import { LoaderCircle, FileText, Copy, Check, StopCircle, List, Layers } from "lucide-react" +import { LoaderCircle, FileText, Copy, Check, StopCircle } from "lucide-react" import type { Run, TaskMetrics as _TaskMetrics, Task } from "@roo-code/evals" import type { ToolName } from "@roo-code/types" @@ -41,9 +41,6 @@ import { RunStatus } from "./run-status" type TaskMetrics = Pick<_TaskMetrics, "tokensIn" | "tokensOut" | "tokensContext" | "duration" | "cost"> -// Extended Task type with taskMetrics from useRunStatus -type TaskWithMetrics = Task & { taskMetrics: _TaskMetrics | null } - type ToolUsageEntry = { attempts: number; failures: number } type ToolUsage = Record @@ -245,7 +242,7 @@ function formatLogContent(log: string): React.ReactNode[] { export function Run({ run }: { run: Run }) { const runStatus = useRunStatus(run) - const { tasks, tokenUsage, toolUsage, usageUpdatedAt, heartbeat, runners } = runStatus + const { tasks, tokenUsage, usageUpdatedAt, heartbeat, runners } = runStatus const [selectedTask, setSelectedTask] = useState(null) const [taskLog, setTaskLog] = useState(null) @@ -253,19 +250,6 @@ export function Run({ run }: { run: Run }) { const [copied, setCopied] = useState(false) const [showKillDialog, setShowKillDialog] = useState(false) const [isKilling, setIsKilling] = useState(false) - const [groupByStatus, setGroupByStatus] = useState(() => { - // Initialize from localStorage if available (client-side only) - if (typeof window !== "undefined") { - const stored = localStorage.getItem("evals-group-by-status") - return stored === "true" - } - return false - }) - - // Persist groupByStatus to localStorage - useEffect(() => { - localStorage.setItem("evals-group-by-status", String(groupByStatus)) - }, [groupByStatus]) // Determine if run is still active (has heartbeat or runners) const isRunActive = !run.taskMetricsId && (!!heartbeat || (runners && runners.length > 0)) @@ -316,91 +300,10 @@ export function Run({ run }: { run: Run }) { return () => document.removeEventListener("keydown", handleKeyDown) }, [selectedTask]) - const taskMetrics: Record = useMemo(() => { - // Reference usageUpdatedAt to trigger recomputation when Map contents change - void usageUpdatedAt - const metrics: Record = {} - - // Helper to calculate duration from database timestamps when streaming duration - // is unavailable (e.g., page was loaded after TaskStarted event was published) - const calculateDurationFromTimestamps = (task: TaskWithMetrics): number => { - if (!task.startedAt) return 0 - const startTime = new Date(task.startedAt).getTime() - const endTime = task.finishedAt ? new Date(task.finishedAt).getTime() : Date.now() - return endTime - startTime - } - - tasks?.forEach((task) => { - const streamingUsage = tokenUsage.get(task.id) - const dbMetrics = task.taskMetrics - - // For finished tasks, prefer DB values but fall back to streaming values - // This handles race conditions during timeout where DB might not have latest data - if (task.finishedAt) { - // Check if DB metrics have meaningful values (not just default/empty) - const dbHasData = dbMetrics && (dbMetrics.tokensIn > 0 || dbMetrics.tokensOut > 0 || dbMetrics.cost > 0) - if (dbHasData) { - // If DB duration is 0 but we have timestamps, calculate from timestamps - const duration = dbMetrics.duration || calculateDurationFromTimestamps(task) - metrics[task.id] = { ...dbMetrics, duration } - } else if (streamingUsage) { - // Fall back to streaming values if DB is empty/stale - // Use streaming duration, or calculate from timestamps if not available - const duration = streamingUsage.duration || calculateDurationFromTimestamps(task) - metrics[task.id] = { - tokensIn: streamingUsage.totalTokensIn, - tokensOut: streamingUsage.totalTokensOut, - tokensContext: streamingUsage.contextTokens, - duration, - cost: streamingUsage.totalCost, - } - } else { - // Task finished but no DB metrics and no streaming data - // (e.g., page loaded after task completed, metrics not persisted) - // Still provide duration calculated from timestamps - metrics[task.id] = { - tokensIn: 0, - tokensOut: 0, - tokensContext: 0, - duration: calculateDurationFromTimestamps(task), - cost: 0, - } - } - } else if (streamingUsage) { - // For running tasks, use streaming values - // Use streaming duration, or calculate from task.startedAt if not available - // (happens when page loads after TaskStarted event was already published) - const duration = streamingUsage.duration || calculateDurationFromTimestamps(task) - metrics[task.id] = { - tokensIn: streamingUsage.totalTokensIn, - tokensOut: streamingUsage.totalTokensOut, - tokensContext: streamingUsage.contextTokens, - duration, - cost: streamingUsage.totalCost, - } - } else if (task.startedAt) { - // Task has started (has startedAt in DB) but no streaming data yet - // This can happen when page loads after TaskStarted but before TokenUsageUpdated - metrics[task.id] = { - tokensIn: 0, - tokensOut: 0, - tokensContext: 0, - duration: calculateDurationFromTimestamps(task), - cost: 0, - } - } - }) - - return metrics - }, [tasks, tokenUsage, usageUpdatedAt]) - const onViewTaskLog = useCallback( async (task: Task) => { - // Only allow viewing logs for tasks that have started. - // Note: we treat presence of derived metrics as evidence of a started task, - // since this page may be rendered without streaming `tokenUsage` populated. - const hasStarted = !!task.startedAt || !!tokenUsage.get(task.id) || !!taskMetrics[task.id] - if (!hasStarted) { + // Only allow viewing logs for tasks that have started + if (!task.startedAt && !tokenUsage.get(task.id)) { toast.error("Task has not started yet") return } @@ -429,33 +332,41 @@ export function Run({ run }: { run: Run }) { setIsLoadingLog(false) } }, - [run.id, tokenUsage, taskMetrics], + [run.id, tokenUsage], ) + const taskMetrics: Record = useMemo(() => { + const metrics: Record = {} + + tasks?.forEach((task) => { + const usage = tokenUsage.get(task.id) + + if (task.finishedAt && task.taskMetrics) { + metrics[task.id] = task.taskMetrics + } else if (usage) { + metrics[task.id] = { + tokensIn: usage.totalTokensIn, + tokensOut: usage.totalTokensOut, + tokensContext: usage.contextTokens, + duration: usage.duration ?? 0, + cost: usage.totalCost, + } + } + }) + + return metrics + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [tasks, tokenUsage, usageUpdatedAt]) + // Collect all unique tool names from all tasks and sort by total attempts const toolColumns = useMemo(() => { - // Reference usageUpdatedAt to trigger recomputation when Map contents change - void usageUpdatedAt if (!tasks) return [] const toolTotals = new Map() for (const task of tasks) { - // Get both DB and streaming values - const dbToolUsage = task.taskMetrics?.toolUsage - const streamingToolUsage = toolUsage.get(task.id) - - // For finished tasks, prefer DB values but fall back to streaming values - // For running tasks, use streaming values - // This handles race conditions during timeout where DB might not have latest data - const taskToolUsage = task.finishedAt - ? dbToolUsage && Object.keys(dbToolUsage).length > 0 - ? dbToolUsage - : streamingToolUsage - : streamingToolUsage - - if (taskToolUsage) { - for (const [toolName, usage] of Object.entries(taskToolUsage)) { + if (task.taskMetrics?.toolUsage) { + for (const [toolName, usage] of Object.entries(task.taskMetrics.toolUsage)) { const tool = toolName as ToolName const current = toolTotals.get(tool) ?? 0 toolTotals.set(tool, current + usage.attempts) @@ -467,13 +378,10 @@ export function Run({ run }: { run: Run }) { return Array.from(toolTotals.entries()) .sort((a, b) => b[1] - a[1]) .map(([name]): ToolName => name) - // toolUsage ref is stable; usageUpdatedAt triggers recomputation when Map contents change - }, [tasks, toolUsage, usageUpdatedAt]) + }, [tasks]) // Compute aggregate stats const stats = useMemo(() => { - // Reference usageUpdatedAt to trigger recomputation when Map contents change - void usageUpdatedAt if (!tasks) return null const passed = tasks.filter((t) => t.passed === true).length @@ -485,8 +393,8 @@ export function Run({ run }: { run: Run }) { let totalCost = 0 let totalDuration = 0 - // Aggregate tool usage from all tasks (both finished and running) - const toolUsageAggregate: ToolUsage = {} + // Aggregate tool usage from completed tasks + const toolUsage: ToolUsage = {} for (const task of tasks) { const metrics = taskMetrics[task.id] @@ -497,49 +405,35 @@ export function Run({ run }: { run: Run }) { totalDuration += metrics.duration } - // Aggregate tool usage: prefer DB values for finished tasks, fall back to streaming values - // This handles race conditions during timeout where DB might not have latest data - const dbToolUsage = task.taskMetrics?.toolUsage - const streamingToolUsage = toolUsage.get(task.id) - const taskToolUsage = task.finishedAt - ? dbToolUsage && Object.keys(dbToolUsage).length > 0 - ? dbToolUsage - : streamingToolUsage - : streamingToolUsage - - if (taskToolUsage) { - for (const [key, usage] of Object.entries(taskToolUsage)) { + // Aggregate tool usage from finished tasks with taskMetrics + if (task.finishedAt && task.taskMetrics?.toolUsage) { + for (const [key, usage] of Object.entries(task.taskMetrics.toolUsage)) { const tool = key as keyof ToolUsage - if (!toolUsageAggregate[tool]) { - toolUsageAggregate[tool] = { attempts: 0, failures: 0 } + if (!toolUsage[tool]) { + toolUsage[tool] = { attempts: 0, failures: 0 } } - toolUsageAggregate[tool].attempts += usage.attempts - toolUsageAggregate[tool].failures += usage.failures + toolUsage[tool].attempts += usage.attempts + toolUsage[tool].failures += usage.failures } } } - const remaining = tasks.length - completed - return { passed, failed, completed, - remaining, passRate: completed > 0 ? ((passed / completed) * 100).toFixed(1) : null, totalTokensIn, totalTokensOut, totalCost, totalDuration, - toolUsage: toolUsageAggregate, + toolUsage, } - // Map refs are stable; usageUpdatedAt triggers recomputation when Map contents change - }, [tasks, taskMetrics, toolUsage, usageUpdatedAt]) + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [tasks, taskMetrics, tokenUsage, usageUpdatedAt]) // Calculate elapsed time (wall-clock time from run creation to completion or now) const elapsedTime = useMemo(() => { - // Reference usageUpdatedAt to trigger recomputation for live elapsed time updates - void usageUpdatedAt if (!tasks || tasks.length === 0) return null const startTime = new Date(run.createdAt).getTime() @@ -558,401 +452,254 @@ export function Run({ run }: { run: Run }) { // If still running, use current time return Date.now() - startTime + // eslint-disable-next-line react-hooks/exhaustive-deps }, [tasks, run.createdAt, run.taskMetricsId, usageUpdatedAt]) - // Task status categories - type TaskStatusCategory = "failed" | "in_progress" | "passed" | "not_started" - - const getTaskStatusCategory = useCallback( - (task: TaskWithMetrics): TaskStatusCategory => { - if (task.passed === false) return "failed" - if (task.passed === true) return "passed" - // Check streaming data, DB metrics, or startedAt timestamp - const hasStarted = !!task.startedAt || !!tokenUsage.get(task.id) || !!taskMetrics[task.id] - if (hasStarted) return "in_progress" - return "not_started" - }, - [tokenUsage, taskMetrics], - ) - - // Group tasks by status while preserving original index - const groupedTasks = useMemo(() => { - if (!tasks || !groupByStatus) return null - - const groups: Record> = { - failed: [], - in_progress: [], - passed: [], - not_started: [], - } - - tasks.forEach((task, index) => { - const status = getTaskStatusCategory(task) - groups[status].push({ task, originalIndex: index }) - }) - - return groups - }, [tasks, groupByStatus, getTaskStatusCategory]) - - const statusLabels = useMemo( - (): Record => ({ - failed: { label: "Failed", className: "text-red-500", count: groupedTasks?.failed.length ?? 0 }, - in_progress: { - label: "In Progress", - className: "text-yellow-500", - count: groupedTasks?.in_progress.length ?? 0, - }, - passed: { label: "Passed", className: "text-green-500", count: groupedTasks?.passed.length ?? 0 }, - not_started: { - label: "Not Started", - className: "text-muted-foreground", - count: groupedTasks?.not_started.length ?? 0, - }, - }), - [groupedTasks], - ) - - const statusOrder: TaskStatusCategory[] = ["failed", "in_progress", "passed", "not_started"] - - // Helper to render a task row - const renderTaskRow = (task: TaskWithMetrics, originalIndex: number) => { - const hasStarted = !!task.startedAt || !!tokenUsage.get(task.id) || !!taskMetrics[task.id] - return ( - hasStarted && onViewTaskLog(task)}> - - {originalIndex + 1} - - -
- -
- - {task.language}/{task.exercise} - {task.iteration > 1 && ( - (#{task.iteration}) - )} - - {hasStarted && ( + return ( + <> +
+ {stats && ( +
+ {/* Provider, Model title and status */} +
+ {run.settings?.apiProvider && ( + {run.settings.apiProvider} + )} +
{run.model}
+ + {run.description && ( + - {run.description} + )} + {isRunActive && ( - + - Click to view log + Stop all containers for this run )}
-
- - {taskMetrics[task.id] ? ( - <> - -
-
{formatTokens(taskMetrics[task.id]!.tokensIn)}
/ -
{formatTokens(taskMetrics[task.id]!.tokensOut)}
+ {/* Main Stats Row */} +
+ {/* Passed/Failed */} +
+
+ {stats.passed} + / + {stats.failed} +
+
Passed / Failed
- - - {formatTokens(taskMetrics[task.id]!.tokensContext)} - - {toolColumns.map((toolName) => { - const dbUsage = task.taskMetrics?.toolUsage?.[toolName] - const streamingUsage = toolUsage.get(task.id)?.[toolName] - const usage = task.finishedAt ? (dbUsage ?? streamingUsage) : streamingUsage - - const successRate = - usage && usage.attempts > 0 - ? ((usage.attempts - usage.failures) / usage.attempts) * 100 - : 100 - const rateColor = - successRate === 100 - ? "text-muted-foreground" - : successRate >= 80 - ? "text-yellow-500" - : "text-red-500" - return ( - - {usage ? ( -
- {usage.attempts} - {formatToolUsageSuccessRate(usage)} -
- ) : ( - - - )} -
- ) - })} - - {taskMetrics[task.id]!.duration ? formatDuration(taskMetrics[task.id]!.duration) : "-"} - - - {formatCurrency(taskMetrics[task.id]!.cost)} - - - ) : ( - - )} - - ) - } - - return ( - <> -
- {!tasks ? ( - - ) : ( - <> - {/* View Toggle */} -
- - - - - - {groupByStatus ? "Show tasks in run order" : "Group tasks by status"} - - -
- - - {stats && ( - - - {/* Provider, Model title and status */} -
- {run.settings?.apiProvider && ( - - {run.settings.apiProvider} - - )} -
{run.model}
- - {run.description && ( - - - {run.description} - - )} - {isRunActive && ( - - - - - - Stop all containers for this run - - - )} -
- {/* Main Stats Row */} -
- {/* Pass Rate / Fail Rate / Remaining % */} -
-
- - {stats.completed > 0 - ? `${((stats.passed / stats.completed) * 100).toFixed(1)}%` - : "-"} - - / - - {stats.completed > 0 - ? `${((stats.failed / stats.completed) * 100).toFixed(1)}%` - : "-"} - - / - - {tasks.length > 0 - ? `${((stats.remaining / tasks.length) * 100).toFixed(1)}%` - : "-"} - -
-
- {stats.passed} - {" / "} - {stats.failed} - {" / "} - {stats.remaining} - {" of "} - {tasks.length} -
-
- {/* Tokens */} -
-
- {formatTokens(stats.totalTokensIn)} - / - {formatTokens(stats.totalTokensOut)} -
-
Tokens In / Out
-
+ {/* Pass Rate */} +
+
= 80 + ? "text-yellow-500" + : "text-red-500" + }`}> + {stats.passRate ? `${stats.passRate}%` : "-"} +
+
Pass Rate
+
- {/* Cost */} -
-
- {formatCurrency(stats.totalCost)} -
-
Cost
-
+ {/* Tokens */} +
+
+ {formatTokens(stats.totalTokensIn)} + / + {formatTokens(stats.totalTokensOut)} +
+
Tokens In / Out
+
- {/* Duration */} -
-
- {stats.totalDuration > 0 - ? formatDuration(stats.totalDuration) - : "-"} -
-
Duration
-
+ {/* Cost */} +
+
{formatCurrency(stats.totalCost)}
+
Cost
+
- {/* Elapsed Time */} -
-
- {elapsedTime !== null ? formatDuration(elapsedTime) : "-"} -
-
Elapsed
-
+ {/* Duration */} +
+
+ {stats.totalDuration > 0 ? formatDuration(stats.totalDuration) : "-"} +
+
Duration
+
- {/* Estimated Time Remaining - only show if run is active and we have data */} - {!run.taskMetricsId && - elapsedTime !== null && - stats.completed > 0 && - stats.remaining > 0 && ( -
-
- ~ - {formatDuration( - (elapsedTime / stats.completed) * stats.remaining, - )} -
-
- Est. Remaining -
-
- )} -
+ {/* Elapsed Time */} +
+
+ {elapsedTime !== null ? formatDuration(elapsedTime) : "-"} +
+
Elapsed
+
+ - {/* Tool Usage Row */} - {Object.keys(stats.toolUsage).length > 0 && ( -
- {Object.entries(stats.toolUsage) - .sort(([, a], [, b]) => b.attempts - a.attempts) - .map(([toolName, usage]) => { - const abbr = getToolAbbreviation(toolName) - const successRate = - usage.attempts > 0 - ? ((usage.attempts - usage.failures) / - usage.attempts) * - 100 - : 100 - const rateColor = - successRate === 100 - ? "text-green-500" - : successRate >= 80 - ? "text-yellow-500" - : "text-red-500" - return ( - - -
- - {abbr} - - - {usage.attempts} - - - {formatToolUsageSuccessRate(usage)} - -
-
- - {toolName} - -
- ) - })} -
- )} -
-
- )} - - # - Exercise - Tokens In / Out - Context - {toolColumns.map((toolName) => ( - - - {getToolAbbreviation(toolName)} - {toolName} + {/* Tool Usage Row */} + {Object.keys(stats.toolUsage).length > 0 && ( +
+ {Object.entries(stats.toolUsage) + .sort(([, a], [, b]) => b.attempts - a.attempts) + .map(([toolName, usage]) => { + const abbr = getToolAbbreviation(toolName) + const successRate = + usage.attempts > 0 + ? ((usage.attempts - usage.failures) / usage.attempts) * 100 + : 100 + const rateColor = + successRate === 100 + ? "text-green-500" + : successRate >= 80 + ? "text-yellow-500" + : "text-red-500" + return ( + + +
+ + {abbr} + + {usage.attempts} + + {formatToolUsageSuccessRate(usage)} + +
+
+ {toolName}
- - ))} - Duration - Cost - - - - {groupByStatus && groupedTasks - ? // Grouped view - statusOrder.map((status) => { - const group = groupedTasks[status] - if (group.length === 0) return null - const { label, className } = statusLabels[status] - return ( - - - - - {label} ({group.length}) + ) + })} +
+ )} + + )} + {!tasks ? ( + + ) : ( +
+ + + Exercise + Tokens In / Out + Context + {toolColumns.map((toolName) => ( + + + {getToolAbbreviation(toolName)} + {toolName} + + + ))} + Duration + Cost + + + + {tasks.map((task) => { + const hasStarted = !!task.startedAt || !!tokenUsage.get(task.id) + return ( + hasStarted && onViewTaskLog(task)}> + +
+ +
+ + {task.language}/{task.exercise} + {task.iteration > 1 && ( + + (#{task.iteration}) - - - {group.map(({ task, originalIndex }) => - renderTaskRow(task, originalIndex), + )} + + {hasStarted && ( + + + + + Click to view log + )} - - ) - }) - : // Default order view - tasks.map((task, index) => renderTaskRow(task, index))} - -
- +
+
+ + {taskMetrics[task.id] ? ( + <> + +
+
{formatTokens(taskMetrics[task.id]!.tokensIn)}
/ +
{formatTokens(taskMetrics[task.id]!.tokensOut)}
+
+
+ + {formatTokens(taskMetrics[task.id]!.tokensContext)} + + {toolColumns.map((toolName) => { + const usage = task.taskMetrics?.toolUsage?.[toolName] + const successRate = + usage && usage.attempts > 0 + ? ((usage.attempts - usage.failures) / usage.attempts) * 100 + : 100 + const rateColor = + successRate === 100 + ? "text-muted-foreground" + : successRate >= 80 + ? "text-yellow-500" + : "text-red-500" + return ( + + {usage ? ( +
+ + {usage.attempts} + + + {formatToolUsageSuccessRate(usage)} + +
+ ) : ( + - + )} +
+ ) + })} + + {taskMetrics[task.id]!.duration + ? formatDuration(taskMetrics[task.id]!.duration) + : "-"} + + + {formatCurrency(taskMetrics[task.id]!.cost)} + + + ) : ( + + )} + + ) + })} + + )}
diff --git a/apps/web-evals/src/app/runs/new/new-run.tsx b/apps/web-evals/src/app/runs/new/new-run.tsx index cea15c6ddd8..561c3ceb27a 100644 --- a/apps/web-evals/src/app/runs/new/new-run.tsx +++ b/apps/web-evals/src/app/runs/new/new-run.tsx @@ -1,32 +1,22 @@ "use client" -import { useCallback, useEffect, useMemo, useRef, useState } from "react" +import { useCallback, useEffect, useMemo, useState } from "react" import { useRouter } from "next/navigation" import { z } from "zod" import { useQuery } from "@tanstack/react-query" import { useForm, FormProvider } from "react-hook-form" import { zodResolver } from "@hookform/resolvers/zod" import { toast } from "sonner" -import { - X, - Rocket, - Check, - ChevronsUpDown, - SlidersHorizontal, - Info, - Plus, - Minus, - Terminal, - MonitorPlay, -} from "lucide-react" +import { X, Rocket, Check, ChevronsUpDown, SlidersHorizontal, Info } from "lucide-react" import { - type ProviderSettings, - type GlobalSettings, globalSettingsSchema, providerSettingsSchema, - getModelId, EVALS_SETTINGS, + getModelId, + type ProviderSettings, + type GlobalSettings, + type ReasoningEffort, } from "@roo-code/types" import { createRun } from "@/actions/runs" @@ -34,7 +24,6 @@ import { getExercises } from "@/actions/exercises" import { type CreateRun, - type ExecutionMethod, createRunSchema, CONCURRENCY_MIN, CONCURRENCY_MAX, @@ -48,9 +37,6 @@ import { } from "@/lib/schemas" import { cn } from "@/lib/utils" -import { loadRooLastModelSelection, saveRooLastModelSelection } from "@/lib/roo-last-model-selection" -import { normalizeCreateRunForSubmit } from "@/lib/normalize-create-run" - import { useOpenRouterModels } from "@/hooks/use-open-router-models" import { useRooCodeCloudModels } from "@/hooks/use-roo-code-cloud-models" @@ -58,6 +44,7 @@ import { Button, Checkbox, FormControl, + FormDescription, FormField, FormItem, FormLabel, @@ -79,6 +66,11 @@ import { PopoverTrigger, Slider, Label, + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, Tooltip, TooltipContent, TooltipTrigger, @@ -92,37 +84,21 @@ type ImportedSettings = { currentApiConfigName: string } -type ModelSelection = { - id: string - model: string - popoverOpen: boolean -} - -type ConfigSelection = { - id: string - configName: string - popoverOpen: boolean -} - export function NewRun() { const router = useRouter() - const modelSelectionsByProviderRef = useRef>({}) - const modelValueByProviderRef = useRef>({}) const [provider, setModelSource] = useState<"roo" | "openrouter" | "other">("other") - const [executionMethod, setExecutionMethod] = useState("vscode") + const [modelPopoverOpen, setModelPopoverOpen] = useState(false) const [useNativeToolProtocol, setUseNativeToolProtocol] = useState(true) + const [useMultipleNativeToolCalls, setUseMultipleNativeToolCalls] = useState(false) + const [reasoningEffort, setReasoningEffort] = useState("") const [commandExecutionTimeout, setCommandExecutionTimeout] = useState(20) const [terminalShellIntegrationTimeout, setTerminalShellIntegrationTimeout] = useState(30) // seconds - const [modelSelections, setModelSelections] = useState([ - { id: crypto.randomUUID(), model: "", popoverOpen: false }, - ]) - + // State for imported settings with config selection const [importedSettings, setImportedSettings] = useState(null) - const [configSelections, setConfigSelections] = useState([ - { id: crypto.randomUUID(), configName: "", popoverOpen: false }, - ]) + const [selectedConfigName, setSelectedConfigName] = useState("") + const [configPopoverOpen, setConfigPopoverOpen] = useState(false) const openRouter = useOpenRouterModels() const rooCodeCloud = useRooCodeCloudModels() @@ -133,6 +109,7 @@ export function NewRun() { const exercises = useQuery({ queryKey: ["getExercises"], queryFn: () => getExercises() }) + // State for selected exercises (needed for language toggle buttons) const [selectedExercises, setSelectedExercises] = useState([]) const form = useForm({ @@ -147,91 +124,50 @@ export function NewRun() { timeout: TIMEOUT_DEFAULT, iterations: ITERATIONS_DEFAULT, jobToken: "", - executionMethod: "vscode", }, }) const { - register, setValue, clearErrors, watch, - getValues, formState: { isSubmitting }, } = form - const [suite, settings] = watch(["suite", "settings", "concurrency"]) - - const selectedModelIds = useMemo( - () => modelSelections.map((s) => s.model).filter((m) => m.length > 0), - [modelSelections], - ) - - const applyModelIds = useCallback( - (modelIds: string[]) => { - const unique = Array.from(new Set(modelIds.map((m) => m.trim()).filter((m) => m.length > 0))) - - if (unique.length === 0) { - setModelSelections([{ id: crypto.randomUUID(), model: "", popoverOpen: false }]) - setValue("model", "") - return - } - - setModelSelections(unique.map((model) => ({ id: crypto.randomUUID(), model, popoverOpen: false }))) - setValue("model", unique[0] ?? "") - }, - [setValue], - ) - - // Ensure the `exercises` field is registered so RHF always includes it in submit values. - useEffect(() => { - register("exercises") - }, [register]) + const [model, suite, settings] = watch(["model", "suite", "settings", "concurrency"]) // Load settings from localStorage on mount useEffect(() => { const savedConcurrency = localStorage.getItem("evals-concurrency") - if (savedConcurrency) { const parsed = parseInt(savedConcurrency, 10) - if (!isNaN(parsed) && parsed >= CONCURRENCY_MIN && parsed <= CONCURRENCY_MAX) { setValue("concurrency", parsed) } } - const savedTimeout = localStorage.getItem("evals-timeout") - if (savedTimeout) { const parsed = parseInt(savedTimeout, 10) - if (!isNaN(parsed) && parsed >= TIMEOUT_MIN && parsed <= TIMEOUT_MAX) { setValue("timeout", parsed) } } - const savedCommandTimeout = localStorage.getItem("evals-command-execution-timeout") - if (savedCommandTimeout) { const parsed = parseInt(savedCommandTimeout, 10) - if (!isNaN(parsed) && parsed >= 20 && parsed <= 60) { setCommandExecutionTimeout(parsed) } } - const savedShellTimeout = localStorage.getItem("evals-shell-integration-timeout") - if (savedShellTimeout) { const parsed = parseInt(savedShellTimeout, 10) - if (!isNaN(parsed) && parsed >= 30 && parsed <= 60) { setTerminalShellIntegrationTimeout(parsed) } } - + // Load saved exercises selection const savedSuite = localStorage.getItem("evals-suite") - if (savedSuite === "partial") { setValue("suite", "partial") const savedExercises = localStorage.getItem("evals-exercises") @@ -243,102 +179,48 @@ export function NewRun() { setValue("exercises", parsed) } } catch { - // Invalid JSON, ignore. + // Invalid JSON, ignore } } } }, [setValue]) - // Track previous provider to detect switches - const [prevProvider, setPrevProvider] = useState(provider) - - // Preserve selections per provider; avoids cross-contamination while keeping UX stable. - useEffect(() => { - if (provider === prevProvider) return - - modelSelectionsByProviderRef.current[prevProvider] = modelSelections - modelValueByProviderRef.current[prevProvider] = getValues("model") - - const nextModelSelections = - modelSelectionsByProviderRef.current[provider] ?? - ([{ id: crypto.randomUUID(), model: "", popoverOpen: false }] satisfies ModelSelection[]) - - setModelSelections(nextModelSelections) - - const nextModelValue = - modelValueByProviderRef.current[provider] ?? - nextModelSelections.find((s) => s.model.trim().length > 0)?.model ?? - (provider === "other" && importedSettings && configSelections[0]?.configName - ? (getModelId(importedSettings.apiConfigs[configSelections[0].configName] ?? {}) ?? "") - : "") - - setValue("model", nextModelValue) - setPrevProvider(provider) - }, [provider, prevProvider, modelSelections, setValue, getValues, importedSettings, configSelections]) - - // When switching to Roo provider, restore last-used selection if current selection is empty - useEffect(() => { - if (provider !== "roo") return - if (selectedModelIds.length > 0) return - - const last = loadRooLastModelSelection() - if (last.length > 0) { - applyModelIds(last) - } - }, [applyModelIds, provider, selectedModelIds.length]) - - // Persist last-used Roo provider model selection - useEffect(() => { - if (provider !== "roo") return - saveRooLastModelSelection(selectedModelIds) - }, [provider, selectedModelIds]) - // Extract unique languages from exercises const languages = useMemo(() => { - if (!exercises.data) { - return [] - } - + if (!exercises.data) return [] const langs = new Set() - for (const path of exercises.data) { const lang = path.split("/")[0] - - if (lang) { - langs.add(lang) - } + if (lang) langs.add(lang) } - return Array.from(langs).sort() }, [exercises.data]) + // Get exercises for a specific language const getExercisesForLanguage = useCallback( (lang: string) => { - if (!exercises.data) { - return [] - } - + if (!exercises.data) return [] return exercises.data.filter((path) => path.startsWith(`${lang}/`)) }, [exercises.data], ) + // Toggle all exercises for a language const toggleLanguage = useCallback( (lang: string) => { const langExercises = getExercisesForLanguage(lang) const allSelected = langExercises.every((ex) => selectedExercises.includes(ex)) let newSelected: string[] - if (allSelected) { + // Remove all exercises for this language newSelected = selectedExercises.filter((ex) => !ex.startsWith(`${lang}/`)) } else { + // Add all exercises for this language (avoiding duplicates) const existing = new Set(selectedExercises) - for (const ex of langExercises) { existing.add(ex) } - newSelected = Array.from(existing) } @@ -349,6 +231,7 @@ export function NewRun() { [getExercisesForLanguage, selectedExercises, setValue], ) + // Check if all exercises for a language are selected const isLanguageSelected = useCallback( (lang: string) => { const langExercises = getExercisesForLanguage(lang) @@ -357,6 +240,7 @@ export function NewRun() { [getExercisesForLanguage, selectedExercises], ) + // Check if some (but not all) exercises for a language are selected const isLanguagePartiallySelected = useCallback( (lang: string) => { const langExercises = getExercisesForLanguage(lang) @@ -366,158 +250,83 @@ export function NewRun() { [getExercisesForLanguage, selectedExercises], ) - const addModelSelection = useCallback(() => { - setModelSelections((prev) => [...prev, { id: crypto.randomUUID(), model: "", popoverOpen: false }]) - }, []) - - const removeModelSelection = useCallback((id: string) => { - setModelSelections((prev) => prev.filter((s) => s.id !== id)) - }, []) - - const updateModelSelection = useCallback( - (id: string, model: string) => { - setModelSelections((prev) => prev.map((s) => (s.id === id ? { ...s, model, popoverOpen: false } : s))) - // Also set the form model field for validation (use first non-empty model). - setValue("model", model) - }, - [setValue], - ) - - const toggleModelPopover = useCallback((id: string, open: boolean) => { - setModelSelections((prev) => prev.map((s) => (s.id === id ? { ...s, popoverOpen: open } : s))) - }, []) - - const addConfigSelection = useCallback(() => { - setConfigSelections((prev) => [...prev, { id: crypto.randomUUID(), configName: "", popoverOpen: false }]) - }, []) - - const removeConfigSelection = useCallback((id: string) => { - setConfigSelections((prev) => prev.filter((s) => s.id !== id)) - }, []) - - const updateConfigSelection = useCallback( - (id: string, configName: string) => { - setConfigSelections((prev) => prev.map((s) => (s.id === id ? { ...s, configName, popoverOpen: false } : s))) - - // Also update the form settings for the first config (for validation). - if (importedSettings) { - const providerSettings = importedSettings.apiConfigs[configName] ?? {} - setValue("model", getModelId(providerSettings) ?? "") - setValue("settings", { ...EVALS_SETTINGS, ...providerSettings, ...importedSettings.globalSettings }) - } - }, - [importedSettings, setValue], - ) - - const toggleConfigPopover = useCallback((id: string, open: boolean) => { - setConfigSelections((prev) => prev.map((s) => (s.id === id ? { ...s, popoverOpen: open } : s))) - }, []) - const onSubmit = useCallback( async (values: CreateRun) => { try { - const baseValues = normalizeCreateRunForSubmit(values, selectedExercises, suite) - // Validate jobToken for Roo Code Cloud provider - if (provider === "roo" && !baseValues.jobToken?.trim()) { + if (provider === "roo" && !values.jobToken?.trim()) { toast.error("Roo Code Cloud Token is required") return } - const selectionsToLaunch: { model: string; configName?: string }[] = [] - - if (provider === "other") { - for (const config of configSelections) { - if (config.configName) { - selectionsToLaunch.push({ model: "", configName: config.configName }) - } - } - } else { - for (const selection of modelSelections) { - if (selection.model) { - selectionsToLaunch.push({ model: selection.model }) - } - } - } - - if (selectionsToLaunch.length === 0) { - toast.error("Please select at least one model or config") - return - } - - const totalRuns = selectionsToLaunch.length - toast.info(totalRuns > 1 ? `Launching ${totalRuns} runs (every 20 seconds)...` : "Launching run...") - - for (let i = 0; i < selectionsToLaunch.length; i++) { - const selection = selectionsToLaunch[i]! - - // Wait 20 seconds between runs (except for the first one). - if (i > 0) { - await new Promise((resolve) => setTimeout(resolve, 20_000)) + // Build experiments settings + const experimentsSettings = useMultipleNativeToolCalls + ? { experiments: { multipleNativeToolCalls: true } } + : {} + + if (provider === "openrouter") { + values.settings = { + ...(values.settings || {}), + apiProvider: "openrouter", + openRouterModelId: model, + toolProtocol: useNativeToolProtocol ? "native" : "xml", + commandExecutionTimeout, + terminalShellIntegrationTimeout: terminalShellIntegrationTimeout * 1000, // Convert to ms + ...experimentsSettings, } - - const runValues = { ...baseValues } - - if (provider === "openrouter") { - runValues.model = selection.model - runValues.settings = { - ...(runValues.settings || {}), - apiProvider: "openrouter", - openRouterModelId: selection.model, - toolProtocol: useNativeToolProtocol ? "native" : "xml", - commandExecutionTimeout, - terminalShellIntegrationTimeout: terminalShellIntegrationTimeout * 1000, - } - } else if (provider === "roo") { - runValues.model = selection.model - runValues.settings = { - ...(runValues.settings || {}), - apiProvider: "roo", - apiModelId: selection.model, - toolProtocol: useNativeToolProtocol ? "native" : "xml", - commandExecutionTimeout, - terminalShellIntegrationTimeout: terminalShellIntegrationTimeout * 1000, - } - } else if (provider === "other" && selection.configName && importedSettings) { - const providerSettings = importedSettings.apiConfigs[selection.configName] ?? {} - runValues.model = getModelId(providerSettings) ?? "" - runValues.settings = { - ...EVALS_SETTINGS, - ...providerSettings, - ...importedSettings.globalSettings, - toolProtocol: useNativeToolProtocol ? "native" : "xml", - commandExecutionTimeout, - terminalShellIntegrationTimeout: terminalShellIntegrationTimeout * 1000, - } + } else if (provider === "roo") { + values.settings = { + ...(values.settings || {}), + apiProvider: "roo", + apiModelId: model, + toolProtocol: useNativeToolProtocol ? "native" : "xml", + commandExecutionTimeout, + terminalShellIntegrationTimeout: terminalShellIntegrationTimeout * 1000, // Convert to ms + ...experimentsSettings, + ...(reasoningEffort + ? { + enableReasoningEffort: true, + reasoningEffort: reasoningEffort as ReasoningEffort, + } + : {}), } - - try { - await createRun(runValues) - toast.success(`Run ${i + 1}/${totalRuns} launched`) - } catch (e) { - toast.error(`Run ${i + 1} failed: ${e instanceof Error ? e.message : "Unknown error"}`) + } else if (provider === "other" && values.settings) { + // For imported settings, merge in experiments and tool protocol + values.settings = { + ...values.settings, + toolProtocol: useNativeToolProtocol ? "native" : "xml", + commandExecutionTimeout, + terminalShellIntegrationTimeout: terminalShellIntegrationTimeout * 1000, // Convert to ms + ...experimentsSettings, } } - router.push("/") + const { id } = await createRun(values) + router.push(`/runs/${id}`) } catch (e) { toast.error(e instanceof Error ? e.message : "An unknown error occurred.") } }, [ - suite, - selectedExercises, provider, - modelSelections, - configSelections, - importedSettings, + model, router, useNativeToolProtocol, + useMultipleNativeToolCalls, + reasoningEffort, commandExecutionTimeout, terminalShellIntegrationTimeout, ], ) + const onSelectModel = useCallback( + (model: string) => { + setValue("model", model) + setModelPopoverOpen(false) + }, + [setValue, setModelPopoverOpen], + ) + const onImportSettings = useCallback( async (event: React.ChangeEvent) => { const file = event.target.files?.[0] @@ -539,15 +348,18 @@ export function NewRun() { }) .parse(JSON.parse(await file.text())) + // Store all imported configs for user selection setImportedSettings({ apiConfigs: providerProfiles.apiConfigs, globalSettings, currentApiConfigName: providerProfiles.currentApiConfigName, }) + // Default to the current config const defaultConfigName = providerProfiles.currentApiConfigName - setConfigSelections([{ id: crypto.randomUUID(), configName: defaultConfigName, popoverOpen: false }]) + setSelectedConfigName(defaultConfigName) + // Apply the default config const providerSettings = providerProfiles.apiConfigs[defaultConfigName] ?? {} setValue("model", getModelId(providerSettings) ?? "") setValue("settings", { ...EVALS_SETTINGS, ...providerSettings, ...globalSettings }) @@ -561,6 +373,22 @@ export function NewRun() { [clearErrors, setValue], ) + const onSelectConfig = useCallback( + (configName: string) => { + if (!importedSettings) { + return + } + + setSelectedConfigName(configName) + setConfigPopoverOpen(false) + + const providerSettings = importedSettings.apiConfigs[configName] ?? {} + setValue("model", getModelId(providerSettings) ?? "") + setValue("settings", { ...EVALS_SETTINGS, ...providerSettings, ...importedSettings.globalSettings }) + }, + [importedSettings, setValue], + ) + return ( <> @@ -600,91 +428,59 @@ export function NewRun() { onChange={onImportSettings} /> - {importedSettings && Object.keys(importedSettings.apiConfigs).length > 0 && ( -
- - {configSelections.map((selection, index) => ( -
- - toggleConfigPopover(selection.id, open) - }> - - - - - - - - No config found. - - {Object.keys( - importedSettings.apiConfigs, - ).map((configName) => ( - - updateConfigSelection( - selection.id, - configName, - ) - }> - {configName} - {configName === - importedSettings.currentApiConfigName && ( - - (default) - + {importedSettings && Object.keys(importedSettings.apiConfigs).length > 1 && ( +
+ + + + + + + + + + No config found. + + {Object.keys(importedSettings.apiConfigs).map( + (configName) => ( + + {configName} + {configName === + importedSettings.currentApiConfigName && ( + + (default) + + )} + - - ))} - - - - - - {index === configSelections.length - 1 ? ( - - ) : ( - - )} -
- ))} + /> +
+ ), + )} +
+
+
+
+
)} @@ -705,6 +501,18 @@ export function NewRun() { /> Use Native Tool Calls +
@@ -714,103 +522,110 @@ export function NewRun() {
) : ( <> -
- {modelSelections.map((selection, index) => ( -
- toggleModelPopover(selection.id, open)}> - - - - - - - - No model found. - - {models?.map(({ id, name }) => ( - - updateModelSelection( - selection.id, - id, - ) - }> - {name} - - - ))} - - - - - - {index === modelSelections.length - 1 ? ( - - ) : ( - - )} -
- ))} -
- -
- -
- + + No model found. + + {models?.map(({ id, name }) => ( + + {name} + + + ))} + + + + + + +
+
+ +
+ + +
+ + {provider === "roo" && ( +
+ + +

+ When set, enableReasoningEffort will be automatically enabled +

+
+ )}
)} @@ -917,184 +732,148 @@ export function NewRun() { )} /> - {/* Concurrency, Timeout, and Iterations in a 3-column row */} -
- ( - - Concurrency - -
- { - field.onChange(value[0]) - localStorage.setItem("evals-concurrency", String(value[0])) - }} - /> -
{field.value}
-
-
- -
- )} - /> - - ( - - Timeout (Minutes) - -
- { - field.onChange(value[0]) - localStorage.setItem("evals-timeout", String(value[0])) - }} - /> -
{field.value}
-
-
- -
- )} - /> - - ( - - Iterations - -
- { - field.onChange(value[0]) - }} - /> -
{field.value}
-
-
- -
- )} - /> -
- - {/* Terminal timeouts in a 2-column row */} -
- -
- - - - - - -

- Maximum time in seconds to wait for terminal command execution to complete - before timing out. This applies to commands run via the execute_command - tool. -

-
-
-
-
- { - if (value !== undefined) { - setCommandExecutionTimeout(value) - localStorage.setItem("evals-command-execution-timeout", String(value)) - } - }} - /> -
{commandExecutionTimeout}
-
-
+ ( + + Concurrency + +
+ { + field.onChange(value[0]) + localStorage.setItem("evals-concurrency", String(value[0])) + }} + /> +
{field.value}
+
+
+ +
+ )} + /> - -
- - - - - - -

- Maximum time in seconds to wait for shell integration to initialize when - opening a new terminal. -

-
-
-
-
- { - if (value !== undefined) { - setTerminalShellIntegrationTimeout(value) - localStorage.setItem("evals-shell-integration-timeout", String(value)) - } - }} - /> -
{terminalShellIntegrationTimeout}
-
-
-
+ ( + + Timeout (Minutes) + +
+ { + field.onChange(value[0]) + localStorage.setItem("evals-timeout", String(value[0])) + }} + /> +
{field.value}
+
+
+ +
+ )} + /> - {/* Execution Method */} ( + name="iterations" + render={({ field }) => ( - Execution Method - { - const newExecutionMethod = value as ExecutionMethod - setExecutionMethod(newExecutionMethod) - setValue("executionMethod", newExecutionMethod) - }}> - - - - VSCode - - - - CLI - - - + Iterations per Exercise + +
+ { + field.onChange(value[0]) + }} + /> +
{field.value}
+
+
+ Run each exercise multiple times to compare results
)} /> + +
+ + + + + + +

+ Maximum time in seconds to wait for terminal command execution to complete + before timing out. This applies to commands run via the execute_command tool. +

+
+
+
+
+ { + if (value !== undefined) { + setCommandExecutionTimeout(value) + localStorage.setItem("evals-command-execution-timeout", String(value)) + } + }} + /> +
{commandExecutionTimeout}
+
+
+ + +
+ + + + + + +

+ Maximum time in seconds to wait for shell integration to initialize when opening + a new terminal. +

+
+
+
+
+ { + if (value !== undefined) { + setTerminalShellIntegrationTimeout(value) + localStorage.setItem("evals-shell-integration-timeout", String(value)) + } + }} + /> +
{terminalShellIntegrationTimeout}
+
+
+ () const [showSettings, setShowSettings] = useState(false) const [isExportingLogs, setIsExportingLogs] = useState(false) - const [showNotesDialog, setShowNotesDialog] = useState(false) - const [editingDescription, setEditingDescription] = useState(run.description ?? "") - const [isSavingNotes, setIsSavingNotes] = useState(false) const continueRef = useRef(null) const { isPending, copyRun, copied } = useCopyRun(run.id) - const hasDescription = Boolean(run.description && run.description.trim().length > 0) - - const handleSaveDescription = useCallback(async () => { - setIsSavingNotes(true) - try { - const result = await updateRunDescription(run.id, editingDescription.trim() || null) - if (result.success) { - toast.success("Description saved") - setShowNotesDialog(false) - router.refresh() - } else { - toast.error("Failed to save description") - } - } catch (error) { - console.error("Error saving description:", error) - toast.error("Failed to save description") - } finally { - setIsSavingNotes(false) - } - }, [run.id, editingDescription, router]) - const onExportFailedLogs = useCallback(async () => { if (run.failed === 0) { toast.error("No failed tasks to export") @@ -151,62 +113,6 @@ export function Run({ run, taskMetrics, toolColumns, toolGroups }: RunProps) { [router, run.id], ) - // Helper to render a tool group cell - const renderToolGroupCell = (group: ToolGroup) => { - if (!taskMetrics?.toolUsage) { - return - - } - - let totalAttempts = 0 - let totalFailures = 0 - const breakdown: Array<{ tool: string; attempts: number; rate: string }> = [] - - for (const toolName of group.tools) { - const usage = taskMetrics.toolUsage[toolName as ToolName] - if (usage) { - totalAttempts += usage.attempts - totalFailures += usage.failures - const rate = - usage.attempts > 0 - ? `${Math.round(((usage.attempts - usage.failures) / usage.attempts) * 100)}%` - : "0%" - breakdown.push({ tool: toolName, attempts: usage.attempts, rate }) - } - } - - if (totalAttempts === 0) { - return - - } - - const successRate = ((totalAttempts - totalFailures) / totalAttempts) * 100 - const rateColor = - successRate === 100 ? "text-muted-foreground" : successRate >= 80 ? "text-yellow-500" : "text-red-500" - - return ( - - -
- {totalAttempts} - {Math.round(successRate)}% -
-
- -
-
{group.name}
- {breakdown.map(({ tool, attempts, rate }) => ( -
- {tool}: - - {attempts} ({rate}) - -
- ))} -
-
-
- ) - } - return ( <> @@ -234,12 +140,6 @@ export function Run({ run, taskMetrics, toolColumns, toolGroups }: RunProps) {
)} - {/* Tool Group Columns */} - {toolGroups.map((group) => ( - - {renderToolGroupCell(group)} - - ))} {toolColumns.map((toolName) => { const usage = taskMetrics?.toolUsage?.[toolName] const successRate = @@ -266,107 +166,80 @@ export function Run({ run, taskMetrics, toolColumns, toolGroups }: RunProps) { {taskMetrics && formatCurrency(taskMetrics.cost)} {taskMetrics && formatDuration(taskMetrics.duration)} e.stopPropagation()}> -
- {/* Note Icon */} - - - - - - {hasDescription ? ( -
{run.description}
- ) : ( -
No description. Click to add one.
- )} -
-
- - {/* More Actions Menu */} - - - - - -
- -
View Tasks
-
- + + + + + +
+ +
View Tasks
+
+ +
+ {run.settings && ( + setShowSettings(true)}> +
+ +
View Settings
+
+
+ )} + {run.taskMetricsId && ( + copyRun()} disabled={isPending || copied}> +
+ {isPending ? ( + <> + + Copying... + + ) : copied ? ( + <> + + Copied! + + ) : ( + <> + + Copy to Production + + )} +
- {run.settings && ( - setShowSettings(true)}> -
- -
View Settings
-
-
- )} - {run.taskMetricsId && ( - copyRun()} disabled={isPending || copied}> -
- {isPending ? ( - <> - - Copying... - - ) : copied ? ( - <> - - Copied! - - ) : ( - <> - - Copy to Production - - )} -
-
- )} - {run.failed > 0 && ( - -
- {isExportingLogs ? ( - <> - - Exporting... - - ) : ( - <> - - Export Failed Logs - - )} -
-
- )} - { - setDeleteRunId(run.id) - setTimeout(() => continueRef.current?.focus(), 0) - }}> + )} + {run.failed > 0 && ( +
- -
Delete
+ {isExportingLogs ? ( + <> + + Exporting... + + ) : ( + <> + + Export Failed Logs + + )}
-
-
-
+ )} + { + setDeleteRunId(run.id) + setTimeout(() => continueRef.current?.focus(), 0) + }}> +
+ +
Delete
+
+
+ +
setDeleteRunId(undefined)}> @@ -395,39 +268,6 @@ export function Run({ run, taskMetrics, toolColumns, toolGroups }: RunProps) { - - {/* Notes/Description Dialog */} - - - - Run Description - -
-